/** * Logs a frame number. * * @category Debug */ declare const TRACEID_RENDER_FRAME: "RenderFrame"; /** * Logs a frame time. * * @category Debug */ declare const TRACEID_RENDER_FRAME_TIME: "RenderFrameTime"; /** * Logs basic information about generated render passes. * * @category Debug */ declare const TRACEID_RENDER_PASS: "RenderPass"; /** * Logs additional detail for render passes. * * @category Debug */ declare const TRACEID_RENDER_PASS_DETAIL: "RenderPassDetail"; /** * Logs render actions created by the layer composition. Only executes when the * layer composition changes. * * @category Debug */ declare const TRACEID_RENDER_ACTION: "RenderAction"; /** * Logs the allocation of render targets. * * @category Debug */ declare const TRACEID_RENDER_TARGET_ALLOC: "RenderTargetAlloc"; /** * Logs the allocation of textures. * * @category Debug */ declare const TRACEID_TEXTURE_ALLOC: "TextureAlloc"; /** * Logs the creation of shaders. * * @category Debug */ declare const TRACEID_SHADER_ALLOC: "ShaderAlloc"; /** * Logs the compilation time of shaders. * * @category Debug */ declare const TRACEID_SHADER_COMPILE: "ShaderCompile"; /** * Logs the vram use by the textures. * * @category Debug */ declare const TRACEID_VRAM_TEXTURE: "VRAM.Texture"; /** * Logs the vram use by the vertex buffers. * * @category Debug */ declare const TRACEID_VRAM_VB: "VRAM.Vb"; /** * Logs the vram use by the index buffers. * * @category Debug */ declare const TRACEID_VRAM_IB: "VRAM.Ib"; /** * Logs the vram use by the storage buffers. * * @category Debug */ declare const TRACEID_VRAM_SB: "VRAM.Sb"; /** * Logs the creation of bind groups. * * @category Debug */ declare const TRACEID_BINDGROUP_ALLOC: "BindGroupAlloc"; /** * Records where a material was created and last changed, so that the debug build can report them * when a material property is changed without a subsequent call to {@link Material#update}. * * @category Debug */ declare const TRACEID_MATERIAL_UPDATE: "MaterialUpdate"; /** * Logs the creation of bind group formats. * * @category Debug */ declare const TRACEID_BINDGROUPFORMAT_ALLOC: "BindGroupFormatAlloc"; /** * Logs the creation of render pipelines. WebGPU only. * * @category Debug */ declare const TRACEID_RENDERPIPELINE_ALLOC: "RenderPipelineAlloc"; /** * Logs the creation of compute pipelines. WebGPU only. * * @category Debug */ declare const TRACEID_COMPUTEPIPELINE_ALLOC: "ComputePipelineAlloc"; /** * Logs the creation of pipeline layouts. WebGPU only. * * @category Debug */ declare const TRACEID_PIPELINELAYOUT_ALLOC: "PipelineLayoutAlloc"; /** * Logs the internal debug information for Elements. * * @category Debug */ declare const TRACEID_ELEMENT: "Element"; /** * Logs the vram use by all textures in memory. * * @category Debug */ declare const TRACEID_TEXTURES: "Textures"; /** * Logs GPU buffer memory tracked on the graphics device (vertex, index, storage). * * @category Debug */ declare const TRACEID_BUFFERS: "Buffers"; /** * Logs all assets in the asset registry. * * @category Debug */ declare const TRACEID_ASSETS: "Assets"; /** * Logs the render queue commands. * * @category Debug */ declare const TRACEID_RENDER_QUEUE: "RenderQueue"; /** * Logs the loaded GSplat resources for individual LOD levels of an octree. * * @category Debug */ declare const TRACEID_OCTREE_RESOURCES: "OctreeResources"; /** * Logs the GPU timings. * * @category Debug */ declare const TRACEID_GPU_TIMINGS: "GpuTimings"; /** * A linear interpolation scheme. * * @category Math */ declare const CURVE_LINEAR: 0; /** * A smooth step interpolation scheme. * * @category Math */ declare const CURVE_SMOOTHSTEP: 1; /** * Cardinal spline interpolation scheme. For a Catmull-Rom spline, specify a curve tension of 0.5. * * @category Math */ declare const CURVE_SPLINE: 4; /** * A stepped interpolator that does not perform any blending. * * @category Math */ declare const CURVE_STEP: 5; /** * Ignores the integer part of texture coordinates, using only the fractional part. * * @category Graphics */ declare const ADDRESS_REPEAT: 0; /** * Clamps texture coordinate to the range 0 to 1. * * @category Graphics */ declare const ADDRESS_CLAMP_TO_EDGE: 1; /** * Texture coordinate to be set to the fractional part if the integer part is even. If the integer * part is odd, then the texture coordinate is set to 1 minus the fractional part. * * @category Graphics */ declare const ADDRESS_MIRRORED_REPEAT: 2; /** * Multiply all fragment components by zero. * * @category Graphics */ declare const BLENDMODE_ZERO: 0; /** * Multiply all fragment components by one. * * @category Graphics */ declare const BLENDMODE_ONE: 1; /** * Multiply all fragment components by the components of the source fragment. * * @category Graphics */ declare const BLENDMODE_SRC_COLOR: 2; /** * Multiply all fragment components by one minus the components of the source fragment. * * @category Graphics */ declare const BLENDMODE_ONE_MINUS_SRC_COLOR: 3; /** * Multiply all fragment components by the components of the destination fragment. * * @category Graphics */ declare const BLENDMODE_DST_COLOR: 4; /** * Multiply all fragment components by one minus the components of the destination fragment. * * @category Graphics */ declare const BLENDMODE_ONE_MINUS_DST_COLOR: 5; /** * Multiply all fragment components by the alpha value of the source fragment. * * @category Graphics */ declare const BLENDMODE_SRC_ALPHA: 6; /** * Multiply all fragment components by the alpha value of the source fragment. * * @category Graphics */ declare const BLENDMODE_SRC_ALPHA_SATURATE: 7; /** * Multiply all fragment components by one minus the alpha value of the source fragment. * * @category Graphics */ declare const BLENDMODE_ONE_MINUS_SRC_ALPHA: 8; /** * Multiply all fragment components by the alpha value of the destination fragment. * * @category Graphics */ declare const BLENDMODE_DST_ALPHA: 9; /** * Multiply all fragment components by one minus the alpha value of the destination fragment. * * @category Graphics */ declare const BLENDMODE_ONE_MINUS_DST_ALPHA: 10; /** * Multiplies all fragment components by a constant. * * @category Graphics */ declare const BLENDMODE_CONSTANT: 11; /** * Multiplies all fragment components by 1 minus a constant. * * @category Graphics */ declare const BLENDMODE_ONE_MINUS_CONSTANT: 12; /** * Multiply all fragment components by the components of the secondary source fragment. This can * only be used when {@link GraphicsDevice#supportsDualSourceBlending} is true. * * @category Graphics */ declare const BLENDMODE_SRC1_COLOR: 13; /** * Multiply all fragment components by one minus the components of the secondary source fragment. * This can only be used when {@link GraphicsDevice#supportsDualSourceBlending} is true. * * @category Graphics */ declare const BLENDMODE_ONE_MINUS_SRC1_COLOR: 14; /** * Multiply all fragment components by the alpha value of the secondary source fragment. This can * only be used when {@link GraphicsDevice#supportsDualSourceBlending} is true. * * @category Graphics */ declare const BLENDMODE_SRC1_ALPHA: 15; /** * Multiply all fragment components by one minus the alpha value of the secondary source fragment. * This can only be used when {@link GraphicsDevice#supportsDualSourceBlending} is true. * * @category Graphics */ declare const BLENDMODE_ONE_MINUS_SRC1_ALPHA: 16; /** * Add the results of the source and destination fragment multiplies. * * @category Graphics */ declare const BLENDEQUATION_ADD: 0; /** * Subtract the results of the source and destination fragment multiplies. * * @category Graphics */ declare const BLENDEQUATION_SUBTRACT: 1; /** * Reverse and subtract the results of the source and destination fragment multiplies. * * @category Graphics */ declare const BLENDEQUATION_REVERSE_SUBTRACT: 2; /** * Use the smallest value. * * @category Graphics */ declare const BLENDEQUATION_MIN: 3; /** * Use the largest value. * * @category Graphics */ declare const BLENDEQUATION_MAX: 4; /** * A flag utilized during the construction of a {@link StorageBuffer} to make it available for read * access by CPU. * * @category Graphics */ declare const BUFFERUSAGE_READ: 1; /** * A flag utilized during the construction of a {@link StorageBuffer} to make it available for write * access by CPU. * * @category Graphics */ declare const BUFFERUSAGE_WRITE: 2; /** * A flag utilized during the construction of a {@link StorageBuffer} to ensure its compatibility * when used as a source of a copy operation. * * @category Graphics */ declare const BUFFERUSAGE_COPY_SRC: 4; /** * A flag utilized during the construction of a {@link StorageBuffer} to ensure its compatibility * when used as a destination of a copy operation, or as a target of a write operation. * * @category Graphics */ declare const BUFFERUSAGE_COPY_DST: 8; /** * A flag utilized during the construction of a {@link StorageBuffer} to ensure its compatibility * when used as an index buffer. * * @category Graphics */ declare const BUFFERUSAGE_INDEX: 16; /** * A flag utilized during the construction of a {@link StorageBuffer} to ensure its compatibility * when used as a vertex buffer. * * @category Graphics */ declare const BUFFERUSAGE_VERTEX: 32; /** * A flag utilized during the construction of a {@link StorageBuffer} to ensure its compatibility * when used as an uniform buffer. * * @category Graphics */ declare const BUFFERUSAGE_UNIFORM: 64; /** * An internal flag utilized during the construction of a {@link StorageBuffer} to ensure its * compatibility when used as a storage buffer. * This flag is hidden as it's automatically used by the StorageBuffer constructor. * * @category Graphics * @ignore */ declare const BUFFERUSAGE_STORAGE: 128; /** * A flag utilized during the construction of a {@link StorageBuffer} to allow it to store indirect * command arguments. * TODO: This flag is hidden till the feature is implemented. * * @category Graphics * @ignore */ declare const BUFFERUSAGE_INDIRECT: 256; /** * The data store contents will be modified once and used many times. * * @category Graphics */ declare const BUFFER_STATIC: 0; /** * The data store contents will be modified repeatedly and used many times. * * @category Graphics */ declare const BUFFER_DYNAMIC: 1; /** * The data store contents will be modified once and used at most a few times. * * @category Graphics */ declare const BUFFER_STREAM: 2; /** * The data store contents will be modified repeatedly on the GPU and used many times. Optimal for * transform feedback usage. * * @category Graphics */ declare const BUFFER_GPUDYNAMIC: 3; /** * Captures all varyings into one interleaved transform feedback buffer. * * @category Graphics */ declare const TRANSFORM_FEEDBACK_INTERLEAVED: 0; /** * Captures each varying into its own transform feedback buffer. * * @category Graphics */ declare const TRANSFORM_FEEDBACK_SEPARATE: 1; /** * Clear the color buffer. * * @category Graphics */ declare const CLEARFLAG_COLOR: 1; /** * Clear the depth buffer. * * @category Graphics */ declare const CLEARFLAG_DEPTH: 2; /** * Clear the stencil buffer. * * @category Graphics */ declare const CLEARFLAG_STENCIL: 4; /** * The positive X face of a cubemap. * * @category Graphics */ declare const CUBEFACE_POSX: 0; /** * The negative X face of a cubemap. * * @category Graphics */ declare const CUBEFACE_NEGX: 1; /** * The positive Y face of a cubemap. * * @category Graphics */ declare const CUBEFACE_POSY: 2; /** * The negative Y face of a cubemap. * * @category Graphics */ declare const CUBEFACE_NEGY: 3; /** * The positive Z face of a cubemap. * * @category Graphics */ declare const CUBEFACE_POSZ: 4; /** * The negative Z face of a cubemap. * * @category Graphics */ declare const CUBEFACE_NEGZ: 5; /** * The render target stores the image with row 0 being the top row of the rendered image, on all * graphics APIs - the same layout image textures use. See the `origin` option of the * {@link RenderTarget} constructor for guidance on which origin to use. * * @category Graphics */ declare const RENDERTARGET_ORIGIN_TOP: "top"; /** * The render target stores the image with row 0 being the bottom row of the rendered image, on * all graphics APIs - replicating WebGL2's native layout. See the `origin` option of the * {@link RenderTarget} constructor for guidance on which origin to use. * * @category Graphics */ declare const RENDERTARGET_ORIGIN_BOTTOM: "bottom"; /** * The render target stores the image in the native orientation of the graphics API - bottom-up * on WebGL2, top-down on WebGPU - so the stored row order differs between the APIs. This is the * default. See the `origin` option of the {@link RenderTarget} constructor for guidance on which * origin to use. * * @category Graphics */ declare const RENDERTARGET_ORIGIN_NATIVE: "native"; /** * The depth value of the multisampled depth buffer is resolved by taking its sample at index 0. * See {@link RenderTarget#depthResolveMode}. * * @category Graphics */ declare const DEPTHRESOLVE_SAMPLE0: "sample0"; /** * The depth value of the multisampled depth buffer is resolved by taking the minimum value of all * samples - with a standard depth buffer this selects the nearest surface, which is a conservative * and stable choice for depth-consuming effects. This is the default. See * {@link RenderTarget#depthResolveMode}. * * @category Graphics */ declare const DEPTHRESOLVE_MIN: "min"; /** * The depth value of the multisampled depth buffer is resolved by taking the maximum value of all * samples - with a standard depth buffer this selects the farthest surface. See * {@link RenderTarget#depthResolveMode}. * * @category Graphics */ declare const DEPTHRESOLVE_MAX: "max"; /** * No triangles are culled. * * @category Graphics */ declare const CULLFACE_NONE: 0; /** * Triangles facing away from the view direction are culled. * * @category Graphics */ declare const CULLFACE_BACK: 1; /** * Triangles facing the view direction are culled. * * @category Graphics */ declare const CULLFACE_FRONT: 2; /** * Triangles are culled regardless of their orientation with respect to the view direction. Note * that point or line primitives are unaffected by this render state. * * @ignore * @category Graphics */ declare const CULLFACE_FRONTANDBACK: 3; /** * The counterclockwise winding. Specifies whether polygons are front- or back-facing by setting a winding orientation. * * @category Graphics */ declare const FRONTFACE_CCW: 0; /** * The clockwise winding. Specifies whether polygons are front- or back-facing by setting a winding orientation. * * @category Graphics */ declare const FRONTFACE_CW: 1; /** * Point sample filtering. * * @category Graphics */ declare const FILTER_NEAREST: 0; /** * Bilinear filtering. * * @category Graphics */ declare const FILTER_LINEAR: 1; /** * Use the nearest neighbor in the nearest mipmap level. * * @category Graphics */ declare const FILTER_NEAREST_MIPMAP_NEAREST: 2; /** * Linearly interpolate in the nearest mipmap level. * * @category Graphics */ declare const FILTER_NEAREST_MIPMAP_LINEAR: 3; /** * Use the nearest neighbor after linearly interpolating between mipmap levels. * * @category Graphics */ declare const FILTER_LINEAR_MIPMAP_NEAREST: 4; /** * Linearly interpolate both the mipmap levels and between texels. * * @category Graphics */ declare const FILTER_LINEAR_MIPMAP_LINEAR: 5; /** * Never pass. * * @category Graphics */ declare const FUNC_NEVER: 0; /** * Pass if (ref & mask) < (stencil & mask). * * @category Graphics */ declare const FUNC_LESS: 1; /** * Pass if (ref & mask) == (stencil & mask). * * @category Graphics */ declare const FUNC_EQUAL: 2; /** * Pass if (ref & mask) <= (stencil & mask). * * @category Graphics */ declare const FUNC_LESSEQUAL: 3; /** * Pass if (ref & mask) > (stencil & mask). * * @category Graphics */ declare const FUNC_GREATER: 4; /** * Pass if (ref & mask) != (stencil & mask). * * @category Graphics */ declare const FUNC_NOTEQUAL: 5; /** * Pass if (ref & mask) >= (stencil & mask). * * @category Graphics */ declare const FUNC_GREATEREQUAL: 6; /** * Always pass. * * @category Graphics */ declare const FUNC_ALWAYS: 7; /** * 8-bit unsigned vertex indices (0 to 255). * * @category Graphics */ declare const INDEXFORMAT_UINT8: 0; /** * 16-bit unsigned vertex indices (0 to 65,535). * * @category Graphics */ declare const INDEXFORMAT_UINT16: 1; /** * 32-bit unsigned vertex indices (0 to 4,294,967,295). * * @category Graphics */ declare const INDEXFORMAT_UINT32: 2; /** * Byte size of index formats. * * @category Graphics * @ignore */ declare const indexFormatByteSize: number[]; declare const PIXELFORMAT_A8: 0; declare const PIXELFORMAT_L8: 1; declare const PIXELFORMAT_LA8: 2; /** * 16-bit RGB (5-bits for red channel, 6 for green and 5 for blue). * * @category Graphics */ declare const PIXELFORMAT_RGB565: 3; /** * 16-bit RGBA (5-bits for red channel, 5 for green, 5 for blue with 1-bit alpha). * * @category Graphics */ declare const PIXELFORMAT_RGBA5551: 4; /** * 16-bit RGBA (4-bits for red channel, 4 for green, 4 for blue with 4-bit alpha). * * @category Graphics */ declare const PIXELFORMAT_RGBA4: 5; /** * 24-bit RGB (8-bits for red channel, 8 for green and 8 for blue). * * @category Graphics */ declare const PIXELFORMAT_RGB8: 6; /** * 32-bit RGBA (8-bits for red channel, 8 for green, 8 for blue with 8-bit alpha). * * @category Graphics */ declare const PIXELFORMAT_RGBA8: 7; /** * Block compressed format storing 16 input pixels in 64 bits of output, consisting of two 16-bit * RGB 5:6:5 color values and a 4x4 two bit lookup table. * * @category Graphics */ declare const PIXELFORMAT_DXT1: 8; /** * Block compressed format storing 16 input pixels (corresponding to a 4x4 pixel block) into 128 * bits of output, consisting of 64 bits of alpha channel data (4 bits for each pixel) followed by * 64 bits of color data; encoded the same way as DXT1. * * @category Graphics */ declare const PIXELFORMAT_DXT3: 9; /** * Block compressed format storing 16 input pixels into 128 bits of output, consisting of 64 bits * of alpha channel data (two 8 bit alpha values and a 4x4 3 bit lookup table) followed by 64 bits * of color data (encoded the same way as DXT1). * * @category Graphics */ declare const PIXELFORMAT_DXT5: 10; /** * 16-bit floating point RGB (16-bit float for each red, green and blue channels). * * @category Graphics */ declare const PIXELFORMAT_RGB16F: 11; /** * 16-bit floating point RGBA (16-bit float for each red, green, blue and alpha channels). * * @category Graphics */ declare const PIXELFORMAT_RGBA16F: 12; /** * 32-bit floating point RGB (32-bit float for each red, green and blue channels). * * @category Graphics */ declare const PIXELFORMAT_RGB32F: 13; /** * 32-bit floating point RGBA (32-bit float for each red, green, blue and alpha channels). * * @category Graphics */ declare const PIXELFORMAT_RGBA32F: 14; /** * 32-bit floating point single channel format. * * @category Graphics */ declare const PIXELFORMAT_R32F: 15; /** * A readable depth buffer format. * * @category Graphics */ declare const PIXELFORMAT_DEPTH: 16; /** * A readable depth/stencil buffer format. * * @category Graphics */ declare const PIXELFORMAT_DEPTHSTENCIL: 17; /** * A floating-point color-only format with 11 bits for red and green channels and 10 bits for the * blue channel. * * @category Graphics */ declare const PIXELFORMAT_111110F: 18; /** * Color-only sRGB format. * * @category Graphics */ declare const PIXELFORMAT_SRGB8: 19; /** * Color sRGB format with additional alpha channel. * * @category Graphics */ declare const PIXELFORMAT_SRGBA8: 20; /** * ETC1 compressed format. * * @category Graphics */ declare const PIXELFORMAT_ETC1: 21; /** * ETC2 (RGB) compressed format. * * @category Graphics */ declare const PIXELFORMAT_ETC2_RGB: 22; /** * ETC2 (RGBA) compressed format. * * @category Graphics */ declare const PIXELFORMAT_ETC2_RGBA: 23; /** * PVRTC (2BPP RGB) compressed format. * * @category Graphics */ declare const PIXELFORMAT_PVRTC_2BPP_RGB_1: 24; /** * PVRTC (2BPP RGBA) compressed format. * * @category Graphics */ declare const PIXELFORMAT_PVRTC_2BPP_RGBA_1: 25; /** * PVRTC (4BPP RGB) compressed format. * * @category Graphics */ declare const PIXELFORMAT_PVRTC_4BPP_RGB_1: 26; /** * PVRTC (4BPP RGBA) compressed format. * * @category Graphics */ declare const PIXELFORMAT_PVRTC_4BPP_RGBA_1: 27; /** * ATC compressed format with alpha channel in blocks of 4x4. * * @category Graphics */ declare const PIXELFORMAT_ASTC_4x4: 28; /** * ATC compressed format with no alpha channel. * * @category Graphics */ declare const PIXELFORMAT_ATC_RGB: 29; /** * ATC compressed format with alpha channel. * * @category Graphics */ declare const PIXELFORMAT_ATC_RGBA: 30; /** * 32-bit BGRA (8-bits for blue channel, 8 for green, 8 for red with 8-bit alpha). This is an * internal format used by the WebGPU's backbuffer only. * * @ignore * @category Graphics */ declare const PIXELFORMAT_BGRA8: 31; /** * 8-bit signed integer single-channel (R) format. * * @category Graphics */ declare const PIXELFORMAT_R8I: 32; /** * 8-bit unsigned integer single-channel (R) format. * * @category Graphics */ declare const PIXELFORMAT_R8U: 33; /** * 16-bit signed integer single-channel (R) format. * * @category Graphics */ declare const PIXELFORMAT_R16I: 34; /** * 16-bit unsigned integer single-channel (R) format. * * @category Graphics */ declare const PIXELFORMAT_R16U: 35; /** * 32-bit signed integer single-channel (R) format. * * @category Graphics */ declare const PIXELFORMAT_R32I: 36; /** * 32-bit unsigned integer single-channel (R) format. * * @category Graphics */ declare const PIXELFORMAT_R32U: 37; /** * 8-bit per-channel signed integer (RG) format. * * @category Graphics */ declare const PIXELFORMAT_RG8I: 38; /** * 8-bit per-channel unsigned integer (RG) format. * * @category Graphics */ declare const PIXELFORMAT_RG8U: 39; /** * 16-bit per-channel signed integer (RG) format. * * @category Graphics */ declare const PIXELFORMAT_RG16I: 40; /** * 16-bit per-channel unsigned integer (RG) format. * * @category Graphics */ declare const PIXELFORMAT_RG16U: 41; /** * 32-bit per-channel signed integer (RG) format. * * @category Graphics */ declare const PIXELFORMAT_RG32I: 42; /** * 32-bit per-channel unsigned integer (RG) format. * * @category Graphics */ declare const PIXELFORMAT_RG32U: 43; /** * 8-bit per-channel signed integer (RGBA) format. * * @category Graphics */ declare const PIXELFORMAT_RGBA8I: 44; /** * 8-bit per-channel unsigned integer (RGBA) format. * * @category Graphics */ declare const PIXELFORMAT_RGBA8U: 45; /** * 16-bit per-channel signed integer (RGBA) format. * * @category Graphics */ declare const PIXELFORMAT_RGBA16I: 46; /** * 16-bit per-channel unsigned integer (RGBA) format. * * @category Graphics */ declare const PIXELFORMAT_RGBA16U: 47; /** * 32-bit per-channel signed integer (RGBA) format. * * @category Graphics */ declare const PIXELFORMAT_RGBA32I: 48; /** * 32-bit per-channel unsigned integer (RGBA) format. * * @category Graphics */ declare const PIXELFORMAT_RGBA32U: 49; /** * 16-bit floating point R (16-bit float for red channel). * * @category Graphics */ declare const PIXELFORMAT_R16F: 50; /** * 16-bit floating point RG (16-bit float for each red and green channels). * * @category Graphics */ declare const PIXELFORMAT_RG16F: 51; /** * 8-bit per-channel (R) format. * * @category Graphics */ declare const PIXELFORMAT_R8: 52; /** * 8-bit per-channel (RG) format. * * @category Graphics */ declare const PIXELFORMAT_RG8: 53; /** * Format equivalent to {@link PIXELFORMAT_DXT1} but sampled in linear color space. * * @category Graphics */ declare const PIXELFORMAT_DXT1_SRGB: 54; /** * Format equivalent to {@link PIXELFORMAT_DXT3} but sampled in linear color space. * * @category Graphics */ declare const PIXELFORMAT_DXT3_SRGBA: 55; /** * Format equivalent to {@link PIXELFORMAT_DXT5} but sampled in linear color space. * * @category Graphics */ declare const PIXELFORMAT_DXT5_SRGBA: 56; /** * Format equivalent to {@link PIXELFORMAT_ETC2_RGB} but sampled in linear color space. * * @category Graphics */ declare const PIXELFORMAT_ETC2_SRGB: 61; /** * Format equivalent to {@link PIXELFORMAT_ETC2_RGBA} but sampled in linear color space. * * @category Graphics */ declare const PIXELFORMAT_ETC2_SRGBA: 62; /** * Format equivalent to {@link PIXELFORMAT_ASTC_4x4} but sampled in linear color space. * * @category Graphics */ declare const PIXELFORMAT_ASTC_4x4_SRGB: 63; /** * 32-bit BGRA sRGB format. This is an internal format used by the WebGPU's backbuffer only. * * @ignore * @category Graphics */ declare const PIXELFORMAT_SBGRA8: 64; /** * Compressed high dynamic range signed floating point format storing RGB values. * * @category Graphics */ declare const PIXELFORMAT_BC6F: 65; /** * Compressed high dynamic range unsigned floating point format storing RGB values. * * @category Graphics */ declare const PIXELFORMAT_BC6UF: 66; /** * Compressed 8-bit fixed-point data. Each 4x4 block of texels consists of 128 bits of RGBA data. * * @category Graphics */ declare const PIXELFORMAT_BC7: 67; /** * Compressed 8-bit fixed-point data. Each 4x4 block of texels consists of 128 bits of SRGB_ALPHA * data. * * @category Graphics */ declare const PIXELFORMAT_BC7_SRGBA: 68; /** * A 16-bit depth buffer format. * * @category Graphics */ declare const PIXELFORMAT_DEPTH16: 69; /** * 32-bit floating point RG (32-bit float for each red and green channels). WebGPU only. * * @category Graphics */ declare const PIXELFORMAT_RG32F: 70; /** * 32-bit RGB format with shared 5-bit exponent (9 bits each for RGB mantissa). HDR format. * * @category Graphics */ declare const PIXELFORMAT_RGB9E5: 71; /** * 8-bit per-channel signed normalized (RG) format. * * @category Graphics */ declare const PIXELFORMAT_RG8S: 72; /** * 8-bit per-channel signed normalized (RGBA) format. * * @category Graphics */ declare const PIXELFORMAT_RGBA8S: 73; /** * 10-bit RGB with 2-bit alpha unsigned normalized format. * * @category Graphics */ declare const PIXELFORMAT_RGB10A2: 74; /** * 10-bit RGB with 2-bit alpha unsigned integer format. * * @category Graphics */ declare const PIXELFORMAT_RGB10A2U: 75; /** * Information about pixel formats. * * ldr: whether the format is low dynamic range (LDR), which typically means it's not HDR, and uses * sRGB color space to store the color values * srgbFormat: the corresponding sRGB format (which automatically converts the sRGB value to linear) * * @type {Map} * @ignore */ declare const pixelFormatInfo: Map; declare function isCompressedPixelFormat(format: any): boolean; declare function isSrgbPixelFormat(format: any): boolean; declare function isIntegerPixelFormat(format: any): boolean; declare function isMultisampleCapablePixelFormat(format: number): boolean; declare function isMultisampleResolveCapablePixelFormat(format: number): boolean; declare function getGlslShaderType(format: number): { sampler: string; returnType: string; }; declare function getWgslShaderType(format: number): { textureType: string; returnType: string; }; declare function pixelFormatLinearToGamma(format: number): number; declare function pixelFormatGammaToLinear(format: number): number; declare function requiresManualGamma(format: number): boolean; declare function getPixelFormatArrayType(format: any): Int8ArrayConstructor | Uint8ArrayConstructor | Int16ArrayConstructor | Uint16ArrayConstructor | Int32ArrayConstructor | Uint32ArrayConstructor | Float32ArrayConstructor; /** * List of distinct points. * * @category Graphics */ declare const PRIMITIVE_POINTS: 0; /** * Discrete list of line segments. * * @category Graphics */ declare const PRIMITIVE_LINES: 1; /** * List of points that are linked sequentially by line segments, with a closing line segment * between the last and first points. * * @category Graphics */ declare const PRIMITIVE_LINELOOP: 2; /** * List of points that are linked sequentially by line segments. * * @category Graphics */ declare const PRIMITIVE_LINESTRIP: 3; /** * Discrete list of triangles. * * @category Graphics */ declare const PRIMITIVE_TRIANGLES: 4; /** * Connected strip of triangles where a specified vertex forms a triangle using the previous two. * * @category Graphics */ declare const PRIMITIVE_TRISTRIP: 5; /** * Connected fan of triangles where the first vertex forms triangles with the following pairs of vertices. * * @category Graphics */ declare const PRIMITIVE_TRIFAN: 6; /** * Vertex attribute to be treated as a position. * * @category Graphics */ declare const SEMANTIC_POSITION: "POSITION"; /** * Vertex attribute to be treated as a normal. * * @category Graphics */ declare const SEMANTIC_NORMAL: "NORMAL"; /** * Vertex attribute to be treated as a tangent. * * @category Graphics */ declare const SEMANTIC_TANGENT: "TANGENT"; /** * Vertex attribute to be treated as skin blend weights. * * @category Graphics */ declare const SEMANTIC_BLENDWEIGHT: "BLENDWEIGHT"; /** * Vertex attribute to be treated as skin blend indices. * * @category Graphics */ declare const SEMANTIC_BLENDINDICES: "BLENDINDICES"; /** * Vertex attribute to be treated as a color. * * @category Graphics */ declare const SEMANTIC_COLOR: "COLOR"; declare const SEMANTIC_TEXCOORD: "TEXCOORD"; /** * Vertex attribute to be treated as a texture coordinate (set 0). * * @category Graphics */ declare const SEMANTIC_TEXCOORD0: "TEXCOORD0"; /** * Vertex attribute to be treated as a texture coordinate (set 1). * * @category Graphics */ declare const SEMANTIC_TEXCOORD1: "TEXCOORD1"; /** * Vertex attribute to be treated as a texture coordinate (set 2). * * @category Graphics */ declare const SEMANTIC_TEXCOORD2: "TEXCOORD2"; /** * Vertex attribute to be treated as a texture coordinate (set 3). * * @category Graphics */ declare const SEMANTIC_TEXCOORD3: "TEXCOORD3"; /** * Vertex attribute to be treated as a texture coordinate (set 4). * * @category Graphics */ declare const SEMANTIC_TEXCOORD4: "TEXCOORD4"; /** * Vertex attribute to be treated as a texture coordinate (set 5). * * @category Graphics */ declare const SEMANTIC_TEXCOORD5: "TEXCOORD5"; /** * Vertex attribute to be treated as a texture coordinate (set 6). * * @category Graphics */ declare const SEMANTIC_TEXCOORD6: "TEXCOORD6"; /** * Vertex attribute to be treated as a texture coordinate (set 7). * * @category Graphics */ declare const SEMANTIC_TEXCOORD7: "TEXCOORD7"; /** * Vertex attribute with a user defined semantic. * * @category Graphics */ declare const SEMANTIC_ATTR0: "ATTR0"; /** * Vertex attribute with a user defined semantic. * * @category Graphics */ declare const SEMANTIC_ATTR1: "ATTR1"; /** * Vertex attribute with a user defined semantic. * * @category Graphics */ declare const SEMANTIC_ATTR2: "ATTR2"; /** * Vertex attribute with a user defined semantic. * * @category Graphics */ declare const SEMANTIC_ATTR3: "ATTR3"; /** * Vertex attribute with a user defined semantic. * * @category Graphics */ declare const SEMANTIC_ATTR4: "ATTR4"; /** * Vertex attribute with a user defined semantic. * * @category Graphics */ declare const SEMANTIC_ATTR5: "ATTR5"; /** * Vertex attribute with a user defined semantic. * * @category Graphics */ declare const SEMANTIC_ATTR6: "ATTR6"; /** * Vertex attribute with a user defined semantic. * * @category Graphics */ declare const SEMANTIC_ATTR7: "ATTR7"; /** * Vertex attribute with a user defined semantic. * * @category Graphics */ declare const SEMANTIC_ATTR8: "ATTR8"; /** * Vertex attribute with a user defined semantic. * * @category Graphics */ declare const SEMANTIC_ATTR9: "ATTR9"; /** * Vertex attribute with a user defined semantic. * * @category Graphics */ declare const SEMANTIC_ATTR10: "ATTR10"; /** * Vertex attribute with a user defined semantic. * * @category Graphics */ declare const SEMANTIC_ATTR11: "ATTR11"; /** * Vertex attribute with a user defined semantic. * * @category Graphics */ declare const SEMANTIC_ATTR12: "ATTR12"; /** * Vertex attribute with a user defined semantic. * * @category Graphics */ declare const SEMANTIC_ATTR13: "ATTR13"; /** * Vertex attribute with a user defined semantic. * * @category Graphics */ declare const SEMANTIC_ATTR14: "ATTR14"; /** * Vertex attribute with a user defined semantic. * * @category Graphics */ declare const SEMANTIC_ATTR15: "ATTR15"; declare const SHADERTAG_MATERIAL: 1; /** * Don't change the stencil buffer value. * * @category Graphics */ declare const STENCILOP_KEEP: 0; /** * Set value to zero. * * @category Graphics */ declare const STENCILOP_ZERO: 1; /** * Replace value with the reference value (see {@link StencilParameters}). * * @category Graphics */ declare const STENCILOP_REPLACE: 2; /** * Increment the value. * * @category Graphics */ declare const STENCILOP_INCREMENT: 3; /** * Increment the value but wrap it to zero when it's larger than a maximum representable value. * * @category Graphics */ declare const STENCILOP_INCREMENTWRAP: 4; /** * Decrement the value. * * @category Graphics */ declare const STENCILOP_DECREMENT: 5; /** * Decrement the value but wrap it to a maximum representable value if the current value is 0. * * @category Graphics */ declare const STENCILOP_DECREMENTWRAP: 6; /** * Invert the value bitwise. * * @category Graphics */ declare const STENCILOP_INVERT: 7; /** * The texture is not in a locked state. * * @category Graphics */ declare const TEXTURELOCK_NONE: 0; /** * Read only. Any changes to the locked mip level's pixels will not update the texture. * * @category Graphics */ declare const TEXTURELOCK_READ: 1; /** * Write only. The contents of the specified mip level will be entirely replaced. * * @category Graphics */ declare const TEXTURELOCK_WRITE: 2; /** * Texture is a default type. * * @category Graphics */ declare const TEXTURETYPE_DEFAULT: "default"; /** * Texture stores high dynamic range data in RGBM format. * * @category Graphics */ declare const TEXTURETYPE_RGBM: "rgbm"; /** * Texture stores high dynamic range data in RGBE format. * * @category Graphics */ declare const TEXTURETYPE_RGBE: "rgbe"; /** * Texture stores high dynamic range data in RGBP encoding. * * @category Graphics */ declare const TEXTURETYPE_RGBP: "rgbp"; /** * Texture stores normalmap data swizzled in GGGR format. This is used for tangent space normal * maps. The R component is stored in alpha and G is stored in RGB. This packing can result in * higher quality when the texture data is compressed. * * @category Graphics */ declare const TEXTURETYPE_SWIZZLEGGGR: "swizzleGGGR"; declare const TEXHINT_NONE: 0; declare const TEXHINT_SHADOWMAP: 1; declare const TEXHINT_ASSET: 2; declare const TEXHINT_LIGHTMAP: 3; /** * Texture data is stored in a 1-dimensional texture. * * @category Graphics */ declare const TEXTUREDIMENSION_1D: "1d"; /** * Texture data is stored in a 2-dimensional texture. * * @category Graphics */ declare const TEXTUREDIMENSION_2D: "2d"; /** * Texture data is stored in an array of 2-dimensional textures. * * @category Graphics */ declare const TEXTUREDIMENSION_2D_ARRAY: "2d-array"; /** * Texture data is stored in a cube texture. * * @category Graphics */ declare const TEXTUREDIMENSION_CUBE: "cube"; /** * Texture data is stored in an array of cube textures. * * @category Graphics */ declare const TEXTUREDIMENSION_CUBE_ARRAY: "cube-array"; /** * Texture data is stored in a 3-dimensional texture. * * @category Graphics */ declare const TEXTUREDIMENSION_3D: "3d"; /** * A sampler type of a texture that contains floating-point data. Typically stored for color * textures, where data can be filtered. * * @category Graphics */ declare const SAMPLETYPE_FLOAT: 0; /** * A sampler type of a texture that contains floating-point data, but cannot be filtered. Typically * used for textures storing data that cannot be interpolated. * * @category Graphics */ declare const SAMPLETYPE_UNFILTERABLE_FLOAT: 1; /** * A sampler type of a texture that contains depth data. Typically used for depth textures. * * @category Graphics */ declare const SAMPLETYPE_DEPTH: 2; /** * A sampler type of a texture that contains signed integer data. * * @category Graphics */ declare const SAMPLETYPE_INT: 3; /** * A sampler type of a texture that contains unsigned integer data. * * @category Graphics */ declare const SAMPLETYPE_UINT: 4; /** * Texture data is not stored a specific projection format. * * @category Graphics */ declare const TEXTUREPROJECTION_NONE: "none"; /** * Texture data is stored in cubemap projection format. * * @category Graphics */ declare const TEXTUREPROJECTION_CUBE: "cube"; /** * Texture data is stored in equirectangular projection format. * * @category Graphics */ declare const TEXTUREPROJECTION_EQUIRECT: "equirect"; /** * Texture data is stored in octahedral projection format. * * @category Graphics */ declare const TEXTUREPROJECTION_OCTAHEDRAL: "octahedral"; /** * Shader source code uses GLSL language. * * @category Graphics */ declare const SHADERLANGUAGE_GLSL: "glsl"; /** * Shader source code uses WGSL language. * * @category Graphics */ declare const SHADERLANGUAGE_WGSL: "wgsl"; /** * Signed byte vertex element type. * * @category Graphics */ declare const TYPE_INT8: 0; /** * Unsigned byte vertex element type. * * @category Graphics */ declare const TYPE_UINT8: 1; /** * Signed short vertex element type. * * @category Graphics */ declare const TYPE_INT16: 2; /** * Unsigned short vertex element type. * * @category Graphics */ declare const TYPE_UINT16: 3; /** * Signed integer vertex element type. * * @category Graphics */ declare const TYPE_INT32: 4; /** * Unsigned integer vertex element type. * * @category Graphics */ declare const TYPE_UINT32: 5; /** * Floating point vertex element type. * * @category Graphics */ declare const TYPE_FLOAT32: 6; /** * 16-bit floating point vertex element type. * * @category Graphics */ declare const TYPE_FLOAT16: 7; /** * Boolean uniform type. * * @category Graphics */ declare const UNIFORMTYPE_BOOL: 0; /** * Integer uniform type. * * @category Graphics */ declare const UNIFORMTYPE_INT: 1; /** * Float uniform type. * * @category Graphics */ declare const UNIFORMTYPE_FLOAT: 2; /** * 2 x Float uniform type. * * @category Graphics */ declare const UNIFORMTYPE_VEC2: 3; /** * 3 x Float uniform type. * * @category Graphics */ declare const UNIFORMTYPE_VEC3: 4; /** * 4 x Float uniform type. * * @category Graphics */ declare const UNIFORMTYPE_VEC4: 5; /** * 2 x Integer uniform type. * * @category Graphics */ declare const UNIFORMTYPE_IVEC2: 6; /** * 3 x Integer uniform type. * * @category Graphics */ declare const UNIFORMTYPE_IVEC3: 7; /** * 4 x Integer uniform type. * * @category Graphics */ declare const UNIFORMTYPE_IVEC4: 8; /** * 2 x Boolean uniform type. * * @category Graphics */ declare const UNIFORMTYPE_BVEC2: 9; /** * 3 x Boolean uniform type. * * @category Graphics */ declare const UNIFORMTYPE_BVEC3: 10; /** * 4 x Boolean uniform type. * * @category Graphics */ declare const UNIFORMTYPE_BVEC4: 11; /** * 2 x 2 x Float uniform type. * * @category Graphics */ declare const UNIFORMTYPE_MAT2: 12; /** * 3 x 3 x Float uniform type. * * @category Graphics */ declare const UNIFORMTYPE_MAT3: 13; /** * 4 x 4 x Float uniform type. * * @category Graphics */ declare const UNIFORMTYPE_MAT4: 14; declare const UNIFORMTYPE_TEXTURE2D: 15; declare const UNIFORMTYPE_TEXTURECUBE: 16; declare const UNIFORMTYPE_FLOATARRAY: 17; declare const UNIFORMTYPE_TEXTURE2D_SHADOW: 18; declare const UNIFORMTYPE_TEXTURECUBE_SHADOW: 19; declare const UNIFORMTYPE_TEXTURE3D: 20; declare const UNIFORMTYPE_VEC2ARRAY: 21; declare const UNIFORMTYPE_VEC3ARRAY: 22; declare const UNIFORMTYPE_VEC4ARRAY: 23; declare const UNIFORMTYPE_MAT4ARRAY: 24; declare const UNIFORMTYPE_TEXTURE2D_ARRAY: 25; /** * Unsigned integer uniform type. * * @category Graphics */ declare const UNIFORMTYPE_UINT: 26; /** * 2 x Unsigned integer uniform type. * * @category Graphics */ declare const UNIFORMTYPE_UVEC2: 27; /** * 3 x Unsigned integer uniform type. * * @category Graphics */ declare const UNIFORMTYPE_UVEC3: 28; /** * 4 x Unsigned integer uniform type. * * @category Graphics */ declare const UNIFORMTYPE_UVEC4: 29; declare const UNIFORMTYPE_INTARRAY: 30; declare const UNIFORMTYPE_UINTARRAY: 31; declare const UNIFORMTYPE_BOOLARRAY: 32; declare const UNIFORMTYPE_IVEC2ARRAY: 33; declare const UNIFORMTYPE_UVEC2ARRAY: 34; declare const UNIFORMTYPE_BVEC2ARRAY: 35; declare const UNIFORMTYPE_IVEC3ARRAY: 36; declare const UNIFORMTYPE_UVEC3ARRAY: 37; declare const UNIFORMTYPE_BVEC3ARRAY: 38; declare const UNIFORMTYPE_IVEC4ARRAY: 39; declare const UNIFORMTYPE_UVEC4ARRAY: 40; declare const UNIFORMTYPE_BVEC4ARRAY: 41; declare const UNIFORMTYPE_ITEXTURE2D: 42; declare const UNIFORMTYPE_UTEXTURE2D: 43; declare const UNIFORMTYPE_ITEXTURECUBE: 44; declare const UNIFORMTYPE_UTEXTURECUBE: 45; declare const UNIFORMTYPE_ITEXTURE3D: 46; declare const UNIFORMTYPE_UTEXTURE3D: 47; declare const UNIFORMTYPE_ITEXTURE2D_ARRAY: 48; declare const UNIFORMTYPE_UTEXTURE2D_ARRAY: 49; declare const uniformTypeToName: string[]; declare const uniformTypeToNameWGSL: string[][]; declare const uniformTypeToNameMapWGSL: Map; declare const uniformTypeToStorage: Uint8Array; /** * A WebGL 2 device type. * * @category Graphics */ declare const DEVICETYPE_WEBGL2: "webgl2"; /** * A WebGL 2 device type with only the extensions available on 99%+ of devices exposed, and * capabilities clamped to the values 99%+ of devices report. Useful for testing engine behavior * on the most constrained WebGL 2 devices (e.g. no multi-draw, no float texture filtering, no * compressed textures, 4k textures). * * @category Graphics */ declare const DEVICETYPE_WEBGL2_BARE: "webgl2:bare"; /** * A WebGPU device type. * * @category Graphics */ declare const DEVICETYPE_WEBGPU: "webgpu"; /** * A WebGPU device type with no optional features requested and default spec limits. Useful for * testing engine behavior on the most constrained WebGPU devices (e.g. no compressed textures, no * float32-filterable, no timestamp-query). * * @category Graphics */ declare const DEVICETYPE_WEBGPU_BARE: "webgpu:bare"; /** * A Null device type. * * @category Graphics */ declare const DEVICETYPE_NULL: "null"; /** * The resource is visible to the vertex shader. * * @category Graphics */ declare const SHADERSTAGE_VERTEX: 1; /** * The resource is visible to the fragment shader. * * @category Graphics */ declare const SHADERSTAGE_FRAGMENT: 2; /** * The resource is visible to the compute shader. * * @category Graphics */ declare const SHADERSTAGE_COMPUTE: 4; /** * Display format for low dynamic range data. This is always supported; however, due to the cost, it * does not implement linear alpha blending on the main framebuffer. Instead, alpha blending occurs * in sRGB space. * * @category Graphics */ declare const DISPLAYFORMAT_LDR: "ldr"; /** * Display format for low dynamic range data in the sRGB color space. This format correctly * implements linear alpha blending on the main framebuffer, with the alpha blending occurring in * linear space. This is currently supported on WebGPU platform only. On unsupported platforms, it * silently falls back to {@link DISPLAYFORMAT_LDR}. * * @category Graphics */ declare const DISPLAYFORMAT_LDR_SRGB: "ldr_srgb"; /** * Display format for high dynamic range data, using 16bit floating point values. * Note: This is supported on WebGPU platform only, and ignored on other platforms. On displays * without HDR support, it silently falls back to {@link DISPLAYFORMAT_LDR}. Use * {@link GraphicsDevice.isHdr} to see if the HDR format is used. When it is, it's recommended to * use {@link TONEMAP_NONE} for the tonemapping mode, to avoid it clipping the high dynamic range. * * @category Graphics */ declare const DISPLAYFORMAT_HDR: "hdr"; declare const TEXPROPERTY_MIN_FILTER: 1; declare const TEXPROPERTY_MAG_FILTER: 2; declare const TEXPROPERTY_ADDRESS_U: 4; declare const TEXPROPERTY_ADDRESS_V: 8; declare const TEXPROPERTY_ADDRESS_W: 16; declare const TEXPROPERTY_COMPARE_ON_READ: 32; declare const TEXPROPERTY_COMPARE_FUNC: 64; declare const TEXPROPERTY_ANISOTROPY: 128; declare const TEXPROPERTY_ALL: 255; declare const BINDGROUP_VIEW: 0; declare const BINDGROUP_MATERIAL: 1; declare const BINDGROUP_MESH: 2; declare const BINDGROUP_MESH_UB: 3; declare const bindGroupNames: string[]; declare const UNIFORM_BUFFER_DEFAULT_SLOT_NAME: "default"; declare const UNUSED_UNIFORM_NAME: "_unused_float_uniform"; declare const typedArrayTypes: (Int8ArrayConstructor | Uint8ArrayConstructor | Int16ArrayConstructor | Uint16ArrayConstructor | Int32ArrayConstructor | Uint32ArrayConstructor | Float32ArrayConstructor)[]; declare const typedArrayTypesByteSize: number[]; declare const vertexTypesNames: string[]; declare namespace typedArrayToType { export { TYPE_INT8 as Int8Array }; export { TYPE_UINT8 as Uint8Array }; export { TYPE_INT16 as Int16Array }; export { TYPE_UINT16 as Uint16Array }; export { TYPE_INT32 as Int32Array }; export { TYPE_UINT32 as Uint32Array }; export { TYPE_FLOAT32 as Float32Array }; } declare const typedArrayIndexFormats: (Uint8ArrayConstructor | Uint16ArrayConstructor | Uint32ArrayConstructor)[]; declare const typedArrayIndexFormatsByteSize: number[]; declare const primitiveGlslToWgslTypeMap: Map; /** * Map of engine semantics into location on device in range 0..15 (note - semantics mapping to the * same location cannot be used at the same time) organized in a way that ATTR0-ATTR7 do not * overlap with common important semantics. * * @type {object} * @ignore * @category Graphics */ declare const semanticToLocation: object; declare const ACTION_MOUSE: "mouse"; declare const ACTION_KEYBOARD: "keyboard"; declare const ACTION_GAMEPAD: "gamepad"; declare const AXIS_MOUSE_X: "mousex"; declare const AXIS_MOUSE_Y: "mousey"; declare const AXIS_PAD_L_X: "padlx"; declare const AXIS_PAD_L_Y: "padly"; declare const AXIS_PAD_R_X: "padrx"; declare const AXIS_PAD_R_Y: "padry"; declare const AXIS_KEY: "key"; /** * @type {number} * @category Input Devices */ declare const KEY_BACKSPACE: number; /** * @type {number} * @category Input Devices */ declare const KEY_TAB: number; /** * @type {number} * @category Input Devices */ declare const KEY_RETURN: number; /** * @type {number} * @category Input Devices */ declare const KEY_ENTER: number; /** * @type {number} * @category Input Devices */ declare const KEY_SHIFT: number; /** * @type {number} * @category Input Devices */ declare const KEY_CONTROL: number; /** * @type {number} * @category Input Devices */ declare const KEY_ALT: number; /** * @type {number} * @category Input Devices */ declare const KEY_PAUSE: number; /** * @type {number} * @category Input Devices */ declare const KEY_CAPS_LOCK: number; /** * @type {number} * @category Input Devices */ declare const KEY_ESCAPE: number; /** * @type {number} * @category Input Devices */ declare const KEY_SPACE: number; /** * @type {number} * @category Input Devices */ declare const KEY_PAGE_UP: number; /** * @type {number} * @category Input Devices */ declare const KEY_PAGE_DOWN: number; /** * @type {number} * @category Input Devices */ declare const KEY_END: number; /** * @type {number} * @category Input Devices */ declare const KEY_HOME: number; /** * @type {number} * @category Input Devices */ declare const KEY_LEFT: number; /** * @type {number} * @category Input Devices */ declare const KEY_UP: number; /** * @type {number} * @category Input Devices */ declare const KEY_RIGHT: number; /** * @type {number} * @category Input Devices */ declare const KEY_DOWN: number; /** * @type {number} * @category Input Devices */ declare const KEY_PRINT_SCREEN: number; /** * @type {number} * @category Input Devices */ declare const KEY_INSERT: number; /** * @type {number} * @category Input Devices */ declare const KEY_DELETE: number; /** * @type {number} * @category Input Devices */ declare const KEY_0: number; /** * @type {number} * @category Input Devices */ declare const KEY_1: number; /** * @type {number} * @category Input Devices */ declare const KEY_2: number; /** * @type {number} * @category Input Devices */ declare const KEY_3: number; /** * @type {number} * @category Input Devices */ declare const KEY_4: number; /** * @type {number} * @category Input Devices */ declare const KEY_5: number; /** * @type {number} * @category Input Devices */ declare const KEY_6: number; /** * @type {number} * @category Input Devices */ declare const KEY_7: number; /** * @type {number} * @category Input Devices */ declare const KEY_8: number; /** * @type {number} * @category Input Devices */ declare const KEY_9: number; /** * @type {number} * @category Input Devices */ declare const KEY_SEMICOLON: number; /** * @type {number} * @category Input Devices */ declare const KEY_EQUAL: number; /** * @type {number} * @category Input Devices */ declare const KEY_A: number; /** * @type {number} * @category Input Devices */ declare const KEY_B: number; /** * @type {number} * @category Input Devices */ declare const KEY_C: number; /** * @type {number} * @category Input Devices */ declare const KEY_D: number; /** * @type {number} * @category Input Devices */ declare const KEY_E: number; /** * @type {number} * @category Input Devices */ declare const KEY_F: number; /** * @type {number} * @category Input Devices */ declare const KEY_G: number; /** * @type {number} * @category Input Devices */ declare const KEY_H: number; /** * @type {number} * @category Input Devices */ declare const KEY_I: number; /** * @type {number} * @category Input Devices */ declare const KEY_J: number; /** * @type {number} * @category Input Devices */ declare const KEY_K: number; /** * @type {number} * @category Input Devices */ declare const KEY_L: number; /** * @type {number} * @category Input Devices */ declare const KEY_M: number; /** * @type {number} * @category Input Devices */ declare const KEY_N: number; /** * @type {number} * @category Input Devices */ declare const KEY_O: number; /** * @type {number} * @category Input Devices */ declare const KEY_P: number; /** * @type {number} * @category Input Devices */ declare const KEY_Q: number; /** * @type {number} * @category Input Devices */ declare const KEY_R: number; /** * @type {number} * @category Input Devices */ declare const KEY_S: number; /** * @type {number} * @category Input Devices */ declare const KEY_T: number; /** * @type {number} * @category Input Devices */ declare const KEY_U: number; /** * @type {number} * @category Input Devices */ declare const KEY_V: number; /** * @type {number} * @category Input Devices */ declare const KEY_W: number; /** * @type {number} * @category Input Devices */ declare const KEY_X: number; /** * @type {number} * @category Input Devices */ declare const KEY_Y: number; /** * @type {number} * @category Input Devices */ declare const KEY_Z: number; /** * @type {number} * @category Input Devices */ declare const KEY_WINDOWS: number; /** * @type {number} * @category Input Devices */ declare const KEY_CONTEXT_MENU: number; /** * @type {number} * @category Input Devices */ declare const KEY_NUMPAD_0: number; /** * @type {number} * @category Input Devices */ declare const KEY_NUMPAD_1: number; /** * @type {number} * @category Input Devices */ declare const KEY_NUMPAD_2: number; /** * @type {number} * @category Input Devices */ declare const KEY_NUMPAD_3: number; /** * @type {number} * @category Input Devices */ declare const KEY_NUMPAD_4: number; /** * @type {number} * @category Input Devices */ declare const KEY_NUMPAD_5: number; /** * @type {number} * @category Input Devices */ declare const KEY_NUMPAD_6: number; /** * @type {number} * @category Input Devices */ declare const KEY_NUMPAD_7: number; /** * @type {number} * @category Input Devices */ declare const KEY_NUMPAD_8: number; /** * @type {number} * @category Input Devices */ declare const KEY_NUMPAD_9: number; /** * @type {number} * @category Input Devices */ declare const KEY_MULTIPLY: number; /** * @type {number} * @category Input Devices */ declare const KEY_ADD: number; /** * @type {number} * @category Input Devices */ declare const KEY_SEPARATOR: number; /** * @type {number} * @category Input Devices */ declare const KEY_SUBTRACT: number; /** * @type {number} * @category Input Devices */ declare const KEY_DECIMAL: number; /** * @type {number} * @category Input Devices */ declare const KEY_DIVIDE: number; /** * @type {number} * @category Input Devices */ declare const KEY_F1: number; /** * @type {number} * @category Input Devices */ declare const KEY_F2: number; /** * @type {number} * @category Input Devices */ declare const KEY_F3: number; /** * @type {number} * @category Input Devices */ declare const KEY_F4: number; /** * @type {number} * @category Input Devices */ declare const KEY_F5: number; /** * @type {number} * @category Input Devices */ declare const KEY_F6: number; /** * @type {number} * @category Input Devices */ declare const KEY_F7: number; /** * @type {number} * @category Input Devices */ declare const KEY_F8: number; /** * @type {number} * @category Input Devices */ declare const KEY_F9: number; /** * @type {number} * @category Input Devices */ declare const KEY_F10: number; /** * @type {number} * @category Input Devices */ declare const KEY_F11: number; /** * @type {number} * @category Input Devices */ declare const KEY_F12: number; /** * @type {number} * @category Input Devices */ declare const KEY_COMMA: number; /** * @type {number} * @category Input Devices */ declare const KEY_PERIOD: number; /** * @type {number} * @category Input Devices */ declare const KEY_SLASH: number; /** * @type {number} * @category Input Devices */ declare const KEY_OPEN_BRACKET: number; /** * @type {number} * @category Input Devices */ declare const KEY_BACK_SLASH: number; /** * @type {number} * @category Input Devices */ declare const KEY_CLOSE_BRACKET: number; /** * @type {number} * @category Input Devices */ declare const KEY_META: number; /** * No mouse buttons pressed. * * @category Input Devices */ declare const MOUSEBUTTON_NONE: -1; /** * The left mouse button. * * @category Input Devices */ declare const MOUSEBUTTON_LEFT: 0; /** * The middle mouse button. * * @category Input Devices */ declare const MOUSEBUTTON_MIDDLE: 1; /** * The right mouse button. * * @category Input Devices */ declare const MOUSEBUTTON_RIGHT: 2; /** * Index for pad 1. * * @category Input Devices */ declare const PAD_1: 0; /** * Index for pad 2. * * @category Input Devices */ declare const PAD_2: 1; /** * Index for pad 3. * * @category Input Devices */ declare const PAD_3: 2; /** * Index for pad 4. * * @category Input Devices */ declare const PAD_4: 3; /** * The first face button, from bottom going clockwise. * * @category Input Devices */ declare const PAD_FACE_1: 0; /** * The second face button, from bottom going clockwise. * * @category Input Devices */ declare const PAD_FACE_2: 1; /** * The third face button, from bottom going clockwise. * * @category Input Devices */ declare const PAD_FACE_3: 2; /** * The fourth face button, from bottom going clockwise. * * @category Input Devices */ declare const PAD_FACE_4: 3; /** * The first shoulder button on the left. * * @category Input Devices */ declare const PAD_L_SHOULDER_1: 4; /** * The first shoulder button on the right. * * @category Input Devices */ declare const PAD_R_SHOULDER_1: 5; /** * The second shoulder button on the left. * * @category Input Devices */ declare const PAD_L_SHOULDER_2: 6; /** * The second shoulder button on the right. * * @category Input Devices */ declare const PAD_R_SHOULDER_2: 7; /** * The select button. * * @category Input Devices */ declare const PAD_SELECT: 8; /** * The start button. * * @category Input Devices */ declare const PAD_START: 9; /** * The button when depressing the left analogue stick. * * @category Input Devices */ declare const PAD_L_STICK_BUTTON: 10; /** * The button when depressing the right analogue stick. * * @category Input Devices */ declare const PAD_R_STICK_BUTTON: 11; /** * Direction pad up. * * @category Input Devices */ declare const PAD_UP: 12; /** * Direction pad down. * * @category Input Devices */ declare const PAD_DOWN: 13; /** * Direction pad left. * * @category Input Devices */ declare const PAD_LEFT: 14; /** * Direction pad right. * * @category Input Devices */ declare const PAD_RIGHT: 15; /** * Vendor specific button. * * @category Input Devices */ declare const PAD_VENDOR: 16; /** * Horizontal axis on the left analogue stick. * * @category Input Devices */ declare const PAD_L_STICK_X: 0; /** * Vertical axis on the left analogue stick. * * @category Input Devices */ declare const PAD_L_STICK_Y: 1; /** * Horizontal axis on the right analogue stick. * * @category Input Devices */ declare const PAD_R_STICK_X: 2; /** * Vertical axis on the right analogue stick. * * @category Input Devices */ declare const PAD_R_STICK_Y: 3; /** * Horizontal axis on the touchpad of an XR pad. * * @category Input Devices */ declare const XRPAD_TOUCHPAD_X: 0; /** * Vertical axis on the touchpad of an XR pad. * * @category Input Devices */ declare const XRPAD_TOUCHPAD_Y: 1; /** * Horizontal axis on the stick of an XR pad. * * @category Input Devices */ declare const XRPAD_STICK_X: 2; /** * Vertical axis on the stick of an XR pad. * * @category Input Devices */ declare const XRPAD_STICK_Y: 3; /** * The button when pressing the XR pad's touchpad. * * @category Input Devices */ declare const XRPAD_TOUCHPAD_BUTTON: 2; /** * The trigger button from XR pad. * * @category Input Devices */ declare const XRPAD_TRIGGER: 0; /** * The squeeze button from XR pad. * * @category Input Devices */ declare const XRPAD_SQUEEZE: 1; /** * The button when pressing the XR pad's stick. * * @category Input Devices */ declare const XRPAD_STICK_BUTTON: 3; /** * The A button from XR pad. * * @category Input Devices */ declare const XRPAD_A: 4; /** * The B button from XR pad. * * @category Input Devices */ declare const XRPAD_B: 5; /** * Linear distance model. * * @category Sound */ declare const DISTANCE_LINEAR: "linear"; /** * Inverse distance model. * * @category Sound */ declare const DISTANCE_INVERSE: "inverse"; /** * Exponential distance model. * * @category Sound */ declare const DISTANCE_EXPONENTIAL: "exponential"; /** * Subtract the color of the source fragment from the destination fragment and write the result to * the frame buffer. * * @category Graphics */ declare const BLEND_SUBTRACTIVE: 0; /** * Add the color of the source fragment to the destination fragment and write the result to the * frame buffer. * * @category Graphics */ declare const BLEND_ADDITIVE: 1; /** * Enable simple translucency for materials such as glass. This is equivalent to enabling a source * blend mode of {@link BLENDMODE_SRC_ALPHA} and a destination blend mode of * {@link BLENDMODE_ONE_MINUS_SRC_ALPHA}. * * @category Graphics */ declare const BLEND_NORMAL: 2; /** * Disable blending. * * @category Graphics */ declare const BLEND_NONE: 3; /** * Similar to {@link BLEND_NORMAL} expect the source fragment is assumed to have already been * multiplied by the source alpha value. * * @category Graphics */ declare const BLEND_PREMULTIPLIED: 4; /** * Multiply the color of the source fragment by the color of the destination fragment and write the * result to the frame buffer. * * @category Graphics */ declare const BLEND_MULTIPLICATIVE: 5; /** * Same as {@link BLEND_ADDITIVE} except the source RGB is multiplied by the source alpha. * * @category Graphics */ declare const BLEND_ADDITIVEALPHA: 6; /** * Multiplies colors and doubles the result. * * @category Graphics */ declare const BLEND_MULTIPLICATIVE2X: 7; /** * Softer version of additive. * * @category Graphics */ declare const BLEND_SCREEN: 8; /** * Minimum color. * * @category Graphics */ declare const BLEND_MIN: 9; /** * Maximum color. * * @category Graphics */ declare const BLEND_MAX: 10; declare const blendNames: { 0: string; 1: string; 2: string; 3: string; 4: string; 5: string; 6: string; 7: string; 8: string; 9: string; 10: string; }; /** * No fog is applied to the scene. * * @category Graphics */ declare const FOG_NONE: "none"; /** * Fog rises linearly from zero to 1 between a start and end depth. * * @category Graphics */ declare const FOG_LINEAR: "linear"; /** * Fog rises according to an exponential curve controlled by a density value. * * @category Graphics */ declare const FOG_EXP: "exp"; /** * Fog rises according to an exponential curve controlled by a density value. * * @category Graphics */ declare const FOG_EXP2: "exp2"; /** * No Fresnel. * * @category Graphics */ declare const FRESNEL_NONE: 0; /** * Schlick's approximation of Fresnel. * * @category Graphics */ declare const FRESNEL_SCHLICK: 2; declare const fresnelNames: { 0: string; 2: string; }; declare const LAYER_HUD: 0; declare const LAYER_GIZMO: 1; declare const LAYER_WORLD: 15; /** * The world layer. * * @category Graphics */ declare const LAYERID_WORLD: 0; /** * The depth layer. * * @category Graphics */ declare const LAYERID_DEPTH: 1; /** * The skybox layer. * * @category Graphics */ declare const LAYERID_SKYBOX: 2; /** * The immediate layer. * * @category Graphics */ declare const LAYERID_IMMEDIATE: 3; /** * The UI layer. * * @category Graphics */ declare const LAYERID_UI: 4; /** * Directional (global) light source. * * @category Graphics */ declare const LIGHTTYPE_DIRECTIONAL: 0; /** * Omni-directional (local) light source. * * @category Graphics */ declare const LIGHTTYPE_OMNI: 1; /** * Point (local) light source. * * @ignore * @category Graphics */ declare const LIGHTTYPE_POINT: 1; /** * Spot (local) light source. * * @category Graphics */ declare const LIGHTTYPE_SPOT: 2; declare const LIGHTTYPE_COUNT: 3; declare const lightTypeNames: { 0: string; 1: string; 2: string; }; declare const LIGHT_COLOR_DIVIDER: 100; /** * Infinitesimally small point light source shape. * * @category Graphics */ declare const LIGHTSHAPE_PUNCTUAL: 0; /** * Rectangle shape of light source. * * @category Graphics */ declare const LIGHTSHAPE_RECT: 1; /** * Disk shape of light source. * * @category Graphics */ declare const LIGHTSHAPE_DISK: 2; /** * Sphere shape of light source. * * @category Graphics */ declare const LIGHTSHAPE_SPHERE: 3; declare const lightShapeNames: { 0: string; 1: string; 2: string; 3: string; }; /** * Linear distance falloff model for light attenuation. * * @category Graphics */ declare const LIGHTFALLOFF_LINEAR: 0; /** * Inverse squared distance falloff model for light attenuation. * * @category Graphics */ declare const LIGHTFALLOFF_INVERSESQUARED: 1; declare const lightFalloffNames: { 0: string; 1: string; }; /** * A shadow sampling technique using 32bit shadow map that averages depth comparisons from a 3x3 * grid of texels for softened shadow edges. * * @category Graphics */ declare const SHADOW_PCF3_32F: 0; /** * @deprecated * @ignore */ declare const SHADOW_PCF3: 0; /** * A shadow sampling technique using a 16-bit exponential variance shadow map that leverages * variance to approximate shadow boundaries, enabling soft shadows. Only supported when * {@link GraphicsDevice#textureHalfFloatRenderable} is true. Falls back to {@link SHADOW_PCF3_32F}, * if not supported. * * @category Graphics */ declare const SHADOW_VSM_16F: 2; /** * @deprecated * @ignore */ declare const SHADOW_VSM16: 2; /** * A shadow sampling technique using a 32-bit exponential variance shadow map that leverages * variance to approximate shadow boundaries, enabling soft shadows. Only supported when * {@link GraphicsDevice#textureFloatRenderable} is true. Falls back to {@link SHADOW_VSM_16F}, if * not supported. * * @category Graphics */ declare const SHADOW_VSM_32F: 3; /** * @deprecated * @ignore */ declare const SHADOW_VSM32: 3; /** * A shadow sampling technique using 32bit shadow map that averages depth comparisons from a 5x5 * grid of texels for softened shadow edges. * * @category Graphics */ declare const SHADOW_PCF5_32F: 4; /** * @deprecated * @ignore */ declare const SHADOW_PCF5: 4; /** * A shadow sampling technique using a 32-bit shadow map that performs a single depth comparison for * sharp shadow edges. * * @category Graphics */ declare const SHADOW_PCF1_32F: 5; /** * @deprecated * @ignore */ declare const SHADOW_PCF1: 5; /** * A shadow sampling technique using a 32-bit shadow map that adjusts filter size based on blocker * distance, producing realistic, soft shadow edges that vary with the light's occlusion. Note that * this technique requires both {@link GraphicsDevice#textureFloatRenderable} and * {@link GraphicsDevice#textureFloatFilterable} to be true, and falls back to * {@link SHADOW_PCF3_32F} otherwise. * * @category Graphics */ declare const SHADOW_PCSS_32F: 6; /** * A shadow sampling technique using a 16-bit shadow map that performs a single depth comparison for * sharp shadow edges. * * @category Graphics */ declare const SHADOW_PCF1_16F: 7; /** * A shadow sampling technique using 16-bit shadow map that averages depth comparisons from a 3x3 * grid of texels for softened shadow edges. * * @category Graphics */ declare const SHADOW_PCF3_16F: 8; /** * A shadow sampling technique using 16-bit shadow map that averages depth comparisons from a 3x3 * grid of texels for softened shadow edges. * * @category Graphics */ declare const SHADOW_PCF5_16F: 9; /** * Information about shadow types. * * @type {Map} * @ignore */ declare const shadowTypeInfo: Map; /** * The flag that controls shadow rendering for the 0 cascade * * @category Graphics */ declare const SHADOW_CASCADE_0: 1; /** * The flag that controls shadow rendering for the 1 cascade * * @category Graphics */ declare const SHADOW_CASCADE_1: 2; /** * The flag that controls shadow rendering for the 2 cascade * * @category Graphics */ declare const SHADOW_CASCADE_2: 4; /** * The flag that controls shadow rendering for the 3 cascade * * @category Graphics */ declare const SHADOW_CASCADE_3: 8; /** * The flag that controls shadow rendering for the all cascades * * @category Graphics */ declare const SHADOW_CASCADE_ALL: 255; /** * Box filter. * * @category Graphics */ declare const BLUR_BOX: 0; /** * Gaussian filter. May look smoother than box, but requires more samples. * * @category Graphics */ declare const BLUR_GAUSSIAN: 1; /** * No sorting, particles are drawn in arbitrary order. Can be simulated on GPU. * * @category Graphics */ declare const PARTICLESORT_NONE: 0; /** * Sorting based on distance to the camera. CPU only. * * @category Graphics */ declare const PARTICLESORT_DISTANCE: 1; /** * Newer particles are drawn first. CPU only. * * @category Graphics */ declare const PARTICLESORT_NEWER_FIRST: 2; /** * Older particles are drawn first. CPU only. * * @category Graphics */ declare const PARTICLESORT_OLDER_FIRST: 3; declare const PARTICLEMODE_GPU: 0; declare const PARTICLEMODE_CPU: 1; /** * Box shape parameterized by emitterExtents. Initial velocity is directed towards local Z axis. * * @category Graphics */ declare const EMITTERSHAPE_BOX: 0; /** * Sphere shape parameterized by emitterRadius. Initial velocity is directed outwards from the * center. * * @category Graphics */ declare const EMITTERSHAPE_SPHERE: 1; /** * Particles are facing camera. * * @category Graphics */ declare const PARTICLEORIENTATION_SCREEN: 0; /** * User defines world space normal (particleNormal) to set planes orientation. * * @category Graphics */ declare const PARTICLEORIENTATION_WORLD: 1; /** * Similar to previous, but the normal is affected by emitter(entity) transformation. * * @category Graphics */ declare const PARTICLEORIENTATION_EMITTER: 2; /** * A perspective camera projection where the frustum shape is essentially pyramidal. * * @category Graphics */ declare const PROJECTION_PERSPECTIVE: 0; /** * An orthographic camera projection where the frustum shape is essentially a cuboid. * * @category Graphics */ declare const PROJECTION_ORTHOGRAPHIC: 1; /** * Render mesh instance as solid geometry. * * @category Graphics */ declare const RENDERSTYLE_SOLID: 0; /** * Render mesh instance as wireframe. * * @category Graphics */ declare const RENDERSTYLE_WIREFRAME: 1; /** * Render mesh instance as points. * * @category Graphics */ declare const RENDERSTYLE_POINTS: 2; /** * The cube map is treated as if it is infinitely far away. * * @category Graphics */ declare const CUBEPROJ_NONE: 0; /** * The cube map is box-projected based on a world space axis-aligned bounding box. * * @category Graphics */ declare const CUBEPROJ_BOX: 1; declare const cubemaProjectionNames: { 0: string; 1: string; }; /** * Multiply together the primary and secondary colors. * * @category Graphics */ declare const DETAILMODE_MUL: "mul"; /** * Add together the primary and secondary colors. * * @category Graphics */ declare const DETAILMODE_ADD: "add"; /** * Softer version of {@link DETAILMODE_ADD}. * * @category Graphics */ declare const DETAILMODE_SCREEN: "screen"; /** * Multiplies or screens the colors, depending on the primary color. * * @category Graphics */ declare const DETAILMODE_OVERLAY: "overlay"; /** * Select whichever of the primary and secondary colors is darker, component-wise. * * @category Graphics */ declare const DETAILMODE_MIN: "min"; /** * Select whichever of the primary and secondary colors is lighter, component-wise. * * @category Graphics */ declare const DETAILMODE_MAX: "max"; /** * No gamma correction. * * @category Graphics */ declare const GAMMA_NONE: 0; /** * Apply sRGB gamma correction. * * @category Graphics */ declare const GAMMA_SRGB: 1; declare const gammaNames: { 0: string; 1: string; }; /** * Linear tonemapping. The colors are preserved, but the exposure is applied. * * @category Graphics */ declare const TONEMAP_LINEAR: 0; /** * Filmic tonemapping curve. * * @category Graphics */ declare const TONEMAP_FILMIC: 1; /** * Hejl filmic tonemapping curve. * * @category Graphics */ declare const TONEMAP_HEJL: 2; /** * ACES filmic tonemapping curve. * * @category Graphics */ declare const TONEMAP_ACES: 3; /** * ACES v2 filmic tonemapping curve. * * @category Graphics */ declare const TONEMAP_ACES2: 4; /** * Khronos PBR Neutral tonemapping curve. * * @category Graphics */ declare const TONEMAP_NEUTRAL: 5; /** * No tonemapping or exposure is applied. Used for HDR rendering. * * @category Graphics */ declare const TONEMAP_NONE: 6; declare const tonemapNames: string[]; /** * No specular occlusion. * * @category Graphics */ declare const SPECOCC_NONE: 0; /** * Use AO directly to occlude specular. * * @category Graphics */ declare const SPECOCC_AO: 1; /** * Modify AO based on material glossiness/view angle to occlude specular. * * @category Graphics */ declare const SPECOCC_GLOSSDEPENDENT: 2; declare const specularOcclusionNames: { 0: string; 1: string; 2: string; }; declare const REFLECTIONSRC_NONE: "none"; declare const REFLECTIONSRC_ENVATLAS: "envAtlas"; declare const REFLECTIONSRC_ENVATLASHQ: "envAtlasHQ"; declare const REFLECTIONSRC_CUBEMAP: "cubeMap"; declare const REFLECTIONSRC_SPHEREMAP: "sphereMap"; declare namespace reflectionSrcNames { let none: string; let envAtlas: string; let envAtlasHQ: string; let cubeMap: string; let sphereMap: string; } declare const AMBIENTSRC_AMBIENTSH: "ambientSH"; declare const AMBIENTSRC_ENVALATLAS: "envAtlas"; declare const AMBIENTSRC_CONSTANT: "constant"; declare namespace ambientSrcNames { export let ambientSH: string; let envAtlas_1: string; export { envAtlas_1 as envAtlas }; export let constant: string; } declare const SHADERDEF_NOSHADOW: 1; declare const SHADERDEF_SKIN: 2; declare const SHADERDEF_UV0: 4; declare const SHADERDEF_UV1: 8; declare const SHADERDEF_VCOLOR: 16; declare const SHADERDEF_INSTANCING: 32; declare const SHADERDEF_LM: 64; declare const SHADERDEF_DIRLM: 128; declare const SHADERDEF_SCREENSPACE: 256; declare const SHADERDEF_TANGENTS: 512; declare const SHADERDEF_MORPH_POSITION: 1024; declare const SHADERDEF_MORPH_NORMAL: 2048; declare const SHADERDEF_LMAMBIENT: 4096; declare const SHADERDEF_MORPH_TEXTURE_BASED_INT: 8192; declare const SHADERDEF_BATCH: 16384; declare const SHADERDEF_INSTANCEINDEX: 32768; declare const SHADERDEF_MASK_SHIFT: 24; /** * The shadow map is not to be updated. * * @category Graphics */ declare const SHADOWUPDATE_NONE: 0; /** * The shadow map is regenerated this frame and not on subsequent frames. * * @category Graphics */ declare const SHADOWUPDATE_THISFRAME: 1; /** * The shadow map is regenerated every frame. * * @category Graphics */ declare const SHADOWUPDATE_REALTIME: 2; /** * Light mask bit: on a light, it lights mesh instances that are lit at runtime rather than from a * lightmap; on a mesh instance, it is lit at runtime by such lights. This is the default mask * value of both {@link LightComponent#mask} and {@link MeshInstance#mask}. * * @ignore */ declare const MASK_AFFECT_DYNAMIC: 1; /** * Light mask bit: on a light, it lights mesh instances that are lightmapped; on a mesh instance, * it receives its lighting from a lightmap and is lit at runtime only by lights carrying this bit. * See {@link LightComponent#mask} and {@link MeshInstance#mask}. * * @ignore */ declare const MASK_AFFECT_LIGHTMAPPED: 2; /** * Light mask bit: on a light, it is baked into lightmaps by the {@link Lightmapper}; on a mesh * instance, it is a lightmap target that such lights bake into. See {@link LightComponent#mask} * and {@link MeshInstance#mask}. * * @ignore */ declare const MASK_BAKE: 4; /** * The light mask bits under which a light is applied at runtime. A light carrying none of them * contributes only to lightmaps, reaches no mesh instance while rendering, and so takes no light * slot in a shader. See {@link MASK_AFFECT_DYNAMIC} and {@link MASK_AFFECT_LIGHTMAPPED}. * * @ignore */ declare const MASK_AFFECT_RUNTIME: number; /** * Render shaded materials using forward rendering. * * @category Graphics */ declare const SHADER_FORWARD: 0; declare const SHADER_PREPASS: 1; declare const SHADER_SHADOW: 2; declare const SHADER_PICK: 3; declare const SHADER_DEPTH_PICK: 4; /** * Shader that performs forward rendering. * * @category Graphics */ declare const SHADERPASS_FORWARD: "forward"; /** * Shader used for debug rendering of albedo. * * @category Graphics */ declare const SHADERPASS_ALBEDO: "debug_albedo"; /** * Shader used for debug rendering of world normal. * * @category Graphics */ declare const SHADERPASS_WORLDNORMAL: "debug_world_normal"; /** * Shader used for debug rendering of opacity. * * @category Graphics */ declare const SHADERPASS_OPACITY: "debug_opacity"; /** * Shader used for debug rendering of specularity. * * @category Graphics */ declare const SHADERPASS_SPECULARITY: "debug_specularity"; /** * Shader used for debug rendering of gloss. * * @category Graphics */ declare const SHADERPASS_GLOSS: "debug_gloss"; /** * Shader used for debug rendering of metalness. * * @category Graphics */ declare const SHADERPASS_METALNESS: "debug_metalness"; /** * Shader used for debug rendering of ao. * * @category Graphics */ declare const SHADERPASS_AO: "debug_ao"; /** * Shader used for debug rendering of emission. * * @category Graphics */ declare const SHADERPASS_EMISSION: "debug_emission"; /** * Shader used for debug rendering of lighting. * * @category Graphics */ declare const SHADERPASS_LIGHTING: "debug_lighting"; /** * Shader used for debug rendering of UV0 texture coordinates. * * @category Graphics */ declare const SHADERPASS_UV0: "debug_uv0"; /** * This mode renders a sprite as a simple quad. * * @category Graphics */ declare const SPRITE_RENDERMODE_SIMPLE: 0; /** * This mode renders a sprite using 9-slicing in 'sliced' mode. Sliced mode stretches the top and * bottom regions of the sprite horizontally, the left and right regions vertically and the middle * region both horizontally and vertically. * * @category Graphics */ declare const SPRITE_RENDERMODE_SLICED: 1; /** * This mode renders a sprite using 9-slicing in 'tiled' mode. Tiled mode tiles the top and bottom * regions of the sprite horizontally, the left and right regions vertically and the middle region * both horizontally and vertically. * * @category Graphics */ declare const SPRITE_RENDERMODE_TILED: 2; declare const spriteRenderModeNames: { 0: string; 1: string; 2: string; }; /** * Single color lightmap. * * @category Graphics */ declare const BAKE_COLOR: 0; /** * Single color lightmap + dominant light direction (used for bump/specular). * * @category Graphics */ declare const BAKE_COLORDIR: 1; /** * Center of view. * * @category Graphics */ declare const VIEW_CENTER: 0; /** * Left of view. Only used in stereo rendering. * * @category Graphics */ declare const VIEW_LEFT: 1; /** * Right of view. Only used in stereo rendering. * * @category Graphics */ declare const VIEW_RIGHT: 2; /** * No sorting is applied. Mesh instances are rendered in the same order they were added to a layer. * * @category Graphics */ declare const SORTMODE_NONE: 0; /** * Mesh instances are sorted based on {@link MeshInstance#drawOrder}. * * @category Graphics */ declare const SORTMODE_MANUAL: 1; /** * Mesh instances are sorted to minimize switching between materials and meshes to improve * rendering performance. * * @category Graphics */ declare const SORTMODE_MATERIALMESH: 2; /** * Mesh instances are sorted back to front. This is the way to properly render many * semi-transparent objects on different depth, one is blended on top of another. * * @category Graphics */ declare const SORTMODE_BACK2FRONT: 3; /** * Mesh instances are sorted front to back. Depending on GPU and the scene, this option may give * better performance than {@link SORTMODE_MATERIALMESH} due to reduced overdraw. * * @category Graphics */ declare const SORTMODE_FRONT2BACK: 4; /** * Provide custom functions for sorting drawcalls and calculating distance. * * @ignore * @category Graphics */ declare const SORTMODE_CUSTOM: 5; /** * Automatically set aspect ratio to current render target's width divided by height. * * @category Graphics */ declare const ASPECT_AUTO: 0; /** * Use the manual aspect ratio value. * * @category Graphics */ declare const ASPECT_MANUAL: 1; /** * Horizontal orientation. * * @category Graphics */ declare const ORIENTATION_HORIZONTAL: 0; /** * Vertical orientation. * * @category Graphics */ declare const ORIENTATION_VERTICAL: 1; /** * A sky texture is rendered using an infinite projection. * * @category Graphics */ declare const SKYTYPE_INFINITE: "infinite"; /** * A sky texture is rendered using a box projection. This is generally suitable for interior * environments. * * @category Graphics */ declare const SKYTYPE_BOX: "box"; /** * A sky texture is rendered using a dome projection. This is generally suitable for exterior * environments. * * @category Graphics */ declare const SKYTYPE_DOME: "dome"; /** * Opacity dithering is disabled. * * @category Graphics */ declare const DITHER_NONE: "none"; /** * Opacity is dithered using a Bayer 2 matrix. * * @category Graphics */ declare const DITHER_BAYER2: "bayer2"; /** * Opacity is dithered using a Bayer 4 matrix. * * @category Graphics */ declare const DITHER_BAYER4: "bayer4"; /** * Opacity is dithered using a Bayer 8 matrix. * * @category Graphics */ declare const DITHER_BAYER8: "bayer8"; /** * Opacity is dithered using a Bayer 16 matrix. * * @category Graphics */ declare const DITHER_BAYER16: "bayer16"; /** * Opacity is dithered using a blue noise. * * @category Graphics */ declare const DITHER_BLUENOISE: "bluenoise"; /** * Opacity is dithered using an interleaved gradient noise. * * @category Graphics */ declare const DITHER_IGNNOISE: "ignnoise"; /** * Parallax mapping computes the uv offset from a single tap of the height map. This is the cheapest * option, and suits shallow surface detail. * * @category Graphics */ declare const PARALLAX_OFFSET: "offset"; /** * Parallax occlusion mapping marches the view ray through the height field to find where it meets * the displaced surface. This costs more than {@link PARALLAX_OFFSET}, but represents deeper * displacement without smearing the texture. * * @category Graphics */ declare const PARALLAX_OCCLUSION: "occlusion"; declare namespace parallaxNames { let offset: string; let occlusion: string; } declare namespace ditherNames { let none_1: string; export { none_1 as none }; export let bayer2: string; export let bayer4: string; export let bayer8: string; export let bayer16: string; export let bluenoise: string; export let ignnoise: string; } /** * Name of event fired before the camera renders the scene. * * @ignore */ declare const EVENT_PRERENDER: "prerender"; /** * Name of event fired after the camera renders the scene. * * @ignore */ declare const EVENT_POSTRENDER: "postrender"; /** * Name of event fired before a layer is rendered by a camera. * * @ignore */ declare const EVENT_PRERENDER_LAYER: "prerender:layer"; /** * Name of event fired after a layer is rendered by a camera. * * @ignore */ declare const EVENT_POSTRENDER_LAYER: "postrender:layer"; /** * Name of event fired before visibility culling is performed for the camera. * * @ignore */ declare const EVENT_PRECULL: "precull"; /** * Name of event after visibility culling is performed for the camera. * * @ignore */ declare const EVENT_POSTCULL: "postcull"; /** * Name of event after the engine has finished culling all cameras. * * @ignore */ declare const EVENT_CULL_END: "cull:end"; /** @ignore */ declare const GSPLAT_FORWARD: 1; /** @ignore */ declare const GSPLAT_SHADOW: 2; /** @ignore */ declare const SHADOWCAMERA_NAME: "pcShadowCamera"; /** * Work buffer is updated only when needed (transform, format, LOD changes, new gsplat etc). * * @type {number} * @category Graphics */ declare const WORKBUFFER_UPDATE_AUTO: number; /** * Work buffer is updated once on the next frame, then automatically switches to * {@link WORKBUFFER_UPDATE_AUTO}. * * @type {number} * @category Graphics */ declare const WORKBUFFER_UPDATE_ONCE: number; /** * Work buffer is updated every frame. Useful for custom shader code via * {@link GSplatComponent#setWorkBufferModifier} that depends on time or animated uniforms. * * @type {number} * @category Graphics */ declare const WORKBUFFER_UPDATE_ALWAYS: number; /** * Stream texture is stored at resource level, shared across all component instances. * * @type {number} * @category Graphics */ declare const GSPLAT_STREAM_RESOURCE: number; /** * Stream texture is stored per gsplat component instance. * * @type {number} * @category Graphics */ declare const GSPLAT_STREAM_INSTANCE: number; /** * Large work buffer data format with full precision. Uses RGBA16F color, float16 * rotation and float16 scale. 32 bytes per splat. * * @type {string} * @category Graphics */ declare const GSPLATDATA_LARGE: string; /** * Compact work buffer data format optimized for reduced memory and bandwidth. Uses 11+11+10 bit * RGB color, half-angle quaternion rotation and log-encoded scale. 20 bytes per splat. * * @type {string} * @category Graphics */ declare const GSPLATDATA_COMPACT: string; /** * Automatically selects the best rendering pipeline for the current platform. * * @type {number} * @category Graphics */ declare const GSPLAT_RENDERER_AUTO: number; /** * Rasterization-based rendering with CPU-side sorting. * * @type {number} * @category Graphics */ declare const GSPLAT_RENDERER_RASTER_CPU_SORT: number; /** * Rasterization-based rendering with GPU-side culling and sorting. WebGPU only. * * @type {number} * @category Graphics */ declare const GSPLAT_RENDERER_RASTER_GPU_SORT: number; declare const GSPLAT_RENDERER_COMPUTE: 3; /** * The splat budget is a target: LOD detail is raised until {@link GSplatParams#splatBudget} is * used up, wherever the camera is. The LOD distances of each GSplat still shape how detail falls * off with distance and how it divides between GSplats, but not how much of it there is. The * default. * * @category Graphics */ declare const GSPLAT_BUDGET_TARGET: "target"; /** * The splat budget is a limit: the LOD distances of each GSplat decide the detail, and * {@link GSplatParams#splatBudget} only lowers it when they would ask for more splats than it * allows. A distant GSplat uses only the few splats its distance calls for, leaving the rest of * the budget unused. * * @category Graphics */ declare const GSPLAT_BUDGET_LIMIT: "limit"; declare const GSPLAT_LODMODE_ERROR: "error"; declare const GSPLAT_LODMODE_DISTANCE: "distance"; /** * No debug rendering for Gaussian splats. Normal rendering mode. * * @type {number} * @category Graphics */ declare const GSPLAT_DEBUG_NONE: number; /** * Debug rendering that colorizes Gaussian splats by their selected LOD level. * * @type {number} * @category Graphics */ declare const GSPLAT_DEBUG_LOD: number; /** * Debug rendering that assigns a random color per spherical harmonics update pass, * visualizing when SH color updates occur. * * @type {number} * @category Graphics */ declare const GSPLAT_DEBUG_SH_UPDATE: number; declare const GSPLAT_DEBUG_HEATMAP: 3; /** * Debug rendering that draws world-space AABBs for each GSplat, colorized by LOD. * * @type {number} * @category Graphics */ declare const GSPLAT_DEBUG_AABBS: number; /** * Debug rendering that draws world-space AABBs for each octree node of streamed GSplats, * colorized by the currently selected LOD. * * @type {number} * @category Graphics */ declare const GSPLAT_DEBUG_NODE_AABBS: number; /** * Automatically selects the best radix sort backend for the current WebGPU device: * OneSweep on supported hardware (NVIDIA), the portable backend elsewhere. See * `ComputeRadixSort`. * * @type {number} * @ignore */ declare const RADIX_SORT_AUTO: number; /** * Portable radix sort backend. Runs on every WebGPU device (no subgroup * intrinsics required) and is chosen by {@link RADIX_SORT_AUTO} when no * faster hardware-specific backend is available. See `ComputeRadixSort`. * * @type {number} * @ignore */ declare const RADIX_SORT_PORTABLE: number; /** * Single-sweep 8-bit radix sort (OneSweep). Requires subgroup support, 32-lane * subgroups, and forward-thread-progress guarantees — currently enabled only on * NVIDIA. See `ComputeRadixSort`. * * @type {number} * @ignore */ declare const RADIX_SORT_ONESWEEP: number; /** * The name of the scene depth texture - a scene texture storing the linear depth of the scene, * rendered by the scene pass alongside the scene color. See * {@link CameraShaderParams#sceneTextures}. * * @type {string} * @ignore */ declare const SCENETEXTURE_DEPTH: string; /** * The uniform each scene texture is published under by the render pass which rendered it. Note that * the depth uses the same uniform as the depth prepass, as those are two producers of the same thing, * and the consumers sample whichever of them ran later in the frame. * * @type {Object} * @ignore */ declare const sceneTextureUniformNames: { [x: string]: string; }; /** * The uniforms a mesh instance publishes its own lightmaps under, the color lightmap first and the * directional one second, matching the order of the lightmapper's bake passes. The color one is * deliberately not `texture_lightMap`, the uniform of a lightmap assigned to a material, so that a * mesh instance keeping a lightmap of its own leaves the material's lightmap alone. A mesh instance * lightmap takes priority when both are present. * * @type {string[]} * @ignore */ declare const instanceLightmapUniformNames: string[]; /** * When resizing the window the size of the canvas will not change. */ declare const FILLMODE_NONE: "NONE"; /** * When resizing the window the size of the canvas will change to fill the window exactly. */ declare const FILLMODE_FILL_WINDOW: "FILL_WINDOW"; /** * When resizing the window the size of the canvas will change to fill the window as best it can, * while maintaining the same aspect ratio. */ declare const FILLMODE_KEEP_ASPECT: "KEEP_ASPECT"; /** * When the canvas is resized the resolution of the canvas will change to match the size of the * canvas. */ declare const RESOLUTION_AUTO: "AUTO"; /** * When the canvas is resized the resolution of the canvas will remain at the same value and the * output will just be scaled to fit the canvas. */ declare const RESOLUTION_FIXED: "FIXED"; /** * Specifies different color tints for the hover, pressed and inactive states. * * @category User Interface */ declare const BUTTON_TRANSITION_MODE_TINT: 0; /** * Specifies different sprites for the hover, pressed and inactive states. * * @category User Interface */ declare const BUTTON_TRANSITION_MODE_SPRITE_CHANGE: 1; /** * A {@link ElementComponent} that contains child {@link ElementComponent}s. * * @category User Interface */ declare const ELEMENTTYPE_GROUP: "group"; /** * A {@link ElementComponent} that displays an image. * * @category User Interface */ declare const ELEMENTTYPE_IMAGE: "image"; /** * A {@link ElementComponent} that displays text. * * @category User Interface */ declare const ELEMENTTYPE_TEXT: "text"; /** * Fit the content exactly to Element's bounding box. * * @category User Interface */ declare const FITMODE_STRETCH: "stretch"; /** * Fit the content within the Element's bounding box while preserving its Aspect Ratio. * * @category User Interface */ declare const FITMODE_CONTAIN: "contain"; /** * Fit the content to cover the entire Element's bounding box while preserving its Aspect Ratio. * * @category User Interface */ declare const FITMODE_COVER: "cover"; /** * @import { EventHandler } from './event-handler.js' * @import { HandleEventCallback } from './event-handler.js' */ /** * Event Handle that is created by {@link EventHandler} and can be used for easier event removal * and management. * * @example * const evt = obj.on('test', (a, b) => { * console.log(a + b); * }); * obj.fire('test'); * * evt.off(); // easy way to remove this event * obj.fire('test'); // this will not trigger an event * @example * // store an array of event handles * let events = []; * * events.push(objA.on('testA', () => {})); * events.push(objB.on('testB', () => {})); * * // when needed, remove all events * events.forEach((evt) => { * evt.off(); * }); * events = []; * @category Framework */ declare class EventHandle { /** * @param {EventHandler} handler - source object of the event. * @param {string} name - Name of the event. * @param {HandleEventCallback} callback - Function that is called when event is fired. * @param {object} scope - Object that is used as `this` when event is fired. * @param {boolean} [once] - If this is a single event and will be removed after event is fired. */ constructor(handler: EventHandler, name: string, callback: HandleEventCallback, scope: object, once?: boolean); /** * @type {EventHandler} * @private */ private handler; /** * @type {string} * @ignore */ name: string; /** * @type {HandleEventCallback} * @ignore */ callback: HandleEventCallback; /** * @type {object} * @ignore */ scope: object; /** * @type {boolean} * @ignore */ _once: boolean; /** * True if event has been removed. * * @private */ private _removed; /** * Remove this event from its handler. */ off(): void; on(name: any, callback: any, scope?: this): EventHandle; once(name: any, callback: any, scope?: this): EventHandle; /** * Mark if event has been removed. * * @type {boolean} * @ignore */ set removed(value: boolean); /** * True if event has been removed. * * @type {boolean} * @ignore */ get removed(): boolean; toJSON(key: any): any; } /** * Callback used by {@link EventHandler} functions. Note the callback is limited to 8 arguments. */ type HandleEventCallback = (arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any) => void; /** * @callback HandleEventCallback * Callback used by {@link EventHandler} functions. Note the callback is limited to 8 arguments. * @param {any} [arg1] - First argument that is passed from caller. * @param {any} [arg2] - Second argument that is passed from caller. * @param {any} [arg3] - Third argument that is passed from caller. * @param {any} [arg4] - Fourth argument that is passed from caller. * @param {any} [arg5] - Fifth argument that is passed from caller. * @param {any} [arg6] - Sixth argument that is passed from caller. * @param {any} [arg7] - Seventh argument that is passed from caller. * @param {any} [arg8] - Eighth argument that is passed from caller. * @returns {void} */ /** * Abstract base class that implements functionality for event handling. * * ```javascript * const obj = new EventHandlerSubclass(); * * // subscribe to an event * obj.on('hello', (str) => { * console.log('event hello is fired', str); * }); * * // fire event * obj.fire('hello', 'world'); * ``` * * @category Framework */ declare class EventHandler { /** * @type {Map>} * @private */ private _callbacks; /** * @type {Map>} * @private */ private _callbackActive; /** * Reinitialize the event handler. * @ignore */ initEventHandler(): void; /** * Registers a new event handler. * * @param {string} name - Name of the event to bind the callback to. * @param {HandleEventCallback} callback - Function that is called when event is fired. Note * the callback is limited to 8 arguments. * @param {object} scope - Object to use as 'this' when the event is fired, defaults to * current this. * @param {boolean} once - If true, the callback will be unbound after being fired once. * @returns {EventHandle} Created {@link EventHandle}. * @ignore */ _addCallback(name: string, callback: HandleEventCallback, scope: object, once: boolean): EventHandle; /** * Attach an event handler to an event. * * @param {string} name - Name of the event to bind the callback to. * @param {HandleEventCallback} callback - Function that is called when event is fired. Note * the callback is limited to 8 arguments. * @param {object} [scope] - Object to use as 'this' when the event is fired, defaults to * current this. * @returns {EventHandle} An event handle. For later removal, prefer retaining this handle and * calling its {@link EventHandle#off} over {@link EventHandler#off} with a name/callback: it * removes exactly this subscription and is faster (no scan of the callback list). * @example * obj.on('test', (a, b) => { * console.log(a + b); * }); * obj.fire('test', 1, 2); // prints 3 to the console * @example * // preferred removal: retain the handle and call off() on it * const evt = obj.on('test', (a, b) => { * console.log(a + b); * }); * // some time later * evt.off(); */ on(name: string, callback: HandleEventCallback, scope?: object): EventHandle; /** * Attach an event handler to an event. This handler will be removed after being fired once. * * @param {string} name - Name of the event to bind the callback to. * @param {HandleEventCallback} callback - Function that is called when event is fired. Note * the callback is limited to 8 arguments. * @param {object} [scope] - Object to use as 'this' when the event is fired, defaults to * current this. * @returns {EventHandle} An event handle. For removal before it fires, prefer retaining this * handle and calling its {@link EventHandle#off} over {@link EventHandler#off} with a * name/callback: it removes exactly this subscription and is faster (no scan of the callback * list). * @example * obj.once('test', (a, b) => { * console.log(a + b); * }); * obj.fire('test', 1, 2); // prints 3 to the console * obj.fire('test', 1, 2); // not going to get handled */ once(name: string, callback: HandleEventCallback, scope?: object): EventHandle; /** * Detach an event handler from an event. If callback is not provided then all callbacks are * unbound from the event, if scope is not provided then all events with the callback will be * unbound. * * Use this form to remove all listeners matching a name (and optionally callback/scope). To * remove a single known subscription, prefer retaining the {@link EventHandle} returned by * {@link EventHandler#on} / {@link EventHandler#once} and calling its {@link EventHandle#off}: * it removes exactly that subscription and is faster (no scan of the callback list). * * @param {string} [name] - Name of the event to unbind. * @param {HandleEventCallback} [callback] - Function to be unbound. * @param {object} [scope] - Scope that was used as the this when the event is fired. * @returns {EventHandler} Self for chaining. * @example * const handler = () => {}; * obj.on('test', handler); * * obj.off(); // Removes all events * obj.off('test'); // Removes all events called 'test' * obj.off('test', handler); // Removes all handler functions, called 'test' * obj.off('test', handler, this); // Removes all handler functions, called 'test' with scope this */ off(name?: string, callback?: HandleEventCallback, scope?: object): EventHandler; /** * Detach an event handler from an event using EventHandle instance. More optimal remove * as it does not have to scan callbacks array. * * @param {EventHandle} handle - Handle of event. * @ignore */ offByHandle(handle: EventHandle): this; /** * Fire an event, all additional arguments are passed on to the event listener. * * @param {string} name - Name of event to fire. * @param {any} [arg1] - First argument that is passed to the event handler. * @param {any} [arg2] - Second argument that is passed to the event handler. * @param {any} [arg3] - Third argument that is passed to the event handler. * @param {any} [arg4] - Fourth argument that is passed to the event handler. * @param {any} [arg5] - Fifth argument that is passed to the event handler. * @param {any} [arg6] - Sixth argument that is passed to the event handler. * @param {any} [arg7] - Seventh argument that is passed to the event handler. * @param {any} [arg8] - Eighth argument that is passed to the event handler. * @returns {EventHandler} Self for chaining. * @example * obj.fire('test', 'This is the message'); */ fire(name: string, arg1?: any, arg2?: any, arg3?: any, arg4?: any, arg5?: any, arg6?: any, arg7?: any, arg8?: any): EventHandler; /** * Test if there are any handlers bound to an event name. * * @param {string} name - The name of the event to test. * @returns {boolean} True if the object has handlers bound to the specified event name. * @example * obj.on('test', () => {}); // bind an event to 'test' * obj.hasEvent('test'); // returns true * obj.hasEvent('hello'); // returns false */ hasEvent(name: string): boolean; } declare class Version { globalId: number; revision: number; equals(other: any): boolean; copy(other: any): void; reset(): void; } declare class VersionedObject { version: Version; increment(): void; } /** * The scope for a variable. * * @category Graphics */ declare class ScopeId { /** * Create a new ScopeId instance. * * @param {string} name - The variable name. */ constructor(name: string); /** * The variable name. * * @type {string} */ name: string; value: any; versionObject: VersionedObject; toJSON(key: any): any; /** * Set variable value. * * @param {*} value - The value. */ setValue(value: any): void; /** * Get variable value. * * @returns {*} The value. */ getValue(): any; } /** * A TextureView specifies a texture and a subset of its mip levels and array layers. It is used * when binding textures to compute shaders to specify which portion of the texture should be * accessed. Create a TextureView using {@link Texture#getView}. * * Note: TextureView is only supported on WebGPU. On WebGL, the full texture is always bound and * this class has no effect. * * @category Graphics */ declare class TextureView { /** * Create a new TextureView instance. Use {@link Texture#getView} instead of calling this * constructor directly. * * @param {Texture} texture - The texture this view references. * @param {number} [baseMipLevel] - The first mip level accessible to the view. Defaults to 0. * @param {number} [mipLevelCount] - The number of mip levels accessible to the view. Defaults * to 1. * @param {number} [baseArrayLayer] - The first array layer accessible to the view. Defaults to * 0. * @param {number} [arrayLayerCount] - The number of array layers accessible to the view. * Defaults to 1. * @ignore */ constructor(texture: Texture, baseMipLevel?: number, mipLevelCount?: number, baseArrayLayer?: number, arrayLayerCount?: number); /** * The texture this view references. * * @type {Texture} * @readonly */ readonly texture: Texture; /** * The first mip level accessible to the view. * * @type {number} * @readonly */ readonly baseMipLevel: number; /** * The number of mip levels accessible to the view. * * @type {number} * @readonly */ readonly mipLevelCount: number; /** * The first array layer accessible to the view. * * @type {number} * @readonly */ readonly baseArrayLayer: number; /** * The number of array layers accessible to the view. * * @type {number} * @readonly */ readonly arrayLayerCount: number; /** * A unique numeric key for this view configuration, used for caching. * * @type {number} * @ignore */ key: number; } /** * Represents a texture, which is typically an image composed of pixels (texels). Textures are * fundamental resources for rendering graphical objects. They are commonly used by * {@link Material}s and sampled in {@link Shader}s (usually fragment shaders) to define the visual * appearance of a 3D model's surface. Beyond storing color images, textures can hold various data * types like normal maps, environment maps (cubemaps), or custom data for shader computations. Key * properties control how the texture data is sampled, including filtering modes and coordinate * wrapping. * * Note on **HDR texture format** support: * 1. **As textures**: * - float (i.e. {@link PIXELFORMAT_RGBA32F}), half-float (i.e. {@link PIXELFORMAT_RGBA16F}) and * small-float ({@link PIXELFORMAT_111110F}) formats are always supported on both WebGL2 and WebGPU * with point sampling. * - half-float and small-float formats are always supported on WebGL2 and WebGPU with linear * sampling. * - float formats are supported on WebGL2 and WebGPU with linear sampling only if * {@link GraphicsDevice#textureFloatFilterable} is true. * - {@link PIXELFORMAT_RGB9E5} is a compact HDR format with shared exponent, supported for * sampling on both WebGL2 and WebGPU, but cannot be used as a render target. * * 2. **As renderable textures** that can be used as color buffers in a {@link RenderTarget}: * - on WebGPU, rendering to float and half-float formats is always supported. * - on WebGPU, rendering to small-float format is supported only if * {@link GraphicsDevice#textureRG11B10Renderable} is true. * - on WebGL2, rendering to these 3 formats is supported only if * {@link GraphicsDevice#textureFloatRenderable} is true. * - on WebGL2, if {@link GraphicsDevice#textureFloatRenderable} is false, but * {@link GraphicsDevice#textureHalfFloatRenderable} is true, rendering to half-float formats only * is supported. This is the case of many mobile iOS devices. * - you can determine available renderable HDR format using * {@link GraphicsDevice#getRenderableHdrFormat}. * - {@link PIXELFORMAT_RGB10A2} provides 10 bits per RGB channel with 2-bit alpha, offering * higher precision than {@link PIXELFORMAT_RGBA8} at the same memory cost. It is renderable on * both WebGL2 and WebGPU. {@link PIXELFORMAT_RGB10A2U} is the unsigned integer variant. * * @category Graphics */ declare class Texture { /** * Creates a 2D data texture with nearest filtering, clamp-to-edge addressing and no mipmaps. * * @param {GraphicsDevice} graphicsDevice - The graphics device used to manage this texture. * @param {string} name - The name of the texture. * @param {number} width - The width of the texture in pixels. * @param {number} height - The height of the texture in pixels. * @param {number} format - The pixel format of the texture. * @param {Uint8Array[]|Uint8ClampedArray[]|Uint16Array[]|Uint32Array[]|Float32Array[]|HTMLCanvasElement[]|HTMLImageElement[]|HTMLVideoElement[]|Uint8Array[][]} [levels] * - Optional initial mip level data. * @returns {Texture} The created texture. * @ignore */ static createDataTexture2D(graphicsDevice: GraphicsDevice, name: string, width: number, height: number, format: number, levels?: Uint8Array[] | Uint8ClampedArray[] | Uint16Array[] | Uint32Array[] | Float32Array[] | HTMLCanvasElement[] | HTMLImageElement[] | HTMLVideoElement[] | Uint8Array[][]): Texture; /** * Create a new Texture instance. * * @param {GraphicsDevice} graphicsDevice - The graphics device used to manage this texture. * @param {object} [options] - Object for passing optional arguments. * @param {string} [options.name] - The name of the texture. Defaults to null. * @param {number} [options.width] - The width of the texture in pixels. Defaults to 4. * @param {number} [options.height] - The height of the texture in pixels. Defaults to 4. * @param {number} [options.depth] - The number of depth slices in a 3D texture. * @param {number} [options.format] - The pixel format of the texture. Can be: * * - {@link PIXELFORMAT_R8} * - {@link PIXELFORMAT_RG8} * - {@link PIXELFORMAT_RGB565} * - {@link PIXELFORMAT_RGBA5551} * - {@link PIXELFORMAT_RGBA4} * - {@link PIXELFORMAT_RGB8} * - {@link PIXELFORMAT_RGBA8} * - {@link PIXELFORMAT_DXT1} * - {@link PIXELFORMAT_DXT3} * - {@link PIXELFORMAT_DXT5} * - {@link PIXELFORMAT_RGB16F} * - {@link PIXELFORMAT_RGBA16F} * - {@link PIXELFORMAT_RGB32F} * - {@link PIXELFORMAT_RGBA32F} * - {@link PIXELFORMAT_ETC1} * - {@link PIXELFORMAT_PVRTC_2BPP_RGB_1} * - {@link PIXELFORMAT_PVRTC_2BPP_RGBA_1} * - {@link PIXELFORMAT_PVRTC_4BPP_RGB_1} * - {@link PIXELFORMAT_PVRTC_4BPP_RGBA_1} * - {@link PIXELFORMAT_111110F} * - {@link PIXELFORMAT_ASTC_4x4} * - {@link PIXELFORMAT_ATC_RGB} * - {@link PIXELFORMAT_ATC_RGBA} * * Defaults to {@link PIXELFORMAT_RGBA8}. * @param {boolean} [options.srgb] - When true, the texture is created in the sRGB variant of * the requested format, if one exists, and is automatically converted to linear space when * sampled. When the format has no sRGB variant, this option is ignored. Defaults to false. * @param {string} [options.projection] - The projection type of the texture, used when the * texture represents an environment. Can be: * * - {@link TEXTUREPROJECTION_NONE} * - {@link TEXTUREPROJECTION_CUBE} * - {@link TEXTUREPROJECTION_EQUIRECT} * - {@link TEXTUREPROJECTION_OCTAHEDRAL} * * Defaults to {@link TEXTUREPROJECTION_CUBE} if options.cubemap is true, otherwise * {@link TEXTUREPROJECTION_NONE}. * @param {number} [options.minFilter] - The minification filter type to use. Defaults to * {@link FILTER_LINEAR_MIPMAP_LINEAR}. * @param {number} [options.magFilter] - The magnification filter type to use. Defaults to * {@link FILTER_LINEAR}. * @param {number} [options.anisotropy] - The level of anisotropic filtering to use. Defaults * to 1. * @param {number} [options.addressU] - The repeat mode to use in the U direction. Defaults to * {@link ADDRESS_REPEAT}. * @param {number} [options.addressV] - The repeat mode to use in the V direction. Defaults to * {@link ADDRESS_REPEAT}. * @param {number} [options.addressW] - The repeat mode to use in the W direction. Defaults to * {@link ADDRESS_REPEAT}. * @param {boolean} [options.mipmaps] - When enabled try to generate or use mipmaps for this * texture. Default is true. * @param {number} [options.numLevels] - Specifies the number of mip levels to generate. If not * specified, the number is calculated based on the texture size. When this property is set, * the mipmaps property is ignored. * @param {boolean} [options.cubemap] - Specifies whether the texture is to be a cubemap. * Defaults to false. * @param {number} [options.arrayLength] - Specifies whether the texture is to be a 2D texture array. * When passed in as undefined or < 1, this is not an array texture. If >= 1, this is an array texture. * Defaults to undefined. * @param {boolean} [options.volume] - Specifies whether the texture is to be a 3D volume. * Defaults to false. * @param {string} [options.type] - Specifies the texture type. Can be: * * - {@link TEXTURETYPE_DEFAULT} * - {@link TEXTURETYPE_RGBM} * - {@link TEXTURETYPE_RGBE} * - {@link TEXTURETYPE_RGBP} * - {@link TEXTURETYPE_SWIZZLEGGGR} * * Defaults to {@link TEXTURETYPE_DEFAULT}. * @param {boolean} [options.flipY] - Specifies whether the texture should be flipped in the * Y-direction. Only affects textures with a source that is an image, canvas or video element. * Does not affect cubemaps, compressed textures or textures set from raw pixel data. Defaults * to false. * @param {boolean} [options.premultiplyAlpha] - If true, the alpha channel of the texture (if * present) is multiplied into the color channels. Defaults to false. * @param {boolean} [options.compareOnRead] - When enabled, and if texture format is * {@link PIXELFORMAT_DEPTH} or {@link PIXELFORMAT_DEPTHSTENCIL}, hardware PCF is enabled for * this texture, and you can get filtered results of comparison using texture() in your shader. * Defaults to false. * @param {number} [options.compareFunc] - Comparison function when compareOnRead is enabled. * Can be: * * - {@link FUNC_LESS} * - {@link FUNC_LESSEQUAL} * - {@link FUNC_GREATER} * - {@link FUNC_GREATEREQUAL} * - {@link FUNC_EQUAL} * - {@link FUNC_NOTEQUAL} * * Defaults to {@link FUNC_LESS}. * @param {Uint8Array[]|Uint8ClampedArray[]|Uint16Array[]|Uint32Array[]|Float32Array[]|HTMLCanvasElement[]|HTMLImageElement[]|HTMLVideoElement[]|Uint8Array[][]} [options.levels] * - Array of Uint8Array or other supported browser interface; or a two-dimensional array * of Uint8Array if options.arrayLength is defined and greater than zero. * @param {boolean} [options.storage] - Defines if texture can be used as a storage texture by * a compute shader. Defaults to false. * @param {number} [options.samples] - The number of MSAA samples. A value greater than 1 * creates a multisampled texture (WebGPU only, ignored with a warning on other devices, and * rounded up to the device's supported sample count). A multisampled texture can only be * rendered into, and its individual samples read in a shader using `textureLoad` - it cannot * be sampled with a sampler, uploaded to or read back. It must be a 2D non-array * texture with a format that supports multisampling, cannot be a storage texture, and has no * mipmaps (the mipmaps option is ignored). Defaults to 1. * @example * // Create a 8x8x24-bit texture * const texture = new Texture(graphicsDevice, { * width: 8, * height: 8, * format: PIXELFORMAT_RGB8 * }); * * // Fill the texture with a gradient * const pixels = texture.lock(); * const count = 0; * for (let i = 0; i < 8; i++) { * for (let j = 0; j < 8; j++) { * pixels[count++] = i * 32; * pixels[count++] = j * 32; * pixels[count++] = 255; * } * } * texture.unlock(); */ constructor(graphicsDevice: GraphicsDevice, options?: { name?: string; width?: number; height?: number; depth?: number; format?: number; srgb?: boolean; projection?: string; minFilter?: number; magFilter?: number; anisotropy?: number; addressU?: number; addressV?: number; addressW?: number; mipmaps?: boolean; numLevels?: number; cubemap?: boolean; arrayLength?: number; volume?: boolean; type?: string; flipY?: boolean; premultiplyAlpha?: boolean; compareOnRead?: boolean; compareFunc?: number; levels?: Uint8Array[] | Uint8ClampedArray[] | Uint16Array[] | Uint32Array[] | Float32Array[] | HTMLCanvasElement[] | HTMLImageElement[] | HTMLVideoElement[] | Uint8Array[][]; storage?: boolean; samples?: number; }); /** * The name of the texture. * * @type {string} */ name: string; /** @ignore */ _gpuSize: number; /** @ignore */ releaseSourceAfterUpload: boolean; /** @protected */ protected id: number; /** @protected */ protected _invalid: boolean; /** @protected */ protected _lockedLevel: number; /** @protected */ protected _lockedMode: number; /** * A render version used to track the last time the texture properties requiring bind group * to be updated were changed. * * @ignore */ renderVersionDirty: number; /** * A render version stamped each time the texture content is marked for upload to the GPU. * Unlike {@link renderVersionDirty} (which tracks property changes), this tracks pixel content * changes - including same-size video frame uploads - allowing consumers to detect when the * texture content has changed since they last used it. * * @ignore */ uploadVersion: number; /** @protected */ protected _storage: boolean; /** * The number of MSAA samples of the texture, 1 if not multisampled. * * @type {number} * @protected */ protected _samples: number; /** @protected */ protected _numLevels: number; /** @protected */ protected _numLevelsRequested: number; device: GraphicsDevice; _width: number; _height: number; _format: number; _compressed: boolean; _integerFormat: boolean; _volume: boolean; _depth: number; _arrayLength: number; _cubemap: boolean; _flipY: boolean; _premultiplyAlpha: boolean; _mipmaps: boolean; _minFilter: number; _magFilter: number; _anisotropy: number; _addressU: number; _addressV: number; _addressW: number; _compareOnRead: boolean; _compareFunc: number; _type: string; projection: string; profilerHint: any; _levels: Uint8Array[] | Uint8ClampedArray[] | Uint16Array[] | Uint32Array[] | Float32Array[] | HTMLCanvasElement[] | HTMLImageElement[] | HTMLVideoElement[] | Uint8Array[][]; /** * Frees resources associated with this texture. */ destroy(): void; /** * Closes any ImageBitmaps held on `_levels` and nulls those entries. The GPU has its own * copy after upload, so the decoded pixels in CPU memory can be released. Safe to call only * when no subsequent re-upload from CPU source will be needed and the source is owned by * the engine (not shared with caller code or other textures). Clears the * `releaseSourceAfterUpload` flag so future uploads keep their sources by default. * * @ignore */ releaseImageSources(): void; /** * One-shot opt-in: marks this texture so its CPU-side ImageBitmap source is released after * the next upload completes. The flag is cleared once the release runs, so callers must * re-arm after assigning a new source. The caller must own the ImageBitmap and guarantee * that no re-upload from CPU source will be needed (e.g. the owner re-creates the texture * on device loss). Used by the gsplat octree for streamed SOG textures. * * @ignore */ setReleaseSourceAfterUpload(): void; recreateImpl(upload?: boolean): void; impl: any; _clearLevels(): void; /** * Resizes the texture. This operation is supported for render target textures, and it resizes * the allocated buffer used for rendering, not the existing content of the texture. * * It is also supported for textures with data provided via the {@link lock} method. After * resizing, the appropriately sized data must be assigned by calling {@link lock} again. * * @param {number} width - The new width of the texture. * @param {number} height - The new height of the texture. * @param {number} [depth] - The new depth of the texture. Defaults to 1. * @ignore */ resize(width: number, height: number, depth?: number): void; /** * Called when the rendering context was lost. It releases all context related resources. * * @ignore */ loseContext(): void; /** * Updates vram size tracking for the texture, size can be positive to add or negative to subtract * * @ignore */ adjustVramSizeTracking(vram: any, size: any): void; propertyChanged(flag: any): void; _updateNumLevels(): void; /** * Returns the current lock mode. One of: * * - {@link TEXTURELOCK_NONE} * - {@link TEXTURELOCK_READ} * - {@link TEXTURELOCK_WRITE} * * @ignore * @type {number} */ get lockedMode(): number; /** * Sets the minification filter to be applied to the texture. Can be: * * - {@link FILTER_NEAREST} * - {@link FILTER_LINEAR} * - {@link FILTER_NEAREST_MIPMAP_NEAREST} * - {@link FILTER_NEAREST_MIPMAP_LINEAR} * - {@link FILTER_LINEAR_MIPMAP_NEAREST} * - {@link FILTER_LINEAR_MIPMAP_LINEAR} * * @type {number} */ set minFilter(v: number); /** * Gets the minification filter to be applied to the texture. * * @type {number} */ get minFilter(): number; /** * Sets the magnification filter to be applied to the texture. Can be: * * - {@link FILTER_NEAREST} * - {@link FILTER_LINEAR} * * @type {number} */ set magFilter(v: number); /** * Gets the magnification filter to be applied to the texture. * * @type {number} */ get magFilter(): number; /** * Sets the addressing mode to be applied to the texture horizontally. Can be: * * - {@link ADDRESS_REPEAT} * - {@link ADDRESS_CLAMP_TO_EDGE} * - {@link ADDRESS_MIRRORED_REPEAT} * * @type {number} */ set addressU(v: number); /** * Gets the addressing mode to be applied to the texture horizontally. * * @type {number} */ get addressU(): number; /** * Sets the addressing mode to be applied to the texture vertically. Can be: * * - {@link ADDRESS_REPEAT} * - {@link ADDRESS_CLAMP_TO_EDGE} * - {@link ADDRESS_MIRRORED_REPEAT} * * @type {number} */ set addressV(v: number); /** * Gets the addressing mode to be applied to the texture vertically. * * @type {number} */ get addressV(): number; /** * Sets the addressing mode to be applied to the 3D texture depth. Can be: * * - {@link ADDRESS_REPEAT} * - {@link ADDRESS_CLAMP_TO_EDGE} * - {@link ADDRESS_MIRRORED_REPEAT} * * @type {number} */ set addressW(addressW: number); /** * Gets the addressing mode to be applied to the 3D texture depth. * * @type {number} */ get addressW(): number; /** * When enabled, and if texture format is {@link PIXELFORMAT_DEPTH} or * {@link PIXELFORMAT_DEPTHSTENCIL}, hardware PCF is enabled for this texture, and you can get * filtered results of comparison using texture() in your shader. * * @type {boolean} */ set compareOnRead(v: boolean); /** * Gets whether you can get filtered results of comparison using texture() in your shader. * * @type {boolean} */ get compareOnRead(): boolean; /** * Sets the comparison function when {@link compareOnRead} is enabled. Possible values: * * - {@link FUNC_LESS} * - {@link FUNC_LESSEQUAL} * - {@link FUNC_GREATER} * - {@link FUNC_GREATEREQUAL} * - {@link FUNC_EQUAL} * - {@link FUNC_NOTEQUAL} * * @type {number} */ set compareFunc(v: number); /** * Gets the comparison function when {@link compareOnRead} is enabled. * * @type {number} */ get compareFunc(): number; /** * Sets the integer value specifying the level of anisotropy to apply to the texture. The value * ranges from 1 (no anisotropic filtering) to the maximum anisotropy supported by the graphics * device (see {@link GraphicsDevice#maxAnisotropy}). * * @type {number} */ set anisotropy(v: number); /** * Gets the integer value specifying the level of anisotropy to apply to the texture. * * @type {number} */ get anisotropy(): number; /** * Sets whether the texture should generate/upload mipmaps. Note that changing this property * on an array texture, or on any texture on WebGPU, re-creates the texture on the GPU, which * is an expensive operation, so it is preferable to create the texture with the correct * mipmaps setting from the start. * * @type {boolean} */ set mipmaps(v: boolean); /** * Gets whether the texture should generate/upload mipmaps. * * @type {boolean} */ get mipmaps(): boolean; _needsMipmapsUpload: boolean; /** * Gets the number of mip levels. * * @type {number} */ get numLevels(): number; /** * Defines if texture can be used as a storage texture by a compute shader. * * @type {boolean} */ get storage(): boolean; /** * The number of MSAA samples of the texture, 1 if the texture is not multisampled. Specified * via the `samples` constructor option (WebGPU only). A multisampled texture can only be * rendered into, and its individual samples read in a shader using `textureLoad`. * * @type {number} */ get samples(): number; /** * The width of the texture in pixels. * * @type {number} */ get width(): number; /** * The height of the texture in pixels. * * @type {number} */ get height(): number; /** * The number of depth slices in a 3D texture. * * @type {number} */ get depth(): number; /** * The pixel format of the texture. Can be: * * - {@link PIXELFORMAT_R8} * - {@link PIXELFORMAT_RG8} * - {@link PIXELFORMAT_RGB565} * - {@link PIXELFORMAT_RGBA5551} * - {@link PIXELFORMAT_RGBA4} * - {@link PIXELFORMAT_RGB8} * - {@link PIXELFORMAT_RGBA8} * - {@link PIXELFORMAT_DXT1} * - {@link PIXELFORMAT_DXT3} * - {@link PIXELFORMAT_DXT5} * - {@link PIXELFORMAT_RGB16F} * - {@link PIXELFORMAT_RGBA16F} * - {@link PIXELFORMAT_RGB32F} * - {@link PIXELFORMAT_RGBA32F} * - {@link PIXELFORMAT_ETC1} * - {@link PIXELFORMAT_PVRTC_2BPP_RGB_1} * - {@link PIXELFORMAT_PVRTC_2BPP_RGBA_1} * - {@link PIXELFORMAT_PVRTC_4BPP_RGB_1} * - {@link PIXELFORMAT_PVRTC_4BPP_RGBA_1} * - {@link PIXELFORMAT_111110F} * - {@link PIXELFORMAT_ASTC_4x4} * - {@link PIXELFORMAT_ATC_RGB} * - {@link PIXELFORMAT_ATC_RGBA} * * @type {number} */ get format(): number; /** * Returns true if this texture is a cube map and false otherwise. * * @type {boolean} */ get cubemap(): boolean; get gpuSize(): number; /** * Returns true if this texture is a 2D texture array and false otherwise. * * @type {boolean} */ get array(): boolean; /** * Returns the number of textures inside this texture if this is a 2D array texture or 0 otherwise. * * @type {number} */ get arrayLength(): number; /** * Returns true if this texture is a 3D volume and false otherwise. * * @type {boolean} */ get volume(): boolean; /** * Sets the texture type. * * @type {string} * @ignore */ set type(value: string); /** * Gets the texture type. * * @type {string} * @ignore */ get type(): string; /** * @deprecated Use Texture#type instead. * @ignore */ set rgbm(value: boolean); /** * @deprecated Use Texture#type instead. * @ignore */ get rgbm(): boolean; /** * @deprecated Use Texture#type instead. * @ignore */ set swizzleGGGR(value: boolean); /** * @deprecated Use Texture#type instead. * @ignore */ get swizzleGGGR(): boolean; get _glTexture(): any; /** * Sets the texture's internal format to an sRGB or linear equivalent of its current format. * When set to true, the texture is stored in sRGB format and automatically converted to linear * space when sampled. When set to false, the texture remains in a linear format. Changing this * property recreates the texture on the GPU, which is an expensive operation, so it is * preferable to create the texture with the correct format from the start. If the texture * format has no sRGB variant, this operation is ignored. * This is not a public API and is used by Editor only to update rendering when the sRGB * property is changed in the inspector. The higher cost is acceptable in this case. * * @type {boolean} * @ignore */ set srgb(value: boolean); /** * Returns true if the texture is stored in an sRGB format, meaning it will be converted to * linear space when sampled. Returns false if the texture is stored in a linear format. * * @type {boolean} */ get srgb(): boolean; /** * Sets whether the texture should be flipped in the Y-direction. Only affects textures * with a source that is an image, canvas or video element. Does not affect cubemaps, * compressed textures or textures set from raw pixel data. Defaults to true. * * @type {boolean} */ set flipY(flipY: boolean); /** * Gets whether the texture should be flipped in the Y-direction. * * @type {boolean} */ get flipY(): boolean; set premultiplyAlpha(premultiplyAlpha: boolean); get premultiplyAlpha(): boolean; /** * Returns true if all dimensions of the texture are power of two, and false otherwise. * * @type {boolean} */ get pot(): boolean; get encoding(): "rgbm" | "rgbe" | "rgbp" | "srgb" | "linear"; dirtyAll(): void; _levelsUpdated: boolean[] | boolean[][]; _mipmapsUploaded: boolean; /** * Locks a miplevel of the texture, returning a typed array to be filled with pixel data. * * @param {object} [options] - Optional options object. Valid properties are as follows: * @param {number} [options.level] - The mip level to lock with 0 being the top level. Defaults * to 0. * @param {number} [options.face] - If the texture is a cubemap, this is the index of the face * to lock. * @param {number} [options.mode] - The lock mode. Can be: * - {@link TEXTURELOCK_READ} * - {@link TEXTURELOCK_WRITE} * Defaults to {@link TEXTURELOCK_WRITE}. * @returns {Uint8Array|Uint16Array|Uint32Array|Float32Array} A typed array containing the pixel data of * the locked mip level. */ lock(options?: { level?: number; face?: number; mode?: number; }): Uint8Array | Uint16Array | Uint32Array | Float32Array; /** * Set the pixel data of the texture from a canvas, image, video, or HTML DOM element. If the * texture is a cubemap, the supplied source must be an array of 6 canvases, images or videos. * * Note: using an HTML element (e.g. `
`) as a source requires * {@link GraphicsDevice#supportsHtmlTextures} to be true. * * @param {HTMLCanvasElement|HTMLImageElement|HTMLVideoElement|HTMLElement|HTMLCanvasElement[]|HTMLImageElement[]|HTMLVideoElement[]|HTMLElement[]} source - A * canvas, image, video, or HTML element, or an array of 6 canvas, image, video, or HTML * elements. * @param {number} [mipLevel] - A non-negative integer specifying the image level of detail. * Defaults to 0, which represents the base image source. A level value of N, that is greater * than 0, represents the image source for the Nth mipmap reduction level. */ setSource(source: HTMLCanvasElement | HTMLImageElement | HTMLVideoElement | HTMLElement | HTMLCanvasElement[] | HTMLImageElement[] | HTMLVideoElement[] | HTMLElement[], mipLevel?: number): void; /** * Get the pixel data of the texture. If this is a cubemap then an array of 6 images will be * returned otherwise a single image. * * @param {number} [mipLevel] - A non-negative integer specifying the image level of detail. * Defaults to 0, which represents the base image source. A level value of N, that is greater * than 0, represents the image source for the Nth mipmap reduction level. * @returns {HTMLImageElement} The source image of this texture. Can be null if source not * assigned for specific image level. */ getSource(mipLevel?: number): HTMLImageElement; /** * Unlocks the currently locked mip level and uploads it to VRAM. */ unlock(): void; /** * Mark this texture as needing upload to the GPU. * * @ignore */ markForUpload(): void; _needsUpload: boolean; /** * Forces a reupload of the texture's pixel data to graphics memory. Ordinarily, this function * is called internally by {@link setSource} and {@link unlock}. However, it still needs to * be called explicitly in the case where an HTMLVideoElement is set as the source of the * texture. Normally, this is done once every frame before video textured geometry is * rendered. */ upload(): void; /** * Download the textures data from the graphics memory to the local memory. * * @param {number} x - The left edge of the rectangle. * @param {number} y - The top edge of the rectangle. * @param {number} width - The width of the rectangle. * @param {number} height - The height of the rectangle. * @param {object} [options] - Object for passing optional arguments. * @param {RenderTarget} [options.renderTarget] - The render target using the texture as a color * buffer. Provide as an optimization to avoid creating a new render target. Important especially * when this function is called with high frequency (per frame). Note that this is only utilized * on the WebGL platform, and ignored on WebGPU. * @param {number} [options.mipLevel] - The mip level to download. Defaults to 0. * @param {number} [options.face] - The face to download. Defaults to 0. * @param {Uint8Array|Uint16Array|Uint32Array|Float32Array} [options.data] - The data buffer to * write the pixel data to. If not provided, a new buffer will be created. The type of the buffer * must match the texture's format. * @param {boolean} [options.immediate] - If true, the read operation will be executed as soon as * possible. This has a performance impact, so it should be used only when necessary. Defaults * to false. * @param {boolean} [options.frequent] - Set this when the read is one of many, issued every * frame or every few frames. Such a read is given the treatment which costs it a frame of * latency and keeps it from stalling the frame it is issued in, which is the trade a one-off * read would not want. Only utilized on the WebGL platform, where a readback has a blocking * step; ignored on WebGPU, whose readback does not block. Defaults to false. * @returns {Promise} A promise that resolves * with the pixel data of the texture. */ read(x: number, y: number, width: number, height: number, options?: { renderTarget?: RenderTarget; mipLevel?: number; face?: number; data?: Uint8Array | Uint16Array | Uint32Array | Float32Array; immediate?: boolean; frequent?: boolean; }): Promise; /** * Upload texture data asynchronously to the GPU. * * @param {number} x - The left edge of the rectangle. * @param {number} y - The top edge of the rectangle. * @param {number} width - The width of the rectangle. * @param {number} height - The height of the rectangle. * @param {Uint8Array|Uint16Array|Uint32Array|Float32Array} data - The pixel data to upload. This should be a typed array. * * @returns {Promise} A promise that resolves when the upload is complete. * @ignore */ write(x: number, y: number, width: number, height: number, data: Uint8Array | Uint16Array | Uint32Array | Float32Array): Promise; /** * Validates the parameters of a {@link Texture#copy} operation. * * @param {Texture} source - The source texture. * @param {object} options - The copy options (see {@link Texture#copy}). * @returns {boolean} True if the copy parameters are valid. * @private */ private _validateCopy; /** * Copies a region of a source texture into this texture. Both textures must have the same * pixel format. The copied region sizes must match (no scaling), and must lie within the * chosen mip levels of both textures. Multisampled textures can be copied to other * multisampled textures with the same sample count (WebGPU only), but only as a full-texture * copy - no offsets or partial regions, and no copies between different sample counts (use a * resolve instead). * * @param {Texture} source - The source texture to copy from. * @param {object} [options] - Optional arguments. * @param {number} [options.sourceMipLevel] - The source mip level to copy from. Defaults to 0. * @param {number} [options.destMipLevel] - The destination mip level to copy to. Defaults to 0. * @param {number} [options.face] - The cubemap face or array layer to copy (applies to both * source and destination). Defaults to 0. * @param {number} [options.sourceX] - The left edge of the source region. Defaults to 0. * @param {number} [options.sourceY] - The top edge of the source region. Defaults to 0. * @param {number} [options.width] - The width of the copied region. Defaults to the full width * of the source mip level (minus sourceX). * @param {number} [options.height] - The height of the copied region. Defaults to the full * height of the source mip level (minus sourceY). * @param {number} [options.destX] - The left edge of the destination region. Defaults to 0. * @param {number} [options.destY] - The top edge of the destination region. Defaults to 0. * @param {RenderTarget} [options.sourceRenderTarget] - A render target wrapping the source * texture as its color buffer, at the matching face / mip level. Provide as an optimization to * avoid allocating a temporary one when copying with high frequency (per frame). Note that this * is only utilized on the WebGL platform, and ignored on WebGPU. * @returns {boolean} True if the copy was successful, false otherwise. */ copy(source: Texture, options?: { sourceMipLevel?: number; destMipLevel?: number; face?: number; sourceX?: number; sourceY?: number; width?: number; height?: number; destX?: number; destY?: number; sourceRenderTarget?: RenderTarget; }): boolean; /** * Creates a TextureView for this texture, specifying a subset of mip levels and array layers. * TextureViews can be used with compute shaders to access specific portions of a texture. * * Note: TextureView is only supported on WebGPU. On WebGL, the full texture is always bound. * * @param {number} [baseMipLevel] - The first mip level accessible to the view. Defaults to 0. * @param {number} [mipLevelCount] - The number of mip levels accessible to the view. Defaults * to 1. * @param {number} [baseArrayLayer] - The first array layer accessible to the view. Defaults to * 0. * @param {number} [arrayLayerCount] - The number of array layers accessible to the view. * Defaults to 1. * @returns {TextureView} A new TextureView for this texture. * @example * // Create a view for mip level 1 * const mip1View = texture.getView(1); * * // Use with compute shader * compute.setParameter('outputTexture', mip1View); */ getView(baseMipLevel?: number, mipLevelCount?: number, baseArrayLayer?: number, arrayLayerCount?: number): TextureView; } /** * A render target is a rectangular rendering surface that can be rendered into, instead of the * screen. It wraps one or more color buffer {@link Texture}s and an optional depth (and stencil) * buffer. Once a camera or a render pass has rendered into it, the color texture holds the result * and can be used anywhere a normal texture can - applied to a material to display it in the * scene, or fed into further processing. This underpins effects such as in-world screens, mirrors * and portals, reflections, picking and custom multi-pass pipelines. * * ## Usage * Create a texture to render into, wrap it in a render target and assign it to a camera. The * texture must use a renderable, uncompressed format: * * ```javascript * const texture = new Texture(device, { * width: 512, * height: 512, * format: PIXELFORMAT_SRGBA8, * mipmaps: false, * minFilter: FILTER_LINEAR, * magFilter: FILTER_LINEAR * }); * * const renderTarget = new RenderTarget({ * colorBuffer: texture, * depth: true, * origin: RENDERTARGET_ORIGIN_TOP * }); * * // the camera renders into the texture instead of the screen * cameraEntity.camera.renderTarget = renderTarget; * * // and the texture can be used as any other, for example by a material * material.emissiveMap = texture; * ``` * * When the result is sampled as a regular texture like this, specify the `origin` option as * {@link RENDERTARGET_ORIGIN_TOP}, which stores the image in the same orientation on all graphics * APIs. Multiple color buffers can be attached using the `colorBuffers` option, to render into * all of them simultaneously from a single pass (MRT). * * A live example: {@link https://playcanvas.github.io/#/graphics/render-to-texture} * * ## Multisampling (MSAA) * Set the `samples` option to a value greater than 1 to render with hardware anti-aliasing. The * render target internally allocates a multisampled buffer to render into, and automatically * resolves it into the single-sampled `colorBuffer` at the end of a render pass - the color * texture is used the same way as in the single-sampled case. * * ```javascript * const renderTarget = new RenderTarget({ colorBuffer: texture, depth: true, samples: 4 }); * ``` * * ## Explicit multisampled color buffers and custom resolves (WebGPU) * A multisampled texture (a {@link Texture} created with `samples` greater than 1, WebGPU only) * can be used as the color buffer directly. The render target then renders into its samples, and * the sample count is inferred from the texture. Provide a `resolveBuffer` to get the standard * hardware resolve, or omit it to keep the individual samples: these are then read in a shader * using `textureLoad` on a `texture_multisampled_2d`, typically by a follow-up pass implementing * a custom resolve - an operation the hardware resolve cannot express, such as a tonemapped or * min/max resolve. This is also the only way to use multisampling with formats the hardware * cannot resolve, such as integer formats. * * ```javascript * // a multisampled texture, rendered into directly * const msColor = new Texture(device, { * width: 512, * height: 512, * format: PIXELFORMAT_RGBA16F, * samples: 4 * }); * * // renders into the samples of msColor, which are stored (no resolve buffer), * // to be read by a custom resolve pass using textureLoad * const renderTarget = new RenderTarget({ colorBuffer: msColor, depth: true }); * ``` * * A live example: {@link https://playcanvas.github.io/#/graphics-advanced/custom-msaa-resolve} * * @category Graphics */ declare class RenderTarget { /** * Creates a new RenderTarget instance. A color buffer or a depth buffer must be set. * * @param {object} [options] - Object for passing optional arguments. * @param {boolean} [options.autoResolve] - If samples > 1, enables or disables automatic MSAA * resolve after rendering to this RT (see {@link resolve}). Applies to the implicit * multisampled path only - resolves of explicit multisampled attachments (a multisampled * `colorBuffer` with a `resolveBuffer`, or a multisampled `depthBuffer` with a * `depthResolveBuffer`) are controlled by the per-pass resolve flags instead. Defaults to * true. * @param {string} [options.depthResolveMode] - How the samples of the multisampled depth * buffer are resolved into a single depth value, whenever the depth of this render target is * resolved by a shader-based resolve (WebGPU only) - the depth grab pass (`sceneDepthMap`), a * depth {@link copy}, or the automatic resolve into a provided `depthBuffer`. Can be: * * - {@link DEPTHRESOLVE_MIN}: the minimum sample value - with a standard depth buffer this * selects the nearest surface, a conservative and stable choice for depth-consuming effects. * - {@link DEPTHRESOLVE_MAX}: the maximum sample value - the farthest surface. * - {@link DEPTHRESOLVE_SAMPLE0}: the value of the sample at index 0. * * Defaults to {@link DEPTHRESOLVE_MIN}. Ignored on WebGL2, where the sample selection of the * depth resolve is defined by the implementation. Can also be changed at any time using the * {@link RenderTarget#depthResolveMode} property. * @param {Texture} [options.colorBuffer] - The texture that this render target will treat as a * rendering surface. This can be a multisampled texture (a texture created with `samples` > 1, * WebGPU only), in which case the render target renders directly into its samples, the sample * count is inferred from the texture, and an optional `resolveBuffer` receives the hardware * resolve. * @param {Texture[]} [options.colorBuffers] - The textures that this render target will treat * as a rendering surfaces. If this option is set, the colorBuffer option is ignored. All * textures must have the same sample count. * @param {Texture|null} [options.resolveBuffer] - A single-sampled texture that the * multisampled color buffer is hardware-resolved into at the end of a render pass. Only valid * when `colorBuffer` is a multisampled texture, and must match its format and dimensions. When * not provided, the multisampled samples are stored instead, to be read in a shader using * `textureLoad` (a custom resolve). Note that integer formats and {@link PIXELFORMAT_R32F} * cannot be hardware-resolved. * @param {(Texture|null)[]} [options.resolveBuffers] - Per-attachment resolve textures * matching `colorBuffers` by index; use null for attachments that should not be * hardware-resolved. If this option is set, the resolveBuffer option must not be used. * @param {boolean} [options.depth] - If set to true, depth buffer will be created. Defaults to * true. Ignored if depthBuffer is defined. * @param {Texture} [options.depthBuffer] - The texture that this render target will treat as a * depth/stencil surface. If set, the 'depth' and 'stencil' properties are ignored. The texture * must use {@link PIXELFORMAT_DEPTH}, {@link PIXELFORMAT_DEPTH16} or * {@link PIXELFORMAT_DEPTHSTENCIL} format. On WebGPU this can be a multisampled texture (a * texture created with `samples` > 1), in which case the render target renders directly into * its depth samples, which can later be read in a shader using `textureLoad` on a * `texture_depth_multisampled_2d`, or resolved into an optional `depthResolveBuffer`. * @param {Texture} [options.depthResolveBuffer] - A single-sampled {@link PIXELFORMAT_R32F} * texture that the multisampled depth buffer is resolved into at the end of a render pass, * using a shader-based resolve controlled by {@link RenderTarget#depthResolveMode} (WebGPU * only - no hardware depth resolve exists). Only valid when `depthBuffer` is a multisampled * texture, and must match its dimensions. * @param {number} [options.mipLevel] - If set to a number greater than 0, the render target * will render to the specified mip level of the color buffer. Defaults to 0. * @param {number} [options.face] - If the colorBuffer parameter is a cubemap, use this option * to specify the face of the cubemap to render to. Can be: * * - {@link CUBEFACE_POSX} * - {@link CUBEFACE_NEGX} * - {@link CUBEFACE_POSY} * - {@link CUBEFACE_NEGY} * - {@link CUBEFACE_POSZ} * - {@link CUBEFACE_NEGZ} * * Defaults to {@link CUBEFACE_POSX}. * @param {string} [options.name] - The name of the render target. * @param {string} [options.origin] - Controls the vertical orientation of the image stored * in the render target. Choose based on how the texture is sampled. Can be: * * - {@link RENDERTARGET_ORIGIN_TOP}: row 0 of the stored image is the top row of the * rendered image, on all graphics APIs - the same layout image textures use. Use for * anything treated as a picture: sampling with mesh UVs, cube map faces, or pixel readback * saved as an image. Recommended for all new content - write the sampling code as if the * texture was a loaded image. Internally the image is rendered upside-down on WebGL2. * - {@link RENDERTARGET_ORIGIN_BOTTOM}: row 0 of the stored image is the bottom row of the * rendered image, on all graphics APIs - replicating WebGL2's native layout. Use to keep * consuming code written against WebGL conventions working unchanged on all APIs: shaders * deriving UVs from projected (NDC) coordinates or a projection scale-bias matrix, and * texture atlases addressing cells by viewport rectangles (on WebGPU this also switches * viewport / scissor rectangles to raw texel-row addressing). If a render target that worked * on WebGL2 appears upside-down on WebGPU, this is the drop-in fix; migrating the sampling * code to image orientation and {@link RENDERTARGET_ORIGIN_TOP} is the better long-term * choice. Internally the image is rendered upside-down on WebGPU. * - {@link RENDERTARGET_ORIGIN_NATIVE}: the image is stored in the native orientation of the * graphics API and the row order differs between WebGL2 (bottom-up) and WebGPU (top-down). * No flipping takes place. Only appropriate for orientation-agnostic consumers: UVs derived * from gl_FragCoord, sampling via the same matrix the target was rendered with (shadow * maps), or integer texel fetch. * * Takes precedence over the deprecated `flipY` option. Defaults to * {@link RENDERTARGET_ORIGIN_NATIVE}. * @param {number} [options.samples] - Number of hardware anti-aliasing samples. Default is 1. * @param {boolean} [options.stencil] - If set to true, depth buffer will include stencil. * Defaults to false. Ignored if depthBuffer is defined or depth is false. * @param {boolean} [options.transientColor] - If set to true, the multi-sampled (MSAA) color * attachment is allocated as a transient ("memoryless") attachment, allowing tile-based GPUs to * keep its contents in on-chip memory and avoid VRAM allocation. WebGPU only, and only effective * when samples > 1 - it has no effect on single-sampled color (which is always stored). Ignored * on devices without transient attachment support. The attachment must be cleared on load and * discarded on store, so it is incompatible with a scene color grab pass (`sceneColorMap`). * Defaults to false. * @param {boolean} [options.transientDepth] - If set to true, the (engine-allocated) depth * attachment is allocated as a transient ("memoryless") attachment (see `transientColor`). * Applies to both single- and multi-sampled depth. WebGPU only; ignored on devices without * transient attachment support, and ignored (with a warning) when an explicit `depthBuffer` is * provided. Incompatible with a scene depth grab pass (`sceneDepthMap`), a depth prepass, or any * depth resolve, as the depth cannot be sampled or copied out. Defaults to false. * @example * // Create a 512x512x24-bit render target with a depth buffer * const colorBuffer = new Texture(graphicsDevice, { * width: 512, * height: 512, * format: PIXELFORMAT_RGB8 * }); * const renderTarget = new RenderTarget({ * colorBuffer: colorBuffer, * depth: true * }); * * // Set the render target on a camera component * camera.renderTarget = renderTarget; * * // Destroy render target at a later stage. Note that the color buffer needs * // to be destroyed separately. * renderTarget.colorBuffer.destroy(); * renderTarget.destroy(); * camera.renderTarget = null; */ constructor(options?: { autoResolve?: boolean; depthResolveMode?: string; colorBuffer?: Texture; colorBuffers?: Texture[]; resolveBuffer?: Texture | null; resolveBuffers?: (Texture | null)[]; depth?: boolean; depthBuffer?: Texture; depthResolveBuffer?: Texture; mipLevel?: number; face?: number; name?: string; origin?: string; samples?: number; stencil?: boolean; transientColor?: boolean; transientDepth?: boolean; }); /** * The name of the render target. * * @type {string} */ name: string; /** * @type {GraphicsDevice} * @private */ private _device; /** * @type {Texture} * @private */ private _colorBuffer; /** * @type {Texture[]} * @private */ private _colorBuffers; /** * @type {Texture} * @private */ private _depthBuffer; /** * Per-attachment resolve targets for explicit multisampled color attachments. * * @type {(Texture|null)[]|null} * @private */ private _resolveBuffers; /** * Single-sampled resolve target for an explicit multisampled depth buffer. * * @type {Texture|null} * @private */ private _depthResolveBuffer; /** * @type {boolean} * @private */ private _depth; /** * @type {boolean} * @private */ private _stencil; /** * @type {number} * @private */ private _samples; /** * @type {boolean} * @private */ private _transientColor; /** * @type {boolean} * @private */ private _transientDepth; /** @type {boolean} */ autoResolve: boolean; /** * @type {string} * @private */ private _depthResolveMode; /** * @type {number} * @private */ private _face; /** * @type {number} * @private */ private _mipLevel; /** * True if the mipmaps should be automatically generated for the color buffer(s) if it contains * a mip chain. * * @type {boolean} * @private */ private _mipmaps; /** * @type {number | undefined} * @private */ private _width; /** * @type {number | undefined} * @private */ private _height; /** * @type {boolean} * @private */ private _flipY; /** * @type {string} * @private */ private _origin; id: number; /** * Sets how the samples of the multisampled depth buffer are resolved into a single depth * value (WebGPU only). Can be changed at any time - the mode is used at the time the depth is * resolved. See the `depthResolveMode` constructor option. * * @type {string} */ set depthResolveMode(value: string); /** * Gets how the samples of the multisampled depth buffer are resolved into a single depth * value. * * @type {string} */ get depthResolveMode(): string; impl: any; /** * Frees resources associated with this render target. */ destroy(): void; /** * Free device resources associated with this render target. * * @ignore */ destroyFrameBuffers(): void; /** * Free textures associated with this render target. * * @ignore */ destroyTextureBuffers(): void; /** * Resizes the render target to the specified width and height. Internally this resizes all the * assigned texture color and depth buffers. * * @param {number} width - The width of the render target in pixels. * @param {number} height - The height of the render target in pixels. */ resize(width: number, height: number): void; validateMrt(): void; /** * Evaluates and stores the width and height of the render target based on the color/depth * buffers and mip level. * * @private */ private evaluateDimensions; /** * Initializes the resources associated with this render target. * * @ignore */ init(): void; /** @ignore */ get initialized(): any; /** @ignore */ get device(): GraphicsDevice; /** * Called when the device context was lost. It releases all context related resources. * * @ignore */ loseContext(): void; /** * If samples > 1, resolves the anti-aliased render target (WebGL2 only). When you're rendering * to an anti-aliased render target, pixels aren't written directly to the readable texture. * Instead, they're first written to an MSAA buffer, where each sample for each pixel is stored * independently. In order to read the results, you first need to 'resolve' the buffer - to * average all samples and create a simple texture with one color per pixel. This function * performs this averaging and updates the colorBuffer and the depthBuffer. If autoResolve is * set to true, the resolve will happen after every rendering to this render target, otherwise * you can do it manually, during the app update or similar. * * @param {boolean} [color] - Resolve color buffer. Defaults to true. * @param {boolean} [depth] - Resolve depth buffer. Defaults to true if the render target has a * depth buffer. */ resolve(color?: boolean, depth?: boolean): void; /** * Copies color and/or depth contents of source render target to this one. Formats, sizes and * anti-aliasing samples must match. * * A depth copy is supported in these cases: * * - On WebGL 2.0, between render targets with matching sample counts. * - On WebGPU, between single-sampled render targets. * - On WebGPU, from a multisampled source into a multisampled `depthBuffer` of this render * target with an equal sample count and matching format - a full depth snapshot, including * the individual samples. * - On WebGPU, from a multisampled source into a single-sampled {@link PIXELFORMAT_R32F} * color buffer of this render target - a shader-based resolve controlled by the source's * {@link RenderTarget#depthResolveMode}. * * @param {RenderTarget} source - Source render target to copy from. * @param {boolean} [color] - If true, will copy the color buffer. Defaults to false. * @param {boolean} [depth] - If true, will copy the depth buffer. Defaults to false. * @returns {boolean} True if the copy was successful, false otherwise. */ copy(source: RenderTarget, color?: boolean, depth?: boolean): boolean; /** * @deprecated Use the "origin" option of the RenderTarget constructor instead. Typical * migration: flipY: !device.isWebGPU -> origin: RENDERTARGET_ORIGIN_TOP, flipY: device.isWebGPU * -> origin: RENDERTARGET_ORIGIN_BOTTOM. * @ignore */ set flipY(value: boolean); /** * Gets whether the rendered image is flipped in Y. * * @type {boolean} * @ignore */ get flipY(): boolean; /** * Gets the vertical orientation of the image stored in this render target, as resolved at * construction from the `origin` option, or derived from the deprecated flipY option or * property. Can be {@link RENDERTARGET_ORIGIN_TOP}, {@link RENDERTARGET_ORIGIN_BOTTOM} or * {@link RENDERTARGET_ORIGIN_NATIVE}. See the `origin` option of the constructor for * details. * * @type {string} */ get origin(): string; /** * Number of antialiasing samples the render target uses. * * @type {number} */ get samples(): number; /** * True if the multi-sampled color attachment is allocated as a transient ("memoryless") * attachment (WebGPU only). See the `transientColor` constructor option. * * @type {boolean} */ get transientColor(): boolean; /** * True if the depth attachment is allocated as a transient ("memoryless") attachment (WebGPU * only). See the `transientDepth` constructor option. * * @type {boolean} */ get transientDepth(): boolean; /** * True if the render target contains the depth attachment. * * @type {boolean} */ get depth(): boolean; /** * True if the render target contains the stencil attachment. * * @type {boolean} */ get stencil(): boolean; /** * Color buffer set up on the render target. * * @type {Texture} */ get colorBuffer(): Texture; /** * The number of color buffers (attachments) set up on the render target. * * @type {number} */ get colorBufferCount(): number; /** * Accessor for multiple render target color buffers. * * @param {number} index - Index of the color buffer to get. * @returns {Texture} - Color buffer at the specified index. */ getColorBuffer(index: number): Texture; /** * The resolve texture of the first color attachment, when the render target uses explicit * multisampled color buffers and a resolve buffer was provided. See the `resolveBuffer` * constructor option. Null otherwise. * * @type {Texture|null} */ get resolveBuffer(): Texture | null; /** * Accessor for the per-attachment resolve textures. See the `resolveBuffers` constructor * option. * * @param {number} [index] - Index of the color attachment. Defaults to 0. * @returns {Texture|null} - The resolve texture at the specified index, or null when the * attachment has none. */ getResolveBuffer(index?: number): Texture | null; /** * Depth buffer set up on the render target. Only available, if depthBuffer was set in * constructor. Not available if depth property was used instead. * * @type {Texture} */ get depthBuffer(): Texture; /** * The single-sampled texture the multisampled depth buffer is resolved into at the end of a * render pass. See the `depthResolveBuffer` constructor option. Null when not provided. * * @type {Texture|null} */ get depthResolveBuffer(): Texture | null; /** * If the render target is bound to a cubemap, this property specifies which face of the * cubemap is rendered to. Can be: * * - {@link CUBEFACE_POSX} * - {@link CUBEFACE_NEGX} * - {@link CUBEFACE_POSY} * - {@link CUBEFACE_NEGY} * - {@link CUBEFACE_POSZ} * - {@link CUBEFACE_NEGZ} * * @type {number} */ get face(): number; /** * Mip level of the render target. * * @type {number} */ get mipLevel(): number; /** * True if the mipmaps are automatically generated for the color buffer(s) if it contains * a mip chain. * * @type {boolean} */ get mipmaps(): boolean; /** * Width of the render target in pixels. * * @type {number} */ get width(): number; /** * Height of the render target in pixels. * * @type {number} */ get height(): number; set _glFrameBuffer(value: any); get _glFrameBuffer(): any; /** * Gets whether the format of the specified color buffer is sRGB. * * @param {number} index - The index of the color buffer. * @returns {boolean} True if the color buffer is sRGB, false otherwise. * @ignore */ isColorBufferSrgb(index?: number): boolean; } /** * A 2-dimensional vector. Vec2 is commonly used to represent 2D positions, directions, texture * coordinates (UVs) or any pair of related numeric values. * * Operations follow one convention throughout the math classes: a method that modifies the vector * it is called on returns it, so calls can be chained and nothing is allocated, while queries such * as {@link distance} and {@link dot} return a number. Two-operand forms such as {@link add2} and * {@link sub2} write the result of `lhs op rhs` into `this`, and it is safe for `this` to also be * one of the operands. Use {@link clone} for an independent copy and {@link copy} to overwrite one * vector with another. * * The static constants such as {@link ZERO} and {@link UP} are frozen shared instances: read them * freely, but writing to one throws. Copy a constant before modifying it. * * @example * // Scroll a texture offset each frame without allocating * const offset = new Vec2(0, 0); * const speed = new Vec2(0.1, 0); * offset.addScaled(speed, dt); * @example * // Chain mutating operations; each returns the vector it was called on * const toTarget = new Vec2().sub2(target, position).normalize(); * const distance = target.distance(position); * @category Math */ declare class Vec2 { /** * Calculates the angle between two Vec2's in radians. * * @param {Vec2} lhs - The first vector operand for the calculation. * @param {Vec2} rhs - The second vector operand for the calculation. * @returns {number} The calculated angle in radians. * @ignore */ static angleRad(lhs: Vec2, rhs: Vec2): number; /** * A constant vector set to [0, 0]. * * @type {Vec2} * @readonly */ static readonly ZERO: Vec2; /** * A constant vector set to [0.5, 0.5]. * * @type {Vec2} * @readonly */ static readonly HALF: Vec2; /** * A constant vector set to [1, 1]. * * @type {Vec2} * @readonly */ static readonly ONE: Vec2; /** * A constant vector set to [0, 1]. * * @type {Vec2} * @readonly */ static readonly UP: Vec2; /** * A constant vector set to [0, -1]. * * @type {Vec2} * @readonly */ static readonly DOWN: Vec2; /** * A constant vector set to [1, 0]. * * @type {Vec2} * @readonly */ static readonly RIGHT: Vec2; /** * A constant vector set to [-1, 0]. * * @type {Vec2} * @readonly */ static readonly LEFT: Vec2; /** * Creates a new Vec2 instance. * * @overload * @param {number} [x] - The x value. Defaults to 0. * @param {number} [y] - The y value. Defaults to 0. * @example * const v1 = new Vec2(); // defaults to 0, 0 * const v2 = new Vec2(1, 2); */ constructor(x?: number, y?: number); /** * Creates a new Vec2 instance. * * @overload * @param {number[]} arr - The array to set the vector values from. * @example * const v = new Vec2([1, 2]); */ constructor(arr: number[]); /** * The first component of the vector. * * @type {number} */ x: number; /** * The second component of the vector. * * @type {number} */ y: number; /** * Adds a 2-dimensional vector to another in place. * * @param {Vec2} rhs - The vector to add to the specified vector. * @returns {Vec2} Self for chaining. * @example * const a = new Vec2(10, 10); * const b = new Vec2(20, 20); * * a.add(b); * * // Outputs [30, 30] * console.log("The result of the addition is: " + a.toString()); */ add(rhs: Vec2): Vec2; /** * Adds two 2-dimensional vectors together and returns the result. * * @param {Vec2} lhs - The first vector operand for the addition. * @param {Vec2} rhs - The second vector operand for the addition. * @returns {Vec2} Self for chaining. * @example * const a = new Vec2(10, 10); * const b = new Vec2(20, 20); * const r = new Vec2(); * * r.add2(a, b); * // Outputs [30, 30] * * console.log("The result of the addition is: " + r.toString()); */ add2(lhs: Vec2, rhs: Vec2): Vec2; /** * Adds a number to each element of a vector. * * @param {number} scalar - The number to add. * @returns {Vec2} Self for chaining. * @example * const vec = new Vec2(3, 4); * * vec.addScalar(2); * * // Outputs [5, 6] * console.log("The result of the addition is: " + vec.toString()); */ addScalar(scalar: number): Vec2; /** * Adds a 2-dimensional vector scaled by scalar value. Does not modify the vector being added. * * @param {Vec2} rhs - The vector to add to the specified vector. * @param {number} scalar - The number to multiply the added vector with. * @returns {Vec2} Self for chaining. * @example * const vec = new Vec2(1, 2); * * vec.addScaled(Vec2.UP, 2); * * // Outputs [1, 4] * console.log("The result of the addition is: " + vec.toString()); */ addScaled(rhs: Vec2, scalar: number): Vec2; /** * Returns an identical copy of the specified 2-dimensional vector. * * @returns {this} A 2-dimensional vector containing the result of the cloning. * @example * const v = new Vec2(10, 20); * const vclone = v.clone(); * console.log("The result of the cloning is: " + vclone.toString()); */ clone(): this; /** * Copies the contents of a source 2-dimensional vector to a destination 2-dimensional vector. * * @param {Vec2} rhs - A vector to copy to the specified vector. * @returns {Vec2} Self for chaining. * @example * const src = new Vec2(10, 20); * const dst = new Vec2(); * * dst.copy(src); * * console.log("The two vectors are " + (dst.equals(src) ? "equal" : "different")); */ copy(rhs: Vec2): Vec2; /** * Returns the result of a cross product operation performed on the two specified 2-dimensional * vectors. * * @param {Vec2} rhs - The second 2-dimensional vector operand of the cross product. * @returns {number} The cross product of the two vectors. * @example * const right = new Vec2(1, 0); * const up = new Vec2(0, 1); * const crossProduct = right.cross(up); * * // Prints 1 * console.log("The result of the cross product is: " + crossProduct); */ cross(rhs: Vec2): number; /** * Returns the distance between the two specified 2-dimensional vectors. * * @param {Vec2} rhs - The second 2-dimensional vector to test. * @returns {number} The distance between the two vectors. * @example * const v1 = new Vec2(5, 10); * const v2 = new Vec2(10, 20); * const d = v1.distance(v2); * console.log("The distance between v1 and v2 is: " + d); */ distance(rhs: Vec2): number; /** * Returns the squared distance between the two specified 2-dimensional vectors. * * @param {Vec2} rhs - The second 2-dimensional vector to test. * @returns {number} The squared distance between the two vectors. * @example * const v1 = new Vec2(5, 10); * const v2 = new Vec2(10, 20); * const d = v1.distanceSq(v2); * console.log("The squared distance between v1 and v2 is: " + d); */ distanceSq(rhs: Vec2): number; /** * Divides a 2-dimensional vector by another in place. * * @param {Vec2} rhs - The vector to divide the specified vector by. * @returns {Vec2} Self for chaining. * @example * const a = new Vec2(4, 9); * const b = new Vec2(2, 3); * * a.div(b); * * // Outputs [2, 3] * console.log("The result of the division is: " + a.toString()); */ div(rhs: Vec2): Vec2; /** * Divides one 2-dimensional vector by another and writes the result to the specified vector. * * @param {Vec2} lhs - The dividend vector (the vector being divided). * @param {Vec2} rhs - The divisor vector (the vector dividing the dividend). * @returns {Vec2} Self for chaining. * @example * const a = new Vec2(4, 9); * const b = new Vec2(2, 3); * const r = new Vec2(); * * r.div2(a, b); * * // Outputs [2, 3] * console.log("The result of the division is: " + r.toString()); */ div2(lhs: Vec2, rhs: Vec2): Vec2; /** * Divides each element of a vector by a number. * * @param {number} scalar - The number to divide by. * @returns {Vec2} Self for chaining. * @example * const vec = new Vec2(3, 6); * * vec.divScalar(3); * * // Outputs [1, 2] * console.log("The result of the division is: " + vec.toString()); */ divScalar(scalar: number): Vec2; /** * Returns the result of a dot product operation performed on the two specified 2-dimensional * vectors. * * @param {Vec2} rhs - The second 2-dimensional vector operand of the dot product. * @returns {number} The result of the dot product operation. * @example * const v1 = new Vec2(5, 10); * const v2 = new Vec2(10, 20); * const v1dotv2 = v1.dot(v2); * console.log("The result of the dot product is: " + v1dotv2); */ dot(rhs: Vec2): number; /** * Reports whether two vectors are equal. * * @param {Vec2} rhs - The vector to compare to the specified vector. * @returns {boolean} True if the vectors are equal and false otherwise. * @example * const a = new Vec2(1, 2); * const b = new Vec2(4, 5); * console.log("The two vectors are " + (a.equals(b) ? "equal" : "different")); */ equals(rhs: Vec2): boolean; /** * Reports whether two vectors are equal using an absolute error tolerance. * * @param {Vec2} rhs - The vector to be compared against. * @param {number} [epsilon] - The maximum difference between each component of the two * vectors. Defaults to 1e-6. * @returns {boolean} True if the vectors are equal and false otherwise. * @example * const a = new Vec2(); * const b = new Vec2(); * console.log("The two vectors are approximately " + (a.equalsApprox(b, 1e-9) ? "equal" : "different")); */ equalsApprox(rhs: Vec2, epsilon?: number): boolean; /** * Returns the magnitude of the specified 2-dimensional vector. * * @returns {number} The magnitude of the specified 2-dimensional vector. * @example * const vec = new Vec2(3, 4); * const len = vec.length(); * // Outputs 5 * console.log("The length of the vector is: " + len); */ length(): number; /** * Returns the magnitude squared of the specified 2-dimensional vector. * * @returns {number} The magnitude squared of the specified 2-dimensional vector. * @example * const vec = new Vec2(3, 4); * const len = vec.lengthSq(); * // Outputs 25 * console.log("The length squared of the vector is: " + len); */ lengthSq(): number; /** * Returns the result of a linear interpolation between two specified 2-dimensional vectors. * * @param {Vec2} lhs - The 2-dimensional vector to interpolate from. * @param {Vec2} rhs - The 2-dimensional vector to interpolate to. * @param {number} alpha - The value controlling the point of interpolation. Between 0 and 1, * the linear interpolant will occur on a straight line between lhs and rhs. Outside of this * range, the linear interpolant will occur on a ray extrapolated from this line. * @returns {Vec2} Self for chaining. * @example * const a = new Vec2(0, 0); * const b = new Vec2(10, 10); * const r = new Vec2(); * * r.lerp(a, b, 0); // r is equal to a * r.lerp(a, b, 0.5); // r is 5, 5 * r.lerp(a, b, 1); // r is equal to b */ lerp(lhs: Vec2, rhs: Vec2, alpha: number): Vec2; /** * Multiplies a 2-dimensional vector to another in place. * * @param {Vec2} rhs - The 2-dimensional vector used as the second multiplicand of the operation. * @returns {Vec2} Self for chaining. * @example * const a = new Vec2(2, 3); * const b = new Vec2(4, 5); * * a.mul(b); * * // Outputs 8, 15 * console.log("The result of the multiplication is: " + a.toString()); */ mul(rhs: Vec2): Vec2; /** * Returns the result of multiplying the specified 2-dimensional vectors together. * * @param {Vec2} lhs - The 2-dimensional vector used as the first multiplicand of the operation. * @param {Vec2} rhs - The 2-dimensional vector used as the second multiplicand of the operation. * @returns {Vec2} Self for chaining. * @example * const a = new Vec2(2, 3); * const b = new Vec2(4, 5); * const r = new Vec2(); * * r.mul2(a, b); * * // Outputs 8, 15 * console.log("The result of the multiplication is: " + r.toString()); */ mul2(lhs: Vec2, rhs: Vec2): Vec2; /** * Multiplies each element of a vector by a number. * * @param {number} scalar - The number to multiply by. * @returns {Vec2} Self for chaining. * @example * const vec = new Vec2(3, 6); * * vec.mulScalar(3); * * // Outputs [9, 18] * console.log("The result of the multiplication is: " + vec.toString()); */ mulScalar(scalar: number): Vec2; /** * @deprecated Use Vec2#mulScalar instead. * @param {number} scalar - The number to multiply by. * @returns {Vec2} Self for chaining. * @ignore */ scale(scalar: number): Vec2; /** * Returns this 2-dimensional vector converted to a unit vector in place. If the vector has a * length of zero, the vector's elements will be set to zero. * * @param {Vec2} [src] - The vector to normalize. If not set, the operation is done in place. * @returns {Vec2} Self for chaining. * @example * const v = new Vec2(25, 0); * * v.normalize(); * * // Outputs 1, 0 * console.log("The result of the vector normalization is: " + v.toString()); */ normalize(src?: Vec2): Vec2; /** * Rotate a vector by an angle in degrees. * * @param {number} degrees - The number to degrees to rotate the vector by. * @returns {Vec2} Self for chaining. * @example * const v = new Vec2(0, 10); * * v.rotate(45); // rotates by 45 degrees * * // Outputs [7.071068.., 7.071068..] * console.log("Vector after rotation is: " + v.toString()); */ rotate(degrees: number): Vec2; /** * Returns the angle in degrees of the specified 2-dimensional vector. * * @returns {number} The angle in degrees of the specified 2-dimensional vector. * @example * const v = new Vec2(6, 0); * const angle = v.angle(); * // Outputs 90.. * console.log("The angle of the vector is: " + angle); */ angle(): number; /** * Returns the shortest Euler angle between two 2-dimensional vectors. * * @param {Vec2} rhs - The 2-dimensional vector to calculate angle to. * @returns {number} The shortest angle in degrees between two 2-dimensional vectors. * @example * const a = new Vec2(0, 10); // up * const b = new Vec2(1, -1); // down-right * const angle = a.angleTo(b); * // Outputs 135.. * console.log("The angle between vectors a and b: " + angle); */ angleTo(rhs: Vec2): number; /** * Each element is set to the largest integer less than or equal to its value. * * @param {Vec2} [src] - The vector to floor. If not set, the operation is done in place. * @returns {Vec2} Self for chaining. * @example * const v = new Vec2(1.2, 3.9); * v.floor(); * // v is now [1, 3] */ floor(src?: Vec2): Vec2; /** * Each element is rounded up to the next largest integer. * * @param {Vec2} [src] - The vector to ceil. If not set, the operation is done in place. * @returns {Vec2} Self for chaining. * @example * const v = new Vec2(1.2, 3.1); * v.ceil(); * // v is now [2, 4] */ ceil(src?: Vec2): Vec2; /** * Each element is rounded up or down to the nearest integer. * * @param {Vec2} [src] - The vector to round. If not set, the operation is done in place. * @returns {Vec2} Self for chaining. * @example * const v = new Vec2(1.4, 3.6); * v.round(); * // v is now [1, 4] */ round(src?: Vec2): Vec2; /** * Each element is assigned a value from rhs parameter if it is smaller. * * @param {Vec2} rhs - The 2-dimensional vector used as the source of elements to compare to. * @returns {Vec2} Self for chaining. * @example * const a = new Vec2(5, 1); * const b = new Vec2(2, 8); * a.min(b); * // a is now [2, 1] */ min(rhs: Vec2): Vec2; /** * Each element is assigned a value from rhs parameter if it is larger. * * @param {Vec2} rhs - The 2-dimensional vector used as the source of elements to compare to. * @returns {Vec2} Self for chaining. * @example * const a = new Vec2(5, 1); * const b = new Vec2(2, 8); * a.max(b); * // a is now [5, 8] */ max(rhs: Vec2): Vec2; /** * Sets the specified 2-dimensional vector to the supplied numerical values. * * @param {number} x - The value to set on the first component of the vector. * @param {number} y - The value to set on the second component of the vector. * @returns {Vec2} Self for chaining. * @example * const v = new Vec2(); * v.set(5, 10); * * // Outputs 5, 10 * console.log("The result of the vector set is: " + v.toString()); */ set(x: number, y: number): Vec2; /** * Subtracts a 2-dimensional vector from another in place. * * @param {Vec2} rhs - The vector to subtract from the specified vector. * @returns {Vec2} Self for chaining. * @example * const a = new Vec2(10, 10); * const b = new Vec2(20, 20); * * a.sub(b); * * // Outputs [-10, -10] * console.log("The result of the subtraction is: " + a.toString()); */ sub(rhs: Vec2): Vec2; /** * Subtracts two 2-dimensional vectors from one another and returns the result. * * @param {Vec2} lhs - The first vector operand for the subtraction. * @param {Vec2} rhs - The second vector operand for the subtraction. * @returns {Vec2} Self for chaining. * @example * const a = new Vec2(10, 10); * const b = new Vec2(20, 20); * const r = new Vec2(); * * r.sub2(a, b); * * // Outputs [-10, -10] * console.log("The result of the subtraction is: " + r.toString()); */ sub2(lhs: Vec2, rhs: Vec2): Vec2; /** * Subtracts a number from each element of a vector. * * @param {number} scalar - The number to subtract. * @returns {Vec2} Self for chaining. * @example * const vec = new Vec2(3, 4); * * vec.subScalar(2); * * // Outputs [1, 2] * console.log("The result of the subtraction is: " + vec.toString()); */ subScalar(scalar: number): Vec2; /** * Set the values of the vector from an array. * * @param {number[]|ArrayBufferView} arr - The array to set the vector values from. * @param {number} [offset] - The zero-based index at which to start copying elements from the * array. Default is 0. * @returns {Vec2} Self for chaining. * @example * const v = new Vec2(); * v.fromArray([20, 10]); * // v is set to [20, 10] */ fromArray(arr: number[] | ArrayBufferView, offset?: number): Vec2; /** * Converts the vector to string form. * * @returns {string} The vector in string form. * @example * const v = new Vec2(20, 10); * // Outputs [20, 10] * console.log(v.toString()); */ toString(): string; /** * @overload * @param {number[]} [arr] - The array to populate with the vector's number * components. If not specified, a new array is created. * @param {number} [offset] - The zero-based index at which to start copying elements to the * array. Default is 0. * @returns {number[]} The vector as an array. */ toArray(arr?: number[], offset?: number): number[]; /** * @overload * @param {ArrayBufferView} arr - The array to populate with the vector's number * components. If not specified, a new array is created. * @param {number} [offset] - The zero-based index at which to start copying elements to the * array. Default is 0. * @returns {ArrayBufferView} The vector as an array. */ toArray(arr: ArrayBufferView, offset?: number): ArrayBufferView; } /** * The scope for variables. * * @category Graphics */ declare class ScopeSpace { /** * Create a new ScopeSpace instance. * * @param {string} name - The scope name. */ constructor(name: string); /** * The scope name. * * @type {string} */ name: string; variables: Map; /** * Get (or create, if it doesn't already exist) a variable in the scope. * * @param {string} name - The variable name. * @returns {ScopeId} The variable instance. */ resolve(name: string): ScopeId; /** * Clears value for any uniform with matching value (used to remove deleted textures). * * @param {*} value - The value to clear. * @ignore */ removeValue(value: any): void; } /** * A storage buffer represents a memory which both the CPU and the GPU can access. Typically it is * used to provide data for compute shader, and to store the result of the computation. * Note that this class is only supported on the WebGPU platform. * * After a graphics device is lost and restored, the GPU backing for a storage buffer is * recreated at the same byte size but its contents are undefined until you write to it again or * repopulate it via compute. * * For debug identification in buffer memory listings (when the {@link TRACEID_BUFFERS} trace * channel is enabled), call sites may assign the instance's `name` property to a descriptive * string. * * @category Graphics */ declare class StorageBuffer { /** * Create a new StorageBuffer instance. * * @param {GraphicsDevice} graphicsDevice - The graphics device used to manage this storage buffer. * @param {number} byteSize - The size of the storage buffer in bytes. * @param {number} [bufferUsage] - The usage type of the storage buffer. Can be a combination * of {@link BUFFERUSAGE_READ}, {@link BUFFERUSAGE_WRITE}, {@link BUFFERUSAGE_COPY_SRC} and * {@link BUFFERUSAGE_COPY_DST} flags. This parameter can be omitted if no special usage is * required. * @param {boolean} [addStorageUsage] - If true, automatically adds BUFFERUSAGE_STORAGE flag. * Set to false for staging buffers that use BUFFERUSAGE_WRITE. Defaults to true. */ constructor(graphicsDevice: GraphicsDevice, byteSize: number, bufferUsage?: number, addStorageUsage?: boolean); id: number; device: GraphicsDevice; byteSize: number; bufferUsage: number; impl: any; /** * Frees resources associated with this storage buffer. */ destroy(): void; /** * Called when the rendering context was lost. It releases the GPU buffer handle. * * @ignore */ loseContext(): void; /** * Called when the rendering context is restored. Recreates an empty GPU buffer of the same * size; contents are not restored from CPU memory. * * @ignore */ restoreContext(): void; adjustVramSizeTracking(vram: any, size: any): void; /** * Read the contents of a storage buffer. * * @param {number} [offset] - The byte offset of data to read. Defaults to 0. * @param {number} [size] - The byte size of data to read. Defaults to the full size of the * buffer minus the offset. * @param {ArrayBufferView|null} [data] - Typed array to populate with the data read from the * storage buffer. When typed array is supplied, enough space needs to be reserved, otherwise * only partial data is copied. If not specified, the data is returned in an Uint8Array. * Defaults to null. * @param {boolean} [immediate] - If true, the read operation will be executed as soon as * possible. This has a performance impact, so it should be used only when necessary. Defaults * to false. * @returns {Promise} A promise that resolves with the data read from the * storage buffer. Rejects with an `AbortError` if the read is cancelled, for example by device * loss. Other read failures also reject the promise. */ read(offset?: number, size?: number, data?: ArrayBufferView | null, immediate?: boolean): Promise; /** * Issues a write operation of the provided data into a storage buffer. * * @param {number} bufferOffset - The offset in bytes to start writing to the storage buffer. * @param {ArrayBufferView|ArrayBuffer} data - The data to write to the storage buffer. * @param {number} [dataOffset] - Offset in data to begin writing from. Given in elements if * data is a TypedArray and bytes otherwise. Defaults to 0. * @param {number} [size] - Size of content to write from data to buffer. Given in elements if * data is a TypedArray and bytes otherwise. Defaults to the remaining size of the data. */ write(bufferOffset: number, data: ArrayBufferView | ArrayBuffer, dataOffset?: number, size?: number): void; /** * Clear the content of a storage buffer to 0. * * @param {number} [offset] - The byte offset of data to clear. Defaults to 0. * @param {number} [size] - The byte size of data to clear. Defaults to the full size of the * buffer minus the offset. */ clear(offset?: number, size?: number): void; /** * Copy data from another storage buffer into this storage buffer. * * @param {StorageBuffer} srcBuffer - The source storage buffer to copy from. * @param {number} [srcOffset] - The byte offset in the source buffer. Defaults to 0. * @param {number} [dstOffset] - The byte offset in this buffer. Defaults to 0. * @param {number} [size] - The byte size of data to copy. Defaults to the full size of the * source buffer minus the source offset. */ copy(srcBuffer: StorageBuffer, srcOffset?: number, dstOffset?: number, size?: number): void; } /** * The per mesh instance data the vertex shaders read from a storage buffer instead of a per draw * uniform buffer: a slot per mesh instance, holding its model and normal matrix. A draw passes * the slot as its first instance, and the shader indexes the buffer by the instance index. The * data persists between frames, so only the slots of the mesh instances whose transform changed * are written, into a CPU copy of the buffer, and uploaded when the device submits its command * buffers - before those run. The buffer grows when it runs out of slots, and never shrinks. * * WebGPU only, see {@link GraphicsDevice#supportsMeshInstanceStorage}. * * @ignore */ declare class MeshInstanceStorage { /** * @param {GraphicsDevice} device - The graphics device. * @param {number} [capacity] - The initial number of slots. Defaults to 1024. */ constructor(device: GraphicsDevice, capacity?: number); /** * The number of slots the buffer holds. * * @type {number} */ capacity: number; /** * The number of slots ever allocated, the freed ones included. * * @type {number} */ count: number; /** * Incremented when the buffer is replaced by a larger one, so that the bind groups holding it * are updated. * * @type {number} */ version: number; /** @type {StorageBuffer|null} */ buffer: StorageBuffer | null; /** * The CPU copy of the buffer. * * @type {Float32Array} */ data: Float32Array; /** * The slots which can be allocated. * * @type {number[]} * @private */ private _freeSlots; /** * The slots released since the last submit, which can be allocated once it is done. The * draws recorded before it may still use them, and the data of the slots is uploaded once * for all of these draws. * * @type {number[]} * @private */ private _releasedSlots; /** * A bit per slot, set when the slot was written since the last upload, which walks them in * slot order. * * @type {Uint32Array} * @private */ private _dirtyBits; /** * True when any slot was written since the last upload. * * @type {boolean} * @private */ private _dirty; device: GraphicsDevice; scopeId: ScopeId; destroy(): void; /** * Uploads all the slots again after the device was lost and restored, which recreates the * buffer empty. The slots and their CPU copy are kept, as the mesh instances hold on to them. */ restoreContext(): void; /** * Allocates a slot, growing the buffer when all are in use. * * @returns {number} The slot. */ allocate(): number; /** * Returns a slot for reuse. * * @param {number} slot - The slot. */ free(slot: number): void; /** * Writes the matrices of a slot, uploaded on the next submit. * * @param {number} slot - The slot. * @param {Float32Array} model - The 16 floats of the model matrix. * @param {Float32Array} normal - The 9 floats of the normal matrix. */ write(slot: number, model: Float32Array, normal: Float32Array): void; /** * Uploads the slots written since the last upload, merging slots close together into one * write, and makes the slots released since available for allocation. Called by the device * before it submits its command buffers, which then run after the upload. */ upload(): void; /** * Makes the released slots available for allocation, once no draws recorded before their * release are pending. * * @private */ private _recycleReleasedSlots; /** * @private */ private _uploadDirtySlots; /** * @param {number} first - The first slot. * @param {number} last - The last slot, included. * @private */ private _writeRange; /** * Replaces the buffer with one of a new capacity, keeping the data. The old buffer is still * used by the commands recorded this frame, so the writes pending for it are uploaded to it * first, and its destruction is deferred until the commands are submitted. * * @param {number} capacity - The number of slots. * @private */ private _resize; } /** * A class storing description of an individual uniform, stored inside a uniform buffer. * * @category Graphics */ declare class UniformFormat { /** * Create a new UniformFormat instance. * * @param {string} name - The name of the uniform. * @param {number} type - The type of the uniform. One of the UNIFORMTYPE_*** constants. * @param {number} count - The number of elements in the array. Defaults to 0, which represents * a single element (not an array). */ constructor(name: string, type: number, count?: number); /** * @type {string} * @ignore */ name: string; /** * @type {number} * @ignore */ type: number; /** * @type {number} * @ignore */ byteSize: number; /** * Index of the uniform in an array of 32bit values (Float32Array and similar) * * @type {number} * @ignore */ offset: number; /** * @type {ScopeId} * @ignore */ scopeId: ScopeId; /** * Count of elements for arrays, otherwise 0. * * @type {number} * @ignore */ count: number; /** * Number of components in each element (e.g. vec2 has 2 components, mat4 has 16 components) * * @type {number} * @ignore */ numComponents: number; /** * True if this is an array of elements (i.e. count > 0) * * @type {boolean} */ get isArrayType(): boolean; shortName: string; updateType: number; invalid: boolean; calculateOffset(offset: any): void; } /** * A descriptor that defines the layout of data inside the uniform buffer. * * @category Graphics */ declare class UniformBufferFormat { /** * Create a new UniformBufferFormat instance. * * @param {GraphicsDevice} graphicsDevice - The graphics device. * @param {UniformFormat[]} uniforms - An array of uniforms to be stored in the buffer. * @param {object} [options] - Options. * @param {boolean} [options.pack] - Reorder the uniforms to minimize the padding of the std140 * layout: uniforms occupying whole 16-byte rows first (vec4, matrices and arrays), then each * vec3 followed by a scalar, then vec2s and the remaining scalars. The uniforms of the format * are then in layout order rather than in the order of the array. Only use it when the shader * declaration of the buffer is generated from this format, and never against a hand-written * declaration, whose member order has to match the array. Defaults to false. */ constructor(graphicsDevice: GraphicsDevice, uniforms: UniformFormat[], options?: { pack?: boolean; }); /** @ignore */ byteSize: number; /** * @type {Map} * @ignore */ map: Map; /** * A string uniquely describing the layout of the buffer (the names, types and array sizes * of its uniforms, in layout order), used to key caches of shaders processed against this * format. * * @type {string} * @ignore */ key: string; scope: ScopeSpace; /** @type {UniformFormat[]} */ uniforms: UniformFormat[]; /** * Returns format of a uniform with specified name. Returns undefined if the uniform is not found. * * @param {string} name - The name of the uniform. * @returns {UniformFormat|undefined} - The format of the uniform. */ get(name: string): UniformFormat | undefined; } /** * A class to describe the format of the uniform buffer for {@link BindGroupFormat}. * * @category Graphics */ declare class BindUniformBufferFormat extends BindBaseFormat { } /** * A class to describe the format of the texture for {@link BindGroupFormat}. * * @category Graphics */ declare class BindTextureFormat extends BindBaseFormat { /** * Create a new instance. * * @param {string} name - The name of the texture. * @param {number} visibility - A bit-flag that specifies the shader stages in which the texture * is visible. Can be: * * - {@link SHADERSTAGE_VERTEX} * - {@link SHADERSTAGE_FRAGMENT} * - {@link SHADERSTAGE_COMPUTE} * * @param {string} [textureDimension] - The dimension of the texture. Defaults to * {@link TEXTUREDIMENSION_2D}. Can be: * * - {@link TEXTUREDIMENSION_1D} * - {@link TEXTUREDIMENSION_2D} * - {@link TEXTUREDIMENSION_2D_ARRAY} * - {@link TEXTUREDIMENSION_CUBE} * - {@link TEXTUREDIMENSION_CUBE_ARRAY} * - {@link TEXTUREDIMENSION_3D} * * When `multisampled` is true, must be {@link TEXTUREDIMENSION_2D}. * * @param {number} [sampleType] - The type of the texture samples. Defaults to * {@link SAMPLETYPE_FLOAT}. Can be: * * - {@link SAMPLETYPE_FLOAT} * - {@link SAMPLETYPE_UNFILTERABLE_FLOAT} * - {@link SAMPLETYPE_DEPTH} * - {@link SAMPLETYPE_INT} * - {@link SAMPLETYPE_UINT} * * When `multisampled` is true, {@link SAMPLETYPE_FLOAT} is coerced to * {@link SAMPLETYPE_UNFILTERABLE_FLOAT} (WebGPU rejects `sampleType: "float"` on a * multisampled binding). * * @param {boolean} [hasSampler] - True if the sampler for the texture is needed. Note that if the * sampler is used, it will take up an additional slot, directly following the texture slot. * Defaults to true. Forced to false when `multisampled` is true. * @param {string|null} [samplerName] - Sampler uniform name. If omitted, generated as * `${name}_sampler`. Ignored and stored as `null` when `multisampled` is true. * @param {boolean} [multisampled] - True if this is a multisampled texture binding * (`texture_multisampled_2d` / `texture_depth_multisampled_2d`). When set, `hasSampler` is * forced to false and `samplerName` to null (WGSL only allows `textureLoad`, and a WebGPU * multisampled texture binding cannot be paired with a sampler). Defaults to false. */ constructor(name: string, visibility: number, textureDimension?: string, sampleType?: number, hasSampler?: boolean, samplerName?: string | null, multisampled?: boolean); /** * Sampler uniform name. `null` when `multisampled` is true; otherwise the provided name or * `${name}_sampler`. * * @type {string|null} */ samplerName: string | null; /** * Whether a sampler binding follows this texture. Always false when `multisampled` is true. * * @type {boolean} */ hasSampler: boolean; /** * Whether this is a multisampled (`texture_multisampled_*`) binding. * * @type {boolean} */ multisampled: boolean; /** * The name of the built-in texture to substitute when a bind group has no value for this slot, * which is an error. Resolved from the name here, so the render path does not have to. * * @type {string} * @ignore */ substituteTexture: string; textureDimension: string; sampleType: number; } /** * BindGroupFormat is a data structure that defines the layout of resources (buffers, textures, * samplers) used by rendering or compute shaders. It describes the binding points for each * resource type, and the visibility of these resources in the shader stages. * Currently this class is only used on WebGPU platform to specify the input and output resources * for vertex, fragment and compute shaders written in {@link SHADERLANGUAGE_WGSL} language. * * Call {@link BindGroupFormat#destroy} when no longer needed. On WebGPU, the graphics device * retains bind group formats for device recovery until they are explicitly destroyed. * * @category Graphics */ declare class BindGroupFormat { /** * Create a new instance. * * @param {GraphicsDevice} graphicsDevice - The graphics device used to manage this vertex format. * @param {(BindTextureFormat|BindStorageTextureFormat|BindUniformBufferFormat|BindStorageBufferFormat)[]} formats * An array of bind formats. Note that each entry in the array uses up one slot. The exception * is a texture format that has a sampler, which uses up two slots. The slots are allocated * sequentially, starting from 0. */ constructor(graphicsDevice: GraphicsDevice, formats: (BindTextureFormat | BindStorageTextureFormat | BindUniformBufferFormat | BindStorageBufferFormat)[]); /** * @type {BindUniformBufferFormat[]} * @private */ private uniformBufferFormats; /** * @type {BindTextureFormat[]} * @private */ private textureFormats; /** * @type {BindStorageTextureFormat[]} * @private */ private storageTextureFormats; /** * @type {BindStorageBufferFormat[]} * @private */ private storageBufferFormats; /** * A string uniquely describing the resources of the format (their kinds, names, slots and * the properties that select the shader declaration), used to key caches of shaders * processed against this format. * * @type {string} * @ignore */ key: string; /** * True when the format holds no resources. A bind group of it binds nothing, so the empty bind * group of the device can be bound in its place. * * @type {boolean} * @ignore */ empty: boolean; id: number; /** @type {GraphicsDevice} */ device: GraphicsDevice; /** @type {Map} */ bufferFormatsMap: Map; /** @type {Map} */ textureFormatsMap: Map; /** @type {Map} */ storageTextureFormatsMap: Map; /** @type {Map} */ storageBufferFormatsMap: Map; impl: any; /** * Frees resources associated with this bind group. */ destroy(): void; /** * Returns format of texture with specified name. * * @param {string} name - The name of the texture slot. * @returns {BindTextureFormat|null} - The format. * @ignore */ getTexture(name: string): BindTextureFormat | null; /** * Returns format of storage texture with specified name. * * @param {string} name - The name of the texture slot. * @returns {BindStorageTextureFormat|null} - The format. * @ignore */ getStorageTexture(name: string): BindStorageTextureFormat | null; loseContext(): void; } /** * A class to describe the format of the storage texture for {@link BindGroupFormat}. Storage * texture is a texture created with the storage flag set to true, which allows it to be used as an * output of a compute shader. * * Note: At the current time, storage textures are only supported in compute shaders in a * write-only mode. * * @category Graphics */ declare class BindStorageTextureFormat extends BindBaseFormat { /** * Create a new instance. * * @param {string} name - The name of the storage buffer. * @param {number} [format] - The pixel format of the texture. Note that not all formats can be * used. Defaults to {@link PIXELFORMAT_RGBA8}. * @param {string} [textureDimension] - The dimension of the texture. Defaults to * {@link TEXTUREDIMENSION_2D}. Can be: * * - {@link TEXTUREDIMENSION_1D} * - {@link TEXTUREDIMENSION_2D} * - {@link TEXTUREDIMENSION_2D_ARRAY} * - {@link TEXTUREDIMENSION_3D} * * @param {boolean} [write] - Whether the storage texture is writable. Defaults to true. * @param {boolean} [read] - Whether the storage texture is readable. Defaults to false. Note * that storage texture reads are only supported if * {@link GraphicsDevice#supportsStorageTextureRead} is true. Also note that only a subset of * pixel formats can be used for storage texture reads - as an example, PIXELFORMAT_RGBA8 is not * compatible, but PIXELFORMAT_R32U is. */ constructor(name: string, format?: number, textureDimension?: string, write?: boolean, read?: boolean); format: number; textureDimension: string; write: boolean; read: boolean; } /** * A class to describe the format of the storage buffer for {@link BindGroupFormat}. * * @category Graphics */ declare class BindStorageBufferFormat extends BindBaseFormat { /** * Create a new instance. * * @param {string} name - The name of the storage buffer. * @param {number} visibility - A bit-flag that specifies the shader stages in which the storage * buffer is visible. Can be: * * - {@link SHADERSTAGE_VERTEX} * - {@link SHADERSTAGE_FRAGMENT} * - {@link SHADERSTAGE_COMPUTE} * * @param {boolean} [readOnly] - Whether the storage buffer is read-only, or read-write. Defaults * to false. This has to be true for the storage buffer used in the vertex shader. */ constructor(name: string, visibility: number, readOnly?: boolean); /** * Format, extracted from vertex and fragment shader. * * @ignore */ format: string; readOnly: boolean; } /** * A base class to describe the format of the resource for {@link BindGroupFormat}. * * @category Graphics */ declare class BindBaseFormat { /** * Create a new instance. * * @param {string} name - The name of the resource. * @param {number} visibility - A bit-flag that specifies the shader stages in which the resource * is visible. Can be: * * - {@link SHADERSTAGE_VERTEX} * - {@link SHADERSTAGE_FRAGMENT} * - {@link SHADERSTAGE_COMPUTE} */ constructor(name: string, visibility: number); /** @ignore */ slot: number; /** * @type {ScopeId|null} * @ignore */ scopeId: ScopeId | null; /** @type {string} */ name: string; visibility: number; /** * A string describing the resource for the purpose of keying caches of shaders processed * against it. Subclasses prefix it with the kind of the resource and append the properties * that select their shader declaration. Valid once the slot has been assigned by the * {@link BindGroupFormat}. * * @type {string} * @ignore */ get key(): string; } /** * A shader is a program that is responsible for rendering graphical primitives on a device's * graphics processor. The shader is generated from a shader definition. This shader definition * specifies the code for processing vertices and fragments processed by the GPU. The language of * the code is GLSL (or more specifically ESSL, the OpenGL ES Shading Language). The shader * definition also describes how the PlayCanvas engine should map vertex buffer elements onto the * attributes specified in the vertex shader code. * * @category Graphics */ declare class Shader { /** * Creates a new Shader instance. * * Consider {@link ShaderUtils.createShader} as a simpler and more powerful way to create * a shader. * * @param {GraphicsDevice} graphicsDevice - The graphics device used to manage this shader. * @param {object} definition - The shader definition from which to build the shader. * @param {string} [definition.name] - The name of the shader. * @param {Object} [definition.attributes] - Object detailing the mapping of * vertex shader attribute names to semantics SEMANTIC_*. This enables the engine to match * vertex buffer data as inputs to the shader. When not specified, rendering without vertex * buffer is assumed. * @param {string[]} [definition.feedbackVaryings] - A list of shader output variable * names that will be captured when using transform feedback. This setting is only effective * if the useTransformFeedback property is enabled. * @param {number} [definition.feedbackVaryingsMode] - Specifies how transform feedback varyings * are written into GPU buffers. Use {@link TRANSFORM_FEEDBACK_INTERLEAVED} to pack all captured * varyings into a single buffer, or {@link TRANSFORM_FEEDBACK_SEPARATE} to store each varying * in its own buffer. This setting is only effective when useTransformFeedback property is enabled. * Defaults to {@link TRANSFORM_FEEDBACK_INTERLEAVED}. * @param {string} [definition.vshader] - Vertex shader source (GLSL code). Optional when * compute shader is specified. * @param {string} [definition.fshader] - Fragment shader source (GLSL code). Optional when * useTransformFeedback or compute shader is specified. * @param {string} [definition.cshader] - Compute shader source (WGSL code). Only supported on * WebGPU platform. * @param {string} [definition.computeEntryPoint] - The entry point function name for the compute * shader. Defaults to 'main'. * @param {BindGroupFormat} [definition.computeBindGroupFormat] - The bind group format for * caller-provided compute resources in group 0. Only used on WebGPU. * @param {Object} [definition.computeUniformBufferFormats] - The * uniform buffer formats keyed by bind group entry name. Requires computeBindGroupFormat. * @param {Map} [definition.vincludes] - A map containing key-value pairs of * include names and their content. These are used for resolving #include directives in the * vertex shader source. * @param {Map} [definition.fincludes] - A map containing key-value pairs * of include names and their content. These are used for resolving #include directives in the * fragment shader source. * @param {Map} [definition.cincludes] - A map containing key-value pairs * of include names and their content. These are used for resolving #include directives in the * compute shader source. * @param {Map} [definition.cdefines] - A map containing key-value pairs of * define names and their values. These are used for resolving defines in the compute shader. * @param {boolean} [definition.useTransformFeedback] - Specifies that this shader outputs * post-VS data to a buffer. * @param {string | string[]} [definition.fragmentOutputTypes] - Fragment shader output types, * which default to vec4. Passing a string will set the output type for all color attachments. * Passing an array will set the output type for each color attachment. * @param {boolean} [definition.useDualSourceBlending] - Whether the fragment shader outputs a * secondary color for dual-source blending. Defaults to false. * @param {string} [definition.shaderLanguage] - Specifies the shader language of vertex and * fragment shaders. Defaults to {@link SHADERLANGUAGE_GLSL}. * @example * // Create a shader that renders primitives with a solid red color * * // Vertex shader * const vshader = ` * attribute vec3 aPosition; * * void main(void) { * gl_Position = vec4(aPosition, 1.0); * } * `; * * // Fragment shader * const fshader = ` * precision ${graphicsDevice.precision} float; * * void main(void) { * gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0); * } * `; * * const shaderDefinition = { * attributes: { * aPosition: SEMANTIC_POSITION * }, * vshader, * fshader * }; * * const shader = new Shader(graphicsDevice, shaderDefinition); */ constructor(graphicsDevice: GraphicsDevice, definition: { name?: string; attributes?: { [x: string]: string; }; feedbackVaryings?: string[]; feedbackVaryingsMode?: number; vshader?: string; fshader?: string; cshader?: string; computeEntryPoint?: string; computeBindGroupFormat?: BindGroupFormat; computeUniformBufferFormats?: { [x: string]: UniformBufferFormat; }; vincludes?: Map; fincludes?: Map; cincludes?: Map; cdefines?: Map; useTransformFeedback?: boolean; fragmentOutputTypes?: string | string[]; useDualSourceBlending?: boolean; shaderLanguage?: string; }); /** * Format of the uniform buffer for mesh bind group. * * @type {UniformBufferFormat} * @ignore */ meshUniformBufferFormat: UniformBufferFormat; /** * True when the mesh uniform buffer holds no uniforms of the shader, only a placeholder, as * WebGPU requires the buffer bound. Its draws can share one buffer, bound once per pass. * * @type {boolean} * @ignore */ meshUniformBufferEmpty: boolean; /** * Format of the bind group for the mesh bind group. * * @type {BindGroupFormat} * @ignore */ meshBindGroupFormat: BindGroupFormat; /** * Format of the view bind group when the shader reads textures the renderer supplies per pass * in it, following the view uniform buffer, or null when the group holds only the view uniform * buffer. The format is shared by all shaders reading the same textures, and is not owned by * the shader. * * @type {BindGroupFormat|null} * @ignore */ viewBindGroupFormat: BindGroupFormat | null; /** * True when the vertex shader reads the model and normal matrices of the mesh instance from the * mesh instance storage of the device, see {@link GraphicsDevice#meshInstanceStorage}, indexed * by the instance index. The draws of such a shader pass the slot of the mesh instance as the * first instance. * * @type {boolean} * @ignore */ usesMeshInstanceStorage: boolean; /** * The attributes that this shader code uses. The location is the key, the value is the name. * These attributes are queried / extracted from the final shader. * * @type {Map} * @ignore */ attributes: Map; /** * Set by the shadow renderer once it has checked whether the shader reads the normal matrix, * which the shadow pass does not supply. Debug builds only. * * @type {boolean} * @private */ private _debugNormalMatrixChecked; id: number; device: GraphicsDevice; definition: { name?: string; attributes?: { [x: string]: string; }; feedbackVaryings?: string[]; feedbackVaryingsMode?: number; vshader?: string; fshader?: string; cshader?: string; computeEntryPoint?: string; computeBindGroupFormat?: BindGroupFormat; computeUniformBufferFormats?: { [x: string]: UniformBufferFormat; }; vincludes?: Map; fincludes?: Map; cincludes?: Map; cdefines?: Map; useTransformFeedback?: boolean; fragmentOutputTypes?: string | string[]; useDualSourceBlending?: boolean; shaderLanguage?: string; }; name: string; cUnmodified: string; vUnmodified: string; fUnmodified: string; failed: boolean; impl: any; /** * Initialize a shader back to its default state. * * @private */ private init; ready: boolean; /** @ignore */ get label(): string; /** * Whether the shader reads a uniform, for debug validation. On WebGL the active uniforms of the * linked program, from which the driver strips the unused ones. On WebGPU the uniforms the * shader declares, as WGSL is not reflected. Debug builds only. * * @param {string} name - The name of the uniform. * @returns {boolean|null} Whether the shader reads the uniform, or null when that is not known, * before the shader is ready or on a device without shader reflection. * @ignore */ debugReadsUniform(name: string): boolean | null; /** * Frees resources associated with this shader. */ destroy(): void; /** * Called when the WebGL context was lost. It releases all context related resources. * * @ignore */ loseContext(): void; /** @ignore */ restoreContext(): void; } /** * A vertex format is a descriptor that defines the layout of vertex data inside a * {@link VertexBuffer}. * * @property {object[]} elements The vertex attribute elements. * @property {string} elements[].name The meaning of the vertex element. This is used to link the * vertex data to a shader input. Can be: * * - {@link SEMANTIC_POSITION} * - {@link SEMANTIC_NORMAL} * - {@link SEMANTIC_TANGENT} * - {@link SEMANTIC_BLENDWEIGHT} * - {@link SEMANTIC_BLENDINDICES} * - {@link SEMANTIC_COLOR} * - {@link SEMANTIC_TEXCOORD0} * - {@link SEMANTIC_TEXCOORD1} * - {@link SEMANTIC_TEXCOORD2} * - {@link SEMANTIC_TEXCOORD3} * - {@link SEMANTIC_TEXCOORD4} * - {@link SEMANTIC_TEXCOORD5} * - {@link SEMANTIC_TEXCOORD6} * - {@link SEMANTIC_TEXCOORD7} * * If vertex data has a meaning other that one of those listed above, use the user-defined * semantics: {@link SEMANTIC_ATTR0} to {@link SEMANTIC_ATTR15}. * @property {number} elements[].numComponents The number of components of the vertex attribute. * Can be 1, 2, 3 or 4. * @property {number} elements[].dataType The data type of the attribute. Can be: * * - {@link TYPE_INT8} * - {@link TYPE_UINT8} * - {@link TYPE_INT16} * - {@link TYPE_UINT16} * - {@link TYPE_INT32} * - {@link TYPE_UINT32} * - {@link TYPE_FLOAT32} * - {@link TYPE_FLOAT16} * @property {boolean} elements[].normalize If true, vertex attribute data will be mapped from a 0 * to 255 range down to 0 to 1 when fed to a shader. If false, vertex attribute data is left * unchanged. If this property is unspecified, false is assumed. * @property {number} elements[].offset The number of initial bytes at the start of a vertex that * are not relevant to this attribute. * @property {number} elements[].stride The number of total bytes that are between the start of one * vertex, and the start of the next. * @property {number} elements[].size The size of the attribute in bytes. * @category Graphics */ declare class VertexFormat { /** * The {@link VertexFormat} used to store matrices of type {@link Mat4} for hardware instancing. * The matrix rows use {@link SEMANTIC_ATTR11}, {@link SEMANTIC_ATTR12}, {@link SEMANTIC_ATTR14} * and {@link SEMANTIC_ATTR15}. The first two share their attribute locations with * {@link SEMANTIC_TEXCOORD6} and {@link SEMANTIC_TEXCOORD7}, so a shader reading those texture * coordinate sets needs a custom instancing format on other attributes. * * @param {GraphicsDevice} graphicsDevice - The graphics device used to create this vertex * format. * @returns {VertexFormat} The default instancing vertex format. */ static getDefaultInstancingFormat(graphicsDevice: GraphicsDevice): VertexFormat; /** * @deprecated Use VertexFormat.getDefaultInstancingFormat(graphicsDevice). * @returns {null} Always null. * @ignore */ static get defaultInstancingFormat(): null; static isElementValid(graphicsDevice: any, elementDesc: any): boolean; /** * @typedef {object} AttributeDescription * @property {string} semantic - The meaning of the vertex element. This is used to * link the vertex data to a shader input. Can be: * * - {@link SEMANTIC_POSITION} * - {@link SEMANTIC_NORMAL} * - {@link SEMANTIC_TANGENT} * - {@link SEMANTIC_BLENDWEIGHT} * - {@link SEMANTIC_BLENDINDICES} * - {@link SEMANTIC_COLOR} * - {@link SEMANTIC_TEXCOORD0} * - {@link SEMANTIC_TEXCOORD1} * - {@link SEMANTIC_TEXCOORD2} * - {@link SEMANTIC_TEXCOORD3} * - {@link SEMANTIC_TEXCOORD4} * - {@link SEMANTIC_TEXCOORD5} * - {@link SEMANTIC_TEXCOORD6} * - {@link SEMANTIC_TEXCOORD7} * * If vertex data has a meaning other that one of those listed above, use the user-defined * semantics: {@link SEMANTIC_ATTR0} to {@link SEMANTIC_ATTR15}. * @property {number} components - The number of components of the vertex attribute. * Can be 1, 2, 3 or 4. * @property {number} type - The data type of the attribute. Can be: * * - {@link TYPE_INT8} * - {@link TYPE_UINT8} * - {@link TYPE_INT16} * - {@link TYPE_UINT16} * - {@link TYPE_INT32} * - {@link TYPE_UINT32} * - {@link TYPE_FLOAT16} * - {@link TYPE_FLOAT32} * * @property {boolean} [normalize] - If true, vertex attribute data will be mapped * from a 0 to 255 range down to 0 to 1 when fed to a shader. If false, vertex attribute data * is left unchanged. If this property is unspecified, false is assumed. This property is * ignored when asInt is true. * @property {boolean} [asInt] - If true, vertex attribute data will be accessible * as integer numbers in shader code. Defaults to false, which means that vertex attribute data * will be accessible as floating point numbers. Can be only used with INT and UINT data types. */ /** * Create a new VertexFormat instance. * * @param {GraphicsDevice} graphicsDevice - The graphics device used to manage this vertex * format. * @param {AttributeDescription[]} description - An array of vertex attribute descriptions. * @param {number} [vertexCount] - When specified, vertex format will be set up for * non-interleaved format with a specified number of vertices. (example: PPPPNNNNCCCC), where * arrays of individual attributes will be stored one right after the other (subject to * alignment requirements). Note that in this case, the format depends on the number of * vertices, and needs to change when the number of vertices changes. When not specified, * vertex format will be interleaved. (example: PNCPNCPNCPNC). * @example * // Specify 3-component positions (x, y, z) * const vertexFormat = new VertexFormat(graphicsDevice, [ * { semantic: SEMANTIC_POSITION, components: 3, type: TYPE_FLOAT32 } * ]); * @example * // Specify 2-component positions (x, y), a texture coordinate (u, v) and a vertex color (r, g, b, a) * const vertexFormat = new VertexFormat(graphicsDevice, [ * { semantic: SEMANTIC_POSITION, components: 2, type: TYPE_FLOAT32 }, * { semantic: SEMANTIC_TEXCOORD0, components: 2, type: TYPE_FLOAT32 }, * { semantic: SEMANTIC_COLOR, components: 4, type: TYPE_UINT8, normalize: true } * ]); */ constructor(graphicsDevice: GraphicsDevice, description: { /** * - The meaning of the vertex element. This is used to * link the vertex data to a shader input. Can be: * * - {@link SEMANTIC_POSITION} * - {@link SEMANTIC_NORMAL} * - {@link SEMANTIC_TANGENT} * - {@link SEMANTIC_BLENDWEIGHT} * - {@link SEMANTIC_BLENDINDICES} * - {@link SEMANTIC_COLOR} * - {@link SEMANTIC_TEXCOORD0} * - {@link SEMANTIC_TEXCOORD1} * - {@link SEMANTIC_TEXCOORD2} * - {@link SEMANTIC_TEXCOORD3} * - {@link SEMANTIC_TEXCOORD4} * - {@link SEMANTIC_TEXCOORD5} * - {@link SEMANTIC_TEXCOORD6} * - {@link SEMANTIC_TEXCOORD7} * * If vertex data has a meaning other that one of those listed above, use the user-defined * semantics: {@link SEMANTIC_ATTR0} to {@link SEMANTIC_ATTR15}. */ semantic: string; /** * - The number of components of the vertex attribute. * Can be 1, 2, 3 or 4. */ components: number; /** * - The data type of the attribute. Can be: * * - {@link TYPE_INT8} * - {@link TYPE_UINT8} * - {@link TYPE_INT16} * - {@link TYPE_UINT16} * - {@link TYPE_INT32} * - {@link TYPE_UINT32} * - {@link TYPE_FLOAT16} * - {@link TYPE_FLOAT32} */ type: number; /** * - If true, vertex attribute data will be mapped * from a 0 to 255 range down to 0 to 1 when fed to a shader. If false, vertex attribute data * is left unchanged. If this property is unspecified, false is assumed. This property is * ignored when asInt is true. */ normalize?: boolean; /** * - If true, vertex attribute data will be accessible * as integer numbers in shader code. Defaults to false, which means that vertex attribute data * will be accessible as floating point numbers. Can be only used with INT and UINT data types. */ asInt?: boolean; }[], vertexCount?: number); device: GraphicsDevice; _elements: { name: string; offset: any; stride: any; dataType: number; numComponents: number; normalize: boolean; size: number; asInt: boolean; }[]; _uvMask: number; hasColor: boolean; hasTangents: boolean; verticesByteSize: number; vertexCount: number; interleaved: boolean; instancing: boolean; size: number; get elements(): { name: string; offset: any; stride: any; dataType: number; numComponents: number; normalize: boolean; size: number; asInt: boolean; }[]; /** * The texture coordinate sets contained in the format, as a bit mask with bit i set when the * format contains the semantic {@link SEMANTIC_TEXCOORD0} + i. * * @type {number} * @ignore */ get uvMask(): number; /** * Returns true if the format contains the texture coordinate set with the specified index. * * @param {number} index - The index of the texture coordinate set, from 0 for * {@link SEMANTIC_TEXCOORD0} to 7 for {@link SEMANTIC_TEXCOORD7}. * @returns {boolean} True if the format contains the texture coordinate set. */ hasUv(index: number): boolean; /** * Applies any changes made to the VertexFormat's properties. * * @private */ private update; /** * Evaluates hash values for the format allowing fast compare of batching / rendering compatibility. * * @private */ private _evaluateHash; batchingHash: number; shaderProcessingHashString: string; renderingHashString: string; renderingHash: number; } /** * A vertex buffer is the mechanism via which the application specifies vertex data to the graphics * hardware. * * @category Graphics */ declare class VertexBuffer { /** * Create a new VertexBuffer instance. * * @param {GraphicsDevice} graphicsDevice - The graphics device used to manage this vertex * buffer. * @param {VertexFormat} format - The vertex format of this vertex buffer. * @param {number} numVertices - The number of vertices that this vertex buffer will hold. * @param {object} [options] - Object for passing optional arguments. * @param {number} [options.usage] - The usage type of the vertex buffer (see BUFFER_*). * Defaults to BUFFER_STATIC. * @param {ArrayBuffer|ArrayBufferView} [options.data] - Initial data. Can be an * `ArrayBuffer` or a typed array (for example a `Float32Array`). The data is * stored by reference and is not copied, so a typed array that is a view into a larger buffer * is kept as-is. If left unspecified, the vertex buffer will be initialized to zeros. * @param {boolean} [options.storage] - Defines if the vertex buffer can be used as a storage * buffer by a compute shader. Defaults to false. Only supported on WebGPU. */ constructor(graphicsDevice: GraphicsDevice, format: VertexFormat, numVertices: number, options?: { usage?: number; data?: ArrayBuffer | ArrayBufferView; storage?: boolean; }, ...args: any[]); usage: number; /** * Lazily evaluated cache of {@link VertexBuffer#vaoKeyPart}. * * @type {string|null} * @private */ private _vaoKeyPart; device: GraphicsDevice; format: VertexFormat; numVertices: number; id: number; impl: any; numBytes: number; storage: ArrayBuffer; /** * This buffer's contribution to the key of the device's vertex array object cache. It identifies * both the buffer and its format, and is delimited so that the parts of several buffers can be * concatenated without ambiguity. * * Evaluated lazily, as it is only needed by buffers taking part in a draw which uses more than * one vertex buffer, and most buffers never do. The format of a vertex buffer never changes, so * the value is safe to cache. * * @type {string} * @ignore */ get vaoKeyPart(): string; /** * Frees resources associated with this vertex buffer. */ destroy(): void; adjustVramSizeTracking(vram: any, size: any): void; /** * Called when the rendering context was lost. It releases all context related resources. * * @ignore */ loseContext(): void; /** * Called when the rendering context is restored. Recreates the GPU buffer and uploads from * {@link VertexBuffer#lock|lock} storage. * * @ignore */ restoreContext(): void; /** * Returns the data format of the specified vertex buffer. * * @returns {VertexFormat} The data format of the specified vertex buffer. */ getFormat(): VertexFormat; /** * Returns the usage type of the specified vertex buffer. This indicates whether the buffer can * be modified once and used many times {@link BUFFER_STATIC}, modified repeatedly and used * many times {@link BUFFER_DYNAMIC} or modified once and used at most a few times * {@link BUFFER_STREAM}. * * @returns {number} The usage type of the vertex buffer (see BUFFER_*). */ getUsage(): number; /** * Returns the number of vertices stored in the specified vertex buffer. * * @returns {number} The number of vertices stored in the vertex buffer. */ getNumVertices(): number; /** * Returns a mapped memory block representing the content of the vertex buffer. * * @returns {ArrayBuffer|ArrayBufferView} The memory that stores the buffer's vertices. This * matches whatever was supplied as the initial data: an {@link ArrayBuffer} when none was * provided, otherwise the {@link ArrayBuffer} or typed array that was passed in. Use * {@link ArrayBuffer.isView} to distinguish the two before accessing it. */ lock(): ArrayBuffer | ArrayBufferView; /** * Uploads the client side copy of the vertex buffer to the GPU. When called without arguments, * uploads the entire buffer. An explicit range uploads only those bytes at the same GPU offset. * The first upload always initializes the entire GPU buffer, regardless of the requested range. * A zero byte length does nothing, including before the first upload. * * Partial uploads do not resize the buffer or change its CPU storage. The caller must upload * every modified range before expecting those changes on the GPU. Context restoration uploads * the entire CPU storage. Invalid ranges are ignored in all builds and report an assertion * in debug builds. * * @param {number} [byteOffset] - Offset in bytes from the start of the buffer's storage. * Defaults to 0. Must be a non-negative integer and a multiple of 4 on all graphics backends. * @param {number} [byteLength] - Number of bytes to upload. Defaults to the remaining bytes * after byteOffset. The length must be a non-negative integer and the range must fit within * the buffer. Partial ranges require a length that is a multiple of 4. Full-buffer uploads * support any byte length, whether the range is explicit or the arguments are omitted. * @example * // After modifying bytes 16 through 31 of the CPU storage: * vertexBuffer.unlock(16, 16); */ unlock(byteOffset?: number, byteLength?: number): void; /** * Sets the data of the vertex buffer and uploads it to the GPU. * * @param {ArrayBuffer|ArrayBufferView} [data] - Source data. Can be an {@link ArrayBuffer} or * a typed array. Stored by reference, not copied. * @returns {boolean} True if function finished successfully, false otherwise. */ setData(data?: ArrayBuffer | ArrayBufferView): boolean; } /** * An index buffer stores index values into a {@link VertexBuffer}. Indexed graphical primitives * can normally utilize less memory that unindexed primitives (if vertices are shared). * * Typically, index buffers are set on {@link Mesh} objects. * * @category Graphics */ declare class IndexBuffer { /** * Create a new IndexBuffer instance. * * @param {GraphicsDevice} graphicsDevice - The graphics device used to manage this index buffer. * @param {number} format - The type of each index to be stored in the index buffer. Can be: * * - {@link INDEXFORMAT_UINT8} * - {@link INDEXFORMAT_UINT16} * - {@link INDEXFORMAT_UINT32} * @param {number} numIndices - The number of indices to be stored in the index buffer. * @param {number} [usage] - The usage type of the vertex buffer. Can be: * * - {@link BUFFER_DYNAMIC} * - {@link BUFFER_STATIC} * - {@link BUFFER_STREAM} * * Defaults to {@link BUFFER_STATIC}. * @param {ArrayBuffer|ArrayBufferView} [initialData] - Initial data. Can be an * {@link ArrayBuffer} or a typed array (for example a {@link Uint16Array}). The data is stored * by reference and is not copied, so a typed array that is a view into a larger buffer is kept * as-is. If left unspecified, the index buffer will be initialized to zeros. * @param {object} [options] - Object for passing optional arguments. * @param {boolean} [options.storage] - Defines if the index buffer can be used as a storage * buffer by a compute shader. Defaults to false. Only supported on WebGPU. * @example * // Create an index buffer holding 3 16-bit indices. The buffer is marked as * // static, hinting that the buffer will never be modified. * const indices = new Uint16Array([0, 1, 2]); * const indexBuffer = new IndexBuffer(graphicsDevice, * INDEXFORMAT_UINT16, * 3, * BUFFER_STATIC, * indices); */ constructor(graphicsDevice: GraphicsDevice, format: number, numIndices: number, usage?: number, initialData?: ArrayBuffer | ArrayBufferView, options?: { storage?: boolean; }); device: GraphicsDevice; format: number; numIndices: number; usage: number; id: number; impl: any; bytesPerIndex: number; numBytes: number; storage: ArrayBuffer; /** * Frees resources associated with this index buffer. */ destroy(): void; adjustVramSizeTracking(vram: any, size: any): void; /** * Called when the rendering context was lost. It releases all context related resources. * * @ignore */ loseContext(): void; /** * Called when the rendering context is restored. Recreates the GPU buffer and uploads from * {@link IndexBuffer#lock|lock} storage. * * @ignore */ restoreContext(): void; /** * Returns the data format of the specified index buffer. * * @returns {number} The data format of the specified index buffer. Can be: * * - {@link INDEXFORMAT_UINT8} * - {@link INDEXFORMAT_UINT16} * - {@link INDEXFORMAT_UINT32} */ getFormat(): number; /** * Returns the number of indices stored in the specified index buffer. * * @returns {number} The number of indices stored in the specified index buffer. */ getNumIndices(): number; /** * Gives access to the block of memory that stores the buffer's indices. * * @returns {ArrayBuffer|ArrayBufferView} The memory that stores the buffer's indices. This * matches whatever was supplied as the initial data: an {@link ArrayBuffer} when none was * provided, otherwise the {@link ArrayBuffer} or typed array that was passed in. Use * {@link ArrayBuffer.isView} to distinguish the two before accessing it. */ lock(): ArrayBuffer | ArrayBufferView; /** * Uploads the client side copy of the index buffer to the GPU. When called without arguments, * uploads the entire buffer. An explicit range uploads only those bytes at the same GPU offset. * The first upload always initializes the entire GPU buffer, regardless of the requested range. * A zero byte length does nothing, including before the first upload. * * Partial uploads do not resize the buffer or change its CPU storage. The caller must upload * every modified range before expecting those changes on the GPU. Context restoration uploads * the entire CPU storage. Invalid ranges are ignored in all builds and report an assertion * in debug builds. * * @param {number} [byteOffset] - Offset in bytes from the start of the buffer's storage. * Defaults to 0. Must be a non-negative integer and a multiple of 4 on all graphics backends. * @param {number} [byteLength] - Number of bytes to upload. Defaults to the remaining bytes * after byteOffset. The length must be a non-negative integer and the range must fit within * the buffer. Partial ranges require a length that is a multiple of 4. Full-buffer uploads * support any byte length, whether the range is explicit or the arguments are omitted. * @example * // After modifying bytes 16 through 31 of the CPU storage: * indexBuffer.unlock(16, 16); */ unlock(byteOffset?: number, byteLength?: number): void; /** * Set preallocated data on the index buffer. * * @param {ArrayBuffer|ArrayBufferView} data - The index data to set. Can be an * {@link ArrayBuffer} or a typed array. Stored by reference, not copied. * @returns {boolean} True if the data was set successfully, false otherwise. * @ignore */ setData(data: ArrayBuffer | ArrayBufferView): boolean; /** * Copies the specified number of elements from data into index buffer. Optimized for * performance from both typed array as well as array. * * @param {Uint8Array|Uint16Array|Uint32Array|number[]} data - The data to write. * @param {number} count - The number of indices to write. * @ignore */ writeData(data: Uint8Array | Uint16Array | Uint32Array | number[], count: number): void; /** * Copies index data from index buffer into provided data array. * * @param {Uint8Array|Uint16Array|Uint32Array|number[]} data - The data array to write to. * @returns {number} The number of indices read. * @ignore */ readData(data: Uint8Array | Uint16Array | Uint32Array | number[]): number; } /** * @import { GraphicsDevice } from './graphics-device.js' */ /** * A set of 1x1 textures the engine binds in place of a texture it was not given, such as a * shader's texture slot with no value at all. * * These are owned by the {@link GraphicsDevice} and created together with it, as they cannot be * created on demand: creating a texture uploads its data, and on WebGPU an upload submits the * scheduled command buffers, which finishes the command encoder an in-flight render pass belongs * to. * * @ignore */ declare class BuiltInTextures { /** * @param {GraphicsDevice} device - The graphics device. */ constructor(device: GraphicsDevice); /** * An opaque white texture. * * @type {Texture} */ white: Texture; /** * An opaque pink texture, used where the missing texture is a mistake and so is better off * obvious on the screen. * * @type {Texture} */ pink: Texture; destroy(): void; } /** * BlendState is a descriptor that defines how output of fragment shader is written and blended * into render target. A blend state can be set on a material using {@link Material#blendState}, * or in some cases on the graphics device using {@link GraphicsDevice#setBlendState}. * * For the best performance, do not modify blend state after it has been created, but create * multiple blend states and assign them to the material or graphics device as needed. * * By default the blend state applies to all color attachments of the render target. When multiple * color attachments are used, individual attachments can be given an independent blend state using * {@link BlendState#setAttachment}. This requires {@link GraphicsDevice#supportsIndependentBlending} - * on devices without support, the state of the attachment 0 is used for all attachments. * * @category Graphics */ declare class BlendState { /** * A blend state that has blending disabled and writes to all color channels. * * @type {BlendState} * @readonly */ static readonly NOBLEND: BlendState; /** * @deprecated Use BlendState.NOBLEND instead. * @ignore */ static get DEFAULT(): BlendState; /** * A blend state that does not write to color channels. * * @type {BlendState} * @readonly */ static readonly NOWRITE: BlendState; /** * A blend state that does simple translucency using alpha channel. * * @type {BlendState} * @readonly */ static readonly ALPHABLEND: BlendState; /** * A blend state that does simple additive blending. * * @type {BlendState} * @readonly */ static readonly ADDBLEND: BlendState; /** * Create a new BlendState instance. * * All factor parameters can take the following values: * * - {@link BLENDMODE_ZERO} * - {@link BLENDMODE_ONE} * - {@link BLENDMODE_SRC_COLOR} * - {@link BLENDMODE_ONE_MINUS_SRC_COLOR} * - {@link BLENDMODE_DST_COLOR} * - {@link BLENDMODE_ONE_MINUS_DST_COLOR} * - {@link BLENDMODE_SRC_ALPHA} * - {@link BLENDMODE_SRC_ALPHA_SATURATE} * - {@link BLENDMODE_ONE_MINUS_SRC_ALPHA} * - {@link BLENDMODE_DST_ALPHA} * - {@link BLENDMODE_ONE_MINUS_DST_ALPHA} * - {@link BLENDMODE_CONSTANT} * - {@link BLENDMODE_ONE_MINUS_CONSTANT} * - {@link BLENDMODE_SRC1_COLOR} * - {@link BLENDMODE_ONE_MINUS_SRC1_COLOR} * - {@link BLENDMODE_SRC1_ALPHA} * - {@link BLENDMODE_ONE_MINUS_SRC1_ALPHA} * * All op parameters can take the following values: * * - {@link BLENDEQUATION_ADD} * - {@link BLENDEQUATION_SUBTRACT} * - {@link BLENDEQUATION_REVERSE_SUBTRACT} * - {@link BLENDEQUATION_MIN} * - {@link BLENDEQUATION_MAX} * * @param {boolean} [blend] - Enables or disables blending. Defaults to false. * @param {number} [colorOp] - Configures color blending operation. Defaults to * {@link BLENDEQUATION_ADD}. * @param {number} [colorSrcFactor] - Configures source color blending factor. Defaults to * {@link BLENDMODE_ONE}. * @param {number} [colorDstFactor] - Configures destination color blending factor. Defaults to * {@link BLENDMODE_ZERO}. * @param {number} [alphaOp] - Configures alpha blending operation. Defaults to * {@link BLENDEQUATION_ADD}. * @param {number} [alphaSrcFactor] - Configures source alpha blending factor. Defaults to * {@link BLENDMODE_ONE}. * @param {number} [alphaDstFactor] - Configures destination alpha blending factor. Defaults to * {@link BLENDMODE_ZERO}. * @param {boolean} [redWrite] - True to enable writing of the red channel and false otherwise. * Defaults to true. * @param {boolean} [greenWrite] - True to enable writing of the green channel and false * otherwise. Defaults to true. * @param {boolean} [blueWrite] - True to enable writing of the blue channel and false otherwise. * Defaults to true. * @param {boolean} [alphaWrite] - True to enable writing of the alpha channel and false * otherwise. Defaults to true. */ constructor(blend?: boolean, colorOp?: number, colorSrcFactor?: number, colorDstFactor?: number, alphaOp?: number, alphaSrcFactor?: number, alphaDstFactor?: number, redWrite?: boolean, greenWrite?: boolean, blueWrite?: boolean, alphaWrite?: boolean); /** * Bit field representing the blend state for attachment 0. Bit 31 additionally flags the * presence of per-attachment overrides. * * @private */ private attachment0; /** * Per-attachment blend states, indexed directly by the attachment index. Slot 0 is unused and * always zero, as attachment 0 is stored in `attachment0`. A slot value of zero means the * attachment follows attachment 0. Allocated lazily, only when an override is set. * * @type {Int32Array|null} * @private */ private _attachments; /** * Interned key of a state with per-attachment overrides. Unused by states without overrides, * which use attachment0 as their key directly. * * @private */ private _key; /** * True when `_key` needs re-evaluating. Set by all attachment 0 mutations, and only relevant * when per-attachment overrides are present. * * @private */ private _keyDirty; /** * Sets whether blending is enabled. * * @type {boolean} */ set blend(value: boolean); /** * Gets whether blending is enabled. * * @type {boolean} */ get blend(): boolean; setColorBlend(op: any, srcFactor: any, dstFactor: any): void; setAlphaBlend(op: any, srcFactor: any, dstFactor: any): void; setColorWrite(redWrite: any, greenWrite: any, blueWrite: any, alphaWrite: any): void; set redWrite(value: boolean); get redWrite(): boolean; set greenWrite(value: boolean); get greenWrite(): boolean; set blueWrite(value: boolean); get blueWrite(): boolean; set alphaWrite(value: boolean); get alphaWrite(): boolean; get colorOp(): number; get colorSrcFactor(): number; get colorDstFactor(): number; get alphaOp(): number; get alphaSrcFactor(): number; get alphaDstFactor(): number; get allWrite(): number; /** * Gets whether any color attachment has been given an independent blend state using * {@link BlendState#setAttachment}. * * @type {boolean} */ get hasAttachmentOverrides(): boolean; /** * Assigns an independent blend state to the specified color attachment. The blend state of the * supplied source is copied, and so subsequent changes to either the source or to attachment 0 do * not affect it. An attachment which has not been assigned an independent state instead follows * attachment 0. * * Note that this requires {@link GraphicsDevice#supportsIndependentBlending} - on devices * without support, the state of attachment 0 is used for all attachments. * * @param {number} index - The index of the color attachment, in 1 to 7 range. Attachment 0 is * configured using the other functions and properties of this class. * @param {BlendState|null} src - The blend state to copy from, or null to make the attachment * follow attachment 0 again. * @example * // attachment 1 keeps the blending of attachment 0, but does not write any channels * const state = material.blendState.clone(); * const noWrite = state.clone(); * noWrite.setColorWrite(false, false, false, false); * state.setAttachment(1, noWrite); */ setAttachment(index: number, src: BlendState | null): void; /** * Removes the independent blend state of the specified color attachment, making it follow * attachment 0 again. * * @param {number} index - The index of the color attachment, in 1 to 7 range. */ clearAttachment(index: number): void; /** * Stores the blend state of the specified color attachment in the supplied blend state. When * the attachment does not have an independent blend state, the state of attachment 0 is stored. * * @param {number} index - The index of the color attachment, in 0 to 7 range. * @param {BlendState} dst - The blend state to store the result in. This avoids allocations, as * a single instance can be reused. * @returns {BlendState} The supplied dst, for chaining. */ getAttachment(index: number, dst: BlendState): BlendState; /** * Refreshes the overrides flag and the interned key after the per-attachment states have changed. * * @private */ private _attachmentsUpdated; /** * Assigns a unique key to the combination of attachment 0 and the per-attachment states. * * @private */ private _evalKey; /** * True if any blend factor uses the secondary fragment output. * * @type {boolean} * @ignore */ get usesDualSourceBlending(): boolean; /** * Copies the contents of a source blend state to this blend state. * * @param {BlendState} rhs - A blend state to copy from. * @returns {BlendState} Self for chaining. */ copy(rhs: BlendState): BlendState; /** * Returns an identical copy of the specified blend state. * * @returns {this} The result of the cloning. */ clone(): this; get key(): number; /** * Reports whether two BlendStates are equal. * * @param {BlendState} rhs - The blend state to compare to. * @returns {boolean} True if the blend states are equal and false otherwise. */ equals(rhs: BlendState): boolean; } /** * DepthState is a descriptor that defines how the depth value of the fragment is used by the * rendering pipeline. A depth state can be set on a material using {@link Material#depthState}, * or in some cases on the graphics device using {@link GraphicsDevice#setDepthState}. * * For the best performance, do not modify depth state after it has been created, but create * multiple depth states and assign them to the material or graphics device as needed. * * @category Graphics */ declare class DepthState { /** * A default depth state that has the depth testing function set to {@link FUNC_LESSEQUAL} and * depth writes enabled. * * @type {DepthState} * @readonly */ static readonly DEFAULT: DepthState; /** * A depth state that always passes the fragment but does not write depth to the depth buffer. * * @type {DepthState} * @readonly */ static readonly NODEPTH: DepthState; /** * A depth state that always passes the fragment and writes depth to the depth buffer. * * @type {DepthState} * @readonly */ static readonly WRITEDEPTH: DepthState; /** * Create a new Depth State instance. * * @param {number} func - Controls how the depth of the fragment is compared against the * current depth contained in the depth buffer. See {@link DepthState#func} for details. * Defaults to {@link FUNC_LESSEQUAL}. * @param {boolean} write - If true, depth values are written to the depth buffer of the * currently active render target. Defaults to true. */ constructor(func?: number, write?: boolean); /** * Bit field representing the depth state. * * @private */ private data; _depthBias: number; _depthBiasSlope: number; /** * A unique number representing the depth state. You can use this number to quickly compare * two depth states for equality. The key is always maintained valid without a dirty flag, * to avoid condition check at runtime, considering these change rarely. */ key: number; /** * Sets the depth testing function. Controls how the depth of the fragment is compared against * the current depth contained in the depth buffer. Can be: * * - {@link FUNC_NEVER}: don't draw * - {@link FUNC_LESS}: draw if new depth < depth buffer * - {@link FUNC_EQUAL}: draw if new depth == depth buffer * - {@link FUNC_LESSEQUAL}: draw if new depth <= depth buffer * - {@link FUNC_GREATER}: draw if new depth > depth buffer * - {@link FUNC_NOTEQUAL}: draw if new depth != depth buffer * - {@link FUNC_GREATEREQUAL}: draw if new depth >= depth buffer * - {@link FUNC_ALWAYS}: always draw * * @type {number} */ set func(value: number); /** * Gets the depth testing function. * * @type {number} */ get func(): number; /** * Sets whether depth writing is performed. If true, shader write a depth value to the depth * buffer of the currently active render target. If false, no depth value is written. * * @type {boolean} */ set write(value: boolean); /** * Gets whether depth writing is performed. * * @type {boolean} */ get write(): boolean; /** * Sets whether depth testing is performed. If true, a shader fragment is only written to the * current render target if it passes the depth test. If false, it is written regardless of * what is in the depth buffer. Disabling the test sets {@link DepthState#func} to * {@link FUNC_ALWAYS}, and enabling it sets {@link FUNC_LESSEQUAL} - unless the test is * already enabled, in which case the current depth testing function is kept. Depth writes are * controlled independently by {@link DepthState#write}, so a fragment still writes its depth * when the test is disabled. Defaults to true. * * @type {boolean} */ set test(value: boolean); /** * Gets whether depth testing is performed. * * @type {boolean} */ get test(): boolean; /** * Sets the constant depth bias added to each fragment's depth. Useful for decals to prevent * z-fighting. Typically a small negative value (-0.1) is used to render the mesh slightly * closer to the camera. Defaults to 0. * * @type {number} */ set depthBias(value: number); /** * Gets the constant depth bias added to each fragment's depth. * * @type {number} */ get depthBias(): number; /** * Sets the depth bias that scales with the fragment's slope. Defaults to 0. * * @type {number} */ set depthBiasSlope(value: number); /** * Gets the depth bias that scales with the fragment's slope. * * @type {number} */ get depthBiasSlope(): number; /** * Copies the contents of a source depth state to this depth state. * * @param {DepthState} rhs - A depth state to copy from. * @returns {DepthState} Self for chaining. */ copy(rhs: DepthState): DepthState; /** * Returns an identical copy of the specified depth state. * * @returns {this} The result of the cloning. */ clone(): this; updateKey(): void; /** * Reports whether two DepthStates are equal. * * @param {DepthState} rhs - The depth state to compare to. * @returns {boolean} True if the depth states are equal and false otherwise. */ equals(rhs: DepthState): boolean; } /** * Holds stencil test settings. * * @category Graphics */ declare class StencilParameters { /** * A default stencil state. * * @type {StencilParameters} * @readonly */ static readonly DEFAULT: StencilParameters; /** * Create a new StencilParameters instance. * * @param {object} [options] - Options object to configure the stencil parameters. */ constructor(options?: object); /** * @type {number} * @private */ private _func; /** * @type {number} * @private */ private _ref; /** * @type {number} * @private */ private _fail; /** * @type {number} * @private */ private _zfail; /** * @type {number} * @private */ private _zpass; /** * @type {number} * @private */ private _readMask; /** * @type {number} * @private */ private _writeMask; /** @private */ private _dirty; /** * @type {number} * @private */ private _key; /** * Sets the comparison function that decides if the pixel should be written, based on the * current stencil buffer value, reference value, and mask value. Can be: * * - {@link FUNC_NEVER}: never pass * - {@link FUNC_LESS}: pass if (ref & mask) < (stencil & mask) * - {@link FUNC_EQUAL}: pass if (ref & mask) == (stencil & mask) * - {@link FUNC_LESSEQUAL}: pass if (ref & mask) <= (stencil & mask) * - {@link FUNC_GREATER}: pass if (ref & mask) > (stencil & mask) * - {@link FUNC_NOTEQUAL}: pass if (ref & mask) != (stencil & mask) * - {@link FUNC_GREATEREQUAL}: pass if (ref & mask) >= (stencil & mask) * - {@link FUNC_ALWAYS}: always pass * * @type {number} */ set func(value: number); /** * Sets the comparison function that decides if the pixel should be written. * * @type {number} */ get func(): number; /** * Sets the stencil test reference value used in comparisons. * * @type {number} */ set ref(value: number); /** * Gets the stencil test reference value used in comparisons. * * @type {number} */ get ref(): number; /** * Sets the operation to perform if stencil test is failed. Can be: * * - {@link STENCILOP_KEEP}: don't change the stencil buffer value * - {@link STENCILOP_ZERO}: set value to zero * - {@link STENCILOP_REPLACE}: replace value with the reference value. * - {@link STENCILOP_INCREMENT}: increment the value * - {@link STENCILOP_INCREMENTWRAP}: increment the value, but wrap it to zero when it's larger * than a maximum representable value * - {@link STENCILOP_DECREMENT}: decrement the value * - {@link STENCILOP_DECREMENTWRAP}: decrement the value, but wrap it to a maximum * representable value, if the current value is 0 * - {@link STENCILOP_INVERT}: invert the value bitwise * * @type {number} */ set fail(value: number); /** * Gets the operation to perform if stencil test is failed. * * @type {number} */ get fail(): number; /** * Sets the operation to perform if depth test is failed. Accepts the same values as `fail`. * * @type {number} */ set zfail(value: number); /** * Gets the operation to perform if depth test is failed. * * @type {number} */ get zfail(): number; /** * Sets the operation to perform if both stencil and depth test are passed. Accepts the same * values as `fail`. * * @type {number} */ set zpass(value: number); /** * Gets the operation to perform if both stencil and depth test are passed. * * @type {number} */ get zpass(): number; /** * Sets the mask applied to stencil buffer value and reference value before comparison. * * @type {number} */ set readMask(value: number); /** * Gets the mask applied to stencil buffer value and reference value before comparison. * * @type {number} */ get readMask(): number; /** * Sets the bit mask applied to the stencil value when written. * * @type {number} */ set writeMask(value: number); /** * Gets the bit mask applied to the stencil value when written. * * @type {number} */ get writeMask(): number; _evalKey(): void; get key(): number; /** * Copies the contents of a source stencil parameters to this stencil parameters. * * @param {StencilParameters} rhs - A stencil parameters to copy from. * @returns {StencilParameters} Self for chaining. */ copy(rhs: StencilParameters): StencilParameters; /** * Clone the stencil parameters. * * @returns {StencilParameters} A cloned StencilParameters object. */ clone(): StencilParameters; } /** * A uniform buffer represents a GPU memory buffer storing the uniforms. * * @ignore */ declare class UniformBuffer { /** * Create a new UniformBuffer instance. * * @param {GraphicsDevice} graphicsDevice - The graphics device used to manage this uniform * buffer. * @param {UniformBufferFormat} format - Format of the uniform buffer. * @param {boolean} [persistent] - Whether the buffer is persistent. Defaults to true. */ constructor(graphicsDevice: GraphicsDevice, format: UniformBufferFormat, persistent?: boolean); device: GraphicsDevice; /** @type {boolean} */ persistent: boolean; /** @type {DynamicBufferAllocation} */ allocation: DynamicBufferAllocation; /** @type {Float32Array} */ storageFloat32: Float32Array; /** @type {Int32Array} */ storageInt32: Int32Array; /** @type {Uint32Array} */ storageUint32: Uint32Array; /** * Where this uniform buffer's data starts in the storage views, in 4 byte elements. Zero for a * persistent buffer, which owns its storage, and the offset of the allocation for a * non-persistent one, which borrows the storage of a dynamic buffer. * * @type {number} */ storageOffset: number; format: UniformBufferFormat; impl: any; /** * Frees resources associated with this uniform buffer. */ destroy(): void; get offset(): number; /** * Assign the storage a persistent uniform buffer owns. This runs once per buffer, unlike * {@link UniformBuffer#assignDynamicStorage}. * * @param {Int32Array} storage - The storage to assign to this uniform buffer. */ assignStorage(storage: Int32Array): void; /** * Borrow the storage views of the dynamic buffer this uniform buffer was allocated from, and * remember where in them its own data starts. The views span the whole dynamic buffer, so this * creates none of its own - it runs for every draw that updates a non-persistent buffer. * * @param {DynamicBuffer} dynamicBuffer - The buffer the allocation came from. * @param {number} storageOffset - Where the allocation starts in the views, in 4 byte elements. */ assignDynamicStorage(dynamicBuffer: DynamicBuffer, storageOffset: number): void; /** * Called when the rendering context was lost. It releases all context related resources. */ loseContext(): void; /** * Called when the rendering context is restored. Recreates the GPU buffer and re-uploads the * data from the persistent CPU storage. Only persistent uniform buffers are tracked for context * loss; non-persistent ones are re-allocated from the dynamic buffers on their next update. */ restoreContext(): void; /** * Assign a value to the uniform specified by its format. This is the fast version of assigning * a value to a uniform, avoiding any lookups. * * @param {UniformFormat} uniformFormat - The format of the uniform. * @param {any} value - The value to assign to the uniform. */ setUniform(uniformFormat: UniformFormat, value: any): void; /** * Assign a value to the uniform specified by name. * * @param {string} name - The name of the uniform. * @param {any} value - The value to assign to the uniform. */ set(name: string, value: any): void; startUpdate(dynamicBindGroup: any): void; endUpdate(): void; /** * Uploads the storage of a persistent uniform buffer to the GPU. Use this after writing to * the storage directly, instead of {@link UniformBuffer#update} which reads the values from * the scope. * * @ignore */ upload(): void; /** * @param {DynamicBindGroup} [dynamicBindGroup] - The function fills in the info about the * dynamic bind group for this frame, which uses this uniform buffer. Only used if the uniform * buffer is non-persistent. This allows the uniform buffer to be used without having to create * a bind group for it. Note that the bind group can only contains this single uniform buffer, * and no other resources. */ update(dynamicBindGroup?: DynamicBindGroup): void; } /** * A bind group represents a collection of {@link UniformBuffer}, {@link Texture} and * {@link StorageBuffer} instanced, which can be bind on a GPU for rendering. * * Call {@link BindGroup#destroy} when no longer needed. On WebGPU, the graphics device retains * bind groups for device recovery until they are explicitly destroyed. * * @ignore */ declare class BindGroup { /** * Create a new Bind Group. * * @param {GraphicsDevice} graphicsDevice - The graphics device used to manage this uniform buffer. * @param {BindGroupFormat} format - Format of the bind group. * @param {UniformBuffer} [defaultUniformBuffer] - The default uniform buffer. Typically a bind * group only has a single uniform buffer, and this allows easier access. */ constructor(graphicsDevice: GraphicsDevice, format: BindGroupFormat, defaultUniformBuffer?: UniformBuffer); /** * A render version the bind group was last updated on. * * @private */ private renderVersionUpdated; /** @type {UniformBuffer[]} */ uniformBuffers: UniformBuffer[]; /** * The offset of each uniform buffer of the format in the buffer where its data starts. A typed * array of one entry per uniform buffer slot, which the WebGPU device passes to setBindGroup * without a per-call conversion, and which holds exactly the number of dynamic offsets the bind * group layout requires. * * @type {Uint32Array} */ uniformBufferOffsets: Uint32Array; /** * For each uniform buffer slot, the dynamic GPU buffer a non-persistent uniform buffer was * last built against. Used to detect when such a buffer is re-allocated into a different * dynamic buffer (which requires the bind group to be rebuilt). * * @type {DynamicBuffer[]} * @private */ private _uniformBufferContainers; /** * For each texture / storage-texture slot, the GPU implementation object the slot was last * built against. A texture's `impl` is replaced when its GPU resource is recreated (e.g. * {@link Texture#resize}), which can happen mid-render in the same render version the bind * group was last built — so the {@link renderVersionDirty} check alone misses it and the bind * group keeps a view of the (now destroyed) old GPU texture. Tracking impl identity forces a * rebuild whenever the underlying GPU resource is recreated. * * @type {object[]} * @private */ private _textureImpls; /** * @type {object[]} * @private */ private _storageTextureImpls; id: number; device: GraphicsDevice; format: BindGroupFormat; dirty: boolean; impl: any; /** @type {(Texture|TextureView)[]} */ textures: (Texture | TextureView)[]; /** @type {(Texture|TextureView)[]} */ storageTextures: (Texture | TextureView)[]; storageBuffers: any[]; /** @type {UniformBuffer} */ defaultUniformBuffer: UniformBuffer; /** * Frees resources associated with this bind group. */ destroy(): void; /** * Assign a uniform buffer to a slot. * * @param {string} name - The name of the uniform buffer slot * @param {UniformBuffer} uniformBuffer - The Uniform buffer to assign to the slot. */ setUniformBuffer(name: string, uniformBuffer: UniformBuffer): void; /** * Assign a storage buffer to a slot. * * @param {string} name - The name of the storage buffer slot. * @param {StorageBuffer} storageBuffer - The storage buffer to assign to the slot. */ setStorageBuffer(name: string, storageBuffer: StorageBuffer): void; /** * Assign a storage buffer to a slot, given its index in the format's storage buffers. * * @param {number} index - The index of the storage buffer slot. * @param {StorageBuffer} storageBuffer - The storage buffer to assign to the slot. * @private */ private setStorageBufferAt; /** * Assign a texture to a named slot. * * @param {string} name - The name of the texture slot. * @param {Texture|TextureView} value - Texture or TextureView to assign to the slot. */ setTexture(name: string, value: Texture | TextureView): void; /** * Assign a texture to a slot, given its index in the format's textures. This is the form the * update uses, as it walks the slots in order and so knows the index without looking it up, * and the form an owner of the bind group uses when it tracks the slots of its own resources. * * @param {number} index - The index of the texture slot. * @param {Texture|TextureView} value - Texture or TextureView to assign to the slot. * @ignore */ setTextureAt(index: number, value: Texture | TextureView): void; /** * Assign a storage texture to a named slot. * * @param {string} name - The name of the texture slot. * @param {Texture|TextureView} value - Texture or TextureView to assign to the slot. */ setStorageTexture(name: string, value: Texture | TextureView): void; /** * Assign a storage texture to a slot, given its index in the format's storage textures. * * @param {number} index - The index of the storage texture slot. * @param {Texture|TextureView} value - Texture or TextureView to assign to the slot. * @private */ private setStorageTextureAt; /** * Updates the uniform buffers in this bind group. */ updateUniformBuffers(): void; /** * Applies any changes made to the bind group's properties, taking the value of each texture, * storage texture and storage buffer slot from the scope. Note that the content of used * uniform buffers needs to be updated before calling this method. */ update(): void; /** * Applies any changes made to the bind group's properties, for a bind group whose owner assigns * its slots instead of them being taken from the scope. The owner is expected to have assigned * every slot of the format; the resources they hold are re-checked here, as they can change * without the owner re-assigning them. Note that the content of used uniform buffers needs to * be updated before calling this method. */ commit(): void; /** * Assigns every slot of the format the value the scope currently holds for it. * * @private */ private _assignFromScope; /** * The texture to bind for a slot with no value, which is an error - a substitute keeps the * rendering going instead of failing on an unset binding, and reports the mistake. * * @param {BindTextureFormat} textureFormat - The format of the slot. * @returns {Texture} The texture to bind. * @private */ private _substituteTexture; /** * Re-checks the resources the slots already hold. A texture's properties can change, and its * GPU resource can be recreated (by a resize, for example), without the slot being assigned * again - which the assignment path detects as it goes, and this path has to look for. * * @private */ private _revalidate; /** * Refreshes the offsets of the uniform buffers, and rebuilds the GPU bind group if anything * about the bind group has changed. * * @private */ private _finalize; } /** * Data structure to hold a bind group and its offsets. This is used by {@link UniformBuffer#update} * to return a dynamic bind group and offset for the uniform buffer. * * @ignore */ declare class DynamicBindGroup { bindGroup: any; /** * The dynamic offset of the uniform buffer. A typed array, which the WebGPU device passes to * setBindGroup without a per-call conversion. * * @type {Uint32Array} */ offsets: Uint32Array; } /** * @import { GraphicsDevice } from './graphics-device.js' */ /** * A base class representing a single per platform buffer. * * @ignore */ declare class DynamicBuffer { constructor(device: any); /** @type {GraphicsDevice} */ device: GraphicsDevice; /** * A cache of bind groups for each uniform buffer size, which is used to avoid creating a new * bind group for each uniform buffer. * * @type {Map} */ bindGroupCache: Map; /** * Int32 access over the CPU accessible memory of the whole buffer, or null when the buffer has * none. The views span the whole buffer and an allocation is addressed by an offset into them, * so handing out an allocation creates no views of its own - which matters, as that happens for * every draw. * * @type {Int32Array|null} */ storageInt32: Int32Array | null; /** * Uint32 access over the whole buffer. See {@link DynamicBuffer#storageInt32}. * * @type {Uint32Array|null} */ storageUint32: Uint32Array | null; /** * Float32 access over the whole buffer. See {@link DynamicBuffer#storageInt32}. * * @type {Float32Array|null} */ storageFloat32: Float32Array | null; bindGroupFormat: BindGroupFormat; /** * Create the storage views over the CPU accessible memory of the whole buffer. * * @param {ArrayBuffer|null} arrayBuffer - The memory of the whole buffer, or null to release * the views when the memory is no longer accessible. */ setStorage(arrayBuffer: ArrayBuffer | null): void; /** * Upload the buffer's data to the GPU. A no-op on backends (such as WebGPU) that copy the data * to the GPU separately; WebGL overrides this to eagerly upload, as it has no buffer mapping and * executes draws immediately. */ upload(): void; getBindGroup(ub: any): BindGroup; } /** * The DynamicBuffers class provides a dynamic memory allocation system for uniform buffer data, * particularly for non-persistent uniform buffers. This class utilizes a bump allocator to * efficiently allocate aligned memory space from a set of large buffers managed internally. To * utilize this system, the user writes data to CPU-accessible staging buffers. When submitting * command buffers that require these buffers, the system automatically uploads the data to the GPU * buffers. This approach ensures efficient memory management and smooth data transfer between the * CPU and GPU. * * @ignore */ declare class DynamicBuffers { /** * Create the system of dynamic buffers. * * @param {GraphicsDevice} device - The graphics device. * @param {number} bufferSize - The size of the underlying large buffers. * @param {number} bufferAlignment - Alignment of each allocation. */ constructor(device: GraphicsDevice, bufferSize: number, bufferAlignment: number); /** * Allocation size of the underlying buffers. * * @type {number} */ bufferSize: number; /** * Internally allocated gpu buffers. * * @type {DynamicBuffer[]} */ gpuBuffers: DynamicBuffer[]; /** * Internally allocated staging buffers (CPU writable) * * @type {DynamicBuffer[]} */ stagingBuffers: DynamicBuffer[]; /** * @type {UsedBuffer[]} */ usedBuffers: UsedBuffer[]; /** * @type {UsedBuffer|null} */ activeBuffer: UsedBuffer | null; device: GraphicsDevice; bufferAlignment: number; /** * Number of backing GPU uniform buffers, including free and in-flight buffers. * Staging buffers and individual suballocations are excluded. * * @type {number} */ get bufferCount(): number; /** * Destroy the system of dynamic buffers. */ destroy(): void; /** * Allocate an aligned space of the given size from a dynamic buffer. * * @param {DynamicBufferAllocation} allocation - The allocation info to fill. * @param {number} size - The size of the allocation. */ alloc(allocation: DynamicBufferAllocation, size: number): void; scheduleSubmit(): void; submit(): void; } /** * A container for storing the return values of an allocation function. * * @ignore */ declare class DynamicBufferAllocation { /** * The buffer the allocation is inside, whose storage views give CPU access to the data. * * @type {DynamicBuffer} */ storageBuffer: DynamicBuffer; /** * Where the allocation starts in the storage views of the buffer, in 4 byte elements. * * @type {number} */ storageOffset: number; /** * The gpu buffer this allocation will be copied to. * * @type {DynamicBuffer} */ gpuBuffer: DynamicBuffer; /** * Offset in the gpuBuffer where the data will be copied to. * * @type {number} */ offset: number; } /** * @import { DynamicBuffer } from './dynamic-buffer.js' * @import { GraphicsDevice } from './graphics-device.js' */ /** * A container for storing the used areas of a pair of staging and gpu buffers. * * @ignore */ declare class UsedBuffer { /** @type {DynamicBuffer} */ gpuBuffer: DynamicBuffer; /** @type {DynamicBuffer} */ stagingBuffer: DynamicBuffer; /** * The beginning position of the used area that needs to be copied from staging to the GPU * buffer. * * @type {number} */ offset: number; /** * Used byte size of the buffer, from the offset. * * @type {number} */ size: number; } /** * Base class of a simple GPU profiler. * * @ignore */ declare class GpuProfiler { /** * Profiling slots allocated for the current frame, storing the names of the slots. * * @type {string[]} * @ignore */ frameAllocations: string[]; /** * Map of past frame allocations, indexed by renderVersion * * @type {Map} * @ignore */ pastFrameAllocations: Map; /** * True if enabled in the current frame. * * @private */ private _enabled; /** * The enable request for the next frame. * * @private */ private _enableRequest; /** * The time it took to render the last frame on GPU, or 0 if the profiler is not enabled. * * @private */ private _frameTime; /** * Whether a valid frame timing has arrived since profiling was enabled or reset. * * @private */ private _frameTimeValid; /** * Per-pass timing data, with accumulated timings for passes with the same name. * * @type {Map} * @private */ private _passTimings; /** * Cache for parsed pass names to avoid repeated string operations. * * @type {Map} * @private */ private _nameCache; /** * The maximum number of slots that can be allocated during the frame. */ maxCount: number; loseContext(): void; /** * Invalidate timings and discard pending reports so asynchronous results from an earlier * profiling session cannot become the latest sample after a reset. * * @ignore */ invalidateTimings(): void; /** * True to enable the profiler. * * @type {boolean} */ set enabled(value: boolean); get enabled(): boolean; /** * The latest valid GPU frame duration, or undefined when no timing is available. * * @type {number|undefined} * @ignore */ get frameTime(): number | undefined; /** * Get the per-pass timing data. * * @type {Map} * @ignore */ get passTimings(): Map; processEnableRequest(): void; request(renderVersion: any): void; /** * Parse a render pass name to a simplified form for stats. * Uses a cache to avoid repeated string operations. * * @param {string} name - The original pass name (e.g., "RenderPassCompose"). * @returns {string} The parsed name (e.g., "compose"). * @private */ private _parsePassName; report(renderVersion: any, timings: any, frameTime: any): void; /** * Allocate a slot for GPU timing during the frame. This slot is valid only for the current * frame. This allows multiple timers to be used during the frame, each with a unique name. * * @param {string} name - The name of the slot. * @returns {number} The assigned slot index, or -1 if the slot count exceeds the maximum number * of slots. * * @ignore */ getSlot(name: string): number; /** * Number of slots allocated during the frame. * * @ignore */ get slotCount(): number; } /** * An RGBA color. * * Each color component is a floating point value in the range 0 to 1. The {@link r} (red), * {@link g} (green) and {@link b} (blue) components define a color in RGB color space. The * {@link a} (alpha) component defines transparency. An alpha of 1 is fully opaque. An alpha of 0 is * fully transparent. * * A Color stores the values it is given and does not track whether they are in linear or gamma * (sRGB) space. Convert explicitly with {@link linear} and {@link gamma} when a value crosses that * boundary. {@link fromString} and {@link toString} exchange colors with the `#RRGGBB` and * `#RRGGBBAA` notation used by CSS, and {@link lerp} blends two colors. * * Methods modify the color they are called on and return it for chaining. Use {@link clone} for an * independent copy and {@link copy} to overwrite. The named constants such as {@link WHITE} and * {@link RED} are frozen shared instances, so copy one before modifying it. * * @example * // Set a material color from a CSS hex string * material.diffuse.fromString('#ff8800'); * material.update(); * @example * // Fade between two colors without allocating * const tint = new Color(); * tint.lerp(Color.RED, Color.BLUE, t); * @category Math */ declare class Color { /** * A constant color set to black [0, 0, 0, 1]. * * @type {Color} * @readonly */ static readonly BLACK: Color; /** * A constant color set to blue [0, 0, 1, 1]. * * @type {Color} * @readonly */ static readonly BLUE: Color; /** * A constant color set to cyan [0, 1, 1, 1]. * * @type {Color} * @readonly */ static readonly CYAN: Color; /** * A constant color set to gray [0.5, 0.5, 0.5, 1]. * * @type {Color} * @readonly */ static readonly GRAY: Color; /** * A constant color set to green [0, 1, 0, 1]. * * @type {Color} * @readonly */ static readonly GREEN: Color; /** * A constant color set to magenta [1, 0, 1, 1]. * * @type {Color} * @readonly */ static readonly MAGENTA: Color; /** * A constant color set to red [1, 0, 0, 1]. * * @type {Color} * @readonly */ static readonly RED: Color; /** * A constant color set to white [1, 1, 1, 1]. * * @type {Color} * @readonly */ static readonly WHITE: Color; /** * A constant color set to yellow [1, 1, 0, 1]. * * @type {Color} * @readonly */ static readonly YELLOW: Color; /** * Creates a new Color instance. * * @overload * @param {number} [r] - The r value. Defaults to 0. * @param {number} [g] - The g value. Defaults to 0. * @param {number} [b] - The b value. Defaults to 0. * @param {number} [a] - The a value. Defaults to 1. * @example * const c1 = new Color(); // defaults to 0, 0, 0, 1 * const c2 = new Color(0.1, 0.2, 0.3, 0.4); */ constructor(r?: number, g?: number, b?: number, a?: number); /** * Creates a new Color instance. * * @overload * @param {number[]} arr - The array to set the color values from. * @example * const c = new Color([0.1, 0.2, 0.3, 0.4]); */ constructor(arr: number[]); /** * The red component of the color. * * @type {number} */ r: number; /** * The green component of the color. * * @type {number} */ g: number; /** * The blue component of the color. * * @type {number} */ b: number; /** * The alpha component of the color. * * @type {number} */ a: number; /** * Returns a clone of the specified color. * * @returns {this} A duplicate color object. * @example * const c = new Color(1, 0, 0, 1); * const cClone = c.clone(); * // cClone is [1, 0, 0, 1] */ clone(): this; /** * Copies the contents of a source color to a destination color. * * @param {Color} rhs - A color to copy to the specified color. * @returns {Color} Self for chaining. * @example * const src = new Color(1, 0, 0, 1); * const dst = new Color(); * * dst.copy(src); * * console.log("The two colors are " + (dst.equals(src) ? "equal" : "different")); */ copy(rhs: Color): Color; /** * Reports whether two colors are equal. * * @param {Color} rhs - The color to compare to the specified color. * @returns {boolean} True if the colors are equal and false otherwise. * @example * const a = new Color(1, 0, 0, 1); * const b = new Color(1, 1, 0, 1); * console.log("The two colors are " + (a.equals(b) ? "equal" : "different")); */ equals(rhs: Color): boolean; /** * Assign values to the color components, including alpha. * * @param {number} r - The value for red (0-1). * @param {number} g - The value for green (0-1). * @param {number} b - The value for blue (0-1). * @param {number} [a] - The value for the alpha (0-1), defaults to 1. * @returns {Color} Self for chaining. * @example * const c = new Color(); * c.set(1, 0, 0, 1); * // c is now red [1, 0, 0, 1] */ set(r: number, g: number, b: number, a?: number): Color; /** * Returns the result of a linear interpolation between two specified colors. * * @param {Color} lhs - The color to interpolate from. * @param {Color} rhs - The color to interpolate to. * @param {number} alpha - The value controlling the point of interpolation. Between 0 and 1, * the linear interpolant will occur on a straight line between lhs and rhs. Outside of this * range, the linear interpolant will occur on a ray extrapolated from this line. * @returns {Color} Self for chaining. * @example * const a = new Color(0, 0, 0); * const b = new Color(1, 1, 0.5); * const r = new Color(); * * r.lerp(a, b, 0); // r is equal to a * r.lerp(a, b, 0.5); // r is 0.5, 0.5, 0.25 * r.lerp(a, b, 1); // r is equal to b */ lerp(lhs: Color, rhs: Color, alpha: number): Color; /** * Converts the color from gamma to linear color space. * * @param {Color} [src] - The color to convert to linear color space. If not set, the operation * is done in place. * @returns {Color} Self for chaining. * @example * const c = new Color(0.5, 0.5, 0.5, 1); * c.linear(); * // c is now approximately [0.218, 0.218, 0.218, 1] */ linear(src?: Color): Color; /** * Converts the color from linear to gamma color space. * * @param {Color} [src] - The color to convert to gamma color space. If not set, the operation is * done in place. * @returns {Color} Self for chaining. * @example * const c = new Color(0.218, 0.218, 0.218, 1); * c.gamma(); * // c is now approximately [0.5, 0.5, 0.5, 1] */ gamma(src?: Color): Color; /** * Multiplies RGB elements of a Color by a number. Note that the alpha value is left unchanged. * * @param {number} scalar - The number to multiply by. * @returns {Color} Self for chaining. * @example * const c = new Color(0.2, 0.4, 0.6, 1); * c.mulScalar(2); * // c is now [0.4, 0.8, 1.2, 1] */ mulScalar(scalar: number): Color; /** * Set the values of the color from a string representation '#11223344' or '#112233'. * * @param {string} hex - A string representation in the format '#RRGGBBAA' or '#RRGGBB'. Where * RR, GG, BB, AA are red, green, blue and alpha values. This is the same format used in * HTML/CSS. * @returns {Color} Self for chaining. * @example * const c = new Color(); * c.fromString('#ff0000'); * // c is now [1, 0, 0, 1] */ fromString(hex: string): Color; /** * Set the values of the color from an array. * * @param {number[]} arr - The array to set the color values from. * @param {number} [offset] - The zero-based index at which to start copying elements from the * array. Default is 0. * @returns {Color} Self for chaining. * @example * const c = new Color(); * c.fromArray([1, 0, 1, 1]); * // c is set to [1, 0, 1, 1] */ fromArray(arr: number[], offset?: number): Color; /** * Converts the color to string form. The format is '#RRGGBBAA', where RR, GG, BB, AA are the * red, green, blue and alpha values. When the alpha value is not included (the default), this * is the same format as used in HTML/CSS. * * @param {boolean} alpha - If true, the output string will include the alpha value. * @param {boolean} [asArray] - If true, the output will be an array of numbers. Defaults to false. * @returns {string} The color in string form. * @example * const c = new Color(1, 1, 1); * // Outputs #ffffff * console.log(c.toString()); */ toString(alpha: boolean, asArray?: boolean): string; /** * @overload * @param {number[]} [arr] - The array to populate with the color's number * components. If not specified, a new array is created. * @param {number} [offset] - The zero-based index at which to start copying elements to the * array. Default is 0. * @returns {number[]} The color as an array. */ toArray(arr?: number[], offset?: number): number[]; /** * @overload * @param {ArrayBufferView} arr - The array to populate with the color's number * components. If not specified, a new array is created. * @param {number} [offset] - The zero-based index at which to start copying elements to the * array. Default is 0. * @returns {ArrayBufferView} The color as an array. */ toArray(arr: ArrayBufferView, offset?: number): ArrayBufferView; } /** * Container holding parameters for multi-draw commands. * * Obtain an instance via {@link MeshInstance#setMultiDraw} and populate it using {@link add} * followed by {@link update}. * * @category Graphics */ declare class DrawCommands { /** * @param {import('./graphics-device.js').GraphicsDevice} device - The graphics device. * @param {number} [indexSizeBytes] - Size of index in bytes for WebGL multi-draw (1, 2 or 4). * @ignore */ constructor(device: GraphicsDevice, indexSizeBytes?: number); /** * Graphics device used to determine backend (WebGPU vs WebGL). * * @type {import('./graphics-device.js').GraphicsDevice} * @ignore */ device: GraphicsDevice; /** * Size of single index in bytes for WebGL multi-draw (1, 2 or 4). 0 represents non-indexed draw. * * @type {number} * @ignore */ indexSizeBytes: number; /** * Maximum number of multi-draw calls the space is allocated for. Ignored for indirect draw commands. * * @private */ private _maxCount; /** * Maximum number of multi-draw calls the space is allocated for. * * @type {number} */ get maxCount(): number; /** * Platform-specific implementation. * * @type {any} * @ignore */ impl: any; /** * Number of draw calls to perform. * * @private */ private _count; /** * Number of draw calls to perform. * * @type {number} */ get count(): number; /** * Slot index of the first indirect draw call. Ignored for multi-draw commands. * * @ignore */ slotIndex: number; /** * The last {@link GraphicsDevice#drawCommandsVersion} at which these commands are still valid. * Indirect commands are frame-scoped, as their slots are recycled each frame, so * {@link MeshInstance#setIndirect} stamps this with the current version on every call. * Multi-draw commands persist across frames and keep the default, which they can only do * because {@link multiDraw} keeps the two kinds from sharing an instance. * * @ignore */ validUntilVersion: number; /** * Whether these are multi-draw commands ({@link MeshInstance#setMultiDraw}) rather than * indirect ones ({@link MeshInstance#setIndirect}). The two are not interchangeable - they * draw from different backing storage - so a mesh instance releases a cached set of the wrong * kind instead of reusing it. * * @ignore */ multiDraw: boolean; /** @private */ private _primitiveCount; /** @private */ private _primitiveType; /** @private */ private _primitiveInstanced; /** @ignore */ destroy(): void; /** * Allocates persistent storage for the draw commands. * * @param {number} maxCount - Maximum number of draw calls to allocate storage for. * @ignore */ allocate(maxCount: number): void; /** * Writes one draw command into the allocated storage. * * @param {number} i - Draw index to update. * @param {number} indexOrVertexCount - Number of indices or vertices to draw. * @param {number} instanceCount - Number of instances to draw (use 1 if not instanced). * @param {number} firstIndexOrVertex - Starting index (in indices, not bytes) or starting vertex. * @param {number} [baseVertex] - Signed base vertex (WebGPU only). Defaults to 0. * @param {number} [firstInstance] - First instance (WebGPU only). Defaults to 0. */ add(i: number, indexOrVertexCount: number, instanceCount: number, firstIndexOrVertex: number, baseVertex?: number, firstInstance?: number): void; /** * Finalize and set draw count after all commands have been added. * * @param {number} count - Number of draws to execute. */ update(count: number): void; /** * Count primitives using the topology at submission time, which is not known when commands * are populated. Cache the result across passes and frames until update is called again. * * @param {number} type - Primitive topology. * @param {boolean} [instanced] - Whether to apply per-command instance counts. Defaults to true. * @returns {number} Primitive count, or zero for GPU-authored indirect commands. * @ignore */ getPrimitiveCount(type: number, instanced?: boolean): number; } /** * A representation of a compute shader with the associated resources, that can be executed on the * GPU. Only supported on WebGPU platform. * * Call {@link Compute#destroy} when no longer needed. The graphics device retains compute * instances for device recovery until they are explicitly destroyed. * * @category Graphics */ declare class Compute { /** * Calculate near-square 2D dispatch dimensions for a given workgroup count, * respecting the WebGPU per-dimension limit. When the count fits within a single * dimension, Y is 1. Otherwise, dimensions are chosen to be roughly square to * minimize wasted padding threads. * * @param {number} count - Total number of workgroups needed. * @param {Vec2} result - Output vector to receive X (x) and Y (y) dimensions. * @param {number} [maxDimension] - Maximum workgroups per dimension. * @returns {Vec2} The result vector with dimensions set. * @ignore */ static calcDispatchSize(count: number, result: Vec2, maxDimension?: number): Vec2; /** * Create a compute instance. Note that this is supported on WebGPU only and is a no-op on * other platforms. * * @param {GraphicsDevice} graphicsDevice * The graphics device. * @param {Shader} shader - The compute shader. * @param {string} [name] - The name of the compute instance, used for debugging only. */ constructor(graphicsDevice: GraphicsDevice, shader: Shader, name?: string); /** * A compute shader. * * @type {Shader|null} * @ignore */ shader: Shader | null; /** * The non-unique name of an instance of the class. Defaults to 'Unnamed'. * * @type {string} */ name: string; /** * @type {Map} * @ignore */ parameters: Map; /** @ignore */ countX: number; /** * @type {number|undefined} * @ignore */ countY: number | undefined; /** * @type {number|undefined} * @ignore */ countZ: number | undefined; /** * Slot index in the indirect dispatch buffer, or -1 for direct dispatch. * * @ignore */ indirectSlotIndex: number; /** * Custom buffer for indirect dispatch, or null to use device's built-in buffer. * * @type {StorageBuffer|null} * @ignore */ indirectBuffer: StorageBuffer | null; /** * Frame stamp (device.renderVersion) when indirect slot was set. Used for validation * when using the built-in buffer. * * @ignore */ indirectFrameStamp: number; device: GraphicsDevice; impl: any; /** * Sets a shader parameter on a compute instance. * * @param {string} name - The name of the parameter to set. * @param {number|number[]|Float32Array|Texture|StorageBuffer|VertexBuffer|IndexBuffer|TextureView} value * The value for the specified parameter. */ setParameter(name: string, value: number | number[] | Float32Array | Texture | StorageBuffer | VertexBuffer | IndexBuffer | TextureView): void; /** * Returns the value of a shader parameter from the compute instance. * * @param {string} name - The name of the parameter to get. * @returns {number|number[]|Float32Array|Texture|StorageBuffer|VertexBuffer|IndexBuffer|TextureView|undefined} * The value of the specified parameter. */ getParameter(name: string): number | number[] | Float32Array | Texture | StorageBuffer | VertexBuffer | IndexBuffer | TextureView | undefined; /** * Deletes a shader parameter from the compute instance. * * @param {string} name - The name of the parameter to delete. */ deleteParameter(name: string): void; /** * Frees resources associated with this compute instance. */ destroy(): void; /** * Apply the parameters to the scope. * * @ignore */ applyParameters(): void; /** * Prepare the compute work dispatch. * * @param {number} x - X dimension of the grid of work-groups to dispatch. * @param {number} [y] - Y dimension of the grid of work-groups to dispatch. * @param {number} [z] - Z dimension of the grid of work-groups to dispatch. */ setupDispatch(x: number, y?: number, z?: number): void; /** * Prepare the compute work dispatch to use indirect parameters from a buffer. The dispatch * parameters (x, y, z workgroup counts) are read from the buffer at the specified slot index. * * When using the device's built-in buffer (buffer parameter is null), this method must be * called each frame as slots are only valid for the current frame. * * @param {number} slotIndex - Slot index in the indirect dispatch buffer. When using the * device's built-in buffer, obtain this by calling {@link GraphicsDevice#getIndirectDispatchSlot}. * @param {StorageBuffer|null} [buffer] - Optional custom storage buffer containing dispatch * parameters. If not provided, uses the device's built-in {@link GraphicsDevice#indirectDispatchBuffer}. * When providing a custom buffer, the user is responsible for its lifetime and contents. * @example * // Reserve a slot in the indirect dispatch buffer * const slot = device.getIndirectDispatchSlot(); * * // First compute shader writes dispatch parameters to the buffer * prepareCompute.setParameter('indirectBuffer', device.indirectDispatchBuffer); * prepareCompute.setParameter('slot', slot); * prepareCompute.setupDispatch(1, 1, 1); * device.computeDispatch([prepareCompute]); * * // Second compute shader uses indirect dispatch * processCompute.setupIndirectDispatch(slot); * device.computeDispatch([processCompute]); */ setupIndirectDispatch(slotIndex: number, buffer?: StorageBuffer | null): void; } /** * @import { GraphicsDevice } from './graphics-device.js' * @import { IndexBuffer } from './index-buffer.js' * @import { ScopeId } from './scope-id.js' * @import { Shader } from './shader.js' * @import { StorageBuffer } from './storage-buffer.js' * @import { Texture } from './texture.js' * @import { TextureView } from './texture-view.js' * @import { Vec2 } from '../../core/math/vec2.js' * @import { VertexBuffer } from './vertex-buffer.js' */ /** * A helper class storing a parameter value as well as its scope ID. * * @ignore */ declare class ComputeParameter { value: any; /** @type {ScopeId} */ scopeId: ScopeId; } /** * The graphics device manages the underlying graphics context. It is responsible for submitting * render state changes and graphics primitives to the hardware. A graphics device is tied to a * specific canvas HTML element. It is valid to have more than one canvas element per page and * create a new graphics device against each. * * @category Graphics */ declare class GraphicsDevice extends EventHandler { static EVENT_RESIZE: string; constructor(canvas: any, options: any); /** * Fired when the canvas is resized. The handler is passed the new width and height as number * parameters. * * @event * @example * graphicsDevice.on('resizecanvas', (width, height) => { * console.log(`The canvas was resized to ${width}x${height}`); * }); */ /** * The canvas DOM element that provides the underlying WebGL context used by the graphics device. * * @type {HTMLCanvasElement} * @readonly */ readonly canvas: HTMLCanvasElement; /** * The render target representing the main back-buffer. * * @type {RenderTarget|null} * @ignore */ backBuffer: RenderTarget | null; /** * The dimensions of the back buffer. * * @ignore */ backBufferSize: Vec2; /** * The pixel format of the back buffer. Typically PIXELFORMAT_RGBA8, PIXELFORMAT_BGRA8 or * PIXELFORMAT_RGB8. * * @ignore */ backBufferFormat: any; /** * True if the back buffer should use anti-aliasing. */ backBufferAntialias: boolean; /** * True if the deviceType is WebGPU * * @type {boolean} * @readonly */ readonly isWebGPU: boolean; /** * True if the deviceType is WebGL2 * * @type {boolean} * @readonly */ readonly isWebGL2: boolean; /** * True if the deviceType is Null * * @type {boolean} * @readonly */ readonly isNull: boolean; /** * True if the back-buffer is using HDR format, which means that the browser will display the * rendered images in high dynamic range mode. This is true if the options.displayFormat is set * to {@link DISPLAYFORMAT_HDR} when creating the graphics device using * {@link createGraphicsDevice}, and HDR is supported by the device. */ isHdr: boolean; /** * The scope namespace for shader attributes and variables. * * @type {ScopeSpace} * @readonly */ readonly scope: ScopeSpace; /** * The maximum number of indirect draw calls that can be used within a single frame. Used on * WebGPU only. This needs to be adjusted based on the maximum number of draw calls that can * be used within a single frame. Defaults to 1024. */ maxIndirectDrawCount: number; /** * The maximum number of indirect compute dispatches that can be used within a single frame. * Used on WebGPU only. Defaults to 256. */ maxIndirectDispatchCount: number; /** * The maximum supported texture anisotropy setting. * * @type {number} * @readonly */ readonly maxAnisotropy: number; /** * The maximum supported dimension of a cube map. * * @type {number} * @readonly */ readonly maxCubeMapSize: number; /** * The maximum supported dimension of a texture. * * @type {number} * @readonly */ readonly maxTextureSize: number; /** * The maximum supported dimension of a 3D texture (any axis). * * @type {number} * @readonly */ readonly maxVolumeSize: number; /** * The maximum supported number of color buffers attached to a render target. * * @type {number} * @readonly */ readonly maxColorAttachments: number; /** * The highest shader precision supported by this graphics device. Can be 'highp', 'mediump' or * 'lowp'. * * @type {string} * @readonly */ readonly precision: string; /** * The number of hardware anti-aliasing samples used by the frame buffer. * * @readonly * @type {number} */ readonly samples: number; /** * The maximum supported number of hardware anti-aliasing samples. * * @readonly * @type {number} */ readonly maxSamples: number; /** * True if the main framebuffer contains stencil attachment. * * @ignore * @type {boolean} */ supportsStencil: boolean; /** * True if the device supports multi-draw. This is always supported on WebGPU, and support on * WebGL2 is optional, but pretty common. */ supportsMultiDraw: boolean; /** * True if the device supports indirect draw calls, where the draw parameters are sourced from * a GPU buffer instead of being supplied by the CPU (WebGPU only). Also see * {@link MeshInstance#setIndirect}. * * @type {boolean} * @readonly */ readonly supportsIndirectDraw: boolean; /** * True if the vertex shaders can read the model and normal matrices of a mesh instance from * a storage buffer the device holds, see {@link GraphicsDevice#meshInstanceStorage} (WebGPU * only). * * @type {boolean} * @readonly * @ignore */ readonly supportsMeshInstanceStorage: boolean; /** * The storage of the per mesh instance data read by the vertex shaders, or null when not * supported, see {@link GraphicsDevice#supportsMeshInstanceStorage}. * * @type {MeshInstanceStorage|null} * @ignore */ meshInstanceStorage: MeshInstanceStorage | null; /** * True if the device supports compute shaders. * * @readonly * @type {boolean} */ readonly supportsCompute: boolean; /** * True if the device can read from StorageTexture in the compute shader. By default, the * storage texture can be only used with the write operation. * When a shader uses this feature, add a `requires` directive to signal non-portability at the * top of the WGSL shader code. The shader define `CAPS_STORAGE_TEXTURE_READ` is set when this * capability is available. * ```wgsl * requires readonly_and_readwrite_storage_textures; * ``` * * @readonly * @type {boolean} */ readonly supportsStorageTextureRead: boolean; /** * True if the device supports subgroup operations in shaders (WebGPU only). When supported, * compute and fragment shaders can use WGSL subgroup builtins such as `subgroupBroadcast`, * `subgroupAll`, `subgroupAny`, `subgroupAdd`, `subgroupShuffle`, etc. The `enable subgroups;` * directive is automatically injected into WGSL shaders when this feature is available. * * @type {boolean} * @readonly */ readonly supportsSubgroups: boolean; /** * True if the device supports subgroup size control (WebGPU only). This depends on * {@link supportsSubgroups} and, when available, allows a compute shader to pin its execution * to a specific subgroup size (a power of two within the {@link minSubgroupSize} to * {@link maxSubgroupSize} range) via the WGSL `@subgroup_size` attribute. The * `subgroup-size-control` device feature is automatically requested when this is supported, and * the shader define `CAPS_SUBGROUP_SIZE_CONTROL` is set for conditional compilation. * * @type {boolean} * @readonly */ readonly supportsSubgroupSizeControl: boolean; /** * True if the device supports the WGSL subgroup_uniformity extension, which allows * subgroup functionality to be considered uniform in more cases during shader compilation. * This is automatically enabled via the `enable subgroups;` directive when * {@link supportsSubgroups} is true. * * @readonly * @type {boolean} */ readonly supportsSubgroupUniformity: boolean; /** * True if the device supports the WGSL subgroup_id extension, which provides access to * `subgroup_id` and `num_subgroups` built-in values in workgroups. The `requires subgroup_id;` * directive is automatically injected into WGSL shaders when this feature is available. * * @type {boolean} * @readonly */ readonly supportsSubgroupId: boolean; /** * True if the device supports the WGSL `linear_indexing` extension, which provides the * `global_invocation_index` and `workgroup_index` built-in values in compute shaders. The * `requires linear_indexing;` directive is then automatically injected for compute shader * modules, and the shader define `CAPS_LINEAR_INDEXING` is set for conditional * compilation. * * @type {boolean} * @readonly */ readonly supportsLinearIndexing: boolean; /** * True if the device supports the WGSL `pointer_composite_access` language feature, which * provides syntactic sugar for dereferencing pointers to composite types: `p.field` and * `p[i]` may be written instead of `(*p).field` and `(*p)[i]`. The * `requires pointer_composite_access;` directive is automatically injected into WGSL * shaders when this feature is available, and the shader define * `CAPS_POINTER_COMPOSITE_ACCESS` is set for conditional compilation. * * @type {boolean} * @readonly */ readonly supportsPointerCompositeAccess: boolean; /** * True if the device supports the WGSL `packed_4x8_integer_dot_product` language feature, * which exposes the DP4a-family built-in functions for 8-bit packed integer dot products: * `dot4U8Packed`, `dot4I8Packed`, and the `pack4x{I,U}8`, `pack4x{I,U}8Clamp`, * `unpack4x{I,U}8` helpers. Useful for accelerating quantized inference and similar * integer-heavy compute workloads. The `requires packed_4x8_integer_dot_product;` * directive is automatically injected into WGSL shaders when this feature is available, * and the shader define `CAPS_PACKED_4X8_INTEGER_DOT_PRODUCT` is set for conditional * compilation. * * @type {boolean} * @readonly */ readonly supportsPacked4x8IntegerDotProduct: boolean; /** * True if the device supports the WGSL `texture_and_sampler_let` language feature, which * allows assigning texture and sampler variables to `let` bindings within a WGSL shader * (preparation for bindless-style indirection patterns). The * `requires texture_and_sampler_let;` directive is automatically injected into WGSL * shaders when this feature is available, and the shader define * `CAPS_TEXTURE_AND_SAMPLER_LET` is set for conditional compilation. * * @type {boolean} * @readonly */ readonly supportsTextureAndSamplerLet: boolean; /** * True if the device supports the WGSL `unrestricted_pointer_parameters` language feature, * which allows passing pointers in the `storage`, `uniform`, and `workgroup` address spaces * as function arguments. The `requires unrestricted_pointer_parameters;` directive is * automatically injected into WGSL shaders when this feature is available, and the shader * define `CAPS_UNRESTRICTED_POINTER_PARAMETERS` is set for conditional compilation. * * @type {boolean} * @readonly */ readonly supportsUnrestrictedPointerParameters: boolean; /** * Maximum subgroup (warp/wavefront) size reported for the device. Zero means either the device * does not expose subgroup sizes, or the WebGPU implementation did not report the value. * * @type {number} * @readonly */ readonly maxSubgroupSize: number; /** * Minimum subgroup (warp/wavefront) size reported for the device. Zero means either the device * does not expose subgroup sizes, or the WebGPU implementation did not report the value. * * @type {number} * @readonly */ readonly minSubgroupSize: number; /** * Currently active render target. * * @type {RenderTarget|null} * @ignore */ renderTarget: RenderTarget | null; /** * Array of objects that need to be re-initialized after a context restore event * * @type {Shader[]} * @ignore */ shaders: Shader[]; /** * A set of currently created textures. * * @type {Set} * @ignore */ textures: Set; /** * A set of textures that need to be uploaded to the GPU. * * @type {Set} * @ignore */ texturesToUpload: Set; /** * A set of currently created render targets. * * @type {Set} * @ignore */ targets: Set; /** * A version number that is incremented every frame. This is used to detect if some object were * invalidated. * * @ignore */ renderVersion: number; /** * Index of the currently active render pass. * * @type {number} * @ignore */ renderPassIndex: number; /** @type {boolean} */ insideRenderPass: boolean; /** * True if the device binds the mesh resources through bind groups: the textures and samplers * in the mesh bind group and the per-draw mesh uniforms in a dynamic uniform buffer (WebGPU). * Otherwise they are set individually through the scope. Uniform buffers for the view and the * materials are used on every device. * * @ignore */ usesMeshBindGroups: boolean; /** * True if the device supports clip distances (WebGPU only). Clip distances allow you to restrict * primitives' clip volume with user-defined half-spaces in the output of vertex stage. */ supportsClipDistances: boolean; /** * True if the device supports transient ("memoryless") render target attachments (WebGPU only). * When supported, attachments that are only used within a single render pass (cleared on load * and discarded on store) can be allocated as memoryless, allowing tile-based GPUs to keep their * contents in on-chip memory and avoid VRAM allocation. See the `transientColor` / * `transientDepth` options of {@link RenderTarget} and {@link createGraphicsDevice}. * * @type {boolean} * @readonly */ readonly supportsTransientAttachments: boolean; /** * True if the device supports the WebGPU 'texture-formats-tier1' feature (WebGPU only). When * available, 16-bit unorm and snorm texture formats become usable, the 8-bit snorm formats * become renderable, blendable and multisample-capable, and a wider set of 8-bit and 16-bit * formats can be bound as storage textures. Implied by {@link supportsTextureFormatsTier2}. * * @type {boolean} * @readonly */ readonly supportsTextureFormatsTier1: boolean; /** * True if the device supports the WebGPU 'texture-formats-tier2' feature (WebGPU only). This * extends tier 1 and enables read-write storage access for additional texture formats. * * @type {boolean} * @readonly */ readonly supportsTextureFormatsTier2: boolean; /** * True if the device supports primitive index in fragment shaders (WebGPU only). When * supported, fragment shaders can access the `pcPrimitiveIndex` built-in variable which * uniquely identifies the current primitive being processed. * * @type {boolean} * @readonly */ readonly supportsPrimitiveIndex: boolean; /** * True if the device supports dual-source blending, which allows a fragment shader to output a * secondary color used by the source 1 blend factors. * * @type {boolean} * @readonly */ readonly supportsDualSourceBlending: boolean; /** * True if the device supports independent blending, which allows each color attachment of a * render target to use its own blend state and color write mask, specified using * {@link BlendState#setAttachment}. When false, the state of the attachment 0 is used for all * attachments. * * @type {boolean} * @readonly */ readonly supportsIndependentBlending: boolean; /** * True if the device supports 16-bit floating-point types in shaders (WebGPU only). When * supported, shaders can use native WGSL types: `f16`, `vec2h`, `vec3h`, `vec4h`, `mat2x2h`, * `mat3x3h`, `mat4x4h`. For convenience, PlayCanvas also provides type aliases (`half`, * `half2`, `half3`, `half4`, `half2x2`, `half3x3`, `half4x4`) that resolve to f16 types when * supported, or fall back to f32 types when not supported. * * @type {boolean} * @readonly */ readonly supportsShaderF16: boolean; /** * True if HTML elements (e.g. `
`) can be used as texture sources via the HTML-in-Canvas * API. When supported, an HTML element appended to a canvas with the `layoutsubtree` attribute * can be passed to {@link Texture#setSource} and rendered as a live texture in the 3D scene. * * @type {boolean} * @readonly */ readonly supportsHtmlTextures: boolean; /** * True if 32-bit floating-point textures can be used as a frame buffer. * * @type {boolean} * @readonly */ readonly textureFloatRenderable: boolean; /** * True if 16-bit floating-point textures can be used as a frame buffer. * * @type {boolean} * @readonly */ readonly textureHalfFloatRenderable: boolean; /** * True if small-float textures with format {@link PIXELFORMAT_111110F} can be used as a frame * buffer. This is always true on WebGL2, but optional on WebGPU device. * * @type {boolean} * @readonly */ readonly textureRG11B10Renderable: boolean; /** * True if filtering can be applied when sampling float textures. * * @type {boolean} * @readonly */ readonly textureFloatFilterable: boolean; /** * True if blending can be used when rendering to 32-bit floating-point render targets. Note that * 16-bit floating-point render targets are always blendable when they are renderable. * * @type {boolean} * @readonly */ readonly textureFloatBlendable: boolean; /** * A vertex buffer representing a quad. * * @type {VertexBuffer} * @ignore */ quadVertexBuffer: VertexBuffer; /** * An index buffer for drawing a quad as an indexed triangle list. * Contains 6 indices: [0, 1, 2, 2, 1, 3] forming two triangles. * * @type {IndexBuffer} * @ignore */ quadIndexBuffer: IndexBuffer; /** * The textures the engine binds in place of a texture it was not given. * * @type {BuiltInTextures} * @ignore */ builtInTextures: BuiltInTextures; /** * An object representing current blend state * * @ignore */ blendState: BlendState; /** * The current depth state. * * @ignore */ depthState: DepthState; /** * True if stencil is enabled and stencilFront and stencilBack are used * * @ignore */ stencilEnabled: boolean; /** * The current front stencil parameters. * * @ignore */ stencilFront: StencilParameters; /** * The current back stencil parameters. * * @ignore */ stencilBack: StencilParameters; /** * The dynamic buffer manager. * * @type {DynamicBuffers} * @ignore */ dynamicBuffers: DynamicBuffers; /** * The GPU profiler. * * @type {GpuProfiler} */ gpuProfiler: GpuProfiler; /** @ignore */ _destroyed: boolean; defaultClearOptions: { color: number[]; depth: number; stencil: number; flags: number; }; /** * The current client rect. * * @type {{ width: number, height: number }} * @ignore */ clientRect: { width: number; height: number; }; /** * A very heavy handed way to force all shaders to be rebuilt. Avoid using as much as possible. * * @ignore */ _shadersDirty: boolean; /** * A list of shader defines based on the capabilities of the device. * * @type {Map} * @ignore */ capsDefines: Map; /** * A version number incremented at the end of every frame. Frame-scoped draw commands are * stamped with it, see {@link DrawCommands#validUntilVersion}. * * @ignore */ drawCommandsVersion: number; initOptions: any; _maxPixelRatio: number; buffers: Set; _vram: { texShadow: number; texAsset: number; texLightmap: number; tex: number; vb: number; ib: number; ub: number; sb: number; }; _shaderStats: { vsCompiled: number; fsCompiled: number; linked: number; materialShaders: number; compileTime: number; }; _drawCallsPerFrame: number; _shaderSwitchesPerFrame: number; _primitiveCount: number; _renderTargetCreationTime: number; textureBias: ScopeId; /** * Function that executes after the device has been created. */ postInit(): void; /** * Initialize the map of device capabilities, which are supplied to shaders as defines. * * @ignore */ initCapsDefines(): void; /** * Samples existing resource registries for diagnostic overlays. Counts include internal * resources; dynamic uniform buffers count backing GPU buffers, not suballocations or staging * buffers. This walks the buffer registry and should only be called at diagnostic refresh rates. * * @param {Map} counts - Receives the current counts, replacing previous values. * @ignore */ getResourceCounts(counts: Map): void; /** * Destroy the graphics device. */ destroy(): void; onDestroyShader(shader: any): void; /** * Called when a texture is destroyed to remove it from internal tracking structures. * * @param {Texture} texture - The texture being destroyed. * @ignore */ onTextureDestroyed(texture: Texture): void; postDestroy(): void; /** * Called when the device context was lost. It releases all context related resources. * * @ignore */ loseContext(): void; contextLost: boolean; /** * Called when the device context is restored. It reinitializes all context related resources. * * @ignore */ restoreContext(): void; /** * Reports whether the device is lost or destroyed, including a native loss whose event has not * arrived yet. * * @returns {boolean} Whether the device is lost or destroyed. * @ignore */ isContextLost(): boolean; /** * Forces an actual graphics context or device loss for testing, then attempts recovery after * the specified delay. Only has an effect in debug builds on WebGL and WebGPU. Calls made while * a loss or recovery is pending are ignored. Recovery is asynchronous and is not guaranteed * to succeed. Listen for `devicelost` and `devicerestored` to observe the recovery lifecycle. * * @param {number} [delay] - Delay in milliseconds after loss is observed before attempting * recovery. Defaults to 100. * @ignore * @example * app.graphicsDevice.debugLoseContext(1000); */ debugLoseContext(delay?: number): void; toJSON(key: any): any; initializeContextCaches(): void; vertexBuffers: any[]; shader: any; shaderValid: any; shaderAsyncCompile: boolean; initializeRenderState(): void; cullMode: number; frontFace: number; alphaToCoverage: boolean; vx: number; vy: number; vw: number; vh: number; sx: number; sy: number; sw: number; sh: number; blendColor: Color; /** * @deprecated The limit has been removed. * @ignore */ get boneLimit(): number; /** * @deprecated Use GraphicsDevice#isWebGL2 instead. * @ignore */ get webgl2(): boolean; /** * @deprecated Always returns true. * @ignore */ get textureFloatHighPrecision(): boolean; /** * @deprecated Always returns true. * @ignore */ get extBlendMinmax(): boolean; /** * @deprecated Always returns true. * @ignore */ get extTextureHalfFloat(): boolean; /** * @deprecated Always returns true. * @ignore */ get extTextureLod(): boolean; /** * @deprecated Always returns true. * @ignore */ get textureHalfFloatFilterable(): boolean; /** * @deprecated Always returns true. * @ignore */ get supportsMrt(): boolean; /** * @deprecated Always returns true. * @ignore */ get supportsVolumeTextures(): boolean; /** * @deprecated Always returns true. * @ignore */ get supportsInstancing(): boolean; /** * @deprecated Always returns true. * @ignore */ get textureHalfFloatUpdatable(): boolean; /** * @deprecated Always returns true. * @ignore */ get extTextureFloat(): boolean; /** * @deprecated Always returns true. * @ignore */ get extStandardDerivatives(): boolean; /** * @deprecated Use GraphicsDevice.setBlendState instead. * @param {number} blendSrc - The blend mode. Can be any of the BLENDMODE_* constants. * @param {number} blendDst - The blend mode. Can be any of the BLENDMODE_* constants. * @ignore */ setBlendFunction(blendSrc: number, blendDst: number): void; /** * @deprecated Use GraphicsDevice.setBlendState instead. * @param {number} blendSrc - The blend mode. Can be any of the BLENDMODE_* constants. * @param {number} blendDst - The blend mode. Can be any of the BLENDMODE_* constants. * @param {number} blendSrcAlpha - The blend mode. Can be any of the BLENDMODE_* constants. * @param {number} blendDstAlpha - The blend mode. Can be any of the BLENDMODE_* constants. * @ignore */ setBlendFunctionSeparate(blendSrc: number, blendDst: number, blendSrcAlpha: number, blendDstAlpha: number): void; /** * @deprecated Use GraphicsDevice.setBlendState instead. * @param {number} blendEquation - The blend equation. Can be any of the BLENDEQUATION_* * constants. * @ignore */ setBlendEquation(blendEquation: number): void; /** * @deprecated Use GraphicsDevice.setBlendState instead. * @param {number} blendEquation - The blend equation. Can be any of the BLENDEQUATION_* * constants. * @param {number} blendAlphaEquation - The blend equation. Can be any of the BLENDEQUATION_* * constants. * @ignore */ setBlendEquationSeparate(blendEquation: number, blendAlphaEquation: number): void; /** * @deprecated Use GraphicsDevice.setBlendState instead. * @param {boolean} redWrite - True to enable writing of the red channel and false otherwise. * @param {boolean} greenWrite - True to enable writing of the green channel and false otherwise. * @param {boolean} blueWrite - True to enable writing of the blue channel and false otherwise. * @param {boolean} alphaWrite - True to enable writing of the alpha channel and false otherwise. * @ignore */ setColorWrite(redWrite: boolean, greenWrite: boolean, blueWrite: boolean, alphaWrite: boolean): void; getBlending(): boolean; /** * @deprecated Use GraphicsDevice.setBlendState instead. * @param {boolean} blending - True to enable blending and false to disable it. * @ignore */ setBlending(blending: boolean): void; /** * @deprecated Use GraphicsDevice.setDepthState instead. * @param {boolean} write - True to enable depth writing and false otherwise. * @ignore */ setDepthWrite(write: boolean): void; /** * @deprecated Use GraphicsDevice.setDepthState instead. * @param {number} func - The depth testing function. Can be any of the FUNC_* constants. * @ignore */ setDepthFunc(func: number): void; /** * @deprecated Use GraphicsDevice.setDepthState instead. * @param {boolean} test - True to enable depth testing and false otherwise. * @ignore */ setDepthTest(test: boolean): void; getCullMode(): number; /** * Sets the specified stencil state. If both stencilFront and stencilBack are null, stencil * operation is disabled. * * @param {StencilParameters} [stencilFront] - The front stencil parameters. Defaults to * {@link StencilParameters.DEFAULT} if not specified. * @param {StencilParameters} [stencilBack] - The back stencil parameters. Defaults to * {@link StencilParameters.DEFAULT} if not specified. */ setStencilState(stencilFront?: StencilParameters, stencilBack?: StencilParameters): void; /** * Sets the specified blend state. * * @param {BlendState} blendState - New blend state. */ setBlendState(blendState: BlendState): void; /** * Sets the constant blend color and alpha values used with {@link BLENDMODE_CONSTANT} and * {@link BLENDMODE_ONE_MINUS_CONSTANT} factors specified in {@link BlendState}. Defaults to * [0, 0, 0, 0]. * * @param {number} r - The value for red. * @param {number} g - The value for green. * @param {number} b - The value for blue. * @param {number} a - The value for alpha. */ setBlendColor(r: number, g: number, b: number, a: number): void; /** * Sets the specified depth state. * * @param {DepthState} depthState - New depth state. */ setDepthState(depthState: DepthState): void; /** * Controls how triangles are culled based on their face direction. The default cull mode is * {@link CULLFACE_BACK}. * * @param {number} cullMode - The cull mode to set. Can be: * * - {@link CULLFACE_NONE} * - {@link CULLFACE_BACK} * - {@link CULLFACE_FRONT} */ setCullMode(cullMode: number): void; /** * Controls whether polygons are front- or back-facing by setting a winding * orientation. The default frontFace is {@link FRONTFACE_CCW}. * * @param {number} frontFace - The front face to set. Can be: * * - {@link FRONTFACE_CW} * - {@link FRONTFACE_CCW} */ setFrontFace(frontFace: number): void; /** * Sets all draw-related render states in a single call. All parameters have sensible defaults * for utility rendering (full-screen quads, particles, etc.), so calling `setDrawStates()` with * no arguments resets to a safe baseline. * * @param {BlendState} [blendState] - Blend state. Defaults to {@link BlendState.NOBLEND}. * @param {DepthState} [depthState] - Depth state. Defaults to {@link DepthState.NODEPTH}. * @param {number} [cullMode] - Cull mode. Defaults to {@link CULLFACE_NONE}. * @param {number} [frontFace] - Front face winding. Defaults to {@link FRONTFACE_CCW}. * @param {StencilParameters} [stencilFront] - Front stencil parameters. * @param {StencilParameters} [stencilBack] - Back stencil parameters. */ setDrawStates(blendState?: BlendState, depthState?: DepthState, cullMode?: number, frontFace?: number, stencilFront?: StencilParameters, stencilBack?: StencilParameters): void; /** * Sets the specified render target on the device. If null is passed as a parameter, the back * buffer becomes the current target for all rendering operations. * * @param {RenderTarget|null} renderTarget - The render target to activate. * @example * // Set a render target to receive all rendering output * device.setRenderTarget(renderTarget); * * // Set the back buffer to receive all rendering output * device.setRenderTarget(null); */ setRenderTarget(renderTarget: RenderTarget | null): void; /** * Sets the current vertex buffer on the graphics device. For subsequent draw calls, the * specified vertex buffer(s) will be used to provide vertex data for any primitives. * * @param {VertexBuffer} vertexBuffer - The vertex buffer to assign to the device. * @ignore */ setVertexBuffer(vertexBuffer: VertexBuffer): void; /** * Clears the vertex buffer set on the graphics device. This is called automatically by the * renderer. * * @ignore */ clearVertexBuffer(): void; /** * Retrieves the first available slot in the {@link indirectDrawBuffer} used for indirect * rendering, which can be utilized by a {@link Compute} shader to generate indirect draw * parameters and by {@link MeshInstance#setIndirect} to configure indirect draw calls. * * When reserving multiple consecutive slots, specify the optional `count` parameter. * * Only available on WebGPU, see {@link GraphicsDevice#supportsIndirectDraw}. Returns 0 on * other platforms. * * @param {number} [count] - Number of consecutive slots to reserve. Defaults to 1. * @returns {number} - The first reserved slot index used for indirect rendering. */ getIndirectDrawSlot(count?: number): number; /** * Returns the buffer used to store arguments for indirect draw calls. The size of the buffer is * controlled by the {@link maxIndirectDrawCount} property. This buffer can be passed to a * {@link Compute} shader along with a slot obtained by calling {@link getIndirectDrawSlot}, in * order to prepare indirect draw parameters. Also see {@link MeshInstance#setIndirect}. * * Only available on WebGPU, returns null on other platforms. * * @type {StorageBuffer|null} */ get indirectDrawBuffer(): StorageBuffer | null; /** * Retrieves the first available slot in the {@link indirectDispatchBuffer} used for indirect * compute dispatch, which can be utilized by a {@link Compute} shader to generate indirect * dispatch parameters for another compute shader. * * When reserving multiple consecutive slots, specify the optional `count` parameter. * * @param {number} [count] - Number of consecutive slots to reserve. Defaults to 1. * @returns {number} - The first reserved slot index used for indirect dispatch. */ getIndirectDispatchSlot(count?: number): number; /** * Returns the buffer used to store arguments for indirect compute dispatch calls. The size of * the buffer is controlled by the {@link maxIndirectDispatchCount} property. This buffer can * be passed to a {@link Compute} shader along with a slot obtained by calling * {@link getIndirectDispatchSlot}, in order to prepare indirect dispatch parameters. * * Only available on WebGPU, returns null on other platforms. * * @type {StorageBuffer|null} */ get indirectDispatchBuffer(): StorageBuffer | null; /** * Queries the currently set render target on the device. * * @returns {RenderTarget} The current render target. * @example * // Get the current render target * const renderTarget = device.getRenderTarget(); */ getRenderTarget(): RenderTarget; /** * Initialize render target before it can be used. * * @param {RenderTarget} target - The render target to be initialized. * @ignore */ initRenderTarget(target: RenderTarget): void; /** * Submits a graphical primitive to the hardware for immediate rendering. * * @param {object} primitive - Primitive object describing how to submit current vertex/index * buffers. * @param {number} primitive.type - The type of primitive to render. Can be: * * - {@link PRIMITIVE_POINTS} * - {@link PRIMITIVE_LINES} * - {@link PRIMITIVE_LINELOOP} * - {@link PRIMITIVE_LINESTRIP} * - {@link PRIMITIVE_TRIANGLES} * - {@link PRIMITIVE_TRISTRIP} * - {@link PRIMITIVE_TRIFAN} * * @param {number} primitive.base - The offset of the first index or vertex to dispatch in the * draw call. * @param {number} primitive.count - The number of indices or vertices to dispatch in the draw * call. * @param {boolean} [primitive.indexed] - True to interpret the primitive as indexed, thereby * using the currently set index buffer and false otherwise. * @param {IndexBuffer} [indexBuffer] - The index buffer to use for the draw call. * @param {number} [numInstances] - The number of instances to render when using instancing. * Defaults to 1. * @param {DrawCommands} [drawCommands] - The draw commands to use for the draw call. * @param {boolean} [first] - True if this is the first draw call in a sequence of draw calls. * When set to true, vertex and index buffers related state is set up. Defaults to true. * @param {boolean} [last] - True if this is the last draw call in a sequence of draw calls. * When set to true, vertex and index buffers related state is cleared. Defaults to true. * @param {number} [firstInstance] - The first instance of a draw without draw commands, * which offsets the instance index of the vertex shader. Ignored on WebGL. Defaults to 0. * @example * // Render a single, unindexed triangle * device.draw({ * type: PRIMITIVE_TRIANGLES, * base: 0, * count: 3, * indexed: false * }); * * @ignore */ draw(primitive: { type: number; base: number; count: number; indexed?: boolean; }, indexBuffer?: IndexBuffer, numInstances?: number, drawCommands?: DrawCommands, first?: boolean, last?: boolean, firstInstance?: number): void; /** * Reports whether a texture source is a canvas, image, video, ImageBitmap, or HTML element. * * @param {*} texture - Texture source data. * @returns {boolean} True if the texture is a canvas, image, video, ImageBitmap, or HTML * element and false otherwise. * @ignore */ _isBrowserInterface(texture: any): boolean; _isImageBrowserInterface(texture: any): boolean; _isImageCanvasInterface(texture: any): boolean; _isImageVideoInterface(texture: any): boolean; /** * Reports whether a texture source is a generic HTML element (not image, canvas, or video). * Used for the HTML-in-Canvas proposal (texElementImage2D). * * @param {*} texture - Texture source data. * @returns {boolean} True if the texture is an HTMLElement that is not an image, canvas, or * video. * @ignore */ _isHTMLElementInterface(texture: any): boolean; /** * Sets the width and height of the canvas, then fires the `resizecanvas` event. Note that the * specified width and height values will be multiplied by the value of {@link maxPixelRatio} * to give the final resultant width and height for the canvas. * * @param {number} width - The new width of the canvas. * @param {number} height - The new height of the canvas. * @ignore */ resizeCanvas(width: number, height: number): void; /** * Sets the width and height of the canvas, then fires the `resizecanvas` event. Note that the * value of {@link maxPixelRatio} is ignored. * * @param {number} width - The new width of the canvas. * @param {number} height - The new height of the canvas. * @ignore */ setResolution(width: number, height: number): void; update(): void; updateClientRect(): void; /** * Width of the back buffer in pixels. * * @type {number} */ get width(): number; /** * Height of the back buffer in pixels. * * @type {number} */ get height(): number; /** * Sets whether the device is currently in fullscreen mode. * * @type {boolean} */ set fullscreen(fullscreen: boolean); /** * Gets whether the device is currently in fullscreen mode. * * @type {boolean} */ get fullscreen(): boolean; /** * Sets the maximum pixel ratio. * * @type {number} */ set maxPixelRatio(ratio: number); /** * Gets the maximum pixel ratio. * * @type {number} */ get maxPixelRatio(): number; /** * Gets the type of the device. Can be: * * - {@link DEVICETYPE_WEBGL2} * - {@link DEVICETYPE_WEBGPU} * * @type {DEVICETYPE_WEBGL2|DEVICETYPE_WEBGPU} */ get deviceType(): "webgl2" | "webgpu"; startRenderPass(renderPass: any): void; endRenderPass(renderPass: any): void; startComputePass(name: any): void; endComputePass(): void; /** * Function which executes at the start of the frame. This should not be called manually, as * it is handled by the AppBase instance. * * @ignore */ frameStart(): void; /** * Function which executes at the end of the frame. This should not be called manually, as it is * handled by the AppBase instance. * * @ignore */ frameEnd(): void; /** * Dispatch multiple compute shaders inside a single compute shader pass. * * @param {Array} computes - An array of compute shaders to dispatch. * @param {string} [name] - The name of the dispatch, used for debugging and reporting only. */ computeDispatch(computes: Array, name?: string): void; /** * Get a renderable HDR pixel format supported by the graphics device. * * Note: * * - When the `filterable` parameter is set to false, this function returns one of the supported * formats on the majority of devices apart from some very old iOS and Android devices (99%). * - When the `filterable` parameter is set to true, the function returns a format on a * considerably lower number of devices (70%). * - Support is determined by the precision of a format and not by its number of channels, and so * all the half float formats are supported wherever any of them is, and similarly for the 32bit * float formats. * * @param {number[]} [formats] - An array of pixel formats to check for support. Can contain: * * - {@link PIXELFORMAT_111110F} * - {@link PIXELFORMAT_R16F} * - {@link PIXELFORMAT_R32F} * - {@link PIXELFORMAT_RG16F} * - {@link PIXELFORMAT_RG32F} * - {@link PIXELFORMAT_RGBA16F} * - {@link PIXELFORMAT_RGBA32F} * * Any other format in the array is skipped, allowing a non-HDR format to be included in the * list and handled by the caller's own fallback. * * @param {boolean} [filterable] - If true, the format also needs to be filterable, allowing it * to be sampled with linear filtering. Defaults to true. * @param {number} [samples] - The number of samples to check for. Some formats are not * compatible with multi-sampling, for example {@link PIXELFORMAT_RGBA32F} on WebGPU platform. * Defaults to 1. * @param {boolean} [blendable] - If true, the format also needs to be blendable, allowing it to * be used as a blended render target attachment. This is an independent capability to * filtering, and only the 32bit float formats can fail to support it. Defaults to false. * @returns {number|undefined} The first supported renderable HDR format or undefined if none is * supported. */ getRenderableHdrFormat(formats?: number[], filterable?: boolean, samples?: number, blendable?: boolean): number | undefined; /** * Validate that all attributes required by the shader are present in the currently assigned * vertex buffers. * * @param {Shader} shader - The shader to validate. * @param {(VertexBuffer|null|undefined)[]} vertexBuffers - The vertex buffers of the draw. * @protected */ protected validateAttributes(shader: Shader, vertexBuffers: (VertexBuffer | null | undefined)[]): void; } /** * @import { GraphicsDevice } from '../graphics/graphics-device.js' */ /** * A frame pass represents a node in the frame graph. It encapsulates a unit of work that * executes during frame rendering. Subclasses include {@link RenderPass} for GPU render passes * with render targets, and non-rendering passes for compute dispatches or other tasks. * * @ignore */ declare class FramePass { /** * Creates an instance of the FramePass. * * @param {GraphicsDevice} graphicsDevice - The graphics device. */ constructor(graphicsDevice: GraphicsDevice); /** @type {string} */ _name: string; /** * The graphics device. * * @type {GraphicsDevice} */ device: GraphicsDevice; /** * True if the frame pass is enabled. * * @private */ private _enabled; /** * True if the render pass start is skipped. This means the render pass is merged into the * previous one. Used by FrameGraph.compile() for pass merging. * * @private */ private _skipStart; /** * True if the render pass end is skipped. This means the following render pass is merged into * this one. Used by FrameGraph.compile() for pass merging. * * @private */ private _skipEnd; /** * True if the frame pass is enabled and execute function will be called. Note that before and * after functions are called regardless of this flag. */ executeEnabled: boolean; /** * If true, this pass might use dynamically rendered cubemaps. Defaults to false for non-render * passes (RenderPass overrides to true). */ requiresCubemaps: boolean; /** * Frame passes which need to be executed before this pass. * * @type {FramePass[]} */ beforePasses: FramePass[]; /** * Frame passes which need to be executed after this pass. * * @type {FramePass[]} */ afterPasses: FramePass[]; set name(value: string); get name(): string; set enabled(value: boolean); get enabled(): boolean; onEnable(): void; onDisable(): void; frameUpdate(): void; /** * Called before execution when the pass is enabled, even if {@link executeEnabled} is false. * Overrides that require execution must check {@link executeEnabled} themselves. */ before(): void; execute(): void; /** * Called after execution when the pass is enabled, even if {@link executeEnabled} is false. * Overrides that require execution must check {@link executeEnabled} themselves. */ after(): void; destroy(): void; render(): void; log(device: any, index?: number): void; } /** * A render pass represents a node in the frame graph that renders to a render target using a GPU * render pass. It extends {@link FramePass} with render target management, color/depth/stencil * attachment operations, and GPU render pass lifecycle (start/end). * * @ignore */ declare class RenderPass extends FramePass { /** * The render target for this render pass: * * - `undefined`: render pass does not render to any render target * - `null`: render pass renders to the backbuffer * - Otherwise, renders to the provided RT. * * @type {RenderTarget|null|undefined} */ renderTarget: RenderTarget | null | undefined; /** * The options specified when the render target was initialized. */ _options: any; /** * Number of samples. 0 if no render target, otherwise number of samples from the render target, * or the main framebuffer if render target is null. */ samples: number; /** * Array of color attachment operations. The first element corresponds to the color attachment * 0, and so on. * * @type {Array} */ colorArrayOps: Array; /** * Color attachment operations for the first color attachment. * * @type {ColorAttachmentOps} */ get colorOps(): ColorAttachmentOps; /** @type {DepthStencilAttachmentOps} */ depthStencilOps: DepthStencilAttachmentOps; /** * True if the render pass uses the full viewport / scissor for rendering into the render target. */ fullSizeClearRect: boolean; set scaleX(value: any); get scaleX(): any; set scaleY(value: any); get scaleY(): any; set options(value: any); get options(): any; /** * @param {RenderTarget|null} [renderTarget] - The render target to render into (output). This * function should be called only for render passes which use render target, or passes which * render directly into the default framebuffer, in which case a null or undefined render * target is expected. * @param {object} [options] - Object for passing optional arguments. * @param {Texture} [options.resizeSource] - A texture to use as a source for the automatic * render target resize operation. If not provided, no automatic resizing takes place. * @param {number} [options.scaleX] - The scale factor for the render target width. Defaults to 1. * @param {number} [options.scaleY] - The scale factor for the render target height. Defaults to 1. */ init(renderTarget?: RenderTarget | null, options?: { resizeSource?: Texture; scaleX?: number; scaleY?: number; }): void; allocateAttachments(): void; postInit(): void; /** * Mark render pass as clearing the full color buffer. * * @param {Color|undefined} color - The color to clear to, or undefined to preserve the existing * content. * @param {number} [index] - The index of the color attachment to modify. When not specified, * all color attachments are modified. */ setClearColor(color: Color | undefined, index?: number): void; /** * Mark render pass as clearing the full depth buffer. * * @param {number|undefined} depthValue - The depth value to clear to, or undefined to preserve * the existing content. */ setClearDepth(depthValue: number | undefined): void; /** * Mark render pass as clearing the full stencil buffer. * * @param {number|undefined} stencilValue - The stencil value to clear to, or undefined to * preserve the existing content. */ setClearStencil(stencilValue: number | undefined): void; } declare class ColorAttachmentOps { /** * A color used to clear the color attachment when the clear is enabled, specified in sRGB space. */ clearValue: Color; /** * A color used to clear the color attachment when the clear is enabled, specified in linear * space. */ clearValueLinear: Color; /** * True if the attachment should be cleared before rendering, false to preserve * the existing content. */ clear: boolean; /** * True if the attachment needs to be stored after the render pass. False if it can be * discarded. Note: This relates to the surface that is getting rendered to, and can be either * single or multi-sampled. Further, if a multi-sampled surface is used, the resolve flag * further specifies if this gets resolved to a single-sampled surface. This behavior matches * the WebGPU specification. */ store: boolean; /** * True if the attachment needs to be resolved. */ resolve: boolean; /** * True if the attachment needs to have mipmaps generated. */ genMipmaps: boolean; } declare class DepthStencilAttachmentOps { /** * A depth value used to clear the depth attachment when the clear is enabled. */ clearDepthValue: number; /** * A stencil value used to clear the stencil attachment when the clear is enabled. */ clearStencilValue: number; /** * True if the depth attachment should be cleared before rendering, false to preserve * the existing content. */ clearDepth: boolean; /** * True if the stencil attachment should be cleared before rendering, false to preserve * the existing content. */ clearStencil: boolean; /** * True if the depth attachment needs to be stored after the render pass. False * if it can be discarded. */ storeDepth: boolean; /** * True if the depth attachment needs to be resolved. */ resolveDepth: boolean; /** * True if the stencil attachment needs to be stored after the render pass. False * if it can be discarded. */ storeStencil: boolean; } /** * @import { GraphicsDevice } from '../../platform/graphics/graphics-device.js' */ /** * A frame pass that wraps an ordered list of child frame passes and runs them once per XR view. * Currently used by the WebGPU XR path: per eye, the wrapper sets the active view index on the * graphics device, swaps the backbuffer color view to the matching XR sub-image view descriptor, * and invokes each child's `render()`. * * The children are not added to {@link FrameGraph#renderPasses} - they are owned by the wrapper * and invoked from {@link FramePassMultiView#render}. This guarantees the frame graph's * pass-merging cannot accidentally merge eye-N's last pass with eye-(N+1)'s first pass. * * ## Future extension paths * * ### GPU-native multiview (single-pass stereo) * Both WebGL (`OVR_multiview2`) and a future WebGPU multiview extension allow the GPU to render * all views in **one draw call**, writing to each array layer simultaneously via * `gl_ViewID_OVR` (WebGL) or `@builtin(view_index)` (WGSL). When those APIs become available * this class is the right place to switch strategy: instead of looping N times, `render()` would * configure a single multiview render pass targeting an array render target, upload all N view * matrices as an array UBO, and issue children once. The serial-iteration path would remain as a * fallback when the extension is absent. * * ### WebGL stereo * WebGL XR currently uses a single framebuffer with per-eye viewports (no wrapper needed). * If `OVR_multiview2` support is added, `ForwardRenderer._isMultiview` could be extended to * return `true` for WebGL when the extension is present, allowing this wrapper to orchestrate * the multiview setup on both backends with a shared code path. * * @ignore */ declare class FramePassMultiView extends FramePass { /** * Ordered list of child passes executed once per XR view. * * @type {FramePass[]} */ children: FramePass[]; /** * Append a child pass to be replayed per view. * * @param {FramePass} pass - The pass to add. */ addChild(pass: FramePass): void; } /** * @import { FramePass } from '../platform/graphics/frame-pass.js' * @import { GraphicsDevice } from '../platform/graphics/graphics-device.js' * @import { RenderPass } from '../platform/graphics/render-pass.js' * @import { RenderTarget } from '../platform/graphics/render-target.js' * @import { Texture } from '../platform/graphics/texture.js' */ /** * A frame graph represents a single rendering frame as a sequence of frame passes. * * @ignore */ declare class FrameGraph { /** @type {FramePass[]} */ renderPasses: FramePass[]; /** * Map used during frame graph compilation. It maps a render target to its previous occurrence. * * @type {Map} */ renderTargetMap: Map; /** * Active multi-view capture wrapper. When non-null, passes scheduled via * {@link FrameGraph#addRenderPass} are appended as children of this wrapper instead of being * pushed directly into {@link FrameGraph#renderPasses}. Set/cleared via * {@link FrameGraph#beginMultiView} / {@link FrameGraph#endMultiView}. * * @type {FramePassMultiView|null} */ multiview: FramePassMultiView | null; /** * Open a multi-view capture scope. Subsequent passes added through * {@link FrameGraph#addRenderPass} are captured as children of a single * {@link FramePassMultiView} until {@link FrameGraph#endMultiView} is called. * * @param {GraphicsDevice} device - The graphics device used to construct the wrapper. */ beginMultiView(device: GraphicsDevice): void; /** * Close the multi-view capture scope. Pushes the wrapper into the frame graph render passes * unless it captured no children (in which case it is dropped). */ endMultiView(): void; /** * Add a frame pass to the frame. * * @param {FramePass} renderPass - The frame pass to add. */ addRenderPass(renderPass: FramePass): void; reset(): void; compile(): void; /** * Run the frame-graph compile optimizations (store-on-no-clear, pass merging, cube mipmap * skipping) over a flat list of passes. * * @param {FramePass[]} passes - Passes to optimize. * @private */ private _compilePasses; render(device: any): void; } type ChunkValidation = { /** * - Deprecation message to display. */ message?: string; /** * - Validation callback receiving chunk name and code. */ callback?: (arg0: string, arg1: string) => void; /** * - Default GLSL code. If matches, no warning. */ defaultCodeGLSL?: string; /** * - Default WGSL code. If matches, no warning. */ defaultCodeWGSL?: string; }; /** * @typedef {object} ChunkValidation * @property {string} [message] - Deprecation message to display. * @property {function(string, string):void} [callback] - Validation callback receiving chunk name and code. * @property {string} [defaultCodeGLSL] - Default GLSL code. If matches, no warning. * @property {string} [defaultCodeWGSL] - Default WGSL code. If matches, no warning. */ /** * A collection of shader chunks, used by {@link ShaderChunks}. This is a map of shader chunk names * to their code. As this class extends `Map`, it can be used as a `Map` as well in addition to * custom functionality it provides. * * @category Graphics */ declare class ShaderChunkMap extends Map { /** * Create a new ShaderChunkMap instance. * * @param {Map} [validations] - Optional map of chunk validations. * @ignore */ constructor(validations?: Map); /** * Reference to chunk validations map. * * @type {Map|undefined} * @private */ private _validations; _keyDirty: boolean; _key: string; /** * Adds a new shader chunk with a specified name and shader source code to the Map. If an * element with the same name already exists, the element will be updated. * * @param {string} name - The name of the shader chunk. * @param {string} code - The shader source code. * @returns {this} The ShaderChunkMap instance. */ set(name: string, code: string): this; /** * Adds multiple shader chunks to the Map. This method accepts an object where the keys are the * names of the shader chunks and the values are the shader source code. If an element with the * same name already exists, the element will be updated. * * @param {Object} object - Object containing shader chunks. * @param {boolean} override - Whether to override existing shader chunks. Defaults to true. * @returns {this} The ShaderChunkMap instance. */ add(object: any, override?: boolean): this; /** * Removes a shader chunk by name from the Map. If the element does not exist, no action is * taken. * * @param {string} name - The name of the shader chunk to remove. * @returns {boolean} True if an element in the Map existed and has been removed, or false if the * element does not exist. */ delete(name: string): boolean; markDirty(): void; _dirty: boolean; isDirty(): boolean; resetDirty(): void; get key(): string; /** * Copy the shader chunk map. * * @param {ShaderChunkMap} source - The instance to copy. * @returns {this} The destination instance. * @ignore */ copy(source: ShaderChunkMap): this; } /** * A collection of GLSL and WGSL shader chunks, used to generate shaders. * * @category Graphics */ declare class ShaderChunks { /** * Static map of chunk validations shared by all instances. * * @type {Map} * @private */ private static _validations; /** * Returns a shader chunks map for the given device and shader language. * * @param {GraphicsDevice} device - The graphics device. * @param {string} shaderLanguage - The shader language to use (GLSL or WGSL). * @returns {ShaderChunkMap} The shader chunks for the specified language. */ static get(device: GraphicsDevice, shaderLanguage?: string): ShaderChunkMap; /** * Register a validation for a shader chunk. When the chunk is set, the validation will be * executed. This is useful for deprecation warnings or content validation. * * @param {string} name - The name of the shader chunk. * @param {ChunkValidation} options - Validation options. * @example * // Deprecate an existing chunk - only warn when overridden with non-default code * import { myChunksGLSL } from './glsl/collections/my-chunks-glsl.js'; * import { myChunksWGSL } from './wgsl/collections/my-chunks-wgsl.js'; * * ShaderChunks.registerValidation('myChunkVS', { * message: 'myChunkVS is deprecated. Use newChunkVS instead.', * defaultCodeGLSL: myChunksGLSL.myChunkVS, * defaultCodeWGSL: myChunksWGSL.myChunkVS * }); * @example * // Warn for a removed chunk - any attempt to use it triggers warning * ShaderChunks.registerValidation('removedChunkVS', { * message: 'removedChunkVS has been removed. Use replacementChunkVS instead.' * }); * @example * // Use callback for custom validation logic * ShaderChunks.registerValidation('myChunkVS', { * callback: (name, code) => { * if (code.includes('gl_FragColor')) { * Debug.error(`Chunk ${name} uses deprecated gl_FragColor. Use pcFragColor instead.`); * } * } * }); * @ignore */ static registerValidation(name: string, options: ChunkValidation): void; /** * A map of shader chunks for GLSL. * * @type {ShaderChunkMap} * @ignore */ glsl: ShaderChunkMap; /** * A map of shader chunks for WGSL. * * @type {ShaderChunkMap} * @ignore */ wgsl: ShaderChunkMap; /** * Specifies the API version of the shader chunks. * * This should be a string containing the current engine major and minor version (e.g., '2.8' * for engine v2.8.1) and ensures compatibility with the current engine version. When providing * custom shader chunks, set this to the latest supported version. If a future engine release no * longer supports the specified version, a warning will be issued. In that case, update your * shader chunks to match the new format and set this to the latest version accordingly. */ version: string; get useWGSL(): boolean; get key(): string; isDirty(): boolean; resetDirty(): void; /** * Copy the shader chunks. * * @param {ShaderChunks} source - The instance to copy. * @returns {ShaderChunks} The destination instance. * @ignore */ copy(source: ShaderChunks): ShaderChunks; } /** * @import { ShaderChunks } from '../shader-chunks.js'; */ /** * The lit shader options determines how the lit-shader gets generated. It specifies a set of * parameters which triggers different fragment and vertex shader generation in the backend. * * You do not create one. The engine fills a LitShaderOptions from the material and scene state * each time a {@link StandardMaterial} needs a shader variant, and every distinct set of values * produces a distinct compiled shader. Developers rarely need to touch it: the material properties * such as `useFog`, `useLighting` and `useSkybox` on {@link StandardMaterial} cover the usual * cases, and the values here mirror them together with the scene state. It is exposed for the * rare case of customizing shader generation through {@link StandardMaterial#onUpdateShader}. * * @category Graphics */ declare class LitShaderOptions { hasTangents: boolean; /** * Custom shader chunks that will replace default ones. * * @type {ShaderChunks|null} */ shaderChunks: ShaderChunks | null; pass: number; /** * Enable alpha testing. See {@link Material#alphaTest}. */ alphaTest: boolean; /** * The value of {@link Material#blendType}. * * @type {number} */ blendType: number; separateAmbient: boolean; screenSpace: boolean; skin: boolean; batch: boolean; /** * If hardware instancing compatible shader should be generated. Transform is read from * per-instance {@link VertexBuffer} instead of shader's uniforms. */ useInstancing: boolean; /** * If morphing code should be generated to morph positions. */ useMorphPosition: boolean; /** * If morphing code should be generated to morph normals. */ useMorphNormal: boolean; useMorphTextureBasedInt: boolean; nineSlicedMode: number; clusteredLightingEnabled: boolean; clusteredLightingCookiesEnabled: boolean; clusteredLightingShadowsEnabled: boolean; clusteredLightingShadowType: number; clusteredLightingAreaLightsEnabled: boolean; vertexColors: boolean; useVertexColorGamma: boolean; lightMapEnabled: boolean; dirLightMapEnabled: boolean; useHeights: boolean; useNormals: boolean; useClearCoatNormals: boolean; useAo: boolean; diffuseMapEnabled: boolean; pixelSnap: boolean; /** * If ambient spherical harmonics are used. Ambient SH replace prefiltered cubemap ambient on * certain platforms (mostly Android) for performance reasons. */ ambientSH: boolean; /** * Apply SSAO during the lighting. */ ssao: boolean; /** * The value of {@link StandardMaterial#twoSidedLighting}. */ twoSidedLighting: boolean; /** * The value of {@link StandardMaterial#occludeDirect}. */ occludeDirect: boolean; /** * The value of {@link StandardMaterial#occludeSpecular}. */ occludeSpecular: number; /** * Defines if {@link StandardMaterial#occludeSpecularIntensity} constant should affect specular * occlusion. */ occludeSpecularFloat: boolean; useMsdf: boolean; msdfTextAttribute: boolean; /** * Enable alpha to coverage. See {@link Material#alphaToCoverage}. */ alphaToCoverage: boolean; /** * Enable specular fade. See {@link StandardMaterial#opacityFadesSpecular}. */ opacityFadesSpecular: boolean; /** * Enable opacity dithering. See {@link StandardMaterial#opacityDither}. * * @type {string} */ opacityDither: string; /** * Enable opacity shadow dithering. See {@link StandardMaterial#opacityShadowDither}. * * @type {string} */ opacityShadowDither: string; /** * The value of {@link StandardMaterial#cubeMapProjection}. */ cubeMapProjection: number; /** * If any specular or reflections are needed at all. */ useSpecular: boolean; useSpecularityFactor: boolean; enableGGXSpecular: boolean; /** * The value of {@link StandardMaterial#fresnelModel}. */ fresnelModel: number; /** * If refraction is used. */ useRefraction: boolean; useClearCoat: boolean; useSheen: boolean; useIridescence: boolean; /** * The value of {@link StandardMaterial#useMetalness}. */ useMetalness: boolean; useDynamicRefraction: boolean; dispersion: boolean; /** * The type of fog being applied in the shader. See {@link Scene#fog} for the list of possible * values. * * @type {string} */ fog: string; /** * The type of gamma correction being applied in the shader. See * {@link CameraComponent#gammaCorrection} for the list of possible values. * * @type {number} */ gamma: number; /** * The type of tone mapping being applied in the shader. See {@link CameraComponent#toneMapping} * for the list of possible values. */ toneMap: number; /** * One of REFLECTIONSRC_*** constants. * * @type {string} */ reflectionSource: string; reflectionEncoding: any; reflectionCubemapEncoding: any; /** * One of "ambientSH", "envAtlas", "constant". */ ambientSource: string; ambientEncoding: any; /** * Skybox intensity factor. */ skyboxIntensity: number; /** * If cube map rotation is enabled. */ useCubeMapRotation: boolean; /** * If the environment chunks sample the scene environment, published by the renderer as * `scene_envAtlas` and `scene_skybox`, instead of the textures owned by the material * (`texture_envAtlas`, `texture_cubeMap`). */ useSceneEnv: boolean; lightMapWithoutAmbient: boolean; lights: any[]; noShadow: boolean; lightMaskDynamic: number; /** * Object containing a map of user defined vertex attributes to attached shader semantics. * * @type {Object} */ userAttributes: { [x: string]: string; }; /** * Make vLinearDepth available in the shader. */ linearDepth: boolean; /** * Shader outputs the accumulated shadow value, used for shadow catcher materials. */ shadowCatcher: boolean; } /** * The standard material options define a set of options used to control the shader frontend shader * generation, such as textures, tints and multipliers. * * @category Graphics */ declare class StandardMaterialOptions { /** * The set of defines used to generate the shader. * * @type {Map} */ defines: Map; /** @ignore */ useDualSourceBlending: boolean; /** * If UV1 (second set of texture coordinates) is required in the shader. Will be declared as * "vUv1" and passed to the fragment shader. */ forceUv1: boolean; /** * Defines if {@link StandardMaterial#metalness} constant should affect metalness value. */ metalnessTint: boolean; /** * Defines if {@link StandardMaterial#gloss} constant should affect glossiness value. */ glossTint: boolean; emissiveEncoding: string; lightMapEncoding: string; /** * True if the lightmap comes from the mesh instance rather than from the material, and so is * sampled from the mesh instance's own texture slot. See {@link Lightmapper}. */ useInstanceLightMap: boolean; vertexColorGamma: boolean; /** * If normal map contains X in RGB, Y in Alpha, and Z must be reconstructed. */ packedNormal: boolean; /** * If normal detail map contains X in RGB, Y in Alpha, and Z must be reconstructed. */ normalDetailPackedNormal: boolean; /** * If normal clear coat map contains X in RGB, Y in Alpha, and Z must be reconstructed. */ clearCoatPackedNormal: boolean; /** * Invert the gloss channel. */ glossInvert: boolean; /** * Invert the sheen gloss channel. */ sheenGlossInvert: boolean; /** * Invert the clearcoat gloss channel. */ clearCoatGlossInvert: boolean; /** * True to include AO variables even if AO is not used, which allows SSAO to be used in the lit shader. */ useAO: boolean; /** * Storage for the options for lit the shader and material. * * @type {LitShaderOptions} */ litOptions: LitShaderOptions; get pass(): number; } /** * Internal camera shader parameters, used to generate and use matching shaders. * * @ignore */ declare class CameraShaderParams { /** @private */ private _gammaCorrection; /** @private */ private _toneMapping; /** @private */ private _srgbRenderTarget; /** @private */ private _ssaoEnabled; /** @private */ private _fog; /** @private */ private _sceneDepthMapLinear; /** * True when each depth in the linear scene depth map is stored as a float bit-packed into an * RGBA8 texel, the encoding the producer of the map falls back to when float textures cannot be * rendered to. Only meaningful when {@link CameraShaderParams#sceneDepthMapLinear} is set. * * @private */ private _sceneDepthMapPacked; /** * True when the linear scene depth map holds a coverage weighted average of the reciprocals of the * depths, which a consumer inverts to recover the depth. This is how the scene pass accumulates a * depth the blended gaussian splats contribute to. A pixel nothing was rendered to holds the * reciprocal of the far clip the map was cleared to, and so reads back as the far clip itself. Only * meaningful when {@link CameraShaderParams#sceneDepthMapLinear} is set. * * @private */ private _sceneDepthMapReciprocal; /** * The names of the scene textures the scene pass renders alongside the scene color, in the order * of the color attachments they are rendered to - the name at index i goes to the attachment at * index i + 1, as attachment 0 is the scene color itself. Empty when the scene pass renders the * scene color alone. * * The render pass is what owns this, as only the passes rendering to a render target the scene * textures are attached to may write them - a camera's pass rendering the UI to the output render * target must not. It is mirrored here because shader generation is given no more than the camera * shader params, so this is how a material learns that its shader has to write the additional * attachments, and how those attachments take part in the shader variant key. * * That makes the value transient: {@link RenderPassForward} assigns it and restores the previous * value around each layer step it renders, in the same way it overrides the gamma correction and * the tone mapping. Outside of those draws the camera reads as rendering no scene textures. * * @type {string[]} * @private */ private _sceneTextures; /** * The hash of the rendering parameters, or undefined if the hash has not been computed yet. * * @type {number|undefined} * @private */ private _hash; /** * Content of this class relevant to shader generation, which is supplied as defines for the * shader. * * @type {Map} * @private */ private _defines; _definesDirty: boolean; /** * The hash of the rendering parameters. * * @type {number} * @ignore */ get hash(): number; get defines(): Map; markDirty(): void; set fog(type: string); get fog(): string; set ssaoEnabled(value: boolean); get ssaoEnabled(): boolean; set gammaCorrection(value: number); get gammaCorrection(): number; _gammaCorrectionAssigned: boolean; set toneMapping(value: number); get toneMapping(): number; set srgbRenderTarget(value: boolean); get srgbRenderTarget(): boolean; set sceneDepthMapLinear(value: boolean); get sceneDepthMapLinear(): boolean; set sceneDepthMapPacked(value: boolean); get sceneDepthMapPacked(): boolean; set sceneDepthMapReciprocal(value: boolean); get sceneDepthMapReciprocal(): boolean; /** * Sets the names of the scene textures the scene pass renders alongside the scene color, for * example `['depth']`. Their order is the order of the color attachments they are rendered to, * so the name at index i is written to the attachment at index i + 1. Assign an empty array when * the scene pass renders the scene color alone. This is assigned by the render pass rendering * them, for the duration of its draws only - see the note on the backing field. * * Each name generates a pair of shader defines, following the same naming as the shader passes: * `'depth'` supplies `SCENE_TEXTURE_DEPTH`, which enables the write, and * `{SCENE_TEXTURE_DEPTH_SLOT}`, which the sceneTexturesPS chunk substitutes into the name of the * output it writes. A name can only contain letters, numbers and underscores, and start with a * letter. * * @type {string[]} */ set sceneTextures(value: string[]); get sceneTextures(): string[]; /** * Returns {@link GAMMA_SRGB} if the shader code needs to output gamma corrected color, otherwise * returns {@link GAMMA_NONE}. * * @type {number} * @ignore */ get shaderOutputGamma(): number; } /** * Class responsible for management of shader passes, associated with a device. * * @ignore */ declare class ShaderPass { /** * Get access to the shader pass instance for the specified device. * * @param {GraphicsDevice} device - The graphics device. * @returns { ShaderPass } The shader pass instance for the specified device. */ static get(device: GraphicsDevice): ShaderPass; /** * Allocated shader passes, map of a shader pass name to info. * * @type {Map} */ passesNamed: Map; /** * Allocated shader passes, indexed by their index. * * @type {Array} */ passesIndexed: Array; /** Next available index */ nextIndex: number; /** * Allocates a shader pass with the specified name and options. * * @param {string} name - A name of the shader pass. * @param {object} [options] - Options for the shader pass, which are added as properties to the * shader pass info. * @returns {ShaderPassInfo} The allocated shader pass info. */ allocate(name: string, options?: object): ShaderPassInfo; /** * Return the shader pass info for the specified index. * * @param {number} index - The shader pass index. * @returns {ShaderPassInfo} - The shader pass info. */ getByIndex(index: number): ShaderPassInfo; getByName(name: any): ShaderPassInfo; } /** * Info about a shader pass. Shader pass is represented by a unique index and a name, and the * index is used to access the shader required for the pass, from an array stored in the * material or mesh instance. * * @ignore */ declare class ShaderPassInfo { /** * @param {string} name - The name, for example 'depth'. Must contain only letters, numbers, * and underscores, and start with a letter. * @param {number} index - Index from ShaderPass#nextIndex. * @param {object} [options] - Options for additional configuration of the shader pass. * @param {boolean} [options.isForward] - Whether the pass is forward. * @param {boolean} [options.isShadow] - Whether the pass is shadow. * @param {number} [options.lightType] - Type of light, for example `LIGHTTYPE_DIRECTIONAL`. * @param {number} [options.shadowType] - Type of shadow, for example `SHADOW_PCF3_32F`. */ constructor(name: string, index: number, options?: { isForward?: boolean; isShadow?: boolean; lightType?: number; shadowType?: number; }); /** @type {number} */ index: number; /** @type {string} */ name: string; /** @type {Map} */ defines: Map; buildShaderDefines(): void; } /** * A render pass implementing grab of a color buffer. * * @ignore */ declare class FramePassColorGrab extends FramePass { colorRenderTarget: any; /** * The source render target to grab the color from. * * @type {RenderTarget|null} */ source: RenderTarget | null; shouldReallocate(targetRT: any, sourceTexture: any, sourceFormat: any): boolean; allocateRenderTarget(renderTarget: any, sourceRenderTarget: any, device: any, format: any): any; releaseRenderTarget(rt: any): void; } /** * A render pass implementing grab of a depth buffer, used on WebGL 2 and WebGPU devices. * * @ignore */ declare class FramePassDepthGrab extends FramePass { constructor(device: any, camera: any); depthRenderTarget: any; camera: any; shouldReallocate(targetRT: any, sourceTexture: any): boolean; allocateRenderTarget(renderTarget: any, sourceRenderTarget: any, device: any, format: any, isDepth: any): any; releaseRenderTarget(rt: any): void; } /** * Fog parameters. * * @category Graphics */ declare class FogParams { /** * The type of fog used by the scene. Can be: * * - {@link FOG_NONE} * - {@link FOG_LINEAR} * - {@link FOG_EXP} * - {@link FOG_EXP2} * * Defaults to {@link FOG_NONE}. * * @type {string} */ type: string; /** * The color of the fog (if enabled), specified in sRGB color space. Defaults to black (0, 0, 0). */ color: Color; /** * The density of the fog (if enabled). This property is only valid if the fog property is set * to {@link FOG_EXP} or {@link FOG_EXP2}. Defaults to 0. */ density: number; /** * The distance from the viewpoint where linear fog begins. This property is only valid if the * fog property is set to {@link FOG_LINEAR}. Defaults to 1. */ start: number; /** * The distance from the viewpoint where linear fog reaches its maximum. This property is only * valid if the fog property is set to {@link FOG_LINEAR}. Defaults to 1000. */ end: number; } /** * A 4-dimensional vector. Vec4 is commonly used to represent homogeneous coordinates or shader * uniforms requiring four components. * * Operations follow one convention throughout the math classes: a method that modifies the vector * it is called on returns it, so calls can be chained and nothing is allocated, while queries such * as {@link length} and {@link dot} return a number. Two-operand forms such as {@link add2} and * {@link mul2} write the result of `lhs op rhs` into `this`, and it is safe for `this` to also be * one of the operands. Use {@link clone} for an independent copy and {@link copy} to overwrite one * vector with another. * * The static constants {@link ZERO}, {@link HALF} and {@link ONE} are frozen shared instances: read * them freely, but writing to one throws. * * @example * // Interpolate between two 4-component values into a third, without allocating * const from = new Vec4(0, 0, 0, 0); * const to = new Vec4(1, 1, 1, 1); * const result = new Vec4(); * result.lerp(from, to, 0.25); // result is now [0.25, 0.25, 0.25, 0.25] * @category Math */ declare class Vec4 { /** * A constant vector set to [0, 0, 0, 0]. * * @type {Vec4} * @readonly */ static readonly ZERO: Vec4; /** * A constant vector set to [0.5, 0.5, 0.5, 0.5]. * * @type {Vec4} * @readonly */ static readonly HALF: Vec4; /** * A constant vector set to [1, 1, 1, 1]. * * @type {Vec4} * @readonly */ static readonly ONE: Vec4; /** * Creates a new Vec4 instance. * * @overload * @param {number} [x] - The x value. Defaults to 0. * @param {number} [y] - The y value. Defaults to 0. * @param {number} [z] - The z value. Defaults to 0. * @param {number} [w] - The w value. Defaults to 0. * @example * const v1 = new Vec4(); // defaults to 0, 0, 0, 0 * const v2 = new Vec4(1, 2, 3, 4); */ constructor(x?: number, y?: number, z?: number, w?: number); /** * Creates a new Vec4 instance. * * @overload * @param {number[]} arr - The array to set the vector values from. * @example * const v = new Vec4([1, 2, 3, 4]); */ constructor(arr: number[]); /** * The first component of the vector. * * @type {number} */ x: number; /** * The second component of the vector. * * @type {number} */ y: number; /** * The third component of the vector. * * @type {number} */ z: number; /** * The fourth component of the vector. * * @type {number} */ w: number; /** * Adds a 4-dimensional vector to another in place. * * @param {Vec4} rhs - The vector to add to the specified vector. * @returns {Vec4} Self for chaining. * @example * const a = new Vec4(10, 10, 10, 10); * const b = new Vec4(20, 20, 20, 20); * * a.add(b); * * // Outputs [30, 30, 30, 30] * console.log("The result of the addition is: " + a.toString()); */ add(rhs: Vec4): Vec4; /** * Adds two 4-dimensional vectors together and returns the result. * * @param {Vec4} lhs - The first vector operand for the addition. * @param {Vec4} rhs - The second vector operand for the addition. * @returns {Vec4} Self for chaining. * @example * const a = new Vec4(10, 10, 10, 10); * const b = new Vec4(20, 20, 20, 20); * const r = new Vec4(); * * r.add2(a, b); * // Outputs [30, 30, 30, 30] * * console.log("The result of the addition is: " + r.toString()); */ add2(lhs: Vec4, rhs: Vec4): Vec4; /** * Adds a number to each element of a vector. * * @param {number} scalar - The number to add. * @returns {Vec4} Self for chaining. * @example * const vec = new Vec4(3, 4, 5, 6); * * vec.addScalar(2); * * // Outputs [5, 6, 7, 8] * console.log("The result of the addition is: " + vec.toString()); */ addScalar(scalar: number): Vec4; /** * Adds a 4-dimensional vector scaled by scalar value. Does not modify the vector being added. * * @param {Vec4} rhs - The vector to add to the specified vector. * @param {number} scalar - The number to multiply the added vector with. * @returns {Vec4} Self for chaining. * @example * const vec = new Vec4(1, 2, 3, 4); * * vec.addScaled(Vec4.ONE, 2); * * // Outputs [3, 4, 5, 6] * console.log("The result of the addition is: " + vec.toString()); */ addScaled(rhs: Vec4, scalar: number): Vec4; /** * Returns an identical copy of the specified 4-dimensional vector. * * @returns {this} A 4-dimensional vector containing the result of the cloning. * @example * const v = new Vec4(10, 20, 30, 40); * const vclone = v.clone(); * console.log("The result of the cloning is: " + vclone.toString()); */ clone(): this; /** * Copies the contents of a source 4-dimensional vector to a destination 4-dimensional vector. * * @param {Vec4} rhs - A vector to copy to the specified vector. * @returns {Vec4} Self for chaining. * @example * const src = new Vec4(10, 20, 30, 40); * const dst = new Vec4(); * * dst.copy(src); * * console.log("The two vectors are " + (dst.equals(src) ? "equal" : "different")); */ copy(rhs: Vec4): Vec4; /** * Divides a 4-dimensional vector by another in place. * * @param {Vec4} rhs - The vector to divide the specified vector by. * @returns {Vec4} Self for chaining. * @example * const a = new Vec4(4, 9, 16, 25); * const b = new Vec4(2, 3, 4, 5); * * a.div(b); * * // Outputs [2, 3, 4, 5] * console.log("The result of the division is: " + a.toString()); */ div(rhs: Vec4): Vec4; /** * Divides one 4-dimensional vector by another and writes the result to the specified vector. * * @param {Vec4} lhs - The dividend vector (the vector being divided). * @param {Vec4} rhs - The divisor vector (the vector dividing the dividend). * @returns {Vec4} Self for chaining. * @example * const a = new Vec4(4, 9, 16, 25); * const b = new Vec4(2, 3, 4, 5); * const r = new Vec4(); * * r.div2(a, b); * * // Outputs [2, 3, 4, 5] * console.log("The result of the division is: " + r.toString()); */ div2(lhs: Vec4, rhs: Vec4): Vec4; /** * Divides each element of a vector by a number. * * @param {number} scalar - The number to divide by. * @returns {Vec4} Self for chaining. * @example * const vec = new Vec4(3, 6, 9, 12); * * vec.divScalar(3); * * // Outputs [1, 2, 3, 4] * console.log("The result of the division is: " + vec.toString()); */ divScalar(scalar: number): Vec4; /** * Returns the result of a dot product operation performed on the two specified 4-dimensional * vectors. * * @param {Vec4} rhs - The second 4-dimensional vector operand of the dot product. * @returns {number} The result of the dot product operation. * @example * const v1 = new Vec4(5, 10, 20, 40); * const v2 = new Vec4(10, 20, 40, 80); * const v1dotv2 = v1.dot(v2); * console.log("The result of the dot product is: " + v1dotv2); */ dot(rhs: Vec4): number; /** * Reports whether two vectors are equal. * * @param {Vec4} rhs - The vector to compare to the specified vector. * @returns {boolean} True if the vectors are equal and false otherwise. * @example * const a = new Vec4(1, 2, 3, 4); * const b = new Vec4(5, 6, 7, 8); * console.log("The two vectors are " + (a.equals(b) ? "equal" : "different")); */ equals(rhs: Vec4): boolean; /** * Reports whether two vectors are equal using an absolute error tolerance. * * @param {Vec4} rhs - The vector to be compared against. * @param {number} [epsilon] - The maximum difference between each component of the two * vectors. Defaults to 1e-6. * @returns {boolean} True if the vectors are equal and false otherwise. * @example * const a = new Vec4(); * const b = new Vec4(); * console.log("The two vectors are approximately " + (a.equalsApprox(b, 1e-9) ? "equal" : "different")); */ equalsApprox(rhs: Vec4, epsilon?: number): boolean; /** * Returns the magnitude of the specified 4-dimensional vector. * * @returns {number} The magnitude of the specified 4-dimensional vector. * @example * const vec = new Vec4(3, 4, 0, 0); * const len = vec.length(); * // Outputs 5 * console.log("The length of the vector is: " + len); */ length(): number; /** * Returns the magnitude squared of the specified 4-dimensional vector. * * @returns {number} The magnitude squared of the specified 4-dimensional vector. * @example * const vec = new Vec4(3, 4, 0, 0); * const len = vec.lengthSq(); * // Outputs 25 * console.log("The length squared of the vector is: " + len); */ lengthSq(): number; /** * Returns the result of a linear interpolation between two specified 4-dimensional vectors. * * @param {Vec4} lhs - The 4-dimensional vector to interpolate from. * @param {Vec4} rhs - The 4-dimensional vector to interpolate to. * @param {number} alpha - The value controlling the point of interpolation. Between 0 and 1, * the linear interpolant will occur on a straight line between lhs and rhs. Outside of this * range, the linear interpolant will occur on a ray extrapolated from this line. * @returns {Vec4} Self for chaining. * @example * const a = new Vec4(0, 0, 0, 0); * const b = new Vec4(10, 10, 10, 10); * const r = new Vec4(); * * r.lerp(a, b, 0); // r is equal to a * r.lerp(a, b, 0.5); // r is 5, 5, 5, 5 * r.lerp(a, b, 1); // r is equal to b */ lerp(lhs: Vec4, rhs: Vec4, alpha: number): Vec4; /** * Multiplies a 4-dimensional vector to another in place. * * @param {Vec4} rhs - The 4-dimensional vector used as the second multiplicand of the operation. * @returns {Vec4} Self for chaining. * @example * const a = new Vec4(2, 3, 4, 5); * const b = new Vec4(4, 5, 6, 7); * * a.mul(b); * * // Outputs 8, 15, 24, 35 * console.log("The result of the multiplication is: " + a.toString()); */ mul(rhs: Vec4): Vec4; /** * Returns the result of multiplying the specified 4-dimensional vectors together. * * @param {Vec4} lhs - The 4-dimensional vector used as the first multiplicand of the operation. * @param {Vec4} rhs - The 4-dimensional vector used as the second multiplicand of the operation. * @returns {Vec4} Self for chaining. * @example * const a = new Vec4(2, 3, 4, 5); * const b = new Vec4(4, 5, 6, 7); * const r = new Vec4(); * * r.mul2(a, b); * * // Outputs 8, 15, 24, 35 * console.log("The result of the multiplication is: " + r.toString()); */ mul2(lhs: Vec4, rhs: Vec4): Vec4; /** * Multiplies each element of a vector by a number. * * @param {number} scalar - The number to multiply by. * @returns {Vec4} Self for chaining. * @example * const vec = new Vec4(3, 6, 9, 12); * * vec.mulScalar(3); * * // Outputs [9, 18, 27, 36] * console.log("The result of the multiplication is: " + vec.toString()); */ mulScalar(scalar: number): Vec4; /** * @deprecated Use Vec4#mulScalar instead. * @param {number} scalar - The number to multiply by. * @returns {Vec4} Self for chaining. * @ignore */ scale(scalar: number): Vec4; /** * Returns this 4-dimensional vector converted to a unit vector in place. If the vector has a * length of zero, the vector's elements will be set to zero. * * @param {Vec4} [src] - The vector to normalize. If not set, the operation is done in place. * @returns {Vec4} Self for chaining. * @example * const v = new Vec4(25, 0, 0, 0); * * v.normalize(); * * // Outputs 1, 0, 0, 0 * console.log("The result of the vector normalization is: " + v.toString()); */ normalize(src?: Vec4): Vec4; /** * Each element is set to the largest integer less than or equal to its value. * * @param {Vec4} [src] - The vector to floor. If not set, the operation is done in place. * @returns {Vec4} Self for chaining. * @example * const v = new Vec4(1.2, 3.9, 5.5, 7.8); * v.floor(); * // v is now [1, 3, 5, 7] */ floor(src?: Vec4): Vec4; /** * Each element is rounded up to the next largest integer. * * @param {Vec4} [src] - The vector to ceil. If not set, the operation is done in place. * @returns {Vec4} Self for chaining. * @example * const v = new Vec4(1.2, 3.1, 5.9, 7.4); * v.ceil(); * // v is now [2, 4, 6, 8] */ ceil(src?: Vec4): Vec4; /** * Each element is rounded up or down to the nearest integer. * * @param {Vec4} [src] - The vector to round. If not set, the operation is done in place. * @returns {Vec4} Self for chaining. * @example * const v = new Vec4(1.4, 3.6, 5.5, 7.2); * v.round(); * // v is now [1, 4, 6, 7] */ round(src?: Vec4): Vec4; /** * Each element is assigned a value from rhs parameter if it is smaller. * * @param {Vec4} rhs - The 4-dimensional vector used as the source of elements to compare to. * @returns {Vec4} Self for chaining. * @example * const a = new Vec4(5, 1, 7, 3); * const b = new Vec4(2, 8, 3, 9); * a.min(b); * // a is now [2, 1, 3, 3] */ min(rhs: Vec4): Vec4; /** * Each element is assigned a value from rhs parameter if it is larger. * * @param {Vec4} rhs - The 4-dimensional vector used as the source of elements to compare to. * @returns {Vec4} Self for chaining. * @example * const a = new Vec4(5, 1, 7, 3); * const b = new Vec4(2, 8, 3, 9); * a.max(b); * // a is now [5, 8, 7, 9] */ max(rhs: Vec4): Vec4; /** * Sets the specified 4-dimensional vector to the supplied numerical values. * * @param {number} x - The value to set on the first component of the vector. * @param {number} y - The value to set on the second component of the vector. * @param {number} z - The value to set on the third component of the vector. * @param {number} w - The value to set on the fourth component of the vector. * @returns {Vec4} Self for chaining. * @example * const v = new Vec4(); * v.set(5, 10, 20, 40); * * // Outputs 5, 10, 20, 40 * console.log("The result of the vector set is: " + v.toString()); */ set(x: number, y: number, z: number, w: number): Vec4; /** * Subtracts a 4-dimensional vector from another in place. * * @param {Vec4} rhs - The vector to subtract from the specified vector. * @returns {Vec4} Self for chaining. * @example * const a = new Vec4(10, 10, 10, 10); * const b = new Vec4(20, 20, 20, 20); * * a.sub(b); * * // Outputs [-10, -10, -10, -10] * console.log("The result of the subtraction is: " + a.toString()); */ sub(rhs: Vec4): Vec4; /** * Subtracts two 4-dimensional vectors from one another and returns the result. * * @param {Vec4} lhs - The first vector operand for the subtraction. * @param {Vec4} rhs - The second vector operand for the subtraction. * @returns {Vec4} Self for chaining. * @example * const a = new Vec4(10, 10, 10, 10); * const b = new Vec4(20, 20, 20, 20); * const r = new Vec4(); * * r.sub2(a, b); * * // Outputs [-10, -10, -10, -10] * console.log("The result of the subtraction is: " + r.toString()); */ sub2(lhs: Vec4, rhs: Vec4): Vec4; /** * Subtracts a number from each element of a vector. * * @param {number} scalar - The number to subtract. * @returns {Vec4} Self for chaining. * @example * const vec = new Vec4(3, 4, 5, 6); * * vec.subScalar(2); * * // Outputs [1, 2, 3, 4] * console.log("The result of the subtraction is: " + vec.toString()); */ subScalar(scalar: number): Vec4; /** * Set the values of the vector from an array. * * @param {number[]|ArrayBufferView} arr - The array to set the vector values from. * @param {number} [offset] - The zero-based index at which to start copying elements from the * array. Default is 0. * @returns {Vec4} Self for chaining. * @example * const v = new Vec4(); * v.fromArray([20, 10, 5, 0]); * // v is set to [20, 10, 5, 0] */ fromArray(arr: number[] | ArrayBufferView, offset?: number): Vec4; /** * Converts the vector to string form. * * @returns {string} The vector in string form. * @example * const v = new Vec4(20, 10, 5, 0); * // Outputs [20, 10, 5, 0] * console.log(v.toString()); */ toString(): string; /** * @overload * @param {number[]} [arr] - The array to populate with the vector's number * components. If not specified, a new array is created. * @param {number} [offset] - The zero-based index at which to start copying elements to the * array. Default is 0. * @returns {number[]} The vector as an array. */ toArray(arr?: number[], offset?: number): number[]; /** * @overload * @param {ArrayBufferView} arr - The array to populate with the vector's number * components. If not specified, a new array is created. * @param {number} [offset] - The zero-based index at which to start copying elements to the * array. Default is 0. * @returns {ArrayBufferView} The vector as an array. */ toArray(arr: ArrayBufferView, offset?: number): ArrayBufferView; } /** * A 3-dimensional vector. Vec3 is commonly used to represent 3D positions, directions, Euler angles * or scales. * * Operations follow one convention throughout the math classes: a method that modifies the vector * it is called on returns it, so calls can be chained and nothing is allocated, while queries such * as {@link distance} and {@link dot} return a number. Two-operand forms such as {@link add2}, * {@link sub2} and {@link cross} write the result of `lhs op rhs` into `this`, and it is safe for * `this` to also be one of the operands. Use {@link clone} for an independent copy and {@link copy} * to overwrite one vector with another. * * The static constants such as {@link ZERO}, {@link UP} and {@link FORWARD} are frozen shared * instances: read them freely, but writing to one throws. Vectors returned by engine getters such * as {@link GraphNode#getPosition} are internal storage and should be treated as read-only; clone * them if you need to keep or modify the value. * * @example * // Move a point 5 units along a direction without allocating * const position = new Vec3(1, 2, 3); * const direction = new Vec3(0, 0, -1); * position.addScaled(direction, 5); // position is now [1, 2, -2] * @example * // Chain mutating operations; each returns the vector it was called on * const toTarget = new Vec3().sub2(target, origin).normalize(); * const distance = target.distance(origin); * @example * // Keep a copy of an entity's position, then modify it safely * const start = entity.getPosition().clone(); * start.y += 1; * @category Math */ declare class Vec3 { /** * A constant vector set to [0, 0, 0]. * * @type {Vec3} * @readonly */ static readonly ZERO: Vec3; /** * A constant vector set to [0.5, 0.5, 0.5]. * * @type {Vec3} * @readonly */ static readonly HALF: Vec3; /** * A constant vector set to [1, 1, 1]. * * @type {Vec3} * @readonly */ static readonly ONE: Vec3; /** * A constant vector set to [0, 1, 0]. * * @type {Vec3} * @readonly */ static readonly UP: Vec3; /** * A constant vector set to [0, -1, 0]. * * @type {Vec3} * @readonly */ static readonly DOWN: Vec3; /** * A constant vector set to [1, 0, 0]. * * @type {Vec3} * @readonly */ static readonly RIGHT: Vec3; /** * A constant vector set to [-1, 0, 0]. * * @type {Vec3} * @readonly */ static readonly LEFT: Vec3; /** * A constant vector set to [0, 0, -1]. * * @type {Vec3} * @readonly */ static readonly FORWARD: Vec3; /** * A constant vector set to [0, 0, 1]. * * @type {Vec3} * @readonly */ static readonly BACK: Vec3; /** * Creates a new Vec3 instance. * * @overload * @param {number} [x] - The x value. Defaults to 0. * @param {number} [y] - The y value. Defaults to 0. * @param {number} [z] - The z value. Defaults to 0. * @example * const v1 = new Vec3(); // defaults to 0, 0, 0 * const v2 = new Vec3(1, 2, 3); */ constructor(x?: number, y?: number, z?: number); /** * Creates a new Vec3 instance. * * @overload * @param {number[]} arr - The array to set the vector values from. * @example * const v = new Vec3([1, 2, 3]); */ constructor(arr: number[]); /** * The first component of the vector. * * @type {number} */ x: number; /** * The second component of the vector. * * @type {number} */ y: number; /** * The third component of the vector. * * @type {number} */ z: number; /** * Adds a 3-dimensional vector to another in place. * * @param {Vec3} rhs - The vector to add to the specified vector. * @returns {Vec3} Self for chaining. * @example * const a = new Vec3(10, 10, 10); * const b = new Vec3(20, 20, 20); * * a.add(b); * * // Outputs [30, 30, 30] * console.log("The result of the addition is: " + a.toString()); */ add(rhs: Vec3): Vec3; /** * Adds two 3-dimensional vectors together and returns the result. * * @param {Vec3} lhs - The first vector operand for the addition. * @param {Vec3} rhs - The second vector operand for the addition. * @returns {Vec3} Self for chaining. * @example * const a = new Vec3(10, 10, 10); * const b = new Vec3(20, 20, 20); * const r = new Vec3(); * * r.add2(a, b); * // Outputs [30, 30, 30] * * console.log("The result of the addition is: " + r.toString()); */ add2(lhs: Vec3, rhs: Vec3): Vec3; /** * Adds a number to each element of a vector. * * @param {number} scalar - The number to add. * @returns {Vec3} Self for chaining. * @example * const vec = new Vec3(3, 4, 5); * * vec.addScalar(2); * * // Outputs [5, 6, 7] * console.log("The result of the addition is: " + vec.toString()); */ addScalar(scalar: number): Vec3; /** * Adds a 3-dimensional vector scaled by scalar value. Does not modify the vector being added. * * @param {Vec3} rhs - The vector to add to the specified vector. * @param {number} scalar - The number to multiply the added vector with. * @returns {Vec3} Self for chaining. * @example * const vec = new Vec3(1, 2, 3); * * vec.addScaled(Vec3.UP, 2); * * // Outputs [1, 4, 3] * console.log("The result of the addition is: " + vec.toString()); */ addScaled(rhs: Vec3, scalar: number): Vec3; /** * Returns an identical copy of the specified 3-dimensional vector. * * @returns {this} A 3-dimensional vector containing the result of the cloning. * @example * const v = new Vec3(10, 20, 30); * const vclone = v.clone(); * console.log("The result of the cloning is: " + vclone.toString()); */ clone(): this; /** * Copies the contents of a source 3-dimensional vector to a destination 3-dimensional vector. * * @param {Vec3} rhs - A vector to copy to the specified vector. * @returns {Vec3} Self for chaining. * @example * const src = new Vec3(10, 20, 30); * const dst = new Vec3(); * * dst.copy(src); * * console.log("The two vectors are " + (dst.equals(src) ? "equal" : "different")); */ copy(rhs: Vec3): Vec3; /** * Returns the result of a cross product operation performed on the two specified 3-dimensional * vectors. * * @param {Vec3} lhs - The first 3-dimensional vector operand of the cross product. * @param {Vec3} rhs - The second 3-dimensional vector operand of the cross product. * @returns {Vec3} Self for chaining. * @example * const back = new Vec3().cross(Vec3.RIGHT, Vec3.UP); * * // Prints the Z axis (i.e. [0, 0, 1]) * console.log("The result of the cross product is: " + back.toString()); */ cross(lhs: Vec3, rhs: Vec3): Vec3; /** * Returns the distance between the two specified 3-dimensional vectors. * * @param {Vec3} rhs - The second 3-dimensional vector to test. * @returns {number} The distance between the two vectors. * @example * const v1 = new Vec3(5, 10, 20); * const v2 = new Vec3(10, 20, 40); * const d = v1.distance(v2); * console.log("The distance between v1 and v2 is: " + d); */ distance(rhs: Vec3): number; /** * Returns the squared distance between the two specified 3-dimensional vectors. * * @param {Vec3} rhs - The second 3-dimensional vector to test. * @returns {number} The squared distance between the two vectors. * @example * const v1 = new Vec3(5, 10, 20); * const v2 = new Vec3(10, 20, 40); * const d = v1.distanceSq(v2); * console.log("The squared distance between v1 and v2 is: " + d); */ distanceSq(rhs: Vec3): number; /** * Divides a 3-dimensional vector by another in place. * * @param {Vec3} rhs - The vector to divide the specified vector by. * @returns {Vec3} Self for chaining. * @example * const a = new Vec3(4, 9, 16); * const b = new Vec3(2, 3, 4); * * a.div(b); * * // Outputs [2, 3, 4] * console.log("The result of the division is: " + a.toString()); */ div(rhs: Vec3): Vec3; /** * Divides one 3-dimensional vector by another and writes the result to the specified vector. * * @param {Vec3} lhs - The dividend vector (the vector being divided). * @param {Vec3} rhs - The divisor vector (the vector dividing the dividend). * @returns {Vec3} Self for chaining. * @example * const a = new Vec3(4, 9, 16); * const b = new Vec3(2, 3, 4); * const r = new Vec3(); * * r.div2(a, b); * * // Outputs [2, 3, 4] * console.log("The result of the division is: " + r.toString()); */ div2(lhs: Vec3, rhs: Vec3): Vec3; /** * Divides each element of a vector by a number. * * @param {number} scalar - The number to divide by. * @returns {Vec3} Self for chaining. * @example * const vec = new Vec3(3, 6, 9); * * vec.divScalar(3); * * // Outputs [1, 2, 3] * console.log("The result of the division is: " + vec.toString()); */ divScalar(scalar: number): Vec3; /** * Returns the result of a dot product operation performed on the two specified 3-dimensional * vectors. * * @param {Vec3} rhs - The second 3-dimensional vector operand of the dot product. * @returns {number} The result of the dot product operation. * @example * const v1 = new Vec3(5, 10, 20); * const v2 = new Vec3(10, 20, 40); * const v1dotv2 = v1.dot(v2); * console.log("The result of the dot product is: " + v1dotv2); */ dot(rhs: Vec3): number; /** * Reports whether two vectors are equal. * * @param {Vec3} rhs - The vector to compare to the specified vector. * @returns {boolean} True if the vectors are equal and false otherwise. * @example * const a = new Vec3(1, 2, 3); * const b = new Vec3(4, 5, 6); * console.log("The two vectors are " + (a.equals(b) ? "equal" : "different")); */ equals(rhs: Vec3): boolean; /** * Reports whether two vectors are equal using an absolute error tolerance. * * @param {Vec3} rhs - The vector to be compared against. * @param {number} [epsilon] - The maximum difference between each component of the two * vectors. Defaults to 1e-6. * @returns {boolean} True if the vectors are equal and false otherwise. * @example * const a = new Vec3(); * const b = new Vec3(); * console.log("The two vectors are approximately " + (a.equalsApprox(b, 1e-9) ? "equal" : "different")); */ equalsApprox(rhs: Vec3, epsilon?: number): boolean; /** * Returns the magnitude of the specified 3-dimensional vector. * * @returns {number} The magnitude of the specified 3-dimensional vector. * @example * const vec = new Vec3(3, 4, 0); * const len = vec.length(); * // Outputs 5 * console.log("The length of the vector is: " + len); */ length(): number; /** * Returns the magnitude squared of the specified 3-dimensional vector. * * @returns {number} The magnitude squared of the specified 3-dimensional vector. * @example * const vec = new Vec3(3, 4, 0); * const len = vec.lengthSq(); * // Outputs 25 * console.log("The length squared of the vector is: " + len); */ lengthSq(): number; /** * Returns the result of a linear interpolation between two specified 3-dimensional vectors. * * @param {Vec3} lhs - The 3-dimensional vector to interpolate from. * @param {Vec3} rhs - The 3-dimensional vector to interpolate to. * @param {number} alpha - The value controlling the point of interpolation. Between 0 and 1, * the linear interpolant will occur on a straight line between lhs and rhs. Outside of this * range, the linear interpolant will occur on a ray extrapolated from this line. * @returns {Vec3} Self for chaining. * @example * const a = new Vec3(0, 0, 0); * const b = new Vec3(10, 10, 10); * const r = new Vec3(); * * r.lerp(a, b, 0); // r is equal to a * r.lerp(a, b, 0.5); // r is 5, 5, 5 * r.lerp(a, b, 1); // r is equal to b */ lerp(lhs: Vec3, rhs: Vec3, alpha: number): Vec3; /** * Multiplies a 3-dimensional vector to another in place. * * @param {Vec3} rhs - The 3-dimensional vector used as the second multiplicand of the operation. * @returns {Vec3} Self for chaining. * @example * const a = new Vec3(2, 3, 4); * const b = new Vec3(4, 5, 6); * * a.mul(b); * * // Outputs [8, 15, 24] * console.log("The result of the multiplication is: " + a.toString()); */ mul(rhs: Vec3): Vec3; /** * Returns the result of multiplying the specified 3-dimensional vectors together. * * @param {Vec3} lhs - The 3-dimensional vector used as the first multiplicand of the operation. * @param {Vec3} rhs - The 3-dimensional vector used as the second multiplicand of the operation. * @returns {Vec3} Self for chaining. * @example * const a = new Vec3(2, 3, 4); * const b = new Vec3(4, 5, 6); * const r = new Vec3(); * * r.mul2(a, b); * * // Outputs [8, 15, 24] * console.log("The result of the multiplication is: " + r.toString()); */ mul2(lhs: Vec3, rhs: Vec3): Vec3; /** * Multiplies each element of a vector by a number. * * @param {number} scalar - The number to multiply by. * @returns {Vec3} Self for chaining. * @example * const vec = new Vec3(3, 6, 9); * * vec.mulScalar(3); * * // Outputs [9, 18, 27] * console.log("The result of the multiplication is: " + vec.toString()); */ mulScalar(scalar: number): Vec3; /** * @deprecated Use Vec3#mulScalar instead. * @param {number} scalar - The number to multiply by. * @returns {Vec3} Self for chaining. * @ignore */ scale(scalar: number): Vec3; /** * Returns this 3-dimensional vector converted to a unit vector in place. If the vector has a * length of zero, the vector's elements will be set to zero. * * @param {Vec3} [src] - The vector to normalize. If not set, the operation is done in place. * @returns {Vec3} Self for chaining. * @example * const v = new Vec3(25, 0, 0); * * v.normalize(); * * // Outputs [1, 0, 0] * console.log("The result of the vector normalization is: " + v.toString()); */ normalize(src?: Vec3): Vec3; /** * Each element is set to the largest integer less than or equal to its value. * * @param {Vec3} [src] - The vector to floor. If not set, the operation is done in place. * @returns {Vec3} Self for chaining. * @example * const v = new Vec3(1.2, 3.9, 5.5); * v.floor(); * // v is now [1, 3, 5] */ floor(src?: Vec3): Vec3; /** * Each element is rounded up to the next largest integer. * * @param {Vec3} [src] - The vector to ceil. If not set, the operation is done in place. * @returns {Vec3} Self for chaining. * @example * const v = new Vec3(1.2, 3.1, 5.9); * v.ceil(); * // v is now [2, 4, 6] */ ceil(src?: Vec3): Vec3; /** * Each element is rounded up or down to the nearest integer. * * @param {Vec3} [src] - The vector to round. If not set, the operation is done in place. * @returns {Vec3} Self for chaining. * @example * const v = new Vec3(1.4, 3.6, 5.5); * v.round(); * // v is now [1, 4, 6] */ round(src?: Vec3): Vec3; /** * Each element is assigned a value from rhs parameter if it is smaller. * * @param {Vec3} rhs - The 3-dimensional vector used as the source of elements to compare to. * @returns {Vec3} Self for chaining. * @example * const a = new Vec3(5, 1, 7); * const b = new Vec3(2, 8, 3); * a.min(b); * // a is now [2, 1, 3] */ min(rhs: Vec3): Vec3; /** * Each element is assigned a value from rhs parameter if it is larger. * * @param {Vec3} rhs - The 3-dimensional vector used as the source of elements to compare to. * @returns {Vec3} Self for chaining. * @example * const a = new Vec3(5, 1, 7); * const b = new Vec3(2, 8, 3); * a.max(b); * // a is now [5, 8, 7] */ max(rhs: Vec3): Vec3; /** * Projects this 3-dimensional vector onto the specified vector. * * @param {Vec3} rhs - The vector onto which the original vector will be projected on. * @returns {Vec3} Self for chaining. * @example * const v = new Vec3(5, 5, 5); * const normal = new Vec3(1, 0, 0); * * v.project(normal); * * // Outputs [5, 0, 0] * console.log("The result of the vector projection is: " + v.toString()); */ project(rhs: Vec3): Vec3; /** * Sets the specified 3-dimensional vector to the supplied numerical values. * * @param {number} x - The value to set on the first component of the vector. * @param {number} y - The value to set on the second component of the vector. * @param {number} z - The value to set on the third component of the vector. * @returns {Vec3} Self for chaining. * @example * const v = new Vec3(); * v.set(5, 10, 20); * * // Outputs [5, 10, 20] * console.log("The result of the vector set is: " + v.toString()); */ set(x: number, y: number, z: number): Vec3; /** * Subtracts a 3-dimensional vector from another in place. * * @param {Vec3} rhs - The vector to subtract from the specified vector. * @returns {Vec3} Self for chaining. * @example * const a = new Vec3(10, 10, 10); * const b = new Vec3(20, 20, 20); * * a.sub(b); * * // Outputs [-10, -10, -10] * console.log("The result of the subtraction is: " + a.toString()); */ sub(rhs: Vec3): Vec3; /** * Subtracts two 3-dimensional vectors from one another and returns the result. * * @param {Vec3} lhs - The first vector operand for the subtraction. * @param {Vec3} rhs - The second vector operand for the subtraction. * @returns {Vec3} Self for chaining. * @example * const a = new Vec3(10, 10, 10); * const b = new Vec3(20, 20, 20); * const r = new Vec3(); * * r.sub2(a, b); * * // Outputs [-10, -10, -10] * console.log("The result of the subtraction is: " + r.toString()); */ sub2(lhs: Vec3, rhs: Vec3): Vec3; /** * Subtracts a number from each element of a vector. * * @param {number} scalar - The number to subtract. * @returns {Vec3} Self for chaining. * @example * const vec = new Vec3(3, 4, 5); * * vec.subScalar(2); * * // Outputs [1, 2, 3] * console.log("The result of the subtraction is: " + vec.toString()); */ subScalar(scalar: number): Vec3; /** * Set the values of the vector from an array. * * @param {number[]|ArrayBufferView} arr - The array to set the vector values from. * @param {number} [offset] - The zero-based index at which to start copying elements from the * array. Default is 0. * @returns {Vec3} Self for chaining. * @example * const v = new Vec3(); * v.fromArray([20, 10, 5]); * // v is set to [20, 10, 5] */ fromArray(arr: number[] | ArrayBufferView, offset?: number): Vec3; /** * Converts the vector to string form. * * @returns {string} The vector in string form. * @example * const v = new Vec3(20, 10, 5); * // Outputs [20, 10, 5] * console.log(v.toString()); */ toString(): string; /** * @overload * @param {number[]} [arr] - The array to populate with the vector's number * components. If not specified, a new array is created. * @param {number} [offset] - The zero-based index at which to start copying elements to the * array. Default is 0. * @returns {number[]} The vector as an array. */ toArray(arr?: number[], offset?: number): number[]; /** * @overload * @param {ArrayBufferView} arr - The array to populate with the vector's number * components. If not specified, a new array is created. * @param {number} [offset] - The zero-based index at which to start copying elements to the * array. Default is 0. * @returns {ArrayBufferView} The vector as an array. */ toArray(arr: ArrayBufferView, offset?: number): ArrayBufferView; } /** * @import { Mat4 } from './mat4.js' */ /** * A quaternion representing rotation in 3D space. Quaternions are typically used to represent * rotations in 3D applications, offering advantages over Euler angles including no gimbal lock and * more efficient interpolation. * * A new Quat is the identity rotation. Build a rotation with {@link setFromEulerAngles}, * {@link setFromAxisAngle}, {@link setFromDirections} or {@link setFromMat4}, and read one back * with {@link getEulerAngles} or {@link getAxisAngle}. Angles are in degrees throughout. Rotations * combine by multiplication: `a.mul(b)` and `r.mul2(a, b)` both compute `a * b`, the same product * {@link Mat4} uses, and {@link transformVector} applies a rotation to a {@link Vec3}. Interpolate * with {@link slerp} for constant angular speed, or with the cheaper {@link lerp} when the two * rotations are close together. * * Methods modify the quaternion they are called on and return it for chaining. Use {@link clone} * for an independent copy and {@link copy} to overwrite. The static constants {@link IDENTITY} and * {@link ZERO} are frozen shared instances, and the quaternion returned by * {@link GraphNode#getRotation} is internal storage to be treated as read-only. * * @example * // Rotate an entity 90 degrees about the world Y axis * const rotation = new Quat().setFromAxisAngle(Vec3.UP, 90); * entity.setRotation(rotation); * @example * // Turn smoothly towards a target orientation each frame * const smoothed = new Quat().slerp(entity.getRotation(), targetRotation, 0.1); * entity.setRotation(smoothed); * @category Math */ declare class Quat { /** * A constant quaternion set to [0, 0, 0, 1] (the identity). Represents no rotation. * * @type {Quat} * @readonly */ static readonly IDENTITY: Quat; /** * A constant quaternion set to [0, 0, 0, 0]. * * @type {Quat} * @readonly */ static readonly ZERO: Quat; /** * Creates a new Quat instance. * * @overload * @param {number} [x] - The x value. Defaults to 0. * @param {number} [y] - The y value. Defaults to 0. * @param {number} [z] - The z value. Defaults to 0. * @param {number} [w] - The w value. Defaults to 1. * @example * const q1 = new Quat(); // defaults to 0, 0, 0, 1 * const q2 = new Quat(1, 2, 3, 4); */ constructor(x?: number, y?: number, z?: number, w?: number); /** * Creates a new Quat instance. * * @overload * @param {number[]} arr - The array to set the quaternion values from. * @example * const q = new Quat([1, 2, 3, 4]); */ constructor(arr: number[]); /** * The x component of the quaternion. * * @type {number} */ x: number; /** * The y component of the quaternion. * * @type {number} */ y: number; /** * The z component of the quaternion. * * @type {number} */ z: number; /** * The w component of the quaternion. * * @type {number} */ w: number; /** * Returns an identical copy of the specified quaternion. * * @returns {this} A new quaternion identical to this one. * @example * const q = new Quat(-0.11, -0.15, -0.46, 0.87); * const qclone = q.clone(); * * console.log("The result of the cloning is: " + qclone.toString()); */ clone(): this; /** * Conjugates a quaternion. * * @param {Quat} [src] - The quaternion to conjugate. If not set, the operation is done in place. * @returns {Quat} Self for chaining. * @example * const q = new Quat(1, 2, 3, 4); * q.conjugate(); * // q is now [-1, -2, -3, 4] * @ignore */ conjugate(src?: Quat): Quat; /** * Copies the contents of a source quaternion to a destination quaternion. * * @param {Quat} rhs - The quaternion to be copied. * @returns {Quat} Self for chaining. * @example * const src = new Quat(); * const dst = new Quat(); * dst.copy(src); * console.log("The two quaternions are " + (src.equals(dst) ? "equal" : "different")); */ copy(rhs: Quat): Quat; /** * Calculates the dot product of two quaternions. * * @param {Quat} other - The quaternion to calculate the dot product with. * @returns {number} The dot product of the two quaternions. * @example * const a = new Quat(1, 0, 0, 0); * const b = new Quat(0, 1, 0, 0); * console.log("Dot product: " + a.dot(b)); // Outputs 0 */ dot(other: Quat): number; /** * Reports whether two quaternions are equal. * * @param {Quat} rhs - The quaternion to be compared against. * @returns {boolean} True if the quaternions are equal and false otherwise. * @example * const a = new Quat(); * const b = new Quat(); * console.log("The two quaternions are " + (a.equals(b) ? "equal" : "different")); */ equals(rhs: Quat): boolean; /** * Reports whether two quaternions are equal using an absolute error tolerance. * * @param {Quat} rhs - The quaternion to be compared against. * @param {number} [epsilon] - The maximum difference between each component of the two * quaternions. Defaults to 1e-6. * @returns {boolean} True if the quaternions are equal and false otherwise. * @example * const a = new Quat(); * const b = new Quat(); * console.log("The two quaternions are approximately " + (a.equalsApprox(b, 1e-9) ? "equal" : "different")); */ equalsApprox(rhs: Quat, epsilon?: number): boolean; /** * Gets the rotation axis and angle for a given quaternion. If a quaternion is created with * `setFromAxisAngle`, this method will return the same values as provided in the original * parameter list OR functionally equivalent values. * * @param {Vec3} axis - The 3-dimensional vector to receive the axis of rotation. * @returns {number} Angle, in degrees, of the rotation. * @example * const q = new Quat(); * q.setFromAxisAngle(new Vec3(0, 1, 0), 90); * const v = new Vec3(); * const angle = q.getAxisAngle(v); * // Outputs 90 * console.log(angle); * // Outputs [0, 1, 0] * console.log(v.toString()); */ getAxisAngle(axis: Vec3): number; /** * Converts this quaternion to Euler angles, specified in degrees. The decomposition uses an * **intrinsic XYZ** order, representing the angles required to achieve the quaternion's * orientation by rotating sequentially: first around the X-axis, then around the newly * transformed Y-axis, and finally around the resulting Z-axis. * * @param {Vec3} [eulers] - An optional 3-dimensional vector to receive the calculated * Euler angles (output parameter). If not provided, a new Vec3 object will be allocated * and returned. * @returns {Vec3} The 3-dimensional vector holding the Euler angles in degrees. This will be * the same object passed in as the `eulers` parameter (if one was provided). * @example * const q = new Quat(); * q.setFromAxisAngle(Vec3.UP, 90); * const e = new Vec3(); * q.getEulerAngles(e); * // Outputs [0, 90, 0] * console.log(e.toString()); */ getEulerAngles(eulers?: Vec3): Vec3; /** * Generates the inverse of the specified quaternion. * * @param {Quat} [src] - The quaternion to invert. If not set, the operation is done in place. * @returns {Quat} Self for chaining. * @example * // Create a quaternion rotated 180 degrees around the y-axis * const rot = new Quat().setFromEulerAngles(0, 180, 0); * * // Invert in place * rot.invert(); */ invert(src?: Quat): Quat; /** * Returns the magnitude of the specified quaternion. * * @returns {number} The magnitude of the specified quaternion. * @example * const q = new Quat(0, 0, 0, 5); * const len = q.length(); * // Outputs 5 * console.log("The length of the quaternion is: " + len); */ length(): number; /** * Returns the magnitude squared of the specified quaternion. * * @returns {number} The magnitude squared of the quaternion. * @example * const q = new Quat(3, 4, 0, 0); * const lenSq = q.lengthSq(); * // Outputs 25 * console.log("The length squared of the quaternion is: " + lenSq); */ lengthSq(): number; /** * Performs a linear interpolation between two quaternions. The result of the interpolation * is written to the quaternion calling the function. * * @param {Quat} lhs - The quaternion to interpolate from. * @param {Quat} rhs - The quaternion to interpolate to. * @param {number} alpha - The unclamped interpolation factor. Values between 0 and 1 interpolate * between lhs and rhs; values outside this range extrapolate beyond them. * @returns {Quat} Self for chaining. * @example * const q1 = new Quat(-0.11, -0.15, -0.46, 0.87); * const q2 = new Quat(-0.21, -0.21, -0.67, 0.68); * * const result = new Quat(); * result.lerp(q1, q2, 0); // Return q1 * result.lerp(q1, q2, 0.5); // Return the midpoint interpolant * result.lerp(q1, q2, 1); // Return q2 */ lerp(lhs: Quat, rhs: Quat, alpha: number): Quat; /** * Returns the result of multiplying the specified quaternions together. * * @param {Quat} rhs - The quaternion used as the second multiplicand of the operation. * @returns {Quat} Self for chaining. * @example * const a = new Quat().setFromEulerAngles(0, 30, 0); * const b = new Quat().setFromEulerAngles(0, 60, 0); * * // a becomes a 90 degree rotation around the Y axis * // In other words, a = a * b * a.mul(b); * * console.log("The result of the multiplication is: " + a.toString()); */ mul(rhs: Quat): Quat; /** * Multiplies each element of a quaternion by a number. * * @param {number} scalar - The number to multiply by. * @param {Quat} [src] - The quaternion to scale. If not set, the operation is done in place. * @returns {Quat} Self for chaining. * @example * const q = new Quat(1, 2, 3, 4); * q.mulScalar(2); * // q is now [2, 4, 6, 8] */ mulScalar(scalar: number, src?: Quat): Quat; /** * Returns the result of multiplying the specified quaternions together. * * @param {Quat} lhs - The quaternion used as the first multiplicand of the operation. * @param {Quat} rhs - The quaternion used as the second multiplicand of the operation. * @returns {Quat} Self for chaining. * @example * const a = new Quat().setFromEulerAngles(0, 30, 0); * const b = new Quat().setFromEulerAngles(0, 60, 0); * const r = new Quat(); * * // r is set to a 90 degree rotation around the Y axis * // In other words, r = a * b * r.mul2(a, b); */ mul2(lhs: Quat, rhs: Quat): Quat; /** * Normalizes the specified quaternion. * * @param {Quat} [src] - The quaternion to normalize. If not set, the operation is done in place. * @returns {Quat} Self for chaining. * @example * const v = new Quat(0, 0, 0, 5); * v.normalize(); * // Outputs [0, 0, 0, 1] * console.log(v.toString()); */ normalize(src?: Quat): Quat; /** * Sets the specified quaternion to the supplied numerical values. * * @param {number} x - The x component of the quaternion. * @param {number} y - The y component of the quaternion. * @param {number} z - The z component of the quaternion. * @param {number} w - The w component of the quaternion. * @returns {Quat} Self for chaining. * @example * const q = new Quat(); * q.set(1, 0, 0, 0); * * // Outputs 1, 0, 0, 0 * console.log("The result of the quaternion set is: " + q.toString()); */ set(x: number, y: number, z: number, w: number): Quat; /** * Sets a quaternion from an angular rotation around an axis. * * @param {Vec3} axis - World space axis around which to rotate. Should be normalized. * @param {number} angle - Angle to rotate around the given axis in degrees. * @returns {Quat} Self for chaining. * @example * const q = new Quat(); * q.setFromAxisAngle(Vec3.UP, 90); */ setFromAxisAngle(axis: Vec3, angle: number): Quat; /** * Sets this quaternion to represent a rotation specified by Euler angles in degrees. * The rotation is applied using an **intrinsic XYZ** order: first around the X-axis, then * around the newly transformed Y-axis, and finally around the resulting Z-axis. * * @param {number|Vec3} ex - The angle to rotate around the X-axis in degrees, or a Vec3 * object containing the X, Y, and Z angles in degrees in its respective components (`ex.x`, * `ex.y`, `ex.z`). * @param {number} [ey] - The angle to rotate around the Y-axis in degrees. This parameter is * only used if `ex` is provided as a number. * @param {number} [ez] - The angle to rotate around the Z-axis in degrees. This parameter is * only used if `ex` is provided as a number. * @returns {Quat} The quaternion itself (this), now representing the orientation from the * specified XYZ Euler angles. Allows for method chaining. * @example * // Create a quaternion from 3 individual Euler angles (interpreted as X, Y, Z order) * const q1 = new Quat(); * q1.setFromEulerAngles(45, 90, 180); // 45 deg around X, then 90 deg around Y', then 180 deg around Z'' * console.log("From numbers:", q1.toString()); * @example * // Create the same quaternion from a Vec3 containing the angles (X, Y, Z) * const anglesVec = new Vec3(45, 90, 180); * const q2 = new Quat(); * q2.setFromEulerAngles(anglesVec); * console.log("From Vec3:", q2.toString()); // Should match q1 */ setFromEulerAngles(ex: number | Vec3, ey?: number, ez?: number): Quat; /** * Converts the specified 4x4 matrix to a quaternion. Note that since a quaternion is purely a * representation for orientation, only the rotational part of the matrix is used. * * @param {Mat4} m - The 4x4 matrix to convert. * @returns {Quat} Self for chaining. * @example * // Create a 4x4 rotation matrix of 180 degrees around the y-axis * const rot = new Mat4().setFromAxisAngle(Vec3.UP, 180); * * // Convert to a quaternion * const q = new Quat().setFromMat4(rot); */ setFromMat4(m: Mat4): Quat; /** * Set the quaternion that represents the shortest rotation from one direction to another. * * @param {Vec3} from - The direction to rotate from. It should be normalized. * @param {Vec3} to - The direction to rotate to. It should be normalized. * @returns {Quat} Self for chaining. * @example * const q = new Quat(); * const from = new Vec3(0, 0, 1); * const to = new Vec3(0, 1, 0); * q.setFromDirections(from, to); */ setFromDirections(from: Vec3, to: Vec3): Quat; /** * Performs a spherical interpolation between two quaternions. The result of the interpolation * is written to the quaternion calling the function. * * @param {Quat} lhs - The quaternion to interpolate from. * @param {Quat} rhs - The quaternion to interpolate to. * @param {number} alpha - The unclamped interpolation factor. Values between 0 and 1 interpolate * between lhs and rhs; values outside this range extrapolate beyond them. * @returns {Quat} Self for chaining. * @example * const q1 = new Quat(-0.11, -0.15, -0.46, 0.87); * const q2 = new Quat(-0.21, -0.21, -0.67, 0.68); * * const result = new Quat(); * result.slerp(q1, q2, 0); // Return q1 * result.slerp(q1, q2, 0.5); // Return the midpoint interpolant * result.slerp(q1, q2, 1); // Return q2 */ slerp(lhs: Quat, rhs: Quat, alpha: number): Quat; /** * Transforms a 3-dimensional vector by the specified quaternion. * * @param {Vec3} vec - The 3-dimensional vector to be transformed. * @param {Vec3} [res] - An optional 3-dimensional vector to receive the result of the transformation. * @returns {Vec3} The transformed vector (res if specified, otherwise a new Vec3). * @example * // Create a 3-dimensional vector * const v = new Vec3(1, 2, 3); * * // Create a quaternion rotation * const q = new Quat().setFromEulerAngles(10, 20, 30); * * const tv = q.transformVector(v); */ transformVector(vec: Vec3, res?: Vec3): Vec3; /** * Set the values of the quaternion from an array. * * @param {number[]|ArrayBufferView} arr - The array to set the quaternion values from. * @param {number} [offset] - The zero-based index at which to start copying elements from the * array. Default is 0. * @returns {Quat} Self for chaining. * @example * const q = new Quat(); * q.fromArray([20, 10, 5, 0]); * // q is set to [20, 10, 5, 0] */ fromArray(arr: number[] | ArrayBufferView, offset?: number): Quat; /** * Converts the quaternion to string form. * * @returns {string} The quaternion in string form. * @example * const q = new Quat(0, 0, 0, 1); * // Outputs [0, 0, 0, 1] * console.log(q.toString()); */ toString(): string; /** * @overload * @param {number[]} [arr] - The array to populate with the quaternion's number * components. If not specified, a new array is created. * @param {number} [offset] - The zero-based index at which to start copying elements to the * array. Default is 0. * @returns {number[]} The quaternion as an array. */ toArray(arr?: number[], offset?: number): number[]; /** * @overload * @param {ArrayBufferView} arr - The array to populate with the quaternion's number * components. If not specified, a new array is created. * @param {number} [offset] - The zero-based index at which to start copying elements to the * array. Default is 0. * @returns {ArrayBufferView} The quaternion as an array. */ toArray(arr: ArrayBufferView, offset?: number): ArrayBufferView; } /** * A 4x4 matrix. Mat4 is commonly used to represent world, view and projection transformations in 3D * graphics, combining rotation, translation and scale into a single matrix. * * A new Mat4 is the identity. Elements live in {@link data}, a 16-element `Float32Array` in * column-major order: the translation occupies elements 12, 13 and 14. Build a transform with * {@link setTRS}, {@link setFromEulerAngles} or {@link setFromAxisAngle}, a camera matrix with * {@link setLookAt}, {@link setPerspective} or {@link setOrtho}, and read parts back with * {@link getTranslation}, {@link getScale} and {@link getEulerAngles}. Angles are in degrees. * * Matrices combine by multiplication: `r.mul2(a, b)` computes `a * b`, so `b` is applied first when * the result transforms a point. {@link transformPoint} applies the full transform including * translation, while {@link transformVector} applies only rotation and scale, which is what * directions need. * * Methods modify the matrix they are called on and return it for chaining. Use {@link clone} for an * independent copy and {@link copy} to overwrite. {@link IDENTITY} and {@link ZERO} are frozen * shared instances, and the matrix returned by {@link GraphNode#getWorldTransform} is internal * storage to be treated as read-only. * * @example * // Compose a transform from position, rotation and scale * const world = new Mat4().setTRS( * new Vec3(0, 1, 0), * new Quat().setFromEulerAngles(0, 45, 0), * Vec3.ONE * ); * @example * // Transform a local point into world space * const worldPoint = entity.getWorldTransform().transformPoint(localPoint); * @category Math */ declare class Mat4 { static _getPerspectiveHalfSize(halfSize: any, fov: any, aspect: any, znear: any, fovIsHorizontal: any): void; /** * A constant matrix set to the identity. * * @type {Mat4} * @readonly */ static readonly IDENTITY: Mat4; /** * A constant matrix with all elements set to 0. * * @type {Mat4} * @readonly */ static readonly ZERO: Mat4; /** * Matrix elements in the form of a flat array. * * @type {Float32Array} */ data: Float32Array; /** * Adds the specified 4x4 matrices together and stores the result in the current instance. * * @param {Mat4} lhs - The 4x4 matrix used as the first operand of the addition. * @param {Mat4} rhs - The 4x4 matrix used as the second operand of the addition. * @returns {Mat4} Self for chaining. * @example * const m = new Mat4(); * * m.add2(Mat4.IDENTITY, Mat4.ONE); * * console.log("The result of the addition is: " + m.toString()); */ add2(lhs: Mat4, rhs: Mat4): Mat4; /** * Adds the specified 4x4 matrix to the current instance. * * @param {Mat4} rhs - The 4x4 matrix used as the second operand of the addition. * @returns {Mat4} Self for chaining. * @example * const m = new Mat4(); * * m.add(Mat4.ONE); * * console.log("The result of the addition is: " + m.toString()); */ add(rhs: Mat4): Mat4; /** * Creates a duplicate of the specified matrix. * * @returns {this} A duplicate matrix. * @example * const src = new Mat4().setFromEulerAngles(10, 20, 30); * const dst = src.clone(); * console.log("The two matrices are " + (src.equals(dst) ? "equal" : "different")); */ clone(): this; /** * Copies the contents of a source 4x4 matrix to a destination 4x4 matrix. * * @param {Mat4} rhs - A 4x4 matrix to be copied. * @returns {Mat4} Self for chaining. * @example * const src = new Mat4().setFromEulerAngles(10, 20, 30); * const dst = new Mat4(); * dst.copy(src); * console.log("The two matrices are " + (src.equals(dst) ? "equal" : "different")); */ copy(rhs: Mat4): Mat4; /** * Reports whether two matrices are equal. * * @param {Mat4} rhs - The other matrix. * @returns {boolean} True if the matrices are equal and false otherwise. * @example * const a = new Mat4().setFromEulerAngles(10, 20, 30); * const b = new Mat4(); * console.log("The two matrices are " + (a.equals(b) ? "equal" : "different")); */ equals(rhs: Mat4): boolean; /** * Reports whether the specified matrix is the identity matrix. * * @returns {boolean} True if the matrix is identity and false otherwise. * @example * const m = new Mat4(); * console.log("The matrix is " + (m.isIdentity() ? "identity" : "not identity")); */ isIdentity(): boolean; /** * Multiplies the specified 4x4 matrices together and stores the result in the current * instance. * * @param {Mat4} lhs - The 4x4 matrix used as the first multiplicand of the operation. * @param {Mat4} rhs - The 4x4 matrix used as the second multiplicand of the operation. * @returns {Mat4} Self for chaining. * @example * const a = new Mat4().setFromEulerAngles(10, 20, 30); * const b = new Mat4().setFromAxisAngle(Vec3.UP, 180); * const r = new Mat4(); * * // r = a * b * r.mul2(a, b); * * console.log("The result of the multiplication is: " + r.toString()); */ mul2(lhs: Mat4, rhs: Mat4): Mat4; /** * Multiplies the specified 4x4 matrices together and stores the result in the current * instance. This function assumes the matrices are affine transformation matrices, where the * upper left 3x3 elements are a rotation matrix, and the bottom left 3 elements are * translation. The rightmost column is assumed to be [0, 0, 0, 1]. The parameters are not * verified to be in the expected format. This function is faster than general {@link mul2}. * * @param {Mat4} lhs - The affine transformation 4x4 matrix used as the first multiplicand of * the operation. * @param {Mat4} rhs - The affine transformation 4x4 matrix used as the second multiplicand of * the operation. * @returns {Mat4} Self for chaining. * @example * const a = new Mat4().setFromEulerAngles(10, 20, 30); * const b = new Mat4().setFromAxisAngle(Vec3.UP, 180); * const r = new Mat4(); * * // r = a * b (optimized for affine transforms) * r.mulAffine2(a, b); */ mulAffine2(lhs: Mat4, rhs: Mat4): Mat4; /** * Multiplies the current instance by the specified 4x4 matrix. * * @param {Mat4} rhs - The 4x4 matrix used as the second multiplicand of the operation. * @returns {Mat4} Self for chaining. * @example * const a = new Mat4().setFromEulerAngles(10, 20, 30); * const b = new Mat4().setFromAxisAngle(Vec3.UP, 180); * * // a = a * b * a.mul(b); * * console.log("The result of the multiplication is: " + a.toString()); */ mul(rhs: Mat4): Mat4; /** * Transforms a 3-dimensional point by a 4x4 matrix. * * @param {Vec3} vec - The 3-dimensional point to be transformed. * @param {Vec3} [res] - An optional 3-dimensional point to receive the result of the * transformation. * @returns {Vec3} The input point v transformed by the current instance. * @example * // Create a 3-dimensional point * const v = new Vec3(1, 2, 3); * * // Create a 4x4 rotation matrix * const m = new Mat4().setFromEulerAngles(10, 20, 30); * * const tv = m.transformPoint(v); */ transformPoint(vec: Vec3, res?: Vec3): Vec3; /** * Transforms a 3-dimensional vector by a 4x4 matrix. * * @param {Vec3} vec - The 3-dimensional vector to be transformed. * @param {Vec3} [res] - An optional 3-dimensional vector to receive the result of the * transformation. * @returns {Vec3} The input vector v transformed by the current instance. * @example * // Create a 3-dimensional vector * const v = new Vec3(1, 2, 3); * * // Create a 4x4 rotation matrix * const m = new Mat4().setFromEulerAngles(10, 20, 30); * * const tv = m.transformVector(v); */ transformVector(vec: Vec3, res?: Vec3): Vec3; /** * Transforms a 4-dimensional vector by a 4x4 matrix. * * @param {Vec4} vec - The 4-dimensional vector to be transformed. * @param {Vec4} [res] - An optional 4-dimensional vector to receive the result of the * transformation. * @returns {Vec4} The input vector v transformed by the current instance. * @example * // Create an input 4-dimensional vector * const v = new Vec4(1, 2, 3, 4); * * // Create an output 4-dimensional vector * const result = new Vec4(); * * // Create a 4x4 rotation matrix * const m = new Mat4().setFromEulerAngles(10, 20, 30); * * m.transformVec4(v, result); */ transformVec4(vec: Vec4, res?: Vec4): Vec4; /** * Sets the specified matrix to a viewing matrix derived from an eye point, a target point and * an up vector. The matrix maps the target point to the negative z-axis and the eye point to * the origin, so that when you use a typical projection matrix, the center of the scene maps * to the center of the viewport. Similarly, the direction described by the up vector projected * onto the viewing plane is mapped to the positive y-axis so that it points upward in the * viewport. The up vector must not be parallel to the line of sight from the eye to the * reference point. * * @param {Vec3} position - 3-d vector holding view position. * @param {Vec3} target - 3-d vector holding reference point. * @param {Vec3} up - 3-d vector holding the up direction. * @returns {Mat4} Self for chaining. * @example * const position = new Vec3(10, 10, 10); * const target = new Vec3(0, 0, 0); * const up = new Vec3(0, 1, 0); * const m = new Mat4().setLookAt(position, target, up); */ setLookAt(position: Vec3, target: Vec3, up: Vec3): Mat4; /** * Sets the specified matrix to a perspective projection matrix. The function's parameters * define the shape of a frustum. * * @param {number} left - The x-coordinate for the left edge of the camera's projection plane * in eye space. * @param {number} right - The x-coordinate for the right edge of the camera's projection plane * in eye space. * @param {number} bottom - The y-coordinate for the bottom edge of the camera's projection * plane in eye space. * @param {number} top - The y-coordinate for the top edge of the camera's projection plane in * eye space. * @param {number} znear - The near clip plane in eye coordinates. * @param {number} zfar - The far clip plane in eye coordinates. * @returns {Mat4} Self for chaining. * @example * // Create a 4x4 perspective projection matrix * const f = new Mat4().setFrustum(-2, 2, -1, 1, 1, 1000); * @ignore */ setFrustum(left: number, right: number, bottom: number, top: number, znear: number, zfar: number): Mat4; /** * Sets the specified matrix to a perspective projection matrix. The function's parameters * define the shape of a frustum. * * @param {number} fov - The frustum's field of view in degrees. The fovIsHorizontal parameter * controls whether this is a vertical or horizontal field of view. By default, it's a vertical * field of view. * @param {number} aspect - The aspect ratio of the frustum's projection plane * (width / height). * @param {number} znear - The near clip plane in eye coordinates. * @param {number} zfar - The far clip plane in eye coordinates. * @param {boolean} [fovIsHorizontal] - Set to true to treat the fov as horizontal (x-axis) and * false for vertical (y-axis). Defaults to false. * @returns {Mat4} Self for chaining. * @example * // Create a 4x4 perspective projection matrix * const persp = new Mat4().setPerspective(45, 16 / 9, 1, 1000); */ setPerspective(fov: number, aspect: number, znear: number, zfar: number, fovIsHorizontal?: boolean): Mat4; /** * Sets the specified matrix to an orthographic projection matrix. The function's parameters * define the shape of a cuboid-shaped frustum. * * @param {number} left - The x-coordinate for the left edge of the camera's projection plane * in eye space. * @param {number} right - The x-coordinate for the right edge of the camera's projection plane * in eye space. * @param {number} bottom - The y-coordinate for the bottom edge of the camera's projection * plane in eye space. * @param {number} top - The y-coordinate for the top edge of the camera's projection plane in * eye space. * @param {number} near - The near clip plane in eye coordinates. * @param {number} far - The far clip plane in eye coordinates. * @returns {Mat4} Self for chaining. * @example * // Create a 4x4 orthographic projection matrix * const ortho = new Mat4().setOrtho(-2, 2, -2, 2, 1, 1000); */ setOrtho(left: number, right: number, bottom: number, top: number, near: number, far: number): Mat4; /** * Sets the specified matrix to a rotation matrix equivalent to a rotation around an axis. The * axis must be normalized (unit length) and the angle must be specified in degrees. * * @param {Vec3} axis - The normalized axis vector around which to rotate. * @param {number} angle - The angle of rotation in degrees. * @returns {Mat4} Self for chaining. * @example * // Create a 4x4 rotation matrix * const rm = new Mat4().setFromAxisAngle(Vec3.UP, 90); */ setFromAxisAngle(axis: Vec3, angle: number): Mat4; /** * Sets the specified matrix to a translation matrix. * * @param {number} x - The x-component of the translation. * @param {number} y - The y-component of the translation. * @param {number} z - The z-component of the translation. * @returns {Mat4} Self for chaining. * @example * // Create a 4x4 translation matrix * const tm = new Mat4().setTranslate(10, 10, 10); * @ignore */ setTranslate(x: number, y: number, z: number): Mat4; /** * Sets the specified matrix to a scale matrix. * * @param {number} x - The x-component of the scale. * @param {number} y - The y-component of the scale. * @param {number} z - The z-component of the scale. * @returns {Mat4} Self for chaining. * @example * // Create a 4x4 scale matrix * const sm = new Mat4().setScale(10, 10, 10); * @ignore */ setScale(x: number, y: number, z: number): Mat4; /** * Sets the specified matrix to a matrix transforming a normalized view volume (in range of * -1 .. 1) to their position inside a viewport (in range of 0 .. 1). This encapsulates a * scaling to the size of the viewport and a translation to the position of the viewport. * * @param {number} x - The x-component of the position of the viewport (in 0..1 range). * @param {number} y - The y-component of the position of the viewport (in 0..1 range). * @param {number} width - The width of the viewport (in 0..1 range). * @param {number} height - The height of the viewport (in 0..1 range). * @returns {Mat4} Self for chaining. * @example * // Create a 4x4 viewport matrix which scales normalized view volume to full texture viewport * const vm = new Mat4().setViewport(0, 0, 1, 1); * @ignore */ setViewport(x: number, y: number, width: number, height: number): Mat4; /** * Sets the matrix to a reflection matrix, which can be used as a mirror transformation by the * plane. * * @param {Vec3} normal - The normal of the plane to reflect by. * @param {number} distance - The distance of plane to reflect by. * @returns {Mat4} Self for chaining. * @example * // Create a reflection matrix for a horizontal plane at y=0 * const reflection = new Mat4().setReflection(Vec3.UP, 0); */ setReflection(normal: Vec3, distance: number): Mat4; /** * Sets the matrix to the inverse of a source matrix. * * @param {Mat4} [src] - The matrix to invert. If not set, the matrix is inverted in-place. * @returns {Mat4} Self for chaining. * @example * // Create a 4x4 rotation matrix of 180 degrees around the y-axis * const rot = new Mat4().setFromAxisAngle(Vec3.UP, 180); * * // Invert in place * rot.invert(); */ invert(src?: Mat4): Mat4; /** * Sets matrix data from an array. * * @param {number[]} src - Source array. Must have 16 values. * @returns {Mat4} Self for chaining. * @example * const m = new Mat4(); * m.set([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 10, 20, 30, 1]); */ set(src: number[]): Mat4; /** * Sets the specified matrix to the identity matrix. * * @returns {Mat4} Self for chaining. * @example * m.setIdentity(); * console.log("The matrix is " + (m.isIdentity() ? "identity" : "not identity")); */ setIdentity(): Mat4; /** * Sets the specified matrix to the concatenation of a translation, a quaternion rotation and a * scale. * * @param {Vec3} t - A 3-d vector translation. * @param {Quat} r - A quaternion rotation. * @param {Vec3} s - A 3-d vector scale. * @returns {Mat4} Self for chaining. * @example * const t = new Vec3(10, 20, 30); * const r = new Quat(); * const s = new Vec3(2, 2, 2); * * const m = new Mat4(); * m.setTRS(t, r, s); */ setTRS(t: Vec3, r: Quat, s: Vec3): Mat4; /** * Sets the matrix to the transpose of a source matrix. * * @param {Mat4} [src] - The matrix to transpose. If not set, the matrix is transposed in-place. * @returns {Mat4} Self for chaining. * @example * const m = new Mat4(); * * // Transpose in place * m.transpose(); */ transpose(src?: Mat4): Mat4; /** * Extracts the translational component from the specified 4x4 matrix. * * @param {Vec3} [t] - The vector to receive the translation of the matrix. * @returns {Vec3} The translation of the specified 4x4 matrix. * @example * // Create a 4x4 matrix * const m = new Mat4(); * * // Query the translation component * const t = new Vec3(); * m.getTranslation(t); */ getTranslation(t?: Vec3): Vec3; /** * Extracts the x-axis from the specified 4x4 matrix. * * @param {Vec3} [x] - The vector to receive the x axis of the matrix. * @returns {Vec3} The x-axis of the specified 4x4 matrix. * @example * // Create a 4x4 matrix * const m = new Mat4(); * * // Query the x-axis component * const x = new Vec3(); * m.getX(x); */ getX(x?: Vec3): Vec3; /** * Extracts the y-axis from the specified 4x4 matrix. * * @param {Vec3} [y] - The vector to receive the y axis of the matrix. * @returns {Vec3} The y-axis of the specified 4x4 matrix. * @example * // Create a 4x4 matrix * const m = new Mat4(); * * // Query the y-axis component * const y = new Vec3(); * m.getY(y); */ getY(y?: Vec3): Vec3; /** * Extracts the z-axis from the specified 4x4 matrix. * * @param {Vec3} [z] - The vector to receive the z axis of the matrix. * @returns {Vec3} The z-axis of the specified 4x4 matrix. * @example * // Create a 4x4 matrix * const m = new Mat4(); * * // Query the z-axis component * const z = new Vec3(); * m.getZ(z); */ getZ(z?: Vec3): Vec3; /** * Extracts the scale component from the specified 4x4 matrix. * * @param {Vec3} [scale] - Vector to receive the scale. * @returns {Vec3} The scale in X, Y and Z of the specified 4x4 matrix. * @example * // Query the scale component * const scale = m.getScale(); */ getScale(scale?: Vec3): Vec3; /** * -1 if the matrix has an odd number of negative scales (mirrored); 1 otherwise. * * @type {number} * @ignore */ get scaleSign(): number; /** * Sets the specified matrix to a rotation matrix defined by Euler angles. The rotation is * applied using an **intrinsic XYZ** order: first around the X-axis, then around the newly * transformed Y-axis, and finally around the resulting Z-axis. Angles are specified in * degrees. * * @param {number} ex - Angle to rotate around X axis in degrees. * @param {number} ey - Angle to rotate around Y axis in degrees. * @param {number} ez - Angle to rotate around Z axis in degrees. * @returns {Mat4} Self for chaining. * @example * const m = new Mat4(); * m.setFromEulerAngles(45, 90, 180); */ setFromEulerAngles(ex: number, ey: number, ez: number): Mat4; /** * Extracts the Euler angles equivalent to the rotational portion of the specified matrix. The * returned Euler angles are in **intrinsic XYZ** order and in degrees. * * @param {Vec3} [eulers] - A 3-d vector to receive the Euler angles. * @returns {Vec3} A 3-d vector containing the Euler angles. * @example * // Create a 4x4 rotation matrix of 45 degrees around the y-axis * const m = new Mat4().setFromAxisAngle(Vec3.UP, 45); * * const eulers = m.getEulerAngles(); */ getEulerAngles(eulers?: Vec3): Vec3; /** * Converts the specified matrix to string form. * * @returns {string} The matrix in string form. * @example * const m = new Mat4(); * // Outputs [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1] * console.log(m.toString()); */ toString(): string; } /** * An infinite ray. Rays are commonly used for picking, raycasting and intersection tests. * * A ray is an {@link origin} and a {@link direction}. It performs no intersection itself: pass it * to the `intersectsRay` method of a {@link BoundingBox}, {@link BoundingSphere}, * {@link OrientedBox}, {@link Plane} or {@link Tri}. Keep the direction normalized, as those tests * require it. The constructor copies the vectors it is given, and {@link set} updates both in * place. * * @example * // A ray from the camera through a screen position * const ray = new Ray(); * entity.camera.screenToWorld(x, y, entity.camera.nearClip, ray.origin); * entity.camera.screenToWorld(x, y, entity.camera.farClip, ray.direction); * ray.direction.sub(ray.origin).normalize(); * @category Math */ declare class Ray { /** * Creates a new Ray instance. The ray is infinite, starting at a given origin and pointing in * a given direction. * * @param {Vec3} [origin] - The starting point of the ray. The constructor copies * this parameter. Defaults to the origin (0, 0, 0). * @param {Vec3} [direction] - The direction of the ray. The constructor copies * this parameter. Defaults to a direction down the world negative Z axis (0, 0, -1). * @example * // Create a new ray starting at the position of this entity and pointing down * // the entity's negative Z axis * const ray = new Ray(this.entity.getPosition(), this.entity.forward); */ constructor(origin?: Vec3, direction?: Vec3); /** * The starting point of the ray. * * @readonly * @type {Vec3} */ readonly origin: Vec3; /** * The direction of the ray. * * @readonly * @type {Vec3} */ readonly direction: Vec3; /** * Sets origin and direction to the supplied vector values. * * @param {Vec3} origin - The starting point of the ray. * @param {Vec3} direction - The direction of the ray. * @returns {Ray} Self for chaining. */ set(origin: Vec3, direction: Vec3): Ray; /** * Copies the contents of a source Ray. * * @param {Ray} src - The Ray to copy from. * @returns {Ray} Self for chaining. */ copy(src: Ray): Ray; /** * Returns a clone of the Ray. * * @returns {this} A duplicate Ray. */ clone(): this; } /** * @import { Ray } from './ray.js' */ /** * An infinite plane. Internally, it's represented in a parametric equation form: * `ax + by + cz + distance = 0`. * * A plane is a {@link normal} and a {@link distance} from the origin along that normal. Define one * with the constructor or {@link setFromPointNormal} from a normal and a point the plane passes * through, or with {@link set} from the four coefficients. None of these normalize the normal they * are given, and {@link distance} is only a true distance when the normal is unit length, so call * {@link normalize} afterwards if it is not. {@link intersectsRay} and {@link intersectsLine} * return whether a hit occurred and write the hit point into an optional vector. The ray's * direction must be normalized. * * @example * // Find where a ray from the camera meets the ground plane at y = 0 * const ground = new Plane(Vec3.UP, 0); * const hit = new Vec3(); * if (ground.intersectsRay(ray, hit)) { * marker.setPosition(hit); * } * @category Math */ declare class Plane { /** * Create a new Plane instance. * * @param {Vec3} [normal] - Normal of the plane. The constructor copies this parameter. Defaults * to {@link Vec3.UP}. * @param {number} [distance] - The distance from the plane to the origin, along its normal. * Defaults to 0. */ constructor(normal?: Vec3, distance?: number); /** * The normal of the plane. */ normal: Vec3; /** * The distance from the plane to the origin, along its normal. * * @type {number} */ distance: number; /** * Returns a clone of the specified plane. * * @returns {this} A duplicate plane. */ clone(): this; /** * Copies the contents of a source plane to a destination plane. * * @param {Plane} src - A source plane to copy to the destination plane. * @returns {Plane} Self for chaining. */ copy(src: Plane): Plane; /** * Test if the plane intersects between two points. * * @param {Vec3} start - Start position of line. * @param {Vec3} end - End position of line. * @param {Vec3} [point] - If there is an intersection, the intersection point will be copied * into here. * @returns {boolean} True if there is an intersection. */ intersectsLine(start: Vec3, end: Vec3, point?: Vec3): boolean; /** * Test if a ray intersects with the infinite plane. * * @param {Ray} ray - Ray to test against (direction must be normalized). * @param {Vec3} [point] - If there is an intersection, the intersection point will be copied * into here. * @returns {boolean} True if there is an intersection. */ intersectsRay(ray: Ray, point?: Vec3): boolean; /** * Normalize the plane. * * @returns {Plane} Self for chaining. */ normalize(): Plane; /** * Sets the plane based on a normal and a distance from the origin. * * @param {number} nx - The x-component of the normal. * @param {number} ny - The y-component of the normal. * @param {number} nz - The z-component of the normal. * @param {number} d - The distance from the origin. * @returns {Plane} Self for chaining. */ set(nx: number, ny: number, nz: number, d: number): Plane; /** * Sets the plane based on a specified normal and a point on the plane. * * @param {Vec3} point - The point on the plane. * @param {Vec3} normal - The normal of the plane. * @returns {Plane} Self for chaining. */ setFromPointNormal(point: Vec3, normal: Vec3): Plane; } /** * A bounding sphere is a volume for facilitating fast intersection testing. * * A sphere is a {@link center} and a {@link radius}. It is the cheapest bounding volume to test, so * it suits broad-phase checks made before a finer test. {@link containsPoint}, * {@link intersectsBoundingSphere} and {@link intersectsRay} return a boolean and allocate nothing. * Unlike {@link BoundingBox}, the constructor keeps a reference to the center vector it is given * rather than copying it, so the sphere follows any later changes to that vector. * * @example * // A trigger volume 2 units around an entity * const sphere = new BoundingSphere(entity.getPosition().clone(), 2); * if (sphere.containsPoint(player.getPosition())) { * // the player is within 2 units of the entity * } * @category Math */ declare class BoundingSphere { /** * Creates a new BoundingSphere instance. * * @param {Vec3} [center] - The world space coordinate marking the center of the sphere. The * constructor takes a reference of this parameter. * @param {number} [radius] - The radius of the bounding sphere. Defaults to 0.5. * @example * // Create a new bounding sphere centered on the origin with a radius of 0.5 * const sphere = new BoundingSphere(); */ constructor(center?: Vec3, radius?: number); /** * Center of sphere. * * @type {Vec3} * @readonly */ readonly center: Vec3; /** * The radius of the bounding sphere. * * @type {number} */ radius: number; /** * Test if a point is inside the sphere. * * @param {Vec3} point - Point to test. * @returns {boolean} True if the point is inside the sphere and false otherwise. * @example * const sphere = new BoundingSphere(new Vec3(0, 0, 0), 1); * const point = new Vec3(0.5, 0, 0); * const isInside = sphere.containsPoint(point); // true */ containsPoint(point: Vec3): boolean; /** * Test if a ray intersects with the sphere. * * @param {Ray} ray - Ray to test against (direction must be normalized). * @param {Vec3} [point] - If there is an intersection, the intersection point will be copied * into here. * @returns {boolean} True if there is an intersection. */ intersectsRay(ray: Ray, point?: Vec3): boolean; /** * Test if a Bounding Sphere is overlapping, enveloping, or inside this Bounding Sphere. * * @param {BoundingSphere} sphere - Bounding Sphere to test. * @returns {boolean} True if the Bounding Sphere is overlapping, enveloping, or inside this Bounding Sphere and false otherwise. */ intersectsBoundingSphere(sphere: BoundingSphere): boolean; } /** * Axis-Aligned Bounding Box. An AABB is commonly used for fast overlap tests in collision * detection, spatial indexing and frustum culling. * * A box is stored as a {@link center} and {@link halfExtents}. Set it from its extreme corners with * {@link setMinMax} and read them back with {@link getMin} and {@link getMax}. Fit a box to vertex * data with {@link compute}, grow it to enclose another box with {@link add}, and move a local box * into world space with {@link setFromTransformedAabb}, which is how the engine derives a mesh * instance's world bounds from its mesh's local bounds. * * Tests such as {@link intersects}, {@link containsPoint} and {@link intersectsRay} return a * boolean and allocate nothing. {@link closestPoint} writes into an optional result vector, while * {@link getMin} and {@link getMax} return the box's own cached vectors, which should be treated as * read-only. The constructor copies the vectors it is given. * * @example * // Enclose every mesh instance of a render component in one box * const bounds = new BoundingBox(); * entity.render.meshInstances.forEach((meshInstance, i) => { * if (i === 0) { * bounds.copy(meshInstance.aabb); * } else { * bounds.add(meshInstance.aabb); * } * }); * @example * // Pick against a box; the ray's direction must be normalized * const hit = new Vec3(); * if (bounds.intersectsRay(ray, hit)) { * console.log(`Hit at ${hit}`); * } * @category Math */ declare class BoundingBox { /** * Compute the min and max bounding values to encapsulate all specified vertices. * * @param {ArrayLike} vertices - The vertices used to compute the new size for the * AABB. * @param {Vec3} min - Stored computed min value. * @param {Vec3} max - Stored computed max value. * @param {number} [numVerts] - Number of vertices to use from the beginning of vertices array. * All vertices are used if not specified. */ static computeMinMax(vertices: ArrayLike, min: Vec3, max: Vec3, numVerts?: number): void; /** * Create a new BoundingBox instance. The bounding box is axis-aligned. * * @param {Vec3} [center] - Center of box. The constructor copies this parameter. Defaults to * (0, 0, 0). * @param {Vec3} [halfExtents] - Half the distance across the box in each axis. The constructor * copies this parameter. Defaults to (0.5, 0.5, 0.5). */ constructor(center?: Vec3, halfExtents?: Vec3); /** * Center of box. * * @type {Vec3} * @readonly */ readonly center: Vec3; /** * Half the distance across the box in each axis. * * @type {Vec3} * @readonly */ readonly halfExtents: Vec3; /** @private */ private _min; /** @private */ private _max; /** * Combines two bounding boxes into one, enclosing both. * * @param {BoundingBox} other - Bounding box to add. */ add(other: BoundingBox): void; /** * Copies the contents of a source AABB. * * @param {BoundingBox} src - The AABB to copy from. */ copy(src: BoundingBox): void; /** * Returns a clone of the AABB. * * @returns {BoundingBox} A duplicate AABB. */ clone(): BoundingBox; /** * Reports whether two axis-aligned bounding boxes are equal. * * @param {BoundingBox} other - The AABB to compare to. * @returns {boolean} True if the AABBs have the same center and half extents, false otherwise. */ equals(other: BoundingBox): boolean; /** * Test whether two axis-aligned bounding boxes intersect. * * @param {BoundingBox} other - Bounding box to test against. * @returns {boolean} True if there is an intersection. */ intersects(other: BoundingBox): boolean; _intersectsRay(ray: any, point: any): boolean; _fastIntersectsRay(ray: any): boolean; /** * Test if a ray intersects with the AABB. * * @param {Ray} ray - Ray to test against (direction must be normalized). * @param {Vec3} [point] - If there is an intersection, the intersection point will be copied * into here. * @returns {boolean} True if there is an intersection. */ intersectsRay(ray: Ray, point?: Vec3): boolean; /** * Sets the minimum and maximum corner of the AABB. Using this function is faster than * assigning min and max separately. * * @param {Vec3} min - The minimum corner of the AABB. * @param {Vec3} max - The maximum corner of the AABB. */ setMinMax(min: Vec3, max: Vec3): void; /** * Return the minimum corner of the AABB. * * @returns {Vec3} Minimum corner. */ getMin(): Vec3; /** * Return the maximum corner of the AABB. * * @returns {Vec3} Maximum corner. */ getMax(): Vec3; /** * Test if a point is inside an AABB. * * @param {Vec3} point - Point to test. * @returns {boolean} True if the point is inside the AABB and false otherwise. */ containsPoint(point: Vec3): boolean; /** * Return the point on the AABB closest to a given point. If the point is inside the AABB, the * point itself is returned. * * @param {Vec3} point - Point to find the closest point to. * @param {Vec3} [result] - The vector to store the result in. If not provided, a new Vec3 is * created and returned. * @returns {Vec3} The closest point on the AABB. * @example * const box = new BoundingBox(new Vec3(0, 0, 0), new Vec3(1, 1, 1)); * const point = new Vec3(2, 0, 0); * const closest = box.closestPoint(point); // Returns Vec3(1, 0, 0) * @example * // Reuse a result vector to avoid allocations in hot paths * const result = new Vec3(); * box.closestPoint(point, result); */ closestPoint(point: Vec3, result?: Vec3): Vec3; /** * Set an AABB to enclose the specified AABB if it were to be transformed by the specified 4x4 * matrix. * * @param {BoundingBox} aabb - Box to transform and enclose. * @param {Mat4} m - Transformation matrix to apply to source AABB. * @param {boolean} ignoreScale - If true is specified, a scale from the matrix is ignored. Defaults to false. */ setFromTransformedAabb(aabb: BoundingBox, m: Mat4, ignoreScale?: boolean): void; /** * Compute the size of the AABB to encapsulate all specified vertices. * * @param {ArrayLike} vertices - The vertices used to compute the new size for the * AABB. * @param {number} [numVerts] - Number of vertices to use from the beginning of vertices array. * All vertices are used if not specified. */ compute(vertices: ArrayLike, numVerts?: number): void; /** * Test if a Bounding Sphere is overlapping, enveloping, or inside this AABB. * * @param {BoundingSphere} sphere - Bounding Sphere to test. * @returns {boolean} True if the Bounding Sphere is overlapping, enveloping, or inside the * AABB and false otherwise. */ intersectsBoundingSphere(sphere: BoundingSphere): boolean; _distanceToBoundingSphereSq(sphere: any): number; _expand(expandMin: any, expandMax: any): void; } /** * A frustum is a shape that defines the viewing space of a camera. It can be used to determine * visibility of points and bounding spheres. Typically, you would not create a Frustum shape * directly, but instead query {@link CameraComponent#frustum}. * * A frustum is six {@link Plane}s, read and written with {@link getPlane} and {@link setPlane}, * and normally derived from a camera's combined view-projection matrix with {@link setFromMat4}. * {@link containsPoint} and {@link containsAabb} return a boolean. {@link containsSphere} returns 0 * for a sphere outside, 1 for one that intersects and 2 for one fully inside, so callers can skip * finer tests for objects that are entirely visible. None of the tests allocate. * * @example * // Skip work for objects the camera cannot see * const frustum = entity.camera.frustum; * if (frustum.containsAabb(meshInstance.aabb)) { * // visible: update it * } * @category Math */ declare class Frustum { /** * The six planes of the frustum, packed as four floats each - the normal's x, y and z followed * by the plane's distance from the origin - in the order right, left, bottom, top, far, near. * The normals point inwards, so a point is outside a plane when * `normal.dot(point) + distance` is negative. * * This is the frustum's storage, exposed for internal use where the packed form avoids * per-plane object access. Use {@link Frustum#getPlane} and {@link Frustum#setPlane} instead. * * @type {Float32Array} * @ignore */ planeData: Float32Array; /** * @type {Plane[]} * @deprecated Use {@link Frustum#getPlane} and {@link Frustum#setPlane} instead. * @ignore */ get planes(): Plane[]; /** * Returns a clone of the specified frustum. * * @returns {Frustum} A duplicate frustum. * @example * const frustum = new Frustum(); * const clone = frustum.clone(); */ clone(): Frustum; /** * Copies the contents of a source frustum to a destination frustum. * * @param {Frustum} src - A source frustum to copy to the destination frustum. * @returns {Frustum} Self for chaining. * @example * const src = entity.camera.frustum; * const dst = new Frustum(); * dst.copy(src); */ copy(src: Frustum): Frustum; /** * Returns one of the frustum's six planes. The planes are ordered right, left, bottom, top, * far, near, and their normals point inwards. * * @param {number} index - The index of the plane, from 0 to 5. * @param {Plane} result - The plane to write to. * @returns {Plane} The supplied plane, containing the frustum plane. * @example * const plane = new Plane(); * entity.camera.frustum.getPlane(0, plane); */ getPlane(index: number, result: Plane): Plane; /** * Sets one of the frustum's six planes. The plane is normalized as it is stored, as the * frustum's tests require unit length normals. The planes are ordered right, left, bottom, top, * far, near, and their normals must point inwards. * * @param {number} index - The index of the plane, from 0 to 5. * @param {Plane} plane - The plane to store. * @returns {Frustum} Self for chaining. */ setPlane(index: number, plane: Plane): Frustum; /** * Stores a normalized plane at the given index. * * @param {number} index - The index of the plane, from 0 to 5. * @param {number} nx - The x component of the plane normal. * @param {number} ny - The y component of the plane normal. * @param {number} nz - The z component of the plane normal. * @param {number} distance - The plane's distance from the origin. * @private */ private _setPlane; /** * Updates the frustum shape based on the supplied 4x4 matrix. * * @param {Mat4} matrix - The matrix describing the shape of the frustum. * @example * // Create a perspective projection matrix * const projection = new Mat4(); * projection.setPerspective(45, 16 / 9, 1, 1000); * * // Create a frustum shape that is represented by the matrix * const frustum = new Frustum(); * frustum.setFromMat4(projection); */ setFromMat4(matrix: Mat4): void; /** * Tests whether a point is inside the frustum. Note that points lying in a frustum plane are * considered to be outside the frustum. * * @param {Vec3} point - The point to test. * @returns {boolean} True if the point is inside the frustum, false otherwise. */ containsPoint(point: Vec3): boolean; /** * Expands this frustum to also contain another frustum. The other frustum's 8 corner points * are computed, and each of this frustum's planes is pushed outwards just far enough to * contain them all. The result is a conservative convex volume that contains both frustums. * This is useful for multi-view rendering such as stereo XR, where culling should keep * objects visible in any view. * * Note: keeping each plane's orientation makes this correct for arbitrary frusta, including * the asymmetric per-eye projections of XR headsets, where matching planes of the two eyes * have different normals and a per-plane "outermost" selection would wrongly cut into the * combined volume at a distance. * * @param {Frustum} other - The other frustum to add. * @returns {Frustum} Self for chaining. */ add(other: Frustum): Frustum; /** * Tests whether a bounding sphere intersects the frustum. If the sphere is outside the * frustum, zero is returned. If the sphere intersects the frustum, 1 is returned. If the * sphere is completely inside the frustum, 2 is returned. Note that a sphere touching a * frustum plane from the outside is considered to be outside the frustum. * * @param {BoundingSphere} sphere - The sphere to test. * @returns {number} 0 if the bounding sphere is outside the frustum, 1 if it intersects the * frustum and 2 if it is contained by the frustum. */ containsSphere(sphere: BoundingSphere): number; /** * Tests whether an axis aligned bounding box intersects the frustum. * * The test is conservative in the same way the plane based sphere test is: a box lying just * outside a frustum corner can be reported as intersecting. It is however always at least as * tight as testing the box's bounding sphere, since the extent of a box along a plane normal * never exceeds the radius of its bounding sphere. * * Unlike {@link Frustum#containsSphere}, a box completely inside the frustum is not * distinguished from one merely intersecting it. Detecting that costs a comparison per plane * and no caller needs it. * * @param {BoundingBox} aabb - The bounding box to test. * @returns {boolean} True if the bounding box intersects or is inside the frustum, false if it * is completely outside. */ containsAabb(aabb: BoundingBox): boolean; } /** * An Animation contains the data that defines how a {@link Skeleton} animates over time. The * Animation contains an array of {@link AnimationNode}s, where each AnimationNode targets a * specific {@link GraphNode} referenced by a {@link Skeleton}. * * An Animation can be played back by an {@link AnimationComponent}. * * @category Animation (Legacy) */ declare class Animation { /** * Human-readable name of the animation. */ name: string; /** * Duration of the animation in seconds. */ duration: number; _nodes: any[]; _nodeDict: {}; /** * Gets a {@link AnimationNode} by name. * * @param {string} name - The name of the {@link AnimationNode}. * @returns {AnimationNode} The {@link AnimationNode} with the specified name. */ getNode(name: string): AnimationNode; /** * Adds a node to the internal nodes array. * * @param {AnimationNode} node - The node to add. */ addNode(node: AnimationNode): void; /** * A read-only property to get array of animation nodes. * * @type {AnimationNode[]} */ get nodes(): AnimationNode[]; } declare class AnimationKey { constructor(time: any, position: any, rotation: any, scale: any); time: any; position: any; rotation: any; scale: any; } /** * AnimationNode represents an array of keyframes that animate the transform of a {@link GraphNode} * over time. Typically, an {@link Animation} maintains a collection of AnimationNodes, one for * each GraphNode in a {@link Skeleton}. * * @category Animation (Legacy) */ declare class AnimationNode { _name: string; _keys: any[]; } /** * Wraps a set of data used in animation: a flat {@link data} array read {@link components} values * at a time, so a three-component set holds positions and a four-component set holds quaternions. * An {@link AnimTrack} keeps its keyframe times and values as AnimData that its curves index into. * * @category Animation */ declare class AnimData { /** * Create a new animation AnimData instance. * * @param {number} components - Specifies how many components make up an element of data. For * example, specify 3 for a set of 3-dimensional vectors. The number of elements in data array * must be a multiple of components. * @param {Float32Array|number[]} data - The set of data. */ constructor(components: number, data: Float32Array | number[]); _components: number; _data: number[] | Float32Array; /** * Gets the number of components that make up an element. * * @type {number} */ get components(): number; /** * Gets the data. * * @type {Float32Array|number[]} */ get data(): Float32Array | number[]; } /** * Identifies the property that an {@link AnimCurve} drives. The path is resolved by an animation * binder into a concrete target on an entity. */ type AnimCurvePath = { /** * - The names of the entities from the animation root down to the * target entity. */ entityPath: string[]; /** * - The name of the component that owns the property, or `graph` * for a transform on the entity itself. */ component: string; /** * - The property name segments, for example * `['localPosition']` or `['weight.Smile']`. */ propertyPath: string[]; }; /** * Identifies the property that an {@link AnimCurve} drives. The path is resolved by an animation * binder into a concrete target on an entity. * * @typedef {object} AnimCurvePath * @property {string[]} entityPath - The names of the entities from the animation root down to the * target entity. * @property {string} component - The name of the component that owns the property, or `graph` * for a transform on the entity itself. * @property {string[]} propertyPath - The property name segments, for example * `['localPosition']` or `['weight.Smile']`. * @category Animation */ /** * Animation curve links an input data set to an output data set and defines the interpolation * method to use. The {@link paths} name the targets the curve drives, {@link input} and * {@link output} index into the owning {@link AnimTrack}'s keyframe time and value data, and * {@link interpolation} is one of {@link INTERPOLATION_STEP}, {@link INTERPOLATION_LINEAR} or * {@link INTERPOLATION_CUBIC}. * * @category Animation */ declare class AnimCurve { /** * Create a new animation curve. * * @param {AnimCurvePath[]} paths - Array of paths identifying the targets of this curve, for * example the local position of a node. * @param {number} input - Index of the curve which specifies the key data. * @param {number} output - Index of the curve which specifies the value data. * @param {number} interpolation - The interpolation method to use. One of the following: * * - {@link INTERPOLATION_STEP} * - {@link INTERPOLATION_LINEAR} * - {@link INTERPOLATION_CUBIC} */ constructor(paths: AnimCurvePath[], input: number, output: number, interpolation: number); _paths: AnimCurvePath[]; _input: number; _output: number; _interpolation: number; /** * The list of paths which identify targets of this curve. * * @type {AnimCurvePath[]} */ get paths(): AnimCurvePath[]; /** * The index of the AnimTrack input which contains the key data for this curve. * * @type {number} */ get input(): number; /** * The index of the AnimTrack input which contains the key data for this curve. * * @type {number} */ get output(): number; /** * The interpolation method used by this curve. * * @type {number} */ get interpolation(): number; } /** * AnimEvents stores a sorted array of animation events which should fire sequentially during the * playback of an {@link AnimTrack}. Each event is an object with a `name` and a `time` in * seconds plus any extra properties you attach. When playback passes an event's time it is fired * on the {@link AnimComponent} under the event's name, so a script listens with * `entity.anim.on('footstep', callback)` and receives the event object. * * @category Animation */ declare class AnimEvents { /** * Create a new AnimEvents instance. * * @param {object[]} events - An array of animation events. * @example * const events = new AnimEvents([ * { * name: 'my_event', * time: 1.3, // given in seconds * // any additional properties added are optional and will be available in the EventHandler callback's event object * myProperty: 'test', * myOtherProperty: true * } * ]); * animTrack.events = events; */ constructor(events: object[]); _events: any[]; get events(): any[]; } /** * @import { AnimCurve } from './anim-curve.js' * @import { AnimData } from './anim-data.js' */ /** * An AnimTrack stores the curve data necessary to animate a set of target nodes. It can be linked * to the nodes it should animate using the {@link AnimComponent#assignAnimation} method. * * A track is the engine's animation clip: a {@link name}, a {@link duration} in seconds and a list * of {@link curves}, each of which reads keyframe times from one of the {@link inputs} and values * from one of the {@link outputs}, and writes the result to a target path such as a node's local * position or a component property. Optional {@link events} fire at set times during playback. * Tracks come from `animation` assets, GLB animations among them, and are what an * {@link AnimState} plays; one track can be assigned in any number of components. * * @category Animation */ declare class AnimTrack { /** * This AnimTrack can be used as a placeholder track when creating a state graph before having all associated animation data available. * * @type {AnimTrack} */ static EMPTY: AnimTrack; /** * Create a new AnimTrack instance. * * @param {string} name - The track name. * @param {number} duration - The duration of the track in seconds. * @param {AnimData[]} inputs - List of curve key data. * @param {AnimData[]} outputs - List of curve value data. * @param {AnimCurve[]} curves - The list of curves. * @param {AnimEvents} animEvents - A sequence of animation events. * @ignore */ constructor(name: string, duration: number, inputs: AnimData[], outputs: AnimData[], curves: AnimCurve[], animEvents?: AnimEvents); _name: string; _duration: number; _inputs: AnimData[]; _outputs: AnimData[]; _curves: AnimCurve[]; _animEvents: AnimEvents; /** * Gets the name of the AnimTrack. * * @type {string} */ get name(): string; /** * Gets the duration of the AnimTrack. * * @type {number} */ get duration(): number; /** * Gets the list of curve key data contained in the AnimTrack. * * @type {AnimData[]} */ get inputs(): AnimData[]; /** * Gets the list of curve values contained in the AnimTrack. * * @type {AnimData[]} */ get outputs(): AnimData[]; /** * Gets the list of curves contained in the AnimTrack. * * @type {AnimCurve[]} */ get curves(): AnimCurve[]; /** * Sets the animation events that will fire during the playback of this anim track. * * @type {AnimEvents} */ set events(animEvents: AnimEvents); /** * Gets the animation events that will fire during the playback of this anim track. * * @type {AnimEvents} */ get events(): AnimEvents; eval(time: any, snapshot: any): void; } /** * An asset resource which represents an anim state graph. It can be loaded into an anim component using the {@link AnimComponent#loadStateGraph} method. * * The graph is data, not behavior. It lists its `layers`, each with its states, the * transitions between them and their conditions, and the `parameters` those conditions read. * Loading it into a component builds the runtime {@link AnimState}, {@link AnimTransition} and * {@link AnimBlendTree} objects, and {@link AnimComponent#assignAnimation} then attaches an * {@link AnimTrack} to each state. One graph can drive any number of components. * * ## Usage * Scripts can retrieve an AnimStateGraph instance from assets of type 'animstategraph'. An AnimStateGraph can then be loaded into an anim component as follows: * ```javascript * const animStateGraph = app.assets.get(ASSET_ID).resource; * const entity = new Entity(); * entity.addComponent('anim'); * entity.anim.loadStateGraph(animStateGraph); * ``` * * @category Animation */ declare class AnimStateGraph { /** * Create an AnimStateGraph instance from JSON data. * * @param {object} data - The JSON data to create the AnimStateGraph from. * @ignore */ constructor(data: object); _layers: any; _parameters: {}; get parameters(): {}; get layers(): any; } /** * Represents the raw audio data of a playable sound. A Sound is the resource of an audio * {@link Asset}. An audio asset can be assigned to a {@link SoundSlot} owned by a * {@link SoundComponent}. * * The {@link buffer} is the decoded Web Audio `AudioBuffer`, so {@link duration} is known as soon * as the asset has loaded. Playing a sound creates one {@link SoundInstance} per playback, normally * through a slot rather than by constructing the instance directly. * * @category Sound */ declare class Sound { /** * Create a new Sound instance. * * @param {AudioBuffer} buffer - The decoded audio data. */ constructor(buffer: AudioBuffer); /** * Contains the decoded audio data. * * @type {AudioBuffer} */ buffer: AudioBuffer; /** * Gets the duration of the sound. If the sound is not loaded it returns 0. * * @type {number} */ get duration(): number; } /** * A Bundle is the resource of a `bundle` asset: an archive whose files back other assets. As the * archive downloads, each file is indexed by its URL and announced with the `add` event, and * `load` fires once the whole archive has arrived. When a file's URL is indexed by a bundle, the * {@link ResourceLoader} reads it from the bundle through the {@link BundleRegistry} instead of * fetching it from the network. * * @ignore */ declare class Bundle extends EventHandler { /** * Fired when a file has been added to a Bundle. * * @event * @example * bundle.on("add", (url, data) => { * console.log("file added: " + url); * }); */ static EVENT_ADD: string; /** * Fired when all files of a Bundle has been loaded. * * @event * @example * bundle.on("load", () => { * console.log("All Bundle files has been loaded"); * }); */ static EVENT_LOAD: string; /** * Index of file url to DataView. * * @type {Map} * @private */ private _index; /** * If Bundle has all files loaded. * * @private */ private _loaded; /** * Add file to a Bundle. * * @param {string} url - A url of a file. * @param {DataView} data - A DataView of a file. * @ignore */ addFile(url: string, data: DataView): void; /** * Returns true if the specified URL exists in the loaded bundle. * * @param {string} url - The original file URL. Make sure you have called decodeURIComponent on * the URL first. * @returns {boolean} True of false. */ has(url: string): boolean; /** * Returns a DataView for the specified URL. * * @param {string} url - The original file URL. Make sure you have called decodeURIComponent on * the URL first. * @returns {DataView|null} A DataView. */ get(url: string): DataView | null; /** * Destroys the bundle. */ destroy(): void; /** * True if all files of a Bundle are loaded. * * @type {boolean} */ set loaded(value: boolean); get loaded(): boolean; } /** * @import { AppBase } from '../app-base.js' * @import { Asset } from '../asset/asset.js' * @import { Entity } from '../entity.js' * @import { MeshInstance } from '../../scene/mesh-instance.js' */ /** * Container for a list of animations, textures, materials, renders, gsplats and a model. * * @interface * @category Graphics */ declare class ContainerResource { /** * An array of the render assets. Each holds the meshes of one glTF mesh. * * @type {Asset<'render'>[]} */ renders: Asset<"render">[]; /** * An array of the {@link Material} and/or {@link StandardMaterial} assets. * * @type {Asset<'material'>[]} */ materials: Asset<"material">[]; /** * An array of the {@link Texture} assets. * * @type {Asset<'texture'>[]} */ textures: Asset<"texture">[]; /** * An array of the animation assets. Each resource is an {@link AnimTrack}. * * @type {Asset<'animation'>[]} */ animations: Asset<"animation">[]; /** * An array of the gsplat assets, created for meshes using the KHR_gaussian_splatting glTF * extension. * * @type {Asset<'gsplat'>[]} */ gsplats: Asset<"gsplat">[]; /** * Instantiates an entity with a model component. * * @param {object} [options] - The initialization data for the model component type * {@link ModelComponent}. * @returns {Entity} A single entity with a model component. Model component internally * contains a hierarchy based on {@link GraphNode}. * @example * // load a glb file and instantiate an entity with a model component based on it * app.assets.loadFromUrl("statue.glb", "container", (err, asset) => { * const entity = asset.resource.instantiateModelEntity({ * castShadows: true * }); * app.root.addChild(entity); * }); */ instantiateModelEntity(options?: object): Entity; /** * Instantiates an entity with a render component. * * @param {object} [options] - The initialization data for the render component type * {@link RenderComponent}. * @returns {Entity} A hierarchy of entities with render components on entities containing * renderable geometry. * @example * // load a glb file and instantiate an entity with a render component based on it * app.assets.loadFromUrl("statue.glb", "container", (err, asset) => { * const entity = asset.resource.instantiateRenderEntity({ * castShadows: true * }); * app.root.addChild(entity); * * // find all render components containing mesh instances, and change blend mode on their materials * const renders = entity.findComponents("render"); * renders.forEach((render) => { * render.meshInstances.forEach((meshInstance) => { * meshInstance.material.blendType = BLEND_MULTIPLICATIVE; * meshInstance.material.update(); * }); * }); * }); */ instantiateRenderEntity(options?: object): Entity; /** * Queries the list of available material variants. * * @returns {string[]} An array of variant names. */ getMaterialVariants(): string[]; /** * Applies a material variant to an entity hierarchy. * * @param {Entity} entity - The entity root to which material variants will be applied. * @param {string} [name] - The name of the variant, as queried from getMaterialVariants, if * null the variant will be reset to the default. * @example * // load a glb file and instantiate an entity with a render component based on it * app.assets.loadFromUrl("statue.glb", "container", (err, asset) => { * const entity = asset.resource.instantiateRenderEntity({ * castShadows: true * }); * app.root.addChild(entity); * const materialVariants = asset.resource.getMaterialVariants(); * asset.resource.applyMaterialVariant(entity, materialVariants[0]); * }); */ applyMaterialVariant(entity: Entity, name?: string): void; /** * Applies a material variant to a set of mesh instances. Compared to the applyMaterialVariant, * this method allows for setting the variant on a specific set of mesh instances instead of the * whole entity. * * @param {MeshInstance[]} instances - An array of mesh instances. * @param {string} [name] - The name of the variant, as queried by getMaterialVariants. If null, * the variant will be reset to the default. * @example * // load a glb file and instantiate an entity with a render component based on it * app.assets.loadFromUrl("statue.glb", "container", (err, asset) => { * const entity = asset.resource.instantiateRenderEntity({ * castShadows: true * }); * app.root.addChild(entity); * const materialVariants = asset.resource.getMaterialVariants(); * const renders = entity.findComponents("render"); * for (let i = 0; i < renders.length; i++) { * const renderComponent = renders[i]; * asset.resource.applyMaterialVariantInstances(renderComponent.meshInstances, materialVariants[0]); * } * }); */ applyMaterialVariantInstances(instances: MeshInstance[], name?: string): void; } /** * Resource handler for the `container` asset type. Loads glTF and GLB files, whose meshes, * materials, textures, animations and Gaussian splats become one {@link ContainerResource}. * * For glTF files, the asset options object can be used to pass load time callbacks for handling * the various resources at different stages of loading. The table below lists the resource types * and the corresponding supported process functions. * * | resource | preprocess | process | processAsync | postprocess | * | ---------- | :--------: | :-----: | :----------: | :---------: | * | global | √ | | | √ | * | node | √ | √ | | √ | * | light | √ | √ | | √ | * | camera | √ | √ | | √ | * | animation | √ | | | √ | * | material | √ | √ | | √ | * | image | √ | | √ | √ | * | texture | √ | | √ | √ | * | buffer | √ | | √ | √ | * | bufferView | √ | | √ | √ | * * Additional options that can be passed for glTF files: * [options.morphPreserveData] - When true, the morph target keeps its data passed using the options, * allowing the clone operation. * [options.morphPreferHighPrecision] - When true, high precision storage for morph targets should * be preferred. This is faster to create and allows higher precision, but takes more memory and * might be slower to render. Defaults to false. * [options.skipMeshes] - When true, the meshes and gaussian splats from the container are not * created. This can be useful if you only need access to textures or animations and similar. * * For example, to receive a texture preprocess callback: * * ```javascript * const containerAsset = new Asset(filename, 'container', { url: url, filename: filename }, null, { * texture: { * preprocess: (gltfTexture) => { * console.log("texture preprocess"); * } * } * }); * ``` * * @category Asset */ declare class ContainerHandler extends ResourceHandler { /** * Create a new ContainerResource instance. * * @param {AppBase} app - The running {@link AppBase}. * @ignore */ constructor(app: AppBase); } /** * @import { Asset } from '../asset/asset.js' * @import { AssetRegistry } from '../asset/asset-registry.js' * @import { Bundle } from './bundle.js' */ /** * The BundleRegistry tracks which assets are packed into `bundle` assets and serves their files * from a loaded {@link Bundle} instead of fetching them individually. It watches the * {@link AssetRegistry} for bundle assets and is available at {@link AssetRegistry#bundles}. * * @ignore */ declare class BundleRegistry { /** * Create a new BundleRegistry instance. * * @param {AssetRegistry} assets - The asset registry. */ constructor(assets: AssetRegistry); /** * Index of bundle assets. * @type {Map} * @private */ private _idToBundle; /** * Index of asset id to set of bundle assets. * @type {Map>} * @private */ private _assetToBundles; /** * Index of file url to set of bundle assets. * @type {Map>} * @private */ private _urlsToBundles; /** * Index of file request to load callbacks. * @type {Map} * @private */ private _fileRequests; _assets: AssetRegistry; /** * Called when asset is added to AssetRegistry. * * @param {Asset} asset - The asset that has been added. * @private */ private _onAssetAdd; _unbindAssetEvents(id: any): void; _indexAssetInBundle(id: any, bundle: any): void; _indexAssetFileUrls(asset: any): void; _getAssetFileUrls(asset: any): any[]; _onAssetRemove(asset: any): void; _onBundleLoadStart(asset: any): void; _onBundleLoad(asset: any): void; _onBundleError(err: any): void; _findLoadedOrLoadingBundleForUrl(url: any): any; /** * Lists all of the available bundles that reference the specified asset. * * @param {Asset} asset - The asset to search by. * @returns {Asset[]|null} An array of bundle assets or null if the * asset is not in any bundle. */ listBundlesForAsset(asset: Asset): Asset[] | null; /** * Lists all bundle assets. * * @returns {Asset[]} An array of bundle assets. */ list(): Asset[]; /** * Returns true if there is a bundle that contains the specified URL. * * @param {string} url - The url. * @returns {boolean} True or false. */ hasUrl(url: string): boolean; /** * Returns true if there is a bundle that contains the specified URL and that bundle is either * loaded or currently being loaded. * * @param {string} url - The url. * @returns {boolean} True or false. */ urlIsLoadedOrLoading(url: string): boolean; /** * Loads the specified file URL from a bundle that is either loaded or currently being loaded. * * @param {string} url - The URL. Make sure you are using a relative URL that does not contain * any query parameters. * @param {Function} callback - The callback is called when the file has been loaded or if an * error occurs. The callback expects the first argument to be the error message (if any) and * the second argument is the file blob URL. * @example * const asset = app.assets.find('level', 'json'); * const url = asset.getFileUrl().split('?')[0]; // get normalized asset URL * app.assets.bundles.loadUrl(url, (err, data) => { * // do something with the data * }); */ loadUrl(url: string, callback: Function): void; /** * Destroys the registry, and releases its resources. Does not unload bundle assets as these * should be unloaded by the {@link AssetRegistry}. */ destroy(): void; } /** * Callback used by {@link AssetRegistry#filter} to filter assets. */ type FilterAssetCallback = (asset: Asset) => boolean; /** * Callback used by {@link AssetRegistry#loadFromUrl} and called when an asset is loaded (or an * error occurs). */ type LoadAssetCallback = (err: string | null, asset?: Asset) => void; /** * Callback used by {@link ResourceLoader#load} and called when an asset is choosing a bundle * to load from. Return a single bundle to ensure asset is loaded from it. */ type BundlesFilterCallback = (bundles: Asset[]) => Asset; /** * @import { AssetType } from './asset.js' * @import { Bundle } from '../bundle/bundle.js' * @import { BundleRegistry } from '../bundle/bundle-registry.js' * @import { ResourceLoader } from '../handlers/loader.js' */ /** * @callback FilterAssetCallback * Callback used by {@link AssetRegistry#filter} to filter assets. * @param {Asset} asset - The current asset to filter. * @returns {boolean} Return `true` to include asset to result list. */ /** * @template {AssetType | (string & {})} [K=string] * @callback LoadAssetCallback * Callback used by {@link AssetRegistry#loadFromUrl} and called when an asset is loaded (or an * error occurs). * @param {string|null} err - The error message is null if no errors were encountered. * @param {Asset} [asset] - The loaded asset if no errors were encountered. Its type follows the * `type` passed to {@link AssetRegistry#loadFromUrl}. * @returns {void} */ /** * @callback BundlesFilterCallback * Callback used by {@link ResourceLoader#load} and called when an asset is choosing a bundle * to load from. Return a single bundle to ensure asset is loaded from it. * @param {Asset[]} bundles - List of bundle assets which contain the asset. * @returns {Asset} Return a single bundle asset to ensure asset is loaded from it. */ /** * The AssetRegistry holds every {@link Asset} an application knows about and drives their loading * through the {@link ResourceLoader}. Each application has one at {@link AppBase#assets}. * * Look assets up by id with {@link get}, by name and type with {@link find} and {@link findAll}, by * URL with {@link getByUrl}, or by tag with {@link findByTag}. Register an asset with {@link add}, * or create and load one in a single call with {@link loadFromUrl}, which reuses any asset already * registered for that URL. * * Adding an asset does not fetch it unless {@link Asset#preload} is true. Call {@link load} to * fetch it, then wait with {@link Asset#ready} or listen for the registry's `load`, `error`, `add` * and `remove` events. Each also fires per asset as `load:[id]` and, except for `error`, per URL as * `load:url:[url]`. * * @example * const asset = app.assets.find('brick', 'texture'); * app.assets.load(asset); * asset.ready((asset) => { * material.diffuseMap = asset.resource; * }); * @example * app.assets.loadFromUrl('models/robot.glb', 'container', (err, asset) => { * app.root.addChild(asset.resource.instantiateRenderEntity()); * }); * @category Asset */ declare class AssetRegistry extends EventHandler { /** * Fired when an asset completes loading. This event is available in three forms. They are as * follows: * * 1. `load` - Fired when any asset finishes loading. * 2. `load:[id]` - Fired when a specific asset has finished loading, where `[id]` is the * unique id of the asset. * 3. `load:url:[url]` - Fired when an asset finishes loading whose URL matches `[url]`, where * `[url]` is the URL of the asset. * * @event * @example * app.assets.on('load', (asset) => { * console.log(`Asset loaded: ${asset.name}`); * }); * @example * const id = 123456; * const asset = app.assets.get(id); * app.assets.on('load:' + id, (asset) => { * console.log(`Asset loaded: ${asset.name}`); * }); * app.assets.load(asset); * @example * const id = 123456; * const asset = app.assets.get(id); * app.assets.on('load:url:' + asset.file.url, (asset) => { * console.log(`Asset loaded: ${asset.name}`); * }); * app.assets.load(asset); */ static EVENT_LOAD: string; /** * Fired when an asset is added to the registry. This event is available in three forms. They * are as follows: * * 1. `add` - Fired when any asset is added to the registry. * 2. `add:[id]` - Fired when an asset is added to the registry, where `[id]` is the unique id * of the asset. * 3. `add:url:[url]` - Fired when an asset is added to the registry and matches the URL * `[url]`, where `[url]` is the URL of the asset. * * @event * @example * app.assets.on('add', (asset) => { * console.log(`Asset added: ${asset.name}`); * }); * @example * const id = 123456; * app.assets.on('add:' + id, (asset) => { * console.log(`Asset added: ${asset.name}`); * }); * @example * const id = 123456; * const asset = app.assets.get(id); * app.assets.on('add:url:' + asset.file.url, (asset) => { * console.log(`Asset added: ${asset.name}`); * }); */ static EVENT_ADD: string; /** * Fired when an asset is removed from the registry. This event is available in three forms. * They are as follows: * * 1. `remove` - Fired when any asset is removed from the registry. * 2. `remove:[id]` - Fired when an asset is removed from the registry, where `[id]` is the * unique id of the asset. * 3. `remove:url:[url]` - Fired when an asset is removed from the registry and matches the * URL `[url]`, where `[url]` is the URL of the asset. * * @event * @param {Asset} asset - The asset that was removed. * @example * app.assets.on('remove', (asset) => { * console.log(`Asset removed: ${asset.name}`); * }); * @example * const id = 123456; * app.assets.on('remove:' + id, (asset) => { * console.log(`Asset removed: ${asset.name}`); * }); * @example * const id = 123456; * const asset = app.assets.get(id); * app.assets.on('remove:url:' + asset.file.url, (asset) => { * console.log(`Asset removed: ${asset.name}`); * }); */ static EVENT_REMOVE: string; /** * Fired when an error occurs during asset loading. This event is available in two forms. They * are as follows: * * 1. `error` - Fired when any asset reports an error in loading. * 2. `error:[id]` - Fired when an asset reports an error in loading, where `[id]` is the * unique id of the asset. * * @event * @example * const id = 123456; * const asset = app.assets.get(id); * app.assets.on('error', (err, asset) => { * console.error(err); * }); * app.assets.load(asset); * @example * const id = 123456; * const asset = app.assets.get(id); * app.assets.on('error:' + id, (err, asset) => { * console.error(err); * }); * app.assets.load(asset); */ static EVENT_ERROR: string; /** * Create an instance of an AssetRegistry. * * @param {ResourceLoader} loader - The ResourceLoader used to load the asset files. */ constructor(loader: ResourceLoader); /** * @type {Set} * @private */ private _assets; /** * @type {ResourceLoader} * @private */ private _loader; /** * @type {Map} * @private */ private _idToAsset; /** * @type {Map} * @private */ private _urlToAsset; /** * @type {Map>} * @private */ private _nameToAsset; /** * Index for looking up by tags. * * @private */ private _tags; /** * A URL prefix that will be added to all asset loading requests. * * @type {string|null} */ prefix: string | null; /** * The bundle registry that tracks which assets are packed into bundle assets and serves * their files from loaded bundles. Assigned when the application creates its bundle registry; * null until then. * * @type {BundleRegistry|null} */ bundles: BundleRegistry | null; /** * The ResourceLoader used to load asset files. * * @type {ResourceLoader} * @ignore */ get loader(): ResourceLoader; /** * Create a filtered list of assets from the registry. * * @param {object} [filters] - Filter options. * @param {boolean} [filters.preload] - Filter by preload setting. * @returns {Asset[]} The filtered list of assets. */ list(filters?: { preload?: boolean; }): Asset[]; /** * Add an asset to the registry. If {@link Asset#preload} is `true`, it will also get loaded. * * @param {Asset} asset - The asset to add. * @example * const asset = new Asset("My Asset", "texture", { * url: "../path/to/image.jpg" * }); * app.assets.add(asset); */ add(asset: Asset): void; /** * Remove an asset from the registry. * * @param {Asset} asset - The asset to remove. * @returns {boolean} True if the asset was successfully removed and false otherwise. * @example * const asset = app.assets.get(100); * app.assets.remove(asset); */ remove(asset: Asset): boolean; /** * Destroys the registry, releasing all assets held by it. Called by {@link AppBase#destroy}. * Note that this does not destroy the resources of the assets - {@link Asset#unload} needs to * be called for each asset before the registry is destroyed. * * @ignore */ destroy(): void; /** * Retrieve an asset from the registry by its id field. * * @param {number} id - The id of the asset to get. * @returns {Asset|undefined} The asset. * @example * const asset = app.assets.get(100); */ get(id: number): Asset | undefined; /** * Retrieve an asset from the registry by its file's URL field. * * @param {string} url - The url of the asset to get. * @returns {Asset|undefined} The asset. * @example * const asset = app.assets.getByUrl("../path/to/image.jpg"); */ getByUrl(url: string): Asset | undefined; /** * Load the asset's file from a remote source. Listen for `load` events on the asset to find * out when it is loaded. * * Container-backed render assets wait for the container referenced by `data.containerAsset` * to be registered and loaded before firing `load`. The container can be registered later, * but if it is never registered, the render asset remains loading indefinitely. If that * render asset is marked for preload, it also prevents {@link AppBase#preload} from completing. * * @param {Asset} asset - The asset to load. * @param {object} [options] - Options for asset loading. * @param {boolean} [options.bundlesIgnore] - If set to true, then asset will not try to load * from a bundle. Defaults to false. * @param {boolean} [options.force] - If set to true, then the check of asset being loaded or * is already loaded is bypassed, which forces loading of asset regardless. * @param {BundlesFilterCallback} [options.bundlesFilter] - A callback that will be called * when loading an asset that is contained in any of the bundles. It provides an array of * bundles and will ensure asset is loaded from bundle returned from a callback. By default, * the smallest filesize bundle is chosen. * @example * // load some assets * const assetsToLoad = [ * app.assets.find("My Asset"), * app.assets.find("Another Asset") * ]; * let count = 0; * assetsToLoad.forEach((assetToLoad) => { * assetToLoad.ready((asset) => { * count++; * if (count === assetsToLoad.length) { * // done * } * }); * app.assets.load(assetToLoad); * }); */ load(asset: Asset, options?: { bundlesIgnore?: boolean; force?: boolean; bundlesFilter?: BundlesFilterCallback; }): void; /** * Use this to load and create an asset if you don't have assets created. Usually you would * only use this if you are not integrated with the PlayCanvas Editor. * * The `type` also types the loaded asset: `loadFromUrl(url, 'texture', callback)` passes an * `Asset<'texture'>` to `callback`, whose `resource` is a {@link Texture}. See {@link AssetMap}. * An asset already registered for the URL is reused, whatever its type, so load a URL as one * type only; otherwise the callback can receive an asset of another type than requested. * * @template {AssetType | (string & {})} K * @param {string} url - The url to load. * @param {K} type - The type of asset to load (an {@link AssetType}). * @param {LoadAssetCallback} callback - Function called when asset is loaded, passed (err, * asset), where err is null if no errors were encountered. * @example * app.assets.loadFromUrl("../path/to/texture.jpg", "texture", function (err, asset) { * const texture = asset.resource; // a Texture * }); */ loadFromUrl(url: string, type: K, callback: LoadAssetCallback): void; /** * Use this to load and create an asset when both the URL and filename are required. For * example, use this function when loading BLOB assets, where the URL does not adequately * identify the file. * * @template {AssetType | (string & {})} K * @param {string} url - The url to load. * @param {string} filename - The filename of the asset to load. * @param {K} type - The type of asset to load (an {@link AssetType}). * @param {LoadAssetCallback} callback - Function called when asset is loaded, passed (err, * asset), where err is null if no errors were encountered. * @example * const file = magicallyObtainAFile(); * app.assets.loadFromUrlAndFilename(URL.createObjectURL(file), "texture.png", "texture", function (err, asset) { * const texture = asset.resource; // a Texture * }); */ loadFromUrlAndFilename(url: string, filename: string, type: K, callback: LoadAssetCallback): void; loadFromUrlError: any; _loadModel(modelAsset: any, continuation: any): void; _loadMaterials(modelAsset: any, mapping: any, callback: any): void; _loadTextures(materialAsset: any, callback: any): void; _onTagAdd(tag: any, asset: any): void; _onTagRemove(tag: any, asset: any): void; _onNameChange(asset: any, name: any, nameOld: any): void; /** * Return all Assets that satisfy the search query. Query can be simply a string, or comma * separated strings, to have inclusive results of assets that match at least one query. A * query that consists of an array of tags can be used to match assets that have each tag of * array. * * @param {...*} query - Name of a tag or array of tags. * @returns {Asset[]} A list of all Assets matched query. * @example * const assets = app.assets.findByTag("level-1"); * // returns all assets that tagged by `level-1` * @example * const assets = app.assets.findByTag("level-1", "level-2"); * // returns all assets that tagged by `level-1` OR `level-2` * @example * const assets = app.assets.findByTag(["level-1", "monster"]); * // returns all assets that tagged by `level-1` AND `monster` * @example * const assets = app.assets.findByTag(["level-1", "monster"], ["level-2", "monster"]); * // returns all assets that tagged by (`level-1` AND `monster`) OR (`level-2` AND `monster`) */ findByTag(...query: any[]): Asset[]; /** * Return all Assets that satisfy a filter callback. * * @param {FilterAssetCallback} callback - The callback function that is used to filter assets. * Return `true` to include an asset in the returned array. * @returns {Asset[]} A list of all Assets found. * @example * const assets = app.assets.filter(asset => asset.name.includes('monster')); * console.log(`Found ${assets.length} assets with a name containing 'monster'`); */ filter(callback: FilterAssetCallback): Asset[]; /** * Return the first Asset with the specified name and type found in the registry. * * The `type` also types the result: `find('brick', 'texture')` returns * `Asset<'texture'> | null`, whose `resource` is a {@link Texture}. See {@link AssetMap}. * * @template {AssetType | (string & {})} K * @overload * @param {string} name - The name of the Asset to find. * @param {K} type - The type of the Asset to find (an {@link AssetType}). * @returns {Asset|null} A single Asset or null if no Asset is found. * @example * const asset = app.assets.find("myTextureAsset", "texture"); * if (asset) { * const texture = asset.resource; // a Texture * } */ find(name: string, type: K): Asset | null; /** * Return the first Asset with the specified name found in the registry, of any type or of a * type only known as a `string`. The result is a plain `Asset`, whose `resource` is `unknown`. * * @overload * @param {string} name - The name of the Asset to find. * @param {string} [type] - The type of the Asset to find. * @returns {Asset|null} A single Asset or null if no Asset is found. * @example * const asset = app.assets.find("myAsset"); */ find(name: string, type?: string): Asset | null; /** * Return all Assets with the specified name and type found in the registry. * * The `type` also types the result, as for {@link AssetRegistry#find}: * `findAll('brick', 'texture')` returns `Asset<'texture'>[]`. * * @template {AssetType | (string & {})} K * @overload * @param {string} name - The name of the Assets to find. * @param {K} type - The type of the Assets to find (an {@link AssetType}). * @returns {Asset[]} A list of all Assets found. * @example * const assets = app.assets.findAll('brick', 'texture'); * console.log(`Found ${assets.length} texture assets named 'brick'`); * const textures = assets.map(asset => asset.resource); // Texture[] */ findAll(name: string, type: K): Asset[]; /** * Return all Assets with the specified name found in the registry, of any type or of a type * only known as a `string`. * * @overload * @param {string} name - The name of the Assets to find. * @param {string} [type] - The type of the Assets to find. * @returns {Asset[]} A list of all Assets found. * @example * const assets = app.assets.findAll('brick'); */ findAll(name: string, type?: string): Asset[]; /** * Logs all assets in the registry to the console. Used for debugging with TRACEID_ASSETS. * * @ignore */ log(): void; /** * Retrieve an asset from the registry by its id. * * @param {number} id - The id of the asset to get. * @returns {Asset|undefined} The asset. * @ignore * @deprecated Use {@link AssetRegistry#get} instead. */ getAssetById(id: number): Asset | undefined; } /** * Callback used by {@link ResourceLoader#load} when a resource is loaded (or an error occurs). */ type ResourceLoaderCallback = (err: string | null, resource?: any) => void; /** * @import { AppBase } from '../app-base.js' * @import { AssetRegistry } from '../asset/asset-registry.js' * @import { Asset } from '../asset/asset.js' * @import { AssetType } from '../asset/asset.js' * @import { BundlesFilterCallback } from '../asset/asset-registry.js' * @import { ResourceHandler } from './handler.js' */ /** * @callback ResourceLoaderCallback * Callback used by {@link ResourceLoader#load} when a resource is loaded (or an error occurs). * @param {string|null} err - The error message in the case where the load fails. * @param {any} [resource] - The resource that has been successfully loaded. * @returns {void} */ /** * The ResourceLoader turns a URL and an asset type into a loaded resource. It owns one * {@link ResourceHandler} per type, dispatches each request to the matching handler, and caches the * result by URL and type so the same request is fetched once. Each application has one at * {@link AppBase#loader}. * * Most code never calls the loader directly: the {@link AssetRegistry} does so on its behalf when * an {@link Asset} loads. Use the loader to add support for a new asset type with * {@link addHandler}, to reach an existing handler with {@link getHandler}, or to tune requests * with {@link maxConcurrentRequests}, {@link withCredentials} and {@link enableRetry}. * * Parsers for formats the engine does not load by default ship in the package and are registered on * an existing handler rather than added as one: `playcanvas/scripts/esm/parsers/obj-model.mjs` adds * `.obj` model loading and `playcanvas/scripts/esm/parsers/spz-parser.mjs` adds `.spz` * Gaussian-splat loading. * * @example * app.loader.getHandler('model').addParser(new ObjModelParser(app.graphicsDevice)); * @example * app.loader.getHandler('gsplat').addParser(new SpzParser(app)); * @category Asset */ declare class ResourceLoader { static makeKey(url: any, type: any): string; /** * Create a new ResourceLoader instance. * * @param {AppBase} app - The application. */ constructor(app: AppBase); _handlers: {}; _requests: {}; _cache: {}; _app: AppBase; /** * Add a {@link ResourceHandler} for a resource type. Handler should support at least `load()` * and `open()`. Handlers can optionally support patch(asset, assets) to handle dependencies on * other assets. * * @param {AssetType | (string & {})} type - The name of the resource type that the handler will * be registered with: one of the built-in {@link AssetType} names, such as `'texture'`, `'model'` * or `'container'`, or a new name for an application-defined handler. See {@link AssetMap} for * typing the resource of a new name. * @param {ResourceHandler} handler - An instance of a resource handler * supporting at least `load()` and `open()`. * @example * // register a handler for a new 'csv' asset type (see ResourceHandler for the class) * app.loader.addHandler('csv', new CsvHandler(app)); */ addHandler(type: AssetType | (string & {}), handler: ResourceHandler): void; /** * Remove a {@link ResourceHandler} for a resource type. * * @param {AssetType | (string & {})} type - The name of the type that the handler will be removed. */ removeHandler(type: AssetType | (string & {})): void; /** * Get a {@link ResourceHandler} for a resource type. * * @param {AssetType | (string & {})} type - The name of the resource type that the handler is * registered with. * @returns {ResourceHandler|undefined} The registered handler, or * undefined if the requested handler is not registered. */ getHandler(type: AssetType | (string & {})): ResourceHandler | undefined; /** * Make a request for a resource from a remote URL. Parse the returned data using the handler * for the specified type. When loaded and parsed, use the callback to return an instance of * the resource. * * @param {string} url - The URL of the resource to load. * @param {string} type - The type of resource expected. * @param {ResourceLoaderCallback} callback - The callback used when the resource is loaded or * an error occurs. Passed (err, resource) where err is null if there are no errors. * @param {Asset} [asset] - Optional asset that is passed into * handler. * @param {object} [options] - Additional options for loading. * @param {boolean} [options.bundlesIgnore] - If set to true, then asset will not try to load * from a bundle. Defaults to false. * @param {BundlesFilterCallback} [options.bundlesFilter] - A callback that will be called * when loading an asset that is contained in any of the bundles. It provides an array of * bundles and will ensure asset is loaded from bundle returned from a callback. By default, * the smallest filesize bundle is chosen. * @example * app.loader.load("../path/to/texture.png", "texture", function (err, texture) { * // use texture here * }); */ load(url: string, type: string, callback: ResourceLoaderCallback, asset?: Asset, options?: { bundlesIgnore?: boolean; bundlesFilter?: BundlesFilterCallback; }): void; _loadNull(handler: any, callback: any, asset: any): void; _onSuccess(key: any, result: any, extra: any): void; _onFailure(key: any, err: any): void; /** * Convert raw resource data into a resource instance. E.g. Take 3D model format JSON and * return a {@link Model}. * * @param {string} type - The type of resource. * @param {*} data - The raw resource data. * @returns {*} The parsed resource data. */ open(type: string, data: any): any; /** * Perform any operations on a resource, that requires a dependency on its asset data or any * other asset data. * * @param {Asset} asset - The asset to patch. * @param {AssetRegistry} assets - The asset registry. */ patch(asset: Asset, assets: AssetRegistry): void; /** * Remove resource from cache. * * @param {string} url - The URL of the resource. * @param {string} type - The type of resource. */ clearCache(url: string, type: string): void; /** * Check cache for resource from a URL. If present, return the cached value. * * @param {string} url - The URL of the resource to get from the cache. * @param {string} type - The type of the resource. * @returns {*} The resource loaded from the cache. */ getFromCache(url: string, type: string): any; /** * Enables retrying of failed requests when loading assets. Retries use exponential backoff and * are also enabled by default for new applications. * * @param {number} [maxRetries] - The maximum number of times to retry loading an asset. * Defaults to 5. */ enableRetry(maxRetries?: number): void; /** * Disables retrying of failed requests when loading assets. */ disableRetry(): void; /** * Sets the maximum number of asset requests that can be in flight at the same time. Additional * requests are queued and dispatched as earlier ones complete. This prevents browsers from * rejecting requests with `net::ERR_INSUFFICIENT_RESOURCES` when an app loads a very large * number of assets at once. Set to `0` to disable throttling. Defaults to 128. * * Note: this is a process-global limit (it applies to the shared HTTP layer, matching the * browser's per-process resource limit), so with multiple applications the last value set wins. * It applies to all XHR-based requests, which covers the large majority of asset loads. * * @type {number} * @example * // never have more than 50 asset requests in flight at once * app.loader.maxConcurrentRequests = 50; */ set maxConcurrentRequests(value: number); /** * Gets the maximum number of asset requests that can be in flight at the same time. * * @type {number} */ get maxConcurrentRequests(): number; /** * Sets whether asset requests are sent with credentials. When true, cross-origin requests * include credentials (cookies, client TLS certificates and HTTP authentication), allowing * assets to be loaded from an authenticated cross-origin host. The server must respond with a * non-wildcard `Access-Control-Allow-Origin` and `Access-Control-Allow-Credentials: true`. * Defaults to false. * * Set this before assets start loading (i.e. before {@link AppBase#preload} or * {@link AssetRegistry#load}). Note this is a process-global setting (it applies to the shared * HTTP layer), so with multiple applications the last value set wins. It covers every asset * load, including the asset bundle and gaussian splat loaders that fetch their data directly * rather than through the HTTP layer. * * @type {boolean} * @example * // load all assets from an authenticated cross-origin host * app.loader.withCredentials = true; */ set withCredentials(value: boolean); /** * Gets whether asset requests are sent with credentials. * * @type {boolean} */ get withCredentials(): boolean; /** * Destroys the resource loader. */ destroy(): void; } /** * @import { ResourceLoader } from '../handlers/loader.js' * @import { Texture } from '../../platform/graphics/texture.js' */ /** * Represents the resource of a font asset. * * @category User Interface */ declare class Font { /** * Create a new Font instance. * * @param {Texture[]} textures - The font textures. * @param {object} data - The font data. */ constructor(textures: Texture[], data: object); type: any; em: number; /** * The font textures. * * @type {Texture[]} */ textures: Texture[]; /** * The font intensity. */ intensity: number; /** * The resource loader used to load the font textures. Set by the {@link FontHandler} so * that {@link Font#destroy} can release the textures from the loader cache. Null for fonts * created without going through the resource loader. * * @type {ResourceLoader|null} * @ignore */ _loader: ResourceLoader | null; _data: any; set data(value: any); get data(): any; /** * Frees the GPU textures owned by the font and removes them from the resource loader cache. * Called automatically when the owning font asset is unloaded (see {@link Asset#unload}). */ destroy(): void; } /** * Represents the resource of a canvas font asset. * * @ignore */ declare class CanvasFont extends EventHandler { /** * Create a new CanvasFont instance. * * @param {AppBase} app - The application. * @param {object} options - The font options. * @param {string} [options.fontName] - The name of the font. CSS font names are supported. * Defaults to 'Arial'. * @param {string} [options.fontWeight] - The weight of the font, e.g. 'normal', 'bold'. * Defaults to 'normal'. * @param {number} [options.fontSize] - The font size in pixels. Defaults to 32. * @param {Color} [options.color] - The font color.Defaults to white. * @param {number} [options.width] - The width of each texture atlas. Defaults to 512. * @param {number} [options.height] - The height of each texture atlas. Defaults to 512. * @param {number} [options.padding] - Amount of glyph padding in pixels that is added to each * glyph in the atlas. Defaults to 0. */ constructor(app: AppBase, options?: { fontName?: string; fontWeight?: string; fontSize?: number; color?: Color; width?: number; height?: number; padding?: number; }); type: string; app: AppBase; intensity: number; fontWeight: string; fontSize: number; glyphSize: number; fontName: string; color: Color; padding: number; width: number; height: number; atlases: any[]; chars: string; data: {}; /** * Render the necessary textures for all characters in a string to be used for the canvas font. * * @param {string} text - The list of characters to render into the texture atlas. */ createTextures(text: string): void; /** * Update the list of characters to include in the atlas to include those provided and * re-render the texture atlas to include all the characters that have been supplied so far. * * @param {string} text - The list of characters to add to the texture atlas. */ updateTextures(text: string): void; /** * Destroys the font. This also destroys the textures owned by the font. */ destroy(): void; /** * @param {Color} color - The color to covert. * @param {boolean} alpha - Whether to include the alpha channel. * @returns {string} The hex string for the color. * @private */ private _colorToRgbString; /** * @param {CanvasRenderingContext2D} context - The canvas 2D context. * @param {string} char - The character to render. * @param {number} x - The x position to render the character at. * @param {number} y - The y position to render the character at. * @param {string} color - The color to render the character in. * @ignore */ renderCharacter(context: CanvasRenderingContext2D, char: string, x: number, y: number, color: string): void; /** * Return the atlas at the specified index. * * @param {number} index - The atlas index * @private */ private _getAtlas; /** * Renders an array of characters into one or more textures atlases. * * @param {string[]} charsArray - The list of characters to render. * @private */ private _renderAtlas; /** * @param {string[]} chars - A list of characters. * @param {string} fontName - The font name. * @param {number} width - The width of the texture atlas. * @param {number} height - The height of the texture atlas. * @returns {object} The font JSON object. * @private */ private _createJson; /** * @param {object} json - Font data. * @param {string} char - The character to add. * @param {number} charCode - The code point number of the character to add. * @param {number} x - The x position of the character. * @param {number} y - The y position of the character. * @param {number} w - The width of the character. * @param {number} h - The height of the character. * @param {number} xoffset - The x offset of the character. * @param {number} yoffset - The y offset of the character. * @param {number} xadvance - The x advance of the character. * @param {number} mapNum - The map number of the character. * @param {number} mapW - The width of the map. * @param {number} mapH - The height of the map. * @private */ private _addChar; /** * Take a unicode string and produce the set of characters used to create that string. * e.g. "abcabcabc" -> ['a', 'b', 'c'] * * @param {string} text - The unicode string to process. * @returns {string[]} The set of characters used to create the string. * @private */ private _normalizeCharsSet; /** * Calculate some metrics that aren't available via the browser API, notably character height * and descent size. * * @param {string} text - The text to measure. * @returns {{ascent: number, descent: number, height: number}} The metrics of the text. * @private */ private _getTextMetrics; get textures(): any[]; } type GSplatOctreeNodeLod = { /** * - The file path */ file: string; /** * - The file index in the octree files array */ fileIndex: number; /** * - The offset in the file */ offset: number; /** * - The count of items */ count: number; }; declare class GSplatOctreeNode { /** * @param {GSplatOctreeNodeLod[]} lods - The LOD data for this node * @param {Object} [boundData] - The bounding box data with min and max arrays */ constructor(lods: GSplatOctreeNodeLod[], boundData?: any); /** * @type {GSplatOctreeNodeLod[]} */ lods: GSplatOctreeNodeLod[]; /** * The axis-aligned bounding box of this octree node in local space. */ bounds: BoundingBox; /** * Precomputed bounding sphere derived from the AABB. Stored as (center.x, center.y, * center.z, radius) for efficient GPU frustum culling. */ boundingSphere: Vec4; } /** @ignore */ declare class GSplatResource extends GSplatResourceBase { /** * @param {GraphicsDevice} device - The graphics device. * @param {GSplatData} gsplatData - The splat data. * @param {object} [options] - Passed to {@link GSplatResourceBase} constructor. */ constructor(device: GraphicsDevice, gsplatData: GSplatData, options?: object); /** @type {0 | 1 | 2 | 3} */ shBands: 0 | 1 | 2 | 3; configureMaterialDefines(defines: any): void; /** * Updates pixel data of splatColor texture based on the supplied color components and opacity. * Assumes that the texture is using an RGBA format where RGB are color components influenced * by SH spherical harmonics and A is opacity after a sigmoid transformation. * * @param {GSplatData} gsplatData - The source data */ updateColorData(gsplatData: GSplatData): void; /** * @param {GSplatData} gsplatData - The source data */ updateTransformData(gsplatData: GSplatData): void; /** * @param {GSplatData} gsplatData - The source data */ updateSHData(gsplatData: GSplatData): void; } /** * Base class for GSplat asset loaders. This provides the interface that all * GSplat asset loaders must implement. * * @category Asset * @ignore */ declare class GSplatAssetLoaderBase { /** * Initiates loading of a gsplat asset. This is a fire-and-forget operation that starts * the loading process. * * @param {string} url - The URL of the gsplat file to load. * @param {number} [priority] - Load priority, higher loads first. When omitted, a queued load * keeps its current priority. * @abstract */ load(url: string, priority?: number): void; /** * Removes a load that has not started yet. Loaders without a queue have nothing to remove. * * @param {string} url - The URL of the gsplat file. * @returns {boolean} True if a waiting load was removed. */ dequeue(url: string): boolean; /** * Unloads an asset that was previously loaded by this loader. * * @param {string} url - The URL of the asset to unload. * @abstract */ unload(url: string): void; /** * Gets the resource for a given URL if it has been loaded by this loader. * * @param {string} url - The URL of the asset to retrieve the resource from. * @returns {object|undefined} The loaded resource if found and loaded, undefined otherwise. * @abstract */ getResource(url: string): object | undefined; /** * Destroys the loader and cleans up any resources it holds. * * @abstract */ destroy(): void; } /** * @import { GSplatOctree } from './gsplat-octree.js' */ /** * Everything the LOD allocator needs to know about an octree before it sees a camera, precomputed * once per LOD range. * * LOD selection is by distance band: a node's band is the LOD index its distance calls for, * clamped to the range. The table maps each band to the level the node actually renders for it, * and that level's splat count. Normally that is the band itself, since every level is kept - a * node whose levels barely differ in splat count still renders the level its distance asks for, so * nearby nodes keep sharing the same files instead of pulling in finer ones for a handful of * splats. * * Levels a node has no data for are resolved to one it has: * - A gap between two levels with data renders the next finer level with data, or the next coarser * one when there is nothing finer. * - A node whose data stops before `rangeMax` - the generator decimated the region to nothing at * the coarser levels - renders nothing at the bands past its coarsest data. That is its *empty* * level: zero splats and no file, placed at the first missing index. Without it such a node would * be pinned to its finest available data at any distance, which loads a whole file for a handful * of splats. * * The distinct levels of a node's bands, coarsest first, form its *chain*: the states streaming and * underfill step through. Chain entries are ordered by LOD index, not by splat count - nothing * guarantees a coarser level holds fewer splats, and barely decimated nodes often do not. * * @ignore */ declare class GSplatLodTable { /** * @param {GSplatOctree} octree - The octree to build the table for. * @param {number} rangeMin - Finest allowed LOD index. * @param {number} rangeMax - Coarsest allowed LOD index. */ constructor(octree: GSplatOctree, rangeMin: number, rangeMax: number); /** * Finest allowed LOD index. * * @type {number} */ rangeMin: number; /** * Coarsest allowed LOD index. * * @type {number} */ rangeMax: number; /** * Number of bands, `rangeMax - rangeMin + 1`, and so the row length of * {@link GSplatLodTable#bandLod} and {@link GSplatLodTable#bandCount}. * * @type {number} */ span: number; /** * How many octree instances currently hold this table. Managed by the owning * {@link GSplatOctree}, which drops the table when this reaches zero - so a table is retained * exactly while some instance is using its range, rather than on a fixed cap that could evict * one still in use. * * @type {number} */ refCount: number; /** * Per node and band, the LOD index rendered for that band. Node `n`, band `b` (absolute LOD * index `rangeMin + b`) is at `n * span + b`. -1 across the whole row when the node has nothing * renderable in range. May be the node's empty level, which has no file. * * @type {Int16Array} */ bandLod: Int16Array; /** * Per node and band, the splat count of {@link GSplatLodTable#bandLod}. Same layout. * * @type {Int32Array} */ bandCount: Int32Array; /** * Sum of the coarsest band's splat count over all nodes - the splat cost of the whole octree at * its coarsest. * * @type {number} */ totalCoarsestCount: number; /** * Sum of the finest band's splat count over all nodes - the splat cost of the whole octree at * its finest. * * @type {number} */ totalFinestCount: number; /** * Walks a node's chain to the coarsest level that is no finer than `lod` and no coarser than * `limit` levels above it, preferring the finest such level that satisfies `accept`. * * Streaming fallbacks use this instead of walking raw LOD indices, so they can only ever pick * a level the allocator itself could choose. * * @param {number} nodeIndex - The node. * @param {number} lod - The target LOD index, expected to be on the node's chain. * @param {number} limit - How many chain steps coarser than the target are acceptable. * @param {(lod: number) => boolean} accept - Predicate a level must satisfy. * @returns {number} The chosen LOD index, or -1 when nothing in the window qualifies. */ findCoarserAccepted(nodeIndex: number, lod: number, limit: number, accept: (lod: number) => boolean): number; /** * Returns the next coarser level on a node's chain, or -1 when `lod` is already its coarsest. * * @param {number} nodeIndex - The node. * @param {number} lod - A LOD index on the node's chain. * @returns {number} The next coarser chain entry, or -1. */ coarserOnChain(nodeIndex: number, lod: number): number; /** * Returns the next finer level on a node's chain, or -1 when `lod` is already its finest. * * @param {number} nodeIndex - The node. * @param {number} lod - A LOD index on the node's chain. * @returns {number} The next finer chain entry, or -1. */ finerOnChain(nodeIndex: number, lod: number): number; } /** * @import { GSplatResource } from '../gsplat/gsplat-resource.js' * @import { GSplatOctreeNodeLod } from './gsplat-octree-node.js' * @import { GSplatAssetLoaderBase } from './gsplat-asset-loader-base.js' */ declare class GSplatOctree { /** * Computes {@link GSplatOctree#nodeBoundsExcess} from packed node bounds. * * @param {Float32Array} boundsFlat - Packed per-node bounds, see nodeBoundsMinMax. * @param {number} nodeCount - Number of nodes. * @returns {Float32Array} The per-node, per-axis excess over the median half extent. * @private */ private static _computeBoundsExcess; /** * @param {string} assetFileUrl - The file URL of the container asset. * @param {Object} data - The parsed JSON data containing info, filenames and tree. */ constructor(assetFileUrl: string, data: any); /** * @type {GSplatOctreeNode[]} */ nodes: GSplatOctreeNode[]; /** * Packed per-node axis-aligned bounds in octree local space for CPU hot paths (e.g. LOD). * Length is {@link GSplatOctree.nodes}.length * 6. For node index `i`, base `b = i * 6`: * `[minX, minY, minZ, maxX, maxY, maxZ]` matching {@link GSplatOctreeNode.bounds}. * * @type {Float32Array} */ nodeBoundsMinMax: Float32Array; /** * Per node, how far its half extents exceed the octree's typical node on each axis - zero on * any axis where the node is no larger. Length is {@link GSplatOctree.nodes}.length * 3, * `[x, y, z]` per node. The typical node is the median half extent on each axis, so it follows * the content: a node standing out from its neighbours in size, such as a sparse region the * generator left as one wide node, has an excess, while ordinary nodes have none. The distance * pass trims only this excess - see GSplatParams#lodDistanceShrink. * * @type {Float32Array} */ nodeBoundsExcess: Float32Array; /** * @type {{ url: string, lodLevel: number }[]} */ files: { url: string; lodLevel: number; }[]; /** * @type {number} */ lodLevels: number; /** * Precomputed LOD selection tables, keyed by the LOD range they were built for and shared by * every instance of this octree using that range. * * `lodRangeMin`/`lodRangeMax` are per placement, so instances of one octree may legitimately * differ and each live range needs its own table - holding only the most recent would rebuild * on every request. Entries are reference counted by the instances holding them and dropped at * zero, so nothing is retained for a range that has fallen out of use, and nothing still in use * can be evicted. * * @type {Map} * @private */ private _lodTables; /** * The file URL of the container asset, used as the base for resolving relative URLs. * * @type {string} */ assetFileUrl: string; /** * Resources of individual files, identified by their file index. * * @type {Map} */ fileResources: Map; /** * Reference counts for each file by file index. Index is fileIndex, value is reference count. * When a file reaches zero references, it is scheduled for cooldown and unload. * * @type {Int32Array} */ fileRefCounts: Int32Array; /** * Cooldown timers for files that reached zero references. Key is fileIndex, value is ticks * remaining. * * @type {Map} */ cooldowns: Map; /** * The latest file requests of each instance of this octree, mapped to their load priority. * An instance replaces its own set on each of its LOD updates and keeps it in between, so the * requests of an instance whose camera is not re-evaluating LOD stay alive. * * @type {Map>} * @private */ private _requesters; /** * Files whose request changed since the last {@link GSplatOctree#flushRequests} - those in a * newly submitted set, and those an instance stopped requesting. Each is issued again at its * current highest priority, or withdrawn when no instance requests it any more. * * @type {Set} * @private */ private _changedRequests; /** * Token of the last {@link GSplatOctree#updateCooldownTick} that advanced the cooldowns. * * @type {number|undefined} * @private */ private _cooldownToken; /** * Optional environment asset URL. * * @type {string|null} */ environmentUrl: string | null; /** * Loaded environment resource. * * @type {GSplatResource|null} */ environmentResource: GSplatResource | null; /** * Reference count for environment usage. */ environmentRefCount: number; /** * Asset loader used for loading/unloading resources. * * @type {GSplatAssetLoaderBase|null} */ assetLoader: GSplatAssetLoaderBase | null; /** * Whether this octree has been destroyed. */ destroyed: boolean; /** * Number of update ticks before unloading unused file resources. Set from GSplatParams. * * @private */ private cooldownTicks; /** * Destroys the octree and clears internal state. Does not force-unload resources as they may * still be referenced by managers. Resources will be cleaned up when their reference counts * reach zero through the normal cleanup mechanisms. */ destroy(): void; /** * Trace out per-LOD counts of currently loaded file resources. * * @private */ private _traceLodCounts; /** * Takes a reference to the LOD selection table for a LOD range, building it on first use. The * caller must pass it back to {@link GSplatOctree#releaseLodTable} when it stops using it. * * The table has to be per range, because the range decides how bands past a node's data, and * gaps in it, resolve. * * @param {number} rangeMin - Finest allowed LOD index. * @param {number} rangeMax - Coarsest allowed LOD index. * @returns {GSplatLodTable} The selection table, with its reference count incremented. */ acquireLodTable(rangeMin: number, rangeMax: number): GSplatLodTable; /** * Releases a reference taken by {@link GSplatOctree#acquireLodTable}, dropping the table once * no instance holds it. * * @param {GSplatLodTable|null} table - The table to release. Null is ignored, so callers can * release unconditionally. */ releaseLodTable(table: GSplatLodTable | null): void; /** * Recursively extracts leaf nodes (nodes with 'lods' property) from the hierarchical tree. * * @param {Object} node - The current tree node to process. * @param {Array} leafNodes - Array to collect leaf nodes. * @private */ private _extractLeafNodes; getFileResource(fileIndex: any): GSplatResource; /** * Increments reference count for a file by index and cancels any pending cooldown. * * @param {number} fileIndex - Index of the file in `files` array. */ incRefCount(fileIndex: number): void; /** * Decrements reference count for a file by index. When it reaches zero, either unload * immediately (if cooldownTicks is 0) or schedule for cooldown. * * @param {number} fileIndex - Index of the file in `files` array. * @param {number} cooldownTicks - Number of update ticks before unloading when unused. If 0, * unload immediately. */ decRefCount(fileIndex: number, cooldownTicks: number): void; /** * Unloads a resource for a file index if currently loaded. * * @param {number} fileIndex - Index of the file in `files` array. */ unloadResource(fileIndex: number): void; /** * Advances cooldowns for zero-ref files and unloads those whose timers expired. * * @param {number} cooldownTicks - Number of ticks for new cooldowns, synced from GSplatParams. * @param {number} [token] - Per-frame token. Every world using this octree ticks it, one per * camera and layer, so a repeated token is ignored to advance the cooldowns once per frame. * When omitted, every call advances them. */ updateCooldownTick(cooldownTicks: number, token?: number): void; /** * Checks whether a file has finished loading, and stores its resource if so. * * @param {number} fileIndex - The index of the file in the `files` array. * @returns {boolean} True if the file is loaded. */ pollFileResource(fileIndex: number): boolean; /** * Ensures a file resource is loaded and available. This function: * - Starts loading if not already started * - Checks if loading completed and stores the resource if available * * A load it starts or continues keeps whatever priority it was last requested with. * * @param {number} fileIndex - The index of the file in the `files` array. */ ensureFileResource(fileIndex: number): void; /** * Replaces the file requests of one instance of this octree - the files it waits for, mapped to * their load priority. Nothing is loaded until {@link GSplatOctree#flushRequests}, which lets * every instance sharing this octree contribute before the requests are ordered. * * @param {object} requester - The instance the requests belong to. * @param {Map} requests - File indices mapped to their load priority, higher * loads first. Copied, so the caller may reuse the map. */ submitRequests(requester: object, requests: Map): void; /** * Removes all file requests of an instance of this octree, when the instance is destroyed. This * takes effect straight away, as there may be no later {@link GSplatOctree#flushRequests} to * apply it: the files no other instance requests are withdrawn, and the rest are re-issued at * the highest priority the remaining instances give them. * * @param {object} requester - The instance the requests belong to. * @param {boolean} unloadNow - When true, a withdrawn download already in progress is unloaded * right away instead of after a cooldown. */ removeRequests(requester: object, unloadNow: boolean): void; /** * Issues the requests that changed since the last flush to the asset loader, each at the * highest priority any instance gives it and highest first, and withdraws the files no * instance requests any more. * * Every instance re-requests each file it still waits for on every LOD update, so a file no * instance's latest requests contain is no longer wanted. If it is still queued it is simply * dropped, as nothing has been fetched yet. A download already in progress is left to finish - * canceling it would waste the transfer if the camera swings back - and if nothing references * the file it gets a cooldown, so it is released once the cooldown expires unless it is * requested again. */ flushRequests(): void; /** * Returns the highest load priority any instance requests a file with. * * @param {number} fileIndex - The index of the file in the `files` array. * @returns {number|undefined} The priority, or undefined when no instance requests the file. * @private */ private _getRequestPriority; /** * Withdraws the load of a file no instance requests any more. A queued load is dropped. One * already in progress is left running, and if nothing references the file it is unloaded - * after a cooldown, or right away when asked to. * * @param {number} fileIndex - The index of the file in the `files` array. * @param {boolean} unloadNow - Unload an unreferenced download right away. * @private */ private _withdrawRequest; /** * Increments reference count for environment. */ incEnvironmentRefCount(): void; /** * Decrements reference count for environment. When it reaches zero, immediately unload. */ decEnvironmentRefCount(): void; /** * Ensures environment resource is loaded and available. */ ensureEnvironmentResource(): void; /** * Unloads environment resource if currently loaded. */ unloadEnvironmentResource(): void; } declare class GSplatOctreeResource { /** * @param {string} assetFileUrl - The file URL of the container asset. * @param {object} data - Parsed JSON data. * @param {object} assetLoader - Asset loader instance (framework-level object). */ constructor(assetFileUrl: string, data: object, assetLoader: object); /** @type {BoundingBox} */ aabb: BoundingBox; /** * Version counter for centers array changes. Always 0 for octree resources (static). * * @ignore */ centersVersion: number; /** @type {GSplatOctree|null} */ octree: GSplatOctree | null; /** * Cached total splat count at full detail (LOD 0). Lazily computed by {@link numSplats}. * * @type {number|null} * @private */ private _numSplats; /** * Raw parsed manifest data, retained for consumers that read custom or extension * fields the octree itself does not consume (for example application-specific * metadata accompanying a `lod-meta.json`). The `tree` field is nulled out by the * constructor since {@link GSplatOctree} consumes it — access node hierarchy via * {@link GSplatOctreeResource#octree} instead. * * @type {object} */ data: object; /** * Total number of splats across all leaf nodes at the highest LOD (LOD 0) — the full-detail * splat count of the captured scene. Not all of these are resident at runtime: the LOD * streaming system selects a subset per node based on view distance and the configured * splat budget. * * @type {number} */ get numSplats(): number; /** * Destroys the octree resource and cleans up all associated resources. */ destroy(): void; } /** * Tags is a powerful tag management system for categorizing and filtering objects in PlayCanvas * applications. It provides an efficient way to attach string identifiers to objects and query them * using logical operations. * * Tags are automatically available on {@link Asset}s and {@link Entity}s (see {@link Asset#tags} * and {@link GraphNode#tags}). You can search for specific assets via {@link AssetRegistry#findByTag} * and specific entities via {@link GraphNode#findByTag}. * * @category Framework */ declare class Tags extends EventHandler { /** * Fired for each individual tag that is added. * * @event * @example * tags.on('add', (tag, parent) => { * console.log(`${tag} added to ${parent.name}`); * }); */ static EVENT_ADD: string; /** * Fired for each individual tag that is removed. * * @event * @example * tags.on('remove', (tag, parent) => { * console.log(`${tag} removed from ${parent.name}`); * }); */ static EVENT_REMOVE: string; /** * Fired when tags have been added or removed. It will fire once on bulk changes, while `add` * and `remove` will fire on each tag operation. * * @event * @example * tags.on('change', (parent) => { * console.log(`Tags changed on ${parent.name}`); * }); */ static EVENT_CHANGE: string; /** * Create a new Tags instance. * * @param {object} [parent] - Parent object who tags belong to. */ constructor(parent?: object); /** @private */ private _index; /** @private */ private _list; /** * @type {object} * @private */ private _parent; /** * Add a tag, duplicates are ignored. Can be array or comma separated arguments for multiple tags. * * @param {...*} args - Name of a tag, or array of tags. * @returns {boolean} True if any tag were added. * @example * tags.add('level-1'); * @example * tags.add('ui', 'settings'); * @example * tags.add(['level-2', 'mob']); */ add(...args: any[]): boolean; /** * Remove tag. * * @param {...*} args - Name of a tag or array of tags. * @returns {boolean} True if any tag were removed. * @example * tags.remove('level-1'); * @example * tags.remove('ui', 'settings'); * @example * tags.remove(['level-2', 'mob']); */ remove(...args: any[]): boolean; /** * Remove all tags. * * @example * tags.clear(); */ clear(): void; /** * Check if tags satisfy filters. Filters can be provided by simple name of tag, as well as by * array of tags. When an array is provided it will check if tags contain each tag within the * array. If any of comma separated argument is satisfied, then it will return true. Any number * of combinations are valid, and order is irrelevant. * * @param {...*} query - Name of a tag or array of tags. * @returns {boolean} True if filters are satisfied. * @example * tags.has('player'); // player * @example * tags.has('mob', 'player'); // player OR mob * @example * tags.has(['level-1', 'mob']); // monster AND level-1 * @example * tags.has(['ui', 'settings'], ['ui', 'levels']); // (ui AND settings) OR (ui AND levels) */ has(...query: any[]): boolean; /** * @param {string[]|string[][]} tags - Array of tags. * @returns {boolean} True if the supplied tags are present. * @private */ private _has; /** * Returns immutable array of tags. * * @returns {string[]} Copy of tags array. */ list(): string[]; /** * @param {Array} args - Arguments to process. * @param {boolean} [flat] - If true, will flatten array of tags. Defaults to false. * @returns {string[]|string[][]} Array of tags. * @private */ private _processArguments; /** * Number of tags in set. * * @type {number} */ get size(): number; } /** * @import { Mat4 } from './mat4.js' * @import { Quat } from './quat.js' */ /** * A 3x3 matrix. Mat3 is commonly used to represent rotation matrices, 2D transformations or the * upper-left portion of a 4x4 matrix for transforming normals. * * A new Mat3 is the identity. Elements live in {@link data}, a 9-element `Float32Array` in * column-major order, so the first three entries are the first column. Build one from a rotation * with {@link setFromQuat}, or take the upper-left 3x3 of a {@link Mat4} with {@link setFromMat4}, * and apply it to a {@link Vec3} with {@link transformVector}. {@link getX}, {@link getY} and * {@link getZ} read the columns, which for a rotation matrix are its axes. * * Methods modify the matrix they are called on and return it for chaining. Use {@link clone} for an * independent copy and {@link copy} to overwrite. {@link IDENTITY} and {@link ZERO} are frozen * shared instances. * * @example * // Take the rotation and scale of an entity's world transform and apply it to a direction * const rotationScale = new Mat3().setFromMat4(entity.getWorldTransform()); * const worldDirection = rotationScale.transformVector(localDirection); * @category Math */ declare class Mat3 { /** * A constant matrix set to the identity. * * @type {Mat3} * @readonly */ static readonly IDENTITY: Mat3; /** * A constant matrix with all elements set to 0. * * @type {Mat3} * @readonly */ static readonly ZERO: Mat3; /** * Matrix elements in the form of a flat array. * * @type {Float32Array} */ data: Float32Array; /** * Creates a duplicate of the specified matrix. * * @returns {this} A duplicate matrix. * @example * const src = new Mat3().setFromQuat(new Quat(0, 0, 0.383, 0.924)); * const dst = src.clone(); * console.log("The two matrices are " + (src.equals(dst) ? "equal" : "different")); */ clone(): this; /** * Copies the contents of a source 3x3 matrix to a destination 3x3 matrix. * * @param {Mat3} rhs - A 3x3 matrix to be copied. * @returns {Mat3} Self for chaining. * @example * const src = new Mat3().setFromQuat(new Quat(0, 0, 0.383, 0.924)); * const dst = new Mat3(); * dst.copy(src); * console.log("The two matrices are " + (src.equals(dst) ? "equal" : "different")); */ copy(rhs: Mat3): Mat3; /** * Copies the contents of a source array[9] to a destination 3x3 matrix. * * @param {number[]} src - An array[9] to be copied. * @returns {Mat3} Self for chaining. * @example * const dst = new Mat3(); * dst.set([0, 1, 2, 3, 4, 5, 6, 7, 8]); */ set(src: number[]): Mat3; /** * Extracts the x-axis from the specified matrix. * * @param {Vec3} [x] - The vector to receive the x axis of the matrix. * @returns {Vec3} The x-axis of the specified matrix. * @example * const m = new Mat3(); * const xAxis = m.getX(); // Vec3(1, 0, 0) for identity matrix */ getX(x?: Vec3): Vec3; /** * Extracts the y-axis from the specified matrix. * * @param {Vec3} [y] - The vector to receive the y axis of the matrix. * @returns {Vec3} The y-axis of the specified matrix. * @example * const m = new Mat3(); * const yAxis = m.getY(); // Vec3(0, 1, 0) for identity matrix */ getY(y?: Vec3): Vec3; /** * Extracts the z-axis from the specified matrix. * * @param {Vec3} [z] - The vector to receive the z axis of the matrix. * @returns {Vec3} The z-axis of the specified matrix. * @example * const m = new Mat3(); * const zAxis = m.getZ(); // Vec3(0, 0, 1) for identity matrix */ getZ(z?: Vec3): Vec3; /** * Reports whether two matrices are equal. * * @param {Mat3} rhs - The other matrix. * @returns {boolean} True if the matrices are equal and false otherwise. * @example * const a = new Mat3().setFromQuat(new Quat(0, 0, 0.383, 0.924)); * const b = new Mat3(); * console.log("The two matrices are " + (a.equals(b) ? "equal" : "different")); */ equals(rhs: Mat3): boolean; /** * Reports whether the specified matrix is the identity matrix. * * @returns {boolean} True if the matrix is identity and false otherwise. * @example * const m = new Mat3(); * console.log("The matrix is " + (m.isIdentity() ? "identity" : "not identity")); */ isIdentity(): boolean; /** * Sets the matrix to the identity matrix. * * @returns {Mat3} Self for chaining. * @example * m.setIdentity(); * console.log("The matrix is " + (m.isIdentity() ? "identity" : "not identity")); */ setIdentity(): Mat3; /** * Converts the matrix to string form. * * @returns {string} The matrix in string form. * @example * const m = new Mat3(); * // Outputs [1, 0, 0, 0, 1, 0, 0, 0, 1] * console.log(m.toString()); */ toString(): string; /** * Generates the transpose of the specified 3x3 matrix. * * @param {Mat3} [src] - The matrix to transpose. If not set, the matrix is transposed in-place. * @returns {Mat3} Self for chaining. * @example * const m = new Mat3(); * * // Transpose in place * m.transpose(); */ transpose(src?: Mat3): Mat3; /** * Converts the specified 4x4 matrix to a Mat3. * * @param {Mat4} m - The 4x4 matrix to convert. * @returns {Mat3} Self for chaining. * @example * const m4 = new Mat4(); * const m3 = new Mat3().setFromMat4(m4); */ setFromMat4(m: Mat4): Mat3; /** * Sets this matrix to the given quaternion rotation. * * @param {Quat} r - A quaternion rotation. * @returns {Mat3} Self for chaining. * @example * const r = new Quat(1, 2, 3, 4).normalize(); * * const m = new Mat3(); * m.setFromQuat(r); */ setFromQuat(r: Quat): Mat3; /** * Set the matrix to the inverse of the specified 4x4 matrix. * * @param {Mat4} src - The 4x4 matrix to invert. * @returns {Mat3} Self for chaining. * * @ignore */ invertMat4(src: Mat4): Mat3; /** * Transforms a 3-dimensional vector by a 3x3 matrix. * * @param {Vec3} vec - The 3-dimensional vector to be transformed. * @param {Vec3} [res] - An optional 3-dimensional vector to receive the result of the * transformation. * @returns {Vec3} The input vector v transformed by the current instance. * @example * const m = new Mat3(); * const v = new Vec3(1, 2, 3); * const result = m.transformVector(v); */ transformVector(vec: Vec3, res?: Vec3): Vec3; } /** * Callback used by {@link GraphNode#find} and {@link GraphNode#findOne} to search through a graph * node and all of its descendants. */ type FindNodeCallback = (node: GraphNode) => boolean; /** * Callback used by {@link GraphNode#forEach} to iterate through a graph node and all of its * descendants. */ type ForEachNodeCallback = (node: GraphNode) => void; /** * @callback FindNodeCallback * Callback used by {@link GraphNode#find} and {@link GraphNode#findOne} to search through a graph * node and all of its descendants. * @param {GraphNode} node - The current graph node. * @returns {boolean} Returning `true` will result in that node being returned from * {@link GraphNode#find} or {@link GraphNode#findOne}. */ /** * @callback ForEachNodeCallback * Callback used by {@link GraphNode#forEach} to iterate through a graph node and all of its * descendants. * @param {GraphNode} node - The current graph node. * @returns {void} */ /** * A GraphNode is a node in the scene graph: a named object with a position, rotation and scale, * and a list of {@link children} whose transforms are expressed relative to it. Nodes form a tree, * and the world transform of any node is its local transform combined with the world transform of * its {@link parent}; the {@link root} has no parent, so its world transform is its local one. The * engine brings every world transform up to date each frame before rendering, so a change to a * parent reaches all of its descendants. * * GraphNode is the base class of {@link Entity}, which adds components, so in practice these * methods are called on entities. The conventions are the same on both: * * - Local methods such as {@link setLocalPosition} and {@link getLocalRotation} work relative to * the parent. Their world counterparts, {@link setPosition}, {@link getRotation} and the rest, * account for the whole chain of ancestors. * - Setters accept separate components or a vector or quaternion, and copy the value. * - Getters return the node's internal storage as read-only; clone the result if you need to * keep or modify it. * - Euler angles are in degrees, and {@link forward} is the node's negative Z axis. * * Build the hierarchy with {@link addChild}, {@link insertChild}, {@link removeChild} and * {@link reparent}, and search it with {@link findByName}, {@link findByPath}, {@link findByTag} * and {@link find}. Setting {@link enabled} to false disables the node and its whole subtree. * * @example * // Move a node one unit in its own facing direction, then turn it to face a target * node.translateLocal(0, 0, -1); * node.lookAt(target.getPosition()); * @example * // Getters return read-only internal storage: clone before modifying * const start = node.getPosition().clone(); * start.y += 1; * node.setPosition(start); * @category Framework */ declare class GraphNode extends EventHandler { /** * Create a new GraphNode instance. * * @param {string} [name] - The non-unique name of a graph node. Defaults to 'Untitled'. */ constructor(name?: string); /** * The non-unique name of a graph node. Defaults to 'Untitled'. * * @type {string} */ name: string; /** * Interface for tagging graph nodes. Tag based searches can be performed using the * {@link findByTag} function. * * @type {Tags} */ tags: Tags; /** @private */ private localPosition; /** @private */ private localRotation; /** @private */ private localScale; /** * @type {Vec3} * @private */ private localEulerAngles; /** @private */ private position; /** @private */ private rotation; /** @private */ private eulerAngles; /** * @type {Vec3|null} * @private */ private _scale; /** @private */ private localTransform; /** @private */ private _dirtyLocal; /** @private */ private _aabbVer; /** * Marks the node to ignore hierarchy sync entirely (including children nodes). The engine code * automatically freezes and unfreezes objects whenever required. Segregating dynamic and * stationary nodes into subhierarchies allows to reduce sync time significantly. * * @private */ private _frozen; /** @private */ private worldTransform; /** @private */ private _dirtyWorld; /** * Cached value representing the negatively scaled world transform. If the value is 0, this * marks this value as dirty and it needs to be recalculated. If the value is 1, the world * transform is not negatively scaled. If the value is -1, the world transform is negatively * scaled. * * @private */ private _worldScaleSign; /** @private */ private _normalMatrix; /** @private */ private _dirtyNormal; /** * @type {Vec3|null} * @private */ private _right; /** * @type {Vec3|null} * @private */ private _up; /** * @type {Vec3|null} * @private */ private _forward; /** * @type {GraphNode|null} * @private */ private _parent; /** * @type {GraphNode[]} * @protected */ protected _children: GraphNode[]; /** @private */ private _graphDepth; /** * Represents enabled state of the entity. If the entity is disabled, the entity including all * children are excluded from updates. * * @private */ private _enabled; /** * Represents enabled state of the entity in the hierarchy. It's true only if this entity and * all parent entities all the way to the scene's root are enabled. * * @private */ private _enabledInHierarchy; /** @ignore */ scaleCompensation: boolean; /** * Gets the normalized local space X-axis vector of the graph node in world space. * * @type {Readonly} */ get right(): Readonly; /** * Gets the normalized local space Y-axis vector of the graph node in world space. * * @type {Readonly} */ get up(): Readonly; /** * Gets the normalized local space negative Z-axis vector of the graph node in world space. * * @type {Readonly} */ get forward(): Readonly; /** * Gets the 3x3 transformation matrix used to transform normals. * * @type {Mat3} * @ignore */ get normalMatrix(): Mat3; /** * Sets the enabled state of the GraphNode. If one of the GraphNode's parents is disabled there * will be no other side effects. If all the parents are enabled then the new value will * activate or deactivate all the enabled children of the GraphNode. * * @type {boolean} */ set enabled(enabled: boolean); /** * Gets the enabled state of the GraphNode. * * @type {boolean} */ get enabled(): boolean; /** * Gets the parent of this graph node. * * @type {GraphNode|null} */ get parent(): GraphNode | null; /** * Gets the path of this graph node relative to the root of the hierarchy. * * @type {string} */ get path(): string; /** * Gets the oldest ancestor graph node from this graph node. * * @type {GraphNode} */ get root(): GraphNode; /** * Gets the children of this graph node. Use addChild, insertChild, removeChild or reparent to * change the hierarchy. * * @type {ReadonlyArray} */ get children(): ReadonlyArray; /** * @deprecated Use GraphNode#children instead. * @ignore */ getChildren(): readonly GraphNode[]; /** * @deprecated Use GraphNode#name instead. * @ignore */ getName(): string; /** * @deprecated Use GraphNode#path instead. * @ignore */ getPath(): string; /** * @deprecated Use GraphNode#root instead. * @ignore */ getRoot(): GraphNode; /** * @deprecated Use GraphNode#parent instead. * @returns {GraphNode|null} The parent node, or null if this node has no parent. * @ignore */ getParent(): GraphNode | null; /** * @deprecated Use GraphNode#name instead. * @param {string} name - The name to set. * @ignore */ setName(name: string): void; /** * Gets the depth of this child within the graph. Note that for performance reasons this is * only recalculated when a node is added to a new parent. In other words, it is not * recalculated when a node is simply removed from the graph. * * @type {number} */ get graphDepth(): number; /** * @param {GraphNode} node - Graph node to update. * @param {boolean} enabled - True if enabled in the hierarchy, false if disabled. * @protected */ protected _notifyHierarchyStateChanged(node: GraphNode, enabled: boolean): void; /** * Called when the enabled flag of the entity or one of its parents changes. * * @param {boolean} enabled - True if enabled in the hierarchy, false if disabled. * @protected */ protected _onHierarchyStateChanged(enabled: boolean): void; /** * @param {this} clone - The cloned graph node to copy into. * @private */ private _cloneInternal; /** * Clone a graph node. * * @returns {this} A clone of the specified graph node. */ clone(): this; /** * Copy a graph node. * * @param {GraphNode} source - The graph node to copy. * @returns {GraphNode} The destination graph node. * @ignore */ copy(source: GraphNode): GraphNode; /** * Destroy the graph node and all of its descendants. First, the graph node is removed from the * hierarchy. This is then repeated recursively for all descendants of the graph node. * * The last thing the graph node does is fire the `destroy` event. * * @example * const firstChild = graphNode.children[0]; * firstChild.destroy(); // destroy child and all of its descendants */ destroy(): void; /** * Search the graph node and all of its descendants for the nodes that satisfy some search * criteria. * * @param {FindNodeCallback|string} attr - This can either be a function or a string. If it's a * function, it is executed for each descendant node to test if node satisfies the search * logic. Returning true from the function will include the node into the results. If it's a * string then it represents the name of a field or a method of the node. If this is the name * of a field then the value passed as the second argument will be checked for equality. If * this is the name of a function then the return value of the function will be checked for * equality against the value passed as the second argument to this function. * @param {*} [value] - If the first argument (attr) is a property name then this value * will be checked against the value of the property. * @returns {GraphNode[]} The array of graph nodes that match the search criteria. * @example * // Finds all nodes that have a model component and have 'door' in their lower-cased name * const doors = house.find((node) => { * return node.model && node.name.toLowerCase().indexOf('door') !== -1; * }); * @example * // Finds all nodes that have the name property set to 'Test' * const entities = parent.find('name', 'Test'); */ find(attr: FindNodeCallback | string, value?: any): GraphNode[]; /** * Search the graph node and all of its descendants for the first node that satisfies some * search criteria. * * @param {FindNodeCallback|string} attr - This can either be a function or a string. If it's a * function, it is executed for each descendant node to test if node satisfies the search * logic. Returning true from the function will result in that node being returned from * findOne. If it's a string then it represents the name of a field or a method of the node. If * this is the name of a field then the value passed as the second argument will be checked for * equality. If this is the name of a function then the return value of the function will be * checked for equality against the value passed as the second argument to this function. * @param {*} [value] - If the first argument (attr) is a property name then this value * will be checked against the value of the property. * @returns {GraphNode|null} A graph node that matches the search criteria. Returns null if no * node is found. * @example * // Find the first node that is called 'head' and has a model component * const head = player.findOne((node) => { * return node.model && node.name === 'head'; * }); * @example * // Finds the first node that has the name property set to 'Test' * const node = parent.findOne('name', 'Test'); */ findOne(attr: FindNodeCallback | string, value?: any): GraphNode | null; /** * Return all graph nodes that satisfy the search query. Query can be simply a string, or comma * separated strings, to have inclusive results of graph nodes that match at least one query. A * query that consists of an array of tags can be used to match graph nodes that have each tag * of the array. * * @param {...*} query - Name of a tag or array of tags. * @returns {GraphNode[]} A list of all graph nodes that match the query. * @example * // Return all graph nodes tagged with `animal` * const animals = node.findByTag("animal"); * @example * // Return all graph nodes tagged with `bird` OR `mammal` * const birdsAndMammals = node.findByTag("bird", "mammal"); * @example * // Return all graph nodes tagged with `carnivore` AND `mammal` * const meatEatingMammals = node.findByTag(["carnivore", "mammal"]); * @example * // Return all graph nodes tagged with (`carnivore` AND `mammal`) OR (`carnivore` AND `reptile`) * const meatEatingMammalsAndReptiles = node.findByTag(["carnivore", "mammal"], ["carnivore", "reptile"]); */ findByTag(...query: any[]): GraphNode[]; /** * Get the first node found in the graph with the name. The search is depth first. * * @param {string} name - The name of the node. * @returns {GraphNode|null} The first node to be found matching the supplied name. Returns * null if no node is found. */ findByName(name: string): GraphNode | null; /** * Get the first node found in the graph by its full path in the graph. The full path has this * form 'parent/child/sub-child'. The search is depth first. * * @param {string|string[]} path - The full path of the GraphNode as either a string or array * of GraphNode names. * @returns {GraphNode|null} The first node to be found matching the supplied path. Returns * null if no node is found. * @example * // String form * const grandchild = this.entity.findByPath('child/grandchild'); * @example * // Array form * const grandchild = this.entity.findByPath(['child', 'grandchild']); */ findByPath(path: string | string[]): GraphNode | null; /** * Executes a provided function once on this graph node and all of its descendants. * * @param {ForEachNodeCallback} callback - The function to execute on the graph node and each * descendant. * @param {object} [thisArg] - Optional value to use as this when executing callback function. * @example * // Log the path and name of each node in descendant tree starting with "parent" * parent.forEach((node) => { * console.log(node.path + "/" + node.name); * }); */ forEach(callback: ForEachNodeCallback, thisArg?: object): void; /** * Check if node is descendant of another node. * * @param {GraphNode} node - Potential ancestor of node. * @returns {boolean} If node is descendant of another node. * @example * if (roof.isDescendantOf(house)) { * // roof is descendant of house entity * } */ isDescendantOf(node: GraphNode): boolean; /** * Check if node is ancestor for another node. * * @param {GraphNode} node - Potential descendant of node. * @returns {boolean} If node is ancestor for another node. * @example * if (body.isAncestorOf(foot)) { * // foot is within body's hierarchy * } */ isAncestorOf(node: GraphNode): boolean; /** * Get the world space rotation for the specified GraphNode in Euler angles. The angles are in * degrees and in XYZ order. * * Important: The value returned by this function should be considered read-only. In order to * set the world space rotation of the graph node, use {@link setEulerAngles}. * * @returns {Readonly} The world space rotation of the graph node in Euler angle form. * @example * const angles = this.entity.getEulerAngles(); * angles.y = 180; // rotate the entity around Y by 180 degrees * this.entity.setEulerAngles(angles); */ getEulerAngles(): Readonly; /** * Get the local space rotation for the specified GraphNode in Euler angles. The angles are in * degrees and in XYZ order. * * Important: The value returned by this function should be considered read-only. In order to * set the local space rotation of the graph node, use {@link setLocalEulerAngles}. * * @returns {Readonly} The local space rotation of the graph node as Euler angles in XYZ order. * @example * const angles = this.entity.getLocalEulerAngles(); * angles.y = 180; * this.entity.setLocalEulerAngles(angles); */ getLocalEulerAngles(): Readonly; /** * Get the position in local space for the specified GraphNode. The position is returned as a * {@link Vec3}. The returned vector should be considered read-only. To update the local * position, use {@link setLocalPosition}. * * @returns {Readonly} The local space position of the graph node. * @example * const position = this.entity.getLocalPosition().clone(); * position.x += 1; // move the entity 1 unit along x. * this.entity.setLocalPosition(position); */ getLocalPosition(): Readonly; /** * Get the rotation in local space for the specified GraphNode. The rotation is returned as a * {@link Quat}. The returned quaternion should be considered read-only. To update the local * rotation, use {@link setLocalRotation}. * * @returns {Readonly} The local space rotation of the graph node as a quaternion. * @example * const rotation = this.entity.getLocalRotation(); */ getLocalRotation(): Readonly; /** * Get the scale in local space for the specified GraphNode. The scale is returned as a * {@link Vec3}. The returned vector should be considered read-only. To update the local scale, * use {@link setLocalScale}. * * @returns {Readonly} The local space scale of the graph node. * @example * const scale = this.entity.getLocalScale().clone(); * scale.x = 100; * this.entity.setLocalScale(scale); */ getLocalScale(): Readonly; /** * Get the local transform matrix for this graph node. This matrix is the transform relative to * the node's parent's world transformation matrix. * * @returns {Readonly} The node's local transformation matrix. * @example * const transform = this.entity.getLocalTransform(); */ getLocalTransform(): Readonly; /** * Get the world space position for the specified GraphNode. The position is returned as a * {@link Vec3}. The value returned by this function should be considered read-only. In order * to set the world space position of the graph node, use {@link setPosition}. * * @returns {Readonly} The world space position of the graph node. * @example * const position = this.entity.getPosition().clone(); * position.x = 10; * this.entity.setPosition(position); */ getPosition(): Readonly; /** * Get the world space rotation for the specified GraphNode. The rotation is returned as a * {@link Quat}. The value returned by this function should be considered read-only. In order * to set the world space rotation of the graph node, use {@link setRotation}. * * @returns {Readonly} The world space rotation of the graph node as a quaternion. * @example * const rotation = this.entity.getRotation(); */ getRotation(): Readonly; /** * Get the world space scale for the specified GraphNode. The returned value will only be * correct for graph nodes that have a non-skewed world transform (a skew can be introduced by * the compounding of rotations and scales higher in the graph node hierarchy). The scale is * returned as a {@link Vec3}. The value returned by this function should be considered * read-only. Note that it is not possible to set the world space scale of a graph node * directly. * * @returns {Readonly} The world space scale of the graph node. * @example * const scale = this.entity.getScale(); * @ignore */ getScale(): Readonly; /** * Get the world transformation matrix for this graph node. * * @returns {Readonly} The node's world transformation matrix. * @example * const transform = this.entity.getWorldTransform(); */ getWorldTransform(): Readonly; /** * Gets the cached value of negative scale sign of the world transform. * * @returns {number} -1 if world transform has negative scale, 1 otherwise. * @ignore */ get worldScaleSign(): number; /** * Remove graph node from current parent. */ remove(): void; /** * Remove graph node from current parent and add as child to new parent. * * @param {GraphNode} parent - New parent to attach graph node to. * @param {number} [index] - The child index where the child node should be placed. */ reparent(parent: GraphNode, index?: number): void; /** * Sets the local space rotation of the specified graph node using Euler angles. Eulers are * interpreted in XYZ order. * * @overload * @param {number} x - Rotation around local space x-axis in degrees. * @param {number} y - Rotation around local space y-axis in degrees. * @param {number} z - Rotation around local space z-axis in degrees. * @returns {void} * @example * // Set rotation of 90 degrees around y-axis via 3 numbers * this.entity.setLocalEulerAngles(0, 90, 0); */ setLocalEulerAngles(x: number, y: number, z: number): void; /** * Sets the local space rotation of the specified graph node using Euler angles. Eulers are * interpreted in XYZ order. * * @overload * @param {Vec3} angles - Vector holding rotations around local space axes in degrees. * @returns {void} * @example * // Set rotation of 90 degrees around y-axis via a vector * const angles = new Vec3(0, 90, 0); * this.entity.setLocalEulerAngles(angles); */ setLocalEulerAngles(angles: Vec3): void; /** * Sets the local space position of the specified graph node. * * @overload * @param {number} x - X-coordinate of local space position. * @param {number} y - Y-coordinate of local space position. * @param {number} z - Z-coordinate of local space position. * @returns {void} * @example * this.entity.setLocalPosition(0, 10, 0); */ setLocalPosition(x: number, y: number, z: number): void; /** * Sets the local space position of the specified graph node. * * @overload * @param {Vec3} position - Vector holding local space position. * @returns {void} * @example * const pos = new Vec3(0, 10, 0); * this.entity.setLocalPosition(pos); */ setLocalPosition(position: Vec3): void; /** * Sets the local space rotation of the specified graph node. * * @overload * @param {number} x - X-component of local space quaternion rotation. * @param {number} y - Y-component of local space quaternion rotation. * @param {number} z - Z-component of local space quaternion rotation. * @param {number} w - W-component of local space quaternion rotation. * @returns {void} * @example * this.entity.setLocalRotation(0, 0, 0, 1); */ setLocalRotation(x: number, y: number, z: number, w: number): void; /** * Sets the local space rotation of the specified graph node. * * @overload * @param {Quat} rotation - Quaternion holding local space rotation. * @returns {void} * @example * const q = new Quat(); * this.entity.setLocalRotation(q); */ setLocalRotation(rotation: Quat): void; /** * Sets the local space scale factor of the specified graph node. * * @overload * @param {number} x - X-coordinate of local space scale. * @param {number} y - Y-coordinate of local space scale. * @param {number} z - Z-coordinate of local space scale. * @returns {void} * @example * this.entity.setLocalScale(10, 10, 10); */ setLocalScale(x: number, y: number, z: number): void; /** * Sets the local space scale factor of the specified graph node. * * @overload * @param {Vec3} scale - Vector holding local space scale. * @returns {void} * @example * const scale = new Vec3(10, 10, 10); * this.entity.setLocalScale(scale); */ setLocalScale(scale: Vec3): void; /** @private */ private _dirtifyLocal; /** @private */ private _unfreezeParentToRoot; /** @private */ private _dirtifyWorld; /** @private */ private _dirtifyWorldInternal; /** * Sets the world space position of the specified graph node. * * @overload * @param {number} x - X-coordinate of world space position. * @param {number} y - Y-coordinate of world space position. * @param {number} z - Z-coordinate of world space position. * @returns {void} * @example * this.entity.setPosition(0, 10, 0); */ setPosition(x: number, y: number, z: number): void; /** * Sets the world space position of the specified graph node. * * @overload * @param {Vec3} position - Vector holding world space position. * @returns {void} * @example * const position = new Vec3(0, 10, 0); * this.entity.setPosition(position); */ setPosition(position: Vec3): void; /** * Sets the world space rotation of the specified graph node. * * @overload * @param {number} x - X-component of world space quaternion rotation. * @param {number} y - Y-component of world space quaternion rotation. * @param {number} z - Z-component of world space quaternion rotation. * @param {number} w - W-component of world space quaternion rotation. * @returns {void} * @example * this.entity.setRotation(0, 0, 0, 1); */ setRotation(x: number, y: number, z: number, w: number): void; /** * Sets the world space rotation of the specified graph node. * * @overload * @param {Quat} rotation - Quaternion holding world space rotation. * @returns {void} * @example * const rotation = new Quat(); * this.entity.setRotation(rotation); */ setRotation(rotation: Quat): void; /** * Sets the world space position and rotation of the specified graph node. This is faster than * setting the position and rotation independently. * * @param {Vec3} position - The world space position to set. * @param {Quat} rotation - The world space rotation to set. * @example * const position = new Vec3(0, 10, 0); * const rotation = new Quat().setFromEulerAngles(0, 90, 0); * this.entity.setPositionAndRotation(position, rotation); */ setPositionAndRotation(position: Vec3, rotation: Quat): void; /** * Sets the world space rotation of the specified graph node using Euler angles. Eulers are * interpreted in XYZ order. * * @overload * @param {number} x - Rotation around world space x-axis in degrees. * @param {number} y - Rotation around world space y-axis in degrees. * @param {number} z - Rotation around world space z-axis in degrees. * @returns {void} * @example * this.entity.setEulerAngles(0, 90, 0); */ setEulerAngles(x: number, y: number, z: number): void; /** * Sets the world space rotation of the specified graph node using Euler angles. Eulers are * interpreted in XYZ order. * * @overload * @param {Vec3} angles - Vector holding rotations around world space axes in degrees. * @returns {void} * @example * const angles = new Vec3(0, 90, 0); * this.entity.setEulerAngles(angles); */ setEulerAngles(angles: Vec3): void; /** * Add a new child to the child list and update the parent value of the child node. * If the node already had a parent, it is removed from its child list. * * The child keeps its existing local transform, which is now interpreted relative to the new * parent, so a node placed in world space before being added will appear to move. Set the * transform after adding, or re-apply the world placement with {@link GraphNode#setPosition}. * * @param {GraphNode} node - The new child to add. * @example * const e = new Entity(app); * this.entity.addChild(e); */ addChild(node: GraphNode): void; /** * Add a child to this node, maintaining the child's transform in world space. * If the node already had a parent, it is removed from its child list. * * @param {GraphNode} node - The child to add. * @example * const e = new Entity(app); * this.entity.addChildAndSaveTransform(e); * @ignore */ addChildAndSaveTransform(node: GraphNode): void; /** * Insert a new child to the child list at the specified index and update the parent value of * the child node. If the node already had a parent, it is removed from its child list. * * @param {GraphNode} node - The new child to insert. * @param {number} index - The index in the child list of the parent where the new node will be * inserted. * @example * const e = new Entity(app); * this.entity.insertChild(e, 1); */ insertChild(node: GraphNode, index: number): void; /** * Prepares node for being inserted to a parent node, and removes it from the previous parent. * * @param {GraphNode} node - The node being inserted. * @private */ private _prepareInsertChild; /** * Fires an event on all children of the node. The event `name` is fired on the first (root) * node only. The event `nameHierarchy` is fired for all children. * * @param {string} name - The name of the event to fire on the root. * @param {string} nameHierarchy - The name of the event to fire for all descendants. * @param {GraphNode} parent - The parent of the node being added/removed from the hierarchy. * @private */ private _fireOnHierarchy; /** * Called when a node is inserted into a node's child list. * * @param {GraphNode} node - The node that was inserted. * @private */ private _onInsertChild; /** * Recurse the hierarchy and update the graph depth at each node. * * @private */ private _updateGraphDepth; /** * Remove the node from the child list and update the parent value of the child. * * This detaches the node without disabling it: the removed subtree still reports * `enabled === true`, and its lights, cameras, scripts and sounds keep running. Set * `enabled = false` to deactivate a node, or destroy the entity to remove it outright. * * @param {GraphNode} child - The node to remove. * @example * const child = this.entity.children[0]; * this.entity.removeChild(child); */ removeChild(child: GraphNode): void; _sync(): void; /** * Updates the world transformation matrices at this node and all of its descendants. * * @ignore */ syncHierarchy(): void; /** * Reorients the graph node so that the negative z-axis points towards the target. * * The up vector must not be parallel to the direction from the node to the target. When it is — * looking straight up or down with the default up vector, or at the node's own position — the * basis is degenerate and the node's rotation is reset to identity, discarding whatever * rotation it already had, with nothing reported. Pass a different up vector in those cases. * * @overload * @param {number} x - X-component of the world space coordinate to look at. * @param {number} y - Y-component of the world space coordinate to look at. * @param {number} z - Z-component of the world space coordinate to look at. * @param {number} [ux] - X-component of the up vector for the look at transform. Defaults to 0. * @param {number} [uy] - Y-component of the up vector for the look at transform. Defaults to 1. * @param {number} [uz] - Z-component of the up vector for the look at transform. Defaults to 0. * @returns {void} * @example * // Look at the world space origin, using the (default) positive y-axis for up * this.entity.lookAt(0, 0, 0); * @example * // Look at world space coordinate [10, 10, 10], using the negative world y-axis for up * this.entity.lookAt(10, 10, 10, 0, -1, 0); */ lookAt(x: number, y: number, z: number, ux?: number, uy?: number, uz?: number): void; /** * Reorients the graph node so that the negative z-axis points towards the target. * * @overload * @param {Vec3} target - The world space coordinate to look at. * @param {Vec3} [up] - The world space up vector for look at transform. Defaults to {@link Vec3.UP}. * @returns {void} * @example * // Look at another entity, using the (default) positive y-axis for up * const target = otherEntity.getPosition(); * this.entity.lookAt(target); * @example * // Look at another entity, using the negative world y-axis for up * const target = otherEntity.getPosition(); * this.entity.lookAt(target, Vec3.DOWN); */ lookAt(target: Vec3, up?: Vec3): void; /** * Translates the graph node in world space by the specified translation vector. * * @overload * @param {number} x - X-coordinate of world space translation. * @param {number} y - Y-coordinate of world space translation. * @param {number} z - Z-coordinate of world space translation. * @returns {void} * @example * this.entity.translate(10, 0, 0); */ translate(x: number, y: number, z: number): void; /** * Translates the graph node in world space by the specified translation vector. * * @overload * @param {Vec3} translation - Vector holding world space translation. * @returns {void} * @example * const translation = new Vec3(10, 0, 0); * this.entity.translate(translation); */ translate(translation: Vec3): void; /** * Translates the graph node in local space by the specified translation vector. * * @overload * @param {number} x - X-coordinate of local space translation. * @param {number} y - Y-coordinate of local space translation. * @param {number} z - Z-coordinate of local space translation. * @returns {void} * @example * this.entity.translateLocal(10, 0, 0); */ translateLocal(x: number, y: number, z: number): void; /** * Translates the graph node in local space by the specified translation vector. * * @overload * @param {Vec3} translation - Vector holding local space translation. * @returns {void} * @example * const t = new Vec3(10, 0, 0); * this.entity.translateLocal(t); */ translateLocal(translation: Vec3): void; /** * Rotates the graph node in world space by the specified Euler angles. Eulers are specified in * degrees in XYZ order. * * @overload * @param {number} x - Rotation around world space x-axis in degrees. * @param {number} y - Rotation around world space y-axis in degrees. * @param {number} z - Rotation around world space z-axis in degrees. * @returns {void} * @example * this.entity.rotate(0, 90, 0); */ rotate(x: number, y: number, z: number): void; /** * Rotates the graph node in world space by the specified Euler angles. Eulers are specified in * degrees in XYZ order. * * @overload * @param {Vec3} rotation - Vector holding world space rotation. * @returns {void} * @example * const rotation = new Vec3(0, 90, 0); * this.entity.rotate(rotation); */ rotate(rotation: Vec3): void; /** * Rotates the graph node in local space by the specified Euler angles. Eulers are specified in * degrees in XYZ order. * * @overload * @param {number} x - Rotation around local space x-axis in degrees. * @param {number} y - Rotation around local space y-axis in degrees. * @param {number} z - Rotation around local space z-axis in degrees. * @returns {void} * @example * this.entity.rotateLocal(0, 90, 0); */ rotateLocal(x: number, y: number, z: number): void; /** * Rotates the graph node in local space by the specified Euler angles. Eulers are specified in * degrees in XYZ order. * * @overload * @param {Vec3} rotation - Vector holding local space rotation. * @returns {void} * @example * const rotation = new Vec3(0, 90, 0); * this.entity.rotateLocal(rotation); */ rotateLocal(rotation: Vec3): void; } /** * @import { GraphicsDevice } from '../platform/graphics/graphics-device.js' * @import { Mat4 } from '../core/math/mat4.js' */ /** * A skin contains data about the bones in a hierarchy that drive a skinned mesh animation. * Specifically, the skin stores the bone name and inverse bind matrix and for each bone. Inverse * bind matrices are instrumental in the mathematics of vertex skinning. * * @category Graphics */ declare class Skin { /** * Create a new Skin instance. * * @param {GraphicsDevice} graphicsDevice - The graphics device used to manage this skin. * @param {Mat4[]} ibp - The array of inverse bind matrices. * @param {string[]} boneNames - The array of bone names for the bones referenced by this skin. */ constructor(graphicsDevice: GraphicsDevice, ibp: Mat4[], boneNames: string[]); device: GraphicsDevice; inverseBindPose: Mat4[]; boneNames: string[]; } /** * A skin instance is responsible for generating the matrix palette that is used to skin vertices * from object space to world space. * * @category Graphics */ declare class SkinInstance { /** * Create a new SkinInstance instance. * * @param {Skin} skin - The skin that will provide the inverse bind pose * matrices to generate the final matrix palette. */ constructor(skin: Skin); /** * An array of nodes representing each bone in this skin instance. * * @type {GraphNode[]} */ bones: GraphNode[]; _dirty: boolean; _rootBone: any; _skinUpdateIndex: number; _updateBeforeCull: boolean; set rootBone(rootBone: any); get rootBone(): any; init(device: any, numBones: any): void; boneTexture: Texture; matrixPalette: Float32Array | Uint8Array | Uint16Array | Uint32Array; destroy(): void; /** * Resolves skin bones to a hierarchy with the rootBone at its root. * * @param {Entity} rootBone - A reference to the entity to be used as the root bone. * @param {Entity} entity - Specifies the entity used if the bone match is not found in the * hierarchy - usually the entity the render component is attached to. * @ignore */ resolve(rootBone: Entity, entity: Entity): void; /** * @param {Skin} skin - The skin. */ initSkin(skin: Skin): void; skin: Skin; matrices: any[]; uploadBones(device: any): void; _updateMatrices(rootNode: any, skinUpdateIndex: any): void; updateMatrices(rootNode: any, skinUpdateIndex: any): void; updateMatrixPalette(rootNode: any, skinUpdateIndex: any): void; } /** * Base class that implements reference counting for objects. * * @category Framework */ declare class RefCountedObject { /** @private */ private _refCount; /** * Increments the reference counter. */ incRefCount(): void; /** * Decrements the reference counter. */ decRefCount(): void; /** * Gets the current reference count. * * @type {number} */ get refCount(): number; } /** * A Morph Target (also known as Blend Shape) contains deformation data to apply to existing mesh. * Multiple morph targets can be blended together on a mesh. This is useful for effects that are * hard to achieve with conventional animation and skinning. * * @category Graphics */ declare class MorphTarget { /** * Create a new MorphTarget instance. * * @param {object} options - Object for passing optional arguments. * @param {ArrayLike} options.deltaPositions - An array of 3-dimensional vertex position * offsets. * @param {ArrayLike} [options.deltaNormals] - An array of 3-dimensional vertex normal * offsets. * @param {string} [options.name] - Name. * @param {BoundingBox} [options.aabb] - Bounding box. Will be automatically generated, if * undefined. * @param {number} [options.defaultWeight] - Default blend weight to use for this morph target. * @param {boolean} [options.preserveData] - When true, the morph target keeps its data passed using the options, * allowing the clone operation. */ constructor(options: { deltaPositions: ArrayLike; deltaNormals?: ArrayLike; name?: string; aabb?: BoundingBox; defaultWeight?: number; preserveData?: boolean; }, ...args: any[]); /** * A used flag. A morph target can be used / owned by the Morph class only one time. */ used: boolean; options: { deltaPositions: ArrayLike; deltaNormals?: ArrayLike; name?: string; aabb?: BoundingBox; defaultWeight?: number; preserveData?: boolean; }; _name: string; _defaultWeight: number; _aabb: BoundingBox; deltaPositions: ArrayLike; morphPositions: boolean; morphNormals: boolean; /** * Gets the name of the morph target. * * @type {string} */ get name(): string; /** * Gets the default weight of the morph target. * * @type {number} */ get defaultWeight(): number; get aabb(): BoundingBox; /** * Returns an identical copy of the specified morph target. This can only be used if the morph target * was created with options.preserveData set to true. * * @returns {MorphTarget} A morph target instance containing the result of the cloning. */ clone(): MorphTarget; _postInit(): void; } /** * @import { GraphicsDevice } from '../platform/graphics/graphics-device.js' * @import { MorphTarget } from './morph-target.js' */ /** * Contains a list of {@link MorphTarget}s, a combined delta AABB and some associated data. * * @category Graphics */ declare class Morph extends RefCountedObject { /** * Create a new Morph instance. * * @param {MorphTarget[]} targets - A list of morph targets. * @param {GraphicsDevice} graphicsDevice - The graphics device used to manage this morph target. * @param {object} [options] - Object for passing optional arguments. * @param {boolean} [options.preferHighPrecision] - True if high precision storage should be * preferred. This is faster to create and allows higher precision, but takes more memory and * might be slower to render. Defaults to false. */ constructor(targets: MorphTarget[], graphicsDevice: GraphicsDevice, { preferHighPrecision }?: { preferHighPrecision?: boolean; }); /** * @type {BoundingBox} * @private */ private _aabb; /** @type {boolean} */ preferHighPrecision: boolean; device: GraphicsDevice; _targets: MorphTarget[]; _renderTextureFormat: number; intRenderFormat: boolean; _textureFormat: number; /** * Frees video memory allocated by this object. */ destroy(): void; vertexBufferIds: VertexBuffer; targetsTexturePositions: Texture; targetsTextureNormals: Texture; get aabb(): BoundingBox; get morphPositions(): boolean; get morphNormals(): boolean; _init(): void; _findSparseSet(deltaArrays: any, ids: any, usedDataIndices: any): number; _initTextureBased(): boolean; morphTextureWidth: number; morphTextureHeight: number; /** * Gets the array of morph targets. * * @type {MorphTarget[]} */ get targets(): MorphTarget[]; /** * @deprecated Use Morph#targets instead. * @param {number} index - The index of the morph target. * @returns {MorphTarget} The morph target at the given index. * @ignore */ getTarget(index: number): MorphTarget; _updateMorphFlags(): void; _morphPositions: boolean; _morphNormals: boolean; /** * Creates a texture / texture array. Used to create both source morph target data, as well as * render target used to morph these into, positions and normals. * * @param {string} name - The name of the texture. * @param {number} format - The format of the texture. * @param {number} [arrayLength] - The length of the texture array. * @param {Array} [levels] - The levels of the texture. * @returns {Texture} The created texture. * @private */ private _createTexture; } /** * @import { Morph } from './morph.js' * @import { Shader } from '../platform/graphics/shader.js' */ /** * An instance of {@link Morph}. Contains weights to assign to every {@link MorphTarget}, manages * selection of active morph targets. * * @category Graphics */ declare class MorphInstance { /** * Create a new MorphInstance instance. * * @param {Morph} morph - The {@link Morph} to instance. */ constructor(morph: Morph); /** * The morph with its targets, which is being instanced. * * @type {Morph} */ morph: Morph; device: GraphicsDevice; shader: Shader; _weights: any[]; _weightMap: Map; _shaderMorphWeights: Float32Array; _shaderMorphIndex: Uint32Array; rtPositions: RenderTarget; rtNormals: RenderTarget; _textureParams: Float32Array; _aabbSize: Float32Array; _aabbMin: Float32Array; _aabbNrmSize: Float32Array; _aabbNrmMin: Float32Array; aabbSizeId: ScopeId; aabbMinId: ScopeId; morphTextureId: ScopeId; morphFactor: ScopeId; morphIndex: ScopeId; countId: ScopeId; zeroTextures: boolean; /** * Frees video memory allocated by this object. */ destroy(): void; texturePositions: any; textureNormals: any; /** * Clones a MorphInstance. The returned clone uses the same {@link Morph} and weights are set * to defaults. * * @returns {MorphInstance} A clone of the specified MorphInstance. */ clone(): MorphInstance; _getWeightIndex(key: any): any; /** * Gets current weight of the specified morph target. * * @param {string|number} key - An identifier for the morph target. Either the weight index or * the weight name. * @returns {number} Weight. */ getWeight(key: string | number): number; /** * Sets weight of the specified morph target. * * @param {string|number} key - An identifier for the morph target. Either the weight index or * the weight name. * @param {number} weight - Weight. */ setWeight(key: string | number, weight: number): void; _dirty: boolean; /** * Create the shader for texture based morphing. * * @param {number} maxCount - Maximum number of textures to blend. * @returns {Shader} Shader. * @private */ private _createShader; _updateTextureRenderTarget(renderTarget: any, activeCount: any, isPos: any): void; _updateTextureMorph(activeCount: any): void; setAabbUniforms(isPos?: boolean): void; prepareRendering(device: any): void; /** * Selects active morph targets and prepares morph for rendering. Called automatically by * renderer. */ update(): void; } /** * @import { GraphNode } from './graph-node.js' */ /** * A model is a graphical object that can be added to or removed from a scene. It contains a * hierarchy and any number of mesh instances. * * @category Graphics */ declare class Model { /** * The root node of the model's graph node hierarchy. * * @type {GraphNode|null} */ graph: GraphNode | null; /** * An array of MeshInstances contained in this model. * * @type {MeshInstance[]} */ meshInstances: MeshInstance[]; /** * An array of SkinInstances contained in this model. * * @type {SkinInstance[]} */ skinInstances: SkinInstance[]; /** * An array of MorphInstances contained in this model. * * @type {MorphInstance[]} */ morphInstances: MorphInstance[]; cameras: any[]; lights: any[]; _shadersVersion: number; _immutable: boolean; getGraph(): GraphNode; setGraph(graph: any): void; getCameras(): any[]; setCameras(cameras: any): void; getLights(): any[]; setLights(lights: any): void; getMaterials(): Material[]; /** * Clones a model. The returned model has a newly created hierarchy and mesh instances, but * meshes are shared between the clone and the specified model. * * @returns {Model} A clone of the specified model. * @example * const clonedModel = model.clone(); */ clone(): Model; /** * Destroys skinning texture and possibly deletes vertex/index buffers of a model. Mesh is * reference-counted, so buffers are only deleted if all models with referencing mesh instances * were deleted. That means all in-scene models + the "base" one (asset.resource) which is * created when the model is parsed. It is recommended to use asset.unload() instead, which * will also remove the model from the scene. */ destroy(): void; /** * Generates the necessary internal data for a model to be renderable as wireframe. Once this * function has been called, any mesh instance in the model can have its renderStyle property * set to {@link RENDERSTYLE_WIREFRAME}. * * @example * model.generateWireframe(); * for (let i = 0; i < model.meshInstances.length; i++) { * model.meshInstances[i].renderStyle = RENDERSTYLE_WIREFRAME; * } */ generateWireframe(): void; } /** * The Geometry class serves as a container for storing geometric information. It encapsulates data * such as positions, normals, colors, and indices. * * @category Graphics */ declare class Geometry { /** * Positions. * * @type {ArrayLike|undefined} */ positions: ArrayLike | undefined; /** * Normals. * * @type {ArrayLike|undefined} */ normals: ArrayLike | undefined; /** * Colors. * * @type {ArrayLike|undefined} */ colors: ArrayLike | undefined; /** * UVs. * * @type {ArrayLike|undefined} */ uvs: ArrayLike | undefined; /** * Additional Uvs. * * @type {ArrayLike|undefined} */ uvs1: ArrayLike | undefined; /** * Blend indices. * * @type {ArrayLike|undefined} */ blendIndices: ArrayLike | undefined; /** * Blend weights. * * @type {ArrayLike|undefined} */ blendWeights: ArrayLike | undefined; /** * Tangents. * * @type {ArrayLike|undefined} */ tangents: ArrayLike | undefined; /** * Indices. * * @type {number[]|Uint8Array|Uint16Array|Uint32Array|undefined} */ indices: number[] | Uint8Array | Uint16Array | Uint32Array | undefined; /** * Generates normal information from the positions and triangle indices. */ calculateNormals(): void; /** * Generates tangent information from the positions, normals, texture coordinates and triangle * indices. */ calculateTangents(): void; } /** * A writable array of numbers - either a JavaScript array or any numeric typed array. */ type NumericArray = number[] | Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array; /** * A graphical primitive. The mesh is defined by a {@link VertexBuffer} and an optional * {@link IndexBuffer}. It also contains a primitive definition which controls the type of the * primitive and the portion of the vertex or index buffer to use. * * A mesh holds geometry only. To draw it, pair it with a {@link Material} in a {@link MeshInstance} * and give that instance to a {@link RenderComponent} or a {@link Layer}; one mesh can back any * number of instances. {@link Mesh.fromGeometry} builds a mesh from a {@link Geometry} such as * {@link BoxGeometry} in one call. Meshes are reference counted: every {@link MeshInstance} holds * a reference to its mesh, so call {@link destroy} on a mesh you created only once no instance * uses it. * * ## Mesh APIs * There are two ways a mesh can be generated or updated. * * ### Simple Mesh API * {@link Mesh} class provides interfaces such as {@link setPositions} and {@link setUvs} that * provide a simple way to provide vertex and index data for the Mesh, and hiding the complexity * of creating the {@link VertexFormat}. This is the recommended interface to use. * * A simple example which creates a Mesh with 3 vertices, containing position coordinates only, to * form a single triangle. * * ```javascript * const mesh = new Mesh(device); * const positions = [ * 0, 0, 0, // pos 0 * 1, 0, 0, // pos 1 * 1, 1, 0 // pos 2 * ]; * mesh.setPositions(positions); * mesh.update(); * ``` * * An example which creates a Mesh with 4 vertices, containing position and uv coordinates in * channel 0, and an index buffer to form two triangles. Float32Array is used for positions and uvs. * * ```javascript * const mesh = new Mesh(device); * const positions = new Float32Array([ * 0, 0, 0, // pos 0 * 1, 0, 0, // pos 1 * 1, 1, 0, // pos 2 * 0, 1, 0 // pos 3 * ]); * const uvs = new Float32Array([ * 0, 1 // uv 3 * 1, 1, // uv 2 * 1, 0, // uv 1 * 0, 0, // uv 0 * ]); * const indices = [ * 0, 1, 2, // triangle 0 * 0, 2, 3 // triangle 1 * ]; * mesh.setPositions(positions); * mesh.setNormals(calculateNormals(positions, indices)); * mesh.setUvs(0, uvs); * mesh.setIndices(indices); * mesh.update(); * ``` * * This example demonstrates that vertex attributes such as position and normals, and also indices * can be provided using Arrays ([]) and also Typed Arrays (Float32Array and similar). Note that * typed arrays have higher performance, and are generally recommended for per-frame operations or * larger meshes, but their construction using new operator is costly operation. If you only need * to operate on a small number of vertices or indices, consider using Arrays to avoid the overhead * associated with allocating Typed Arrays. * * Follow these links for more complex examples showing the functionality. * * - {@link https://playcanvas.github.io/#graphics/mesh-decals} * - {@link https://playcanvas.github.io/#graphics/mesh-deformation} * - {@link https://playcanvas.github.io/#graphics/mesh-generation} * - {@link https://playcanvas.github.io/#graphics/point-cloud-simulation} * * ### Update Vertex and Index buffers * This allows greater flexibility, but is more complex to use. It allows more advanced setups, for * example sharing a Vertex or Index Buffer between multiple meshes. See {@link VertexBuffer}, * {@link IndexBuffer} and {@link VertexFormat} for details. * * @category Graphics */ declare class Mesh extends RefCountedObject { /** * Create a new Mesh instance from {@link Geometry} object. * * @param {GraphicsDevice} graphicsDevice - The graphics device used to manage this mesh. * @param {Geometry} geometry - The geometry object to create the mesh from. * @param {object} [options] - An object that specifies optional inputs for the function as follows: * @param {boolean} [options.storageVertex] - Defines if the vertex buffer of the mesh can be used as * a storage buffer by a compute shader. Defaults to false. Only supported on WebGPU. * @param {boolean} [options.storageIndex] - Defines if the index buffer of the mesh can be used as * a storage buffer by a compute shader. Defaults to false. Only supported on WebGPU. * @returns {Mesh} A new mesh. */ static fromGeometry(graphicsDevice: GraphicsDevice, geometry: Geometry, options?: { storageVertex?: boolean; storageIndex?: boolean; }): Mesh; /** * Create a new Mesh instance. * * @param {GraphicsDevice} graphicsDevice - The graphics device used to manage this mesh. * @param {object} [options] - Object for passing optional arguments. * @param {boolean} [options.storageVertex] - Defines if the vertex buffer can be used as * a storage buffer by a compute shader. Defaults to false. Only supported on WebGPU. * @param {boolean} [options.storageIndex] - Defines if the index buffer can be used as * a storage buffer by a compute shader. Defaults to false. Only supported on WebGPU. */ constructor(graphicsDevice: GraphicsDevice, options?: { storageVertex?: boolean; storageIndex?: boolean; }); /** * An array of index buffers. For unindexed meshes, this array can be empty. The first index * buffer in the array is used by {@link MeshInstance}s with a `renderStyle` property set to * {@link RENDERSTYLE_SOLID}. The second index buffer in the array is used if `renderStyle` is * set to {@link RENDERSTYLE_WIREFRAME}. * * @type {IndexBuffer[]} */ indexBuffer: IndexBuffer[]; /** * The vertex buffer holding the vertex data of the mesh. * * @type {VertexBuffer} */ vertexBuffer: VertexBuffer; /** * Array of primitive objects defining how vertex (and index) data in the mesh should be * interpreted by the graphics device. * * - `type` is the type of primitive to render. Can be: * * - {@link PRIMITIVE_POINTS} * - {@link PRIMITIVE_LINES} * - {@link PRIMITIVE_LINELOOP} * - {@link PRIMITIVE_LINESTRIP} * - {@link PRIMITIVE_TRIANGLES} * - {@link PRIMITIVE_TRISTRIP} * - {@link PRIMITIVE_TRIFAN} * * - `base` is the offset of the first index or vertex to dispatch in the draw call. * - `baseVertex` is the number added to each index value before indexing into the vertex buffers. (supported only in WebGPU, ignored in WebGL2) * - `count` is the number of indices or vertices to dispatch in the draw call. * - `indexed` specifies whether to interpret the primitive as indexed, thereby using the * currently set index buffer. * * @type {{type: number, base: number, baseVertex: number, count: number, indexed?: boolean}[]} */ primitive: { type: number; base: number; baseVertex: number; count: number; indexed?: boolean; }[]; /** * The skin data (if any) that drives skinned mesh animations for this mesh. * * @type {Skin|null} */ skin: Skin | null; /** * Array of object space AABBs of vertices affected by each bone. * * @type {BoundingBox[]|null} * @ignore */ boneAabb: BoundingBox[] | null; /** * Internal version of AABB, incremented when local AABB changes. * * @ignore */ _aabbVer: number; /** * AABB representing object space bounds of the mesh. * * @private */ private _aabb; /** * @type {GeometryData|null} * @private */ private _geometryData; /** * @type {Morph|null} * @private */ private _morph; /** * True if the created index buffer should be accessible as a storage buffer in compute shader. * * @private */ private _storageIndex; /** * True if the created vertex buffer should be accessible as a storage buffer in compute shader. * * @private */ private _storageVertex; id: number; device: GraphicsDevice; /** * Sets the morph data that drives morph target animations for this mesh. Set to null if * morphing is not used. * * @type {Morph|null} */ set morph(morph: Morph | null); /** * Gets the morph data that drives morph target animations for this mesh. * * @type {Morph|null} */ get morph(): Morph | null; /** * Sets the axis-aligned bounding box for the object space vertices of this mesh. * * @type {BoundingBox} */ set aabb(aabb: BoundingBox); /** * Gets the axis-aligned bounding box for the object space vertices of this mesh. * * @type {BoundingBox} */ get aabb(): BoundingBox; /** * Destroys the {@link VertexBuffer} and {@link IndexBuffer}s associated with the mesh. This is * normally called by {@link Model#destroy} and does not need to be called manually. */ destroy(): void; _destroyIndexBuffer(index: any): void; _initBoneAabbs(morphTargets: any): void; boneUsed: any[]; _initGeometryData(): void; /** * Clears the mesh of existing vertices and indices and resets the {@link VertexFormat} * associated with the mesh. This call is typically followed by calls to methods such as * {@link setPositions}, {@link setVertexStream} or {@link setIndices} and finally * {@link update} to rebuild the mesh, allowing different {@link VertexFormat}. * * @param {boolean} [verticesDynamic] - Indicates the {@link VertexBuffer} should be created * with {@link BUFFER_DYNAMIC} usage. If not specified, {@link BUFFER_STATIC} is used. * @param {boolean} [indicesDynamic] - Indicates the {@link IndexBuffer} should be created with * {@link BUFFER_DYNAMIC} usage. If not specified, {@link BUFFER_STATIC} is used. * @param {number} [maxVertices] - A {@link VertexBuffer} will be allocated with at least * maxVertices, allowing additional vertices to be added to it without the allocation. If no * value is provided, a size to fit the provided vertices will be allocated. * @param {number} [maxIndices] - An {@link IndexBuffer} will be allocated with at least * maxIndices, allowing additional indices to be added to it without the allocation. If no * value is provided, a size to fit the provided indices will be allocated. */ clear(verticesDynamic?: boolean, indicesDynamic?: boolean, maxVertices?: number, maxIndices?: number): void; /** * Sets the vertex data for any supported semantic. * * @param {string} semantic - The meaning of the vertex element. For supported semantics, see * SEMANTIC_* in {@link VertexFormat}. * @param {ArrayLike} data - Vertex data for the specified semantic. * @param {number} componentCount - The number of values that form a single Vertex element. For * example when setting a 3D position represented by 3 numbers per vertex, number 3 should be * specified. * @param {number} [numVertices] - The number of vertices to be used from data array. If not * provided, the whole data array is used. This allows to use only part of the data array. * @param {number} [dataType] - The format of data when stored in the {@link VertexBuffer}, see * TYPE_* in {@link VertexFormat}. When not specified, {@link TYPE_FLOAT32} is used. * @param {boolean} [dataTypeNormalize] - If true, vertex attribute data will be mapped from a * 0 to 255 range down to 0 to 1 when fed to a shader. If false, vertex attribute data is left * unchanged. If this property is unspecified, false is assumed. * @param {boolean} [asInt] - If true, vertex attribute data will be accessible as integer * numbers in shader code. Defaults to false, which means that vertex attribute data will be * accessible as floating point numbers. Can be only used with INT and UINT data types. */ setVertexStream(semantic: string, data: ArrayLike, componentCount: number, numVertices?: number, dataType?: number, dataTypeNormalize?: boolean, asInt?: boolean): void; /** * Gets the vertex data corresponding to a semantic. * * @param {string} semantic - The semantic of the vertex element to get. For supported * semantics, see SEMANTIC_* in {@link VertexFormat}. * @param {NumericArray} data - An array to populate with the vertex data. When * typed array is supplied, enough space needs to be reserved, otherwise only partial data is * copied. * @returns {number} Returns the number of vertices populated. */ getVertexStream(semantic: string, data: NumericArray): number; /** * Sets the vertex positions array. Vertices are stored using {@link TYPE_FLOAT32} format. * * @param {ArrayLike} positions - Vertex data containing positions. * @param {number} [componentCount] - The number of values that form a single position element. * Defaults to 3 if not specified, corresponding to x, y and z coordinates. * @param {number} [numVertices] - The number of vertices to be used from data array. If not * provided, the whole data array is used. This allows to use only part of the data array. */ setPositions(positions: ArrayLike, componentCount?: number, numVertices?: number): void; /** * Sets the vertex normals array. Normals are stored using {@link TYPE_FLOAT32} format. * * @param {ArrayLike} normals - Vertex data containing normals. * @param {number} [componentCount] - The number of values that form a single normal element. * Defaults to 3 if not specified, corresponding to x, y and z direction. * @param {number} [numVertices] - The number of vertices to be used from data array. If not * provided, the whole data array is used. This allows to use only part of the data array. */ setNormals(normals: ArrayLike, componentCount?: number, numVertices?: number): void; /** * Sets the vertex uv array. Uvs are stored using {@link TYPE_FLOAT32} format. * * @param {number} channel - The uv channel in [0..7] range. * @param {ArrayLike} uvs - Vertex data containing uv-coordinates. * @param {number} [componentCount] - The number of values that form a single uv element. * Defaults to 2 if not specified, corresponding to u and v coordinates. * @param {number} [numVertices] - The number of vertices to be used from data array. If not * provided, the whole data array is used. This allows to use only part of the data array. */ setUvs(channel: number, uvs: ArrayLike, componentCount?: number, numVertices?: number): void; /** * Sets the vertex color array. Colors are stored using {@link TYPE_FLOAT32} format, which is * useful for HDR colors. * * @param {ArrayLike} colors - Vertex data containing colors. * @param {number} [componentCount] - The number of values that form a single color element. * Defaults to 4 if not specified, corresponding to r, g, b and a. * @param {number} [numVertices] - The number of vertices to be used from data array. If not * provided, the whole data array is used. This allows to use only part of the data array. */ setColors(colors: ArrayLike, componentCount?: number, numVertices?: number): void; /** * Sets the vertex color array. Colors are stored using {@link TYPE_UINT8} format, which is * useful for LDR colors. Values in the array are expected in [0..255] range, and are mapped to * [0..1] range in the shader. * * @param {ArrayLike} colors - Vertex data containing colors. The array is * expected to contain 4 components per vertex, corresponding to r, g, b and a. * @param {number} [numVertices] - The number of vertices to be used from data array. If not * provided, the whole data array is used. This allows to use only part of the data array. */ setColors32(colors: ArrayLike, numVertices?: number): void; /** * Sets the index array. Indices are stored using 16-bit format by default, unless more than * 65535 vertices are specified, in which case 32-bit format is used. * * @param {number[]|Uint8Array|Uint16Array|Uint32Array} indices - The array of indices that * define primitives (lines, triangles, etc.). * @param {number} [numIndices] - The number of indices to be used from data array. If not * provided, the whole data array is used. This allows to use only part of the data array. */ setIndices(indices: number[] | Uint8Array | Uint16Array | Uint32Array, numIndices?: number): void; /** * Gets the vertex positions data. * * @param {NumericArray} positions - An array to populate with the vertex data. * When typed array is supplied, enough space needs to be reserved, otherwise only partial data * is copied. * @returns {number} Returns the number of vertices populated. */ getPositions(positions: NumericArray): number; /** * Gets the vertex normals data. * * @param {NumericArray} normals - An array to populate with the vertex data. When * typed array is supplied, enough space needs to be reserved, otherwise only partial data is * copied. * @returns {number} Returns the number of vertices populated. */ getNormals(normals: NumericArray): number; /** * Gets the vertex uv data. * * @param {number} channel - The uv channel in [0..7] range. * @param {NumericArray} uvs - An array to populate with the vertex data. When * typed array is supplied, enough space needs to be reserved, otherwise only partial data is * copied. * @returns {number} Returns the number of vertices populated. */ getUvs(channel: number, uvs: NumericArray): number; /** * Gets the vertex color data. * * @param {NumericArray} colors - An array to populate with the vertex data. When * typed array is supplied, enough space needs to be reserved, otherwise only partial data is * copied. * @returns {number} Returns the number of vertices populated. */ getColors(colors: NumericArray): number; /** * Gets the index data. * * @param {number[]|Uint8Array|Uint16Array|Uint32Array} indices - An array to populate with the * index data. When a typed array is supplied, enough space needs to be reserved, otherwise * only partial data is copied. * @returns {number} Returns the number of indices populated. */ getIndices(indices: number[] | Uint8Array | Uint16Array | Uint32Array): number; /** * Applies any changes to vertex stream and indices to mesh. This allocates or reallocates * {@link vertexBuffer} or {@link indexBuffer} to fit all provided vertices and indices, and * fills them with data. * * @param {number} [primitiveType] - The type of primitive to render. Can be: * * - {@link PRIMITIVE_POINTS} * - {@link PRIMITIVE_LINES} * - {@link PRIMITIVE_LINELOOP} * - {@link PRIMITIVE_LINESTRIP} * - {@link PRIMITIVE_TRIANGLES} * - {@link PRIMITIVE_TRISTRIP} * - {@link PRIMITIVE_TRIFAN} * * Defaults to {@link PRIMITIVE_TRIANGLES} if not specified. * @param {boolean} [updateBoundingBox] - True to update bounding box. Bounding box is updated * only if positions were set since last time update was called, and `componentCount` for * position was 3, otherwise bounding box is not updated. See {@link setPositions}. Defaults to * true if not specified. Set this to false to avoid update of the bounding box and use aabb * property to set it instead. */ update(primitiveType?: number, updateBoundingBox?: boolean): void; _buildVertexFormat(vertexCount: any): VertexFormat; _updateVertexBuffer(): void; _updateIndexBuffer(): void; prepareRenderState(renderStyle: any): void; updateRenderStates(): void; generateWireframe(): void; } /** * @import { Mesh } from './mesh.js' */ /** * A `Render` contains an array of meshes that are referenced by a single hierarchy node in a GLB * scene, and are accessible using the {@link ContainerResource#renders} property. A `Render` is * the resource of a Render Asset. They are usually created by the GLB loader and not created by * hand. * * @ignore */ declare class Render extends EventHandler { /** * Fired when the meshes are set on the render. The handler is passed the an array of * {@link Mesh} objects. * * @event * @example * render.on('set:meshes', (meshes) => { * console.log(`Render has ${meshes.length} meshes`); * }); */ static EVENT_SETMESHES: string; /** * Meshes are reference counted, and this class owns the references and is responsible for * releasing the meshes when they are no longer referenced. * * @type {Array|null} * @private */ private _meshes; /** * Sets the meshes that the render contains. * * @type {Array|null} */ set meshes(value: Array | null); /** * Gets the meshes that the render contains. * * @type {Array|null} */ get meshes(): Array | null; destroy(): void; /** * Decrement references to meshes. Destroy the ones with zero references. */ decRefMeshes(): void; /** * Increments ref count on all meshes. */ incRefMeshes(): void; } /** * @import { AppBase } from '../app-base.js' * @import { Entity } from '../entity.js' */ /** * The `Script` class is the fundamental base class for all scripts within PlayCanvas. It provides * the minimal interface required for a script to be compatible with both the Engine and the * Editor. * * At its core, a script is simply a collection of methods that are called at various points in the * Engine's lifecycle. These methods are: * * - `Script#initialize` - Called once when the script is initialized. * - `Script#postInitialize` - Called once after all scripts have been initialized. * - `Script#update` - Called every frame, if the script is enabled. * - `Script#postUpdate` - Called every frame, after all scripts have been updated. * - `Script#swap` - Called when a script is redefined. * * These methods are entirely optional, but provide a useful way to manage the lifecycle of a * script and perform any necessary setup and cleanup. * * Below is a simple example of a script that rotates an entity every frame. * @example * ```javascript * import { Script } from 'playcanvas'; * * export class Rotator extends Script { * static scriptName = 'rotator'; * * update(dt) { * this.entity.rotateLocal(0, 1, 0); * } * } * ``` * * When this script is attached to an entity, the update will be called every frame, slowly * rotating the entity around the Y-axis. * * For more information on how to create scripts, see the [Scripting Overview](https://developer.playcanvas.com/user-manual/scripting/). * * The `playcanvas` package also ships a library of ready-to-use `Script` subclasses under the * `playcanvas/scripts/esm/` subpath — camera and character controllers, post-processing, water, * sky, grid, shadow catcher, planar reflections, XR and Gaussian-splat effects. Import them * directly, for example * `import { CameraControls } from 'playcanvas/scripts/esm/camera-controls.mjs'`. * * @category Script */ declare class Script extends EventHandler { /** * Fired when a script instance becomes enabled. * * @event * @example * export class PlayerController extends Script { * static scriptName = 'playerController'; * initialize() { * this.on('enable', () => { * // Script Instance is now enabled * }); * } * }; */ static EVENT_ENABLE: string; /** * Fired when a script instance becomes disabled. * * @event * @example * export class PlayerController extends Script { * static scriptName = 'playerController'; * initialize() { * this.on('disable', () => { * // Script Instance is now disabled * }); * } * }; */ static EVENT_DISABLE: string; /** * Fired when a script instance changes state to enabled or disabled. The handler is passed a * boolean parameter that states whether the script instance is now enabled or disabled. * * @event * @example * export class PlayerController extends Script { * static scriptName = 'playerController'; * initialize() { * this.on('state', (enabled) => { * console.log(`Script Instance is now ${enabled ? 'enabled' : 'disabled'}`); * }); * } * }; */ static EVENT_STATE: string; /** * Fired when a script instance is destroyed and removed from component. * * @event * @example * export class PlayerController extends Script { * static scriptName = 'playerController'; * initialize() { * this.on('destroy', () => { * // no longer part of the entity * // this is a good place to clean up allocated resources used by the script * }); * } * }; */ static EVENT_DESTROY: string; /** * Fired when script attributes have changed. This event is available in two forms. They are as * follows: * * 1. `attr` - Fired for any attribute change. The handler is passed the name of the attribute * that changed, the value of the attribute before the change and the value of the attribute * after the change. * 2. `attr:[name]` - Fired for a specific attribute change. The handler is passed the value of * the attribute before the change and the value of the attribute after the change. * * @event * @example * export class PlayerController extends Script { * static scriptName = 'playerController'; * initialize() { * this.on('attr', (name, newValue, oldValue) => { * console.log(`Attribute '${name}' changed from '${oldValue}' to '${newValue}'`); * }); * } * }; * @example * export class PlayerController extends Script { * static scriptName = 'playerController'; * initialize() { * this.on('attr:speed', (newValue, oldValue) => { * console.log(`Attribute 'speed' changed from '${oldValue}' to '${newValue}'`); * }); * } * }; */ static EVENT_ATTR: string; /** * Fired when a script instance had an exception. The script instance will be automatically * disabled. The handler is passed an Error object containing the details of the * exception and the name of the method that threw the exception. * * @event * @example * export class PlayerController extends Script { * static scriptName = 'playerController'; * initialize() { * this.on('error', (err, method) => { * // caught an exception * console.log(err.stack); * }); * } * }; */ static EVENT_ERROR: string; /** * @type {string|null} * @private */ private static __name; /** * @param {*} constructorFn - The constructor function of the script type. * @returns {string} The script name. * @private */ private static __getScriptName; /** * Sets the unique name of the script. * * @type {string|null} */ static set scriptName(value: string | null); /** * Gets the unique name of the script. * * @type {string|null} */ static get scriptName(): string | null; /** * Create a new Script instance. * * @param {object} args - The input arguments object. * @param {AppBase} args.app - The AppBase that is running the script. * @param {Entity} args.entity - The Entity that the script is attached to. */ constructor(args: { app: AppBase; entity: Entity; }); /** * The {@link AppBase} that the instance of this script belongs to. * * @type {AppBase} */ app: AppBase; /** * The {@link Entity} that the instance of this script belongs to. * * @type {Entity} */ entity: Entity; /** @private */ private _enabled; /** @private */ private _enabledOld; /** @private */ private _initialized; /** @private */ private _postInitialized; /** @private */ private __destroyed; /** @private */ private __scriptType; /** * The order in the script component that the methods of this script instance will run * relative to other script instances in the component. * * @type {number} * @private */ private __executionOrder; /** * Sets the enabled state of the script instance. When disabled, no update methods will be * called on each tick. `initialize` and `postInitialize` methods will run once when the script * instance is next in the `enabled` state during an app tick. * * @type {boolean} */ set enabled(value: boolean); /** * Gets the running state of the script instance. Returns true when the script instance is * enabled and its owning {@link Entity} (and all ancestors) and {@link ScriptComponent} are * also enabled; otherwise false. * * @type {boolean} */ get enabled(): boolean; /** * @typedef {object} ScriptInitializationArgs * @property {boolean} [enabled] - True if the script instance is in running state. * @property {AppBase} app - The AppBase that is running the script. * @property {Entity} entity - The Entity that the script is attached to. */ /** * @param {ScriptInitializationArgs} args - The input arguments object. * @protected */ protected initScript(args: { /** * - True if the script instance is in running state. */ enabled?: boolean; /** * - The AppBase that is running the script. */ app: AppBase; /** * - The Entity that the script is attached to. */ entity: Entity; }): void; } /** * @import { Texture } from '../platform/graphics/texture.js' * @import { Vec2 } from '../core/math/vec2.js' * @import { Vec4 } from '../core/math/vec4.js' */ /** * A TextureAtlas contains a number of frames from a texture. Each frame defines a region in a * texture. The TextureAtlas is referenced by {@link Sprite}s. * * @category Graphics */ declare class TextureAtlas extends EventHandler { /** * @type {Texture} * @private */ private _texture; /** * @type {object} * @private */ private _frames; /** * Sets the texture used by the atlas. * * @type {Texture} */ set texture(value: Texture); /** * Gets the texture used by the atlas. * * @type {Texture} */ get texture(): Texture; /** * Sets the frames which define portions of the texture atlas. * * @type {object} */ set frames(value: object); /** * Gets the frames which define portions of the texture atlas. * * @type {object} */ get frames(): object; /** * Set a new frame in the texture atlas. * * @param {string} key - The key of the frame. * @param {object} data - The properties of the frame. * @param {Vec4} data.rect - The u, v, width, height properties of the frame in pixels. * @param {Vec2} data.pivot - The pivot of the frame - values are between 0-1. * @param {Vec4} data.border - The border of the frame for 9-slicing. Values are ordered as * follows: left, bottom, right, top border in pixels. * @example * atlas.setFrame('1', { * rect: new Vec4(0, 0, 128, 128), * pivot: new Vec2(0.5, 0.5), * border: new Vec4(5, 5, 5, 5) * }); */ setFrame(key: string, data: { rect: Vec4; pivot: Vec2; border: Vec4; }): void; /** * Removes a frame from the texture atlas. * * @param {string} key - The key of the frame. * @example * atlas.removeFrame('1'); */ removeFrame(key: string): void; /** * Free up the underlying texture owned by the atlas. */ destroy(): void; } /** * A Sprite contains references to one or more frames of a {@link TextureAtlas}. It can be used by * the {@link SpriteComponent} or the {@link ElementComponent} to render a single frame or a sprite * animation. * * @category Graphics */ declare class Sprite extends EventHandler { /** * Create a new Sprite instance. * * @param {GraphicsDevice} device - The graphics device of the application. * @param {object} [options] - Options for creating the Sprite. * @param {number} [options.pixelsPerUnit] - The number of pixels that map to one PlayCanvas * unit. Defaults to 1. * @param {number} [options.renderMode] - The rendering mode of the sprite. Can be: * * - {@link SPRITE_RENDERMODE_SIMPLE} * - {@link SPRITE_RENDERMODE_SLICED} * - {@link SPRITE_RENDERMODE_TILED} * * Defaults to {@link SPRITE_RENDERMODE_SIMPLE}. * @param {TextureAtlas} [options.atlas] - The texture atlas. Defaults to null. * @param {string[]} [options.frameKeys] - The keys of the frames in the sprite atlas that this * sprite is using. Defaults to null. */ constructor(device: GraphicsDevice, options?: { pixelsPerUnit?: number; renderMode?: number; atlas?: TextureAtlas; frameKeys?: string[]; }); _device: GraphicsDevice; _pixelsPerUnit: number; _renderMode: number; _atlas: TextureAtlas; _frameKeys: string[]; _meshes: any[]; _updatingProperties: boolean; _meshesDirty: boolean; /** * Sets the keys of the frames in the sprite atlas that this sprite is using. * * @type {string[]} */ set frameKeys(value: string[]); /** * Gets the keys of the frames in the sprite atlas that this sprite is using. * * @type {string[]} */ get frameKeys(): string[]; /** * Sets the texture atlas. * * @type {TextureAtlas} */ set atlas(value: TextureAtlas); /** * Gets the texture atlas. * * @type {TextureAtlas} */ get atlas(): TextureAtlas; /** * Sets the number of pixels that map to one PlayCanvas unit. * * @type {number} */ set pixelsPerUnit(value: number); /** * Gets the number of pixels that map to one PlayCanvas unit. * * @type {number} */ get pixelsPerUnit(): number; /** * Sets the rendering mode of the sprite. Can be: * * - {@link SPRITE_RENDERMODE_SIMPLE} * - {@link SPRITE_RENDERMODE_SLICED} * - {@link SPRITE_RENDERMODE_TILED} * * @type {number} */ set renderMode(value: number); /** * Sets the rendering mode of the sprite. * * @type {number} */ get renderMode(): number; /** * An array that contains a mesh for each frame. * * @type {Mesh[]} */ get meshes(): Mesh[]; _createMeshes(): void; _createSimpleMesh(frame: any): Mesh; _create9SliceMesh(): Mesh; _onSetFrames(frames: any): void; _onFrameChanged(frameKey: any, frame: any): void; _onFrameRemoved(frameKey: any): void; startUpdate(): void; endUpdate(): void; /** * Free up the meshes created by the sprite. */ destroy(): void; } /** * @import { AppBase } from './app-base.js' * @import { Entity } from './entity.js' */ /** * Create a Template resource from raw database data. * * @category Framework */ declare class Template { /** * Create a new Template instance. * * @param {AppBase} app - The application. * @param {object} data - Asset data from the database. */ constructor(app: AppBase, data: object); /** * @type {AppBase} * @private */ private _app; /** @private */ private _data; /** * @type {Entity|null} * @private */ private _templateRoot; /** * Create an instance of this template. * * @returns {Entity} The root entity of the created instance. */ instantiate(): Entity; /** @private */ private _parseTemplate; set data(value: any); get data(): any; } /** * The resource each asset type loads, keyed by the `type` string passed to the {@link Asset} * constructor and to {@link AssetRegistry#find}: `'texture'` maps to {@link Texture}, `'material'` * to {@link Material} and so on. This is what types {@link Asset#resource}: an `Asset<'texture'>` * holds a {@link Texture}. An application that registers its own resource handler with * {@link ResourceLoader#addHandler} extends the map - and with it the typing of * {@link Asset#resource}, {@link AssetRegistry#find}, {@link AssetRegistry#findAll} and * {@link AssetRegistry#loadFromUrl} - by augmenting this interface: * * ```ts * declare module 'playcanvas' { * interface AssetMap { * mytype: MyResource; * } * } * ``` */ interface AssetMap { /** * - An animation: an {@link AnimTrack} when loaded from * a glTF or GLB file, or a legacy {@link Animation} when loaded from JSON. */ animation: Animation | AnimTrack; /** * - An animation clip. */ animclip: AnimTrack; /** * - An animation state graph. */ animstategraph: AnimStateGraph; /** * - A sound. */ audio: Sound; /** * - The raw contents of the file. */ binary: ArrayBuffer; /** * - A bundle: an archive whose files back other assets. */ bundle: Bundle; /** * - The renders, materials, textures, animations and * gsplats of a glTF or GLB file. */ container: ContainerResource; /** * - The CSS text. */ css: string; /** * - The cube map, or null when the asset provides only prefiltered * levels. {@link Asset#resources} holds the cube map followed by its six prefiltered levels, with * null for each level the asset does not provide. */ cubemap: Texture | null; /** * - Folders hold no resource. */ folder: null; /** * - A {@link Font} loaded from a font file. */ font: Font | CanvasFont; /** * - A Gaussian splat resource, or the * octree resource of a level-of-detail splat scene. */ gsplat: GSplatResourceBase | GSplatOctreeResource; /** * - The root entity of an instantiated scene hierarchy. */ hierarchy: Entity; /** * - The HTML text. */ html: string; /** * - The parsed JSON data. */ json: unknown; /** * - A material, a {@link StandardMaterial} unless a custom parser * creates another kind. */ material: Material; /** * - A model. */ model: Model; /** * - The meshes of one glTF mesh, created when a container asset loads. */ render: Render; /** * - A scene. */ scene: Scene; /** * - The settings block of a scene file. */ scenesettings: object; /** * - The script classes declared by a script file, * keyed by class name. */ script: Record; /** * - The shader source text. */ shader: string; /** * - A sprite. */ sprite: Sprite; /** * - A template. */ template: Template; /** * - The text of the file. */ text: string; /** * - A texture. */ texture: Texture; /** * - A texture atlas. */ textureatlas: TextureAtlas; } /** * The type of an {@link Asset}, such as `'texture'` or `'material'`: the keys of {@link AssetMap}. * This is what the {@link Asset} constructor, {@link AssetRegistry#find}, * {@link AssetRegistry#findAll} and {@link AssetRegistry#loadFromUrl} take, and what * {@link AssetResource} is indexed by. */ type AssetType = keyof AssetMap & string; /** * The resource an {@link Asset} of type `K` holds: `AssetMap[K]` for a type in {@link AssetMap}, so * `AssetResource<'texture'>` is {@link Texture}, and `unknown` for any other string, including a * plain `string`. This is the type of {@link Asset#resource}. */ type AssetResource = K extends AssetType ? AssetMap[K] : unknown; /** * Callback used by {@link Asset#ready} and called when an asset is ready. */ type AssetReadyCallback = (asset: Asset) => void; /** * The resource each asset type loads, keyed by the `type` string passed to the {@link Asset} * constructor and to {@link AssetRegistry#find}: `'texture'` maps to {@link Texture}, `'material'` * to {@link Material} and so on. This is what types {@link Asset#resource}: an `Asset<'texture'>` * holds a {@link Texture}. An application that registers its own resource handler with * {@link ResourceLoader#addHandler} extends the map - and with it the typing of * {@link Asset#resource}, {@link AssetRegistry#find}, {@link AssetRegistry#findAll} and * {@link AssetRegistry#loadFromUrl} - by augmenting this interface: * * ```ts * declare module 'playcanvas' { * interface AssetMap { * mytype: MyResource; * } * } * ``` * * @typedef {object} AssetMap * @property {Animation | AnimTrack} animation - An animation: an {@link AnimTrack} when loaded from * a glTF or GLB file, or a legacy {@link Animation} when loaded from JSON. * @property {AnimTrack} animclip - An animation clip. * @property {AnimStateGraph} animstategraph - An animation state graph. * @property {Sound} audio - A sound. * @property {ArrayBuffer} binary - The raw contents of the file. * @property {Bundle} bundle - A bundle: an archive whose files back other assets. * @property {ContainerResource} container - The renders, materials, textures, animations and * gsplats of a glTF or GLB file. * @property {string} css - The CSS text. * @property {Texture | null} cubemap - The cube map, or null when the asset provides only prefiltered * levels. {@link Asset#resources} holds the cube map followed by its six prefiltered levels, with * null for each level the asset does not provide. * @property {null} folder - Folders hold no resource. * @property {Font | CanvasFont} font - A {@link Font} loaded from a font file. * @property {GSplatResourceBase | GSplatOctreeResource} gsplat - A Gaussian splat resource, or the * octree resource of a level-of-detail splat scene. * @property {Entity} hierarchy - The root entity of an instantiated scene hierarchy. * @property {string} html - The HTML text. * @property {unknown} json - The parsed JSON data. * @property {Material} material - A material, a {@link StandardMaterial} unless a custom parser * creates another kind. * @property {Model} model - A model. * @property {Render} render - The meshes of one glTF mesh, created when a container asset loads. * @property {Scene} scene - A scene. * @property {object} scenesettings - The settings block of a scene file. * @property {Record} script - The script classes declared by a script file, * keyed by class name. * @property {string} shader - The shader source text. * @property {Sprite} sprite - A sprite. * @property {Template} template - A template. * @property {string} text - The text of the file. * @property {Texture} texture - A texture. * @property {TextureAtlas} textureatlas - A texture atlas. */ /** * The type of an {@link Asset}, such as `'texture'` or `'material'`: the keys of {@link AssetMap}. * This is what the {@link Asset} constructor, {@link AssetRegistry#find}, * {@link AssetRegistry#findAll} and {@link AssetRegistry#loadFromUrl} take, and what * {@link AssetResource} is indexed by. * * @typedef {keyof AssetMap & string} AssetType */ /** * The resource an {@link Asset} of type `K` holds: `AssetMap[K]` for a type in {@link AssetMap}, so * `AssetResource<'texture'>` is {@link Texture}, and `unknown` for any other string, including a * plain `string`. This is the type of {@link Asset#resource}. * * @template {AssetType | (string & {})} K * @typedef {K extends AssetType ? AssetMap[K] : unknown} AssetResource */ /** * @template {AssetType | (string & {})} [K=string] * @callback AssetReadyCallback * Callback used by {@link Asset#ready} and called when an asset is ready. * @param {Asset} asset - The ready asset. * @returns {void} */ /** * An Asset is the engine's record of a single resource: a texture, a material, a glTF container, a * sound, a script and so on. Assets live in the application's {@link AssetRegistry} at * {@link AppBase#assets}, which loads them on demand. * * An asset has five parts: * * - `type` selects the {@link ResourceHandler} that loads it and the type of `resource`. * - `file` names the file that holds the data, when there is one. * - `data` carries JSON that either is the resource, as for materials, or describes how to process * the file, as for texture and model mappings. * - `options` carries handler-specific load options. * - `resource` holds the loaded object, such as a {@link Texture}. `resources` holds every object * the handler produced when there is more than one, such as a cube map and its prefiltered levels. * * Loading is driven by the registry: call {@link AssetRegistry#load}, or set {@link preload} so the * asset loads when added. Wait for the result with {@link ready} or listen for the `load` and * `error` events. {@link unload} releases the resource. * * The `type` string also types the resource: `new Asset('brick', 'texture', file)` creates an * `Asset<'texture'>` whose `resource` is a {@link Texture} once loaded, and * `app.assets.find('brick', 'texture')` returns one. See {@link AssetMap} for the built-in types * and for adding application-defined ones. An asset whose type is only known as a `string` has a * `resource` of type `unknown`. * * @example * const asset = new Asset('brick', 'texture', { url: 'textures/brick.png' }); * app.assets.add(asset); * app.assets.load(asset); * asset.ready((asset) => { * material.diffuseMap = asset.resource; * }); * @template {AssetType | (string & {})} [K=string] * @category Asset */ declare class Asset extends EventHandler { /** * Fired when the asset has completed loading. * * @event * @example * asset.on('load', (asset) => { * console.log(`Asset loaded: ${asset.name}`); * }); */ static EVENT_LOAD: string; /** * Fired just before the asset unloads the resource. This allows for the opportunity to prepare * for an asset that will be unloaded. E.g. Changing the texture of a model to a default before * the one it was using is unloaded. * * @event * @example * asset.on('unload', (asset) => { * console.log(`Asset about to unload: ${asset.name}`); * }); */ static EVENT_UNLOAD: string; /** * Fired when the asset is removed from the asset registry. * * @event * @example * asset.on('remove', (asset) => { * console.log(`Asset removed: ${asset.name}`); * }); */ static EVENT_REMOVE: string; /** * Fired if the asset encounters an error while loading. * * @event * @example * asset.on('error', (err, asset) => { * console.error(`Error loading asset ${asset.name}: ${err}`); * }); */ static EVENT_ERROR: string; /** * Fired when one of the asset properties `file`, `data`, `resource` or `resources` is changed. * * @event * @example * asset.on('change', (asset, property, newValue, oldValue) => { * console.log(`Asset ${asset.name} has property ${property} changed from ${oldValue} to ${newValue}`); * }); */ static EVENT_CHANGE: string; /** * Fired as the asset's file downloads, with the number of bytes received so far and the total * expected. Only asset types whose file is fetched as binary data report progress: * `animation` (GLB only), `audio`, `binary`, `container`, `gsplat`, `model` and `texture`. * Textures loaded through an image element have no download progress, so they fire once at 0 * and once at a fixed placeholder total, whether or not the file was downloaded. * * Please note: * - downloads are skipped when `asset.file.contents` is supplied, so no progress is reported * - totalBytes may not be reliable as it is based on the content-length header of the response * * @event * @example * asset.on('progress', (receivedBytes, totalBytes) => { * console.log(`Asset ${asset.name} progress ${receivedBytes / totalBytes}`); * }); */ static EVENT_PROGRESS: string; /** * Fired when we add a new localized asset id to the asset. * * @event * @example * asset.on('add:localized', (locale, assetId) => { * console.log(`Asset ${asset.name} has added localized asset ${assetId} for locale ${locale}`); * }); */ static EVENT_ADDLOCALIZED: string; /** * Fired when we remove a localized asset id from the asset. * * @event * @example * asset.on('remove:localized', (locale, assetId) => { * console.log(`Asset ${asset.name} has removed localized asset ${assetId} for locale ${locale}`); * }); */ static EVENT_REMOVELOCALIZED: string; /** * Helper function to resolve asset file data and return the contents as an ArrayBuffer. If the * asset file contents are present, that is returned. Otherwise the file data is be downloaded * via http. * * @param {string} loadUrl - The URL as passed into the handler * @param {ResourceLoaderCallback} callback - The callback function to receive results. * @param {Asset} [asset] - The asset * @param {number} maxRetries - Number of retries if http download is required * @ignore */ static fetchArrayBuffer(loadUrl: string, callback: ResourceLoaderCallback, asset?: Asset, maxRetries?: number): void; /** * Create a new Asset record. Add it to the {@link AssetRegistry} with * {@link AssetRegistry#add} so the application can find and load it. * * @param {string} name - A non-unique but human-readable name which can be later used to * retrieve the asset. * @param {K} type - The type of asset (an {@link AssetType}), which selects the resource * handler and the type of {@link Asset#resource}. The types a developer commonly creates are: * * - "animation" - see {@link Animation} and {@link AnimTrack} * - "animclip" - see {@link AnimTrack} * - "animstategraph" - see {@link AnimStateGraph} * - "audio" - see {@link Sound} * - "binary" - an `ArrayBuffer` * - "container" - see {@link ContainerResource} * - "css" - a `string` * - "cubemap" - see {@link Texture}; null when only prefiltered levels are provided * - "font" - see {@link Font} * - "gsplat" - a Gaussian splat resource * - "html" - a `string` * - "json" - the parsed JSON * - "material" - see {@link Material} * - "model" - see {@link Model} * - "script" - see {@link Script} * - "shader" - a `string` * - "sprite" - see {@link Sprite} * - "text" - a `string` * - "texture" - see {@link Texture} * - "textureatlas" - see {@link TextureAtlas} * * Types that the engine creates itself while loading, such as `render` or `scene`, are omitted * here; every built-in type is listed in {@link AssetMap}. Any other string is accepted for an * application-defined handler; see {@link AssetMap} for typing its resource. * @param {object} [file] - Details about the file the asset is made from. At the least must * contain the 'url' field. For assets that don't contain file data use null. * @param {string} [file.url] - The URL of the resource file that contains the asset data. * @param {string} [file.filename] - The filename of the resource file or null if no filename * was set (e.g from using {@link AssetRegistry#loadFromUrl}). * @param {number} [file.size] - The size of the resource file or null if no size was set * (e.g. from using {@link AssetRegistry#loadFromUrl}). * @param {string} [file.hash] - The MD5 hash of the resource file data and the Asset data * field or null if hash was set (e.g from using {@link AssetRegistry#loadFromUrl}). * @param {ArrayBuffer} [file.contents] - Optional file contents. This is faster than wrapping * the data in a (base64 encoded) blob. Currently only used by container assets. * @param {object|string} [data] - JSON object or string with additional data about the asset. * (e.g. for texture and model assets) or contains the asset data itself (e.g. in the case of * materials). * @param {object} [options] - The asset handler options. For container options see * {@link ContainerHandler}. * @param {'anonymous'|'use-credentials'|null} [options.crossOrigin] - For use with texture assets * that are loaded using the browser. This setting overrides the default crossOrigin specifier. * For more details on crossOrigin and its use, see * https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/crossOrigin. * @example * // an Asset<'texture'>: once loaded, asset.resource is a Texture * const asset = new Asset("a texture", "texture", { * url: "http://example.com/my/assets/here/texture.png" * }); */ constructor(name: string, type: K, file?: { url?: string; filename?: string; size?: number; hash?: string; contents?: ArrayBuffer; }, data?: object | string, options?: { crossOrigin?: "anonymous" | "use-credentials" | null; }); /** * @type {AssetFile | null} * @private */ private _file; /** * A string-assetId dictionary that maps locale to asset id. * * @type {object} * @private */ private _i18n; /** * Whether to preload the asset. * * @private */ private _preload; /** * This is where the loaded resource(s) are stored. * * @type {AssetResource[]} * @private */ private _resources; /** * The asset id. * * @type {number} */ id: number; /** * True if the asset has finished attempting to load the resource. It is not guaranteed * that the resources are available as there could have been a network error. */ loaded: boolean; /** * True if the resource is currently being loaded. */ loading: boolean; /** * Optional JSON data that contains the asset handler options. * * @type {object} */ options: object; /** * The asset registry that this Asset belongs to. * * @type {AssetRegistry|null} */ registry: AssetRegistry | null; /** * Asset tags. Enables finding of assets by tags using the {@link AssetRegistry#findByTag} method. * * @type {Tags} */ tags: Tags; /** * The type of the asset: one of the {@link AssetType} names, or the name of an * application-defined resource handler. See {@link AssetMap}. * * @type {K} */ type: K; /** * The URL object. * * @type {string | null} * @ignore */ urlObject: string | null; _name: string; _data: any; /** * Sets the file details or null if no file. * * @type {object} */ set file(value: object); /** * Gets the file details or null if no file. * * @type {object} */ get file(): object; /** * Sets the asset name. * * @type {string} */ set name(value: string); /** * Gets the asset name. * * @type {string} */ get name(): string; /** * Sets optional asset JSON data. This contains either the complete resource data (such as in * the case of a material) or additional data (such as in the case of a model which contains * mappings from mesh to material). * * @type {object} */ set data(value: object); /** * Gets optional asset JSON data. * * @type {object} */ get data(): object; /** * Sets the asset resource. For example, a {@link StandardMaterial} or a {@link Texture}. The * value is checked against the asset's type. As with the elements of an array, the check is * bypassed when assigning through a variable typed as a plain `Asset`, so keep typed assets * typed where their resource is assigned. * * @param {AssetResource} value - The resource. */ set resource(value: AssetResource); /** * Gets the asset resource. Its type follows the asset's type: a {@link Texture} for an * `Asset<'texture'>`, a {@link Material} for an `Asset<'material'>` and so on (see * {@link AssetMap}), or `unknown` when the type is only known as a `string`. It is `undefined` * until the asset has loaded and after {@link Asset#unload}, so narrow it before use unless the * asset is known to be loaded, for example inside {@link Asset#ready}. * * @type {AssetResource | undefined} */ get resource(): AssetResource | undefined; /** * Sets the asset resources. Some assets can hold more than one runtime resource (cube maps, * for example). * * @type {AssetResource[]} */ set resources(value: AssetResource[]); /** * Gets the asset resources. For a cube map asset, the first entry is the cube map and the * remaining entries are its prefiltered levels, some of which may be `null`. * * @type {AssetResource[]} */ get resources(): AssetResource[]; /** * Sets whether to preload an asset. If true, the asset will be loaded during the preload phase * of application initialization or when calling {@link AssetRegistry#add}. * * @type {boolean} */ set preload(value: boolean); /** * Gets whether to preload an asset. * * @type {boolean} */ get preload(): boolean; set loadFaces(value: any); get loadFaces(): any; _loadFaces: any; /** * Return the URL required to fetch the file for this asset. * * @returns {string|null} The URL. Returns null if the asset has no associated file. * @example * const asset = app.assets.find("My Image", "texture"); * const img = "<img src='" + asset.getFileUrl() + "'>"; */ getFileUrl(): string | null; /** * Construct an asset URL from this asset's location and a relative path. If the relativePath * is a blob or Base64 URI, then return that instead. * * @param {string} relativePath - The relative path to be concatenated to this asset's base url. * @returns {string} Resulting URL of the asset. * @ignore */ getAbsoluteUrl(relativePath: string): string; /** * Returns the asset id of the asset that corresponds to the specified locale. * * @param {string} locale - The desired locale e.g. Ar-AR. * @returns {number} An asset id or null if there is no asset specified for the desired locale. * @ignore */ getLocalizedAssetId(locale: string): number; /** * Adds a replacement asset id for the specified locale. When the locale in * {@link AppBase#i18n} changes then references to this asset will be replaced with the * specified asset id. (Currently only supported by the {@link ElementComponent}). * * @param {string} locale - The locale e.g. Ar-AR. * @param {number} assetId - The asset id. * @ignore */ addLocalizedAssetId(locale: string, assetId: number): void; /** * Removes a localized asset. * * @param {string} locale - The locale e.g. Ar-AR. * @ignore */ removeLocalizedAssetId(locale: string): void; /** * Take a callback which is called as soon as the asset is loaded. If the asset is already * loaded the callback is called straight away. * * The callback fires on success only, and a failed load still marks the asset as loaded while * firing `error` rather than `load`. So a callback registered before the failure never runs, * and one registered after it runs immediately with {@link Asset#resource} still null. Listen * for the `error` event as well whenever a failure has to be handled, check `asset.resource` * inside the callback, and never await this callback alone. * * @param {AssetReadyCallback} callback - The function called when the asset is ready. Passed * the (asset) arguments. * @param {object} [scope] - Scope object to use when calling the callback. * @example * const asset = app.assets.find("My Asset"); * asset.ready((asset) => { * // asset loaded * }); * app.assets.load(asset); */ ready(callback: AssetReadyCallback, scope?: object): void; reload(): void; /** * Destroys the associated resource and marks asset as unloaded. * The `unload` event also fires while the asset is loading, allowing resource handlers to * cancel pending work. * * @example * const asset = app.assets.find("My Asset"); * asset.unload(); * // asset.resource is null */ unload(): void; } /** * Callback used by {@link ResourceHandler#load} when a resource is loaded (or an error occurs). */ type ResourceHandlerCallback = (err: string | null, response?: any) => void; /** * The context describing the resource being loaded, passed to {@link ResourceParser#canParse}. */ type ParserContext = { /** * - The original resource URL with any query string removed, or null. */ url: string | null; /** * - The lower-cased file extension without a leading dot (for example `'json'`), * or an empty string if there is none. */ ext: string; /** * - The lower-cased file name (for example `'lod-meta.json'`), or an empty * string. */ basename: string; /** * - The asset being loaded, if any. */ asset: Asset | undefined; /** * - The running {@link AppBase}. */ app: AppBase; }; /** * A parser used by a {@link ResourceHandler} to recognize and load a specific resource format. A parser * implements `canParse` (to claim a resource) and `load` (to fetch and produce it), and may implement * `open`. When registered with {@link ResourceHandler#addParser} the handler assigns itself to the * parser's `handler` property, so `load` can fetch the data via `this.handler.fetch(...)`. */ type ResourceParser = { /** * - Returns true if this parser can handle the * described resource. Parsers are consulted newest-first; the first to return true is used. */ canParse: (context: ParserContext) => boolean; /** * - * Fetches (typically via `this.handler.fetch`) and produces the resource, then invokes the callback. */ load: (url: (string | { load: string; original: string; }), callback: ResourceHandlerCallback, asset?: Asset) => void; /** * - Optional. Called by the default * {@link ResourceHandler#open} when parsers are registered. Handlers that override `open` may call * it with an extended signature - for example the texture handler calls * `open(url, data, device, textureOptions)` on its parsers. */ open?: (url: string, data: any, asset?: Asset) => any; /** * - Assigned by the owning handler on registration; available in * `load`/`open` (for example `this.handler.fetch(...)`). */ handler?: ResourceHandler; }; /** * @import { AppBase } from '../app-base.js' * @import { AssetRegistry } from '../asset/asset-registry.js' */ /** * @callback ResourceHandlerCallback * Callback used by {@link ResourceHandler#load} when a resource is loaded (or an error occurs). * @param {string|null} err - The error message in the case where the load fails. * @param {any} [response] - The raw data that has been successfully loaded. * @returns {void} */ /** * The context describing the resource being loaded, passed to {@link ResourceParser#canParse}. * * @typedef {object} ParserContext * @property {string|null} url - The original resource URL with any query string removed, or null. * @property {string} ext - The lower-cased file extension without a leading dot (for example `'json'`), * or an empty string if there is none. * @property {string} basename - The lower-cased file name (for example `'lod-meta.json'`), or an empty * string. * @property {Asset|undefined} asset - The asset being loaded, if any. * @property {AppBase} app - The running {@link AppBase}. * @category Asset */ /** * A parser used by a {@link ResourceHandler} to recognize and load a specific resource format. A parser * implements `canParse` (to claim a resource) and `load` (to fetch and produce it), and may implement * `open`. When registered with {@link ResourceHandler#addParser} the handler assigns itself to the * parser's `handler` property, so `load` can fetch the data via `this.handler.fetch(...)`. * * @typedef {object} ResourceParser * @property {(context: ParserContext) => boolean} canParse - Returns true if this parser can handle the * described resource. Parsers are consulted newest-first; the first to return true is used. * @property {(url: (string | {load: string, original: string}), callback: ResourceHandlerCallback, asset?: Asset) => void} load - * Fetches (typically via `this.handler.fetch`) and produces the resource, then invokes the callback. * @property {(url: string, data: *, asset?: Asset) => *} [open] - Optional. Called by the default * {@link ResourceHandler#open} when parsers are registered. Handlers that override `open` may call * it with an extended signature - for example the texture handler calls * `open(url, data, device, textureOptions)` on its parsers. * @property {ResourceHandler} [handler] - Assigned by the owning handler on registration; available in * `load`/`open` (for example `this.handler.fetch(...)`). * @category Asset */ /** * A ResourceHandler loads and opens resources of one asset type on behalf of the * {@link ResourceLoader}. The engine ships a handler for every built-in {@link AssetType}, and an * application registers the ones listed in {@link AppOptions#resourceHandlers}, so a * hand-configured {@link AppBase} may support only some types. Register your own with * {@link ResourceLoader#addHandler} to add a new type. * * A handler works in two steps. {@link load} fetches the raw data for a URL and {@link open} turns * that data into the resource stored on {@link Asset#resource}. A handler may also implement * {@link patch} to resolve references to other assets once the resource exists. Rather than * overriding those methods, a handler can register one {@link ResourceParser} per file format with * {@link addParser} and let the base class pick the parser that claims the file. * * @example * class CsvHandler extends ResourceHandler { * constructor(app) { * super(app, 'csv'); * } * * load(url, callback) { * this.fetch(url, 'text', callback); * } * * open(url, data) { * return data.split('\n').map(line => line.split(',')); * } * } * app.loader.addHandler('csv', new CsvHandler(app)); * @category Asset */ declare class ResourceHandler { /** * @param {AppBase} app - The running {@link AppBase}. * @param {string} handlerType - The type of the resource the handler handles. */ constructor(app: AppBase, handlerType: string); /** * Type of the resource the handler handles. */ handlerType: string; /** * The running app instance. * * @type {AppBase} * @protected */ protected _app: AppBase; /** @private */ private _maxRetries; /** * The registered parsers, consulted newest-first during selection. * * @type {ResourceParser[]} * @ignore */ _parsers: ResourceParser[]; /** * Gets the running {@link AppBase} instance. * * @type {AppBase} */ get app(): AppBase; /** * Sets the number of times to retry a failed request for the resource. * * @type {number} */ set maxRetries(value: number); /** * Gets the number of times to retry a failed request for the resource. * * @type {number} */ get maxRetries(): number; /** * Registers a {@link ResourceParser} for this handler. Parsers are consulted newest-first: the most * recently added parser whose {@link ResourceParser#canParse} returns true is selected. This lets a * later registration override a built-in parser for the same format. * * Register parsers before starting loads for this handler's type - selection runs for both the * load and open phases, so changing the registry while loads are in flight can route them * inconsistently. Note that handlers that implement their own loading without consulting * registered parsers (for example cubemap or font) ignore registered parsers. * * @param {ResourceParser} parser - The parser to register. Must implement `canParse(context)`. * @param {*} [decider] - Removed. Previously a `(url, data) => boolean` selector; implement * `canParse(context)` on the parser instead. If passed, it is ignored and logs a warning. * @example * app.loader.getHandler('model').addParser(new ObjModelParser(app.graphicsDevice)); */ addParser(parser: ResourceParser, decider?: any): void; /** * Removes a previously registered {@link ResourceParser}. * * @param {ResourceParser} parser - The parser to remove. */ removeParser(parser: ResourceParser): void; /** * Gets a read-only copy of the registered parsers. * * @type {ResourceParser[]} */ get parsers(): ResourceParser[]; /** * Fetches a resource's raw data using this handler's retry settings, reusing pre-fetched * `asset.file.contents` when available. A convenience for a {@link ResourceParser}'s `load` method, * so parsers don't reimplement the fetch boilerplate. * * @param {string | {load: string, original: string}} url - The resource URL, or a load/original * structure. * @param {string} responseType - The {@link Http} response type to fetch as (for example * `Http.ResponseType.ARRAY_BUFFER` for a binary format, or `Http.ResponseType.TEXT`). * @param {ResourceHandlerCallback} callback - Called with `(err, data)` when the fetch completes. * @param {Asset} [asset] - The asset being loaded, used to reuse already-fetched contents. */ fetch(url: string | { load: string; original: string; }, responseType: string, callback: ResourceHandlerCallback, asset?: Asset): void; /** * Builds the {@link ParserContext} used for parser selection. * * @param {string | {load: string, original: string} | null} url - The URL, a load/original * structure, or null. * @param {Asset} [asset] - The asset being loaded, if any. * @returns {ParserContext} The parser context. * @ignore */ _makeContext(url: string | { load: string; original: string; } | null, asset?: Asset): ParserContext; /** * Selects a parser for the given context, consulting registered parsers newest-first. * * @param {ParserContext} context - The context built by {@link ResourceHandler#_makeContext}. * @returns {ResourceParser|null} The first parser whose `canParse` returns true, or null. * @ignore */ _selectParser(context: ParserContext): ResourceParser | null; /** * Load a resource from a remote URL. When parsers are registered, the matching parser's `load` is * used; otherwise the base implementation does nothing (subclasses may override). * * @param {string | {load: string, original: string}} url - Either the URL of the resource to * load or a structure containing the load URL (used for loading the resource) and the original * URL (used for identifying the resource format; necessary when loading, for example, from * a blob URL). * @param {ResourceHandlerCallback} callback - The callback used when the resource is loaded or * an error occurs. * @param {Asset} [asset] - Optional asset that is passed by ResourceLoader. */ load(url: string | { load: string; original: string; }, callback: ResourceHandlerCallback, asset?: Asset): void; /** * The open function is passed the raw resource data. The handler can then process the data * into a format that can be used at runtime. When parsers are registered, the matching parser's * `open` is used (if it implements one); otherwise the base implementation simply returns the data. * * @param {string} url - The URL of the resource to open. * @param {*} data - The raw resource data passed by callback from {@link load}. * @param {Asset} [asset] - Optional asset that is passed by ResourceLoader. * @returns {*} The parsed resource data. */ open(url: string, data: any, asset?: Asset): any; /** * The patch function performs any operations on a resource that requires a dependency on its * asset data or any other asset data. The base implementation does nothing. * * @param {Asset} asset - The asset to patch. * @param {AssetRegistry} assets - The asset registry. */ patch(asset: Asset, assets: AssetRegistry): void; } type DataType = Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array; type PlyProperty = { /** * - E.g. 'float'. */ type: string; /** * - E.g. 'x', 'y', 'z', 'f_dc_0' etc. */ name: string; /** * - Data type, e.g. instance of Float32Array. */ storage: DataType; /** * - BYTES_PER_ELEMENT of given data type. */ byteSize: number; }; type PlyElement = { /** * - E.g. 'vertex'. */ name: string; /** * - Given count. */ count: number; /** * - The properties. */ properties: PlyProperty[]; }; declare class GSplatData { /** * @param {BoundingBox} result - Bounding box instance holding calculated result. * @param {Vec3} p - The splat position * @param {Quat} r - The splat rotation * @param {Vec3} s - The splat scale */ static calcSplatAabb(result: BoundingBox, p: Vec3, r: Quat, s: Vec3): void; /** * @param {PlyElement[]} elements - The elements. * @param {string[]} comments - File header comments. */ constructor(elements: PlyElement[], comments?: string[]); /** @type {PlyElement[]} */ elements: PlyElement[]; numSplats: number; /** * File header comments. * * @type { string[] } */ comments: string[]; /** * True when the splat data stores activated values: linear scale and post-sigmoid opacity * (e.g. data sourced from the glTF KHR_gaussian_splatting extension). False when the data * uses PLY conventions: log-space scale and pre-sigmoid opacity. * * @type {boolean} */ activated: boolean; getProp(name: any, elementName?: string): DataType; getElement(name: any): PlyElement; addProp(name: any, storage: any): void; /** * Create an iterator for accessing splat data * * @param {Vec3|null} [p] - the vector to receive splat position * @param {Quat|null} [r] - the quaternion to receive splat rotation * @param {Vec3|null} [s] - the vector to receive splat scale * @param {Vec4|null} [c] - the vector to receive splat color * @returns {SplatIterator} - The iterator */ createIter(p?: Vec3 | null, r?: Quat | null, s?: Vec3 | null, c?: Vec4 | null): SplatIterator; /** * Calculate pessimistic scene aabb taking into account splat size. This is faster than * calculating an exact aabb. * * @param {BoundingBox} result - Where to store the resulting bounding box. * @param {(i: number) => boolean} [pred] - Optional predicate function to filter splats. * @returns {boolean} - Whether the calculation was successful. */ calcAabb(result: BoundingBox, pred?: (i: number) => boolean): boolean; /** * Calculate exact scene aabb taking into account splat size * * @param {BoundingBox} result - Where to store the resulting bounding box. * @param {(i: number) => boolean} [pred] - Optional predicate function to filter splats. * @returns {boolean} - Whether the calculation was successful. */ calcAabbExact(result: BoundingBox, pred?: (i: number) => boolean): boolean; /** * Returns a new Float32Array of centers (x, y, z per splat). * @returns {Float32Array} Centers buffer */ getCenters(): Float32Array; /** * @param {Vec3} result - The result. * @param {Function} [pred] - Predicate given index for skipping. */ calcFocalPoint(result: Vec3, pred?: Function): void; /** * @param {Scene} scene - The application's scene. * @param {Mat4} worldMat - The world matrix. */ renderWireframeBounds(scene: Scene, worldMat: Mat4): void; get isCompressed(): boolean; get shBands(): any; calcMortonOrder(): Uint32Array; reorder(order: any): void; reorderData(): void; } declare class SplatIterator { constructor(gsplatData: any, p: any, r: any, s: any, c: any); read: (i: any) => void; } declare class GSplatCompressedData { numSplats: any; /** * File header comments. * * @type { string[] } */ comments: string[]; /** * Contains either 12 or 18 floats per chunk: * min_x, min_y, min_z, * max_x, max_y, max_z, * min_scale_x, min_scale_y, min_scale_z, * max_scale_x, max_scale_y, max_scale_z * min_r, min_g, min_b, * max_r, max_g, max_b * @type {Float32Array} */ chunkData: Float32Array; /** * Contains 4 uint32 per vertex: * packed_position * packed_rotation * packed_scale * packed_color * @type {Uint32Array} */ vertexData: Uint32Array; /** * Contains optional quantized spherical harmonic data. * @type {Uint8Array} */ shData0: Uint8Array; /** * Contains optional quantized spherical harmonic data. * @type {Uint8Array} */ shData1: Uint8Array; /** * Contains optional quantized spherical harmonic data. * @type {Uint8Array} */ shData2: Uint8Array; /** * Contains the number of bands of spherical harmonics data. * @type {number} */ shBands: number; /** * Create an iterator for accessing splat data * * @param {Vec3|null} [p] - the vector to receive splat position * @param {Quat|null} [r] - the quaternion to receive splat rotation * @param {Vec3|null} [s] - the vector to receive splat scale * @param {Vec4|null} [c] - the vector to receive splat color * @param {Float32Array|null} [sh] - the array to receive spherical harmonics data * @returns {SplatCompressedIterator} - The iterator */ createIter(p?: Vec3 | null, r?: Quat | null, s?: Vec3 | null, c?: Vec4 | null, sh?: Float32Array | null): SplatCompressedIterator; /** * Calculate pessimistic scene aabb taking into account splat size. This is faster than * calculating an exact aabb. * * @param {BoundingBox} result - Where to store the resulting bounding box. * @returns {boolean} - Whether the calculation was successful. */ calcAabb(result: BoundingBox): boolean; /** * Returns a new Float32Array of centers (x, y, z per splat). * @returns {Float32Array} Centers buffer */ getCenters(): Float32Array; getChunks(result: any): void; /** * @param {Vec3} result - The result. */ calcFocalPoint(result: Vec3): void; get isCompressed(): boolean; get numChunks(): number; get chunkSize(): number; decompress(): GSplatData; } declare class SplatCompressedIterator { constructor(gsplatData: any, p: any, r: any, s: any, c: any, sh: any); read: (i: any) => void; } declare class GSplatSogData { static calcBands(centroidsWidth: any): any; meta: any; numSplats: any; means_l: any; means_u: any; quats: any; scales: any; sh0: any; sh_centroids: any; sh_labels: any; /** * V2-only codebook LUT (256x1 RGBA32F): .r = scales, .g = sh0, .b = shN, .a unused. * Built from meta codebooks in prepareCodebook(). Null for V1 assets. * * @type {Texture|null} */ codebookTexture: Texture | null; /** * URL of the asset, used for debugging texture names. */ url: string; /** * Cached centers array (x, y, z per splat), length = numSplats * 3. * * @type {Float32Array | null} * @private */ private _centers; /** * Recovery waits that must also finish if this data is destroyed before the device recovers. * * @type {Set<() => void> | null} * @private */ private _pendingRestoreWaits; destroyed: boolean; /** * Number of spherical harmonics bands. */ shBands: number; _destroyGpuResources(): void; destroy(): void; createIter(p: any, r: any, s: any, c: any, sh: any): GSplatSogIterator; calcAabb(result: any): void; getCenters(): Float32Array; calcFocalPoint(result: any, pred: any): void; get isSog(): boolean; decompress(): Promise; generateCenters(): Promise; /** * Creates the V2 codebook LUT texture. Packs the three 256-entry scalar codebooks * (scales, sh0, shN) into a single 256x1 RGBA32F texture: * - .r = scales codebook * - .g = sh0 codebook * - .b = shN codebook * - .a = 0 (unused) * * @private */ private _createCodebookTexture; /** * Patches any null-leading codebook entries in place. A null `codebook[0]` was a bug in * older SOG creation tools (since fixed); this workaround keeps already-published assets * in the wild renderable by synthesizing a plausible value so downstream sampling never * produces NaN. Required for both GPU rendering and CPU decompression flows. * * @private */ private _patchCodebooks; /** * Synchronous codebook preparation. Patches any null-leading codebook entries and, for V2 * assets, builds the codebook LUT texture. Must be called before {@link prepareGpuData}. */ prepareCodebook(): void; prepareGpuData(): any; } declare class GSplatSogIterator { constructor(data: any, p: any, r: any, s: any, c: any, sh: any); read: (i: any) => void; } type GSplatStreamDescriptor = { /** * - The name of the stream (used as texture uniform name). */ name: string; /** * - The pixel format of the texture (e.g. PIXELFORMAT_RGBA32F). * When used as an extra stream for work buffers or as a destination stream for * GSplatProcessor, the format must be renderable as these textures are used as render * targets. Ensure the format is renderable on all target devices. See {@link Texture} for * details on renderable formats and device capabilities. */ format: number; /** * - Storage type: GSPLAT_STREAM_RESOURCE (default, shared across * instances) or GSPLAT_STREAM_INSTANCE (per-component instance). Note: Work buffer formats * (accessed via `app.scene.gsplat.format`) do not support GSPLAT_STREAM_INSTANCE. */ storage?: number; }; /** * Gsplat resources store per-splat data (positions, colors, rotations, scales, spherical * harmonics) in GPU textures. This class describes those texture streams and generates the * shader code needed to access them. * * Each stream defines a texture with a name and pixel format. The class automatically generates * shader declarations (uniforms/samplers) and load functions (e.g. `loadColor()`) for each * stream. A read shader can be provided to define how splat attributes are extracted from * these textures. * * Users can add extra streams via {@link addExtraStreams} for custom per-splat data. These * can be per-resource (shared across instances) or per-instance (unique to each gsplat * component). * * For loaded gsplat resources, base streams are automatically configured based on the loaded * data format. For {@link GSplatContainer}, users define both base and extra streams to * specify the complete data layout. * * @category Graphics */ declare class GSplatFormat { /** * Creates a default format using 32F/16F textures, simple to use for CPU data population. * This format can be rendered to by {@link GSplatProcessor} when supported. Check * {@link GraphicsDevice#textureFloatRenderable} (for RGBA32F) and * {@link GraphicsDevice#textureHalfFloatRenderable} (for RGBA16F). * * The format stores: * - `dataColor` (RGBA16F): color.rgba as half floats * - `dataCenter` (RGBA32F): center.xyz as floats (w unused) * - `dataScale` (RGBA16F): scale.xyz as half floats (w unused) * - `dataRotation` (RGBA16F): rotation.xyzw as half floats (w stored directly, not derived) * * @param {GraphicsDevice} device - The graphics device. * @returns {GSplatFormat} The default format. */ static createDefaultFormat(device: GraphicsDevice): GSplatFormat; /** * Creates a simple format with uniform-scale splats and no rotation. * Streams: * - `dataCenter` (RGBA32F): center.xyz + uniform size in w * - `dataColor` (RGBA16F): color.rgba as half floats * * @param {GraphicsDevice} device - The graphics device. * @returns {GSplatFormat} The simple format. */ static createSimpleFormat(device: GraphicsDevice): GSplatFormat; /** * Creates a new GSplatFormat instance. * * @param {GraphicsDevice} device - The graphics device. * @param {GSplatStreamDescriptor[]} streams - Array of stream descriptors. * @param {object} options - Format options. * @param {string} [options.readGLSL] - GLSL code defining getCenter(), getColor(), * getRotation(), getScale() functions. Can include additional declarations at module scope. * Required for WebGL. * @param {string} [options.readWGSL] - WGSL code defining getCenter(), getColor(), * getRotation(), getScale() functions. Can include additional declarations at module scope. * Required for WebGPU. */ constructor(device: GraphicsDevice, streams: GSplatStreamDescriptor[], options: { readGLSL?: string; readWGSL?: string; }); /** * @type {GraphicsDevice} * @private */ private _device; /** * Array of stream descriptors. * * @type {GSplatStreamDescriptor[]} * @readonly */ readonly streams: GSplatStreamDescriptor[]; /** * User-provided code for reading splat data (GLSL or WGSL based on device). * Must define getCenter(), getColor(), getRotation(), getScale() functions. * * @type {string} * @private */ private _read; /** * When true, allows extra streams to be removed via {@link removeExtraStreams}. * Only work buffer formats (returned by {@link GSplatParams#format}) should set this. * * @ignore */ allowStreamRemoval: boolean; /** * Work buffer data layout identifier (one of GSPLATDATA_*), or null for resource formats. * Set by {@link GSplatParams} when creating a work buffer format. Identifies how transform * data is encoded, so consumers (e.g. the work-buffer-sourced spherical harmonics update) * can select the matching decode without inspecting individual stream pixel formats. * * @type {string|null} * @ignore */ dataFormat: string | null; /** * Extra streams added via addExtraStreams(). For resource formats, streams can only be * added, never removed. For work buffer formats (where {@link allowStreamRemoval} is true), * streams can also be removed via {@link removeExtraStreams}. * * @type {GSplatStreamDescriptor[]} * @private */ private _extraStreams; /** * Set of all stream names (base + extra) for fast duplicate checking. * * @type {Set} * @private */ private _streamNames; /** * Change token, refreshed from the shared counter when extra streams change. Never repeats * a value used by any other format instance. * * @private */ private _extraStreamsVersion; /** * Cached hash value. * * @type {number|undefined} * @private */ private _hash; /** * Cached resource streams array. * * @type {GSplatStreamDescriptor[]|null} * @private */ private _resourceStreams; /** * Cached instance streams array. * * @type {GSplatStreamDescriptor[]|null} * @private */ private _instanceStreams; /** * Returns a hash of this format's configuration. Used for shader caching. * Computed from raw inputs to avoid generating shader code just for the hash. * * @type {number} * @ignore */ get hash(): number; /** * Returns an opaque change token that changes when extra streams change. Values are unique * across format instances, so comparing it against a cached copy also detects a wholesale * format swap (e.g. {@link GSplatParams#dataFormat}) and not just in-place stream edits. * * @type {number} * @ignore */ get extraStreamsVersion(): number; /** * Gets the extra streams array. Streams can only be added via {@link addExtraStreams}, * not removed. Do not modify the returned array directly. * * @type {GSplatStreamDescriptor[]} */ get extraStreams(): GSplatStreamDescriptor[]; /** * Returns all resource-level streams (base streams + extra streams where instance !== true). * Used by GSplatStreams for resource texture management. * * @type {GSplatStreamDescriptor[]} * @ignore */ get resourceStreams(): GSplatStreamDescriptor[]; /** * Returns all instance-level streams (extra streams with GSPLAT_STREAM_INSTANCE storage). * Used by GSplatStreams for per-component-instance texture management. * * @type {GSplatStreamDescriptor[]} * @ignore */ get instanceStreams(): GSplatStreamDescriptor[]; /** * Adds additional texture streams for custom gsplat data. Each stream defines a texture * that can store extra information, accessible in shaders via generated load functions. * Streams with `storage: GSPLAT_STREAM_INSTANCE` are created per gsplat component instance, * while others are shared across all instances of the same resource. * * Note: Streams cannot be removed once added currently. * * @param {GSplatStreamDescriptor[]} streams - Array of stream descriptors to add. */ addExtraStreams(streams: GSplatStreamDescriptor[]): void; /** * Removes extra streams by name. Only supported on work buffer formats * (returned by {@link GSplatParams#format}). Removing streams from resource * formats is not supported. * * @param {string[]} names - Array of stream names to remove. * @ignore */ removeExtraStreams(names: string[]): void; /** * Generates input declarations (texture uniforms + load functions). * * @param {string[]} [streamNames] - Optional array of stream names to filter. If not provided, * generates declarations for all streams. * @returns {string} Shader code for declarations. * @ignore */ getInputDeclarations(streamNames?: string[]): string; /** * Returns the read code. * * @returns {string} Shader code for reading splat data. * @ignore */ getReadCode(): string; /** * Generates compute shader input declarations with explicit binding annotations. * Format texture bindings are placed at indices starting from startBinding. * * @param {number} startBinding - The first @group(0) @binding() index for format textures. * @param {string[]} [streamNames] - Optional array of stream names to filter. * @returns {string} WGSL code for compute shader declarations. * @ignore */ getComputeInputDeclarations(startBinding: number, streamNames?: string[]): string; /** * Returns an array of BindTextureFormat entries for the format's streams, suitable for * appending to a compute shader's BindGroupFormat. Sample types are derived from pixel formats. * * @param {string[]} [streamNames] - Optional array of stream names to filter. * @returns {BindTextureFormat[]} Array of bind texture format entries. * @ignore */ getComputeBindFormats(streamNames?: string[]): BindTextureFormat[]; /** * Sets the write code for encoding splat data into the work buffer. The appropriate code * for the current backend (GLSL or WGSL) is stored. * * @param {string} writeGLSL - GLSL code for writing/encoding splat data. * @param {string} writeWGSL - WGSL code for writing/encoding splat data. * @ignore */ setWriteCode(writeGLSL: string, writeWGSL: string): void; _write: string; /** * Returns the write code for encoding splat data into the work buffer. * * @returns {string|undefined} Shader code for writing splat data, or undefined if not set. * @ignore */ getWriteCode(): string | undefined; /** * Generates output declarations (write functions) for MRT output streams. * Used by GSplatProcessor to generate output functions for dstStreams. * Each stream maps to an MRT slot (pcFragColor0, pcFragColor1, etc. in GLSL or * processOutput.color, processOutput.color1, etc. in WGSL). * * @param {GSplatStreamDescriptor[]} outputStreams - Stream descriptors for output. * @returns {string} Shader code for output write functions. * @ignore */ getOutputDeclarations(outputStreams: GSplatStreamDescriptor[]): string; /** * Generates no-op stub functions for streams that aren't render targets. * Used in color-only mode so user modifier code compiles but writes are ignored. * * @param {GSplatStreamDescriptor[]} streams - Stream descriptors to generate stubs for. * @returns {string} Shader code for no-op write functions. * @ignore */ getOutputStubs(streams: GSplatStreamDescriptor[]): string; /** * Returns a stream descriptor by name. * * @param {string} name - The name of the stream to find. * @returns {GSplatStreamDescriptor|undefined} The stream descriptor, or undefined if not found. * @ignore */ getStream(name: string): GSplatStreamDescriptor | undefined; /** * Invalidates all cached values when streams change. * * @private */ private _invalidateCaches; } /** * @import { GraphicsDevice } from '../../platform/graphics/graphics-device.js' * @import { GSplatFormat } from './gsplat-format.js' */ /** * Manages textures for a GSplatFormat, creating them from stream definitions. * * @ignore */ declare class GSplatStreams { /** * Creates a new GSplatStreams instance. * * @param {GraphicsDevice} device - The graphics device. * @param {boolean} [isInstance] - Whether this manages instance-level textures (true) or * resource-level textures (false). Defaults to false. */ constructor(device: GraphicsDevice, isInstance?: boolean); /** * The graphics device. * * @type {GraphicsDevice} */ device: GraphicsDevice; /** * The format defining the streams. * * @type {GSplatFormat|null} */ format: GSplatFormat | null; /** * Map of texture names to Texture instances. * * @type {Map} */ textures: Map; /** * Texture dimensions (width and height). * * @private */ private _textureDimensions; /** * Whether this manages instance-level textures (true) or resource-level textures (false). * * @private */ private _isInstance; /** * The format version at last sync. * * @private */ private _formatVersion; /** * Gets the texture dimensions (width and height). * * @type {Vec2} */ get textureDimensions(): Vec2; /** * Destroys all managed textures. */ destroy(): void; /** * Initialize with format and create textures for all streams. * * @param {GSplatFormat} format - The format defining streams. * @param {number} numElements - Number of elements (splats) to size textures for. */ init(format: GSplatFormat, numElements: number): void; /** * Gets a texture by name. * * @param {string} name - Texture name. * @returns {Texture|undefined} The texture, or undefined if not found. */ getTexture(name: string): Texture | undefined; /** * Gets all textures in format order (streams followed by extraStreams). * * @returns {Texture[]} Array of textures in format order. * @ignore */ getTexturesInOrder(): Texture[]; /** * Synchronizes textures with the format's stream definitions. * Creates new textures for added streams. Textures are never destroyed here - * streams can only be added, not removed (see GSplatFormat._extraStreams for rationale). * * @param {GSplatFormat|null} format - The format to sync with, or null to skip. * @ignore */ syncWithFormat(format: GSplatFormat | null): void; /** * Resizes all managed textures to the specified dimensions. This assumes all textures * have uniform dimensions (e.g. work buffer textures). Do not use on resources with * mixed-size textures (e.g. SOG with differently-sized SH textures). * * @param {number} width - The new width. * @param {number} height - The new height. */ resize(width: number, height: number): void; /** * Creates a new texture with the specified parameters. * * @param {string} name - The name of the texture to be created. * @param {number} format - The pixel format of the texture. * @param {Vec2} size - The size of the texture in a Vec2 object, containing width (x) and height (y). * @param {Uint8Array|Uint16Array|Uint32Array|Float32Array} [data] - The initial data to fill the texture with. * @returns {Texture} The created texture instance. */ createTexture(name: string, format: number, size: Vec2, data?: Uint8Array | Uint16Array | Uint32Array | Float32Array): Texture; } /** * @import { GraphicsDevice } from './graphics-device.js' * @import { StorageBuffer } from './storage-buffer.js' * @import { Texture } from './texture.js' * @import { EventHandle } from '../../core/event-handle.js' */ /** * Manages non-blocking uploads of data to GPU resources (textures or storage buffers). * Internally pools staging resources (PBOs on WebGL, staging buffers on WebGPU) to avoid blocking * when the GPU is busy with previous uploads. * * Important: Create one UploadStream per target resource. * * @category Graphics * @ignore */ declare class UploadStream { /** * Create a new UploadStream instance. * * @param {GraphicsDevice} device - The graphics device. * @param {boolean} [useSingleBuffer] - If true, uses simple direct uploads (single texture on * WebGL, direct write on WebGPU). If false (default), uses optimized multi-buffer strategy (PBOs * with orphaning on WebGL, staging buffers on WebGPU) for potentially non-blocking uploads. */ constructor(device: GraphicsDevice, useSingleBuffer?: boolean); /** * Event handle for device lost event. * * @type {EventHandle|null} * @protected */ protected _deviceLostEvent: EventHandle | null; device: GraphicsDevice; useSingleBuffer: boolean; impl: any; /** * Destroy the upload stream and clean up all pooled resources. */ destroy(): void; /** * Upload data to a texture (WebGL path) or storage buffer (WebGPU path). * For WebGL textures, both offset and size must be multiples of the texture width (aligned to * full rows). * For WebGPU storage buffers, both offset and size byte values must be multiples of 4. * * @param {Uint8Array|Uint32Array|Float32Array} data - The data to upload. Must contain at least * `size` elements. * @param {Texture|StorageBuffer} target - The target resource (texture for WebGL, storage * buffer for WebGPU). * @param {number} [offset] - The element offset in the target where upload starts. Defaults to 0. * For WebGL textures, must be a multiple of texture width. For WebGPU, the byte offset must be * a multiple of 4. * @param {number} [size] - The number of elements to upload. Defaults to data.length. * For WebGL textures, must be a multiple of texture width. For WebGPU, the byte size must be * a multiple of 4. */ upload(data: Uint8Array | Uint32Array | Float32Array, target: Texture | StorageBuffer, offset?: number, size?: number): void; /** * Handles device lost event. Override in platform implementations. * * @private */ private _onDeviceLost; } /** * - Defines the vertex and fragment shader source for * {@link ShaderMaterial}, supporting both GLSL and WGSL formats. WebGL always uses the GLSL code. * WebGPU prefers the WGSL code if available, otherwise it automatically transpiles the provided * GLSL code at runtime. */ type ShaderDesc = { /** * - Unique name for the shader. If a shader with this name already * exists, it will be returned instead of a new shader instance. */ uniqueName: string; /** * - The vertex shader code in GLSL. */ vertexGLSL?: string; /** * - The fragment shader code in GLSL. */ fragmentGLSL?: string; /** * - The vertex shader code in WGSL. */ vertexWGSL?: string; /** * - The fragment shader code in WGSL. */ fragmentWGSL?: string; /** * - Object detailing the mapping of vertex shader * attribute names to semantics SEMANTIC_*. This enables the engine to match vertex buffer data as * inputs to the shader. Defaults to undefined, which generates the default attributes. */ attributes?: { [x: string]: string; }; /** * - Fragment shader output types, which default to * vec4. Passing a string will set the output type for all color attachments. Passing an array will * set the output type for each color attachment. */ fragmentOutputTypes?: string | string[]; }; /** * @typedef {object} ShaderDesc - Defines the vertex and fragment shader source for * {@link ShaderMaterial}, supporting both GLSL and WGSL formats. WebGL always uses the GLSL code. * WebGPU prefers the WGSL code if available, otherwise it automatically transpiles the provided * GLSL code at runtime. * @property {string} uniqueName - Unique name for the shader. If a shader with this name already * exists, it will be returned instead of a new shader instance. * @property {string} [vertexGLSL] - The vertex shader code in GLSL. * @property {string} [fragmentGLSL] - The fragment shader code in GLSL. * @property {string} [vertexWGSL] - The vertex shader code in WGSL. * @property {string} [fragmentWGSL] - The fragment shader code in WGSL. * @property {Object} [attributes] - Object detailing the mapping of vertex shader * attribute names to semantics SEMANTIC_*. This enables the engine to match vertex buffer data as * inputs to the shader. Defaults to undefined, which generates the default attributes. * @property {string | string[]} [fragmentOutputTypes] - Fragment shader output types, which default to * vec4. Passing a string will set the output type for all color attachments. Passing an array will * set the output type for each color attachment. @see ShaderDefinitionUtils.createDefinition */ /** * A ShaderMaterial is a type of material that utilizes a specified shader for rendering purposes. * * Use it when a surface cannot be expressed with {@link StandardMaterial} properties or shader * chunk overrides. The shader is described by a {@link ShaderDesc}: a `uniqueName`, vertex and * fragment source in GLSL for WebGL, in WGSL for WebGPU, or both, and an `attributes` map from * shader inputs to `SEMANTIC_*` values so the engine can bind vertex data. Provide both languages * when the application must run on both backends. The engine supplies the standard uniforms a * shader declares by name, such as `matrix_viewProjection`; your own uniforms are set with * {@link Material#setParameter}. Render state such as {@link Material#blendType}, * {@link Material#cull} and {@link Material#depthWrite} comes from {@link Material}. Lighting, fog * and shadows are not generated for you; the shader draws exactly what it is written to draw. * * A simple example which creates a material with custom vertex and fragment shaders specified in * GLSL format: * * ```javascript * const material = new ShaderMaterial({ * uniqueName: 'MyShader', * attributes: { aPosition: SEMANTIC_POSITION }, * vertexGLSL: ` * attribute vec3 aPosition; * uniform mat4 matrix_viewProjection; * void main(void) * { * gl_Position = matrix_viewProjection * pos; * }`, * fragmentGLSL: ` * void main(void) { * gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0); * }` * }); * ``` * * @category Graphics */ declare class ShaderMaterial extends Material { /** * Create a new ShaderMaterial instance. * * @param {ShaderDesc} [shaderDesc] - The description of the shader to be used by the material. */ constructor(shaderDesc?: ShaderDesc); /** * @type {ShaderDesc|undefined} * @private */ private _shaderDesc; /** * Sets the shader description. * * @type {ShaderDesc|undefined} */ set shaderDesc(value: ShaderDesc | undefined); /** * Gets the shader description. * * @type {ShaderDesc|undefined} */ get shaderDesc(): ShaderDesc | undefined; /** * Copy a `ShaderMaterial`. * * @param {ShaderMaterial} source - The material to copy from. * @returns {ShaderMaterial} The destination material. */ copy(source: ShaderMaterial): ShaderMaterial; /** @ignore */ getShaderVariant(params: any): Shader; } type GSplatVaryingDescriptor = { /** * - The varying name. Must be a valid shader identifier. */ name: string; /** * - The component data type: {@link TYPE_FLOAT32}, {@link TYPE_INT32} or * {@link TYPE_UINT32}. */ type: number; /** * - The number of components, 1 to 4. */ components: number; }; /** * Manages custom varying streams for the gsplat render customization. Streams added here generate * set functions available to the `gsplatModifyVS` shader chunk, where they run once per splat, * and matching get functions available to the `gsplatModifyPS` shader chunk, where the per-splat * value can be read for each rendered fragment. * * Access the instance via {@link GSplatParams#varyings}. * * @category Graphics */ declare class GSplatVaryings { /** * Creates a new GSplatVaryings instance. * * @param {GraphicsDevice} device - The graphics device. * @ignore */ constructor(device: GraphicsDevice); /** * @type {GraphicsDevice} * @private */ private _device; /** * @type {GSplatVaryingDescriptor[]} * @private */ private _streams; /** * @type {number} * @private */ private _words; /** * @type {number} * @private */ private _version; /** * Gets the varying stream descriptors. Do not modify the returned array. * * @type {GSplatVaryingDescriptor[]} */ get streams(): GSplatVaryingDescriptor[]; /** * The number of u32 words the varying streams add to the per-splat projection cache of the * {@link GSPLAT_RENDERER_RASTER_GPU_SORT} renderer. * * @type {number} * @ignore */ get words(): number; /** * The version of the varying streams, incremented on every change. * * @type {number} * @ignore */ get version(): number; /** * Adds varying streams. For each stream, a set function (`set`) is generated and made * available to the `gsplatModifyVS` shader chunk, where it runs once per splat, and a * matching get function (`get`) is made available to the `gsplatModifyPS` shader * chunk, where the per-splat value can be read for each rendered fragment. * * Supported types are {@link TYPE_FLOAT32}, {@link TYPE_INT32} and {@link TYPE_UINT32}, with * 1 to 4 components. Adding or removing streams rebuilds the gsplat shaders. * * Note: on some platforms each component is stored in per-splat video memory, so its size * scales with the number of rendered splats. Keep the data as compact as possible - prefer * fewer components, and consider bit-packing multiple small values into a single uint * component instead of using separate streams. * * @param {GSplatVaryingDescriptor[]} streams - The streams to add. * @example * // Add a per-splat flag, written once per splat in gsplatModifyVS using setFlag(value), * // and read per fragment in gsplatModifyPS using getFlag() * app.scene.gsplat.varyings.add([{ * name: 'flag', * type: TYPE_UINT32, * components: 1 * }]); */ add(streams: GSplatVaryingDescriptor[]): void; /** * Removes varying streams previously added by {@link GSplatVaryings#add}. * * @param {string[]} names - The names of the streams to remove. */ remove(names: string[]): void; /** * Marks the streams as changed: recomputes the cache word count eagerly (so consumers never * see a stale value) and bumps the version. The shader chunks are regenerated and applied to * the material once per frame by the engine via {@link GSplatVaryings#apply}. * * @private */ private _changed; /** * Generates the shader chunks implementing the varying streams: declarations and set * functions for the vertex stage (and its compute projector equivalent), declarations and * get functions for the fragment stage, and the projection cache read / write code used by * the hybrid renderer. * * @returns {object} The generated chunk sources. * @private */ private _generateChunks; /** * Regenerates the shader chunks and applies them to the material, from where the renderers * pick them up (and rebuild shaders) via the existing chunk synchronization. Consumers track * {@link GSplatVaryings#version} to call this only when the streams changed. * * @param {ShaderMaterial} material - The gsplat material to apply the chunks to. * @ignore */ apply(material: ShaderMaterial): void; } /** * @import { GraphicsDevice } from '../../platform/graphics/graphics-device.js' * @import { Texture } from '../../platform/graphics/texture.js' */ /** * Parameters for the GSplat system. * * @category Graphics */ declare class GSplatParams { /** * Creates a new GSplatParams instance. * * @param {GraphicsDevice} device - The graphics device. */ constructor(device: GraphicsDevice); /** * @type {ShaderMaterial} * @private */ private _material; /** * Format descriptor for work buffer streams. * * @type {GSplatFormat} * @private */ private _format; /** * @type {GraphicsDevice} * @private */ private _device; /** * @type {string} * @private */ private _dataFormat; /** * Resolved renderer in effect; computed from {@link _renderer} and the device in the * constructor and the {@link renderer} setter. * * @type {number} * @private */ private _currentRenderer; /** * @type {GSplatVaryings} * @private */ private _varyings; /** * @param {string} dataFormat - The data format constant. * @returns {GSplatFormat} The created format. * @private */ private _createFormat; /** * Enables radial sorting based on distance from camera (for cubemap rendering). When false, * uses directional sorting along camera forward vector. Defaults to false. * * Note: Radial sorting helps reduce sorting artifacts when the camera rotates (looks around), * while linear sorting is better at minimizing artifacts when the camera translates (moves). */ radialSorting: boolean; /** * Enables stochastic alpha rendering on the WebGPU GPU-sort renderer. Splats are drawn * without sorting, using dithered coverage, opaque blending and depth writes. Ignored by * the CPU-sort renderer. Picking continues to use sorted rendering. Defaults to false. * Applications can customize the sampling through the material's opacityDitherPS chunk. * * @type {boolean} */ stochastic: boolean; /** * The noise pattern the coverage of a {@link GSplatParams#stochastic} splat is dithered * against, ignored when `stochastic` is false. Can be: * * - {@link DITHER_BAYER2}: Coverage is dithered using a Bayer 2 matrix. * - {@link DITHER_BAYER4}: Coverage is dithered using a Bayer 4 matrix. * - {@link DITHER_BAYER8}: Coverage is dithered using a Bayer 8 matrix. * - {@link DITHER_BAYER16}: Coverage is dithered using a Bayer 16 matrix. * - {@link DITHER_BLUENOISE}: Coverage is dithered using a blue noise. * - {@link DITHER_IGNNOISE}: Coverage is dithered using an interleaved gradient noise. * * Defaults to {@link DITHER_BLUENOISE}, which looks best under temporal anti-aliasing. * {@link DITHER_NONE} is not a coverage pattern, so it is not accepted here - turn * `stochastic` off instead. * * @type {string} */ dither: string; /** * @type {number} * @private */ private _renderer; /** * Resolves a requested renderer mode to the concrete one used on this device. * * @param {number} value - The requested renderer mode. * @returns {number} The resolved renderer mode. * @private */ private _resolveRenderer; /** * Sets the rendering pipeline used for gaussian splatting. Can be: * * - {@link GSPLAT_RENDERER_AUTO}: Automatically selects the best pipeline for the platform. * Selects {@link GSPLAT_RENDERER_RASTER_GPU_SORT} on WebGPU and * {@link GSPLAT_RENDERER_RASTER_CPU_SORT} on WebGL. * - {@link GSPLAT_RENDERER_RASTER_CPU_SORT}: Rasterization with CPU-side sorting. * - {@link GSPLAT_RENDERER_RASTER_GPU_SORT}: Rasterization with GPU-side sorting (WebGPU only). * * Defaults to {@link GSPLAT_RENDERER_AUTO}. Modes requiring WebGPU fall back to * {@link GSPLAT_RENDERER_RASTER_CPU_SORT} on WebGL devices. The resolved mode actually used * can be queried via {@link currentRenderer}. * * @type {number} */ set renderer(value: number); /** * Gets the requested rendering pipeline for gaussian splatting. This may differ from * {@link currentRenderer} when a WebGPU mode falls back on a WebGL device. * * @type {number} */ get renderer(): number; /** * The current rendering pipeline in effect after platform-based fallback resolution. When * {@link renderer} is set to a mode requiring WebGPU on a WebGL device, this returns the * fallback mode actually being used. * * @type {number} */ get currentRenderer(): number; /** * Internal dirty flag to trigger update of gsplat managers when some params change. * * @ignore */ dirty: boolean; /** * @type {number} * @private */ private _debug; /** * Sets the debug rendering mode for Gaussian splats. Can be: * * - {@link GSPLAT_DEBUG_NONE}: Normal rendering (default). * - {@link GSPLAT_DEBUG_LOD}: Colorize splats by their selected LOD level. * - {@link GSPLAT_DEBUG_SH_UPDATE}: Random color per SH update pass to visualize update * frequency. * - {@link GSPLAT_DEBUG_AABBS}: Draw world-space AABBs for each GSplat, colorized by LOD. * - {@link GSPLAT_DEBUG_NODE_AABBS}: Draw world-space AABBs for each octree node of * streamed GSplats, colorized by the currently selected LOD. * * Only one debug mode can be active at a time. Defaults to {@link GSPLAT_DEBUG_NONE}. * * @type {number} */ set debug(value: number); /** * Gets the debug rendering mode for Gaussian splats. * * @type {number} */ get debug(): number; /** * @type {boolean} * @deprecated Use {@link debug} with {@link GSPLAT_DEBUG_LOD} instead. * @ignore */ set colorizeLod(value: boolean); /** * @type {boolean} * @deprecated Use {@link debug} with {@link GSPLAT_DEBUG_LOD} instead. * @ignore */ get colorizeLod(): boolean; /** * @type {boolean} * @deprecated Use {@link debug} with {@link GSPLAT_DEBUG_AABBS} instead. * @ignore */ set debugAabbs(value: boolean); /** * @type {boolean} * @deprecated Use {@link debug} with {@link GSPLAT_DEBUG_AABBS} instead. * @ignore */ get debugAabbs(): boolean; /** * @type {boolean} * @deprecated Use {@link debug} with {@link GSPLAT_DEBUG_NODE_AABBS} instead. * @ignore */ set debugNodeAabbs(value: boolean); /** * @type {boolean} * @deprecated Use {@link debug} with {@link GSPLAT_DEBUG_NODE_AABBS} instead. * @ignore */ get debugNodeAabbs(): boolean; /** @private */ private _enableIds; /** * Enables or disables per-component ID storage in the work buffer. When enabled, each GSplat * component gets a unique ID written to the work buffer. This ID is used by the picking * system to identify which component was picked, but is also available to custom shaders for * effects like highlighting, animation, or any per-component differentiation. * * @type {boolean} */ set enableIds(value: boolean); /** * Gets the ID storage enabled state. * * @type {boolean} */ get enableIds(): boolean; /** * Distance threshold in world units to trigger LOD updates for camera and gsplat instances. * Defaults to 1. */ lodUpdateDistance: number; /** * Angle threshold in degrees to trigger LOD updates based on camera rotation. Set to 0 to * disable rotation-based updates. Rotation only affects LOD through {@link lodBehindPenalty}, * so rotation-based updates also stop when the penalty is 1. Defaults to 90. */ lodUpdateAngle: number; /** @private */ private _lodBehindPenalty; /** * Multiplier applied to effective distance for nodes behind the camera when determining LOD. * Value 1 means no penalty; higher values drop LOD faster for nodes behind the camera. Streamed * LOD files also load in order of the same penalized distance, so higher values load the view * in front of the camera earlier. Works together with {@link lodUpdateAngle}, which * re-evaluates LOD as the camera rotates. Defaults to 1.5. * * @type {number} */ set lodBehindPenalty(value: number); /** * Gets behind-camera LOD penalty multiplier. * * @type {number} */ get lodBehindPenalty(): number; /** @private */ private _lodDistanceShrink; /** * Sets how the camera distance to each part of a streamed GSplat is judged when choosing its * level of detail. At 0, a part counts as near as soon as any of it is near, so unusually * large or sparse areas that reach towards the camera - sky, distant background, long thin * regions - can get more detail than their surroundings and show up as patches of higher * detail. Higher values judge those oversized parts closer to their middle instead, which * removes the patches and lowers memory use; parts of typical size are unaffected. Use 1 * when memory matters more than detail close up, for example on mobile - it gives the lowest * memory use. Clamped to [0, 1]. Defaults to 0.75. * * @type {number} * @ignore */ set lodDistanceShrink(value: number); /** * @type {number} * @ignore */ get lodDistanceShrink(): number; /** * @type {number} * @deprecated Set {@link GSplatComponent#lodRangeMin} on the gsplat component instead. * @ignore */ set lodRangeMin(value: number); /** * @type {number} * @deprecated Set {@link GSplatComponent#lodRangeMin} on the gsplat component instead. * @ignore */ get lodRangeMin(): number; /** * @type {number} * @deprecated Set {@link GSplatComponent#lodRangeMax} on the gsplat component instead. * @ignore */ set lodRangeMax(value: number); /** * @type {number} * @deprecated Set {@link GSplatComponent#lodRangeMax} on the gsplat component instead. * @ignore */ get lodRangeMax(): number; /** @private */ private _lodUnderfillLimit; /** * Maximum number of LOD levels allowed below the optimal level when the optimal data is not * resident in memory. The system may temporarily use a coarser LOD within this limit until the * optimal LOD is available. Defaults to 0, which disables fallback (always load optimal). * Higher values allow faster loading by using lower-quality data. * * @type {number} */ set lodUnderfillLimit(value: number); /** * Gets the maximum allowed underfill LOD range. * * @type {number} */ get lodUnderfillLimit(): number; /** @private */ private _splatBudget; /** * Number of splats across all GSplats in the scene. How it is used depends on * {@link GSplatParams#splatBudgetMode}: as a target that LOD detail is raised to fill, or as a * limit that only lowers the detail the LOD distances of each GSplat ask for. Set to 0 for no * budget at all - in target mode everything then renders at its finest level, in limit mode * the LOD distances alone decide. Defaults to 1000000. * * @type {number} */ set splatBudget(value: number); /** * Gets the number of splats across all GSplats in the scene. * * @type {number} */ get splatBudget(): number; /** @private */ private _splatBudgetMode; /** * Sets how {@link GSplatParams#splatBudget} is used for streamed GSplats. Can be: * * - {@link GSPLAT_BUDGET_TARGET}: detail is raised until the budget is used up, wherever the * camera is. The LOD distances of each GSplat only shape how detail falls off with distance * and how it divides between GSplats. * - {@link GSPLAT_BUDGET_LIMIT}: the LOD distances of each GSplat decide the detail, and the * budget only lowers it when they would exceed it. A distant GSplat uses only the few splats * its distance calls for. * * Defaults to {@link GSPLAT_BUDGET_TARGET}. * * @type {string} */ set splatBudgetMode(value: string); /** * Gets how the splat budget is used. * * @type {string} */ get splatBudgetMode(): string; /** * @type {string} * @deprecated LOD levels are always chosen by distance. * @ignore */ set lodMode(value: string); /** * @type {string} * @deprecated LOD levels are always chosen by distance. * @ignore */ get lodMode(): string; /** * @type {import('../../platform/graphics/texture.js').Texture|null} * @private */ private _colorRamp; /** * Gradient texture for elevation-based coloring in overdraw visualization mode. * When set, enables overdraw mode with additive blending. When null, uses normal rendering. * Texture should be (width x 1) size. World Y coordinate (0-20 range) maps to texture U coordinate. * Defaults to null. * * @type {Texture|null} */ set colorRamp(value: Texture | null); /** * Gets the color ramp texture for overdraw visualization. * * @type {import('../../platform/graphics/texture.js').Texture|null} */ get colorRamp(): Texture | null; /** * Intensity multiplier for overdraw visualization mode. Value of 1 uses alpha of 1/32, * allowing approximately 32 overdraws to reach full brightness with additive blending. * Higher values increase brightness per splat. Defaults to 1. */ colorRampIntensity: number; /** * Whether to apply scene fog to Gaussian splats. When false, splats ignore fog settings * even if the scene or camera has fog configured. Defaults to true. */ useFog: boolean; /** * Whether to apply the camera's tonemapping and the scene exposure to Gaussian splats. When * false, splats render with their stored colors, unaffected by {@link Scene#exposure} and the * camera's {@link CameraComponent#toneMapping}. Fog, when enabled, still applies. Defaults to * true. */ useTonemap: boolean; /** @deprecated Use {@link debug} with {@link GSPLAT_DEBUG_SH_UPDATE} instead. */ set colorizeColorUpdate(value: boolean); /** * @deprecated Use {@link debug} with {@link GSPLAT_DEBUG_SH_UPDATE} instead. * @returns {boolean} Whether SH update colorization is enabled. */ get colorizeColorUpdate(): boolean; /** * Viewing angle threshold in degrees for triggering spherical harmonics color updates. * When the camera translates enough to change the viewing angle to an octree node or * splat by this amount, its SH colors are re-evaluated. Distant nodes naturally update * less frequently since they require more camera movement to reach the angle threshold. * An orthographic camera views all splats along its forward direction, so their colors are * re-evaluated together once the camera rotates by this amount, and moving it has no effect. * Set to 0 to update every frame where camera moves. Defaults to 10. */ colorUpdateAngle: number; /** @ignore */ set colorUpdateDistance(value: number); /** @ignore */ get colorUpdateDistance(): number; /** @ignore */ set colorUpdateDistanceLodScale(value: number); /** @ignore */ get colorUpdateDistanceLodScale(): number; /** @ignore */ set colorUpdateAngleLodScale(value: number); /** @ignore */ get colorUpdateAngleLodScale(): number; /** * Sets the alpha threshold for shadow, pick, and prepass rendering (not the main forward * splat pass). Higher values create more aggressive clipping, while lower values preserve more * translucent splats. Defaults to 0.3. * * @type {number} */ set alphaClip(value: number); /** * Gets the alpha threshold for shadow, pick, and prepass rendering. * * @type {number} */ get alphaClip(): number; /** * Sets the alpha threshold below which splats are culled or clipped in the **forward** splat * rendering pass. Does not apply to shadow, pick, or prepass — use {@link GSplatParams#alphaClip} * for those. Higher values improve performance by culling more low-opacity splats; lower values * preserve more translucent splats. Defaults to 1 / 255. * * @type {number} */ set alphaClipForward(value: number); /** * Gets the forward-pass alpha threshold. * * @type {number} */ get alphaClipForward(): number; /** * Sets the minimum screen-space pixel size below which splats are discarded. Defaults to 2. * * @type {number} */ set minPixelSize(value: number); /** * Gets the minimum pixel size threshold. * * @type {number} */ get minPixelSize(): number; /** * Sets the minimum visual contribution threshold for the {@link GSPLAT_RENDERER_RASTER_GPU_SORT} * renderer. Splats whose total screen contribution (opacity * projected area) falls below this value are * discarded. Higher values cull more aggressively, improving performance at the cost of quality. * Set to 0 to disable contribution culling. Defaults to 3. * * @type {number} */ set minContribution(value: number); /** * Gets the minimum contribution threshold. * * @type {number} */ get minContribution(): number; /** * Sets the foveated contribution culling strength. Only used by the * {@link GSPLAT_RENDERER_RASTER_GPU_SORT} renderer. When greater than zero, the contribution * culling threshold is raised radially from the screen centre: the effective threshold is * `minContribution + foveationStrength * smoothstep(foveationCenter, 1, length(ndc))`, so the * centre of the screen is unaffected and low-contribution splats are culled increasingly * toward the edges, reaching full strength at the screen edge and beyond (corners). Set to 0 * to disable. Defaults to 0. * * @type {number} */ set foveationStrength(value: number); /** * Gets the foveated contribution culling strength. * * @type {number} */ get foveationStrength(): number; /** * Sets the protected centre radius for foveated contribution culling. Only used by the * {@link GSPLAT_RENDERER_RASTER_GPU_SORT} renderer. Expressed in NDC radius units (0 at the * screen centre, 1 at the edge): within this radius {@link foveationStrength} has no effect, * and the falloff ramps smoothly from this radius to the screen edge. Defaults to 0.3. * * @type {number} */ set foveationCenter(value: number); /** * Gets the protected centre radius for foveated contribution culling. * * @type {number} */ get foveationCenter(): number; /** * Enables anti-aliasing compensation for Gaussian splats. Defaults to false. * * This option is intended for splat data that was generated with anti-aliasing * enabled during training/export. It improves visual stability and reduces * flickering for very small or distant splats. * * If the source splats were generated without anti-aliasing, enabling this * option may slightly soften the image or alter opacity. * * @type {boolean} */ set antiAlias(value: boolean); /** * Gets whether anti-aliasing compensation is enabled. * * @type {boolean} */ get antiAlias(): boolean; /** * Enables 2D Gaussian Splatting mode. Defaults to false. * * Renders splats as oriented 2D surface elements instead of volumetric 3D Gaussians. * This provides a more surface-accurate appearance but requires splat data that * was generated for 2D Gaussian Splatting. * * Enabling this with standard 3D splat data may produce incorrect results. * * @type {boolean} */ set twoDimensional(value: boolean); /** * Gets whether 2D Gaussian Splatting mode is enabled. * * @type {boolean} */ get twoDimensional(): boolean; /** @private */ private _fisheye; /** * Controls the fisheye projection strength for Gaussian splats. The value is in the * range [0, 1]: * * - 0: Standard rectilinear (perspective) projection. * - (0, 1]: Increasing barrel distortion, producing a wider field of view with a * "little planet" effect at higher values. * * Enabling fisheye for the first time has a small one-off cost as new shaders are * compiled. Subsequent switches between 0 and non-zero are instantaneous. * * Only supported with perspective cameras. Has no effect with orthographic projection. * * Note: This only affects Gaussian splat rendering. Other objects in the scene (meshes, * sprites, etc.) continue to use the standard camera projection and are not distorted. * * For best results, enable {@link radialSorting} when using fisheye projection * to avoid sorting artifacts caused by the wide field of view. * * Defaults to 0. * * @type {number} */ set fisheye(value: number); /** * Gets the fisheye projection strength. * * @type {number} */ get fisheye(): number; /** * Number of update ticks before unloading unused streamed resources. When a streamed resource's * reference count reaches zero, it enters a cooldown period before being unloaded. This allows * recently used data to remain in memory for quick reuse if needed again soon. Set to 0 to * unload immediately when unused. Defaults to 100. */ cooldownTicks: number; /** * Whether the gaussian splats contribute to the scene depth, which the volumetric fog and the depth * of field need in order to be bounded by the splats instead of drawing through them. * * This costs an extra full screen render target, and so defaults to false. Enable it for a scene * where the splats need to take part in those effects. Requires the camera to render using * {@link CameraFrame} - see {@link CameraFrame.isSplatSceneDepthSupported}. * * On some devices enabling this stores the scene depth at a lower precision, which the other * effects using it share. The depth stays accurate over camera clip distances of roughly 0.000015 * to 16384 there; past the far end of that a distant depth loses accuracy, and the pixels nothing * covers stop reading as far away as they are. Keep the far clip inside that range on those * devices, or leave the effects which read the depth off. * * @type {boolean} */ sceneDepthWrite: boolean; /** * Work buffer data format. Controls the precision and bandwidth of the intermediate work buffer * used during GSplat rendering. Can be set to {@link GSPLATDATA_COMPACT} (20 bytes/splat) * or {@link GSPLATDATA_LARGE} (32 bytes/splat). Defaults to {@link GSPLATDATA_COMPACT}. * * @type {string} */ set dataFormat(value: string); /** * Gets the work buffer data format. * * @type {string} */ get dataFormat(): string; /** * A material template that can be customized by the user. Any defines, parameters, or shader * chunks set on this material will be automatically applied to all GSplat components. After * making changes, call {@link Material#update} to for the changes to be applied on the next * frame. * * @type {ShaderMaterial} * @example * // Set a custom parameter on all GSplat materials * app.scene.gsplat.material.setParameter('myCustomParam', 1.0); * app.scene.gsplat.material.update(); */ get material(): ShaderMaterial; /** * Format descriptor for work buffer streams. Describes the textures used by the work buffer * for intermediate storage during rendering. Users can add extra streams via * {@link GSplatFormat#addExtraStreams} for custom per-splat data. * * @type {GSplatFormat} * @example * // Add a custom stream to store per-splat component IDs * app.scene.gsplat.format.addExtraStreams([{ * name: 'splatId', * format: PIXELFORMAT_R32U * }]); */ get format(): GSplatFormat; /** * The varyings version last applied to the material. * * @type {number} * @private */ private _appliedVaryingsVersion; /** * Custom varying streams for the gsplat render customization: per-splat values written by * the `gsplatModifyVS` shader chunk and read per fragment by the `gsplatModifyPS` shader * chunk. See {@link GSplatVaryings}. * * @type {GSplatVaryings} * @example * // Add a per-splat flag, written once per splat in gsplatModifyVS using setFlag(value), * // and read per fragment in gsplatModifyPS using getFlag() * app.scene.gsplat.varyings.add([{ * name: 'flag', * type: TYPE_UINT32, * components: 1 * }]); */ get varyings(): GSplatVaryings; /** * Applies serialized scene settings (e.g. from the Editor) to the gsplat parameters. Reads * flat `gsplat`-prefixed keys off the `render` settings object; missing keys leave the current * value unchanged. * * @param {object} render - The render settings object. * @ignore */ applySettings(render: object): void; /** * Called at the end of the frame to clear the parameter dirty flag. * * @ignore */ frameEnd(): void; /** * Called at the start of the frame, before the renderers synchronize the material, to apply * pending changes. * * @ignore */ frameUpdate(): void; } /** * @import { BoundingBox } from '../../core/shape/bounding-box.js' * @import { GraphicsDevice } from '../../platform/graphics/graphics-device.js' * @import { GraphNode } from '../graph-node.js' * @import { GSplatResource } from '../gsplat/gsplat-resource.js' * @import { GSplatResourceBase } from '../gsplat/gsplat-resource-base.js' * @import { GSplatOctreeResource } from './gsplat-octree.resource.js' * @import { ScopeId } from '../../platform/graphics/scope-id.js' * @import { Texture } from '../../platform/graphics/texture.js' * @import { Vec2 } from '../../core/math/vec2.js' */ /** * Class representing a placement of a gsplat resource. * * @ignore */ declare class GSplatPlacement { /** * Create a new GSplatPlacement. * * @param {GSplatResource|null} resource - The resource of the splat. * @param {GraphNode} node - The node that the gsplat is linked to. * @param {number} [lodIndex] - The LOD index for this placement. * @param {Map|null} [parameters] - Per-instance shader parameters. * @param {GSplatPlacement|null} [parentPlacement] - Parent placement for shader config delegation. * @param {number|null} [id] - Unique identifier for picking. If not provided, inherits from parentPlacement. */ constructor(resource: GSplatResource | null, node: GraphNode, lodIndex?: number, parameters?: Map | null, parentPlacement?: GSplatPlacement | null, id?: number | null); /** * The resource of the splat.. * * @type {GSplatResource|GSplatOctreeResource|null} */ resource: GSplatResource | GSplatOctreeResource | null; /** * The node that the gsplat is linked to. * * @type {GraphNode} */ node: GraphNode; /** * Map of intervals for octree nodes using this placement. * Key is octree node index, value is Vec2 representing start and end index (inclusive). * * @type {Map} */ intervals: Map; /** * Unique identifier for this placement. Used by the picking system and available * for custom shader effects. */ id: number; /** * Unique allocation identifier for persistent work buffer allocation tracking. * * @type {number} */ allocId: number; /** * The LOD index for this placement. */ lodIndex: number; /** * Minimum allowed LOD index (inclusive). Clamped to the asset's valid range at use. * * @private */ private _lodRangeMin; /** * Maximum allowed LOD index (inclusive). Clamped to the asset's valid range at use. * * @private */ private _lodRangeMax; /** * Distance of the first LOD transition, from LOD 0 to LOD 1, in world units. * * @private */ private _lodBaseDistance; /** * Factor between successive LOD transition distances. * * @private */ private _lodMultiplier; /** * @type {number} */ set lodBaseDistance(value: number); get lodBaseDistance(): number; /** * Flag indicating LOD parameters have changed and LOD needs re-evaluation. */ lodDirty: boolean; /** * @type {number} */ set lodMultiplier(value: number); get lodMultiplier(): number; /** * @type {number} */ set lodRangeMin(value: number); get lodRangeMin(): number; /** * @type {number} */ set lodRangeMax(value: number); get lodRangeMax(): number; /** * The axis-aligned bounding box for this placement, in local space. * Null means use resource.aabb as fallback. * * @type {BoundingBox|null} */ _aabb: BoundingBox | null; /** * Per-instance shader parameters. Reference to the component's parameters Map. * * @type {Map|null} */ parameters: Map | null; /** * Optional streams for instance-level textures. * * @type {GSplatStreams|null} * @private */ private _streams; /** * Monotonically increasing counter, bumped whenever this placement's splats need to be * re-copied to the work buffer (parameter or modifier changes, or an explicit one-shot update * request). Each consumer (a per-camera {@link GSplatInfo}) remembers the value it last * copied at, so a single request re-copies every consumer of a shared placement exactly once, * and child placements (octree files, environment) fan out from their parent's counter. * * @type {number} * @ignore */ dirtyVersion: number; /** * Work buffer update mode (see WORKBUFFER_UPDATE_*). WORKBUFFER_UPDATE_ONCE is not stored as a * mode - it is converted into a single {@link dirtyVersion} bump. * * @type {number} * @private */ private _workBufferUpdate; /** * Custom work buffer modifier code for this placement (object with code and pre-computed hash). * * @type {{ code: string, hash: number }|null} * @private */ private _workBufferModifier; /** * Parent placement. Used by octree file placements to inherit workBufferModifier and * parameters from the component's placement. * * @type {GSplatPlacement|null} * @ignore */ parentPlacement: GSplatPlacement | null; /** * Destroys this placement and releases all resources. */ destroy(): void; /** * Sets the work buffer modifier for this placement. Triggers work buffer re-render. * Must provide all three functions: modifySplatCenter, modifySplatRotationScale, modifySplatColor. * * @type {{ code: string, hash: number }|null} */ set workBufferModifier(value: { code: string; hash: number; } | null); /** * Gets the work buffer modifier for this placement. * Delegates to parent placement if available (for octree file placements). * * @type {{ code: string, hash: number }|null} */ get workBufferModifier(): { code: string; hash: number; } | null; /** * Sets the work buffer update mode (see WORKBUFFER_UPDATE_*). WORKBUFFER_UPDATE_ONCE is turned * into a single {@link dirtyVersion} bump so every consumer re-copies once, rather than being * stored as a persistent mode. * * @type {number} */ set workBufferUpdate(value: number); /** * Gets the work buffer update mode. * * @type {number} */ get workBufferUpdate(): number; /** * Marks the placement as needing a one-time re-copy to the work buffer by all of its * consumers. */ markDirty(): void; /** * Sets a custom AABB for this placement. Pass null to use resource.aabb as fallback. * * @param {BoundingBox|null} aabb - The bounding box to set, or null to clear. */ set aabb(aabb: BoundingBox | null); /** * Gets the AABB for this placement. Returns custom AABB if set, otherwise resource.aabb. * * @returns {BoundingBox} The bounding box. */ get aabb(): BoundingBox; /** * Gets an instance-level texture by name. Creates the streams container on first access * if the format has instance streams defined. * * @param {string} name - The name of the texture to get. * @param {GraphicsDevice} device - The graphics device (required for lazy initialization). * @returns {Texture|undefined} The texture, or undefined if not found. */ getInstanceTexture(name: string, device: GraphicsDevice): Texture | undefined; /** * Gets the instance streams container, or null if not initialized. * Delegates to parent placement if available (for octree file placements). * * @type {GSplatStreams|null} * @ignore */ get streams(): GSplatStreams | null; /** * Ensures instance streams container exists if format has instance streams. * * @param {GraphicsDevice} device - The graphics device. * @ignore */ ensureInstanceStreams(device: GraphicsDevice): void; } declare class GSplatOctreeInstance { /** * @param {GraphicsDevice} device - The graphics device. * @param {GSplatOctree} octree - The octree. * @param {GSplatPlacement} placement - The placement. */ constructor(device: GraphicsDevice, octree: GSplatOctree, placement: GSplatPlacement); /** @type {GSplatOctree} */ octree: GSplatOctree; /** @type {GSplatPlacement} */ placement: GSplatPlacement; /** @type {Set} */ activePlacements: Set; /** @type {boolean} */ dirtyModifiedPlacements: boolean; /** * Set to true when placements are added or removed, signaling that the manager needs to * create a new world state and trigger a full work buffer rebuild. */ dirtyPlacementSetChanged: boolean; /** @type {GraphicsDevice} */ device: GraphicsDevice; /** * Array of NodeInfo instances, one per octree node. * * @type {NodeInfo[]} */ nodeInfos: NodeInfo[]; /** * Array of current placements per file. Index is fileIndex, value is GSplatPlacement or null. * Value null indicates file is not used / no placement. * * @type {(GSplatPlacement|null)[]} */ filePlacements: (GSplatPlacement | null)[]; /** * Set of pending file loads (file indices). * * @type {Set} */ pending: Set; /** * Map of nodeIndex -> { oldFileIndex, newFileIndex } that needs to be decremented when the * new LOD resource loads. This ensures we decrement even if the node switches LOD again * before the new resource arrives. * * @type {Map} */ pendingDecrements: Map; /** * Files that became unused by this instance this update. Each entry represents a single decRef. * * @type {Set} */ removedCandidates: Set; /** * Minimum allowed LOD index for this instance, clamped to valid octree bounds. */ rangeMin: number; /** * Maximum allowed LOD index for this instance, clamped to valid octree bounds. */ rangeMax: number; /** * Selection table for this instance's current LOD range, refreshed by * {@link GSplatOctreeInstance#resolveLodRange}. Read by the budget balancer rather than having * it resolve the range a second time. * * @type {import('./gsplat-lod-table.js').GSplatLodTable|null} */ lodTable: GSplatLodTable | null; /** * Previous node position at which LOD was last updated. This is used to determine if LOD needs * to be updated as the octree splat moves. */ previousPosition: Vec3; /** * Set when a resource has completed loading and LOD should be re-evaluated. */ needsLodUpdate: boolean; /** * Tracks prefetched file indices that are being loaded without active placements, rebuilt on * every LOD update. When any completes, we trigger LOD re-evaluation to allow promotion. * * @type {Set} */ prefetchPending: Set; /** * Files this instance waits for, mapped to their load priority. Rebuilt on every LOD update * and submitted to the octree, which combines the requests of all its instances. * * @type {Map} * @private */ private _fileRequests; /** * Tracks invisible->visible pending adds per node: nodeIndex -> fileIndex. * Ensures only a single pending placement exists for a node while it's not yet displayed. * * @type {Map} */ pendingVisibleAdds: Map; /** * Returns the count of resources pending load or prefetch, including environment if loading. * * @type {number} */ get pendingLoadCount(): number; /** * Environment placement. * * @type {GSplatPlacement|null} */ environmentPlacement: GSplatPlacement | null; /** * Event handle for device lost event. * * @type {EventHandle|null} * @private */ private _deviceLostEvent; /** * Destroys this octree instance and clears internal references. * * @param {boolean} [skipRefCounting] - When true, skip decrementing file ref counts * on the octree. Used when the caller handles ref counting externally via pendingReleases * (e.g. during world state updates where decrements must be deferred). */ destroy(skipRefCounting?: boolean): void; /** * Handles device lost event by releasing all loaded resources. * * @private */ private _onDeviceLost; /** * Returns the file indices currently referenced by this instance that should be decremented * when the instance is destroyed. * * @returns {number[]} Array of file indices to decRef. */ getFileDecrements(): number[]; /** * Selects the LOD index to display for a node, applying the underfill strategy. When underfill * is enabled it prefers the finest already-loaded level within `lodUnderfillLimit` steps * coarser than the target, so a node shows something rather than nothing while its target * streams in. If none are loaded it takes the coarsest level in that window. * * Steps are taken along the node's LOD chain rather than over raw LOD indices, so levels the * node has no data for are skipped - see GSplatLodTable. * * @param {number} nodeIndex - The octree node index. * @param {number} optimalLodIndex - LOD index the allocator chose. * @param {number} lodUnderfillLimit - Allowed number of coarser chain steps. * @returns {number} LOD index to display. */ selectDesiredLodIndex(nodeIndex: number, optimalLodIndex: number, lodUnderfillLimit: number): number; /** * Prefetch only the next-better LOD toward optimal. This stages loading in steps across all * nodes, avoiding intermixing requests before coarse is present. Steps follow the node's LOD * chain, so they skip levels the node has no data for and never overshoot the level the * allocator chose. * * @param {number} nodeIndex - The octree node index. * @param {number} desiredLodIndex - Currently selected LOD for display (may be coarser than optimal). * @param {number} optimalLodIndex - Target optimal LOD. * @param {number} priority - Load priority for the prefetched file. */ prefetchNextLod(nodeIndex: number, desiredLodIndex: number, optimalLodIndex: number, priority: number): void; /** * Requests a file for this LOD update, unless it is already loaded. A file requested more than * once keeps its highest priority. * * @param {number} fileIndex - The file index. * @param {number} priority - Load priority, higher loads first. * @returns {boolean} True if the file is already loaded. */ requestFile(fileIndex: number, priority: number): boolean; /** * Resolves the configured LOD range against the octree and caches the selection table for it. * Called before the budget allocator, so it sees the current range. */ resolveLodRange(): void; /** * Evaluates each node's squared world distance from the camera, with FOV compensation and the * behind-camera penalty folded in. This is Pass 1 of the LOD update process; results are * stored in the nodeInfos array and consumed by the budget allocator, which is what actually * picks a LOD level. Distance is measured to the nearest point of the node's bounds, and the * same way under both projections - an orthographic footprint carries no depth term, so this * is what gives it a distance ordering at all. * * @param {GraphNode} cameraNode - The camera node. * @param {import('./gsplat-params.js').GSplatParams} params - Global gsplat parameters. */ evaluateNodeDistances(cameraNode: GraphNode, params: GSplatParams): void; /** * Applies calculated LOD changes and manages file placements. * This is Pass 2 of the LOD update process. Reads the levels the budget allocator wrote into * the nodeInfos array. * * Also requests every file this instance still waits for, with a load priority. The priority * is ranked by tier first - a node that shows nothing yet, then a node waiting to switch LOD, * then a prefetch of the next finer level - and within a tier by the node's * {@link NodeInfo#worldDistanceSq}, so the view fills with coarse data first and then refines * nearest the camera first. A file shared by several nodes takes the highest priority of them. * The requests are submitted to the octree, which combines them with those of its other * instances and issues them in {@link GSplatOctree#flushRequests}. * * @param {import('./gsplat-params.js').GSplatParams} params - Global gsplat parameters. */ applyLodChanges(params: GSplatParams): void; /** * Increments reference count for a file and creates placement immediately. * * @param {number} fileIndex - The file index. * @param {number} nodeIndex - The octree node index. * @param {number} lodIndex - The LOD index for this node. */ incrementFileRef(fileIndex: number, nodeIndex: number, lodIndex: number): void; /** * Decrements reference count for a file and removes placement if needed. * * @param {number} fileIndex - The file index. * @param {number} nodeIndex - The octree node index. */ decrementFileRef(fileIndex: number, nodeIndex: number): void; /** * Updates existing placement with loaded resource and adds to manager. * * @param {number} fileIndex - The file index. * @returns {boolean} True if placement was updated and added to manager, false otherwise. */ addFilePlacement(fileIndex: number): boolean; /** * Tests if the octree instance has moved by more than the provided LOD update distance. * * @param {number} threshold - Distance threshold to trigger an update. * @returns {boolean} True if the octree instance has moved by more than the threshold, false otherwise. */ testMoved(threshold: number): boolean; /** * Updates the previous position of the octree instance. */ updateMoved(): void; /** * Updates the octree instance each frame. * * @returns {boolean} True if octree instance is dirty, false otherwise. */ update(): boolean; /** * Consumes and returns whether the active placement set membership changed (add/remove). * * @returns {boolean} True if placements were added or removed since last call. */ consumePlacementSetChanged(): boolean; debugRender(scene: any): void; /** * Returns true if this instance requests LOD re-evaluation and resets the flag. * * @returns {boolean} True if LOD should be re-evaluated. */ consumeNeedsLodUpdate(): boolean; /** * Polls prefetched file indices for completion and updates state. */ pollPrefetchCompletions(): void; } /** * Stores LOD state for a single octree node. * * @ignore */ declare class NodeInfo { /** * Current LOD index being rendered. -1 indicates node is not visible. */ currentLod: number; /** * LOD index the budget allocator chose for this node, before underfill. -1 when the node has * nothing renderable in its LOD range. */ optimalLod: number; /** * Squared world-space distance from the camera to this node, with the FOV compensation and * the behind-camera penalty folded in. The only way camera position influences LOD selection, * and what orders loads within a priority tier. Kept squared so the per-node pass needs no * square root - every consumer works in squared or log space. */ worldDistanceSq: number; /** * Accumulated camera translation for SH color update threshold tracking. */ colorAccumulatedTranslation: number; /** * Back-reference to owning GSplatOctreeInstance. * * @type {GSplatOctreeInstance|null} */ inst: GSplatOctreeInstance | null; /** * Unique allocation identifier for persistent work buffer allocation tracking. * * @type {number} */ allocId: number; /** * Resets all LOD values to -1 (invisible/uninitialized). */ resetLod(): void; } /** * Represents a snapshot of gsplat state for rendering. This class captures all necessary data * at a point in time and should not hold references back to the source placement. All required * data should be copied or referenced, allowing placement to be modified without affecting the * info. The only exception is shader configuration and dirty state, which are deliberately read * live through narrow accessor closures (see the fields documented as 'retrieved live'), so that * changes raised after the snapshot was taken are still observed. * * @ignore */ declare class GSplatInfo { /** * Create a new GSplatInfo. * * @param {GraphicsDevice} device - The graphics device. * @param {GSplatResourceBase} resource - The splat resource. * @param {GSplatPlacement} placement - The placement of the splat. Do not store it - snapshot * its data instead, as the placement is mutated for future world states while this info still * renders. Only shader configuration and dirty state may be read live, via accessor closures. * @param {GSplatOctreeNode[]|null} [octreeNodes] - Octree nodes for bounds lookup. * @param {NodeInfo[]|null} [nodeInfos] - Per-node info array from octree instance. */ constructor(device: GraphicsDevice, resource: GSplatResourceBase, placement: GSplatPlacement, octreeNodes?: GSplatOctreeNode[] | null, nodeInfos?: NodeInfo[] | null); /** @type {GraphicsDevice} */ device: GraphicsDevice; /** @type {GSplatResourceBase} */ resource: GSplatResourceBase; /** @type {GraphNode} */ node: GraphNode; /** @type {number} */ lodIndex: number; /** * Unique identifier from the placement, used for picking. * * @type {number} */ placementId: number; /** * Unique allocation identifier for persistent work buffer allocation tracking. * Copied from the source placement. * * @type {number} */ allocId: number; /** * Identifies the bounds group this splat belongs to. All file placements from the same * octree instance share the parent placement's allocId. Non-octree placements use their * own allocId. Used to deduplicate bounds and transform texture entries. * * @type {number} */ parentPlacementId: number; /** @type {number} */ numSplats: number; /** @type {number} */ activeSplats: number; /** * Array of intervals for remapping of indices, each two consecutive numbers represent * start and end of a range of splats. * * @type {number[]} */ intervals: number[]; /** * Per-interval pixel offsets in the work buffer. For non-octree splats this has one entry. * For octree splats each entry corresponds to one interval in this.intervals. * * @type {number[]} */ intervalOffsets: number[]; /** * Per-interval allocation IDs for persistent tracking. Parallel to intervals: for octree * splats each entry is the NodeInfo.allocId for that interval's node; for non-octree * splats this has one entry equal to this.allocId. * * @type {number[]} */ intervalAllocIds: number[]; /** * Per-interval octree node indices. Parallel to intervals: for octree splats each entry * is the nodeIndex for that interval. Empty for non-octree splats. * * @type {number[]} */ intervalNodeIndices: number[]; /** @type {Mat4} */ previousWorldTransform: Mat4; /** @type {BoundingBox} */ aabb: BoundingBox; /** * Small RGBA32U texture storing per-sub-draw data for instanced interval rendering. * Each texel: R = rowStart | (numRows << 16), G = colStart, B = colEnd, A = sourceBase. * Created lazily by {@link ensureSubDrawTexture} when needed for rendering. * * @type {Texture|null} */ subDrawTexture: Texture | null; /** * Number of sub-draw instances for instanced interval rendering. */ subDrawCount: number; /** * Number of bounding sphere entries this GSplatInfo contributes to the shared bounds texture. */ numBoundsEntries: number; /** * Base index into the shared bounds sphere texture for this GSplatInfo's entries. */ boundsBaseIndex: number; /** * Octree nodes array reference for writing bounding sphere data. Set when the GSplatInfo * is created from an octree placement. * * @type {GSplatOctreeNode[]|null} */ octreeNodes: GSplatOctreeNode[] | null; /** * Per-node info array from the octree instance, providing allocId for each node. * Indexed by nodeIndex. Null for non-octree splats. * * @type {NodeInfo[]|null} */ nodeInfos: NodeInfo[] | null; /** @type {number} */ colorAccumulatedTranslation: number; /** * Per-instance shader parameters. Reference to the component's parameters Map. * * @type {Map|null} */ parameters: Map | null; /** * Function to get current work buffer modifier from source placement. * Retrieved live (not snapshotted) to ensure shader configuration stays current. * * @type {(() => ({ code: string, hash: number }|null))|null} */ getWorkBufferModifier: (() => ({ code: string; hash: number; } | null)) | null; /** * Function to get current instance streams from source placement. * Retrieved live (not snapshotted) to ensure streams are available after lazy creation. * * @type {(() => GSplatStreams|null)|null} */ getInstanceStreams: (() => GSplatStreams | null) | null; /** * Function to get the placement that owns the dirty state - the parent placement for child * placements (octree files, environment), the placement itself otherwise. Retrieved live (not * snapshotted) so dirty requests raised after this info was created are still observed. * * @type {(() => GSplatPlacement)|null} * @private */ private _getDirtySource; /** * The last {@link GSplatPlacement#dirtyVersion} this consumer re-copied at. Tracked here (per * camera) rather than on the shared placement, so a single dirty request re-copies every * consumer of the placement exactly once. * * @type {number} * @private */ private _lastDirtyVersion; /** * The last resource format extra-streams version this consumer re-copied at. * * @type {number} * @private */ private _lastFormatVersion; destroy(): void; /** * Sets per-interval pixel offsets for this splat. Sub-draw computation and GPU texture * creation are deferred to {@link ensureSubDrawTexture} to avoid work for splats that * may never be rendered (e.g. intermediate world states or unchanged splats). * * @param {number[]} intervalOffsets - Per-interval pixel offsets in the work buffer. */ setLayout(intervalOffsets: number[]): void; /** * Ensures the sub-draw texture exists, computing sub-draw data and creating the GPU texture * on first call. Must be called outside a render pass (e.g. in the render pass update method) * since WebGPU does not allow texture creation inside a render pass. * * @param {number} textureWidth - The work buffer texture width. */ ensureSubDrawTexture(textureWidth: number): void; /** * Updates the flattened intervals array from placement intervals. Intervals are sorted and * stored as half-open pairs [start, end). Called once from the constructor; sub-draw data * is built later in setLayout when the work buffer texture width is known. * * @param {Map} intervals - Map of node index to inclusive [x, y] intervals. */ updateIntervals(intervals: Map): void; /** * Splits an interval at row boundaries into sub-draws (partial first row, full middle rows, * partial last row) and appends them to the sub-draw data array. * * @param {Uint32Array} subDrawData - The output array to append sub-draw entries to. * @param {number} subDrawCount - Current number of sub-draws already in the array. * @param {number} sourceBase - Source splat index for this interval. * @param {number} size - Number of splats in this interval. * @param {number} targetOffset - Pixel offset in the work buffer texture. * @param {number} textureWidth - Width of the work buffer texture. * @returns {number} Updated sub-draw count. */ appendSubDraws(subDrawData: Uint32Array, subDrawCount: number, sourceBase: number, size: number, targetOffset: number, textureWidth: number): number; /** * Builds the sub-draw data texture from the current intervals (or a synthetic full-range * interval when none exist). Each interval is split at row boundaries of the work buffer * texture to produce axis-aligned rectangles stored as a small RGBA32U texture. * * @param {number} textureWidth - The work buffer texture width. */ updateSubDraws(textureWidth: number): void; update(): boolean; /** * Writes bounding sphere data for this GSplatInfo into a shared Float32Array. * For octree resources, writes spheres for ALL nodes (indexed by nodeIndex) to keep * boundsBaseIndex stable across LOD changes. * For non-octree resources, computes a single sphere from the resource AABB. * * @param {Float32Array} data - The shared bounds sphere data array. * @param {number} offset - The float offset to start writing at. */ writeBoundsSpheres(data: Float32Array, offset: number): void; get hasSphericalHarmonics(): boolean; } /** * A render pass used to render multiple gsplats to a work buffer render target. * * @ignore */ declare class GSplatWorkBufferRenderPass extends RenderPass { constructor(device: any, workBuffer: any, colorOnly?: boolean); /** * Array of GSplatInfo objects to render in this pass. * * @type {GSplatInfo[]} */ splats: GSplatInfo[]; /** @type {number[][]|undefined} */ colorsByLod: number[][] | undefined; /** * The camera node used for rendering. * * @type {GraphNode} */ cameraNode: GraphNode; /** @type {GSplatWorkBuffer} */ workBuffer: GSplatWorkBuffer; /** @type {boolean} */ colorOnly: boolean; /** * True when any splat in the current pass sources geometry from the work buffer (see * GSplatResourceBase#supportsWorkBufferGeometry). Computed in update(); gates the * work-buffer-geometry uniform setup in execute() so non-opted-in passes skip it. * * @type {boolean} */ _usesWorkBufferGeometry: boolean; /** @type {Float32Array} */ _modelScaleData: Float32Array; /** @type {Float32Array} */ _modelRotationData: Float32Array; /** @type {Float32Array} */ _cameraPositionData: Float32Array; /** @type {Int32Array} */ _textureSize: Int32Array; /** * Shared grow-only texture holding packed sub-draw data for all partial renders in a frame. * * @type {Texture} */ _subDrawTexture: Texture; /** * Flat array of interleaved [baseOffset, count] pairs, parallel to this.splats. * For splat at index i: _partialData[i*2] = base offset into _subDrawTexture, * _partialData[i*2+1] = sub-draw count (0 means use splat's own sub-draws). * * @type {number[]} */ _partialData: number[]; /** * Initialize the render pass with the specified render target. * * @param {RenderTarget} renderTarget - The target to render to. */ init(renderTarget: RenderTarget): void; /** * Update the render pass with splats to render and camera. * * @param {GSplatInfo[]} splats - Array of GSplatInfo objects to render. * @param {GraphNode} cameraNode - The camera node for rendering. * @param {number[][]|undefined} colorsByLod - Optional array of RGB colors per LOD index. * @param {Set|null} [changedAllocIds] - Set of changed allocIds for partial render. * @returns {boolean} True if there are splats to render, false otherwise. */ update(splats: GSplatInfo[], cameraNode: GraphNode, colorsByLod: number[][] | undefined, changedAllocIds?: Set | null): boolean; /** * Render a single splat info object. Optionally renders only a subset of sub-draws * using an override texture and count (for partial work buffer updates). * * @param {GSplatInfo} splatInfo - The splat info to render. * @param {Texture} [overrideSubDrawTexture] - Override sub-draw texture for partial renders. * @param {number} [overrideSubDrawCount] - Override sub-draw count for partial renders. * @param {number} [subDrawBase] - Base offset into the sub-draw texture. */ renderSplat(splatInfo: GSplatInfo, overrideSubDrawTexture?: Texture, overrideSubDrawCount?: number, subDrawBase?: number): void; } /** * Frustum culling data for GSplat octree nodes. Manages bounding-sphere and * transform storage buffers and computes frustum planes from camera matrices. * The actual culling test is performed inline by the interval compaction compute shader. * * @ignore */ declare class GSplatFrustumCuller { /** * @param {GraphicsDevice} device - The graphics device. */ constructor(device: GraphicsDevice); /** @type {GraphicsDevice} */ device: GraphicsDevice; /** * Storage buffer holding interleaved BoundsEntry structs (center.xyz, radius, * transformIndex, pad x3). 32 bytes per entry. * * @type {StorageBuffer|null} */ boundsBuffer: StorageBuffer | null; /** * Total number of bounds entries across all GSplatInfos. */ totalBoundsEntries: number; /** @type {number} */ _allocatedBoundsEntries: number; /** @type {Float32Array|null} */ _boundsFloatView: Float32Array | null; /** @type {Uint32Array|null} */ _boundsUintView: Uint32Array | null; /** @type {Float32Array|null} */ _tmpSpheres: Float32Array | null; /** * Storage buffer holding world matrices as vec4f triplets (3 vec4f per matrix, * rows of a 4x3 affine matrix). 48 bytes per matrix. * * @type {StorageBuffer|null} */ transformsBuffer: StorageBuffer | null; /** @type {number} */ _allocatedTransformCount: number; /** @type {Float32Array|null} */ _transformsData: Float32Array | null; /** * Packed frustum planes (6 planes x 4 floats: nx, ny, nz, distance). * Updated by {@link computeFrustumPlanes} and consumed by the interval cull shader. * * @type {Float32Array} */ frustumPlanes: Float32Array; /** * Camera world position for fisheye cone culling (xyz). * * @type {Float32Array} */ fisheyeCameraPos: Float32Array; /** * Camera forward direction (normalized) for fisheye cone culling (xyz). * * @type {Float32Array} */ fisheyeCameraForward: Float32Array; /** * Maximum visible angle from forward direction for fisheye cone culling. */ fisheyeMaxTheta: number; destroy(): void; /** * Updates the bounds buffer with local-space bounding spheres and transform * indices from pre-built bounds groups. * * @param {Array<{splat: GSplatInfo, boundsBaseIndex: number, numBoundsEntries: number}>} boundsGroups - Pre-built bounds groups. */ updateBoundsData(boundsGroups: Array<{ splat: GSplatInfo; boundsBaseIndex: number; numBoundsEntries: number; }>): void; /** * Updates the transforms buffer with one world matrix per bounds group. * Each matrix is stored as 3 vec4f (rows of a 4x3 affine matrix). * * @param {Array<{splat: GSplatInfo, boundsBaseIndex: number, numBoundsEntries: number}>} boundsGroups - Pre-built bounds groups. */ updateTransformsData(boundsGroups: Array<{ splat: GSplatInfo; boundsBaseIndex: number; numBoundsEntries: number; }>): void; /** * Stores the planes of the given frustum in {@link frustumPlanes} for use by the interval * cull compute shader. * * @param {Frustum} frustum - The frustum to take the planes from. */ setFrustumPlanes(frustum: Frustum): void; /** * Computes frustum planes from camera matrices and stores them in * {@link frustumPlanes} for use by the interval cull compute shader. * * @param {Mat4} projectionMatrix - The camera projection matrix. * @param {Mat4} viewMatrix - The camera view matrix. */ computeFrustumPlanes(projectionMatrix: Mat4, viewMatrix: Mat4): void; /** * Sets fisheye cone culling data for the interval cull shader. * * @param {import('../../core/math/vec3.js').Vec3} cameraPos - Camera world position. * @param {import('../../core/math/vec3.js').Vec3} cameraForward - Camera forward direction (normalized). * @param {number} maxTheta - Maximum visible angle from forward direction in radians. */ setFisheyeData(cameraPos: Vec3, cameraForward: Vec3, maxTheta: number): void; } /** * An object that renders a quad using a {@link Shader}. * * Note: QuadRender does not modify render states. Before calling {@link render}, you should set * up the required states using {@link GraphicsDevice#setDrawStates}, or the individual setters * ({@link GraphicsDevice#setBlendState}, {@link GraphicsDevice#setCullMode}, * {@link GraphicsDevice#setFrontFace}, {@link GraphicsDevice#setDepthState}, * {@link GraphicsDevice#setStencilState}). Otherwise previously set states will be used. * * Example: * * ```javascript * const shader = ShaderUtils.createShader(app.graphicsDevice, { * uniqueName: 'MyShader', * attributes: { aPosition: SEMANTIC_POSITION }, * vertexGLSL: '// vertex shader code', * fragmentGLSL: '// fragment shader code' * }); * const quad = new QuadRender(shader); * * // Set up render states before rendering (defaults are suitable for full-screen quads) * app.graphicsDevice.setDrawStates(); * * quad.render(); * quad.destroy(); * ``` * * @category Graphics */ declare class QuadRender { /** * Create a new QuadRender instance. * * @param {Shader} shader - The shader to be used to render the quad. */ constructor(shader: Shader); /** * @type {UniformBuffer} * @ignore */ uniformBuffer: UniformBuffer; /** * @type {BindGroup} * @ignore */ bindGroup: BindGroup; shader: Shader; /** * Destroys the resources associated with this instance. */ destroy(): void; /** * Renders the quad. If the viewport is provided, the original viewport and scissor is restored * after the rendering. * * @param {Vec4} [viewport] - The viewport rectangle of the quad, in pixels. The viewport is * not changed if not provided. * @param {Vec4} [scissor] - The scissor rectangle of the quad, in pixels. Used only if the * viewport is provided. * @param {number} [numInstances] - Number of instances to draw. When provided, renders * multiple quads using instanced drawing. Each instance can use the instance index * (`gl_InstanceID` in GLSL, `pcInstanceIndex` in WGSL) to fetch per-quad data from * a texture or buffer, allowing each quad to be parameterized independently. */ render(viewport?: Vec4, scissor?: Vec4, numInstances?: number): void; } /** @ignore */ declare class GSplatWorkBuffer { /** * @param {GraphicsDevice} device - The graphics device. * @param {GSplatFormat} format - The work buffer format descriptor. */ constructor(device: GraphicsDevice, format: GSplatFormat); /** @type {GraphicsDevice} */ device: GraphicsDevice; /** @type {GSplatFormat} */ format: GSplatFormat; /** @type {number} */ id: number; /** * Manages textures for format streams. * * @type {GSplatStreams} */ streams: GSplatStreams; /** * Main MRT render target for all work buffer streams. * * @type {RenderTarget} */ renderTarget: RenderTarget; /** * Color-only render target for updating just the dataColor stream. * * @type {RenderTarget} */ colorRenderTarget: RenderTarget; /** @type {Texture|undefined} */ orderTexture: Texture | undefined; /** @type {StorageBuffer|undefined} */ orderBuffer: StorageBuffer | undefined; /** @type {UploadStream} */ uploadStream: UploadStream; /** @type {GSplatWorkBufferRenderPass} */ renderPass: GSplatWorkBufferRenderPass; /** @type {GSplatWorkBufferRenderPass} */ colorRenderPass: GSplatWorkBufferRenderPass; /** * GPU frustum culler for octree node visibility. * * @type {GSplatFrustumCuller} */ frustumCuller: GSplatFrustumCuller; /** * Gets or creates the resource-specific render information used to copy splats into this work * buffer. The cache remains on the resource because its material binds the resource's textures, * parameters and format-specific shader chunks. * * @param {GSplatResourceBase} resource - The source GSplat resource. * @param {boolean} colorOnly - Whether to render only color instead of the full MRT. * @param {{ code: string, hash: number }|null} workBufferModifier - Optional custom modifier. * @param {number} formatHash - Captured resource format hash for shader caching. * @param {string} formatDeclarations - Captured resource format declarations. * @returns {WorkBufferRenderInfo} The cached render information. * @private */ private getRenderInfo; /** * Creates or recreates render targets from current textures. * * @private */ private _createRenderTargets; /** * Syncs textures and render targets with the format when extra streams are added. * Call this before rendering to ensure all streams have textures. */ syncWithFormat(): void; /** * Gets a texture by name. * * @param {string} name - The texture name. * @returns {Texture|undefined} The texture, or undefined if not found. */ getTexture(name: string): Texture | undefined; destroy(): void; get textureSize(): number; setOrderData(data: any): void; /** * @param {number} textureSize - The texture size to resize to. */ resize(textureSize: number): void; /** * Render given splats to the work buffer. * * @param {GSplatInfo[]} splats - The splats to render. * @param {GraphNode} cameraNode - The camera node. * @param {number[][]|undefined} colorsByLod - Array of RGB colors per LOD. Index by lodIndex; if a * shorter array is provided, index 0 will be reused as fallback. * @param {Set|null} [changedAllocIds] - When provided, only render sub-draws for intervals * whose allocIds are in this set (per-node partial update). */ render(splats: GSplatInfo[], cameraNode: GraphNode, colorsByLod: number[][] | undefined, changedAllocIds?: Set | null): void; /** * Render only the color data to the work buffer (not geometry/covariance). * * @param {GSplatInfo[]} splats - The splats to render. * @param {GraphNode} cameraNode - The camera node. * @param {number[][]|undefined} colorsByLod - Array of RGB colors per LOD. Index by lodIndex; if a * shorter array is provided, index 0 will be reused as fallback. * @param {Set|null} [changedAllocIds] - Set of changed allocIds for partial render. */ renderColor(splats: GSplatInfo[], cameraNode: GraphNode, colorsByLod: number[][] | undefined, changedAllocIds?: Set | null): void; } /** * @import { GSplatFormat } from '../gsplat/gsplat-format.js' * @import { GSplatInfo } from "./gsplat-info.js" * @import { GraphicsDevice } from '../../platform/graphics/graphics-device.js' * @import { GraphNode } from '../graph-node.js'; * @import { GSplatResourceBase } from '../gsplat/gsplat-resource-base.js' * @import { ShaderMaterial } from '../materials/shader-material.js' */ /** * A helper class to cache quad renders for work buffer rendering. * * @ignore */ declare class WorkBufferRenderInfo { /** * @param {GraphicsDevice} device - The graphics device. * @param {string} key - Cache key for this render info. * @param {ShaderMaterial} material - The material to use. * @param {boolean} colorOnly - Whether to render only color (not full MRT). * @param {GSplatFormat} format - The work buffer format descriptor. */ constructor(device: GraphicsDevice, key: string, material: ShaderMaterial, colorOnly: boolean, format: GSplatFormat); /** @type {ShaderMaterial} */ material: ShaderMaterial; /** @type {QuadRender} */ quadRender: QuadRender; destroy(): void; } /** * Base class for a GSplat resource and defines common properties. * * @ignore */ declare class GSplatResourceBase { static createMesh(device: any): Mesh; static get instanceSize(): number; /** * @param {GraphicsDevice} device - The graphics device. * @param {object} gsplatData - Data source with getCenters(), calcAabb(), numSplats, etc. * @param {object} [options] - Construction options. * @param {boolean} [options.prepareCenters] - When omitted or true, calls gsplatData.getCenters() * and stores the result. When false, `centers` stays null until set or * materialized by a subclass (e.g. lazy allocation in GSplatContainer). */ constructor(device: GraphicsDevice, gsplatData: object, options?: { prepareCenters?: boolean; }); /** * @type {GraphicsDevice} * @ignore */ device: GraphicsDevice; /** * @type {GSplatData | GSplatCompressedData | GSplatSogData} * @ignore */ gsplatData: GSplatData | GSplatCompressedData | GSplatSogData; /** * CPU-side splat center positions (xyz per splat), or null when not built for this resource. * * @type {Float32Array|null} */ set centers(value: Float32Array); get centers(): Float32Array; /** * @type {Float32Array|null} * @protected */ protected _centers: Float32Array | null; /** * True when a centers buffer has been allocated (`centers` is non-null). * Reads internal storage only so checks do not trigger lazy allocation in {@link GSplatContainer}. * * @type {boolean} */ get hasCenters(): boolean; /** * Version counter for centers array changes. Remains 0 for static resources. * Only GSplatContainer increments this via its update() method. * * @ignore */ centersVersion: number; /** @type {BoundingBox} */ aabb: BoundingBox; /** * @type {Mesh|null} * @ignore */ mesh: Mesh | null; /** * @type {number} * @ignore */ id: number; /** * Cache for work buffer render materials/shaders. Keyed by configuration hash. * Stored per-resource because materials depend on resource-specific configuration * (SH bands, textures, defines). Cleaned up when resource is destroyed. * * @type {Map} * @ignore */ workBufferRenderInfos: Map; /** * Format descriptor for this resource. Assigned by derived classes. * * @type {GSplatFormat} * @protected */ protected _format: GSplatFormat; /** * Manages textures for this resource based on format streams. * * @type {GSplatStreams} * @ignore */ streams: GSplatStreams; /** * Non-texture uniform parameters required by this resource's format. * This is the single source of truth for format-specific uniforms (e.g., dequantization * parameters) used by both material configuration and processing. * * @type {Map} * @ignore */ parameters: Map; /** @private */ private _refCount; /** @private */ private _meshRefCount; /** * Destroys this resource. If the resource is still in use by the sorter, destruction is * automatically deferred until it's safe. */ destroy(): void; /** * Actually destroys this resource and releases all GPU resources. * Derived classes should override this method instead of destroy(). * * @protected */ protected _actualDestroy(): void; /** * Increments the reference count. * * @ignore */ incRefCount(): void; /** * Decrements the reference count. * * @ignore */ decRefCount(): void; /** * Gets the current reference count. This represents how many times this resource is currently * being used internally by the engine. For {@link GSplatComponent#asset|assets} assigned to * {@link GSplatComponent#unified|unified} gsplat components, this tracks active usage during * rendering and sorting operations. * * Resources should not be unloaded while the reference count is non-zero, as they are still * in use by the rendering pipeline. * * @type {number} * @ignore */ get refCount(): number; /** * Ensures mesh and instanceIndices exist. Creates them lazily on first call. Must be paired * with a call to releaseMesh() when done. * * @ignore */ ensureMesh(): void; /** * Releases reference to mesh. When all references are released, cleans up instanceIndices. * The mesh itself is destroyed by MeshInstance when its internal refCount reaches zero. * * @ignore */ releaseMesh(): void; /** * True when this resource's color-only work buffer updates (spherical harmonics refresh) can * source geometry from the work buffer itself instead of re-reading the source textures. The * resource format's read chunk must compile out getCenter/getRotation/getScale when * GSPLAT_WORKBUFFER_GEOMETRY is defined (see gsplatWorkBufferGeometryPS chunk). * * @type {boolean} * @ignore */ get supportsWorkBufferGeometry(): boolean; get numSplats(): any; /** * Gets the format descriptor for this resource. The format defines texture streams and * shader code for reading splat data. Use this to add extra streams. * * @type {GSplatFormat} */ get format(): GSplatFormat; /** * Gets a texture by name. * * @param {string} name - The name of the texture. * @returns {Texture|null} The texture, or null if not found. */ getTexture(name: string): Texture | null; /** * Gets the texture dimensions (width and height) used by this resource's data textures. * * @type {Vec2} */ get textureDimensions(): Vec2; /** * Configures a material to use this resource's data. Base implementation injects format's * shader chunks and binds textures from the streams. * * @param {ShaderMaterial} material - The material to configure. * @param {{ code: string, hash: number }|null} workBufferModifier - Optional custom modifier (object with code and pre-computed hash). * @param {string} formatDeclarations - Captured format declarations for shader compilation. * @ignore */ configureMaterial(material: ShaderMaterial, workBufferModifier: { code: string; hash: number; } | null, formatDeclarations: string): void; /** * Configures material defines for this resource. Derived classes should override this. * * @param {Map} defines - The defines map to configure. * @ignore */ configureMaterialDefines(defines: Map): void; instantiate(): void; } /** * @import { GraphicsDevice } from '../../platform/graphics/graphics-device.js' * @import { StorageBuffer } from '../../platform/graphics/storage-buffer.js' * @import { Texture } from '../../platform/graphics/texture.js' */ declare class GSplatSorter extends EventHandler { /** * @param {GraphicsDevice} device - The graphics device. * @param {import('../scene.js').Scene} [scene] - The scene to fire sort timing events on. */ constructor(device: GraphicsDevice, scene?: Scene); worker: Worker; /** @type {Texture|StorageBuffer} */ target: Texture | StorageBuffer; /** @type {ArrayBuffer} */ orderData: ArrayBuffer; centers: any; scene: Scene; /** @type {UploadStream} */ uploadStream: UploadStream; /** * Pending sorted result from the worker, applied on the next applyPendingSorted() call. * When multiple results arrive between frames, only the latest is kept. * * @type {{ count: number, data: Uint32Array }|null} */ pendingSorted: { count: number; data: Uint32Array; } | null; /** @type {number} */ count: number; _deviceRestoredEvent: EventHandle; destroy(): void; /** * @param {Texture|StorageBuffer} target - The GPU target for order data uploads. * @param {number} numSplats - The number of splats. * @param {Float32Array} centers - The splat center positions. * @param {Uint32Array} [chunks] - Optional chunk data. */ init(target: Texture | StorageBuffer, numSplats: number, centers: Float32Array, chunks?: Uint32Array): void; /** * Applies the most recent pending sorted result (if any), uploading order data to the GPU. * Call once per frame from the instance's update(). * * @returns {number} The splat count from the applied result, or -1 if nothing was pending. */ applyPendingSorted(): number; setMapping(mapping: any): void; setCamera(pos: any, dir: any): void; } /** @ignore */ declare class GSplatInstance { /** * @param {GSplatResourceBase} resource - The splat instance. * @param {object} [options] - Options for the instance. * @param {ShaderMaterial|null} [options.material] - The material instance. * @param {import('../scene.js').Scene} [options.scene] - The scene to fire sort timing events on. */ constructor(resource: GSplatResourceBase, options?: { material?: ShaderMaterial | null; scene?: Scene; }); /** @type {GSplatResourceBase} */ resource: GSplatResourceBase; /** @type {Texture|undefined} */ orderTexture: Texture | undefined; /** @type {StorageBuffer|undefined} */ orderBuffer: StorageBuffer | undefined; /** @type {ShaderMaterial} */ _material: ShaderMaterial; /** @type {MeshInstance} */ meshInstance: MeshInstance; options: {}; /** @type {GSplatSorter|null} */ sorter: GSplatSorter | null; lastCameraPosition: Vec3; lastCameraDirection: Vec3; /** * List of cameras this instance is visible for. Updated every frame by the renderer. * * @type {Camera[]} * @ignore */ cameras: Camera[]; destroy(): void; /** * Set order data parameters on the material. * * @param {ShaderMaterial} material - The material to configure. */ setMaterialOrderData(material: ShaderMaterial): void; /** * @param {ShaderMaterial} value - The material instance. */ set material(value: ShaderMaterial); get material(): ShaderMaterial; /** * Configure the material with gsplat instance and resource properties. * * @param {ShaderMaterial} material - The material to configure. * @param {object} [options] - Object for passing optional arguments. * @param {boolean} [options.dither] - Specify true to configure the material for dithered rendering (stochastic alpha). */ configureMaterial(material: ShaderMaterial, options?: { dither?: boolean; }): void; /** * Sorts the GS vertices based on the given camera. * @param {GraphNode} cameraNode - The camera node used for sorting. */ sort(cameraNode: GraphNode): void; update(): void; } /** * Base class for all post effects. Post effects take a render target as input, apply effects to * it, and then render the result to an output render target or the screen if no output is * specified. * * @category Graphics */ declare class PostEffect { /** * A simple vertex shader used to render a quad, which requires 'vec2 aPosition' in the vertex * buffer, and generates uv coordinates vUv0 for use in the fragment shader. * * @type {string} */ static quadVertexShader: string; /** * Create a new PostEffect instance. * * @param {GraphicsDevice} graphicsDevice - The graphics device of the application. */ constructor(graphicsDevice: GraphicsDevice); /** * The graphics device of the application. * * @type {GraphicsDevice} */ device: GraphicsDevice; /** * The property that should to be set to `true` (by the custom post effect) if a depth map * is necessary (default is false). */ needsDepthBuffer: boolean; /** * Render the post effect using the specified inputTarget to the specified outputTarget. * * @param {RenderTarget} inputTarget - The input render target. * @param {RenderTarget} outputTarget - The output render target. If null then this will be the * screen. * @param {Vec4} [rect] - The rect of the current camera. If not specified, it will default to * `[0, 0, 1, 1]`. */ render(inputTarget: RenderTarget, outputTarget: RenderTarget, rect?: Vec4): void; /** * Draw a screen-space rectangle in a render target, using a specified shader. * * @param {RenderTarget|null} target - The output render target. * @param {Shader} shader - The shader to be used for drawing the rectangle. * @param {Vec4} [rect] - The normalized screen-space position (rect.x, rect.y) and size (rect.z, * rect.w) of the rectangle. Default is `[0, 0, 1, 1]`. */ drawQuad(target: RenderTarget | null, shader: Shader, rect?: Vec4): void; } /** * Used to manage multiple post effects for a camera. This is the legacy post-processing path. For * new work use {@link CameraFrame}, which implements bloom, SSAO, depth of field, TAA, volumetric * fog and tone mapping as one HDR pipeline; `playcanvas/scripts/esm/camera-frame.mjs` wraps it as * an attachable script. * * @category Graphics */ declare class PostEffectQueue { /** * Create a new PostEffectQueue instance. * * @param {AppBase} app - The application. * @param {CameraComponent} camera - The camera component. */ constructor(app: AppBase, camera: CameraComponent); app: AppBase; camera: CameraComponent; /** * Render target where the postprocessed image needs to be rendered to. Defaults to null * which is main framebuffer. * * @type {RenderTarget} * @ignore */ destinationRenderTarget: RenderTarget; /** * All of the post effects in the queue. * * @type {PostEffectEntry[]} * @ignore */ effects: PostEffectEntry[]; /** * If the queue is enabled it will render all of its effects, otherwise it will not render * anything. * * @ignore */ enabled: boolean; depthTarget: any; /** * Allocate a color buffer texture. * * @param {number} format - The format of the color buffer. * @param {string} name - The name of the color buffer. * @returns {Texture} The color buffer texture. * @private */ private _allocateColorBuffer; /** * Creates a render target with the dimensions of the canvas, with an optional depth buffer. * * @param {boolean} useDepth - Set to true to create a render target with a depth buffer. * @param {boolean} hdr - Use HDR render target format. * @returns {RenderTarget} The render target. * @private */ private _createOffscreenTarget; _resizeOffscreenTarget(rt: any): void; _destroyOffscreenTarget(rt: any): void; /** * Adds a post effect to the queue. If the queue is disabled adding a post effect will * automatically enable the queue. * * @param {PostEffect} effect - The post effect to add to the queue. */ addEffect(effect: PostEffect): void; _sourceTarget: any; _newPostEffect: PostEffect; /** * Removes a post effect from the queue. If the queue becomes empty it will be disabled * automatically. * * @param {PostEffect} effect - The post effect to remove. */ removeEffect(effect: PostEffect): void; _requestDepthMaps(): void; _releaseDepthMaps(): void; _requestDepthMap(): void; _releaseDepthMap(): void; /** * Removes all the effects from the queue and disables it. */ destroy(): void; /** * Enables the queue and all of its effects. If there are no effects then the queue will not be * enabled. */ enable(): void; /** * Disables the queue and all of its effects. */ disable(): void; /** * Handler called when the application's canvas element is resized. * * @param {number} width - The new width of the canvas. * @param {number} height - The new height of the canvas. * @private */ private _onCanvasResized; resizeRenderTargets(): void; onCameraRectChanged(name: any, oldValue: any, newValue: any): void; } /** * @import { AppBase } from '../../app-base.js' * @import { CameraComponent } from './component.js' * @import { PostEffect } from '../../../scene/graphics/post-effect.js' */ declare class PostEffectEntry { constructor(effect: any, inputTarget: any); effect: any; inputTarget: any; outputTarget: any; name: any; } /** * @import { GraphicsDevice } from './graphics-device.js' * @import { EventHandler } from '../../core/event-handler.js' * @import { EventHandle } from '../../core/event-handle.js' * @import { Texture } from './texture.js' * @import { Vec2 } from '../../core/math/vec2.js' */ /** * Bridges WebXR presentation to the graphics device backend. * * @ignore */ declare class XrBridge { /** * @param {GraphicsDevice} device - The graphics device. * @param {EventHandler} eventHandler - Target for firing XR-related errors. */ constructor(device: GraphicsDevice, eventHandler: EventHandler); /** * @type {GraphicsDevice} */ device: GraphicsDevice; /** * Receives XR presentation-related events (for example {@link EventHandler#fire} with name `"error"`). * * @type {EventHandler} */ eventHandler: EventHandler; /** * @type {object} */ impl: object; /** * @type {EventHandle|null} * @private */ private _evtDeviceLost; /** * @type {EventHandle|null} * @private */ private _evtDeviceRestored; /** * Active XR session for presentation (shared across graphics backends). * * @type {XRSession|null} * @private */ private _session; /** * Resolved framebuffer scale from the last {@link XrBridge#attachPresentation}. * * @type {number} * @private */ private _framebufferScaleFactor; /** * Callback when backend GPU binding construction fails. * * @type {Function|undefined} * @private */ private _onBindingError; destroy(): void; /** @private */ private _onDeviceLost; /** @private */ private _onDeviceRestored; /** * @param {XRSession} session - XR session. * @param {object} options - Presentation options (backend-specific; includes framebufferScaleFactor, depthNear, depthFar). */ attachPresentation(session: XRSession, options: object): void; releasePresentation(): void; /** * Called once per XR frame before rendering to set the backend render target for this frame. * * @param {XRFrame} frame - Current XR frame. * @param {XRReferenceSpace|null} referenceSpace - Active XR reference space (WebGPU path uses * it for subimages). */ beginFrame(frame: XRFrame, referenceSpace: XRReferenceSpace | null): void; /** * Resets the backend render target after the XR session ends. */ endFrame(): void; /** * Writes immersive framebuffer size in pixels for this frame (backend-specific source) * into {@link Vec2#x} (width) and {@link Vec2#y} (height). * * @param {XRFrame} frame - Current XR frame. * @param {Vec2} out - Receives width and height; reused by the caller to avoid per-frame allocation. */ getFramebufferSize(frame: XRFrame, out: Vec2): void; /** * Viewport rectangle for an XR view within the immersive framebuffer (or per-view texture). * * @param {XRFrame} frame - Current XR frame. * @param {XRView} xrView - WebXR view. * @returns {XRViewport} Viewport for this view. */ getViewport(frame: XRFrame, xrView: XRView): XRViewport; /** * Copies the XR passthrough camera image for the given `XRCamera` into a PlayCanvas * {@link Texture}. Delegates to the backend implementation; no-ops if not supported. * * @param {any} xrCamera - The XR camera whose image should be copied (XRCamera from WebXR API). * @param {Texture} texture - Destination engine texture. */ syncCameraColorTexture(xrCamera: any, texture: Texture): void; /** * Binds XR GPU depth information to the engine depth texture on backends that support it * (WebGL). No-ops on WebGPU until a binding API exists. * * @param {any} depthInfo - Depth information from WebXR (`getDepthInformation`). * @param {Texture} texture - Destination engine texture. * @param {number} depthPixelFormat - Resolved depth pixel format constant (`PIXELFORMAT_*`). */ syncCameraDepthTexture(depthInfo: any, texture: Texture, depthPixelFormat: number): void; /** * @returns {XRLayer|null} Backend output layer (e.g. XRWebGLLayer), if any. */ get presentationLayer(): XRLayer | null; /** * Backend graphics binding for camera/depth when available (for example WebGL * `XRWebGLBinding` or WebGPU `XRGPUBinding` when exposed by the user agent). * * @returns {Object|null} The binding object, or null. */ get graphicsBinding(): any | null; } /** * @import { XrManager } from './xr-manager.js' */ /** * DOM Overlay provides the ability to use DOM elements as an overlay in a WebXR AR session. It * requires that the root DOM element is provided for session start. That way, input source * `select` events are first tested against DOM Elements and then propagated down to the XR * Session. If this propagation is not desirable, use the `beforexrselect` event on a DOM element * and the `preventDefault` function to stop propagation. * * ```javascript * app.xr.domOverlay.root = element; * app.xr.start(camera, XRTYPE_AR, XRSPACE_LOCALFLOOR); * ``` * * ```javascript * // Disable input source firing `select` event when some descendant element of DOM overlay root * // is touched/clicked. This is useful when the user interacts with UI elements and there should * // not be `select` events behind UI. * someElement.addEventListener('beforexrselect', (evt) => { * evt.preventDefault(); * }); * ``` * * @category XR */ declare class XrDomOverlay { /** * Create a new XrDomOverlay instance. * * @param {XrManager} manager - WebXR Manager. * @ignore */ constructor(manager: XrManager); /** * @type {XrManager} * @private */ private _manager; /** * @type {boolean} * @private */ private _supported; /** * @type {Element|null} * @private */ private _root; /** * True if DOM Overlay is supported. * * @type {boolean} */ get supported(): boolean; /** * True if DOM Overlay is available. This information becomes available only when the session has * started and a valid root DOM element has been provided. * * @type {boolean} */ get available(): boolean; /** * State of the DOM Overlay, which defines how the root DOM element is rendered. Can be: * * - `screen` - indicates that the DOM element is covering the whole physical screen, matching * XR viewports. * - `floating` - indicates that the underlying platform renders the DOM element as floating in * space, which can move during the WebXR session or allow the application to move the element. * - `head-locked` - indicates that the DOM element follows the user's head movement * consistently, appearing similar to a helmet heads-up display. * * @type {"screen"|"floating"|"head-locked"|null} */ get state(): "screen" | "floating" | "head-locked" | null; /** * Sets the DOM element to be used as the root for DOM Overlay. Can be changed only when the XR * session is not running. * * @type {Element|null} * @example * app.xr.domOverlay.root = element; * app.xr.start(camera, XRTYPE_AR, XRSPACE_LOCALFLOOR); */ set root(value: Element | null); /** * Gets the DOM element to be used as the root for DOM Overlay. * * @type {Element|null} */ get root(): Element | null; } /** * @import { XrHand } from './xr-hand.js' * @import { XrJoint } from './xr-joint.js' */ /** * Represents a finger of a tracked {@link XrHand} with related joints and index. * * @category XR */ declare class XrFinger { /** * Create a new XrFinger instance. * * @param {number} index - Index of the finger. * @param {XrHand} hand - Hand that the finger belongs to. * @ignore */ constructor(index: number, hand: XrHand); /** * @type {number} * @private */ private _index; /** * @type {XrHand} * @private */ private _hand; /** * @type {XrJoint[]} * @private */ private _joints; /** * @type {XrJoint|null} * @private */ private _tip; /** * Gets the index of the finger. Enumeration is: thumb, index, middle, ring, little. * * @type {number} */ get index(): number; /** * Gets the hand that the finger belongs to. * * @type {XrHand} */ get hand(): XrHand; /** * Array of joints that belong to this finger, starting from joint closest to wrist all the way * to the tip of a finger. * * @type {XrJoint[]} */ get joints(): XrJoint[]; /** * Tip joint of the finger, or null if not available. * * @type {XrJoint|null} */ get tip(): XrJoint | null; } /** * Represents the joint of a finger. * * @category XR */ declare class XrJoint { /** * Create an XrJoint instance. * * @param {number} index - Index of a joint within a finger. * @param {XRHandJoint} id - Id of a joint based on WebXR Hand Input Specs. * @param {XrHand} hand - Hand that joint relates to. * @param {XrFinger|null} finger - Finger that joint is related to. Can be null in the case of * the wrist joint. * @ignore */ constructor(index: number, id: XRHandJoint, hand: XrHand, finger?: XrFinger | null); /** * @type {number} * @private */ private _index; /** * @type {XRHandJoint} * @private */ private _id; /** * @type {XrHand} * @private */ private _hand; /** * @type {XrFinger|null} * @private */ private _finger; /** * @type {boolean} * @private */ private _wrist; /** * @type {boolean} * @private */ private _tip; /** * @type {number|null} * @private */ private _radius; /** @private */ private _localTransform; /** @private */ private _worldTransform; /** @private */ private _localPosition; /** @private */ private _localRotation; /** @private */ private _position; /** @private */ private _rotation; /** @private */ private _dirtyLocal; /** * @param {XRJointPose} pose - XRJointPose of this joint. * @ignore */ update(pose: XRJointPose): void; /** @private */ private _updateTransforms; /** * Get the world space position of a joint. * * @returns {Vec3} The world space position of a joint. */ getPosition(): Vec3; /** * Get the world space rotation of a joint. * * @returns {Quat} The world space rotation of a joint. */ getRotation(): Quat; /** * Id of a joint based on WebXR Hand Input Specs. * * @type {XRHandJoint} */ get id(): XRHandJoint; /** * Index of a joint within a finger, starting from 0 (root of a finger) all the way to tip of * the finger. * * @type {number} */ get index(): number; /** * Hand that joint relates to. * * @type {XrHand} */ get hand(): XrHand; /** * Finger that joint relates to. * * @type {XrFinger|null} */ get finger(): XrFinger | null; /** * True if joint is a wrist. * * @type {boolean} */ get wrist(): boolean; /** * True if joint is a tip of a finger. * * @type {boolean} */ get tip(): boolean; /** * The radius of a joint, which is a distance from joint to the edge of a skin. * * @type {number} */ get radius(): number; } /** * Represents a hand with fingers and joints. * * @category XR */ declare class XrHand extends EventHandler { /** * Fired when tracking becomes available. * * @event * @example * hand.on('tracking', () => { * console.log('Hand tracking is available'); * }); */ static EVENT_TRACKING: string; /** * Fired when tracking is lost. * * @event * @example * hand.on('trackinglost', () => { * console.log('Hand tracking is lost'); * }); */ static EVENT_TRACKINGLOST: string; /** * Represents a hand with fingers and joints. * * @param {XrInputSource} inputSource - Input Source that hand is related to. * @ignore */ constructor(inputSource: XrInputSource); /** * @type {XrManager} * @private */ private _manager; /** * @type {XrInputSource} * @private */ private _inputSource; /** @private */ private _tracking; /** * @type {XrFinger[]} * @private */ private _fingers; /** * @type {XrJoint[]} * @private */ private _joints; /** * @type {Object} * @private */ private _jointsById; /** * @type {XrJoint[]} * @private */ private _tips; /** * @type {XrJoint|null} * @private */ private _wrist; /** * @param {XRFrame} frame - XRFrame from requestAnimationFrame callback. * @ignore */ update(frame: XRFrame): void; /** * @param {number} index - Finger index. * @returns {boolean} True if finger is closed and false otherwise. * @private */ private _fingerIsClosed; /** * Returns joint by its XRHand id. * * @param {string} id - Id of a joint based on specs ID's in XRHand: https://immersive-web.github.io/webxr-hand-input/#skeleton-joints-section. * @returns {XrJoint|null} Joint or null if not available. */ getJointById(id: string): XrJoint | null; /** * Array of fingers of the hand. * * @type {XrFinger[]} */ get fingers(): XrFinger[]; /** * Array of joints in the hand. * * @type {XrJoint[]} */ get joints(): XrJoint[]; /** * Array of joints that are fingertips. * * @type {XrJoint[]} */ get tips(): XrJoint[]; /** * Wrist of a hand, or null if it is not available by WebXR underlying system. * * @type {XrJoint|null} */ get wrist(): XrJoint | null; /** * True if tracking is available, otherwise tracking might be lost. * * @type {boolean} */ get tracking(): boolean; } /** * Represents XR input source, which is any input mechanism which allows the user to perform * targeted actions in the same virtual space as the viewer. Example XR input sources include, but * are not limited to: handheld controllers, optically tracked hands, touch screen taps, and * gaze-based input methods that operate on the viewer's pose. * * @category XR */ declare class XrInputSource extends EventHandler { /** * Fired when {@link XrInputSource} is removed. * * @event * @example * inputSource.once('remove', () => { * // input source is not available anymore * }); */ static EVENT_REMOVE: string; /** * Fired when input source has triggered primary action. This could be pressing a trigger * button, or touching a screen. The handler is passed an * [XRInputSourceEvent](https://developer.mozilla.org/en-US/docs/Web/API/XRInputSourceEvent) * object from the WebXR API. * * @event * @example * const ray = new Ray(); * inputSource.on('select', (evt) => { * ray.set(inputSource.getOrigin(), inputSource.getDirection()); * if (obj.intersectsRay(ray)) { * // selected an object with input source * } * }); */ static EVENT_SELECT: string; /** * Fired when input source has started to trigger primary action. The handler is passed an * [XRInputSourceEvent](https://developer.mozilla.org/en-US/docs/Web/API/XRInputSourceEvent) * object from the WebXR API. * * @event * @example * inputSource.on('selectstart', (evt) => { * console.log('Select started'); * }); */ static EVENT_SELECTSTART: string; /** * Fired when input source has ended triggering primary action. The handler is passed an * [XRInputSourceEvent](https://developer.mozilla.org/en-US/docs/Web/API/XRInputSourceEvent) * object from the WebXR API. * * @event * @example * inputSource.on('selectend', (evt) => { * console.log('Select ended'); * }); */ static EVENT_SELECTEND: string; /** * Fired when input source has triggered squeeze action. This is associated with "grabbing" * action on the controllers. The handler is passed an * [XRInputSourceEvent](https://developer.mozilla.org/en-US/docs/Web/API/XRInputSourceEvent) * object from the WebXR API. * * @event * @example * inputSource.on('squeeze', (evt) => { * console.log('Squeeze'); * }); */ static EVENT_SQUEEZE: string; /** * Fired when input source has started to trigger squeeze action. The handler is passed an * [XRInputSourceEvent](https://developer.mozilla.org/en-US/docs/Web/API/XRInputSourceEvent) * object from the WebXR API. * * @event * @example * inputSource.on('squeezestart', (evt) => { * if (obj.containsPoint(inputSource.getPosition())) { * // grabbed an object * } * }); */ static EVENT_SQUEEZESTART: string; /** * Fired when input source has ended triggering squeeze action. The handler is passed an * [XRInputSourceEvent](https://developer.mozilla.org/en-US/docs/Web/API/XRInputSourceEvent) * object from the WebXR API. * * @event * @example * inputSource.on('squeezeend', (evt) => { * console.log('Squeeze ended'); * }); */ static EVENT_SQUEEZEEND: string; /** * Fired when new {@link XrHitTestSource} is added to the input source. The handler is passed * the {@link XrHitTestSource} object that has been added. * * @event * @example * inputSource.on('hittest:add', (hitTestSource) => { * // new hit test source is added * }); */ static EVENT_HITTESTADD: string; /** * Fired when {@link XrHitTestSource} is removed from the input source. The handler is passed * the {@link XrHitTestSource} object that has been removed. * * @event * @example * inputSource.on('hittest:remove', (hitTestSource) => { * // hit test source is removed * }); */ static EVENT_HITTESTREMOVE: string; /** * Fired when hit test source receives new results. It provides transform information that * tries to match real world picked geometry. The handler is passed the {@link XrHitTestSource} * object that produced the hit result, the {@link Vec3} position, the {@link Quat} * rotation and the [XRHitTestResult](https://developer.mozilla.org/en-US/docs/Web/API/XRHitTestResult) * object that is created by the WebXR API. * * @event * @example * inputSource.on('hittest:result', (hitTestSource, position, rotation, hitTestResult) => { * target.setPosition(position); * target.setRotation(rotation); * }); */ static EVENT_HITTESTRESULT: string; /** * Create a new XrInputSource instance. * * @param {XrManager} manager - WebXR Manager. * @param {XRInputSource} xrInputSource - A WebXR input source. * @ignore */ constructor(manager: XrManager, xrInputSource: XRInputSource); /** * @type {number} * @private */ private _id; /** * @type {XrManager} * @private */ private _manager; /** * @type {XRInputSource} * @private */ private _xrInputSource; /** @private */ private _ray; /** @private */ private _rayLocal; /** @private */ private _grip; /** * @type {XrHand|null} * @private */ private _hand; /** @private */ private _velocitiesAvailable; /** @private */ private _velocitiesTimestamp; /** * @type {Mat4|null} * @private */ private _localTransform; /** * @type {Mat4|null} * @private */ private _worldTransform; /** @private */ private _position; /** @private */ private _rotation; /** * @type {Vec3|null} * @private */ private _localPosition; /** * @type {Vec3|null} * @private */ private _localPositionLast; /** * @type {Quat|null} * @private */ private _localRotation; /** * @type {Vec3|null} * @private */ private _linearVelocity; /** * Linear velocity relative to the parent of the XR camera. * * @type {Vec3|null} * @private */ private _localLinearVelocity; /** @private */ private _dirtyLocal; /** @private */ private _dirtyRay; /** @private */ private _selecting; /** @private */ private _squeezing; /** @private */ private _elementInput; /** * @type {Entity|null} * @private */ private _elementEntity; /** * @type {XrHitTestSource[]} * @private */ private _hitTestSources; /** * Unique number associated with instance of input source. Same physical devices when * reconnected will not share this ID. * * @type {number} */ get id(): number; /** * XRInputSource object that is associated with this input source. * * @type {XRInputSource} */ get inputSource(): XRInputSource; /** * Type of ray Input Device is based on. Can be one of the following: * * - {@link XRTARGETRAY_GAZE}: Gaze - indicates the target ray will originate at the viewer and * follow the direction it is facing. This is commonly referred to as a "gaze input" device in * the context of head-mounted displays. * - {@link XRTARGETRAY_SCREEN}: Screen - indicates that the input source was an interaction * with the canvas element associated with an inline session's output context, such as a mouse * click or touch event. * - {@link XRTARGETRAY_POINTER}: Tracked Pointer - indicates that the target ray originates * from either a handheld device or other hand-tracking mechanism and represents that the user * is using their hands or the held device for pointing. * * @type {string} */ get targetRayMode(): string; /** * Describes which hand input source is associated with. Can be one of the following: * * - {@link XRHAND_NONE}: None - input source is not meant to be held in hands. * - {@link XRHAND_LEFT}: Left - indicates that input source is meant to be held in left hand. * - {@link XRHAND_RIGHT}: Right - indicates that input source is meant to be held in right * hand. * * @type {string} */ get handedness(): string; /** * List of input profile names indicating both the preferred visual representation and behavior * of the input source. * * @type {string[]} */ get profiles(): string[]; /** * If input source can be held, then it will have node with its world transformation, that can * be used to position and rotate visual object based on it. * * @type {boolean} */ get grip(): boolean; /** * If input source is a tracked hand, then it will point to {@link XrHand} otherwise it is * null. * * @type {XrHand|null} */ get hand(): XrHand | null; /** * If input source has buttons, triggers, thumbstick or touchpad, then this object provides * access to its states. * * @type {Gamepad|null} */ get gamepad(): Gamepad | null; /** * True if input source is in active primary action between selectstart and selectend events. * * @type {boolean} */ get selecting(): boolean; /** * True if input source is in active squeeze action between squeezestart and squeezeend events. * * @type {boolean} */ get squeezing(): boolean; /** * Sets whether the input source can interact with {@link ElementComponent}s. Defaults to true. * * @type {boolean} */ set elementInput(value: boolean); /** * Gets whether the input source can interact with {@link ElementComponent}s. * * @type {boolean} */ get elementInput(): boolean; /** * If {@link elementInput} is true, this property will hold entity with Element * component at which this input source is hovering, or null if not hovering over any element. * * @type {Entity|null} */ get elementEntity(): Entity | null; /** * List of active {@link XrHitTestSource} instances associated with this input source. * * @type {XrHitTestSource[]} */ get hitTestSources(): XrHitTestSource[]; /** * @param {XRFrame} frame - XRFrame from requestAnimationFrame callback. * @ignore */ update(frame: XRFrame): void; /** @private */ private _updateTransforms; /** @private */ private _updateRayTransforms; /** * Get the world space position of input source if it is handheld ({@link grip} is true). * Otherwise it will return null. * * @returns {Vec3|null} The world space position of handheld input source. */ getPosition(): Vec3 | null; /** * Get the local space position of input source if it is handheld ({@link grip} is true). Local * space is relative to parent of the XR camera. Otherwise it will return null. * * @returns {Vec3|null} The local space position of handheld input source. */ getLocalPosition(): Vec3 | null; /** * Get the world space rotation of input source if it is handheld ({@link grip} is true). * Otherwise it will return null. * * @returns {Quat|null} The world space rotation of handheld input source. */ getRotation(): Quat | null; /** * Get the local space rotation of input source if it is handheld ({@link grip} is true). Local * space is relative to parent of the XR camera. Otherwise it will return null. * * @returns {Quat|null} The local space rotation of handheld input source. */ getLocalRotation(): Quat | null; /** * Get the linear velocity (units per second) of the input source if it is handheld * ({@link grip} is true). Otherwise it will return null. The velocity is relative to the * parent of the XR camera, so it does not include the motion of the parent. * * @returns {Vec3|null} The world space linear velocity of the handheld input source. */ getLinearVelocity(): Vec3 | null; /** * Get the world space origin of input source ray. * * @returns {Vec3} The world space origin of input source ray. */ getOrigin(): Vec3; /** * Get the world space direction of input source ray. * * @returns {Vec3} The world space direction of input source ray. */ getDirection(): Vec3; /** * Attempts to start hit test source based on this input source. * * @param {object} [options] - Object for passing optional arguments. * @param {string[]} [options.entityTypes] - Optional list of underlying entity types against * which hit tests will be performed. Defaults to [{@link XRTRACKABLE_PLANE}]. Can be any * combination of the following: * * - {@link XRTRACKABLE_POINT}: Point - indicates that the hit test results will be computed * based on the feature points detected by the underlying Augmented Reality system. * - {@link XRTRACKABLE_PLANE}: Plane - indicates that the hit test results will be computed * based on the planes detected by the underlying Augmented Reality system. * - {@link XRTRACKABLE_MESH}: Mesh - indicates that the hit test results will be computed * based on the meshes detected by the underlying Augmented Reality system. * * @param {Ray} [options.offsetRay] - Optional ray by which hit test ray can be offset. * @param {XrHitTestStartCallback} [options.callback] - Optional callback function called once * hit test source is created or failed. * @example * app.xr.input.on('add', (inputSource) => { * inputSource.hitTestStart({ * callback: (err, hitTestSource) => { * if (err) return; * hitTestSource.on('result', (position, rotation, inputSource, hitTestResult) => { * // position and rotation of hit test result * // that will be created from touch on mobile devices * }); * } * }); * }); */ hitTestStart(options?: { entityTypes?: string[]; offsetRay?: Ray; callback?: XrHitTestStartCallback; }): void; /** * @param {XrHitTestSource} hitTestSource - Hit test source to be added. * @private */ private onHitTestSourceAdd; /** * @param {XrHitTestSource} hitTestSource - Hit test source to be removed. * @private */ private onHitTestSourceRemove; /** * Gets the local space ray of the input source. * * @type {Ray} * @ignore * @deprecated Use {@link XrInputSource#getOrigin} and {@link XrInputSource#getDirection} instead. */ get ray(): Ray; /** * Gets the local space position of the input source. * * @type {Vec3|null} * @ignore * @deprecated Use {@link XrInputSource#getLocalPosition} instead. */ get position(): Vec3 | null; /** * Gets the local space rotation of the input source. * * @type {Quat|null} * @ignore * @deprecated Use {@link XrInputSource#getLocalRotation} instead. */ get rotation(): Quat | null; } /** * Represents XR hit test source, which provides access to hit results of real world geometry from * AR session. * * ```javascript * // start a hit test from a viewer origin forward * app.xr.hitTest.start({ * spaceType: XRSPACE_VIEWER, * callback: (err, hitTestSource) => { * if (err) return; * // subscribe to hit test results * hitTestSource.on('result', (position, rotation, inputSource, hitTestResult) => { * // position and rotation of hit test result * }); * } * }); * ``` * * @category XR */ declare class XrHitTestSource extends EventHandler { /** * Fired when {@link XrHitTestSource} is removed. * * @event * @example * hitTestSource.once('remove', () => { * // hit test source has been removed * }); */ static EVENT_REMOVE: string; /** * Fired when the hit test source receives new results. It provides transform information that * tries to match real world geometry. Callback provides the {@link Vec3} position, the * {@link Quat} rotation, the {@link XrInputSource} (if it is a transient hit test source) * and the [XRHitTestResult](https://developer.mozilla.org/en-US/docs/Web/API/XRHitTestResult) * object that is created by WebXR API. * * @event * @example * hitTestSource.on('result', (position, rotation, inputSource, hitTestResult) => { * target.setPosition(position); * target.setRotation(rotation); * }); */ static EVENT_RESULT: string; /** * Create a new XrHitTestSource instance. * * @param {XrManager} manager - WebXR Manager. * @param {XRHitTestSource} xrHitTestSource - XRHitTestSource object that is created by WebXR API. * @param {boolean} transient - True if XRHitTestSource created for input source profile. * @param {null|XrInputSource} inputSource - Input Source for which hit test is created for, or null. * @ignore */ constructor(manager: XrManager, xrHitTestSource: XRHitTestSource, transient: boolean, inputSource?: null | XrInputSource); /** * @type {XrManager} * @private */ private manager; /** * @type {XRHitTestSource} * @private */ private _xrHitTestSource; /** * @type {boolean} * @private */ private _transient; /** * @type {null|XrInputSource} * @private */ private _inputSource; /** * Stop and remove hit test source. */ remove(): void; /** @ignore */ onStop(): void; /** * @param {XRFrame} frame - XRFrame from requestAnimationFrame callback. * @ignore */ update(frame: XRFrame): void; /** * @param {XRTransientInputHitTestResult[]} results - Hit test results. * @param {null|XrInputSource} inputSource - Input source. * @private */ private updateHitResults; } /** * Callback used by {@link XrHitTest#start} and {@link XrInputSource#hitTestStart}. */ type XrHitTestStartCallback = (err: Error | null, hitTestSource: XrHitTestSource | null) => void; /** * @import { Ray } from '../../core/shape/ray.js' * @import { XrInputSource } from './xr-input-source.js' * @import { XrManager } from './xr-manager.js' */ /** * @callback XrHitTestStartCallback * Callback used by {@link XrHitTest#start} and {@link XrInputSource#hitTestStart}. * @param {Error|null} err - The Error object if failed to create hit test source or null. * @param {XrHitTestSource|null} hitTestSource - Object that provides access to hit results against * real world geometry. * @returns {void} */ /** * The Hit Test interface allows initiating hit testing against real-world geometry from various * sources: the view, input sources, or an arbitrary ray in space. Results reflect the underlying * AR system's understanding of the real world. * * @category XR */ declare class XrHitTest extends EventHandler { /** * Fired when hit test becomes available. * * @event * @example * app.xr.hitTest.on('available', () => { * console.log('Hit Testing is available'); * }); */ static EVENT_AVAILABLE: string; /** * Fired when hit test becomes unavailable. * * @event * @example * app.xr.hitTest.on('unavailable', () => { * console.log('Hit Testing is unavailable'); * }); */ static EVENT_UNAVAILABLE: string; /** * Fired when new {@link XrHitTestSource} is added to the list. The handler is passed the * {@link XrHitTestSource} object that has been added. * * @event * @example * app.xr.hitTest.on('add', (hitTestSource) => { * // new hit test source is added * }); */ static EVENT_ADD: string; /** * Fired when {@link XrHitTestSource} is removed to the list. The handler is passed the * {@link XrHitTestSource} object that has been removed. * * @event * @example * app.xr.hitTest.on('remove', (hitTestSource) => { * // hit test source is removed * }); */ static EVENT_REMOVE: string; /** * Fired when hit test source receives new results. It provides transform information that * tries to match real world picked geometry. The handler is passed the {@link XrHitTestSource} * that produced the hit result, the {@link Vec3} position, the {@link Quat} rotation and the * {@link XrInputSource} (if it is a transient hit test source). * * @event * @example * app.xr.hitTest.on('result', (hitTestSource, position, rotation, inputSource) => { * target.setPosition(position); * target.setRotation(rotation); * }); */ static EVENT_RESULT: string; /** * Fired when failed create hit test source. The handler is passed the Error object. * * @event * @example * app.xr.hitTest.on('error', (err) => { * console.error(err.message); * }); */ static EVENT_ERROR: string; /** * Create a new XrHitTest instance. * * @param {XrManager} manager - WebXR Manager. * @ignore */ constructor(manager: XrManager); /** * @type {XrManager} * @private */ private manager; /** * @type {boolean} * @private */ private _supported; /** @private */ private _available; /** @private */ private _checkingAvailability; /** * List of active {@link XrHitTestSource}. * * @type {XrHitTestSource[]} */ sources: XrHitTestSource[]; /** @private */ private _onSessionStart; /** @private */ private _onSessionEnd; /** * Attempts to start hit test with provided reference space. * * @param {object} [options] - Optional object for passing arguments. * @param {string} [options.spaceType] - Reference space type. Defaults to * {@link XRSPACE_VIEWER}. Can be one of the following: * * - {@link XRSPACE_VIEWER}: Viewer - hit test will be facing relative to viewers space. * - {@link XRSPACE_LOCAL}: Local - represents a tracking space with a native origin near the * viewer at the time of creation. * - {@link XRSPACE_LOCALFLOOR}: Local Floor - represents a tracking space with a native origin * at the floor in a safe position for the user to stand. The y axis equals 0 at floor level. * Floor level value might be estimated by the underlying platform. * - {@link XRSPACE_BOUNDEDFLOOR}: Bounded Floor - represents a tracking space with its native * origin at the floor, where the user is expected to move within a pre-established boundary. * - {@link XRSPACE_UNBOUNDED}: Unbounded - represents a tracking space where the user is * expected to move freely around their environment, potentially long distances from their * starting point. * * @param {string} [options.profile] - if hit test source meant to match input source instead * of reference space, then name of profile of the {@link XrInputSource} should be provided. * @param {string[]} [options.entityTypes] - Optional list of underlying entity types against * which hit tests will be performed. Defaults to [ {@link XRTRACKABLE_PLANE} ]. Can be any * combination of the following: * * - {@link XRTRACKABLE_POINT}: Point - indicates that the hit test results will be computed * based on the feature points detected by the underlying Augmented Reality system. * - {@link XRTRACKABLE_PLANE}: Plane - indicates that the hit test results will be computed * based on the planes detected by the underlying Augmented Reality system. * - {@link XRTRACKABLE_MESH}: Mesh - indicates that the hit test results will be computed * based on the meshes detected by the underlying Augmented Reality system. * * @param {Ray} [options.offsetRay] - Optional ray by which * hit test ray can be offset. * @param {XrHitTestStartCallback} [options.callback] - Optional callback function called once * hit test source is created or failed. * @example * // start hit testing from viewer position facing forwards * app.xr.hitTest.start({ * spaceType: XRSPACE_VIEWER, * callback: (err, hitTestSource) => { * if (err) return; * hitTestSource.on('result', (position, rotation) => { * // position and rotation of hit test result * }); * } * }); * @example * // start hit testing using an arbitrary ray * const ray = new Ray(new Vec3(0, 0, 0), new Vec3(0, -1, 0)); * app.xr.hitTest.start({ * spaceType: XRSPACE_LOCAL, * offsetRay: ray, * callback: (err, hitTestSource) => { * // hit test source that will sample real world geometry straight down * // from the position where AR session started * } * }); * @example * // start hit testing for touch screen taps * app.xr.hitTest.start({ * profile: 'generic-touchscreen', * callback: (err, hitTestSource) => { * if (err) return; * hitTestSource.on('result', (position, rotation, inputSource) => { * // position and rotation of hit test result * // that will be created from touch on mobile devices * }); * } * }); */ start(options?: { spaceType?: string; profile?: string; entityTypes?: string[]; offsetRay?: Ray; callback?: XrHitTestStartCallback; }): void; /** * @param {XRHitTestSource} xrHitTestSource - Hit test source. * @param {boolean} transient - True if hit test source is created from transient input source. * @param {XrInputSource|null} inputSource - Input Source with which hit test source is associated with. * @param {Function} callback - Callback called once hit test source is created. * @private */ private _onHitTestSource; /** * @param {XRFrame} frame - XRFrame from requestAnimationFrame callback. * @ignore */ update(frame: XRFrame): void; /** * True if AR Hit Test is supported. * * @type {boolean} */ get supported(): boolean; /** * True if Hit Test is available. This information is available only when the session has started. * * @type {boolean} */ get available(): boolean; } /** * The tracked image interface that is created by the Image Tracking system and is provided as a * list from {@link XrImageTracking#images}. It contains information about the tracking state as * well as the position and rotation of the tracked image. * * @category XR */ declare class XrTrackedImage extends EventHandler { /** * Fired when image becomes actively tracked. * * @event * @example * trackedImage.on('tracked', () => { * console.log('Image is now tracked'); * }); */ static EVENT_TRACKED: string; /** * Fired when image is no longer actively tracked. * * @event * @example * trackedImage.on('untracked', () => { * console.log('Image is no longer tracked'); * }); */ static EVENT_UNTRACKED: string; /** * Create a new XrTrackedImage instance. * * @param {HTMLCanvasElement|HTMLImageElement|SVGImageElement|HTMLVideoElement|Blob|ImageData|ImageBitmap} image - Image * that is matching the real world image as closely as possible. Resolution of images should be * at least 300x300. High resolution does NOT improve tracking performance. Color of image is * irrelevant, so grayscale images can be used. Images with too many geometric features or * repeating patterns will reduce tracking stability. * @param {number} width - Width (in meters) of image in real world. Providing this value as * close to the real value will improve tracking quality. * @ignore */ constructor(image: HTMLCanvasElement | HTMLImageElement | SVGImageElement | HTMLVideoElement | Blob | ImageData | ImageBitmap, width: number); /** * @type {HTMLCanvasElement|HTMLImageElement|SVGImageElement|HTMLVideoElement|Blob|ImageData|ImageBitmap} * @private */ private _image; /** * @type {number} * @private */ private _width; /** * @type {ImageBitmap|null} * @private */ private _bitmap; /** @ignore */ _measuredWidth: number; /** @private */ private _trackable; /** @private */ private _tracking; /** @private */ private _emulated; /** * @type {XRPose|null} * @ignore */ _pose: XRPose | null; /** @private */ private _position; /** @private */ private _rotation; /** * Image that is used for tracking. * * @type {HTMLCanvasElement|HTMLImageElement|SVGImageElement|HTMLVideoElement|Blob|ImageData|ImageBitmap} */ get image(): HTMLCanvasElement | HTMLImageElement | SVGImageElement | HTMLVideoElement | Blob | ImageData | ImageBitmap; /** * Width that is provided to assist tracking performance. This property can be updated only * when the AR session is not running. * * @type {number} */ set width(value: number); /** * Get the width (in meters) of image in real world. * * @type {number} */ get width(): number; /** * True if image is trackable. A too small resolution or invalid images can be untrackable by * the underlying AR system. * * @type {boolean} */ get trackable(): boolean; /** * True if image is in tracking state and being tracked in real world by the underlying AR * system. * * @type {boolean} */ get tracking(): boolean; /** * True if image was recently tracked but currently is not actively tracked due to inability of * identifying the image by the underlying AR system. Position and rotation will be based on * the previously known transformation assuming the tracked image has not moved. * * @type {boolean} */ get emulated(): boolean; /** * @returns {Promise} Promise that resolves to an image bitmap. * @ignore */ prepare(): Promise; /** * Destroys the tracked image. * * @ignore */ destroy(): void; /** * Get the world position of the tracked image. * * @returns {Vec3} Position in world space. * @example * // update entity position to match tracked image position * entity.setPosition(trackedImage.getPosition()); */ getPosition(): Vec3; /** * Get the world rotation of the tracked image. * * @returns {Quat} Rotation in world space. * @example * // update entity rotation to match tracked image rotation * entity.setRotation(trackedImage.getRotation()); */ getRotation(): Quat; } /** * @import { XrManager } from './xr-manager.js' */ /** * Image Tracking provides the ability to track real world images using provided image samples and * their estimated sizes. The underlying system will assume that the tracked image can move and * rotate in the real world and will try to provide transformation estimates and its tracking * state. * * @category XR */ declare class XrImageTracking extends EventHandler { /** * Fired when the XR session is started, but image tracking failed to process the provided * images. The handler is passed the Error object. * * @event * @example * app.xr.imageTracking.on('error', (err) => { * console.error(err.message); * }); */ static EVENT_ERROR: string; /** * Create a new XrImageTracking instance. * * @param {XrManager} manager - WebXR Manager. * @ignore */ constructor(manager: XrManager); /** * @type {XrManager} * @private */ private _manager; /** * @type {boolean} * @private */ private _supported; /** @private */ private _available; /** * @type {XrTrackedImage[]} * @private */ private _images; /** * Add an image for image tracking. A width can also be provided to help the underlying system * estimate the appropriate transformation. Modifying the tracked images list is only possible * before an AR session is started. * * @param {HTMLCanvasElement|HTMLImageElement|SVGImageElement|HTMLVideoElement|Blob|ImageData|ImageBitmap} image * Image that is matching real world image as close as possible. Resolution of images should be * at least 300x300. High resolution does _not_ improve tracking performance. The color of the * image is irrelevant, so grayscale images can be used. Images with too many geometric * features or repeating patterns will reduce tracking stability. * @param {number} width - Width (in meters) of image in the real world. Providing this value * as close to the real value will improve tracking quality. * @returns {XrTrackedImage|null} Tracked image object that will contain tracking information. * Returns null if image tracking is not supported or if the XR manager is not active. * @example * // image of a book cover that has width of 20cm (0.2m) * app.xr.imageTracking.add(bookCoverImg, 0.2); */ add(image: HTMLCanvasElement | HTMLImageElement | SVGImageElement | HTMLVideoElement | Blob | ImageData | ImageBitmap, width: number): XrTrackedImage | null; /** * Remove an image from image tracking. * * @param {XrTrackedImage} trackedImage - Tracked image to be removed. Modifying the tracked * images list is only possible before an AR session is started. */ remove(trackedImage: XrTrackedImage): void; /** @private */ private _onSessionStart; /** @private */ private _onSessionEnd; /** * @param {Function} callback - Function to call when all images have been prepared as image * bitmaps. * @ignore */ prepareImages(callback: Function): void; /** * @param {XRFrame} frame - XRFrame from requestAnimationFrame callback. * @ignore */ update(frame: XRFrame): void; /** * True if Image Tracking is supported. * * @type {boolean} */ get supported(): boolean; /** * True if Image Tracking is available. This information is only available when the * XR session has started, and will be true if image tracking is supported and * images were provided and they have been processed successfully. * * @type {boolean} */ get available(): boolean; /** * List of {@link XrTrackedImage} that contain tracking information. * * @type {XrTrackedImage[]} */ get images(): XrTrackedImage[]; } /** * Represents a detected plane in the real world, providing its position, rotation, polygon points, * and semantic label. The plane data may change over time as the system updates its understanding * of the environment. Instances of this class are created and managed by the * {@link XrPlaneDetection} system. * * @category XR */ declare class XrPlane extends EventHandler { /** * Fired when an {@link XrPlane} is removed. Its attributes, such as its points and label, keep * their last values. * * @event * @example * plane.once('remove', () => { * // plane is not available anymore * }); */ static EVENT_REMOVE: string; /** * Fired when {@link XrPlane} attributes such as: orientation and/or points have been changed. * Position and rotation can change at any time without triggering a `change` event. * * @event * @example * plane.on('change', () -> { * // plane has been changed * }); */ static EVENT_CHANGE: string; /** * Create a new XrPlane instance. * * @param {XrPlaneDetection} planeDetection - Plane detection system. * @param {*} xrPlane - XRPlane that is instantiated by WebXR system. * @ignore */ constructor(planeDetection: XrPlaneDetection, xrPlane: any); /** * @type {number} * @private */ private _id; /** * @type {XrPlaneDetection} * @private */ private _planeDetection; /** * @type {XRPlane} * @private */ private _xrPlane; /** * @type {number} * @private */ private _lastChangedTime; /** @private */ private _destroyed; /** @private */ private _position; /** @private */ private _rotation; /** @ignore */ destroy(): void; /** * @param {XRFrame} frame - XRFrame from requestAnimationFrame callback. * @ignore */ update(frame: XRFrame): void; /** * Get the world space position of a plane. * * @returns {Vec3} The world space position of a plane. */ getPosition(): Vec3; /** * Get the world space rotation of a plane. * * @returns {Quat} The world space rotation of a plane. */ getRotation(): Quat; /** * Unique identifier of a plane. * * @type {number} */ get id(): number; /** * Gets the plane's specific orientation. This can be "horizontal" for planes that are parallel * to the ground, "vertical" for planes that are perpendicular to the ground, or `null` if the * orientation is different or unknown. * * @type {"horizontal"|"vertical"|null} * @example * if (plane.orientation === 'horizontal') { * console.log('This plane is horizontal.'); * } else if (plane.orientation === 'vertical') { * console.log('This plane is vertical.'); * } else { * console.log('Orientation of this plane is unknown or different.'); * } */ get orientation(): "horizontal" | "vertical" | null; /** * Gets the array of points that define the polygon of the plane in its local coordinate space. * Each point is represented as a `DOMPointReadOnly` object with `x`, `y`, and `z` properties. * These points can be transformed to world coordinates using the plane's position and * rotation. * * @type {DOMPointReadOnly[]} * @example * // prepare reusable objects * const transform = new Mat4(); * const vecA = new Vec3(); * const vecB = new Vec3(); * * // update Mat4 to plane position and rotation * transform.setTRS(plane.getPosition(), plane.getRotation(), Vec3.ONE); * * // draw lines between points * for (let i = 0; i < plane.points.length; i++) { * vecA.copy(plane.points[i]); * vecB.copy(plane.points[(i + 1) % plane.points.length]); * * // transform points to world space * transform.transformPoint(vecA, vecA); * transform.transformPoint(vecB, vecB); * * // render line * app.drawLine(vecA, vecB, Color.WHITE); * } */ get points(): DOMPointReadOnly[]; /** * Gets the semantic label of the plane provided by the underlying system. The label describes * the type of surface the plane represents, such as "floor", "wall", "ceiling", etc. The list * of possible labels can be found in the [semantic labels repository](https://github.com/immersive-web/semantic-labels). * * @type {string} * @example * if (plane.label === 'floor') { * console.log('This plane represents the floor.'); * } else if (plane.label === 'wall') { * console.log('This plane represents a wall.'); * } */ get label(): string; } /** * @import { XrManager } from './xr-manager.js' */ /** * Plane Detection provides the ability to detect real world surfaces based on estimations of the * underlying AR system. * * ```javascript * // start session with plane detection enabled * app.xr.start(camera, XRTYPE_VR, XRSPACE_LOCALFLOOR, { * planeDetection: true * }); * ``` * * ```javascript * app.xr.planeDetection.on('add', (plane) => { * // new plane been added * }); * ``` * * @category XR */ declare class XrPlaneDetection extends EventHandler { /** * Fired when plane detection becomes available. * * @event * @example * app.xr.planeDetection.on('available', () => { * console.log('Plane detection is available'); * }); */ static EVENT_AVAILABLE: string; /** * Fired when plane detection becomes unavailable. * * @event * @example * app.xr.planeDetection.on('unavailable', () => { * console.log('Plane detection is unavailable'); * }); */ static EVENT_UNAVAILABLE: string; /** * Fired when new {@link XrPlane} is added to the list. The handler is passed the * {@link XrPlane} instance that has been added. * * @event * @example * app.xr.planeDetection.on('add', (plane) => { * // new plane is added * }); */ static EVENT_ADD: string; /** * Fired when a {@link XrPlane} is removed from the list. The handler is passed the * {@link XrPlane} instance that has been removed. * * @event * @example * app.xr.planeDetection.on('remove', (plane) => { * // new plane is removed * }); */ static EVENT_REMOVE: string; /** * Create a new XrPlaneDetection instance. * * @param {XrManager} manager - WebXR Manager. * @ignore */ constructor(manager: XrManager); /** * @type {XrManager} * @private */ private _manager; /** * @type {boolean} * @private */ private _supported; /** @private */ private _available; /** * @type {Map} * @private */ private _planesIndex; /** * @type {XrPlane[]} * @private */ private _planes; /** @private */ private _onSessionStart; /** @private */ private _onSessionEnd; /** * @param {XRFrame} frame - XRFrame from requestAnimationFrame callback. * @ignore */ update(frame: XRFrame): void; /** * True if Plane Detection is supported. * * @type {boolean} */ get supported(): boolean; /** * True if Plane Detection is available. This information is available only when the session has started. * * @type {boolean} */ get available(): boolean; /** * Array of {@link XrPlane} instances that contain individual plane information. * * @type {XrPlane[]} */ get planes(): XrPlane[]; } /** * @import { XrMeshDetection } from './xr-mesh-detection.js' */ /** * Detected Mesh instance that provides its transform (position, rotation), triangles (vertices, * indices) and its semantic label. Any of its properties can change during its lifetime. * * @category XR */ declare class XrMesh extends EventHandler { /** * Fired when an {@link XrMesh} is removed. Its attributes, such as its vertices and label, * keep their last values. * * @event * @example * mesh.once('remove', () => { * // mesh is no longer available * }); */ static EVENT_REMOVE: string; /** * Fired when {@link XrMesh} attributes such as vertices, indices and/or label have been * changed. Position and rotation can change at any time without triggering a `change` event. * * @event * @example * mesh.on('change', () => { * // mesh attributes have been changed * }); */ static EVENT_CHANGE: string; /** * Create a new XrMesh instance. * * @param {XrMeshDetection} meshDetection - Mesh Detection * interface. * @param {XRMesh} xrMesh - XRMesh that is instantiated by WebXR system. * @ignore */ constructor(meshDetection: XrMeshDetection, xrMesh: XRMesh); /** * @type {XrMeshDetection} * @private */ private _meshDetection; /** * @type {XRMesh} * @private */ private _xrMesh; /** @private */ private _lastChanged; /** @private */ private _destroyed; /** @private */ private _position; /** @private */ private _rotation; /** * @type {XRMesh} * @ignore */ get xrMesh(): XRMesh; /** * Semantic Label of a mesh that is provided by underlying system. Current list includes (but * not limited to): https://github.com/immersive-web/semantic-labels/blob/master/labels.json * * @type {string} */ get label(): string; /** * Array of mesh vertices. This array contains 3 components per vertex (`x, y, z`). * * @type {Float32Array} */ get vertices(): Float32Array; /** * Array of mesh indices. * * @type {Uint32Array} */ get indices(): Uint32Array; /** @ignore */ destroy(): void; /** * @param {XRFrame} frame - XRFrame from requestAnimationFrame callback. * @ignore */ update(frame: XRFrame): void; /** * Get the world space position of a mesh. * * @returns {Vec3} The world space position of a mesh. */ getPosition(): Vec3; /** * Get the world space rotation of a mesh. * * @returns {Quat} The world space rotation of a mesh. */ getRotation(): Quat; } /** * @import { XrManager } from './xr-manager.js' */ /** * Mesh Detection provides the ability to detect real world meshes based on the * scanning and reconstruction by the underlying AR system. * * ```javascript * // start session with plane detection enabled * app.xr.start(camera, XRTYPE_AR, XRSPACE_LOCALFLOOR, { * meshDetection: true * }); * ``` * * ```javascript * app.xr.meshDetection.on('add', (mesh) => { * // new mesh been added * }); * ``` * * @category XR */ declare class XrMeshDetection extends EventHandler { /** * Fired when mesh detection becomes available. * * @event * @example * app.xr.meshDetection.on('available', () => { * console.log('Mesh detection is available'); * }); */ static EVENT_AVAILABLE: string; /** * Fired when mesh detection becomes unavailable. * * @event * @example * app.xr.meshDetection.on('unavailable', () => { * console.log('Mesh detection is unavailable'); * }); */ static EVENT_UNAVAILABLE: string; /** * Fired when new {@link XrMesh} is added to the list. The handler is passed the {@link XrMesh} * instance that has been added. * * @event * @example * app.xr.meshDetection.on('add', (mesh) => { * // a new XrMesh has been added * }); */ static EVENT_ADD: string; /** * Fired when a {@link XrMesh} is removed from the list. The handler is passed the * {@link XrMesh} instance that has been removed. * * @event * @example * app.xr.meshDetection.on('remove', (mesh) => { * // XrMesh has been removed * }); */ static EVENT_REMOVE: string; /** * Create a new XrMeshDetection instance. * * @param {XrManager} manager - WebXR Manager. * @ignore */ constructor(manager: XrManager); /** * @type {XrManager} * @private */ private _manager; /** * @type {boolean} * @private */ private _supported; /** @private */ private _available; /** * @type {Map} * @private */ private _index; /** * @type {XrMesh[]} * @private */ private _list; /** * @param {XRFrame} frame - XRFrame from requestAnimationFrame callback. * @ignore */ update(frame: XRFrame): void; /** * @param {XrMesh} mesh - XrMesh to remove. * @private */ private _removeMesh; /** @private */ private _onSessionStart; /** @private */ private _onSessionEnd; /** * True if Mesh Detection is supported. * * @type {boolean} */ get supported(): boolean; /** * True if Mesh Detection is available. This information is available only when session has started. * * @type {boolean} */ get available(): boolean; /** * Array of {@link XrMesh} instances that contain transform, vertices and label information. * * @type {XrMesh[]} */ get meshes(): XrMesh[]; } /** * @import { XrManager } from './xr-manager.js' */ /** * Provides access to input sources for WebXR. * * Input sources represent: * * - hand held controllers - and their optional capabilities: gamepad and vibration * - hands - with their individual joints * - transient sources - such as touch screen taps and voice commands * * @category XR */ declare class XrInput extends EventHandler { /** * Fired when a new {@link XrInputSource} is added to the list. The handler is passed the * {@link XrInputSource} that has been added. * * @event * @example * app.xr.input.on('add', (inputSource) => { * // new input source is added * }); */ static EVENT_ADD: string; /** * Fired when an {@link XrInputSource} is removed from the list. The handler is passed the * {@link XrInputSource} that has been removed. * * @event * @example * app.xr.input.on('remove', (inputSource) => { * // input source is removed * }); */ static EVENT_REMOVE: string; /** * Fired when {@link XrInputSource} has triggered primary action. This could be pressing a * trigger button, or touching a screen. The handler is passed the {@link XrInputSource} that * triggered the `select` event and the XRInputSourceEvent event from the WebXR API. * * @event * @example * const ray = new Ray(); * app.xr.input.on('select', (inputSource, evt) => { * ray.set(inputSource.getOrigin(), inputSource.getDirection()); * if (obj.intersectsRay(ray)) { * // selected an object with input source * } * }); */ static EVENT_SELECT: string; /** * Fired when {@link XrInputSource} has started to trigger primary action. The handler is * passed the {@link XrInputSource} that triggered the `selectstart` event and the * XRInputSourceEvent event from the WebXR API. * * @event * @example * app.xr.input.on('selectstart', (inputSource, evt) => { * console.log('Select started'); * }); */ static EVENT_SELECTSTART: string; /** * Fired when {@link XrInputSource} has ended triggering primary action. The handler is passed * the {@link XrInputSource} that triggered the `selectend` event and the XRInputSourceEvent * event from the WebXR API. * * @event * @example * app.xr.input.on('selectend', (inputSource, evt) => { * console.log('Select ended'); * }); */ static EVENT_SELECTEND: string; /** * Fired when {@link XrInputSource} has triggered squeeze action. This is associated with * "grabbing" action on the controllers. The handler is passed the {@link XrInputSource} that * triggered the `squeeze` event and the XRInputSourceEvent event from the WebXR API. * * @event * @example * app.xr.input.on('squeeze', (inputSource, evt) => { * console.log('Squeeze'); * }); */ static EVENT_SQUEEZE: string; /** * Fired when {@link XrInputSource} has started to trigger squeeze action. The handler is * passed the {@link XrInputSource} that triggered the `squeezestart` event and the * XRInputSourceEvent event from the WebXR API. * * @event * @example * app.xr.input.on('squeezestart', (inputSource, evt) => { * if (obj.containsPoint(inputSource.getPosition())) { * // grabbed an object * } * }); */ static EVENT_SQUEEZESTART: string; /** * Fired when {@link XrInputSource} has ended triggering squeeze action. The handler is passed * the {@link XrInputSource} that triggered the `squeezeend` event and the XRInputSourceEvent * event from the WebXR API. * * @event * @example * app.xr.input.on('squeezeend', (inputSource, evt) => { * console.log('Squeeze ended'); * }); */ static EVENT_SQUEEZEEND: string; /** * Create a new XrInput instance. * * @param {XrManager} manager - WebXR Manager. * @ignore */ constructor(manager: XrManager); /** * @type {XrManager} * @private */ private manager; /** * @type {XrInputSource[]} * @private */ private _inputSources; /** * @type {Function} * @private */ private _onInputSourcesChangeEvt; /** @ignore */ velocitiesSupported: boolean; /** @private */ private _onSessionStart; /** @private */ private _onSessionEnd; /** * @param {XRInputSourcesChangeEvent} evt - WebXR input sources change event. * @private */ private _onInputSourcesChange; /** * @param {XRInputSource} xrInputSource - Input source to search for. * @returns {XrInputSource|null} The input source that matches the given WebXR input source or * null if no match is found. * @private */ private _getByInputSource; /** * @param {XRInputSource} xrInputSource - Input source to add. * @private */ private _addInputSource; /** * @param {XRInputSource} xrInputSource - Input source to remove. * @private */ private _removeInputSource; /** * @param {XRFrame} frame - XRFrame from requestAnimationFrame callback. * @ignore */ update(frame: XRFrame): void; /** * List of active {@link XrInputSource} instances. * * @type {XrInputSource[]} */ get inputSources(): XrInputSource[]; } /** * Light Estimation provides illumination data from the real world, which is estimated by the * underlying AR system. It provides a reflection Cube Map, that represents the reflection * estimation from the viewer position. A more simplified approximation of light is provided by L2 * Spherical Harmonics data. And the most simple level of light estimation is the most prominent * directional light, its rotation, intensity and color. * * @category XR */ declare class XrLightEstimation extends EventHandler { /** * Fired when light estimation data becomes available. * * @event * @example * app.xr.lightEstimation.on('available', () => { * console.log('Light estimation is available'); * }); */ static EVENT_AVAILABLE: string; /** * Fired when light estimation has failed to start. The handler is passed the Error object * related to failure of light estimation start. * * @event * @example * app.xr.lightEstimation.on('error', (error) => { * console.error(error.message); * }); */ static EVENT_ERROR: string; /** * Create a new XrLightEstimation instance. * * @param {XrManager} manager - WebXR Manager. * @ignore */ constructor(manager: XrManager); /** * @type {XrManager} * @private */ private _manager; /** @private */ private _supported; /** @private */ private _available; /** @private */ private _lightProbeRequested; /** * @type {XRLightProbe|null} * @private */ private _lightProbe; /** @private */ private _intensity; /** @private */ private _rotation; /** @private */ private _color; /** * @type {Float32Array} * @private */ private _sphericalHarmonics; /** @private */ private _onSessionStart; /** @private */ private _onSessionEnd; /** * Start estimation of illumination data. Availability of such data will come later and an * `available` event will be fired. If it failed to start estimation, an `error` event will be * fired. * * @example * app.xr.on('start', () => { * if (app.xr.lightEstimation.supported) { * app.xr.lightEstimation.start(); * } * }); */ start(): void; /** * End estimation of illumination data. */ end(): void; /** * @param {XRFrame} frame - XRFrame from requestAnimationFrame callback. * @ignore */ update(frame: XRFrame): void; /** * True if Light Estimation is supported. This information is available only during an active AR * session. * * @type {boolean} */ get supported(): boolean; /** * True if estimated light information is available. * * @type {boolean} * @example * if (app.xr.lightEstimation.available) { * entity.light.intensity = app.xr.lightEstimation.intensity; * } */ get available(): boolean; /** * Intensity of what is estimated to be the most prominent directional light. Or null if data * is not available. * * @type {number|null} */ get intensity(): number | null; /** * Color of what is estimated to be the most prominent directional light. Or null if data is * not available. * * @type {Color|null} */ get color(): Color | null; /** * Rotation of what is estimated to be the most prominent directional light. Or null if data is * not available. * * @type {Quat|null} */ get rotation(): Quat | null; /** * Spherical harmonic coefficients of estimated ambient light. Or null if data is not available. * * @type {Float32Array|null} */ get sphericalHarmonics(): Float32Array | null; } /** * Represents a single view of the scene - a region of the render target rendered from a single * viewpoint. A standard camera produces one view, while in XR each eye (or screen) is a separate * view. This is the base class for {@link XrView}. * * @category Graphics */ declare class RenderView extends EventHandler { /** * World space position of the view, used by shaders. Derived by {@link updateTransforms}. * * @type {Float32Array} * @private */ private _positionData; /** * The viewport (x, y, width, height) this view renders into. * * @type {Vec4} * @private */ private _viewport; /** * Projection matrix, supplied by the producer. * * @type {Mat4} * @private */ private _projMat; /** * Combined projection * view matrix, with the camera's parent transform applied. Derived. * * @type {Mat4} * @private */ private _projViewOffMat; /** * View matrix (world-to-view), supplied by the producer. * * @type {Mat4} * @private */ private _viewMat; /** * View matrix with the camera's parent transform applied. Derived. * * @type {Mat4} * @private */ private _viewOffMat; /** * 3x3 rotational part of {@link _viewOffMat}. Derived. * * @type {Mat3} * @private */ private _viewMat3; /** * Inverse view matrix (view-to-world), supplied by the producer. * * @type {Mat4} * @private */ private _viewInvMat; /** * Inverse view matrix with the camera's parent transform applied. Derived. * * @type {Mat4} * @private */ private _viewInvOffMat; /** * A Vec4 (x, y, width, height) that represents the view's viewport. For a monoscopic screen it * defines the fullscreen view; for stereoscopic views (left/right eye) it defines the part of * the screen the view occupies. * * @type {Vec4} */ get viewport(): Vec4; /** * @type {Mat4} * @ignore */ get projMat(): Mat4; /** * @type {Mat4} * @ignore */ get projViewOffMat(): Mat4; /** * @type {Mat4} * @ignore */ get viewOffMat(): Mat4; /** * @type {Mat4} * @ignore */ get viewInvOffMat(): Mat4; /** * @type {Mat3} * @ignore */ get viewMat3(): Mat3; /** * @type {Float32Array} * @ignore */ get positionData(): Float32Array; /** * Sets the projection and pose matrices for this view. Each matrix is supplied as a 16-element * array (a `Float32Array` from WebXR, or the `data` of a {@link Mat4}). The inverse view matrix * (view-to-world) is the source of truth; the view matrix is optional and is derived by * inverting it when not supplied (WebXR provides both, so it is passed to avoid the inverse). * * @param {Float32Array|number[]} projMat - Projection matrix data (16 elements). * @param {Float32Array|number[]} viewInvMat - Inverse view (view-to-world) matrix data (16 * elements). * @param {Float32Array|number[]} [viewMat] - View (world-to-view) matrix data (16 elements). If * omitted, it is computed by inverting `viewInvMat`. * @ignore */ setView(projMat: Float32Array | number[], viewInvMat: Float32Array | number[], viewMat?: Float32Array | number[]): void; /** * Sets the viewport this view renders into. * * @param {number} x - The x coordinate of the viewport. * @param {number} y - The y coordinate of the viewport. * @param {number} width - The width of the viewport. * @param {number} height - The height of the viewport. * @ignore */ setViewport(x: number, y: number, width: number, height: number): void; /** * Updates the derived "off" matrices from the supplied view matrices and the camera's parent * world transform. Cheap and idempotent, so it can be called multiple times per frame (the * gsplat passes refresh these before {@link Renderer#setCameraUniforms} runs). * * @param {Mat4|null} parentWorldTransform - World transform of the camera's parent node, or * null when the camera has no parent. * @ignore */ updateTransforms(parentWorldTransform: Mat4 | null): void; } /** * @import { EventHandle } from '../../core/event-handle.js' * @import { XrManager } from './xr-manager.js' */ /** * Represents an XR View which represents a screen (monoscopic scenario such as a mobile phone) or an eye * (stereoscopic scenario such as an HMD context). It provides access to the view's color and depth information * based on the capabilities of underlying AR system. * * @category XR */ declare class XrView extends RenderView { /** * Fired when the depth sensing texture has been resized. The {@link depthUvMatrix} needs * to be updated for relevant shaders. The handler is passed the new width and height of the * depth texture in pixels. * * @event * @example * view.on('depth:resize', () => { * material.setParameter('matrix_depth_uv', view.depthUvMatrix); * }); */ static EVENT_DEPTHRESIZE: string; /** * Create a new XrView instance. * * @param {XrManager} manager - WebXR Manager. * @param {XRView} xrView - XRView object that is created by WebXR API. * @param {number} viewsCount - Number of views available for the session. * @ignore */ constructor(manager: XrManager, xrView: XRView, viewsCount: number); /** * @type {XrManager} * @private */ private _manager; /** * @type {XRView} * @private */ private _xrView; /** * @type {XRCamera} * @private */ private _xrCamera; /** * @type {Texture|null} * @private */ private _textureColor; /** * @type {Texture|null} * @private */ private _textureDepth; /** * @type {XRDepthInformation|null} * @private */ private _depthInfo; /** * @type {EventHandle|null} * @private */ private _evtDeviceLost; /** * @type {Uint8Array} * @private */ private _emptyDepthBuffer; /** @private */ private _depthMatrix; /** * Texture associated with this view's camera color. Equals to null if camera color is * not available or is not supported. * * @type {Texture|null} */ get textureColor(): Texture | null; /** * Texture that contains packed depth information which is reconstructed using the underlying * AR system. This texture can be used (not limited to) for reconstructing real world * geometry, virtual object placement, occlusion of virtual object by the real world geometry, * and more. * The format of this texture is any of `PIXELFORMAT_LA8`, {@link PIXELFORMAT_DEPTH}, or * {@link PIXELFORMAT_R32F} based on {@link XrViews#depthPixelFormat}. It is UV transformed * based on the underlying AR system which can be normalized using {@link depthUvMatrix}. * Equals to null if camera depth is not supported. * * @type {Texture|null} * @example * // GPU path, attaching texture to material * material.setParameter('texture_depthSensingMap', view.textureDepth); * material.setParameter('matrix_depth_uv', view.depthUvMatrix.data); * material.setParameter('depth_to_meters', view.depthValueToMeters); * @example * // GLSL shader to unpack depth texture * // when depth information is provided in form of LA8 * varying vec2 vUv0; * * uniform sampler2D texture_depthSensingMap; * uniform mat4 matrix_depth_uv; * uniform float depth_to_meters; * * void main(void) { * // transform UVs using depth matrix * vec2 texCoord = (matrix_depth_uv * vec4(vUv0.xy, 0.0, 1.0)).xy; * * // get luminance alpha components from depth texture * vec2 packedDepth = texture2D(texture_depthSensingMap, texCoord).ra; * * // unpack into single value in millimeters * float depth = dot(packedDepth, vec2(255.0, 256.0 * 255.0)) * depth_to_meters; // m * * // normalize: 0m to 8m distance * depth = min(depth / 8.0, 1.0); // 0..1 = 0m..8m * * // paint scene from black to white based on distance * gl_FragColor = vec4(depth, depth, depth, 1.0); * } */ get textureDepth(): Texture | null; /** * 4x4 matrix that should be used to transform depth texture UVs to normalized UVs in a shader. * It is updated when the depth texture is resized. Refer to {@link EVENT_DEPTHRESIZE}. * * @type {Mat4} * @example * material.setParameter('matrix_depth_uv', view.depthUvMatrix.data); */ get depthUvMatrix(): Mat4; /** * Multiply this coefficient number by raw depth value to get depth in meters. * * @type {number} * @example * material.setParameter('depth_to_meters', view.depthValueToMeters); */ get depthValueToMeters(): number; /** * An eye with which this view is associated. Can be any of: * * - {@link XREYE_NONE}: None - indicates a monoscopic view (likely mobile phone screen). * - {@link XREYE_LEFT}: Left - indicates left eye view. * - {@link XREYE_RIGHT}: Right - indicates a right eye view. * * @type {string} */ get eye(): string; /** * @param {XRFrame} frame - XRFrame from requestAnimationFrame callback. * @param {XRView} xrView - XRView from WebXR API. * @ignore */ update(frame: XRFrame, xrView: XRView): void; /** @private */ private _updateTextureColor; /** * @param {XRFrame} frame - XRFrame from requestAnimationFrame callback. * @private */ private _updateDepth; _onDeviceLost(): void; /** * Get a depth value from depth information in meters. The specified UV is in the range 0..1, * with the origin in the top-left corner of the depth texture. * * @param {number} u - U coordinate of pixel in depth texture, which is in range from 0.0 to * 1.0 (left to right). * @param {number} v - V coordinate of pixel in depth texture, which is in range from 0.0 to * 1.0 (top to bottom). * @returns {number|null} Depth in meters or null if depth information is currently not * available. * @example * const depth = view.getDepth(u, v); * if (depth !== null) { * // depth in meters * } */ getDepth(u: number, v: number): number | null; /** @ignore */ destroy(): void; } /** * @import { XrManager } from './xr-manager.js' */ /** * Provides access to list of {@link XrView}s and information about their capabilities, such as * support and availability of view's camera color texture, depth texture and other parameters. * * @category XR */ declare class XrViews extends EventHandler { /** * Fired when a view has been added. Views are not available straight away on session start and * are added mid-session. They can be added/removed mid session by the underlying system. The * handler is passed the {@link XrView} that has been added. * * @event * @example * xr.views.on('add', (view) => { * console.log('View added'); * }); */ static EVENT_ADD: string; /** * Fired when a view has been removed. They can be added/removed mid session by the underlying * system. The handler is passed the {@link XrView} that has been removed. * * @event * @example * xr.views.on('remove', (view) => { * console.log('View removed'); * }); */ static EVENT_REMOVE: string; /** * Create a new XrViews instance. * * @param {XrManager} manager - WebXR Manager. * @ignore */ constructor(manager: XrManager); /** * @type {XrManager} * @private */ private _manager; /** * @type {Map} * @private */ private _index; /** * @type {Map} * @private */ private _indexTmp; /** * @type {XrView[]} * @private */ private _list; /** * @type {boolean} * @private */ private _supportedColor; /** * @type {boolean} * @private */ private _supportedDepth; /** @private */ private _availableColor; /** @private */ private _availableDepth; /** @private */ private _depthUsage; /** @private */ private _depthFormat; /** * @type {object} * @private */ private _depthFormats; /** * An array of {@link XrView}s of this session. Views are not available straight away on * session start, and can be added/removed mid-session. So use of `add`/`remove` events is * required for accessing views. * * @type {XrView[]} */ get list(): XrView[]; /** * Check if Camera Color is supported. It might be still unavailable even if requested, * based on hardware capabilities and granted permissions. * * @type {boolean} */ get supportedColor(): boolean; /** * Check if Camera Depth is supported. It might be still unavailable even if requested, * based on hardware capabilities and granted permissions. * * @type {boolean} */ get supportedDepth(): boolean; /** * Check if Camera Color is available. This information becomes available only after * session has started. * * @type {boolean} */ get availableColor(): boolean; /** * Check if Camera Depth is available. This information becomes available only after * session has started. * * @type {boolean} */ get availableDepth(): boolean; /** * @type {string} * @ignore */ get depthUsage(): string; /** * Whether the depth sensing is GPU optimized. * * @type {boolean} */ get depthGpuOptimized(): boolean; /** * @type {string} * @ignore */ get depthFormat(): string; /** * The depth sensing pixel format. Can be: * * - `PIXELFORMAT_LA8` * - {@link PIXELFORMAT_R32F} * * @type {PIXELFORMAT_LA8|PIXELFORMAT_R32F|null} */ get depthPixelFormat(): 2 | 15 | null; /** * @param {XRFrame} frame - XRFrame from requestAnimationFrame callback. * @param {XRView[]} xrViews - XRViews from the WebXR API. * @ignore */ update(frame: XRFrame, xrViews: XRView[]): void; /** * Get an {@link XrView} by its associated eye constant. * * @param {string} eye - An XREYE_* view is associated with. Can be 'none' for monoscope views. * @returns {XrView|null} View or null if view of such eye is not available. */ get(eye: string): XrView | null; /** @private */ private _onSessionStart; /** @private */ private _onSessionEnd; } /** * Callback used by {@link XrAnchor#persist}. */ type XrAnchorPersistCallback = (err: Error | null, uuid: string | null) => void; /** * Callback used by {@link XrAnchor#forget}. */ type XrAnchorForgetCallback = (err: Error | null) => void; /** * @import { XrAnchors } from './xr-anchors.js' */ /** * @callback XrAnchorPersistCallback * Callback used by {@link XrAnchor#persist}. * @param {Error|null} err - The Error object if persisting the anchor failed, or null. * @param {string|null} uuid - Unique string that can be used to restore an {@link XrAnchor} in * another session. * @returns {void} */ /** * @callback XrAnchorForgetCallback * Callback used by {@link XrAnchor#forget}. * @param {Error|null} err - The Error object if forgetting the {@link XrAnchor} failed, or null * if it succeeded. * @returns {void} */ /** * An anchor keeps track of a position and rotation that is fixed relative to the real world. This * allows the application to adjust the location of virtual objects placed in the scene in a way * that helps with maintaining the illusion that the placed objects are really present in the * user's environment. * * @category XR */ declare class XrAnchor extends EventHandler { /** * Fired when an anchor is destroyed. * * @event * @example * // once anchor is destroyed * anchor.once('destroy', () => { * // destroy its related entity * entity.destroy(); * }); */ static EVENT_DESTROY: string; /** * Fired when an anchor's position and/or rotation is changed. * * @event * @example * anchor.on('change', () => { * // anchor has been updated * entity.setPosition(anchor.getPosition()); * entity.setRotation(anchor.getRotation()); * }); */ static EVENT_CHANGE: string; /** * Fired when an anchor has been persisted. The handler is passed the UUID string that can * be used to restore this anchor. * * @event * @example * anchor.on('persist', (uuid) => { * // anchor has been persisted * }); */ static EVENT_PERSIST: string; /** * Fired when an anchor has been forgotten. * * @event * @example * anchor.on('forget', () => { * // anchor has been forgotten * }); */ static EVENT_FORGET: string; /** * @param {XrAnchors} anchors - Anchor manager. * @param {object} xrAnchor - Native XRAnchor object that is provided by WebXR API. * @param {string|null} uuid - ID string associated with a persistent anchor. * @ignore */ constructor(anchors: XrAnchors, xrAnchor: object, uuid?: string | null); /** @private */ private _position; /** @private */ private _rotation; /** * @type {string|null} * @private */ private _uuid; /** * @type {XrAnchorPersistCallback[]|null} * @private */ private _uuidRequests; _anchors: XrAnchors; _xrAnchor: any; /** * Destroy an anchor. */ destroy(): void; /** * @param {XRFrame} frame - XRFrame from requestAnimationFrame callback. * @ignore */ update(frame: XRFrame): void; /** * Get the world space position of an anchor. * * @returns {Vec3} The world space position of an anchor. */ getPosition(): Vec3; /** * Get the world space rotation of an anchor. * * @returns {Quat} The world space rotation of an anchor. */ getRotation(): Quat; /** * Persists the anchor between WebXR sessions by generating a universally unique identifier * (UUID) for the anchor. This UUID can be used later to restore the anchor from the underlying * system. Note that the underlying system may have a limit on the number of anchors that can * be persisted per origin. * * @param {XrAnchorPersistCallback} [callback] - Optional callback function to be called when * the persistent UUID has been generated or if an error occurs. * @example * // Persist the anchor and log the UUID or error * anchor.persist((err, uuid) => { * if (err) { * console.error('Failed to persist anchor:', err); * } else { * console.log('Anchor persisted with UUID:', uuid); * } * }); */ persist(callback?: XrAnchorPersistCallback): void; /** * Removes the persistent UUID of an anchor from the underlying system. This effectively makes * the anchor non-persistent, so it will not be restored in future WebXR sessions. * * @param {XrAnchorForgetCallback} [callback] - Optional callback function to be called when * the anchor has been forgotten or if an error occurs. * @example * // Forget the anchor and log the result or error * anchor.forget((err) => { * if (err) { * console.error('Failed to forget anchor:', err); * } else { * console.log('Anchor has been forgotten'); * } * }); */ forget(callback?: XrAnchorForgetCallback): void; /** * Gets the UUID string of a persisted anchor or null if the anchor is not persisted. * * @type {null|string} */ get uuid(): null | string; /** * Gets whether an anchor is persistent. * * @type {boolean} */ get persistent(): boolean; } /** * Callback used by {@link XrAnchors#create}. */ type XrAnchorCreateCallback = (err: Error | null, anchor: XrAnchor | null) => void; /** * @import { Quat } from '../../core/math/quat.js' * @import { Vec3 } from '../../core/math/vec3.js' * @import { XrAnchorForgetCallback } from './xr-anchor.js' * @import { XrManager } from './xr-manager.js' */ /** * @callback XrAnchorCreateCallback * Callback used by {@link XrAnchors#create}. * @param {Error|null} err - The Error object if failed to create an anchor or null. * @param {XrAnchor|null} anchor - The anchor that is tracked against real world geometry. * @returns {void} */ /** * Anchors provide an ability to specify a point in the world that needs to be updated to * correctly reflect the evolving understanding of the world by the underlying AR system, * such that the anchor remains aligned with the same place in the physical world. * Anchors tend to persist better relative to the real world, especially during a longer * session with lots of movement. * * ```javascript * app.xr.start(camera, XRTYPE_AR, XRSPACE_LOCALFLOOR, { * anchors: true * }); * ``` * * @category XR */ declare class XrAnchors extends EventHandler { /** * Fired when anchors become available. * * @event * @example * app.xr.anchors.on('available', () => { * console.log('Anchors are available'); * }); */ static EVENT_AVAILABLE: string; /** * Fired when anchors become unavailable. * * @event * @example * app.xr.anchors.on('unavailable', () => { * console.log('Anchors are unavailable'); * }); */ static EVENT_UNAVAILABLE: string; /** * Fired when an anchor failed to be created. The handler is passed an Error object. * * @event * @example * app.xr.anchors.on('error', (err) => { * console.error(err.message); * }); */ static EVENT_ERROR: string; /** * Fired when a new {@link XrAnchor} is added. The handler is passed the {@link XrAnchor} that * was added. * * @event * @example * app.xr.anchors.on('add', (anchor) => { * console.log('Anchor added'); * }); */ static EVENT_ADD: string; /** * Fired when an {@link XrAnchor} is destroyed. The handler is passed the {@link XrAnchor} that * was destroyed. * * @event * @example * app.xr.anchors.on('destroy', (anchor) => { * console.log('Anchor destroyed'); * }); */ static EVENT_DESTROY: string; /** * Create a new XrAnchors instance. * * @param {XrManager} manager - WebXR Manager. * @ignore */ constructor(manager: XrManager); /** * @type {XrManager} * @ignore */ manager: XrManager; /** * @type {boolean} * @private */ private _supported; /** @private */ private _available; /** @private */ private _checkingAvailability; /** * @type {boolean} * @private */ private _persistence; /** * List of anchor creation requests. * * @type {object[]} * @private */ private _creationQueue; /** * Index of XrAnchors, with XRAnchor (native handle) used as a key. * * @type {Map} * @private */ private _index; /** * Index of XrAnchors, with UUID (persistent string) used as a key. * * @type {Map} * @private */ private _indexByUuid; /** * @type {XrAnchor[]} * @private */ private _list; /** * Map of callbacks to XRAnchors so that we can call its callback once an anchor is updated * with a pose for the first time. * * @type {Map} * @private */ private _callbacksAnchors; /** @private */ private _onSessionStart; /** @private */ private _onSessionEnd; /** * @param {XRAnchor} xrAnchor - XRAnchor that has been added. * @param {string|null} [uuid] - UUID string associated with persistent anchor. * @returns {XrAnchor} new instance of XrAnchor. * @private */ private _createAnchor; /** * @param {XRAnchor} xrAnchor - XRAnchor that has been destroyed. * @param {XrAnchor} anchor - Anchor that has been destroyed. * @private */ private _onAnchorDestroy; /** * Create an anchor using position and rotation, or from hit test result. * * @param {Vec3|XRHitTestResult} position - Position for an anchor or a hit test result. * @param {Quat|XrAnchorCreateCallback} [rotation] - Rotation for an anchor or a callback if * creating from a hit test result. * @param {XrAnchorCreateCallback} [callback] - Callback to fire when anchor was created or * failed to be created. * @example * // create an anchor using a position and rotation * app.xr.anchors.create(position, rotation, (err, anchor) => { * if (!err) { * // new anchor has been created * } * }); * @example * // create an anchor from a hit test result * hitTestSource.on('result', (position, rotation, inputSource, hitTestResult) => { * app.xr.anchors.create(hitTestResult, (err, anchor) => { * if (!err) { * // new anchor has been created * } * }); * }); */ create(position: Vec3 | XRHitTestResult, rotation?: Quat | XrAnchorCreateCallback, callback?: XrAnchorCreateCallback): void; /** * Restore anchor using persistent UUID. * * @param {string} uuid - UUID string associated with persistent anchor. * @param {XrAnchorCreateCallback} [callback] - Callback to fire when anchor was created or * failed to be created. * @example * // restore an anchor using uuid string * app.xr.anchors.restore(uuid, (err, anchor) => { * if (!err) { * // new anchor has been created * } * }); * @example * // restore all available persistent anchors * const uuids = app.xr.anchors.uuids; * for(let i = 0; i < uuids.length; i++) { * app.xr.anchors.restore(uuids[i]); * } */ restore(uuid: string, callback?: XrAnchorCreateCallback): void; /** * Forget an anchor by removing its UUID from underlying systems. * * @param {string} uuid - UUID string associated with persistent anchor. * @param {XrAnchorForgetCallback} [callback] - Callback to fire when anchor persistent data * was removed or error if failed. * @example * // forget all available anchors * const uuids = app.xr.anchors.uuids; * for (let i = 0; i < uuids.length; i++) { * app.xr.anchors.forget(uuids[i]); * } */ forget(uuid: string, callback?: XrAnchorForgetCallback): void; /** * @param {XRFrame} frame - XRFrame from requestAnimationFrame callback. * @ignore */ update(frame: XRFrame): void; /** * True if Anchors are supported. * * @type {boolean} */ get supported(): boolean; /** * True if Anchors are available. This information is available only when session has started. * * @type {boolean} */ get available(): boolean; /** * True if Anchors support persistence. * * @type {boolean} */ get persistence(): boolean; /** * Array of UUID strings of persistent anchors, or null if not available. * * @type {null|string[]} */ get uuids(): null | string[]; /** * List of available {@link XrAnchor}s. * * @type {XrAnchor[]} */ get list(): XrAnchor[]; } /** * Callback used by {@link XrManager#start} and {@link XrManager#end}. */ type XrErrorCallback = (err: Error | null) => void; /** * Callback used by {@link XrManager#initiateRoomCapture}. */ type XrRoomCaptureCallback = (err: Error | null) => void; /** * @callback XrErrorCallback * Callback used by {@link XrManager#start} and {@link XrManager#end}. * @param {Error|null} err - The Error object or null if operation was successful. * @returns {void} */ /** * @callback XrRoomCaptureCallback * Callback used by {@link XrManager#initiateRoomCapture}. * @param {Error|null} err - The Error object or null if manual room capture was successful. * @returns {void} */ /** * XrManager provides a comprehensive interface for WebXR integration in PlayCanvas applications. * It manages the full lifecycle of XR sessions (VR/AR), handles device capabilities, and provides * access to various XR features through specialized subsystems. * * In order for XR to be available, ensure that your application is served over HTTPS or localhost. * * The {@link AppBase} class automatically creates an instance of this class and makes it available * as {@link AppBase#xr}. * * Ready-made XR building blocks ship under `playcanvas/scripts/esm/xr/`: `xr-session.mjs` for * session lifecycle and camera rig transforms, `xr-controllers.mjs` for WebXR controller and hand * models, `xr-navigation.mjs` for teleportation, smooth locomotion and turning, * `xr-manipulation.mjs` for two-handed drag, rotate and scale of the world, and `xr-menu.mjs` for * hand-tracked and controller-driven 3D menus. * * @category XR */ declare class XrManager extends EventHandler { /** * Fired when availability of the XR type is changed. This event is available in two * forms. They are as follows: * * 1. `available` - Fired when availability of any XR type is changed. The handler is passed * the session type that has changed availability and a boolean representing the availability. * 2. `available:[type]` - Fired when availability of specific XR type is changed. The handler * is passed a boolean representing the availability. * * @event * @example * app.xr.on('available', (type, available) => { * console.log(`XR type ${type} is now ${available ? 'available' : 'unavailable'}`); * }); * @example * app.xr.on(`available:${XRTYPE_VR}`, (available) => { * console.log(`XR type VR is now ${available ? 'available' : 'unavailable'}`); * }); */ static EVENT_AVAILABLE: string; /** * Fired when XR session is started. * * @event * @example * app.xr.on('start', () => { * // XR session has started * }); */ static EVENT_START: string; /** * Fired when XR session is ended. While the handlers run, {@link XrManager#camera}, * {@link XrManager#type} and {@link XrManager#spaceType} still describe the session that has * ended, and they are reset once all handlers have run. * * @event * @example * app.xr.on('end', () => { * // XR session has ended * }); */ static EVENT_END: string; /** * Fired when XR session is updated, providing relevant XRFrame object. The handler is passed * [XRFrame](https://developer.mozilla.org/en-US/docs/Web/API/XRFrame) object that can be used * for interfacing directly with WebXR APIs. * * @event * @example * app.xr.on('update', (frame) => { * console.log('XR frame updated'); * }); */ static EVENT_UPDATE: string; /** * Fired when XR session is failed to start or failed to check for session type support. The handler * is passed the [Error](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) * object related to failure of session start or check of session type support. * * @event * @example * app.xr.on('error', (error) => { * console.error(error.message); * }); */ static EVENT_ERROR: string; /** * The startup availability probe calls {@link navigator.xr.isSessionSupported}, which the * browser blocks - logging a `xr-spatial-tracking is not allowed in this document` permissions * policy violation - when the `xr-spatial-tracking` feature is disallowed for the document (for * example when the app runs in an iframe without `allow="xr-spatial-tracking"`). Only skip the * probe when the policy explicitly disallows the feature; when the Feature Policy API is * unavailable (e.g. Safari / visionOS) we cannot tell, so proceed as before. * * @returns {boolean} - True if the probe should run. * @private */ private static _allowsSpatialTracking; /** * Tests whether an immersive WebXR session of the given type can run on the specified graphics * backend. Unlike {@link XrManager#isAvailable}, this is a static method that can be called * before a graphics device (or the {@link AppBase}) is created, which makes it useful for * deciding which device type to create for XR - for example WebGPU vs WebGL2. * * This is a best-effort preflight check. The only authoritative test remains a successful * {@link XrManager#start}, so a fallback path should always be kept. * * @param {string} deviceType - The graphics device type the session would run on. Can be * {@link DEVICETYPE_WEBGPU} or {@link DEVICETYPE_WEBGL2}. * @param {string} type - The session type. Can be: * * - {@link XRTYPE_VR}: Immersive VR session. * - {@link XRTYPE_AR}: Immersive AR session. * * @returns {Promise} Promise that resolves to true if a session of the given type is * reported supported on the given backend, false otherwise. * @example * const supported = await XrManager.isDeviceSupported(DEVICETYPE_WEBGPU, XRTYPE_VR); * if (supported) { * // a WebGPU device can be created and used to offer VR * } */ static isDeviceSupported(deviceType: string, type: string): Promise; /** * Returns whether the given graphics backend meets the WebXR binding requirement. A WebGPU * backend can only host an XR session when the browser exposes `XRGPUBinding`; a WebGL backend * uses the classic `XRWebGLLayer` and needs no additional binding. * * @param {string} [deviceType] - The graphics device type, see DEVICETYPE_*. * @returns {boolean} True if the backend can host a WebXR session. * @private */ private static _backendSupportsXr; /** * Create a new XrManager instance. * * @param {AppBase} app - The main application. * @ignore */ constructor(app: AppBase); /** * @type {AppBase} * @ignore */ app: AppBase; /** * @type {boolean} * @private */ private _supported; /** * @type {Object} * @private */ private _available; /** * Listener for the `devicechange` event of `navigator.xr`, which is removed on destroy. * * @type {Function|null} * @private */ private _onDeviceChange; /** * @type {string|null} * @private */ private _type; /** * @type {string|null} * @private */ private _spaceType; /** * @type {XRSession|null} * @private */ private _session; /** * True while a session requested by {@link XrManager#start} is pending. * * @type {boolean} * @private */ private _starting; /** * Graphics-backend XR glue for the active session. * * @type {XrBridge|null} * @ignore */ xrBridge: XrBridge | null; /** * Backend-specific XR binding for GPU camera/depth paths when available (for example WebGL * `XRWebGLBinding` or WebGPU `XRGPUBinding` when exposed by the user agent). * * @type {Object|null} */ get graphicsBinding(): any | null; /** * @type {XRReferenceSpace|null} * @ignore */ _referenceSpace: XRReferenceSpace | null; /** * Provides access to DOM overlay capabilities. * * @type {XrDomOverlay} */ domOverlay: XrDomOverlay; /** * Provides the ability to perform hit tests on the representation of real world geometry * of the underlying AR system. * * @type {XrHitTest} */ hitTest: XrHitTest; /** * Provides access to image tracking capabilities. * * @type {XrImageTracking} */ imageTracking: XrImageTracking; /** * Provides access to plane detection capabilities. * * @type {XrPlaneDetection} */ planeDetection: XrPlaneDetection; /** * Provides access to mesh detection capabilities. * * @type {XrMeshDetection} */ meshDetection: XrMeshDetection; /** * Provides access to Input Sources. * * @type {XrInput} */ input: XrInput; /** * Provides access to light estimation capabilities. * * @type {XrLightEstimation} */ lightEstimation: XrLightEstimation; /** * Provides access to views and their capabilities. * * @type {XrViews} */ views: XrViews; /** * Provides access to Anchors. * * @type {XrAnchors} */ anchors: XrAnchors; /** * @type {CameraComponent|null} * @private */ private _camera; /** @private */ private _localPosition; /** @private */ private _localRotation; /** @private */ private _depthNear; /** @private */ private _depthFar; /** * @type {number[]|null} * @private */ private _supportedFrameRates; /** @private */ private _width; /** @private */ private _height; /** * Scratch for {@link XrBridge#getFramebufferSize}; avoids per-frame allocation. * * @type {Vec2} * @private */ private _framebufferSize; /** @private */ private _framebufferScaleFactor; /** * Projection matrix of the first view, which the camera properties were last derived from. * * @type {Mat4} * @private */ private _xrPropertiesProjMat; /** * Destroys the XrManager instance. * * @ignore */ destroy(): void; /** * Attempts to start XR session for provided {@link CameraComponent} and optionally fires * callback when session is created or failed to create. Integrated XR APIs need to be enabled * by providing relevant options. * * Note that the start method needs to be called in response to user action, such as a button * click. It will not work if called in response to a timer or other event. * * @param {CameraComponent} camera - It will be used to render XR session and manipulated based * on pose tracking. * @param {string} type - Session type. Can be one of the following: * * - {@link XRTYPE_INLINE}: Inline - always available type of session. It has limited features * availability and is rendered into HTML element. * - {@link XRTYPE_VR}: Immersive VR - session that provides exclusive access to VR device with * best available tracking features. * - {@link XRTYPE_AR}: Immersive AR - session that provides exclusive access to VR/AR device * that is intended to be blended with real-world environment. * * @param {string} spaceType - Reference space type. Can be one of the following: * * - {@link XRSPACE_VIEWER}: Viewer - always supported space with some basic tracking * capabilities. * - {@link XRSPACE_LOCAL}: Local - represents a tracking space with a native origin near the * viewer at the time of creation. It is meant for seated or basic local XR sessions. * - {@link XRSPACE_LOCALFLOOR}: Local Floor - represents a tracking space with a native origin * at the floor in a safe position for the user to stand. The y axis equals 0 at floor level. * Floor level value might be estimated by the underlying platform. It is meant for seated or * basic local XR sessions. * - {@link XRSPACE_BOUNDEDFLOOR}: Bounded Floor - represents a tracking space with its native * origin at the floor, where the user is expected to move within a pre-established boundary. * - {@link XRSPACE_UNBOUNDED}: Unbounded - represents a tracking space where the user is * expected to move freely around their environment, potentially long distances from their * starting point. * * @param {object} [options] - Object with additional options for XR session initialization. * @param {number} [options.framebufferScaleFactor] - Framebuffer scale factor should * be higher than 0.0, by default 1.0 (no scaling). A value of 0.5 will reduce the resolution * of an XR session in half, and a value of 2.0 will double the resolution. * @param {string[]} [options.optionalFeatures] - Optional features for XRSession start. It is * used for getting access to additional WebXR spec extensions. * @param {boolean} [options.anchors] - Set to true to attempt to enable * {@link XrAnchors}. * @param {boolean} [options.imageTracking] - Set to true to attempt to enable * {@link XrImageTracking}. * @param {boolean} [options.planeDetection] - Set to true to attempt to enable * {@link XrPlaneDetection}. * @param {boolean} [options.meshDetection] - Set to true to attempt to enable * {@link XrMeshDetection}. * @param {XrErrorCallback} [options.callback] - Optional callback function called once session * is started. The callback has one argument Error - it is null if successfully started XR * session. * @param {object} [options.depthSensing] - Optional object with parameters to attempt to enable * depth sensing. * @param {string} [options.depthSensing.usagePreference] - Optional usage preference for depth * sensing, can be 'cpu-optimized' or 'gpu-optimized' (XRDEPTHSENSINGUSAGE_*), defaults to * 'cpu-optimized'. Most preferred and supported will be chosen by the underlying depth sensing * system. * @param {string} [options.depthSensing.dataFormatPreference] - Optional data format * preference for depth sensing, can be 'luminance-alpha' or 'float32' * (XRDEPTHSENSINGFORMAT_*), defaults to 'luminance-alpha'. Most preferred and supported will * be chosen by the underlying depth sensing system. * @example * button.on('click', () => { * app.xr.start(camera, XRTYPE_VR, XRSPACE_LOCALFLOOR); * }); * @example * button.on('click', () => { * app.xr.start(camera, XRTYPE_AR, XRSPACE_LOCALFLOOR, { * anchors: true, * imageTracking: true, * depthSensing: { } * }); * }); */ start(camera: CameraComponent, type: string, spaceType: string, options?: { framebufferScaleFactor?: number; optionalFeatures?: string[]; anchors?: boolean; imageTracking?: boolean; planeDetection?: boolean; meshDetection?: boolean; callback?: XrErrorCallback; depthSensing?: { usagePreference?: string; dataFormatPreference?: string; }; }): void; /** * @param {string} type - Session type. * @param {string} spaceType - Reference space type. * @param {*} options - Session options. * @param {XrErrorCallback} callback - Error callback. * @private */ private _onStartOptionsReady; /** * Resets the state set by {@link XrManager#start} when no session could be requested, and * reports the error. * * @param {Error} err - The error that stopped the session from starting. * @param {XrErrorCallback} callback - Error callback. * @private */ private _onStartFailed; /** * Attempts to end XR session and optionally fires callback when session is ended or failed to * end. * * @param {XrErrorCallback} [callback] - Optional callback function called once session is * ended. The callback has one argument Error - it is null if successfully ended XR session. * @example * app.keyboard.on('keydown', (evt) => { * if (evt.key === KEY_ESCAPE && app.xr.active) { * app.xr.end(); * } * }); */ end(callback?: XrErrorCallback): void; /** * Check if the specified type of session is available. * * @param {string} type - Session type. Can be one of the following: * * - {@link XRTYPE_INLINE}: Inline - always available type of session. It has limited features * availability and is rendered into HTML element. * - {@link XRTYPE_VR}: Immersive VR - session that provides exclusive access to VR device with * best available tracking features. * - {@link XRTYPE_AR}: Immersive AR - session that provides exclusive access to VR/AR device * that is intended to be blended with real-world environment. * * @example * if (app.xr.isAvailable(XRTYPE_VR)) { * // VR is available * } * @returns {boolean} True if the specified session type is available. */ isAvailable(type: string): boolean; /** @private */ private _deviceAvailabilityCheck; /** * Initiate manual room capture. If the underlying XR system supports manual capture of the * room, it will start the capturing process, which can affect plane and mesh detection, * and improve hit-test quality against real-world geometry. * * @param {XrRoomCaptureCallback} callback - Callback that will be fired once capture is complete * or failed. * * @example * this.app.xr.initiateRoomCapture((err) => { * if (err) { * // capture failed * return; * } * // capture was successful * }); */ initiateRoomCapture(callback: XrRoomCaptureCallback): void; /** * Update target frame rate of an XR session to one of supported value provided by * supportedFrameRates list. * * @param {number} frameRate - Target frame rate. It should be any value from the list * of supportedFrameRates. * @param {Function} [callback] - Callback that will be called when frameRate has been * updated or failed to update with error provided. */ updateTargetFrameRate(frameRate: number, callback?: Function): void; /** * @param {string} type - Session type. * @private */ private _sessionSupportCheck; /** * @param {XRSession} session - XR session. * @param {string} spaceType - Space type to request for the session. * @param {Function} callback - Callback to call when session is started. * @private */ private _onSessionStart; /** * @param {number} near - Near plane distance. * @param {number} far - Far plane distance. * @private */ private _setClipPlanes; /** * @param {XRFrame} frame - XRFrame from requestAnimationFrame callback. * @returns {boolean} True if update was successful, false otherwise. * @ignore */ update(frame: XRFrame): boolean; /** * True if XR is supported. * * @type {boolean} */ get supported(): boolean; /** * True if XR session is running. * * @type {boolean} */ get active(): boolean; /** * Returns type of currently running XR session or null if no session is running. Can be any of * XRTYPE_*. * * @type {string|null} */ get type(): string | null; /** * Returns reference space type of currently running XR session or null if no session is * running. Can be any of XRSPACE_*. * * @type {string|null} */ get spaceType(): string | null; /** * Provides access to XRSession of WebXR. * * @type {XRSession|null} */ get session(): XRSession | null; /** * XR session frameRate or null if this information is not available. This value can change * during an active XR session. * * @type {number|null} */ get frameRate(): number | null; /** * List of supported frame rates, or null if this data is not available. * * @type {number[]|null} */ get supportedFrameRates(): number[] | null; /** * Framebuffer scale factor. This value is read-only and can only be set when starting a new * XR session. * * @type {number} */ get framebufferScaleFactor(): number; /** * Set fixed foveation to the value between 0 and 1. Where 0 is no foveation and 1 is highest * foveation. It only can be set during an active XR session. Fixed foveation will reduce the * resolution of the back buffer at the edges of the screen, which can improve rendering * performance. * * @type {number} */ set fixedFoveation(value: number | null); /** * Gets the current fixed foveation level, which is between 0 and 1. 0 is no foveation and 1 * is highest foveation. If fixed foveation is not supported, this value returns null. * * @type {number|null} */ get fixedFoveation(): number | null; /** * Active camera for which XR session is running or null. * * @type {Entity|null} */ get camera(): Entity | null; /** * Indicates whether WebXR content is currently visible to the user, and if it is, whether it's * the primary focus. Can be 'hidden', 'visible' or 'visible-blurred'. * * @type {"hidden"|"visible"|"visible-blurred"|null} * @ignore */ get visibilityState(): "hidden" | "visible" | "visible-blurred" | null; } /** * Options of the `camera` component accepted by {@link CameraComponentSystem} that differ from the * properties of {@link CameraComponent}. Each replaces the same-named property of the options that * {@link Entity#addComponent} derives from the component class; see * {@link ComponentOptionsOverrides}. */ type CameraComponentOptionsOverrides = { /** * - Same as * {@link CameraComponent#calculateProjection}. */ calculateProjection?: CalculateMatrixCallback; /** * - Same as * {@link CameraComponent#calculateTransform}. */ calculateTransform?: CalculateMatrixCallback; /** * - Same as {@link CameraComponent#clearColor}, also * accepting an `[r, g, b, a]` array. */ clearColor?: Color | number[]; /** * - Same as * {@link CameraComponent#projectionOffset}, also accepting an `[x, y]` array. */ projectionOffset?: Vec2 | number[]; /** * - Same as {@link CameraComponent#rect}, also accepting an `[x, * y, w, h]` array. */ rect?: Vec4 | number[]; /** * - Same as {@link CameraComponent#scissorRect}, also * accepting an `[x, y, w, h]` array. */ scissorRect?: Vec4 | number[]; }; /** * Used to add and remove {@link CameraComponent}s from Entities. It also holds an array of all * active cameras. * * @category Graphics */ declare class CameraComponentSystem extends ComponentSystem { /** * Holds all the active camera components. * * @type {CameraComponent[]} */ cameras: CameraComponent[]; id: string; ComponentType: typeof CameraComponent; initializeComponentData(component: any, data: any): void; cloneComponent(entity: any, clone: any): Component; onBeforeRemove(entity: any, component: any): void; onAppPrerender(): void; addCamera(camera: any): void; removeCamera(camera: any): void; } /** * Callback used by {@link CameraComponent#calculateTransform} and {@link CameraComponent#calculateProjection}. */ type CalculateMatrixCallback = (transformMatrix: Mat4, view: number) => void; /** * @import { CameraComponentSystem } from './system.js' * @import { Color } from '../../../core/math/color.js' * @import { Entity } from '../../entity.js' * @import { EventHandle } from '../../../core/event-handle.js' * @import { Frustum } from '../../../core/shape/frustum.js' * @import { LayerComposition } from '../../../scene/composition/layer-composition.js' * @import { Layer } from '../../../scene/layer.js' * @import { Mat4 } from '../../../core/math/mat4.js' * @import { FramePass } from '../../../platform/graphics/frame-pass.js' * @import { RenderTarget } from '../../../platform/graphics/render-target.js' * @import { FogParams } from '../../../scene/fog-params.js' * @import { Vec2 } from '../../../core/math/vec2.js' * @import { Vec3 } from '../../../core/math/vec3.js' * @import { Vec4 } from '../../../core/math/vec4.js' * @import { XrErrorCallback } from '../../xr/xr-manager.js' */ /** * @callback CalculateMatrixCallback * Callback used by {@link CameraComponent#calculateTransform} and {@link CameraComponent#calculateProjection}. * @param {Mat4} transformMatrix - Output of the function. * @param {number} view - Type of view. Can be {@link VIEW_CENTER}, {@link VIEW_LEFT} or * {@link VIEW_RIGHT}. Left and right are only used in stereo rendering. * @returns {void} */ /** * The CameraComponent enables an {@link Entity} to render the scene. A scene requires at least * one enabled camera component to be rendered. The camera's view direction is along the negative * z-axis of the owner entity. * * Note that multiple camera components can be enabled simultaneously (for split-screen or * offscreen rendering, for example). * * You should never need to use the CameraComponent constructor directly. To add a CameraComponent * to an {@link Entity}, use {@link Entity#addComponent}: * * ```javascript * const entity = new Entity(); * entity.addComponent('camera', { * nearClip: 1, * farClip: 100, * fov: 55 * }); * ``` * * Once the CameraComponent is added to the entity, you can access it via the {@link Entity#camera} * property: * * ```javascript * entity.camera.nearClip = 2; // Set the near clip of the camera * * console.log(entity.camera.nearClip); // Get the near clip of the camera * ``` * * For ready-made camera behaviour, attach the `CameraControls` script from * `playcanvas/scripts/esm/camera-controls.mjs`, which provides orbit, fly and pan driven by mouse, * touch and gamepad input. * * Relevant Engine API examples: * * - [First Person Camera](https://playcanvas.github.io/#/camera/first-person) * - [Fly Camera](https://playcanvas.github.io/#/camera/fly) * - [Multiple Cameras](https://playcanvas.github.io/#/camera/multi) * - [Orbit Camera](https://playcanvas.github.io/#/camera/orbit) * * @hideconstructor * @category Graphics */ declare class CameraComponent extends Component { /** * Create a new CameraComponent instance. * * @param {CameraComponentSystem} system - The ComponentSystem that created this Component. * @param {Entity} entity - The Entity that this Component is attached to. */ constructor(system: CameraComponentSystem, entity: Entity); /** * Custom function that is called when postprocessing should execute. * * @type {Function|null} * @ignore */ onPostprocessing: Function | null; /** * A counter of requests of depth map rendering. * * @private */ private _renderSceneDepthMap; /** * A counter of requests of color map rendering. * * @private */ private _renderSceneColorMap; /** @private */ private _sceneDepthMapRequested; /** @private */ private _sceneColorMapRequested; /** @private */ private _priority; /** * Layer id at which the postprocessing stops for the camera. * * @type {number} * @private */ private _disablePostEffectsLayer; /** * @type {Camera} * @private */ private _camera; /** * @type {EventHandle|null} * @private */ private _evtLayersChanged; /** * @type {EventHandle|null} * @private */ private _evtLayerAdded; /** * @type {EventHandle|null} * @private */ private _evtLayerRemoved; _postEffects: PostEffectQueue; /** * Sets the name of the shader pass the camera will use when rendering. * * In addition to existing names (see the parameter description), a new name can be specified, * which creates a new shader pass with the given name. The name provided can only use * alphanumeric characters and underscores. When a shader is compiled for the new pass, a define * is added to the shader. For example, if the name is 'custom_rendering', the define * 'CUSTOM_RENDERING_PASS' is added to the shader, allowing the shader code to conditionally * execute code only when that shader pass is active. * * Another instance where this approach may prove useful is when a camera needs to render a more * cost-effective version of shaders, such as when creating a reflection texture. To accomplish * this, a callback on the material that triggers during shader compilation can be used. This * callback can modify the shader generation options specifically for this shader pass. * * ```javascript * const shaderPassId = camera.setShaderPass('custom_rendering'); * * material.onUpdateShader = function (options) { * if (options.pass === shaderPassId) { * options.litOptions.normalMapEnabled = false; * options.litOptions.useSpecular = false; * } * return options; * }; * ``` * * @param {string} name - The name of the shader pass. Defaults to undefined, which is * equivalent to {@link SHADERPASS_FORWARD}. Can be: * * - {@link SHADERPASS_FORWARD} * - {@link SHADERPASS_ALBEDO} * - {@link SHADERPASS_OPACITY} * - {@link SHADERPASS_WORLDNORMAL} * - {@link SHADERPASS_SPECULARITY} * - {@link SHADERPASS_GLOSS} * - {@link SHADERPASS_METALNESS} * - {@link SHADERPASS_AO} * - {@link SHADERPASS_EMISSION} * - {@link SHADERPASS_LIGHTING} * - {@link SHADERPASS_UV0} * * The returned index can be used with {@link MeshInstance#shaderPassMask} to control which mesh * instances are rendered in this pass. * * @returns {number} The id of the shader pass. */ setShaderPass(name: string): number; /** * Shader pass name. * * @returns {string|undefined} The name of the shader pass, or undefined if no shader pass is set. */ getShaderPass(): string | undefined; /** * Sets the frame passes the camera uses for rendering, instead of its default rendering. * Set this to null to return to the default behavior. * * @type {FramePass[]|null} * @ignore */ set framePasses(passes: FramePass[]); /** * Gets the frame passes the camera uses for rendering, instead of its default rendering. * * @type {FramePass[]} * @ignore */ get framePasses(): FramePass[]; /** * @type {FramePass[]|null} * @deprecated Use `framePasses` instead. * @ignore */ set renderPasses(passes: FramePass[]); /** * @type {FramePass[]} * @deprecated Use `framePasses` instead. * @ignore */ get renderPasses(): FramePass[]; get shaderParams(): CameraShaderParams; /** * Sets the gamma correction to apply when rendering the scene. Can be: * * - {@link GAMMA_SRGB}: Output is gamma-encoded for standard sRGB displays. This is the * default and recommended setting for all normal rendering. * - {@link GAMMA_NONE}: Output remains in linear space. This is only intended for advanced * HDR pipelines where the output is rendered to an intermediate HDR texture that will be * tonemapped and gamma-corrected in a subsequent pass. * * **Warning**: Setting `GAMMA_NONE` will cause the entire scene (including UI) to appear * too dark on standard displays, as linear values are written directly without gamma * encoding. For HDR rendering with post-processing, use {@link CameraFrame} which handles * this automatically. * * Defaults to {@link GAMMA_SRGB}. * * @type {number} */ set gammaCorrection(value: number); /** * Gets the gamma correction used when rendering the scene. * * @type {number} */ get gammaCorrection(): number; /** * Sets the tonemapping transform to apply to the rendered color buffer. Can be: * * - {@link TONEMAP_LINEAR} * - {@link TONEMAP_FILMIC} * - {@link TONEMAP_HEJL} * - {@link TONEMAP_ACES} * - {@link TONEMAP_ACES2} * - {@link TONEMAP_NEUTRAL} * * Defaults to {@link TONEMAP_LINEAR}. * * @type {number} */ set toneMapping(value: number); /** * Gets the tonemapping transform applied to the rendered color buffer. * * @type {number} */ get toneMapping(): number; /** * Sets the fog parameters. If this is not null, the camera will use these fog parameters * instead of those specified on the {@link Scene#fog}. * * @type {FogParams|null} */ set fog(value: FogParams | null); /** * Gets a {@link FogParams} that defines fog parameters, or null if those are not set. * * @type {FogParams|null} */ get fog(): FogParams | null; /** * Sets the camera aperture in f-stops. Default is 16. Higher value means less exposure. Used * if {@link Scene#physicalUnits} is true. * * @type {number} */ set aperture(value: number); /** * Gets the camera aperture in f-stops. * * @type {number} */ get aperture(): number; /** * Sets the aspect ratio (width divided by height) of the camera. If {@link aspectRatioMode} is * {@link ASPECT_AUTO}, then this value will be automatically calculated every frame, and you * can only read it. If it's {@link ASPECT_MANUAL}, you can set the value. * * @type {number} */ set aspectRatio(value: number); /** * Gets the aspect ratio (width divided by height) of the camera. * * @type {number} */ get aspectRatio(): number; /** * Sets the aspect ratio mode of the camera. Can be: * * - {@link ASPECT_AUTO}: aspect ratio will be calculated from the current render * target's width divided by height. * - {@link ASPECT_MANUAL}: use the aspectRatio value. * * Defaults to {@link ASPECT_AUTO}. * * @type {number} */ set aspectRatioMode(value: number); /** * Gets the aspect ratio mode of the camera. * * @type {number} */ get aspectRatioMode(): number; /** * Sets the custom function to calculate the camera projection matrix manually. Can be used for * complex effects like doing oblique projection. Function is called using component's scope. * * Arguments: * * - {@link Mat4} transformMatrix: output of the function * - view: Type of view. Can be {@link VIEW_CENTER}, {@link VIEW_LEFT} or {@link VIEW_RIGHT}. * * Left and right are only used in stereo rendering. * * @type {CalculateMatrixCallback} */ set calculateProjection(value: CalculateMatrixCallback); /** * Gets the custom function to calculate the camera projection matrix manually. * * @type {CalculateMatrixCallback} */ get calculateProjection(): CalculateMatrixCallback; /** * Sets the custom function to calculate the camera transformation matrix manually. Can be used * for complex effects like reflections. Function is called using component's scope. Arguments: * * - {@link Mat4} transformMatrix: output of the function. * - view: Type of view. Can be {@link VIEW_CENTER}, {@link VIEW_LEFT} or {@link VIEW_RIGHT}. * * Left and right are only used in stereo rendering. * * @type {CalculateMatrixCallback} */ set calculateTransform(value: CalculateMatrixCallback); /** * Gets the custom function to calculate the camera transformation matrix manually. * * @type {CalculateMatrixCallback} */ get calculateTransform(): CalculateMatrixCallback; /** * Gets the camera component's underlying Camera instance. * * @type {Camera} * @ignore */ get camera(): Camera; /** * Sets the camera component's clear color. Defaults to `[0.75, 0.75, 0.75, 1]`. When the camera * renders to a {@link RenderTarget} with multiple color buffers, this is the clear color of * the color attachment 0, and also of the other attachments unless they are given their own * using {@link CameraComponent#setClearColor}. * * @type {Color} */ set clearColor(value: Color); /** * Gets the camera component's clear color. * * @type {Color} */ get clearColor(): Color; /** * Sets the clear color of a color attachment of the camera's render target, which allows the * color buffers of a {@link RenderTarget} with multiple color buffers to clear to different * colors. The attachment 0 clears to {@link CameraComponent#clearColor}, and the other * attachments clear to the same color unless given their own here. Pass null to remove the * color of an attachment, so that it clears to the attachment 0 color again. The components * of the clear color of an integer format attachment are the integer values to clear to. * * @param {number} index - The index of the color attachment. * @param {Color|null} color - The clear color, specified in sRGB space, or null to clear to * the color of the attachment 0. * @example * // clear the second color buffer of the render target to a different color * entity.camera.setClearColor(1, new pc.Color(0.5, 0.5, 1, 1)); */ setClearColor(index: number, color: Color | null): void; /** * Gets the clear color of a color attachment of the camera's render target. * * @param {number} index - The index of the color attachment. * @returns {Color} The clear color of the attachment. */ getClearColor(index: number): Color; /** * Sets whether the camera will automatically clear the color buffer before rendering. Defaults to true. * * @type {boolean} */ set clearColorBuffer(value: boolean); /** * Gets whether the camera will automatically clear the color buffer before rendering. * * @type {boolean} */ get clearColorBuffer(): boolean; /** * Sets the depth value to clear the depth buffer to. Defaults to 1. * * @type {number} */ set clearDepth(value: number); /** * Gets the depth value to clear the depth buffer to. * * @type {number} */ get clearDepth(): number; /** * Sets whether the camera will automatically clear the depth buffer before rendering. Defaults to true. * * @type {boolean} */ set clearDepthBuffer(value: boolean); /** * Gets whether the camera will automatically clear the depth buffer before rendering. * * @type {boolean} */ get clearDepthBuffer(): boolean; /** * Sets whether the camera will automatically clear the stencil buffer before rendering. Defaults to true. * * @type {boolean} */ set clearStencilBuffer(value: boolean); /** * Gets whether the camera will automatically clear the stencil buffer before rendering. * * @type {boolean} */ get clearStencilBuffer(): boolean; /** * Sets whether the camera will cull triangle faces. If true, the camera will take * {@link Material#cull} into account. Otherwise both front and back faces will be rendered. * Defaults to true. * * @type {boolean} */ set cullFaces(value: boolean); /** * Gets whether the camera will cull triangle faces. * * @type {boolean} */ get cullFaces(): boolean; /** * Sets the layer id of the layer on which the post-processing of the camera stops being applied * to. Defaults to {@link LAYERID_UI}, which causes post-processing to not be applied to UI * layer and any following layers for the camera. Set to `undefined` for post-processing to be * applied to all layers of the camera. * * @type {number} */ set disablePostEffectsLayer(layer: number); /** * Gets the layer id of the layer on which the post-processing of the camera stops being applied * to. * * @type {number} */ get disablePostEffectsLayer(): number; /** * Sets the distance from the camera after which no rendering will take place. Defaults to 1000. * * @type {number} */ set farClip(value: number); /** * Gets the distance from the camera after which no rendering will take place. * * @type {number} */ get farClip(): number; /** * Sets whether the camera will flip the face direction of triangles. If set to true, the * camera will invert front and back faces. Can be useful for reflection rendering. Defaults to * false. * * @type {boolean} */ set flipFaces(value: boolean); /** * Gets whether the camera will flip the face direction of triangles. * * @type {boolean} */ get flipFaces(): boolean; /** * Sets the field of view of the camera in degrees. Usually this is the Y-axis field of view * (see {@link horizontalFov}). Used for {@link PROJECTION_PERSPECTIVE} cameras only. Defaults to * 45. * * @type {number} */ set fov(value: number); /** * Gets the field of view of the camera in degrees. * * @type {number} */ get fov(): number; /** * Gets the camera's frustum shape. * * @type {Frustum} */ get frustum(): Frustum; /** * Sets whether frustum culling is enabled. This controls the culling of {@link MeshInstance}s * against the camera frustum, i.e. if objects outside of the camera's frustum should be * omitted from rendering. If false, all mesh instances in the scene are rendered by the * camera, regardless of visibility. Defaults to false. * * @type {boolean} */ set frustumCulling(value: boolean); /** * Gets whether frustum culling is enabled. * * @type {boolean} */ get frustumCulling(): boolean; /** * Sets whether the camera's field of view ({@link fov}) is horizontal or vertical. Defaults to * false (meaning it is vertical by default). * * @type {boolean} */ set horizontalFov(value: boolean); /** * Gets whether the camera's field of view ({@link fov}) is horizontal or vertical. * * @type {boolean} */ get horizontalFov(): boolean; /** * Sets the array of layer IDs ({@link Layer#id}) to which this camera should belong. Don't * push, pop, splice or modify this array. If you want to change it, set a new one instead. * Defaults to [{@link LAYERID_WORLD}, {@link LAYERID_DEPTH}, {@link LAYERID_SKYBOX}, * {@link LAYERID_UI}, {@link LAYERID_IMMEDIATE}]. * * @type {number[]} */ set layers(newValue: ReadonlyArray); /** * Gets the array of layer IDs ({@link Layer#id}) to which this camera belongs. * * @type {ReadonlyArray} */ get layers(): ReadonlyArray; get layersSet(): Set; /** * Sets the jitter intensity applied in the projection matrix. Used for jittered sampling by TAA. * A value of 1 represents a jitter in the range of `[-1, 1]` of a pixel. Smaller values result * in a crisper yet more aliased outcome, whereas increased values produce a smoother but blurred * result. Defaults to 0, representing no jitter. * * @type {number} */ set jitter(value: number); /** * Gets the jitter intensity applied in the projection matrix. * * @type {number} */ get jitter(): number; /** * Sets the distance from the camera before which no rendering will take place. Defaults to 0.1. * * @type {number} */ set nearClip(value: number); /** * Gets the distance from the camera before which no rendering will take place. * * @type {number} */ get nearClip(): number; /** * Sets the half-height of the orthographic view window (in the Y-axis). Used for * {@link PROJECTION_ORTHOGRAPHIC} cameras only. Defaults to 10. * * @type {number} */ set orthoHeight(value: number); /** * Gets the half-height of the orthographic view window (in the Y-axis). * * @type {number} */ get orthoHeight(): number; /** * Gets the post effects queue for this camera. Use this to add or remove post effects from the * camera. * * @type {PostEffectQueue} */ get postEffects(): PostEffectQueue; get postEffectsEnabled(): boolean; /** * Sets the priority to control the render order of this camera. Cameras with a smaller * priority value are rendered first. Defaults to 0. * * @type {number} */ set priority(newValue: number); /** * Gets the priority to control the render order of this camera. * * @type {number} */ get priority(): number; /** * Sets the type of projection used to render the camera. Can be: * * - {@link PROJECTION_PERSPECTIVE}: A perspective projection. The camera frustum * resembles a truncated pyramid. * - {@link PROJECTION_ORTHOGRAPHIC}: An orthographic projection. The camera * frustum is a cuboid. * * Defaults to {@link PROJECTION_PERSPECTIVE}. * * @type {number} */ set projection(value: number); /** * Gets the type of projection used to render the camera. * * @type {number} */ get projection(): number; /** * Gets the camera's projection matrix. * * @type {Mat4} */ get projectionMatrix(): Mat4; /** * Sets the offset of the projection window from the view direction, creating an off-center * (asymmetric) projection. The offset is expressed in half-frustum units - an offset of * `(0, 1)` moves the projection window up by half of the frustum height. Applies to both * perspective and orthographic projections and is ignored in XR, where the projection is * supplied by the XR system. Defaults to `(0, 0)`. * * A typical use case is perspective correction (shift lens): keep the camera level and use * a vertical offset to frame a tall object, so its vertical lines stay parallel: * * @example * // frame content that is `pitch` degrees above the horizon, without tilting the camera * const fovY = entity.camera.fov * math.DEG_TO_RAD; * const shift = Math.tan(pitch * math.DEG_TO_RAD) / Math.tan(fovY / 2); * entity.camera.projectionOffset = new Vec2(0, shift); * @type {Vec2} */ set projectionOffset(value: Vec2); /** * Gets the offset of the projection window. * * @type {Vec2} */ get projectionOffset(): Vec2; /** * Sets the rendering rectangle for the camera. This controls where on the screen the camera * will render in normalized screen coordinates. Defaults to `[0, 0, 1, 1]`. * * The rectangle can extend past the render target bounds, for example `[-0.5, 0, 1.5, 1]`, * with only its overlapping part being rendered. This is supported on WebGL2, and on WebGPU * on platforms that allow viewports extending past the render target bounds. * * @type {Vec4} */ set rect(value: Readonly); /** * Gets the rendering rectangle for the camera. * * @type {Readonly} */ get rect(): Readonly; set renderSceneColorMap(value: boolean); get renderSceneColorMap(): boolean; set renderSceneDepthMap(value: boolean); get renderSceneDepthMap(): boolean; /** * Sets the render target to which rendering of the camera is performed. If not set, it will * render simply to the screen. * * @type {RenderTarget} */ set renderTarget(value: RenderTarget); /** * Gets the render target to which rendering of the camera is performed. * * @type {RenderTarget} */ get renderTarget(): RenderTarget; /** * Sets the scissor rectangle for the camera. This clips all pixels which are not in the * rectangle. The order of the values is `[x, y, width, height]`. Defaults to `[0, 0, 1, 1]`. * * @type {Vec4} */ set scissorRect(value: Vec4); /** * Gets the scissor rectangle for the camera. * * @type {Vec4} */ get scissorRect(): Vec4; /** * Sets the camera sensitivity in ISO. Defaults to 1000. Higher value means more exposure. Used * if {@link Scene#physicalUnits} is true. * * @type {number} */ set sensitivity(value: number); /** * Gets the camera sensitivity in ISO. * * @type {number} */ get sensitivity(): number; /** * Sets the camera shutter speed in seconds. Defaults to 1/1000s. Longer shutter means more * exposure. Used if {@link Scene#physicalUnits} is true. * * @type {number} */ set shutter(value: number); /** * Gets the camera shutter speed in seconds. * * @type {number} */ get shutter(): number; /** * Gets the camera's view matrix. * * @type {Mat4} */ get viewMatrix(): Mat4; /** * Based on the value, the depth layer's enable counter is incremented or decremented. * * @param {boolean} value - True to increment the counter, false to decrement it. * @returns {boolean} True if the counter was incremented or decremented, false if the depth * layer is not present. * @private */ private _enableDepthLayer; /** * Request the scene to generate a texture containing the scene color map. Note that this call * is accumulative, and for each enable request, a disable request need to be called. Note that * this setting is ignored when `framePasses` is used. * * @param {boolean} enabled - True to request the generation, false to disable it. */ requestSceneColorMap(enabled: boolean): void; /** * Request the scene to generate a texture containing the scene depth map. Note that this call * is accumulative, and for each enable request, a disable request need to be called. Note that * this setting is ignored when `framePasses` is used. * * @param {boolean} enabled - True to request the generation, false to disable it. */ requestSceneDepthMap(enabled: boolean): void; dirtyLayerCompositionCameras(): void; /** * Convert a point from 2D screen space to 3D world space. * * @param {number} screenx - X coordinate on PlayCanvas' canvas element. Should be in the range * 0 to `canvas.offsetWidth` of the application's canvas element. * @param {number} screeny - Y coordinate on PlayCanvas' canvas element. Should be in the range * 0 to `canvas.offsetHeight` of the application's canvas element. * @param {number} cameraz - The distance from the camera in world space to create the new * point. * @param {Vec3} [worldCoord] - 3D vector to receive world coordinate result. * @example * // Get the start and end points of a 3D ray fired from a screen click position * const start = entity.camera.screenToWorld(clickX, clickY, entity.camera.nearClip); * const end = entity.camera.screenToWorld(clickX, clickY, entity.camera.farClip); * * // Use the ray coordinates to perform a raycast * const result = app.systems.rigidbody.raycastFirst(start, end); * if (result) { * console.log(`Entity ${result.entity.name} was selected`); * } * @returns {Vec3} The world space coordinate. */ screenToWorld(screenx: number, screeny: number, cameraz: number, worldCoord?: Vec3): Vec3; /** * Convert a point from 3D world space to 2D screen space. * * The returned `z` is the unnormalized clip space depth, not a behind-the-camera flag: it also * goes negative for points in front of a perspective camera that are nearer than twice the * near clip, and for an orthographic camera it is negative across the whole near half of the * depth range. To reject points behind the camera, test the view space depth instead - pass * the world position through {@link CameraComponent#viewMatrix} and discard it when the * resulting `z` is zero or greater. * * @param {Vec3} worldCoord - The world space coordinate. * @param {Vec3} [screenCoord] - 3D vector to receive screen coordinate result. * @returns {Vec3} The screen space coordinate. */ worldToScreen(worldCoord: Vec3, screenCoord?: Vec3): Vec3; /** * Called before application renders the scene. * * @ignore */ onAppPrerender(): void; /** @private */ private addCameraToLayers; /** @private */ private removeCameraFromLayers; /** * @param {LayerComposition} oldComp - Old layer composition. * @param {LayerComposition} newComp - New layer composition. * @private */ private onLayersChanged; /** * @param {Layer} layer - The layer to add the camera to. * @private */ private onLayerAdded; /** * @param {Layer} layer - The layer to remove the camera from. * @private */ private onLayerRemoved; onBeforeRemove(): void; /** * Computes the aspect ratio this camera would produce when rendering to the given render * target, without changing the camera's state. When `rt` is omitted, the camera's own * {@link CameraComponent#renderTarget} is used, and if that is also null, the backbuffer * is used. The camera's {@link CameraComponent#rect} viewport is taken into account. * * @param {RenderTarget|null} [rt] - Optional render target to compute the aspect ratio * against. Defaults to the camera's current render target, or the backbuffer if none is * assigned. * @returns {number} The computed aspect ratio. */ calculateAspectRatio(rt?: RenderTarget | null): number; /** * Attempt to start XR session with this camera. * * @param {string} type - The type of session. Can be one of the following: * * - {@link XRTYPE_INLINE}: Inline - always available type of session. It has limited feature * availability and is rendered into HTML element. * - {@link XRTYPE_VR}: Immersive VR - session that provides exclusive access to the VR device * with the best available tracking features. * - {@link XRTYPE_AR}: Immersive AR - session that provides exclusive access to the VR/AR * device that is intended to be blended with the real-world environment. * * @param {string} spaceType - Reference space type. Can be one of the following: * * - {@link XRSPACE_VIEWER}: Viewer - always supported space with some basic tracking * capabilities. * - {@link XRSPACE_LOCAL}: Local - represents a tracking space with a native origin near the * viewer at the time of creation. It is meant for seated or basic local XR sessions. * - {@link XRSPACE_LOCALFLOOR}: Local Floor - represents a tracking space with a native origin * at the floor in a safe position for the user to stand. The y-axis equals 0 at floor level. * Floor level value might be estimated by the underlying platform. It is meant for seated or * basic local XR sessions. * - {@link XRSPACE_BOUNDEDFLOOR}: Bounded Floor - represents a tracking space with its native * origin at the floor, where the user is expected to move within a pre-established boundary. * - {@link XRSPACE_UNBOUNDED}: Unbounded - represents a tracking space where the user is * expected to move freely around their environment, potentially long distances from their * starting point. * * @param {object} [options] - Object with options for XR session initialization. * @param {string[]} [options.optionalFeatures] - Optional features for XRSession start. It is * used for getting access to additional WebXR spec extensions. * @param {boolean} [options.imageTracking] - Set to true to attempt to enable {@link XrImageTracking}. * @param {boolean} [options.planeDetection] - Set to true to attempt to enable {@link XrPlaneDetection}. * @param {XrErrorCallback} [options.callback] - Optional callback function called once the * session is started. The callback has one argument Error - it is null if the XR session * started successfully. * @param {boolean} [options.anchors] - Optional boolean to attempt to enable {@link XrAnchors}. * @param {object} [options.depthSensing] - Optional object with parameters to attempt to enable * depth sensing. * @param {string} [options.depthSensing.usagePreference] - Optional usage preference for depth * sensing, can be 'cpu-optimized' or 'gpu-optimized' (XRDEPTHSENSINGUSAGE_*), defaults to * 'cpu-optimized'. Most preferred and supported will be chosen by the underlying depth sensing * system. * @param {string} [options.depthSensing.dataFormatPreference] - Optional data format * preference for depth sensing. Can be 'luminance-alpha' or 'float32' (XRDEPTHSENSINGFORMAT_*), * defaults to 'luminance-alpha'. Most preferred and supported will be chosen by the underlying * depth sensing system. * @example * // On an entity with a camera component * this.entity.camera.startXr(XRTYPE_VR, XRSPACE_LOCAL, { * callback: (err) => { * if (err) { * // failed to start XR session * } else { * // in XR * } * } * }); */ startXr(type: string, spaceType: string, options?: { optionalFeatures?: string[]; imageTracking?: boolean; planeDetection?: boolean; callback?: XrErrorCallback; anchors?: boolean; depthSensing?: { usagePreference?: string; dataFormatPreference?: string; }; }): void; /** * Attempt to end XR session of this camera. * * @param {XrErrorCallback} [callback] - Optional callback function called once session is * ended. The callback has one argument Error - it is null if successfully ended XR session. * @example * // On an entity with a camera component * this.entity.camera.endXr((err) => { * // not anymore in XR * }); */ endXr(callback?: XrErrorCallback): void; /** * Function to copy properties from the source CameraComponent. Properties not copied: * postEffects. Inherited properties not copied (all): system, entity, enabled. * * @param {CameraComponent} source - The source component. * @ignore */ copy(source: CameraComponent): void; } /** * - A parameter of a mesh instance, overriding the value of * the material for that instance. */ type MeshInstanceParameter = { /** * - The name of the uniform. */ name: string; /** * - The value. */ data: any; /** * - The scope id, resolved on first use for scope parameters. */ scopeId: ScopeId | null; /** * - True when the uniform is stored in the material uniform buffer, so * the parameter is applied through the mesh instance's copy of it rather than through the scope. */ override: boolean; /** * - The format of the uniform in the material uniform * buffer, resolved on first use for overrides. */ uniformFormat: UniformFormat | null; /** * - The index of the texture slot of the material bind group the * parameter overrides, or -1 when it does not override a texture of the material. */ textureSlot: number; /** * - The value of the scope the parameter replaced when last applied, * such as a value set globally, restored after the draw when the material does not have the * parameter. */ replacedValue: any; }; /** * Callback used by {@link Layer} to calculate the "sort distance" for a {@link MeshInstance}, * which determines its place in the render order. */ type CalculateSortDistanceCallback = (meshInstance: MeshInstance, cameraPosition: Vec3, cameraForward: Vec3) => number; /** * @callback CalculateSortDistanceCallback * Callback used by {@link Layer} to calculate the "sort distance" for a {@link MeshInstance}, * which determines its place in the render order. * @param {MeshInstance} meshInstance - The mesh instance. * @param {Vec3} cameraPosition - The position of the camera. * @param {Vec3} cameraForward - The forward vector of the camera. * @returns {number} The sort distance for the mesh instance. Mesh instances are sorted by this * value in ascending or descending order depending on the layer's sort mode. */ /** * An instance of a {@link Mesh}. A single mesh can be referenced by many mesh instances that can * have different transforms and materials. * * A mesh instance is created from a {@link Mesh}, a {@link Material} and the {@link GraphNode} * whose world transform places it, and it is drawn only once it belongs to a {@link Layer}. * Components such as {@link RenderComponent} create mesh instances from their assets and add them * to the layers in their `layers` list. A mesh instance you construct yourself is placed either * by assigning it to {@link RenderComponent#meshInstances} or by adding it to a layer directly * with {@link Layer#addMeshInstances}. * * Per-instance rendering state lives here rather than on the shared mesh or material: * {@link visible}, {@link castShadow} and `receiveShadow`, {@link cull} for frustum culling, * {@link drawOrder} for manual sorting, and {@link setParameter} for shader uniforms that override * the material's. {@link aabb} is the world-space bounds derived from the mesh bounds and the * node's transform, and can be assigned to override it. * * ### Instancing * * Hardware instancing lets the GPU draw many copies of the same geometry with a single draw call. * Use {@link setInstancing} to attach a vertex buffer that holds per-instance data * (for example a mat4 world-matrix for every instance). Set {@link instancingCount} * to control how many instances are rendered. Passing `null` to {@link setInstancing} * disables instancing once again. * * ```javascript * // vb is a vertex buffer with one 4×4 matrix per instance * meshInstance.setInstancing(vb); * meshInstance.instancingCount = numInstances; * ``` * * The default matrix format, {@link VertexFormat.getDefaultInstancingFormat}, occupies the * attribute locations of `TEXCOORD6` and `TEXCOORD7`. A material sampling those UV sets on an * instanced mesh needs a custom instancing vertex format on other attributes, as shown by the * instancing-custom example. * * **Examples** * * - {@link https://playcanvas.github.io/#graphics/instancing-basic graphics/instancing-basic} * - {@link https://playcanvas.github.io/#graphics/instancing-custom graphics/instancing-custom} * * ### GPU-Driven Indirect Rendering (WebGPU Only) * * Instead of issuing draw calls from the CPU, parameters are written into a GPU * storage buffer and executed via indirect draw commands. Allocate one or more slots with * `GraphicsDevice.getIndirectDrawSlot(count)`, then bind the mesh instance to those slots: * * ```javascript * const slot = app.graphicsDevice.getIndirectDrawSlot(count); * meshInstance.setIndirect(null, slot, count); // first arg can be a CameraComponent or null * ``` * * **Example** * * - {@link https://playcanvas.github.io/#compute/indirect-draw compute/indirect-draw} * * ### Multi-draw * * Multi-draw lets the engine submit multiple sub-draws with a single API call. On WebGL2 this maps * to the `WEBGL_multi_draw` extension; on WebGPU, to indirect multi-draw. Use {@link setMultiDraw} * to allocate a {@link DrawCommands} container, fill it with sub-draws using * {@link DrawCommands#add} and finalize with {@link DrawCommands#update} whenever the data changes. * * Support: {@link GraphicsDevice#supportsMultiDraw} is true on WebGPU and commonly true on WebGL2 * (high coverage). When not supported, the engine can still render by issuing a fast internal loop * of single draws using the multi-draw data. * * ```javascript * // two indexed sub-draws from a single mesh * const cmd = meshInstance.setMultiDraw(null, 2); * cmd.add(0, 36, 1, 0); * cmd.add(1, 60, 1, 36); * cmd.update(2); * ``` * * ### Precedence * * When draw commands (indirect or multi-draw, see {@link setIndirect} and {@link setMultiDraw}) * are bound, they are the source of truth for rendering: the number of draws and the per-draw * instance counts come from the draw commands, and {@link instancingCount} is ignored. In this * case setting {@link instancingCount} to 0 does not skip rendering. {@link instancingCount} only * takes effect for plain hardware instancing, when no draw commands are bound. * * @category Graphics */ declare class MeshInstance { static lightmapParamNames: string[]; /** * Sets the render style for an array of mesh instances. * * @param {MeshInstance[]} meshInstances - The mesh instances to set the render style for. * @param {number} renderStyle - The render style to set. * @ignore */ static _prepareRenderStyleForArray(meshInstances: MeshInstance[], renderStyle: number): void; /** * Create a new MeshInstance instance. * * @param {Mesh} mesh - The graphics mesh to instance. * @param {Material} material - The material to use for this mesh instance. * @param {GraphNode} [node] - The graph node defining the transform for this instance. This * parameter is optional when used with {@link RenderComponent} and will use the node the * component is attached to. * @example * // Create a mesh instance pointing to a 1x1x1 'cube' mesh * const mesh = Mesh.fromGeometry(app.graphicsDevice, new BoxGeometry()); * const material = new StandardMaterial(); * * const meshInstance = new MeshInstance(mesh, material); * * const entity = new Entity(); * entity.addComponent('render', { * meshInstances: [meshInstance] * }); * * // Add the entity to the scene hierarchy * this.app.scene.root.addChild(entity); */ constructor(mesh: Mesh, material: Material, node?: GraphNode); /** * Enable shadow casting for this mesh instance. Use this property to enable/disable shadow * casting without overhead of removing from scene. Note that this property does not add the * mesh instance to appropriate list of shadow casters on a {@link Layer}, but allows mesh to * be skipped from shadow casting while it is in the list already. Defaults to false. */ castShadow: boolean; /** * Specifies a bitmask that controls which shadow cascades a mesh instance contributes * to when rendered with a {@link LIGHTTYPE_DIRECTIONAL} light source. * This setting is only effective if the {@link castShadow} property is enabled. * Defaults to {@link SHADOW_CASCADE_ALL}, which means the mesh casts shadows into all available cascades. * * @type {number} */ shadowCascadeMask: number; /** * Controls whether the mesh instance can be culled by frustum culling (see * {@link CameraComponent#frustumCulling}). Defaults to true. */ cull: boolean; /** * Determines the rendering order of mesh instances. Only used when mesh instances are added to * a {@link Layer} with {@link Layer#opaqueSortMode} or {@link Layer#transparentSortMode} * (depending on the material) set to {@link SORTMODE_MANUAL}. */ drawOrder: number; /** @ignore */ _drawBucket: number; /** * @type {GraphNode} * @private */ private _node; /** * Enable rendering for this mesh instance. Use visible property to enable/disable rendering * without overhead of removing from scene. But note that the mesh instance is still in the * hierarchy and still in the draw call list. */ visible: boolean; /** * A bitmask controlling which shader passes this mesh instance is rendered in. Bit N * corresponds to the shader pass with index N: the built-in forward pass is * {@link SHADER_FORWARD}, and indices for custom shader passes are obtained from * {@link CameraComponent#setShaderPass}. Defaults to `0xFFFFFFFF` (all passes). For example, * clearing the forward pass bit keeps the mesh in the other passes (such as the camera depth * prepass that feeds Depth of Field) while making it invisible in the rendered color image. * * @type {number} * @example * // clear the forward (color) pass bit, leaving all other pass bits set: the mesh is no longer * // drawn in the color image, but still takes part in the other passes (such as the prepass) * meshInstance.shaderPassMask &= ~(1 << SHADER_FORWARD); * @example * // set the forward (color) pass bit, leaving all other pass bits unchanged * meshInstance.shaderPassMask |= (1 << SHADER_FORWARD); * @example * // exclude the mesh from a custom shader pass set up on the camera (see * // CameraComponent#setShaderPass), leaving all other pass bits set * const customPass = cameraComponent.setShaderPass('custom_rendering'); * meshInstance.shaderPassMask &= ~(1 << customPass); * @example * // test whether the forward (color) pass bit is set * const forwardBitSet = (meshInstance.shaderPassMask & (1 << SHADER_FORWARD)) !== 0; * @example * // set every pass bit (the default value) * meshInstance.shaderPassMask = 0xFFFFFFFF; */ shaderPassMask: number; /** * Read this value in the {@link Scene.EVENT_POSTCULL} event to determine if the object is * actually going to be rendered. */ visibleThisFrame: boolean; /** * Negative scale batching support. * * @ignore */ flipFacesFactor: number; /** * @type {GSplatInstance|null} * @ignore */ gsplatInstance: GSplatInstance | null; /** @ignore */ id: number; /** * Custom function used to customize culling (e.g. for 2D UI elements). * * @type {Function|null} * @ignore */ isVisibleFunc: Function | null; /** * @type {InstancingData|null} * @ignore */ instancingData: InstancingData | null; /** * Map of {@link Camera#id} to the draw commands bound to that camera, with the null key * holding the commands shared by all cameras. Lazily allocated. Keyed by id rather than by * camera so a long-lived mesh instance cannot retain a camera, and with it the camera's node * hierarchy and render target. * * @type {Map|null} * @ignore */ drawCommands: Map | null; /** * Stores mesh metadata used for indirect rendering. Lazily allocated on first access * via getIndirectMetaData(). * * @type {Int32Array|null} * @ignore */ meshMetaData: Int32Array | null; /** * The parameters overriding the material values for this mesh instance, by name. A parameter * naming the uniform of a typed material property is applied through a per-instance copy of the * material uniform buffer (an override), any other parameter is set on the scope before the * draw. The two groups are also kept in dense lists for the render loop. * * @type {Map} * @ignore */ parameters: Map; /** * The parameters set on the scope before the draw. * * @type {MeshInstanceParameter[]} * @private */ private _scopeParameters; /** * The parameters overriding uniforms of the material uniform buffer. * * @type {MeshInstanceParameter[]} * @private */ private _materialOverrides; /** * The parameters overriding textures of the material bind group. * * @type {MeshInstanceParameter[]} * @private */ private _materialTextureOverrides; /** * The layout version of the material the parameters were last split against, see * {@link Material#layoutVersion}. * * @type {number} * @private */ private _materialLayoutVersion; /** * Incremented when an override of the material uniform buffer is added, removed or changed. * * @type {number} * @private */ private _materialOverridesVersion; /** * The per-instance copy of the material uniform buffer with the overrides applied, created on * first use, or null. * * @type {UniformBuffer|null} * @private */ private _materialUniformBuffer; /** * The bind group holding {@link MeshInstance#_materialUniformBuffer}. * * @type {BindGroup|null} * @private */ private _materialBindGroup; /** * The material uniform data version the copy was last synchronized with. * * @type {number} * @private */ private _syncedMaterialDataVersion; /** * The overrides version the copy was last synchronized with. * * @type {number} * @private */ private _syncedOverridesVersion; /** * True if the mesh instance is pickable by the {@link Picker}. Defaults to true. * * @ignore */ pick: boolean; /** * The stencil parameters for front faces or null if no stencil is enabled. * * @type {StencilParameters|null} * @ignore */ stencilFront: StencilParameters | null; /** * The stencil parameters for back faces or null if no stencil is enabled. * * @type {StencilParameters|null} * @ignore */ stencilBack: StencilParameters | null; /** * True if the material of the mesh instance is transparent. Optimization to avoid accessing * the material. Updated by the material instance itself. * * @ignore */ transparent: boolean; /** @private */ private _aabb; /** @private */ private _aabbVer; /** @private */ private _aabbMeshVer; /** * The slot of the mesh instance in the mesh instance storage of the device, or -1 when it has * none, see {@link GraphicsDevice#meshInstanceStorage}. Allocated on the first draw with a * shader reading it. * * @type {number} * @ignore */ storageSlot: number; /** * The transform version of the node the slot was last written for, see * {@link Renderer#updateStorageSlot}. * * @type {number} * @ignore */ storageSlotVersion: number; /** * @type {BoundingBox|null} * @private */ private _customAabb; /** @private */ private _updateAabb; /** @private */ private _updateAabbFunc; /** * The internal sorting key used by the shadow renderer: the id of the shadow shader the mesh * instance was last rendered with, scaled above the 22 bits of the id of its material. * * @ignore */ _sortKeyShadow: number; /** * The internal sorting key used by the forward renderer, in case SORTMODE_MATERIALMESH sorting * is used. * * @private */ private _sortKeyForward; /** * The internal sorting key used by the forward renderer, in case SORTMODE_BACK2FRONT or * SORTMODE_FRONT2BACK sorting is used. * * @ignore */ _sortKeyDynamic: number; /** @private */ private _layer; /** * @type {Material|null} * @private */ private _material; /** * @type {SkinInstance|null} * @private */ private _skinInstance; /** * @type {MorphInstance|null} * @private */ private _morphInstance; /** @private */ private _receiveShadow; /** @private */ private _renderStyle; /** @private */ private _screenSpace; /** * The cache of shaders, indexed by a hash value. * * @type {Map} * @private */ private _shaderCache; /** * The shader defines: 24 bits of flags, and the light mask in the top 8 bits, see * SHADERDEF_MASK_SHIFT. Defaults to no flags and a mask of MASK_AFFECT_DYNAMIC. * * @private */ private _shaderDefs; /** * @type {CalculateSortDistanceCallback|null} * @private */ private _calculateSortDistance; /** * Sets the graph node defining the transform for this instance. * * @type {GraphNode} */ set node(node: GraphNode); /** * Gets the graph node defining the transform for this instance. * * @type {GraphNode} */ get node(): GraphNode; _mesh: Mesh; /** * Sets the material used by this mesh instance. * * @type {Material|null} */ set material(material: Material | null); /** * Gets the material used by this mesh instance. * * @type {Material|null} */ get material(): Material | null; /** * Sets the draw bucket for mesh instances. The draw bucket, an integer from 0 to 255 (default * 127), serves as the primary sort key for mesh rendering. Meshes are sorted by draw bucket, * then by sort mode. This setting is only effective when mesh instances are added to a * {@link Layer} with its {@link Layer#opaqueSortMode} or {@link Layer#transparentSortMode} * (depending on the material) set to {@link SORTMODE_BACK2FRONT}, {@link SORTMODE_FRONT2BACK}, * or {@link SORTMODE_MATERIALMESH}. * * Note: When {@link SORTMODE_BACK2FRONT} is used, a descending sort order is used; otherwise, * an ascending sort order is used. * * @type {number} */ set drawBucket(bucket: number); /** * Gets the draw bucket for mesh instance. * * @type {number} */ get drawBucket(): number; /** * Sets the render style of the mesh instance. Can be: * * - {@link RENDERSTYLE_SOLID} * - {@link RENDERSTYLE_WIREFRAME} * - {@link RENDERSTYLE_POINTS} * * Defaults to {@link RENDERSTYLE_SOLID}. * * @type {number} */ set renderStyle(renderStyle: number); /** * Gets the render style of the mesh instance. * * @type {number} */ get renderStyle(): number; /** * Sets the graphics mesh being instanced. * * @type {Mesh|null} */ set mesh(mesh: Mesh | null); /** * Gets the graphics mesh being instanced. * * @type {Mesh|null} */ get mesh(): Mesh | null; /** * Sets the world space axis-aligned bounding box for this mesh instance. * * @type {BoundingBox} */ set aabb(aabb: BoundingBox); /** * Gets the world space axis-aligned bounding box for this mesh instance. * * @type {BoundingBox} */ get aabb(): BoundingBox; /** * Clear the internal shader cache. * * @ignore */ clearShaders(): void; /** * Returns the shader instance for the specified shader pass and lights that is compatible * with this mesh instance. * * @param {number} shaderPass - The shader pass index. * @param {LightList} lightList - The lights of the pass. * @param {Scene} scene - The scene. * @param {CameraShaderParams} cameraShaderParams - The camera shader parameters. * @param {UniformBufferFormat} [viewUniformFormat] - The format of the view uniform buffer. * @returns {ShaderInstance} - the shader instance. * @ignore */ getShaderInstance(shaderPass: number, lightList: LightList, scene: Scene, cameraShaderParams: CameraShaderParams, viewUniformFormat?: UniformBufferFormat): ShaderInstance; /** * @param {number} shaderDefs - The shader definitions to set. * @private */ private _updateShaderDefs; /** * Sets the callback to calculate sort distance. In some circumstances mesh instances are * sorted by a distance calculation to determine their rendering order. Set this callback to * override the default distance calculation, which gives the dot product of the camera forward * vector and the vector between the camera position and the center of the mesh instance's * axis-aligned bounding box. This option can be particularly useful for rendering transparent * meshes in a better order than the default. * * @type {CalculateSortDistanceCallback|null} */ set calculateSortDistance(calculateSortDistance: CalculateSortDistanceCallback | null); /** * Gets the callback to calculate sort distance. * * @type {CalculateSortDistanceCallback|null} */ get calculateSortDistance(): CalculateSortDistanceCallback | null; set receiveShadow(val: boolean); get receiveShadow(): boolean; set batching(val: boolean); get batching(): boolean; /** * Sets the skin instance managing skinning of this mesh instance. Set to null if skinning is * not used. * * @type {SkinInstance|null} */ set skinInstance(val: SkinInstance | null); /** * Gets the skin instance managing skinning of this mesh instance. * * @type {SkinInstance|null} */ get skinInstance(): SkinInstance | null; /** * Sets the morph instance managing morphing of this mesh instance. Set to null if morphing is * not used. * * @type {MorphInstance|null} */ set morphInstance(val: MorphInstance | null); /** * Gets the morph instance managing morphing of this mesh instance. * * @type {MorphInstance|null} */ get morphInstance(): MorphInstance | null; set screenSpace(val: boolean); get screenSpace(): boolean; set key(val: number); get key(): number; /** * Sets the light mask of this mesh instance: which {@link LightComponent}s light it. The value * is a combination of `MASK_AFFECT_DYNAMIC`, `MASK_AFFECT_LIGHTMAPPED` and `MASK_BAKE`, and * only its lowest 8 bits are used. Defaults to `MASK_AFFECT_DYNAMIC`. * * @type {number} */ set mask(val: number); /** * Gets the light mask of this mesh instance: which {@link LightComponent}s light it. * * @type {number} */ get mask(): number; /** * Sets the number of instances when using hardware instancing to render the mesh. * * @type {number} */ set instancingCount(value: number); /** * Gets the number of instances when using hardware instancing to render the mesh. * * @type {number} */ get instancingCount(): number; destroy(): void; destroyDrawCommands(): void; /** * Returns the shader defines with {@link SHADERDEF_INSTANCEINDEX} set when the draws of this * mesh instance use the instance index for their own data: draw commands set the first * instance of their draws, and instancing without a vertex buffer indexes the data of the * instances by it. The shaders of other draws read the mesh instance storage by it. * * @param {number} shaderDefs - The shader defines. * @returns {number} The shader defines with the flag updated. * @private */ private _applyInstanceIndexDef; /** * Test if meshInstance is visible by camera. It requires the frustum of the camera to be up to * date, which forward-renderer takes care of. This function should not be called elsewhere. * * @param {Camera} camera - The camera to test visibility against. * @returns {boolean} - True if the mesh instance is visible by the camera, false otherwise. * @ignore */ _isVisible(camera: Camera): boolean; updateKey(): void; /** * Sets up {@link MeshInstance} to be rendered using Hardware Instancing. * Note that {@link instancingCount} is automatically set to the number of vertices of the * vertex buffer when it is provided. * * @param {VertexBuffer|true|null} vertexBuffer - Vertex buffer to hold per-instance vertex data * (usually world matrices). Pass `true` to enable attributeless instancing where the instance * index is derived from `gl_InstanceID` / `instance_index` builtins rather than a vertex * buffer attribute — the caller must set {@link instancingCount} manually. Pass null to turn * off hardware instancing. * @param {boolean} cull - Whether to perform frustum culling on this instance. If true, the whole * instance will be culled by the camera frustum. This often involves setting * {@link RenderComponent#customAabb} containing all instances. Defaults to false, which means * the whole instance is always rendered. */ setInstancing(vertexBuffer: VertexBuffer | true | null, cull?: boolean): void; /** * Sets the {@link MeshInstance} to be rendered using indirect rendering, where the GPU, * typically using a Compute shader, stores draw call parameters in a buffer. * Note that this is only supported on WebGPU (see * {@link GraphicsDevice#supportsIndirectDraw}), and ignored on other platforms, where the * mesh instance renders as a normal draw call. * * @param {CameraComponent|null} camera - Camera component to set indirect data for, or * null if the indirect slot should be used for all cameras. * @param {number} slot - Slot in the buffer to set the draw call parameters. Allocate a slot * in the buffer by calling {@link GraphicsDevice#getIndirectDrawSlot}. Pass -1 to disable * indirect rendering for the specified camera (or the shared entry when camera is null). * @param {number} [count] - Optional number of consecutive slots to use. Defaults to 1. */ setIndirect(camera: CameraComponent | null, slot: number, count?: number): void; /** * Sets the {@link MeshInstance} to be rendered using multi-draw, where multiple sub-draws are * executed with a single draw call. * * Note: Each call to this method invalidates any previously stored draw command data for the * specified camera. * * @param {CameraComponent|null} camera - Camera component to bind commands to, or null to share * across all cameras. * @param {number} [maxCount] - Maximum number of sub-draws to allocate. Defaults to 1. Pass 0 * to disable multi-draw for the specified camera (or the shared entry when camera is null). * @returns {DrawCommands|undefined} The commands container to populate with sub-draw commands. */ setMultiDraw(camera: CameraComponent | null, maxCount?: number): DrawCommands | undefined; /** * Returns the cached draw commands for a key, allocating them when missing. A cached set of * the other kind is released first - indirect and multi-draw commands draw from different * backing storage, so they cannot share an instance. * * @param {number|null} key - The {@link Camera#id} the commands are bound to, or null for the * set shared by all cameras. * @param {boolean} multiDraw - True for multi-draw commands, false for indirect ones. * @returns {DrawCommands} The draw commands to populate. * @private */ private _allocDrawCommands; _deleteDrawCommandsKey(key: any): void; /** * Retrieves the draw commands for a specific camera, or the default commands when none are * bound to that camera. * * @param {Camera} camera - The camera to retrieve commands for. * @returns {DrawCommands|undefined} - The draw commands, or undefined. * @ignore */ getDrawCommands(camera: Camera): DrawCommands | undefined; /** * Retrieves the mesh metadata needed for indirect rendering. * * @returns {Int32Array} - A typed array with 4 elements representing the mesh metadata, which * is typically needed when generating indirect draw call parameters using Compute shader. These * can be provided to the Compute shader using vec4i uniform. The values are based on * {@link Mesh#primitive}, stored in this order: [count, base, baseVertex, 0]. The last value is * always zero and is reserved for future use. */ getIndirectMetaData(): Int32Array; ensureMaterial(device: any): void; clearParameters(): void; getParameters(): Map; /** * Retrieves the specified shader parameter from a mesh instance. * * @param {string} name - The name of the parameter to query. * @returns {object|undefined} The named parameter, or `undefined` if no parameter with that * name is set on this mesh instance. */ getParameter(name: string): object | undefined; /** * Sets a shader parameter on a mesh instance. Note that this parameter will take precedence * over parameter of the same name if set on Material this mesh instance uses for rendering. * To change an array value, call this method again with it; the contents of an array are not * guaranteed to be re-read on later draws. * * @param {string} name - The name of the parameter to set. * @param {number|number[]|Texture|Float32Array} data - The value for the specified parameter. */ setParameter(name: string, data: number | number[] | Texture | Float32Array): void; /** * A wrapper over settings parameter specifically for realtime baked lightmaps. This handles * reference counting of lightmaps and releases them when no longer referenced. * * @param {string} name - The name of the parameter to set. * @param {Texture|null} texture - The lightmap texture to set. * @ignore */ setRealtimeLightmap(name: string, texture: Texture | null): void; /** * Deletes a shader parameter on a mesh instance. * * @param {string} name - The name of the parameter to delete. */ deleteParameter(name: string): void; /** * Used to apply parameters from this mesh instance into scope of uniforms, called internally * by forward-renderer. Parameters overriding uniforms of the material uniform buffer are not * part of this, they are applied by {@link MeshInstance#getMaterialBindGroup}. * * @param {GraphicsDevice} device - The graphics device. * @ignore */ setParameters(device: GraphicsDevice): void; /** * Restores the scope values the parameters of this mesh instance replaced, such as values set * globally, for the parameters its material does not have - no material sets those again for * the draws that follow. The parameters the material has are restored to its values when the * next draw uses the same material. Called internally by the renderers after a draw. * * @param {Material} material - The material the mesh instance was drawn with. * @ignore */ restoreReplacedParameters(material: Material): void; /** * Adds a parameter to the scope list, or to the overrides of the material uniform buffer when * its name is the uniform of a typed property of the material. * * @param {MeshInstanceParameter} parameter - The parameter. * @private */ private _addParameter; /** * Splits the parameters between the scope and the material uniform buffer again, after the * material or its set of typed properties changed. * * @private */ private _rebuildParameterLists; /** * Returns the bind group to use at the material bind group index for this mesh instance: a * per-instance copy of the material's bind group with the overriding parameters applied, or * null when no parameter overrides anything in it, in which case the material's own bind group * is used. The copy of the uniform buffer is synchronized when the material data or the * overrides changed; the textures are assigned every time, as they are only references. * * @param {GraphicsDevice} device - The graphics device. * @returns {BindGroup|null} The bind group of the overriding copy, or null. * @ignore */ getMaterialBindGroup(device: GraphicsDevice): BindGroup | null; _debugWarnedOverridesVersion: any; /** * Releases the per-instance copy of the material uniform buffer. * * @private */ private _destroyMaterialUniformBuffer; /** * @param {boolean} value - True to enable lightmapped rendering, false to disable. * @ignore */ setLightmapped(value: boolean): void; /** * @param {BoundingBox|null} aabb - The custom axis-aligned bounding box or null to reset to * the mesh's bounding box. * @ignore */ setCustomAabb(aabb: BoundingBox | null): void; /** @private */ private _setupSkinUpdate; } /** * Internal data structure used to store data used by hardware instancing. * * @ignore */ declare class InstancingData { /** * @param {number} numObjects - The number of objects instanced. */ constructor(numObjects: number); /** @type {VertexBuffer|null} */ vertexBuffer: VertexBuffer | null; /** * True if the vertex buffer is destroyed when the mesh instance is destroyed. */ _destroyVertexBuffer: boolean; count: number; destroy(): void; } /** * Internal helper class for storing the shader and related mesh bind group in the shader cache. * * @ignore */ declare class ShaderInstance { /** * A shader. * * @type {Shader|undefined} */ shader: Shader | undefined; /** * A bind group storing mesh textures / samplers for the shader. but not the uniform buffer. * * @type {BindGroup|null} */ bindGroup: BindGroup | null; /** * A uniform buffer storing mesh uniforms for the shader. * * @type {UniformBuffer|null} */ uniformBuffer: UniformBuffer | null; /** * The full array of hashes used to lookup the pipeline, used in case of hash collision. * * @type {Uint32Array} */ hashes: Uint32Array; /** * Returns the mesh bind group for the shader. * * @param {GraphicsDevice} device - The graphics device. * @returns {BindGroup} - The mesh bind group. */ getBindGroup(device: GraphicsDevice): BindGroup; /** * Returns the uniform buffer for the shader. * * @param {GraphicsDevice} device - The graphics device. * @returns {UniformBuffer} - The uniform buffer. */ getUniformBuffer(device: GraphicsDevice): UniformBuffer; destroy(): void; } /** * Options of the `light` component accepted by {@link LightComponentSystem} that differ from the * properties of {@link LightComponent}. Each replaces the same-named property of the options that * {@link Entity#addComponent} derives from the component class; see * {@link ComponentOptionsOverrides}. */ type LightComponentOptionsOverrides = { /** * - Same as {@link LightComponent#color}, also accepting an * `[r, g, b]` array. */ color?: Color | number[]; /** * - Same as {@link LightComponent#cookieOffset}, also * accepting an `[x, y]` array. */ cookieOffset?: Vec2 | number[]; /** * - Same as {@link LightComponent#cookieScale}, also * accepting an `[x, y]` array. */ cookieScale?: Vec2 | number[]; /** * - Deprecated alias of `enabled`. */ enable?: boolean; }; /** * @import { AppBase } from '../../app-base.js' * @import { Entity } from '../../entity.js' */ /** * Options of the `light` component accepted by {@link LightComponentSystem} that differ from the * properties of {@link LightComponent}. Each replaces the same-named property of the options that * {@link Entity#addComponent} derives from the component class; see * {@link ComponentOptionsOverrides}. * * @typedef {object} LightComponentOptionsOverrides * @property {Color | number[]} [color] - Same as {@link LightComponent#color}, also accepting an * `[r, g, b]` array. * @property {Vec2 | number[]} [cookieOffset] - Same as {@link LightComponent#cookieOffset}, also * accepting an `[x, y]` array. * @property {Vec2 | number[]} [cookieScale] - Same as {@link LightComponent#cookieScale}, also * accepting an `[x, y]` array. * @property {boolean} [enable] - Deprecated alias of `enabled`. * @ignore */ /** * Manages the {@link LightComponent}s of an application. Reach it through `app.systems.light`; * components are created with {@link Entity#addComponent}, never by calling the system directly. * * @category Graphics */ declare class LightComponentSystem extends ComponentSystem { id: string; ComponentType: typeof LightComponent; initializeComponentData(component: any, _data: any): void; onBeforeRemove(entity: any, component: any): void; cloneComponent(entity: any, clone: any): Component; } /** * The LightComponent enables an {@link Entity} to light the scene. There are three types of light: * * - `directional`: A global light that emits light in the direction of the negative y-axis of the * owner entity. Emulates light sources that appear to be infinitely far away such as the sun. The * owner entity's position is effectively ignored. * - `omni`: A local light that emits light in all directions from the owner entity's position. * Emulates candles, lamps, bulbs, etc. * - `spot`: A local light that emits light similarly to an omni light but is bounded by a cone * centered on the owner entity's negative y-axis. Emulates flashlights, spotlights, etc. * * Directional and spot lights are therefore aimed with the owner entity's rotation, and shine along * its negative y-axis - so an unrotated light shines straight down. Note that * {@link GraphNode#lookAt} orients an entity's negative z-axis, which aims a camera but not a * light: * * ```javascript * // an unrotated light shines straight down * light.setEulerAngles(0, 0, 0); * * // tilted 45 degrees, it shines down and towards negative z * light.setEulerAngles(45, 0, 0); * * // to aim it at a target, lookAt orients the negative z-axis and the extra rotation brings the * // negative y-axis onto it * light.lookAt(target.getPosition()); * light.rotateLocal(90, 0, 0); * * // to aim it along a world space direction, rotate the negative y-axis onto that direction. * // Unlike lookAt, this is well defined even when the direction is straight up or down * const dir = new Vec3(-0.5, -1, -0.3).normalize(); * light.setRotation(new Quat().setFromDirections(Vec3.DOWN, dir)); * * // the direction a light currently shines in is the negative of its world space up vector * const currentDir = light.up.clone().mulScalar(-1); * ``` * * You should never need to use the LightComponent constructor directly. To add a LightComponent * to an {@link Entity}, use {@link Entity#addComponent}: * * ```javascript * const entity = new Entity(); * entity.addComponent('light', { * type: 'omni', * color: new Color(1, 0, 0), * intensity: 2 * }); * ``` * * Once the LightComponent is added to the entity, you can access it via the {@link Entity#light} * property: * * ```javascript * entity.light.intensity = 3; // Set the intensity of the light * * console.log(entity.light.intensity); // Get the intensity of the light * ``` * * Relevant Engine API examples: * * - [Area Lights](https://playcanvas.github.io/#/graphics/area-lights) * - [Clustered Area Lights](https://playcanvas.github.io/#/graphics/clustered-area-lights) * - [Clustered Lighting](https://playcanvas.github.io/#/graphics/clustered-lighting) * - [Clustered Omni Shadows](https://playcanvas.github.io/#/graphics/clustered-omni-shadows) * - [Clustered Spot Shadows](https://playcanvas.github.io/#/graphics/clustered-spot-shadows) * - [Lights](https://playcanvas.github.io/#/graphics/lights) * * @hideconstructor * @category Graphics */ declare class LightComponent extends Component { /** * Create a new LightComponent instance. * * @param {LightComponentSystem} system - The ComponentSystem that created this Component. * @param {Entity} entity - The Entity that this Component is attached to. */ constructor(system: LightComponentSystem, entity: Entity); /** * @type {Light} * @private */ private _light; /** * @type {EventHandle|null} * @private */ private _evtLayersChanged; /** * @type {EventHandle|null} * @private */ private _evtLayerAdded; /** * @type {EventHandle|null} * @private */ private _evtLayerRemoved; /** * @type {Asset|null} * @private */ private _cookieAsset; /** * @type {number|null} * @private */ private _cookieAssetId; /** @private */ private _cookieAssetAdd; /** * @type {Vec4|null} * @private */ private _cookieMatrix; /** * @type {number} * @private */ private _shadowBias; /** * @type {number} * @private */ private _cookieAngle; /** * @type {Vec2|null} * @private */ private _cookieScale; /** * @type {boolean} * @private */ private _castShadows; /** * Mirrors the user-supplied value. {@link Light#affectSpecularity} silently ignores writes for * non-directional lights, so storing it on the component is required to round-trip the user's * intent and re-apply it when the type later becomes directional (via {@link refreshProperties}). * * @type {boolean} * @private */ private _affectSpecularity; /** * @type {boolean} * @private */ private _affectDynamic; /** * @type {boolean} * @private */ private _affectLightmapped; /** * @type {boolean} * @private */ private _bake; /** * @type {number[]} * @private */ private _layers; /** * Preserves the user-facing type string. Required because `'point'` and `'omni'` both map to * the same underlying int on the {@link Light}, so reverse-mapping would normalize the user's * input. * * @type {string} * @private */ private _type; /** * Gets the light component's underlying Light instance. * * @type {Light} * @ignore */ get light(): Light; /** * Sets the type of the light. Can be: * * - `"directional"`: A global light that emits light in the direction of the negative y-axis * of the owner entity. * - `"omni"`: A local light that emits light in all directions from the owner entity's * position. * - `"spot"`: A local light that emits light similarly to an omni light but is bounded by a * cone centered on the owner entity's negative y-axis. * * Defaults to `"directional"`. See {@link LightComponent} for how a light is aimed. * * @type {string} */ set type(value: string); /** * Gets the type of the light. * * @type {string} */ get type(): string; /** * Sets the color of the light in sRGB space. The alpha component of the color is ignored. * Defaults to white (`[1, 1, 1]`). * * @type {Color} */ set color(value: Readonly); /** * Gets the color of the light. Use the setter to update the color. * * @type {Readonly} */ get color(): Readonly; /** * Sets the brightness of the light. Defaults to 1. * * @type {number} */ set intensity(value: number); /** * Gets the brightness of the light. * * @type {number} */ get intensity(): number; /** * Sets the physically-based luminance. Only used if `scene.physicalUnits` is true. Defaults to 0. * * @type {number} */ set luminance(value: number); /** * Gets the physically-based luminance. * * @type {number} */ get luminance(): number; /** * Sets the light source shape. Can be: * * - {@link LIGHTSHAPE_PUNCTUAL}: Infinitesimally small point. * - {@link LIGHTSHAPE_RECT}: Rectangle shape. * - {@link LIGHTSHAPE_DISK}: Disk shape. * - {@link LIGHTSHAPE_SPHERE}: Sphere shape. * * Defaults to {@link LIGHTSHAPE_PUNCTUAL}. * * @type {number} */ set shape(value: number); /** * Gets the light source shape. * * @type {number} */ get shape(): number; /** * Sets whether material specularity will be affected by this light. Only takes effect when * {@link type} is `"directional"`; for other types the value is preserved on the component and * applied if {@link type} later becomes `"directional"`. Defaults to true. * * @type {boolean} */ set affectSpecularity(value: boolean); /** * Gets whether material specularity will be affected by this light. * * @type {boolean} */ get affectSpecularity(): boolean; /** * Sets whether the light will cast shadows. Defaults to false. * * For a directional light, shadows are only rendered out to * {@link LightComponent#shadowDistance} from the viewpoint, which defaults to 40. Size that to * the area the camera actually sees, or shadows simply stop appearing beyond it. * * @type {boolean} */ set castShadows(value: boolean); /** * Gets whether the light will cast shadows. * * @type {boolean} */ get castShadows(): boolean; /** * Sets the distance from the viewpoint beyond which shadows are no longer rendered. Affects * directional lights only. Defaults to 40. * * @type {number} */ set shadowDistance(value: number); /** * Gets the distance from the viewpoint beyond which shadows are no longer rendered. * * @type {number} */ get shadowDistance(): number; /** * Sets the intensity of the shadow darkening. 0 having no effect and 1 meaning shadows are * entirely black. Defaults to 1. * * @type {number} */ set shadowIntensity(value: number); /** * Gets the intensity of the shadow darkening. * * @type {number} */ get shadowIntensity(): number; /** * Sets a multiplier of the light's contribution to the volumetric fog, allowing individual * lights to scatter more or less light than the others, or none at all when set to 0. Only * used by omni and spot lights, when {@link CameraFrame} renders volumetric fog with local * lights enabled. Defaults to 1. * * @type {number} */ set volumetricScattering(value: number); /** * Gets the multiplier of the light's contribution to the volumetric fog. * * @type {number} */ get volumetricScattering(): number; /** * Sets the size of the texture used for the shadow map. Valid sizes are 64, 128, 256, 512, * 1024, 2048. Defaults to 1024. * * @type {number} */ set shadowResolution(value: number); /** * Gets the size of the texture used for the shadow map. * * @type {number} */ get shadowResolution(): number; /** * Set the depth bias for tuning the appearance of the shadow mapping generated by this light. Valid * range is 0 to 1. Defaults to 0.05. * * @type {number} */ set shadowBias(value: number); /** * Get the depth bias for tuning the appearance of the shadow mapping generated by this light. * * @type {number} */ get shadowBias(): number; /** * Sets the number of shadow cascades. Can be 1, 2, 3 or 4. Defaults to 1, representing no * cascades. * * @type {number} */ set numCascades(value: number); /** * Gets the number of shadow cascades. * * @type {number} */ get numCascades(): number; /** * Sets the blend factor for cascaded shadow maps, defining the fraction of each cascade level * used for blending between adjacent cascades. The value should be between 0 and 1. Defaults * to 0, which disables blending between cascades and fading at the shadow distance. Also fades * shadows to fully lit over this fraction of the shadow distance, including when using a single * cascade. For example, a value of 0.1 fades shadows over the last 10% of the shadow distance. * * @type {number} */ set cascadeBlend(value: number); /** * Gets the blend factor for cascaded shadow maps. * * @type {number} */ get cascadeBlend(): number; /** * Sets the number of samples used to bake this light into the lightmap. Defaults to 1. Maximum * value is 255. * * @type {number} */ set bakeNumSamples(value: number); /** * Gets the number of samples used to bake this light into the lightmap. * * @type {number} */ get bakeNumSamples(): number; /** * Sets the angular size in degrees of the area used when baking soft shadow boundaries for the * directional light into the lightmap. Range is 0 to 180. Requires {@link bake} to be set to * true and {@link type} to be `"directional"`. Defaults to 0. * * @type {number} */ set bakeArea(value: number); /** * Gets the angular size in degrees of the area used when baking soft shadow boundaries for * the directional light into the lightmap. * * @type {number} */ get bakeArea(): number; /** * Sets the distribution of subdivision of the camera frustum for individual shadow cascades. * Only used if {@link numCascades} is larger than 1. Can be a value in range of 0 and 1. Value * of 0 represents a linear distribution, value of 1 represents a logarithmic distribution. * Defaults to 0.5. Larger value increases the resolution of the shadows in the near distance. * * @type {number} */ set cascadeDistribution(value: number); /** * Gets the distribution of subdivision of the camera frustum for individual shadow cascades. * * @type {number} */ get cascadeDistribution(): number; /** * Sets the normal offset depth bias. Valid range is 0 to 1. Defaults to 0. * * @type {number} */ set normalOffsetBias(value: number); /** * Gets the normal offset depth bias. * * @type {number} */ get normalOffsetBias(): number; /** * Sets the range of the light. Affects omni and spot lights only. Defaults to 10. * * @type {number} */ set range(value: number); /** * Gets the range of the light. * * @type {number} */ get range(): number; /** * Sets the half-angle (measured in degrees from the light's direction axis to the cone edge) * at which the spotlight cone starts to fade off. The full inner beam angle is twice this * value. Affects spot lights only. Defaults to 40 (i.e. an 80-degree full inner beam). * * @type {number} */ set innerConeAngle(value: number); /** * Gets the half-angle (measured in degrees from the light's direction axis to the cone edge) * at which the spotlight cone starts to fade off. * * @type {number} */ get innerConeAngle(): number; /** * Sets the half-angle (measured in degrees from the light's direction axis to the cone edge) * at which the spotlight cone has faded to nothing. The full outer beam angle is twice this * value. Affects spot lights only. Defaults to 45 (i.e. a 90-degree full outer beam). * * @type {number} */ set outerConeAngle(value: number); /** * Gets the half-angle (measured in degrees from the light's direction axis to the cone edge) * at which the spotlight cone has faded to nothing. * * @type {number} */ get outerConeAngle(): number; /** * Sets the fall off mode for the light. This controls the rate at which a light attenuates * from its position. Can be: * * - {@link LIGHTFALLOFF_LINEAR}: Linear. * - {@link LIGHTFALLOFF_INVERSESQUARED}: Inverse squared. * * Affects omni and spot lights only. Defaults to {@link LIGHTFALLOFF_LINEAR}. * * @type {number} */ set falloffMode(value: number); /** * Gets the fall off mode for the light. * * @type {number} */ get falloffMode(): number; /** * Sets the type of shadows being rendered by this light. Can be: * * - {@link SHADOW_PCF1_32F} * - {@link SHADOW_PCF3_32F} * - {@link SHADOW_PCF5_32F} * - {@link SHADOW_PCF1_16F} * - {@link SHADOW_PCF3_16F} * - {@link SHADOW_PCF5_16F} * - {@link SHADOW_VSM_16F} * - {@link SHADOW_VSM_32F} * - {@link SHADOW_PCSS_32F} * * Defaults to {@link SHADOW_PCF3_32F}. * * @type {number} */ set shadowType(value: number); /** * Gets the type of shadows being rendered by this light. * * @type {number} */ get shadowType(): number; /** * Sets the number of samples used for blurring a variance shadow map. Only odd values are * supported; even values are rounded up to the next odd value. Values should be between 1 and * 25. Defaults to 11. * * @type {number} */ set vsmBlurSize(value: number); /** * Gets the number of samples used for blurring a variance shadow map. * * @type {number} */ get vsmBlurSize(): number; /** * Sets the blurring mode for variance shadow maps. Can be: * * - {@link BLUR_BOX}: Box filter. * - {@link BLUR_GAUSSIAN}: Gaussian filter. May look smoother than box, but requires more samples. * * Defaults to {@link BLUR_GAUSSIAN}. * * @type {number} */ set vsmBlurMode(value: number); /** * Gets the blurring mode for variance shadow maps. * * @type {number} */ get vsmBlurMode(): number; /** * Sets the bias used to fight shadow acne when rendering variance shadow maps. Range is 0 to * 1. Defaults to 0.0025. * * @type {number} */ set vsmBias(value: number); /** * Gets the VSM bias value. * * @type {number} */ get vsmBias(): number; /** * Sets the id of the texture asset to be used as the cookie for this light. Only spot and * omni lights can have cookies. Spot lights expect a 2D texture; omni lights expect a * cubemap. Defaults to null. * * @type {number|null} */ set cookieAsset(value: number | null); /** * Gets the id of the texture asset used as the cookie for this light, or null if none is set. * * @type {number|null} */ get cookieAsset(): number | null; /** * Sets the texture to be used as the cookie for this light. Only spot and omni lights can have * cookies. Spot lights expect a 2D texture; omni lights expect a cubemap. Defaults to null. * * @type {Texture|null} */ set cookie(value: Texture | null); /** * Gets the texture to be used as the cookie for this light. * * @type {Texture|null} */ get cookie(): Texture | null; /** * Sets the cookie texture intensity. Defaults to 1. * * @type {number} */ set cookieIntensity(value: number); /** * Gets the cookie texture intensity. * * @type {number} */ get cookieIntensity(): number; /** * Sets whether normal spotlight falloff is active when a cookie texture is set. When set to * false, a spotlight will work like a pure texture projector (only fading with distance). * Defaults to true. * * @type {boolean} */ set cookieFalloff(value: boolean); /** * Gets whether normal spotlight falloff is active when a cookie texture is set. * * @type {boolean} */ get cookieFalloff(): boolean; /** * Sets the color channels of the cookie texture to use. Can be `"r"`, `"g"`, `"b"`, `"a"` or * `"rgb"`. Defaults to `"rgb"`. * * @type {string} */ set cookieChannel(value: string); /** * Gets the color channels of the cookie texture to use. * * @type {string} */ get cookieChannel(): string; /** * Sets the angle for spotlight cookie rotation in degrees. Defaults to 0. * * @type {number} */ set cookieAngle(value: number); /** * Gets the angle for spotlight cookie rotation (in degrees). * * @type {number} */ get cookieAngle(): number; /** * Sets the spotlight cookie scale. Set to null to use no scaling. Defaults to null. * * @type {Vec2|null} */ set cookieScale(value: Vec2 | null); /** * Gets the spotlight cookie scale. * * @type {Vec2|null} */ get cookieScale(): Vec2 | null; /** * Sets the spotlight cookie position offset. Defaults to null. * * @type {Vec2|null} */ set cookieOffset(value: Vec2 | null); /** * Gets the spotlight cookie position offset. * * @type {Vec2|null} */ get cookieOffset(): Vec2 | null; /** * Sets the shadow update mode. This tells the renderer how often shadows must be updated for * this light. Can be: * * - {@link SHADOWUPDATE_NONE}: Don't render shadows. * - {@link SHADOWUPDATE_THISFRAME}: Render shadows only once (then automatically switches to * {@link SHADOWUPDATE_NONE}). * - {@link SHADOWUPDATE_REALTIME}: Render shadows every frame. * * Defaults to {@link SHADOWUPDATE_REALTIME}. * * @type {number} */ set shadowUpdateMode(value: number); /** * Gets the shadow update mode. * * @type {number} */ get shadowUpdateMode(): number; /** * Sets the bitmask that determines which {@link MeshInstance}s are lit by this light. The * value is composed from `MASK_AFFECT_DYNAMIC`, `MASK_AFFECT_LIGHTMAPPED` and * `MASK_BAKE`, and only its lowest 8 bits are used. The {@link affectDynamic}, * {@link affectLightmapped} and {@link bake} helpers write to the same underlying mask but * maintain their own state and are not recomputed from `mask`, so writing `mask` directly * will not update those helpers (and a subsequent write to a helper may overwrite bits set via * `mask`). Defaults to `MASK_AFFECT_DYNAMIC`. * * @type {number} */ set mask(value: number); /** * Gets the mask to determine which {@link MeshInstance}s are lit by this light. * * @type {number} */ get mask(): number; /** * Sets whether the light will affect non-lightmapped objects. Toggles the * `MASK_AFFECT_DYNAMIC` bit on {@link mask}. Defaults to true. * * @type {boolean} */ set affectDynamic(value: boolean); /** * Gets whether the light will affect non-lightmapped objects. * * @type {boolean} */ get affectDynamic(): boolean; /** * Sets whether the light will affect lightmapped objects. Toggles the * `MASK_AFFECT_LIGHTMAPPED` bit on {@link mask}. Mutually exclusive with {@link bake} on * the mask: enabling one clears the other's mask bit. Defaults to false. * * @type {boolean} */ set affectLightmapped(value: boolean); /** * Gets whether the light will affect lightmapped objects. * * @type {boolean} */ get affectLightmapped(): boolean; /** * Sets whether the light will be rendered into lightmaps. Toggles the `MASK_BAKE` bit * on {@link mask}. Mutually exclusive with {@link affectLightmapped} on the mask: enabling one * clears the other's mask bit. Defaults to false. * * @type {boolean} */ set bake(value: boolean); /** * Gets whether the light will be rendered into lightmaps. * * @type {boolean} */ get bake(): boolean; /** * Sets whether the light's direction will contribute to directional lightmaps. The light must * be enabled and {@link bake} set to true. Be aware that the directional lightmap is an * approximation and can only hold a single direction per pixel. Intersecting multiple lights * with {@link bakeDir} set to true may lead to incorrect-looking specular/bump mapping in the * area of intersection. The error is not always visible though, and is highly scene-dependent. * Defaults to true. * * @type {boolean} */ set bakeDir(value: boolean); /** * Gets whether the light's direction will contribute to directional lightmaps. * * @type {boolean} */ get bakeDir(): boolean; /** * Sets whether the light ever moves. This is an optimization hint. Defaults to false. * * @type {boolean} */ set isStatic(value: boolean); /** * Gets whether the light ever moves. * * @type {boolean} */ get isStatic(): boolean; /** * Sets the array of layer IDs ({@link Layer#id}) to which this light should belong. Don't * push/pop/splice or modify this array. If you want to change it, set a new one instead. * Defaults to [{@link LAYERID_WORLD}]. * * @type {number[]} */ set layers(value: ReadonlyArray); /** * Gets the array of layer IDs ({@link Layer#id}) to which this light should belong. * * @type {ReadonlyArray} */ get layers(): ReadonlyArray; /** * Sets an array of SHADOWUPDATE_ settings per shadow cascade. Set to null if not used. * Defaults to null. * * @type {number[]|null} */ set shadowUpdateOverrides(values: number[] | null); /** * Gets an array of SHADOWUPDATE_ settings per shadow cascade. * * @type {number[]|null} */ get shadowUpdateOverrides(): number[] | null; /** * Sets the number of shadow samples used for soft shadows when the shadow type is * {@link SHADOW_PCSS_32F}. This value should be a positive whole number starting at 1. Higher * values result in smoother shadows but can significantly decrease performance. Defaults to 16. * * @type {number} */ set shadowSamples(value: number); /** * Gets the number of shadow samples used for soft shadows. * * @type {number} */ get shadowSamples(): number; /** * Sets the number of blocker samples used for soft shadows when the shadow type is * {@link SHADOW_PCSS_32F}. These samples are used to estimate the distance between the shadow * caster and the shadow receiver, which is then used for the estimation of contact hardening * in the shadow. This value should be a non-negative whole number. Higher values improve * shadow quality by considering more occlusion points, but can decrease performance. When set * to 0, contact hardening is disabled and the shadow has constant softness. Defaults to 16. * Note that this value can be lower than shadowSamples to optimize performance, often without * large impact on quality. * * @type {number} */ set shadowBlockerSamples(value: number); /** * Gets the number of blocker samples used for contact hardening shadows. * * @type {number} */ get shadowBlockerSamples(): number; /** * Sets the size of penumbra for contact hardening shadows. For area lights, acts as a * multiplier with the dimensions of the area light. For punctual and directional lights it's * the area size of the light. Defaults to 1. * * @type {number} */ set penumbraSize(value: number); /** * Gets the size of penumbra for contact hardening shadows. * * @type {number} */ get penumbraSize(): number; /** * Sets the falloff rate for shadow penumbra for contact hardening shadows. This is a value larger * than or equal to 1. This parameter determines how quickly the shadow softens with distance. * Higher values result in a faster softening of the shadow, while lower values produce a more * gradual transition. Defaults to 1. * * @type {number} */ set penumbraFalloff(value: number); /** * Gets the falloff rate for shadow penumbra for contact hardening shadows. * * @type {number} */ get penumbraFalloff(): number; addLightToLayers(): void; removeLightFromLayers(): void; onLayersChanged(oldComp: any, newComp: any): void; onLayerAdded(layer: any): void; onLayerRemoved(layer: any): void; refreshProperties(): void; onCookieAssetSet(): void; onCookieAssetAdd(asset: any): void; onCookieAssetLoad(): void; onCookieAssetRemove(): void; onBeforeRemove(): void; } /** * A Layer represents a renderable subset of the scene. It can contain a list of mesh instances, * lights and cameras, their render settings and also defines custom callbacks before, after or * during rendering. Layers are organized inside {@link LayerComposition} in a desired order. * * A mesh instance is drawn through the layers it belongs to, and a camera draws only the layers * listed in {@link CameraComponent#layers}. Components place their mesh instances by layer id, for * example through {@link RenderComponent#layers}, and lights through {@link LightComponent#layers}; * mesh instances you create yourself go in with {@link addMeshInstances} and out with * {@link removeMeshInstances}. * * The application creates five layers, reachable by id from {@link Scene#layers}: * {@link LAYERID_WORLD} for the scene itself, {@link LAYERID_DEPTH}, {@link LAYERID_SKYBOX}, * {@link LAYERID_IMMEDIATE} for debug drawing and {@link LAYERID_UI}. Within a layer, opaque and * transparent mesh instances are drawn as two separate parts, ordered by {@link opaqueSortMode} * and {@link transparentSortMode}, and the composition decides where each part falls in the frame. * Set {@link enabled} to false to skip a layer entirely, and use {@link onEnable} and * {@link onDisable} to react to that. * * @example * // Draw a set of mesh instances in a layer of their own, right after the world's opaque objects * const layers = app.scene.layers; * const layer = new Layer({ name: 'Overlay' }); * const world = layers.getLayerById(LAYERID_WORLD); * layers.insert(layer, layers.getOpaqueIndex(world) + 1); * layer.addMeshInstances(meshInstances); * @category Graphics */ declare class Layer { /** * Create a new Layer instance. * * @param {object} options - Object for passing optional arguments. These arguments are the * same as properties of the Layer. */ constructor(options?: object); /** * A unique ID of the layer. Layer IDs are stored inside {@link ModelComponent#layers}, * {@link RenderComponent#layers}, {@link CameraComponent#layers}, * {@link LightComponent#layers} and {@link ElementComponent#layers} instead of names. * Can be used in {@link LayerComposition#getLayerById}. * * @type {number} */ id: number; /** * Name of the layer. Can be used in {@link LayerComposition#getLayerByName}. * * @type {string} */ name: string; /** * @type {boolean} * @private */ private _enabled; /** * @type {number} * @private */ private _refCounter; /** * Defines the method used for sorting opaque (that is, not semi-transparent) mesh * instances before rendering. Can be: * * - {@link SORTMODE_NONE} * - {@link SORTMODE_MANUAL} * - {@link SORTMODE_MATERIALMESH} * - {@link SORTMODE_BACK2FRONT} * - {@link SORTMODE_FRONT2BACK} * * Defaults to {@link SORTMODE_MATERIALMESH}. * * @type {number} */ opaqueSortMode: number; /** * Defines the method used for sorting semi-transparent mesh instances before rendering. Can be: * * - {@link SORTMODE_NONE} * - {@link SORTMODE_MANUAL} * - {@link SORTMODE_MATERIALMESH} * - {@link SORTMODE_BACK2FRONT} * - {@link SORTMODE_FRONT2BACK} * * Defaults to {@link SORTMODE_BACK2FRONT}. * * @type {number} */ transparentSortMode: number; /** * @type {Function|null} * @ignore */ customSortCallback: Function | null; /** * @type {Function|null} * @ignore */ customCalculateSortValues: Function | null; /** @private */ private _clearColorBuffer; /** @private */ private _clearDepthBuffer; /** @private */ private _clearStencilBuffer; /** * Custom function that is called after the layer has been enabled. This happens when: * * - The layer is created with {@link enabled} set to true (which is the default value). * - {@link enabled} was changed from false to true * * @type {Function} */ onEnable: Function; /** * Custom function that is called after the layer has been disabled. This happens when: * * - {@link enabled} was changed from true to false * - `decrementCounter` was called and set the counter to zero. * * @type {Function} */ onDisable: Function; /** * Cached mesh instances, rebuilt from the set after removals. * * @type {MeshInstance[]} * @private */ private _meshInstances; /** * Whether both membership caches need rebuilding from their sets. * * @private */ private _meshInstancesDirty; /** * Mesh instances assigned to this layer, stored in a set. * * @type {Set} * @ignore */ meshInstancesSet: Set; /** * Cached shadow casters, rebuilt from the set after removals. * * @type {MeshInstance[]} * @private */ private _shadowCasters; /** * Shadow casting instances assigned to this layer, stored in a set. * * @type {Set} * @ignore */ shadowCastersSet: Set; /** * Visible (culled) mesh instances assigned to this layer. Looked up by the Camera. * * @type {WeakMap} * @private */ private _visibleInstances; /** * All lights assigned to a layer. * * @type {Light[]} * @private */ private _lights; /** * All lights assigned to a layer stored in a set. * * @type {Set} * @private */ private _lightsSet; /** * Set of light used by clustered lighting (omni and spot, but no directional). * * @type {Set} * @private */ private _clusteredLightsSet; /** * The lights of the layer in the forms the renderer consumes, see {@link LightList}. Rebuilt * lazily by {@link Layer#getLightList} when lights were added or removed, or their key changed. * * @type {LightList} * @private */ private _lightList; /** @private */ private _lightListDirty; /** @private */ private _lightIdHash; /** @private */ private _lightIdHashDirty; /** * True if the objects rendered on the layer require light cube (emitters with lighting do). * * @ignore */ requiresLightCube: boolean; /** * @type {CameraComponent[]} * @ignore */ cameras: CameraComponent[]; /** * @type {Set} * @ignore */ camerasSet: Set; /** * @type {GSplatPlacement[]} * @ignore */ gsplatPlacements: GSplatPlacement[]; /** * @type {Set} * @ignore */ gsplatPlacementsSet: Set; /** * @type {GSplatPlacement[]} * @ignore */ gsplatShadowCasters: GSplatPlacement[]; /** * @type {Set} * @ignore */ gsplatShadowCastersSet: Set; /** * True if the gsplatPlacements array was modified. * * @ignore */ gsplatPlacementsDirty: boolean; /** * True if the composition is invalidated. * * @ignore */ _dirtyComposition: boolean; /** @private */ private _shaderVersion; _renderTime: number; _forwardDrawCalls: number; _shadowDrawCalls: number; /** * Mesh instances assigned to this layer. The cached array is refreshed on access after * removals; callers should use the layer's add/remove methods to change membership. * * @type {MeshInstance[]} * @ignore */ get meshInstances(): MeshInstance[]; /** * Shadow casting instances assigned to this layer. The cached array is refreshed on access * after removals; callers should use the layer's add/remove methods to change membership. * * @type {MeshInstance[]} * @ignore */ get shadowCasters(): MeshInstance[]; /** @private */ private _updateMeshInstanceCaches; /** @private */ private _clearMeshInstanceCaches; /** * Sets the enabled state of the layer. Disabled layers are skipped. Defaults to true. * * @type {boolean} */ set enabled(val: boolean); /** * Gets the enabled state of the layer. * * @type {boolean} */ get enabled(): boolean; /** * Sets whether the camera will clear the color buffer when it renders this layer. * * @type {boolean} */ set clearColorBuffer(val: boolean); /** * Gets whether the camera will clear the color buffer when it renders this layer. * * @type {boolean} */ get clearColorBuffer(): boolean; /** * Sets whether the camera will clear the depth buffer when it renders this layer. * * @type {boolean} */ set clearDepthBuffer(val: boolean); /** * Gets whether the camera will clear the depth buffer when it renders this layer. * * @type {boolean} */ get clearDepthBuffer(): boolean; /** * Sets whether the camera will clear the stencil buffer when it renders this layer. * * @type {boolean} */ set clearStencilBuffer(val: boolean); /** * Gets whether the camera will clear the stencil buffer when it renders this layer. * * @type {boolean} */ get clearStencilBuffer(): boolean; /** * Gets whether the layer contains omni or spot lights. * * @type {boolean} * @ignore */ get hasClusteredLights(): boolean; /** * Gets the lights used by clustered lighting in a set. * * @type {Set} * @ignore */ get clusteredLightsSet(): Set; /** * Increments the usage counter of this layer. By default, layers are created with counter set * to 1 (if {@link Layer.enabled} is true) or 0 (if it was false). Incrementing the counter * from 0 to 1 will enable the layer and call {@link Layer.onEnable}. Use this function to * "subscribe" multiple effects to the same layer. For example, if the layer is used to render * a reflection texture which is used by 2 mirrors, then each mirror can call this function * when visible and {@link Layer.decrementCounter} if invisible. In such case the reflection * texture won't be updated, when there is nothing to use it, saving performance. * * @ignore */ incrementCounter(): void; /** * Decrements the usage counter of this layer. Decrementing the counter from 1 to 0 will * disable the layer and call {@link Layer.onDisable}. * * @ignore */ decrementCounter(): void; /** * Adds a gsplat placement to this layer. * * @param {GSplatPlacement} placement - A placement of a gsplat. * @ignore */ addGSplatPlacement(placement: GSplatPlacement): void; /** * Removes a gsplat placement from this layer. * * @param {GSplatPlacement} placement - A placement of a gsplat. * @ignore */ removeGSplatPlacement(placement: GSplatPlacement): void; /** * Adds a gsplat placement to this layer as a shadow caster. * * @param {GSplatPlacement} placement - A placement of a gsplat. * @ignore */ addGSplatShadowCaster(placement: GSplatPlacement): void; /** * Removes a gsplat placement from the shadow casters of this layer. * * @param {GSplatPlacement} placement - A placement of a gsplat. * @ignore */ removeGSplatShadowCaster(placement: GSplatPlacement): void; /** * Adds an array of mesh instances to this layer. * * @param {MeshInstance[]} meshInstances - Array of {@link MeshInstance}. * @param {boolean} [skipShadowCasters] - Set it to true if you don't want these mesh instances * to cast shadows in this layer. Defaults to false. */ addMeshInstances(meshInstances: MeshInstance[], skipShadowCasters?: boolean): void; /** * Removes multiple mesh instances from this layer. * * @param {MeshInstance[]} meshInstances - Array of {@link MeshInstance}. If they were added to * this layer, they will be removed. * @param {boolean} [skipShadowCasters] - Set it to true if you want to still cast shadows from * removed mesh instances or if they never did cast shadows before. Defaults to false. */ removeMeshInstances(meshInstances: MeshInstance[], skipShadowCasters?: boolean): void; /** * Adds an array of mesh instances to this layer, but only as shadow casters (they will not be * rendered anywhere, but only cast shadows on other objects). * * @param {MeshInstance[]} meshInstances - Array of {@link MeshInstance}. */ addShadowCasters(meshInstances: MeshInstance[]): void; /** * Removes multiple mesh instances from the shadow casters list of this layer, meaning they * will stop casting shadows. * * @param {MeshInstance[]} meshInstances - Array of {@link MeshInstance}. If they were added to * this layer, they will be removed. */ removeShadowCasters(meshInstances: MeshInstance[]): void; /** * Removes all mesh instances from this layer. * * @param {boolean} [skipShadowCasters] - Set it to true if you want to continue the existing mesh * instances to cast shadows. Defaults to false, which removes shadow casters as well. */ clearMeshInstances(skipShadowCasters?: boolean): void; markLightsDirty(): void; hasLight(light: any): boolean; /** * Adds a light to this layer. * * @param {LightComponent} light - A {@link LightComponent}. */ addLight(light: LightComponent): void; /** * Removes a light from this layer. * * @param {LightComponent} light - A {@link LightComponent}. */ removeLight(light: LightComponent): void; /** * Removes all lights from this layer. */ clearLights(): void; /** * Returns the lights of the layer in the forms the renderer consumes, rebuilding them if the * lights changed since, or if clustered lighting was toggled - the local lights take a light * slot only when it is disabled. Callers reading only the directional lights, which do not * depend on it, may leave the flag out. * * @param {boolean} [clustered] - Whether clustered lighting is enabled. Defaults to the value * the list was last built for. * @returns {LightList} The lights of the layer. * @ignore */ getLightList(clustered?: boolean): LightList; evaluateLightHash(localLights: any, directionalLights: any, useIds: any): number; getLightIdHash(): number; /** * Adds a camera to this layer. * * @param {CameraComponent} camera - A {@link CameraComponent}. */ addCamera(camera: CameraComponent): void; /** * Removes a camera from this layer. * * @param {CameraComponent} camera - A {@link CameraComponent}. */ removeCamera(camera: CameraComponent): void; /** * Removes all cameras from this layer. */ clearCameras(): void; /** * @param {MeshInstance[]} drawCalls - Array of mesh instances. * @param {Vec3} camPos - Camera position. * @param {Vec3} camFwd - Camera forward vector. * @private */ private _calculateSortDistances; /** * Get access to culled mesh instances for the provided camera. * * @param {Camera} camera - The camera. * @returns {CulledInstances} The culled mesh instances. * @ignore */ getCulledInstances(camera: Camera): CulledInstances; /** * @param {Camera} camera - The camera to sort the visible mesh instances for. * @param {boolean} transparent - True if transparent sorting should be used. * @ignore */ sortVisible(camera: Camera, transparent: boolean): void; } declare class CulledInstances { /** * Visible opaque mesh instances. * * @type {MeshInstance[]} */ opaque: MeshInstance[]; /** * Visible transparent mesh instances. * * @type {MeshInstance[]} */ transparent: MeshInstance[]; } /** * A camera. * * @ignore */ declare class Camera { /** @private */ private static _flipYProjectionMatrix; /** @private */ private static _webGpuDepthRangeMatrix; /** @private */ private static _applyShaderProjectionScratch; /** * Builds the projection matrix matching shader `matrix_projection` after optional flip-Y * for render targets and optional WebGPU clip-depth range adjustment. * * @param {Mat4} projection - Source projection ({@link Camera#projectionMatrix}). * @param {Mat4} out - Receives the transformed matrix. * @param {boolean} flipY - When true, apply render-target Y flip first. * @param {boolean} applyWebGpuDepthRange - When true, map clip Z from -1..1 to 0..1. * @returns {Mat4} out */ static applyShaderProjectionTransform(projection: Mat4, out: Mat4, flipY: boolean, applyWebGpuDepthRange: boolean): Mat4; /** * @param {GraphicsDevice} graphicsDevice - The graphics device this camera will use for * automatic aspect ratio calculation against the backbuffer size. */ constructor(graphicsDevice: GraphicsDevice); /** * @type {ShaderPassInfo|null} */ shaderPassInfo: ShaderPassInfo | null; /** * @type {FramePassColorGrab|null} */ renderPassColorGrab: FramePassColorGrab | null; /** * @type {FramePassDepthGrab|null} */ renderPassDepthGrab: FramePassDepthGrab | null; /** * The fog parameters. * * @type {FogParams|null} */ fogParams: FogParams | null; /** * Shader parameters used to generate and use matching shaders. * * @type {CameraShaderParams} */ shaderParams: CameraShaderParams; /** * Frame passes used to render this camera. If empty, the camera will render using the default * frame passes. * * @type {FramePass[]} */ framePasses: FramePass[]; /** * Frame passes that execute before this camera's main scene rendering, after the camera's * directional shadow passes. Entries are picked up by the RenderPassForward that renders * this camera's layers. * * @type {FramePass[]} */ beforePasses: FramePass[]; /** * The scene depth texture most recently published for this camera, or null. The uniform it is * published to is global - the last camera to render owns it - so anything wanting the depth of * one camera in particular reads it from here instead. See {@link SceneDepthReader}. * * @type {Texture|null} * @ignore */ sceneDepthMap: Texture | null; /** * The render version {@link Camera#sceneDepthMap} was published in, so a consumer can tell a * texture rendered this frame from one left over from an earlier one. * * @type {number} * @ignore */ sceneDepthMapVersion: number; /** @type {number} */ jitter: number; /** * A unique id of the camera, used where the camera needs to be referenced without retaining * it, for example as a key in {@link MeshInstance} draw command maps. * * @type {number} */ id: number; /** * The graphics device used by this camera. Required so the camera can compute its aspect * ratio from the backbuffer size when no render target is assigned. * * @type {GraphicsDevice} */ device: GraphicsDevice; _aspectRatio: number; _aspectRatioMode: number; _calculateProjection: any; _calculateTransform: any; _clearColor: Color; _clearColors: any; _clearColorBuffer: boolean; _clearDepth: number; _clearDepthBuffer: boolean; _clearStencil: number; _clearStencilBuffer: boolean; _cullFaces: boolean; _farClip: number; _flipFaces: boolean; _fov: number; _frustumCulling: boolean; _horizontalFov: boolean; _layers: number[]; _layersSet: Set; _nearClip: number; _node: any; _orthoHeight: number; _projection: number; _projectionOffset: Vec2; _rect: Vec4; _renderTarget: any; _scissorRect: Vec4; _scissorRectClear: boolean; _aperture: number; _shutter: number; _sensitivity: number; _projMat: Mat4; _projMatDirty: boolean; _projMatSkybox: Mat4; _viewMat: Mat4; _viewMatDirty: boolean; _viewProjMat: Mat4; _viewProjMatDirty: boolean; _shaderMatricesVersion: number; _viewProjInverse: Mat4; _viewProjCurrent: any; _viewProjPrevious: Mat4; _jitters: number[]; frustum: Frustum; /** @type {Set} */ _cullLayers: Set; /** @type {RenderView[]|null} */ _xrViews: RenderView[] | null; _xrProperties: { horizontalFov: boolean; fov: number; aspectRatio: number; farClip: number; nearClip: number; }; destroy(): void; /** * Records the scene depth texture a producer has published for this camera, alongside the render * version it was published in. * * @param {Texture} texture - The texture the depth was rendered to. * @param {number} renderVersion - The render version it was rendered in. * @ignore */ publishSceneDepthMap(texture: Texture, renderVersion: number): void; /** * Store camera matrices required by TAA. Only update them once per frame. */ _storeShaderMatrices(viewProjMat: any, jitterX: any, jitterY: any, renderVersion: any): void; /** * True if the camera clears the full render target. (viewport / scissor are full size) */ get fullSizeClearRect(): boolean; set aspectRatio(newValue: number); get aspectRatio(): number; set aspectRatioMode(newValue: number); get aspectRatioMode(): number; set calculateProjection(newValue: any); get calculateProjection(): any; set calculateTransform(newValue: any); get calculateTransform(): any; set clearColor(newValue: Color); get clearColor(): Color; /** * Sets the clear color of a color attachment of the render target. Attachment 0 is * {@link Camera#clearColor}, and the other attachments of a multiple render target clear to the * same color unless given their own. Passing null removes the color of an attachment, so it * clears to the attachment 0 color again. * * @param {number} index - The index of the color attachment. * @param {Color|null} color - The clear color, or null to clear to the attachment 0 color. */ setClearColor(index: number, color: Color | null): void; /** * Gets the clear color of a color attachment of the render target. * * @param {number} index - The index of the color attachment. * @returns {Color} The clear color of the attachment. */ getClearColor(index: number): Color; set clearColorBuffer(newValue: boolean); get clearColorBuffer(): boolean; set clearDepth(newValue: number); get clearDepth(): number; set clearDepthBuffer(newValue: boolean); get clearDepthBuffer(): boolean; set clearStencil(newValue: number); get clearStencil(): number; set clearStencilBuffer(newValue: boolean); get clearStencilBuffer(): boolean; set cullFaces(newValue: boolean); get cullFaces(): boolean; set farClip(newValue: number); get farClip(): number; set flipFaces(newValue: boolean); get flipFaces(): boolean; set fov(newValue: number); get fov(): number; set frustumCulling(newValue: boolean); get frustumCulling(): boolean; set horizontalFov(newValue: boolean); get horizontalFov(): boolean; set layers(newValue: ReadonlyArray); /** * Gets the layer IDs this camera renders. Use the setter to replace the array; do not mutate * the returned array. * * @type {ReadonlyArray} */ get layers(): ReadonlyArray; get layersSet(): Set; set nearClip(newValue: number); get nearClip(): number; set node(newValue: any); get node(): any; set orthoHeight(newValue: number); get orthoHeight(): number; set projection(newValue: number); get projection(): number; get projectionMatrix(): Mat4; set projectionOffset(newValue: Vec2); get projectionOffset(): Vec2; set rect(newValue: Vec4); get rect(): Vec4; set renderTarget(newValue: any); get renderTarget(): any; set scissorRect(newValue: Vec4); get scissorRect(): Vec4; get viewMatrix(): Mat4; set aperture(newValue: number); get aperture(): number; set sensitivity(newValue: number); get sensitivity(): number; set shutter(newValue: number); get shutter(): number; /** * Sets the list of {@link RenderView}s this camera renders with (one per XR eye/screen), or * null when not rendering an XR session. Set by the XR manager. * * @param {RenderView[]|null} value - The per-view list, or null when not in XR. */ set xrViews(value: RenderView[] | null); /** * @type {RenderView[]|null} */ get xrViews(): RenderView[] | null; /** * True while an XR session owns this camera (equivalent to {@link Camera#xrViews} being set). * * @type {boolean} */ get xrActive(): boolean; /** * Registers a layer to be culled for this camera in the current frame. Used by the renderer's * request/execute mesh-instance culling. * * @param {Layer} layer - The layer to cull for this camera. * @returns {boolean} True if this is the first layer registered for this camera this frame, * letting the caller track the camera exactly once. * @ignore */ addCullLayer(layer: Layer): boolean; /** * Gets the set of layers registered to be culled for this camera in the current frame. For * read-only iteration; use {@link Camera#addCullLayer} and {@link Camera#clearCullLayers} to * mutate it. * * @type {Set} * @ignore */ get cullLayers(): Set; /** * Clears the set of layers registered to be culled for this camera, called once the camera's * culling has been performed. * * @ignore */ clearCullLayers(): void; /** * Calculates the aspect ratio that should be used for the camera, based on the size of the * given render target (or the backbuffer if no render target is given), and the camera's * `rect`. The `rect` is included so that a camera rendering into a sub-region of a render * target gets the aspect ratio of the actual rendered pixel area (important for split-screen * and similar setups, otherwise rendering would appear stretched). * * @param {RenderTarget|null} [rt] - Optional render target. If unspecified, the camera's * own render target (or, if that is also null, the backbuffer) is used. * @returns {number} The computed aspect ratio. */ calculateAspectRatio(rt?: RenderTarget | null): number; /** * Creates a duplicate of the camera. * * @returns {Camera} A cloned Camera. */ clone(): Camera; /** * Copies one camera to another. * * @param {Camera} other - Camera to copy. * @returns {Camera} Self for chaining. */ copy(other: Camera): Camera; _enableRenderPassColorGrab(device: any, enable: any): void; _enableRenderPassDepthGrab(device: any, renderer: any, enable: any): void; _updateViewProjMat(): void; /** * Refreshes the derived per-view matrices of all {@link Camera#xrViews}, using this camera's * parent world transform. The renderer, the gsplat passes and {@link Camera#updateXrFrustum} * call this before reading the per-view matrices. * * Note: this recomputes on every call. Within a frame the parent transform is stable, so the * several calls per frame could be collapsed to a single recompute by guarding on * `device.renderVersion` (as {@link Camera#_storeShaderMatrices} does) - left as a future * optimization, as it needs checking against cameras that render multiple times per frame * (e.g. multiple render targets). */ updateViewTransforms(): void; /** * Updates {@link Camera#frustum} to the combined volume of all XR views, to avoid culling * objects visible in any view (e.g. the right edge of the right eye in stereo rendering). * The views are merged conservatively via {@link Frustum#add}, which handles the asymmetric * per-eye projections real headsets report (matching planes of the two eyes have different * normals, so a simple outermost-plane selection would over-cull at a distance). * * @returns {boolean} True when XR views were present and the frustum was updated, false * otherwise (the caller should fall back to the mono frustum path). * @ignore */ updateXrFrustum(): boolean; /** * Updates {@link Camera#frustum} for the camera's current transform and projection, for * visibility culling. Uses the combined (VIEW_CENTER) view; XR cameras delegate to * {@link Camera#updateXrFrustum}. Honors the {@link Camera#calculateProjection} and * {@link Camera#calculateTransform} overrides. * * @ignore */ updateFrustum(): void; /** * Convert a point from 3D world space to 2D canvas pixel space based on the camera's rect. * * @param {Vec3} worldCoord - The world space coordinate to transform. * @param {number} cw - The width of PlayCanvas' canvas element. * @param {number} ch - The height of PlayCanvas' canvas element. * @param {Vec3} [screenCoord] - 3D vector to receive screen coordinate result. * @returns {Vec3} The screen space coordinate. */ worldToScreen(worldCoord: Vec3, cw: number, ch: number, screenCoord?: Vec3): Vec3; /** * Convert a point from 2D canvas pixel space to 3D world space based on the camera's rect. * * @param {number} x - X coordinate on PlayCanvas' canvas element. * @param {number} y - Y coordinate on PlayCanvas' canvas element. * @param {number} z - The distance from the camera in world space to create the new point. * @param {number} cw - The width of PlayCanvas' canvas element. * @param {number} ch - The height of PlayCanvas' canvas element. * @param {Vec3} [worldCoord] - 3D vector to receive world coordinate result. * @returns {Vec3} The world space coordinate. */ screenToWorld(x: number, y: number, z: number, cw: number, ch: number, worldCoord?: Vec3): Vec3; _evaluateProjectionMatrix(): void; getProjectionMatrixSkybox(): Mat4; getExposure(): number; getScreenSize(sphere: any): number; /** * Returns an array of corners of the frustum of the camera in the local coordinate system of the camera. * * @param {number} [near] - Near distance for the frustum points. Defaults to the near clip distance of the camera. * @param {number} [far] - Far distance for the frustum points. Defaults to the far clip distance of the camera. * @returns {Vec3[]} - An array of corners, using a global storage space. */ getFrustumCorners(near?: number, far?: number): Vec3[]; /** * Sets XR camera properties that should be derived physical camera in {@link XrManager}. * * @param {object} [properties] - Properties object. * @param {number} [properties.aspectRatio] - Aspect ratio. * @param {number} [properties.farClip] - Far clip. * @param {number} [properties.fov] - Field of view. * @param {boolean} [properties.horizontalFov] - Enable horizontal field of view. * @param {number} [properties.nearClip] - Near clip. */ setXrProperties(properties?: { aspectRatio?: number; farClip?: number; fov?: number; horizontalFov?: boolean; nearClip?: number; }): void; /** * Fills the provided array with camera parameters for use in shaders. * The array format is: [1/far, far, near, isOrtho]. * * @param {Float32Array} output - Array to fill with camera parameters. * @returns {Float32Array} The output array. * @ignore */ fillShaderParams(output: Float32Array): Float32Array; } /** * A light. * * @ignore */ declare class Light { /** * Get conversion factor for luminance -> light specific light unit. * * @param {number} type - The type of light. * @param {number} [outerAngle] - The outer angle of a spot light. * @param {number} [innerAngle] - The inner angle of a spot light. * @returns {number} The scaling factor to multiply with the luminance value. */ static getLightUnitConversion(type: number, outerAngle?: number, innerAngle?: number): number; /** * @param {GraphicsDevice} graphicsDevice - The graphics device. * @param {boolean} clusteredLighting - True if the clustered lighting is enabled. */ constructor(graphicsDevice: GraphicsDevice, clusteredLighting: boolean); /** * The Layers the light is on. * * @type {Set} */ layers: Set; /** * True if the clustered lighting is enabled. * * @type {boolean} */ clusteredLighting: boolean; /** * The depth state used when rendering the shadow map. * * @type {DepthState} */ shadowDepthState: DepthState; /** * A multiplier of the light's contribution to the volumetric fog. Only used by omni and spot * lights, when the volumetric fog renders local lights. * * @type {number} */ volumetricScattering: number; /** * The flags used for clustered lighting. Stored as a bitfield, updated as properties change to * avoid those being updated each frame. * * @ignore */ clusteredFlags: number; /** * Storage data for light properties encoded as a Uint32Array. * * @type {Uint32Array} * @ignore */ clusteredData: Uint32Array; /** * Alias for clusteredData using 16bit unsigned integers. * * @type {Uint16Array} * @ignore */ clusteredData16: Uint16Array; /** * Event handle for device restored event. * * @type {EventHandle|null} * @private */ private _evtDeviceRestored; device: GraphicsDevice; id: number; _type: number; _color: Color; _intensity: number; _affectSpecularity: boolean; _luminance: number; _castShadows: boolean; _enabled: boolean; _mask: number; isStatic: boolean; key: number; bakeDir: boolean; bakeNumSamples: number; bakeArea: number; attenuationStart: number; attenuationEnd: number; _falloffMode: number; _shadowType: number; _vsmBlurSize: number; vsmBlurMode: number; vsmBias: number; _cookie: any; cookieIntensity: number; _cookieFalloff: boolean; _cookieChannel: string; _cookieTransform: any; _cookieTransformUniform: Float32Array; _cookieOffset: any; _cookieOffsetUniform: Float32Array; _cookieTransformSet: boolean; _cookieOffsetSet: boolean; _innerConeAngle: number; _outerConeAngle: number; cascades: any; _shadowMatrixPalette: Float32Array; _shadowCascadeDistances: Float32Array; set numCascades(value: any); get numCascades(): any; _cascadeBlend: number; cascadeDistribution: number; _shape: number; _colorLinear: Float32Array; _position: Vec3; _direction: Vec3; _innerConeAngleCos: number; _usePhysicalUnits: any; _shadowMap: any; _shadowCascadesInvalidated: boolean; _shadowRenderParams: any[]; _shadowCameraParams: any[]; _shadowCascadeParams: any; shadowDistance: number; _shadowResolution: number; _shadowBias: number; _shadowIntensity: number; _normalOffsetBias: number; shadowUpdateMode: number; shadowUpdateOverrides: any; _isVsm: boolean; _isPcf: boolean; _isPcss: boolean; _softShadowParams: Float32Array; set shadowSamples(value: number); get shadowSamples(): number; set shadowBlockerSamples(value: number); get shadowBlockerSamples(): number; set penumbraSize(value: any); get penumbraSize(): any; set penumbraFalloff(value: number); get penumbraFalloff(): number; _cookieMatrix: Mat4; _atlasViewport: Vec4; atlasViewportAllocated: boolean; atlasVersion: number; atlasSlotIndex: number; atlasSlotUpdated: boolean; cookieRenderVersion: number; _node: any; _renderData: any[]; visibleThisFrame: boolean; maxScreenSize: number; destroy(): void; onDeviceRestored(): void; releaseRenderData(): void; addLayer(layer: any): void; removeLayer(layer: any): void; set shadowBias(value: number); get shadowBias(): number; set cascadeBlend(value: number); get cascadeBlend(): number; set shadowMap(shadowMap: any); get shadowMap(): any; set mask(value: number); get mask(): number; get numShadowFaces(): any; set type(value: number); get type(): number; set shadowType(value: number); get shadowType(): number; set shape(value: number); get shape(): number; set usePhysicalUnits(value: any); get usePhysicalUnits(): any; set enabled(value: boolean); get enabled(): boolean; set castShadows(value: boolean); get castShadows(): boolean; set shadowIntensity(value: number); get shadowIntensity(): number; get bakeShadows(): boolean; set shadowResolution(value: number); get shadowResolution(): number; set vsmBlurSize(value: number); get vsmBlurSize(): number; set normalOffsetBias(value: number); get normalOffsetBias(): number; set falloffMode(value: number); get falloffMode(): number; set innerConeAngle(value: number); get innerConeAngle(): number; set outerConeAngle(value: number); get outerConeAngle(): number; _penumbraSize: any; _updateOuterAngle(angle: any): void; _outerConeAngleCos: number; _outerConeAngleSin: number; set intensity(value: number); get intensity(): number; set affectSpecularity(value: boolean); get affectSpecularity(): boolean; set luminance(value: number); get luminance(): number; get cookieMatrix(): Mat4; get atlasViewport(): Vec4; set cookie(value: any); get cookie(): any; set cookieFalloff(value: boolean); get cookieFalloff(): boolean; set cookieChannel(value: string); get cookieChannel(): string; set cookieTransform(value: any); get cookieTransform(): any; set cookieOffset(value: any); get cookieOffset(): any; beginFrame(): void; _destroyShadowMap(): void; getRenderData(camera: any, face: any): any; /** * Duplicates a light node but does not 'deep copy' the hierarchy. * * @returns {Light} A cloned Light. */ clone(): Light; _getUniformBiasValues(lightRenderData: any): { bias: number; normalBias: number; }; getColor(): Color; getBoundingSphere(sphere: any): void; getBoundingBox(box: any): void; _updateShadowBias(): void; _updateLinearColor(): void; setColor(...args: any[]): void; layersDirty(): void; /** * Updates an integer key for the light. The key is used to identify all shader related features * of the light, and so needs to have all properties that modify the generated shader encoded. * Properties without an effect on the shader (color, shadow intensity) should not be encoded. */ updateKey(): void; /** * Updates 32bit flags used by the clustered lighting. This only stores constant data. * Note: this needs to match shader code in clusteredLight.js */ updateClusteredFlags(): void; /** * Adds per-frame dynamic data to the 32bit flags used by the clustered lighting. */ getClusteredFlags(castShadows: any, useCookie: any): number; updateClusterData(updateColor: any, updateAngles: any): void; } /** * The lights of a set that take part in rendering, in the forms the renderer consumes. A layer * owns one for its lights and rebuilds it lazily when they change, and the lightmapper owns one * for the single light it bakes at a time. * * The central form is the light slots: the lights applied at runtime, in the order that gives each * its slot in a shader - `light_` is the light at index N. The slot order is the same for every * mesh instance in a pass whatever its light mask selects, so a light's uniforms are dispatched * once per pass and each shader reads its own slots. The shader generator, the shader variant hash * and the light dispatch all read this one array, so they cannot disagree. * * @ignore */ declare class LightList { /** * The lights applied at runtime, in slot order. Directional lights, then - when clustered * lighting is disabled - omni and spot lights, since clustered lighting supplies the local * lights another way. A light that only contributes to a lightmap reaches nothing at runtime * and takes no slot. * * @type {Light[]} */ slots: Light[]; /** * The enabled directional lights, in no particular order. Read by the shadow cull and the * gsplat shadow renderer, which look for the shadow casters among them. * * @type {Light[]} */ directional: Light[]; /** * The keys of the slot lights, joined in slot order. Identifies the layout of the lights, and * so the shader code and the uniform layout they generate. * * @type {string} */ key: string; /** * A hash of {@link LightList#key}, for the shader variant hash. * * @type {number} */ hash: number; /** * Whether the slots were built for clustered lighting. * * @type {boolean} */ clustered: boolean; /** * Rebuilds every form from the given lights. The arrays are reused, so nothing is allocated * on a rebuild but the key. * * @param {Light[]} lights - The lights of the set, enabled or not. * @param {boolean} clustered - Whether clustered lighting is enabled, in which case the local * lights take no slot. */ update(lights: Light[], clustered: boolean): void; } /** * Describes a typed material property whose value is stored in the material uniform buffer: the * public property name, the uniform it feeds, the uniform type and the conversion from the public * value to the uniform data. Descriptors are static, one per property of a material class, and * are shared by all instances of that class. * * @ignore */ declare class MaterialProperty { /** * @param {string} name - The public property name. * @param {string} uniformName - The name of the uniform in the material uniform buffer. * @param {number} type - The type of the uniform, one of UNIFORMTYPE_***. * @param {(value: any, storage: Float32Array, offset: number, material: Material) => void} convert - Converts * the public value into the uniform data, reading any other property it depends on from the * material. * @param {number} [count] - The array size of the uniform. Defaults to 0 (not an array). */ constructor(name: string, uniformName: string, type: number, convert: (value: any, storage: Float32Array, offset: number, material: Material) => void, count?: number); /** * The public property name, for example 'diffuse'. * * @type {string} */ name: string; /** * The name of the field storing the public value on the material, for example '_diffuse'. * * @type {string} */ backingName: string; /** * The name of the uniform in the material uniform buffer, for example 'material_diffuse'. * * @type {string} */ uniformName: string; /** * The type of the uniform, one of UNIFORMTYPE_***. * * @type {number} */ type: number; /** * The array size of the uniform, 0 for a non-array uniform. * * @type {number} */ count: number; /** * Writes the uniform data for a public value into the float storage of a uniform buffer at * the given element offset. A uniform derived from several properties reads the others from * the material. * * @type {(value: any, storage: Float32Array, offset: number, material: Material) => void} */ convert: (value: any, storage: Float32Array, offset: number, material: Material) => void; /** * A string describing the uniform of the property, used to build and order the layout key. * * @type {string} */ key: string; } /** * A texture of a standard material, which is one slot of its bind group and one sampler of its * shader. */ type MaterialTextureDescriptor = { /** * - The name of the texture uniform, `texture_Map`. */ name: string; /** * - The name of the sampler which goes with it, as the WGSL chunks * declare it. */ samplerName: string; /** * - The property of the material holding the texture, `Map`. */ mapName: string; }; /** * - The description of the parameters used by the * Material#getShaderVariant function. */ type ShaderVariantParams = { /** * - The graphics device. */ device: GraphicsDevice; /** * - The scene. */ scene: Scene; /** * - The object definitions. */ objDefs: number; /** * - The camera shader parameters. */ cameraShaderParams: CameraShaderParams; /** * - The shader pass. */ pass: number; /** * - The lights of the pass. */ lightList: LightList; /** * - The view uniform format. */ viewUniformFormat?: UniformBufferFormat | null; /** * - The vertex format. */ vertexFormat: VertexFormat; }; /** * @typedef {object} ShaderVariantParams - The description of the parameters used by the * Material#getShaderVariant function. * @property {GraphicsDevice} device - The graphics device. * @property {Scene} scene - The scene. * @property {number} objDefs - The object definitions. * @property {CameraShaderParams} cameraShaderParams - The camera shader parameters. * @property {number} pass - The shader pass. * @property {LightList} lightList - The lights of the pass. * @property {UniformBufferFormat|null} [viewUniformFormat] - The view uniform format. * @property {VertexFormat} vertexFormat - The vertex format. * @ignore */ /** * A material determines how a particular {@link MeshInstance} is rendered, and specifies * render state including uniforms, textures, defines, and other properties. * * This is a base class and cannot be instantiated and used directly. Only subclasses such * as {@link ShaderMaterial} and {@link StandardMaterial} can be used to define materials * for rendering. * * Choose {@link StandardMaterial} for a physically based surface described by properties and * textures, and {@link ShaderMaterial} to supply your own vertex and fragment shaders. Both share * the state defined here: blending through {@link blendType}, depth behavior through * {@link depthTest}, {@link depthWrite} and {@link depthFunc}, face culling through {@link cull}, * alpha testing through {@link alphaTest}, shader uniforms through {@link setParameter}, and * preprocessor defines through {@link setDefine}. {@link getShaderChunks} exposes the GLSL and WGSL * chunks the material's shader is built from, so one chunk can be replaced without writing a whole * shader. * * After changing properties, call {@link update} so the change reaches the GPU. Most changes only * refresh uniforms; a change that alters how the shader is generated also clears the material's * compiled shader variants, which are rebuilt on demand. A material can be shared by any number of * mesh instances, and {@link clone} makes an independent copy. * * @example * // Make a material additive and double-sided, then apply the change * material.blendType = BLEND_ADDITIVE; * material.cull = CULLFACE_NONE; * material.update(); * @category Graphics */ declare class Material { /** * The mesh instances referencing this material * * @type {Set} * @private */ private meshInstances; /** * The name of the material. */ name: string; /** * A unique id the user can assign to the material. The engine internally does not use this for * anything, and the user can assign a value to this id for any purpose they like. Defaults to * an empty string. */ userId: string; id: number; /** * The cache of shader variants generated for this material. The key represents the unique * variant, the value is the shader. * * @type {Map} * @ignore */ variants: Map; /** * The set of defines used to generate the shader variants. Mutate this only via * {@link Material#setDefine} (or {@link Material#copy}); direct mutation bypasses the cached * {@link Material#definesKey}. * * @type {Map} * @ignore */ defines: Map; _definesDirty: boolean; /** * Cached content key for {@link Material#defines}, or null when it needs recomputing. An empty * defines set caches as '', so null unambiguously means "dirty". * * @type {string|null} * @private */ private _definesKey; parameters: {}; /** * @type {number} * @private */ private _alphaTest; /** * Enables or disables alpha to coverage. When enabled, and if hardware anti-aliasing is on, * limited order-independent transparency can be achieved. Quality depends on the number of * MSAA samples of the current render target. It can nicely soften edges of otherwise sharp * alpha cutouts, but isn't recommended for large area semi-transparent surfaces. Note, that * you don't need to enable blending to make alpha to coverage work. It will work without it, * just like alphaTest. * * This requires a multi-sampled render target, and is silently ignored when rendering to a * single-sampled one. On WebGPU it additionally requires the first color attachment of the * render target to use a blendable format with an alpha channel, and is silently ignored * otherwise - note that {@link PIXELFORMAT_111110F}, the default HDR format used by * {@link CameraFrame}, has no alpha channel. */ alphaToCoverage: boolean; /** @ignore */ _blendState: BlendState; /** * Explicit setting of sceneTexturesWrite, or undefined to derive it from transparency. * * @type {boolean|undefined} * @private */ private _sceneTexturesWrite; /** @ignore */ _depthState: DepthState; /** * Controls how triangles are culled based on their face direction with respect to the * viewpoint. Can be: * * - {@link CULLFACE_NONE}: Do not cull triangles based on face direction. * - {@link CULLFACE_BACK}: Cull the back faces of triangles (do not render triangles facing * away from the view point). * - {@link CULLFACE_FRONT}: Cull the front faces of triangles (do not render triangles facing * towards the view point). * * Defaults to {@link CULLFACE_BACK}. * * @type {number} */ cull: number; /** * Controls whether polygons are front- or back-facing by setting a winding * orientation. Can be: * * - {@link FRONTFACE_CW}: The clock-wise winding. * - {@link FRONTFACE_CCW}: The counterclockwise winding. * * Defaults to {@link FRONTFACE_CCW}. * * @type {number} */ frontFace: number; /** * Stencil parameters for front faces (default is null). * * @type {StencilParameters|null} */ stencilFront: StencilParameters | null; /** * Stencil parameters for back faces (default is null). * * @type {StencilParameters|null} */ stencilBack: StencilParameters | null; /** * @type {ShaderChunks|null} * @private */ private _shaderChunks; _oldChunks: {}; _dirtyShader: boolean; /** * True for a material whose shaders are built from the engine shader chunks, in which the names * of the textures the renderer supplies per pass are reserved. On WebGPU those shaders read the * textures from the view bind group, see getViewTextures, so a value set per material or per * mesh instance is ignored. Other materials, such as a {@link ShaderMaterial} running a user's * shader, keep all their textures in the mesh bind group. * * @type {boolean} * @ignore */ _usesViewTextures: boolean; /** * Enables or disables flat shading. When enabled, the surface is shaded using the geometric * normal of the triangle the fragment belongs to, instead of the normal interpolated from the * vertex normals, giving the mesh a faceted look. This works on skinned and morphed geometry as * well. * * The geometric normal is oriented to match the winding of the triangle, as configured by * {@link Material#frontFace}, and so it agrees with correctly authored vertex normals. Flat * shading therefore only changes the faceting - {@link Material#cull}, * {@link Material#frontFace} and {@link StandardMaterial#twoSidedLighting} all behave the same * as they do for smooth shading. * * {@link StandardMaterial} and `LitMaterial` implement this automatically. For a * {@link ShaderMaterial}, this adds a `FLAT_SHADING` define to the shader, which the supplied * shader code needs to handle. The `flatNormalPS` chunk provides the `getFlatNormal` function * used by the engine internally, and can be used for this: * * ```javascript * #include "flatNormalPS" * ... * #ifdef FLAT_SHADING * vec3 normal = getFlatNormal(worldPos); * #else * vec3 normal = normalize(interpolatedNormal); * #endif * ``` * * As with other material properties, call {@link Material#update} after changing this. * * Defaults to false. * * @type {boolean} */ set flatShading(value: boolean); /** * Gets whether flat shading is enabled. * * @type {boolean} */ get flatShading(): boolean; /** * Returns true if the material has custom shader chunks. * * @type {boolean} * @ignore */ get hasShaderChunks(): boolean; /** * Returns the shader chunks for the material. Those get allocated if they are not already. * * @type {ShaderChunks} * @ignore */ get shaderChunks(): ShaderChunks; /** * Returns an object containing shader chunks for a specific shader language for the material. * These chunks define custom GLSL or WGSL code used to construct the final shader for the * material. The chunks can be also be included in shaders using the `#include "ChunkName"` * directive. * * On the WebGL platform: * - If GLSL chunks are provided, they are used directly. * * On the WebGPU platform: * - If WGSL chunks are provided, they are used directly. * - If only GLSL chunks are provided, a GLSL shader is generated and then transpiled to WGSL, * which is less efficient. * * To ensure faster shader compilation, it is recommended to provide shader chunks for all * supported platforms. * * A simple example on how to override a shader chunk providing emissive color for both GLSL and * WGSL to simply return a red color: * * ```javascript * material.getShaderChunks(SHADERLANGUAGE_GLSL).set('emissivePS', ` * void getEmission() { * dEmission = vec3(1.0, 0.0, 1.0); * } * `); * * material.getShaderChunks(SHADERLANGUAGE_WGSL).set('emissivePS', ` * fn getEmission() { * dEmission = vec3f(1.0, 0.0, 1.0); * } * `); * * // call update to apply the changes * material.update(); * ``` * * @param {string} [shaderLanguage] - Specifies the shader language of shaders. Defaults to * {@link SHADERLANGUAGE_GLSL}. * @returns {ShaderChunkMap} - The shader chunks for the specified shader language. */ getShaderChunks(shaderLanguage?: string): ShaderChunkMap; /** * Sets the version of the shader chunks. * * This should be a string containing the current engine major and minor version (e.g., '2.8' * for engine v2.8.1) and ensures compatibility with the current engine version. When providing * custom shader chunks, set this to the latest supported version. If a future engine release no * longer supports the specified version, a warning will be issued. In that case, update your * shader chunks to match the new format and set this to the latest version accordingly. * * @type {string} */ set shaderChunksVersion(value: string); /** * Returns the version of the shader chunks. * * @type {string} */ get shaderChunksVersion(): string; /** * @deprecated Use Material.getShaderChunks instead. For example: * material.getShaderChunks(SHADERLANGUAGE_GLSL).set("chunkName", "chunkCode") * @type {Object} * @ignore */ set chunks(value: { [x: string]: string; }); /** * @deprecated Use Material.getShaderChunks instead. For example: * material.getShaderChunks(SHADERLANGUAGE_GLSL).set("chunkName", "chunkCode") * @type {Object} * @ignore */ get chunks(): { [x: string]: string; }; /** * Sets the alpha test reference value to control which fragments are written to the currently * active render target based on alpha value. All fragments with an alpha value of less than * the alphaTest reference value will be discarded. Defaults to 0 (all fragments pass). * * @type {number} */ set alphaTest(value: number); /** * Gets the alpha test reference value. * * @type {number} */ get alphaTest(): number; /** * Sets the offset for the output depth buffer value. Useful for decals to prevent z-fighting. * Typically a small negative value (-0.1) is used to render the mesh slightly closer to the * camera. * * @type {number} */ set depthBias(value: number); /** * Gets the offset for the output depth buffer value. * * @type {number} */ get depthBias(): number; /** * Sets the offset for the output depth buffer value based on the slope of the triangle * relative to the camera. * * @type {number} */ set slopeDepthBias(value: number); /** * Gets the offset for the output depth buffer value based on the slope of the triangle * relative to the camera. * * @type {number} */ get slopeDepthBias(): number; _shaderVersion: number; _scene: any; /** * Incremented by {@link Material#update} so internal consumers can detect material changes * without consuming shared dirty state. * * @type {number} * @private */ private _updateVersion; /** * The update version most recently processed by {@link Material#prepareForRender}. * * @type {number} * @private */ private _preparedVersion; /** * Typed properties whose public value changed and has not been written to the uniform buffer * yet. Allocated on first use. * * @type {Set|null} * @private */ private _modifiedProperties; /** * Snapshots of the aggregate typed property values handed out by a getter, by property. * Compared on update to detect in-place mutation of the returned object. Allocated on first * use. * * @type {Map|null} * @private */ private _mutableProperties; /** * The uniform buffer storing the typed properties, created on the first preparation for * rendering. Null for materials without typed properties. * * @type {UniformBuffer|null} * @private */ private _uniformBuffer; /** * The bind group holding the material uniform buffer. * * @type {BindGroup|null} * @private */ private _uniformBufferBindGroup; /** * The layout the uniform buffer and the bind group were built from, null until the first * render of the material. * * @type {MaterialUniformBufferLayout|null} * @private */ private _layout; /** * Incremented when a texture of the material is assigned. A material whose textures decide the * slots of its bind group moves this, as assigning one can change those slots without changing * any of its typed properties. * * @type {number} * @ignore */ _textureAssignmentVersion: number; /** * The texture assignment version the layout was last resolved for. * * @type {number} * @private */ private _resolvedTextureVersion; /** * Incremented each time typed property data is written to the uniform buffer storage. * * @type {number} * @private */ private _uniformDataVersion; /** * The uniform data version most recently uploaded to the GPU. * * @type {number} * @private */ private _uniformUploadedVersion; /** * The version incremented each time {@link Material#update} is called. * * @type {number} * @ignore */ get updateVersion(): number; /** * The typed properties of the material, stored in its uniform buffer, or null for a material * without typed properties. * * @type {MaterialProperty[]|null} * @ignore */ get propertyDescriptors(): MaterialProperty[] | null; /** * Returns the typed property whose uniform, stored in the material uniform buffer, has the given * name, or null when no typed property uses it. A mesh instance parameter of that name * overrides the uniform through a copy of the buffer rather than through the scope. * * @param {string} name - The name of the uniform. * @returns {MaterialProperty|null} The property, or null. * @ignore */ getUniformBufferProperty(name: string): MaterialProperty | null; /** * The textures of the material, one per slot of its bind group. Empty for a material which * keeps its textures on the scope instead. * * @type {MaterialTextureDescriptor[]} * @ignore */ get textureDescriptors(): MaterialTextureDescriptor[]; /** * The textures the material holds in its own bind group on this device. Only a device using * bind groups has one to hold them; without it they stay on the scope, which is also where a * mesh instance overriding one of them has to apply it. * * @param {GraphicsDevice} device - The graphics device. * @returns {MaterialTextureDescriptor[]} The textures. * @ignore */ getTextureDescriptors(device: GraphicsDevice): MaterialTextureDescriptor[]; /** * The index of the texture slot of the material's bind group a name refers to, or -1 when the * name is not one of them. A mesh instance parameter of such a name overrides that texture of * the material for its own draws, applied through the copy of the bind group the mesh instance * keeps rather than through the scope. * * @param {string} name - The name of the texture. * @returns {number} The index of the texture slot, or -1. * @ignore */ getTextureSlot(name: string): number; /** * Incremented when the layout of the material is replaced - the set of its typed properties or * of its textures changed - so that mesh instances re-classify their parameters against it. * Constant for a material whose layout never changes. * * @type {number} * @private */ private _layoutVersion; /** * True when the set of uniforms of the material uniform buffer changed since the buffer was * created, so the layout is fetched again on the next preparation. * * @type {boolean} * @private */ private _layoutDirty; /** * The version of the layout of the material: its typed properties, see * {@link Material#getUniformBufferProperty}, and its textures, see * {@link Material#getTextureSlot}. * * @type {number} * @ignore */ get layoutVersion(): number; /** * Marks the layout of the material as changed: the next preparation fetches it again, and * replaces the uniform buffer and the bind group when it differs. * * @protected */ protected _markLayoutDirty(): void; /** * The bind group holding the material uniform buffer, or null until the material has been * prepared for rendering, or when it has no typed properties. * * @type {BindGroup|null} * @ignore */ get uniformBufferBindGroup(): BindGroup | null; /** * The uniform buffer storing the typed properties, or null until the material has been * prepared for rendering, or when it has no typed properties. * * @type {UniformBuffer|null} * @ignore */ get uniformBuffer(): UniformBuffer | null; /** * Incremented each time typed property data is written to the uniform buffer storage, so that * copies of the buffer (mesh instance overrides) can detect a change. * * @type {number} * @ignore */ get uniformDataVersion(): number; /** @ignore */ get dirty(): any; /** * Sets whether the red channel is written to the color buffer. If true, the red component of * fragments generated by the shader of this material is written to the color buffer of the * currently active render target. If false, the red component will not be written. Defaults to * true. * * @type {boolean} */ set redWrite(value: boolean); /** * Gets whether the red channel is written to the color buffer. * * @type {boolean} */ get redWrite(): boolean; /** * Sets whether the green channel is written to the color buffer. If true, the red component of * fragments generated by the shader of this material is written to the color buffer of the * currently active render target. If false, the green component will not be written. Defaults * to true. * * @type {boolean} */ set greenWrite(value: boolean); /** * Gets whether the green channel is written to the color buffer. * * @type {boolean} */ get greenWrite(): boolean; /** * Sets whether the blue channel is written to the color buffer. If true, the red component of * fragments generated by the shader of this material is written to the color buffer of the * currently active render target. If false, the blue component will not be written. Defaults * to true. * * @type {boolean} */ set blueWrite(value: boolean); /** * Gets whether the blue channel is written to the color buffer. * * @type {boolean} */ get blueWrite(): boolean; /** * Sets whether the alpha channel is written to the color buffer. If true, the red component of * fragments generated by the shader of this material is written to the color buffer of the * currently active render target. If false, the alpha component will not be written. Defaults * to true. * * @type {boolean} */ set alphaWrite(value: boolean); /** * Gets whether the alpha channel is written to the color buffer. * * @type {boolean} */ get alphaWrite(): boolean; get transparent(): boolean; /** * Declares whether this material's shader generates the scene textures - the additional render * target attachments the scene pass renders alongside the scene color, holding per pixel data * such as the linear depth. It applies to all of them at once, as a shader either supports the * scene textures or it does not. The attachments of a material that does not generate them are * masked off, as a shader leaving an attachment unwritten makes the draw invalid. * * The default depends on where the shader comes from, so this rarely needs setting: * * - {@link StandardMaterial} and `LitMaterial` generate them from the engine's own shader, * so they default to true when opaque and false when transparent - blending the values of * ordinary transparent geometry into them is not meaningful. * - {@link ShaderMaterial} defaults to false, as its shader is supplied by the user. Set this to * true if that shader outputs them using the `sceneTexturesPS` chunk. * - Gaussian splat materials set it to true, the deliberate exception to the transparency rule - * their premultiplied blending accumulates a transmittance weighted average. * - Particle materials set it to false, as they use their own shader. * * Unlike {@link Material#depthWrite} and the color write properties this is not purely a mask: * setting it to true for a shader that does not generate the scene textures makes its draws * invalid, rather than simply skipping the write. * * @type {boolean} * @ignore */ set sceneTexturesWrite(value: boolean); /** * Gets whether this material's shader generates the scene textures. Returns the explicitly set * value when there is one, and otherwise derives it from transparency - opaque materials generate * them, transparent ones do not. See the setter for the default of each material type. * * @type {boolean} * @ignore */ get sceneTexturesWrite(): boolean; _updateTransparency(): void; /** * Sets the blend state for this material. Controls how fragment shader outputs are blended * when being written to the currently active render target. This overwrites blending type set * using {@link blendType}, and offers more control over blending. * * @type {BlendState} */ set blendState(value: Readonly); /** * Gets the blend state for this material. Use the setter to update transparency and sort state. * * @type {Readonly} */ get blendState(): Readonly; /** * Sets the blend mode for this material. Controls how fragment shader outputs are blended when * being written to the currently active render target. Can be: * * - {@link BLEND_SUBTRACTIVE}: Subtract the color of the source fragment from the destination * fragment and write the result to the frame buffer. * - {@link BLEND_ADDITIVE}: Add the color of the source fragment to the destination fragment * and write the result to the frame buffer. * - {@link BLEND_NORMAL}: Enable simple translucency for materials such as glass. This is * equivalent to enabling a source blend mode of {@link BLENDMODE_SRC_ALPHA} and a destination * blend mode of {@link BLENDMODE_ONE_MINUS_SRC_ALPHA}. * - {@link BLEND_NONE}: Disable blending. * - {@link BLEND_PREMULTIPLIED}: Similar to {@link BLEND_NORMAL} expect the source fragment is * assumed to have already been multiplied by the source alpha value. * - {@link BLEND_MULTIPLICATIVE}: Multiply the color of the source fragment by the color of the * destination fragment and write the result to the frame buffer. * - {@link BLEND_ADDITIVEALPHA}: Same as {@link BLEND_ADDITIVE} except the source RGB is * multiplied by the source alpha. * - {@link BLEND_MULTIPLICATIVE2X}: Multiplies colors and doubles the result. * - {@link BLEND_SCREEN}: Softer version of additive. * - {@link BLEND_MIN}: Minimum color. * - {@link BLEND_MAX}: Maximum color. * * Defaults to {@link BLEND_NONE}. * * @type {number} */ set blendType(type: number); /** * Gets the blend mode for this material. * * @type {number} */ get blendType(): number; /** * Sets the depth state. Note that this can also be done by using {@link depthTest}, * {@link depthFunc} and {@link depthWrite}. * * @type {DepthState} */ set depthState(value: DepthState); /** * Gets the depth state. * * @type {DepthState} */ get depthState(): DepthState; /** * Sets whether depth testing is enabled. If true, fragments generated by the shader of this * material are only written to the current render target if they pass the depth test. If * false, fragments generated by the shader of this material are written to the current render * target regardless of what is in the depth buffer. See {@link DepthState#test} for how this * interacts with {@link depthFunc}. Depth writes are controlled independently by * {@link depthWrite}. Defaults to true. * * @type {boolean} */ set depthTest(value: boolean); /** * Gets whether depth testing is enabled. * * @type {boolean} */ get depthTest(): boolean; /** * Sets the depth test function. Controls how the depth of new fragments is compared against * the current depth contained in the depth buffer. Can be: * * - {@link FUNC_NEVER}: don't draw * - {@link FUNC_LESS}: draw if new depth < depth buffer * - {@link FUNC_EQUAL}: draw if new depth == depth buffer * - {@link FUNC_LESSEQUAL}: draw if new depth <= depth buffer * - {@link FUNC_GREATER}: draw if new depth > depth buffer * - {@link FUNC_NOTEQUAL}: draw if new depth != depth buffer * - {@link FUNC_GREATEREQUAL}: draw if new depth >= depth buffer * - {@link FUNC_ALWAYS}: always draw * * Defaults to {@link FUNC_LESSEQUAL}. * * @type {number} */ set depthFunc(value: number); /** * Gets the depth test function. * * @type {number} */ get depthFunc(): number; /** * Sets whether depth writing is enabled. If true, fragments generated by the shader of this * material write a depth value to the depth buffer of the currently active render target. If * false, no depth value is written. Defaults to true. * * @type {boolean} */ set depthWrite(value: boolean); /** * Gets whether depth writing is enabled. * * @type {boolean} */ get depthWrite(): boolean; /** * Copy a material. * * @param {Material} source - The material to copy. * @returns {Material} The destination material. */ copy(source: Material): Material; /** * Clone a material. * * @returns {this} A newly cloned material. */ clone(): this; _updateMeshInstanceKeys(): void; /** @private */ private _clearVariantsIfDirty; updateUniforms(device: any, scene: any): void; /** * Records that the public value of a typed property changed. The value is written to the * uniform buffer by the next {@link Material#update}. * * @param {MaterialProperty} property - The property. * @protected */ protected _markPropertyModified(property: MaterialProperty): void; /** * Records that the aggregate value of a typed property was handed out by its getter, so that * an in-place mutation of the returned object can be detected by the next * {@link Material#update}. Only the first exposure allocates a snapshot. * * @param {MaterialProperty} property - The property. * @param {object} value - The value returned by the getter, with clone, equals and copy. * @protected */ protected _markPropertyMutable(property: MaterialProperty, value: object): void; /** * Processes the typed property changes: in-place mutations of exposed values are detected and * treated as modifications, and modified values are converted into the uniform buffer storage. * Until the uniform buffer exists, the modified properties stay pending and are written when it * is created. Runs from {@link Material#update} - the renderer does not process changes, so a * change made without a subsequent update is not applied (and reported in the debug build). * * @private */ private _updateProperties; /** * Creates the material uniform buffer and its bind group on first use, and uploads the * uniform buffer when its data changed. * * @param {GraphicsDevice} device - The graphics device. * @private */ private _prepareUniformBuffer; /** * Prepares the material for rendering when it has been updated since the previous preparation. * Typed property changes are applied by {@link Material#update} only; the debug build reports * changes that were made without a subsequent update, as they are not applied. * * @param {GraphicsDevice} device - The graphics device. * @param {Scene} scene - The scene. * @ignore */ prepareForRender(device: GraphicsDevice, scene: Scene): void; _debugWarnedUnapplied: boolean; /** * @param {ShaderVariantParams} params - The parameters used to generate the shader variant. * @ignore */ getShaderVariant(params: ShaderVariantParams): void; /** * Applies any changes made to the material's properties. This method should be called after * modifying material properties to ensure the changes take effect. * * The method will clear cached shader variants and trigger recompilation if: * - Modified material properties require a different shader variant (e.g., enabling/disabling * textures or other properties that affect shader generation) * - Material-specific shader chunks (from {@link getShaderChunks}) have been modified * - Global shader chunks (from {@link ShaderChunks.get}) have been modified * - Material defines have been changed * * Note: Shaders are not compiled immediately. Instead, existing shader variants are cleared * and new variants will be compiled on-demand as they are needed for different render passes * (e.g., forward, shadow, pick). * * When global shader chunks are modified, `update()` must be called on each material that * should reflect those changes. */ update(): void; clearParameters(): void; getParameters(): {}; clearVariants(): void; /** * Retrieves the specified shader parameter from a material. * * @param {string} name - The name of the parameter to query. * @returns {object} The named parameter. */ getParameter(name: string): object; _setParameterSimple(name: any, data: any): void; /** * Sets a shader parameter on a material. * * @param {string} name - The name of the parameter to set. * @param {number|number[]|ArrayBufferView|Texture|StorageBuffer} data - The value for the specified parameter. */ setParameter(name: string, data: number | number[] | ArrayBufferView | Texture | StorageBuffer): void; /** * Deletes a shader parameter on a material. * * @param {string} name - The name of the parameter to delete. */ deleteParameter(name: string): void; /** * Applies the parameters of this material to the scope. Called internally by the renderer at * a material switch, and again after a draw whose mesh instance overrode some of them on the * scope, to restore the material values for the next draw. * * @param {GraphicsDevice} device - The graphics device. * @param {{name: string}[]} [restore] - When specified, only the parameters with the names of * these entries are applied (the scope parameters of a mesh instance), otherwise all are. * @ignore */ setParameters(device: GraphicsDevice, restore?: { name: string; }[]): void; /** * @param {GraphicsDevice} device - The graphics device. * @param {{scopeId: ScopeId|null, data: any}} parameter - The parameter. * @param {string} name - The name of the parameter. * @private */ private _setScopeParameter; /** * Adds or removes a define on the material. Defines can be used to enable or disable various * parts of the shader code. * * @param {string} name - The name of the define to set. * @param {string|undefined|boolean} value - The value of the define. If undefined or false, the * define is removed. * * A simple example on how to set a custom shader define value used by the shader processor. * * ```javascript * material.setDefine('MY_DEFINE', true); * * // call update to apply the changes, which will recompile the shader using the new define * material.update(); * ``` */ setDefine(name: string, value: string | undefined | boolean): void; /** * A cached content key for the material defines, rebuilt lazily only when the defines change. * Useful to cheaply detect define changes without scanning the map every frame. * * @type {string} * @ignore */ get definesKey(): string; /** * Returns true if a define is enabled on the material, otherwise false. * * @param {string} name - The name of the define to check. * @returns {boolean} The value of the define. */ getDefine(name: string): boolean; /** * Removes this material from the scene and possibly frees up memory from its shaders (if there * are no other materials using it). */ destroy(): void; /** * Registers mesh instance as referencing the material. * * @param {MeshInstance} meshInstance - The mesh instance to register. * @ignore */ addMeshInstanceRef(meshInstance: MeshInstance): void; /** * De-registers mesh instance as referencing the material. * * @param {MeshInstance} meshInstance - The mesh instance to de-register. * @ignore */ removeMeshInstanceRef(meshInstance: MeshInstance): void; /** * Sets the material's shader. Not supported. * * @ignore * @deprecated Use {@link ShaderMaterial} instead. */ set shader(value: any); /** * Gets the material's shader. Always returns null. * * @ignore * @deprecated Use {@link ShaderMaterial} instead. */ get shader(): any; /** * Sets whether blending is enabled. Note: this is used by the Editor. * * @type {boolean} * @ignore * @deprecated Use {@link Material#blendState} instead. */ set blend(value: boolean); /** * Gets whether blending is enabled. * * @type {boolean} * @ignore * @deprecated Use {@link Material#blendState} instead. */ get blend(): boolean; } declare class StandardMaterialOptionsBuilder { /** * The refraction index for which the shader uses a built-in constant instead of the * material_refractionIndex uniform. Shared with StandardMaterial, which needs to invalidate its * shaders when refractionIndex moves across this value. * * @type {number} * @ignore */ static DEFAULT_REFRACTION_INDEX: number; /** * Compares two material numbers with the tolerance used to decide whether a shader constant can * replace a uniform. * * @param {number} a - The first value. * @param {number} b - The second value. * @returns {boolean} True when the values are equal within tolerance. * @ignore */ static equalish(a: number, b: number): boolean; updateMinRef(options: any, scene: any, stdMat: any, objDefs: any, pass: any, lightList: any, vertexFormat: any, outlinePass?: boolean): void; updateRef(options: any, scene: any, cameraShaderParams: any, stdMat: any, objDefs: any, pass: any, lightList: any, vertexFormat: any): void; _updateSharedOptions(options: any, scene: any, stdMat: any, objDefs: any, pass: any, cameraShaderParams: any): void; _updateUVOptions(options: any, stdMat: any, objDefs: any, vertexFormat: any, minimalOptions: any, cameraShaderParams: any): void; _updateTexOptions(options: any, stdMat: any, p: any, vertexFormat: any, hasVcolor: any, minimalOptions: any, textureIdentifiers: any): void; _updateMinOptions(options: any, stdMat: any, pass: any, outlinePass: any): void; _updateMaterialOptions(options: any, stdMat: any, scene: any): void; _updateEnvOptions(options: any, stdMat: any, scene: any, cameraShaderParams: any): void; _updateLightOptions(options: any, scene: any, stdMat: any, objDefs: any, lightList: any): void; } /** * Callback used by {@link StandardMaterial#onUpdateShader}. */ type UpdateShaderCallback = (options: StandardMaterialOptions) => StandardMaterialOptions; /** * @callback UpdateShaderCallback * Callback used by {@link StandardMaterial#onUpdateShader}. * @param {StandardMaterialOptions} options - An object with shader generator settings (based on current * material and scene properties), that you can change and then return. Properties of the object passed * into this function are documented in {@link StandardMaterial}. Also contains a member named litOptions * which holds some of the options only used by the lit shader backend {@link LitShaderOptions}. * @returns {StandardMaterialOptions} Returned settings will be used by the shader. */ /** * A standard material is the main, general purpose material that is most often used for rendering. * It can approximate a wide variety of surface types and can simulate dynamic reflected light. * Most maps can use 3 types of input values in any combination: constant ({@link Color} or number), * mesh vertex colors and a {@link Texture}. All enabled inputs are multiplied together. A texture * samples one of the mesh's UV sets, selected by the map's UV channel property (0 to 7), and is * ignored when the mesh does not provide that set. UV sets 6 and 7 share their vertex attribute * locations with the default hardware instancing format, so an instanced mesh sampling them needs a * custom instancing vertex format, see {@link MeshInstance#setInstancing}. * * A property assignment only reaches the GPU once {@link Material#update} is called: a `diffuse` * or `emissive` change made after the material's first frame is not applied until * `material.update()` runs. The debug build reports unapplied changes to the properties stored in * the material uniform buffer, such as `diffuse`. * * Properties come in families that share a naming pattern. A family such as `diffuse` has a * constant (`diffuse`), a texture (`diffuseMap`) with its `diffuseMapUv`, `diffuseMapTiling`, * `diffuseMapOffset`, `diffuseMapRotation` and `diffuseMapChannel`, and a vertex color switch * (`diffuseVertexColor`). The main families are `diffuse`; `specular`, or `metalness` when * `useMetalness` is set; `gloss`; `normalMap` with `bumpiness`; `emissive`; `opacity` together * with {@link Material#blendType}; `ao`; `lightMap`; and the advanced layers `clearCoat`, `sheen`, * `iridescence` and `refraction`. Lighting can be turned off entirely with `useLighting`. * * To go beyond the properties, replace individual shader chunks with * {@link Material#getShaderChunks}. When the surface is not a lit material at all, use * {@link ShaderMaterial} instead. * * @example * const material = new StandardMaterial(); * material.diffuse.set(0.8, 0.2, 0.2); * material.diffuseMap = brickAsset.resource; * material.useMetalness = true; * material.metalness = 0.1; * material.gloss = 0.6; * material.update(); * entity.render.material = material; * @property {Texture|null} diffuseMap The main (primary) diffuse map of the material (default is * null). * @property {number} diffuseMapUv Main (primary) diffuse map UV channel. Valid values are 0 to 7. * @property {Vec2} diffuseMapTiling Controls the 2D tiling of the main (primary) diffuse map. * @property {Vec2} diffuseMapOffset Controls the 2D offset of the main (primary) diffuse map. Each * component is between 0 and 1. * @property {number} diffuseMapRotation Controls the 2D rotation (in degrees) of the main * (primary) diffuse map. * @property {string} diffuseMapChannel Color channels of the main (primary) diffuse map to use. * Can be "r", "g", "b", "a", "rgb" or any swizzled combination. * @property {boolean} diffuseVertexColor Multiply diffuse by the mesh vertex colors. * @property {string} diffuseVertexColorChannel Vertex color channels to use for diffuse. Can be * "r", "g", "b", "a", "rgb" or any swizzled combination. * @property {Texture|null} diffuseDetailMap The detail (secondary) diffuse map of the material * (default is null). Will only be used if main (primary) diffuse map is non-null. * @property {number} diffuseDetailMapUv Detail (secondary) diffuse map UV channel. Valid values are 0 to 7. * @property {Vec2} diffuseDetailMapTiling Controls the 2D tiling of the detail (secondary) diffuse * map. * @property {Vec2} diffuseDetailMapOffset Controls the 2D offset of the detail (secondary) diffuse * map. Each component is between 0 and 1. * @property {number} diffuseDetailMapRotation Controls the 2D rotation (in degrees) of the detail * (secondary) diffuse map. * @property {string} diffuseDetailMapChannel Color channels of the detail (secondary) diffuse map * to use. Can be "r", "g", "b", "a", "rgb" or any swizzled combination. * @property {string} diffuseDetailMode Determines how the main (primary) and detail (secondary) * diffuse maps are blended together. Can be: * * - {@link DETAILMODE_MUL}: Multiply together the primary and secondary colors. * - {@link DETAILMODE_ADD}: Add together the primary and secondary colors. * - {@link DETAILMODE_SCREEN}: Softer version of {@link DETAILMODE_ADD}. * - {@link DETAILMODE_OVERLAY}: Multiplies or screens the colors, depending on the primary color. * - {@link DETAILMODE_MIN}: Select whichever of the primary and secondary colors is darker, * component-wise. * - {@link DETAILMODE_MAX}: Select whichever of the primary and secondary colors is lighter, * component-wise. * * Defaults to {@link DETAILMODE_MUL}. * @property {Texture|null} specularMap The specular map of the material (default is null). * @property {number} specularMapUv Specular map UV channel. Valid values are 0 to 7. * @property {Vec2} specularMapTiling Controls the 2D tiling of the specular map. * @property {Vec2} specularMapOffset Controls the 2D offset of the specular map. Each component is * between 0 and 1. * @property {number} specularMapRotation Controls the 2D rotation (in degrees) of the specular map. * @property {string} specularMapChannel Color channels of the specular map to use. Can be "r", "g", * "b", "a", "rgb" or any swizzled combination. * @property {boolean} specularVertexColor Multiply specular by the mesh vertex colors. * @property {string} specularVertexColorChannel Vertex color channels to use for specular. Can be * "r", "g", "b", "a", "rgb" or any swizzled combination. * @property {boolean} specularityFactorTint Force inclusion of the constant `specularityFactor` * when compositing with `specularityFactorMap` and/or specularity factor vertex colors. Defaults * to `false`. Setting this to `true` is rarely needed - the constant is automatically applied * whenever `specularityFactor` differs from 1. Provided as an explicit override. * @property {Texture|null} specularityFactorMap The factor of specularity as a texture (default is * null). * @property {number} specularityFactorMapUv Specularity factor map UV channel. Valid values are 0 to 7. * @property {Vec2} specularityFactorMapTiling Controls the 2D tiling of the specularity factor map. * @property {Vec2} specularityFactorMapOffset Controls the 2D offset of the specularity factor map. Each component is * between 0 and 1. * @property {number} specularityFactorMapRotation Controls the 2D rotation (in degrees) of the specularity factor map. * @property {string} specularityFactorMapChannel The channel used by the specularity factor texture to sample from (default is 'a'). * @property {boolean} specularityFactorVertexColor Use mesh vertex colors for specularity factor. If specularityFactorMap or * are specularityFactorTint are set, they'll be multiplied by vertex colors. * @property {string} specularityFactorVertexColorChannel Vertex color channels to use for specularity factor. Can be * "r", "g", "b", "a", "rgb" or any swizzled combination. * @property {boolean} enableGGXSpecular Enables GGX specular. Also enables * {@link anisotropyIntensity} parameter to set material anisotropy. * @property {Texture|null} anisotropyMap The anisotropy map of the material (default is null). * @property {number} anisotropyMapUv Anisotropy map UV channel. Valid values are 0 to 7. * @property {Vec2} anisotropyMapTiling Controls the 2D tiling of the anisotropy map. * @property {Vec2} anisotropyMapOffset Controls the 2D offset of the anisotropy map. Each * component is between 0 and 1. * @property {number} anisotropyMapRotation Controls the 2D rotation (in degrees) of the anisotropy map. * @property {Texture|null} clearCoatMap Monochrome clearcoat intensity map (default is null). If * specified, will be multiplied by normalized 'clearCoat' value and/or vertex colors. * @property {number} clearCoatMapUv Clearcoat intensity map UV channel. Valid values are 0 to 7. * @property {Vec2} clearCoatMapTiling Controls the 2D tiling of the clearcoat intensity map. * @property {Vec2} clearCoatMapOffset Controls the 2D offset of the clearcoat intensity map. Each * component is between 0 and 1. * @property {number} clearCoatMapRotation Controls the 2D rotation (in degrees) of the clearcoat * intensity map. * @property {string} clearCoatMapChannel Color channel of the clearcoat intensity map to use. Can * be "r", "g", "b" or "a". * @property {boolean} clearCoatVertexColor Use mesh vertex colors for clearcoat intensity. If * clearCoatMap is set, it'll be multiplied by vertex colors. * @property {string} clearCoatVertexColorChannel Vertex color channel to use for clearcoat * intensity. Can be "r", "g", "b" or "a". * @property {boolean} clearCoatGlossInvert Invert the clearcoat gloss component (default is false). * Enabling this flag results in material treating the clear coat gloss members as roughness. * @property {Texture|null} clearCoatGlossMap Monochrome clearcoat glossiness map (default is * null). If specified, will be multiplied by normalized 'clearCoatGloss' value and/or vertex * colors. * @property {number} clearCoatGlossMapUv Clearcoat gloss map UV channel. Valid values are 0 to 7. * @property {Vec2} clearCoatGlossMapTiling Controls the 2D tiling of the clearcoat gloss map. * @property {Vec2} clearCoatGlossMapOffset Controls the 2D offset of the clearcoat gloss map. * Each component is between 0 and 1. * @property {number} clearCoatGlossMapRotation Controls the 2D rotation (in degrees) of the clear * coat gloss map. * @property {string} clearCoatGlossMapChannel Color channel of the clearcoat gloss map to use. * Can be "r", "g", "b" or "a". * @property {boolean} clearCoatGlossVertexColor Use mesh vertex colors for clearcoat glossiness. * If clearCoatGlossMap is set, it'll be multiplied by vertex colors. * @property {string} clearCoatGlossVertexColorChannel Vertex color channel to use for clearcoat * glossiness. Can be "r", "g", "b" or "a". * @property {Texture|null} clearCoatNormalMap The clearcoat normal map of the material (default is * null). The texture must contains normalized, tangent space normals. * @property {number} clearCoatNormalMapUv Clearcoat normal map UV channel. Valid values are 0 to 7. * @property {Vec2} clearCoatNormalMapTiling Controls the 2D tiling of the main clearcoat normal * map. * @property {Vec2} clearCoatNormalMapOffset Controls the 2D offset of the main clearcoat normal * map. Each component is between 0 and 1. * @property {number} clearCoatNormalMapRotation Controls the 2D rotation (in degrees) of the main * clearcoat map. * @property {boolean} useIridescence Enable thin-film iridescence. * @property {Texture|null} iridescenceMap The per-pixel iridescence intensity. Only used when * useIridescence is enabled. * @property {number} iridescenceMapUv Iridescence map UV channel. Valid values are 0 to 7. * @property {Vec2} iridescenceMapTiling Controls the 2D tiling of the iridescence map. * @property {Vec2} iridescenceMapOffset Controls the 2D offset of the iridescence map. Each component is * between 0 and 1. * @property {number} iridescenceMapRotation Controls the 2D rotation (in degrees) of the iridescence * map. * @property {string} iridescenceMapChannel Color channels of the iridescence map to use. Can be "r", * "g", "b" or "a". * @property {Texture|null} iridescenceThicknessMap The per-pixel iridescence thickness. Defines a * gradient weight between iridescenceThicknessMin and iridescenceThicknessMax. Only used when * useIridescence is enabled. * @property {number} iridescenceThicknessMapUv Iridescence thickness map UV channel. Valid values are 0 to 7. * @property {Vec2} iridescenceThicknessMapTiling Controls the 2D tiling of the iridescence * thickness map. * @property {Vec2} iridescenceThicknessMapOffset Controls the 2D offset of the iridescence * thickness map. Each component is between 0 and 1. * @property {number} iridescenceThicknessMapRotation Controls the 2D rotation (in degrees) * of the iridescence thickness map. * @property {string} iridescenceThicknessMapChannel Color channels of the iridescence thickness * map to use. Can be "r", "g", "b" or "a". * @property {boolean} useMetalness Use metalness properties instead of specular. When enabled, * diffuse colors also affect specular instead of the dedicated specular map. This can be used as * alternative to specular color to save space. With metalness == 0, the pixel is assumed to be * dielectric, and diffuse color is used as normal. With metalness == 1, the pixel is fully * metallic, and diffuse color is used as specular color instead. * @property {boolean} useMetalnessSpecularColor When metalness is enabled, use the * specular map to apply color tint to specular reflections. * @property {Texture|null} metalnessMap Monochrome metalness map (default is null). * @property {number} metalnessMapUv Metalness map UV channel. Valid values are 0 to 7. * @property {Vec2} metalnessMapTiling Controls the 2D tiling of the metalness map. * @property {Vec2} metalnessMapOffset Controls the 2D offset of the metalness map. Each component * is between 0 and 1. * @property {number} metalnessMapRotation Controls the 2D rotation (in degrees) of the metalness * map. * @property {string} metalnessMapChannel Color channel of the metalness map to use. Can be "r", * "g", "b" or "a". * @property {boolean} metalnessVertexColor Use mesh vertex colors for metalness. If metalnessMap * is set, it'll be multiplied by vertex colors. * @property {string} metalnessVertexColorChannel Vertex color channel to use for metalness. Can be * "r", "g", "b" or "a". * @property {Texture|null} glossMap Gloss map (default is null). If specified, will be multiplied * by normalized gloss value and/or vertex colors. * @property {boolean} glossInvert Invert the gloss component (default is false). Enabling this * flag results in material treating the gloss members as roughness. * @property {number} glossMapUv Gloss map UV channel. Valid values are 0 to 7. * @property {string} glossMapChannel Color channel of the gloss map to use. Can be "r", "g", "b" * or "a". * @property {Vec2} glossMapTiling Controls the 2D tiling of the gloss map. * @property {Vec2} glossMapOffset Controls the 2D offset of the gloss map. Each component is * between 0 and 1. * @property {number} glossMapRotation Controls the 2D rotation (in degrees) of the gloss map. * @property {boolean} glossVertexColor Use mesh vertex colors for glossiness. If glossMap is set, * it'll be multiplied by vertex colors. * @property {string} glossVertexColorChannel Vertex color channel to use for glossiness. Can be * "r", "g", "b" or "a". * @property {Texture|null} refractionMap The map of the refraction visibility. * @property {number} refractionMapUv Refraction map UV channel. Valid values are 0 to 7. * @property {Vec2} refractionMapTiling Controls the 2D tiling of the refraction map. * @property {Vec2} refractionMapOffset Controls the 2D offset of the refraction map. Each component * is between 0 and 1. * @property {number} refractionMapRotation Controls the 2D rotation (in degrees) of the * refraction map. * @property {string} refractionMapChannel Color channels of the refraction map to use. Can be "r", * "g", "b", "a", "rgb" or any swizzled combination. * @property {boolean} refractionVertexColor Use mesh vertex colors for refraction. If * refraction map is set, it will be multiplied by vertex colors. * @property {string} refractionVertexColorChannel Vertex color channel to use for refraction. * Can be "r", "g", "b" or "a". * @property {boolean} useDynamicRefraction Enables higher quality refractions using the grab pass * instead of pre-computed cube maps for refractions. * @property {Texture|null} thicknessMap The per-pixel thickness of the medium, only used when * useDynamicRefraction is enabled. * @property {number} thicknessMapUv Thickness map UV channel. Valid values are 0 to 7. * @property {Vec2} thicknessMapTiling Controls the 2D tiling of the thickness map. * @property {Vec2} thicknessMapOffset Controls the 2D offset of the thickness map. Each component is * between 0 and 1. * @property {number} thicknessMapRotation Controls the 2D rotation (in degrees) of the thickness * map. * @property {string} thicknessMapChannel Color channels of the thickness map to use. Can be "r", * "g", "b" or "a". * @property {boolean} thicknessVertexColor Use mesh vertex colors for thickness. If * thickness map is set, it will be multiplied by vertex colors. * @property {string} thicknessVertexColorChannel Vertex color channel to use for thickness. Can * be "r", "g", "b" or "a". * @property {Texture|null} emissiveMap The emissive map of the material (default is null). Can be * HDR. When the emissive map is applied, the emissive color is multiplied by the texel color in the * map. Since the emissive color is black by default, the emissive map won't be visible unless the * emissive color is changed. * @property {number} emissiveMapUv Emissive map UV channel. Valid values are 0 to 7. * @property {Vec2} emissiveMapTiling Controls the 2D tiling of the emissive map. * @property {Vec2} emissiveMapOffset Controls the 2D offset of the emissive map. Each component is * between 0 and 1. * @property {number} emissiveMapRotation Controls the 2D rotation (in degrees) of the emissive * map. * @property {string} emissiveMapChannel Color channels of the emissive map to use. Can be "r", * "g", "b", "a", "rgb" or any swizzled combination. * @property {boolean} emissiveVertexColor Use mesh vertex colors for emission. If emissiveMap or * emissive are set, they'll be multiplied by vertex colors. * @property {string} emissiveVertexColorChannel Vertex color channels to use for emission. Can be * "r", "g", "b", "a", "rgb" or any swizzled combination. * @property {boolean} useSheen Toggle sheen specular effect on/off. * @property {Texture|null} sheenMap The sheen microstructure color map of the material (default is * null). * @property {number} sheenMapUv Sheen map UV channel. Valid values are 0 to 7. * @property {Vec2} sheenMapTiling Controls the 2D tiling of the sheen map. * @property {Vec2} sheenMapOffset Controls the 2D offset of the sheen map. Each component is * between 0 and 1. * @property {number} sheenMapRotation Controls the 2D rotation (in degrees) of the sheen * map. * @property {string} sheenMapChannel Color channels of the sheen map to use. Can be "r", * "g", "b", "a", "rgb" or any swizzled combination. * @property {boolean} sheenVertexColor Use mesh vertex colors for sheen. If sheen map or * sheen tint are set, they'll be multiplied by vertex colors. * @property {string} sheenVertexColorChannel Vertex color channels to use for sheen. Can be "r", * "g", "b", "a", "rgb" or any swizzled combination. * @property {boolean} sheenGlossInvert Invert the sheen gloss component (default is false). * Enabling this flag results in material treating the sheen gloss members as roughness. * @property {Texture|null} sheenGlossMap The sheen glossiness microstructure color map of the * material (default is null). * @property {number} sheenGlossMapUv Sheen glossiness map UV channel. Valid values are 0 to 7. * @property {Vec2} sheenGlossMapTiling Controls the 2D tiling of the sheen glossiness map. * @property {Vec2} sheenGlossMapOffset Controls the 2D offset of the sheen glossiness map. * Each component is between 0 and 1. * @property {number} sheenGlossMapRotation Controls the 2D rotation (in degrees) of the sheen * glossiness map. * @property {string} sheenGlossMapChannel Color channels of the sheen glossiness map to use. * Can be "r", "g", "b", "a", "rgb" or any swizzled combination. * @property {boolean} sheenGlossVertexColor Use mesh vertex colors for sheen glossiness. * If sheen glossiness map or sheen glossiness tint are set, they'll be multiplied by vertex colors. * @property {string} sheenGlossVertexColorChannel Vertex color channels to use for sheen glossiness. * Can be "r", "g", "b" or "a". * @property {Texture|null} opacityMap The opacity map of the material (default is null). * @property {number} opacityMapUv Opacity map UV channel. Valid values are 0 to 7. * @property {string} opacityMapChannel Color channel of the opacity map to use. Can be "r", "g", * "b" or "a". * @property {Vec2} opacityMapTiling Controls the 2D tiling of the opacity map. * @property {Vec2} opacityMapOffset Controls the 2D offset of the opacity map. Each component is * between 0 and 1. * @property {number} opacityMapRotation Controls the 2D rotation (in degrees) of the opacity map. * @property {boolean} opacityVertexColor Use mesh vertex colors for opacity. If opacityMap is set, * it'll be multiplied by vertex colors. * @property {string} opacityVertexColorChannel Vertex color channels to use for opacity. Can be * "r", "g", "b" or "a". * @property {boolean} opacityFadesSpecular Used to specify whether specular and reflections are * faded out using {@link opacity}. Default is true. When set to false use {@link alphaFade} to * fade out materials. * @property {string} opacityDither Used to specify whether opacity is dithered, which allows * transparency without alpha blending. Can be: * * - {@link DITHER_NONE}: Opacity dithering is disabled. * - {@link DITHER_BAYER2}: Opacity is dithered using a Bayer 2 matrix. * - {@link DITHER_BAYER4}: Opacity is dithered using a Bayer 4 matrix. * - {@link DITHER_BAYER8}: Opacity is dithered using a Bayer 8 matrix. * - {@link DITHER_BAYER16}: Opacity is dithered using a Bayer 16 matrix. * - {@link DITHER_BLUENOISE}: Opacity is dithered using a blue noise. * - {@link DITHER_IGNNOISE}: Opacity is dithered using an interleaved gradient noise. * * Defaults to {@link DITHER_NONE}. * @property {string} opacityShadowDither Used to specify whether shadow opacity is dithered, which * allows shadow transparency without alpha blending. Can be: * * - {@link DITHER_NONE}: Opacity dithering is disabled. * - {@link DITHER_BAYER2}: Opacity is dithered using a Bayer 2 matrix. * - {@link DITHER_BAYER4}: Opacity is dithered using a Bayer 4 matrix. * - {@link DITHER_BAYER8}: Opacity is dithered using a Bayer 8 matrix. * - {@link DITHER_BAYER16}: Opacity is dithered using a Bayer 16 matrix. * - {@link DITHER_BLUENOISE}: Opacity is dithered using a blue noise. * - {@link DITHER_IGNNOISE}: Opacity is dithered using an interleaved gradient noise. * * Defaults to {@link DITHER_NONE}. * @property {Texture|null} normalMap The main (primary) normal map of the material (default is * null). The texture must contains normalized, tangent space normals. * @property {number} normalMapUv Main (primary) normal map UV channel. Valid values are 0 to 7. * @property {Vec2} normalMapTiling Controls the 2D tiling of the main (primary) normal map. * @property {Vec2} normalMapOffset Controls the 2D offset of the main (primary) normal map. Each * component is between 0 and 1. * @property {number} normalMapRotation Controls the 2D rotation (in degrees) of the main (primary) * normal map. * @property {Texture|null} normalDetailMap The detail (secondary) normal map of the material * (default is null). Will only be used if main (primary) normal map is non-null. * @property {number} normalDetailMapUv Detail (secondary) normal map UV channel. Valid values are 0 to 7. * @property {Vec2} normalDetailMapTiling Controls the 2D tiling of the detail (secondary) normal * map. * @property {Vec2} normalDetailMapOffset Controls the 2D offset of the detail (secondary) normal * map. Each component is between 0 and 1. * @property {number} normalDetailMapRotation Controls the 2D rotation (in degrees) of the detail * (secondary) normal map. * @property {Texture|null} heightMap The height map of the material (default is null). Used for a * view-dependent parallax effect. The texture must represent the height of the surface where * darker pixels are lower and lighter pixels are higher, with {@link heightMapBase} selecting the * value that sits at the level of the original geometry. It is recommended to use it together with * a normal map. Note that the parallax offset is applied to all other maps of the material, so the * height map should use the same tiling and offset as those maps. * @property {number} heightMapUv Height map UV channel. Valid values are 0 to 7. * @property {string} heightMapChannel Color channel of the height map to use. Can be "r", "g", "b" * or "a". * @property {Vec2} heightMapTiling Controls the 2D tiling of the height map. * @property {Vec2} heightMapOffset Controls the 2D offset of the height map. Each component is * between 0 and 1. * @property {number} heightMapRotation Controls the 2D rotation (in degrees) of the height map. * @property {string} parallaxMode Selects how the height map is used to offset the UV of the other * maps of the material. Can be: * * - {@link PARALLAX_OFFSET}: A single tap of the height map, which pivots the surface around the * {@link heightMapBase} level of the map. * - {@link PARALLAX_OCCLUSION}: The view ray is marched through the height field, which spans * {@link heightMapFactor} of depth with the geometry sitting at the {@link heightMapBase} level. * This represents deeper displacement without smearing, at the cost of multiple taps per pixel. * Note that the silhouette of the mesh is not affected, and the depth buffer still sees the flat * surface. * * Defaults to {@link PARALLAX_OFFSET}. * @property {Texture|null} envAtlas The prefiltered environment lighting atlas (default is null). * This setting overrides cubeMap and sphereMap and will replace the scene lighting environment. * @property {Texture|null} cubeMap The cubic environment map of the material (default is null). * This setting overrides sphereMap and will replace the scene lighting environment. * @property {Texture|null} sphereMap The spherical environment map of the material (default is * null). This will replace the scene lighting environment. * @property {number} cubeMapProjection The type of projection applied to the cubeMap property: * - {@link CUBEPROJ_NONE}: The cube map is treated as if it is infinitely far away. * - {@link CUBEPROJ_BOX}: Box-projection based on a world space axis-aligned bounding box. * Defaults to {@link CUBEPROJ_NONE}. * @property {Texture|null} lightMap A custom lightmap of the material (default is null). Lightmaps * are textures that contain pre-rendered lighting. Can be HDR. When a mesh instance rendered with * this material has a lightmap of its own, baked by the {@link Lightmapper}, that lightmap is used * instead of this one. * @property {number} lightMapUv Lightmap UV channel. Valid values are 0 to 7. * @property {string} lightMapChannel Color channels of the lightmap to use. Can be "r", "g", "b", * "a", "rgb" or any swizzled combination. * @property {Vec2} lightMapTiling Controls the 2D tiling of the lightmap. * @property {Vec2} lightMapOffset Controls the 2D offset of the lightmap. Each component is * between 0 and 1. * @property {number} lightMapRotation Controls the 2D rotation (in degrees) of the lightmap. * @property {boolean} lightVertexColor Use baked vertex lighting. If lightMap is set, it'll be * multiplied by vertex colors. * @property {string} lightVertexColorChannel Vertex color channels to use for baked lighting. Can * be "r", "g", "b", "a", "rgb" or any swizzled combination. * @property {Texture|null} aoMap The main (primary) baked ambient occlusion (AO) map (default is * null). Modulates ambient color. * @property {number} aoMapUv Main (primary) AO map UV channel. Valid values are 0 to 7. * @property {string} aoMapChannel Color channel of the main (primary) AO map to use. Can be "r", "g", "b" or "a". * @property {Vec2} aoMapTiling Controls the 2D tiling of the main (primary) AO map. * @property {Vec2} aoMapOffset Controls the 2D offset of the main (primary) AO map. Each component is between 0 * and 1. * @property {number} aoMapRotation Controls the 2D rotation (in degrees) of the main (primary) AO map. * @property {boolean} aoVertexColor Use mesh vertex colors for AO. If aoMap is set, it'll be * multiplied by vertex colors. * @property {string} aoVertexColorChannel Vertex color channels to use for AO. Can be "r", "g", * "b" or "a". * @property {Texture|null} aoDetailMap The detail (secondary) baked ambient occlusion (AO) map of * the material (default is null). Will only be used if main (primary) ao map is non-null. * @property {number} aoDetailMapUv Detail (secondary) AO map UV channel. Valid values are 0 to 7. * @property {Vec2} aoDetailMapTiling Controls the 2D tiling of the detail (secondary) AO map. * @property {Vec2} aoDetailMapOffset Controls the 2D offset of the detail (secondary) AO map. Each * component is between 0 and 1. * @property {number} aoDetailMapRotation Controls the 2D rotation (in degrees) of the detail * (secondary) AO map. * @property {string} aoDetailMapChannel Color channels of the detail (secondary) AO map to use. * Can be "r", "g", "b" or "a" (default is "g"). * @property {string} aoDetailMode Determines how the main (primary) and detail (secondary) * AO maps are blended together. Can be: * * - {@link DETAILMODE_MUL}: Multiply together the primary and secondary colors. * - {@link DETAILMODE_ADD}: Add together the primary and secondary colors. * - {@link DETAILMODE_SCREEN}: Softer version of {@link DETAILMODE_ADD}. * - {@link DETAILMODE_OVERLAY}: Multiplies or screens the colors, depending on the primary color. * - {@link DETAILMODE_MIN}: Select whichever of the primary and secondary colors is darker, * component-wise. * - {@link DETAILMODE_MAX}: Select whichever of the primary and secondary colors is lighter, * component-wise. * * Defaults to {@link DETAILMODE_MUL}. * @property {number} occludeSpecular Uses ambient occlusion to darken specular/reflection. It's a * hack, because real specular occlusion is view-dependent. However, it can be better than nothing. * * - {@link SPECOCC_NONE}: No specular occlusion * - {@link SPECOCC_AO}: Use AO directly to occlude specular. * - {@link SPECOCC_GLOSSDEPENDENT}: Modify AO based on material glossiness/view angle to occlude * specular. * * @property {boolean} occludeDirect Tells if AO should darken directional lighting. Defaults to * false. * @property {number} fresnelModel Defines the formula used for Fresnel effect. * As a side-effect, enabling any Fresnel model changes the way diffuse and reflection components * are combined. When Fresnel is off, legacy non energy-conserving combining is used. When it is * on, combining behavior is energy-conserving. * * - {@link FRESNEL_NONE}: No Fresnel. * - {@link FRESNEL_SCHLICK}: Schlick's approximation of Fresnel (recommended). Parameterized by * specular color. * * @property {boolean} useFog Apply fogging (as configured in scene settings) * @property {boolean} useLighting Apply lighting * @property {boolean} useSkybox Apply scene skybox as prefiltered environment map * @property {boolean} useTonemap Apply tonemapping (as configured via * {@link CameraComponent#toneMapping}). Defaults to true. * @property {boolean} pixelSnap Align vertices to pixel coordinates when rendering. Useful for * pixel perfect 2D graphics. * @property {boolean} twoSidedLighting Calculate proper normals (and therefore lighting) on * backfaces. * @property {boolean} shadowCatcher When enabled, the material will output accumulated directional * shadow value in linear space as the color. * @property {boolean} vertexColorGamma When set to true, the vertex shader converts vertex colors * from gamma to linear space to ensure correct interpolation in the fragment shader. This flag is * provided for backwards compatibility, allowing users to mark their materials to handle vertex * colors in gamma space. Defaults to false, which indicates that vertex colors are stored in * linear space. * * @category Graphics */ declare class StandardMaterial extends Material { static TEXTURE_PARAMETERS: any[]; static CUBEMAP_PARAMETERS: any[]; userAttributes: Map; /** * Whether the specular color was black at the last update. * * @type {boolean} * @private */ private _specularIsBlack; /** * Which of the assigned maps share a texture, as of the last update. * * @type {string} * @private */ private _textureSharing; /** * The texture assignment version the texture sharing was last checked for. * * @type {number} * @private */ private _sharingCheckedVersion; /** * Texture transform grouping state. * * @type {StandardMaterialMapTransforms} * @private */ private _mapTransforms; /** * A custom function that will be called after all shader generator properties are collected * and before shader code is generated. This function will receive an object with shader * generator settings (based on current material and scene properties), that you can change and * then return. Returned value will be used instead. This is mostly useful when rendering the * same set of objects, but with different shader variations based on the same material. For * example, you may wish to render a depth or normal pass using textures assigned to the * material, a reflection pass with simpler shaders and so on. These properties are split into * two sections, generic standard material options and lit options. Properties of the standard * material options are {@link StandardMaterialOptions} and the options for the lit options are * {@link LitShaderOptions}. * * @type {UpdateShaderCallback|undefined} */ onUpdateShader: UpdateShaderCallback | undefined; _assetReferences: {}; _activeParams: Set; shaderOptBuilder: StandardMaterialOptionsBuilder; reset(): void; /** The anisotropy map of the material (default is null). */ set anisotropyMap(arg: Texture|null); get anisotropyMap(): Texture|null; /** Controls the 2D offset of the anisotropy map. Each component is between 0 and 1. */ set anisotropyMapOffset(arg: Vec2); get anisotropyMapOffset(): Vec2; /** Controls the 2D rotation (in degrees) of the anisotropy map. */ set anisotropyMapRotation(arg: number); get anisotropyMapRotation(): number; /** Controls the 2D tiling of the anisotropy map. */ set anisotropyMapTiling(arg: Vec2); get anisotropyMapTiling(): Vec2; /** Anisotropy map UV channel. Valid values are 0 to 7. */ set anisotropyMapUv(arg: number); get anisotropyMapUv(): number; /** The main (primary) baked ambient occlusion (AO) map (default is null). Modulates ambient color. */ set aoMap(arg: Texture|null); get aoMap(): Texture|null; /** Color channel of the main (primary) AO map to use. Can be "r", "g", "b" or "a". */ set aoMapChannel(arg: string); get aoMapChannel(): string; /** Controls the 2D offset of the main (primary) AO map. Each component is between 0 and 1. */ set aoMapOffset(arg: Vec2); get aoMapOffset(): Vec2; /** Controls the 2D rotation (in degrees) of the main (primary) AO map. */ set aoMapRotation(arg: number); get aoMapRotation(): number; /** Controls the 2D tiling of the main (primary) AO map. */ set aoMapTiling(arg: Vec2); get aoMapTiling(): Vec2; /** Main (primary) AO map UV channel. Valid values are 0 to 7. */ set aoMapUv(arg: number); get aoMapUv(): number; /** The detail (secondary) baked ambient occlusion (AO) map of the material (default is null). Will only be used if main (primary) ao map is non-null. */ set aoDetailMap(arg: Texture|null); get aoDetailMap(): Texture|null; /** Color channels of the detail (secondary) AO map to use. Can be "r", "g", "b" or "a" (default is "g"). */ set aoDetailMapChannel(arg: string); get aoDetailMapChannel(): string; /** Controls the 2D offset of the detail (secondary) AO map. Each component is between 0 and 1. */ set aoDetailMapOffset(arg: Vec2); get aoDetailMapOffset(): Vec2; /** Controls the 2D rotation (in degrees) of the detail (secondary) AO map. */ set aoDetailMapRotation(arg: number); get aoDetailMapRotation(): number; /** Controls the 2D tiling of the detail (secondary) AO map. */ set aoDetailMapTiling(arg: Vec2); get aoDetailMapTiling(): Vec2; /** Detail (secondary) AO map UV channel. Valid values are 0 to 7. */ set aoDetailMapUv(arg: number); get aoDetailMapUv(): number; /** Determines how the main (primary) and detail (secondary) AO maps are blended together. Can be: - {@link DETAILMODE_MUL}: Multiply together the primary and secondary colors. - {@link DETAILMODE_ADD}: Add together the primary and secondary colors. - {@link DETAILMODE_SCREEN}: Softer version of {@link DETAILMODE_ADD}. - {@link DETAILMODE_OVERLAY}: Multiplies or screens the colors, depending on the primary color. - {@link DETAILMODE_MIN}: Select whichever of the primary and secondary colors is darker, component-wise. - {@link DETAILMODE_MAX}: Select whichever of the primary and secondary colors is lighter, component-wise. Defaults to {@link DETAILMODE_MUL}. */ set aoDetailMode(arg: string); get aoDetailMode(): string; /** Use mesh vertex colors for AO. If aoMap is set, it'll be multiplied by vertex colors. */ set aoVertexColor(arg: boolean); get aoVertexColor(): boolean; /** Vertex color channels to use for AO. Can be "r", "g", "b" or "a". */ set aoVertexColorChannel(arg: string); get aoVertexColorChannel(): string; /** Invert the clearcoat gloss component (default is false). Enabling this flag results in material treating the clear coat gloss members as roughness. */ set clearCoatGlossInvert(arg: boolean); get clearCoatGlossInvert(): boolean; /** Monochrome clearcoat glossiness map (default is null). If specified, will be multiplied by normalized 'clearCoatGloss' value and/or vertex colors. */ set clearCoatGlossMap(arg: Texture|null); get clearCoatGlossMap(): Texture|null; /** Color channel of the clearcoat gloss map to use. Can be "r", "g", "b" or "a". */ set clearCoatGlossMapChannel(arg: string); get clearCoatGlossMapChannel(): string; /** Controls the 2D offset of the clearcoat gloss map. Each component is between 0 and 1. */ set clearCoatGlossMapOffset(arg: Vec2); get clearCoatGlossMapOffset(): Vec2; /** Controls the 2D rotation (in degrees) of the clear coat gloss map. */ set clearCoatGlossMapRotation(arg: number); get clearCoatGlossMapRotation(): number; /** Controls the 2D tiling of the clearcoat gloss map. */ set clearCoatGlossMapTiling(arg: Vec2); get clearCoatGlossMapTiling(): Vec2; /** Clearcoat gloss map UV channel. Valid values are 0 to 7. */ set clearCoatGlossMapUv(arg: number); get clearCoatGlossMapUv(): number; /** Use mesh vertex colors for clearcoat glossiness. If clearCoatGlossMap is set, it'll be multiplied by vertex colors. */ set clearCoatGlossVertexColor(arg: boolean); get clearCoatGlossVertexColor(): boolean; /** Vertex color channel to use for clearcoat glossiness. Can be "r", "g", "b" or "a". */ set clearCoatGlossVertexColorChannel(arg: string); get clearCoatGlossVertexColorChannel(): string; /** Monochrome clearcoat intensity map (default is null). If specified, will be multiplied by normalized 'clearCoat' value and/or vertex colors. */ set clearCoatMap(arg: Texture|null); get clearCoatMap(): Texture|null; /** Color channel of the clearcoat intensity map to use. Can be "r", "g", "b" or "a". */ set clearCoatMapChannel(arg: string); get clearCoatMapChannel(): string; /** Controls the 2D offset of the clearcoat intensity map. Each component is between 0 and 1. */ set clearCoatMapOffset(arg: Vec2); get clearCoatMapOffset(): Vec2; /** Controls the 2D rotation (in degrees) of the clearcoat intensity map. */ set clearCoatMapRotation(arg: number); get clearCoatMapRotation(): number; /** Controls the 2D tiling of the clearcoat intensity map. */ set clearCoatMapTiling(arg: Vec2); get clearCoatMapTiling(): Vec2; /** Clearcoat intensity map UV channel. Valid values are 0 to 7. */ set clearCoatMapUv(arg: number); get clearCoatMapUv(): number; /** The clearcoat normal map of the material (default is null). The texture must contains normalized, tangent space normals. */ set clearCoatNormalMap(arg: Texture|null); get clearCoatNormalMap(): Texture|null; /** Controls the 2D offset of the main clearcoat normal map. Each component is between 0 and 1. */ set clearCoatNormalMapOffset(arg: Vec2); get clearCoatNormalMapOffset(): Vec2; /** Controls the 2D rotation (in degrees) of the main clearcoat map. */ set clearCoatNormalMapRotation(arg: number); get clearCoatNormalMapRotation(): number; /** Controls the 2D tiling of the main clearcoat normal map. */ set clearCoatNormalMapTiling(arg: Vec2); get clearCoatNormalMapTiling(): Vec2; /** Clearcoat normal map UV channel. Valid values are 0 to 7. */ set clearCoatNormalMapUv(arg: number); get clearCoatNormalMapUv(): number; /** Use mesh vertex colors for clearcoat intensity. If clearCoatMap is set, it'll be multiplied by vertex colors. */ set clearCoatVertexColor(arg: boolean); get clearCoatVertexColor(): boolean; /** Vertex color channel to use for clearcoat intensity. Can be "r", "g", "b" or "a". */ set clearCoatVertexColorChannel(arg: string); get clearCoatVertexColorChannel(): string; /** The cubic environment map of the material (default is null). This setting overrides sphereMap and will replace the scene lighting environment. */ set cubeMap(arg: Texture|null); get cubeMap(): Texture|null; /** The type of projection applied to the cubeMap property: - {@link CUBEPROJ_NONE}: The cube map is treated as if it is infinitely far away. - {@link CUBEPROJ_BOX}: Box-projection based on a world space axis-aligned bounding box. Defaults to {@link CUBEPROJ_NONE}. */ set cubeMapProjection(arg: number); get cubeMapProjection(): number; /** The detail (secondary) diffuse map of the material (default is null). Will only be used if main (primary) diffuse map is non-null. */ set diffuseDetailMap(arg: Texture|null); get diffuseDetailMap(): Texture|null; /** Color channels of the detail (secondary) diffuse map to use. Can be "r", "g", "b", "a", "rgb" or any swizzled combination. */ set diffuseDetailMapChannel(arg: string); get diffuseDetailMapChannel(): string; /** Controls the 2D offset of the detail (secondary) diffuse map. Each component is between 0 and 1. */ set diffuseDetailMapOffset(arg: Vec2); get diffuseDetailMapOffset(): Vec2; /** Controls the 2D rotation (in degrees) of the detail (secondary) diffuse map. */ set diffuseDetailMapRotation(arg: number); get diffuseDetailMapRotation(): number; /** Controls the 2D tiling of the detail (secondary) diffuse map. */ set diffuseDetailMapTiling(arg: Vec2); get diffuseDetailMapTiling(): Vec2; /** Detail (secondary) diffuse map UV channel. Valid values are 0 to 7. */ set diffuseDetailMapUv(arg: number); get diffuseDetailMapUv(): number; /** Determines how the main (primary) and detail (secondary) diffuse maps are blended together. Can be: - {@link DETAILMODE_MUL}: Multiply together the primary and secondary colors. - {@link DETAILMODE_ADD}: Add together the primary and secondary colors. - {@link DETAILMODE_SCREEN}: Softer version of {@link DETAILMODE_ADD}. - {@link DETAILMODE_OVERLAY}: Multiplies or screens the colors, depending on the primary color. - {@link DETAILMODE_MIN}: Select whichever of the primary and secondary colors is darker, component-wise. - {@link DETAILMODE_MAX}: Select whichever of the primary and secondary colors is lighter, component-wise. Defaults to {@link DETAILMODE_MUL}. */ set diffuseDetailMode(arg: string); get diffuseDetailMode(): string; /** The main (primary) diffuse map of the material (default is null). */ set diffuseMap(arg: Texture|null); get diffuseMap(): Texture|null; /** Color channels of the main (primary) diffuse map to use. Can be "r", "g", "b", "a", "rgb" or any swizzled combination. */ set diffuseMapChannel(arg: string); get diffuseMapChannel(): string; /** Controls the 2D offset of the main (primary) diffuse map. Each component is between 0 and 1. */ set diffuseMapOffset(arg: Vec2); get diffuseMapOffset(): Vec2; /** Controls the 2D rotation (in degrees) of the main (primary) diffuse map. */ set diffuseMapRotation(arg: number); get diffuseMapRotation(): number; /** Controls the 2D tiling of the main (primary) diffuse map. */ set diffuseMapTiling(arg: Vec2); get diffuseMapTiling(): Vec2; /** Main (primary) diffuse map UV channel. Valid values are 0 to 7. */ set diffuseMapUv(arg: number); get diffuseMapUv(): number; /** Multiply diffuse by the mesh vertex colors. */ set diffuseVertexColor(arg: boolean); get diffuseVertexColor(): boolean; /** Vertex color channels to use for diffuse. Can be "r", "g", "b", "a", "rgb" or any swizzled combination. */ set diffuseVertexColorChannel(arg: string); get diffuseVertexColorChannel(): string; /** The emissive map of the material (default is null). Can be HDR. When the emissive map is applied, the emissive color is multiplied by the texel color in the map. Since the emissive color is black by default, the emissive map won't be visible unless the emissive color is changed. */ set emissiveMap(arg: Texture|null); get emissiveMap(): Texture|null; /** Color channels of the emissive map to use. Can be "r", "g", "b", "a", "rgb" or any swizzled combination. */ set emissiveMapChannel(arg: string); get emissiveMapChannel(): string; /** Controls the 2D offset of the emissive map. Each component is between 0 and 1. */ set emissiveMapOffset(arg: Vec2); get emissiveMapOffset(): Vec2; /** Controls the 2D rotation (in degrees) of the emissive map. */ set emissiveMapRotation(arg: number); get emissiveMapRotation(): number; /** Controls the 2D tiling of the emissive map. */ set emissiveMapTiling(arg: Vec2); get emissiveMapTiling(): Vec2; /** Emissive map UV channel. Valid values are 0 to 7. */ set emissiveMapUv(arg: number); get emissiveMapUv(): number; /** Use mesh vertex colors for emission. If emissiveMap or emissive are set, they'll be multiplied by vertex colors. */ set emissiveVertexColor(arg: boolean); get emissiveVertexColor(): boolean; /** Vertex color channels to use for emission. Can be "r", "g", "b", "a", "rgb" or any swizzled combination. */ set emissiveVertexColorChannel(arg: string); get emissiveVertexColorChannel(): string; /** Enables GGX specular. Also enables {@link anisotropyIntensity} parameter to set material anisotropy. */ set enableGGXSpecular(arg: boolean); get enableGGXSpecular(): boolean; /** The prefiltered environment lighting atlas (default is null). This setting overrides cubeMap and sphereMap and will replace the scene lighting environment. */ set envAtlas(arg: Texture|null); get envAtlas(): Texture|null; /** Defines the formula used for Fresnel effect. As a side-effect, enabling any Fresnel model changes the way diffuse and reflection components are combined. When Fresnel is off, legacy non energy-conserving combining is used. When it is on, combining behavior is energy-conserving. - {@link FRESNEL_NONE}: No Fresnel. - {@link FRESNEL_SCHLICK}: Schlick's approximation of Fresnel (recommended). Parameterized by specular color. */ set fresnelModel(arg: number); get fresnelModel(): number; /** Invert the gloss component (default is false). Enabling this flag results in material treating the gloss members as roughness. */ set glossInvert(arg: boolean); get glossInvert(): boolean; /** Gloss map (default is null). If specified, will be multiplied by normalized gloss value and/or vertex colors. */ set glossMap(arg: Texture|null); get glossMap(): Texture|null; /** Color channel of the gloss map to use. Can be "r", "g", "b" or "a". */ set glossMapChannel(arg: string); get glossMapChannel(): string; /** Controls the 2D offset of the gloss map. Each component is between 0 and 1. */ set glossMapOffset(arg: Vec2); get glossMapOffset(): Vec2; /** Controls the 2D rotation (in degrees) of the gloss map. */ set glossMapRotation(arg: number); get glossMapRotation(): number; /** Controls the 2D tiling of the gloss map. */ set glossMapTiling(arg: Vec2); get glossMapTiling(): Vec2; /** Gloss map UV channel. Valid values are 0 to 7. */ set glossMapUv(arg: number); get glossMapUv(): number; /** Use mesh vertex colors for glossiness. If glossMap is set, it'll be multiplied by vertex colors. */ set glossVertexColor(arg: boolean); get glossVertexColor(): boolean; /** Vertex color channel to use for glossiness. Can be "r", "g", "b" or "a". */ set glossVertexColorChannel(arg: string); get glossVertexColorChannel(): string; /** The height map of the material (default is null). Used for a view-dependent parallax effect. The texture must represent the height of the surface where darker pixels are lower and lighter pixels are higher, with {@link heightMapBase} selecting the value that sits at the level of the original geometry. It is recommended to use it together with a normal map. Note that the parallax offset is applied to all other maps of the material, so the height map should use the same tiling and offset as those maps. */ set heightMap(arg: Texture|null); get heightMap(): Texture|null; /** Color channel of the height map to use. Can be "r", "g", "b" or "a". */ set heightMapChannel(arg: string); get heightMapChannel(): string; /** Controls the 2D offset of the height map. Each component is between 0 and 1. */ set heightMapOffset(arg: Vec2); get heightMapOffset(): Vec2; /** Controls the 2D rotation (in degrees) of the height map. */ set heightMapRotation(arg: number); get heightMapRotation(): number; /** Controls the 2D tiling of the height map. */ set heightMapTiling(arg: Vec2); get heightMapTiling(): Vec2; /** Height map UV channel. Valid values are 0 to 7. */ set heightMapUv(arg: number); get heightMapUv(): number; /** A custom lightmap of the material (default is null). Lightmaps are textures that contain pre-rendered lighting. Can be HDR. When a mesh instance rendered with this material has a lightmap of its own, baked by the {@link Lightmapper}, that lightmap is used instead of this one. */ set lightMap(arg: Texture|null); get lightMap(): Texture|null; /** Color channels of the lightmap to use. Can be "r", "g", "b", "a", "rgb" or any swizzled combination. */ set lightMapChannel(arg: string); get lightMapChannel(): string; /** Controls the 2D offset of the lightmap. Each component is between 0 and 1. */ set lightMapOffset(arg: Vec2); get lightMapOffset(): Vec2; /** Controls the 2D rotation (in degrees) of the lightmap. */ set lightMapRotation(arg: number); get lightMapRotation(): number; /** Controls the 2D tiling of the lightmap. */ set lightMapTiling(arg: Vec2); get lightMapTiling(): Vec2; /** Lightmap UV channel. Valid values are 0 to 7. */ set lightMapUv(arg: number); get lightMapUv(): number; /** Use baked vertex lighting. If lightMap is set, it'll be multiplied by vertex colors. */ set lightVertexColor(arg: boolean); get lightVertexColor(): boolean; /** Vertex color channels to use for baked lighting. Can be "r", "g", "b", "a", "rgb" or any swizzled combination. */ set lightVertexColorChannel(arg: string); get lightVertexColorChannel(): string; /** Monochrome metalness map (default is null). */ set metalnessMap(arg: Texture|null); get metalnessMap(): Texture|null; /** Color channel of the metalness map to use. Can be "r", "g", "b" or "a". */ set metalnessMapChannel(arg: string); get metalnessMapChannel(): string; /** Controls the 2D offset of the metalness map. Each component is between 0 and 1. */ set metalnessMapOffset(arg: Vec2); get metalnessMapOffset(): Vec2; /** Controls the 2D rotation (in degrees) of the metalness map. */ set metalnessMapRotation(arg: number); get metalnessMapRotation(): number; /** Controls the 2D tiling of the metalness map. */ set metalnessMapTiling(arg: Vec2); get metalnessMapTiling(): Vec2; /** Metalness map UV channel. Valid values are 0 to 7. */ set metalnessMapUv(arg: number); get metalnessMapUv(): number; /** Use mesh vertex colors for metalness. If metalnessMap is set, it'll be multiplied by vertex colors. */ set metalnessVertexColor(arg: boolean); get metalnessVertexColor(): boolean; /** Vertex color channel to use for metalness. Can be "r", "g", "b" or "a". */ set metalnessVertexColorChannel(arg: string); get metalnessVertexColorChannel(): string; /** The detail (secondary) normal map of the material (default is null). Will only be used if main (primary) normal map is non-null. */ set normalDetailMap(arg: Texture|null); get normalDetailMap(): Texture|null; /** Controls the 2D offset of the detail (secondary) normal map. Each component is between 0 and 1. */ set normalDetailMapOffset(arg: Vec2); get normalDetailMapOffset(): Vec2; /** Controls the 2D rotation (in degrees) of the detail (secondary) normal map. */ set normalDetailMapRotation(arg: number); get normalDetailMapRotation(): number; /** Controls the 2D tiling of the detail (secondary) normal map. */ set normalDetailMapTiling(arg: Vec2); get normalDetailMapTiling(): Vec2; /** Detail (secondary) normal map UV channel. Valid values are 0 to 7. */ set normalDetailMapUv(arg: number); get normalDetailMapUv(): number; /** The main (primary) normal map of the material (default is null). The texture must contains normalized, tangent space normals. */ set normalMap(arg: Texture|null); get normalMap(): Texture|null; /** Controls the 2D offset of the main (primary) normal map. Each component is between 0 and 1. */ set normalMapOffset(arg: Vec2); get normalMapOffset(): Vec2; /** Controls the 2D rotation (in degrees) of the main (primary) normal map. */ set normalMapRotation(arg: number); get normalMapRotation(): number; /** Controls the 2D tiling of the main (primary) normal map. */ set normalMapTiling(arg: Vec2); get normalMapTiling(): Vec2; /** Main (primary) normal map UV channel. Valid values are 0 to 7. */ set normalMapUv(arg: number); get normalMapUv(): number; /** Tells if AO should darken directional lighting. Defaults to false. */ set occludeDirect(arg: boolean); get occludeDirect(): boolean; /** Uses ambient occlusion to darken specular/reflection. It's a hack, because real specular occlusion is view-dependent. However, it can be better than nothing. - {@link SPECOCC_NONE}: No specular occlusion - {@link SPECOCC_AO}: Use AO directly to occlude specular. - {@link SPECOCC_GLOSSDEPENDENT}: Modify AO based on material glossiness/view angle to occlude specular. */ set occludeSpecular(arg: number); get occludeSpecular(): number; /** Used to specify whether opacity is dithered, which allows transparency without alpha blending. Can be: - {@link DITHER_NONE}: Opacity dithering is disabled. - {@link DITHER_BAYER2}: Opacity is dithered using a Bayer 2 matrix. - {@link DITHER_BAYER4}: Opacity is dithered using a Bayer 4 matrix. - {@link DITHER_BAYER8}: Opacity is dithered using a Bayer 8 matrix. - {@link DITHER_BAYER16}: Opacity is dithered using a Bayer 16 matrix. - {@link DITHER_BLUENOISE}: Opacity is dithered using a blue noise. - {@link DITHER_IGNNOISE}: Opacity is dithered using an interleaved gradient noise. Defaults to {@link DITHER_NONE}. */ set opacityDither(arg: string); get opacityDither(): string; /** Used to specify whether shadow opacity is dithered, which allows shadow transparency without alpha blending. Can be: - {@link DITHER_NONE}: Opacity dithering is disabled. - {@link DITHER_BAYER2}: Opacity is dithered using a Bayer 2 matrix. - {@link DITHER_BAYER4}: Opacity is dithered using a Bayer 4 matrix. - {@link DITHER_BAYER8}: Opacity is dithered using a Bayer 8 matrix. - {@link DITHER_BAYER16}: Opacity is dithered using a Bayer 16 matrix. - {@link DITHER_BLUENOISE}: Opacity is dithered using a blue noise. - {@link DITHER_IGNNOISE}: Opacity is dithered using an interleaved gradient noise. Defaults to {@link DITHER_NONE}. */ set opacityShadowDither(arg: string); get opacityShadowDither(): string; /** Used to specify whether specular and reflections are faded out using {@link opacity}. Default is true. When set to false use {@link alphaFade} to fade out materials. */ set opacityFadesSpecular(arg: boolean); get opacityFadesSpecular(): boolean; /** The opacity map of the material (default is null). */ set opacityMap(arg: Texture|null); get opacityMap(): Texture|null; /** Color channel of the opacity map to use. Can be "r", "g", "b" or "a". */ set opacityMapChannel(arg: string); get opacityMapChannel(): string; /** Controls the 2D offset of the opacity map. Each component is between 0 and 1. */ set opacityMapOffset(arg: Vec2); get opacityMapOffset(): Vec2; /** Controls the 2D rotation (in degrees) of the opacity map. */ set opacityMapRotation(arg: number); get opacityMapRotation(): number; /** Controls the 2D tiling of the opacity map. */ set opacityMapTiling(arg: Vec2); get opacityMapTiling(): Vec2; /** Opacity map UV channel. Valid values are 0 to 7. */ set opacityMapUv(arg: number); get opacityMapUv(): number; /** Use mesh vertex colors for opacity. If opacityMap is set, it'll be multiplied by vertex colors. */ set opacityVertexColor(arg: boolean); get opacityVertexColor(): boolean; /** Vertex color channels to use for opacity. Can be "r", "g", "b" or "a". */ set opacityVertexColorChannel(arg: string); get opacityVertexColorChannel(): string; /** Align vertices to pixel coordinates when rendering. Useful for pixel perfect 2D graphics. */ set pixelSnap(arg: boolean); get pixelSnap(): boolean; /** When enabled, the material will output accumulated directional shadow value in linear space as the color. */ set shadowCatcher(arg: boolean); get shadowCatcher(): boolean; /** The specular map of the material (default is null). */ set specularMap(arg: Texture|null); get specularMap(): Texture|null; /** Color channels of the specular map to use. Can be "r", "g", "b", "a", "rgb" or any swizzled combination. */ set specularMapChannel(arg: string); get specularMapChannel(): string; /** Controls the 2D offset of the specular map. Each component is between 0 and 1. */ set specularMapOffset(arg: Vec2); get specularMapOffset(): Vec2; /** Controls the 2D rotation (in degrees) of the specular map. */ set specularMapRotation(arg: number); get specularMapRotation(): number; /** Controls the 2D tiling of the specular map. */ set specularMapTiling(arg: Vec2); get specularMapTiling(): Vec2; /** Specular map UV channel. Valid values are 0 to 7. */ set specularMapUv(arg: number); get specularMapUv(): number; /** Multiply specular by the mesh vertex colors. */ set specularVertexColor(arg: boolean); get specularVertexColor(): boolean; /** Vertex color channels to use for specular. Can be "r", "g", "b", "a", "rgb" or any swizzled combination. */ set specularVertexColorChannel(arg: string); get specularVertexColorChannel(): string; /** The factor of specularity as a texture (default is null). */ set specularityFactorMap(arg: Texture|null); get specularityFactorMap(): Texture|null; /** The channel used by the specularity factor texture to sample from (default is 'a'). */ set specularityFactorMapChannel(arg: string); get specularityFactorMapChannel(): string; /** Controls the 2D offset of the specularity factor map. Each component is between 0 and 1. */ set specularityFactorMapOffset(arg: Vec2); get specularityFactorMapOffset(): Vec2; /** Controls the 2D rotation (in degrees) of the specularity factor map. */ set specularityFactorMapRotation(arg: number); get specularityFactorMapRotation(): number; /** Controls the 2D tiling of the specularity factor map. */ set specularityFactorMapTiling(arg: Vec2); get specularityFactorMapTiling(): Vec2; /** Specularity factor map UV channel. Valid values are 0 to 7. */ set specularityFactorMapUv(arg: number); get specularityFactorMapUv(): number; /** Toggle sheen specular effect on/off. */ set useSheen(arg: boolean); get useSheen(): boolean; /** The sheen microstructure color map of the material (default is null). */ set sheenMap(arg: Texture|null); get sheenMap(): Texture|null; /** Color channels of the sheen map to use. Can be "r", "g", "b", "a", "rgb" or any swizzled combination. */ set sheenMapChannel(arg: string); get sheenMapChannel(): string; /** Controls the 2D offset of the sheen map. Each component is between 0 and 1. */ set sheenMapOffset(arg: Vec2); get sheenMapOffset(): Vec2; /** Controls the 2D rotation (in degrees) of the sheen map. */ set sheenMapRotation(arg: number); get sheenMapRotation(): number; /** Controls the 2D tiling of the sheen map. */ set sheenMapTiling(arg: Vec2); get sheenMapTiling(): Vec2; /** Sheen map UV channel. Valid values are 0 to 7. */ set sheenMapUv(arg: number); get sheenMapUv(): number; /** Use mesh vertex colors for sheen. If sheen map or sheen tint are set, they'll be multiplied by vertex colors. */ set sheenVertexColor(arg: boolean); get sheenVertexColor(): boolean; /** Vertex color channels to use for sheen. Can be "r", "g", "b", "a", "rgb" or any swizzled combination. */ set sheenVertexColorChannel(arg: string); get sheenVertexColorChannel(): string; /** The spherical environment map of the material (default is null). This will replace the scene lighting environment. */ set sphereMap(arg: Texture|null); get sphereMap(): Texture|null; /** Calculate proper normals (and therefore lighting) on backfaces. */ set twoSidedLighting(arg: boolean); get twoSidedLighting(): boolean; /** Apply fogging (as configured in scene settings) */ set useFog(arg: boolean); get useFog(): boolean; /** Apply tonemapping (as configured via {@link CameraComponent#toneMapping}). Defaults to true. */ set useTonemap(arg: boolean); get useTonemap(): boolean; /** Apply lighting */ set useLighting(arg: boolean); get useLighting(): boolean; /** Use metalness properties instead of specular. When enabled, diffuse colors also affect specular instead of the dedicated specular map. This can be used as alternative to specular color to save space. With metalness == 0, the pixel is assumed to be dielectric, and diffuse color is used as normal. With metalness == 1, the pixel is fully metallic, and diffuse color is used as specular color instead. */ set useMetalness(arg: boolean); get useMetalness(): boolean; /** When metalness is enabled, use the specular map to apply color tint to specular reflections. */ set useMetalnessSpecularColor(arg: boolean); get useMetalnessSpecularColor(): boolean; /** Apply scene skybox as prefiltered environment map */ set useSkybox(arg: boolean); get useSkybox(): boolean; /** * The map property which claims the sampler of each assigned map, so that the shader samples * the slots of the material's bind group under the names that group declares them with. * * @ignore */ get textureIdentifiers(): Map; /** @ignore */ getUniformBufferProperty(name: any): MaterialProperty; /** * Adds the names of the map properties changed without a subsequent update, for the debug * warning about unapplied changes. * * @param {string[]} names - The names to add to. * @private */ private _collectUnappliedChanges; /** * Sets the diffuse color of the material, specified in sRGB color space. This color value is * 3-component (RGB), where each component is between 0 and 1. Defines basic surface color (aka * albedo). * * @type {Color} */ set diffuse(value: Color); /** * Gets the diffuse color of the material. * * @type {Color} */ get diffuse(): Color; /** * Sets the emissive color of the material, specified in sRGB color space. This color value is * 3-component (RGB), where each component is between 0 and 1. The emission is this color * multiplied by {@link StandardMaterial#emissiveIntensity}, and by the emissive map when one is * set. * * @type {Color} */ set emissive(value: Color); /** * Gets the emissive color of the material. * * @type {Color} */ get emissive(): Color; /** * Sets the emissive color multiplier. Defaults to 1. * * @type {number} */ set emissiveIntensity(value: number); /** * Gets the emissive color multiplier. * * @type {number} */ get emissiveIntensity(): number; _emissiveIntensity: any; /** * The ambient color of the material, specified in sRGB color space. This color value is * 3-component (RGB), where each component is between 0 and 1. * * @type {Color} */ set ambient(value: Color); /** * Gets the ambient color of the material. * * @type {Color} */ get ambient(): Color; /** * The specular color of the material, specified in sRGB color space. This color value is * 3-component (RGB), where each component is between 0 and 1. Defines surface * reflection/specular color. Affects specular intensity and tint. * * @type {Color} */ set specular(value: Color); /** * Gets the specular color of the material. * * @type {Color} */ get specular(): Color; /** * The specular color of the sheen (fabric) microfiber structure, specified in sRGB color space. * This color value is 3-component (RGB), where each component is between 0 and 1. * * @type {Color} */ set sheen(value: Color); /** * Gets the sheen color of the material. * * @type {Color} */ get sheen(): Color; /** * The attenuation color for refractive materials, specified in sRGB color space. Only used when * useDynamicRefraction is enabled. * * @type {Color} */ set attenuation(value: Color); /** * Gets the attenuation color of the material. * * @type {Color} */ get attenuation(): Color; /** * The factor of specular intensity, used to weight the fresnel and specularity. Default is 1.0. * * @type {number} */ set specularityFactor(value: number); /** * Gets the specularity factor of the material. * * @type {number} */ get specularityFactor(): number; _specularityFactor: any; /** * The glossiness of the sheen (fabric) microfiber structure. This color value is a single value * between 0 and 1. * * @type {number} */ set sheenGloss(value: number); /** * Gets the sheen glossiness of the material. * * @type {number} */ get sheenGloss(): number; _sheenGloss: any; /** * Defines the glossiness of the material from 0 (rough) to 1 (shiny). Materials imported from * glTF enable {@link StandardMaterial#glossInvert}, which reverses this: on those materials * gloss holds roughness, so 0 is shiny and 1 is rough. * * @type {number} */ set gloss(value: number); /** * Gets the glossiness of the material. * * @type {number} */ get gloss(): number; _gloss: any; /** * Ambient occlusion intensity. Defaults to 1. * * @type {number} */ set aoIntensity(value: number); /** * Gets the ambient occlusion intensity of the material. * * @type {number} */ get aoIntensity(): number; _aoIntensity: any; /** * The height map value that sits at the level of the original geometry, in the 0 to 1 range * (default is 0.5). Relief above the base appears to stand out of the surface and relief below * it appears to sink in. Set it to 1 to treat the map as pure depth carved below the geometry, * or to 0 to treat it as pure elevation above it. Both parallax modes honor it. * * @type {number} */ set heightMapBase(value: number); /** * Gets the height map base level of the material. * * @type {number} */ get heightMapBase(): number; _heightMapBase: any; /** * The maximum number of height map taps taken along the view ray when {@link parallaxMode} is * {@link PARALLAX_OCCLUSION} (default is 16). Fewer taps are taken as the view direction * approaches the surface normal, where the ray barely moves. Has no effect in {@link * PARALLAX_OFFSET} mode. * * @type {number} */ set parallaxSamples(value: number); /** * Gets the maximum number of height map taps of parallax occlusion mapping of the material. * * @type {number} */ get parallaxSamples(): number; _parallaxSamples: any; /** * The maximum number of height map taps taken towards each directional light to shadow the * relief against itself, or 0 to disable it (default is 0). The shadow is soft: the march * accumulates how far the height field stands above the light ray and weights it by distance, * so more taps buy a smoother penumbra rather than an earlier exit. Applies only to directional * lights, and only when {@link parallaxMode} is {@link PARALLAX_OCCLUSION}. * * @type {number} */ set parallaxShadowSamples(value: number); /** * Gets the maximum number of height map taps of the parallax self shadowing of the material. * * @type {number} */ get parallaxShadowSamples(): number; _parallaxShadowSamples: any; /** * The opacity of the material. This value can be between 0 and 1, where 0 is fully transparent * and 1 is fully opaque. If you want the material to be semi-transparent you also need to set * the {@link Material#blendType} to {@link BLEND_NORMAL}, {@link BLEND_ADDITIVE} or any other * mode. Also note that for most semi-transparent objects you want {@link Material#depthWrite} * to be false, otherwise they can fully occlude objects behind them. * * @type {number} */ set opacity(value: number); /** * Gets the opacity of the material. * * @type {number} */ get opacity(): number; _opacity: any; /** * Used to fade out materials when {@link opacityFadesSpecular} is set to false. * * @type {number} */ set alphaFade(value: number); /** * Gets the alpha fade of the material. * * @type {number} */ get alphaFade(): number; _alphaFade: any; /** * The bumpiness of the material. This value scales the assigned main (primary) normal map. It * should be normally between 0 (no bump mapping) and 1 (full bump mapping), but can be set to * e.g. 2 to give even more pronounced bump effect. * * @type {number} */ set bumpiness(value: number); /** * Gets the bumpiness of the material. * * @type {number} */ get bumpiness(): number; _bumpiness: any; /** * The bumpiness of the material. This value scales the assigned detail (secondary) normal map. * It should be normally between 0 (no bump mapping) and 1 (full bump mapping), but can be set * to e.g. 2 to give even more pronounced bump effect. * * @type {number} */ set normalDetailMapBumpiness(value: number); /** * Gets the detail normal map bumpiness of the material. * * @type {number} */ get normalDetailMapBumpiness(): number; _normalDetailMapBumpiness: any; /** * Environment map intensity. * * @type {number} */ set reflectivity(value: number); /** * Gets the environment map intensity of the material. * * @type {number} */ get reflectivity(): number; _reflectivity: any; /** * Controls visibility of specular occlusion. * * @type {number} */ set occludeSpecularIntensity(value: number); /** * Gets the specular occlusion intensity of the material. * * @type {number} */ get occludeSpecularIntensity(): number; _occludeSpecularIntensity: any; /** * Defines the visibility of refraction. Material can refract the same cube map as used for * reflections. * * @type {number} */ set refraction(value: number); /** * Gets the refraction of the material. * * @type {number} */ get refraction(): number; _refraction: any; /** * Defines the index of refraction, i.e. The amount of distortion. The value is calculated as * (outerIor / surfaceIor), where inputs are measured indices of refraction, the one around the * object and the one of its own surface. In most situations outer medium is air, so outerIor * will be approximately 1. Then you only need to do (1.0 / surfaceIor). * * @type {number} */ set refractionIndex(value: number); /** * Gets the index of refraction of the material. * * @type {number} */ get refractionIndex(): number; _refractionIndex: any; /** * The strength of the angular separation of colors (chromatic aberration) transmitting through * a volume. Defaults to 0, which is equivalent to no dispersion. * * @type {number} */ set dispersion(value: number); /** * Gets the dispersion of the material. * * @type {number} */ get dispersion(): number; _dispersion: any; /** * The thickness of the medium, only used when useDynamicRefraction is enabled. The unit is in * base units, and scales with the size of the object. * * @type {number} */ set thickness(value: number); /** * Gets the thickness of the medium of the material. * * @type {number} */ get thickness(): number; _thickness: any; /** * Defines how much the surface is metallic. From 0 (dielectric) to 1 (metal). * * @type {number} */ set metalness(value: number); /** * Gets the metalness of the material. * * @type {number} */ get metalness(): number; _metalness: any; /** * Defines amount of anisotropy. Requires {@link enableGGXSpecular} is set to true. - When * anisotropyIntensity == 0, specular is isotropic. - Specular anisotropy increases as * anisotropyIntensity value increases to maximum of 1. * * @type {number} */ set anisotropyIntensity(value: number); /** * Gets the anisotropy intensity of the material. * * @type {number} */ get anisotropyIntensity(): number; _anisotropyIntensity: any; /** * Defines intensity of clearcoat layer from 0 to 1. Clearcoat layer is disabled when clearCoat * == 0. Default value is 0 (disabled). * * @type {number} */ set clearCoat(value: number); /** * Gets the clearcoat intensity of the material. * * @type {number} */ get clearCoat(): number; _clearCoat: any; /** * Defines the clearcoat glossiness of the clearcoat layer from 0 (rough) to 1 (mirror). * * @type {number} */ set clearCoatGloss(value: number); /** * Gets the clearcoat glossiness of the material. * * @type {number} */ get clearCoatGloss(): number; _clearCoatGloss: any; /** * The bumpiness of the clearcoat layer. This value scales the assigned main clearcoat normal * map. It should be normally between 0 (no bump mapping) and 1 (full bump mapping), but can be * set to e.g. 2 to give even more pronounced bump effect. * * @type {number} */ set clearCoatBumpiness(value: number); /** * Gets the clearcoat bumpiness of the material. * * @type {number} */ get clearCoatBumpiness(): number; _clearCoatBumpiness: any; /** * Defines the intensity of the iridescence layer from 0 to 1. Only used when useIridescence is * enabled, and the layer is disabled when iridescence == 0. If an iridescenceMap is specified, * it is multiplied by this value. Default value is 0 (disabled). * * @type {number} */ set iridescence(value: number); /** * Gets the iridescence intensity of the material. * * @type {number} */ get iridescence(): number; _iridescence: any; /** * The index of refraction of the iridescent thin-film. Affects the color phase shift as * described here: * https://github.com/KhronosGroup/glTF/tree/main/extensions/2.0/Khronos/KHR_materials_iridescence * * @type {number} */ set iridescenceRefractionIndex(value: number); /** * Gets the index of refraction of the iridescent thin-film of the material. * * @type {number} */ get iridescenceRefractionIndex(): number; _iridescenceRefractionIndex: any; /** * The minimum thickness for the iridescence layer. Only used when an iridescence thickness map * is used. The unit is in nm. * * @type {number} */ set iridescenceThicknessMin(value: number); /** * Gets the minimum iridescence thickness of the material. * * @type {number} */ get iridescenceThicknessMin(): number; _iridescenceThicknessMin: any; /** * The maximum thickness for the iridescence layer. Used as the 'base' thickness when no * iridescence thickness map is defined. The unit is in nm. * * @type {number} */ set iridescenceThicknessMax(value: number); /** * Gets the maximum iridescence thickness of the material. * * @type {number} */ get iridescenceThicknessMax(): number; _iridescenceThicknessMax: any; /** * Defines the rotation (in degrees) of anisotropy. * * @type {number} */ set anisotropyRotation(value: number); /** * Gets the anisotropy rotation of the material. * * @type {number} */ get anisotropyRotation(): number; _anisotropyRotation: any; /** * The distance defining the absorption rate of light within the medium. Only used when * useDynamicRefraction is enabled. * * @type {number} */ set attenuationDistance(value: number); /** * Gets the attenuation distance of the material. * * @type {number} */ get attenuationDistance(): number; _attenuationDistance: any; /** * Height map multiplier (default is 1). Affects the strength of the parallax effect. A value of * 1 displaces the texture by up to 5% of a UV tile, so useful values are typically in the 0 to * 2 range. * * @type {number} */ set heightMapFactor(value: number); /** * Gets the height map factor of the material. * * @type {number} */ get heightMapFactor(): number; _heightMapFactor: any; /** * The alpha value used by the opacity dither path, in the range [0, 1]. Independent of {@link * opacity}, which keeps driving alpha blending. Lets a material be alpha-blended and dithered * at the same time with different strengths — useful for fading objects out via dither while * preserving their alpha-blended look (e.g. fading glass as the camera approaches). Has no * effect unless {@link opacityDither} (or {@link opacityShadowDither}) is set to a dither mode. * Set to `1.0` to disable dither at runtime without changing the dither mode, or `0.0` to fully * discard via dither. For backwards compatibility, a material that has never had this property * assigned uses {@link opacity} as the dither alpha, matching the historical behavior where the * dither pass shares the blend alpha. * * @type {number} */ set alphaDither(value: number); /** * Gets the dither alpha of the material. * * @type {number} */ get alphaDither(): number; _alphaDither: any; /** * Sets the world space axis-aligned bounding box defining the box-projection used for the * cubeMap property, or null for no box. Only used when cubeMapProjection is set to * {@link CUBEPROJ_BOX}. The box is copied into the material. * * @type {BoundingBox|null} */ set cubeMapProjectionBox(value: BoundingBox | null); /** * Gets the world space axis-aligned bounding box of the box-projection, or null. A change of * its center or half extents is applied by {@link StandardMaterial#update}. * * @type {BoundingBox|null} */ get cubeMapProjectionBox(): BoundingBox | null; _cubeMapProjectionBox: BoundingBox; /** * Copy a `StandardMaterial`. * * @param {StandardMaterial} source - The material to copy from. * @returns {StandardMaterial} The destination material. */ copy(source: StandardMaterial): StandardMaterial; /** * Returns the transform group assigned to a texture map. * * @param {string} name - Texture map base name. * @returns {number} The transform group, or zero when no transform is needed. * @private */ private _getMapTransformId; /** * Sets a vertex shader attribute on a material. * * @param {string} name - The name of the parameter to set. * @param {string} semantic - Semantic to map the vertex data. Must match with the semantic set * on vertex stream of the mesh. * @example * mesh.setVertexStream(SEMANTIC_ATTR15, offset, 3); * material.setAttribute('offset', SEMANTIC_ATTR15); */ setAttribute(name: string, semantic: string): void; _setParameter(name: any, value: any): void; /** * Replaces the set of parameters published by the previous update with the parameters published * since, deleting the ones that were dropped. * * @private */ private _processParameters; _updateMap(p: any): void; /** @ignore */ getShaderVariant(params: any): Shader; /** * Sets the shininess in the range 0 to 100, mapping to {@link StandardMaterial#gloss} in the * range 0 to 1. * * @type {number} * @ignore * @deprecated Use {@link StandardMaterial#gloss} instead. */ set shininess(value: number); /** * Gets the shininess. * * @type {number} * @ignore * @deprecated Use {@link StandardMaterial#gloss} instead. */ get shininess(): number; /** * Sets whether tonemapping is applied. Note: no deprecation warning is logged, to keep * existing code working without warnings. * * @type {boolean} * @ignore * @deprecated Use {@link StandardMaterial#useTonemap} instead. */ set useGammaTonemap(value: boolean); /** * Gets whether tonemapping is applied. * * @type {boolean} * @ignore * @deprecated Use {@link StandardMaterial#useTonemap} instead. */ get useGammaTonemap(): boolean; /** * Sets the anisotropy as a signed intensity, mapping to {@link StandardMaterial#anisotropyIntensity} * and {@link StandardMaterial#anisotropyRotation}. * * @type {number} * @ignore * @deprecated Use {@link StandardMaterial#anisotropyIntensity} and * {@link StandardMaterial#anisotropyRotation} instead. */ set anisotropy(value: number); /** * Gets the anisotropy as a signed intensity. * * @type {number} * @ignore * @deprecated Use {@link StandardMaterial#anisotropyIntensity} and * {@link StandardMaterial#anisotropyRotation} instead. */ get anisotropy(): number; } /** * Lighting parameters, allow configuration of the global lighting parameters. For details see * [Clustered Lighting](https://developer.playcanvas.com/user-manual/graphics/lighting/clustered-lighting/). * * @category Graphics */ declare class LightingParams { /** * Creates a new LightingParams object. * * @ignore */ constructor(supportsAreaLights: any, maxTextureSize: any, dirtyLightsFnc: any); /** @private */ private _areaLightsEnabled; /** @private */ private _cells; /** @private */ private _maxLightsPerCell; /** @private */ private _maxLights; /** @private */ private _shadowsEnabled; /** @private */ private _shadowType; /** @private */ private _shadowAtlasResolution; /** @private */ private _cookiesEnabled; /** @private */ private _cookieAtlasResolution; /** * Layer ID of a layer to contain the debug rendering of clustered lighting. Defaults to * undefined, which disables the debug rendering. Debug rendering is only included in the debug * version of the engine. * * @type {number} */ debugLayer: number; /** * Atlas textures split description, which applies to both the shadow and cookie texture atlas. * Defaults to null, which enables to automatic split mode. For details see [Configuring Atlas * Split](https://developer.playcanvas.com/user-manual/graphics/lighting/clustered-lighting/#configuring-atlas). * * @type {number[]|null} */ atlasSplit: number[] | null; _supportsAreaLights: any; _maxTextureSize: any; _dirtyLightsFnc: any; applySettings(render: any): void; /** * Sets whether clustered lighting supports shadow casting. Defaults to true. * * @type {boolean} */ set shadowsEnabled(value: boolean); /** * Gets whether clustered lighting supports shadow casting. * * @type {boolean} */ get shadowsEnabled(): boolean; /** * Sets whether clustered lighting supports cookie textures. Defaults to false. * * @type {boolean} */ set cookiesEnabled(value: boolean); /** * Gets whether clustered lighting supports cookie textures. * * @type {boolean} */ get cookiesEnabled(): boolean; /** * Sets whether clustered lighting supports area lights. Defaults to false. * * @type {boolean} */ set areaLightsEnabled(value: boolean); /** * Gets whether clustered lighting supports area lights. * * @type {boolean} */ get areaLightsEnabled(): boolean; /** * Sets the resolution of the atlas texture storing all non-directional shadow textures. * Defaults to 2048. * * @type {number} */ set shadowAtlasResolution(value: number); /** * Gets the resolution of the atlas texture storing all non-directional shadow textures. * * @type {number} */ get shadowAtlasResolution(): number; /** * Sets the resolution of the atlas texture storing all non-directional cookie textures. * Defaults to 2048. * * @type {number} */ set cookieAtlasResolution(value: number); /** * Gets the resolution of the atlas texture storing all non-directional cookie textures. * * @type {number} */ get cookieAtlasResolution(): number; /** * Sets the maximum number of lights a cell can store. Defaults to 255. * * @type {number} */ set maxLightsPerCell(value: number); /** * Gets the maximum number of lights a cell can store. * * @type {number} */ get maxLightsPerCell(): number; /** * Sets the maximum number of lights the clustered lighting can use in a single frame. Lights * over this limit are ignored, and a warning is reported. * * Values up to 255 store the light index in the light grid using 8 bits, larger values use 16 * bits and so double the size of the texture the grid is stored in. Defaults to 255. * * @type {number} */ set maxLights(value: number); /** * Gets the maximum number of lights the clustered lighting can use in a single frame. * * @type {number} */ get maxLights(): number; /** * Sets the type of shadow filtering used by all shadows. Can be: * * - {@link SHADOW_PCF1_32F} * - {@link SHADOW_PCF3_32F} * - {@link SHADOW_PCF5_32F} * - {@link SHADOW_PCF1_16F} * - {@link SHADOW_PCF3_16F} * - {@link SHADOW_PCF5_16F} * * Defaults to {@link SHADOW_PCF3_32F} * * @type {number} */ set shadowType(value: number); /** * Gets the type of shadow filtering used by all shadows. * * @type {number} */ get shadowType(): number; /** * Sets the number of cells along each world space axis the space containing lights is * subdivided into. Defaults to `[10, 3, 10]`. * * @type {Vec3} */ set cells(value: Vec3); /** * Gets the number of cells along each world space axis the space containing lights is * subdivided into. * * @type {Vec3} */ get cells(): Vec3; } /** * @import { GraphNode } from '../graph-node.js' * @import { GraphicsDevice } from '../../platform/graphics/graphics-device.js' * @import { Scene } from '../scene.js' * @import { Texture } from '../../platform/graphics/texture.js' */ /** * A visual representation of the sky. * * @ignore */ declare class SkyMesh { /** * @param {GraphicsDevice} device - The graphics device. * @param {Scene} scene - The scene owning the sky. * @param {GraphNode} node - The graph node of the sky mesh instance. * @param {Texture} texture - The texture of the sky. * @param {string} type - The type of the sky. One of the SKYTYPE_* constants. */ constructor(device: GraphicsDevice, scene: Scene, node: GraphNode, texture: Texture, type: string); /** * Mesh instance representing the visuals of the sky. * * @type {MeshInstance|null} */ meshInstance: MeshInstance | null; /** @private */ private _depthWrite; skyLayer: Layer; destroy(): void; set depthWrite(value: boolean); get depthWrite(): boolean; } /** * @import { Scene } from '../scene.js' */ /** * Implementation of the sky. * * @category Graphics */ declare class Sky { /** * Constructs a new sky. * * @param {Scene} scene - The scene owning the sky. * @ignore */ constructor(scene: Scene); /** * The type of the sky. One of the SKYTYPE_* constants. * * @type {string} * @private */ private _type; /** * The center of the sky. * * @private */ private _center; /** * The sky mesh of the scene. * * @type {SkyMesh|null} * @ignore */ skyMesh: SkyMesh | null; /** @private */ private _depthWrite; /** @private */ private _fisheye; /** * Lazily created on first non-zero fisheye set. * * @type {FisheyeProjection|null} * @private */ private _fisheyeProj; /** * A graph node with a transform used to render the sky mesh. Adjust the position, rotation and * scale of this node to orient the sky mesh. Ignored for {@link SKYTYPE_INFINITE}. * * @type {GraphNode} * @readonly */ readonly node: GraphNode; device: GraphicsDevice; scene: Scene; /** * Sets the center of the sky. Ignored for {@link SKYTYPE_INFINITE}. Typically only the * y-coordinate is used, representing the tripod height. Defaults to (0, 1, 0). * * @type {Vec3} */ set center(value: Vec3); /** * Gets the center of the sky. * * @type {Vec3} */ get center(): Vec3; centerArray: Float32Array; projectedSkydomeCenterId: ScopeId; _preRenderEvt: EventHandle; destroy(): void; applySettings(render: any): void; /** * Sets the type of the sky. Can be: * * - {@link SKYTYPE_INFINITE} * - {@link SKYTYPE_BOX} * - {@link SKYTYPE_DOME} * * Defaults to {@link SKYTYPE_INFINITE}. * * @type {string} */ set type(value: string); /** * Gets the type of the sky. * * @type {string} */ get type(): string; /** * Sets whether depth writing is enabled for the sky. Defaults to false. * * Writing a depth value for the skydome is supported when its type is not * {@link SKYTYPE_INFINITE}. When enabled, the depth is written to the scene depth texture during * the scene pass or a depth prepass, allowing subsequent passes to apply depth-based effects, * such as Depth of Field. * * Note: When a depth prepass is used, the Sky Layer must be ordered before * the Depth layer, which is the final layer used in the prepass. * * @type {boolean} */ set depthWrite(value: boolean); /** * Gets whether depth writing is enabled for the sky. * * @type {boolean} */ get depthWrite(): boolean; /** * Sets the fisheye projection strength for the sky. The value is in the range [0, 1]: * * - 0: Standard rectilinear (perspective) projection. * - (0, 1]: Increasing barrel distortion, producing a wider field of view. * * Only supported with {@link SKYTYPE_INFINITE}. Has no effect on dome or box sky types, * and has no effect with orthographic cameras. Defaults to 0. * * @type {number} */ set fisheye(value: number); /** * Gets the fisheye projection strength for the sky. * * @type {number} */ get fisheye(): number; updateSkyMesh(): void; resetSkyMesh(): void; update(): void; /** * @param {boolean} enabled - Whether to enable the SKY_FISHEYE define. * @private */ private _setFisheyeDefine; /** * Per-camera prerender callback that updates fisheye uniforms for the active camera. * * @param {import('../../framework/components/camera/component.js').CameraComponent} cameraComponent - The camera about to render. * @private */ private _onPreRender; } /** * @import { Color } from '../../core/math/color.js' */ /** * A cursor for writing line vertices straight into the storage of an immediate line batch, * avoiding the intermediate array that {@link Immediate#drawLineArrays} style submission needs. * * Obtained from {@link Immediate#allocateLines}, which hands out a single reused instance. The * returned cursor is therefore only valid until the next allocation: use it inside the function * that writes the data and never keep hold of it. * * @ignore */ declare class LineWriter { /** * Packed xyz positions of the batch being written to. * * @type {Float32Array|null} * @private */ private _positions; /** * Packed rgba colors of the batch being written to. * * @type {Float32Array|null} * @private */ private _colors; /** * Index of the next vertex to write. * * @type {number} * @private */ private _cursor; /** * One past the last vertex of the allocated region. * * @type {number} * @private */ private _end; /** @private */ private _r; /** @private */ private _g; /** @private */ private _b; /** @private */ private _a; /** * Points the cursor at a freshly allocated region. * * @param {Float32Array} positions - The batch positions. * @param {Float32Array} colors - The batch colors. * @param {number} first - The first vertex of the region. * @param {number} count - The number of vertices in the region. * @param {Color} color - The color used by {@link LineWriter#segment}. * @ignore */ reset(positions: Float32Array, colors: Float32Array, first: number, count: number, color: Color): void; /** * Sets the color used by {@link LineWriter#segment}. Can be called between segments. A method * rather than an accessor, as the components are unpacked here so they are not read per * vertex, and there is nothing meaningful to read back. * * @param {Color} color - The color to use. */ setColor(color: Color): void; /** * Whether the whole allocated region has been written. Used to check that a caller filled * everything it asked for, since the space is accounted for up front. * * @type {boolean} * @ignore */ get filled(): boolean; /** * The packed xyz storage being written to. Exposed for callers generating enough vertices * that the per-segment call overhead of {@link LineWriter#segment} matters; read it once, * write the region, then advance {@link LineWriter#cursor}. * * @type {Float32Array} * @ignore */ get positions(): Float32Array; /** * The packed rgba storage being written to, one color per position. * * @type {Float32Array} * @ignore */ get colors(): Float32Array; /** * The index of the next vertex to write. A caller writing the storage directly must leave * this pointing past everything it wrote. * * @type {number} * @ignore */ set cursor(value: number); get cursor(): number; /** * One past the last vertex of the allocated region. * * @type {number} * @ignore */ get end(): number; /** * Writes one line segment, both ends in the writer's current color. * * @param {number} x0 - The start x coordinate. * @param {number} y0 - The start y coordinate. * @param {number} z0 - The start z coordinate. * @param {number} x1 - The end x coordinate. * @param {number} y1 - The end y coordinate. * @param {number} z1 - The end z coordinate. */ segment(x0: number, y0: number, z0: number, x1: number, y1: number, z1: number): void; /** * Writes one vertex with an explicit color. Two consecutive vertices form a segment. * * @param {number} x - The x coordinate. * @param {number} y - The y coordinate. * @param {number} z - The z coordinate. * @param {number} r - The red component. * @param {number} g - The green component. * @param {number} b - The blue component. * @param {number} a - The alpha component. */ vertex(x: number, y: number, z: number, r: number, g: number, b: number, a: number): void; } declare class Immediate { constructor(device: any); device: any; cubeLocalPos: any; cubeWorldPos: any; batchesMap: Map; allBatches: Set; lineWriter: LineWriter; _materialDepth: ShaderMaterial; _materialNoDepth: ShaderMaterial; createMaterial(depthTest: any): ShaderMaterial; get materialDepth(): ShaderMaterial; get materialNoDepth(): ShaderMaterial; getBatch(layer: any, depthTest: any): any; /** * Allocates space for exactly `vertexCount` line vertices and returns a cursor positioned at * the start of it, letting a caller generate lines straight into the batch instead of building * an array to be copied in. * * The space is accounted for immediately, so the caller must fill all of it. The cursor is a * single reused instance and is only valid until the next allocation - use it inside the * function that writes the data, and do not keep hold of it. For the same reason an allocation * must not straddle rendering, as the batch may be submitted while it is still being written. * * @param {number} vertexCount - The number of vertices to allocate. Two vertices per segment. * @param {import('../../core/math/color.js').Color} color - The color used by * {@link LineWriter#segment}. * @param {boolean} depthTest - Whether the lines are depth tested. * @param {import('../layer.js').Layer} layer - The layer to render the lines into. * @returns {LineWriter} The cursor to write the vertices with. * @ignore */ allocateLines(vertexCount: number, color: Color, depthTest: boolean, layer: Layer): LineWriter; drawWireAlignedBox(min: any, max: any, color: any, depthTest: any, layer: any, mat: any): void; drawWireSphere(center: any, radius: any, color: any, numSegments: any, depthTest: any, layer: any): void; onPreRenderLayer(layer: any, visibleList: any, transparent: any): void; onPostRender(): void; } /** * @import { Layer } from '../layer.js' * @import { RenderTarget } from '../../platform/graphics/render-target.js' */ /** * Class representing an entry in the final order of rendering of cameras and layers in the engine * this is populated at runtime based on LayerComposition * * @ignore */ declare class RenderAction { camera: any; /** @type {Layer|null} */ layer: Layer | null; transparent: boolean; /** * Render target this render action renders to. * * @type {RenderTarget|null} */ renderTarget: RenderTarget | null; clearColor: boolean; clearDepth: boolean; clearStencil: boolean; triggerPostprocess: boolean; firstCameraUse: boolean; lastCameraUse: boolean; useCameraPasses: boolean; setupClears(camera: any, layer: any): void; } /** * @import { CameraComponent } from '../../framework/components/camera/component.js' * @import { Layer } from '../layer.js' * @import { Camera } from '../camera.js' */ /** * Layer Composition is a collection of {@link Layer} that is fed to {@link Scene#layers} to define * rendering order. * * Each layer is rendered as two parts, its opaque mesh instances and its transparent ones, and * {@link layerList} holds the sequence of parts in the order they are drawn. {@link push} and * {@link insert} add both parts of a layer together, while {@link pushOpaque}, * {@link pushTransparent}, {@link insertOpaque} and {@link insertTransparent} place one part at a * time, which is how the default composition places the depth and skybox layers between the world's * opaque and transparent parts. Look layers up with {@link getLayerById} and * {@link getLayerByName}, find where a part sits with {@link getOpaqueIndex} and * {@link getTransparentIndex}, and take a layer out with {@link remove}. The composition fires * `add` and `remove` as layers come and go. * * The composition the application creates ends with the UI layer, so a pushed layer renders after * the UI and outside the range a camera's post-processing applies to. To render inside that range, * insert at an index taken from {@link getOpaqueIndex} or {@link getTransparentIndex}. * * @example * // Draw decals right after the world's opaque objects and before its transparent ones * const layers = app.scene.layers; * const world = layers.getLayerById(LAYERID_WORLD); * const decals = new Layer({ name: 'Decals' }); * layers.insertOpaque(decals, layers.getOpaqueIndex(world) + 1); * @category Graphics */ declare class LayerComposition extends EventHandler { /** * Create a new layer composition. * * @param {string} [name] - Optional non-unique name of the layer composition. Defaults to * "Untitled" if not specified. */ constructor(name?: string); /** * A read-only array of {@link Layer} sorted in the order they will be rendered. * * @type {Layer[]} */ layerList: Layer[]; /** * A mapping of {@link Layer#id} to {@link Layer}. * * @type {Map} * @ignore */ layerIdMap: Map; /** * A mapping of {@link Layer#name} to {@link Layer}. * * @type {Map} * @ignore */ layerNameMap: Map; /** * A mapping of {@link Layer} to its opaque index in {@link layerList}. * * @type {Map} * @ignore */ layerOpaqueIndexMap: Map; /** * A mapping of {@link Layer} to its transparent index in {@link layerList}. * * @type {Map} * @ignore */ layerTransparentIndexMap: Map; /** * A read-only array of boolean values, matching {@link layerList}. True means only * semi-transparent objects are rendered, and false means opaque. * * @type {boolean[]} * @ignore */ subLayerList: boolean[]; /** * A read-only array of boolean values, matching {@link layerList}. True means the * layer is rendered, false means it's skipped. * * @type {boolean[]} */ subLayerEnabled: boolean[]; /** * An array of {@link CameraComponent}s. * * @type {CameraComponent[]} * @ignore */ cameras: CameraComponent[]; /** * A set of {@link Camera}s. * * @type {Set} * @ignore */ camerasSet: Set; /** * The actual rendering sequence, generated based on layers and cameras * * @type {RenderAction[]} * @ignore */ _renderActions: RenderAction[]; /** * True if the composition needs to be updated before rendering. * * @ignore */ _dirty: boolean; name: string; _opaqueOrder: {}; _transparentOrder: {}; markDirty(): void; _update(): void; getNextRenderAction(renderActionIndex: any): RenderAction; addDummyRenderAction(renderActionIndex: any, camera: any): void; addRenderAction(renderActionIndex: any, layer: any, isTransparent: any, camera: any, cameraFirstRenderAction: any, postProcessMarked: any): RenderAction; propagateRenderTarget(startIndex: any, fromCamera: any): void; _logRenderActions(): void; _isLayerAdded(layer: any): boolean; _isSublayerAdded(layer: any, transparent: any): boolean; /** * Adds a layer (both opaque and semi-transparent parts) to the end of the {@link layerList}. * * The default composition ends with the UI layer, so a layer pushed here renders after the UI * and after the last layer a camera's post-processing applies to. To place a layer inside the * post-processed range instead, use {@link LayerComposition#insert} with an index from * {@link LayerComposition#getOpaqueIndex}. * * @param {Layer} layer - A {@link Layer} to add. */ push(layer: Layer): void; /** * Inserts a layer (both opaque and semi-transparent parts) at the chosen index in the * {@link layerList}. * * @param {Layer} layer - A {@link Layer} to add. * @param {number} index - Insertion position. */ insert(layer: Layer, index: number): void; /** * Removes a layer (both opaque and semi-transparent parts) from {@link layerList}. * * @param {Layer} layer - A {@link Layer} to remove. */ remove(layer: Layer): void; /** * Adds part of the layer with opaque (non semi-transparent) objects to the end of the * {@link layerList}. * * @param {Layer} layer - A {@link Layer} to add. */ pushOpaque(layer: Layer): void; /** * Inserts an opaque part of the layer (non semi-transparent mesh instances) at the chosen * index in the {@link layerList}. * * @param {Layer} layer - A {@link Layer} to add. * @param {number} index - Insertion position. */ insertOpaque(layer: Layer, index: number): void; /** * Removes an opaque part of the layer (non semi-transparent mesh instances) from * {@link layerList}. * * @param {Layer} layer - A {@link Layer} to remove. */ removeOpaque(layer: Layer): void; /** * Adds part of the layer with semi-transparent objects to the end of the {@link layerList}. * * @param {Layer} layer - A {@link Layer} to add. */ pushTransparent(layer: Layer): void; /** * Inserts a semi-transparent part of the layer at the chosen index in the {@link layerList}. * * @param {Layer} layer - A {@link Layer} to add. * @param {number} index - Insertion position. */ insertTransparent(layer: Layer, index: number): void; /** * Removes a transparent part of the layer from {@link layerList}. * * @param {Layer} layer - A {@link Layer} to remove. */ removeTransparent(layer: Layer): void; /** * Gets index of the opaque part of the supplied layer in the {@link layerList}. * * @param {Layer} layer - A {@link Layer} to find index of. * @returns {number} The index of the opaque part of the specified layer, or -1 if it is not * part of the composition. */ getOpaqueIndex(layer: Layer): number; /** * Gets index of the semi-transparent part of the supplied layer in the {@link layerList}. * * @param {Layer} layer - A {@link Layer} to find index of. * @returns {number} The index of the semi-transparent part of the specified layer, or -1 if it * is not part of the composition. */ getTransparentIndex(layer: Layer): number; isEnabled(layer: any, transparent: any): boolean; /** * Returns true if the sub-layer at the given flat {@link LayerComposition#layerList} index is * enabled and rendered by the given camera. Combines the per-layer enabled flag, the per * sub-layer enabled flag and the layer's set of cameras. * * @param {number} index - The index of the sub-layer in {@link LayerComposition#layerList}. * @param {Camera} camera - The camera to test. * @returns {boolean} True if the sub-layer is enabled and the camera renders it. * @ignore */ isSubLayerRenderedByCamera(index: number, camera: Camera): boolean; /** * Update maps of layer IDs and names to match the layer list. * * @private */ private _updateLayerMaps; /** * Finds a layer inside this composition by its ID. Null is returned, if nothing is found. * * @param {number} id - An ID of the layer to find. * @returns {Layer|null} The layer corresponding to the specified ID. Returns null if layer is * not found. */ getLayerById(id: number): Layer | null; /** * Finds a layer inside this composition by its name. Null is returned, if nothing is found. * * @param {string} name - The name of the layer to find. * @returns {Layer|null} The layer corresponding to the specified name. Returns null if layer * is not found. */ getLayerByName(name: string): Layer | null; _updateOpaqueOrder(startIndex: any, endIndex: any): void; _updateTransparentOrder(startIndex: any, endIndex: any): void; _sortLayersDescending(layersA: any, layersB: any, order: any): number; /** * Used to determine which array of layers has any transparent sublayer that is on top of all * the transparent sublayers in the other array. * * @param {number[]} layersA - IDs of layers. * @param {number[]} layersB - IDs of layers. * @returns {number} Returns a negative number if any of the transparent sublayers in layersA * is on top of all the transparent sublayers in layersB, or a positive number if any of the * transparent sublayers in layersB is on top of all the transparent sublayers in layersA, or 0 * otherwise. * @private */ private sortTransparentLayers; /** * Used to determine which array of layers has any opaque sublayer that is on top of all the * opaque sublayers in the other array. * * @param {number[]} layersA - IDs of layers. * @param {number[]} layersB - IDs of layers. * @returns {number} Returns a negative number if any of the opaque sublayers in layersA is on * top of all the opaque sublayers in layersB, or a positive number if any of the opaque * sublayers in layersB is on top of all the opaque sublayers in layersA, or 0 otherwise. * @private */ private sortOpaqueLayers; } /** * @import { Entity } from '../framework/entity.js' * @import { GraphicsDevice } from '../platform/graphics/graphics-device.js' * @import { LayerComposition } from './composition/layer-composition.js' * @import { Layer } from './layer.js' * @import { Texture } from '../platform/graphics/texture.js' * @import { GSplatParams } from './gsplat-unified/gsplat-params.js' */ /** * A scene is a graphical representation of an environment. It manages the scene hierarchy, all * graphical objects, lights, and scene-wide properties. * * Each application has one at {@link AppBase#scene}. The scene owns the rendering setup that is * not tied to a single entity: the {@link layers} composition that decides render order; the * lighting environment through {@link ambientLight}, {@link skybox}, {@link envAtlas} and the * {@link sky} and {@link lighting} parameter objects; {@link exposure}, or {@link physicalUnits} * in its place, for overall brightness; the lightmapping settings; and the fog described below. * * The scene fires `prerender` and `postrender` for each camera that renders it, and `precull` * and `postcull` around visibility culling. Per-frame work that needs to know the camera belongs * in those handlers. * * Fog is scene-wide: {@link fog} is a read-only {@link FogParams} whose `type`, `color`, `start` * and `end` you set, and {@link CameraComponent#fog} can override it for a single camera. * * @example * // Light the scene from a prefiltered environment and brighten it slightly * app.scene.envAtlas = envAtlasAsset.resource; * app.scene.skybox = skyboxAsset.resource; * app.scene.exposure = 1.2; * @example * // Run code for each camera just before it renders the scene * app.scene.on('prerender', (camera) => { * // camera is the CameraComponent about to render * }); * @category Graphics */ declare class Scene extends EventHandler { /** * Fired when the layer composition is set. Use this event to add callbacks or advanced * properties to your layers. The handler is passed the old and the new * {@link LayerComposition}. * * @event * @example * app.scene.on('set:layers', (oldComp, newComp) => { * const list = newComp.layerList; * for (let i = 0; i < list.length; i++) { * const layer = list[i]; * switch (layer.name) { * case 'MyLayer': * layer.onEnable = myOnEnableFunction; * layer.onDisable = myOnDisableFunction; * break; * case 'MyOtherLayer': * layer.clearColorBuffer = true; * break; * } * } * }); */ static EVENT_SETLAYERS: string; /** * Fired when the skybox is set. The handler is passed the {@link Texture} that is the * previously used skybox cubemap texture. The new skybox cubemap texture is in the * {@link skybox} property. * * @event * @example * app.scene.on('set:skybox', (oldSkybox) => { * console.log(`Skybox changed from ${oldSkybox.name} to ${app.scene.skybox.name}`); * }); */ static EVENT_SETSKYBOX: string; /** * Fired before the camera renders the scene. The handler is passed the {@link CameraComponent} * that will render the scene. * * @event * @example * app.scene.on('prerender', (camera) => { * console.log(`Camera ${camera.entity.name} will render the scene`); * }); */ static EVENT_PRERENDER: string; /** * Fired when the camera renders the scene. The handler is passed the {@link CameraComponent} * that rendered the scene. * * @event * @example * app.scene.on('postrender', (camera) => { * console.log(`Camera ${camera.entity.name} rendered the scene`); * }); */ static EVENT_POSTRENDER: string; /** * Fired before the camera renders a layer. The handler is passed the {@link CameraComponent}, * the {@link Layer} that will be rendered, and a boolean parameter set to true if the layer is * transparent. This is called during rendering to a render target or a default framebuffer, and * additional rendering can be performed here, for example using {@link QuadRender#render}. * * @event * @example * app.scene.on('prerender:layer', (camera, layer, transparent) => { * console.log(`Camera ${camera.entity.name} will render the layer ${layer.name} (transparent: ${transparent})`); * }); */ static EVENT_PRERENDER_LAYER: string; /** * Fired when the camera renders a layer. The handler is passed the {@link CameraComponent}, * the {@link Layer} that will be rendered, and a boolean parameter set to true if the layer is * transparent. This is called during rendering to a render target or a default framebuffer, and * additional rendering can be performed here, for example using {@link QuadRender#render}. * * @event * @example * app.scene.on('postrender:layer', (camera, layer, transparent) => { * console.log(`Camera ${camera.entity.name} rendered the layer ${layer.name} (transparent: ${transparent})`); * }); */ static EVENT_POSTRENDER_LAYER: string; /** * Fired before mesh instance visibility culling is performed for a camera, just before the * camera's culling frustum is refreshed (so a handler may still adjust the camera). The handler * is passed the {@link CameraComponent} being culled, or null when the culling is internal (for * example when culling shadow casters for a light's shadow map). Note that light visibility * culling happens earlier in the frame and is not bracketed by this event. * * @event * @example * app.scene.on('precull', (camera) => { * if (camera) { * console.log(`Visibility culling will be performed for camera ${camera.entity.name}`); * } * }); */ static EVENT_PRECULL: string; /** * Fired after mesh instance visibility culling is performed for a camera; mesh instance * visibility (such as {@link MeshInstance#visibleThisFrame}) is up to date when this fires. The * handler is passed the {@link CameraComponent} that was culled, or null when the culling is * internal (for example when culling shadow casters for a light's shadow map). * * @event * @example * app.scene.on('postcull', (camera) => { * if (camera) { * console.log(`Visibility culling was performed for camera ${camera.entity.name}`); * } * }); */ static EVENT_POSTCULL: string; /** * Create a new Scene instance. * * @param {GraphicsDevice} graphicsDevice - The graphics device used to manage this scene. * @ignore */ constructor(graphicsDevice: GraphicsDevice); /** * If enabled, the ambient lighting will be baked into lightmaps. This will be either the * {@link skybox} if set up, otherwise {@link ambientLight}. Defaults to false. */ ambientBake: boolean; /** * If {@link ambientBake} is true, this specifies the brightness of ambient occlusion. Typical * range is -1 to 1. Defaults to 0, representing no change to brightness. */ ambientBakeOcclusionBrightness: number; /** * If {@link ambientBake} is true, this specifies the contrast of ambient occlusion. Typical * range is -1 to 1. Defaults to 0, representing no change to contrast. */ ambientBakeOcclusionContrast: number; /** * The color of the scene's ambient light, specified in sRGB color space. Defaults to black * (0, 0, 0). */ ambientLight: Color; /** * The luminosity of the scene's ambient light in lux (lm/m^2). Used if physicalUnits is true. Defaults to 0. */ ambientLuminance: number; /** * The exposure value tweaks the overall brightness of the scene. Ignored if physicalUnits is true. Defaults to 1. */ exposure: number; /** * The lightmap resolution multiplier. Defaults to 1. */ lightmapSizeMultiplier: number; /** * The maximum lightmap resolution. Defaults to 2048. */ lightmapMaxResolution: number; /** * The lightmap baking mode. Can be: * * - {@link BAKE_COLOR}: single color lightmap * - {@link BAKE_COLORDIR}: single color lightmap + dominant light direction (used for bump or * specular). Only lights with bakeDir=true will be used for generating the dominant light * direction. * * Defaults to {@link BAKE_COLORDIR}. * * @type {number} */ lightmapMode: number; /** * Enables bilateral filter on runtime baked color lightmaps, which removes the noise and * banding while preserving the edges. Defaults to false. Note that the filtering takes place * in the image space of the lightmap, and it does not filter across lightmap UV space seams, * often making the seams more visible. It's important to balance the strength of the filter * with number of samples used for lightmap baking to limit the visible artifacts. */ lightmapFilterEnabled: boolean; /** * Enables HDR lightmaps. This can result in smoother lightmaps especially when many samples * are used. Defaults to false. */ lightmapHDR: boolean; /** * The root entity of the scene, which is usually the only child to the {@link Application} * root entity. * * @type {Entity} */ root: Entity; /** * Use physically based units for cameras and lights. When used, the exposure value is ignored. */ physicalUnits: boolean; /** * Environment lighting atlas * * @type {Texture|null} * @private */ private _envAtlas; /** * The skybox cubemap as set by user (gets used when skyboxMip === 0) * * @type {Texture|null} * @private */ private _skyboxCubeMap; /** * The fog parameters. * * @private */ private _fogParams; device: GraphicsDevice; _gravity: Vec3; /** * @type {LayerComposition} * @private */ private _layers; /** * Array of 6 prefiltered lighting data cubemaps. * * @type {Texture[]} * @private */ private _prefilteredCubemaps; _internalEnvAtlas: any; _skyboxIntensity: number; _skyboxLuminance: number; _skyboxMip: number; _skyboxHighlightMultiplier: number; _skyboxRotationShaderInclude: boolean; _skyboxRotation: Quat; _skyboxRotationMat3: Mat3; _skyboxRotationMat4: Mat4; _ambientBakeNumSamples: number; _ambientBakeSpherePart: number; _lightmapFilterRange: number; _lightmapFilterSmoothness: number; _clusteredLightingEnabled: boolean; _lightingParams: LightingParams; updateShaders: boolean; /** * When true (default), loaded gsplat assets include the extra data needed for * {@link GSPLAT_RENDERER_RASTER_CPU_SORT} and non-unified gsplat rendering. Set to false * **before** you start loading a gsplat asset (e.g. before {@link AppBase#assets}.load) to * use less memory if you only need unified rendering with GPU sorting. Each load uses the * value in effect when that load begins. * * @type {boolean} * @ignore */ gsplatCentersEnabled: boolean; /** * @type {GSplatParams|null} * @ignore */ _gsplatParams: GSplatParams | null; _sky: Sky; _stats: { meshInstances: number; lights: number; dynamicLights: number; bakedLights: number; updateShadersTime: number; }; _shaderVersion: number; immediate: Immediate; /** * Gets the default layer used by the immediate drawing functions. * * @type {Layer} * @ignore */ get defaultDrawLayer(): Layer; /** * Sets the number of samples used to bake the ambient light into the lightmap. Note that * {@link ambientBake} must be true for this to have an effect. Defaults to 1. Maximum value * is 255. * * @type {number} */ set ambientBakeNumSamples(value: number); /** * Gets the number of samples used to bake the ambient light into the lightmap. * * @type {number} */ get ambientBakeNumSamples(): number; /** * Sets the part of the sphere which represents the source of ambient light. Note that * {@link ambientBake} must be true for this to have an effect. The valid range is 0..1, * representing a part of the sphere from top to the bottom. A value of 0.5 represents the * upper hemisphere. A value of 1 represents a full sphere. Defaults to 0.4, which is a smaller * upper hemisphere as this requires fewer samples to bake. * * @type {number} */ set ambientBakeSpherePart(value: number); /** * Gets the part of the sphere which represents the source of ambient light. * * @type {number} */ get ambientBakeSpherePart(): number; /** * Sets whether clustered lighting is enabled. Set to false before the first frame is rendered * to use non-clustered lighting. Defaults to true. * * @type {boolean} */ set clusteredLightingEnabled(value: boolean); /** * Gets whether clustered lighting is enabled. * * @type {boolean} */ get clusteredLightingEnabled(): boolean; /** * Sets the environment lighting atlas: prefiltered mip levels of the environment packed into a * single equirectangular texture. To build one from an equirectangular or cubemap source, use * `EnvLighting.generateLightingSource` followed by `EnvLighting.generateAtlas`; a raw HDR * texture assigned here will not light the scene correctly. * * @type {Texture|null} */ set envAtlas(value: Texture | null); /** * Gets the environment lighting atlas. * * @type {Texture|null} */ get envAtlas(): Texture | null; /** * Sets the {@link LayerComposition} that defines rendering order of this scene. * * @type {LayerComposition} */ set layers(layers: LayerComposition); /** * Gets the {@link LayerComposition} that defines rendering order of this scene. * * @type {LayerComposition} */ get layers(): LayerComposition; /** * Gets the {@link Sky} that defines sky properties. * * @type {Sky} */ get sky(): Sky; /** * Gets the {@link LightingParams} that define lighting parameters. * * @type {LightingParams} */ get lighting(): LightingParams; /** * Gets the GSplat parameters. * * @type {GSplatParams} */ get gsplat(): GSplatParams; /** * Gets the GSplat parameters, or null when GSplatComponentSystem is not included in the app. * * @returns {GSplatParams|null} The GSplat parameters. * @ignore */ getGsplatParams(): GSplatParams | null; /** * Sets the GSplat parameters owned by GSplatComponentSystem. * * @param {GSplatParams|null} value - The GSplat parameters. * @ignore */ setGsplatParams(value: GSplatParams | null): void; /** * Gets the {@link FogParams} that define fog parameters. * * @type {FogParams} */ get fog(): FogParams; /** * Sets the range parameter of the bilateral filter. It's used when * {@link lightmapFilterEnabled} is enabled. Larger value applies more widespread blur. This * needs to be a positive non-zero value. Defaults to 10. * * @type {number} */ set lightmapFilterRange(value: number); /** * Gets the range parameter of the bilateral filter. * * @type {number} */ get lightmapFilterRange(): number; /** * Sets the spatial parameter of the bilateral filter. It's used when * {@link lightmapFilterEnabled} is enabled. Larger value blurs less similar colors. This * needs to be a positive non-zero value. Defaults to 0.2. * * @type {number} */ set lightmapFilterSmoothness(value: number); /** * Gets the spatial parameter of the bilateral filter. * * @type {number} */ get lightmapFilterSmoothness(): number; /** * Sets the 6 prefiltered cubemaps acting as the source of image-based lighting. * * @type {Texture[]} */ set prefilteredCubemaps(value: Texture[]); /** * Gets the 6 prefiltered cubemaps acting as the source of image-based lighting. * * @type {Texture[]} */ get prefilteredCubemaps(): Texture[]; /** * Sets the base cubemap texture used as the scene's skybox when skyboxMip is 0. Defaults to null. * * For a sky that needs no cubemap asset, `playcanvas/scripts/esm/sky/procedural-sky.mjs` * renders an analytic daylight sky and keeps a directional light aligned with the sun so * direct lighting and shadows match. Related scene-dressing scripts ship alongside it: * `water.mjs`, `grid.mjs` and `shadow-catcher.mjs`. * * @type {Texture|null} */ set skybox(value: Texture | null); /** * Gets the base cubemap texture used as the scene's skybox when skyboxMip is 0. * * @type {Texture|null} */ get skybox(): Texture | null; /** * Sets the multiplier for skybox intensity. Defaults to 1. Unused if physical units are used. * * @type {number} */ set skyboxIntensity(value: number); /** * Gets the multiplier for skybox intensity. * * @type {number} */ get skyboxIntensity(): number; /** * Sets the luminance (in lm/m^2) of the skybox. Defaults to 0. Only used if physical units are used. * * @type {number} */ set skyboxLuminance(value: number); /** * Gets the luminance (in lm/m^2) of the skybox. * * @type {number} */ get skyboxLuminance(): number; /** * Sets the mip level of the skybox to be displayed. Only valid for prefiltered cubemap skyboxes. * Defaults to 0 (base level). * * @type {number} */ set skyboxMip(value: number); /** * Gets the mip level of the skybox to be displayed. * * @type {number} */ get skyboxMip(): number; /** * Sets the highlight multiplier for the skybox. The HDR skybox can represent brightness levels * up to a maximum of 64, with any values beyond this being clipped. This limitation prevents * the accurate representation of extremely bright sources, such as the Sun, which can affect * HDR bloom rendering by not producing enough bloom. The multiplier adjusts the brightness * after clipping, enhancing the bloom effect for bright sources. Defaults to 1. * * @type {number} */ set skyboxHighlightMultiplier(value: number); /** * Gets the highlight multiplied for the skybox. * * @type {number} */ get skyboxHighlightMultiplier(): number; /** * Sets the rotation of the skybox to be displayed. Defaults to {@link Quat.IDENTITY}. * * @type {Quat} */ set skyboxRotation(value: Readonly); /** * Gets the rotation of the skybox to be displayed. Use the setter to update skybox state. * * @type {Readonly} */ get skyboxRotation(): Readonly; destroy(): void; drawLine(start: any, end: any, color?: Color, depthTest?: boolean, layer?: Layer): void; drawLines(positions: any, colors: any, depthTest?: boolean, layer?: Layer): void; drawLineArrays(positions: any, colors: any, depthTest?: boolean, layer?: Layer): void; applySettings(settings: any): void; _getSkyboxTex(): Texture; _updateSkyMesh(): void; _resetSkyMesh(): void; /** * Sets the cubemap for the scene skybox. * * @param {Texture[]} [cubemaps] - An array of cubemaps corresponding to the skybox at * different mip levels. If undefined, scene will remove skybox. Cubemap array should be of * size 7, with the first element (index 0) corresponding to the base cubemap (mip level 0) * with original resolution. Each remaining element (index 1-6) corresponds to a fixed * prefiltered resolution (128x128, 64x64, 32x32, 16x16, 8x8, 4x4). */ setSkybox(cubemaps?: Texture[]): void; /** * Gets the lightmap pixel format. * * @type {number} */ get lightmapPixelFormat(): number; /** * @deprecated No replacement is available. * @ignore */ get defaultMaterial(): StandardMaterial; /** * @deprecated Use Scene#fog.color instead. * @ignore */ set fogColor(value: Color); /** * @deprecated Use Scene#fog.color instead. * @ignore */ get fogColor(): Color; /** * @deprecated Use Scene#fog.end instead. * @ignore */ set fogEnd(value: number); /** * @deprecated Use Scene#fog.end instead. * @ignore */ get fogEnd(): number; /** * @deprecated Use Scene#fog.start instead. * @ignore */ set fogStart(value: number); /** * @deprecated Use Scene#fog.start instead. * @ignore */ get fogStart(): number; /** * @deprecated Use Scene#fog.density instead. * @ignore */ set fogDensity(value: number); /** * @deprecated Use Scene#fog.density instead. * @ignore */ get fogDensity(): number; /** * @deprecated Use Scene#prefilteredCubemaps instead. * @ignore */ set skyboxPrefiltered128(value: Texture); /** * @deprecated Use Scene#prefilteredCubemaps instead. * @ignore */ get skyboxPrefiltered128(): Texture; /** * @deprecated Use Scene#prefilteredCubemaps instead. * @ignore */ set skyboxPrefiltered64(value: Texture); /** * @deprecated Use Scene#prefilteredCubemaps instead. * @ignore */ get skyboxPrefiltered64(): Texture; /** * @deprecated Use Scene#prefilteredCubemaps instead. * @ignore */ set skyboxPrefiltered32(value: Texture); /** * @deprecated Use Scene#prefilteredCubemaps instead. * @ignore */ get skyboxPrefiltered32(): Texture; /** * @deprecated Use Scene#prefilteredCubemaps instead. * @ignore */ set skyboxPrefiltered16(value: Texture); /** * @deprecated Use Scene#prefilteredCubemaps instead. * @ignore */ get skyboxPrefiltered16(): Texture; /** * @deprecated Use Scene#prefilteredCubemaps instead. * @ignore */ set skyboxPrefiltered8(value: Texture); /** * @deprecated Use Scene#prefilteredCubemaps instead. * @ignore */ get skyboxPrefiltered8(): Texture; /** * @deprecated Use Scene#prefilteredCubemaps instead. * @ignore */ set skyboxPrefiltered4(value: Texture); /** * @deprecated Use Scene#prefilteredCubemaps instead. * @ignore */ get skyboxPrefiltered4(): Texture; get models(): any; } /** * Performs the visibility culling for a {@link Renderer}: per-camera light visibility, * mesh-instance culling (request/execute) and shadow-caster culling. It holds the per-frame * culling state and operates on the renderer's shared state (lights, shadow renderers, light * atlas, stats) through a back-reference to the renderer. * * @ignore */ declare class Culler { /** * @param {Renderer} renderer - The renderer that owns this culler. */ constructor(renderer: Renderer); /** * A set of visible mesh instances which need further processing before being rendered, e.g. * skinning or morphing. Extracted during culling. * * @type {Set} */ processingMeshInstances: Set; /** * The distinct cameras with mesh-instance cull requests registered for the current frame, in * registration order. Populated by {@link Culler#requestMeshInstanceCull} and drained by * {@link Culler#executeMeshInstanceCull}. Reused across frames to avoid per-frame allocation. * * @type {Camera[]} * @private */ private _cullCameras; /** * Directional (light, camera) pairs requested by shadow passes this frame. References the * existing render data to avoid allocating requests. Kept through splat culling and one-shot * consumption, then reset before the next frame graph is built. * * @type {LightRenderData[]} * @private */ private _directionalShadowCullRequests; /** * Local lights requested by shadow passes this frame. Reuses face 0's render data so * separate cube-map passes share one cull without allocating request objects. * * @type {LightRenderData[]} * @private */ private _localShadowCullRequests; /** * A list of unique directional shadow casting lights for each enabled camera. This is generated * each frame during light culling. * * @type {Map>} */ cameraDirShadowLights: Map>; /** * A mapping of a directional light to a camera, for which the shadow is currently valid. This * is cleared each frame, and updated each time a directional light shadow is rendered for a * camera, and allows us to manually schedule shadow passes when a new camera needs a shadow. * * @type {Map} */ dirLightShadows: Map; /** @type {Renderer} */ renderer: Renderer; /** * @param {Camera} camera - The camera used for culling. * @param {MeshInstance[]} drawCalls - Draw calls to cull. * @param {CulledInstances} culledInstances - Stores culled instances. */ cullMeshInstances(camera: Camera, drawCalls: MeshInstance[], culledInstances: CulledInstances): void; /** * Culls a set of lights against a camera's frustum, marking the visible ones (and updating their * max screen size and physical-units flag). Directional lights are marked visible at the start * of the frame and are skipped here, so only local (omni / spot) lights are frustum tested. In * non-clustered lighting, a shadow-casting light with no shadow map allocated yet is also marked * visible so its shadow map gets allocated. * * @param {Camera} camera - The camera whose frustum the lights are culled against. * @param {Light[]} lights - The lights to cull (typically a layer's lights). */ cullLights(camera: Camera, lights: Light[]): void; /** * Cull shadow casters for the local and directional updates requested by scheduled shadow * passes. Visible mesh instances are collected into the light's render data, and directional * shadow cameras are fitted to their cascades. * * @param {LayerComposition} comp - The layer composition. */ cullShadowmaps(comp: LayerComposition): void; /** * After the frame graph is built and shadow casters are culled, account for shadow-map updates * and consume one-shot ({@link SHADOWUPDATE_THISFRAME}) requests for lights whose shadow * update is scheduled this frame, reverting them to {@link SHADOWUPDATE_NONE}. A light without * a scheduled update keeps its request until its shadow can be rendered. Runs after the frame * graph build and all mesh and splat shadow culling, so every consumer sees the pending update * mode before it is consumed. */ consumeOneShotShadows(): void; /** * Requests directional shadow culling for a scheduled shadow pass. Multiple passes using * the same light and camera share one cull; their render passes remain independently scheduled. * * @param {Light} light - The shadow-casting light. * @param {Camera} camera - The camera the shadow is fitted to. * @param {number} cascadeMask - Bit mask of cascades the pass will render. */ requestDirectionalShadowCull(light: Light, camera: Camera, cascadeMask: number): void; /** * Requests local shadow culling for a scheduled shadow pass. Multiple face passes using * the same light share one cull. * * @param {Light} light - The shadow-casting local light. */ requestLocalShadowCull(light: Light): void; /** * Collects the set of shadow-casting directional lights for each camera into * {@link Culler#cameraDirShadowLights}, and ensures each such light has a shadow map allocated. * This is independent of mesh culling and camera frusta (it uses only the composition's cameras * and the layers' directional lights), so it can run before the frame graph is built. The * actual shadow-caster culling is done separately. * * @param {LayerComposition} comp - The layer composition. */ collectDirectionalShadowLights(comp: LayerComposition): void; /** * Per-camera light visibility culling, light-atlas allocation and directional-shadow-light * collection. This is independent of mesh culling and the frame graph, so it runs before the * frame graph is built. The mesh and shadow-caster culling that depends on it is done later in * {@link Culler#cullComposition}. * * @param {LayerComposition} comp - The layer composition. */ updateLightVisibility(comp: LayerComposition): void; /** * Registers a request to cull a layer's mesh instances for a camera in the current frame. The * culling itself is performed later, in a single batch, by * {@link Culler#executeMeshInstanceCull}. Requests are de-duplicated per (camera, layer), so * requesting the same pair more than once (e.g. for its opaque and transparent sub-layers) is * harmless. * * This lets the frame graph drive culling - each pass requests the (camera, layer) pairs it * will actually render - instead of culling every camera/layer combination in the composition. * * @param {Camera} camera - The camera to cull for. * @param {Layer} layer - The layer whose mesh instances should be culled. */ requestMeshInstanceCull(camera: Camera, layer: Layer): void; /** * Performs all mesh-instance culling requested via {@link Culler#requestMeshInstanceCull} this * frame, then clears the request list. For each requested camera the precull event is fired * (before the frustum is refreshed, so a listener may still adjust the camera), the camera * frustum is updated, each requested layer is culled, and the postcull event is fired. * * The events are passed the owning camera component for a framework camera, or null for an * internal camera (shadow / reflection / picker), matching the documented precull/postcull * contract. */ executeMeshInstanceCull(): void; /** * Visibility culling of meshInstances and shadow casters. Light visibility, the light atlas and * the directional-shadow-light collection are done earlier in * {@link Culler#updateLightVisibility}. * * @param {LayerComposition} comp - The layer composition. */ cullComposition(comp: LayerComposition): void; } declare class LightsBuffer { constructor(device: any); areaLightsEnabled: boolean; /** * Texture storing properties of all lights, one row of pixels per light. * * @type {Texture|null} */ lightsTexture: Texture | null; /** @type {number} */ _maxLights: number; device: any; cookiesEnabled: boolean; shadowsEnabled: boolean; _lightsTextureId: any; /** * Sets the number of light slots the buffer can store, and allocates the storage for them. This * includes slot 0, which is reserved for the 'no light' index, and so the number of usable * lights is one less than this. * * @type {number} */ set maxLights(value: number); /** * Gets the number of light slots the buffer can store. * * @type {number} */ get maxLights(): number; invMaxColorValue: number; invMaxAttenuation: number; boundsMin: Vec3; boundsDelta: Vec3; lightsFloat: Float32Array; lightsUint: Uint32Array; destroy(): void; createTexture(device: any, width: any, height: any, format: any, name: any): Texture; setBounds(min: any, delta: any): void; uploadTextures(): void; updateUniforms(): void; getSpotDirection(direction: any, spot: any): void; getLightAreaSizes(light: any): Float32Array; addLightData(light: any, lightIndex: any): void; } declare class WorldClusters { constructor(device: any); /** @type {Texture} */ clusterTexture: Texture; device: any; name: string; reportCount: number; boundsMin: Vec3; boundsMax: Vec3; boundsDelta: Vec3; _cells: Vec3; _cellsLimit: Vec3; set cells(value: Vec3); get cells(): Vec3; set maxCellLightCount(count: any); get maxCellLightCount(): any; _usedLights: ClusterLight[]; lightsBuffer: LightsBuffer; /** * The lights stored in the cluster structure. The index of a light in this array matches its * index in the lights texture, and the index 0 is reserved for 'no light'. This is the array * used internally by the clustering and must not be modified. * * @type {ReadonlyArray} */ get usedLights(): ReadonlyArray; _maxCellLightCount: any; _cellsDirty: boolean; set maxLights(count: number); get maxLights(): number; destroy(): void; releaseClusterTexture(): void; registerUniforms(device: any): void; _numClusteredLightsId: any; _clusterMaxCellsId: any; _clusterWorldTextureId: any; _clusterBoundsMinId: any; _clusterBoundsMinData: Float32Array; _clusterBoundsDeltaId: any; _clusterBoundsDeltaData: Float32Array; _clusterCellsCountByBoundsSizeId: any; _clusterCellsCountByBoundsSizeData: Float32Array; _clusterCellsDotId: any; _clusterCellsDotData: Int32Array; _clusterCellsMaxId: any; _clusterCellsMaxData: Int32Array; _clusterTextureWidthId: any; updateParams(lightingParams: any): void; updateCells(): void; clusters: Uint16Array | Uint8ClampedArray; counts: Int32Array; uploadTextures(): void; updateUniforms(): void; evalLightCellMinMax(clusteredLight: any, min: any, max: any): void; collectLights(lights: any): void; evaluateBounds(): void; updateClusters(lightingParams: any): void; update(lights: any, lightingParams?: any): void; activate(): void; } declare class ClusterLight { light: any; min: Vec3; max: Vec3; } /** * @import { CameraComponent } from '../../framework/components/camera/component.js' * @import { Layer } from '../layer.js' * @import { RenderTarget } from '../../platform/graphics/render-target.js' * @import { WorldClusters } from '../lighting/world-clusters.js' */ /** * Represents a single layer rendered by a {@link RenderPassForward}: one layer (its opaque or * transparent sublayer) rendered with one camera to one render target. * * @ignore */ declare class LayerRenderStep { /** * @param {CameraComponent} cameraComponent - The camera component used to render the layer. * @param {Layer} layer - The layer to render. * @param {boolean} transparent - True to render the transparent sublayer, opaque otherwise. * @param {RenderTarget|null} renderTarget - The render target to render to. */ constructor(cameraComponent: CameraComponent, layer: Layer, transparent: boolean, renderTarget: RenderTarget | null); /** @type {CameraComponent|null} */ cameraComponent: CameraComponent | null; /** @type {Layer|null} */ layer: Layer | null; /** True if this uses the transparent sublayer, opaque otherwise. */ transparent: boolean; /** @type {RenderTarget|null} */ renderTarget: RenderTarget | null; /** * The world clusters to use for clustered lighting. Assigned later by the * {@link WorldClustersAllocator}, so it always starts as null. * * @type {WorldClusters|null} */ lightClusters: WorldClusters | null; clearColor: boolean; clearDepth: boolean; clearStencil: boolean; firstCameraUse: boolean; lastCameraUse: boolean; setupClears(cameraComponent: any, layer: any): void; } /** * @import { GraphicsDevice } from '../../platform/graphics/graphics-device.js' * @import { LayerRenderStep } from './layer-render-step.js' * @import { LightingParams } from '../lighting/lighting-params.js' */ /** * A class managing instances of world clusters used by the renderer for layers with * unique sets of clustered lights. * * @ignore */ declare class WorldClustersAllocator { /** * Create a new instance. * * @param {GraphicsDevice} graphicsDevice - The graphics device. */ constructor(graphicsDevice: GraphicsDevice); /** * Empty cluster with no lights. * * @type {WorldClusters|null} */ _empty: WorldClusters | null; /** * All allocated clusters * * @type {WorldClusters[]} */ _allocated: WorldClusters[]; /** * Layer render steps with all unique light clusters. The key is the hash of lights on a layer, * the value is a layer render step with unique light clusters. * * @type {Map} */ _clusters: Map; /** * Clusters allocated in a previous frame, available for reuse this frame. Owned by this * allocator (destroyed in {@link WorldClustersAllocator#destroy}) and only transiently non-empty * within a single {@link WorldClustersAllocator#upload} call. * * @type {WorldClusters[]} */ _recycled: WorldClusters[]; /** * Layer render steps that requested a cluster this frame, resolved together in * {@link WorldClustersAllocator#upload} (after culling). * * @type {LayerRenderStep[]} */ _requestedSteps: LayerRenderStep[]; device: GraphicsDevice; destroy(): void; get count(): number; get empty(): WorldClusters; /** * Creates the shared empty (no-lights) cluster if it does not exist yet, and returns it. This * uploads the cluster's texture, so it must run outside a render pass - the clustered update * pass calls it at construction. Reading {@link WorldClustersAllocator#empty} also creates it * lazily, as a fallback. * * @returns {WorldClusters} The empty cluster. */ createEmpty(): WorldClusters; /** * Discards the previous frame's cluster requests. Called once at the start of the frame (before * any {@link WorldClustersAllocator#request}), so a frame that builds but never uploads - e.g. * one interrupted before rendering - does not carry stale steps into the next. */ reset(): void; /** * Records that a layer render step will be rendered this frame and may need a light cluster. * Called during frame graph build (from a render pass's frameUpdate); eligibility, cluster * de-duplication and assignment are all resolved later in {@link WorldClustersAllocator#upload}, * so they observe the final layer state after any culling callbacks. * * @param {LayerRenderStep} step - The layer render step that may need a cluster. */ request(step: LayerRenderStep): void; /** * Resolves and uploads the clusters for the steps requested this frame. For each step whose * layer has clustered lights and meshes it assigns a cluster (steps whose layer shares the same * clustered-light set share one; others are left without a cluster and fall back to * {@link WorldClustersAllocator#empty} at render time), recycling the previous frame's clusters * and destroying any not reused, then uploads each unique cluster's light data. * * Runs from the clustered update pass - after cullComposition and its precull / postcull / * cull:end callbacks, and before the passes that use the clusters execute - so a callback that * adds or removes a layer's meshes or lights is reflected here. The whole assignment (including * the recycle pool) happens within this one synchronous call, so no partially-recycled cluster * is ever visible to {@link WorldClustersAllocator#destroy}. * * @param {LightingParams} lighting - The clustered lighting parameters. */ upload(lighting: LightingParams): void; } /** * The uniforms of one light slot - `light_color`, `light_direction` and so on, where N is * the slot. A slot is a position in the {@link LightList} of a pass, so an instance is not tied to * a light: whichever light holds the slot in a pass has its values written here, and whatever that * light needs is declared in the view uniform buffer format from here. Both read one set of names, * so the format and the values cannot disagree about what a slot's uniforms are called. The * lighting chunks are the third party to this - see lightDeclaration.js - and the shader * processors report a light uniform they do not find in the view format. * * Instances are made once per slot index by the renderer and live as long as it does, as they hold * nothing that depends on the light or the format. * * @ignore */ declare class LightSlotUniforms { /** * @param {GraphicsDevice} device - The graphics device. * @param {number} slot - The light slot, the N of `light_`. */ constructor(device: GraphicsDevice, slot: number); /** @type {number} */ slot: number; _paletteName: string; color: ScopeId; direction: ScopeId; position: ScopeId; radius: ScopeId; innerConeAngle: ScopeId; outerConeAngle: ScopeId; halfWidth: ScopeId; halfHeight: ScopeId; shadowMap: ScopeId; shadowMatrix: ScopeId; shadowParams: ScopeId; shadowIntensity: ScopeId; shadowSearchArea: ScopeId; cameraParams: ScopeId; softShadowParams: ScopeId; shadowMatrixPalette: ScopeId; shadowCascadeDistances: ScopeId; shadowCascadeCount: ScopeId; shadowCascadeBlend: ScopeId; shadowCascadeParams: ScopeId; cookie: ScopeId; cookieIntensity: ScopeId; cookieMatrix: ScopeId; cookieOffset: ScopeId; _direction: Float32Array; _position: Float32Array; _halfWidth: Float32Array; _halfHeight: Float32Array; /** * Appends the formats of the uniforms the given light needs at this slot - the ones the * lighting chunks declare for it, see lightDeclaration.js. Textures are not uniforms and stay * in the mesh bind group. The set may be a superset of what a particular shader declares - a * member no shader reads costs only its bytes - but it must be a pure function of * {@link Light#key}, as the key of the light list identifies the format built from it. * * @param {UniformFormat[]} uniforms - The formats to append to. * @param {Light} light - The light holding the slot. */ appendFormats(uniforms: UniformFormat[], light: Light): void; /** * Writes the values of the given light into the uniforms of this slot. * * @param {Light} light - The light holding the slot. * @param {Camera} camera - The camera, for the shadow data rendered for it. */ dispatch(light: Light, camera: Camera): void; /** * @param {Light} directional - The light. * @param {Camera} camera - The camera, for the shadow data rendered for it. * @private */ private _dispatchDirectional; /** * @param {Light} omni - The light. * @private */ private _dispatchOmni; /** * @param {Light} spot - The light. * @private */ private _dispatchSpot; /** * @param {Vec3} direction - The direction the light shines in. * @private */ private _setDirection; /** * @param {Vec3} position - The position of the light. * @private */ private _setPosition; /** * Sets the extents of a directional area light, placed at the far clip along the light. * * @param {Mat4} wtm - The world transform of the light. * @param {Vec3} dir - The direction the light shines in. * @param {Vec3} campos - The camera position. * @param {number} far - The camera far clip. * @private */ private _setLtcDirectional; /** * Sets the extents of an omni or spot area light. * * @param {Mat4} wtm - The world transform of the light. * @private */ private _setLtcPositional; /** * @param {Mat4} wtm - The world transform of the light. * @param {number} scale - The scale of the extents. * @private */ private _setLtcExtents; } /** * Blue noise based random numbers API. * * @ignore */ declare class BlueNoise { constructor(seed?: number); seed: number; _next(): void; value(): number; vec4(dest?: Vec4): Vec4; } /** * A general-purpose 1D block allocator backed by a doubly-linked list with segregated free-list * buckets. Manages a linear address space where contiguous blocks can be allocated and freed. * Supports incremental defragmentation and automatic growth. * * Free blocks are organized into power-of-2 size buckets for best-fit allocation, which reduces * fragmentation compared to a single first-fit free list. * * @ignore */ declare class BlockAllocator { /** * Create a new BlockAllocator. * * @param {number} [capacity] - Initial address space capacity. Defaults to 0. * @param {number} [growMultiplier] - Multiplicative growth factor for auto-grow in * {@link updateAllocation}. Defaults to 1.1 (10% extra). */ constructor(capacity?: number, growMultiplier?: number); /** * Head of the main list (all blocks, offset-ordered). * * @type {MemBlock|null} * @private */ private _headAll; /** * Tail of the main list. * * @type {MemBlock|null} * @private */ private _tailAll; /** * Segregated free-list bucket heads. Each entry is the head of a doubly-linked list of free * blocks whose size falls in that power-of-2 range. Bucket i covers sizes [2^i, 2^(i+1)). * The array grows dynamically as larger free blocks appear. * * @type {Array} * @private */ private _freeBucketHeads; /** * Pool of recycled MemBlock objects. * * @type {MemBlock[]} * @private */ private _pool; /** * Total address space. * * @private */ private _capacity; /** * Sum of all allocated block sizes. * * @private */ private _usedSize; /** * Sum of all free region sizes. * * @private */ private _freeSize; /** * Number of free regions. Maintained O(1) for the fragmentation metric. * * @private */ private _freeRegionCount; /** * Multiplicative growth factor used by {@link updateAllocation}. When growing, the new * capacity is at least `capacity * growMultiplier`. * * @type {number} * @private */ private _growMultiplier; /** * Total address space capacity. * * @type {number} */ get capacity(): number; /** * Total size of all allocated blocks. * * @type {number} */ get usedSize(): number; /** * Total size of all free regions. * * @type {number} */ get freeSize(): number; /** * Fragmentation ratio in the range [0, 1]. Returns 0 when all free space is one contiguous * block (ideal), and approaches 1 when free space is split into many pieces. Computed O(1) * from the internally maintained free region count. * * @type {number} */ get fragmentation(): number; /** * Compute the bucket index for a given block size. Uses floor(log2(size)) via the CLZ * intrinsic for integer math. * * @param {number} size - Block size (must be > 0). * @returns {number} Bucket index. * @private */ private _bucketFor; /** * Add a free block to the appropriate size bucket. Prepends to the bucket list for O(1) * insertion. Grows the bucket array if needed. * * @param {MemBlock} block - The free block to add. * @private */ private _addToBucket; /** * Remove a free block from its current size bucket. * * @param {MemBlock} block - The free block to remove. * @private */ private _removeFromBucket; /** * Move a free block to the correct bucket after its size changed (e.g. due to merging or * splitting). Only performs the remove+add if the bucket actually changed. * * @param {MemBlock} block - The free block whose size has changed. * @private */ private _rebucket; /** * Obtain a MemBlock from the pool or create a new one. * * @param {number} offset - The offset. * @param {number} size - The size. * @param {boolean} free - Whether the block is free. * @returns {MemBlock} The block. * @private */ private _obtain; /** * Return a MemBlock to the pool. * * @param {MemBlock} block - The block to release. * @private */ private _release; /** * Insert a block into the main list after a given node. * * @param {MemBlock} block - The block to insert. * @param {MemBlock|null} after - Insert after this node (null = insert at head). * @private */ private _insertAfterInMainList; /** * Remove a block from the main list. * * @param {MemBlock} block - The block to remove. * @private */ private _removeFromMainList; /** * Find the best-fit free block for the requested size using segregated buckets. Scans the * target bucket for the smallest block >= size (best-fit), then falls through to higher * buckets where any block is guaranteed large enough (first-fit). * * @param {number} size - Minimum size needed. * @returns {MemBlock|null} The best fitting free block, or null. * @private */ private _findFreeBlock; /** * Allocate a contiguous block of the given size. * * @param {number} size - The number of units to allocate. Must be > 0. * @returns {MemBlock|null} A MemBlock handle, or null if no space is available. */ allocate(size: number): MemBlock | null; /** * Free a previously allocated block. Adjacent free regions are merged automatically. * * @param {MemBlock} block - The block to free (must have been returned by {@link allocate}). */ free(block: MemBlock): void; /** * Grow the address space. Only increases capacity, never decreases. * * @param {number} newCapacity - The new capacity. Must be > current capacity. */ grow(newCapacity: number): void; /** * Defragment the allocator by moving allocated blocks to reduce fragmentation. * * When maxMoves is 0, performs a full compaction in a single O(n) pass: all allocated blocks * are packed contiguously from offset 0 and a single free block is placed at the end. * * When maxMoves > 0, performs incremental defragmentation in two phases: * - Phase 1 (up to maxMoves/2): relocates the last allocated block to the first fitting free * gap (maximizes tail free space). * - Phase 2 (up to maxMoves/2): slides allocated blocks left into adjacent free gaps * (cleans up interior fragmentation). * * @param {number} [maxMoves] - Maximum number of block moves. 0 = full compaction. Defaults * to 0. * @param {Set} [result] - Optional Set to receive moved blocks. Defaults to a new * Set. * @returns {Set} The set of MemBlocks that were moved. */ defrag(maxMoves?: number, result?: Set): Set; /** * Full compaction: single-pass, pack all allocated blocks from offset 0. * * @param {Set} result - Set to receive moved blocks. * @private */ private _defragFull; /** * Incremental defragmentation with two phases. * * @param {number} maxMoves - Maximum total moves. * @param {Set} result - Set to receive moved blocks. * @private */ private _defragIncremental; /** * Move an allocated block to a free gap. The block's offset is updated in-place so caller * handles stay valid. * * @param {MemBlock} block - The allocated block to move. * @param {MemBlock} gap - The free gap to move into (must be >= block size). * @private */ private _moveBlock; /** * Batch update: free a set of blocks and allocate new ones. Handles growth and compaction * internally when allocations cannot be satisfied. * * The `toAllocate` array is modified in-place: each numeric size entry is replaced with the * allocated {@link MemBlock}. * * @param {MemBlock[]} toFree - Blocks to release. * @param {Array} toAllocate - Sizes to allocate. Modified in-place: numbers * are replaced with MemBlock instances. * @returns {boolean} True if a full defrag was performed (all existing blocks have new * offsets and must be re-rendered), false if only incremental allocations were made. */ updateAllocation(toFree: MemBlock[], toAllocate: Array): boolean; } /** * A node in the {@link BlockAllocator}'s linked list, representing either an allocated block or a * free region. Callers receive MemBlock instances as handles from {@link BlockAllocator#allocate} * and must not modify any properties directly. * * @ignore */ declare class MemBlock { /** * Position in the address space. * * @private */ private _offset; /** * Size of this block. * * @private */ private _size; /** * True if this is a free region, false if allocated. * * @private */ private _free; /** * Previous node in the main (all-nodes) list. * * @type {MemBlock|null} * @private */ private _prev; /** * Next node in the main (all-nodes) list. * * @type {MemBlock|null} * @private */ private _next; /** * Previous node in the bucket free-list. * * @type {MemBlock|null} * @private */ private _prevFree; /** * Next node in the bucket free-list. * * @type {MemBlock|null} * @private */ private _nextFree; /** * Index of the size bucket this free block belongs to, or -1 if not in any bucket. * * @private */ private _bucket; /** * The offset of this block in the address space. * * @type {number} */ get offset(): number; /** * The size of this block. * * @type {number} */ get size(): number; } declare class GSplatWorldState { /** * @param {import('../../platform/graphics/graphics-device.js').GraphicsDevice} device - The graphics device. * @param {number} version - The version number. * @param {GSplatInfo[]} splats - The splats for this world state. * @param {BlockAllocator} allocator - Persistent block allocator (owned by GSplatManager). * @param {Map} allocationMap - Persistent allocId-to-MemBlock map (owned by GSplatManager). */ constructor(device: GraphicsDevice, version: number, splats: GSplatInfo[], allocator: BlockAllocator, allocationMap: Map); /** * The version of the world state. */ version: number; /** * Whether the sort parameters have been set on the sorter. */ sortParametersSet: boolean; /** * Whether the world state has been sorted before. */ sortedBefore: boolean; /** * An array of all splats managed by this world state. * * @type {GSplatInfo[]} */ splats: GSplatInfo[]; /** * The texture size of work buffer. */ textureSize: number; /** * Total number of active splats across all placements. */ totalActiveSplats: number; /** * Total number of intervals across all placements. Each placement contributes * either its interval count (intervals.length / 2) or 1 if it has no intervals. */ totalIntervals: number; /** * Deduplicated list of splat groups sharing the same parent placement. Multiple child * placements (e.g. octree file nodes) that reference the same parent share a single * set of bounding spheres and a single world transform, so they are grouped together. * Each entry contains a representative splat, the starting index into the bounds/transforms * textures (boundsBaseIndex), and the number of bounding sphere entries for the group. * * @type {Array<{splat: GSplatInfo, boundsBaseIndex: number, numBoundsEntries: number}>} */ boundsGroups: Array<{ splat: GSplatInfo; boundsBaseIndex: number; numBoundsEntries: number; }>; /** * Files to decrement when this state becomes active. * Array of tuples: [octree, fileIndex] * * @type {Array<[GSplatOctree, number]>} */ pendingReleases: Array<[GSplatOctree, number]>; /** * Splats that need to be rendered to the work buffer. Contains newly allocated or * re-allocated splats, or all splats when fullRebuild is true. * * @type {GSplatInfo[]} */ needsUpload: GSplatInfo[]; /** * AllocIds of splats in needsUpload, for fast membership checks during merge. * * @type {Set} */ needsUploadIds: Set; /** * Reverse map from allocId to the GSplatInfo that owns it, for efficient merge lookups * in cleanupOldWorldStates without scanning all splats. * * @type {Map} */ allocIdToSplat: Map; /** * True when the allocator grew or defragmented, meaning all block offsets may have * changed and every splat must be re-rendered to the work buffer. */ fullRebuild: boolean; destroy(): void; /** * Populates module-scope scratch arrays with allocations to free/create by diffing the * current splat set against the existing allocation map. * * @param {GSplatInfo[]} splats - Active splats for this state. * @param {Map} allocationMap - Persistent allocId-to-MemBlock map. * @private */ private computeAllocationDiff; /** * Process a single allocId/size pair: mark as seen, check for size changes, and * queue allocations or frees as needed. * * @param {number} allocId - The allocation identifier. * @param {number} size - Required size for this allocation. * @param {Map} allocationMap - Persistent allocId-to-MemBlock map. * @private */ private _diffAlloc; /** * Executes pending allocation changes via the BlockAllocator, runs incremental defrag, * derives the texture size, and releases scratch arrays. * * @param {import('../../platform/graphics/graphics-device.js').GraphicsDevice} device - The graphics device. * @param {BlockAllocator} allocator - The block allocator. * @param {Map} allocationMap - Persistent allocId-to-MemBlock map. * @returns {{ fullRebuild: boolean, changedAllocIds: Set|null }} Whether a full * rebuild was triggered and the set of changed allocation ids. * @private */ private applyAllocations; /** * Assigns work-buffer offsets to each splat from allocated blocks and builds the * needsUpload list for splats that require re-rendering. * * @param {GSplatInfo[]} splats - Active splats for this state. * @param {Map} allocationMap - Persistent allocId-to-MemBlock map. * @param {boolean} fullRebuild - Whether all splats must be re-rendered. * @param {Set|null} changedAllocIds - Allocation ids that were newly allocated or moved. * @private */ private assignSplatOffsets; /** * Builds boundsGroups by grouping splats that share a parentPlacementId, assigns * sequential boundsBaseIndex to each group, and propagates it back to splats. * * @param {GSplatInfo[]} splats - Active splats for this state. * @private */ private buildBoundsGroups; } /** * @import { GSplatPlacement } from './gsplat-placement.js' */ /** * Tracks placement state changes for a GSplatManager. * Detects changes in format version, modifier hash, numSplats, and centersVersion. * * @ignore */ declare class GSplatPlacementStateTracker { /** * WeakMap of placement to last seen state. * Using WeakMap allows automatic cleanup when placements are garbage collected. * * @type {WeakMap} * @private */ private _states; /** * Checks if any placements have changed state. Updates internal tracking. * * @param {Iterable} placements - Iterable of placements to check. * @returns {boolean} True if any placement's state changed. */ hasChanges(placements: Iterable): boolean; } /** * Chooses a LOD level per node from its distance, fitted to the splat budget. * * A node at world distance `d` renders the LOD band `1 + log_m(d / (s * b))`, floored and clamped * to its LOD range, where `b` and `m` are its placement's base distance and multiplier. `s` is one * scene-wide scale on every base distance: raising it pushes every band outward, so the splat total * grows with it. The allocator's whole job is to pick `s`: * - in target mode, the largest `s` whose total still fits the budget; * - in limit mode, the same but never above 1, so the configured distances are an upper bound on * detail and the budget only ever lowers it. * * Every node switches band at a scale known in closed form - it is finer than band `L` exactly when * `ln s > ln(d / b) - (L - 1) ln m`. Those switch points all lie on the one `ln s` axis, whatever * the per-placement base distances and multipliers, so the allocator drops each one into a * histogram over that axis with the splat change it causes, then runs a prefix sum from the * coarsest end until a bin would exceed the budget. That bin alone is then resolved the same way on * a finer histogram of its own, so the budget is filled to within a fraction of a percent of * distance rather than to within a bin - captures often hold many nodes at nearly the same distance, and a * single bin can carry a large share of the scene. A last pass assigns each node the band the * resulting cut gives it. There is no queue and no sort. * * Stopping at the first sub-bin that does not fit, rather than skipping it and continuing, keeps a * node's level from depending on unrelated nodes further along the axis, so small camera movements * do not flip levels on and off. Nodes sharing a sub-bin switch together. * * @ignore */ declare class GSplatBudgetBalancer { /** * Splat change per bin of the scale axis, and then per sub-bin of the bin being resolved. * * @type {Float64Array} * @private */ private _histogram; /** * Per global node index, the node's position on the scale axis in bin units, offset so that * its switch point leaving band `rangeMin + b` sits at `position - b * step`. Computed once, * read by every later pass. * * @type {Float64Array} * @private */ private _position; /** * Assigns a LOD level to every node of every instance, keeping the total splat count within * budget. Reads NodeInfo#worldDistanceSq, writes NodeInfo#optimalLod. * * @param {Map} octreeInstances - Map of * GSplatOctreeInstance objects. * @param {number} budget - Splat budget for octrees. Infinity for no budget. * @param {boolean} limit - True when the budget only limits the configured LOD distances, * false when detail is raised to fill it. */ balance(octreeInstances: Map, budget: number, limit: boolean): void; /** * Adds every switch point's splat change to the histogram: by bin when `bin` is negative, or * by sub-bin for the switch points inside `bin` only. * * @param {Map} octreeInstances - The octree instances. * @param {number} bin - The bin to split into sub-bins, or -1 for the whole axis. * @private */ private _accumulate; /** * Puts every node at one end of its LOD chain, for the cases where the budget decides * everything - either the whole scene fits at its finest, or not even the coarsest scene does. * * @param {Map} octreeInstances - The octree instances. * @param {boolean} finest - True for the finest band, false for the coarsest. * @private */ private _assignChainEnd; } /** * Owns the gsplat "world": the work buffer, versioned world states, allocation, octree/LOD * evaluation, streaming, budget enforcement, and the work-buffer bake. A single primary camera * (passed in to {@link GSplatWorld#update} / {@link GSplatWorld#bake}) drives LOD and color. * * The dependency is one-way: {@link GSplatManager} reads world data through getters and drives * mutation through explicit methods. The world never calls into the renderer, sorters, interval * compaction, or projector — instead it writes results into caller-owned result objects, and the * manager reacts (e.g. rebinding the renderer's data source on a work-buffer recreation). * * @ignore */ declare class GSplatWorld { /** * @param {GraphicsDevice} device - The graphics device. * @param {Scene} scene - The scene. * @param {GSplatParams} gsplat - The GSplat parameters. */ constructor(device: GraphicsDevice, scene: Scene, gsplat: GSplatParams); /** @type {GSplatParams} */ _gsplat: GSplatParams; /** @type {GraphicsDevice} */ _device: GraphicsDevice; /** @type {Scene} */ _scene: Scene; /** @type {GSplatWorkBuffer} */ _workBuffer: GSplatWorkBuffer; /** @type {Map} */ _worldStates: Map; /** @type {number} */ _lastWorldStateVersion: number; /** * The render-ready version: the version the work buffer is baked to and rendered from. Advanced * exclusively via {@link GSplatWorld#markSorted}. (Formerly `GSplatManager.sortedVersion`.) * * @type {number} */ _currentVersion: number; /** @type {boolean} */ _worldStateDirty: boolean; /** @type {number} */ _workBufferFormatVersion: number; /** @type {boolean} */ _workBufferRebuildRequired: boolean; /** @type {number} */ _bufferCopyUploaded: number; /** @type {number} */ _bufferCopyTotal: number; /** @type {GSplatPlacementStateTracker} */ _stateTracker: GSplatPlacementStateTracker; /** @type {number} */ _framesTillFullUpdate: number; /** * Latched request for a full LOD update, raised by the 10-frame cadence metronome and cleared * when fulfilled (when the back-pressure gate allows). Decouples "a full update is due" from * "we may run it this frame", so a tick deferred by back-pressure fires on the next available * frame rather than being lost until the next 10-frame mark. * * @type {boolean} */ _lodUpdateRequested: boolean; /** @type {Vec3} */ _lastLodCameraPos: Vec3; /** @type {Vec3} */ _lastLodCameraFwd: Vec3; /** @type {number} */ _lastLodCameraFov: number; /** @type {GSplatBudgetBalancer} */ _budgetBalancer: GSplatBudgetBalancer; /** @type {BlockAllocator} */ _allocator: BlockAllocator; /** @type {Map} */ _allocationMap: Map; /** @type {Vec3} */ _lastColorUpdateCameraPos: Vec3; /** * Whether the spherical harmonics colors of all splats were last evaluated for an orthographic * camera, or null before they were first evaluated. * * @type {boolean|null} */ _colorViewOrtho: boolean | null; /** * The camera forward the spherical harmonics colors of all splats were last evaluated with. An * orthographic camera evaluates every splat along it. * * @type {Vec3} */ _colorViewForward: Vec3; /** @type {GSplatPlacement[]} */ _layerPlacements: GSplatPlacement[]; /** @type {boolean} */ _layerPlacementsDirty: boolean; /** @type {boolean} */ _placementSetChanged: boolean; /** @type {Map} */ _octreeInstances: Map; /** @type {GSplatOctreeInstance[]} */ _octreeInstancesToDestroy: GSplatOctreeInstance[]; /** @type {boolean} */ _hasNewOctreeInstances: boolean; /** * Suppresses ready=true in frame:ready until a fullUpdate cycle runs. Only set when octree * instances exist and params change (dirty). * * @type {boolean} */ _awaitingLodUpdate: boolean; destroy(): void; /** @type {GSplatWorkBuffer} */ get workBuffer(): GSplatWorkBuffer; /** @type {number} */ get currentVersion(): number; /** @type {number} */ get lastWorldStateVersion(): number; /** @type {number} */ get bufferCopyUploaded(): number; /** @type {number} */ get bufferCopyTotal(): number; /** @type {boolean} */ get awaitingLodUpdate(): boolean; /** @type {boolean} */ get hasOctreeInstances(): boolean; /** * Total pending loads across all octree instances (including environment). * * @type {number} */ get pendingLoadCount(): number; /** * The render-ready world state, or undefined if not yet created. * * @type {GSplatWorldState|undefined} */ get currentState(): GSplatWorldState | undefined; /** * Looks up a world state by version. * * @param {number} version - The world state version. * @returns {GSplatWorldState|undefined} The world state, or undefined. */ getState(version: number): GSplatWorldState | undefined; /** * True when frustum culling can run for the given renderer (bounds data available). The renderer * type gate stays on the manager; this only reports bounds availability. * * @type {boolean} */ get hasBounds(): boolean; /** * Resets per-frame buffer-copy stats. Must run before any bake/rebuild of the frame (including * the CPU sorter's async onSorted path, which the manager applies before {@link GSplatWorld#update}). */ resetFrameStats(): void; /** * Marks the world state and/or work buffer as needing a rebuild. Called by the manager on * renderer-mode transitions (the manager must not poke the private flags directly). * * @param {object} [opts] - Options. * @param {boolean} [opts.worldState] - Force a world-state rebuild. * @param {boolean} [opts.workBuffer] - Force a full work-buffer rebuild. */ invalidate({ worldState, workBuffer }?: { worldState?: boolean; workBuffer?: boolean; }): void; /** * Resets the render-ready state's sort bookkeeping so the next sort triggers a full rebuild * (used when switching to the CPU-sort renderer). Returns the state's splats for the manager to * feed its CPU sorter, or null if no state exists. * * @returns {GSplatInfo[]|null} The current state's splats, or null. */ invalidateSortState(): GSplatInfo[] | null; /** * Detects work-buffer format changes and recreates / syncs the work buffer. Must run before the * CPU sorter's pending results are applied (so onSorted rebuilds into the current buffer). * * @param {{ bufferRecreated: boolean, sortNeeded: boolean }} result - Caller-owned result object. * @returns {{ bufferRecreated: boolean, sortNeeded: boolean }} The populated result. */ syncFormat(result: { bufferRecreated: boolean; sortNeeded: boolean; }): { bufferRecreated: boolean; sortNeeded: boolean; }; /** * Supply the placements to use. Updates octree instances and the non-octree placement list, * flagging dirtiness. Called infrequently (when the layer's placements change). * * @param {GSplatPlacement[]} placements - The placements to reconcile with. */ reconcile(placements: GSplatPlacement[]): void; /** * Per-frame LOD/streaming pass: evaluates LOD against the primary camera (subject to the * back-pressure gate), enforces budget, and creates a new world-state version when needed. * * @param {GraphNode} camera - The primary camera driving LOD/streaming. * @param {boolean} allowLodUpdate - Back-pressure gate (false when the CPU sorter is busy). * @param {boolean} requireCenters - Whether resources without a centers buffer must be skipped * (CPU sort path). * @param {{ newVersion: boolean, overdrawDirty: boolean, sortNeeded: boolean }} result * Caller-owned result object the manager reacts to. * @returns {{ newVersion: boolean, overdrawDirty: boolean, sortNeeded: boolean }} The populated result. */ update(camera: GraphNode, allowLodUpdate: boolean, requireCenters: boolean, result: { newVersion: boolean; overdrawDirty: boolean; sortNeeded: boolean; }): { newVersion: boolean; overdrawDirty: boolean; sortNeeded: boolean; }; /** * Creates a new world state version when placements/resources changed. Returns whether a new * version was created. Does NOT feed the CPU sorter (the manager does that on a new version). * * @param {boolean} requireCenters - Whether resources without centers must be skipped. * @returns {boolean} True if a new world-state version was created. * @private */ private _updateWorldState; /** * Advances the render-ready version to `version` (cleaning up older states) and, on the first * sort of that version, rebuilds the work buffer. The manager calls this from the GPU sort * paths and the CPU onSorted callback. Atomic: cleanup + version-advance happen together. * * @param {number} version - The version that has been sorted. * @param {number} count - The splat count for the work-buffer rebuild / renderer update. * @param {GraphNode} camera - The primary camera (for color bake). * @param {boolean} updateBounds - Whether to upload frustum-culling bounds (false for CPU sort). * @param {{ rebuilt: boolean, count: number, textureSize: number }} result - Caller-owned result. * @returns {{ rebuilt: boolean, count: number, textureSize: number }} The populated result. When * `rebuilt` is true the manager must call `renderer.update(count, textureSize)`. */ markSorted(version: number, count: number, camera: GraphNode, updateBounds: boolean, result: { rebuilt: boolean; count: number; textureSize: number; }): { rebuilt: boolean; count: number; textureSize: number; }; /** * Applies a completed CPU sort: advances the render-ready version (via markSorted) and uploads * the sorted order texture. The manager rebinds the renderer afterwards. * * @param {number} version - The sorted version. * @param {number} count - The sorted splat count. * @param {Uint32Array} orderData - The sorted order data. * @param {GraphNode} camera - The primary camera (for color bake on first sort). * @param {boolean} updateBounds - Whether to upload frustum-culling bounds (false for CPU sort). * @param {{ rebuilt: boolean, count: number, textureSize: number }} result - Caller-owned result. * @returns {{ rebuilt: boolean, count: number, textureSize: number }} The populated result. */ onSorted(version: number, count: number, orderData: Uint32Array, camera: GraphNode, updateBounds: boolean, result: { rebuilt: boolean; count: number; textureSize: number; }): { rebuilt: boolean; count: number; textureSize: number; }; /** * Materializes the work buffer for the given (render-ready) version: a full rebuild when one is * pending, otherwise an incremental update. Refreshes color tracking. Camera drives the SH color * bake. * * @param {number} version - The render-ready version to bake. * @param {GraphNode} camera - The primary camera (for color bake). * @param {boolean} updateBounds - Whether to upload frustum-culling bounds (false for CPU sort). * @param {{ rebuilt: boolean, count: number, textureSize: number, sortNeeded: boolean }} result * Caller-owned result. When `rebuilt` is true the manager must call `renderer.update(count, * textureSize)`, `renderer.setOrderData()` and `intervalCompaction.invalidateUpload()`. When * `sortNeeded` is true (a splat moved during the incremental update) the manager must re-sort. * @returns {{ rebuilt: boolean, count: number, textureSize: number, sortNeeded: boolean }} The populated result. */ bake(version: number, camera: GraphNode, updateBounds: boolean, result: { rebuilt: boolean; count: number; textureSize: number; sortNeeded: boolean; }): { rebuilt: boolean; count: number; textureSize: number; sortNeeded: boolean; }; /** * Rebuilds the work buffer for a world state: resizes if needed, renders changed (or all) splats, * syncs transforms, and applies pending file-release requests. Does NOT touch the renderer — the * caller updates the renderer's count/textureSize from {@link GSplatWorld#bake} / * {@link GSplatWorld#markSorted} results. * * @param {GSplatWorldState} worldState - The world state to rebuild for. * @param {number} count - The number of splats (unused here; surfaced via the result for the renderer). * @param {boolean} forceFullRebuild - Force rendering all splats (e.g. format change). * @param {GraphNode} camera - The primary camera (for color bake). * @param {boolean} updateBounds - Whether to upload bounds/transforms for frustum culling. False * for the CPU-sort renderer, whose frustum-culler storage buffers are not allocated. * @private */ private rebuildWorkBuffer; /** * Cleans up old world states between the last render-ready version and the new version. Merges * upload requirements from skipped states into the active state, then decrements ref counts and * destroys old states. Note: reads the current `_currentVersion` (not yet advanced to newVersion). * * @param {number} newVersion - The new version to clean up to. */ cleanupOldWorldStates(newVersion: number): void; /** * Applies incremental work buffer updates for splats that have changed. Detects transform changes * and color update thresholds, then batch renders updates. Reports whether any splat moved (the * manager uses this to set sortNeeded). * * @param {GSplatWorldState} state - The world state to update. * @param {GraphNode} camera - The primary camera (for color delta + bake). * @returns {boolean} True if any splat moved (requires re-sort). */ applyWorkBufferUpdates(state: GSplatWorldState, camera: GraphNode): boolean; /** * Tests if the camera has moved or rotated enough to require LOD update. * * @param {GraphNode} camera - The primary camera. * @returns {boolean} True if camera moved/rotated over thresholds, otherwise false. */ testCameraMovedForLod(camera: GraphNode): boolean; /** * Updates the camera tracking state for color accumulation calculations. * * @param {GraphNode} camera - The primary camera. */ updateColorCameraTracking(camera: GraphNode): void; /** * Records the camera view the spherical harmonics colors of all splats were just evaluated for. * * @param {GraphNode} camera - The primary camera. * @private */ private _recordColorView; /** * Determines the colorization mode for rendering based on debug flags. * * @returns {Array|undefined} Color array for debug visualization, or undefined for normal rendering. */ getDebugColors(): Array | undefined; /** * Calculates camera translation delta since last color update, and whether the colors of all * splats need to be re-evaluated. Updates and returns the shared _cameraDeltas object. * * @param {GraphNode} camera - The primary camera. * @returns {{ translationDelta: number, refreshAll: boolean }} Shared camera movement deltas object. */ calculateColorCameraDeltas(camera: GraphNode): { translationDelta: number; refreshAll: boolean; }; /** * Enforces the global splat budget across all octree instances. * * @param {number} budget - Splat budget from GSplatParams.splatBudget, Infinity for none. * @param {GraphNode} camera - The primary camera. * @private */ private _enforceBudget; /** * Computes the world-space union of all placement AABBs. Returns the shared bounding box, or * null if there are no placements. The manager applies it to the renderer's mesh instance. * * @returns {BoundingBox|null} The aggregate AABB, or null. */ computeAggregateAabb(): BoundingBox | null; /** * Accumulates a placement's transformed AABB into the running mesh-instance AABB. * * @param {GSplatPlacement} placement - The placement. * @param {boolean} initialized - Whether the running AABB has been initialized. * @returns {boolean} The updated initialized flag. * @private */ private _accumulatePlacementAabb; /** * Ticks octree cooldown timers once per frame per unique octree. The octrees are shared with * the worlds of other cameras and layers, and each octree ignores a repeated token, so this * does not depend on how many worlds use it. * * @param {number} token - Per-frame token, see GSplatDirector#_streamToken. */ tickCooldowns(token: number): void; /** * Forces LOD re-evaluation on all octree instances (e.g. after frame:ready listeners changed * params). */ markInstancesNeedLodUpdate(): void; /** * Prepares sort parameters data for the sorter worker. Reads world-state data; the manager owns * the sorter and posts the result. * * @param {GSplatWorldState} worldState - The world state containing all needed data. * @returns {object} Data for the sorter worker. */ prepareSortParameters(worldState: GSplatWorldState): object; } /** * Helper that caches derived fisheye projection values from a normalized slider value, camera FOV, * and projection matrix. Each consumer (renderer, culling, future skydome) creates its own instance * and calls {@link update} when it needs current values. The instance only mutates its own cached * fields, with no external side effects. * * Uses the generalized fisheye model g(θ) = k·tan(θ/k), where k controls the projection * characteristic: k=1 is rectilinear perspective, lower k increases barrel distortion. * * @ignore */ declare class FisheyeProjection { /** * Whether fisheye is active (t > 0). */ enabled: boolean; /** * The fisheye k parameter controlling projection curvature. */ k: number; /** * Precomputed 1/k to avoid per-splat division in shaders. */ invK: number; /** * Scale factor blending from edge-fit (1.0) to corner-fit (sqrt(2)) based on t. */ cornerScale: number; /** * Fisheye-adjusted horizontal projection scale for NDC conversion. */ projMat00: number; /** * Fisheye-adjusted vertical projection scale for NDC conversion. */ projMat11: number; /** * Maximum viewing angle before singularity, used for cone culling. */ maxTheta: number; /** @private */ private _lastT; /** @private */ private _lastFov; /** @private */ private _lastP00; /** @private */ private _lastP11; /** * Recomputes all derived fisheye values. Short-circuits if inputs haven't changed. * * @param {number} t - Normalized fisheye slider value in [0, 1]. 0 = rectilinear, 1 = max distortion. * @param {number} fov - Camera vertical FOV in degrees. * @param {import('../../core/math/mat4.js').Mat4} projMatrix - The camera's projection matrix. */ update(t: number, fov: number, projMatrix: Mat4): void; } /** * Per-call parameters for a renderer view (forward or pick), populated by the manager each frame * from the scene gsplat settings plus the view camera (and pick viewport). Reused per call to avoid * per-frame allocation; the renderer must not retain a reference to it. */ type GSplatRenderViewParams = object; /** * @import { StorageBuffer } from '../../platform/graphics/storage-buffer.js' * @import { ShaderMaterial } from '../materials/shader-material.js' * @import { Layer } from '../layer.js' * @import { GraphNode } from '../graph-node.js' * @import { GraphicsDevice } from '../../platform/graphics/graphics-device.js' * @import { GSplatWorkBuffer } from './gsplat-work-buffer.js' * @import { GSplatWorld } from './gsplat-world.js' * @import { GSplatWorldState } from './gsplat-world-state.js' * @import { GSplatVaryings } from './gsplat-varyings.js' * @import { MeshInstance } from '../mesh-instance.js' */ /** * Per-call parameters for a renderer view (forward or pick), populated by the manager each frame * from the scene gsplat settings plus the view camera (and pick viewport). Reused per call to avoid * per-frame allocation; the renderer must not retain a reference to it. * * @typedef {object} GSplatRenderViewParams * @ignore * @property {GraphNode} cameraNode - The camera node for this view. * @property {boolean} stochastic - Whether the forward view uses unsorted stochastic alpha. * @property {string} dither - The noise pattern stochastic coverage is dithered against. * @property {boolean} radialSorting - Whether radial (vs linear) depth sorting is used. * @property {number} alphaClip - Alpha threshold for shadow/pick/prepass rendering. * @property {number} alphaClipForward - Alpha floor for the forward pass. * @property {number} minPixelSize - Minimum projected splat size. * @property {number} minContribution - Minimum visual contribution threshold. * @property {number} foveationStrength - Foveation strength. * @property {number} foveationCenter - Foveation center. * @property {boolean} antiAlias - Whether antialiasing is enabled. * @property {number} fisheye - Fisheye projection strength. * @property {ShaderMaterial} material - The scene gsplat template material. * @property {GSplatVaryings} varyings - User varying streams (provides the cache `words` count). * @property {number} [width] - Pick viewport width in pixels (picking only). * @property {number} [height] - Pick viewport height in pixels (picking only). */ /** * Base class for splat renderers. Holds common state shared by all renderer * implementations (instanced-quad, hybrid GPU-sort, etc.). Derived classes * implement the actual rendering strategy. * * @ignore */ declare class GSplatRenderer { /** * @param {GraphicsDevice} device - The graphics device. * @param {GraphNode} node - The graph node. * @param {GraphNode} cameraNode - The camera node. * @param {Layer} layer - The layer to add mesh instances to. * @param {GSplatWorkBuffer} workBuffer - The work buffer containing splat data. */ constructor(device: GraphicsDevice, node: GraphNode, cameraNode: GraphNode, layer: Layer, workBuffer: GSplatWorkBuffer); /** @type {GraphicsDevice} */ device: GraphicsDevice; /** @type {GraphNode} */ node: GraphNode; /** @type {GraphNode} */ cameraNode: GraphNode; /** @type {Layer} */ layer: Layer; /** @type {GSplatWorkBuffer} */ workBuffer: GSplatWorkBuffer; /** @type {number|undefined} */ renderMode: number | undefined; /** * Cached work buffer format version for detecting extra stream changes. * * @protected */ protected _workBufferFormatVersion: number; /** * Fisheye projection helper shared by all renderer paths. * The manager calls update() during culling; renderers read the computed values * when binding uniforms. * * @type {FisheyeProjection} * @ignore */ fisheyeProj: FisheyeProjection; destroy(): void; /** * Resolves the effective fisheye strength for this renderer's camera. Fisheye is not supported * in XR by any renderer (it overrides the per-eye perspective projection), so it is forced off * while an XR session is active. Warns once when a non-zero value is suppressed. * * @param {number} fisheye - Requested fisheye strength (typically `scene.gsplat.fisheye`). * @returns {number} The fisheye strength to use (0 while in XR, otherwise `fisheye`). */ resolveFisheye(fisheye: number): number; /** * Sets the render mode for this renderer. * * @param {number} renderMode - Bitmask flags controlling render passes (GSPLAT_FORWARD, GSPLAT_SHADOW, or both). */ setRenderMode(renderMode: number): void; /** * Whether this renderer runs the GPU sort/projection/cull pipeline itself (true) rather than * relying on the manager's CPU worker sorter (false). Drives the manager's per-frame branching. * * @type {boolean} */ get usesGpuSort(): boolean; /** * Whether this renderer needs frustum-culling bounds uploaded to the work buffer (the GPU cull * path allocates them; the CPU path does not). * * @type {boolean} */ get requiresBounds(): boolean; /** * Whether this renderer relies on the manager-owned CPU worker sorter. * * @type {boolean} */ get requiresCpuSort(): boolean; /** * Returns the material used by this renderer, or null if not applicable. * * @type {ShaderMaterial|null} */ get material(): ShaderMaterial | null; /** * Sets the data source providing format and texture access. The base implementation updates * the workBuffer and notifies derived classes of the format change. Derived classes may * override this to react to the source change (e.g. re-pointing materials at the new * work-buffer textures). * * The source object must provide: * - `format` — a {@link GSplatFormat} describing the texture streams and shader read code. * - `getTexture(name)` — a function returning a {@link Texture} for a given stream name. * * @param {object} source - The data source (typically a {@link GSplatWorkBuffer}). */ setDataSource(source: object): void; /** * Called when the work buffer format has changed. Derived classes reconfigure * their rendering resources (materials, pipelines, bindings, etc.). */ onWorkBufferFormatChanged(): void; /** * Updates the renderer with the current splat count and texture size. * * @param {number} count - The number of visible splats. * @param {number} textureSize - The work buffer texture size. */ update(count: number, textureSize: number): void; /** * Configures the renderer to use GPU-sorted data for rendering. * * @param {number} drawSlot - The indirect draw slot index. * @param {StorageBuffer} sortedIds - Buffer containing sorted visible splat IDs. * @param {StorageBuffer} numSplatsBuffer - Buffer containing the visible splat count. * @param {number} textureSize - The work buffer texture size. */ setGpuSortedRendering(drawSlot: number, sortedIds: StorageBuffer, numSplatsBuffer: StorageBuffer, textureSize: number): void; /** * Switches the renderer to CPU-sorted rendering mode. */ setCpuSortedRendering(): void; /** * Binds the current order data (texture or storage buffer) for CPU-sorted rendering. */ setOrderData(): void; /** * Per-frame update for the renderer (material syncing, parameter updates). * * @param {object} params - The gsplat parameters. */ frameUpdate(params: object): void; /** * Updates the overdraw visualization mode. * * @param {object} params - The gsplat parameters. */ updateOverdrawMode(params: object): void; /** * Invalidates any cached cull/compaction upload state (e.g. after a work-buffer rebuild that * may have moved bounds indices). No-op for renderers without a GPU cull pipeline. */ invalidateCullUpload(): void; /** * Prepares the forward view for rendering. Renderers that run their own GPU pipeline (cull + * projection + sort) do their per-frame work here; CPU-sort renderers rely on the manager's * worker instead and leave this as a no-op. * * @param {GSplatWorld} world - The world providing the work buffer, bounds, and states. * @param {GSplatWorldState} worldState - The render-ready world state to draw. * @param {GSplatRenderViewParams} params - Per-call parameters for this view. * @returns {boolean} True if a GPU dispatch ran this call. */ prepareRenderView(world: GSplatWorld, worldState: GSplatWorldState, params: GSplatRenderViewParams): boolean; /** * Prepares a pick view and returns the configured pick mesh instance. Only meaningful for * renderers with a GPU pipeline; others return null. * * @param {GSplatWorld} world - The world providing the work buffer, bounds, and states. * @param {GSplatWorldState} worldState - The render-ready world state. * @param {GSplatRenderViewParams} pickParams - Per-call parameters for the pick view. * @returns {MeshInstance|null} The pick mesh instance, or null. */ preparePickingView(world: GSplatWorld, worldState: GSplatWorldState, pickParams: GSplatRenderViewParams): MeshInstance | null; } /** * @import { GraphicsDevice } from '../../platform/graphics/graphics-device.js' */ /** * Transient GPU scratch shared by the GPU-sort (hybrid) rendering path within a single * {@link GSplatManager} — the forward {@link GSplatHybridRenderer} and the directional * {@link GSplatShadowRenderer}. The manager creates one instance while a GPU-sort renderer is in use * and injects it into both paths' {@link GSplatIntervalCompaction}; it is freed when the manager * switches to a non-GPU-sort renderer or is destroyed. The CPU-sort (quad) path uses none of this. * * Buffers here are written + read at disjoint points in the frame (the forward sort in * `update()`, the shadow cull in `updateShadows()`), so a single shared allocation is safe — the * backend serializes them with the usual read/write barriers. It is per-manager (hence per-world), * so separate cameras/layers never contend on the same buffer. * * Starts with just the compaction candidate-index list; further shared scratch can be added here as * the hybrid path grows. * * @ignore */ declare class GSplatHybridRendererScratch { /** * @param {GraphicsDevice} device - The graphics device (must support compute). */ constructor(device: GraphicsDevice); /** @type {GraphicsDevice} */ device: GraphicsDevice; /** * Dense compacted work-buffer index list produced by {@link GSplatIntervalCompaction} (the * coarse-cull survivors). Sized to the work buffer's active splat count; grows monotonically. * * @type {StorageBuffer|null} */ compactedSplatIds: StorageBuffer | null; /** @type {number} */ _allocatedCompacted: number; /** * Ensures the shared candidate-index scratch holds at least `capacity` u32 entries, growing it * if needed. Returns the buffer so the caller can bind it. * * @param {number} capacity - Required entry count (work-buffer total active splats). * @returns {StorageBuffer} The candidate-index scratch buffer. */ ensureCompactedSplatIds(capacity: number): StorageBuffer; destroy(): void; } /** * Helper class for recursive parallel prefix sum (scan) operations. * Uses Blelloch algorithm with up-sweep and down-sweep phases. * * @ignore */ declare class PrefixSumKernel { /** * Creates a new PrefixSumKernel instance. * Call resize() to initialize passes with the desired count. * * @param {GraphicsDevice} device - The graphics device. */ constructor(device: GraphicsDevice); /** * The graphics device. * * @type {GraphicsDevice} */ device: GraphicsDevice; /** * List of pipeline passes (scan + add_block for each level). * * @type {Array<{scanCompute: Compute, addBlockCompute: Compute|null, blockSumBuffer: StorageBuffer, dispatchX: number, dispatchY: number, count: number, allocatedCount: number}>} */ passes: Array<{ scanCompute: Compute; addBlockCompute: Compute | null; blockSumBuffer: StorageBuffer; dispatchX: number; dispatchY: number; count: number; allocatedCount: number; }>; /** * Uniform buffer format (shared across all passes). * * @type {UniformBufferFormat|null} */ _uniformBufferFormat: UniformBufferFormat | null; /** * Bind group format (shared across all passes). * * @type {BindGroupFormat|null} */ _bindGroupFormat: BindGroupFormat | null; /** * Scan shader (shared, element count is a uniform). * * @type {Shader|null} */ _scanShader: Shader | null; /** * Add block shader (shared, element count is a uniform). * * @type {Shader|null} */ _addBlockShader: Shader | null; /** * Destroys the kernel and releases resources. */ destroy(): void; /** * Creates bind group format and shaders (called once in constructor). * * @private */ private _createFormatsAndShaders; /** * Recursively creates passes for the prefix sum. * * @param {StorageBuffer} dataBuffer - Buffer containing data to scan. * @param {number} count - Number of elements. * @private */ private createPassesRecursive; /** * Creates a shader for prefix sum operations. * * @param {string} name - Shader name. * @param {string} entryPoint - Entry point function name. * @returns {Shader} The created shader. * @private */ private _createShader; /** * Find optimal dispatch dimensions to minimize unused workgroups. * * @param {number} workgroupCount - Total workgroups needed. * @returns {{x: number, y: number}} Dispatch dimensions. * @private */ private findOptimalDispatchSize; /** * Resizes the kernel for a new element count. Grows capacity internally if needed. * * @param {StorageBuffer} dataBuffer - The buffer to perform prefix sum on. * @param {number} count - New element count. */ resize(dataBuffer: StorageBuffer, count: number): void; /** * Destroys passes but keeps shaders and formats. * * @ignore */ destroyPasses(): void; /** * Counts how many recursive passes are needed for a given element count. * * @param {number} count - Element count. * @returns {number} Number of passes needed. * @private */ private _countPassesNeeded; /** * Dispatches all prefix sum passes. * * @param {GraphicsDevice} device - The graphics device. */ dispatch(device: GraphicsDevice): void; } /** * Interval-based GPU stream compaction for the GSplat GPU sort path. Replaces the * per-pixel flag+scatter approach with an O(numIntervals) cull pass and a * workgroup-per-interval scatter pass. Always active when GPU sorting is enabled, * regardless of the culling toggle. * * @ignore */ declare class GSplatIntervalCompaction { /** * @param {GraphicsDevice} device - The graphics device (must support compute). * @param {import('./gsplat-hybrid-renderer-scratch.js').GSplatHybridRendererScratch} scratch * Manager-owned shared scratch the compacted index list is borrowed from (shared across the * forward + shadow GPU-sort passes within a manager). */ constructor(device: GraphicsDevice, scratch: GSplatHybridRendererScratch); /** @type {GraphicsDevice} */ device: GraphicsDevice; /** * Manager-owned shared scratch (see {@link GSplatHybridRendererScratch}) the compacted index list * is borrowed from — shared with the directional-shadow cull. The prefix-sum / count / interval * buffers stay per-instance. * * @type {import('./gsplat-hybrid-renderer-scratch.js').GSplatHybridRendererScratch} * @private */ private _scratch; /** * Borrowed candidate index list from {@link _scratch}, refreshed each dispatch (not owned here). * * @type {StorageBuffer|null} */ compactedSplatIds: StorageBuffer | null; /** @type {StorageBuffer|null} */ intervalsBuffer: StorageBuffer | null; /** @type {StorageBuffer|null} */ countBuffer: StorageBuffer | null; /** @type {PrefixSumKernel|null} */ prefixSumKernel: PrefixSumKernel | null; /** @type {StorageBuffer|null} */ numSplatsBuffer: StorageBuffer | null; /** @type {StorageBuffer|null} */ sortElementCountBuffer: StorageBuffer | null; /** @type {number} */ allocatedIntervalCount: number; /** @type {number} */ allocatedCountBufferSize: number; /** * World state version for which intervals were last uploaded. Avoids redundant * uploads when sortGpu is called repeatedly with the same world state. */ _uploadedVersion: number; /** @type {Compute|null} */ _cullComputePerspective: Compute | null; /** @type {Compute|null} */ _cullComputeFisheye: Compute | null; /** @type {Compute|null} */ _scatterCompute: Compute | null; /** * Reused 2D dispatch size for the scatter pass. The scatter pass dispatches one workgroup per * interval; when the interval count exceeds the device's per-dimension workgroup limit it is * tiled across X and Y (see {@link Compute.calcDispatchSize}). * * @type {Vec2} */ _scatterDispatchSize: Vec2; /** @type {Compute|null} */ _writeIndirectArgsCompute: Compute | null; /** @type {BindGroupFormat|null} */ _cullBindGroupFormatPerspective: BindGroupFormat | null; /** @type {BindGroupFormat|null} */ _cullBindGroupFormatFisheye: BindGroupFormat | null; /** @type {BindGroupFormat|null} */ _scatterBindGroupFormat: BindGroupFormat | null; /** @type {BindGroupFormat|null} */ _writeArgsBindGroupFormat: BindGroupFormat | null; /** @type {UniformBufferFormat|null} */ _scatterUniformBufferFormat: UniformBufferFormat | null; /** @type {UniformBufferFormat|null} */ _writeArgsUniformBufferFormat: UniformBufferFormat | null; destroy(): void; /** @private */ private _destroyCullPass; /** @private */ private _createUniformBufferFormats; /** * Creates a cull compute pass for the given mode. * * @param {boolean} fisheye - Whether to create the fisheye (cone) variant. * @returns {{ compute: Compute, bindGroupFormat: BindGroupFormat }} The created compute and bind group format. * @private */ private _createCullPass; /** * Returns the cached cull Compute for the given mode, lazily creating it on first use. * * @param {boolean} fisheye - Whether fisheye is active. * @returns {Compute} The cached Compute instance. * @private */ private _getCullCompute; /** @private */ private _createScatterCompute; /** @private */ private _createWriteIndirectArgsCompute; /** * Ensures all buffers have sufficient capacity. * * @param {number} numIntervals - Number of intervals. * @param {number} totalActiveSplats - Total active splats (max compacted output size). * @private */ private _ensureCapacity; /** * Forces the next {@link uploadIntervals} call to re-upload interval metadata, even for the * same world-state version. Used after a work-buffer rebuild, where boundsBaseIndex values may * have shifted and the cached upload is stale. */ invalidateUpload(): void; /** * Builds and uploads interval metadata from the world state. Called once per * world state change (not every frame). * * @param {GSplatWorldState} worldState - The world state to extract intervals from. */ uploadIntervals(worldState: GSplatWorldState): void; /** * Runs the full interval compaction pipeline: cull+count, prefix sum, scatter. * * @param {GSplatFrustumCuller} frustumCuller - Frustum culler providing bounds/transforms storage buffers and frustum planes. * @param {number} numIntervals - Total number of intervals. * @param {number} totalActiveSplats - Total active splats across all intervals. * @param {boolean} fisheyeEnabled - Whether fisheye cone culling should be used instead of frustum planes. */ dispatchCompact(frustumCuller: GSplatFrustumCuller, numIntervals: number, totalActiveSplats: number, fisheyeEnabled: boolean): void; /** * Writes indirect draw and dispatch arguments from the prefix sum visible count. * * @param {number} drawSlot - Slot index in the device's indirect draw buffer. * @param {number} dispatchSlotBase - Base slot index in the device's indirect * dispatch buffer. Key-gen args go to `dispatchSlotBase`; sort args to * `dispatchSlotBase + 1` onwards (as described by `sortIndirectInfo`). * @param {number} numIntervals - Total interval count (index into prefix sum for visible count). * @param {Uint32Array} sortIndirectInfo - Sorter-owned 4-element Uint32 array * returned by `ComputeRadixSort.prepareIndirect()`, used as a `vec4` * uniform by the shader to drive the `writeSortIndirectArgs` helper. */ writeIndirectArgs(drawSlot: number, dispatchSlotBase: number, numIntervals: number, sortIndirectInfo: Uint32Array): void; } /** * Per-light shadow draw entry. One cheap material + mesh instance over the shared quad mesh, plus a * visible-index buffer and an atomic visible-count buffer. The mesh instance is registered as a * shadow caster and is visible only for its light's shadow camera. */ type ShadowLightEntry = object; /** * Per-light shadow draw entry. One cheap material + mesh instance over the shared quad mesh, plus a * visible-index buffer and an atomic visible-count buffer. The mesh instance is registered as a * shadow caster and is visible only for its light's shadow camera. * * @typedef {object} ShadowLightEntry * @ignore * @property {Light} light - The directional light this entry casts for. * @property {ShaderMaterial} material - The per-light shadow draw material. * @property {MeshInstance} meshInstance - The cast mesh instance (registered as a shadow caster). * @property {StorageBuffer|null} indexBuffer - Dense visible work-buffer index list (grows with splat count). * @property {number} allocatedIndexCount - Capacity of `indexBuffer` in splats. * @property {StorageBuffer} countBuffer - Single-element atomic visible counter (also bound as `numSplatsStorage`). * @property {Compute|null} cullCompute - Per-entry cull compute (own uniform buffer/bind group), * lazily (re)created against the current cull shader; see {@link ShadowLightEntry.cullComputeGen}. * @property {number} cullComputeGen - Cull-shader generation `cullCompute` was built for; when it no * longer matches the renderer's {@link GSplatShadowRenderer#_cullShaderGen} the compute is rebuilt. * @property {Compute} argsCompute - Per-entry indirect-args compute (own uniform buffer/bind group). */ /** * Casts gsplat directional shadows on behalf of the GPU-sort ({@link GSplatHybridRenderer}) path, * which cannot self-cast. It shares the manager's {@link GSplatWorld} (work buffer + camera- * independent cull bounds + world states) and never allocates a world of its own. * * For each non-cascaded directional light affecting the manager's layer it maintains a cheap draw * entry (a per-light material + mesh instance over one shared quad mesh, plus a visible-index and * count buffer). A projection-free compute cull against the light's frustum produces the visible * index list, and a quad-style per-vertex-projected indirect draw writes the shadow map via the * standard caster pipeline. No sort and no projection cache are needed. * * Lifecycle is split across the frame: * - {@link syncLights} runs pre-cull (from {@link GSplatManager#update}) to reconcile the per-light * pool and register/unregister shadow casters, so `cullComposition` sees them. * - {@link cull} runs post-cull (from {@link GSplatManager#updateShadows} via the director) once * each light's shadow-camera frustum has been fitted, to dispatch the culls and bind results. * * @ignore */ declare class GSplatShadowRenderer { /** * @param {GraphicsDevice} device - The graphics device. * @param {GraphNode} node - The graph node the cast mesh instances are parented to. * @param {GraphNode} cameraNode - The main camera node this manager renders for; used to * resolve each light's shadow camera via `light.getRenderData(sceneCamera, 0)`. * @param {Layer} layer - The layer to register shadow casters on (and read directional lights from). * @param {GSplatWorld} world - The shared world (work buffer, cull bounds, world states). * @param {import('./gsplat-hybrid-renderer-scratch.js').GSplatHybridRendererScratch|null} [scratch] * Manager-owned shared scratch; forwarded to the pass-1 compaction so its candidate index list is * shared with the forward hybrid renderer (they use it at disjoint points in the frame). */ constructor(device: GraphicsDevice, node: GraphNode, cameraNode: GraphNode, layer: Layer, world: GSplatWorld, scratch?: GSplatHybridRendererScratch | null); /** @type {GraphicsDevice} */ device: GraphicsDevice; /** @type {GraphNode} */ node: GraphNode; /** @type {GraphNode} */ cameraNode: GraphNode; /** @type {Layer} */ layer: Layer; /** @type {GSplatWorld} */ world: GSplatWorld; /** * Per-light draw entries, keyed by light. * * @type {Map} */ entries: Map; /** * Reused scratch set of the qualifying directional shadow lights, rebuilt each {@link syncLights} * to diff against {@link entries}. * * @type {Set} * @private */ private _desiredLights; /** * Pass 1 (coarse): interval compaction run with each light's frustum, producing a dense candidate * list (`compactedSplatIds`) + candidate count (`countBuffer[numIntervals]`). Reused across all * lights — one shared scratch, since lights are culled sequentially (light A's pass 2 consumes the * candidate list before light B's pass 1 overwrites it). The expensive per-splat fine cull (pass * 2) then runs flat over the candidate list, so occupancy is independent of interval count. * * @type {GSplatIntervalCompaction|null} */ _compaction: GSplatIntervalCompaction | null; /** @type {Vec2} */ _cullDispatchSize: Vec2; /** * Reused light frustum planes (6 × vec4(normal, distance)) for the cull uniform, refilled per * light entry from its shadow camera. * * @type {Float32Array} */ _frustumPlanes: Float32Array; /** * Change-detection key for the scene material's shader chunks; when it changes, the user * `gsplatModifyVS` chunk is re-applied to the per-light shadow materials. * * @type {string} * @private */ private _userChunksKey; /** * The scene material's user `gsplatModifyVS` WGSL chunk source (or null for the default no-op). * The shadow path is WebGPU-only, so only the WGSL variant is tracked. * * @type {string|null} * @private */ private _userModifyWgsl; /** @type {Shader|null} */ _cullShader: Shader | null; /** @type {BindGroupFormat|null} */ _cullBindGroupFormat: BindGroupFormat | null; /** * Work-buffer format version the cull shader was last built for. The cull shader reads the work * buffer (texture bindings + read code derived from the format), so a format change rebuilds it. * * @type {number} * @private */ private _cullFormatVersion; /** * The scene material's shader-chunks key the cull shader was last built for. A change means the * user `gsplatModifyVS` chunk changed, so the cull shader is rebuilt to match the shadow draw. * * @type {string|null} * @private */ private _cullBuiltChunksKey; /** * Monotonic cull-shader generation, bumped on every (re)build. Per-light cull Computes reference * the shared shader, so they are recreated when this changes (see {@link _cullEntry}). * * @type {number} * @private */ private _cullShaderGen; /** @type {Shader|null} */ _argsShader: Shader | null; /** @type {BindGroupFormat|null} */ _argsBindGroupFormat: BindGroupFormat | null; destroy(): void; /** * (Re)builds the shared cull shader when the work-buffer format or the user `gsplatModifyVS` * chunk changes, bumping {@link _cullShaderGen} so per-light Computes are recreated. Must run * after {@link _syncUserModify} (which refreshes the tracked modify chunk) and once the work * buffer is ready. * * @private */ private _ensureCullShader; /** * Builds the pass-2 fine-cull shader + bind group format against the current work-buffer format * and the tracked user modify chunk. The fixed bindings (0..4) are followed by the work-buffer * format texture bindings; the shader reads each candidate splat (center/opacity/rotation/scale), * applies the render-stage modifier, and runs the opacity/size/frustum fine tests. * * @private */ private _buildCullShader; /** @private */ private _createArgsShader; /** * Rebinds to a new work buffer after a format/resize swap. The per-light materials read the * work-buffer textures, so they must be re-pointed when the manager recreates it. * * @param {GSplatWorkBuffer} workBuffer - The new work buffer. */ setDataSource(workBuffer: GSplatWorkBuffer): void; /** * Sets the world-space AABB on every cast mesh instance. The directional shadow cull derives * each cascade's depth range from the casters' AABBs (which world-space PCSS penumbra scaling * depends on), and the shared quad mesh has no meaningful spatial bounds of its own — so without * this the depth range is wrong and soft shadows are mis-scaled. Must run pre-cull (the manager * calls it before cullComposition fits the shadow cameras). `setCustomAabb` copies, so passing a * shared box instance to every entry is safe. * * @param {import('../../core/shape/bounding-box.js').BoundingBox|null} aabb - World-space splat AABB. */ setCastersAabb(aabb: BoundingBox | null): void; /** * Pre-cull pass: reconcile the per-light caster pool against the layer's directional shadow * lights (enabled, shadow-casting, non-cascaded). Adds entries for new lights and tears down * entries for lights that were disabled, removed, stopped casting, or became cascaded — freeing * their GPU resources and unregistering their caster. Cascaded directional lights are skipped * (warned once); they would need a per-cascade cull. */ syncLights(): void; /** * Post-cull pass: for each light entry run the two-pass cull (coarse candidate compaction with * the light frustum, then a flat per-splat fine cull) and the indirect-args write, then bind the * results to the entry's mesh instance. Runs after `cullComposition` and before the frame graph * renders the shadow maps. Cached shadows skip both preparation and compute dispatches. * * @param {GSplatParams} gsplatParams - Scene gsplat params (alphaClip etc.). */ cull(gsplatParams: GSplatParams): void; /** * Applies the scene material's user `gsplatModifyVS` chunk to every per-light shadow material * (recompiling only when the chunk changes) and forwards the scene material's parameters (e.g. * `uTime`) to them each frame. This keeps cast shadows in sync with any forward-pass vertex * animation, since the shadow draw uses the same quad VS + modify hooks. * * @param {GSplatParams} gsplatParams - Scene gsplat params (carries the template material). * @private */ private _syncUserModify; /** * Sets (or clears) the tracked user `gsplatModifyVS` chunk on one entry's material and rebuilds * its shader. Called when the chunk changes and when a new entry is created. * * @param {ShadowLightEntry} entry - The light entry. * @private */ private _applyUserModify; /** * Dispatches the cull + indirect-args for one light entry and binds the results. * * @param {ShadowLightEntry} entry - The light entry. * @param {number} numIntervals - Total interval count. * @param {number} totalActiveSplats - Max output index count. * @param {number} textureSize - Work buffer texture size. * @param {GSplatParams} gsplatParams - Scene gsplat params. * @private */ private _cullEntry; /** * Fills {@link _frustumPlanes} from a frustum: 6 planes packed as vec4(normal.xyz, distance). * * @param {import('../../core/shape/frustum.js').Frustum} frustum - The light's shadow-camera frustum. * @private */ private _fillFrustumPlanes; /** * Creates a per-light shadow draw entry (material + caster mesh instance + count buffer). * * @param {Light} light - The directional light. * @returns {ShadowLightEntry} The created entry. * @private */ private _createEntry; /** * Tears down a light entry: unregisters the caster and frees its GPU resources. * * @param {ShadowLightEntry} entry - The entry to destroy. * @private */ private _destroyEntry; /** * Creates the quad-style shadow draw material. Uses the same gsplat vertex/fragment chunks as * the forward quad renderer (direct per-vertex projection from the bound view/projection — the * shadow camera's, supplied by the engine's shadow pass), trimmed to depth + alpha-clip (the * engine injects `SHADOW_PASS` when compiling the shadow variant). Indirect-draw mode reads the * visible index list and GPU count. * * @returns {ShaderMaterial} The configured material. * @private */ private _createMaterial; /** * Injects the work-buffer format shader chunks and binds its textures + format-dependent defines * to a material. Mirrors the relevant parts of {@link GSplatQuadRenderer}. * * @param {ShaderMaterial} material - The material to configure. * @private */ private _configureMaterialWorkBuffer; /** * Creates the cast mesh instance for a light, visible only for that light's shadow camera. * * @param {Light} light - The directional light. * @param {ShaderMaterial} material - The entry's material. * @returns {MeshInstance} The mesh instance. * @private */ private _createMeshInstance; } declare class GSplatUnifiedSorter extends EventHandler { /** * @param {Scene} [scene] - The scene to fire sort timing events on. */ constructor(scene?: Scene); worker: Worker; bufferLength: number; availableOrderData: any[]; jobsInFlight: number; hasNewVersion: boolean; /** * Pending sorted result to be applied next frame. If multiple sorted results are received from * the worker, the latest result is stored here. * * @type {{ count: number, version: number, orderData: Uint32Array }|null} */ pendingSorted: { count: number; version: number; orderData: Uint32Array; } | null; /** @type {Set} */ centersSet: Set; /** @type {boolean} */ _destroyed: boolean; /** @type {Scene|null} */ scene: Scene | null; onSorted(message: any): void; applyPendingSorted(): void; releaseOrderData(orderData: any): void; destroy(): void; /** * Adds or removes centers from the sorter. * * @param {number} id - The id of the centers. * @param {Float32Array|null} centers - The centers buffer. */ setCenters(id: number, centers: Float32Array | null): void; /** * Updates centers in the worker based on current splats. * Adds new centers and removes centers no longer needed. * * @param {GSplatInfo[]} splats - Array of active splat infos. */ updateCentersForSplats(splats: GSplatInfo[]): void; /** * Sets sort parameters data for sorting of splats. * * @param {object} payload - The sort parameters payload to send. */ setSortParameters(payload: object): void; /** * Sends sorting parameters to the sorter. Called every frame sorting is needed. * * @param {object} params - The sorting parameters - per-splat directions, offsets, scales, AABBs. * @param {boolean} radialSorting - Whether to use radial distance sorting. */ setSortParams(params: object, radialSorting: boolean): void; } /** * GSplatManager manages the rendering of splats using a work buffer, where all active splats are * stored and rendered from. It owns the {@link GSplatWorld} (work buffer, world-state versions, * streaming, bake), the world version lifecycle ({@link GSplatWorld#markSorted}/`onSorted`), and — * for the CPU-sort path ({@link GSplatQuadRenderer}) — a web-worker sorter. Each frame it bakes the * render-ready world state and then delegates per-view work to the active renderer: * * - CPU sort (WebGPU + WebGL): the manager sends camera + centers to the worker, which returns a * sorted order; the quad renderer's vertex shader reads `orderBuffer[vertexId] → splatId`. No * GPU culling. * - GPU sort ({@link GSplatHybridRenderer}, WebGPU only): the renderer owns the interval cull + * compaction, projector, and radix sort; the manager just marks the version sorted and calls * {@link GSplatRenderer#prepareRenderView}. * * @ignore */ declare class GSplatManager { /** * @param {GraphicsDevice} device - The graphics device. * @param {GSplatDirector} director - The director. * @param {Layer} layer - The layer. * @param {GraphNode} cameraNode - The camera node. */ constructor(device: GraphicsDevice, director: GSplatDirector, layer: Layer, cameraNode: GraphNode); /** @type {GraphicsDevice} */ device: GraphicsDevice; /** @type {GraphNode} */ node: GraphNode; /** * Owns the work buffer, versioned world states, allocation, octree/LOD evaluation, streaming, * budget, and the work-buffer bake. Created 1:1 per manager (no sharing yet). * * @type {GSplatWorld} */ world: GSplatWorld; /** @type {GSplatParams} */ gsplat: GSplatParams; /** @type {GSplatRenderer} */ renderer: GSplatRenderer; /** * Casts directional shadows for the GPU-sort (hybrid) forward renderer, which cannot self-cast. * Null when the forward renderer is CPU-sort (the quad renderer self-casts) or when this * manager has no shadow render mode. Shares this manager's {@link GSplatWorld}. * * @type {GSplatShadowRenderer|null} */ shadowRenderer: GSplatShadowRenderer | null; /** * Shared GPU scratch for the GPU-sort (hybrid) path, created while a GPU-sort renderer is in use * and injected into both the forward {@link GSplatHybridRenderer} and the * {@link GSplatShadowRenderer} so they share the compaction candidate buffer. Null for the * CPU-sort (quad) renderer. * * @type {GSplatHybridRendererScratch|null} * @private */ private _hybridScratch; /** * The currently active renderer mode. Starts as undefined so the first * prepareRendererMode() call always creates the appropriate resources. * * @type {number|undefined} */ activeRenderer: number | undefined; /** * CPU-based sorter (used by the quad renderer; the hybrid renderer owns its own GPU sort). * * @type {GSplatUnifiedSorter|null} */ cpuSorter: GSplatUnifiedSorter | null; /** * Tracks last seen centersVersion per resource ID for detecting centers updates. Used to feed * the CPU sorter when the world creates a new world-state version. * * @type {Map} * @private */ private _centersVersions; /** @type {Vec3} */ lastSortCameraPos: Vec3; /** @type {Vec3} */ lastSortCameraFwd: Vec3; /** @type {boolean} */ sortNeeded: boolean; /** * Event handle for the graphics device restored event. * * @type {EventHandle|null} * @private */ private _deviceRestoredEvent; /** @type {GraphNode} */ cameraNode: GraphNode; /** @type {Scene} */ scene: Scene; /** * Bitmask flags controlling which render passes this manager participates in. * * @type {number|undefined} */ renderMode: number | undefined; /** * Persistent result objects written (out-param) by the {@link GSplatWorld} APIs to avoid * per-frame allocation. Consumed synchronously by the manager after each call. * * @private */ private _updateResult; /** @private */ private _bakeResult; /** @private */ private _markResult; /** @private */ private _formatResult; /** * Frame token of the last {@link updateStreaming} run, for once-per-frame dedup between the * component-system streaming tick and the render path. * * @type {number} * @private */ private _lastStreamToken; /** * Whether the most recent streaming pass produced new data a render would show (new world-state * version or work-buffer recreation). Used by the director to decide whether to fire frame:request. * * @type {boolean} * @private */ private _streamAdvanced; /** * Reused per-call parameter bag passed to the renderer's forward {@link GSplatRenderer#prepareRenderView}. * Avoids per-frame allocation and keeps the renderer free of a back-reference to the manager/scene. * * @type {GSplatRenderViewParams} * @private */ private _renderViewParams; /** * Reused per-call parameter bag passed to the renderer's {@link GSplatRenderer#preparePickingView}. * Separate from {@link _renderViewParams} so mid-frame picking can't corrupt the forward params. * * @type {GSplatRenderViewParams} * @private */ private _pickParams; director: GSplatDirector; layer: Layer; destroy(): void; _destroyed: boolean; /** * Handles a graphics context restore: the work buffer render target is recreated empty, so * force a full rebuild and re-sort to re-materialize the splats from the (auto-restored) source * textures. * * Skipped when the world has streaming octree instances: those destroy and asynchronously * reload their source resources from URL via their own device-lost handling, and rebuilding the * work buffer here would render from textures that have been destroyed (and not yet reloaded). * * @private */ private _onDeviceRestored; /** * Destroys CPU sorting resources (worker-based sorter). * * @private */ private destroyCpuSorting; /** * Creates the CPU sorter and prepares it for the current world state. Disables any * GPU-side indirect draw and hides the mesh until the first sort result arrives. * * @private */ private initCpuSorting; get material(): ShaderMaterial; /** * Number of work-buffer blocks uploaded this frame (forwarded from the world for stats). * * @type {number} */ get bufferCopyUploaded(): number; /** * Total number of work-buffer blocks this frame (forwarded from the world for stats). * * @type {number} */ get bufferCopyTotal(): number; /** * True when the CPU sorter has a completed sort result waiting to be applied by a render. Used * by the director to request a render so the pending result is applied. * * @type {boolean} */ get hasPendingSort(): boolean; /** * Dispatches a renderer-specific pick pipeline and returns the configured pick mesh instance. * The hybrid renderer refreshes its shared projector/sort buffers for the picker camera and * returns a transient pick mesh. * * @param {object} camera - The camera. * @param {number} width - Pick target width. * @param {number} height - Pick target height. * @returns {import('../mesh-instance.js').MeshInstance|null} The pick mesh instance, or null. */ prepareForPicking(camera: object, width: number, height: number): MeshInstance | null; /** * Writes the current scene gsplat params into a renderer per-view parameter bag. Lets the * renderer run its GPU pipeline without a back-reference to the manager or scene. * * @param {GSplatRenderViewParams} p - The parameter bag to populate. * @private */ private _writeGsplatParams; /** * Fills and returns the reused forward-view parameter bag for the manager's camera. * * @returns {GSplatRenderViewParams} The populated {@link _renderViewParams}. * @private */ private _fillRenderViewParams; /** * Fills and returns the reused picking parameter bag for the picker camera. * * @param {object} camera - The picker camera. * @param {number} width - Pick target width. * @param {number} height - Pick target height. * @returns {GSplatRenderViewParams} The populated {@link _pickParams}. * @private */ private _fillPickParams; /** * Creates the CPU sorter (Web Worker based). * * @returns {GSplatUnifiedSorter} The created sorter. */ createSorter(): GSplatUnifiedSorter; /** * Sets the render mode for this manager and its renderer. * * @param {number} renderMode - Bitmask flags controlling render passes (GSPLAT_FORWARD, GSPLAT_SHADOW, or both). * @ignore */ setRenderMode(renderMode: number): void; /** * Creates or destroys {@link shadowRenderer} to match the current render mode and forward * renderer. The GPU-sort (hybrid) renderer cannot self-cast shadows, so when shadow rendering * is requested and the forward renderer uses GPU sort, a dedicated {@link GSplatShadowRenderer} * casts on its behalf (sharing this manager's world). The CPU-sort quad renderer self-casts, so * no shadow renderer is created for it. * * @private */ private _syncShadowRenderer; /** * Creates the renderer and sort resources for the given mode. Used at init time. * * @param {number} mode - The GSPLAT_RENDERER_* constant. * @private */ private _createRenderer; /** * Checks whether the resolved renderer mode has changed and transitions to the new mode * (CPU raster quad <-> hybrid GPU sort). * * @private */ private prepareRendererMode; /** * Supply the manager with the placements to use. This is used to update the manager when the * layer's placements have changed, called infrequently. * * @param {GSplatPlacement[]} placements - The placements to reconcile with. */ reconcile(placements: GSplatPlacement[]): void; onSorted(count: any, version: any, orderData: any): void; /** * On the first sort of a world-state version, advances the render-ready version (cleanup + * first-sort work-buffer rebuild) and applies the renderer rebuild reaction. The world version * lifecycle is owned by the manager; the GPU pipeline (in the renderer) assumes a baked, * render-ready work buffer. This is the synchronous GPU-sort counterpart of {@link onSorted} * (the async CPU path). No-op once the version has been sorted before. * * @param {GSplatWorldState} worldState - The world state about to be sorted. * @private */ private _markSortedIfNeeded; /** * Tests if the camera has moved enough to require re-sorting. * - For radial sorting: only position matters (rotation doesn't affect sort order) * - For directional sorting: only forward direction matters (position doesn't affect sort order) * * @returns {boolean} True if camera moved enough to require re-sorting, otherwise false. */ testCameraMovedForSort(): boolean; /** * Fires the frame:ready event with current sorting and loading state. */ fireFrameReadyEvent(): void; /** * CPU streaming pass: work-buffer format sync, renderer-mode transition, and the world's LOD / * octree streaming / world-state creation. Runs every frame from the component system's * framerender tick (even when rendering is skipped), and once from {@link update} on the render * path. Deduped via `token` so it runs at most once per frame. Performs no render-pass / draw * work — only CPU/IO and GPU resource creation. * * @param {number} token - Per-frame token; a repeated token is a no-op (returns the cached result). * @returns {boolean} True if new data was produced that a render would show (new world-state * version or work-buffer recreation). */ updateStreaming(token: number): boolean; update(): number; /** * Post-cull shadow pass. Called from the director after cullComposition has fitted each * directional light's shadow-camera frustum, and before the frame graph renders the shadow * maps. Dispatches the per-light gsplat shadow cull and binds the results. No-op unless this * manager has a {@link shadowRenderer} (GPU-sort forward path with a shadow render mode). */ updateShadows(): void; /** * Feeds the CPU sorter the centers for the splats in the latest world-state version. Called * after the world creates a new version (the version-change detection lives here because the * CPU sorter is manager-owned). * * @private */ private _feedCpuSorterCenters; /** * Sorts the splats using CPU worker (asynchronous). * * @param {GSplatWorldState} lastState - The last world state. */ sortCpu(lastState: GSplatWorldState): void; } /** * Class responsible for managing {@link GSplatManager} instances for Cameras and their Layers. * * @ignore */ declare class GSplatDirector { /** * @param {GraphicsDevice} device - The graphics device. * @param {Renderer} renderer - The renderer. * @param {Scene} scene - The scene. * @param {EventHandler} eventHandler - Event handler for firing events. * @param {GSplatParams} gsplat - The GSplat parameters. */ constructor(device: GraphicsDevice, renderer: Renderer, scene: Scene, eventHandler: EventHandler, gsplat: GSplatParams); /** * @type {GraphicsDevice} */ device: GraphicsDevice; /** * Per camera data. * * @type {Map} */ camerasMap: Map; /** * @type {Scene} */ scene: Scene; /** * @type {GSplatParams} */ gsplat: GSplatParams; /** * @type {EventHandler} */ eventHandler: EventHandler; /** * Per-frame token, incremented once each streaming tick ({@link updateStreaming}). A manager's * streaming work (LOD evaluation, world-state update) can run from two places in a frame: the * streaming tick, which advances managers that already exist, and the render path * ({@link GSplatManager#update}), which additionally covers managers created during that render * — e.g. at startup, or when a camera, layer, or gsplat component is added — so they render in * the same frame instead of a frame later. * * The manager records the token it last streamed for and skips the work when the token is * unchanged, so the streaming runs at most once per frame regardless of which path reaches it * first (the render-path call is a no-op for managers the tick already advanced). * * @type {number} */ _streamToken: number; renderer: Renderer; destroy(): void; getCameraData(camera: any): GSplatCameraData; /** * Dispatches pick compute for the given camera and layer, returning a ready-to-render * pick mesh instance (or null if no gsplat data exists for this camera/layer pair). * * @param {Camera} camera - The camera. * @param {number} width - Pick target width. * @param {number} height - Pick target height. * @param {Layer} layer - The layer to pick from. * @returns {import('../mesh-instance.js').MeshInstance|null} The configured pick mesh instance. */ prepareForPicking(camera: Camera, width: number, height: number, layer: Layer): MeshInstance | null; /** * CPU streaming tick. Driven by the gsplat component system every frame (even when rendering is * skipped, e.g. `app.autoRender = false`). Applies pending param changes, processes resource * cleanup, and advances each existing manager's LOD/streaming/world-state via * {@link GSplatManager#updateStreaming}. Fires `frame:request` once when a render would show new * data (a new world-state version) or when a CPU-sort result is waiting to be applied. * * Uses the cached `camerasMap` topology (built by {@link update} on the render path). Placement * changes on layers that already have managers are reconciled here, so they reach the world state * this frame. Newly added cameras, and layers without managers yet, register on the next rendered * frame, and cameras whose entity has lost its camera component since are skipped until that * frame prunes them. Does no GPU draw work. */ updateStreaming(): void; /** * Updates the director for the given layer composition cameras and layers. * * @param {LayerComposition} comp - The layer composition. */ update(comp: LayerComposition): void; /** * Post-cull shadow pass. Runs AFTER `cullComposition` (so each directional light's shadow-camera * frustum has been fitted) and before the frame graph renders the shadow maps, dispatching each * manager's per-light gsplat shadow cull. Only managers whose forward renderer is GPU-sort * (which cannot self-cast) hold a shadow renderer; for the rest this is a no-op. The CPU-sort * quad renderer self-casts and is unaffected. */ updateShadows(): void; } /** * Per camera data the director keeps track of. * * @ignore */ declare class GSplatCameraData { /** * @type {Map} */ layersMap: Map; destroy(): void; removeLayerData(layer: any): void; getLayerData(device: any, director: any, layer: any, camera: any): GSplatLayerData; } /** * Per layer data the director keeps track of. * * @ignore */ declare class GSplatLayerData { /** * @param {GraphicsDevice} device - The graphics device. * @param {GSplatDirector} director - The director. * @param {Layer} layer - The layer. * @param {Camera} camera - The camera. */ constructor(device: GraphicsDevice, director: GSplatDirector, layer: Layer, camera: Camera); /** * @type {GSplatManager|null} */ gsplatManager: GSplatManager | null; /** * @type {GSplatManager|null} */ gsplatManagerShadow: GSplatManager | null; /** * Creates a new GSplatManager, sets its render mode, and fires the material:created event. * * @param {GraphicsDevice} device - The graphics device. * @param {GSplatDirector} director - The director. * @param {Layer} layer - The layer. * @param {GraphNode} cameraNode - The camera node. * @param {Camera} camera - The camera. * @param {number} renderMode - The render mode flags. * @returns {GSplatManager} The created manager. * @private */ private createManager; /** * Updates the manager configuration based on current layer placements. * * @param {GraphicsDevice} device - The graphics device. * @param {GSplatDirector} director - The director. * @param {Layer} layer - The layer. * @param {Camera} camera - The camera. */ updateConfiguration(device: GraphicsDevice, director: GSplatDirector, layer: Layer, camera: Camera): void; destroy(): void; } declare class ShadowMap { static create(device: any, light: any): ShadowMap; static createAtlas(device: any, resolution: any, shadowType: any): ShadowMap; static create2dMap(device: any, size: any, shadowType: any): ShadowMap; static createCubemap(device: any, size: any, shadowType: any): ShadowMap; constructor(texture: any, targets: any); texture: any; cached: boolean; renderTargets: any; destroy(): void; } declare class LightTextureAtlas { constructor(device: any); device: any; version: number; shadowAtlasResolution: number; shadowAtlas: ShadowMap; shadowEdgePixels: number; cookieAtlasResolution: number; cookieAtlas: Texture; cookieRenderTarget: RenderTarget; slots: any[]; atlasSplit: any[]; cubeSlotsOffsets: Vec2[]; scissorVec: Vec4; destroy(): void; destroyShadowAtlas(): void; destroyCookieAtlas(): void; allocateShadowAtlas(resolution: any, shadowType?: number): void; allocateCookieAtlas(resolution: any): void; allocateUniforms(): void; _shadowAtlasTextureId: any; _shadowAtlasParamsId: any; _shadowAtlasParams: Float32Array; _cookieAtlasTextureId: any; updateUniforms(): void; subdivide(numLights: any, lightingParams: any): void; collectLights(localLights: any, lightingParams: any): any[]; setupSlot(light: any, rect: any): void; assignSlot(light: any, slotIndex: any, slotReassigned: any): void; update(localLights: any, lightingParams: any): void; } declare class ShadowMapCache { cache: Map; destroy(): void; clear(): void; getKey(light: any): string; get(device: any, light: any): any; add(light: any, shadowMap: any): void; } declare class ShadowRenderer { static createShadowCamera(device: any, shadowType: any, type: any, face: any): Camera; /** * @param {Renderer} renderer - The renderer. * @param {LightTextureAtlas} lightTextureAtlas - The shadow map atlas. */ constructor(renderer: Renderer, lightTextureAtlas: LightTextureAtlas); /** * A cache of shadow passes. First index is looked up by light type, second by shadow type. * * @type {ShaderPassInfo[][]} * @private */ private shadowPassCache; /** * Reusable list of shadow caster arrays, see {@link ShadowRenderer#_collectCasterLists}. * * @type {MeshInstance[][]} * @private */ private _casterLists; device: GraphicsDevice; /** @type {Renderer} */ renderer: Renderer; /** @type {LightTextureAtlas} */ lightTextureAtlas: LightTextureAtlas; sourceId: ScopeId; pixelOffsetId: ScopeId; weightId: ScopeId; blurVsmShader: {}[]; blurVsmWeights: {}; shadowMapLightRadiusId: ScopeId; viewUniformFormat: UniformBufferFormat; blendStateWrite: BlendState; blendStateNoWrite: BlendState; _cullShadowCastersInternal(meshInstances: any, visible: any, camera: any): void; /** * Culls the list of shadow casters used by the light by the camera, storing visible mesh * instances in the specified array. * * @param {LayerComposition} comp - The layer composition used as a source of shadow casters, * if those are not provided directly. * @param {Light} light - The light. * @param {MeshInstance[]} visible - The array to store visible mesh instances in. * @param {Camera} camera - The camera. * @param {MeshInstance[]} [casters] - Optional array of mesh instances to use as casters. */ cullShadowCasters(comp: LayerComposition, light: Light, visible: MeshInstance[], camera: Camera, casters?: MeshInstance[]): void; /** * Collects the lists of shadow casters used by the light: either the supplied array of casters, * or the shadow casters of each layer the light is part of. * * @param {LayerComposition} comp - The layer composition used as a source of shadow casters, * if those are not provided directly. * @param {Light} light - The light. * @param {MeshInstance[]} [casters] - Optional array of mesh instances to use as casters. * @returns {MeshInstance[][]} The lists of shadow casters. This is reused between calls, and so * is only valid until the next call. * @private */ private _collectCasterLists; /** * Culls the shadow casters used by an omni light against all six of its cube map faces in a * single pass over the casters, storing the visible mesh instances in the per-face light render * data. This replaces one full pass over the casters per face. * * The six shadow cameras of an omni light are axis aligned in world space - see * {@link LightCamera.pointLightRotations}, and note that {@link ShadowRendererLocal#cull} only * sets the position of an omni light's shadow cameras, never their rotation. Light space is * therefore world space translated by the light position, and each face's frustum is bounded by * a near and a far plane perpendicular to the face axis, plus four side planes through the * light position with the slope of the face's field of view. Testing a caster's bounding sphere * against those planes in light space is a handful of comparisons per face, and uses the same * planes {@link Frustum#containsAabb} would, so the result is the same set of casters (up to * the slab rejection below, which is tighter than a plane test near the frustum corners). * * @param {LayerComposition} comp - The layer composition used as a source of shadow casters, * if those are not provided directly. * @param {Light} light - The omni light. * @param {MeshInstance[]} [casters] - Optional array of mesh instances to use as casters. */ cullShadowCastersOmni(comp: LayerComposition, light: Light, casters?: MeshInstance[]): void; /** * Orders shadow casters by their shader, then their material, then their mesh, so that the * casters sharing a shader, a material and the vertex buffers are submitted together. See * {@link MeshInstance#_sortKeyShadow}. * * @param {MeshInstance} drawCallA - The first mesh instance. * @param {MeshInstance} drawCallB - The second mesh instance. * @returns {number} The sort order. */ sortCompareShader(drawCallA: MeshInstance, drawCallB: MeshInstance): number; setupRenderState(device: any, light: any): void; dispatchUniforms(light: any, shadowCam: any, lightRenderData: any, face: any): void; /** * @param {Light} light - The light. * @returns {number} Index of shadow pass info. */ getShadowPass(light: Light): number; /** * @param {MeshInstance[]} visibleCasters - Visible mesh instances. * @param {Light} light - The light. * @param {Camera} camera - The camera. */ submitCasters(visibleCasters: MeshInstance[], light: Light, camera: Camera): void; needsShadowRendering(light: any): boolean; getLightRenderData(light: any, camera: any, face: any): any; setupRenderPass(renderPass: any, shadowCamera: any, clearRenderTarget: any): void; prepareFace(light: any, camera: any, face: any): any; renderFace(light: any, camera: any, face: any, clear: any): void; renderVsm(light: any, camera: any, cascadeMask?: number): void; getVsmBlurShader(blurMode: any, filterSize: any): any; applyVsmBlur(light: any, camera: any, cascadeMask: any): void; initViewUniformFormat(): void; frameUpdate(): void; } /** * @import { FrameGraph } from '../../scene/frame-graph.js' * @import { GraphicsDevice } from '../../platform/graphics/graphics-device.js' * @import { Light } from '../../scene/light.js' * @import { Renderer } from './renderer.js' * @import { ShadowRenderer } from './shadow-renderer.js' */ declare class ShadowRendererLocal { constructor(renderer: any, shadowRenderer: any); shadowLights: any[]; /** @type {Renderer} */ renderer: Renderer; /** @type {ShadowRenderer} */ shadowRenderer: ShadowRenderer; /** @type {GraphicsDevice} */ device: GraphicsDevice; prepareShadowMap(light: any): void; cull(light: any, comp: any, casters?: any): void; prepareLights(shadowLights: any, lights: any): any; /** * Prepare render passes for rendering of shadows for local non-clustered lights. Each shadow face * is a separate render pass as it renders to a separate render target. * * @param {FrameGraph} frameGraph - The frame graph. * @param {Light[]} localLights - The list of local lights. */ buildNonClusteredRenderPasses(frameGraph: FrameGraph, localLights: Light[]): void; } /** * A render pass used to render directional shadows. * * @ignore */ declare class RenderPassShadowDirectional extends RenderPass { constructor(device: any, shadowRenderer: any, light: any, camera: any, cascadeMask: any); shadowRenderer: any; light: any; camera: any; cascadeMask: any; allCascadesRendering: boolean; } declare class ShadowRendererDirectional { constructor(renderer: any, shadowRenderer: any); /** @type {Renderer} */ renderer: Renderer; /** @type {ShadowRenderer} */ shadowRenderer: ShadowRenderer; /** @type {GraphicsDevice} */ device: GraphicsDevice; /** * Ensure the shadow map exists and the light is marked visible. When a camera is supplied, * bind its shadow buffer even for cached shadows: forward lighting needs the sampler without * a shadow pass or cull (#3588). * * @param {Light} light - The shadow-casting light. * @param {Camera|null} [camera] - The camera that will sample the shadow map, if any. */ prepareShadowMap(light: Light, camera?: Camera | null): void; cull(light: any, comp: any, camera: any, casters?: any, cascadeMask?: number): void; generateSplitDistances(light: any, nearDist: any, farDist: any): void; /** * @param {Light} light - The directional light. * @returns {number} Bit mask of cascades needing initialization or enabled by the overrides. */ getCascadeMask(light: Light): number; /** * Create a render pass for directional light shadow rendering for a specified camera. * * @param {Light} light - The directional light. * @param {Camera} camera - The camera. * @returns {RenderPassShadowDirectional|null} - The render pass if the shadow rendering is * required, or null otherwise. */ getLightRenderPass(light: Light, camera: Camera): RenderPassShadowDirectional | null; } /** * A render pass used to render cookie textures (both 2D and Cubemap) into the texture atlas. * * @ignore */ declare class RenderPassCookieRenderer extends RenderPass { static create(renderTarget: any, cubeSlotsOffsets: any): RenderPassCookieRenderer; constructor(device: any, cubeSlotsOffsets: any); /** @type {QuadRender|null} */ _quadRenderer2D: QuadRender | null; /** @type {QuadRender|null} */ _quadRendererCube: QuadRender | null; _filteredLights: any[]; _forceCopy: boolean; /** * Event handle for device restored event. * * @type {EventHandle|null} * @private */ private _evtDeviceRestored; _cubeSlotsOffsets: any; blitTextureId: any; invViewProjId: any; onDeviceRestored(): void; update(lights: any): void; filter(lights: any, filteredLights: any): void; initInvViewProjMatrices(): void; get quadRenderer2D(): QuadRender; get quadRendererCube(): QuadRender; } /** * A render pass used to render local clustered shadows. This is done inside a single render pass, * as all shadows are part of a single render target atlas. * * @ignore */ declare class RenderPassShadowLocalClustered extends RenderPass { constructor(device: any, shadowRenderer: any, shadowRendererLocal: any); shadowRenderer: any; shadowRendererLocal: any; update(localLights: any): void; } /** * A render pass used to update clustered lighting data - shadows, cookies, world clusters. * * @ignore */ declare class FramePassUpdateClustered extends FramePass { constructor(device: any, renderer: any, shadowRenderer: any, shadowRendererLocal: any, lightTextureAtlas: any); renderer: any; cookiesRenderPass: RenderPassCookieRenderer; shadowRenderPass: RenderPassShadowLocalClustered; update(shadowsEnabled: any, cookiesEnabled: any, lights: any, localLights: any): void; } /** * A lighting cube represented by 6 colors, one per cube direction. Use for simple lighting on the * particle system. * * @ignore */ declare class LightCube { colors: Float32Array; update(ambientLight: any, lights: any): void; } /** * The base renderer functionality to allow implementation of specialized renderers. * * @ignore */ declare class Renderer { /** * Create a new instance. * * @param {GraphicsDevice} graphicsDevice - The graphics device used by the renderer. * @param {Scene} scene - The scene. */ constructor(graphicsDevice: GraphicsDevice, scene: Scene); /** @type {boolean} */ clustersDebugRendered: boolean; /** @type {Scene} */ scene: Scene; /** * The scene visibility culler: per-camera light visibility, mesh-instance culling (request / * execute) and shadow-caster culling. * * @type {Culler} * @ignore */ culler: Culler; /** * @type {WorldClustersAllocator} * @ignore */ worldClustersAllocator: WorldClustersAllocator; /** * A list of all unique lights in the layer composition. * * @type {Light[]} */ lights: Light[]; /** * A list of all unique local lights (spot & omni) in the layer composition. * * @type {Light[]} */ localLights: Light[]; /** * Formats of the view uniform buffer, by clustered lighting mode and then by the light layout * of the pass they serve. See {@link Renderer#getViewUniformFormat}. * * @type {Map[]} */ _viewUniformFormats: Map[]; /** * The uniforms of each light slot, by slot index. See {@link Renderer#getLightSlotUniforms}. * * @type {LightSlotUniforms[]} */ _lightSlotUniforms: LightSlotUniforms[]; /** * Shared non-persistent view uniform buffers, keyed by their uniform format, one per view * index. Reused every frame, with the storage sourced from the dynamic buffer system. A * multiview pass fills one per view, as the view bind groups holding textures hold the buffer * of their view. * * @type {WeakMap} */ _viewUniformBuffers: WeakMap; /** * All view bind groups holding textures, destroyed with the renderer. * * @type {BindGroup[]} */ _viewTextureBindGroups: BindGroup[]; /** * Counts the passes set up by {@link Renderer#setupViewUniformBuffers}, so that a view bind * group holding textures updates once per pass. * * @type {number} */ _viewPass: number; /** * The number of views of the current pass, or 0 when it is not multiview. * * @type {number} */ _passViewCount: number; /** * The view uniform buffers of the current pass, one per view. * * @type {ViewUniformBuffer[]} */ _passViewUniformBuffers: ViewUniformBuffer[]; /** * The format of the view bind group bound by the current pass, or null for the bind group of * just the view uniform buffer. * * @type {BindGroupFormat|null} */ _boundViewBindGroupFormat: BindGroupFormat | null; /** * True when the current pass has bound the empty bind group at the mesh bind group index. * * @type {boolean} */ _emptyMeshBindGroupBound: boolean; /** * True when the current pass has bound a mesh uniform buffer of a shader without mesh uniforms, * which the draws of such shaders then share, see {@link Shader#meshUniformBufferEmpty}. * * @type {boolean} * @private */ private _emptyMeshUniformBufferBound; /** * The version of the mesh instance storage the view bind groups of the current pass were updated * with, see {@link Renderer#updateStorageSlot}. * * @type {number} * @private */ private _meshInstanceStorageVersion; /** * Reusable receiver for a view uniform buffer's dynamic bind group + offset. * * @type {DynamicBindGroup} */ _dynamicViewBindGroup: DynamicBindGroup; /** * The dynamic bind group of just the view uniform buffer, of each view of the current multiview * pass (allocations may span dynamic buffers, so the bind group is captured per view alongside * its offset). * * @type {BindGroup[]} */ _passDynamicViewBindGroups: BindGroup[]; /** @type {number[]} */ _passDynamicViewOffsets: number[]; /** * The view bind group of each view of the current multiview pass, for the shader set last, * which the forward render loop binds per view. * * @type {BindGroup[]} */ _viewBindGroups: BindGroup[]; /** @type {number[]} */ _viewBindGroupOffsets: number[]; /** * Reused single-element array passed as the dynamic offsets to per-view setBindGroup, to avoid * per-draw allocation. A typed array, as the device passes it to WebGPU without conversion. * * @type {Uint32Array} */ _viewOffsetScratch: Uint32Array; blueNoise: BlueNoise; /** * A gsplat director for unified splat rendering. * * @type {GSplatDirector|null} */ gsplatDirector: GSplatDirector | null; device: GraphicsDevice; lightTextureAtlas: LightTextureAtlas; shadowMapCache: ShadowMapCache; shadowRenderer: ShadowRenderer; _shadowRendererLocal: ShadowRendererLocal; _shadowRendererDirectional: ShadowRendererDirectional; _renderPassUpdateClustered: FramePassUpdateClustered; _skinTime: number; _morphTime: number; _cullTime: number; _shadowMapTime: number; _lightClustersTime: number; _layerCompositionUpdateTime: number; _shadowDrawCalls: number; _skinDrawCalls: number; _instancedDrawCalls: number; _shadowMapUpdates: number; _numDrawCallsCulled: number; _camerasRendered: number; _lightClusters: number; _gsplatCount: number; boneTextureId: ScopeId; modelMatrixId: ScopeId; normalMatrixId: ScopeId; viewInvId: ScopeId; viewPos: Float32Array; viewPosId: ScopeId; projId: ScopeId; projSkyboxId: ScopeId; viewId: ScopeId; viewId3: ScopeId; viewProjId: ScopeId; flipYId: ScopeId; tbnBasis: ScopeId; cameraParams: Float32Array; cameraParamsId: ScopeId; viewportSize: Float32Array; viewportSizeId: ScopeId; viewIndexId: ScopeId; blueNoiseJitterVersion: number; blueNoiseJitterVec: Vec4; blueNoiseJitterData: Float32Array; blueNoiseJitterId: ScopeId; blueNoiseTextureId: ScopeId; alphaTestId: ScopeId; exposureId: ScopeId; morphPositionTex: ScopeId; morphNormalTex: ScopeId; morphTexParams: ScopeId; lightCube: LightCube; constantLightCube: ScopeId; destroy(): void; /** * Set up the viewport and the scissor for camera rendering. * * @param {Camera} camera - The camera containing the viewport information. * @param {RenderTarget} [renderTarget] - The render target. NULL for the default one. */ setupViewport(camera: Camera, renderTarget?: RenderTarget): void; setCameraUniforms(camera: any, target: any): any; /** * Clears the active render target. If the viewport is already set up, only its area is cleared. * * @param {Camera} camera - The camera supplying the value to clear to. * @param {boolean} [clearColor] - True if the color buffer should be cleared. Uses the value * from the camera if not supplied. * @param {boolean} [clearDepth] - True if the depth buffer should be cleared. Uses the value * from the camera if not supplied. * @param {boolean} [clearStencil] - True if the stencil buffer should be cleared. Uses the * value from the camera if not supplied. */ clear(camera: Camera, clearColor?: boolean, clearDepth?: boolean, clearStencil?: boolean): void; setupCullModeAndFrontFace(cullFaces: any, flipFactor: any, drawCall: any): void; setupCullMode(cullFaces: any, flipFactor: any, drawCall: any): void; updateCpuSkinMatrices(drawCalls: any): void; /** * Update skin matrices ahead of rendering. * * @param {MeshInstance[]|Set} drawCalls - MeshInstances containing skinInstance. * @ignore */ updateGpuSkinMatrices(drawCalls: MeshInstance[] | Set): void; /** * Update morphing ahead of rendering. * * @param {MeshInstance[]|Set} drawCalls - MeshInstances containing morphInstance. * @ignore */ updateMorphing(drawCalls: MeshInstance[] | Set): void; /** * Update gsplats ahead of rendering. * * @param {MeshInstance[]|Set} drawCalls - MeshInstances containing gsplatInstances. * @ignore */ updateGSplats(drawCalls: MeshInstance[] | Set): void; /** * Update draw calls ahead of rendering. * * @param {MeshInstance[]|Set} drawCalls - MeshInstances requiring updates. * @ignore */ gpuUpdate(drawCalls: MeshInstance[] | Set): void; setVertexBuffers(device: any, mesh: any): void; setMorphing(device: any, morphInstance: any): void; setSkinning(device: any, meshInstance: any): void; dispatchViewPos(position: any): void; /** * Returns the format of the view uniform buffer of a pass: the view uniforms, the clustered * lighting parameters when enabled, and the uniforms of the lights of the pass. A light's * uniforms are the same for every mesh instance drawn, so they travel with the view, uploaded * once per pass, instead of in the per-draw mesh uniform buffer. The formats are cached by the * light layout, which the light list key identifies - as does the shader variant, so a shader is * only ever processed against the format of the passes it draws in. * * @param {boolean} isClustered - Whether clustered lighting is enabled. * @param {LightList} lightList - The lights of the pass. * @returns {UniformBufferFormat} The format. */ getViewUniformFormat(isClustered: boolean, lightList: LightList): UniformBufferFormat; /** * Returns the uniforms of a light slot - `light_*` - creating them on first use. A slot * is a position in the light list of a pass rather than a light, so the instances are few and * live as long as the renderer: the view uniform format declares from them whatever the light * holding the slot needs, and the light dispatch writes its values through them. * * @param {number} slot - The light slot. * @returns {LightSlotUniforms} The uniforms of the slot. */ getLightSlotUniforms(slot: number): LightSlotUniforms; /** * Set up uniforms for an XR view. */ setupViewUniforms(view: any, index: any): void; /** * Returns the shared non-persistent view uniform buffer for the given format and view index, * creating it on first use. * * @param {UniformBufferFormat} viewUniformFormat - The view uniform buffer format. * @param {number} viewIndex - The index of the view, 0 when the pass is not multiview. * @returns {ViewUniformBuffer} The shared view uniform buffer. */ getViewUniformBuffer(viewUniformFormat: UniformBufferFormat, viewIndex: number): ViewUniformBuffer; /** * Sets up the shared (per-format) view uniform buffer for the current camera, which starts a * pass. For a single view it updates the buffer and binds it immediately; for multiview (XR) * it updates a buffer per view and captures the per-view bind group and dynamic offset, which * the forward render loop then binds per draw. The bind group and dynamic offset come from the * dynamic buffer system. A shader reading textures in the view bind group binds its own group * at the shader switch, see {@link Renderer#setupViewBindGroup}. * * @param {UniformBufferFormat} viewUniformFormat - The view uniform buffer format. * @param {RenderView[]|null} viewList - The list of XR views for multiview, or null for a * single view. */ setupViewUniformBuffers(viewUniformFormat: UniformBufferFormat, viewList: RenderView[] | null): void; /** * The bind group bound at the material bind group index by the current pass, or null. * * @type {BindGroup|null} * @private */ private _boundMaterialBindGroup; /** * Binds the view bind group a shader expects, called after each shader switch. The textures * the renderer supplies per pass are in the view bind group of a shader reading them, * following the view uniform buffer - one bind group per format and view, updated once per * pass, see {@link ShaderProcessorOptions#viewTextures}. Other shaders use the bind group of * just the view uniform buffer. Rebinds only when the format differs from the one bound. * * @param {Shader} shader - The shader set on the device. * @param {boolean} [force] - True to bind the view bind group even when its format is bound, * used when the resources it holds changed. Defaults to false. */ setupViewBindGroup(shader: Shader, force?: boolean): void; /** * Returns the view bind group of a view uniform buffer holding the textures of a format, * creating it on first use, and updated once per pass: the textures are taken from the scope * and the uniform buffer offset from its allocation for the pass. * * @param {ViewUniformBuffer} viewUniformBuffer - The view uniform buffer. * @param {BindGroupFormat} format - The format of the view bind group. * @param {number} pass - The current pass. * @returns {BindGroup} The bind group. * @private */ private getViewTextureBindGroup; /** * Binds the bind group of a material at the material bind group index, or the empty bind group * for a material without one so the pipeline layout has no gap. Called at a material switch, * and again after a draw that bound a mesh instance's copy of the material uniform buffer. * Rebinds only when the group differs from the one bound by the previous draw. * * @param {Material} material - The material. */ setupMaterialBindGroup(material: Material): void; /** * Binds a mesh instance's copy of the material uniform buffer, with the uniforms it overrides * applied, at the material bind group index. Only called for a mesh instance that overrides * some of them, or whose parameters need splitting against a changed material layout, see * {@link Renderer#needsMaterialOverrideBindGroup}. * * @param {MeshInstance} meshInstance - The mesh instance being drawn. */ setupMaterialOverrideBindGroup(meshInstance: MeshInstance): void; /** * Unsets the overrides of a mesh instance back to the values of its material, after its draw * when the next draw uses the same material, which then keeps the state the material switch * set: the material bind group when the mesh instance bound its copy of it, and the scope * parameters. The alpha test reference is set from the material by the renderer rather than * being a material parameter, so it is restored with them. * * @param {MeshInstance} meshInstance - The mesh instance drawn. * @param {Material} material - Its material. */ restoreMaterialOverrides(meshInstance: MeshInstance, material: Material): void; /** * True when this mesh instance overrides something in the material's bind group, and so a draw * of it binds its own copy of that group. Kept to field reads, as this runs for every draw. * * @param {MeshInstance} meshInstance - The mesh instance being drawn. * @returns {boolean} True when the mesh instance overrides a uniform or a texture. */ hasMaterialOverrides(meshInstance: MeshInstance): boolean; /** * True when a draw of this mesh instance needs its own copy of the material's bind group: it * overrides something in it, or the set of typed properties of the material changed and its * parameters need splitting against the new layout again. Kept to field reads, as this runs for * every draw. * * @param {MeshInstance} meshInstance - The mesh instance being drawn. * @param {Material} material - Its material. * @returns {boolean} True when the copy is needed. */ needsMaterialOverrideBindGroup(meshInstance: MeshInstance, material: Material): boolean; setupMeshUniformBuffers(shaderInstance: any): void; /** * Returns the slot of a mesh instance in the mesh instance storage of the device, for a draw * with a shader reading it, which passes the slot as the first instance of the draw, see * {@link Shader#usesMeshInstanceStorage}. The slot is allocated on the first such draw, and its * matrices are written when the transform of the node changed since they were last written, or * when the mesh instance was given a different node. When the allocation grows the storage, the * view bind group of the shader, which holds the storage, is updated and bound again. * * @param {MeshInstance} meshInstance - The mesh instance being drawn. * @param {Shader} shader - The shader of the draw, set on the device. * @returns {number} The slot. */ updateStorageSlot(meshInstance: MeshInstance, shader: Shader): number; setMeshInstanceMatrices(meshInstance: any, setNormalMatrix?: boolean): void; collectLights(comp: any): void; /** * @param {MeshInstance[]} drawCalls - Mesh instances. * @param {boolean} onlyLitShaders - Limits the update to shaders affected by lighting. */ updateShaders(drawCalls: MeshInstance[], onlyLitShaders: boolean): void; updateFrameUniforms(): void; /** * @param {LayerComposition} comp - The layer composition to update. */ beginFrame(comp: LayerComposition): void; updateLightTextureAtlas(): void; /** * Updates the layer composition for rendering. * * @param {LayerComposition} comp - The layer composition to update. */ updateLayerComposition(comp: LayerComposition): void; frameUpdate(): void; } /** * A view uniform buffer, together with the view bind groups holding it with textures. * * @ignore */ declare class ViewUniformBuffer { /** * @param {UniformBuffer} uniformBuffer - The view uniform buffer. */ constructor(uniformBuffer: UniformBuffer); /** @type {UniformBuffer} */ uniformBuffer: UniformBuffer; /** * The view bind groups holding textures, by their format. * * @type {Map} */ textureBindGroups: Map; } /** * A view bind group holding textures, see {@link Renderer#setupViewBindGroup}. * * @ignore */ declare class ViewTextureBindGroup { /** * @param {BindGroup} bindGroup - The bind group. */ constructor(bindGroup: BindGroup); /** @type {BindGroup} */ bindGroup: BindGroup; /** * The pass the bind group was last updated in, see {@link Renderer#_viewPass}. * * @type {number} */ pass: number; } /** * @import { Layer } from '../layer.js' */ declare class WorldClustersDebug { gridPositions: any[]; gridColors: any[]; mesh: any; meshInstance: any; /** @type {MeshInstance|null} */ _pendingMeshInstance: MeshInstance | null; /** @type {Layer|null} */ _layer: Layer | null; colorLow: Vec3; colorHigh: Vec3; frameUpdate(): void; /** * @param {Layer} layer - The layer being rendered. * @param {MeshInstance[]} visibleList - The visible mesh instances for the layer. */ onPreRenderLayer(layer: Layer, visibleList: MeshInstance[]): void; render(worldClusters: any, scene: any): void; destroy(): void; } /** * The forward renderer renders {@link Scene}s. * * @ignore */ declare class ForwardRenderer extends Renderer { static skipRenderCamera: any; static _skipRenderCounter: number; static skipRenderAfter: number; /** @type {WorldClustersDebug|null} */ _worldClustersDebug: WorldClustersDebug | null; /** * Limits how much of one render pass is drawn, for stepping through its draw calls with a * debugging tool. Matched by the camera and render target the pass renders with; for each layer * of the pass, an entry per sub-layer (opaque, transparent) gives either how many of its sorted * instances to draw, or `{ instance, index }` to draw up to and including that instance, found * by identity and falling back to the index when it was culled. Layers without an entry draw in * full. Only honored by the debug engine; other builds ignore it. * * @type {{ camera: Camera, renderTarget: RenderTarget|null, layers: Map> }|null} * @ignore */ debugDrawLimit: { camera: Camera; renderTarget: RenderTarget | null; layers: Map>; } | null; /** * Whether this build honors {@link debugDrawLimit}, which only the debug engine does. * * @type {boolean} * @ignore */ debugDrawLimitSupported: boolean; _forwardDrawCalls: number; _materialSwitches: number; _depthMapTime: number; _forwardTime: number; _sortTime: number; fogColorId: ScopeId; fogStartId: ScopeId; fogEndId: ScopeId; fogDensityId: ScopeId; ambientId: ScopeId; skyboxIntensityId: ScopeId; cubeMapRotationMatrixId: ScopeId; sceneEnvAtlasId: ScopeId; sceneSkyboxId: ScopeId; pcssDiskSamplesId: ScopeId; pcssSphereSamplesId: ScopeId; screenSizeId: ScopeId; screenSizeLegacyId: ScopeId; _screenSize: Float32Array; fogColor: Float32Array; ambientColor: Float32Array; pcssDiskSamples: number[]; pcssSphereSamples: number[]; /** * @param {Scene} scene - The scene. */ dispatchGlobalLights(scene: Scene): void; /** * Sets the uniforms of the lights of a pass, each at its light slot. The slot order is the * same for every mesh instance in the pass whatever its light mask selects, so this runs once * per pass, before the view uniform buffer is filled - the light uniforms are part of it, see * {@link Renderer#getViewUniformFormat} - and each shader reads its own slots. The shader * generator reads the same list, so the two cannot disagree about which light a slot holds. * * @param {LightList} lightList - The lights of the pass. * @param {Camera} camera - The camera, for the shadow data rendered for it. */ dispatchLights(lightList: LightList, camera: Camera): void; renderForwardPrepareMaterials(camera: any, renderTarget: any, drawCalls: any, lightList: any, layer: any, pass: any, viewUniformFormat: any): { drawCalls: any[]; shaderInstances: any[]; isNewMaterial: any[]; clear: () => void; }; renderForwardInternal(camera: any, preparedCalls: any, pass: any, drawCallback: any, flipFaces: any): void; renderForward(camera: any, renderTarget: any, allDrawCalls: any, lightList: any, pass: any, drawCallback: any, layer: any, flipFaces: any, viewUniformFormat: any): void; /** * Forward render mesh instances on a specified layer, using a camera and a render target. * Shaders used are based on the shaderPass provided, with optional clustered lighting support. * * @param {Camera} camera - The camera. * @param {RenderTarget|undefined} renderTarget - The render target. * @param {Layer} layer - The layer. * @param {boolean} transparent - True if transparent sublayer should be rendered, opaque * otherwise. * @param {number} shaderPass - A type of shader to use during rendering. * @param {object} [options] - Object for passing optional arguments. * @param {boolean} [options.clearColor] - True if the color buffer should be cleared. * @param {boolean} [options.clearDepth] - True if the depth buffer should be cleared. * @param {boolean} [options.clearStencil] - True if the stencil buffer should be cleared. * @param {WorldClusters} [options.lightClusters] - The world clusters object to be used for * clustered lighting. * @param {MeshInstance[]} [options.meshInstances] - The mesh instances to be rendered. Use * when layer is not provided. * @param {LightList} [options.lightList] - The lights to render with. Use when layer is not * provided; none by default. * @param {Function} [options.drawCallback] - Function called before each mesh instance is * rendered, with the mesh instance as the argument. * @param {UniformBufferFormat} [options.viewUniformFormat] - A custom view uniform buffer * format to use for this layer. When not provided, the renderer's format for the lights of the * pass is used, see {@link Renderer#getViewUniformFormat}. The shaders are processed and the * view uniform buffer is set up using the same format, so they always match. */ renderForwardLayer(camera: Camera, renderTarget: RenderTarget | undefined, layer: Layer, transparent: boolean, shaderPass: number, options?: { clearColor?: boolean; clearDepth?: boolean; clearStencil?: boolean; lightClusters?: WorldClusters; meshInstances?: MeshInstance[]; lightList?: LightList; drawCallback?: Function; viewUniformFormat?: UniformBufferFormat; }): void; setFogConstants(fogParams: any): void; setSceneConstants(): void; /** * Builds a frame graph for the rendering of the whole frame. * * @param {FrameGraph} frameGraph - The frame-graph that is built. * @param {LayerComposition} layerComposition - The layer composition used to build the frame * graph. * @ignore */ buildFrameGraph(frameGraph: FrameGraph, layerComposition: LayerComposition): void; /** * @param {any} camera - The camera component for the current render action. The XR data lives on * the underlying `Camera` (`CameraComponent.camera`), as `xrActive` / `xrViews`, not on the * component itself, so we dereference it before checking. * @returns {boolean} True if the camera should have its passes replicated per XR view (currently * gated to the WebGPU backend; other backends keep the existing single-pass multi-viewport flow). * @private */ private _isMultiview; /** * @param {FrameGraph} frameGraph - The frame graph. * @param {LayerComposition} layerComposition - The layer composition. */ addMainRenderPass(frameGraph: FrameGraph, layerComposition: LayerComposition, renderTarget: any, startIndex: any, endIndex: any): void; /** * Build a {@link LayerRenderStep} from a composition {@link RenderAction}. This is the only * place that bridges the internal RenderAction scheduling type to the render pass's own * LayerRenderStep, so neither RenderPassForward nor LayerRenderStep reference RenderAction. * * @param {RenderAction} renderAction - The composition render action. * @returns {LayerRenderStep} The layer render step. * @private */ private _layerRenderStepFromRenderAction; /** * @param {LayerComposition} comp - The layer composition. */ update(comp: LayerComposition): void; /** * Visibility culling of mesh instances and shadow casters, followed by GPU data updates for the * resulting visible objects, and consuming one-shot shadow updates. Runs after the frame graph * has been built (which is itself after {@link ForwardRenderer#update}), so shadow-pass building * and shadow-caster culling have both read the shadow update mode before it is consumed here. * * @param {LayerComposition} comp - The layer composition. */ cull(comp: LayerComposition): void; } declare class LightmapFilters { constructor(device: any); shaderDilate: any[]; shaderDenoise: any[]; device: any; constantTexSource: any; constantPixelOffset: any; pixelOffset: Float32Array; sigmas: Float32Array; constantSigmas: any; kernel: any; setSourceTexture(texture: any): void; prepare(textureWidth: any, textureHeight: any): void; prepareDenoise(filterRange: any, filterSmoothness: any, bakeHDR: any): void; constantKernel: any; bZnorm: any; getDenoise(bakeHDR: any): any; getDilate(device: any, bakeHDR: any): any; evaluateDenoiseUniforms(filterRange: any, filterSmoothness: any): void; } /** * The lightmapper is used to bake scene lights into textures. * * @category Graphics */ declare class Lightmapper { /** * Create a new Lightmapper instance. * * @param {GraphicsDevice} device - The graphics device used by the lightmapper. * @param {Entity} root - The root entity of the scene. * @param {Scene} scene - The scene to lightmap. * @param {ForwardRenderer} renderer - The renderer. * @param {AssetRegistry} assets - Registry of assets to lightmap. * @ignore */ constructor(device: GraphicsDevice, root: Entity, scene: Scene, renderer: ForwardRenderer, assets: AssetRegistry); device: GraphicsDevice; root: Entity; scene: Scene; renderer: ForwardRenderer; assets: AssetRegistry; shadowMapCache: ShadowMapCache; _tempSet: Set; _initCalled: boolean; passMaterials: any[]; ambientAOMaterial: StandardMaterial; fog: string; ambientLight: Color; renderTargets: Map; stats: { renderPasses: number; lightmapCount: number; totalRenderTime: number; forwardTime: number; fboTime: number; shadowMapTime: number; compileTime: number; shadersLinked: number; }; destroy(): void; blackTex: Texture; camera: Camera; initBake(device: any): void; bakeHDR: boolean; lightmapFilters: LightmapFilters; constantBakeDir: any; materials: any[]; lightingParams: LightingParams; worldClusters: WorldClusters; shadowLocalClusteredPass: RenderPassShadowLocalClustered; finishBake(bakeNodes: any): void; createMaterialForPass(scene: any, pass: any, addAmbient: any): StandardMaterial; createMaterials(device: any, scene: any, passCount: any): void; createTexture(size: any, name: any): Texture; collectModels(node: any, bakeNodes: any, allNodes: any): void; prepareShadowCasters(nodes: any): any[]; updateTransforms(nodes: any): void; calculateLightmapSize(node: any): number; setLightmapping(nodes: any, value: any, passCount: any, shaderDefs: any): void; /** * Generates and applies the lightmaps. * * @param {Entity[]|null} nodes - An array of entities (with model or render components) to * render lightmaps for. If not supplied, the entire scene will be baked. * @param {number} [mode] - Baking mode. Can be: * * - {@link BAKE_COLOR}: single color lightmap * - {@link BAKE_COLORDIR}: single color lightmap + dominant light direction (used for * bump/specular) * * Only lights with bakeDir=true will be used for generating the dominant light direction. * Defaults to {@link BAKE_COLORDIR}. */ bake(nodes: Entity[] | null, mode?: number): void; allocateTextures(bakeNodes: any, passCount: any): void; prepareLightsToBake(allLights: any, bakeLights: any): void; restoreLights(allLights: any): void; setupScene(): void; restoreScene(): void; computeNodeBounds(meshInstances: any): BoundingBox; computeNodesBounds(nodes: any): void; computeBounds(meshInstances: any): BoundingBox; backupMaterials(meshInstances: any): void; restoreMaterials(meshInstances: any): void; lightCameraPrepare(device: any, bakeLight: any): any; lightCameraPrepareAndCull(bakeLight: any, bakeNode: any, shadowCam: any, casterBounds: any): boolean; setupLightList(lightList: any, light: any, clustered: any): void; renderShadowMap(comp: any, shadowMapRendered: any, casters: any, bakeLight: any): boolean; postprocessTextures(device: any, bakeNodes: any, passCount: any): void; bakeInternal(passCount: any, bakeNodes: any, allNodes: any): void; } /** * Item to be stored in the {@link SceneRegistry}. * * @category Graphics */ declare class SceneRegistryItem { /** * Creates a new SceneRegistryItem instance. * * @param {string} name - The name of the scene. * @param {string} url - The url of the scene file. */ constructor(name: string, url: string); /** * The name of the scene. * * @type {string} */ name: string; /** * The url of the scene file. * * @type {string} */ url: string; /** @ignore */ data: any; /** @private */ private _loading; /** @private */ private _onLoadedCallbacks; /** * Returns true if the scene data has loaded. * * @type {boolean} */ get loaded(): boolean; /** * Returns true if the scene data is still being loaded. * * @type {boolean} */ get loading(): boolean; } /** * Callback used by {@link SceneRegistry#loadSceneHierarchy}. */ type LoadHierarchyCallback = (err: string | null, entity?: Entity) => void; /** * Callback used by {@link SceneRegistry#loadSceneSettings}. */ type LoadSettingsCallback = (err: string | null) => void; /** * Callback used by {@link SceneRegistry#changeScene}. */ type ChangeSceneCallback = (err: string | null, entity?: Entity) => void; /** * Callback used by {@link SceneRegistry#loadScene}. */ type LoadSceneCallback = (err: string | null, entity?: Entity) => void; /** * Callback used by {@link SceneRegistry#loadSceneData}. */ type LoadSceneDataCallback = (err: string | null, sceneItem?: SceneRegistryItem) => void; /** * @import { AppBase } from './app-base.js' * @import { Entity } from './entity.js' */ /** * @callback LoadHierarchyCallback * Callback used by {@link SceneRegistry#loadSceneHierarchy}. * @param {string|null} err - The error message in the case where the loading or parsing fails. * @param {Entity} [entity] - The loaded root entity if no errors were encountered. * @returns {void} */ /** * @callback LoadSettingsCallback * Callback used by {@link SceneRegistry#loadSceneSettings}. * @param {string|null} err - The error message in the case where the loading or parsing fails. * @returns {void} */ /** * @callback ChangeSceneCallback * Callback used by {@link SceneRegistry#changeScene}. * @param {string|null} err - The error message in the case where the loading or parsing fails. * @param {Entity} [entity] - The loaded root entity if no errors were encountered. * @returns {void} */ /** * @callback LoadSceneCallback * Callback used by {@link SceneRegistry#loadScene}. * @param {string|null} err - The error message in the case where the loading or parsing fails. * @param {Entity} [entity] - The loaded root entity if no errors were encountered. * @returns {void} */ /** * @callback LoadSceneDataCallback * Callback used by {@link SceneRegistry#loadSceneData}. * @param {string|null} err - The error message in the case where the loading or parsing fails. * @param {SceneRegistryItem} [sceneItem] - The scene registry item if no errors were encountered. * @returns {void} */ /** * Container for storing and loading of scenes. An instance of the registry is created on the * {@link AppBase} object as {@link AppBase#scenes}. * * @category Graphics */ declare class SceneRegistry { /** * Create a new SceneRegistry instance. * * @param {AppBase} app - The application. */ constructor(app: AppBase); /** * @type {AppBase} * @private */ private _app; /** * @type {SceneRegistryItem[]} * @private */ private _list; /** @private */ private _index; /** @private */ private _urlIndex; /** @ignore */ destroy(): void; /** * Return the list of scene. * * @returns {SceneRegistryItem[]} All items in the registry. */ list(): SceneRegistryItem[]; /** * Add a new item to the scene registry. * * @param {string} name - The name of the scene. * @param {string} url - The url of the scene file. * @returns {boolean} Returns true if the scene was successfully added to the registry, false otherwise. */ add(name: string, url: string): boolean; /** * Find a Scene by name and return the {@link SceneRegistryItem}. * * @param {string} name - The name of the scene. * @returns {SceneRegistryItem|null} The stored data about a scene or null if no scene with * that name exists. */ find(name: string): SceneRegistryItem | null; /** * Find a scene by the URL and return the {@link SceneRegistryItem}. * * @param {string} url - The URL to search by. * @returns {SceneRegistryItem|null} The stored data about a scene or null if no scene with * that URL exists. */ findByUrl(url: string): SceneRegistryItem | null; /** * Remove an item from the scene registry. * * @param {string} name - The name of the scene. */ remove(name: string): void; /** * Private function to load scene data with the option to cache. This allows us to retain * expected behavior of loadSceneSettings and loadSceneHierarchy where they don't store loaded * data which may be undesired behavior with projects that have many scenes. * * @param {SceneRegistryItem | string} sceneItem - The scene item (which can be found with * {@link find}, URL of the scene file (e.g."scene_id.json") or name of the scene. * @param {boolean} storeInCache - Whether to store the loaded data in the scene item. * @param {LoadSceneDataCallback} callback - The function to call after loading, * passed (err, sceneItem) where err is null if no errors occurred. * @private */ private _loadSceneData; /** * Loads and stores the scene data to reduce the number of the network requests when the same * scenes are loaded multiple times. Can also be used to load data before calling * {@link loadSceneHierarchy} and {@link loadSceneSettings} to make scene loading quicker for * the user. * * @param {SceneRegistryItem | string} sceneItem - The scene item (which can be found with * {@link find}, URL of the scene file (e.g."scene_id.json") or name of the scene. * @param {LoadSceneDataCallback} callback - The function to call after loading, * passed (err, sceneItem) where err is null if no errors occurred. * @example * const sceneItem = app.scenes.find("Scene Name"); * app.scenes.loadSceneData(sceneItem, (err, sceneItem) => { * if (err) { * // error * } * }); */ loadSceneData(sceneItem: SceneRegistryItem | string, callback: LoadSceneDataCallback): void; /** * Unloads scene data that has been loaded previously using {@link loadSceneData}. * * @param {SceneRegistryItem | string} sceneItem - The scene item (which can be found with * {@link find} or URL of the scene file. Usually this will be "scene_id.json". * @example * const sceneItem = app.scenes.find("Scene Name"); * app.scenes.unloadSceneData(sceneItem); */ unloadSceneData(sceneItem: SceneRegistryItem | string): void; _loadSceneHierarchy(sceneItem: any, onBeforeAddHierarchy: any, callback: any): void; /** * Load a scene file, create and initialize the Entity hierarchy and add the hierarchy to the * application root Entity. * * @param {SceneRegistryItem | string} sceneItem - The scene item (which can be found with * {@link find}, URL of the scene file (e.g."scene_id.json") or name of the scene. * @param {LoadHierarchyCallback} callback - The function to call after loading, * passed (err, entity) where err is null if no errors occurred. * @example * const sceneItem = app.scenes.find("Scene Name"); * app.scenes.loadSceneHierarchy(sceneItem, (err, entity) => { * if (!err) { * const e = app.root.find("My New Entity"); * } else { * // error * } * }); */ loadSceneHierarchy(sceneItem: SceneRegistryItem | string, callback: LoadHierarchyCallback): void; /** * Load a scene file and apply the scene settings to the current scene. * * @param {SceneRegistryItem | string} sceneItem - The scene item (which can be found with * {@link find}, URL of the scene file (e.g."scene_id.json") or name of the scene. * @param {LoadSettingsCallback} callback - The function called after the settings * are applied. Passed (err) where err is null if no error occurred. * @example * const sceneItem = app.scenes.find("Scene Name"); * app.scenes.loadSceneSettings(sceneItem, (err) => { * if (!err) { * // success * } else { * // error * } * }); */ loadSceneSettings(sceneItem: SceneRegistryItem | string, callback: LoadSettingsCallback): void; /** * Change to a new scene. Calling this function will load the scene data, delete all * entities and graph nodes under `app.root` and load the scene settings and hierarchy. * * @param {SceneRegistryItem | string} sceneItem - The scene item (which can be found with * {@link find}, URL of the scene file (e.g."scene_id.json") or name of the scene. * @param {ChangeSceneCallback} [callback] - The function to call after loading, * passed (err, entity) where err is null if no errors occurred. * @example * app.scenes.changeScene("Scene Name", (err, entity) => { * if (!err) { * // success * } else { * // error * } * }); */ changeScene(sceneItem: SceneRegistryItem | string, callback?: ChangeSceneCallback): void; /** * Load the scene hierarchy and scene settings. This is an internal method used by the * {@link AppBase}. * * @param {string} url - The URL of the scene file. * @param {LoadSceneCallback} callback - The function called after the settings are * applied. Passed (err, scene) where err is null if no error occurred and scene is the * {@link Scene}. */ loadScene(url: string, callback: LoadSceneCallback): void; } /** * @import { WebglGraphicsDevice } from './webgl-graphics-device.js' */ /** * A WebGL implementation of a dynamic buffer - a single whole uniform buffer that is handed out * from a pool for one frame at a time. The data is written into the CPU-side storage views of the * buffer and uploaded with `bufferData` (a full respecify), which orphans the previous storage and lets the * driver hand back fresh storage - so reusing a buffer never stalls on in-flight draws. As each use * gets its own buffer, the offset into it is always zero. * * @ignore */ declare class WebglDynamicBuffer extends DynamicBuffer { /** * @param {WebglGraphicsDevice} device - The graphics device. * @param {number} size - The byte size of the buffer. */ constructor(device: WebglGraphicsDevice, size: number); /** * The GL buffer object (mirrors WebgpuDynamicBuffer.buffer). Created lazily on the first * upload, so it is also recreated automatically after a context loss nulls it. * * @type {WebGLBuffer|null} */ bufferId: WebGLBuffer | null; /** * Byte size of the buffer. * * @type {number} */ size: number; destroy(device: any): void; /** * Called when the rendering context is lost. The GL buffer is gone with the context, so drop * the handle; the next upload recreates it. The CPU storage and pooling are preserved. */ loseContext(): void; } /** * @import { DynamicBufferAllocation } from '../dynamic-buffers.js' * @import { WebglGraphicsDevice } from './webgl-graphics-device.js' */ /** * A WebGL implementation of the dynamic buffers system. Unlike WebGPU (which sub-allocates from * large mapped pages and copies them to the GPU at submit time), WebGL2 has no buffer mapping and * executes draws immediately. So instead this hands out a whole {@link WebglDynamicBuffer} per * allocation from a pool keyed by size, and the buffer uploads its data eagerly using `bufferData` * (orphaning). Each buffer is handed out at most once per frame and returned to the free pool at * the end of the frame, which - together with orphaning - gives distinct buffers for uses that are * live at the same time (e.g. XR multiview eyes) and stall-free reuse across frames. * * @ignore */ declare class WebglDynamicBuffers extends DynamicBuffers { /** * @param {WebglGraphicsDevice} device - The graphics device. */ constructor(device: WebglGraphicsDevice); /** * Free buffers available for allocation, keyed by byte size. * * @type {Map} */ free: Map; /** * Buffers handed out during the current frame, returned to the free pool at frame end. * * @type {WebglDynamicBuffer[]} */ used: WebglDynamicBuffer[]; /** * Return the frame's buffers to the free pool. Called at the end of the frame, so it runs after * all allocations (including any made before frameStart, e.g. from app update handlers). */ onFrameEnd(): void; /** * Called when the rendering context is lost. Returns any in-flight buffers to the free pool and * drops every buffer's GL handle (without deleting - the context is invalid). The buffer objects * and their CPU storage are kept, so they are reused and their GL buffers recreated on the next * upload after the context is restored. */ loseContext(): void; } /** * A WebGL implementation of the Buffer. * * @ignore */ declare class WebglBuffer { bufferId: any; /** @type {Uint8Array|null} */ uploadView: Uint8Array | null; destroy(device: any): void; get initialized(): boolean; loseContext(): void; unlock(device: any, usage: any, target: any, storage: any, byteOffset?: number, byteLength?: number): void; } /** * A WebGL implementation of the VertexBuffer. * * @ignore */ declare class WebglVertexBuffer extends WebglBuffer { vao: any; unlock(vertexBuffer: any, byteOffset: any, byteLength: any): void; } /** * A WebGL implementation of the IndexBuffer. * * @ignore */ declare class WebglIndexBuffer extends WebglBuffer { constructor(indexBuffer: any); glFormat: any; unlock(indexBuffer: any, byteOffset: any, byteLength: any): void; } /** * A WebGL implementation of the Shader. * * @ignore */ declare class WebglShader { constructor(shader: any); compileDuration: number; /** * Free the WebGL resources associated with a shader. * * @param {Shader} shader - The shader to free. */ destroy(shader: Shader): void; glProgram: WebGLProgram; init(): void; uniforms: any[]; samplers: any[]; attributes: any[]; glVertexShader: WebGLShader; glFragmentShader: WebGLShader; _vsource: string; _fsource: string; /** * Dispose the shader when the context has been lost. */ loseContext(): void; /** * Restore shader after the context has been obtained. * * @param {WebglGraphicsDevice} device - The graphics device. * @param {Shader} shader - The shader to restore. */ restoreContext(device: WebglGraphicsDevice, shader: Shader): void; /** * Compile shader programs. * * @param {WebglGraphicsDevice} device - The graphics device. * @param {Shader} shader - The shader to compile. */ compile(device: WebglGraphicsDevice, shader: Shader): void; processed: { vshader: string; fshader: string; }; /** * Link shader programs. This is called at a later stage, to allow many shaders to compile in parallel. * * @param {WebglGraphicsDevice} device - The graphics device. * @param {Shader} shader - The shader to compile. */ link(device: WebglGraphicsDevice, shader: Shader): void; /** * Compiles an individual shader. * * @param {WebglGraphicsDevice} device - The graphics device. * @param {string} src - The shader source code. * @param {boolean} isVertexShader - True if the shader is a vertex shader, false if it is a * fragment shader. * @returns {WebGLShader|null} The compiled shader, or null if the device is lost. * @private */ private _compileShaderSource; /** * Link the shader, and extract its attributes and uniform information. * * @param {WebglGraphicsDevice} device - The graphics device. * @param {Shader} shader - The shader to query. * @returns {boolean} True if the shader was successfully queried and false otherwise. */ finalize(device: WebglGraphicsDevice, shader: Shader): boolean; /** * Check the compilation status of a shader. * * @param {WebglGraphicsDevice} device - The graphics device. * @param {Shader} shader - The shader to query. * @param {WebGLShader} glShader - The WebGL shader. * @param {string} source - The shader source code. * @param {string} shaderType - The shader type. Can be 'vertex' or 'fragment'. * @returns {boolean} True if the shader compiled successfully, false otherwise. * @private */ private _isCompiled; /** * Check the linking status of a shader. * * @param {WebglGraphicsDevice} device - The graphics device. * @returns {boolean} True if the shader is already linked, false otherwise. Note that unless the * device supports the KHR_parallel_shader_compile extension, this will always return true. */ isLinked(device: WebglGraphicsDevice): boolean; /** * Truncate the WebGL shader compilation log to just include the error line plus the 5 lines * before and after it. * * @param {string} src - The shader source code. * @param {string} infoLog - The info log returned from WebGL on a failed shader compilation. * @returns {Array} An array where the first element is the 10 lines of code around the first * detected error, and the second element an object storing the error message, line number and * complete shader source. * @private */ private _processError; /** * See {@link Shader#debugReadsUniform}. * * @param {Shader} shader - The shader. * @param {string} name - The name of the uniform. * @returns {boolean} Whether the linked program has the uniform active. */ debugReadsUniform(shader: Shader, name: string): boolean; } /** * A WebGL implementation of the UniformBuffer. * * @ignore */ declare class WebglUniformBuffer extends WebglBuffer { unlock(uniformBuffer: any): void; } /** * A WebGL implementation of the BindGroupFormat. * * Uniform buffer binding points on WebGL2 are derived directly from the bind group index (see * {@link WebglGraphicsDevice#setBindGroup} and {@link WebglShader} uniform block linking), so the * format itself needs no GPU-side resources. * * @ignore */ declare class WebglBindGroupFormat { destroy(): void; } /** * A WebGL implementation of the BindGroup. * * On WebGL2 there is no GPU-side bind group object. Instead, at update time this captures - per * uniform buffer slot - the object that owns the GL buffer (the persistent buffer impl, or the * dynamic buffer the uniform buffer is currently allocated from). {@link WebglGraphicsDevice#setBindGroup} * then binds those captured buffers. Capturing here (rather than reading the uniform buffer's live * allocation at draw time) is essential when a single uniform buffer is re-allocated several times * in a frame - e.g. the shared view UB across XR multiview eyes: each eye's bind group must bind * the buffer it was built for, not the buffer the shared uniform buffer ends up pointing at. * * @ignore */ declare class WebglBindGroup { /** * Per uniform-buffer slot, the object exposing the GL buffer via its `bufferId` (a * WebglUniformBuffer for persistent buffers, or a WebglDynamicBuffer for dynamic ones). The GL * buffer is read lazily at bind time, as a dynamic buffer's `bufferId` is created on its first * upload, after this bind group is built. * * @type {Array<{ bufferId: WebGLBuffer|null }>} */ buffers: Array<{ bufferId: WebGLBuffer | null; }>; update(bindGroup: any): void; destroy(): void; } /** * WebGL implementation of DrawCommands. * * @ignore */ declare class WebglDrawCommands { /** * @param {number} indexSizeBytes - Size of index in bytes (1, 2 or 4). 0 for non-indexed. */ constructor(indexSizeBytes: number); /** @type {number} */ indexSizeBytes: number; /** @type {Int32Array|null} */ glCounts: Int32Array | null; /** @type {Int32Array|null} */ glOffsetsBytes: Int32Array | null; /** @type {Int32Array|null} */ glInstanceCounts: Int32Array | null; /** * Allocate SoA arrays for multi-draw. * @param {number} maxCount - Number of sub-draws. */ allocate(maxCount: number): void; /** * Write a single draw entry. * @param {number} i - Draw index. * @param {number} indexOrVertexCount - Count of indices/vertices. * @param {number} instanceCount - Instance count. * @param {number} firstIndexOrVertex - First index/vertex. */ add(i: number, indexOrVertexCount: number, instanceCount: number, firstIndexOrVertex: number): void; /** * Calculate primitives per sub-draw before accumulating, so strip overhead and incomplete * list primitives are handled separately for each instance. * @param {number} count - Number of active draws. * @param {number} type - Primitive topology. * @param {boolean} instanced - Whether to apply per-command instance counts. * @returns {number} Total primitive count. */ getPrimitiveCount(count: number, type: number, instanced: boolean): number; } /** * A WebGL implementation of the Texture. * * @ignore */ declare class WebglTexture { constructor(texture: any); _glTexture: any; _glTarget: any; _glFormat: any; _glInternalFormat: any; _glPixelType: any; _glCreated: any; dirtyParameterFlags: number; /** @type {Texture} */ texture: Texture; destroy(device: any): void; loseContext(): void; propertyChanged(flag: any): void; initialize(device: any, texture: any): void; /** * @param {WebglGraphicsDevice} device - The device. * @param {Texture} texture - The texture to update. */ upload(device: WebglGraphicsDevice, texture: Texture): void; /** * @param {WebglGraphicsDevice} device - The graphics device. * @param {Texture} texture - The texture. */ uploadImmediate(device: WebglGraphicsDevice, texture: Texture): void; read(x: any, y: any, width: any, height: any, options: any): Promise; write(x: any, y: any, width: any, height: any, data: any): any; copy(source: any, options: any): any; } /** * WebGL graphics implementation for {@link XrBridge}. * * @ignore */ declare class WebglXrBridge { /** * @param {XrBridge} xrBridge - The XR bridge. */ constructor(xrBridge: XrBridge); /** * @type {XRWebGLLayer|null} * @private */ private _presentationLayer; /** * @type {XRWebGLBinding|null} * @private */ private _graphicsBinding; /** * Read framebuffer used to blit the XR camera image into the engine texture. * * @type {WebGLFramebuffer|null} * @private */ private _cameraFbSource; /** * Draw framebuffer used to blit the XR camera image into the engine texture. * * @type {WebGLFramebuffer|null} * @private */ private _cameraFbDest; /** @type {XrBridge} */ xrBridge: XrBridge; /** * @param {GraphicsDevice} device - The graphics device. */ destroy(device: GraphicsDevice): void; /** * @param {GraphicsDevice} device - The graphics device. * @private */ private _deleteCameraFramebuffers; /** * Sets the WebGL default framebuffer to the XR session's base layer framebuffer. * When there is no base layer (for example after GPU device loss), falls back to the * canvas framebuffer by assigning null. * * @param {XRFrame} frame - Current XR frame. * @param {XRReferenceSpace|null} _referenceSpace - Active XR reference space. */ beginFrame(frame: XRFrame, _referenceSpace: XRReferenceSpace | null): void; /** * Resets the WebGL default framebuffer to the canvas (null). */ endFrame(): void; /** * @returns {XRWebGLLayer|null} The active XR output layer, if any. */ get presentationLayer(): XRWebGLLayer | null; /** * @returns {XRWebGLBinding|null} The WebXR GL binding for GPU camera/depth paths, if any. */ get graphicsBinding(): XRWebGLBinding | null; /** * @param {XRFrame} frame - Current XR frame. * @param {Vec2} out - Width in {@link Vec2#x}, height in {@link Vec2#y}. */ getFramebufferSize(frame: XRFrame, out: Vec2): void; /** * @param {XRFrame} frame - Current XR frame. * @param {XRView} xrView - WebXR view. * @returns {XRViewport} Viewport from the session base layer, or zeros if the base layer is unavailable. */ getViewport(frame: XRFrame, xrView: XRView): XRViewport; /** * @param {XRSession} session - XR session. * @param {object} options - Presentation options. * @param {number} options.framebufferScaleFactor - Resolved framebuffer scale factor. * @param {number} options.depthNear - Depth near plane. * @param {number} options.depthFar - Depth far plane. * @param {Function} [options.onBindingError] - Called if XRWebGLBinding construction fails. */ attachPresentation(session: XRSession, options: { framebufferScaleFactor: number; depthNear: number; depthFar: number; onBindingError?: Function; }): void; /** * Matches {@link XrManager#end} clearing {@link XrManager#graphicsBinding} only. */ releasePresentation(): void; /** * Copies the XR passthrough camera image for the given XRCamera into a PlayCanvas * {@link Texture}, with a Y-flip to match engine UV conventions. No-ops if the graphics * binding is unavailable or the camera image is not ready this frame. * * @param {any} xrCamera - The XR camera whose image should be copied (XRCamera from WebXR API). * @param {Texture} texture - Destination engine texture (must be GPU-uploaded). */ syncCameraColorTexture(xrCamera: any, texture: Texture): void; /** * Aliases the XR runtime depth GL texture into the engine {@link Texture} implementation. * * @param {any} depthInfo - Depth information from WebXR (`getDepthInformation`). * @param {Texture} texture - Destination engine texture. * @param {number} depthPixelFormat - Resolved depth pixel format (`PIXELFORMAT_R32F` or `PIXELFORMAT_DEPTH`). */ syncCameraDepthTexture(depthInfo: any, texture: Texture, depthPixelFormat: number): void; onGraphicsDeviceLost(): void; /** * Recreates presentation after GPU restore; fires `"error"` on the bridge {@link XrBridge#eventHandler} if restore fails. */ onGraphicsDeviceRestored(): void; } /** * A WebGL implementation of the RenderTarget. * * @ignore */ declare class WebglRenderTarget { _glFrameBuffer: any; _glDepthBuffer: any; _glResolveFrameBuffer: any; /** * A list of framebuffers created When MSAA and MRT are used together, one for each color buffer. * This allows color buffers to be resolved separately. * * @type {FramebufferPair[]} */ colorMrtFramebuffers: FramebufferPair[]; _glMsaaColorBuffers: any[]; _glMsaaDepthBuffer: any; /** * Key used to store _glMsaaDepthBuffer in the cache. */ msaaDepthBufferKey: any; /** * The supplied single-sampled framebuffer for rendering. Undefined represents no supplied * framebuffer. Null represents the default framebuffer. A value represents a user-supplied * framebuffer. */ suppliedColorFramebuffer: any; _isInitialized: boolean; destroy(device: any): void; get initialized(): boolean; init(device: any, target: any): void; _createMsaaMrtFramebuffers(device: any, target: any, colorBufferCount: any): void; /** * Checks the completeness status of the currently bound WebGLFramebuffer object. * * @param {WebglGraphicsDevice} device - The graphics device. * @param {RenderTarget} target - The render target. * @param {string} [type] - An optional type string to append to the error message. * @private */ private _checkFbo; loseContext(): void; internalResolve(device: any, src: any, dst: any, target: any, mask: any): void; /** * @param {WebglGraphicsDevice} device - The graphics device. * @param {RenderTarget} target - The render target. * @param {boolean} color - Whether to resolve the color buffer. * @param {boolean} depth - Whether to resolve the depth buffer. */ resolve(device: WebglGraphicsDevice, target: RenderTarget, color: boolean, depth: boolean): void; } /** * A private class representing a pair of framebuffers, when MSAA is used. * * @ignore */ declare class FramebufferPair { /** * @param {WebGLFramebuffer} msaaFB - Multi-sampled rendering framebuffer. * @param {WebGLFramebuffer} resolveFB - Single-sampled resolve framebuffer. */ constructor(msaaFB: WebGLFramebuffer, resolveFB: WebGLFramebuffer); /** * Multi-sampled rendering framebuffer. * * @type {WebGLFramebuffer|null} */ msaaFB: WebGLFramebuffer | null; /** * Single-sampled resolve framebuffer. * * @type {WebGLFramebuffer|null} */ resolveFB: WebGLFramebuffer | null; /** * @param {WebGLRenderingContext} gl - The WebGL rendering context. */ destroy(gl: WebGLRenderingContext): void; } /** * @import { UploadStream } from '../upload-stream.js' * @import { Texture } from '../texture.js' */ /** * WebGL implementation of UploadStream. * Can use either simple direct texture uploads or optimized PBO strategy with orphaning. * * @ignore */ declare class WebglUploadStream { /** * @param {UploadStream} uploadStream - The upload stream. */ constructor(uploadStream: UploadStream); /** * Available PBOs ready for immediate use. * * @type {Array<{pbo: WebGLBuffer, size: number}>} */ availablePBOs: Array<{ pbo: WebGLBuffer; size: number; }>; /** * PBOs currently in use by the GPU. * * @type {Array<{pbo: WebGLBuffer, size: number, sync: WebGLSync}>} */ pendingPBOs: Array<{ pbo: WebGLBuffer; size: number; sync: WebGLSync; }>; uploadStream: UploadStream; useSingleBuffer: boolean; destroy(): void; /** * Handles device lost event by clearing all PBO and sync object arrays. * * @protected */ protected _onDeviceLost(): void; /** * Update PBOs: poll completed ones and remove undersized buffers. * * @param {number} minByteSize - Minimum size for buffers to keep. Smaller buffers are destroyed. */ update(minByteSize: number): void; /** * Upload data to a texture using PBOs (optimized) or direct upload (simple). * * @param {Uint8Array|Uint32Array|Float32Array} data - The data to upload. * @param {Texture} target - The target texture. * @param {number} offset - The element offset in the target. Must be a multiple of texture width. * @param {number} size - The number of elements to upload. Must be a multiple of texture width. */ upload(data: Uint8Array | Uint32Array | Float32Array, target: Texture, offset: number, size: number): void; /** * Direct texture upload via gl.texImage2D — uploads the full buffer with a * fresh storage allocation each call. Bypasses the engine's Texture.upload * path (which uses texSubImage2D after the first frame). This avoids the * texSubImage2D path's stall on multi-MB integer-format uploads through * Chrome's renderer→GPU IPC on some drivers. * * @param {Uint8Array|Uint32Array|Float32Array} data - The data to upload. * @param {Texture} target - The target texture. * @param {number} offset - The element offset in the target. * @param {number} size - The number of elements to upload. * @private */ private uploadDirect; /** * PBO-based upload with orphaning (optimized, potentially non-blocking). * * @param {Uint8Array|Uint32Array|Float32Array} data - The data to upload. * @param {import('../texture.js').Texture} target - The target texture. * @param {number} offset - The element offset in the target. * @param {number} size - The number of elements to upload. * @private */ private uploadPBO; } /** * WebglGraphicsDevice extends the base {@link GraphicsDevice} to provide rendering capabilities * utilizing the WebGL 2.0 specification. * * @category Graphics */ declare class WebglGraphicsDevice extends GraphicsDevice { /** * Creates a new WebglGraphicsDevice instance. * * @param {HTMLCanvasElement} canvas - The canvas to which the graphics device will render. * @param {object} [options] - Options passed when creating the WebGL context. * @param {boolean} [options.alpha] - Boolean that indicates if the canvas contains an * alpha buffer. Defaults to true. * @param {boolean} [options.depth] - Boolean that indicates that the drawing buffer is * requested to have a depth buffer of at least 16 bits. Defaults to true. * @param {boolean} [options.stencil] - Boolean that indicates that the drawing buffer is * requested to have a stencil buffer of at least 8 bits. Defaults to true. * @param {boolean} [options.antialias] - Boolean that indicates whether or not to perform * anti-aliasing if possible. Defaults to true. * @param {boolean} [options.premultipliedAlpha] - Boolean that indicates that the page * compositor will assume the drawing buffer contains colors with pre-multiplied alpha. * Defaults to true. * @param {boolean} [options.preserveDrawingBuffer] - If the value is true the buffers will not * be cleared and will preserve their values until cleared or overwritten by the author. * Defaults to false. * @param {'default'|'high-performance'|'low-power'} [options.powerPreference] - A hint to the * user agent indicating what configuration of GPU is suitable for the WebGL context. Possible * values are: * * - 'default': Let the user agent decide which GPU configuration is most suitable. This is the * default value. * - 'high-performance': Prioritizes rendering performance over power consumption. * - 'low-power': Prioritizes power saving over rendering performance. * * Defaults to 'default'. * @param {boolean} [options.failIfMajorPerformanceCaveat] - Boolean that indicates if a * context will be created if the system performance is low or if no hardware GPU is available. * Defaults to false. * @param {boolean} [options.desynchronized] - Boolean that hints the user agent to reduce the * latency by desynchronizing the canvas paint cycle from the event loop. Defaults to false. * @param {boolean} [options.xrCompatible] - Boolean that hints to the user agent to use a * compatible graphics adapter for an immersive XR device. * @param {WebGL2RenderingContext} [options.gl] - The rendering context * to use. If not specified, a new context will be created. */ constructor(canvas: HTMLCanvasElement, options?: { alpha?: boolean; depth?: boolean; stencil?: boolean; antialias?: boolean; premultipliedAlpha?: boolean; preserveDrawingBuffer?: boolean; powerPreference?: "default" | "high-performance" | "low-power"; failIfMajorPerformanceCaveat?: boolean; desynchronized?: boolean; xrCompatible?: boolean; gl?: WebGL2RenderingContext; }); /** * The WebGL2 context managed by the graphics device. * * @type {WebGL2RenderingContext} * @ignore */ gl: WebGL2RenderingContext; /** * WebGLFramebuffer object that represents the backbuffer of the device for a rendering frame. * When null, this is a framebuffer created when the device was created, otherwise it is a * framebuffer supplied by the XR session. * * @ignore */ _defaultFramebuffer: any; /** * True if the default framebuffer has changed since the last frame. * * @ignore */ _defaultFramebufferChanged: boolean; /** * Helper for resolving MSAA color into the XR framebuffer via a blit-to-scratch + fullscreen * quad copy on visionOS. Created lazily; null on all other platforms. * * @type {import('./webgl-xr-msaa-copy.js').WebglXrMsaaCopy|null} * @private */ private _xrMsaaCopy; /** * Copies out of a pixel buffer waiting to run at the start of the next frame, for the reads * which asked for that, see {@link WebglGraphicsDevice#readPixelsAsync}. Drained by * {@link WebglGraphicsDevice#frameStart}, and on device destruction and context loss. * * @type {Set<{ run: () => void, abandon: () => void, fail: () => void }>} * @private */ private _readbackCopies; _contextLostHandler: (event: any) => void; _contextRestoredHandler: () => void; forceDisableMultisampling: boolean; isWebGL2: boolean; _deviceType: string; dynamicBuffers: WebglDynamicBuffers; supportsImageBitmap: boolean; _samplerTypes: Set<35678 | 35680 | 36306 | 36298 | 35682 | 36293 | 35679 | 36299 | 36307 | 36289 | 36303 | 36311>; glAddress: (10497 | 33071 | 33648)[]; glBlendEquation: (32774 | 32778 | 32779 | 32775 | 32776)[]; glBlendFunctionColor: any[]; glBlendFunctionAlpha: any[]; glComparison: (512 | 513 | 514 | 515 | 516 | 517 | 518 | 519)[]; glStencilOp: (0 | 7680 | 7681 | 7682 | 34055 | 7683 | 34056 | 5386)[]; glClearFlag: number[]; glCull: number[]; glFrontFace: (2305 | 2304)[]; glFilter: (9728 | 9729 | 9984 | 9986 | 9985 | 9987)[]; glPrimitive: (0 | 3 | 1 | 2 | 4 | 5 | 6)[]; glType: (5120 | 5121 | 5122 | 5123 | 5124 | 5125 | 5126 | 5131)[]; pcUniformType: {}; targetToSlot: {}; commitFunction: {}[]; constantTexSource: ScopeId; createBackbuffer(frameBuffer: any): void; updateBackbufferFormat(framebuffer: any): void; updateBackbuffer(): void; createVertexBufferImpl(vertexBuffer: any, format: any): WebglVertexBuffer; createIndexBufferImpl(indexBuffer: any): WebglIndexBuffer; createShaderImpl(shader: any): WebglShader; createUniformBufferImpl(uniformBuffer: any): WebglUniformBuffer; createBindGroupFormatImpl(bindGroupFormat: any): WebglBindGroupFormat; createBindGroupImpl(bindGroup: any): WebglBindGroup; /** * @param {number} index - Index of the bind group slot * @param {BindGroup} bindGroup - Bind group to attach * @param {Uint32Array} [offsets] - Byte offsets for all uniform buffers in the bind group. Unused * on WebGL: every uniform buffer is bound as a whole buffer from offset zero (see below). */ setBindGroup(index: number, bindGroup: BindGroup, offsets?: Uint32Array): void; createDrawCommandImpl(drawCommands: any): WebglDrawCommands; createTextureImpl(texture: any): WebglTexture; createXrBridgeImpl(xrBridge: any): WebglXrBridge; createRenderTargetImpl(renderTarget: any): WebglRenderTarget; createUploadStreamImpl(uploadStream: any): WebglUploadStream; pushMarker(name: any): void; popMarker(): void; /** * Query the precision supported by ints and floats in vertex and fragment shaders. Note that * getShaderPrecisionFormat is not guaranteed to be present (such as some instances of the * default Android browser). In this case, assume highp is available. * * @returns {"highp"|"mediump"|"lowp"} The highest precision supported by the WebGL context. * @ignore */ getPrecision(): "highp" | "mediump" | "lowp"; getExtension(...args: any[]): ANGLE_instanced_arrays; get extDisjointTimerQuery(): ANGLE_instanced_arrays; _extDisjointTimerQuery: ANGLE_instanced_arrays; /** * True when the device was created as {@link DEVICETYPE_WEBGL2_BARE}, and so reports only the * extensions and capabilities available on almost all devices. A getter rather than a field, * as the extensions are initialized from the constructor of this class. * * @type {boolean} * @ignore */ get bare(): boolean; /** * Initialize the extensions provided by the WebGL context. * * @ignore */ initializeExtensions(): void; supportedExtensions: any; extColorBufferFloat: ANGLE_instanced_arrays; extColorBufferHalfFloat: ANGLE_instanced_arrays; extDebugRendererInfo: ANGLE_instanced_arrays; extTextureFloatLinear: ANGLE_instanced_arrays; extFloatBlend: ANGLE_instanced_arrays; extBlendFuncExtended: ANGLE_instanced_arrays; extDrawBuffersIndexed: ANGLE_instanced_arrays; extTextureFilterAnisotropic: ANGLE_instanced_arrays; extParallelShaderCompile: ANGLE_instanced_arrays; extProvokingVertex: ANGLE_instanced_arrays; extMultiDraw: ANGLE_instanced_arrays; extCompressedTextureETC1: ANGLE_instanced_arrays; extCompressedTextureETC: ANGLE_instanced_arrays; extCompressedTexturePVRTC: ANGLE_instanced_arrays; extCompressedTextureS3TC: ANGLE_instanced_arrays; extCompressedTextureS3TC_SRGB: ANGLE_instanced_arrays; extCompressedTextureATC: ANGLE_instanced_arrays; extCompressedTextureASTC: ANGLE_instanced_arrays; extTextureCompressionBPTC: ANGLE_instanced_arrays; /** * Query the capabilities of the WebGL context. * * @ignore */ initializeCapabilities(): void; maxPrecision: "highp" | "mediump" | "lowp"; maxRenderBufferSize: any; maxTextures: any; maxCombinedTextures: any; maxVertexTextures: any; vertexUniformsCount: any; fragmentUniformsCount: any; unmaskedRenderer: any; unmaskedVendor: any; supportsGpuParticles: boolean; supportsAreaLights: boolean; cullFace: any; stencil: any; stencilFuncFront: any; stencilFuncBack: any; stencilRefFront: any; stencilRefBack: any; stencilMaskFront: any; stencilMaskBack: any; stencilFailFront: any; stencilFailBack: any; stencilZfailFront: any; stencilZfailBack: any; stencilZpassFront: any; stencilZpassBack: any; stencilWriteMaskFront: any; stencilWriteMaskBack: any; raster: any; depthBiasEnabled: boolean; clearDepth: any; clearColor: Color; clearStencil: any; textureUnit: any; unpackFlipY: any; unpackPremultiplyAlpha: any; unpackAlignment: any; initTextureUnits(count?: number): void; textureUnits: any[]; _vaoMap: Map; boundVao: any; activeFramebuffer: any; feedback: any; /** @type {VertexBuffer[]|null} */ transformFeedbackBuffers: VertexBuffer[] | null; /** * Set the active rectangle for rendering on the specified device. * * @param {number} x - The pixel space x-coordinate of the bottom left corner of the viewport. * @param {number} y - The pixel space y-coordinate of the bottom left corner of the viewport. * @param {number} w - The width of the viewport in pixels. * @param {number} h - The height of the viewport in pixels. */ setViewport(x: number, y: number, w: number, h: number): void; /** * Set the active scissor rectangle on the specified device. * * @param {number} x - The pixel space x-coordinate of the bottom left corner of the scissor rectangle. * @param {number} y - The pixel space y-coordinate of the bottom left corner of the scissor rectangle. * @param {number} w - The width of the scissor rectangle in pixels. * @param {number} h - The height of the scissor rectangle in pixels. */ setScissor(x: number, y: number, w: number, h: number): void; /** * Binds the specified framebuffer object. * * @param {WebGLFramebuffer | null} fb - The framebuffer to bind. * @ignore */ setFramebuffer(fb: WebGLFramebuffer | null): void; /** * Resolve multisampled color into the WebXR session framebuffer by first blitting MSAA into * an internal scratch texture, then copying that texture into the XR FBO with a single * fullscreen textured quad. Used on visionOS / Apple Vision Pro where direct * `blitFramebuffer` into the XR opaque framebuffer does not produce correct results. * * @param {WebGLFramebuffer} msaaReadFbo - Multisampled source framebuffer. * @param {WebGLFramebuffer} xrDrawFbo - XR base layer framebuffer. * @param {number} width - Full SBS framebuffer width in pixels. * @param {number} height - Framebuffer height in pixels. * @ignore */ resolveMsaaColorToXrFramebufferViaQuads(msaaReadFbo: WebGLFramebuffer, xrDrawFbo: WebGLFramebuffer, width: number, height: number): void; /** * Copies source render target into destination render target. Mostly used by post-effects. * * @param {RenderTarget} [source] - The source render target. Defaults to frame buffer. * @param {RenderTarget} [dest] - The destination render target. Defaults to frame buffer. * @param {boolean} [color] - If true, will copy the color buffer. Defaults to false. * @param {boolean} [depth] - If true, will copy the depth buffer. Defaults to false. * @returns {boolean} True if the copy was successful, false otherwise. */ copyRenderTarget(source?: RenderTarget, dest?: RenderTarget, color?: boolean, depth?: boolean): boolean; /** * Copies a region of a source texture into a destination texture. The destination is written * via `copyTexSubImage2D` as a bound texture, so only the source needs a framebuffer. This is * the WebGL texture-copy primitive used by {@link Texture#copy}. * * @param {Texture} source - The source texture. * @param {Texture} dest - The destination texture. * @param {object} [options] - The copy options (see {@link Texture#copy}). * @returns {boolean} True if the copy was successful. * @ignore */ copyTextureToTexture(source: Texture, dest: Texture, options?: object): boolean; /** * Start a render pass. * * @param {RenderPass} renderPass - The render pass to start. * @ignore */ startRenderPass(renderPass: RenderPass): void; /** * End a render pass. * * @param {RenderPass} renderPass - The render pass to end. * @ignore */ endRenderPass(renderPass: RenderPass): void; set defaultFramebuffer(value: any); get defaultFramebuffer(): any; /** * Marks the beginning of a block of rendering. Internally, this function binds the render * target currently set on the device. This function should be matched with a call to * {@link GraphicsDevice#updateEnd}. Calls to {@link GraphicsDevice#updateBegin} and * {@link GraphicsDevice#updateEnd} must not be nested. * * @ignore */ updateBegin(): void; /** * Marks the end of a block of rendering. This function should be called after a matching call * to {@link GraphicsDevice#updateBegin}. Calls to {@link GraphicsDevice#updateBegin} and * {@link GraphicsDevice#updateEnd} must not be nested. * * @ignore */ updateEnd(): void; /** * Updates a texture's vertical flip. * * @param {boolean} flipY - True to flip the texture vertically. * @ignore */ setUnpackFlipY(flipY: boolean): void; /** * Updates a texture to have its RGB channels premultiplied by its alpha channel or not. * * @param {boolean} premultiplyAlpha - True to premultiply the alpha channel against the RGB * channels. * @ignore */ setUnpackPremultiplyAlpha(premultiplyAlpha: boolean): void; /** * Sets the byte alignment for unpacking pixel data during texture uploads. * * @param {number} alignment - The alignment in bytes. Must be 1, 2, 4, or 8. * @ignore */ setUnpackAlignment(alignment: number): void; /** * Activate the specified texture unit. * * @param {number} textureUnit - The texture unit to activate. * @ignore */ activeTexture(textureUnit: number): void; /** * If the texture is not already bound on the currently active texture unit, bind it. * * @param {Texture} texture - The texture to bind. * @ignore */ bindTexture(texture: Texture): void; /** * If the texture is not bound on the specified texture unit, active the texture unit and bind * the texture to it. * * @param {Texture} texture - The texture to bind. * @param {number} textureUnit - The texture unit to activate and bind the texture to. * @ignore */ bindTextureOnUnit(texture: Texture, textureUnit: number): void; /** * Update the texture parameters for a given texture if they have changed. * * @param {Texture} texture - The texture to update. * @ignore */ setTextureParameters(texture: Texture): void; /** * Sets the specified texture on the specified texture unit. * * @param {Texture} texture - The texture to set. * @param {number} textureUnit - The texture unit to set the texture on. * @ignore */ setTexture(texture: Texture, textureUnit: number): void; /** * Generates the key of the vertex array object cache for the supplied vertex buffers. Each part * identifies both the buffer and its format, and is delimited, so distinct buffer lists cannot * generate the same key. * * @param {VertexBuffer[]} vertexBuffers - The vertex buffers of the draw. * @returns {string} The cache key. * @private */ private _vertexArrayKey; /** * Removes the cached vertex array object for the supplied vertex buffers, if one exists. * * This is needed by code which exchanges the GPU buffers behind VertexBuffer objects while * leaving the objects themselves in place - see {@link TransformFeedback#process}. A vertex * array object captures the GPU buffers it was built from, and this cache is keyed on the * VertexBuffer objects, so such an exchange is invisible to it and a stale vertex array object * would keep reading the buffers from before the exchange. * * Only has an effect when more than one vertex buffer is supplied - a single vertex buffer stores * its vertex array object on itself, and so it travels with the buffer. * * @param {VertexBuffer[]} vertexBuffers - The vertex buffers whose cached vertex array object * should be removed. * @ignore */ removeVertexArrayFromCache(vertexBuffers: VertexBuffer[]): void; createVertexArray(vertexBuffers: any): any; unbindVertexArray(): void; setBuffers(indexBuffer: any): void; _multiDrawLoopFallback(mode: any, primitive: any, indexBuffer: any, numInstances: any, drawCommands: any): void; draw(primitive: any, indexBuffer: any, numInstances: any, drawCommands: any, first?: boolean, last?: boolean, firstInstance?: number): void; /** * Clears the frame buffer of the currently set render target. * * @param {object} [options] - Optional options object that controls the behavior of the clear * operation defined as follows: * @param {number[]} [options.color] - The color to clear the color buffer to in the range 0 to * 1 for each component. * @param {number} [options.depth] - The depth value to clear the depth buffer to in the * range 0 to 1. Defaults to 1. * @param {number} [options.flags] - The buffers to clear (the types being color, depth and * stencil). Can be any bitwise combination of: * * - {@link CLEARFLAG_COLOR} * - {@link CLEARFLAG_DEPTH} * - {@link CLEARFLAG_STENCIL} * * @param {number} [options.stencil] - The stencil value to clear the stencil buffer to. * Defaults to 0. * @example * // Clear color buffer to black and depth buffer to 1 * device.clear(); * * // Clear just the color buffer to red * device.clear({ * color: [1, 0, 0, 1], * flags: CLEARFLAG_COLOR * }); * * // Clear color buffer to yellow and depth to 1.0 * device.clear({ * color: [1, 1, 0, 1], * depth: 1, * flags: CLEARFLAG_COLOR | CLEARFLAG_DEPTH * }); */ clear(options?: { color?: number[]; depth?: number; flags?: number; stencil?: number; }): void; submit(): void; /** * Reads a block of pixels from a specified rectangle of the current color framebuffer into an * ArrayBufferView object. * * @param {number} x - The x-coordinate of the rectangle's lower-left corner. * @param {number} y - The y-coordinate of the rectangle's lower-left corner. * @param {number} w - The width of the rectangle, in pixels. * @param {number} h - The height of the rectangle, in pixels. * @param {ArrayBufferView} pixels - The ArrayBufferView object that holds the returned pixel * data. * @ignore */ readPixels(x: number, y: number, w: number, h: number, pixels: ArrayBufferView): void; clientWaitAsync(flags: any, interval_ms: any): Promise; /** * Asynchronously reads a block of pixels from a specified rectangle of the current color framebuffer * into an ArrayBufferView object. * * @param {number} x - The x-coordinate of the rectangle's lower-left corner. * @param {number} y - The y-coordinate of the rectangle's lower-left corner. * @param {number} w - The width of the rectangle, in pixels. * @param {number} h - The height of the rectangle, in pixels. * @param {ArrayBufferView} pixels - The ArrayBufferView object that holds the returned pixel * data. * @param {boolean} [forceRgba] - If true, forces RGBA/UNSIGNED_BYTE format for guaranteed * WebGL support. Used for reading non-RGBA 8-bit normalized textures. Defaults to false. * @param {boolean} [frequent] - Set for a read issued every frame or every few frames, which * runs the copy out of the pixel buffer at the start of the next frame instead of as soon as * the data is available. Defaults to false. * @ignore */ readPixelsAsync(x: number, y: number, w: number, h: number, pixels: ArrayBufferView, forceRgba?: boolean, frequent?: boolean): Promise>; readTextureAsync(texture: any, x: any, y: any, width: any, height: any, options: any): Promise; writeTextureAsync(texture: any, x: any, y: any, width: any, height: any, data: any): Promise; /** * Enables or disables alpha to coverage. * * @param {boolean} state - True to enable alpha to coverage and false to disable it. * @ignore */ setAlphaToCoverage(state: boolean): void; /** * Sets the output vertex buffers. They will be written to by a shader with transform feedback * varyings. A shader created with {@link TRANSFORM_FEEDBACK_INTERLEAVED} captures all varyings * into a single buffer, and so expects one buffer. A shader created with * {@link TRANSFORM_FEEDBACK_SEPARATE} captures each varying into its own buffer, and so expects * one buffer per varying, in declaration order. * * @param {VertexBuffer[]|null} buffers - The output vertex buffers, or null to disable transform * feedback. * @ignore */ setTransformFeedbackBuffers(buffers: VertexBuffer[] | null): void; /** * Toggles the rasterization render state. Useful with transform feedback, when you only need * to process the data without drawing. * * @param {boolean} on - True to enable rasterization and false to disable it. * @ignore */ setRaster(on: boolean): void; setStencilTest(enable: any): void; setStencilFunc(func: any, ref: any, mask: any): void; setStencilFuncFront(func: any, ref: any, mask: any): void; setStencilFuncBack(func: any, ref: any, mask: any): void; setStencilOperation(fail: any, zfail: any, zpass: any, writeMask: any): void; setStencilOperationFront(fail: any, zfail: any, zpass: any, writeMask: any): void; setStencilOperationBack(fail: any, zfail: any, zpass: any, writeMask: any): void; /** * Applies a blend state to all draw buffers. * * @param {BlendState} blendState - The blend state to apply. Only the state of its attachment 0 * is used, as the non-indexed entry points apply to all draw buffers. * @param {BlendState} [prevState] - The currently applied state, used to skip the calls which * would not change anything. When not specified, all state is set. * @private */ private applyBlendState; /** * Applies a blend state to a single draw buffer, using the indexed entry points of the * OES_draw_buffers_indexed extension. The state is always set in full, as the caller has just * overwritten the state of all draw buffers. * * @param {number} index - The index of the draw buffer. * @param {BlendState} blendState - The blend state to apply. * @private */ private applyBlendStateIndexed; setBlendState(blendState: any): void; setStencilState(stencilFront: any, stencilBack: any): void; setDepthState(depthState: any): void; setCullMode(cullMode: any): void; setFrontFace(frontFace: any): void; /** * Sets the active shader to be used during subsequent draw calls. * * @param {Shader} shader - The shader to assign to the device. * @param {boolean} [asyncCompile] - If true, rendering will be skipped until the shader is * compiled, otherwise the rendering will wait for the shader compilation to finish. Defaults * to false. */ setShader(shader: Shader, asyncCompile?: boolean): void; activateShader(): void; /** * Frees memory from all vertex array objects ever allocated with this device. * * @ignore */ clearVertexArrayObjectCache(): void; /** @private */ private _debugContextLossPending; } declare class ImageElement { constructor(element: any); /** * @type {EventHandle|null} * @private */ private _evtSetMeshes; _element: any; _entity: any; _system: any; /** @type {number} */ _textureAsset: number; /** @type {Texture} */ _texture: Texture; /** @type {number} */ _materialAsset: number; /** @type {Material} */ _material: Material; /** @type {number} */ _spriteAsset: number; /** @type {Sprite} */ _sprite: Sprite; _spriteFrame: number; /** @type {number} */ _pixelsPerUnit: number; _targetAspectRatio: number; _rect: Vec4; _mask: boolean; _maskRef: number; _outerScale: Vec2; _outerScaleUniform: Float32Array; _innerOffset: Vec4; _innerOffsetUniform: Float32Array; _atlasRect: Vec4; _atlasRectUniform: Float32Array; _defaultMesh: Mesh; _renderable: ImageRenderable; _color: Color; _colorUniform: Float32Array; _emissiveUniform: Float32Array; _updateAabbFunc: any; destroy(): void; set textureAsset(value: number); get textureAsset(): number; set spriteAsset(value: number); get spriteAsset(): number; set materialAsset(value: number); get materialAsset(): number; _onResolutionChange(res: any): void; _onParentResizeOrPivotChange(): void; _onScreenSpaceChange(value: any): void; _onScreenChange(screen: any, previous: any): void; _onDrawOrderChange(order: any): void; _hasUserMaterial(): boolean; _use9Slicing(): boolean; _updateMaterial(screenSpace: any): void; _createMesh(): Mesh; _updateMesh(mesh: any): void; _meshDirty: boolean; _updateSprite(): void; set mesh(value: any); get mesh(): any; refreshMesh(): void; _updateAabb(aabb: any): any; _toggleMask(): void; _onMaterialLoad(asset: any): void; set material(value: Material); get material(): Material; _onMaterialAdded(asset: any): void; _bindMaterialAsset(asset: any): void; _unbindMaterialAsset(asset: any): void; _onMaterialChange(): void; _onMaterialRemove(): void; _onTextureAdded(asset: any): void; _bindTextureAsset(asset: any): void; _unbindTextureAsset(asset: any): void; _onTextureLoad(asset: any): void; set texture(value: Texture); get texture(): Texture; _onTextureChange(asset: any): void; _onTextureRemove(asset: any): void; _onSpriteAssetAdded(asset: any): void; _bindSpriteAsset(asset: any): void; _unbindSpriteAsset(asset: any): void; _onSpriteAssetLoad(asset: any): void; set sprite(value: Sprite); get sprite(): Sprite; _onSpriteAssetChange(asset: any): void; _onSpriteAssetRemove(asset: any): void; _bindSprite(sprite: any): void; _unbindSprite(sprite: any): void; _onSpriteMeshesChange(): void; _onSpritePpuChange(): void; _onAtlasTextureChange(): void; _onTextureAtlasLoad(atlasAsset: any): void; onEnable(): void; onDisable(): void; _setStencil(stencilParams: any): void; _updateRenderableEmissive(): void; _updateRenderableOpacity(): void; set color(value: Color); get color(): Color; set opacity(value: number); get opacity(): number; set rect(value: Vec4); get rect(): Vec4; _removeMaterialAssetEvents(): void; set spriteFrame(value: number); get spriteFrame(): number; set mask(value: boolean); get mask(): boolean; set pixelsPerUnit(value: number); get pixelsPerUnit(): number; /** * @type {BoundingBox | null} */ get aabb(): BoundingBox | null; } declare class ImageRenderable { constructor(entity: any, mesh: any, material: any); _entity: any; _element: any; model: Model; node: GraphNode; mesh: any; meshInstance: MeshInstance; _meshDirty: boolean; unmaskMeshInstance: MeshInstance; destroy(): void; setMesh(mesh: any): void; setMask(mask: any): void; setMaterial(material: any): void; setParameter(name: any, value: any): void; deleteParameter(name: any): void; setUnmaskDrawOrder(): void; setDrawOrder(drawOrder: any): void; setCull(cull: any): void; setScreenSpace(screenSpace: any): void; setLayer(layer: any): void; forceUpdateAabb(mask: any): void; setAabbFunc(fn: any): void; } /** * Tracks a default asset and the localized asset that replaces it for the current locale, as * declared through {@link Asset#addLocalizedAssetId}. Used internally by the text element to * switch fonts when the locale changes. * * @ignore */ declare class LocalizedAsset extends EventHandler { constructor(app: any); _app: any; _autoLoad: boolean; _disableLocalization: boolean; /** @type {number} */ _defaultAsset: number; /** @type {number} */ _localizedAsset: number; /** * @param {Asset | number} value - The asset or id. */ set defaultAsset(value: Asset | number); get defaultAsset(): Asset | number; /** * @param {Asset | number} value - The asset or id. */ set localizedAsset(value: Asset | number); get localizedAsset(): Asset | number; set autoLoad(value: boolean); get autoLoad(): boolean; set disableLocalization(value: boolean); get disableLocalization(): boolean; _bindDefaultAsset(): void; _unbindDefaultAsset(): void; _onDefaultAssetAdd(asset: any): void; _onDefaultAssetRemove(asset: any): void; _bindLocalizedAsset(): void; _unbindLocalizedAsset(): void; _onLocalizedAssetAdd(asset: any): void; _onLocalizedAssetLoad(asset: any): void; _onLocalizedAssetChange(asset: any, name: any, newValue: any, oldValue: any): void; _onLocalizedAssetRemove(asset: any): void; _onLocaleAdd(locale: any, assetId: any): void; _onLocaleRemove(locale: any, assetId: any): void; _onSetLocale(locale: any): void; destroy(): void; } declare class TextElement { constructor(element: any); _element: any; _system: any; _entity: any; _text: string; _symbols: any[]; _colorPalette: any[]; _outlinePalette: any[]; _shadowPalette: any[]; _symbolColors: any[]; _symbolOutlineParams: any[]; _symbolShadowParams: any[]; /** @type {string} */ _i18nKey: string; _fontAsset: LocalizedAsset; /** @type {Font | CanvasFont} */ _font: Font | CanvasFont; _color: Color; _colorUniform: Float32Array; _spacing: number; _fontSize: number; _fontMinY: number; _fontMaxY: number; _originalFontSize: number; _maxFontSize: number; _minFontSize: number; _autoFitWidth: boolean; _autoFitHeight: boolean; _maxLines: number; _lineHeight: number; _scaledLineHeight: number; _wrapLines: boolean; _justify: boolean; _drawOrder: number; _alignment: Vec2; _autoWidth: boolean; _autoHeight: boolean; width: number; height: number; _node: GraphNode; _model: Model; _meshInfo: any[]; _material: any; _aabbDirty: boolean; _aabb: BoundingBox; _noResize: boolean; _currentMaterialType: any; _maskedMaterialSrc: any; _rtlReorder: boolean; _unicodeConverter: boolean; _rtl: boolean; _outlineColor: Color; _outlineColorUniform: Float32Array; _outlineThicknessScale: number; _outlineThickness: number; _shadowColor: Color; _shadowColorUniform: Float32Array; _shadowOffsetScale: number; _shadowOffset: Vec2; _shadowOffsetUniform: Float32Array; _enableMarkup: boolean; _rangeStart: number; _rangeEnd: number; destroy(): void; set font(value: CanvasFont | Font); get font(): CanvasFont | Font; _onParentResize(width: any, height: any): void; _onScreenChange(screen: any): void; _onScreenSpaceChange(value: any): void; _onDrawOrderChange(order: any): void; _onPivotChange(pivot: any): void; _onLocaleSet(locale: any): void; _onLocalizationData(locale: any, messages: any): void; _resetLocalizedText(): void; _setText(text: any): void; _updateText(text: any): void; _removeMeshInstance(meshInstance: any): void; _setMaterial(material: any): void; _updateMaterial(screenSpace: any): void; _updateColorUniform(): void; _updateMaterialOutline(): void; _updateMaterialShadow(): void; _isWordBoundary(char: any): boolean; _isValidNextChar(nextchar: any): boolean; _isNextCJKBoundary(char: any, nextchar: any): boolean; _isNextCJKWholeWord(nextchar: any): boolean; _updateMeshes(): void; _lineWidths: any[]; _lineContents: any[]; _lineGaps: any[]; set autoWidth(value: boolean); get autoWidth(): boolean; set autoHeight(value: boolean); get autoHeight(): boolean; _onFontRender(): void; _onFontLoad(asset: any): void; _onFontChange(asset: any, name: any, _new: any, _old: any): void; _onFontRemove(asset: any): void; _setTextureParams(mi: any, texture: any): void; _getPxRange(font: any): number; _getUv(char: any): any; onEnable(): void; onDisable(): void; _setStencil(stencilParams: any): void; _shouldAutoFitWidth(): boolean; _shouldAutoFitHeight(): boolean; _shouldAutoFit(): boolean; _calculateCharsPerTexture(symbolIndex: any): {}; _updateRenderRange(): void; set text(value: string); get text(): string; set key(value: string); get key(): string; set color(value: Color); get color(): Color; set opacity(value: number); get opacity(): number; set lineHeight(value: number); get lineHeight(): number; set wrapLines(value: boolean); get wrapLines(): boolean; set justify(value: boolean); get justify(): boolean; get lines(): any[]; set spacing(value: number); get spacing(): number; set fontSize(value: number); get fontSize(): number; set fontAsset(value: number | Asset); get fontAsset(): number | Asset; set alignment(value: Vec2); get alignment(): Vec2; set rtlReorder(value: boolean); get rtlReorder(): boolean; set unicodeConverter(value: boolean); get unicodeConverter(): boolean; /** * @type {BoundingBox} */ get aabb(): BoundingBox; set outlineColor(value: Color); get outlineColor(): Color; set outlineThickness(value: number); get outlineThickness(): number; set shadowColor(value: Color); get shadowColor(): Color; set shadowOffset(value: Vec2); get shadowOffset(): Vec2; set minFontSize(value: number); get minFontSize(): number; set maxFontSize(value: number); get maxFontSize(): number; set autoFitWidth(value: boolean); get autoFitWidth(): boolean; set autoFitHeight(value: boolean); get autoFitHeight(): boolean; set maxLines(value: number); get maxLines(): number; set enableMarkup(value: boolean); get enableMarkup(): boolean; get symbols(): any[]; get symbolColors(): any[]; get symbolOutlineParams(): any[]; get symbolShadowParams(): any[]; get rtl(): boolean; set rangeStart(rangeStart: number); get rangeStart(): number; set rangeEnd(rangeEnd: number); get rangeEnd(): number; } /** * Options of the `element` component accepted by {@link ElementComponentSystem} that differ from * the properties of {@link ElementComponent}. Each replaces the same-named property of the options * that {@link Entity#addComponent} derives from the component class; see * {@link ComponentOptionsOverrides}. */ type ElementComponentOptionsOverrides = { /** * - Same as {@link ElementComponent#anchor}, also accepting an * `[x, y, z, w]` array. */ anchor?: Vec4 | number[]; /** * - Same as {@link ElementComponent#batchGroupId}. `null` * selects no batch group. */ batchGroupId?: number | null; /** * - Same as {@link ElementComponent#color}, also accepting an * `[r, g, b]` array. */ color?: Color | number[]; /** * - Same as {@link ElementComponent#margin}, also accepting an * `[x, y, z, w]` array. */ margin?: Vec4 | number[]; /** * - Same as {@link ElementComponent#pivot}, also accepting an * `[x, y]` array. */ pivot?: Vec2 | number[]; }; /** * @import { AppBase } from '../../app-base.js' * @import { Entity } from '../../entity.js' */ /** * Options of the `element` component accepted by {@link ElementComponentSystem} that differ from * the properties of {@link ElementComponent}. Each replaces the same-named property of the options * that {@link Entity#addComponent} derives from the component class; see * {@link ComponentOptionsOverrides}. * * @typedef {object} ElementComponentOptionsOverrides * @property {Vec4 | number[]} [anchor] - Same as {@link ElementComponent#anchor}, also accepting an * `[x, y, z, w]` array. * @property {number | null} [batchGroupId] - Same as {@link ElementComponent#batchGroupId}. `null` * selects no batch group. * @property {Color | number[]} [color] - Same as {@link ElementComponent#color}, also accepting an * `[r, g, b]` array. * @property {Vec4 | number[]} [margin] - Same as {@link ElementComponent#margin}, also accepting an * `[x, y, z, w]` array. * @property {Vec2 | number[]} [pivot] - Same as {@link ElementComponent#pivot}, also accepting an * `[x, y]` array. * @ignore */ /** * Manages the {@link ElementComponent}s of an application. Reach it through `app.systems.element`; * components are created with {@link Entity#addComponent}, never by calling the system directly. * * @category User Interface */ declare class ElementComponentSystem extends ComponentSystem { id: string; ComponentType: typeof ElementComponent; _unicodeConverter: any; _rtlReorder: any; _defaultTexture: Texture; defaultImageMaterial: StandardMaterial; defaultImage9SlicedMaterial: StandardMaterial; defaultImage9TiledMaterial: StandardMaterial; defaultImageMaskMaterial: StandardMaterial; defaultImage9SlicedMaskMaterial: StandardMaterial; defaultImage9TiledMaskMaterial: StandardMaterial; defaultScreenSpaceImageMaterial: StandardMaterial; defaultScreenSpaceImage9SlicedMaterial: StandardMaterial; defaultScreenSpaceImage9TiledMaterial: StandardMaterial; defaultScreenSpaceImageMask9SlicedMaterial: StandardMaterial; defaultScreenSpaceImageMask9TiledMaterial: StandardMaterial; defaultScreenSpaceImageMaskMaterial: StandardMaterial; _defaultTextMaterials: {}; defaultImageMaterials: any[]; initializeComponentData(component: any, data: any, properties: any): void; onAddComponent(entity: any, component: any): void; onBeforeRemove(entity: any, component: any): void; cloneComponent(entity: any, clone: any): Component; getTextElementMaterial(screenSpace: any, msdf: any, textAttributes: any): any; _createBaseImageMaterial(): StandardMaterial; getImageElementMaterial(screenSpace: any, mask: any, nineSliced: any, nineSliceTiled: any): StandardMaterial; registerUnicodeConverter(func: any): void; registerRtlReorder(func: any): void; getUnicodeConverter(): any; getRtlReorder(): any; } /** * ElementComponents are used to construct user interfaces. The {@link type} property can be * configured in 3 main ways: as a text element, as an image element or as a group element. If * the ElementComponent has a {@link ScreenComponent} ancestor in the hierarchy, it * will be transformed with respect to the coordinate system of the screen. If there is no * {@link ScreenComponent} ancestor, the ElementComponent will be transformed like any other * entity. * * You should never need to use the ElementComponent constructor directly. To add an * ElementComponent to an {@link Entity}, use {@link Entity#addComponent}: * * ```javascript * const entity = new Entity(); * entity.addComponent('element'); // This defaults to a 'group' element * ``` * * To create a simple text-based element: * * ```javascript * entity.addComponent('element', { * anchor: new Vec4(0.5, 0.5, 0.5, 0.5), // centered anchor * fontAsset: fontAsset, * fontSize: 128, * pivot: new Vec2(0.5, 0.5), // centered pivot * text: 'Hello World!', * type: ELEMENTTYPE_TEXT * }); * ``` * * Once the ElementComponent is added to the entity, you can access it via the * {@link Entity#element} property: * * ```javascript * entity.element.color = Color.RED; // Set the element's color to red * * console.log(entity.element.color); // Get the element's color and print it * ``` * * Relevant Engine API examples: * * - [Anchors](https://playcanvas.github.io/#/user-interface/anchors) * - [Image fitting](https://playcanvas.github.io/#/user-interface/image-fit) * - [Sliced panels](https://playcanvas.github.io/#/user-interface/panel) * - [Masking](https://playcanvas.github.io/#/user-interface/masking) * - [Rendering 3D into an image](https://playcanvas.github.io/#/user-interface/render-to-image) * - [Custom shader](https://playcanvas.github.io/#/user-interface/custom-shader) * - [Basic text rendering](https://playcanvas.github.io/#/user-interface/text) * - [Auto font sizing](https://playcanvas.github.io/#/user-interface/text-auto-font-size) * - [Emojis](https://playcanvas.github.io/#/user-interface/text-emojis) * - [Justified text](https://playcanvas.github.io/#/user-interface/text-justify) * - [Text localization](https://playcanvas.github.io/#/user-interface/text-localization) * - [Text markup](https://playcanvas.github.io/#/user-interface/text-markup) * - [Typewriter text](https://playcanvas.github.io/#/user-interface/text-typewriter) * * @hideconstructor * @category User Interface */ declare class ElementComponent extends Component { /** * Fired when the mouse is pressed while the cursor is on the component. Only fired when * useInput is true. The handler is passed an {@link ElementMouseEvent}. * * @event * @example * entity.element.on('mousedown', (event) => { * console.log(`Mouse down event on entity ${entity.name}`); * }); */ static EVENT_MOUSEDOWN: string; /** * Fired when the mouse is released while the cursor is on the component. Only fired when * useInput is true. The handler is passed an {@link ElementMouseEvent}. * * @event * @example * entity.element.on('mouseup', (event) => { * console.log(`Mouse up event on entity ${entity.name}`); * }); */ static EVENT_MOUSEUP: string; /** * Fired when the mouse cursor enters the component. Only fired when useInput is true. The * handler is passed an {@link ElementMouseEvent}. * * @event * @example * entity.element.on('mouseenter', (event) => { * console.log(`Mouse enter event on entity ${entity.name}`); * }); */ static EVENT_MOUSEENTER: string; /** * Fired when the mouse cursor leaves the component. Only fired when useInput is true. The * handler is passed an {@link ElementMouseEvent}. * * @event * @example * entity.element.on('mouseleave', (event) => { * console.log(`Mouse leave event on entity ${entity.name}`); * }); */ static EVENT_MOUSELEAVE: string; /** * Fired when the mouse cursor is moved on the component. Only fired when useInput is true. The * handler is passed an {@link ElementMouseEvent}. * * @event * @example * entity.element.on('mousemove', (event) => { * console.log(`Mouse move event on entity ${entity.name}`); * }); */ static EVENT_MOUSEMOVE: string; /** * Fired when the mouse wheel is scrolled on the component. Only fired when useInput is true. * The handler is passed an {@link ElementMouseEvent}. * * @event * @example * entity.element.on('mousewheel', (event) => { * console.log(`Mouse wheel event on entity ${entity.name}`); * }); */ static EVENT_MOUSEWHEEL: string; /** * Fired when the mouse is pressed and released on the component, when a touch starts and ends * on the component, or when an XR input source starts and ends a select action on the * component. Only fired when useInput is true. The handler is passed an * {@link ElementMouseEvent}, {@link ElementTouchEvent} or {@link ElementSelectEvent}. * * @event * @example * entity.element.on('click', (event) => { * console.log(`Click event on entity ${entity.name}`); * }); */ static EVENT_CLICK: string; /** * Fired when a touch starts on the component. Only fired when useInput is true. The handler is * passed an {@link ElementTouchEvent}. * * @event * @example * entity.element.on('touchstart', (event) => { * console.log(`Touch start event on entity ${entity.name}`); * }); */ static EVENT_TOUCHSTART: string; /** * Fired when a touch ends on the component. Only fired when useInput is true. The handler is * passed an {@link ElementTouchEvent}. * * @event * @example * entity.element.on('touchend', (event) => { * console.log(`Touch end event on entity ${entity.name}`); * }); */ static EVENT_TOUCHEND: string; /** * Fired when a touch moves after it started touching the component. Only fired when useInput * is true. The handler is passed an {@link ElementTouchEvent}. * * @event * @example * entity.element.on('touchmove', (event) => { * console.log(`Touch move event on entity ${entity.name}`); * }); */ static EVENT_TOUCHMOVE: string; /** * Fired when a touch is canceled on the component. Only fired when useInput is true. The * handler is passed an {@link ElementTouchEvent}. * * @event * @example * entity.element.on('touchcancel', (event) => { * console.log(`Touch cancel event on entity ${entity.name}`); * }); */ static EVENT_TOUCHCANCEL: string; /** * Fired when an XR input source starts a select action, such as pulling a controller trigger * or pinching, while its ray points at the component. Only fired when useInput is true and * the input source's {@link XrInputSource#elementInput} is true. The handler is passed an * {@link ElementSelectEvent}. * * @event * @example * entity.element.on('selectstart', (event) => { * console.log(`Select start event on entity ${entity.name}`); * }); */ static EVENT_SELECTSTART: string; /** * Fired when an XR input source ends a select action that started on the component, even if * its ray no longer points at the component. Only fired when useInput is true. The handler is * passed an {@link ElementSelectEvent}. * * @event * @example * entity.element.on('selectend', (event) => { * console.log(`Select end event on entity ${entity.name}`); * }); */ static EVENT_SELECTEND: string; /** * Fired when the ray of an XR input source starts pointing at the component. Only fired when * useInput is true and the input source's {@link XrInputSource#elementInput} is true. The * handler is passed an {@link ElementSelectEvent}. * * @event * @example * entity.element.on('selectenter', (event) => { * console.log(`Select enter event on entity ${entity.name}`); * }); */ static EVENT_SELECTENTER: string; /** * Fired when the ray of an XR input source stops pointing at the component, or when the input * source is removed while its ray points at the component. Only fired when useInput is true. * The handler is passed an {@link ElementSelectEvent}. * * @event * @example * entity.element.on('selectleave', (event) => { * console.log(`Select leave event on entity ${entity.name}`); * }); */ static EVENT_SELECTLEAVE: string; /** * Fired every XR frame while an XR input source holds a select action that started on the * component, even if its ray no longer points at the component. Only fired when useInput is * true. The handler is passed an {@link ElementSelectEvent}. * * @event * @example * entity.element.on('selectmove', (event) => { * console.log(`Select move event on entity ${entity.name}`); * }); */ static EVENT_SELECTMOVE: string; /** * Create a new ElementComponent instance. * * @param {ElementComponentSystem} system - The ComponentSystem that created this Component. * @param {Entity} entity - The Entity that this Component is attached to. */ constructor(system: ElementComponentSystem, entity: Entity); /** * @type {EventHandle|null} * @private */ private _evtLayersChanged; /** * @type {EventHandle|null} * @private */ private _evtLayerAdded; /** * @type {EventHandle|null} * @private */ private _evtLayerRemoved; _beingInitialized: boolean; _anchor: Vec4; _localAnchor: Vec4; _pivot: Vec2; _width: number; _calculatedWidth: number; _height: number; _calculatedHeight: number; _margin: Vec4; _modelTransform: Mat4; _screenToWorld: Mat4; _anchorTransform: Mat4; _anchorDirty: boolean; _parentWorldTransform: Mat4; _screenTransform: Mat4; _screenCorners: Vec3[]; _canvasCorners: Vec2[]; _worldCorners: Vec3[]; _cornersDirty: boolean; _canvasCornersDirty: boolean; _worldCornersDirty: boolean; /** * The Entity with a {@link ScreenComponent} that this component belongs to. This is * automatically set when the component is a child of a ScreenComponent. * * @type {Entity|null} */ screen: Entity | null; _type: string; _image: ImageElement; _text: TextElement; _group: any; _drawOrder: number; _fitMode: string; _useInput: boolean; _layers: number[]; _addedModels: any[]; _batchGroupId: number; _offsetReadAt: number; _maskOffset: number; _maskedBy: any; /** * @type {number} * @private */ private get _absLeft(); /** * @type {number} * @private */ private get _absRight(); /** * @type {number} * @private */ private get _absTop(); /** * @type {number} * @private */ private get _absBottom(); /** * @type {boolean} * @private */ private get _hasSplitAnchorsX(); /** * @type {boolean} * @private */ private get _hasSplitAnchorsY(); /** * Gets the world space axis-aligned bounding box for this element component. * * @type {BoundingBox | null} */ get aabb(): BoundingBox | null; /** * Sets the anchor for this element component. Specifies where the left, bottom, right and top * edges of the component are anchored relative to its parent. Each value ranges from 0 to 1. * e.g. a value of `[0, 0, 0, 0]` means that the element will be anchored to the bottom left of * its parent. A value of `[1, 1, 1, 1]` means it will be anchored to the top right. A split * anchor is when the left-right or top-bottom pairs of the anchor are not equal. In that case, * the component will be resized to cover that entire area. For example, a value of `[0, 0, 1, 1]` * will make the component resize exactly as its parent. * * @example * this.entity.element.anchor = new Vec4(Math.random() * 0.1, 0, 1, 0); * @example * this.entity.element.anchor = [Math.random() * 0.1, 0, 1, 0]; * * @type {Vec4 | number[]} */ set anchor(value: Readonly); /** * Gets the anchor for this element component. Use the setter to update the anchor. * * @type {Readonly} */ get anchor(): Readonly; /** * Sets the batch group (see {@link BatchGroup}) for this element. Default is -1 (no group). * * @type {number} */ set batchGroupId(value: number); /** * Gets the batch group (see {@link BatchGroup}) for this element. * * @type {number} */ get batchGroupId(): number; /** * Sets the distance from the bottom edge of the anchor. Can be used in combination with a * split anchor to make the component's bottom edge always be 'bottom' units away from the * bottom. * * @type {number} */ set bottom(value: number); /** * Gets the distance from the bottom edge of the anchor. * * @type {number} */ get bottom(): number; /** * Sets the width at which the element will be rendered. In most cases this will be the same as * {@link width}. However, in some cases the engine may calculate a different width for the * element, such as when the element is under the control of a {@link LayoutGroupComponent}. In * these scenarios, `calculatedWidth` may be smaller or larger than the width that was set in * the editor. * * @type {number} */ set calculatedWidth(value: number); /** * Gets the width at which the element will be rendered. * * @type {number} */ get calculatedWidth(): number; /** * Sets the height at which the element will be rendered. In most cases this will be the same * as {@link height}. However, in some cases the engine may calculate a different height for * the element, such as when the element is under the control of a {@link LayoutGroupComponent}. * In these scenarios, `calculatedHeight` may be smaller or larger than the height that was set * in the editor. * * @type {number} */ set calculatedHeight(value: number); /** * Gets the height at which the element will be rendered. * * @type {number} */ get calculatedHeight(): number; /** * Gets the array of 4 {@link Vec2}s that represent the bottom left, bottom right, top right * and top left corners of the component in canvas pixels. Only works for screen space element * components. * * @type {Vec2[]} */ get canvasCorners(): Vec2[]; /** * Sets the draw order of the component. A higher value means that the component will be * rendered on top of other components. * * @type {number} */ set drawOrder(value: number); /** * Gets the draw order of the component. * * @type {number} */ get drawOrder(): number; /** * Sets the height of the element as set in the editor. Note that in some cases this may not * reflect the true height at which the element is rendered, such as when the element is under * the control of a {@link LayoutGroupComponent}. See {@link calculatedHeight} in order to * ensure you are reading the true height at which the element will be rendered. * * @type {number} */ set height(value: number); /** * Gets the height of the element. * * @type {number} */ get height(): number; /** * Sets the array of layer IDs ({@link Layer#id}) to which this element should belong. Don't * push, pop, splice or modify this array. If you want to change it, set a new one instead. * * @type {number[]} */ set layers(value: ReadonlyArray); /** * Gets the array of layer IDs ({@link Layer#id}) to which this element belongs. * * @type {ReadonlyArray} */ get layers(): ReadonlyArray; /** * Sets the distance from the left edge of the anchor. Can be used in combination with a split * anchor to make the component's left edge always be 'left' units away from the left. * * @type {number} */ set left(value: number); /** * Gets the distance from the left edge of the anchor. * * @type {number} */ get left(): number; /** * Sets the distance from the left, bottom, right and top edges of the anchor. For example, if * we are using a split anchor like `[0, 0, 1, 1]` and the margin is `[0, 0, 0, 0]` then the * component will be the same width and height as its parent. * * @type {Vec4} */ set margin(value: Readonly); /** * Gets the distance from the left, bottom, right and top edges of the anchor. Use the setter to * update the margin. * * @type {Readonly} */ get margin(): Readonly; /** * Gets the entity that is currently masking this element. * * @type {Entity} * @private */ private get maskedBy(); /** * Sets the position of the pivot of the component relative to its anchor. Each value ranges * from 0 to 1 where `[0, 0]` is the bottom left and `[1, 1]` is the top right. * * @example * this.entity.element.pivot = [Math.random() * 0.1, Math.random() * 0.1]; * @example * this.entity.element.pivot = new Vec2(Math.random() * 0.1, Math.random() * 0.1); * * @type {Vec2 | number[]} */ set pivot(value: Readonly); /** * Gets the position of the pivot of the component relative to its anchor. Use the setter to * update the pivot. * * @type {Readonly} */ get pivot(): Readonly; /** * Sets the distance from the right edge of the anchor. Can be used in combination with a split * anchor to make the component's right edge always be 'right' units away from the right. * * @type {number} */ set right(value: number); /** * Gets the distance from the right edge of the anchor. * * @type {number} */ get right(): number; /** * Gets the array of 4 {@link Vec3}s that represent the bottom left, bottom right, top right * and top left corners of the component relative to its parent {@link ScreenComponent}. * * @type {Vec3[]} */ get screenCorners(): Vec3[]; _calcScreenCorners(left: any, bottom: any, right: any, top: any, corners: any): any; /** * Gets the width of the text rendered by the component. Only works for * {@link ELEMENTTYPE_TEXT} elements. * * @type {number} */ get textWidth(): number; /** * Gets the height of the text rendered by the component. Only works for * {@link ELEMENTTYPE_TEXT} elements. * * @type {number} */ get textHeight(): number; /** * Sets the distance from the top edge of the anchor. Can be used in combination with a split * anchor to make the component's top edge always be 'top' units away from the top. * * @type {number} */ set top(value: number); /** * Gets the distance from the top edge of the anchor. * * @type {number} */ get top(): number; /** * Sets the type of the ElementComponent. Can be: * * - {@link ELEMENTTYPE_GROUP}: The component can be used as a layout mechanism to create * groups of ElementComponents e.g. panels. * - {@link ELEMENTTYPE_IMAGE}: The component will render an image * - {@link ELEMENTTYPE_TEXT}: The component will render text * * @type {string} */ set type(value: string); /** * Gets the type of the ElementComponent. * * @type {string} */ get type(): string; /** * Sets whether the component will receive mouse and touch input events. * * @type {boolean} */ set useInput(value: boolean); /** * Gets whether the component will receive mouse and touch input events. * * @type {boolean} */ get useInput(): boolean; /** * Sets the fit mode of the element. Controls how the content should be fitted and preserve the * aspect ratio of the source texture or sprite. Only works for {@link ELEMENTTYPE_IMAGE} * elements. Can be: * * - {@link FITMODE_STRETCH}: Fit the content exactly to Element's bounding box. * - {@link FITMODE_CONTAIN}: Fit the content within the Element's bounding box while * preserving its Aspect Ratio. * - {@link FITMODE_COVER}: Fit the content to cover the entire Element's bounding box while * preserving its Aspect Ratio. * * @type {string} */ set fitMode(value: string); /** * Gets the fit mode of the element. * * @type {string} */ get fitMode(): string; /** * Sets the width of the element as set in the editor. Note that in some cases this may not * reflect the true width at which the element is rendered, such as when the element is under * the control of a {@link LayoutGroupComponent}. See {@link calculatedWidth} in order to * ensure you are reading the true width at which the element will be rendered. * * @type {number} */ set width(value: number); /** * Gets the width of the element. * * @type {number} */ get width(): number; /** * Gets the array of 4 {@link Vec3}s that represent the bottom left, bottom right, top right * and top left corners of the component in world space. Only works for 3D element components. * * @type {Vec3[]} */ get worldCorners(): Vec3[]; /** * Sets the size of the font. Measured in the same units as the element's {@link width} and * {@link height}, so its on-screen size depends on whether the element is screen-space or in * world space. Defaults to 32. Only works for {@link ELEMENTTYPE_TEXT} elements. * * @type {number} */ set fontSize(arg: number); /** * Gets the size of the font. * * @type {number} */ get fontSize(): number; /** * Sets the minimum size that the font can scale to when {@link autoFitWidth} or * {@link autoFitHeight} are true. Defaults to 8. * * @type {number} */ set minFontSize(arg: number); /** * Gets the minimum size that the font can scale to when {@link autoFitWidth} or * {@link autoFitHeight} are true. * * @type {number} */ get minFontSize(): number; /** * Sets the maximum size that the font can scale to when {@link autoFitWidth} or * {@link autoFitHeight} are true. Defaults to 32. * * @type {number} */ set maxFontSize(arg: number); /** * Gets the maximum size that the font can scale to when {@link autoFitWidth} or * {@link autoFitHeight} are true. * * @type {number} */ get maxFontSize(): number; /** * Sets the maximum number of lines that the Element can wrap to. Any leftover text will be * appended to the last line. Set this to null to allow unlimited lines. * * @type {number|null} */ set maxLines(arg: number | null); /** * Gets the maximum number of lines that the Element can wrap to. Returns -1 if there is no * limit. * * @type {number|null} */ get maxLines(): number | null; /** * Sets whether the font size and line height will scale so that the text fits inside the width * of the Element. The font size will be scaled between {@link minFontSize} and * {@link maxFontSize}. The value of {@link autoFitWidth} will be ignored if {@link autoWidth} * is true. * * @type {boolean} */ set autoFitWidth(arg: boolean); /** * Gets whether the font size and line height will scale so that the text fits inside the width * of the Element. * * @type {boolean} */ get autoFitWidth(): boolean; /** * Sets whether the font size and line height will scale so that the text fits inside the * height of the Element. The font size will be scaled between {@link minFontSize} and * {@link maxFontSize}. The value of {@link autoFitHeight} will be ignored if * {@link autoHeight} is true. * * @type {boolean} */ set autoFitHeight(arg: boolean); /** * Gets whether the font size and line height will scale so that the text fits inside the * height of the Element. * * @type {boolean} */ get autoFitHeight(): boolean; /** * Sets the color of the image for {@link ELEMENTTYPE_IMAGE} elements or the color of the text for * {@link ELEMENTTYPE_TEXT} elements, specified in sRGB color space. Only the RGB channels are * used; the alpha channel is ignored, so use {@link opacity} to control transparency. * * @type {Color} */ set color(arg: Readonly); /** * Gets the color of the element. Use the setter to update the color. * * @type {Readonly} */ get color(): Readonly; /** * Sets the font used for rendering the text. Only works for {@link ELEMENTTYPE_TEXT} elements. * * @type {Font|CanvasFont} */ set font(arg: Font | CanvasFont); /** * Gets the font used for rendering the text. * * @type {Font|CanvasFont} */ get font(): Font | CanvasFont; /** * Sets the font asset used for rendering the text, as either an {@link Asset} or an asset id. * Only works for {@link ELEMENTTYPE_TEXT} elements. * * @type {Asset | number | null} */ set fontAsset(arg: Asset | number | null); /** * Gets the id of the font asset used for rendering the text. * * @type {Asset | number | null} */ get fontAsset(): Asset | number | null; /** * Sets the spacing between the letters of the text, as a multiplier on the default character * advance, defaulting to 1 (normal spacing). Values below 1 tighten the text and values above 1 * spread it out. Only works for {@link ELEMENTTYPE_TEXT} elements. * * @type {number} */ set spacing(arg: number); /** * Gets the spacing between the letters of the text. * * @type {number} */ get spacing(): number; /** * Sets the height of each line of text, measured in the same units as {@link fontSize}. This is * independent of {@link fontSize}, so it can be used to tighten or loosen vertical line * spacing. Defaults to 32. Only works for {@link ELEMENTTYPE_TEXT} elements. * * @type {number} */ set lineHeight(arg: number); /** * Gets the height of each line of text. * * @type {number} */ get lineHeight(): number; /** * Sets whether to automatically wrap lines based on the element width. Only works for * {@link ELEMENTTYPE_TEXT} elements, and when {@link autoWidth} is set to false. * * @type {boolean} */ set wrapLines(arg: boolean); /** * Gets whether to automatically wrap lines based on the element width. * * @type {boolean} */ get wrapLines(): boolean; /** * Sets whether wrapped lines are stretched to be flush with both edges of the element, by * widening the gaps between their words. The last line of the text and any line ended by an * explicit line break are not stretched, and follow {@link alignment} instead - as does a line * with no gaps to widen. Only works for {@link ELEMENTTYPE_TEXT} elements, and only has an * effect when {@link wrapLines} is set to true and the element has a fixed width. * * @type {boolean} */ set justify(arg: boolean); /** * Gets whether wrapped lines are stretched to be flush with both edges of the element. * * @type {boolean} */ get justify(): boolean; /** * Gets the lines of rendered text, split by line breaks and word wrapping. Only works for * {@link ELEMENTTYPE_TEXT} elements, and is populated when the text is laid out, so it reads as * `undefined` until the first update. * * @type {string[]} */ get lines(): string[]; /** * Sets the horizontal and vertical alignment of the text. Values range from 0 to 1 where * `[0, 0]` is the bottom left and `[1, 1]` is the top right. Only works for * {@link ELEMENTTYPE_TEXT} elements. * * @type {Vec2} */ set alignment(arg: Vec2); /** * Gets the horizontal and vertical alignment of the text. * * @type {Vec2} */ get alignment(): Vec2; /** * Sets whether to automatically set the width of the component to be the same as the * {@link textWidth}. Only works for {@link ELEMENTTYPE_TEXT} elements. * * @type {boolean} */ set autoWidth(arg: boolean); /** * Gets whether to automatically set the width of the component to be the same as the * {@link textWidth}. * * @type {boolean} */ get autoWidth(): boolean; /** * Sets whether to automatically set the height of the component to be the same as the * {@link textHeight}. Only works for {@link ELEMENTTYPE_TEXT} elements. * * @type {boolean} */ set autoHeight(arg: boolean); /** * Gets whether to automatically set the height of the component to be the same as the * {@link textHeight}. * * @type {boolean} */ get autoHeight(): boolean; /** * Sets whether to reorder the text for RTL languages. The reordering uses a function * registered by `app.systems.element.registerRtlReorder`. * * @type {boolean} */ set rtlReorder(arg: boolean); /** * Gets whether to reorder the text for RTL languages. * * @type {boolean} */ get rtlReorder(): boolean; /** * Sets whether to convert unicode characters. This uses a function registered by * `app.systems.element.registerUnicodeConverter`. * * @type {boolean} */ set unicodeConverter(arg: boolean); /** * Gets whether to convert unicode characters. * * @type {boolean} */ get unicodeConverter(): boolean; /** * Sets the text to render. Only works for {@link ELEMENTTYPE_TEXT} elements. To override certain * text styling properties on a per-character basis, the text can optionally include markup * tags contained within square brackets. Supported tags are: * * 1. `color` - override the element's {@link color} property. Examples: * - `[color="#ff0000"]red text[/color]` * - `[color="#00ff00"]green text[/color]` * - `[color="#0000ff"]blue text[/color]` * 2. `outline` - override the element's {@link outlineColor} and {@link outlineThickness} * properties. Example: * - `[outline color="#ffffff" thickness="0.5"]text[/outline]` * 3. `shadow` - override the element's {@link shadowColor} and {@link shadowOffset} * properties. Examples: * - `[shadow color="#ffffff" offset="0.5"]text[/shadow]` * - `[shadow color="#000000" offsetX="0.1" offsetY="0.2"]text[/shadow]` * * Note that markup tags are only processed if the text element's {@link enableMarkup} property * is set to true. * * @type {string} */ set text(arg: string); /** * Gets the text to render. * * @type {string} */ get text(): string; /** * Sets the localization key to use to get the localized text from {@link Application#i18n}. * Only works for {@link ELEMENTTYPE_TEXT} elements. * * @type {string} */ set key(arg: string); /** * Gets the localization key to use to get the localized text from {@link Application#i18n}. * * @type {string} */ get key(): string; /** * Sets the texture to render. Only works for {@link ELEMENTTYPE_IMAGE} elements. * * @type {Texture} */ set texture(arg: Texture); /** * Gets the texture to render. * * @type {Texture} */ get texture(): Texture; /** * Sets the texture asset to render, as either an {@link Asset} or an asset id. Only works for * {@link ELEMENTTYPE_IMAGE} elements. * * @type {Asset | number | null} */ set textureAsset(arg: Asset | number | null); /** * Gets the id of the texture asset to render. * * @type {Asset | number | null} */ get textureAsset(): Asset | number | null; /** * Sets the material to use when rendering an image. Only works for {@link ELEMENTTYPE_IMAGE} elements. * * @type {Material} */ set material(arg: Material); /** * Gets the material to use when rendering an image. * * @type {Material} */ get material(): Material; /** * Sets the material asset to use when rendering an image, as either an {@link Asset} or an * asset id. Only works for {@link ELEMENTTYPE_IMAGE} elements. * * @type {Asset | number | null} */ set materialAsset(arg: Asset | number | null); /** * Gets the id of the material asset to use when rendering an image. * * @type {Asset | number | null} */ get materialAsset(): Asset | number | null; /** * Sets the sprite to render. Only works for {@link ELEMENTTYPE_IMAGE} elements that can render * either a texture or a sprite. * * @type {Sprite} */ set sprite(arg: Sprite); /** * Gets the sprite to render. * * @type {Sprite} */ get sprite(): Sprite; /** * Sets the sprite asset to render, as either an {@link Asset} or an asset id. Only works for * {@link ELEMENTTYPE_IMAGE} elements that can render either a texture or a sprite. * * @type {Asset | number | null} */ set spriteAsset(arg: Asset | number | null); /** * Gets the id of the sprite asset to render. * * @type {Asset | number | null} */ get spriteAsset(): Asset | number | null; /** * Sets the frame of the sprite to render. Only works for {@link ELEMENTTYPE_IMAGE} elements that have a * sprite assigned. * * @type {number} */ set spriteFrame(arg: number); /** * Gets the frame of the sprite to render. * * @type {number} */ get spriteFrame(): number; /** * Sets the number of pixels that map to one PlayCanvas unit. Only affects * {@link ELEMENTTYPE_IMAGE} elements with a sliced or tiled sprite assigned. Set to null to use * the sprite's own pixels-per-unit value. * * @type {number|null} */ set pixelsPerUnit(arg: number | null); /** * Gets the number of pixels that map to one PlayCanvas unit. * * @type {number|null} */ get pixelsPerUnit(): number | null; /** * Sets the opacity of the element. This works for both {@link ELEMENTTYPE_IMAGE} and * {@link ELEMENTTYPE_TEXT} elements. * * @type {number} */ set opacity(arg: number); /** * Gets the opacity of the element. * * @type {number} */ get opacity(): number; /** * Sets the region of the texture to use in order to render an image. Values range from 0 to 1 * and indicate u, v, width, height. Only works for {@link ELEMENTTYPE_IMAGE} elements. * * @type {Vec4} */ set rect(arg: Readonly | null); /** * Gets the region of the texture to use in order to render an image. Use the setter to update * the region. * * @type {Readonly|null} */ get rect(): Readonly | null; /** * Sets whether the Image Element should be treated as a mask. Masks do not render into the * scene, but instead limit child elements to only be rendered where this element is rendered. * * @type {boolean} */ set mask(arg: boolean); /** * Gets whether the Image Element should be treated as a mask. * * @type {boolean} */ get mask(): boolean; /** * Sets the text outline effect color and opacity, with the color specified in sRGB color space. * Only works for {@link ELEMENTTYPE_TEXT} elements. * * @type {Color} */ set outlineColor(arg: Color); /** * Gets the text outline effect color and opacity. * * @type {Color} */ get outlineColor(): Color; /** * Sets the width of the text outline effect, ranging from 0 (no outline) to 1 (maximum * thickness). Defaults to 0. Combine with {@link outlineColor} to style the outline. Only works * for {@link ELEMENTTYPE_TEXT} elements. * * @type {number} */ set outlineThickness(arg: number); /** * Gets the width of the text outline effect. * * @type {number} */ get outlineThickness(): number; /** * Sets the text shadow effect color and opacity, with the color specified in sRGB color space. * Only works for {@link ELEMENTTYPE_TEXT} elements. * * @type {Color} */ set shadowColor(arg: Color); /** * Gets the text shadow effect color and opacity. * * @type {Color} */ get shadowColor(): Color; /** * Sets the offset of the text shadow, relative to the text. The shadow is a second copy of the * text, tinted with {@link shadowColor} and displaced by this amount. Each component ranges * from -1 to 1 and is proportional to the font size, so the shadow stays consistent as the text * scales; positive x shifts the shadow right and positive y shifts it up. The shadow is only * drawn where it extends past the glyph, so the default of `[0, 0]` produces no visible shadow * and a non-zero offset is required to display one. Only works for {@link ELEMENTTYPE_TEXT} * elements. * * @type {Vec2} * @example * // drop shadow, down and to the right of the text * this.entity.element.shadowOffset = new Vec2(0.25, -0.25); */ set shadowOffset(arg: Vec2); /** * Gets the offset of the text shadow, relative to the text. * * @type {Vec2} */ get shadowOffset(): Vec2; /** * Sets whether markup processing is enabled for this element. Only works for * {@link ELEMENTTYPE_TEXT} elements. Defaults to false. * * @type {boolean} */ set enableMarkup(arg: boolean); /** * Gets whether markup processing is enabled for this element. * * @type {boolean} */ get enableMarkup(): boolean; /** * Sets the index of the first character to render. Only works for {@link ELEMENTTYPE_TEXT} elements. * * @type {number} */ set rangeStart(arg: number); /** * Gets the index of the first character to render. * * @type {number} */ get rangeStart(): number; /** * Sets the index of the last character to render. Only works for {@link ELEMENTTYPE_TEXT} elements. * * @type {number} */ set rangeEnd(arg: number); /** * Gets the index of the last character to render. * * @type {number} */ get rangeEnd(): number; /** @ignore */ _setValue(name: any, value: any): void; _patch(): void; _unpatch(): void; /** * Patched method for setting the position. * * @param {number|Vec3} x - The x coordinate or Vec3 * @param {number} [y] - The y coordinate * @param {number} [z] - The z coordinate * @private */ private _setPosition; /** * Patched method for setting the local position. * * @param {number|Vec3} x - The x coordinate or Vec3 * @param {number} [y] - The y coordinate * @param {number} [z] - The z coordinate * @private */ private _setLocalPosition; _sync(): void; _dirtyLocal: boolean; _dirtyWorld: boolean; _onInsert(parent: any): void; _dirtifyMask(): void; _onPrerender(): void; _bindScreen(screen: any): void; _unbindScreen(screen: any): void; _updateScreen(screen: any): void; syncMask(depth: any): void; _setMaskedBy(mask: any): void; _updateMask(currentMask: any, depth: any): void; _parseUpToScreen(): { screen: any; mask: any; }; _onScreenResize(res: any): void; _onScreenSpaceChange(): void; _onScreenRemove(): void; _calculateLocalAnchors(): void; getOffsetPosition(x: any, y: any): Vec3; onLayersChanged(oldComp: any, newComp: any): void; onLayerAdded(layer: any): void; onLayerRemoved(layer: any): void; onBeforeRemove(): void; /** * Recalculates these properties: * - `_localAnchor` * - `width` * - `height` * - Local position is updated if anchors are split * * Assumes these properties are up to date: * - `_margin` * * @param {boolean} propagateCalculatedWidth - If true, call `_setWidth` instead * of `_setCalculatedWidth` * @param {boolean} propagateCalculatedHeight - If true, call `_setHeight` instead * of `_setCalculatedHeight` * @private */ private _calculateSize; _sizeDirty: boolean; /** * Internal set width without updating margin. * * @param {number} w - The new width. * @private */ private _setWidth; /** * Internal set height without updating margin. * * @param {number} h - The new height. * @private */ private _setHeight; /** * This method sets the calculated width value and optionally updates the margins. * * @param {number} value - The new calculated width. * @param {boolean} updateMargins - Update margins or not. * @private */ private _setCalculatedWidth; /** * This method sets the calculated height value and optionally updates the margins. * * @param {number} value - The new calculated height. * @param {boolean} updateMargins - Update margins or not. * @private */ private _setCalculatedHeight; _flagChildrenAsDirty(): void; addModelToLayers(model: any): void; removeModelFromLayers(model: any): void; getMaskOffset(): number; isVisibleForCamera(camera: any): boolean; _isScreenSpace(): boolean; _isScreenCulled(): boolean; _dirtyBatch(): void; } /** * Handles mouse and touch events for {@link ElementComponent}s. When input events occur on an * ElementComponent this fires the appropriate events on the ElementComponent. * * Relevant Engine API examples: * * - [Input events](https://playcanvas.github.io/#/user-interface/input-events) * * @category User Interface */ declare class ElementInput { static buildHitCorners(element: any, screenOrWorldCorners: any, scale: any): any; static calculateScaleToScreen(element: any): Vec3; static calculateScaleToWorld(element: any): Vec3; /** * Create a new ElementInput instance. * * @param {Element} domElement - The DOM element. * @param {object} [options] - Optional arguments. * @param {boolean} [options.useMouse] - Whether to allow mouse input. Defaults to true. * @param {boolean} [options.useTouch] - Whether to allow touch input. Defaults to true. * @param {boolean} [options.useXr] - Whether to allow XR input sources. Defaults to true. */ constructor(domElement: Element, options?: { useMouse?: boolean; useTouch?: boolean; useXr?: boolean; }); _app: any; _attached: boolean; _target: Element; _enabled: boolean; _lastX: number; _lastY: number; _upHandler: any; _downHandler: any; _moveHandler: any; _wheelHandler: any; _touchstartHandler: any; _touchendHandler: any; _touchcancelHandler: any; _touchmoveHandler: any; _sortHandler: any; _elements: any[]; _hoveredElement: any; _pressedElement: any; _touchedElements: {}; _touchesForWhichTouchLeaveHasFired: {}; _selectedElements: {}; _selectedPressedElements: {}; _useMouse: boolean; _useTouch: boolean; _useXr: boolean; _selectEventsAttached: boolean; _clickedEntities: {}; set enabled(value: boolean); get enabled(): boolean; set app(value: any); get app(): any; /** * Attach mouse and touch events to a DOM element. * * @param {Element} domElement - The DOM element. */ attach(domElement: Element): void; attachSelectEvents(): void; /** * Remove mouse and touch events from the DOM element that it is attached to. */ detach(): void; /** * Add a {@link ElementComponent} to the internal list of ElementComponents that are being * checked for input. * * @param {ElementComponent} element - The * ElementComponent. */ addElement(element: ElementComponent): void; /** * Remove a {@link ElementComponent} from the internal list of ElementComponents that are being * checked for input. * * @param {ElementComponent} element - The * ElementComponent. */ removeElement(element: ElementComponent): void; _handleUp(event: any): void; _handleDown(event: any): void; _handleMove(event: any): void; _handleWheel(event: any): void; _determineTouchedElements(event: any): {}; _handleTouchStart(event: any): void; _handleTouchEnd(event: any): void; _handleTouchMove(event: any): void; _onElementMouseEvent(eventType: any, event: any): void; _onXrStart(): void; _onXrEnd(): void; _onXrUpdate(): void; _onXrInputRemove(inputSource: any): void; _onSelectStart(inputSource: any, event: any): void; _onSelectEnd(inputSource: any, event: any): void; _onElementSelectEvent(eventType: any, inputSource: any, event: any): void; _fireEvent(name: any, evt: any): void; _calcMouseCoords(event: any): void; _sortElements(a: any, b: any): any; _getTargetElementByCoords(camera: any, x: any, y: any): any; _getTargetElementByRay(ray: any, camera: any): any; _getTargetElement(camera: any, rayScreen: any, ray3d: any): any; _calculateRayScreen(x: any, y: any, camera: any, ray: any): boolean; _calculateRay3d(x: any, y: any, camera: any, ray: any): boolean; _checkElement(ray: any, element: any, screen: any): number; /** * Gets the mouse wheel value. * * @type {number} * @ignore * @deprecated Use {@link ElementMouseEvent#wheelDelta} instead. */ get wheel(): number; } /** * Represents an input event fired on a {@link ElementComponent}. When an event is raised on an * ElementComponent it bubbles up to its parent ElementComponents unless we call stopPropagation(). * * @category User Interface */ declare class ElementInputEvent { /** * Create a new ElementInputEvent instance. * * @param {globalThis.MouseEvent|globalThis.TouchEvent|XRInputSourceEvent|null} event - The * browser event that was originally raised, or null if there was none. * @param {ElementComponent} element - The ElementComponent that this event was originally * raised on. * @param {CameraComponent} camera - The CameraComponent that this event was originally raised * via. */ constructor(event: globalThis.MouseEvent | globalThis.TouchEvent | XRInputSourceEvent | null, element: ElementComponent, camera: CameraComponent); /** * The browser event that was originally raised: a MouseEvent, TouchEvent or * XRInputSourceEvent. It is null when no browser event caused this one, as for * `selectmove`. * * @type {globalThis.MouseEvent|globalThis.TouchEvent|XRInputSourceEvent|null} */ event: globalThis.MouseEvent | globalThis.TouchEvent | XRInputSourceEvent | null; /** * The ElementComponent that this event was originally raised on. * * @type {ElementComponent} */ element: ElementComponent; /** * The CameraComponent that this event was originally raised via. * * @type {CameraComponent} */ camera: CameraComponent; _stopPropagation: boolean; /** * Stop propagation of the event to parent {@link ElementComponent}s. This also stops * propagation of the event to other event listeners of the original DOM Event. */ stopPropagation(): void; } /** * Represents a Mouse event fired on a {@link ElementComponent}. * * @category User Interface */ declare class ElementMouseEvent extends ElementInputEvent { /** * Create an instance of an ElementMouseEvent. * * @param {globalThis.MouseEvent|globalThis.WheelEvent} event - The browser MouseEvent or * WheelEvent that was originally raised. * @param {ElementComponent} element - The * ElementComponent that this event was originally raised on. * @param {CameraComponent} camera - The * CameraComponent that this event was originally raised via. * @param {number} x - The x coordinate. * @param {number} y - The y coordinate. * @param {number} lastX - The last x coordinate. * @param {number} lastY - The last y coordinate. */ constructor(event: globalThis.MouseEvent | globalThis.WheelEvent, element: ElementComponent, camera: CameraComponent, x: number, y: number, lastX: number, lastY: number); x: number; y: number; /** * Whether the ctrl key was pressed. * * @type {boolean} */ ctrlKey: boolean; /** * Whether the alt key was pressed. * * @type {boolean} */ altKey: boolean; /** * Whether the shift key was pressed. * * @type {boolean} */ shiftKey: boolean; /** * Whether the meta key was pressed. * * @type {boolean} */ metaKey: boolean; /** * The mouse button. * * @type {number} */ button: number; /** * The amount of horizontal movement of the cursor. * * @type {number} */ dx: number; /** * The amount of vertical movement of the cursor. * * @type {number} */ dy: number; /** * The amount of the wheel movement. */ wheelDelta: number; } /** * Represents a XRInputSourceEvent fired on a {@link ElementComponent}. * * @category User Interface */ declare class ElementSelectEvent extends ElementInputEvent { /** * Create an instance of an ElementSelectEvent. * * @param {XRInputSourceEvent|null} event - The XRInputSourceEvent that was originally raised, * or null if there was none. * @param {ElementComponent} element - The * ElementComponent that this event was originally raised on. * @param {CameraComponent} camera - The * CameraComponent that this event was originally raised via. * @param {XrInputSource} inputSource - The XR input source * that this event was originally raised from. */ constructor(event: XRInputSourceEvent | null, element: ElementComponent, camera: CameraComponent, inputSource: XrInputSource); /** * The XR input source that this event was originally raised from. * * @type {XrInputSource} */ inputSource: XrInputSource; } /** * Represents a TouchEvent fired on a {@link ElementComponent}. It carries the browser's own * TouchEvent and Touch objects. * * @category User Interface */ declare class ElementTouchEvent extends ElementInputEvent { /** * Create an instance of an ElementTouchEvent. * * @param {globalThis.TouchEvent} event - The browser TouchEvent that was originally raised. * @param {ElementComponent} element - The * ElementComponent that this event was originally raised on. * @param {CameraComponent} camera - The * CameraComponent that this event was originally raised via. * @param {number} x - The x coordinate of the touch that triggered the event. * @param {number} y - The y coordinate of the touch that triggered the event. * @param {globalThis.Touch} touch - The browser Touch that triggered the event. */ constructor(event: globalThis.TouchEvent, element: ElementComponent, camera: CameraComponent, x: number, y: number, touch: globalThis.Touch); /** * The Touch objects representing all current points of contact with the surface, * regardless of target or changed status. * * @type {globalThis.TouchList} */ touches: globalThis.TouchList; /** * The Touch objects representing individual points of contact whose states changed between * the previous touch event and this one. * * @type {globalThis.TouchList} */ changedTouches: globalThis.TouchList; x: number; y: number; /** * The browser Touch that triggered the event. Match a touch across events by its * `identifier`. * * @type {globalThis.Touch} */ touch: globalThis.Touch; } /** * Manages keyboard input by tracking key states and dispatching events. Extends {@link EventHandler} * in order to fire `keydown` and `keyup` events (see {@link KeyboardEvent}). * * Allows the state of individual keys to be queried to check if they are currently pressed or were * pressed/released since the last update. The class automatically handles browser visibility * changes and window blur events by clearing key states. The Keyboard instance must be attached to * a DOM element before it can detect key events. * * Key state is derived from the legacy `KeyboardEvent.keyCode` property. Browsers populate it for * real input, but a hand-constructed `new KeyboardEvent(...)` leaves it at 0, so synthesized events * must set `keyCode` explicitly in order to be observed. * * {@link Keyboard#wasPressed} and {@link Keyboard#wasReleased} compare against a snapshot taken * once per frame, so a keydown and keyup delivered within the same task are seen by neither. Hold * the key across at least one frame. * * Your application's Keyboard instance is managed and accessible via {@link AppBase#keyboard}. * * For pointer-lock-aware, frame-accumulated input deltas rather than raw events, see * {@link KeyboardMouseSource}, {@link GamepadSource} and {@link MultiTouchSource}, which feed * {@link InputController}s such as {@link OrbitController}, {@link FlyController} and * {@link FocusController}. * * @category Input Devices */ declare class Keyboard extends EventHandler { /** * Fired when a key is pressed. The handler is passed a {@link KeyboardEvent}. * * @event * @example * const onKeyDown = (e) => { * if (e.key === KEY_SPACE) { * // space key pressed * } * e.event.preventDefault(); // Use original browser event to prevent browser action. * }; * * app.keyboard.on('keydown', onKeyDown, this); */ static EVENT_KEYDOWN: string; /** * Fired when a key is released. The handler is passed a {@link KeyboardEvent}. * * @event * @example * const onKeyUp = (e) => { * if (e.key === KEY_SPACE) { * // space key released * } * e.event.preventDefault(); // Use original browser event to prevent browser action. * }; * * app.keyboard.on('keyup', onKeyUp, this); */ static EVENT_KEYUP: string; /** * Create a new Keyboard instance. * * @param {Element|Window} [element] - Element to attach Keyboard to. Note that elements like * <div> can't accept focus by default. To use keyboard events on an element like this it * must have a value of 'tabindex' e.g. tabindex="0". See * [here](https://www.w3.org/WAI/GL/WCAG20/WD-WCAG20-TECHS/SCR29.html) for more details. * @param {object} [options] - Optional options object. * @param {boolean} [options.preventDefault] - Call preventDefault() in key event handlers. * This stops the default action of the event occurring. e.g. Ctrl+T will not open a new * browser tab. * @param {boolean} [options.stopPropagation] - Call stopPropagation() in key event handlers. * This stops the event bubbling up the DOM so no parent handlers will be notified of the * event. * @example * // attach keyboard listeners to the window * const keyboard = new Keyboard(window); */ constructor(element?: Element | Window, options?: { preventDefault?: boolean; stopPropagation?: boolean; }); /** @private */ private _element; /** @private */ private _keymap; /** @private */ private _lastmap; /** * @type {(event: globalThis.KeyboardEvent) => void} * @private */ private _keyDownHandler; /** * @type {(event: globalThis.KeyboardEvent) => void} * @private */ private _keyUpHandler; /** * @type {(event: globalThis.KeyboardEvent) => void} * @private */ private _keyPressHandler; /** * @type {() => void} * @private */ private _visibilityChangeHandler; /** * @type {() => void} * @private */ private _windowBlurHandler; /** * Call preventDefault() in key event handlers. * * @type {boolean} */ preventDefault: boolean; /** * Call stopPropagation() in key event handlers. * * @type {boolean} */ stopPropagation: boolean; /** * Attach the keyboard event handlers to an Element. If already attached, this first detaches * and clears current and previous key states, even when attaching to the same element. No * `keyup` events are fired. Unlike {@link Mouse#attach}, held input states are not preserved. * * @param {Element|Window} element - The element to listen for keyboard events on. */ attach(element: Element | Window): void; /** * Detach the keyboard event handlers from the element it is attached to and clear current and * previous key states. This does not fire `keyup` events. */ detach(): void; /** * Convert a key code into a key identifier. * * @param {number} keyCode - The key code. * @returns {string} The key identifier. * @private */ private toKeyIdentifier; /** * Process the browser keydown event. * * @param {globalThis.KeyboardEvent} event - The browser keyboard event. * @private */ private _handleKeyDown; /** * Process the browser keyup event. * * @param {globalThis.KeyboardEvent} event - The browser keyboard event. * @private */ private _handleKeyUp; /** * Process the browser keypress event. * * @param {globalThis.KeyboardEvent} event - The browser keyboard event. * @private */ private _handleKeyPress; /** * Handle the browser visibilitychange event. * * @private */ private _handleVisibilityChange; /** * Handle the browser blur event. * * @private */ private _handleWindowBlur; /** * Called once per frame to update internal state. * * @ignore */ update(): void; /** * Return true if the key is currently down. * * @param {number} key - The keyCode of the key to test. See the KEY_* constants. * @returns {boolean} True if the key was pressed, false if not. */ isPressed(key: number): boolean; /** * Returns true if the key was pressed since the last update. * * @param {number} key - The keyCode of the key to test. See the KEY_* constants. * @returns {boolean} True if the key was pressed. */ wasPressed(key: number): boolean; /** * Returns true if the key was released since the last update. * * @param {number} key - The keyCode of the key to test. See the KEY_* constants. * @returns {boolean} True if the key was pressed. */ wasReleased(key: number): boolean; } /** * Callback used by {@link Mouse#enablePointerLock} and {@link Mouse#disablePointerLock}. */ type LockMouseCallback = () => void; /** * @callback LockMouseCallback * Callback used by {@link Mouse#enablePointerLock} and {@link Mouse#disablePointerLock}. * @returns {void} */ /** * Manages mouse input by tracking button states and dispatching events. Extends {@link EventHandler} * to fire `mousedown`, `mouseup`, `mousemove` and `mousewheel` events (see {@link MouseEvent}). * * Allows the state of mouse buttons to be queried to check if they are currently pressed or were * pressed/released since the last update. Provides methods to enable/disable pointer lock for * raw mouse movement input and control over the context menu. The class automatically clears * button states when the window loses focus or the document becomes hidden, without firing * `mouseup` events. The Mouse instance must be attached to a DOM element before it can detect * mouse events. * * The first unlocked mouse movement after creation, detachment or focus loss establishes a new * position and reports zero movement delta. Movement outside the target also invalidates the * position, so re-entry reports zero delta. Pointer-locked movement uses the browser's relative * movement deltas. * * Your application's Mouse instance is managed and accessible via {@link AppBase#mouse}. * * For pointer-lock-aware, frame-accumulated input deltas rather than raw events, see * {@link KeyboardMouseSource}, {@link GamepadSource} and {@link MultiTouchSource}, which feed * {@link InputController}s such as {@link OrbitController}, {@link FlyController} and * {@link FocusController}. * * @category Input Devices */ declare class Mouse extends EventHandler { /** * Fired when the mouse is moved. The handler is passed a {@link MouseEvent}. * * @event * @example * app.mouse.on('mousemove', (e) => { * console.log(`Current mouse position is: ${e.x}, ${e.y}`); * }); */ static EVENT_MOUSEMOVE: string; /** * Fired when a mouse button is pressed. The handler is passed a {@link MouseEvent}. * * @event * @example * app.mouse.on('mousedown', (e) => { * console.log(`The ${e.button} button was pressed at position: ${e.x}, ${e.y}`); * }); */ static EVENT_MOUSEDOWN: string; /** * Fired when a mouse button is released. The handler is passed a {@link MouseEvent}. * * @event * @example * app.mouse.on('mouseup', (e) => { * console.log(`The ${e.button} button was released at position: ${e.x}, ${e.y}`); * }); */ static EVENT_MOUSEUP: string; /** * Fired when a mouse wheel is moved. The handler is passed a {@link MouseEvent}. * * @event * @example * app.mouse.on('mousewheel', (e) => { * console.log(`The mouse wheel was moved by ${e.wheelDelta}`); * }); */ static EVENT_MOUSEWHEEL: string; /** * Check if the mouse pointer has been locked, using {@link enablePointerLock}. * * @returns {boolean} True if locked. */ static isPointerLocked(): boolean; /** * Create a new Mouse instance. * * @param {Element} [element] - The Element that the mouse events are attached to. */ constructor(element?: Element); /** @private */ private _lastX; /** @private */ private _lastY; /** @private */ private _lastPositionValid; /** @private */ private _buttons; /** @private */ private _lastbuttons; /** @private */ private _target; /** @private */ private _attached; /** * @type {(event: globalThis.MouseEvent) => void} * @private */ private _upHandler; /** * @type {(event: globalThis.MouseEvent) => void} * @private */ private _downHandler; /** * @type {(event: globalThis.MouseEvent) => void} * @private */ private _moveHandler; /** * @type {(event: globalThis.WheelEvent) => void} * @private */ private _wheelHandler; /** * @type {(event: Event) => void} * @private */ private _contextMenuHandler; /** * @type {() => void} * @private */ private _visibilityChangeHandler; /** * @type {() => void} * @private */ private _windowBlurHandler; /** * Attach mouse events to an Element. If already attached, this changes the target element * while preserving current and previous button states, unlike {@link Keyboard#attach}. * * @param {Element} element - The DOM element to attach the mouse to. */ attach(element: Element): void; /** * Remove mouse events from the element that it is attached to and clear current and previous * button states. The previous mouse position is also invalidated so the next unlocked movement * reports zero delta. This does not fire `mouseup` events. */ detach(): void; /** * Disable the context menu usually activated with right-click. */ disableContextMenu(): void; /** * Enable the context menu usually activated with right-click. This option is active by * default. */ enableContextMenu(): void; /** * Request that the browser hides the mouse cursor and locks the mouse to the element. Allowing * raw access to mouse movement input without risking the mouse exiting the element. Notes: * * - In some browsers this will only work when the browser is running in fullscreen mode. See * {@link https://developer.mozilla.org/en-US/docs/Web/API/Fullscreen_API Fullscreen API} for * more details. * - Enabling pointer lock can only be initiated by a user action e.g. in the event handler for * a mouse or keyboard input. * * @param {LockMouseCallback} [success] - Function called if the request for mouse lock is * successful. * @param {LockMouseCallback} [error] - Function called if the request for mouse lock is * unsuccessful. */ enablePointerLock(success?: LockMouseCallback, error?: LockMouseCallback): void; /** * Return control of the mouse cursor to the user. * * @param {LockMouseCallback} [success] - Function called when the mouse lock is disabled. */ disablePointerLock(success?: LockMouseCallback): void; /** * Update method, should be called once per frame. */ update(): void; /** * Returns true if the mouse button is currently pressed. * * @param {number} button - The mouse button to test. Can be: * * - {@link MOUSEBUTTON_LEFT} * - {@link MOUSEBUTTON_MIDDLE} * - {@link MOUSEBUTTON_RIGHT} * * @returns {boolean} True if the mouse button is current pressed. */ isPressed(button: number): boolean; /** * Returns true if the mouse button was pressed this frame (since the last call to update). * * @param {number} button - The mouse button to test. Can be: * * - {@link MOUSEBUTTON_LEFT} * - {@link MOUSEBUTTON_MIDDLE} * - {@link MOUSEBUTTON_RIGHT} * * @returns {boolean} True if the mouse button was pressed since the last update. */ wasPressed(button: number): boolean; /** * Returns true if the mouse button was released this frame (since the last call to update). * * @param {number} button - The mouse button to test. Can be: * * - {@link MOUSEBUTTON_LEFT} * - {@link MOUSEBUTTON_MIDDLE} * - {@link MOUSEBUTTON_RIGHT} * * @returns {boolean} True if the mouse button was released since the last update. */ wasReleased(button: number): boolean; /** * Handle the browser visibilitychange event. * * @private */ private _handleVisibilityChange; /** * Handle the browser blur event. * * @private */ private _handleWindowBlur; _handleUp(event: any): void; _handleDown(event: any): void; _handleMove(event: any): void; _handleWheel(event: any): void; _getTargetCoords(event: any): { x: number; y: number; }; } /** * Manages touch input by handling and dispatching touch events. Extends {@link EventHandler} * to fire `touchstart`, `touchend`, `touchmove`, and `touchcancel` events (see {@link TouchEvent}). * * Detects and processes touch interactions with the attached DOM element, allowing applications * to respond to common touch gestures. The TouchDevice instance must be attached to a DOM element * before it can detect touch events. * * Your application's TouchDevice instance is managed and accessible via {@link AppBase#touch}. * * @category Input Devices */ declare class TouchDevice extends EventHandler { /** * Fired when a touch starts. The handler is passed a {@link TouchEvent}. * * @event * @example * app.touch.on('touchstart', (e) => { * console.log(`Touch started at position: ${e.x}, ${e.y}`); * }); */ static EVENT_TOUCHSTART: string; /** * Fired when a touch ends. The handler is passed a {@link TouchEvent}. * * @event * @example * app.touch.on('touchend', (e) => { * console.log(`Touch ended at position: ${e.x}, ${e.y}`); * }); */ static EVENT_TOUCHEND: string; /** * Fired when a touch moves. The handler is passed a {@link TouchEvent}. * * @event * @example * app.touch.on('touchmove', (e) => { * console.log(`Touch moved to position: ${e.x}, ${e.y}`); * }); */ static EVENT_TOUCHMOVE: string; /** * Fired when a touch is interrupted in some way. The exact reasons for canceling a touch can * vary from device to device. For example, a modal alert pops up during the interaction; the * touch point leaves the document area, or there are more touch points than the device * supports, in which case the earliest touch point is canceled. The handler is passed a * {@link TouchEvent}. * * @event * @example * app.touch.on('touchcancel', (e) => { * console.log(`Touch canceled at position: ${e.x}, ${e.y}`); * }); */ static EVENT_TOUCHCANCEL: string; /** * Create a new touch device and attach it to an element. * * @param {Element} element - The element to attach listen for events on. */ constructor(element: Element); /** * @type {Element|null} * @private */ private _element; /** * @type {(e: globalThis.TouchEvent) => void} * @private */ private _startHandler; /** * @type {(e: globalThis.TouchEvent) => void} * @private */ private _endHandler; /** * @type {(e: globalThis.TouchEvent) => void} * @private */ private _moveHandler; /** * @type {(e: globalThis.TouchEvent) => void} * @private */ private _cancelHandler; /** * Attach a device to an element in the DOM. If the device is already attached to an element * this method will detach it first. * * @param {Element} element - The element to attach to. */ attach(element: Element): void; /** * Detach a device from the element it is attached to. */ detach(): void; _handleTouchStart(e: any): void; _handleTouchEnd(e: any): void; _handleTouchMove(e: any): void; _handleTouchCancel(e: any): void; } /** * Input handler for accessing GamePad input. * * For frame-accumulated input deltas rather than raw pad state, see {@link GamepadSource}, * {@link KeyboardMouseSource} and {@link MultiTouchSource}, which feed {@link InputController}s * such as {@link OrbitController}, {@link FlyController} and {@link FocusController}. * * @category Input Devices */ declare class GamePads extends EventHandler { /** * Fired when a gamepad is connected. The handler is passed the {@link GamePad} object that was * connected. * * @event * @example * const onPadConnected = (pad) => { * if (!pad.mapping) { * // Map the gamepad as the system could not find the proper map. * } else { * // Make the gamepad pulse. * } * }; * * app.keyboard.on("gamepadconnected", onPadConnected, this); */ static EVENT_GAMEPADCONNECTED: string; /** * Fired when a gamepad is disconnected. The handler is passed the {@link GamePad} object that * was disconnected. * * @event * @example * const onPadDisconnected = (pad) => { * // Pause the game. * }; * * app.keyboard.on("gamepaddisconnected", onPadDisconnected, this); */ static EVENT_GAMEPADDISCONNECTED: string; /** * Whether gamepads are supported by this device. * * @type {boolean} */ gamepadsSupported: boolean; /** * The list of current gamepads. * * @type {GamePad[]} */ current: GamePad[]; /** * @type {(event: GamepadEvent) => void} * @private */ private _ongamepadconnectedHandler; /** * @type {(event: GamepadEvent) => void} * @private */ private _ongamepaddisconnectedHandler; /** * Sets the threshold for axes to return values. Must be between 0 and 1. * * @type {number} * @ignore */ set deadZone(value: number); /** * Gets the threshold for axes to return values. * * @type {number} * @ignore */ get deadZone(): number; /** * Callback function when a gamepad is connecting. * * @param {GamepadEvent} event - The event containing the connecting gamepad. * @private */ private _ongamepadconnected; /** * Callback function when a gamepad is disconnecting. * * @param {GamepadEvent} event - The event containing the disconnecting gamepad. * @private */ private _ongamepaddisconnected; /** * Update the previous state of the gamepads. This must be called every frame for * `wasPressed` and `wasTouched` to work. * * @ignore */ update(): void; /** * Poll for the latest data from the gamepad API. * * @param {GamePad[]} [pads] - An optional array used to receive the gamepads mapping. This * array will be returned by this function. * @returns {GamePad[]} An array of gamepads and mappings for the model of gamepad that is * attached. * @example * const gamepads = new GamePads(); * const pads = gamepads.poll(); */ poll(pads?: GamePad[]): GamePad[]; /** * Read the latest state of every connected device into its {@link GamePad}, creating a * GamePad for any device seen for the first time. * * @param {GamePad[]|null} pads - An optional array that receives the polled gamepads. * @private */ private _poll; /** * Destroy the event listeners. * * @ignore */ destroy(): void; /** * Retrieve the order for buttons and axes for given HTML5 Gamepad. * * @param {Gamepad} pad - The HTML5 Gamepad object. * @returns {object} Object defining the order of buttons and axes for given HTML5 Gamepad. */ getMap(pad: Gamepad): object; /** * Returns true if the button on the pad requested is pressed. * * @param {number} orderIndex - The order index of the pad to check, use constants {@link PAD_1}, {@link PAD_2}, etc. For gamepad index call the function from the pad. * @param {number} button - The button to test, use constants {@link PAD_FACE_1}, etc. * @returns {boolean} True if the button is pressed. */ isPressed(orderIndex: number, button: number): boolean; /** * Returns true if the button was pressed since the last frame. * * @param {number} orderIndex - The index of the pad to check, use constants {@link PAD_1}, {@link PAD_2}, etc. For gamepad index call the function from the pad. * @param {number} button - The button to test, use constants {@link PAD_FACE_1}, etc. * @returns {boolean} True if the button was pressed since the last frame. */ wasPressed(orderIndex: number, button: number): boolean; /** * Returns true if the button was released since the last frame. * * @param {number} orderIndex - The index of the pad to check, use constants {@link PAD_1}, {@link PAD_2}, etc. For gamepad index call the function from the pad. * @param {number} button - The button to test, use constants {@link PAD_FACE_1}, etc. * @returns {boolean} True if the button was released since the last frame. */ wasReleased(orderIndex: number, button: number): boolean; /** * Get the value of one of the analog axes of the pad. * * @param {number} orderIndex - The index of the pad to check, use constants {@link PAD_1}, {@link PAD_2}, etc. For gamepad index call the function from the pad. * @param {number} axis - The axis to get the value of, use constants {@link PAD_L_STICK_X}, etc. * @returns {number} The value of the axis between -1 and 1. */ getAxis(orderIndex: number, axis: number): number; /** * Make the gamepad vibrate. * * @param {number} orderIndex - The index of the pad to check, use constants {@link PAD_1}, {@link PAD_2}, etc. For gamepad index call the function from the pad. * @param {number} intensity - Intensity for the vibration in the range 0 to 1. * @param {number} duration - Duration for the vibration in milliseconds. * @param {object} [options] - Options for special vibration pattern. * @param {number} [options.startDelay] - Delay before the pattern starts, in milliseconds. Defaults to 0. * @param {number} [options.strongMagnitude] - Intensity for strong actuators in the range 0 to 1. Defaults to intensity. * @param {number} [options.weakMagnitude] - Intensity for weak actuators in the range 0 to 1. Defaults to intensity. * @returns {Promise} Return a Promise resulting in true if the pulse was successfully completed. */ pulse(orderIndex: number, intensity: number, duration: number, options?: { startDelay?: number; strongMagnitude?: number; weakMagnitude?: number; }): Promise; /** * Make all gamepads vibrate. * * @param {number} intensity - Intensity for the vibration in the range 0 to 1. * @param {number} duration - Duration for the vibration in milliseconds. * @param {object} [options] - Options for special vibration pattern. * @param {number} [options.startDelay] - Delay before the pattern starts, in milliseconds. Defaults to 0. * @param {number} [options.strongMagnitude] - Intensity for strong actuators in the range 0 to 1. Defaults to intensity. * @param {number} [options.weakMagnitude] - Intensity for weak actuators in the range 0 to 1. Defaults to intensity. * @returns {Promise} Return a Promise resulting in an array of booleans defining if the pulse was successfully completed for every gamepads. */ pulseAll(intensity: number, duration: number, options?: { startDelay?: number; strongMagnitude?: number; weakMagnitude?: number; }): Promise; /** * Find a connected {@link GamePad} from its identifier. * * @param {string} id - The identifier to search for. * @returns {GamePad|null} The {@link GamePad} with the matching identifier or null if no gamepad is found or the gamepad is not connected. */ findById(id: string): GamePad | null; /** * Find a connected {@link GamePad} from its device index. * * @param {number} index - The device index to search for. * @returns {GamePad|null} The {@link GamePad} with the matching device index or null if no gamepad is found or the gamepad is not connected. */ findByIndex(index: number): GamePad | null; } /** * A GamePad stores information about a gamepad from the Gamepad API. * * @category Input Devices */ declare class GamePad { /** * Create a new GamePad Instance. * * @param {Gamepad} gamepad - The original Gamepad API gamepad. * @param {object} map - The buttons and axes map. * @ignore */ constructor(gamepad: Gamepad, map: object); /** * The compiled mapping to reduce lookup delay when retrieving buttons * * @type {object} * @private */ private _compiledMapping; /** * The identifier for the gamepad. Its structure depends on device. * * @type {string} */ id: string; /** * The index for this controller. A gamepad that is disconnected and reconnected will retain the same index. * * @type {number} */ index: number; /** * The buttons present on the GamePad. Order is provided by API, use GamePad#buttons instead. * * @type {GamePadButton[]} * @private */ private _buttons; /** * The axes values from the GamePad. Order is provided by API, use GamePad#axes instead. * * @type {number[]} * @private */ private _axes; /** * Previous value for the analog axes present on the gamepad. Values are between -1 and 1. * * @type {number[]} * @private */ private _previousAxes; /** * The gamepad mapping detected by the browser. Value is either "standard", "xr-standard", "" or "custom". When empty string, you may need to update the mapping yourself. "custom" means you updated the mapping. * * @type {string} */ mapping: string; /** * The buttons and axes map. * * @type {object} */ map: object; /** * The hand this gamepad is usually handled on. Only relevant for XR pads. Value is either "left", "right" or "none". * * @type {string} */ hand: string; /** * The original Gamepad API gamepad. * * @type {Gamepad} * @ignore */ pad: Gamepad; /** * Gets whether the gamepad is connected. * * @type {boolean} */ get connected(): boolean; /** * Compile the buttons mapping to reduce lookup delay. * * @private */ private _compileMapping; /** * Update the existing GamePad Instance. * * @param {Gamepad} gamepad - The original Gamepad API gamepad. * @ignore */ update(gamepad: Gamepad): this; /** * Update the map for this gamepad. * * @param {object} map - The new mapping for this gamepad. * @param {string[]} map.buttons - Buttons mapping for this gamepad. * @param {string[]} map.axes - Axes mapping for this gamepad. * @param {object} [map.synthesizedButtons] - Information about buttons to pull from axes for this gamepad. Requires definition of axis index, min value and max value. * @param {"custom"} [map.mapping] - New mapping format. Will be forced into "custom". * @example * this.pad.updateMap({ * buttons: [[ * 'PAD_FACE_1', * 'PAD_FACE_2', * 'PAD_FACE_3', * 'PAD_FACE_4', * 'PAD_L_SHOULDER_1', * 'PAD_R_SHOULDER_1', * 'PAD_L_SHOULDER_2', * 'PAD_R_SHOULDER_2', * 'PAD_SELECT', * 'PAD_START', * 'PAD_L_STICK_BUTTON', * 'PAD_R_STICK_BUTTON', * 'PAD_VENDOR' * ], * axes: [ * 'PAD_L_STICK_X', * 'PAD_L_STICK_Y', * 'PAD_R_STICK_X', * 'PAD_R_STICK_Y' * ], * synthesizedButtons: { * PAD_UP: { axis: 0, min: 0, max: 1 }, * PAD_DOWN: { axis: 0, min: -1, max: 0 }, * PAD_LEFT: { axis: 0, min: -1, max: 0 }, * PAD_RIGHT: { axis: 0, min: 0, max: 1 } * } * }); */ updateMap(map: { buttons: string[]; axes: string[]; synthesizedButtons?: object; mapping?: "custom"; }): void; /** * Reset gamepad mapping to default. */ resetMap(): void; /** * Gets the values from analog axes present on the GamePad. Values are between -1 and 1. * * @type {number[]} */ get axes(): number[]; /** * Gets the buttons present on the GamePad. * * @type {GamePadButton[]} */ get buttons(): GamePadButton[]; /** * Make the gamepad vibrate. * * @param {number} intensity - Intensity for the vibration in the range 0 to 1. * @param {number} duration - Duration for the vibration in milliseconds. * @param {object} [options] - Options for special vibration pattern. * @param {number} [options.startDelay] - Delay before the pattern starts, in milliseconds. Defaults to 0. * @param {number} [options.strongMagnitude] - Intensity for strong actuators in the range 0 to 1. Defaults to intensity. * @param {number} [options.weakMagnitude] - Intensity for weak actuators in the range 0 to 1. Defaults to intensity. * @returns {Promise} Return a Promise resulting in true if the pulse was successfully completed. */ pulse(intensity: number, duration: number, options?: { startDelay?: number; strongMagnitude?: number; weakMagnitude?: number; }): Promise; /** * Retrieve a button from its index. * * @param {number} index - The index to return the button for. * @returns {GamePadButton} The button for the searched index. May be a placeholder if none found. */ getButton(index: number): GamePadButton; /** * Returns true if the button is pressed. * * @param {number} button - The button to test, use constants {@link PAD_FACE_1}, etc. * @returns {boolean} True if the button is pressed. */ isPressed(button: number): boolean; /** * Return true if the button was pressed since the last update. * * @param {number} button - The button to test, use constants {@link PAD_FACE_1}, etc. * @returns {boolean} Return true if the button was pressed, false if not. */ wasPressed(button: number): boolean; /** * Return true if the button was released since the last update. * * @param {number} button - The button to test, use constants {@link PAD_FACE_1}, etc. * @returns {boolean} Return true if the button was released, false if not. */ wasReleased(button: number): boolean; /** * Returns true if the button is touched. * * @param {number} button - The button to test, use constants {@link PAD_FACE_1}, etc. * @returns {boolean} True if the button is touched. */ isTouched(button: number): boolean; /** * Return true if the button was touched since the last update. * * @param {number} button - The button to test, use constants {@link PAD_FACE_1}, etc. * @returns {boolean} Return true if the button was touched, false if not. */ wasTouched(button: number): boolean; /** * Returns the value of a button between 0 and 1, with 0 representing a button that is not pressed, and 1 representing a button that is fully pressed. * * @param {number} button - The button to retrieve, use constants {@link PAD_FACE_1}, etc. * @returns {number} The value of the button between 0 and 1. */ getValue(button: number): number; /** * Get the value of one of the analog axes of the pad. * * @param {number} axis - The axis to get the value of, use constants {@link PAD_L_STICK_X}, etc. * @returns {number} The value of the axis between -1 and 1. */ getAxis(axis: number): number; } /** * A GamePadButton stores information about a button from the Gamepad API. * * @category Input Devices */ declare class GamePadButton { /** * Create a new GamePadButton instance. * * @param {number|GamepadButton} current - The original Gamepad API gamepad button. * @param {number|GamepadButton} [previous] - The previous Gamepad API gamepad button. * @ignore */ constructor(current: number | GamepadButton, previous?: number | GamepadButton); /** * The value for the button between 0 and 1, with 0 representing a button that is not pressed, and 1 representing a button that is fully pressed. */ value: number; /** * Whether the button is currently down. */ pressed: boolean; /** * Whether the button is currently touched. */ touched: boolean; /** * Whether the button was pressed. */ wasPressed: boolean; /** * Whether the button was released since the last update. */ wasReleased: boolean; /** * Whether the button was touched since the last update. */ wasTouched: boolean; /** * Update the existing GamePadButton Instance. * * @param {GamepadButton} button - The original Gamepad API gamepad button. * @ignore */ update(button: GamepadButton): void; } /** * @import { Entity } from '../entity.js' * @import { Quat } from '../../core/math/quat.js' * @import { Vec3 } from '../../core/math/vec3.js' */ /** * The base class for a rigid body owned by a {@link PhysicsWorld}. Backends subclass it and * override every method. The base implementation is inert: setters do nothing and getters * leave their out-parameters untouched, so callers fall back to their own cached values - * matching the engine's behavior when no physics library is loaded. * * @ignore */ declare class PhysicsBody { /** * The entity this body simulates. Surfaced by raycast and contact results. * * @type {Entity|null} */ entity: Entity | null; /** * The backend-native body object - btRigidBody when the Ammo backend is active, null * otherwise. Surfaced by RigidBodyComponent#body. * * @type {object|null} */ nativeBody: object | null; /** * @param {number} friction - The friction value used when contacts occur. */ setFriction(friction: number): void; /** * @param {number} friction - The torsional friction orthogonal to the contact point. */ setRollingFriction(friction: number): void; /** * @param {number} restitution - The amount of energy preserved on collision. */ setRestitution(restitution: number): void; /** * Sets both damping values in one call. * * @param {number} linear - The rate at which the body loses linear velocity. * @param {number} angular - The rate at which the body loses angular velocity. */ setDamping(linear: number, angular: number): void; /** * @param {Vec3} factor - The scaling factor for linear movement per axis. */ setLinearFactor(factor: Vec3): void; /** * @param {Vec3} factor - The scaling factor for angular movement per axis. */ setAngularFactor(factor: Vec3): void; /** * Scales the world gravity applied to this body. A scale of 1 follows the world gravity, 0 * ignores it. Backends re-apply the scale whenever the world gravity changes. * * @param {number} scale - The gravity scale. */ setGravityScale(scale: number): void; /** * @param {Vec3} velocity - The world space linear velocity. */ setLinearVelocity(velocity: Vec3): void; /** * Reads the body's linear velocity into an out-parameter. Inert backends leave it * untouched. * * @param {Vec3} velocity - The vector to write the linear velocity to. */ getLinearVelocity(velocity: Vec3): void; /** * @param {Vec3} velocity - The world space angular velocity. */ setAngularVelocity(velocity: Vec3): void; /** * Reads the body's angular velocity into an out-parameter. Inert backends leave it * untouched. * * @param {Vec3} velocity - The vector to write the angular velocity to. */ getAngularVelocity(velocity: Vec3): void; /** * Sets the body mass and recomputes its inertia from the current collision shape. * * @param {number} mass - The new mass. */ setMass(mass: number): void; /** * Returns true if the body is actively simulating, i.e. not sleeping. * * @returns {boolean} True if the body is active. */ isActive(): boolean; /** * Forcibly wakes the body. */ activate(): void; /** * Teleports the body to a new world space pose and wakes it. Backends also refresh any * interpolation state so the pose read back by {@link PhysicsBody#getTransform} is the * teleport target even on frames that run zero fixed substeps, and any broadphase bounds so * queries such as raycasts find the body at its new pose before the next step. * * @param {Vec3} position - The world space position. * @param {Quat} rotation - The world space rotation. */ setTransform(position: Vec3, rotation: Quat): void; /** * Reads the simulated pose to present to the scene (the interpolated transform on backends * that interpolate). Inert backends leave the out-parameters untouched. * * @param {Vec3} position - The vector to write the world space position to. * @param {Quat} rotation - The quaternion to write the world space rotation to. */ getTransform(position: Vec3, rotation: Quat): void; /** * Drives a kinematic body towards a world space pose for the next simulation step. * * @param {Vec3} position - The world space position. * @param {Quat} rotation - The world space rotation. */ setKinematicTarget(position: Vec3, rotation: Quat): void; /** * Applies a force at a point relative to the body's origin. The body is not woken - callers * activate first, matching the engine's established call order. * * @param {Vec3} force - The world space force. * @param {Vec3} relativePoint - The world space offset from the body origin. */ applyForce(force: Vec3, relativePoint: Vec3): void; /** * @param {Vec3} torque - The world space torque. */ applyTorque(torque: Vec3): void; /** * Applies an impulse at a point relative to the body's origin. * * @param {Vec3} impulse - The world space impulse. * @param {Vec3} relativePoint - The world space offset from the body origin. */ applyImpulse(impulse: Vec3, relativePoint: Vec3): void; /** * @param {Vec3} torque - The world space torque impulse. */ applyTorqueImpulse(torque: Vec3): void; } /** * Represents a single point of contact between two colliding rigid bodies in the physics * simulation. Each contact point stores detailed spatial information about the collision, * including both local and world space coordinates of the exact contact points on both entities, * the contact normal direction, and the collision impulse force. * * Contact points are generated by the physics engine during collision detection and are typically * accessed through a {@link ContactResult} object, which can contain multiple contact points for a * single collision between two entities. Multiple contact points commonly occur when objects * collide along edges or faces rather than at a single point. * * The impulse property can be particularly useful for gameplay mechanics that need to respond * differently based on the force of impact, such as damage calculations or sound effect volume. * * Contact points are pooled and reused by the physics system, so a contact point and its vectors * are only valid inside the event handler that receives them. Copy any values that are needed * later, for example with {@link Vec3#clone}. * * @example * // Access contact points from a collision event * entity.collision.on('contact', (result) => { * // Get the first contact point * const contact = result.contacts[0]; * * // Get the contact position in world space * const worldPos = contact.point; * * // Check how hard the collision was * if (contact.impulse > 10) { * console.log("That was a hard impact!"); * } * }); * * @category Physics */ declare class ContactPoint { /** * Create a new ContactPoint instance. * * @param {Vec3} [localPoint] - The point on the entity where the contact occurred, in the * local space of its rigid body. * @param {Vec3} [localPointOther] - The point on the other entity where the contact occurred, * in the local space of the other entity's rigid body. * @param {Vec3} [point] - The point on the entity where the contact occurred, in world space. * @param {Vec3} [pointOther] - The point on the other entity where the contact occurred, in * world space. * @param {Vec3} [normal] - The normal vector of the contact on the other entity, in world * space. * @param {number} [impulse] - The total accumulated impulse applied by the constraint solver * during the last sub-step. Describes how hard two objects collide. Defaults to 0. * @ignore */ constructor(localPoint?: Vec3, localPointOther?: Vec3, point?: Vec3, pointOther?: Vec3, normal?: Vec3, impulse?: number); /** * The point on the entity where the contact occurred, in the local space of its rigid body. * That space has the entity's world position and rotation, with any * {@link CollisionComponent#linearOffset} and {@link CollisionComponent#angularOffset} * applied, and ignores the entity's scale. * * @type {Vec3} */ localPoint: Vec3; /** * The point on the other entity where the contact occurred, in the local space of the other * entity's rigid body (see {@link ContactPoint#localPoint}). * * @type {Vec3} */ localPointOther: Vec3; /** * The point on the entity where the contact occurred, in world space. * * @type {Vec3} */ point: Vec3; /** * The point on the other entity where the contact occurred, in world space. * * @type {Vec3} */ pointOther: Vec3; /** * The normal vector of the contact on the other entity, in world space. This vector points * away from the surface of the other entity at the point of contact. * * @type {Vec3} */ normal: Vec3; /** * The total accumulated impulse applied by the constraint solver during the last sub-step. * This value represents how hard two objects collided. Higher values indicate stronger impacts. * * @type {number} */ impulse: number; } /** * @import { PhysicsJointSettings } from './physics-world.js' */ /** * The base class for a joint (constraint) owned by a {@link PhysicsWorld}. Backends subclass * it and override every method. The base implementation is inert: parameter updates do nothing * and the joint never breaks. * * @ignore */ declare class PhysicsJoint { /** * The backend-native constraint object - btTypedConstraint when the Ammo backend is * active, null otherwise. Surfaced by JointComponent#constraint. * * @type {object|null} */ nativeJoint: object | null; /** * Applies the limit-related settings for the joint's type. * * @param {PhysicsJointSettings} settings - The joint parameter bag. * @returns {boolean} True if the joint's type supports limits and they were applied. */ updateLimits(settings: PhysicsJointSettings): boolean; /** * Applies the motor-related settings for the joint's type. * * @param {PhysicsJointSettings} settings - The joint parameter bag. * @returns {boolean} True if the joint's type supports a motor and it was applied. */ updateMotor(settings: PhysicsJointSettings): boolean; /** * Applies the spring-related settings for the joint's type. * * @param {PhysicsJointSettings} settings - The joint parameter bag. * @returns {boolean} True if the joint's type supports springs and they were applied. */ updateSpring(settings: PhysicsJointSettings): boolean; /** * Sets the impulse threshold above which the joint breaks. Infinity makes the joint * unbreakable. * * @param {number} impulse - The break impulse threshold. */ setBreakImpulse(impulse: number): void; /** * Returns whether the joint broke during simulation, or null when the backend cannot * determine it - the caller then falls back to its own heuristic. * * @returns {boolean|null} True if broken, false if intact, null if undeterminable. */ isBroken(): boolean | null; } /** * @import { Entity } from '../../entity.js' * @import { Vec3 } from '../../../core/math/vec3.js' */ /** * Contains the result of a successful raycast intersection with a rigid body. When a ray * intersects with a rigid body in the physics simulation, this class stores the complete * information about that intersection including the entity, the exact point of impact, the normal * at the impact point, and the fractional distance along the ray where the intersection occurred. * * Instances of this class are created and returned by {@link RigidBodyComponentSystem#raycastFirst} * and {@link RigidBodyComponentSystem#raycastAll} methods when performing physics raycasts. * * @category Physics */ declare class RaycastResult { /** * Create a new RaycastResult instance. * * @param {Entity} entity - The entity that was hit. * @param {Vec3} point - The point at which the ray hit the entity in world space. * @param {Vec3} normal - The normal vector of the surface where the ray hit in world space. * @param {number} hitFraction - The normalized distance (between 0 and 1) at which the ray hit * occurred from the starting point. * @ignore */ constructor(entity: Entity, point: Vec3, normal: Vec3, hitFraction: number); /** * The entity that was hit. * * @type {Entity} */ entity: Entity; /** * The point at which the ray hit the entity in world space. * * @type {Vec3} */ point: Vec3; /** * The normal vector of the surface where the ray hit in world space. * * @type {Vec3} */ normal: Vec3; /** * The normalized distance (between 0 and 1) at which the ray hit occurred from the * starting point. * * @type {number} */ hitFraction: number; } type PhysicsBodyDesc = { /** * - The body type: BODYTYPE_STATIC, BODYTYPE_DYNAMIC or * BODYTYPE_KINEMATIC. */ type: string; /** * - The construction mass. Callers pass 0 for non-dynamic bodies. */ mass: number; /** * - An opaque collision shape handle created by * {@link PhysicsWorld#createShape}. */ shape: object; /** * - The initial world space position. Collision component offsets are * already applied by the caller. */ position: Vec3; /** * - The initial world space rotation. */ rotation: Quat; /** * - The entity this body simulates. Surfaced by raycast and * contact results. */ entity: Entity | null; /** * - When true, the body collides and reports contacts * but does not respond to them (used for triggers). Defaults to false. */ noContactResponse?: boolean; }; type PhysicsMeshSource = { /** * - A stable cache key for the source geometry (mesh id). Sources sharing * an id must describe identical unit-scale geometry - backends may cache built triangle data per * id for the lifetime of the world. */ id: number; /** * - Vertex positions, possibly interleaved. */ positions: Float32Array | number[]; /** * - The number of floats between consecutive positions (3 when * tightly packed). */ stride: number; /** * - Triangle indices. Ignored when * convexHull is true. */ indices: number[] | Uint16Array | Uint32Array; /** * - The first index to read. */ base: number; /** * - The number of indices to read (a multiple of 3). Ignored when * convexHull is true - hulls consume every position. */ count: number; /** * - Build a convex hull instead of a triangle mesh. */ convexHull: boolean; /** * - Weld duplicate vertices while building triangle data. */ checkDuplicates: boolean; /** * - The per-instance scale of the source geometry, or null for unit * scale. Backends apply it to the built sub-shape, or bake it into the triangle data when they * cannot - data baked at one scale must never be reused at another. */ scale: Vec3 | null; /** * - The sub-shape position within the mesh shape. Collision component * offsets are already applied by the caller. */ position: Vec3; /** * - The sub-shape rotation within the mesh shape. */ rotation: Quat; }; type PhysicsShapeDesc = { /** * - The shape type: 'box', 'sphere', 'capsule', 'cylinder', 'cone', * 'mesh' or 'compound'. */ type: string; /** * - The box half extents. */ halfExtents?: Vec3; /** * - The sphere/capsule/cylinder/cone radius. */ radius?: number; /** * - The full capsule/cylinder/cone height along the alignment axis. * Backends convert to their own conventions. */ height?: number; /** * - The capsule/cylinder/cone alignment axis: 0 (X), 1 (Y) or 2 (Z). */ axis?: number; /** * - The geometry sources of a 'mesh' shape. Mesh * shapes are created in one atomic call so backends may build immutable composites. */ sources?: PhysicsMeshSource[]; }; /** * The parameter bag consumed by {@link PhysicsWorld#createJoint} and the PhysicsJoint update * methods. JointComponent structurally satisfies this contract and passes itself. */ type PhysicsJointSettings = { /** * - The impulse threshold above which the joint breaks, or * Infinity for an unbreakable joint. Applied at creation - later changes go through * {@link PhysicsJoint#setBreakImpulse}. */ breakImpulse: number; /** * - Whether hinge, slider and ball joint limits are enabled. */ enableLimits: boolean; /** * - The hinge (degrees) or slider (meters) limits. */ limits: Vec2; /** * - The hinge (deg/s) or slider (m/s) motor speed. */ motorSpeed: number; /** * - The maximum motor force. The motor is engaged while > 0. */ maxMotorForce: number; /** * - The ball joint swing limit around Y in degrees. */ swingLimitY: number; /** * - The ball joint swing limit around Z in degrees. */ swingLimitZ: number; /** * - The ball joint twist limit in degrees. */ twistLimit: number; /** * - MOTION_FREE, MOTION_LIMITED or MOTION_LOCKED. */ linearMotionX: string; /** * - MOTION_FREE, MOTION_LIMITED or MOTION_LOCKED. */ linearMotionY: string; /** * - MOTION_FREE, MOTION_LIMITED or MOTION_LOCKED. */ linearMotionZ: string; /** * - The 6dof linear limits along X in meters. */ linearLimitsX: Vec2; /** * - The 6dof linear limits along Y in meters. */ linearLimitsY: Vec2; /** * - The 6dof linear limits along Z in meters. */ linearLimitsZ: Vec2; /** * - The 6dof linear spring stiffness per axis. */ linearStiffness: Vec3; /** * - The 6dof linear spring damping per axis. */ linearDamping: Vec3; /** * - The 6dof linear spring equilibrium point per axis. */ linearEquilibrium: Vec3; /** * - MOTION_FREE, MOTION_LIMITED or MOTION_LOCKED. */ angularMotionX: string; /** * - MOTION_FREE, MOTION_LIMITED or MOTION_LOCKED. */ angularMotionY: string; /** * - MOTION_FREE, MOTION_LIMITED or MOTION_LOCKED. */ angularMotionZ: string; /** * - The 6dof angular limits around X in degrees. */ angularLimitsX: Vec2; /** * - The 6dof angular limits around Y in degrees. */ angularLimitsY: Vec2; /** * - The 6dof angular limits around Z in degrees. */ angularLimitsZ: Vec2; /** * - The 6dof angular spring stiffness per axis. */ angularStiffness: Vec3; /** * - The 6dof angular spring damping per axis. */ angularDamping: Vec3; /** * - The 6dof angular spring equilibrium per axis in degrees. */ angularEquilibrium: Vec3; }; type PhysicsJointDesc = { /** * - The joint type: JOINTTYPE_FIXED, JOINTTYPE_BALL, JOINTTYPE_HINGE, * JOINTTYPE_SLIDER or JOINTTYPE_6DOF. */ type: string; /** * - The first constrained body. */ bodyA: PhysicsBody; /** * - The second constrained body, or null to anchor the joint * to the world (the backend supplies its own fixed anchor body). */ bodyB: PhysicsBody | null; /** * - The joint frame in body A's local space, as a scale-free matrix * with X as the primary joint axis by engine convention. Backends apply their own native axis * corrections. Only valid during the call. */ frameA: Mat4; /** * - The joint frame in body B's local space (or world space when bodyB * is null). */ frameB: Mat4; /** * - Whether the two bodies keep colliding with each other. * Creation-time only - changing it recreates the joint. */ enableCollision: boolean; /** * - The full parameter bag, applied at creation. */ settings: PhysicsJointSettings; }; /** * A single contacting body pair reported to the {@link PhysicsContactListener}. Backends reuse * one instance per world - it is only valid inside onContactPair and must never be retained. */ type PhysicsContactPair = { /** * - The entity owning the first body. */ entityA: Entity; /** * - The entity owning the second body. */ entityB: Entity; /** * - True if the first body has no contact response. */ triggerA: boolean; /** * - True if the second body has no contact response. */ triggerB: boolean; /** * - The number of contact points (always >= 1). */ contactCount: number; /** * - Fills out with contact * point index from A's perspective, allocation free: point and localPoint lie on A, pointOther * and localPointOther on B, and normal is the normal of B's surface at the contact, pointing away * from B toward A. The system derives B's view of the contact by swapping the points and negating * the normal. */ readContact: (index: number, out: ContactPoint) => void; }; /** * Receives contact reports from a {@link PhysicsWorld}. The world runs one complete contact * pass - onContactsBegin, zero or more onContactPair, onContactsEnd - once per simulation * substep where the backend supports substep granularity, otherwise at least once per step. */ type PhysicsContactListener = { /** * - Called when a contact pass begins. */ onContactsBegin: () => void; /** * - Called for each contacting * pair. Pairs with no contact points or without entities on both bodies are not reported. */ onContactPair: (pair: PhysicsContactPair) => void; /** * - Called when a contact pass ends. */ onContactsEnd: () => void; }; /** * @import { Entity } from '../entity.js' * @import { Mat4 } from '../../core/math/mat4.js' * @import { Quat } from '../../core/math/quat.js' * @import { Vec2 } from '../../core/math/vec2.js' * @import { Vec3 } from '../../core/math/vec3.js' * @import { ContactPoint } from '../components/rigid-body/contact-point.js' * @import { RaycastResult } from '../components/rigid-body/raycast-result.js' */ /** * @typedef {object} PhysicsBodyDesc * @property {string} type - The body type: BODYTYPE_STATIC, BODYTYPE_DYNAMIC or * BODYTYPE_KINEMATIC. * @property {number} mass - The construction mass. Callers pass 0 for non-dynamic bodies. * @property {object} shape - An opaque collision shape handle created by * {@link PhysicsWorld#createShape}. * @property {Vec3} position - The initial world space position. Collision component offsets are * already applied by the caller. * @property {Quat} rotation - The initial world space rotation. * @property {Entity|null} entity - The entity this body simulates. Surfaced by raycast and * contact results. * @property {boolean} [noContactResponse] - When true, the body collides and reports contacts * but does not respond to them (used for triggers). Defaults to false. * @ignore */ /** * @typedef {object} PhysicsMeshSource * @property {number} id - A stable cache key for the source geometry (mesh id). Sources sharing * an id must describe identical unit-scale geometry - backends may cache built triangle data per * id for the lifetime of the world. * @property {Float32Array|number[]} positions - Vertex positions, possibly interleaved. * @property {number} stride - The number of floats between consecutive positions (3 when * tightly packed). * @property {number[]|Uint16Array|Uint32Array} indices - Triangle indices. Ignored when * convexHull is true. * @property {number} base - The first index to read. * @property {number} count - The number of indices to read (a multiple of 3). Ignored when * convexHull is true - hulls consume every position. * @property {boolean} convexHull - Build a convex hull instead of a triangle mesh. * @property {boolean} checkDuplicates - Weld duplicate vertices while building triangle data. * @property {Vec3|null} scale - The per-instance scale of the source geometry, or null for unit * scale. Backends apply it to the built sub-shape, or bake it into the triangle data when they * cannot - data baked at one scale must never be reused at another. * @property {Vec3} position - The sub-shape position within the mesh shape. Collision component * offsets are already applied by the caller. * @property {Quat} rotation - The sub-shape rotation within the mesh shape. * @ignore */ /** * @typedef {object} PhysicsShapeDesc * @property {string} type - The shape type: 'box', 'sphere', 'capsule', 'cylinder', 'cone', * 'mesh' or 'compound'. * @property {Vec3} [halfExtents] - The box half extents. * @property {number} [radius] - The sphere/capsule/cylinder/cone radius. * @property {number} [height] - The full capsule/cylinder/cone height along the alignment axis. * Backends convert to their own conventions. * @property {number} [axis] - The capsule/cylinder/cone alignment axis: 0 (X), 1 (Y) or 2 (Z). * @property {PhysicsMeshSource[]} [sources] - The geometry sources of a 'mesh' shape. Mesh * shapes are created in one atomic call so backends may build immutable composites. * @ignore */ /** * The parameter bag consumed by {@link PhysicsWorld#createJoint} and the PhysicsJoint update * methods. JointComponent structurally satisfies this contract and passes itself. * * @typedef {object} PhysicsJointSettings * @property {number} breakImpulse - The impulse threshold above which the joint breaks, or * Infinity for an unbreakable joint. Applied at creation - later changes go through * {@link PhysicsJoint#setBreakImpulse}. * @property {boolean} enableLimits - Whether hinge, slider and ball joint limits are enabled. * @property {Vec2} limits - The hinge (degrees) or slider (meters) limits. * @property {number} motorSpeed - The hinge (deg/s) or slider (m/s) motor speed. * @property {number} maxMotorForce - The maximum motor force. The motor is engaged while > 0. * @property {number} swingLimitY - The ball joint swing limit around Y in degrees. * @property {number} swingLimitZ - The ball joint swing limit around Z in degrees. * @property {number} twistLimit - The ball joint twist limit in degrees. * @property {string} linearMotionX - MOTION_FREE, MOTION_LIMITED or MOTION_LOCKED. * @property {string} linearMotionY - MOTION_FREE, MOTION_LIMITED or MOTION_LOCKED. * @property {string} linearMotionZ - MOTION_FREE, MOTION_LIMITED or MOTION_LOCKED. * @property {Vec2} linearLimitsX - The 6dof linear limits along X in meters. * @property {Vec2} linearLimitsY - The 6dof linear limits along Y in meters. * @property {Vec2} linearLimitsZ - The 6dof linear limits along Z in meters. * @property {Vec3} linearStiffness - The 6dof linear spring stiffness per axis. * @property {Vec3} linearDamping - The 6dof linear spring damping per axis. * @property {Vec3} linearEquilibrium - The 6dof linear spring equilibrium point per axis. * @property {string} angularMotionX - MOTION_FREE, MOTION_LIMITED or MOTION_LOCKED. * @property {string} angularMotionY - MOTION_FREE, MOTION_LIMITED or MOTION_LOCKED. * @property {string} angularMotionZ - MOTION_FREE, MOTION_LIMITED or MOTION_LOCKED. * @property {Vec2} angularLimitsX - The 6dof angular limits around X in degrees. * @property {Vec2} angularLimitsY - The 6dof angular limits around Y in degrees. * @property {Vec2} angularLimitsZ - The 6dof angular limits around Z in degrees. * @property {Vec3} angularStiffness - The 6dof angular spring stiffness per axis. * @property {Vec3} angularDamping - The 6dof angular spring damping per axis. * @property {Vec3} angularEquilibrium - The 6dof angular spring equilibrium per axis in degrees. * @ignore */ /** * @typedef {object} PhysicsJointDesc * @property {string} type - The joint type: JOINTTYPE_FIXED, JOINTTYPE_BALL, JOINTTYPE_HINGE, * JOINTTYPE_SLIDER or JOINTTYPE_6DOF. * @property {PhysicsBody} bodyA - The first constrained body. * @property {PhysicsBody|null} bodyB - The second constrained body, or null to anchor the joint * to the world (the backend supplies its own fixed anchor body). * @property {Mat4} frameA - The joint frame in body A's local space, as a scale-free matrix * with X as the primary joint axis by engine convention. Backends apply their own native axis * corrections. Only valid during the call. * @property {Mat4} frameB - The joint frame in body B's local space (or world space when bodyB * is null). * @property {boolean} enableCollision - Whether the two bodies keep colliding with each other. * Creation-time only - changing it recreates the joint. * @property {PhysicsJointSettings} settings - The full parameter bag, applied at creation. * @ignore */ /** * A single contacting body pair reported to the {@link PhysicsContactListener}. Backends reuse * one instance per world - it is only valid inside onContactPair and must never be retained. * * @typedef {object} PhysicsContactPair * @property {Entity} entityA - The entity owning the first body. * @property {Entity} entityB - The entity owning the second body. * @property {boolean} triggerA - True if the first body has no contact response. * @property {boolean} triggerB - True if the second body has no contact response. * @property {number} contactCount - The number of contact points (always >= 1). * @property {(index: number, out: ContactPoint) => void} readContact - Fills out with contact * point index from A's perspective, allocation free: point and localPoint lie on A, pointOther * and localPointOther on B, and normal is the normal of B's surface at the contact, pointing away * from B toward A. The system derives B's view of the contact by swapping the points and negating * the normal. * @ignore */ /** * Receives contact reports from a {@link PhysicsWorld}. The world runs one complete contact * pass - onContactsBegin, zero or more onContactPair, onContactsEnd - once per simulation * substep where the backend supports substep granularity, otherwise at least once per step. * * @typedef {object} PhysicsContactListener * @property {() => void} onContactsBegin - Called when a contact pass begins. * @property {(pair: PhysicsContactPair) => void} onContactPair - Called for each contacting * pair. Pairs with no contact points or without entities on both bodies are not reported. * @property {() => void} onContactsEnd - Called when a contact pass ends. * @ignore */ /** * The base class for physics backends. A PhysicsWorld owns the lifecycle of a physics engine's * simulation world: stepping, gravity, body and shape factories, joints, raycasts and contact * reporting. Backends subclass it and override every method. * * The base implementation is a functional no-op: bodies and joints are created but inert, * raycasts miss and stepping does nothing. {@link NullPhysicsWorld} uses this to let physics * component lifecycle run without a physics engine loaded. * * Supply a backend to an application with {@link AppOptions#physicsWorld}. * * Applications drive physics through the physics components - the methods of this class form * the internal contract between the engine and a backend and are not called directly. * * @category Physics * @alpha */ declare class PhysicsWorld { /** * The listener driven during {@link PhysicsWorld#step} and * {@link PhysicsWorld#flushContacts}. Assigned by the {@link RigidBodyComponentSystem} * when the world is installed into an application. * * @type {PhysicsContactListener|null} * @ignore */ contactListener: PhysicsContactListener | null; /** * The backend-native world object - btDiscreteDynamicsWorld when the Ammo backend is * active, null otherwise. * * @type {object|null} */ nativeWorld: object | null; /** * Whether mesh shapes honor the per-instance {@link PhysicsMeshSource} scale, so that a * mesh shape is rebuilt when the world scale of its entity changes. Backends that cannot * scale mesh instances independently return false, and mesh shapes are then left alone when * their entity is rescaled. * * @type {boolean} * @ignore */ get supportsMeshScaling(): boolean; /** * Destroys the world and all native resources it owns. The world is unusable afterwards. * * @ignore */ destroy(): void; /** * Applies the given world space gravity. Called once when the backend is installed and again * whenever the system's gravity changes, so backends can apply the value unconditionally. * * @param {Vec3} gravity - The world space gravity. * @ignore */ setGravity(gravity: Vec3): void; /** * Advances the simulation. Contact passes are driven from inside this call on backends * that support substep granularity. * * @param {number} dt - The elapsed time in seconds. * @param {number} maxSubSteps - The maximum number of fixed substeps to take. * @param {number} fixedTimeStep - The duration of a fixed substep in seconds. * @ignore */ step(dt: number, maxSubSteps: number, fixedTimeStep: number): void; /** * Runs a deferred contact pass on backends that could not report contacts from inside * {@link PhysicsWorld#step}. Called by the system after dynamic transform sync. No-op on * backends that report during step. * * @ignore */ flushContacts(): void; /** * Creates a body outside the simulation. Add it with {@link PhysicsWorld#addBody}. * * @param {PhysicsBodyDesc} desc - The body descriptor. * @returns {PhysicsBody} The new body. * @ignore */ createBody(desc: PhysicsBodyDesc): PhysicsBody; /** * Destroys a body. It must not currently be in the simulation. * * @param {PhysicsBody} body - The body to destroy. * @ignore */ destroyBody(body: PhysicsBody): void; /** * Adds a body to the simulation and applies the backend's activation policy for the body's * type (kinematic bodies never deactivate, all others enter the active state). * * @param {PhysicsBody} body - The body to add. * @param {number} [group] - The collision group bits. Used together with mask. * @param {number} [mask] - The collision mask bits. * @ignore */ addBody(body: PhysicsBody, group?: number, mask?: number): void; /** * Removes a body from the simulation. The body becomes inert until re-added. * * @param {PhysicsBody} body - The body to remove. * @ignore */ removeBody(body: PhysicsBody): void; /** * Creates a collision shape from a typed descriptor. The returned handle is opaque - it is * owned by this world and must only be passed back to this world. * * @param {PhysicsShapeDesc} desc - The shape descriptor. * @returns {object} The opaque shape handle. * @ignore */ createShape(desc: PhysicsShapeDesc): object; /** * Destroys a shape handle created by {@link PhysicsWorld#createShape}. * * @param {object} shape - The shape handle. * @ignore */ destroyShape(shape: object): void; /** * Adds a child shape to a 'compound' shape at a local pose. * * @param {object} compound - The compound shape handle. * @param {object} child - The child shape handle. * @param {Vec3} position - The child position in the compound's local space. * @param {Quat} rotation - The child rotation in the compound's local space. * @ignore */ addCompoundChild(compound: object, child: object, position: Vec3, rotation: Quat): void; /** * Updates the local pose of a child within a 'compound' shape. Adds the child if it is not * present. * * @param {object} compound - The compound shape handle. * @param {object} child - The child shape handle. * @param {Vec3} position - The child position in the compound's local space. * @param {Quat} rotation - The child rotation in the compound's local space. * @ignore */ updateCompoundChild(compound: object, child: object, position: Vec3, rotation: Quat): void; /** * Removes a child from a 'compound' shape. No-op if the child is not present. * * @param {object} compound - The compound shape handle. * @param {object} child - The child shape handle. * @ignore */ removeCompoundChild(compound: object, child: object): void; /** * Returns the number of children in a 'compound' shape. * * @param {object} compound - The compound shape handle. * @returns {number} The child count. * @ignore */ getCompoundChildCount(compound: object): number; /** * Creates a joint between two bodies (or one body and the world) and adds it to the * simulation. * * @param {PhysicsJointDesc} desc - The joint descriptor. * @returns {PhysicsJoint} The new joint. * @ignore */ createJoint(desc: PhysicsJointDesc): PhysicsJoint; /** * Removes a joint from the simulation and destroys it. * * @param {PhysicsJoint} joint - The joint to destroy. * @ignore */ destroyJoint(joint: PhysicsJoint): void; /** * Raycast the world and return the first hit. * * @param {Vec3} start - The world space start point. * @param {Vec3} end - The world space end point. * @param {object} [options] - The raycast options. * @param {number} [options.filterCollisionGroup] - Collision group to apply to the raycast. * @param {number} [options.filterCollisionMask] - Collision mask to apply to the raycast. * @param {boolean} [options.hitBackFaces] - Whether the ray can hit the back faces of mesh * colliders. Defaults to true. * @returns {RaycastResult|null} The hit, or null if there was none. * @ignore */ raycastFirst(start: Vec3, end: Vec3, options?: { filterCollisionGroup?: number; filterCollisionMask?: number; hitBackFaces?: boolean; }): RaycastResult | null; /** * Raycast the world and return all hits, in backend order. * * @param {Vec3} start - The world space start point. * @param {Vec3} end - The world space end point. * @param {object} [options] - The raycast options. * @param {number} [options.filterCollisionGroup] - Collision group to apply to the raycast. * @param {number} [options.filterCollisionMask] - Collision mask to apply to the raycast. * @param {boolean} [options.hitBackFaces] - Whether the ray can hit the back faces of mesh * colliders. Defaults to true. * @param {any[]} [options.filterTags] - Tags filters. Defined the same way as a * {@link Tags#has} query but within an array. Hits filtered here are never allocated. * @param {Function} [options.filterCallback] - Custom function to use to filter entities. * Must return true to proceed with result. Takes the entity to evaluate as argument. * @returns {RaycastResult[]} The hits (0 length if there were none). * @ignore */ raycastAll(start: Vec3, end: Vec3, options?: { filterCollisionGroup?: number; filterCollisionMask?: number; hitBackFaces?: boolean; filterTags?: any[]; filterCallback?: Function; }): RaycastResult[]; } /** * @import { ElementInput } from './input/element-input.js' * @import { GamePads } from '../platform/input/game-pads.js' * @import { GraphicsDevice } from '../platform/graphics/graphics-device.js' * @import { Keyboard } from '../platform/input/keyboard.js' * @import { Mouse } from '../platform/input/mouse.js' * @import { PhysicsWorld } from './physics/physics-world.js' * @import { TouchDevice } from '../platform/input/touch-device.js' */ /** * Application is a subclass of {@link AppBase}, which represents the base functionality for all * PlayCanvas applications. It acts as a convenience class by internally registering all * {@link ComponentSystem}s and {@link ResourceHandler}s implemented in the PlayCanvas Engine. This * makes app setup simple but results in the full engine being included when bundling your * application. * * New code should prefer {@link AppBase}, as this class is expected to be deprecated in a future * release. Two limitations motivate that: * * - Its constructor is synchronous, so it cannot create a WebGPU device. Creating one requires * awaiting {@link createGraphicsDevice}. * - It references every component system and resource handler, so none of them can be * [tree-shaken](https://developer.mozilla.org/en-US/docs/Glossary/Tree_shaking) out of your * bundle. {@link AppBase} leaves that choice to you. * * The equivalent {@link AppBase} setup registers only what the app actually uses: * * ```javascript * const device = await createGraphicsDevice(canvas, { deviceTypes: [DEVICETYPE_WEBGPU] }); * * const options = new AppOptions(); * options.graphicsDevice = device; * options.componentSystems = [RenderComponentSystem, CameraComponentSystem, LightComponentSystem]; * options.resourceHandlers = [TextureHandler, ContainerHandler]; * * const app = new AppBase(canvas); * app.init(options); * ``` * * The component systems this class registers are listed on the constructor below. That list * doubles as a migration checklist, as it maps each component name to the system you would need * to register yourself. * * {@link AppBase#keyboard}, {@link AppBase#mouse}, {@link AppBase#touch}, * {@link AppBase#gamepads} and {@link AppBase#elementInput} stay `null` unless the matching device * is passed to this constructor, so a game that reads input must construct with, for example, * `{ keyboard: new Keyboard(window), mouse: new Mouse(canvas), touch: new TouchDevice(canvas) }`. * * @category Framework */ declare class Application extends AppBase { /** * Create a new Application instance. * * Automatically registers these component systems with the application's component system registry: * * - anim ({@link AnimComponentSystem}) * - animation ({@link AnimationComponentSystem}) * - audiolistener ({@link AudioListenerComponentSystem}) * - button ({@link ButtonComponentSystem}) * - camera ({@link CameraComponentSystem}) * - collision ({@link CollisionComponentSystem}) * - element ({@link ElementComponentSystem}) * - gsplat ({@link GSplatComponentSystem}) * - joint ({@link JointComponentSystem}) * - layoutchild ({@link LayoutChildComponentSystem}) * - layoutgroup ({@link LayoutGroupComponentSystem}) * - light ({@link LightComponentSystem}) * - model ({@link ModelComponentSystem}) * - particlesystem ({@link ParticleSystemComponentSystem}) * - rigidbody ({@link RigidBodyComponentSystem}) * - render ({@link RenderComponentSystem}) * - screen ({@link ScreenComponentSystem}) * - script ({@link ScriptComponentSystem}) * - scrollbar ({@link ScrollbarComponentSystem}) * - scrollview ({@link ScrollViewComponentSystem}) * - sound ({@link SoundComponentSystem}) * - sprite ({@link SpriteComponentSystem}) * * @param {HTMLCanvasElement | OffscreenCanvas} canvas - The canvas element. * @param {object} [options] - The options object to configure the Application. * @param {ElementInput} [options.elementInput] - Input handler for {@link ElementComponent}s. * @param {Keyboard} [options.keyboard] - Keyboard handler for input. * @param {Mouse} [options.mouse] - Mouse handler for input. * @param {TouchDevice} [options.touch] - TouchDevice handler for input. * @param {GamePads} [options.gamepads] - Gamepad handler for input. * @param {string} [options.scriptPrefix] - Prefix to apply to script urls before loading. * @param {string} [options.assetPrefix] - Prefix to apply to asset urls before loading. * @param {GraphicsDevice} [options.graphicsDevice] - The graphics device used by the * application. If not provided, a WebGl graphics device will be created. * @param {object} [options.graphicsDeviceOptions] - Options object that is passed into the * {@link GraphicsDevice} constructor. * @param {string[]} [options.scriptsOrder] - Scripts in order of loading first. * @param {PhysicsWorld} [options.physicsWorld] - The physics backend used to simulate rigid * bodies, collisions and joints. When omitted, the Ammo.js backend is created automatically if * the Ammo library is loaded. See {@link AppOptions#physicsWorld}. * @param {boolean} [options.devtools] - Whether the app announces itself to developer tools, * such as the PlayCanvas Inspector browser extension. Defaults to true. See * {@link AppOptions#devtools}. * @example * // Engine-only example: create the application manually * const app = new Application(canvas, options); * * // Start the application's main loop * app.start(); */ constructor(canvas: HTMLCanvasElement | OffscreenCanvas, options?: { elementInput?: ElementInput; keyboard?: Keyboard; mouse?: Mouse; touch?: TouchDevice; gamepads?: GamePads; scriptPrefix?: string; assetPrefix?: string; graphicsDevice?: GraphicsDevice; graphicsDeviceOptions?: object; scriptsOrder?: string[]; physicsWorld?: PhysicsWorld; devtools?: boolean; }); createDevice(canvas: any, options: any): WebglGraphicsDevice; addComponentSystems(appOptions: any): void; addResourceHandles(appOptions: any): void; } /** * @import { AppBase } from '../app-base.js' * @import { Entity } from '../entity.js' */ /** * This is the legacy format for creating a PlayCanvas script returned when calling `createScript()`. * Do not inherit from this class directly. * * @deprecated Use {@link Script} instead. * @category Script */ declare class ScriptType extends Script { /** * The interface to define attributes for Script Types. Refer to {@link ScriptAttributes}. * * @type {ScriptAttributes} * @example * var PlayerController = createScript('playerController'); * * PlayerController.attributes.add('speed', { * type: 'number', * title: 'Speed', * placeholder: 'km/h', * default: 22.2 * }); */ static get attributes(): ScriptAttributes; /** * Shorthand function to extend Script Type prototype with list of methods. * * @param {object} methods - Object with methods, where key - is name of method, and value - is function. * @example * var PlayerController = createScript('playerController'); * * PlayerController.extend({ * initialize: function () { * // called once on initialize * }, * update: function (dt) { * // called each tick * } * }); */ static extend(methods: object): void; /** @private */ private __attributes; /** @private */ private __attributesRaw; /** * @param {*} args - initialization arguments * @protected */ protected initScript(args: any): void; /** * Expose initScript as initScriptType for backwards compatibility * @param {*} args - Initialization arguments * @protected */ protected initScriptType(args: any): void; /** * @param {boolean} [force] - Set to true to force initialization of the attributes. * @ignore */ __initializeAttributes(force?: boolean): void; } /** * Assigns values to a script instance based on a map of attributes schemas * and a corresponding map of data. * * @param {Application} app - The application instance * @param {Object} attributeSchemaMap - A map of names to Schemas * @param {Object} data - A Map of data to assign to the Script instance * @param {Script} script - A Script instance to assign values on */ declare function assignAttributesToScript(app: Application, attributeSchemaMap: { [x: string]: AttributeSchema; }, data: { [x: string]: any; }, script: Script): void; type AttributeSchema = { /** * - The Attribute type */ type: "boolean" | "number" | "string" | "json" | "asset" | "entity" | "rgb" | "rgba" | "vec2" | "vec3" | "vec4" | "curve"; /** * - True if this attribute is an array of `type` */ array?: boolean; }; /** * Container of Script Attribute definitions. Implements an interface to add/remove attributes and * store their definition for a {@link ScriptType}. Note: An instance of ScriptAttributes is * created automatically by each {@link ScriptType}. * * @category Script */ declare class ScriptAttributes { static assignAttributesToScript: typeof assignAttributesToScript; static attributeToValue: typeof attributeToValue; static reservedNames: Set; /** * Create a new ScriptAttributes instance. * * @param {typeof ScriptType} scriptType - Script Type that attributes relate to. */ constructor(scriptType: typeof ScriptType); scriptType: typeof ScriptType; index: {}; /** * Add Attribute. * * @param {string} name - Name of an attribute. * @param {object} args - Object with Arguments for an attribute. * @param {("boolean"|"number"|"string"|"json"|"asset"|"entity"|"rgb"|"rgba"|"vec2"|"vec3"|"vec4"|"curve")} args.type - Type * of an attribute value. Can be: * * - "asset" * - "boolean" * - "curve" * - "entity" * - "json" * - "number" * - "rgb" * - "rgba" * - "string" * - "vec2" * - "vec3" * - "vec4" * * @param {*} [args.default] - Default attribute value. * @param {string} [args.title] - Title for Editor's for field UI. * @param {string} [args.description] - Description for Editor's for field UI. * @param {string|string[]} [args.placeholder] - Placeholder for Editor's for field UI. * For multi-field types, such as vec2, vec3, and others use array of strings. * @param {boolean} [args.array] - If attribute can hold single or multiple values. * @param {number} [args.size] - If attribute is array, maximum number of values can be set. * @param {number} [args.min] - Minimum value for type 'number', if max and min defined, slider * will be rendered in Editor's UI. * @param {number} [args.max] - Maximum value for type 'number', if max and min defined, slider * will be rendered in Editor's UI. * @param {number} [args.precision] - Level of precision for field type 'number' with floating * values. * @param {number} [args.step] - Step value for type 'number'. The amount used to increment the * value when using the arrow keys in the Editor's UI. * @param {string} [args.assetType] - Name of asset type to be used in 'asset' type attribute * picker in Editor's UI, defaults to '*' (all). * @param {string[]} [args.curves] - List of names for Curves for field type 'curve'. * @param {string} [args.color] - String of color channels for Curves for field type 'curve', * can be any combination of `rgba` characters. Defining this property will render Gradient in * Editor's field UI. * @param {object[]} [args.enum] - List of fixed choices for field, defined as array of objects, * where key in object is a title of an option. * @param {object[]} [args.schema] - List of attributes for type 'json'. Each attribute * description is an object with the same properties as regular script attributes but with an * added 'name' field to specify the name of each attribute in the JSON. * @example * PlayerController.attributes.add('fullName', { * type: 'string' * }); * @example * PlayerController.attributes.add('speed', { * type: 'number', * title: 'Speed', * placeholder: 'km/h', * default: 22.2 * }); * @example * PlayerController.attributes.add('resolution', { * type: 'number', * default: 32, * enum: [ * { '32x32': 32 }, * { '64x64': 64 }, * { '128x128': 128 } * ] * }); * @example * PlayerController.attributes.add('config', { * type: 'json', * schema: [{ * name: 'speed', * type: 'number', * title: 'Speed', * placeholder: 'km/h', * default: 22.2 * }, { * name: 'resolution', * type: 'number', * default: 32, * enum: [ * { '32x32': 32 }, * { '64x64': 64 }, * { '128x128': 128 } * ] * }] * }); */ add(name: string, args: { type: ("boolean" | "number" | "string" | "json" | "asset" | "entity" | "rgb" | "rgba" | "vec2" | "vec3" | "vec4" | "curve"); default?: any; title?: string; description?: string; placeholder?: string | string[]; array?: boolean; size?: number; min?: number; max?: number; precision?: number; step?: number; assetType?: string; curves?: string[]; color?: string; enum?: object[]; schema?: object[]; }): void; /** * Remove Attribute. * * @param {string} name - Name of an attribute. * @returns {boolean} True if removed or false if not defined. * @example * PlayerController.attributes.remove('fullName'); */ remove(name: string): boolean; /** * Detect if Attribute is added. * * @param {string} name - Name of an attribute. * @returns {boolean} True if Attribute is defined. * @example * if (PlayerController.attributes.has('fullName')) { * // attribute fullName is defined * } */ has(name: string): boolean; /** * Get object with attribute arguments. Note: Changing argument properties will not affect * existing Script Instances. * * @param {string} name - Name of an attribute. * @returns {?object} Arguments with attribute properties. * @example * // changing default value for an attribute 'fullName' * var attr = PlayerController.attributes.get('fullName'); * if (attr) attr.default = 'Unknown'; */ get(name: string): object | null; } /** * @typedef {Object} AttributeSchema * @property {"boolean"|"number"|"string"|"json"|"asset"|"entity"|"rgb"|"rgba"|"vec2"|"vec3"|"vec4"|"curve"} type - The Attribute type * @property {boolean} [array] - True if this attribute is an array of `type` */ /** * Takes an attribute schema, a value and current value, and return a new value. * * @param {Application} app - The working application * @param {AttributeSchema} schema - The attribute schema used to resolve properties * @param {*} value - The raw value to create * @param {*} current - The existing value * @returns {*} The return value */ declare function attributeToValue(app: Application, schema: AttributeSchema, value: any, current: any): any; /** * @import { AppBase } from '../app-base.js' * @import { AttributeSchema } from './script-attributes.js' * @import { Script } from './script.js' */ /** * Container for all {@link Script} classes that are available to this application. Note that * PlayCanvas scripts can access the Script Registry from inside the application with * {@link AppBase#scripts}. * * @category Script */ declare class ScriptRegistry extends EventHandler { /** * Create a new ScriptRegistry instance. * * @param {AppBase} app - Application to attach registry to. */ constructor(app: AppBase); /** * A Map of script names to script classes. A Map is used (rather than a plain object) so that * script names which collide with `Object.prototype` members - e.g. `hasOwnProperty`, * `toString`, `__proto__` - are stored and looked up safely. * * @type {Map} * @private */ private _scripts; /** * @type {typeof Script[]} * @private */ private _list; /** * A Map of script names to attribute schemas. * * @type {Map} * @private */ private _scriptSchemas; app: AppBase; destroy(): void; /** * Registers a schema against a script instance. * * @param {string} id - The key to use to store the schema * @param {AttributeSchema} schema - An schema definition for the script */ addSchema(id: string, schema: AttributeSchema): void; /** * Returns a schema for a given script name. * * @param {string} id - The key to store the schema under * @returns {AttributeSchema | undefined} - The schema stored under the key */ getSchema(id: string): AttributeSchema | undefined; /** * Add a script to the registry, keyed by its name. The name is taken from the script's static * `scriptName` property (for {@link Script} classes), or assigned by {@link createScript} / * {@link registerScript}. Note: when {@link createScript} or {@link registerScript} is called, * the script is added to the registry automatically, so calling this method directly is only * required when registering a {@link Script} class manually (e.g. in an engine-only project). * * If a script with the same name already exists in the registry, and the new script has a * `swap` method defined, it will perform code hot swapping automatically in an async manner. * * @param {typeof Script} script - The script class to add. Must have a * resolvable name (a static `scriptName`, an assigned `__name`, or an inferable class name). * @returns {boolean} True if the script was added for the first time. False if a script with * the same name already exists, or if the script has no resolvable name. * @example * var PlayerController = createScript('playerController'); * // playerController Script Type will be added to ScriptRegistry automatically * console.log(app.scripts.has('playerController')); // outputs true * @example * // engine-only: register an ESM Script class manually * class Rotator extends Script { * static scriptName = 'rotator'; * } * app.scripts.add(Rotator); * console.log(app.scripts.has('rotator')); // outputs true */ add(script: typeof Script): boolean; /** * Remove a {@link Script} class from the registry. * * @param {string|typeof Script} nameOrType - The name or class of the {@link Script}. * @returns {boolean} True if removed or False if already not in registry. * @example * app.scripts.remove('playerController'); */ remove(nameOrType: string | typeof Script): boolean; /** * Get a {@link Script} class by name. * * @param {string} name - Name of the {@link Script}. * @returns {typeof Script|null} The script class if it exists in the registry or null * otherwise. * @example * var PlayerController = app.scripts.get('playerController'); */ get(name: string): typeof Script | null; /** * Check if a {@link Script} class with the specified name is in the registry. * * @param {string|typeof Script} nameOrType - The name or class of the {@link Script}. * @returns {boolean} True if the {@link Script} class is in the registry. * @example * if (app.scripts.has('playerController')) { * // playerController is in ScriptRegistry * } */ has(nameOrType: string | typeof Script): boolean; /** * Get list of all {@link Script} classes from registry. * * @returns {Array} list of all {@link Script} classes in registry. * @example * // logs array of all Script Type names available in registry * console.log(app.scripts.list().map(function (o) { * return o.name; * })); */ list(): Array; } declare class I18nParser { _validate(data: any): void; parse(data: any): any; } /** * @import { AppBase } from '../app-base.js' */ /** * Handles localization. Responsible for loading localization assets and returning translations for * a certain key. Can also handle plural forms. To override its default behavior define a different * implementation for {@link getText} and {@link getPluralText}. * * @category Framework */ declare class I18n extends EventHandler { /** * Fired when the locale is changed. * * @event * @example * app.i18n.on('change', (newLocale, oldLocale) => { * console.log(`Locale changed from ${oldLocale} to ${newLocale}`); * }); */ static EVENT_CHANGE: string; /** * Returns the first available locale based on the desired locale specified. First tries to * find the desired locale and then tries to find an alternative locale based on the language. * * @param {string} desiredLocale - The desired locale e.g. en-US. * @param {object} availableLocales - A dictionary where each key is an available locale. * @returns {string} The locale found or if no locale is available returns the default en-US * locale. * @example * // With a defined dictionary of locales * const availableLocales = { en: 'en-US', fr: 'fr-FR' }; * const locale = I18n.getText('en-US', availableLocales); * // returns 'en' * @ignore */ static findAvailableLocale(desiredLocale: string, availableLocales: object): string; /** * Create a new I18n instance. * * @param {AppBase} app - The application. */ constructor(app: AppBase); /** * Sets the current locale. For example, "en-US". Changing the locale will raise an event which * will cause localized Text Elements to change language to the new locale. * * @type {string} */ set locale(value: string); /** * Gets the current locale. * * @type {string} */ get locale(): string; _translations: {}; _availableLangs: {}; _app: AppBase; _assets: any[]; _parser: I18nParser; /** * Sets the array of asset ids or assets that contain localization data in the expected format. * I18n will automatically load translations from these assets as the assets are loaded and it * will also automatically unload translations if the assets get removed or unloaded at runtime. * * @type {number[]|Asset[]} */ set assets(value: number[] | Asset[]); /** * Gets the array of asset ids that contain localization data in the expected format. * * @type {number[]|Asset[]} */ get assets(): number[] | Asset[]; _locale: any; _lang: any; _pluralFn: any; /** * Returns the first available locale based on the desired locale specified. First tries to * find the desired locale in the loaded translations and then tries to find an alternative * locale based on the language. * * @param {string} desiredLocale - The desired locale e.g. en-US. * @returns {string} The locale found or if no locale is available returns the default en-US * locale. * @example * const locale = this.app.i18n.getText('en-US'); */ findAvailableLocale(desiredLocale: string): string; /** * Returns the translation for the specified key and locale. If the locale is not specified it * will use the current locale. * * @param {string} key - The localization key. * @param {string} [locale] - The desired locale. * @returns {string} The translated text. If no translations are found at all for the locale * then it will return the en-US translation. If no translation exists for that key then it will * return the localization key. * @example * const localized = this.app.i18n.getText('localization-key'); * const localizedFrench = this.app.i18n.getText('localization-key', 'fr-FR'); */ getText(key: string, locale?: string): string; /** * Returns the pluralized translation for the specified key, number n and locale. If the locale * is not specified it will use the current locale. * * @param {string} key - The localization key. * @param {number} n - The number used to determine which plural form to use. E.g. For the * phrase "5 Apples" n equals 5. * @param {string} [locale] - The desired locale. * @returns {string} The translated text. If no translations are found at all for the locale * then it will return the en-US translation. If no translation exists for that key then it * will return the localization key. * @example * // manually replace {number} in the resulting translation with our number * const localized = this.app.i18n.getPluralText('{number} apples', number).replace("{number}", number); */ getPluralText(key: string, n: number, locale?: string): string; /** * Adds localization data. If the locale and key for a translation already exists it will be * overwritten. * * @param {object} data - The localization data. See example for the expected format of the * data. * @example * this.app.i18n.addData({ * header: { * version: 1 * }, * data: [{ * info: { * locale: 'en-US' * }, * messages: { * "key": "translation", * // The number of plural forms depends on the locale. See the manual for more information. * "plural_key": ["one item", "more than one items"] * } * }, { * info: { * locale: 'fr-FR' * }, * messages: { * // ... * } * }] * }); */ addData(data: object): void; /** * Removes localization data. * * @param {object} data - The localization data. The data is expected to be in the same format * as {@link addData}. */ removeData(data: object): void; /** * Frees up memory. */ destroy(): void; _findFallbackLocale(locale: any, lang: any): any; _onAssetAdd(asset: any): void; _onAssetLoad(asset: any): void; _onAssetChange(asset: any): void; _onAssetRemove(asset: any): void; _onAssetUnload(asset: any): void; } /** * @import { SoundManager } from './manager.js' */ /** * Represents an audio listener - used internally. * * @ignore */ declare class Listener { /** * Create a new listener instance. * * @param {SoundManager} manager - The sound manager. */ constructor(manager: SoundManager); /** * @type {SoundManager} * @private */ private _manager; /** @private */ private position; /** @private */ private orientation; /** * Get the position of the listener. * * @returns {Vec3} The position of the listener. */ getPosition(): Vec3; /** * Set the position of the listener. * * @param {Vec3} position - The new position of the listener. */ setPosition(position: Vec3): void; /** * Set the orientation matrix of the listener. * * @param {Mat4} orientation - The new orientation matrix of the listener. */ setOrientation(orientation: Mat4): void; /** * Get the orientation matrix of the listener. * * @returns {Mat4} The orientation matrix of the listener. */ getOrientation(): Mat4; /** * Get the listener. * * @type {AudioListener|null} */ get listener(): AudioListener | null; } /** * The SoundManager is used to load and play audio. It also applies system-wide settings like * global volume, suspend and resume. * * There is one per application at `app.soundManager`. It owns the Web Audio `context` that * every {@link SoundInstance} plays through and the listener from which positional sounds are * heard, applies the master {@link volume} on top of each instance's own, and `suspend` and * `resume` silence and restart all audio at once, for example when the page loses focus. * * @category Sound */ declare class SoundManager extends EventHandler { /** * @type {AudioContext|null} * @private */ private _context; /** * @type {() => void} * @private */ private _unlockHandlerFunc; /** @private */ private _userSuspended; /** * The listener associated with this manager. * * @type {Listener} */ listener: Listener; /** @private */ private _volume; /** * Sets the global volume for the manager. All {@link SoundInstance}s will scale their volume * with this volume. Valid between [0, 1]. * * @type {number} */ set volume(volume: number); /** * Gets the global volume for the manager. * * @type {number} */ get volume(): number; get suspended(): boolean; /** * Get the Web Audio API context. Returns null if the environment does not support the Web * Audio API. * * @type {AudioContext|null} * @ignore */ get context(): AudioContext | null; suspend(): void; resume(): void; destroy(): void; _resume(): void; _suspend(): void; _unlockHandler(): void; _registerUnlockListeners(): void; _removeUnlockListeners(): void; } /** * Holds mesh batching settings and a unique id. Created via {@link BatchManager#addGroup}. * * @category Graphics */ declare class BatchGroup { static MODEL: string; static ELEMENT: string; static SPRITE: string; static RENDER: string; /** * Create a new BatchGroup instance. * * @param {number} id - Unique id. Can be assigned to model, render and element components. * @param {string} name - The name of the group. * @param {boolean} dynamic - Whether objects within this batch group should support * transforming at runtime. * @param {number} maxAabbSize - Maximum size of any dimension of a bounding box around batched * objects. {@link BatchManager#prepare} will split objects into local groups based on this * size. * @param {number[]} [layers] - Layer ID array. Default is [{@link LAYERID_WORLD}]. The whole * batch group will belong to these layers. Layers of source models will be ignored. */ constructor(id: number, name: string, dynamic: boolean, maxAabbSize: number, layers?: number[]); /** @private */ private _ui; /** @private */ private _sprite; /** @private */ private _obj; /** * Unique id. Can be assigned to model, render and element components. * * @type {number} */ id: number; /** * Name of the group. * * @type {string} */ name: string; /** * Whether objects within this batch group should support transforming at runtime. * * @type {boolean} */ dynamic: boolean; /** * Maximum size of any dimension of a bounding box around batched objects. * {@link BatchManager#prepare} will split objects into local groups based on this size. * * @type {number} */ maxAabbSize: number; /** * Layer ID array. Default is [{@link LAYERID_WORLD}]. The whole batch group will belong to * these layers. Layers of source models will be ignored. * * @type {number[]} */ layers: number[]; } /** * @import { MeshInstance } from '../mesh-instance.js' * @import { Scene } from '../scene.js' */ /** * Holds information about batched mesh instances. Created in {@link BatchManager#create}. * * @category Graphics */ declare class Batch { /** * Create a new Batch instance. * * @param {MeshInstance[]} meshInstances - The mesh instances to be batched. * @param {boolean} dynamic - Whether this batch is dynamic (supports transforming mesh * instances at runtime). * @param {number} batchGroupId - Link this batch to a specific batch group. This is done * automatically with default batches. */ constructor(meshInstances: MeshInstance[], dynamic: boolean, batchGroupId: number); /** @private */ private _aabb; /** * An array of original mesh instances, from which this batch was generated. * * @type {MeshInstance[]} */ origMeshInstances: MeshInstance[]; /** * A single combined mesh instance, the result of batching. * * @type {MeshInstance} */ meshInstance: MeshInstance; /** * Whether this batch is dynamic (supports transforming mesh instances at runtime). * * @type {boolean} */ dynamic: boolean; /** * Link this batch to a specific batch group. This is done automatically with default batches. * * @type {number} */ batchGroupId: number; /** * Removes the batch from the layers and destroys it. * * @param {Scene} scene - The scene. * @param {number[]} layers - The layers to remove the batch from. */ destroy(scene: Scene, layers: number[]): void; addToLayers(scene: any, layers: any): void; removeFromLayers(scene: any, layers: any): void; updateBoundingBox(): void; /** * @type {undefined} * @deprecated * @ignore */ get model(): undefined; } /** * Glues many mesh instances into a single one for better performance. * * @category Graphics */ declare class BatchManager { /** * Create a new BatchManager instance. * * @param {GraphicsDevice} device - The graphics device used by the batch manager. * @param {Entity} root - The entity under which batched models are added. * @param {Scene} scene - The scene that the batch manager affects. */ constructor(device: GraphicsDevice, root: Entity, scene: Scene); device: GraphicsDevice; rootNode: Entity; scene: Scene; _init: boolean; _batchGroups: {}; _batchGroupCounter: number; _batchList: any[]; _dirtyGroups: any[]; _stats: { createTime: number; updateLastFrameTime: number; }; destroy(): void; /** * Adds new global batch group. * * @param {string} name - Custom name. * @param {boolean} dynamic - Is this batch group dynamic? Will these objects move/rotate/scale * after being batched? * @param {number} maxAabbSize - Maximum size of any dimension of a bounding box around batched * objects. {@link prepare} will split objects into local groups based on this size. * @param {number} [id] - Optional custom unique id for the group (will be generated * automatically otherwise). * @param {number[]} [layers] - Optional layer ID array. Default is [{@link LAYERID_WORLD}]. * The whole batch group will belong to these layers. Layers of source models will be ignored. * @returns {BatchGroup} Group object. */ addGroup(name: string, dynamic: boolean, maxAabbSize: number, id?: number, layers?: number[]): BatchGroup; /** * Remove global batch group by id. Note, this traverses the entire scene graph and clears the * batch group id from all components. * * @param {number} id - Batch Group ID. */ removeGroup(id: number): void; /** * Mark a specific batch group as dirty. Dirty groups are re-batched before the next frame is * rendered. Note, re-batching a group is a potentially expensive operation. * * @param {number} id - Batch Group ID to mark as dirty. */ markGroupDirty(id: number): void; /** * Retrieves a {@link BatchGroup} object with a corresponding name, if it exists, or null * otherwise. * * @param {string} name - Name. * @returns {BatchGroup|null} The batch group matching the name or null if not found. */ getGroupByName(name: string): BatchGroup | null; /** * Retrieves a {@link BatchGroup} object with a corresponding id, if it exists, or null * otherwise. * * @param {number} id - The batch group id. * @returns {BatchGroup|null} The batch group matching the id or null if not found. */ getGroupById(id: number): BatchGroup | null; /** * Return a list of all {@link Batch} objects that belong to the Batch Group supplied. * * @param {number} batchGroupId - The id of the batch group. * @returns {Batch[]} A list of batches that are used to render the batch group. * @private */ private getBatches; _removeModelsFromBatchGroup(node: any, id: any): void; insert(type: any, groupId: any, node: any): void; remove(type: any, groupId: any, node: any): void; /** * Filter out mesh instances that have skin or morph, as these are not supported by batching. * If any mesh instance has skin/morph, the entire set is excluded. * * @param {MeshInstance[]} meshInstances - The mesh instances to filter. * @param {string} nodeName - The node name for warning messages. * @returns {MeshInstance[]|null} The mesh instances if none have skin/morph, or null if any do. * @private */ private _filterBatchableInstances; _extractRender(node: any, arr: any, group: any, groupMeshInstances: any): any; _extractModel(node: any, arr: any, group: any, groupMeshInstances: any): any; _extractElement(node: any, arr: any, group: any): void; _collectAndRemoveMeshInstances(groupMeshInstances: any, groupIds: any): void; /** * Destroys all batches and creates new based on scene models. Hides original models. Called by * engine automatically on app start, and if batchGroupIds on models are changed. * * @param {number[]} [groupIds] - Optional array of batch group IDs to update. Otherwise all * groups are updated. */ generate(groupIds?: number[]): void; /** * Takes a list of mesh instances to be batched and sorts them into lists one for each draw * call. The input list will be split, if: * * - Mesh instances use different materials. * - Mesh instances have different parameters (e.g. lightmaps or static lights). * - Mesh instances have different shader defines (shadow receiving, being aligned to screen * space, etc). * - Too many vertices for a single batch (65535 is maximum). * - Too many instances for a single batch (hardware-dependent, expect 128 on low-end and 1024 * on high-end). * - Bounding box of a batch is larger than maxAabbSize in any dimension. * - Mesh instances differ in shadow casting ({@link MeshInstance#castShadow}) or directional * shadow cascade mask ({@link MeshInstance#shadowCascadeMask}). * * @param {MeshInstance[]} meshInstances - Input list of mesh instances * @param {boolean} dynamic - Are we preparing for a dynamic batch? Instance count will matter * then (otherwise not). * @param {number} maxAabbSize - Maximum size of any dimension of a bounding box around batched * objects. * @param {boolean} translucent - Are we batching UI elements or sprites * This is useful to keep a balance between the number of draw calls and the number of drawn * triangles, because smaller batches can be hidden when not visible in camera. * @returns {MeshInstance[][]} An array of arrays of mesh instances, each valid to pass to * {@link create}. */ prepare(meshInstances: MeshInstance[], dynamic: boolean, maxAabbSize: number, translucent: boolean): MeshInstance[][]; collectBatchedMeshData(meshInstances: any, dynamic: any): { streams: {}; batchNumVerts: number; batchNumIndices: number; material: any; }; /** * Takes a mesh instance list that has been prepared by {@link prepare}, and * returns a {@link Batch} object. This method assumes that all mesh instances provided can be * rendered in a single draw call. * * @param {MeshInstance[]} meshInstances - Input list of mesh instances. * @param {boolean} dynamic - Is it a static or dynamic batch? Will objects be transformed * after batching? * @param {number} [batchGroupId] - Link this batch to a specific batch group. This is done * automatically with default batches. * @returns {Batch} The resulting batch object. */ create(meshInstances: MeshInstance[], dynamic: boolean, batchGroupId?: number): Batch; vertexFormats: {}; /** * Updates bounding boxes for all dynamic batches. Called automatically. * * @ignore */ updateAll(): void; clone(batch: any, clonedMeshInstances: any): void; /** * Removes the batch model from all layers and destroys it. * * @param {Batch} batch - A batch object. * @private */ private destroyBatch; } /** * @import { BatchManager } from '../scene/batching/batch-manager.js' * @import { ComponentSystem } from './components/system.js' * @import { ElementInput } from './input/element-input.js' * @import { GamePads } from '../platform/input/game-pads.js' * @import { GraphicsDevice } from '../platform/graphics/graphics-device.js' * @import { Keyboard } from '../platform/input/keyboard.js' * @import { Lightmapper } from './lightmapper/lightmapper.js' * @import { Mouse } from '../platform/input/mouse.js' * @import { PhysicsWorld } from './physics/physics-world.js' * @import { ResourceHandler } from './handlers/handler.js' * @import { SoundManager } from '../platform/sound/manager.js' * @import { TouchDevice } from '../platform/input/touch-device.js' * @import { XrManager } from './xr/xr-manager.js' */ /** * AppOptions holds configuration settings utilized in the creation of an {@link AppBase} instance. * It allows functionality to be included or excluded from the AppBase instance. * * @category Framework */ declare class AppOptions { /** * Input handler for {@link ElementComponent}s. * * @type {ElementInput} */ elementInput: ElementInput; /** * Keyboard handler for input. * * @type {Keyboard} */ keyboard: Keyboard; /** * Mouse handler for input. * * @type {Mouse} */ mouse: Mouse; /** * TouchDevice handler for input. * * @type {TouchDevice} */ touch: TouchDevice; /** * Gamepad handler for input. * * @type {GamePads} */ gamepads: GamePads; /** * Prefix to apply to script urls before loading. * * @type {string} */ scriptPrefix: string; /** * Prefix to apply to asset urls before loading. * * @type {string} */ assetPrefix: string; /** * Scripts in order of loading first. * * @type {string[]} */ scriptsOrder: string[]; /** * The sound manager * * @type {SoundManager} */ soundManager: SoundManager; /** * The physics backend used to simulate rigid bodies, collisions and joints, such as * {@link AmmoPhysicsWorld} or {@link NullPhysicsWorld}. When set, the application installs * it into the {@link RigidBodyComponentSystem} during {@link AppBase#init}, so * {@link AppOptions#componentSystems} must include {@link RigidBodyComponentSystem}. A * useful simulation also requires {@link CollisionComponentSystem} - rigid bodies and * triggers obtain their shapes from collision components - and {@link JointComponentSystem} * if joints are used. The rigid body system registers its contact listener with the * world. When omitted, an {@link AmmoPhysicsWorld} is created automatically once * application libraries have loaded, if the Ammo.js WasmModule is present. The application * takes ownership of the world and destroys it with the application. * * @type {PhysicsWorld} * @alpha */ physicsWorld: PhysicsWorld; /** * The graphics device. * * @type {GraphicsDevice} */ graphicsDevice: GraphicsDevice; /** * The lightmapper. * * @type {typeof Lightmapper} */ lightmapper: typeof Lightmapper; /** * The BatchManager. * * @type {typeof BatchManager} */ batchManager: typeof BatchManager; /** * The XrManager. * * @type {typeof XrManager} */ xr: typeof XrManager; /** * The component systems the app requires. * * @type {typeof ComponentSystem[]} */ componentSystems: (typeof ComponentSystem)[]; /** * The resource handlers the app requires. * * @type {typeof ResourceHandler[]} */ resourceHandlers: (typeof ResourceHandler)[]; /** * Whether the app announces itself to developer tools, such as the PlayCanvas Inspector * browser extension, so they can find and inspect it. Set to false to keep a production build * from announcing itself. This is an opt-out, not a protection: code running on the page can * still reach the app by other means. Defaults to true. * * @type {boolean} */ devtools: boolean; } /** * @import { AppBase } from './app-base.js' * @import { ForwardRenderer } from '../scene/renderer/forward-renderer.js' * @import { GraphicsDevice } from '../platform/graphics/graphics-device.js' */ /** * Performance statistics for an application, accessed through {@link AppBase#stats}. Engine * measurements are read-only; {@link user} holds writable application-defined counters. * Includes frame cadence, CPU phase timings, overall GPU frame timing, and estimated GPU resource * memory usage. CPU timings, GPU timings and memory statistics are available in all builds, subject * to graphics capabilities. Primitive counting requires a debug or profiler build; see each getter * for its availability. * * Durations are in milliseconds and memory sizes are in bytes. Values are the latest available * measurements, not averages, except for {@link fps}, which refreshes approximately once per second. * Frame counters are published at the start of the next application tick; CPU timings are updated * when their respective phases finish. CPU phases overlap and must not all be added together. * CPU timings and counters are initially zero. GPU results arrive asynchronously and can describe * an older frame than the CPU measurements. * * GPU profiling is disabled by default. Enable it with * `app.graphicsDevice.gpuProfiler.enabled = true` when a profiler exists (see the example below). * WebGL requires the disjoint timer query extension; WebGPU requires the timestamp-query feature. * Enabling profiling on an unsupported device produces no timings. {@link gpuFrameTime} returns * undefined when profiling is disabled, unsupported, or no valid result has arrived. Reading stats * does not enable profiling. MiniStats also enables GPU profiling when it creates its GPU timer. * * Memory statistics estimate resources tracked by the application's graphics device, which may be * shared by applications. They do not represent total physical GPU memory usage or capacity, and * exclude untracked driver overhead and JavaScript memory. * * @example * const profiler = app.graphicsDevice.gpuProfiler; * if (profiler) { * profiler.enabled = true; * } * * app.on('frameend', () => { * const stats = app.stats; * console.log(stats.cpuUpdateTime, stats.cpuRenderTime, stats.gpuFrameTime); * }); * * @see AppBase#stats * @category Framework */ declare class AppStats { /** * Create a new AppStats instance. * * @param {AppBase} app - The application. * @ignore */ constructor(app: AppBase); /** * @type {AppBase} * @private */ private _app; /** * @type {Map} * @private */ private _user; frame: { fps: number; ms: number; dt: number; updateStart: number; updateTime: number; renderStart: number; renderTime: number; physicsStart: number; physicsTime: number; scriptUpdateStart: number; scriptUpdate: number; scriptPostUpdateStart: number; scriptPostUpdate: number; animUpdateStart: number; animUpdate: number; cullTime: number; sortTime: number; skinTime: number; morphTime: number; instancingTime: number; primitives: number; gsplats: number; gsplatSort: number; gsplatBufferCopy: number; shaders: number; materials: number; cameras: number; shadowMapUpdates: number; shadowMapTime: number; depthMapTime: number; forwardTime: number; lightClustersTime: number; lightClusters: number; _timeToCountFrames: number; _fpsAccum: number; }; drawCalls: { forward: number; depth: number; shadow: number; immediate: number; misc: number; total: number; skinned: number; instanced: number; removedByInstancing: number; }; misc: { renderTargetCreationTime: number; }; particles: { updatesPerFrame: number; _updatesPerFrame: number; frameTime: number; _frameTime: number; }; shaders: { vsCompiled: number; fsCompiled: number; linked: number; materialShaders: number; compileTime: number; }; vram: { texShadow: number; texAsset: number; texLightmap: number; tex: number; vb: number; ib: number; ub: number; sb: number; }; gpu: Map; /** * Application-defined numeric counters. Returns the same map on every access. Entries can be * added, updated, deleted or cleared by the application; the engine never resets them. * Available in all builds. Values and their units are defined by the application. * * To display a counter in {@link MiniStats}, configure a graph with a path such as `user.ai`. * Counter names used in MiniStats must not contain dots, which separate path segments. * Initialize counters before accumulating values and reset per-frame totals on `frameupdate`. * * @type {Map} * @example * app.stats.user.set('ai', 0); * app.on('frameupdate', () => app.stats.user.set('ai', 0)); * * // Accumulate time spent in application code during this frame. * const start = performance.now(); * // ... run AI logic ... * app.stats.user.set('ai', app.stats.user.get('ai') + performance.now() - start); */ get user(): Map; /** * Total draw calls submitted during the previous frame, published at the start of the next * application tick. Available in all builds. * * @type {number} */ get drawCallCount(): number; /** * Total primitives submitted during the previous frame, published at the start of the next * application tick. Counts triangles, lines and points across all passes, including instances * and CPU-authored multi-draw commands. Counts are calculated before GPU clipping and culling. * * Available only in debug and profiler builds. Returns undefined in release and minified builds. * This is an estimate from draw parameters: GPU-generated indirect draws are excluded, and * primitive-restart indices in indexed strips are not inspected. No GPU readback is performed. * * @type {number|undefined} */ get primitiveCount(): number | undefined; /** * Interval between application ticks in milliseconds, including time outside the engine. * Unaffected by time scaling or delta-time clamping. Available in all builds. * * @type {number} */ get frameTime(): number; /** * Frame count over the latest approximately one-second reporting interval. Initially zero * until an interval completes. Available in all builds. * * @type {number} */ get fps(): number; /** * CPU duration of the latest application update in milliseconds, including component systems, * application update event listeners and input updates. Excludes graphics device updates. * Includes the other CPU update phase timings. Available in all builds. * * @type {number} */ get cpuUpdateTime(): number; /** * CPU duration of the latest scene render in milliseconds, including prerender and postrender * event listeners, hierarchy synchronization, batching and render command submission. Excludes * graphics device frameStart/frameEnd work and does not measure GPU execution. Retains the * latest measurement when rendering is skipped. Available in all builds. * * @type {number} */ get cpuRenderTime(): number; /** * CPU duration of the latest component systems update phase in milliseconds. Includes script * updates, physics and other systems subscribed to the update event. Part of * {@link cpuUpdateTime}. Available in all builds. * * @type {number} */ get cpuSystemUpdateTime(): number; /** * CPU duration of the latest component systems post-update phase in milliseconds, including * script postUpdate callbacks. Part of {@link cpuUpdateTime}. Available in all builds. * * @type {number} */ get cpuSystemPostUpdateTime(): number; /** * CPU duration of the latest dedicated animation-update phase in milliseconds, used by * {@link AnimComponentSystem}. Excludes the legacy {@link AnimationComponentSystem}, which * runs in the system update phase. Part of {@link cpuUpdateTime}. Available in all builds. * * @type {number} */ get cpuAnimationTime(): number; /** * CPU duration of the most recent physics step in milliseconds, including synchronization and * contact handling. Normally part of {@link cpuSystemUpdateTime}. Multiple manual steps are not * accumulated. Zero before any step or when physics is paused through its timeScale property. * Available in all builds. * * @type {number} */ get cpuPhysicsTime(): number; /** * Overall duration of the most recently resolved GPU frame in milliseconds. Available in all * builds when GPU profiling is supported and enabled. Returns undefined until a valid timing * arrives, when profiling is disabled, or after timing invalidation such as context loss. * Results arrive asynchronously and may be several frames old. * * WebGL measures a whole-frame timer query. WebGPU measures the span from the first profiled * pass beginning to the last pass ending, including gaps between passes. This is elapsed GPU * time, not GPU utilization, and is not the sum of potentially overlapping pass durations. * * @type {number|undefined} */ get gpuFrameTime(): number | undefined; /** * Total estimated GPU resource memory in bytes: textures, vertex buffers, index buffers, * uniform buffers and storage buffers. Available in all builds. * * @type {number} */ get vramTotalBytes(): number; /** * Estimated GPU texture memory in bytes. Available in all builds. * * @type {number} */ get vramTextureBytes(): number; /** * Estimated GPU vertex buffer memory in bytes. Available in all builds. * * @type {number} */ get vramVertexBufferBytes(): number; /** * Estimated GPU index buffer memory in bytes. Available in all builds. * * @type {number} */ get vramIndexBufferBytes(): number; /** * Estimated GPU uniform buffer memory in bytes. Available in all builds. Zero when no tracked * uniform buffers have been allocated. * * @type {number} */ get vramUniformBufferBytes(): number; /** * Estimated GPU storage buffer memory in bytes. Available in all builds. Zero on backends * without storage buffers or when none have been allocated. * * @type {number} */ get vramStorageBufferBytes(): number; /** @ignore */ get scene(): { meshInstances: number; lights: number; dynamicLights: number; bakedLights: number; updateShadersTime: number; }; /** @ignore */ get lightmapper(): { renderPasses: number; lightmapCount: number; totalRenderTime: number; forwardTime: number; fboTime: number; shadowMapTime: number; compileTime: number; shadersLinked: number; }; /** @ignore */ get batcher(): { createTime: number; updateLastFrameTime: number; }; /** * Update basic per-frame stats. Called every frame from `AppBase.tick`. * * @param {number} now - High-resolution timestamp for the current frame (ms). * @param {number} dt - Delta time in seconds (time-scaled, clamped). * @param {number} ms - Raw inter-frame time in ms. * @param {ForwardRenderer} renderer - The forward renderer. * @param {GraphicsDevice} device - The graphics device. * @ignore */ updateBasic(now: number, dt: number, ms: number, renderer: ForwardRenderer, device: GraphicsDevice): void; /** * Update detailed per-frame stats (profiler build only). Resets per-frame * counters on the renderer and graphics device. * * @param {ForwardRenderer} renderer - The forward renderer. * @param {GraphicsDevice} device - The graphics device. * @ignore */ updateDetailed(renderer: ForwardRenderer, device: GraphicsDevice): void; /** * Called at the end of each frame to reset per-frame statistics. * * @ignore */ frameEnd(): void; } /** * Callback used by {@link AppBase#configure} when configuration file is loaded and parsed (or an * error occurs). */ type ConfigureAppCallback = (err: string | null) => void; /** * Callback used by {@link AppBase#preload} when all assets (marked as 'preload') are loaded. */ type PreloadAppCallback = () => void; /** * @import { AppOptions } from './app-options.js' * @import { BatchManager } from '../scene/batching/batch-manager.js' * @import { Color } from '../core/math/color.js' * @import { ElementInput } from './input/element-input.js' * @import { GamePads } from '../platform/input/game-pads.js' * @import { GraphicsDevice } from '../platform/graphics/graphics-device.js' * @import { Keyboard } from '../platform/input/keyboard.js' * @import { Lightmapper } from './lightmapper/lightmapper.js' * @import { Mouse } from '../platform/input/mouse.js' * @import { SoundManager } from '../platform/sound/manager.js' * @import { TouchDevice } from '../platform/input/touch-device.js' * @import { Vec3 } from '../core/math/vec3.js' * @import { XrManager } from './xr/xr-manager.js' */ /** * @callback ConfigureAppCallback * Callback used by {@link AppBase#configure} when configuration file is loaded and parsed (or an * error occurs). * @param {string|null} err - The error message in the case where the loading or parsing fails. * @returns {void} */ /** * @callback PreloadAppCallback * Callback used by {@link AppBase#preload} when all assets (marked as 'preload') are loaded. * @returns {void} */ /** * Gets the current application, if any. * * @type {AppBase|null} * @ignore */ declare let app: AppBase | null; /** * AppBase represents the base functionality for all PlayCanvas applications. It is responsible for * initializing and managing the application lifecycle. It coordinates core engine systems such * as: * * - The graphics device - see {@link GraphicsDevice}. * - The asset registry - see {@link AssetRegistry}. * - The component system registry - see {@link ComponentSystemRegistry}. * - The scene - see {@link Scene}. * - Input devices - see {@link Keyboard}, {@link Mouse}, {@link TouchDevice}, and {@link GamePads}. * - The main update/render loop. * * Using AppBase directly requires you to register {@link ComponentSystem}s and * {@link ResourceHandler}s yourself. This facilitates * [tree-shaking](https://developer.mozilla.org/en-US/docs/Glossary/Tree_shaking) when bundling * your application. * * It is the preferred entry point for new code - {@link Application} is a convenience subclass * that registers everything for you, and is expected to be deprecated in a future release. * * `new AppBase(canvas)` only constructs the instance and its root entity. You must then call * {@link AppBase#init} with an {@link AppOptions} supplying at minimum `graphicsDevice`, * `componentSystems` and `resourceHandlers` before adding components or calling * {@link AppBase#start}. Create the `graphicsDevice` with {@link createGraphicsDevice}. * * @category Framework */ declare class AppBase extends EventHandler { static _applications: {}; /** * Get the current application. In the case where there are multiple running applications, the * function can get an application based on a supplied canvas id. This function is particularly * useful when the current Application is not readily available. For example, in the JavaScript * console of the browser's developer tools. * * @param {string} [id] - If defined, the returned application should use the canvas which has * this id. Otherwise current application will be returned. * @returns {AppBase|undefined} The running application, if any. * @example * const app = AppBase.getApplication(); */ static getApplication(id?: string): AppBase | undefined; static cancelTick(app: any): void; /** * Create a new AppBase instance. * * @param {HTMLCanvasElement | OffscreenCanvas} canvas - The canvas element. * @example * const app = new AppBase(canvas); * * const options = new AppOptions(); * app.init(options); * * // Start the application's main loop * app.start(); */ constructor(canvas: HTMLCanvasElement | OffscreenCanvas); /** * The application's batch manager. * * @type {BatchManager|null} * @private */ private _batcher; /** @private */ private _destroyRequested; /** @private */ private _inFrameUpdate; /** * Whether the app announced itself to a devtools hook, and so withdraws on destroy. * * @private */ private _devtoolsRegistered; /** @private */ private _librariesLoaded; /** @private */ private _fillMode; /** @private */ private _resolutionMode; /** @private */ private _allowResize; /** * @type {Asset|null} * @private */ private _skyboxAsset; /** * @type {SoundManager} * @private */ private _soundManager; /** @private */ private _visibilityChangeHandler; /** * Stores all entities that have been created for this app by guid. * * @type {Object} * @ignore */ _entityIndex: { [x: string]: Entity; }; /** @ignore */ _inTools: boolean; /** @ignore */ _scriptPrefix: string; /** @ignore */ _time: number; /** * Set this to false if you want to run without using bundles. We set it to true only if * TextDecoder is available because we currently rely on it for untarring. * * @ignore */ enableBundles: boolean; /** * A request id returned by requestAnimationFrame, allowing us to cancel it. * * @ignore */ frameRequestId: any; /** * Main loop tick, invoked by `requestAnimationFrame` each frame. Bound to this instance so * it can be passed directly to `requestAnimationFrame`. Subclasses may replace this with * their own tick function. * * @param {number} [timestamp] - The timestamp supplied by requestAnimationFrame. * @param {XRFrame} [xrFrame] - XRFrame from requestAnimationFrame callback. * @ignore */ tick: (timestamp?: number, xrFrame?: XRFrame) => void; /** * Set to true to render the scene on the next iteration of the main loop. This only has an * effect if {@link autoRender} is set to false. The value of renderNextFrame is set back to * false again as soon as the scene has been rendered. * * @example * // Render the scene only while space key is pressed * if (this.app.keyboard.isPressed(KEY_SPACE)) { * this.app.renderNextFrame = true; * } */ renderNextFrame: boolean; /** * Scales the global time delta. Defaults to 1. Scripts, animation and physics all receive * the scaled delta, so 0 stops them together. To pause or slow down physics alone while the * rest of the application keeps running, use {@link RigidBodyComponentSystem#timeScale}. * * @example * // Set the app to run at half speed * this.app.timeScale = 0.5; */ timeScale: number; /** * Clamps per-frame delta time to an upper bound. Useful since returning from a tab * deactivation can generate huge values for dt, which can adversely affect game state. * Defaults to 0.1 (seconds). * * @type {number} * @example * // Don't clamp inter-frame times of 200ms or less * this.app.maxDeltaTime = 0.2; */ maxDeltaTime: number; /** * The total number of frames the application has updated since start() was called. * * @ignore */ frame: number; /** * The frame graph. * * @type {FrameGraph} * @ignore */ frameGraph: FrameGraph; /** * The forward renderer. * * @type {ForwardRenderer} * @ignore */ renderer: ForwardRenderer; /** * Scripts in order of loading first. * * @type {string[]} */ scriptsOrder: string[]; /** * @type {AppStats} * @private */ private _stats; /** * When true, the application's render function is called every frame. Setting autoRender to * false is useful to applications where the rendered image may often be unchanged over time. * This can heavily reduce the application's load on the CPU and GPU. Defaults to true. * * @example * // Disable rendering every frame and only render on a keydown event * this.app.autoRender = false; * this.app.keyboard.on('keydown', (event) => { * this.app.renderNextFrame = true; * }); */ autoRender: boolean; /** * The graphics device used by the application. * * @type {GraphicsDevice} */ graphicsDevice: GraphicsDevice; /** * The root entity of the application. * * @type {Entity} * @example * // Return the first entity called 'Camera' in a depth-first search of the scene hierarchy * const camera = this.app.root.findByName('Camera'); */ root: Entity; /** * The scene managed by the application. * * @type {Scene} * @example * // Set the fog type property of the application's scene * this.app.scene.fog.type = FOG_LINEAR; */ scene: Scene; /** * The run-time lightmapper. * * @type {Lightmapper|null} */ lightmapper: Lightmapper | null; /** * The resource loader. * * @type {ResourceLoader} */ loader: ResourceLoader; /** * The asset registry managed by the application. * * @type {AssetRegistry} * @example * // Search the asset registry for all assets with the tag 'vehicle' * const vehicleAssets = this.app.assets.findByTag('vehicle'); */ assets: AssetRegistry; /** * The bundle registry managed by the application. * * @type {BundleRegistry} * @ignore */ bundles: BundleRegistry; /** * The scene registry managed by the application. * * @type {SceneRegistry} * @example * // Search the scene registry for a item with the name 'racetrack1' * const sceneItem = this.app.scenes.find('racetrack1'); * * // Load the scene using the item's url * this.app.scenes.loadScene(sceneItem.url); */ scenes: SceneRegistry; /** * The application's script registry. * * @type {ScriptRegistry} */ scripts: ScriptRegistry; /** * The application's component system registry. * * @type {ComponentSystemRegistry} * @example * // Set global gravity to zero * this.app.systems.rigidbody.gravity.set(0, 0, 0); * @example * // Set the global sound volume to 50% * this.app.systems.sound.volume = 0.5; */ systems: ComponentSystemRegistry; /** * Handles localization. * * @type {I18n} */ i18n: I18n; /** * The keyboard device. * * @type {Keyboard|null} */ keyboard: Keyboard | null; /** * The mouse device. * * @type {Mouse|null} */ mouse: Mouse | null; /** * Used to get touch events input. * * @type {TouchDevice|null} */ touch: TouchDevice | null; /** * Used to access GamePad input. * * @type {GamePads|null} */ gamepads: GamePads | null; /** * Used to handle input for {@link ElementComponent}s. * * @type {ElementInput|null} */ elementInput: ElementInput | null; /** * The XR Manager that provides ability to start VR/AR sessions. * * @type {XrManager|null} * @example * // check if VR is available * if (app.xr.isAvailable(XRTYPE_VR)) { * // VR is available * } */ xr: XrManager | null; /** * Initialize the app. * * @param {AppOptions} appOptions - Options specifying the init parameters for the app. */ init(appOptions: AppOptions): void; defaultLayerWorld: Layer; defaultLayerDepth: Layer; defaultLayerSkybox: Layer; defaultLayerUi: Layer; defaultLayerImmediate: Layer; /** @private */ private _initDefaultMaterial; /** @private */ private _initProgramLibrary; /** * @type {SoundManager} * @ignore */ get soundManager(): SoundManager; /** * The application's batch manager. The batch manager is used to merge mesh instances in * the scene, which reduces the overall number of draw calls, thereby boosting performance. * * @type {BatchManager} */ get batcher(): BatchManager; /** * The current fill mode of the canvas. Can be: * * - {@link FILLMODE_NONE}: the canvas will always match the size provided. * - {@link FILLMODE_FILL_WINDOW}: the canvas will simply fill the window, changing aspect ratio. * - {@link FILLMODE_KEEP_ASPECT}: the canvas will grow to fill the window as best it can while * maintaining the aspect ratio. * * @type {string} */ get fillMode(): string; /** * The application's performance statistics. Returns the same {@link AppStats} instance on * every access. Engine measurements are read-only; {@link AppStats#user} holds writable * application-defined counters. See {@link AppStats} for units, sampling and GPU profiling setup. * * @type {AppStats} */ get stats(): AppStats; /** * The current resolution mode of the canvas, Can be: * * - {@link RESOLUTION_AUTO}: if width and height are not provided, canvas will be resized to * match canvas client size. * - {@link RESOLUTION_FIXED}: resolution of canvas will be fixed. * * @type {string} */ get resolutionMode(): string; /** * Load the application configuration file and apply application properties and fill the asset * registry. * * @param {string} url - The URL of the configuration file to load. * @param {ConfigureAppCallback} callback - The Function called when the configuration file is * loaded and parsed (or an error occurs). */ configure(url: string, callback: ConfigureAppCallback): void; /** * Load all assets in the asset registry that are marked as 'preload'. * * Container-backed render assets wait for their referenced containers to be registered and * loaded. If a preloaded render asset's `data.containerAsset` refers to a container that is * never registered, this method never calls its callback or fires `preload:end`. Debug builds * warn when a render asset starts waiting for an unregistered container. * * @param {PreloadAppCallback} callback - Function called when all assets are loaded. */ preload(callback: PreloadAppCallback): void; _preloadScripts(sceneData: any, callback: any): void; _parseApplicationProperties(props: any, callback: any): void; _width: any; _height: any; /** * @param {string[]} urls - List of URLs to load. * @param {Function} callback - Callback function. * @private */ private _loadLibraries; /** * Insert scene name/urls into the registry. * * @param {*} scenes - Scenes to add to the scene registry. * @private */ private _parseScenes; /** * Insert assets into registry. * * @param {*} assets - Assets to insert. * @private */ private _parseAssets; /** * Start the application. This function does the following: * * 1. Fires an event on the application named 'start' * 2. Calls initialize for all components on entities in the hierarchy * 3. Fires an event on the application named 'initialize' * 4. Calls postInitialize for all components on entities in the hierarchy * 5. Fires an event on the application named 'postinitialize' * 6. Starts executing the main loop of the application * * This function is called internally by PlayCanvas applications made in the Editor but you * will need to call start yourself if you are using the engine stand-alone. * * The main loop is driven by `requestAnimationFrame`. Where that is unavailable, such as in * Node.js, no loop runs, so call {@link update} yourself at the rate you need. * * @example * app.start(); */ start(): void; _alreadyStarted: boolean; /** * Request the next animation frame tick. * * @ignore */ requestAnimationFrame(): void; /** * Update all input devices managed by the application. * * @param {number} dt - The time in seconds since the last update. * @private */ private inputUpdate; /** * Update the application. This function will call the update functions and then the postUpdate * functions of all enabled components. It will then update the current state of all connected * input devices. This function is called internally in the application's main loop and does * not need to be called explicitly, except where there is no main loop, such as in Node.js. * * @param {number} dt - The time delta in seconds since the last frame. * @example * // run a Node.js server at 20 updates per second * setInterval(() => app.update(1 / 20), 50); */ update(dt: number): void; /** * Render the application's scene. More specifically, the scene's {@link LayerComposition} is * rendered. This function is called internally in the application's main loop and does not * need to be called explicitly. * * @ignore */ render(): void; renderComposition(layerComposition: any): void; /** * Controls how the canvas fills the window. The canvas is sized when this is called and on * every {@link AppBase#resizeCanvas}; the engine installs no window `resize` listener of its * own, so call `resizeCanvas` from your own handler to keep the window-relative modes tracking * the window. * * @param {string} mode - The mode to use when setting the size of the canvas. Can be: * * - {@link FILLMODE_NONE}: the canvas will always match the size provided. * - {@link FILLMODE_FILL_WINDOW}: the canvas will simply fill the window, changing aspect ratio. * - {@link FILLMODE_KEEP_ASPECT}: the canvas will grow to fill the window as best it can while * maintaining the aspect ratio. * * @param {number} [width] - The width of the canvas (only used when mode is {@link FILLMODE_NONE}). * @param {number} [height] - The height of the canvas (only used when mode is {@link FILLMODE_NONE}). */ setCanvasFillMode(mode: string, width?: number, height?: number): void; /** * Change the resolution of the canvas, and set the way it behaves when the window is resized. * * @param {string} mode - The mode to use when setting the resolution. Can be: * * - {@link RESOLUTION_AUTO}: if width and height are not provided, canvas will be resized to * match canvas client size. * - {@link RESOLUTION_FIXED}: resolution of canvas will be fixed. * * @param {number} [width] - The horizontal resolution, optional in AUTO mode, if not provided * canvas clientWidth is used. * @param {number} [height] - The vertical resolution, optional in AUTO mode, if not provided * canvas clientHeight is used. */ setCanvasResolution(mode: string, width?: number, height?: number): void; /** * Queries the visibility of the window or tab in which the application is running. * * @returns {boolean} True if the application is not visible and false otherwise. */ isHidden(): boolean; /** * Called when the visibility state of the current tab/window changes. * * @private */ private onVisibilityChange; /** * Resize the application's canvas element in line with the current fill mode. * * - In {@link FILLMODE_KEEP_ASPECT} mode, the canvas will grow to fill the window as best it * can while maintaining the aspect ratio. * - In {@link FILLMODE_FILL_WINDOW} mode, the canvas will simply fill the window, changing * aspect ratio. * - In {@link FILLMODE_NONE} mode, the canvas will always match the size provided. * * @param {number} [width] - The width of the canvas. Only used if current fill mode is {@link FILLMODE_NONE}. * @param {number} [height] - The height of the canvas. Only used if current fill mode is {@link FILLMODE_NONE}. * @returns {{width: number, height: number}|undefined} An object containing the values * calculated to use as width and height, or `undefined` if resizing is not allowed or an XR * session is active. */ resizeCanvas(width?: number, height?: number): { width: number; height: number; } | undefined; /** * Updates the {@link GraphicsDevice} canvas size to match the canvas size on the document * page. It is recommended to call this function when the canvas size changes (e.g on window * resize and orientation change events) so that the canvas resolution is immediately updated. */ updateCanvasSize(): void; /** * Event handler called when all code libraries have been loaded. Code libraries are passed * into the constructor of the Application and the application won't start running or load * packs until all libraries have been loaded. * * @private */ private onLibrariesLoaded; /** * Apply scene settings to the current scene. Useful when your scene settings are parsed or * generated from a non-URL source. * * @param {object} settings - The scene settings to be applied. * @param {object} settings.physics - The physics settings to be applied. * @param {number[]} settings.physics.gravity - The world space vector representing global * gravity in the physics simulation. Must be a fixed size array with three number elements, * corresponding to each axis [ X, Y, Z ]. * @param {object} settings.render - The rendering settings to be applied. * @param {number[]} settings.render.global_ambient - The color of the scene's ambient light. * Must be a fixed size array with three number elements, corresponding to each color channel * [ R, G, B ]. * @param {string} settings.render.fog - The type of fog used by the scene. Can be: * * - {@link FOG_NONE} * - {@link FOG_LINEAR} * - {@link FOG_EXP} * - {@link FOG_EXP2} * * @param {number[]} settings.render.fog_color - The color of the fog (if enabled). Must be a * fixed size array with three number elements, corresponding to each color channel [ R, G, B ]. * @param {number} settings.render.fog_density - The density of the fog (if enabled). This * property is only valid if the fog property is set to {@link FOG_EXP} or {@link FOG_EXP2}. * @param {number} settings.render.fog_start - The distance from the viewpoint where linear fog * begins. This property is only valid if the fog property is set to {@link FOG_LINEAR}. * @param {number} settings.render.fog_end - The distance from the viewpoint where linear fog * reaches its maximum. This property is only valid if the fog property is set to {@link FOG_LINEAR}. * @param {number} settings.render.gamma_correction - The gamma correction to apply when * rendering the scene. Can be: * * - {@link GAMMA_NONE} * - {@link GAMMA_SRGB} * * @param {number} settings.render.tonemapping - The tonemapping transform to apply when * writing fragments to the frame buffer. Can be: * * - {@link TONEMAP_LINEAR} * - {@link TONEMAP_FILMIC} * - {@link TONEMAP_HEJL} * - {@link TONEMAP_ACES} * - {@link TONEMAP_ACES2} * - {@link TONEMAP_NEUTRAL} * * @param {number} settings.render.exposure - The exposure value tweaks the overall brightness * of the scene. * @param {number|null} [settings.render.skybox] - The asset ID of the cube map texture to be * used as the scene's skybox. Defaults to null. * @param {number} [settings.render.skyboxIntensity] - Multiplier for skybox intensity. Defaults to 1. * @param {number} [settings.render.skyboxLuminance] - Lux (lm/m^2) value for skybox intensity when physical light units are enabled. Defaults to 20000. * @param {number} [settings.render.skyboxMip] - The mip level of the skybox to be displayed. Defaults to 0. * Only valid for prefiltered cubemap skyboxes. * @param {number[]} [settings.render.skyboxRotation] - Rotation of skybox. Defaults to [0, 0, 0]. * * @param {string} [settings.render.skyType] - The type of the sky. One of the SKYTYPE_* constants. Defaults to {@link SKYTYPE_INFINITE}. * @param {number[]} [settings.render.skyMeshPosition] - The position of sky mesh. Ignored for {@link SKYTYPE_INFINITE}. Defaults to [0, 0, 0]. * @param {number[]} [settings.render.skyMeshRotation] - The rotation of sky mesh. Ignored for {@link SKYTYPE_INFINITE}. Defaults to [0, 0, 0]. * @param {number[]} [settings.render.skyMeshScale] - The scale of sky mesh. Ignored for {@link SKYTYPE_INFINITE}. Defaults to [1, 1, 1]. * @param {number[]} [settings.render.skyCenter] - The center of the sky. Ignored for {@link SKYTYPE_INFINITE}. Defaults to [0, 1, 0]. * * @param {number} settings.render.lightmapSizeMultiplier - The lightmap resolution multiplier. * @param {number} settings.render.lightmapMaxResolution - The maximum lightmap resolution. * @param {number} settings.render.lightmapMode - The lightmap baking mode. Can be: * * - {@link BAKE_COLOR}: single color lightmap * - {@link BAKE_COLORDIR}: single color lightmap + dominant light direction (used for bump/specular) * * @param {boolean} [settings.render.lightmapFilterEnabled] - Enables bilateral filter on runtime baked color lightmaps. Defaults to false. * @param {number} [settings.render.lightmapFilterRange] - Sets the range parameter of the bilateral filter. Defaults to 10. * @param {number} [settings.render.lightmapFilterSmoothness] - Sets the spatial parameter of the bilateral filter. Defaults to 0.2. * * @param {boolean} [settings.render.ambientBake] - Enable baking ambient light into lightmaps. Defaults to false. * @param {number} [settings.render.ambientBakeNumSamples] - Number of samples to use when baking ambient light. Defaults to 1. * @param {number} [settings.render.ambientBakeSpherePart] - How much of the sphere to include when baking ambient light. Defaults to 0.4. * @param {number} [settings.render.ambientBakeOcclusionBrightness] - Brightness of the baked ambient occlusion. Defaults to 0. * @param {number} [settings.render.ambientBakeOcclusionContrast] - Contrast of the baked ambient occlusion. Defaults to 0. * @param {number} settings.render.ambientLuminance - Lux (lm/m^2) value for ambient light intensity. * * @param {boolean} [settings.render.clusteredLightingEnabled] - Enable clustered lighting. Defaults to false. * @param {boolean} [settings.render.lightingShadowsEnabled] - If set to true, the clustered lighting will support shadows. Defaults to true. * @param {boolean} [settings.render.lightingCookiesEnabled] - If set to true, the clustered lighting will support cookie textures. Defaults to false. * @param {boolean} [settings.render.lightingAreaLightsEnabled] - If set to true, the clustered lighting will support area lights. Defaults to false. * @param {number} [settings.render.lightingShadowAtlasResolution] - Resolution of the atlas texture storing all non-directional shadow textures. Defaults to 2048. * @param {number} [settings.render.lightingCookieAtlasResolution] - Resolution of the atlas texture storing all non-directional cookie textures. Defaults to 2048. * @param {number} [settings.render.lightingMaxLightsPerCell] - Maximum number of lights a cell can store. Defaults to 255. * @param {number} [settings.render.lightingMaxLights] - Maximum number of lights the clustered lighting can use in a single * frame. Keep this as low as the scene allows, as a larger value has a per-frame cost. The value is limited by the maximum * texture size supported by the device. Defaults to 255. * @param {number} [settings.render.lightingShadowType] - The type of shadow filtering used by all shadows. Can be: * * - {@link SHADOW_PCF1_32F} * - {@link SHADOW_PCF3_32F} * - {@link SHADOW_PCF5_32F} * - {@link SHADOW_PCF1_16F} * - {@link SHADOW_PCF3_16F} * - {@link SHADOW_PCF5_16F} * * Defaults to {@link SHADOW_PCF3_32F}. * @param {number[]} [settings.render.lightingCells] - Number of cells along each world space axis the space containing lights * is subdivided into. Defaults to [10, 3, 10]. * * Only lights with bakeDir=true will be used for generating the dominant light direction. * @param {boolean} [settings.render.gsplatRadialSorting] - Enables radial sorting of Gaussian splats. Defaults to false. * @param {number} [settings.render.gsplatLodUpdateDistance] - Distance threshold in world units to trigger gsplat LOD updates. Defaults to 1. * @param {number} [settings.render.gsplatLodUpdateAngle] - Angle threshold in degrees to trigger gsplat LOD updates based on camera rotation. Defaults to 90. * @param {number} [settings.render.gsplatLodBehindPenalty] - Multiplier applied to effective distance for gsplat nodes behind the camera. Defaults to 1.5. * @param {number} [settings.render.gsplatLodUnderfillLimit] - Maximum number of gsplat LOD levels allowed below the optimal level when optimal data is not resident. Defaults to 0. * @param {number} [settings.render.gsplatSplatBudget] - Number of splats across all GSplats in the scene, used as set by `gsplatSplatBudgetMode`. 0 means no budget. Defaults to 1000000. * @param {string} [settings.render.gsplatSplatBudgetMode] - How the splat budget is used for streamed GSplats: 'target' (default) raises detail until the budget is used up; 'limit' lets the LOD distances of each GSplat decide the detail and only lowers it when they would exceed the budget. * @param {number} [settings.render.gsplatAlphaClip] - Alpha threshold for gsplat shadow, pick, and prepass rendering. Defaults to 0.3. * @param {number} [settings.render.gsplatAlphaClipForward] - Alpha threshold for the forward gsplat rendering pass. Defaults to 1 / 255. * @param {number} [settings.render.gsplatMinPixelSize] - Minimum screen-space pixel size below which splats are discarded. Defaults to 2. * @param {number} [settings.render.gsplatMinContribution] - Minimum visual contribution threshold for the compute gsplat renderer. Defaults to 3. * @param {number} [settings.render.gsplatFoveationStrength] - Foveated contribution culling strength. Defaults to 0. * @param {number} [settings.render.gsplatFoveationCenter] - Protected centre radius for foveated contribution culling. Defaults to 0.3. * @param {boolean} [settings.render.gsplatAntiAlias] - Enables anti-aliasing compensation for Gaussian splats. Defaults to false. * @param {boolean} [settings.render.gsplatUseFog] - Whether to apply scene fog to Gaussian splats. Defaults to true. * @param {boolean} [settings.render.gsplatUseTonemap] - Whether to apply the camera's tonemapping and the * scene exposure to Gaussian splats. Defaults to true. * @param {number} [settings.render.gsplatColorUpdateAngle] - Viewing angle threshold in degrees for triggering gsplat spherical harmonics color updates. Defaults to 10. * @param {number} [settings.render.gsplatCooldownTicks] - Number of update ticks before unloading unused streamed gsplat resources. Defaults to 100. * @param {string} [settings.render.gsplatDataFormat] - Work buffer data format for gsplat rendering. One of the GSPLATDATA_* constants. Defaults to {@link GSPLATDATA_COMPACT}. * @param {boolean} [settings.render.gsplatEnableIds] - Enables per-component ID storage in the gsplat work buffer. Defaults to false. * @example * * const settings = { * physics: { * gravity: [0, -9.8, 0] * }, * render: { * fog_end: 1000, * tonemapping: 0, * skybox: null, * fog_density: 0.01, * gamma_correction: 1, * exposure: 1, * fog_start: 1, * global_ambient: [0, 0, 0], * skyboxIntensity: 1, * skyboxRotation: [0, 0, 0], * fog_color: [0, 0, 0], * lightmapMode: 1, * fog: 'none', * lightmapMaxResolution: 2048, * skyboxMip: 2, * lightmapSizeMultiplier: 16 * } * }; * app.applySceneSettings(settings); */ applySceneSettings(settings: { physics: { gravity: number[]; }; render: { global_ambient: number[]; fog: string; fog_color: number[]; fog_density: number; fog_start: number; fog_end: number; gamma_correction: number; tonemapping: number; exposure: number; skybox?: number | null; skyboxIntensity?: number; skyboxLuminance?: number; skyboxMip?: number; skyboxRotation?: number[]; skyType?: string; skyMeshPosition?: number[]; skyMeshRotation?: number[]; skyMeshScale?: number[]; skyCenter?: number[]; lightmapSizeMultiplier: number; lightmapMaxResolution: number; lightmapMode: number; lightmapFilterEnabled?: boolean; lightmapFilterRange?: number; lightmapFilterSmoothness?: number; ambientBake?: boolean; ambientBakeNumSamples?: number; ambientBakeSpherePart?: number; ambientBakeOcclusionBrightness?: number; ambientBakeOcclusionContrast?: number; ambientLuminance: number; clusteredLightingEnabled?: boolean; lightingShadowsEnabled?: boolean; lightingCookiesEnabled?: boolean; lightingAreaLightsEnabled?: boolean; lightingShadowAtlasResolution?: number; lightingCookieAtlasResolution?: number; lightingMaxLightsPerCell?: number; lightingMaxLights?: number; lightingShadowType?: number; lightingCells?: number[]; gsplatRadialSorting?: boolean; gsplatLodUpdateDistance?: number; gsplatLodUpdateAngle?: number; gsplatLodBehindPenalty?: number; gsplatLodUnderfillLimit?: number; gsplatSplatBudget?: number; gsplatSplatBudgetMode?: string; gsplatAlphaClip?: number; gsplatAlphaClipForward?: number; gsplatMinPixelSize?: number; gsplatMinContribution?: number; gsplatFoveationStrength?: number; gsplatFoveationCenter?: number; gsplatAntiAlias?: boolean; gsplatUseFog?: boolean; gsplatUseTonemap?: boolean; gsplatColorUpdateAngle?: number; gsplatCooldownTicks?: number; gsplatDataFormat?: string; gsplatEnableIds?: boolean; }; }): void; /** * Sets the area light LUT tables for this app. * * @param {number[]} ltcMat1 - LUT table of type `array` to be set. * @param {number[]} ltcMat2 - LUT table of type `array` to be set. */ setAreaLightLuts(ltcMat1: number[], ltcMat2: number[]): void; /** * Sets the skybox asset to current scene, and subscribes to asset load/change events. * * @param {Asset} asset - Asset of type `skybox` to be set to, or null to remove skybox. */ setSkybox(asset: Asset): void; /** @private */ private _onSkyboxRemoved; /** @private */ private _onSkyboxChanged; /** @private */ private _firstBake; /** @private */ private _firstBatch; /** * Provide an opportunity to modify the timestamp supplied by requestAnimationFrame. * * @param {number} [timestamp] - The timestamp supplied by requestAnimationFrame. * @returns {number|undefined} The modified timestamp. * @ignore */ _processTimestamp(timestamp?: number): number | undefined; /** * Draws a single line. Line start and end coordinates are specified in world space. The line * will be flat-shaded with the specified color. * * @param {Vec3} start - The start world space coordinate of the line. * @param {Vec3} end - The end world space coordinate of the line. * @param {Color} [color] - The color of the line, specified in sRGB color space. It defaults * to white if not specified. * @param {boolean} [depthTest] - Specifies if the line is depth tested against the depth * buffer. Defaults to true. * @param {Layer} [layer] - The layer to render the line into. Defaults to {@link LAYERID_IMMEDIATE}. * @example * // Render a 1-unit long white line * const start = new Vec3(0, 0, 0); * const end = new Vec3(1, 0, 0); * app.drawLine(start, end); * @example * // Render a 1-unit long red line which is not depth tested and renders on top of other geometry * const start = new Vec3(0, 0, 0); * const end = new Vec3(1, 0, 0); * app.drawLine(start, end, Color.RED, false); * @example * // Render a 1-unit long white line into the world layer * const start = new Vec3(0, 0, 0); * const end = new Vec3(1, 0, 0); * const worldLayer = app.scene.layers.getLayerById(LAYERID_WORLD); * app.drawLine(start, end, Color.WHITE, true, worldLayer); */ drawLine(start: Vec3, end: Vec3, color?: Color, depthTest?: boolean, layer?: Layer): void; /** * Renders an arbitrary number of discrete line segments. The lines are not connected by each * subsequent point in the array. Instead, they are individual segments specified by two * points. Therefore, the lengths of the supplied position and color arrays must be the same * and also must be a multiple of 2. The colors of the ends of each line segment will be * interpolated along the length of each line. * * @param {Vec3[]} positions - An array of points to draw lines between. The length of the * array must be a multiple of 2. * @param {Color[] | Color} colors - An array of colors or a single color. If an array is * specified, this must be the same length as the position array. The length of the array * must also be a multiple of 2. * @param {boolean} [depthTest] - Specifies if the lines are depth tested against the depth * buffer. Defaults to true. * @param {Layer} [layer] - The layer to render the lines into. Defaults to {@link LAYERID_IMMEDIATE}. * @example * // Render a single line, with unique colors for each point * const start = new Vec3(0, 0, 0); * const end = new Vec3(1, 0, 0); * app.drawLines([start, end], [Color.RED, Color.WHITE]); * @example * // Render 2 discrete line segments * const points = [ * // Line 1 * new Vec3(0, 0, 0), * new Vec3(1, 0, 0), * // Line 2 * new Vec3(1, 1, 0), * new Vec3(1, 1, 1) * ]; * const colors = [ * // Line 1 * Color.RED, * Color.YELLOW, * // Line 2 * Color.CYAN, * Color.BLUE * ]; * app.drawLines(points, colors); */ drawLines(positions: Vec3[], colors: Color[] | Color, depthTest?: boolean, layer?: Layer): void; /** * Renders an arbitrary number of discrete line segments. The lines are not connected by each * subsequent point in the array. Instead, they are individual segments specified by two * points. * * @param {number[]} positions - An array of points to draw lines between. Each point is * represented by 3 numbers - x, y and z coordinate. * @param {number[]|Color} colors - A single color for all lines, or an array of colors to color * the lines. If an array is specified, the number of colors it stores must match the number * of positions provided. * @param {boolean} [depthTest] - Specifies if the lines are depth tested against the depth * buffer. Defaults to true. * @param {Layer} [layer] - The layer to render the lines into. Defaults to {@link LAYERID_IMMEDIATE}. * @example * // Render 2 discrete line segments * const points = [ * // Line 1 * 0, 0, 0, * 1, 0, 0, * // Line 2 * 1, 1, 0, * 1, 1, 1 * ]; * const colors = [ * // Line 1 * 1, 0, 0, 1, // red * 0, 1, 0, 1, // green * // Line 2 * 0, 0, 1, 1, // blue * 1, 1, 1, 1 // white * ]; * app.drawLineArrays(points, colors); */ drawLineArrays(positions: number[], colors: number[] | Color, depthTest?: boolean, layer?: Layer): void; /** * @deprecated Use {@link WireRenderer#sphere} instead. * @ignore */ drawWireSphere(): void; /** * @deprecated Use {@link WireRenderer#boxMinMax} instead. * @ignore */ drawWireAlignedBox(): void; drawMeshInstance(): void; drawMesh(): void; drawQuad(): void; drawTexture(): void; drawDepthTexture(): void; /** * Destroys application and removes all event listeners at the end of the current engine frame * update. However, if called outside of the engine frame update, calling destroy() will * destroy the application immediately. * * @example * app.destroy(); */ destroy(): void; _gsplatSortedEvt: EventHandle; context: any; /** * Get entity from the index by guid. * * @param {string} guid - The GUID to search for. * @returns {Entity} The Entity with the GUID or null. * @ignore */ getEntityFromIndex(guid: string): Entity; /** * @param {Scene} scene - The scene. * @private */ private _registerSceneImmediate; /** * Reports whether the document is in fullscreen mode. * * @returns {boolean} True if the document is in fullscreen. * @ignore * @deprecated Use the Fullscreen API directly. */ isFullscreen(): boolean; /** * Requests fullscreen mode on the given element. * * @param {Element} [element] - The element to make fullscreen. Defaults to the graphics * device canvas. * @param {Function} [success] - Called once fullscreen has been entered. * @param {Function} [error] - Called if entering fullscreen fails. * @ignore * @deprecated Use the Fullscreen API directly. */ enableFullscreen(element?: Element, success?: Function, error?: Function): void; /** * Exits fullscreen mode. * * @param {Function} [success] - Called once fullscreen has been exited. * @ignore * @deprecated Use the Fullscreen API directly. */ disableFullscreen(success?: Function): void; /** * Gets the URL of a scene by name. * * @param {string} name - The name of the scene. * @returns {string|null} The URL of the scene, or null if not found. * @ignore * @deprecated Use {@link AppBase#scenes} and {@link SceneRegistry#find} instead. */ getSceneUrl(name: string): string | null; /** * Loads a scene. * * @param {string} url - The URL of the scene file. * @param {Function} callback - Called when the scene has loaded. * @ignore * @deprecated Use {@link AppBase#scenes} and {@link SceneRegistry#loadScene} instead. */ loadScene(url: string, callback: Function): void; /** * Loads a scene hierarchy. * * @param {string} url - The URL of the scene file. * @param {Function} callback - Called when the scene hierarchy has loaded. * @ignore * @deprecated Use {@link AppBase#scenes} and {@link SceneRegistry#loadSceneHierarchy} instead. */ loadSceneHierarchy(url: string, callback: Function): void; /** * Loads scene settings. * * @param {string} url - The URL of the scene file. * @param {Function} callback - Called when the scene settings have loaded. * @ignore * @deprecated Use {@link AppBase#scenes} and {@link SceneRegistry#loadSceneSettings} instead. */ loadSceneSettings(url: string, callback: Function): void; } /** * @import { AppBase } from '../app-base.js' * @import { Component } from './component.js' * @import { ComponentOptionsOverrides } from './registry.js' * @import { Entity } from '../entity.js' */ /** * Component Systems contain the logic and functionality to update all Components of a particular * type. * * @category Framework */ declare class ComponentSystem extends EventHandler { /** * Create a new ComponentSystem instance. * * @param {AppBase} app - The application managing this system. */ constructor(app: AppBase); /** * The id type of the ComponentSystem. * * @type {string} * @readonly */ readonly id: string; /** * A list of option names accepted by {@link ComponentSystem#addComponent} that are not settable * properties of the component itself - for example keys the system consumes to build derived * state (such as `aabbCenter`) or deprecated aliases. Used only by debug-build validation to * avoid false-positive warnings; subclasses that accept such options should override this and * declare the options in their `...OptionsOverrides` typedef (see * {@link ComponentOptionsOverrides}) so that the typed {@link Entity#addComponent} accepts them. * * @type {string[]} * @ignore */ extraDataProperties: string[]; /** * Cache of option names already validated as acceptable by {@link ComponentSystem#addComponent}, * lazily populated the first time each option is seen. Debug builds only. * * @type {Set|null} * @ignore */ _validProps: Set | null; app: AppBase; store: {}; schema: any[]; /** * Create new {@link Component} and component data instances and attach them to the entity. * * @param {Entity} entity - The Entity to attach this component to. * @param {object} [data] - The source data with which to create the component. * @returns {Component} Returns a Component of type defined by the component system. * @example * const entity = new Entity(app); * app.systems.model.addComponent(entity, { type: 'box' }); * // entity.model is now set to a ModelComponent * @ignore */ addComponent(entity: Entity, data?: object): Component; /** * Remove the {@link Component} from the entity and delete the associated component data. * * @param {Entity} entity - The entity to remove the component from. * @example * app.systems.model.removeComponent(entity); * // entity.model === undefined * @ignore */ removeComponent(entity: Entity): void; /** * Create a clone of component. This creates a copy of all component data variables. * * @param {Entity} entity - The entity to clone the component from. * @param {Entity} clone - The entity to clone the component into. * @returns {Component} The newly cloned component. * @ignore */ cloneComponent(entity: Entity, clone: Entity): Component; /** * Called during {@link addComponent} to initialize the component data in the store. This can * be overridden by derived Component Systems and either called by the derived System or * replaced entirely. * * @param {Component} component - The component being initialized. * @param {object} data - The data block used to initialize the component. * @param {Array} [properties] - The array of property * descriptors to initialize from the data block. A descriptor can be either a plain property * name, or an object specifying the name and type. This is a legacy path for external * schema-based components - when omitted, the enabled state is initialized from the data * block instead. Callers that handle the enabled state themselves pass an empty array. * @ignore */ initializeComponentData(component: Component, data?: object, properties?: Array): void; /** * Searches the component schema for properties that match the specified type. * * @param {string} type - The type to search for. * @returns {string[]|object[]} An array of property descriptors matching the specified type. * @ignore */ getPropertiesOfType(type: string): string[] | object[]; destroy(): void; } /** * Stores the information required by {@link AnimEvaluator} for updating a target value. * * @ignore */ declare class AnimTarget { /** * Create a new AnimTarget instance. * * @param {(value: number[]) => void} func - This function will be called when a new animation value is output * by the {@link AnimEvaluator}. * @param {'vector'|'quaternion'|'number'} type - The type of animation data this target * expects. * @param {number} components - The number of components on this target (this should ideally * match the number of components found on all attached animation curves). * @param {string} targetPath - The path to the target value. */ constructor(func: (value: number[]) => void, type: "vector" | "quaternion" | "number", components: number, targetPath: string); _set: any; _get: any; _type: "number" | "quaternion" | "vector"; _components: number; _targetPath: string; _isTransform: boolean; _isWeight: boolean; get set(): any; get get(): any; get type(): "number" | "quaternion" | "vector"; get components(): number; get targetPath(): string; get isTransform(): boolean; get isWeight(): boolean; /** * Returns true if this target should use layer blending (transforms and weights). */ get usesLayerBlending(): boolean; } /** * @import { AnimCurvePath } from '../evaluator/anim-curve.js' * @import { AnimTarget } from '../evaluator/anim-target.js' */ /** * This interface is used by {@link AnimEvaluator} to resolve unique animation target paths * into instances of {@link AnimTarget}. * * @ignore */ declare class AnimBinder { static joinPath(pathSegments: any, character: any): any; static splitPath(path: any, character: any): string[]; /** * Converts a locator array into its string version. * * @param {string|string[]} entityPath - The entity location in the scene defined as an array or * string path. * @param {string} component - The component of the entity the property is located under. * @param {string|string[]} propertyPath - The property location in the entity defined as an array * or string path. * @returns {string} The locator encoded as a string. * @example * // returns 'spotLight/light/color/r' * encode(['spotLight'], 'light', ['color', 'r']); */ static encode(entityPath: string | string[], component: string, propertyPath: string | string[]): string; /** * Resolve the provided target path and return an instance of {@link AnimTarget} which will * handle setting the value, or return null if no such target exists. * * @param {AnimCurvePath} path - The animation curve path to resolve. * @returns {AnimTarget|null} - Returns the target * instance on success and null otherwise. */ resolve(path: AnimCurvePath): AnimTarget | null; /** * Called when the {@link AnimEvaluator} no longer has a curve driving the given key. * * @param {AnimCurvePath} path - The animation curve path which is no longer driven. */ unresolve(path: AnimCurvePath): void; /** * Called by {@link AnimEvaluator} once a frame after animation updates are done. * * @param {number} deltaTime - Amount of time that passed in the current update. */ update(deltaTime: number): void; } /** * Internal cache data for the evaluation of a single curve timeline. * * @ignore */ declare class AnimCache { _left: number; _right: number; _len: number; _recip: number; _p0: number; _p1: number; _t: number; _hermite: { valid: boolean; p0: number; m0: number; p1: number; m1: number; }; update(time: any, input: any): void; _findKey(time: any, input: any): number; eval(result: any, interpolation: any, output: any): void; } /** * @import { AnimTrack } from './anim-track.js' */ /** * AnimSnapshot stores the state of an animation track at a particular time. * * @ignore */ declare class AnimSnapshot { /** * Create a new animation snapshot. * * @param {AnimTrack} animTrack - The source track. */ constructor(animTrack: AnimTrack); _name: string; _time: number; _cache: AnimCache[]; _results: number[][]; } /** * @import { AnimTrack } from './anim-track.js' * @import { EventHandler } from '../../../core/event-handler.js' */ /** * AnimClip wraps the running state of an animation track. It contains and update the animation * 'cursor' and performs looping logic. * * @ignore */ declare class AnimClip { static eventFrame: { start: number; end: number; residual: number; }; /** * Create a new animation clip. * * @param {AnimTrack} track - The animation data. * @param {number} time - The initial time of the clip. * @param {number} speed - Speed of the animation playback. * @param {boolean} playing - true if the clip is playing and false otherwise. * @param {boolean} loop - Whether the clip should loop. * @param {EventHandler} [eventHandler] - The handler to call when an event is fired by the clip. */ constructor(track: AnimTrack, time: number, speed: number, playing: boolean, loop: boolean, eventHandler?: EventHandler); _name: string; _track: AnimTrack; _snapshot: AnimSnapshot; _playing: boolean; _time: number; _speed: number; _loop: boolean; _blendWeight: number; _blendOrder: number; _eventHandler: EventHandler; set name(name: string); get name(): string; set track(track: AnimTrack); get track(): AnimTrack; get snapshot(): AnimSnapshot; set time(time: number); get time(): number; set speed(speed: number); get speed(): number; set loop(loop: boolean); get loop(): boolean; set blendWeight(blendWeight: number); get blendWeight(): number; set blendOrder(blendOrder: number); get blendOrder(): number; set eventCursor(value: any); get eventCursor(): any; _eventCursor: any; get eventCursorEnd(): number; get nextEvent(): any; get isReverse(): boolean; nextEventAheadOfTime(time: any): boolean; nextEventBehindTime(time: any): boolean; resetEventCursor(): void; moveEventCursor(): void; clipFrameTime(frameEndTime: any): void; alignCursorToCurrentTime(): void; fireNextEvent(): void; fireNextEventInFrame(frameStartTime: any, frameEndTime: any): boolean; activeEventsForFrame(frameStartTime: any, frameEndTime: any): void; progressForTime(time: any): number; _update(deltaTime: any): void; play(): void; stop(): void; pause(): void; resume(): void; reset(): void; } /** * @import { AnimBinder } from '../binder/anim-binder.js' * @import { AnimClip } from './anim-clip.js' */ /** * AnimEvaluator blends multiple sets of animation clips together. * * @ignore */ declare class AnimEvaluator { /** * Create a new animation evaluator. * * @param {AnimBinder} binder - Interface that resolves curve paths to instances of * {@link AnimTarget}. */ constructor(binder: AnimBinder); _binder: AnimBinder; _clips: any[]; _inputs: any[]; _outputs: any[]; _targets: {}; /** * The list of animation clips. * * @type {AnimClip[]} */ get clips(): AnimClip[]; /** * Add a clip to the evaluator. * * @param {AnimClip} clip - The clip to add to the evaluator. */ addClip(clip: AnimClip): void; /** * Remove a clip from the evaluator. * * @param {number} index - Index of the clip to remove. */ removeClip(index: number): void; /** * Remove all clips from the evaluator. */ removeClips(): void; updateClipTrack(name: any, animTrack: any): void; /** * Returns the first clip which matches the given name, or null if no such clip was found. * * @param {string} name - Name of the clip to find. * @returns {AnimClip|null} - The clip with the given name or null if no such clip was found. */ findClip(name: string): AnimClip | null; rebind(): void; assignMask(mask: any): any; /** * Evaluator frame update function. All the attached {@link AnimClip}s are evaluated, blended * and the results set on the {@link AnimTarget}. * * @param {number} deltaTime - The amount of time that has passed since the last update, in * seconds. * @param {boolean} [outputAnimation] - Whether the evaluator should output the results of the * update to the bound animation targets. */ update(deltaTime: number, outputAnimation?: boolean): void; } /** * @import { AnimState } from './anim-state.js' * @import { Vec2 } from '../../../core/math/vec2.js' */ /** * AnimBlendTrees are used to store and blend multiple {@link AnimNode}s together. BlendTrees can * be the child of other AnimBlendTrees, in order to create a hierarchy of AnimNodes. It takes a * blend type as an argument which defines which function should be used to determine the weights * of each of its children, based on the current parameter value. * * The blend type is one of {@link ANIM_BLEND_1D}, {@link ANIM_BLEND_2D_DIRECTIONAL}, * {@link ANIM_BLEND_2D_CARTESIAN} and {@link ANIM_BLEND_DIRECT}, each implemented by a subclass. * Every child sits at a point on the parameter axis or plane, and the tree weights the children by * where the current parameter values fall among those points. With `syncAnimations` set, the * children's playback speeds are synchronized so that a walk and a run cycle stay in step while * blending. Blend trees are described in the {@link AnimStateGraph} and built when it loads. * * @category Animation */ declare class AnimBlendTree extends AnimNode { /** * Create a new AnimBlendTree instance. * * @param {AnimState} state - The AnimState that this AnimBlendTree belongs to. * @param {AnimBlendTree|null} parent - The parent of the AnimBlendTree. If not null, the * AnimNode is stored as part of a {@link AnimBlendTree} hierarchy. * @param {string} name - The name of the BlendTree. Used when assigning an {@link AnimTrack} * to its children. * @param {number|Vec2} point - The coordinate/vector that's used to determine the weight of * this node when it's part of an {@link AnimBlendTree}. * @param {string[]} parameters - The anim component parameters which are used to calculate the * current weights of the blend trees children. * @param {object[]} children - The child nodes that this blend tree should create. Can either * be of type {@link AnimNode} or {@link AnimBlendTree}. * @param {boolean} syncAnimations - If true, the speed of each blended animation will be * synchronized. * @param {Function} createTree - Used to create child blend trees of varying types. * @param {Function} findParameter - Used at runtime to get the current parameter values. */ constructor(state: AnimState, parent: AnimBlendTree | null, name: string, point: number | Vec2, parameters: string[], children: object[], syncAnimations: boolean, createTree: Function, findParameter: Function); _parameters: string[]; _parameterValues: any[]; _children: any[]; _findParameter: Function; _syncAnimations: boolean; _pointCache: {}; get weight(): any; get syncAnimations(): boolean; getChild(name: any): any; updateParameterValues(): boolean; getNodeWeightedDuration(i: any): number; getNodeCount(): number; } /** * @import { AnimBlendTree } from './anim-blend-tree.js' * @import { AnimState } from './anim-state.js' */ /** * AnimNodes are used to represent a single animation track in the current state. Each state can * contain multiple AnimNodes, in which case they are stored in a BlendTree hierarchy, which will * control the weight (contribution to the states final animation) of its child AnimNodes. * * `animTrack` is the clip the node plays, `speed` multiplies its playback rate, and * `weight` is set by the parent blend tree, or is one for a node that is the state's only * animation. * * @category Animation */ declare class AnimNode { /** * Create a new AnimNode instance. * * @param {AnimState} state - The AnimState that this BlendTree belongs to. * @param {AnimBlendTree|null} parent - The parent of the AnimNode. If not null, the AnimNode * is stored as part of an {@link AnimBlendTree} hierarchy. * @param {string} name - The name of the AnimNode. Used when assigning an {@link AnimTrack} to * it. * @param {number[]|number} point - The coordinate/vector that's used to determine the weight of * this node when it's part of an {@link AnimBlendTree}. * @param {number} [speed] - The speed that its {@link AnimTrack} should play at. Defaults to 1. */ constructor(state: AnimState, parent: AnimBlendTree | null, name: string, point: number[] | number, speed?: number); _state: AnimState; _parent: AnimBlendTree; _name: string; _point: number | Vec2; _pointLength: number; _speed: number; _weightedSpeed: number; _weight: number; _animTrack: any; get parent(): AnimBlendTree; get name(): string; get path(): any; get point(): number | Vec2; get pointLength(): number; set weight(value: number); get weight(): number; get normalizedWeight(): number; get speed(): number; get absoluteSpeed(): number; set weightedSpeed(weightedSpeed: number); get weightedSpeed(): number; set animTrack(value: any); get animTrack(): any; } /** * @import { AnimState } from './anim-state.js' * @import { Vec2 } from '../../../core/math/vec2.js' */ /** * An AnimBlendTree that calculates its weights using the 1D algorithm from chapter 6 of * [Rune Skovbo Johansen's thesis](https://runevision.com/thesis/rune_skovbo_johansen_thesis.pdf). * * The children sit at points along a single parameter, and the two whose points bracket the * current value share the weight between them. This is the tree for one-dimensional blends such * as idle, walk and run driven by a speed parameter. * * @category Animation */ declare class AnimBlendTree1D extends AnimBlendTree { calculateWeights(): void; } /** * An AnimBlendTree that calculates its weights using the 2D Cartesian algorithm from chapter 6, * section 3 of * [Rune Skovbo Johansen's thesis](https://runevision.com/thesis/rune_skovbo_johansen_thesis.pdf). * * The children sit at points on a plane defined by two parameters, and weights are computed from * where the current parameter point lies among them, treating the two axes as independent. Use it * when the parameters are unrelated quantities, such as forward speed against turn rate. * * @category Animation */ declare class AnimBlendTreeCartesian2D extends AnimBlendTree { static _p: Vec2; static _pip: Vec2; pointDistanceCache(i: any, j: any): any; calculateWeights(): void; } /** * An AnimBlendTree that calculates its weights using the 2D directional algorithm from chapter 6 of * [Rune Skovbo Johansen's thesis](https://runevision.com/thesis/rune_skovbo_johansen_thesis.pdf). * * The children's points are treated as directions from the origin, so the weights follow the * angle and magnitude of the current parameter point. Use it when the two parameters form a * direction, such as a movement vector driving an eight-way locomotion set. * * @category Animation */ declare class AnimBlendTreeDirectional2D extends AnimBlendTree { static _p: Vec2; static _pip: Vec2; pointCache(i: any, j: any): any; calculateWeights(): void; } /** * An AnimBlendTree that calculates normalized weight values based on the total weight. Each * child's weight is read from its own parameter and the weights are then normalized to sum to * one, so the mix is driven explicitly rather than by a position in parameter space. * * @category Animation */ declare class AnimBlendTreeDirect extends AnimBlendTree { calculateWeights(): void; } /** * @import { AnimController } from './anim-controller.js' */ /** * Defines a single state that the controller can be in. Each state contains either a single * {@link AnimNode} or an {@link AnimBlendTree} of multiple {@link AnimNode}s, which will be used * to animate the {@link Entity} while the state is active. An AnimState will stay active and play * as long as there is no {@link AnimTransition} with its conditions met that has that AnimState * as its source state. * * `speed` and `loop` control the playback of the state's tracks. States are defined in * the {@link AnimStateGraph} and entered either by a transition or directly with * {@link AnimComponentLayer#play}. * * @category Animation */ declare class AnimState { /** * Create a new AnimState instance. * * @param {AnimController} controller - The controller this AnimState is associated with. * @param {string} name - The name of the state. Used to find this state when the controller * transitions between states and links animations. * @param {number} [speed] - The speed animations in the state should play at. Individual * {@link AnimNode}s can override this value. * @param {boolean} [loop] - Determines whether animations in this state should loop. * @param {object|null} [blendTree] - If supplied, the AnimState will recursively build a * {@link AnimBlendTree} hierarchy, used to store, blend and play multiple animations. */ constructor(controller: AnimController, name: string, speed?: number, loop?: boolean, blendTree?: object | null); /** @private */ private _animations; /** @private */ private _animationList; _controller: AnimController; _name: string; _speed: number; _loop: boolean; _hasAnimations: boolean; _blendTree: AnimNode | AnimBlendTree1D | AnimBlendTreeCartesian2D | AnimBlendTreeDirectional2D | AnimBlendTreeDirect; _createTree(type: any, state: any, parent: any, name: any, point: any, parameters: any, children: any, syncAnimations: any, createTree: any, findParameter: any): AnimBlendTree1D | AnimBlendTreeCartesian2D | AnimBlendTreeDirectional2D | AnimBlendTreeDirect; _getNodeFromPath(path: any): AnimNode | AnimBlendTree1D | AnimBlendTreeCartesian2D | AnimBlendTreeDirectional2D | AnimBlendTreeDirect; addAnimation(path: any, animTrack: any): void; _updateHasAnimations(): void; get name(): string; set animations(value: any[]); get animations(): any[]; get hasAnimations(): boolean; set speed(value: number); get speed(): number; set loop(value: boolean); get loop(): boolean; get nodeCount(): any; get playable(): boolean; get looping(): boolean; get totalWeight(): number; get timelineDuration(): number; } /** * @import { AnimEvaluator } from '../evaluator/anim-evaluator.js' * @import { EventHandler } from '../../../core/event-handler.js' */ /** * The AnimController manages the animations for its entity, based on the provided state graph and * parameters. Its update method determines which state the controller should be in based on the * current time, parameters and available states / transitions. It also ensures the AnimEvaluator * is supplied with the correct animations, based on the currently active state. * * @ignore */ declare class AnimController { /** * Create a new AnimController. * * @param {AnimEvaluator} animEvaluator - The animation evaluator used to blend all current * playing animation keyframes and update the entities properties based on the current * animation values. * @param {object[]} states - The list of states used to form the controller state graph. * @param {object[]} transitions - The list of transitions used to form the controller state * graph. * @param {boolean} activate - Determines whether the anim controller should automatically play * once all {@link AnimNodes} are assigned animations. * @param {EventHandler} eventHandler - The event handler which should be notified with anim * events. * @param {Function} findParameter - Retrieves a parameter which is used to control the * transition between states. * @param {Function} consumeTrigger - Used to set triggers back to their default state after * they have been consumed by a transition. */ constructor(animEvaluator: AnimEvaluator, states: object[], transitions: object[], activate: boolean, eventHandler: EventHandler, findParameter: Function, consumeTrigger: Function); /** * @type {Object} * @private */ private _states; /** * @type {string[]} * @private */ private _stateNames; /** * @type {Object} * @private */ private _findTransitionsFromStateCache; /** * @type {Object} * @private */ private _findTransitionsBetweenStatesCache; /** * @type {string|null} * @private */ private _previousStateName; /** @private */ private _activeStateName; /** @private */ private _activeStateDuration; /** @private */ private _activeStateDurationDirty; /** @private */ private _playing; /** * @type {boolean} * @private */ private _activate; /** * @type {AnimTransition[]} * @private */ private _transitions; /** @private */ private _currTransitionTime; /** @private */ private _totalTransitionTime; /** @private */ private _isTransitioning; /** @private */ private _transitionInterruptionSource; /** @private */ private _transitionPreviousStates; /** @private */ private _timeInState; /** @private */ private _timeInStateBefore; _animEvaluator: AnimEvaluator; _eventHandler: EventHandler; _findParameter: Function; _consumeTrigger: Function; get animEvaluator(): AnimEvaluator; set activeState(stateName: AnimState); get activeState(): AnimState; get activeStateName(): string; get activeStateAnimations(): any[]; set previousState(stateName: AnimState); get previousState(): AnimState; get previousStateName(): string; get playable(): boolean; set playing(value: boolean); get playing(): boolean; get activeStateProgress(): number; get activeStateDuration(): number; set activeStateCurrentTime(time: number); get activeStateCurrentTime(): number; get transitioning(): boolean; get transitionProgress(): number; get states(): string[]; assignMask(mask: any): any; /** * @param {string} stateName - The name of the state to find. * @returns {AnimState} The state with the given name. * @private */ private _findState; _getActiveStateProgressForTime(time: any): number; /** * Return all the transitions that have the given stateName as their source state. * * @param {string} stateName - The name of the state to find transitions from. * @returns {AnimTransition[]} The transitions that have the given stateName as their source * state. * @private */ private _findTransitionsFromState; /** * Return all the transitions that contain the given source and destination states. * * @param {string} sourceStateName - The name of the source state to find transitions from. * @param {string} destinationStateName - The name of the destination state to find transitions * to. * @returns {AnimTransition[]} The transitions that have the given source and destination states. * @private */ private _findTransitionsBetweenStates; _transitionHasConditionsMet(transition: any): boolean; _findTransition(from: any, to: any): any; updateStateFromTransition(transition: any): void; _transitionToState(newStateName: any): void; assignAnimation(pathString: any, animTrack: any, speed: any, loop: any): void; removeNodeAnimations(nodeName: any): boolean; play(stateName: any): void; pause(): void; reset(): void; rebind(): void; update(dt: any): void; findParameter: (name: any) => any; } /** * @import { AnimComponent } from './component.js' * @import { AnimController } from '../../anim/controller/anim-controller.js' */ /** * An AnimComponentLayer is one layer of an {@link AnimComponent}. It runs the state machine that * the {@link AnimStateGraph} defines for that layer and contributes the result to the entity's * final pose with a {@link weight}, either overwriting the layers beneath it or adding to them * according to `blendType`. A {@link mask} limits which nodes of the hierarchy the layer * animates, which is how an upper-body action plays on top of a full-body locomotion layer. The * first layer is {@link AnimComponent#baseLayer}; add more with {@link AnimComponent#addLayer}. * * Playback is per layer: {@link play} starts a named state, {@link transition} blends to another * state over a given time, {@link pause} and {@link reset} act on the current state, and * {@link activeState}, {@link activeStateProgress} and {@link transitioning} report where the * layer is. {@link assignAnimation} binds an {@link AnimTrack} to a state, or to a node inside a * blend tree using a dotted path, and {@link blendToWeight} fades the whole layer in or out. * * @example * // Fade in an upper-body layer and play its 'Wave' state over the base layer * const layer = entity.anim.findAnimationLayer('UpperBody'); * layer.blendToWeight(1, 0.3); * layer.play('Wave'); * * @category Animation */ declare class AnimComponentLayer { /** * Create a new AnimComponentLayer instance. * * @param {string} name - The name of the layer. * @param {AnimController} controller - The controller to manage this layers animations. * @param {AnimComponent} component - The component that this layer is a member of. * @param {number} [weight] - The weight of this layer. Defaults to 1. * @param {string} [blendType] - The blend type of this layer. Defaults to {@link ANIM_LAYER_OVERWRITE}. * @ignore */ constructor(name: string, controller: AnimController, component: AnimComponent, weight?: number, blendType?: string); /** * @type {string} * @private */ private _name; /** * @type {AnimController} * @private */ private _controller; /** * @type {AnimComponent} * @private */ private _component; /** * @type {number} * @private */ private _weight; /** * @type {string} * @private */ private _blendType; /** @private */ private _mask; /** @private */ private _blendTime; /** @private */ private _blendTimeElapsed; /** @private */ private _startingWeight; /** @private */ private _targetWeight; /** * Returns the name of the layer. * * @type {string} */ get name(): string; /** * Sets whether this layer is currently playing. * * @type {boolean} */ set playing(value: boolean); /** * Gets whether this layer is currently playing. * * @type {boolean} */ get playing(): boolean; /** * Returns true if a state graph has been loaded and all states in the graph have been assigned * animation tracks. * * @type {boolean} */ get playable(): boolean; /** * Gets the currently active state name. * * @type {string} */ get activeState(): string; /** * Gets the previously active state name. * * @type {string|null} */ get previousState(): string | null; /** * Gets the currently active state's progress as a value normalized by the state's animation * duration. Looped animations will return values greater than 1. * * @type {number} */ get activeStateProgress(): number; /** * Gets the currently active states duration. * * @type {number} */ get activeStateDuration(): number; /** * Sets the active state's time in seconds. * * @type {number} */ set activeStateCurrentTime(time: number); /** * Gets the active state's time in seconds. * * @type {number} */ get activeStateCurrentTime(): number; /** * Gets whether the anim component layer is currently transitioning between states. * * @type {boolean} */ get transitioning(): boolean; /** * Gets the progress, if the anim component layer is currently transitioning between states. * Otherwise returns null. * * @type {number|null} */ get transitionProgress(): number | null; /** * Gets all available states in this layers state graph. * * @type {string[]} */ get states(): string[]; /** * Sets the blending weight of this layer. Used when calculating the value of properties that * are animated by more than one layer. * * @type {number} */ set weight(value: number); /** * Sets the blending weight of this layer. * * @type {number} */ get weight(): number; set blendType(value: string); get blendType(): string; /** * Sets the mask of bones which should be animated or ignored by this layer. * * @type {object} * @example * entity.anim.baseLayer.mask = { * // include the spine of the current model and all of its children * "path/to/spine": { * children: true * }, * // include the hip of the current model but not all of its children * "path/to/hip": true * }; */ set mask(value: object); /** * Gets the mask of bones which should be animated or ignored by this layer. * * @type {object} */ get mask(): object; /** * Start playing the animation in the current state. * * @param {string} [name] - If provided, will begin playing from the start of the state with * this name. */ play(name?: string): void; /** * Pause the animation in the current state. */ pause(): void; /** * Reset the animation component to its initial state, including all parameters. The system * will be paused. */ reset(): void; /** * Rebind any animations in the layer to the currently present components and model of the anim * components entity. */ rebind(): void; update(dt: any): void; /** * Blend from the current weight value to the provided weight value over a given amount of time. * * @param {number} weight - The new weight value to blend to. * @param {number} time - The duration of the blend in seconds. */ blendToWeight(weight: number, time: number): void; /** * Assigns an animation track to a state or blend tree node in the current graph. If a state * for the given nodePath doesn't exist, it will be created. If all states nodes are linked and * the {@link AnimComponent#activate} value was set to true then the component will begin * playing. * * @param {string} nodePath - Either the state name or the path to a blend tree node that this * animation should be associated with. Each section of a blend tree path is split using a * period (`.`) therefore state names should not include this character (e.g "MyStateName" or * "MyStateName.BlendTreeNode"). * @param {AnimTrack} animTrack - The animation track that will be assigned to this state and * played whenever this state is active. * @param {number} [speed] - Update the speed of the state you are assigning an animation to. * Defaults to 1. * @param {boolean} [loop] - Update the loop property of the state you are assigning an * animation to. Defaults to true. */ assignAnimation(nodePath: string, animTrack: AnimTrack, speed?: number, loop?: boolean): void; /** * Removes animations from a node in the loaded state graph. * * @param {string} nodeName - The name of the node that should have its animation tracks removed. */ removeNodeAnimations(nodeName: string): void; /** * Returns an object holding the animation asset id that is associated with the given state. * * @param {string} stateName - The name of the state to get the asset for. * @returns {{ asset: number }} An object containing the animation asset id associated with the given state. */ getAnimationAsset(stateName: string): { asset: number; }; /** * Transition to any state in the current layers graph. Transitions can be instant or take an * optional blend time. * * @param {string} to - The state that this transition will transition to. * @param {number} [time] - The duration of the transition in seconds. Defaults to 0. * @param {number} [transitionOffset] - If provided, the destination state will begin playing * its animation at this time. Given in normalized time, based on the states duration & must be * between 0 and 1. Defaults to null. */ transition(to: string, time?: number, transitionOffset?: number): void; } /** * The AnimComponent enables an {@link Entity} to play back animations on models and entity * properties. Animations are driven by animation state graphs, which can be authored in the * PlayCanvas Editor or constructed programmatically, and support blending between multiple * layers and clips. * * You should never need to use the AnimComponent constructor directly. To add an AnimComponent * to an {@link Entity}, use {@link Entity#addComponent}: * * ```javascript * const entity = new Entity(); * entity.addComponent('anim', { * activate: true, * speed: 1 * }); * ``` * * Once the AnimComponent is added to the entity, you can access it via the {@link Entity#anim} * property: * * ```javascript * entity.anim.speed = 2; // Play animations at double speed * * console.log(entity.anim.speed); // Get the playback speed and print it * ``` * * Relevant Engine API examples: * * - [1D Blend Trees](https://playcanvas.github.io/#/animation/blend-trees-1d) * - [2D Cartesian Blend Trees](https://playcanvas.github.io/#/animation/blend-trees-2d-cartesian) * - [2D Directional Blend Trees](https://playcanvas.github.io/#/animation/blend-trees-2d-directional) * - [Animation Events](https://playcanvas.github.io/#/animation/events) * - [Component Properties](https://playcanvas.github.io/#/animation/component-properties) * - [Layer Masks](https://playcanvas.github.io/#/animation/layer-masks) * - [Locomotion](https://playcanvas.github.io/#/animation/locomotion) * * @hideconstructor * @category Animation */ declare class AnimComponent extends Component { /** @private */ private _stateGraphAsset; /** @private */ private _animationAssets; /** @private */ private _speed; /** @private */ private _activate; /** @private */ private _playing; /** @private */ private _rootBone; /** @private */ private _stateGraph; /** @private */ private _layers; /** @private */ private _layerIndices; /** @private */ private _parameters; /** @private */ private _targets; /** @private */ private _consumedTriggers; /** @private */ private _normalizeWeights; set stateGraphAsset(value: any); get stateGraphAsset(): any; /** * Sets whether the animation component will normalize the weights of its layers by their sum total. * * @type {boolean} */ set normalizeWeights(value: boolean); /** * Gets whether the animation component will normalize the weights of its layers by their sum total. * * @type {boolean} */ get normalizeWeights(): boolean; set animationAssets(value: {}); get animationAssets(): {}; /** * Sets the speed multiplier for animation play back speed. 1.0 is playback at normal speed, 0.0 pauses * the animation. * * @type {number} */ set speed(value: number); /** * Gets the speed multiplier for animation play back speed. * * @type {number} */ get speed(): number; /** * Sets whether the first animation will begin playing when the scene is loaded. * * @type {boolean} */ set activate(value: boolean); /** * Gets whether the first animation will begin playing when the scene is loaded. * * @type {boolean} */ get activate(): boolean; /** * Sets whether to play or pause all animations in the component. * * @type {boolean} */ set playing(value: boolean); /** * Gets whether to play or pause all animations in the component. * * @type {boolean} */ get playing(): boolean; /** * Sets the entity that this anim component should use as the root of the animation hierarchy. * * @type {Entity} */ set rootBone(value: Entity); /** * Gets the entity that this anim component should use as the root of the animation hierarchy. * * @type {Entity} */ get rootBone(): Entity; set stateGraph(value: any); get stateGraph(): any; /** * Returns the animation layers available in this anim component. Use addLayer or loadStateGraph * to change layers. * * @type {ReadonlyArray} */ get layers(): ReadonlyArray; set layerIndices(value: {}); get layerIndices(): {}; set parameters(value: {}); get parameters(): {}; set targets(value: {}); get targets(): {}; /** * Returns whether all component layers are currently playable. * * @type {boolean} */ get playable(): boolean; /** * Returns the base layer of the state graph. * * @type {AnimComponentLayer|null} */ get baseLayer(): AnimComponentLayer | null; _onStateGraphAssetChangeEvent(asset: any): void; dirtifyTargets(): void; _addLayer({ name, states, transitions, weight, mask, blendType }: { name: any; states: any; transitions: any; weight: any; mask: any; blendType: any; }): any; /** * Adds a new anim component layer to the anim component. * * @param {string} name - The name of the layer to create. * @param {number} [weight] - The blending weight of the layer. Defaults to 1. * @param {object[]} [mask] - A list of paths to bones in the model which should be animated in * this layer. If omitted the full model is used. Defaults to null. * @param {string} [blendType] - Defines how properties animated by this layer blend with * animations of those properties in previous layers. Defaults to ANIM_LAYER_OVERWRITE. * @returns {AnimComponentLayer} The created anim component layer. */ addLayer(name: string, weight?: number, mask?: object[], blendType?: string): AnimComponentLayer; _assignParameters(stateGraph: any): void; /** * Initializes component animation controllers using the provided state graph. * * @param {object} stateGraph - The state graph asset to load into the component. Contains the * states, transitions and parameters used to define a complete animation controller. * @example * entity.anim.loadStateGraph({ * "layers": [ * { * "name": layerName, * "states": [ * { * "name": "START", * "speed": 1 * }, * { * "name": "Initial State", * "speed": speed, * "loop": loop, * "defaultState": true * } * ], * "transitions": [ * { * "from": "START", * "to": "Initial State" * } * ] * } * ], * "parameters": {} * }); */ loadStateGraph(stateGraph: object): void; setupAnimationAssets(): void; loadAnimationAssets(): void; onAnimationAssetLoaded(layerName: any, stateName: any, asset: any): void; /** * Removes all layers from the anim component. */ removeStateGraph(): void; /** * Reset all of the components layers and parameters to their initial states. If a layer was * playing before it will continue playing. */ reset(): void; unbind(): void; /** * Rebind all of the components layers. */ rebind(): void; /** * Tests whether the given entity is part of the hierarchy this component animates. The binders * resolve their targets within the root bone when one is assigned, and within this component's * entity otherwise, so anything they bind - including the mesh instances backing morph target * weights and animated material textures - belongs to an entity at or below that root. * * @param {Entity} entity - The entity to test. * @returns {boolean} True if the entity is part of the animated hierarchy. * @ignore */ animatesEntity(entity: Entity): boolean; /** * Finds an {@link AnimComponentLayer} in this component. * * @param {string} name - The name of the anim component layer to find. * @returns {AnimComponentLayer} Layer. */ findAnimationLayer(name: string): AnimComponentLayer; addAnimationState(nodeName: any, animTrack: any, speed?: number, loop?: boolean, layerName?: string): void; /** * Associates an animation with a state or blend tree node in the loaded state graph. If all * states are linked and the {@link activate} value was set to true then the component will * begin playing. If no state graph is loaded, a default state graph will be created with a * single state based on the provided nodePath parameter. * * @param {string} nodePath - Either the state name or the path to a blend tree node that this * animation should be associated with. Each section of a blend tree path is split using a * period (`.`) therefore state names should not include this character (e.g "MyStateName" or * "MyStateName.BlendTreeNode"). * @param {AnimTrack} animTrack - The animation track that will be assigned to this state and * played whenever this state is active. * @param {string} [layerName] - The name of the anim component layer to update. If omitted the * default layer is used. If no state graph has been previously loaded this parameter is * ignored. * @param {number} [speed] - Update the speed of the state you are assigning an animation to. * Defaults to 1. * @param {boolean} [loop] - Update the loop property of the state you are assigning an * animation to. Defaults to true. */ assignAnimation(nodePath: string, animTrack: AnimTrack, layerName?: string, speed?: number, loop?: boolean): void; /** * Removes animations from a node in the loaded state graph. * * @param {string} nodeName - The name of the node that should have its animation tracks removed. * @param {string} [layerName] - The name of the anim component layer to update. If omitted the * default layer is used. */ removeNodeAnimations(nodeName: string, layerName?: string): void; getParameterValue(name: any, type: any): any; setParameterValue(name: any, type: any, value: any): void; /** * Returns the parameter object for the specified parameter name. This function is anonymous so that it can be passed to the AnimController * while still being called in the scope of the AnimComponent. * * @param {string} name - The name of the parameter to return the value of. * @returns {object} The parameter object. * @private */ private findParameter; /** * Sets a trigger parameter as having been used by a transition. This function is anonymous so that it can be passed to the AnimController * while still being called in the scope of the AnimComponent. * * @param {string} name - The name of the trigger to set as consumed. * @private */ private consumeTrigger; /** * Returns a float parameter value by name. * * @param {string} name - The name of the float to return the value of. * @returns {number} A float. */ getFloat(name: string): number; /** * Sets the value of a float parameter that was defined in the animation components state graph. * * @param {string} name - The name of the parameter to set. * @param {number} value - The new float value to set this parameter to. */ setFloat(name: string, value: number): void; /** * Returns an integer parameter value by name. * * @param {string} name - The name of the integer to return the value of. * @returns {number} An integer. */ getInteger(name: string): number; /** * Sets the value of an integer parameter that was defined in the animation components state * graph. * * @param {string} name - The name of the parameter to set. * @param {number} value - The new integer value to set this parameter to. */ setInteger(name: string, value: number): void; /** * Returns a boolean parameter value by name. * * @param {string} name - The name of the boolean to return the value of. * @returns {boolean} A boolean. */ getBoolean(name: string): boolean; /** * Sets the value of a boolean parameter that was defined in the animation components state * graph. * * @param {string} name - The name of the parameter to set. * @param {boolean} value - The new boolean value to set this parameter to. */ setBoolean(name: string, value: boolean): void; /** * Returns a trigger parameter value by name. * * @param {string} name - The name of the trigger to return the value of. * @returns {boolean} A boolean. */ getTrigger(name: string): boolean; /** * Sets the value of a trigger parameter that was defined in the animation components state * graph to true. * * @param {string} name - The name of the parameter to set. * @param {boolean} [singleFrame] - If true, this trigger will be set back to false at the end * of the animation update. Defaults to false. */ setTrigger(name: string, singleFrame?: boolean): void; /** * Resets the value of a trigger parameter that was defined in the animation components state * graph to false. * * @param {string} name - The name of the parameter to set. */ resetTrigger(name: string): void; onBeforeRemove(): void; update(dt: any): void; resolveDuplicatedEntityReferenceProperties(oldAnim: any, duplicatedIdsMap: any): void; } /** * Options of the `anim` component accepted by {@link AnimComponentSystem} that differ from the * properties of {@link AnimComponent}. Each replaces the same-named property of the options that * {@link Entity#addComponent} derives from the component class; see * {@link ComponentOptionsOverrides}. */ type AnimComponentOptionsOverrides = { /** * - * Layers to add with {@link AnimComponent#addLayer}, each with a `name` and optional `weight`, * `mask` and `blendType`. */ layers?: { name: string; weight?: number; mask?: object; blendType?: string; }[]; /** * - Bone masks to assign to the added * layers, keyed by layer name. */ masks?: { [layer: string]: { mask: object; }; }; }; /** * @import { AppBase } from '../../app-base.js' * @import { Component } from '../component.js' * @import { Entity } from '../../entity.js' */ /** * Options of the `anim` component accepted by {@link AnimComponentSystem} that differ from the * properties of {@link AnimComponent}. Each replaces the same-named property of the options that * {@link Entity#addComponent} derives from the component class; see * {@link ComponentOptionsOverrides}. * * @typedef {object} AnimComponentOptionsOverrides * @property {{ name: string, weight?: number, mask?: object, blendType?: string }[]} [layers] - * Layers to add with {@link AnimComponent#addLayer}, each with a `name` and optional `weight`, * `mask` and `blendType`. * @property {{ [layer: string]: { mask: object } }} [masks] - Bone masks to assign to the added * layers, keyed by layer name. * @ignore */ /** * Manages the {@link AnimComponent}s of an application and advances their state graphs each * frame. Reach it through `app.systems.anim`; components are created with * {@link Entity#addComponent}, never by calling the system directly. * * @category Animation */ declare class AnimComponentSystem extends ComponentSystem { id: string; ComponentType: typeof AnimComponent; initializeComponentData(component: any, data: any, properties: any): void; onAnimationUpdate(dt: any): void; /** * Rebinds every component animating a hierarchy which contains the entity whose mesh instances * changed. Anim targets which reference mesh instances - morph target weights and animated * material textures - are resolved once and then cached, so they have to be re-resolved when the * mesh instances they point at are created or destroyed. Disabled components are included, as * they keep their bindings and are not rebound when re-enabled. * * @param {Component} component - The component whose mesh instances changed. * @private */ private onMeshInstancesChange; cloneComponent(entity: any, clone: any): Component; onBeforeRemove(entity: any, component: any): void; } /** * The ButtonComponent enables an {@link Entity} to behave like a button, with different visual * states for hover and press interactions. It is designed to be used together with an * {@link ElementComponent} on the same entity, which provides the button's visual appearance and * input hit area. Set {@link imageEntity}, usually to the button's own entity, to choose the * element that is tinted, or has its sprite changed, for each visual state. * * You should never need to use the ButtonComponent constructor directly. To add a * ButtonComponent to an {@link Entity}, use {@link Entity#addComponent}: * * ```javascript * const entity = new Entity(); * entity.addComponent('element', { * type: ELEMENTTYPE_IMAGE, * useInput: true * }); * entity.addComponent('button', { * imageEntity: entity * }); * ``` * * Once the ButtonComponent is added to the entity, you can access it via the * {@link Entity#button} property: * * ```javascript * entity.button.hoverTint = Color.YELLOW; // Set the hover tint color * * console.log(entity.button.hoverTint); // Get the hover tint color and print it * ``` * * Relevant Engine API examples: * * - [Buttons](https://playcanvas.github.io/#/user-interface/buttons) * - [Toggles and radio groups](https://playcanvas.github.io/#/user-interface/common-widgets) * * @hideconstructor * @category User Interface */ declare class ButtonComponent extends Component { /** * Fired when the mouse is pressed while the cursor is on the component. The handler is passed * a {@link ElementMouseEvent}. * * @event * @example * entity.button.on('mousedown', (event) => { * console.log(`Mouse down on entity ${entity.name}`); * }); */ static EVENT_MOUSEDOWN: string; /** * Fired when the mouse is released while the cursor is on the component. The handler is passed * a {@link ElementMouseEvent}. * * @event * @example * entity.button.on('mouseup', (event) => { * console.log(`Mouse up on entity ${entity.name}`); * }); */ static EVENT_MOUSEUP: string; /** * Fired when the mouse cursor enters the component. The handler is passed a * {@link ElementMouseEvent}. * * @event * @example * entity.button.on('mouseenter', (event) => { * console.log(`Mouse entered entity ${entity.name}`); * }); */ static EVENT_MOUSEENTER: string; /** * Fired when the mouse cursor leaves the component. The handler is passed a * {@link ElementMouseEvent}. * * @event * @example * entity.button.on('mouseleave', (event) => { * console.log(`Mouse left entity ${entity.name}`); * }); */ static EVENT_MOUSELEAVE: string; /** * Fired when the mouse is pressed and released on the component or when a touch starts and ends on * the component. The handler is passed a {@link ElementMouseEvent} or {@link ElementTouchEvent}. * * @event * @example * entity.button.on('click', (event) => { * console.log(`Clicked entity ${entity.name}`); * }); */ static EVENT_CLICK: string; /** * Fired when a touch starts on the component. The handler is passed a {@link ElementTouchEvent}. * * @event * @example * entity.button.on('touchstart', (event) => { * console.log(`Touch started on entity ${entity.name}`); * }); */ static EVENT_TOUCHSTART: string; /** * Fired when a touch ends on the component. The handler is passed a {@link ElementTouchEvent}. * * @event * @example * entity.button.on('touchend', (event) => { * console.log(`Touch ended on entity ${entity.name}`); * }); */ static EVENT_TOUCHEND: string; /** * Fired when a touch is canceled on the component. The handler is passed a * {@link ElementTouchEvent}. * * @event * @example * entity.button.on('touchcancel', (event) => { * console.log(`Touch canceled on entity ${entity.name}`); * }); */ static EVENT_TOUCHCANCEL: string; /** * Fired when a touch leaves the component. The handler is passed a {@link ElementTouchEvent}. * * @event * @example * entity.button.on('touchleave', (event) => { * console.log(`Touch left entity ${entity.name}`); * }); */ static EVENT_TOUCHLEAVE: string; /** * Fired when a xr select starts on the component. The handler is passed a * {@link ElementSelectEvent}. * * @event * @example * entity.button.on('selectstart', (event) => { * console.log(`Select started on entity ${entity.name}`); * }); */ static EVENT_SELECTSTART: string; /** * Fired when a xr select ends on the component. The handler is passed a * {@link ElementSelectEvent}. * * @event * @example * entity.button.on('selectend', (event) => { * console.log(`Select ended on entity ${entity.name}`); * }); */ static EVENT_SELECTEND: string; /** * Fired when a xr select now hovering over the component. The handler is passed a * {@link ElementSelectEvent}. * * @event * @example * entity.button.on('selectenter', (event) => { * console.log(`Select entered entity ${entity.name}`); * }); */ static EVENT_SELECTENTER: string; /** * Fired when a xr select not hovering over the component. The handler is passed a * {@link ElementSelectEvent}. * * @event * @example * entity.button.on('selectleave', (event) => { * console.log(`Select left entity ${entity.name}`); * }); */ static EVENT_SELECTLEAVE: string; /** * Fired when the button changes state to be hovered. * * @event * @example * entity.button.on('hoverstart', () => { * console.log(`Entity ${entity.name} hovered`); * }); */ static EVENT_HOVERSTART: string; /** * Fired when the button changes state to be not hovered. * * @event * @example * entity.button.on('hoverend', () => { * console.log(`Entity ${entity.name} unhovered`); * }); */ static EVENT_HOVEREND: string; /** * Fired when the button changes state to be pressed. * * @event * @example * entity.button.on('pressedstart', () => { * console.log(`Entity ${entity.name} pressed`); * }); */ static EVENT_PRESSEDSTART: string; /** * Fired when the button changes state to be not pressed. * * @event * @example * entity.button.on('pressedend', () => { * console.log(`Entity ${entity.name} unpressed`); * }); */ static EVENT_PRESSEDEND: string; /** * Create a new ButtonComponent instance. * * @param {ButtonComponentSystem} system - The ComponentSystem that created this component. * @param {Entity} entity - The entity that this component is attached to. */ constructor(system: ButtonComponentSystem, entity: Entity); /** @private */ private _active; /** @private */ private _hitPadding; /** @private */ private _transitionMode; /** @private */ private _hoverTint; /** @private */ private _pressedTint; /** @private */ private _inactiveTint; /** @private */ private _fadeDuration; /** * @type {Asset|null} * @private */ private _hoverSpriteAsset; /** @private */ private _hoverSpriteFrame; /** * @type {Asset|null} * @private */ private _pressedSpriteAsset; /** @private */ private _pressedSpriteFrame; /** * @type {Asset|null} * @private */ private _inactiveSpriteAsset; /** @private */ private _inactiveSpriteFrame; /** @private */ private _visualState; /** @private */ private _isHovering; /** @private */ private _hoveringCounter; /** @private */ private _isPressed; /** @private */ private _hasHitElementListeners; /** @private */ private _isApplyingTint; /** @private */ private _isApplyingSprite; /** * @type {{startTime: number, from: Color, to: Color, lerpColor: Color}|null} * @private */ private _tweenInfo; /** @private */ private _defaultTint; /** @private */ private _defaultSpriteAsset; /** @private */ private _defaultSpriteFrame; /** * @type {Entity|null} * @private */ private _imageEntity; /** * @type {EventHandle|null} * @private */ private _evtElementAdd; /** * @type {EventHandle|null} * @private */ private _evtImageEntityElementAdd; /** * @type {EventHandle|null} * @private */ private _evtImageEntityElementRemove; /** * @type {EventHandle|null} * @private */ private _evtImageEntityElementColor; /** * @type {EventHandle|null} * @private */ private _evtImageEntityElementOpacity; /** * @type {EventHandle|null} * @private */ private _evtImageEntityElementSpriteAsset; /** * @type {EventHandle|null} * @private */ private _evtImageEntityElementSpriteFrame; /** * Sets the button's active state. If set to false, the button will be visible but will not * respond to hover or touch interactions. Defaults to true. * * @type {boolean} */ set active(arg: boolean); /** * Gets the button's active state. * * @type {boolean} */ get active(): boolean; /** * Sets the entity to be used as the button background. The entity must have an * {@link ElementComponent} configured as an image element. * * @type {Entity|string|null} */ set imageEntity(arg: Entity | null); /** * Gets the entity to be used as the button background. * * @type {Entity|null} */ get imageEntity(): Entity | null; /** * Sets the padding to be used in hit-test calculations. Can be used to expand the bounding box * so that the button is easier to tap. Defaults to `[0, 0, 0, 0]`. * * @type {Vec4} */ set hitPadding(arg: Vec4); /** * Gets the padding to be used in hit-test calculations. * * @type {Vec4} */ get hitPadding(): Vec4; /** * Sets the button transition mode. This controls how the button responds when the user hovers * over it/presses it. Can be: * * - {@link BUTTON_TRANSITION_MODE_TINT} * - {@link BUTTON_TRANSITION_MODE_SPRITE_CHANGE} * * Defaults to {@link BUTTON_TRANSITION_MODE_TINT}. * * @type {number} */ set transitionMode(arg: number); /** * Gets the button transition mode. * * @type {number} */ get transitionMode(): number; /** * Sets the tint color to be used on the button image when the user hovers over it. Defaults to * `[0.75, 0.75, 0.75]`. * * @type {Color} */ set hoverTint(arg: Color); /** * Gets the tint color to be used on the button image when the user hovers over it. * * @type {Color} */ get hoverTint(): Color; /** * Sets the tint color to be used on the button image when the user presses it. Defaults to * `[0.5, 0.5, 0.5]`. * * @type {Color} */ set pressedTint(arg: Color); /** * Gets the tint color to be used on the button image when the user presses it. * * @type {Color} */ get pressedTint(): Color; /** * Sets the tint color to be used on the button image when the button is not interactive. * Defaults to `[0.25, 0.25, 0.25]`. * * @type {Color} */ set inactiveTint(arg: Color); /** * Gets the tint color to be used on the button image when the button is not interactive. * * @type {Color} */ get inactiveTint(): Color; /** * Sets the duration to be used when fading between tints, in milliseconds. Defaults to 0. * * @type {number} */ set fadeDuration(arg: number); /** * Gets the duration to be used when fading between tints, in milliseconds. * * @type {number} */ get fadeDuration(): number; /** * Sets the sprite to be used as the button image when the user hovers over it. * * @type {Asset|null} */ set hoverSpriteAsset(arg: Asset | null); /** * Gets the sprite to be used as the button image when the user hovers over it. * * @type {Asset|null} */ get hoverSpriteAsset(): Asset | null; /** * Sets the frame to be used from the hover sprite. * * @type {number} */ set hoverSpriteFrame(arg: number); /** * Gets the frame to be used from the hover sprite. * * @type {number} */ get hoverSpriteFrame(): number; /** * Sets the sprite to be used as the button image when the user presses it. * * @type {Asset|null} */ set pressedSpriteAsset(arg: Asset | null); /** * Gets the sprite to be used as the button image when the user presses it. * * @type {Asset|null} */ get pressedSpriteAsset(): Asset | null; /** * Sets the frame to be used from the pressed sprite. * * @type {number} */ set pressedSpriteFrame(arg: number); /** * Gets the frame to be used from the pressed sprite. * * @type {number} */ get pressedSpriteFrame(): number; /** * Sets the sprite to be used as the button image when the button is not interactive. * * @type {Asset|null} */ set inactiveSpriteAsset(arg: Asset | null); /** * Gets the sprite to be used as the button image when the button is not interactive. * * @type {Asset|null} */ get inactiveSpriteAsset(): Asset | null; /** * Sets the frame to be used from the inactive sprite. * * @type {number} */ set inactiveSpriteFrame(arg: number); /** * Gets the frame to be used from the inactive sprite. * * @type {number} */ get inactiveSpriteFrame(): number; /** * Sets one of the state tint fields, mirroring the old schema-driven `type: 'rgba'` * conversion in ComponentSystem.convertValue: pass falsy values through untouched, clone a * Color input (so caller mutations do not leak into component state), and treat anything else * as indexable to support `[r, g, b, a]` arrays from JSON-loaded scenes. The visual state is * only reapplied when the tint actually changes in value, as reapplying cancels any in-flight * fade tween. * * @param {string} name - The name of the private tint field to set. * @param {Color|number[]|null} arg - The new tint value. * @private */ private _setTint; /** * Sets one of the state sprite asset/frame fields, reapplying the visual state on change. * * @param {string} name - The name of the private field to set. * @param {Asset|number|null} arg - The new value. * @private */ private _setTransitionValue; _imageEntitySubscribe(): void; _imageEntityUnsubscribe(): void; _imageEntityElementSubscribe(): void; _imageEntityElementUnsubscribe(): void; _onElementComponentRemove(): void; _onElementComponentAdd(): void; _onImageElementLose(): void; _onImageElementGain(): void; _toggleHitElementListeners(onOrOff: any): void; _storeDefaultVisualState(): void; _storeDefaultColor(color: any): void; _storeDefaultOpacity(opacity: any): void; _storeDefaultSpriteAsset(spriteAsset: any): void; _storeDefaultSpriteFrame(spriteFrame: any): void; _onSetColor(color: any): void; _onSetOpacity(opacity: any): void; _onSetSpriteAsset(spriteAsset: any): void; _onSetSpriteFrame(spriteFrame: any): void; _onMouseEnter(event: any): void; _onMouseLeave(event: any): void; _onMouseDown(event: any): void; _onMouseUp(event: any): void; _onTouchStart(event: any): void; _onTouchEnd(event: any): void; _onTouchLeave(event: any): void; _onTouchCancel(event: any): void; _onSelectStart(event: any): void; _onSelectEnd(event: any): void; _onSelectEnter(event: any): void; _onSelectLeave(event: any): void; _onClick(event: any): void; _fireIfActive(name: any, event: any): void; _updateVisualState(force: any): void; _forceReapplyVisualState(): void; _resetToDefaultVisualState(transitionMode: any): void; _determineVisualState(): string; _applySprite(spriteAsset: any, spriteFrame: any): void; _applyTint(tintColor: any): void; _applyTintImmediately(tintColor: any): void; _applyTintWithTween(tintColor: any): void; _updateTintTween(): void; _cancelTween(): void; onUpdate(): void; onBeforeRemove(): void; resolveDuplicatedEntityReferenceProperties(oldButton: any, duplicatedIdsMap: any): void; } /** * Options of the `button` component accepted by {@link ButtonComponentSystem} that differ from the * properties of {@link ButtonComponent}. Each replaces the same-named property of the options that * {@link Entity#addComponent} derives from the component class; see * {@link ComponentOptionsOverrides}. */ type ButtonComponentOptionsOverrides = { /** * - Same as {@link ButtonComponent#hitPadding}, also * accepting an `[x, y, z, w]` array. */ hitPadding?: Vec4 | number[]; }; /** * Manages the {@link ButtonComponent}s of an application. Reach it through `app.systems.button`; * components are created with {@link Entity#addComponent}, never by calling the system directly. * * @category User Interface */ declare class ButtonComponentSystem extends ComponentSystem { id: string; ComponentType: typeof ButtonComponent; initializeComponentData(component: any, data: any, properties: any): void; cloneComponent(entity: any, clone: any): Component; onUpdate(dt: any): void; onBeforeRemove(entity: any, component: any): void; } /** * The CollisionComponent enables an {@link Entity} to act as a collision volume. Use it on its own * to define a trigger volume. Or use it in conjunction with a {@link RigidBodyComponent} to make a * collision volume that can be simulated using the physics engine. * * When an entity is configured as a trigger volume, if an entity with a dynamic or kinematic body * enters or leaves that trigger volume, both entities will receive trigger events. * * You should never need to use the CollisionComponent constructor directly. To add a * CollisionComponent to an {@link Entity}, use {@link Entity#addComponent}: * * ```javascript * const entity = new Entity(); * entity.addComponent('collision'); // This defaults to 1x1x1 box-shaped trigger volume * ``` * * To create a 0.5 radius dynamic rigid body sphere: * * ```javascript * const entity = new Entity(); * entity.addComponent('collision', { * type: 'sphere' * }); * entity.addComponent('rigidbody', { * type: 'dynamic' * }); * ``` * * Once the CollisionComponent is added to the entity, you can access it via the * {@link Entity#collision} property: * * ```javascript * entity.collision.type = 'cylinder'; // Set the collision volume to a cylinder * * console.log(entity.collision.type); // Get the collision volume type and print it * ``` * * Relevant Engine API examples: * * - [Compound Collision](https://playcanvas.github.io/#/physics/compound-collision) * - [Falling Shapes](https://playcanvas.github.io/#/physics/falling-shapes) * - [Offset Collision](https://playcanvas.github.io/#/physics/offset-collision) * * @hideconstructor * @category Physics */ declare class CollisionComponent extends Component { /** * Fired when a contact occurs between two rigid bodies. The handler is passed a * {@link ContactResult} object which contains details of the contact between the two rigid * bodies. * * @event * @example * entity.collision.on('contact', (result) => { * console.log(`Contact between ${entity.name} and ${result.other.name}`); * }); */ static EVENT_CONTACT: string; /** * Fired when two rigid bodies start touching. The handler is passed the {@link ContactResult} * object which contains details of the contact between the two rigid bodies. * * @event * @example * entity.collision.on('collisionstart', (result) => { * console.log(`${entity.name} started touching ${result.other.name}`); * }); */ static EVENT_COLLISIONSTART: string; /** * Fired when two rigid bodies stop touching. The handler is passed an {@link Entity} that * represents the other rigid body involved in the collision. * * @event * @example * entity.collision.on('collisionend', (other) => { * console.log(`${entity.name} stopped touching ${other.name}`); * }); */ static EVENT_COLLISIONEND: string; /** * Fired when a rigid body enters a trigger volume. The handler is passed an {@link Entity} * representing the rigid body that entered this collision volume. * * @event * @example * entity.collision.on('triggerenter', (other) => { * console.log(`${other.name} entered trigger volume ${entity.name}`); * }); */ static EVENT_TRIGGERENTER: string; /** * Fired when a rigid body exits a trigger volume. The handler is passed an {@link Entity} * representing the rigid body that exited this collision volume. * * @event * @example * entity.collision.on('triggerleave', (other) => { * console.log(`${other.name} exited trigger volume ${entity.name}`); * }); */ static EVENT_TRIGGERLEAVE: string; /** * Create a new CollisionComponent. * * @param {CollisionComponentSystem} system - The ComponentSystem that created this Component. * @param {Entity} entity - The Entity that this Component is attached to. */ constructor(system: CollisionComponentSystem, entity: Entity); /** * @type {'box'|'capsule'|'compound'|'cone'|'cylinder'|'mesh'|'sphere'} * @private */ private _type; /** @private */ private _halfExtents; /** @private */ private _linearOffset; /** @private */ private _angularOffset; /** @private */ private _radius; /** @private */ private _axis; /** @private */ private _height; /** * @type {number|null} * @private */ private _asset; /** * @type {number|null} * @private */ private _renderAsset; /** @private */ private _convexHull; /** @private */ private _shape; /** * @type {Model|null} * @private */ private _model; /** @private */ private _render; /** @private */ private _checkVertexDuplicates; /** @private */ private _initialized; /** @private */ private _compoundParent; /** * For a compound child, the local transforms of the nodes between the entity and its * compound root as of the last write into the compound, and the pose that was written. The * per-step sync compares against these to skip a child whose relative pose cannot have * changed. Created when the child first joins a compound. * * @type {{ nodes: { node: GraphNode, position: Vec3, rotation: Quat, scale: Vec3 }[], position: Vec3, rotation: Quat }|null} * @private */ private _compoundSync; /** @private */ private _hasOffset; /** * The entity world scale a mesh shape was last built with - a change triggers a rebuild. * * @type {Vec3|null} * @private */ private _builtWorldScale; /** * The signs of the local scales of the entity and its ancestors when a mesh shape was last * built, one entry per node - see getScaleSigns in the collision system. * * @type {number[]|null} * @private */ private _builtScaleSigns; /** * Sets the type of the collision volume. Can be: * * - "box": A box-shaped collision volume. * - "capsule": A capsule-shaped collision volume. * - "compound": A compound shape. Any descendant entities with a collision component of type * box, capsule, cone, cylinder or sphere will be combined into a single, rigid shape. * - "cone": A cone-shaped collision volume. * - "cylinder": A cylinder-shaped collision volume. * - "mesh": A collision volume that uses a model asset as its shape. * - "sphere": A sphere-shaped collision volume. * * Primitive volumes are sized by their own properties ({@link CollisionComponent#halfExtents}, * {@link CollisionComponent#radius} and {@link CollisionComponent#height}) and ignore the * scale of the entity. Mesh volumes follow the world scale of the entity, including the scale * of its ancestors and any mirroring by negative scale factors, and are rebuilt at the start * of the next physics step when that scale changes. Triangle mesh volumes share one set of * collision triangle data per mesh, so rescaling them is cheap; a * {@link CollisionComponent#convexHull} is rebuilt from the mesh vertices at the new scale. * Sharing requires an Ammo.js build that exposes `btScaledBvhTriangleMeshShape`; with older * builds, triangle mesh colliders sharing a mesh use the scale of the first one built and * rescaling an entity at runtime does not affect its mesh collider. * * Defaults to "box". * * @type {'box'|'capsule'|'compound'|'cone'|'cylinder'|'mesh'|'sphere'} */ set type(arg: "box" | "capsule" | "compound" | "cone" | "cylinder" | "mesh" | "sphere"); /** * Gets the type of the collision volume. * * @type {'box'|'capsule'|'compound'|'cone'|'cylinder'|'mesh'|'sphere'} */ get type(): "box" | "capsule" | "compound" | "cone" | "cylinder" | "mesh" | "sphere"; /** * Sets the half-extents of the box-shaped collision volume in the x, y and z axes. Defaults to * `[0.5, 0.5, 0.5]`. * * @type {Vec3} */ set halfExtents(arg: Readonly); /** * Gets the half-extents of the box-shaped collision volume in the x, y and z axes. Use the * setter to update the collision shape. * * @type {Readonly} */ get halfExtents(): Readonly; /** * Sets the positional offset of the collision shape from the Entity position along the local * axes. Defaults to `[0, 0, 0]`. * * @type {Vec3} */ set linearOffset(arg: Readonly); /** * Gets the positional offset of the collision shape from the Entity position along the local * axes. Use the setter to update the collision shape. * * @type {Readonly} */ get linearOffset(): Readonly; /** * Sets the rotational offset of the collision shape from the Entity rotation in local space. * Defaults to identity. * * @type {Quat} */ set angularOffset(arg: Readonly); /** * Gets the rotational offset of the collision shape from the Entity rotation in local space. Use * the setter to update the collision shape. * * @type {Readonly} */ get angularOffset(): Readonly; /** * Sets the radius of the sphere, capsule, cylinder or cone-shaped collision volumes. * Defaults to 0.5. * * @type {number} */ set radius(arg: number); /** * Gets the radius of the sphere, capsule, cylinder or cone-shaped collision volumes. * * @type {number} */ get radius(): number; /** * Sets the local space axis with which the capsule, cylinder or cone-shaped collision volume's * length is aligned. 0 for X, 1 for Y and 2 for Z. Defaults to 1 (Y-axis). * * @type {number} */ set axis(arg: number); /** * Gets the local space axis with which the capsule, cylinder or cone-shaped collision volume's * length is aligned. * * @type {number} */ get axis(): number; /** * Sets the total height of the capsule, cylinder or cone-shaped collision volume from tip to * tip. Defaults to 2. * * @type {number} */ set height(arg: number); /** * Gets the total height of the capsule, cylinder or cone-shaped collision volume from tip to * tip. * * @type {number} */ get height(): number; /** * Sets the asset or asset id for the model of the mesh collision volume. Defaults to null. * The node hierarchy of the model is interpreted in the local space of the entity: the * transform of each node is applied to its mesh and the world scale of the entity multiplies * the result. * * @type {Asset|number|null} */ set asset(arg: Asset | number | null); /** * Gets the asset or asset id for the model of the mesh collision volume. * * @type {Asset|number|null} */ get asset(): Asset | number | null; /** * Sets the render asset or asset id of the mesh collision volume. Defaults to null. * If not set then the asset property will be checked instead. The meshes are used in the * local space of the entity, scaled by the world scale of the entity. * * @type {Asset|number|null} */ set renderAsset(arg: Asset | number | null); /** * Gets the render asset id of the mesh collision volume. * * @type {Asset|number|null} */ get renderAsset(): Asset | number | null; /** * Sets whether the collision mesh should be treated as a convex hull. When false, the mesh can * only be used with a static body. When true, the mesh can be used with a static, dynamic or * kinematic body. The hull is built from the mesh vertices at the world scale of the entity. * Only applies to meshes from {@link CollisionComponent#renderAsset} or * `render`. Defaults to `false`. * * @type {boolean} */ set convexHull(arg: boolean); /** * Gets whether the collision mesh should be treated as a convex hull. * * @type {boolean} */ get convexHull(): boolean; /** * @type {*} * @ignore */ set shape(arg: any); /** * The physics backend's collision shape - a btCollisionShape with the Ammo backend - or null * if it has not been created. An unsupported escape hatch for native functionality the * component does not expose: code that uses it only works with that physics backend. The * setter is kept for compatibility and does not rebuild the body. * * @type {*} * @ignore */ get shape(): any; /** * Sets the model that is added to the scene graph for the mesh collision volume. * * @type {Model | null} */ set model(arg: Model | null); /** * Gets the model that is added to the scene graph for the mesh collision volume. * * @type {Model | null} */ get model(): Model | null; /** * @type {*} * @ignore */ set render(arg: any); /** * The render resource whose meshes form the mesh collision volume. It is set when * {@link CollisionComponent#renderAsset} loads, and assigning a resource directly rebuilds * the shape from its meshes. Application code should use * {@link CollisionComponent#renderAsset} or {@link CollisionComponent#model} instead. * * @type {*} * @ignore */ get render(): any; /** * Sets whether checking for duplicate vertices should be enabled when creating collision meshes. * * @type {boolean} */ set checkVertexDuplicates(arg: boolean); /** * Gets whether checking for duplicate vertices should be enabled when creating collision meshes. * * @type {boolean} */ get checkVertexDuplicates(): boolean; /** @private */ private _updateHasOffset; /** * @param {Asset} asset - Asset that was removed. * @private */ private onAssetRemoved; /** * @param {Asset} asset - Asset that was removed. * @private */ private onRenderAssetRemoved; /** * @param {GraphNode} parent - The parent node. * @private */ private _onInsert; /** * Wires this component into the nearest compound ancestor, if there is one and the entity * is not a body of its own. Rebuilds the compound when it has no children yet, otherwise * rebuilds this shape so it joins at the current pose. * * @returns {boolean} True if the component joined a compound. * @private */ private _joinCompoundAncestor; /** * An {@link Entity#forEach} callback that syncs the compound child transform of each * descendant wired to this compound root. Invoked with `this` set to the compound root's * entity. * * @param {Entity} entity - The visited descendant entity. * @private */ private _updateEachDescendantTransform; /** * Applies the transform changes of this compound root's children to the compound shape. * Called by the rigid body system before each step for the roots of dynamic and kinematic * compounds. A child is written only when a local transform between it and the root has * changed since the last write, so a compound at rest or moving as a whole costs a walk of * its descendants and a few comparisons per child, nothing more. * * @private */ private _updateCompound; /** * Returns the world position for the collision shape, taking into account of any offsets. * * @returns {Vec3} The world position for the collision shape. */ getShapePosition(): Vec3; /** * Returns the world rotation for the collision shape, taking into account of any offsets. * * @returns {Quat} The world rotation for the collision. */ getShapeRotation(): Quat; onBeforeRemove(): void; } /** * Options of the `collision` component accepted by {@link CollisionComponentSystem} that differ * from the properties of {@link CollisionComponent}. Each replaces the same-named property of the * options that {@link Entity#addComponent} derives from the component class; see * {@link ComponentOptionsOverrides}. */ type CollisionComponentOptionsOverrides = { /** * - Same as {@link CollisionComponent#angularOffset}, * also accepting `[x, y, z]` Euler angles in degrees or an `[x, y, z, w]` quaternion array. */ angularOffset?: Quat | number[]; /** * - Same as {@link CollisionComponent#halfExtents}, also * accepting an `[x, y, z]` array. */ halfExtents?: Vec3 | number[]; /** * - Same as {@link CollisionComponent#linearOffset}, * also accepting an `[x, y, z]` array. */ linearOffset?: Vec3 | number[]; }; /** * Manages the {@link CollisionComponent}s of an application. Reach it through * `app.systems.collision`; components are created with {@link Entity#addComponent}, never by * calling the system directly. * * @category Physics */ declare class CollisionComponentSystem extends ComponentSystem { /** * The mesh components with a built shape, watched for changes to their entity world scale. * Maintained by createMeshShape and beforeRemove. * * @type {CollisionComponent[]} * @private */ private _meshComponents; id: string; ComponentType: typeof CollisionComponent; /** * The physics backend installed on the rigid body system, or null. * * @type {*} * @ignore */ get physicsWorld(): any; initializeComponentData(component: any, data: any): void; cloneComponent(entity: any, clone: any): Component; /** * Destroys the shape of a component that is being removed and discards the collisions * stored for its entity. * * @param {Entity} entity - The entity the component is being removed from. * @param {CollisionComponent} component - The component being removed. * @private */ private onBeforeRemove; /** * Takes the entity's rigid body out of the simulation and destroys its trigger. Runs once the * component has been removed, and when its shape is torn down to be rebuilt. * * @param {Entity} entity - The entity of the component. * @private */ private onRemove; /** * Writes a compound child's pose relative to its compound root into the compound shape, * adding the child when it is absent. Disabled children are skipped. Unless forced, the * write is also skipped when no local transform between the child and the root has changed * since the last write, which is decided from stored local vectors without any matrix math, * so the root moving as a whole costs nothing beyond the comparison. * * @param {Entity} entity - The compound child's entity. * @param {boolean} forceUpdate - Write regardless, for a child known to be absent from the * compound. * @returns {boolean} True if the compound shape was written. * @ignore */ updateCompoundChildTransform(entity: Entity, forceUpdate: boolean): boolean; /** * Returns true if a compound child is wired to a compound that is still one of its ancestors * and nothing between them has changed since its shape was last written, so the shape is * already where the hierarchy says it should be. * * @param {CollisionComponent} component - The compound child. * @returns {boolean} True if the child's shape is in place. * @ignore */ isCompoundChildInPlace(component: CollisionComponent): boolean; _removeCompoundChild(collision: any, shape: any): void; /** * Starts watching a mesh component's entity world scale (see _updateMeshScales). * * @param {CollisionComponent} component - The mesh collision component. * @private */ private _watchMeshScale; /** * Stops watching a component's entity world scale. * * @param {CollisionComponent} component - The collision component. * @private */ private _unwatchMeshScale; /** * Rebuilds the mesh shapes whose entity world scale no longer matches the scale they were * built with. Driven by the rigid body system at the start of each physics step, so like * the other entity to physics syncs it pauses with the simulation and the first step after * resuming catches up. * * @ignore */ _updateMeshScales(): void; changeType(component: any, previousType: any, newType: any): void; recreatePhysicalShapes(component: any): void; /** * Rebuilds a mesh component's shape from its current model or render sources, skipping any * asset loading. Used by the mesh source setters, which assign the resource directly. * * @param {CollisionComponent} component - The mesh collision component to rebuild. * @ignore */ doRecreatePhysicalShape(component: CollisionComponent): void; /** * An {@link Entity#forEach} callback that wires a descendant of a compound root to it and * rebuilds the descendant's shape. Invoked with `this` set to the compound root component. * * @param {Entity} entity - The visited descendant entity. * @private */ private _addEachDescendant; /** * Writes the transform of a node relative to one of its ancestors to the shared scratch * matrix: the signed world scale of the ancestor, followed by the local transforms of the * nodes below it down to the node itself. * * @param {GraphNode} node - The node. * @param {GraphNode} relative - The ancestor. * @private */ private _calculateNodeRelativeTransform; /** * Computes a node's pose (with any collision component offsets applied), optionally * relative to an ancestor node, ignoring scale. * * @param {GraphNode} node - The node to read. * @param {GraphNode|null} relative - The ancestor to compute the pose relative to, or null * for the world pose. * @param {Vec3} position - The vector to write the position to. * @param {Quat} rotation - The quaternion to write the rotation to. * @private */ private _getNodeTransform; } /** * The GSplatComponent enables an {@link Entity} to render 3D Gaussian Splats. Splats are always * loaded from {@link Asset}s rather than being created programmatically. The asset type is * `gsplat` which supports multiple file formats including `.ply`, `.sog`, `.meta.json` (SOG * format), and `.lod-meta.json` (streaming LOD format). * * You should never need to use the GSplatComponent constructor directly. To add a * GSplatComponent to an {@link Entity}, use {@link Entity#addComponent}: * * ```javascript * const entity = new Entity(); * entity.addComponent('gsplat', { * asset: asset * }); * ``` * * Once the GSplatComponent is added to the entity, you can access it via the {@link Entity#gsplat} * property: * * ```javascript * entity.gsplat.customAabb = new BoundingBox(new Vec3(), new Vec3(10, 10, 10)); * * console.log(entity.gsplat.customAabb); * ``` * * Relevant Engine API examples: * * - [Simple Splat Loading](https://playcanvas.github.io/#/gaussian-splatting/simple) * - [Billions of Splats](https://playcanvas.github.io/#/gaussian-splatting/billions) * - [Downtown Streaming](https://playcanvas.github.io/#/gaussian-splatting/downtown) * - [Global Sorting](https://playcanvas.github.io/#/gaussian-splatting/global-sorting) * - [LOD Instances](https://playcanvas.github.io/#/gaussian-splatting/lod-instances) * - [LOD Streaming](https://playcanvas.github.io/#/gaussian-splatting/lod-streaming) * - [LOD Streaming with Spherical Harmonics](https://playcanvas.github.io/#/gaussian-splatting/lod-streaming-sh) * - [Multi-Splat](https://playcanvas.github.io/#/gaussian-splatting/multi-splat) * - [Multi-View](https://playcanvas.github.io/#/gaussian-splatting/multi-view) * - [Picking](https://playcanvas.github.io/#/gaussian-splatting/picking) * - [Reveal Effect](https://playcanvas.github.io/#/gaussian-splatting/reveal) * - [Shader Effects](https://playcanvas.github.io/#/gaussian-splatting/shader-effects) * - [Spherical Harmonics](https://playcanvas.github.io/#/gaussian-splatting/spherical-harmonics) * * @hideconstructor * @category Graphics */ declare class GSplatComponent extends Component { /** * Create a new GSplatComponent. * * @param {GSplatComponentSystem} system - The ComponentSystem that created this Component. * @param {Entity} entity - The Entity that this Component is attached to. */ constructor(system: GSplatComponentSystem, entity: Entity); /** @private */ private _layers; /** * @type {GSplatInstance|null} * @private */ private _instance; /** * @type {GSplatPlacement|null} * @private */ private _placement; /** * Unique identifier for this component, used by the picking system. * * @type {number} * @private */ private _id; /** * @type {ShaderMaterial|null} * @private */ private _materialTmp; /** * Base distance for the first LOD transition. * * @private */ private _lodBaseDistance; /** * Geometric multiplier between successive LOD transition distances. * * @private */ private _lodMultiplier; /** * Minimum allowed LOD index (inclusive). * * @private */ private _lodRangeMin; /** * Maximum allowed LOD index (inclusive). * * @private */ private _lodRangeMax; /** * @type {BoundingBox|null} * @private */ private _customAabb; /** * @type {AssetReference} * @private */ private _assetReference; /** * Direct resource reference (for container splats). * * @type {GSplatResourceBase|null} * @private */ private _resource; /** * @type {EventHandle|null} * @private */ private _evtLayersChanged; /** * @type {EventHandle|null} * @private */ private _evtLayerAdded; /** * @type {EventHandle|null} * @private */ private _evtLayerRemoved; /** @private */ private _castShadows; /** * Whether to use the unified gsplat rendering. Defaults to true. * * @private */ private _unified; /** * Per-instance shader parameters. Stores objects with scopeId and data. * * @type {Map} * @private */ private _parameters; /** * Render mode for work buffer updates. * * @type {number} * @private */ private _workBufferUpdate; /** * Custom shader modify code for this component (object with code and pre-computed hash). * * @type {{ code: string, hash: number }|null} * @private */ private _workBufferModifier; /** * Sets a custom object space bounding box for visibility culling of the attached gsplat. * * @type {BoundingBox|null} */ set customAabb(value: BoundingBox | null); /** * Gets the custom object space bounding box for visibility culling of the attached gsplat. * Returns the custom AABB if set, otherwise falls back to the resource's AABB. * * @type {BoundingBox|null} */ get customAabb(): BoundingBox | null; /** * Sets a {@link GSplatInstance} on the component. If not set or loaded, it returns null. * * @type {GSplatInstance|null} * @ignore */ set instance(value: GSplatInstance | null); /** * Gets the {@link GSplatInstance} on the component. * * @type {GSplatInstance|null} * @ignore */ get instance(): GSplatInstance | null; set material(value: ShaderMaterial); get material(): ShaderMaterial; /** * Sets whether gsplat will cast shadows for lights that have shadow casting enabled. Defaults * to false. * * @type {boolean} */ set castShadows(value: boolean); /** * Gets whether gsplat will cast shadows for lights that have shadow casting enabled. * * @type {boolean} */ get castShadows(): boolean; /** * @type {number} * @deprecated Use {@link GSplatComponent#lodBaseDistance} and * {@link GSplatComponent#lodMultiplier} instead. * @ignore */ set lodFalloff(value: number); /** * @type {number} * @deprecated Use {@link GSplatComponent#lodBaseDistance} and * {@link GSplatComponent#lodMultiplier} instead. * @ignore */ get lodFalloff(): number; /** * Sets the base distance for the first LOD transition (LOD 0 to LOD 1). Objects closer than * this distance use the highest quality LOD. Each subsequent LOD level transitions at a * progressively larger distance, controlled by {@link GSplatComponent#lodMultiplier}. In world * units, and compensated for the camera's field of view. How these distances combine with the * scene's splat budget is set by {@link GSplatParams#splatBudgetMode}: in target mode they only * shape the falloff and how detail divides between splats, in limit mode they decide the * detail. Clamped to a minimum of 0.1. Defaults to 5. * * @type {number} */ set lodBaseDistance(value: number); /** * Gets the base distance for the first LOD transition. * * @type {number} */ get lodBaseDistance(): number; /** * Sets the multiplier between successive LOD distance thresholds. Each LOD level transitions * at this factor times the previous level's distance, creating a geometric progression. Higher * values keep finer detail further from the camera, at a higher memory cost; lower values * switch to coarser levels sooner. LOD distances are compensated for the camera's field of * view - a wider FOV makes objects appear smaller on screen, so LOD switches to coarser levels * sooner. Clamped to a minimum of 1.2. Defaults to 3. * * @type {number} */ set lodMultiplier(value: number); /** * Gets the geometric multiplier between successive LOD distance thresholds. * * @type {number} */ get lodMultiplier(): number; /** * Sets the minimum allowed LOD index (inclusive) for this splat. The optimal LOD selected by * distance is clamped so it never goes finer (lower index) than this value. The value is * further clamped to the asset's valid LOD range `[0, octree.lodLevels - 1]` at use. Setting a * higher minimum prevents downloading the highest quality (largest) LOD files. Defaults to 0. * * @type {number} */ set lodRangeMin(value: number); /** * Gets the minimum allowed LOD index. * * @type {number} */ get lodRangeMin(): number; /** * Sets the maximum allowed LOD index (inclusive) for this splat. The optimal LOD selected by * distance is clamped so it never goes coarser (higher index) than this value. The value is * clamped to the asset's valid LOD range `[0, octree.lodLevels - 1]` at use, so the default of * 99 effectively means "no cap". Defaults to 99. * * @type {number} */ set lodRangeMax(value: number); /** * Gets the maximum allowed LOD index. * * @type {number} */ get lodRangeMax(): number; /** * @type {number[]|null} * @deprecated Use {@link GSplatComponent#lodBaseDistance} and {@link GSplatComponent#lodMultiplier} instead. * @ignore */ set lodDistances(value: number[]); /** * @type {number[]} * @deprecated Use {@link GSplatComponent#lodBaseDistance} and {@link GSplatComponent#lodMultiplier} instead. * @ignore */ get lodDistances(): number[]; /** * @type {number} * @deprecated Use app.scene.gsplat.splatBudget instead for global budget control. * @ignore */ set splatBudget(value: number); /** * @type {number} * @deprecated Use app.scene.gsplat.splatBudget instead for global budget control. * @ignore */ get splatBudget(): number; /** * Sets whether to use the unified gsplat rendering. * * @type {boolean} * @deprecated Non-unified gsplat rendering is being removed; unified rendering will be the only supported mode. * @ignore */ set unified(value: boolean); /** * Gets whether to use the unified gsplat rendering. * * @type {boolean} * @deprecated Non-unified gsplat rendering is being removed; unified rendering will be the only supported mode. * @ignore */ get unified(): boolean; /** * Gets the unique identifier for this component. This ID is used by the picking system * and is also written to the work buffer when `app.scene.gsplat.enableIds` is enabled, making * it available to custom shaders for effects like highlighting or animation. * * @type {number} */ get id(): number; /** * Sets the work buffer update mode. * * Splat data is rendered to a work buffer only when needed (e.g., when transforms change). * Can be: * - {@link WORKBUFFER_UPDATE_AUTO}: Update only when needed (default). * - {@link WORKBUFFER_UPDATE_ONCE}: Force update this frame, then switch to AUTO. * - {@link WORKBUFFER_UPDATE_ALWAYS}: Update every frame. * * This is typically useful when using custom shader code via {@link setWorkBufferModifier} * that depends on external factors like time or animated uniforms. * * Note: {@link WORKBUFFER_UPDATE_ALWAYS} has a performance impact as it re-renders * all splat data to the work buffer every frame. Where possible, consider using shader * customization on the gsplat material (`app.scene.gsplat.material`) which is applied * during final rendering without re-rendering the work buffer. * * @type {number} */ set workBufferUpdate(value: number); /** * Gets the work buffer update mode. * * @type {number} */ get workBufferUpdate(): number; /** * Sets custom shader code for modifying splats when written to the work buffer. * * Must provide all three functions: * - `modifySplatCenter`: Modify the splat center position * - `modifySplatRotationScale`: Modify the splat rotation and scale * - `modifySplatColor`: Modify the splat color * * Calling this method automatically triggers a work buffer re-render. * * @param {{ glsl?: string, wgsl?: string }|null} value - The modifier code for GLSL and/or WGSL. * @example * entity.gsplat.setWorkBufferModifier({ * glsl: ` * void modifySplatCenter(inout vec3 center) {} * void modifySplatRotationScale(vec3 originalCenter, vec3 modifiedCenter, inout vec4 rotation, inout vec3 scale) {} * void modifySplatColor(vec3 center, inout vec4 color) { color.rgb *= vec3(1.0, 0.0, 0.0); } * `, * wgsl: ` * fn modifySplatCenter(center: ptr) {} * fn modifySplatRotationScale(originalCenter: vec3f, modifiedCenter: vec3f, rotation: ptr, scale: ptr) {} * fn modifySplatColor(center: vec3f, color: ptr) { (*color).r = 1.0; (*color).g = 0.0; (*color).b = 0.0; } * ` * }); */ setWorkBufferModifier(value: { glsl?: string; wgsl?: string; } | null): void; /** * Sets an array of layer IDs ({@link Layer#id}) to which this gsplat should belong. Don't * push, pop, splice or modify this array. If you want to change it, set a new one instead. * * @type {number[]} */ set layers(value: number[]); /** * Gets the array of layer IDs ({@link Layer#id}) to which this gsplat belongs. * * @type {number[]} */ get layers(): number[]; /** * Sets the gsplat asset for this gsplat component. Can also be an asset id. * * @type {Asset|number} */ set asset(value: Asset | number); /** * Gets the gsplat asset id for this gsplat component. * * @type {Asset|number} */ get asset(): Asset | number; /** * Sets a GSplat resource directly (for procedural/container splats). * When set, this takes precedence over the asset property. * * @type {GSplatResourceBase|null} */ set resource(value: GSplatResourceBase | null); /** * Gets the GSplat resource. Returns the directly set resource if available, * otherwise returns the resource from the assigned asset. * * @type {GSplatResourceBase|null} */ get resource(): GSplatResourceBase | null; /** @private */ private destroyInstance; /** @private */ private addToLayers; removeFromLayers(): void; /** @private */ private onRemoveChild; /** @private */ private onInsertChild; onBeforeRemove(): void; onLayersChanged(oldComp: any, newComp: any): void; onLayerAdded(layer: any): void; onLayerRemoved(layer: any): void; /** * Stop rendering this component without removing its mesh instance from the scene hierarchy. */ hide(): void; /** * Enable rendering of the component if hidden using {@link hide}. */ show(): void; /** * Sets a shader parameter for this gsplat instance. Parameters set here are applied * during rendering. * * @param {string} name - The name of the parameter (uniform name in shader). * @param {number|number[]|ArrayBufferView|Texture|StorageBuffer} data - The value for the parameter. */ setParameter(name: string, data: number | number[] | ArrayBufferView | Texture | StorageBuffer): void; /** * Gets a shader parameter value previously set with {@link setParameter}. * * @param {string} name - The name of the parameter. * @returns {number|number[]|ArrayBufferView|undefined} The parameter value, or undefined if not set. */ getParameter(name: string): number | number[] | ArrayBufferView | undefined; /** * Deletes a shader parameter previously set with {@link setParameter}. * * @param {string} name - The name of the parameter to delete. */ deleteParameter(name: string): void; /** * Gets an instance texture by name. Instance textures are per-component textures defined * in the resource's format with `storage: GSPLAT_STREAM_INSTANCE`. * * @param {string} name - The name of the texture. * @returns {Texture|null} The texture, or null if not found. * @example * // Add an instance stream to the resource format * resource.format.addExtraStreams([ * { name: 'instanceTint', format: PIXELFORMAT_RGBA8, storage: GSPLAT_STREAM_INSTANCE } * ]); * * // Get the instance texture and fill it with data * const texture = entity.gsplat.getInstanceTexture('instanceTint'); * if (texture) { * const data = texture.lock(); * // Fill texture data... * texture.unlock(); * } */ getInstanceTexture(name: string): Texture | null; _onGSplatAssetAdded(): void; _onGSplatAssetLoad(): void; _onGSplatAssetUnload(): void; _onGSplatAssetRemove(): void; } /** * Options of the `gsplat` component accepted by {@link GSplatComponentSystem} that differ from the * properties of {@link GSplatComponent}. Each replaces the same-named property of the options that * {@link Entity#addComponent} derives from the component class; see * {@link ComponentOptionsOverrides}. */ type GSplatComponentOptionsOverrides = { /** * - Center `[x, y, z]` of a custom bounding box; with * `aabbHalfExtents`, sets {@link GSplatComponent#customAabb}. */ aabbCenter?: number[]; /** * - Half-extents `[x, y, z]` of a custom bounding box; with * `aabbCenter`, sets {@link GSplatComponent#customAabb}. */ aabbHalfExtents?: number[]; }; /** * Manages the {@link GSplatComponent}s of an application. Reach it through `app.systems.gsplat`; * components are created with {@link Entity#addComponent}, never by calling the system directly. * * @category Graphics */ declare class GSplatComponentSystem extends ComponentSystem { /** * Fired when a GSplat material is created for a camera and layer combination. Materials are * created during the first frame update when the GSplat is rendered. The handler is passed * the {@link ShaderMaterial}, the {@link CameraComponent}, and the {@link Layer}. * * This event is useful for setting up custom material chunks and parameters before the * first render. * * @event * @example * app.systems.gsplat.on('material:created', (material, camera, layer) => { * console.log(`Material created for camera ${camera.entity.name} on layer ${layer.name}`); * // Set custom material parameters before first render * material.setParameter('myParam', value); * }); */ static EVENT_MATERIALCREATED: string; /** * Fired every frame for each camera and layer combination rendering GSplats. * The handler is passed the {@link CameraComponent}, the {@link Layer}, a boolean indicating * if the current frame has up-to-date sorting, and a number indicating how many resources are * loading. * * The `ready` parameter indicates whether the current frame reflects all recent changes (camera * movement, splat transforms, lod updates, etc.) with the latest sorting applied. The `loadingCount` * parameter reports the total number of octree LOD resources currently loading or queued to load. * * This event is useful for video capture or other workflows that need to wait for frames * to be fully ready. Only capture frames and move camera to next position when both * `ready === true` and `loadingCount === 0`. Note that `loadingCount` can be used as a boolean * in conditionals (0 is falsy, non-zero is truthy) for backward compatibility. * * @event * @example * // Wait for frame to be ready before capturing * app.systems.gsplat.on('frame:ready', (camera, layer, ready, loadingCount) => { * if (ready && !loadingCount) { * console.log(`Frame ready to capture for camera ${camera.entity.name}`); * // Capture frame here * } * }); * @example * // Track loading progress (0..1) * let maxLoadingCount = 0; * app.systems.gsplat.on('frame:ready', (camera, layer, ready, loadingCount) => { * maxLoadingCount = Math.max(maxLoadingCount, loadingCount); * const progress = maxLoadingCount > 0 ? (maxLoadingCount - loadingCount) / maxLoadingCount : 1; * console.log(`Loading progress: ${(progress * 100).toFixed(1)}%`); * }); */ static EVENT_FRAMEREADY: string; /** * Fired once per frame, after the component/script updates and before rendering, when GSplat * streaming has produced new data that a render would show (newly streamed octree LOD) or a CPU * sort result is ready to be applied. This drives on-demand rendering for apps that run with * {@link AppBase#autoRender} set to false: a typical handler sets {@link AppBase#renderNextFrame} * so the new data is shown. * * Streaming (LOD evaluation, file loading) runs every frame regardless of `autoRender`, so the * scene keeps loading in the background; this event tells you when it's worth rendering. * * Note: this event covers streaming changes only. Changes you make yourself — moving the camera, * modifying the scene, or adding, removing, or changing properties of gsplat components — should * trigger a render yourself. * * @event * @example * app.autoRender = false; * app.systems.gsplat.on('frame:request', () => { * app.renderNextFrame = true; * }); */ static EVENT_FRAMEREQUEST: string; /** * Container handler this system registered its glTF extension with. * * @type {ResourceHandler|null} * @private */ private _containerHandler; id: string; ComponentType: typeof GSplatComponent; onFrameRender(): void; initializeComponentData(component: any, _data: any, properties: any): void; cloneComponent(entity: any, clone: any): Component; onBeforeRemove(entity: any, component: any): void; /** * Gets the GSplat material for the given camera and layer. * * Returns null if the material hasn't been created yet. Materials are created during the first * frame update when the GSplat is rendered. To be notified immediately when materials are * created, listen to the 'material:created' event on GSplatComponentSystem: * * @param {Camera} camera - The camera instance. * @param {Layer} layer - The layer instance. * @returns {ShaderMaterial|null} The material, or null if not created yet. * @example * app.systems.gsplat.on('material:created', (material, camera, layer) => { * // Material is now available * material.setParameter('myParam', value); * }); */ getMaterial(camera: Camera, layer: Layer): ShaderMaterial | null; getGSplatMaterial(camera: any, layer: any): ShaderMaterial; } /** * The LayoutGroupComponent enables an {@link Entity} to position and scale its child * {@link ElementComponent}s according to configurable layout rules. It supports horizontal and * vertical orientations and a variety of alignment, spacing, wrapping and sizing options. * * You should never need to use the LayoutGroupComponent constructor directly. To add a * LayoutGroupComponent to an {@link Entity}, use {@link Entity#addComponent}: * * ```javascript * const entity = new Entity(); * entity.addComponent('element', { * type: ELEMENTTYPE_GROUP * }); * entity.addComponent('layoutgroup', { * orientation: ORIENTATION_HORIZONTAL, * spacing: new Vec2(10, 0) * }); * ``` * * Once the LayoutGroupComponent is added to the entity, you can access it via the * {@link Entity#layoutgroup} property: * * ```javascript * entity.layoutgroup.spacing = new Vec2(20, 0); // Increase spacing between children * * console.log(entity.layoutgroup.spacing); // Get the spacing and print it * ``` * * Relevant Engine API examples: * * - [Layout Group](https://playcanvas.github.io/#/user-interface/layout-group) * * @hideconstructor * @category User Interface */ declare class LayoutGroupComponent extends Component { /** * Create a new LayoutGroupComponent instance. * * @param {LayoutGroupComponentSystem} system - The ComponentSystem that created this Component. * @param {Entity} entity - The Entity that this Component is attached to. */ constructor(system: LayoutGroupComponentSystem, entity: Entity); /** @private */ private _orientation; /** @private */ private _reverseX; /** @private */ private _reverseY; /** @private */ private _alignment; /** @private */ private _padding; /** @private */ private _spacing; /** @private */ private _widthFitting; /** @private */ private _heightFitting; /** @private */ private _wrap; /** @private */ private _layoutCalculator; /** * Sets whether the layout should run horizontally or vertically. Can be: * * - {@link ORIENTATION_HORIZONTAL} * - {@link ORIENTATION_VERTICAL} * * Defaults to {@link ORIENTATION_HORIZONTAL}. * * @type {number} */ set orientation(value: number); /** * Gets whether the layout should run horizontally or vertically. * * @type {number} */ get orientation(): number; /** * Sets whether to reverse the order of children along the x axis. Defaults to false. * * @type {boolean} */ set reverseX(value: boolean); /** * Gets whether to reverse the order of children along the x axis. * * @type {boolean} */ get reverseX(): boolean; /** * Sets whether to reverse the order of children along the y axis. Defaults to true. * * @type {boolean} */ set reverseY(value: boolean); /** * Gets whether to reverse the order of children along the y axis. * * @type {boolean} */ get reverseY(): boolean; /** * Sets the horizontal and vertical alignment of child elements. Values range from 0 to 1 where * `[0, 0]` is the bottom left and `[1, 1]` is the top right. Defaults to `[0, 1]`. * * @type {Vec2} */ set alignment(value: Vec2); /** * Gets the horizontal and vertical alignment of child elements. * * @type {Vec2} */ get alignment(): Vec2; /** * Sets the padding to be applied inside the container before positioning any children. * Specified as left, bottom, right and top values. Defaults to `[0, 0, 0, 0]` (no padding). * * @type {Vec4} */ set padding(value: Vec4); /** * Gets the padding to be applied inside the container before positioning any children. * * @type {Vec4} */ get padding(): Vec4; /** * Sets the spacing to be applied between each child element. Defaults to `[0, 0]` (no spacing). * * @type {Vec2} */ set spacing(value: Vec2); /** * Gets the spacing to be applied between each child element. * * @type {Vec2} */ get spacing(): Vec2; /** * Sets the width fitting mode to be applied when positioning and scaling child elements. Can be: * * - {@link FITTING_NONE}: Child elements will be rendered at their natural size. * - {@link FITTING_STRETCH}: When the natural size of all child elements does not fill the width * of the container, children will be stretched to fit. The rules for how each child will be * stretched are outlined below: * 1. Sum the {@link LayoutChildComponent#fitWidthProportion} values of each child and normalize * so that all values sum to 1. * 2. Apply the natural width of each child. * 3. If there is space remaining in the container, distribute it to each child based on the * normalized {@link LayoutChildComponent#fitWidthProportion} values, but do not exceed the * {@link LayoutChildComponent#maxWidth} of each child. * - {@link FITTING_SHRINK}: When the natural size of all child elements overflows the width of the * container, children will be shrunk to fit. The rules for how each child will be stretched are * outlined below: * 1. Sum the {@link LayoutChildComponent#fitWidthProportion} values of each child and normalize * so that all values sum to 1. * 2. Apply the natural width of each child. * 3. If the new total width of all children exceeds the available space of the container, reduce * each child's width proportionally based on the normalized {@link * LayoutChildComponent#fitWidthProportion} values, but do not exceed the {@link * LayoutChildComponent#minWidth} of each child. * - {@link FITTING_BOTH}: Applies both STRETCH and SHRINK logic as necessary. * * Defaults to {@link FITTING_NONE}. * * @type {number} */ set widthFitting(value: number); /** * Gets the width fitting mode to be applied when positioning and scaling child elements. * * @type {number} */ get widthFitting(): number; /** * Sets the height fitting mode to be applied when positioning and scaling child elements. * Identical to {@link widthFitting} but for the Y axis. Defaults to {@link FITTING_NONE}. * * @type {number} */ set heightFitting(value: number); /** * Gets the height fitting mode to be applied when positioning and scaling child elements. * * @type {number} */ get heightFitting(): number; /** * Sets whether or not to wrap children onto a new row/column when the size of the container is * exceeded. Defaults to false, which means that children will be rendered in a single row * (horizontal orientation) or column (vertical orientation). * * @type {boolean} */ set wrap(value: boolean); /** * Gets whether or not to wrap children onto a new row/column when the size of the container is * exceeded. * * @type {boolean} */ get wrap(): boolean; _isSelfOrChild(entity: any): boolean; _listenForReflowEvents(target: any, onOff: any, component?: any): void; _onElementOrLayoutComponentAdd(entity: any, component: any): void; _onElementOrLayoutComponentRemove(entity: any, component: any): void; _onChildInsert(child: any): void; _onChildRemove(child: any): void; _scheduleReflow(): void; reflow(): void; _isPerformingReflow: boolean; onBeforeRemove(): void; } /** * Options of the `layoutgroup` component accepted by {@link LayoutGroupComponentSystem} that differ * from the properties of {@link LayoutGroupComponent}. Each replaces the same-named property of the * options that {@link Entity#addComponent} derives from the component class; see * {@link ComponentOptionsOverrides}. */ type LayoutGroupComponentOptionsOverrides = { /** * - Same as {@link LayoutGroupComponent#alignment}, also * accepting an `[x, y]` array. */ alignment?: Vec2 | number[]; /** * - Same as {@link LayoutGroupComponent#padding}, also * accepting an `[x, y, z, w]` array. */ padding?: Vec4 | number[]; /** * - Same as {@link LayoutGroupComponent#spacing}, also * accepting an `[x, y]` array. */ spacing?: Vec2 | number[]; }; /** * Manages the {@link LayoutGroupComponent}s of an application. Reach it through * `app.systems.layoutgroup`; components are created with {@link Entity#addComponent}, never by * calling the system directly. * * @category User Interface */ declare class LayoutGroupComponentSystem extends ComponentSystem { id: string; ComponentType: typeof LayoutGroupComponent; _reflowQueue: any[]; initializeComponentData(component: any, data: any, properties: any): void; cloneComponent(entity: any, clone: any): Component; scheduleReflow(component: any): void; _onPostUpdate(): void; _processReflowQueue(): void; onBeforeRemove(entity: any, component: any): void; } /** * @import { BoundingBox } from '../../../core/shape/bounding-box.js' * @import { Entity } from '../../entity.js' * @import { EventHandle } from '../../../core/event-handle.js' * @import { LayerComposition } from '../../../scene/composition/layer-composition.js' * @import { Layer } from '../../../scene/layer.js' * @import { Material } from '../../../scene/materials/material.js' * @import { ModelComponentSystem } from './system.js' */ /** * The ModelComponent enables an {@link Entity} to render 3D models. The {@link type} property can * be set to one of several predefined shapes (such as `box`, `sphere`, `cone` and so on). * Alternatively, the component can be configured to manage an arbitrary {@link Model}. This can * either be created programmatically or loaded from an {@link Asset}. * * The {@link Model} managed by this component is positioned, rotated, and scaled in world space by * the world transformation matrix of the owner {@link Entity}. This world matrix is derived by * combining the entity's local transformation (position, rotation, and scale) with the world * transformation matrix of its parent entity in the scene hierarchy. * * You should never need to use the ModelComponent constructor directly. To add a ModelComponent * to an Entity, use {@link Entity#addComponent}: * * ```javascript * const entity = new Entity(); * entity.addComponent('model', { * type: 'box' * }); * ``` * * Once the ModelComponent is added to the entity, you can access it via the {@link Entity#model} * property: * * ```javascript * entity.model.type = 'capsule'; // Set the model component's type * * console.log(entity.model.type); // Get the model component's type and print it * ``` * * @hideconstructor * @category Graphics */ declare class ModelComponent extends Component { /** * Create a new ModelComponent instance. * * @param {ModelComponentSystem} system - The ComponentSystem that created this Component. * @param {Entity} entity - The Entity that this Component is attached to. */ constructor(system: ModelComponentSystem, entity: Entity); /** * @type {'asset'|'box'|'capsule'|'cone'|'cylinder'|'plane'|'sphere'|'torus'} * @private */ private _type; /** * @type {Asset|number|null} * @private */ private _asset; /** * @type {Model|null} * @private */ private _model; /** * @type {Object} * @private */ private _mapping; /** @private */ private _castShadows; /** @private */ private _receiveShadows; /** * @type {Asset|number|null} * @private */ private _materialAsset; /** * @type {Material} * @private */ private _material; /** @private */ private _castShadowsLightmap; /** @private */ private _lightmapped; /** @private */ private _lightmapSizeMultiplier; /** * Mark meshes as non-movable (optimization). */ isStatic: boolean; /** * @type {number[]} * @private */ private _layers; /** @private */ private _batchGroupId; /** * @type {BoundingBox|null} * @private */ private _customAabb; _area: any; _materialEvents: any; /** @private */ private _clonedModel; /** * @type {EventHandle|null} * @private */ private _evtLayersChanged; /** * @type {EventHandle|null} * @private */ private _evtLayerAdded; /** * @type {EventHandle|null} * @private */ private _evtLayerRemoved; /** * Sets the array of mesh instances contained in the component's model. * * @type {MeshInstance[]|null} */ set meshInstances(value: ReadonlyArray | null); /** * Gets the array of mesh instances contained in the component's model. Use the setter to * replace the array; do not mutate the returned array. * * @type {ReadonlyArray|null} */ get meshInstances(): ReadonlyArray | null; /** * Sets the custom object space bounding box that is used for visibility culling of attached * mesh instances. This is an optimization, allowing an oversized bounding box to be specified * for skinned characters in order to avoid per frame bounding box computations based on bone * positions. * * @type {BoundingBox|null} */ set customAabb(value: BoundingBox | null); /** * Gets the custom object space bounding box that is used for visibility culling of attached * mesh instances. * * @type {BoundingBox|null} */ get customAabb(): BoundingBox | null; /** * Sets the type of the component, determining the source of the geometry to be rendered. * The geometry, whether it's a primitive shape or originates from an asset, is rendered * using the owning entity's final world transform. This world transform is calculated by * concatenating (multiplying) the local transforms (position, rotation, scale) of the * entity and all its ancestors in the scene hierarchy. This process positions, orientates, * and scales the geometry in world space. * * Can be one of the following values: * * - **"asset"**: Renders geometry defined in an {@link Asset} of type `model`. This asset, * assigned to the {@link asset} property, contains a {@link Model}. Alternatively, * {@link model} can be set programmatically. * - **"box"**: A unit cube (sides of length 1) centered at the local space origin. * - **"capsule"**: A shape composed of a cylinder and two hemispherical caps that is aligned * with the local Y-axis. It is centered at the local space origin and has an unscaled height * of 2 and a radius of 0.5. * - **"cone"**: A cone aligned with the local Y-axis. It is centered at the local space * origin, with its base in the local XZ plane at Y = -0.5 and its tip at Y = +0.5. It has * an unscaled height of 1 and a base radius of 0.5. * - **"cylinder"**: A cylinder aligned with the local Y-axis. It is centered at the local * space origin with an unscaled height of 1 and a radius of 0.5. * - **"plane"**: A flat plane in the local XZ plane at Y = 0 (normal along +Y). It is * centered at the local space origin with unscaled dimensions of 1x1 units along local X and * Z axes. * - **"sphere"**: A sphere with a radius of 0.5. It is centered at the local space origin and * has poles at Y = -0.5 and Y = +0.5. * - **"torus"**: A doughnut shape lying in the local XZ plane at Y = 0. It is centered at * the local space origin with a tube radius of 0.2 and a ring radius of 0.3. * * @type {'asset'|'box'|'capsule'|'cone'|'cylinder'|'plane'|'sphere'|'torus'} */ set type(value: "asset" | "box" | "capsule" | "cone" | "cylinder" | "plane" | "sphere" | "torus"); /** * Gets the type of the component. * * @type {'asset'|'box'|'capsule'|'cone'|'cylinder'|'plane'|'sphere'|'torus'} */ get type(): "asset" | "box" | "capsule" | "cone" | "cylinder" | "plane" | "sphere" | "torus"; /** * Sets the model owned by this component. * * @type {Model|null} */ set model(value: Model | null); /** * Gets the model owned by this component. In this case a model is not set or loaded, this will * return null. * * @type {Model|null} */ get model(): Model | null; /** * Sets the model asset (or asset id) for the component. This only applies to model components * with type 'asset'. * * @type {Asset|number|null} */ set asset(value: Asset | number | null); /** * Gets the model asset id for the component. * * @type {Asset|number|null} */ get asset(): Asset | number | null; /** * Sets whether the component is affected by the runtime lightmapper. If true, the meshes will * be lightmapped after using lightmapper.bake(). * * @type {boolean} */ set lightmapped(value: boolean); /** * Gets whether the component is affected by the runtime lightmapper. * * @type {boolean} */ get lightmapped(): boolean; /** * Sets the dictionary that holds material overrides for each mesh instance. Only applies to * model components of type 'asset'. The mapping contains pairs of mesh instance index to * material asset id. * * @type {Object} */ set mapping(value: Readonly>); /** * Gets the dictionary that holds material overrides for each mesh instance. * * @type {Readonly>} */ get mapping(): Readonly>; /** * Sets whether attached meshes will cast shadows for lights that have shadow casting enabled. * * @type {boolean} */ set castShadows(value: boolean); /** * Gets whether attached meshes will cast shadows for lights that have shadow casting enabled. * * @type {boolean} */ get castShadows(): boolean; /** * Sets whether shadows will be cast on attached meshes. * * @type {boolean} */ set receiveShadows(value: boolean); /** * Gets whether shadows will be cast on attached meshes. * * @type {boolean} */ get receiveShadows(): boolean; /** * Sets whether meshes instances will cast shadows when rendering lightmaps. * * @type {boolean} */ set castShadowsLightmap(value: boolean); /** * Gets whether meshes instances will cast shadows when rendering lightmaps. * * @type {boolean} */ get castShadowsLightmap(): boolean; /** * Sets the lightmap resolution multiplier. * * @type {number} */ set lightmapSizeMultiplier(value: number); /** * Gets the lightmap resolution multiplier. * * @type {number} */ get lightmapSizeMultiplier(): number; /** * Sets the array of layer IDs ({@link Layer#id}) to which the mesh instances belong. Don't * push, pop, splice or modify this array. If you want to change it, set a new one instead. * * @type {number[]} */ set layers(value: ReadonlyArray); /** * Gets the array of layer IDs ({@link Layer#id}) to which the mesh instances belong. * * @type {ReadonlyArray} */ get layers(): ReadonlyArray; /** * Sets the batch group for the mesh instances in this component (see {@link BatchGroup}). * Default is -1 (no group). * * @type {number} */ set batchGroupId(value: number); /** * Gets the batch group for the mesh instances in this component (see {@link BatchGroup}). * * @type {number} */ get batchGroupId(): number; /** * Sets the material {@link Asset} that will be used to render the component. The material is * ignored for renders of type 'asset'. * * @type {Asset|number|null} */ set materialAsset(value: Asset | number | null); /** * Gets the material {@link Asset} that will be used to render the component. * * @type {Asset|number|null} */ get materialAsset(): Asset | number | null; /** * Sets the {@link Material} that will be used to render the model. The material is ignored for * renders of type 'asset'. * * @type {Material} */ set material(value: Material); /** * Gets the {@link Material} that will be used to render the model. * * @type {Material} */ get material(): Material; addModelToLayers(): void; removeModelFromLayers(): void; onRemoveChild(): void; onInsertChild(): void; onBeforeRemove(): void; /** * @param {LayerComposition} oldComp - The old layer composition. * @param {LayerComposition} newComp - The new layer composition. * @private */ private onLayersChanged; /** * @param {Layer} layer - The layer that was added. * @private */ private onLayerAdded; /** * @param {Layer} layer - The layer that was removed. * @private */ private onLayerRemoved; /** * @param {number} index - The index of the mesh instance. * @param {string} event - The event name. * @param {number} id - The asset id. * @param {*} handler - The handler function to be bound to the specified event. * @private */ private _setMaterialEvent; /** @private */ private _unsetMaterialEvents; /** * @param {string} idOrPath - The asset id or path. * @returns {Asset|null} The asset. * @private */ private _getAssetByIdOrPath; /** * @param {string} path - The path of the model asset. * @returns {string|null} The model asset URL or null if the asset is not in the registry. * @private */ private _getMaterialAssetUrl; /** * @param {Asset} materialAsset -The material asset to load. * @param {MeshInstance} meshInstance - The mesh instance to assign the material to. * @param {number} index - The index of the mesh instance. * @private */ private _loadAndSetMeshInstanceMaterial; /** * Stop rendering model without removing it from the scene hierarchy. This method sets the * {@link MeshInstance#visible} property of every MeshInstance in the model to false Note, this * does not remove the model or mesh instances from the scene hierarchy or draw call list. So * the model component still incurs some CPU overhead. * * @example * this.timer = 0; * this.visible = true; * // ... * // blink model every 0.1 seconds * this.timer += dt; * if (this.timer > 0.1) { * if (!this.visible) { * this.entity.model.show(); * this.visible = true; * } else { * this.entity.model.hide(); * this.visible = false; * } * this.timer = 0; * } */ hide(): void; /** * Enable rendering of the model if hidden using {@link hide}. This method sets all the * {@link MeshInstance#visible} property on all mesh instances to true. */ show(): void; /** * @param {Asset} asset - The material asset to bind events to. * @private */ private _bindMaterialAsset; /** * @param {Asset} asset - The material asset to unbind events from. * @private */ private _unbindMaterialAsset; /** * @param {Asset} asset - The material asset on which an asset add event has been fired. * @private */ private _onMaterialAssetAdd; /** * @param {Asset} asset - The material asset on which an asset load event has been fired. * @private */ private _onMaterialAssetLoad; /** * @param {Asset} asset - The material asset on which an asset unload event has been fired. * @private */ private _onMaterialAssetUnload; /** * @param {Asset} asset - The material asset on which an asset remove event has been fired. * @private */ private _onMaterialAssetRemove; /** * @param {Asset} asset - The material asset on which an asset change event has been fired. * @private */ private _onMaterialAssetChange; /** * @param {Asset} asset - The model asset to bind events to. * @private */ private _bindModelAsset; /** * @param {Asset} asset - The model asset to unbind events from. * @private */ private _unbindModelAsset; /** * @param {Asset} asset - The model asset on which an asset add event has been fired. * @private */ private _onModelAssetAdded; /** * @param {Asset} asset - The model asset on which an asset load event has been fired. * @private */ private _onModelAssetLoad; /** * @param {Asset} asset - The model asset on which an asset unload event has been fired. * @private */ private _onModelAssetUnload; /** * @param {Asset} asset - The model asset on which an asset change event has been fired. * @param {string} attr - The attribute that was changed. * @param {*} _new - The new value of the attribute. * @param {*} _old - The old value of the attribute. * @private */ private _onModelAssetChange; /** * @param {Asset} asset - The model asset on which an asset remove event has been fired. * @private */ private _onModelAssetRemove; /** * @param {Material} material - The material to be set. * @private */ private _setMaterial; /** * Sets the visibility of the model. * * @param {boolean} visible - True to enable the model. * @ignore * @deprecated Use {@link ModelComponent#enabled} instead. */ setVisible(visible: boolean): void; } /** * Options of the `model` component accepted by {@link ModelComponentSystem} that differ from the * properties of {@link ModelComponent}. Each replaces the same-named property of the options that * {@link Entity#addComponent} derives from the component class; see * {@link ComponentOptionsOverrides}. */ type ModelComponentOptionsOverrides = { /** * - Center `[x, y, z]` of a custom bounding box; with * `aabbHalfExtents`, sets {@link ModelComponent#customAabb}. */ aabbCenter?: number[]; /** * - Half-extents `[x, y, z]` of a custom bounding box; with * `aabbCenter`, sets {@link ModelComponent#customAabb}. */ aabbHalfExtents?: number[]; /** * - Same as {@link ModelComponent#batchGroupId}. `null` * selects no batch group. */ batchGroupId?: number | null; }; /** * Allows an Entity to render a model or a primitive shape like a box, capsule, sphere, cylinder, * cone etc. * * @category Graphics */ declare class ModelComponentSystem extends ComponentSystem { id: string; ComponentType: typeof ModelComponent; defaultMaterial: StandardMaterial; initializeComponentData(component: any, _data: any): void; cloneComponent(entity: any, clone: any): Component; onBeforeRemove(entity: any, component: any): void; } /** * A curve is a collection of keys (time/value pairs). The shape of the curve is defined by its type * that specifies an interpolation scheme for the keys. * * Keys are kept sorted by time. Supply them to the constructor as a flat `[time, value, ...]` array * or insert them one at a time with {@link add}, then evaluate the curve at any time with * {@link value}. The {@link type} selects how values between keys are computed: * {@link CURVE_LINEAR}, {@link CURVE_SMOOTHSTEP}, {@link CURVE_SPLINE} or {@link CURVE_STEP}. * Curves drive values that change over time or over a normalized range, such as particle size over * a particle's lifetime. * * @example * // Ease a value in over one second and read it back a quarter of the way through * const curve = new Curve([0, 0, 1, 1]); * curve.type = CURVE_SMOOTHSTEP; * const v = curve.value(0.25); * @category Math */ declare class Curve { /** * Creates a new Curve instance. * * @param {number[]} [data] - An array of keys (pairs of numbers with the time first and value * second). * @example * const curve = new Curve([ * 0, 0, // At 0 time, value of 0 * 0.33, 2, // At 0.33 time, value of 2 * 0.66, 2.6, // At 0.66 time, value of 2.6 * 1, 3 // At 1 time, value of 3 * ]); */ constructor(data?: number[]); /** * The keys that define the curve. Each key is an array of two numbers with the time first and * the value second. * * @type {number[][]} */ keys: number[][]; /** * The curve interpolation scheme. Can be: * * - {@link CURVE_LINEAR} * - {@link CURVE_SMOOTHSTEP} * - {@link CURVE_SPLINE} * - {@link CURVE_STEP} * * Defaults to {@link CURVE_SMOOTHSTEP}. * * @type {number} */ type: number; /** * Controls how {@link CURVE_SPLINE} tangents are calculated. Valid range is between 0 and 1 * where 0 results in a non-smooth curve (equivalent to linear interpolation) and 1 results in * a very smooth curve. Use 0.5 for a Catmull-Rom spline. */ tension: number; /** * @type {CurveEvaluator} * @private */ private _eval; /** * Gets the number of keys in the curve. * * @type {number} */ get length(): number; /** * Adds a new key to the curve. * * @param {number} time - Time to add new key. * @param {number} value - Value of new key. * @returns {number[]} The newly created `[time, value]` pair. * @example * const curve = new Curve(); * curve.add(0, 1); // add key at time 0 with value 1 * curve.add(1, 2); // add key at time 1 with value 2 */ add(time: number, value: number): number[]; /** * Removes the key at the specified index. * * @param {number} index - The index of the key to remove. * @returns {number[]|null} The removed `[time, value]` pair, or null if the index is out of * range. * @example * const curve = new Curve([0, 1, 1, 2]); * curve.remove(0); // removes the key at time 0 */ remove(index: number): number[] | null; /** * Removes all keys from the curve. * * @returns {this} The curve instance. * @example * const curve = new Curve([0, 1, 1, 2]); * curve.clear(); // curve now has no keys */ clear(): this; /** * Gets the `[time, value]` pair at the specified index. * * @param {number} index - The index of key to return. * @returns {number[]} The `[time, value]` pair at the specified index. * @example * const curve = new Curve([0, 1, 1, 2]); * const key = curve.get(0); // returns [0, 1] */ get(index: number): number[]; /** * Sorts keys by time. */ sort(): void; /** * Returns the interpolated value of the curve at specified time. * * @param {number} time - The time at which to calculate the value. * @returns {number} The interpolated value. * @example * const curve = new Curve([0, 0, 1, 10]); * const value = curve.value(0.5); // returns interpolated value at time 0.5 */ value(time: number): number; /** * Returns the key closest to the specified time. When two keys are equally close, the later * one is returned. * * @param {number} time - The time to find the closest key to. * @returns {number[]|null} The `[time, value]` pair closest to the specified time, or null if * no keys exist. * @example * const curve = new Curve([0, 1, 0.5, 2, 1, 3]); * const key = curve.closest(0.6); // returns [0.5, 2] */ closest(time: number): number[] | null; /** * Returns a clone of the specified curve object. * * @returns {this} A clone of the specified curve. * @example * const curve = new Curve([0, 0, 1, 10]); * const clonedCurve = curve.clone(); */ clone(): this; /** * Sample the curve at regular intervals over the range [0..1]. * * @param {number} precision - The number of samples to return. * @returns {Float32Array} The set of quantized values. * @ignore */ quantize(precision: number): Float32Array; /** * Sample the curve at regular intervals over the range [0..1] and clamp the resulting samples * to [min..max]. * * @param {number} precision - The number of samples to return. * @param {number} min - The minimum output value. * @param {number} max - The maximum output value. * @returns {Float32Array} The set of quantized values. * @ignore */ quantizeClamped(precision: number, min: number, max: number): Float32Array; } /** * A curve set is a collection of curves that share a time axis and are evaluated together, such as * the three channels of a color or the components of a vector changing over time. * * Build one from an array of `[time, value, ...]` key arrays, one per curve, or from a number of * empty curves. Setting {@link type} applies that interpolation to every curve in the set, and * {@link value} returns the value of each curve at a time as one array. Reach an individual * {@link Curve} with {@link get}. * * @example * // Animate an RGB color over time and sample it at the midpoint * const colorOverTime = new CurveSet([ * [0, 1, 1, 0], // red: 1 at t = 0, 0 at t = 1 * [0, 0, 1, 1], // green: 0 at t = 0, 1 at t = 1 * [0, 0, 1, 0] // blue: 0 throughout * ]); * const [r, g, b] = colorOverTime.value(0.5); * @category Math */ declare class CurveSet { /** * Creates a new CurveSet instance. * * @param {...*} args - Variable arguments with several possible formats: * - No arguments: Creates a CurveSet with a single default curve. * - Single number argument: Creates a CurveSet with the specified number of default curves. * - Single array argument: An array of arrays, where each sub-array contains keys (pairs of * numbers with the time first and value second). * - Multiple arguments: Each argument becomes a separate curve. * @example * // Create from an array of arrays of keys * const curveSet = new CurveSet([ * [ * 0, 0, // At 0 time, value of 0 * 0.33, 2, // At 0.33 time, value of 2 * 0.66, 2.6, // At 0.66 time, value of 2.6 * 1, 3 // At 1 time, value of 3 * ], * [ * 0, 34, * 0.33, 35, * 0.66, 36, * 1, 37 * ] * ]); */ constructor(...args: any[]); /** * The array of curves in the set. * * @type {Curve[]} */ curves: Curve[]; /** * @type {number} * @private */ private _type; /** * Gets the number of curves in the curve set. * * @type {number} */ get length(): number; /** * Sets the interpolation scheme applied to all curves in the curve set. Can be: * * - {@link CURVE_LINEAR} * - {@link CURVE_SMOOTHSTEP} * - {@link CURVE_SPLINE} * - {@link CURVE_STEP} * * Defaults to {@link CURVE_SMOOTHSTEP}. * * @type {number} */ set type(value: number); /** * Gets the interpolation scheme applied to all curves in the curve set. * * @type {number} */ get type(): number; /** * Return a specific curve in the curve set. * * @param {number} index - The index of the curve to return. * @returns {Curve} The curve at the specified index. * @example * const curveSet = new CurveSet([[0, 0, 1, 1], [0, 0, 1, 0.5]]); * const curve = curveSet.get(0); // returns the first curve */ get(index: number): Curve; /** * Appends a new curve to the curve set. The new curve adopts the curve set's current * {@link CurveSet#type} interpolation scheme, so that all curves in the set continue to share * the same type. * * @param {number[]} [data] - An array of keys (pairs of numbers with the time first and value * second) for the new curve. * @returns {Curve} The newly created curve. * @example * const curveSet = new CurveSet([[0, 0, 1, 1]]); * const curve = curveSet.add([0, 0, 1, 0.5]); // append a second curve */ add(data?: number[]): Curve; /** * Removes a curve from the curve set. * * @param {number|Curve} indexOrCurve - The index of the curve to remove, or the curve instance * itself. * @returns {Curve|null} The removed curve, or null if it was not found. * @example * const curveSet = new CurveSet([[0, 0, 1, 1], [0, 0, 1, 0.5]]); * curveSet.remove(0); // remove by index * curveSet.remove(curveSet.get(0)); // or remove by reference */ remove(indexOrCurve: number | Curve): Curve | null; /** * Removes all keys from every curve in the set, while keeping the curves themselves. The number * of curves is unchanged, so {@link CurveSet#value} still returns an array of the same length. * * @returns {this} The curve set instance. * @example * const curveSet = new CurveSet([[0, 0, 1, 1], [0, 0, 1, 0.5]]); * curveSet.clearKeys(); // both curves are now empty, but the set still has 2 curves */ clearKeys(): this; /** * Removes all curves from the curve set, leaving it empty. * * @returns {this} The curve set instance. * @example * const curveSet = new CurveSet([[0, 0, 1, 1], [0, 0, 1, 0.5]]); * curveSet.clear(); // the set now has no curves */ clear(): this; /** * Returns the interpolated value of all curves in the curve set at the specified time. * * @param {number} time - The time at which to calculate the value. * @param {number[]} [result] - The interpolated curve values at the specified time. If this * parameter is not supplied, the function allocates a new array internally to return the * result. * @returns {number[]} The interpolated curve values at the specified time. * @example * const curveSet = new CurveSet([[0, 0, 1, 1], [0, 0, 1, 0.5]]); * const values = curveSet.value(0.5); // returns interpolated values for all curves at time 0.5 */ value(time: number, result?: number[]): number[]; /** * Returns a clone of the specified curve set object. * * @returns {this} A clone of the specified curve set. * @example * const curveSet = new CurveSet([[0, 0, 1, 1]]); * const clonedCurveSet = curveSet.clone(); */ clone(): this; /** * Sample the curveset at regular intervals over the range [0..1]. * * @param {number} precision - The number of samples to return. * @returns {Float32Array} The set of quantized values. * @ignore */ quantize(precision: number): Float32Array; /** * Sample the curveset at regular intervals over the range [0..1] and clamp the result to min * and max. * * @param {number} precision - The number of samples to return. * @param {number} min - The minimum output value. * @param {number} max - The maximum output value. * @returns {Float32Array} The set of quantized values. * @ignore */ quantizeClamped(precision: number, min: number, max: number): Float32Array; } /** * @import { ParticleEmitter } from './particle-emitter.js' */ /** * A material for rendering particle geometry by the particle emitter. * * @category Graphics * @ignore */ declare class ParticleMaterial extends Material { constructor(emitter: any); /** * The color of the particles. * * @type {ParticleEmitter} */ emitter: ParticleEmitter; /** @ignore */ getShaderVariant(params: any): Shader; } declare class ParticleGPUUpdater { constructor(emitter: any, gd: any); _emitter: any; frameRandomUniform: Float32Array; emitterPosUniform: Float32Array; emitterScaleUniform: Float32Array; constantParticleTexIN: any; constantParticleTexOUT: any; constantEmitterPos: any; constantEmitterScale: any; constantSpawnBounds: any; constantSpawnPosInnerRatio: any; constantSpawnBoundsSphere: any; constantSpawnBoundsSphereInnerRatio: any; constantInitialVelocity: any; constantFrameRandom: any; constantDelta: any; constantRate: any; constantRateDiv: any; constantLifetime: any; constantGraphSampleSize: any; constantGraphNumSamples: any; constantInternalTex0: any; constantInternalTex1: any; constantInternalTex2: any; constantInternalTex3: any; constantEmitterMatrix: any; constantEmitterMatrixInv: any; constantNumParticles: any; constantNumParticlesPot: any; constantLocalVelocityDivMult: any; constantVelocityDivMult: any; constantRotSpeedDivMult: any; constantSeed: any; constantStartAngle: any; constantStartAngle2: any; constantFaceTangent: any; constantFaceBinorm: any; constantRadialSpeedDivMult: any; randomize(): void; update(device: any, spawnMatrix: any, extentsInnerRatioUniform: any, delta: any, isOnStop: any): void; } declare class ParticleCPUUpdater { constructor(emitter: any); _emitter: any; calcSpawnPosition(particleTex: any, spawnMatrix: any, extentsInnerRatioUniform: any, emitterPos: any, i: any): void; update(data: any, vbToSort: any, particleTex: any, spawnMatrix: any, extentsInnerRatioUniform: any, emitterPos: any, delta: any, isOnStop: any): void; } declare class ParticleEmitter { constructor(graphicsDevice: any, options: any); /** @type {ParticleMaterial|null} */ material: ParticleMaterial | null; /** @type {Texture|null} */ internalTex0: Texture | null; /** @type {Texture|null} */ internalTex1: Texture | null; /** @type {Texture|null} */ internalTex2: Texture | null; /** @type {Texture|null} */ colorParam: Texture | null; graphicsDevice: any; precision: number; _addTimeTime: number; numParticles: any; useFog: boolean; _gpuUpdater: ParticleGPUUpdater; _cpuUpdater: ParticleCPUUpdater; emitterPosUniform: Float32Array; wrapBoundsUniform: Float32Array; emitterScaleUniform: Float32Array; animTilesParams: Float32Array; animParams: Float32Array; animIndexParams: Float32Array; vbToSort: any[]; vbOld: Float32Array; particleDistance: Float32Array; camera: any; swapTex: boolean; useMesh: boolean; useCpu: boolean; localBounds: BoundingBox; worldBoundsNoTrail: BoundingBox; worldBoundsTrail: BoundingBox[]; worldBounds: BoundingBox; prevEmitterExtents: Vec3; prevEmitterRadius: number; timeToSwitchBounds: number; shaderParticleUpdateRespawn: Shader; shaderParticleUpdateNoRespawn: Shader; shaderParticleUpdateOnStop: Shader; numParticleVerts: number; numParticleIndices: number; meshInstance: MeshInstance; drawOrder: number; seed: number; fixedTimeStep: number; maxSubSteps: number; simTime: number; simTimeTotal: number; beenReset: boolean; _layer: any; get defaultParamTexture(): any; calculateWorldBounds(): void; resetWorldBounds(): void; calculateLocalBounds(): void; rebuild(): void; colorMap: any; spawnBounds: any; numParticlesPot: number; particleTex: Float32Array; particleTexStart: any; particleTexIN: Texture; particleTexOUT: Texture; rtParticleTexIN: RenderTarget; rtParticleTexOUT: RenderTarget; _isAnimated(): any; rebuildGraphs(): void; qLocalVelocity: any; qVelocity: any; qColor: any; qRotSpeed: any; qScale: any; qAlpha: any; qRadialSpeed: any; qLocalVelocity2: any; qVelocity2: any; qColor2: any; qRotSpeed2: any; qScale2: any; qAlpha2: any; qRadialSpeed2: any; localVelocityUMax: Float32Array; velocityUMax: Float32Array; colorUMax: Float32Array; rotSpeedUMax: number[]; scaleUMax: number[]; alphaUMax: number[]; radialSpeedUMax: number[]; qLocalVelocityDiv: Float32Array; qVelocityDiv: Float32Array; qColorDiv: Float32Array; qRotSpeedDiv: Float32Array; qScaleDiv: Float32Array; qAlphaDiv: Float32Array; qRadialSpeedDiv: Float32Array; internalTex3: Texture; _setMaterialTextures(): void; _createMaterial(): ParticleMaterial; resetMaterial(): void; _compParticleFaceParams(): void; getVertexInfo(): { semantic: string; components: number; type: number; }[]; _allocate(numParticles: any): void; vertexBuffer: VertexBuffer; indexBuffer: IndexBuffer; vbCPU: Float32Array; reset(): void; loop: any; prewarm(time: any): void; resetTime(duration?: any): void; endTime: any; finishFrame(): void; addTime(delta: any, isOnStop: any): void; _destroyResources(): boolean; destroy(): void; } /** * The ParticleSystemComponent enables an {@link Entity} to simulate particles and produce a * renderable particle mesh on either CPU or GPU. GPU simulation is generally much faster than * its CPU counterpart, because it avoids slow CPU-GPU synchronization and takes advantage of * many GPU cores. However, it requires client support for reasonable uniform counts, reading * from multiple textures in a vertex shader and the OES_texture_float extension, including * rendering into float textures. Most mobile devices fail to satisfy these requirements, so it's * not recommended to simulate thousands of particles on them. The GPU version also can't sort * particles, so enabling sorting forces CPU mode too. * * Particle rotation is specified by a single angle parameter: default billboard particles rotate * around the camera-facing axis, while mesh particles rotate around two different view-independent * axes. Most of the simulation parameters are specified with {@link Curve} or {@link CurveSet}. * Curves are interpolated based on each particle's lifetime, therefore parameters are able to * change over time. Most curve parameters can also be specified by 2 minimum/maximum curves, so * that each particle picks a random value in-between. * * You should never need to use the ParticleSystemComponent constructor directly. To add a * ParticleSystemComponent to an {@link Entity}, use {@link Entity#addComponent}: * * ```javascript * const entity = new Entity(); * entity.addComponent('particlesystem', { * numParticles: 100, * lifetime: 2, * rate: 0.1 * }); * ``` * * Once the ParticleSystemComponent is added to the entity, you can access it via the * {@link Entity#particlesystem} property: * * ```javascript * entity.particlesystem.loop = false; // Play the system once then stop * * console.log(entity.particlesystem.loop); // Get the loop flag and print it * ``` * * Relevant Engine API examples: * * - [Particle Animated Index](https://playcanvas.github.io/#/graphics/particles-anim-index) * - [Particle Mesh](https://playcanvas.github.io/#/graphics/particles-mesh) * - [Particle Random Sprites](https://playcanvas.github.io/#/graphics/particles-random-sprites) * - [Particle Snow](https://playcanvas.github.io/#/graphics/particles-snow) * - [Particle Spark](https://playcanvas.github.io/#/graphics/particles-spark) * - [Particles in a user interface](https://playcanvas.github.io/#/user-interface/particle-system) * * @hideconstructor * @category Graphics */ declare class ParticleSystemComponent extends Component { /** * The particle emitter that performs the simulation. Only set while the component is or has * been enabled and the platform supports particle systems. * * @type {ParticleEmitter|null} * @ignore */ emitter: ParticleEmitter | null; /** @private */ private _requestedDepth; /** @private */ private _drawOrder; /** @private */ private _paused; /** * @type {EventHandle|null} * @private */ private _evtLayersChanged; /** * @type {EventHandle|null} * @private */ private _evtLayerAdded; /** * @type {EventHandle|null} * @private */ private _evtLayerRemoved; /** * @type {EventHandle|null} * @private */ private _evtSetMeshes; /** @private */ private _autoPlay; /** @private */ private _numParticles; /** @private */ private _lifetime; /** @private */ private _rate; /** * @type {number|null} * @private */ private _rate2; /** @private */ private _startAngle; /** * @type {number|null} * @private */ private _startAngle2; /** @private */ private _loop; /** @private */ private _preWarm; /** @private */ private _lighting; /** @private */ private _halfLambert; /** @private */ private _intensity; /** @private */ private _depthWrite; /** @private */ private _useFog; /** @private */ private _useTonemap; /** @private */ private _depthSoftening; /** @private */ private _sort; /** @private */ private _blendType; /** @private */ private _stretch; /** @private */ private _alignToMotion; /** @private */ private _emitterShape; /** @private */ private _emitterExtents; /** @private */ private _emitterExtentsInner; /** @private */ private _emitterRadius; /** @private */ private _emitterRadiusInner; /** @private */ private _initialVelocity; /** @private */ private _wrap; /** @private */ private _wrapBounds; /** @private */ private _localSpace; /** @private */ private _screenSpace; /** * @type {number|null} * @private */ private _colorMapAsset; /** * @type {number|null} * @private */ private _normalMapAsset; /** * @type {Mesh|null} * @private */ private _mesh; /** * @type {number|null} * @private */ private _meshAsset; /** * @type {number|null} * @private */ private _renderAsset; /** @private */ private _orientation; /** @private */ private _particleNormal; /** * @type {CurveSet|null} * @private */ private _localVelocityGraph; /** * @type {CurveSet|null} * @private */ private _localVelocityGraph2; /** * @type {CurveSet|null} * @private */ private _velocityGraph; /** * @type {CurveSet|null} * @private */ private _velocityGraph2; /** * @type {Curve|null} * @private */ private _rotationSpeedGraph; /** * @type {Curve|null} * @private */ private _rotationSpeedGraph2; /** * @type {Curve|null} * @private */ private _radialSpeedGraph; /** * @type {Curve|null} * @private */ private _radialSpeedGraph2; /** * @type {Curve|null} * @private */ private _scaleGraph; /** * @type {Curve|null} * @private */ private _scaleGraph2; /** * @type {CurveSet|null} * @private */ private _colorGraph; /** * @type {CurveSet|null} * @private */ private _colorGraph2; /** * @type {Curve|null} * @private */ private _alphaGraph; /** * @type {Curve|null} * @private */ private _alphaGraph2; /** * @type {Texture|null} * @private */ private _colorMap; /** * @type {Texture|null} * @private */ private _normalMap; /** @private */ private _animTilesX; /** @private */ private _animTilesY; /** @private */ private _animStartFrame; /** @private */ private _animNumFrames; /** @private */ private _animNumAnimations; /** @private */ private _animIndex; /** @private */ private _randomizeAnimIndex; /** @private */ private _animSpeed; /** @private */ private _animLoop; /** * @type {number[]} * @private */ private _layers; /** * Sets whether the particle system plays automatically on creation. If set to false, it is * necessary to call {@link play} for the particle system to play. Defaults to true. * * @type {boolean} */ set autoPlay(arg: boolean); /** * Gets whether the particle system plays automatically on creation. * * @type {boolean} */ get autoPlay(): boolean; /** * Sets the maximum number of simulated particles. * * @type {number} */ set numParticles(arg: number); /** * Gets the maximum number of simulated particles. * * @type {number} */ get numParticles(): number; /** * Sets the length of time in seconds between a particle's birth and its death. * * @type {number} */ set lifetime(arg: number); /** * Gets the length of time in seconds between a particle's birth and its death. * * @type {number} */ get lifetime(): number; /** * Sets the minimal interval in seconds between particle births. * * @type {number} */ set rate(arg: number); /** * Gets the minimal interval in seconds between particle births. * * @type {number} */ get rate(): number; /** * Sets the maximal interval in seconds between particle births. * * @type {number} */ set rate2(arg: number); /** * Gets the maximal interval in seconds between particle births. * * @type {number} */ get rate2(): number; /** * Sets the minimal initial Euler angle of a particle. * * @type {number} */ set startAngle(arg: number); /** * Gets the minimal initial Euler angle of a particle. * * @type {number} */ get startAngle(): number; /** * Sets the maximal initial Euler angle of a particle. * * @type {number} */ set startAngle2(arg: number); /** * Gets the maximal initial Euler angle of a particle. * * @type {number} */ get startAngle2(): number; /** * Sets whether the particle system loops. * * @type {boolean} */ set loop(arg: boolean); /** * Gets whether the particle system loops. * * @type {boolean} */ get loop(): boolean; /** * Sets whether the particle system will be initialized as though it has already completed a * full cycle. This only works with looping particle systems. * * @type {boolean} */ set preWarm(arg: boolean); /** * Gets whether the particle system will be initialized as though it has already completed a * full cycle. * * @type {boolean} */ get preWarm(): boolean; /** * Sets whether particles will be lit by ambient and directional lights. * * @type {boolean} */ set lighting(arg: boolean); /** * Gets whether particles will be lit by ambient and directional lights. * * @type {boolean} */ get lighting(): boolean; /** * Sets whether Half Lambert lighting is enabled. Enabling Half Lambert lighting avoids * particles looking too flat in shadowed areas. It is a completely non-physical lighting model * but can give more pleasing visual results. * * @type {boolean} */ set halfLambert(arg: boolean); /** * Gets whether Half Lambert lighting is enabled. * * @type {boolean} */ get halfLambert(): boolean; /** * Sets the color multiplier. * * @type {number} */ set intensity(arg: number); /** * Gets the color multiplier. * * @type {number} */ get intensity(): number; /** * Sets whether depth writes is enabled. If enabled, the particles will write to the depth * buffer. If disabled, the depth buffer is left unchanged and particles will be guaranteed to * overwrite one another in the order in which they are rendered. * * @type {boolean} */ set depthWrite(arg: boolean); /** * Gets whether depth writes is enabled. * * @type {boolean} */ get depthWrite(): boolean; /** * Sets whether the camera's fog is applied to the particles. When false, the particles ignore * fog even if the rendering camera has it enabled. Defaults to true. * * @type {boolean} */ set useFog(arg: boolean); /** * Gets whether the camera's fog is applied to the particles. * * @type {boolean} */ get useFog(): boolean; /** * Sets whether the camera's tonemapping and the scene exposure are applied to the particles. * When false, the particles keep their authored colors, unaffected by {@link Scene#exposure} * and {@link CameraComponent#toneMapping}. Fog, when enabled, still applies. Defaults to true. * * @type {boolean} */ set useTonemap(arg: boolean); /** * Gets whether the camera's tonemapping and the scene exposure are applied to the particles. * * @type {boolean} */ get useTonemap(): boolean; /** * Sets whether fogging is ignored. * * @type {boolean} * @deprecated Use {@link ParticleSystemComponent#useFog} instead. * @ignore */ set noFog(arg: boolean); /** * Gets whether fogging is ignored. * * @type {boolean} * @deprecated Use {@link ParticleSystemComponent#useFog} instead. * @ignore */ get noFog(): boolean; /** * Sets whether depth softening is enabled. Controls fading of particles near their * intersections with scene geometry. This effect, when it's non-zero, requires scene depth map * to be rendered. Multiple depth-dependent effects can share the same map, but if you only use * it for particles, bear in mind that it can double engine draw calls. * * @type {number} */ set depthSoftening(arg: number); /** * Gets whether depth softening is enabled. * * @type {number} */ get depthSoftening(): number; /** * Sets the particle sorting mode. Forces CPU simulation, so be careful. * * - {@link PARTICLESORT_NONE}: No sorting, particles are drawn in arbitrary order. Can be * simulated on GPU. * - {@link PARTICLESORT_DISTANCE}: Sorting based on distance to the camera. CPU only. * - {@link PARTICLESORT_NEWER_FIRST}: Newer particles are drawn first. CPU only. * - {@link PARTICLESORT_OLDER_FIRST}: Older particles are drawn first. CPU only. * * @type {number} */ set sort(arg: number); /** * Gets the particle sorting mode. * * @type {number} */ get sort(): number; /** * Sets how particles are blended when being written to the currently active render target. * Can be: * * - {@link BLEND_SUBTRACTIVE}: Subtract the color of the source fragment from the destination * fragment and write the result to the frame buffer. * - {@link BLEND_ADDITIVE}: Add the color of the source fragment to the destination fragment and * write the result to the frame buffer. * - {@link BLEND_NORMAL}: Enable simple translucency for materials such as glass. This is * equivalent to enabling a source blend mode of {@link BLENDMODE_SRC_ALPHA} and * a destination * blend mode of {@link BLENDMODE_ONE_MINUS_SRC_ALPHA}. * - {@link BLEND_NONE}: Disable blending. * - {@link BLEND_PREMULTIPLIED}: Similar to {@link BLEND_NORMAL} expect * the source fragment is * assumed to have already been multiplied by the source alpha value. * - {@link BLEND_MULTIPLICATIVE}: Multiply the color of the source fragment by the color of the * destination fragment and write the result to the frame buffer. * - {@link BLEND_ADDITIVEALPHA}: Same as {@link BLEND_ADDITIVE} except * the source RGB is * multiplied by the source alpha. * * @type {number} */ set blendType(arg: number); /** * Gets how particles are blended when being written to the currently active render target. * * @type {number} */ get blendType(): number; /** * Sets how much particles are stretched in their direction of motion. This is a value in world * units that controls the amount by which particles are stretched based on their velocity. * Particles are stretched from their center towards their previous position. * * @type {number} */ set stretch(arg: number); /** * Gets how much particles are stretched in their direction of motion. * * @type {number} */ get stretch(): number; /** * Sets whether particles are oriented in their direction of motion or not. * * @type {boolean} */ set alignToMotion(arg: boolean); /** * Gets whether particles are oriented in their direction of motion or not. * * @type {boolean} */ get alignToMotion(): boolean; /** * Sets the shape of the emitter. Defines the bounds inside which particles are spawned. Also * affects the direction of initial velocity. * * - {@link EMITTERSHAPE_BOX}: Box shape parameterized by emitterExtents. Initial velocity is * directed towards local Z axis. * - {@link EMITTERSHAPE_SPHERE}: Sphere shape parameterized by emitterRadius. Initial velocity is * directed outwards from the center. * * @type {number} */ set emitterShape(arg: number); /** * Gets the shape of the emitter. * * @type {number} */ get emitterShape(): number; /** * Sets the extents of a local space bounding box within which particles are spawned at random * positions. This only applies to particle system with the shape `EMITTERSHAPE_BOX`. * * @type {Vec3} */ set emitterExtents(arg: Vec3); /** * Gets the extents of a local space bounding box within which particles are spawned at random * positions. * * @type {Vec3} */ get emitterExtents(): Vec3; /** * Sets the exception of extents of a local space bounding box within which particles are not * spawned. It is aligned to the center of emitterExtents. This only applies to particle system * with the shape `EMITTERSHAPE_BOX`. * * @type {Vec3} */ set emitterExtentsInner(arg: Vec3); /** * Gets the exception of extents of a local space bounding box within which particles are not * spawned. * * @type {Vec3} */ get emitterExtentsInner(): Vec3; /** * Sets the radius within which particles are spawned at random positions. This only applies to * particle system with the shape `EMITTERSHAPE_SPHERE`. * * @type {number} */ set emitterRadius(arg: number); /** * Gets the radius within which particles are spawned at random positions. * * @type {number} */ get emitterRadius(): number; /** * Sets the inner radius within which particles are not spawned. This only applies to particle * system with the shape `EMITTERSHAPE_SPHERE`. * * @type {number} */ set emitterRadiusInner(arg: number); /** * Gets the inner radius within which particles are not spawned. * * @type {number} */ get emitterRadiusInner(): number; /** * Sets the magnitude of the initial emitter velocity. Direction is given by emitter shape. * * @type {number} */ set initialVelocity(arg: number); /** * Gets the magnitude of the initial emitter velocity. * * @type {number} */ get initialVelocity(): number; /** * Sets whether particles wrap based on the set wrap bounds. * * @type {boolean} */ set wrap(arg: boolean); /** * Gets whether particles wrap based on the set wrap bounds. * * @type {boolean} */ get wrap(): boolean; /** * Sets the wrap bounds of the particle system. This is half extents of a world space box * volume centered on the owner entity's position. If a particle crosses the boundary of one * side of the volume, it teleports to the opposite side. * * @type {Vec3} */ set wrapBounds(arg: Vec3); /** * Gets the wrap bounds of the particle system. * * @type {Vec3} */ get wrapBounds(): Vec3; /** * Sets whether particles move with respect to the emitter's transform rather then world space. * * @type {boolean} */ set localSpace(arg: boolean); /** * Gets whether particles move with respect to the emitter's transform rather then world space. * * @type {boolean} */ get localSpace(): boolean; /** * Sets whether particles are rendered in 2D screen space. This needs to be set when particle * system is part of hierarchy with {@link ScreenComponent} as its ancestor, and allows * particle system to integrate with the rendering of {@link ElementComponent}s. Note that an * entity with ParticleSystem component cannot be parented directly to {@link ScreenComponent}, * but has to be a child of a {@link ElementComponent}, for example {@link LayoutGroupComponent}. * In screen space, particle sizes are measured in viewport heights on both axes, so a size of 1 * in {@link scaleGraph} makes a particle as tall as the viewport and just as wide. * * @type {boolean} */ set screenSpace(arg: boolean); /** * Gets whether particles are rendered in 2D screen space. * * @type {boolean} */ get screenSpace(): boolean; /** * Sets the {@link Asset} used to set the colorMap. * * @type {Asset|null} */ set colorMapAsset(arg: Asset | null); /** * Gets the {@link Asset} used to set the colorMap. * * @type {Asset|null} */ get colorMapAsset(): Asset | null; /** * Sets the color map texture to apply to all particles in the system. If no texture is * assigned, a default spot texture is used. * * @type {Texture} */ set colorMap(arg: Texture); /** * Gets the color map texture to apply to all particles in the system. * * @type {Texture} */ get colorMap(): Texture; /** * Sets the {@link Asset} used to set the normalMap. * * @type {Asset|null} */ set normalMapAsset(arg: Asset | null); /** * Gets the {@link Asset} used to set the normalMap. * * @type {Asset|null} */ get normalMapAsset(): Asset | null; /** * Sets the normal map texture to apply to all particles in the system. If no texture is * assigned, an approximate spherical normal is calculated for each vertex. * * @type {Texture} */ set normalMap(arg: Texture); /** * Gets the normal map texture to apply to all particles in the system. * * @type {Texture} */ get normalMap(): Texture; /** * Sets the polygonal mesh to be used as a particle. Only first vertex/index buffer is used. * Vertex buffer must contain local position at first 3 floats of each vertex. * * @type {Mesh} */ set mesh(arg: Mesh); /** * Gets the polygonal mesh to be used as a particle. * * @type {Mesh} */ get mesh(): Mesh; /** * Sets the {@link Asset} used to set the mesh. * * @type {Asset|null} */ set meshAsset(arg: Asset | null); /** * Gets the {@link Asset} used to set the mesh. * * @type {Asset|null} */ get meshAsset(): Asset | null; /** * Sets the Render {@link Asset} used to set the mesh. * * @type {Asset|null} */ set renderAsset(arg: Asset | null); /** * Gets the Render {@link Asset} used to set the mesh. * * @type {Asset|null} */ get renderAsset(): Asset | null; /** * Sets the particle orientation mode. Can be: * * - {@link PARTICLEORIENTATION_SCREEN}: Particles are facing camera. * - {@link PARTICLEORIENTATION_WORLD}: User defined world space normal (particleNormal) to set * planes orientation. * - {@link PARTICLEORIENTATION_EMITTER}: Similar to previous, but the normal is affected by * emitter (entity) transformation. * * @type {number} */ set orientation(arg: number); /** * Gets the particle orientation mode. * * @type {number} */ get orientation(): number; /** * Sets the particle normal. This only applies to particle system with the orientation modes * `PARTICLEORIENTATION_WORLD` and `PARTICLEORIENTATION_EMITTER`. * * @type {Vec3} */ set particleNormal(arg: Vec3); /** * Gets the particle normal. * * @type {Vec3} */ get particleNormal(): Vec3; /** * Sets the local space velocity graph. * * @type {CurveSet} */ set localVelocityGraph(arg: CurveSet); /** * Gets the local space velocity graph. * * @type {CurveSet} */ get localVelocityGraph(): CurveSet; /** * Sets the second velocity graph. If not null, particles pick random values between * localVelocityGraph and localVelocityGraph2. * * @type {CurveSet} */ set localVelocityGraph2(arg: CurveSet); /** * Gets the second velocity graph. * * @type {CurveSet} */ get localVelocityGraph2(): CurveSet; /** * Sets the world space velocity graph. * * @type {CurveSet} */ set velocityGraph(arg: CurveSet); /** * Gets the world space velocity graph. * * @type {CurveSet} */ get velocityGraph(): CurveSet; /** * Sets the second world space velocity graph. If not null, particles pick random values * between velocityGraph and velocityGraph2. * * @type {CurveSet} */ set velocityGraph2(arg: CurveSet); /** * Gets the second world space velocity graph. * * @type {CurveSet} */ get velocityGraph2(): CurveSet; /** * Sets the rotation speed graph. * * @type {Curve} */ set rotationSpeedGraph(arg: Curve); /** * Gets the rotation speed graph. * * @type {Curve} */ get rotationSpeedGraph(): Curve; /** * Sets the second rotation speed graph. If not null, particles pick random values between * rotationSpeedGraph and rotationSpeedGraph2. * * @type {Curve} */ set rotationSpeedGraph2(arg: Curve); /** * Gets the second rotation speed graph. * * @type {Curve} */ get rotationSpeedGraph2(): Curve; /** * Sets the radial speed graph. Velocity vector points from emitter origin to particle position. * * @type {Curve} */ set radialSpeedGraph(arg: Curve); /** * Gets the radial speed graph. * * @type {Curve} */ get radialSpeedGraph(): Curve; /** * Sets the second radial speed graph. If not null, particles pick random values between * radialSpeedGraph and radialSpeedGraph2. Velocity vector points from emitter origin to * particle position. * * @type {Curve} */ set radialSpeedGraph2(arg: Curve); /** * Gets the second radial speed graph. * * @type {Curve} */ get radialSpeedGraph2(): Curve; /** * Sets the scale graph. * * @type {Curve} */ set scaleGraph(arg: Curve); /** * Gets the scale graph. * * @type {Curve} */ get scaleGraph(): Curve; /** * Sets the second scale graph. If not null, particles pick random values between `scaleGraph` * and `scaleGraph2`. * * @type {Curve} */ set scaleGraph2(arg: Curve); /** * Gets the second scale graph. * * @type {Curve} */ get scaleGraph2(): Curve; /** * Sets the color graph. * * @type {CurveSet} */ set colorGraph(arg: CurveSet); /** * Gets the color graph. * * @type {CurveSet} */ get colorGraph(): CurveSet; /** * Sets the second color graph. If not null, particles pick random values between `colorGraph` * and `colorGraph2`. * * @type {CurveSet} */ set colorGraph2(arg: CurveSet); /** * Gets the second color graph. * * @type {CurveSet} */ get colorGraph2(): CurveSet; /** * Sets the alpha graph. * * @type {Curve} */ set alphaGraph(arg: Curve); /** * Gets the alpha graph. * * @type {Curve} */ get alphaGraph(): Curve; /** * Sets the second alpha graph. If not null, particles pick random values between `alphaGraph` * and `alphaGraph2`. * * @type {Curve} */ set alphaGraph2(arg: Curve); /** * Gets the second alpha graph. * * @type {Curve} */ get alphaGraph2(): Curve; /** * Sets the number of horizontal tiles in the sprite sheet. * * @type {number} */ set animTilesX(arg: number); /** * Gets the number of horizontal tiles in the sprite sheet. * * @type {number} */ get animTilesX(): number; /** * Sets the number of vertical tiles in the sprite sheet. * * @type {number} */ set animTilesY(arg: number); /** * Gets the number of vertical tiles in the sprite sheet. * * @type {number} */ get animTilesY(): number; /** * Sets the sprite sheet frame that the animation should begin playing from. Indexed from the * start of the current animation. * * @type {number} */ set animStartFrame(arg: number); /** * Gets the sprite sheet frame that the animation should begin playing from. * * @type {number} */ get animStartFrame(): number; /** * Sets the number of sprite sheet frames in the current sprite sheet animation. The number of * animations multiplied by number of frames should be a value less than `animTilesX` * multiplied by `animTilesY`. * * @type {number} */ set animNumFrames(arg: number); /** * Gets the number of sprite sheet frames in the current sprite sheet animation. * * @type {number} */ get animNumFrames(): number; /** * Sets the number of sprite sheet animations contained within the current sprite sheet. The * number of animations multiplied by number of frames should be a value less than `animTilesX` * multiplied by `animTilesY`. * * @type {number} */ set animNumAnimations(arg: number); /** * Gets the number of sprite sheet animations contained within the current sprite sheet. * * @type {number} */ get animNumAnimations(): number; /** * Sets the index of the animation to play. When `animNumAnimations` is greater than 1, the * sprite sheet animation index determines which animation the particle system should play. * * @type {number} */ set animIndex(arg: number); /** * Gets the index of the animation to play. * * @type {number} */ get animIndex(): number; /** * Sets whether each particle emitted by the system will play a random animation from the * sprite sheet, up to `animNumAnimations`. * * @type {boolean} */ set randomizeAnimIndex(arg: boolean); /** * Gets whether each particle emitted by the system will play a random animation from the * sprite sheet, up to `animNumAnimations`. * * @type {boolean} */ get randomizeAnimIndex(): boolean; /** * Sets the sprite sheet animation speed. 1 = particle lifetime, 2 = double the particle * lifetime, etc. * * @type {number} */ set animSpeed(arg: number); /** * Gets the sprite sheet animation speed. * * @type {number} */ get animSpeed(): number; /** * Sets whether the sprite sheet animation plays once or loops continuously. * * @type {boolean} */ set animLoop(arg: boolean); /** * Gets whether the sprite sheet animation plays once or loops continuously. * * @type {boolean} */ get animLoop(): boolean; /** * Sets the array of layer IDs ({@link Layer#id}) to which this particle system should belong. * Don't push/pop/splice or modify this array. If you want to change it, set a new one instead. * * @type {number[]} */ set layers(arg: ReadonlyArray); /** * Gets the array of layer IDs ({@link Layer#id}) to which this particle system belongs. * * @type {ReadonlyArray} */ get layers(): ReadonlyArray; /** * Sets the draw order of the component. A higher value means that the component will be * rendered on top of other components in the same layer. This is not used unless the layer's * sort order is set to {@link SORTMODE_MANUAL}. * * @type {number} */ set drawOrder(drawOrder: number); /** * Gets the draw order of the component. * * @type {number} */ get drawOrder(): number; /** * Sets a property that only requires the emitter material to be updated. * * @param {string} name - The name of the property to set. * @param {*} arg - The new value of the property. * @private */ private _setSimpleProperty; /** * Sets a property that requires the particle system to be rebuilt. * * @param {string} name - The name of the property to set. * @param {*} arg - The new value of the property. * @private */ private _setComplexProperty; /** * Sets a curve property that requires the emitter graphs to be rebuilt. * * @param {string} name - The name of the property to set. * @param {*} arg - The new value of the property. * @private */ private _setGraphProperty; addMeshInstanceToLayers(): void; removeMeshInstanceFromLayers(): void; onLayersChanged(oldComp: any, newComp: any): void; onLayerAdded(layer: any): void; onLayerRemoved(layer: any): void; _bindColorMapAsset(asset: any): void; _unbindColorMapAsset(asset: any): void; _onColorMapAssetLoad(asset: any): void; _onColorMapAssetUnload(asset: any): void; _onColorMapAssetRemove(asset: any): void; _onColorMapAssetChange(asset: any): void; _bindNormalMapAsset(asset: any): void; _unbindNormalMapAsset(asset: any): void; _onNormalMapAssetLoad(asset: any): void; _onNormalMapAssetUnload(asset: any): void; _onNormalMapAssetRemove(asset: any): void; _onNormalMapAssetChange(asset: any): void; _bindMeshAsset(asset: any): void; _unbindMeshAsset(asset: any): void; _onMeshAssetLoad(asset: any): void; _onMeshAssetUnload(asset: any): void; _onMeshAssetRemove(asset: any): void; _onMeshAssetChange(asset: any): void; _onMeshChanged(mesh: any): void; _bindRenderAsset(asset: any): void; _unbindRenderAsset(asset: any): void; _onRenderAssetLoad(asset: any): void; _onRenderAssetUnload(asset: any): void; _onRenderAssetRemove(asset: any): void; _onRenderChanged(render: any): void; _onRenderSetMeshes(meshes: any): void; _requestDepth(): void; _releaseDepth(): void; onBeforeRemove(): void; /** * Resets particle state, doesn't affect playing. */ reset(): void; /** * Disables the emission of new particles, lets existing to finish their simulation. */ stop(): void; /** * Freezes the simulation. */ pause(): void; /** * Unfreezes the simulation. */ unpause(): void; /** * Enables/unfreezes the simulation. */ play(): void; /** * Checks if simulation is in progress. * * @returns {boolean} True if the particle system is currently playing and false otherwise. */ isPlaying(): boolean; /** * Called by the Editor when the component is selected, to allow custom in Editor behavior. * * @private */ private setInTools; /** * Rebuilds all data used by this particle system. * * @private */ private rebuild; } /** * Options of the `particlesystem` component accepted by {@link ParticleSystemComponentSystem} that * differ from the properties of {@link ParticleSystemComponent}. Each replaces the same-named * property of the options that {@link Entity#addComponent} derives from the component class; see * {@link ComponentOptionsOverrides}. */ type ParticleSystemComponentOptionsOverrides = { /** * - Same as * {@link ParticleSystemComponent#alphaGraph}, also accepting plain `{ type, keys }` curve data. */ alphaGraph?: Curve | { type?: number; keys: number[]; }; /** * - Same as * {@link ParticleSystemComponent#alphaGraph2}, also accepting plain `{ type, keys }` curve data. */ alphaGraph2?: Curve | { type?: number; keys: number[]; }; /** * - Same as * {@link ParticleSystemComponent#colorGraph}, also accepting plain `{ type, keys }` curve set data. */ colorGraph?: CurveSet | { type?: number; keys: number[][]; }; /** * - Same as * {@link ParticleSystemComponent#colorGraph2}, also accepting plain `{ type, keys }` curve set * data. */ colorGraph2?: CurveSet | { type?: number; keys: number[][]; }; /** * - Same as * {@link ParticleSystemComponent#emitterExtents}, also accepting an `[x, y, z]` array. */ emitterExtents?: Vec3 | number[]; /** * - Same as * {@link ParticleSystemComponent#emitterExtentsInner}, also accepting an `[x, y, z]` array. */ emitterExtentsInner?: Vec3 | number[]; /** * - Same as * {@link ParticleSystemComponent#localVelocityGraph}, also accepting plain `{ type, keys }` curve * set data. */ localVelocityGraph?: CurveSet | { type?: number; keys: number[][]; }; /** * - Same as * {@link ParticleSystemComponent#localVelocityGraph2}, also accepting plain `{ type, keys }` curve * set data. */ localVelocityGraph2?: CurveSet | { type?: number; keys: number[][]; }; /** * - Same as {@link ParticleSystemComponent#mesh}. An * {@link Asset} or asset id is assigned to {@link ParticleSystemComponent#meshAsset} instead. */ mesh?: Mesh | Asset | number; /** * - Same as * {@link ParticleSystemComponent#particleNormal}, also accepting an `[x, y, z]` array. */ particleNormal?: Vec3 | number[]; /** * - Same as * {@link ParticleSystemComponent#radialSpeedGraph}, also accepting plain `{ type, keys }` curve * data. */ radialSpeedGraph?: Curve | { type?: number; keys: number[]; }; /** * - Same as * {@link ParticleSystemComponent#radialSpeedGraph2}, also accepting plain `{ type, keys }` curve * data. */ radialSpeedGraph2?: Curve | { type?: number; keys: number[]; }; /** * - Same as * {@link ParticleSystemComponent#rotationSpeedGraph}, also accepting plain `{ type, keys }` curve * data. */ rotationSpeedGraph?: Curve | { type?: number; keys: number[]; }; /** * - Same as * {@link ParticleSystemComponent#rotationSpeedGraph2}, also accepting plain `{ type, keys }` curve * data. */ rotationSpeedGraph2?: Curve | { type?: number; keys: number[]; }; /** * - Same as * {@link ParticleSystemComponent#scaleGraph}, also accepting plain `{ type, keys }` curve data. */ scaleGraph?: Curve | { type?: number; keys: number[]; }; /** * - Same as * {@link ParticleSystemComponent#scaleGraph2}, also accepting plain `{ type, keys }` curve data. */ scaleGraph2?: Curve | { type?: number; keys: number[]; }; /** * - Same as * {@link ParticleSystemComponent#velocityGraph}, also accepting plain `{ type, keys }` curve set * data. */ velocityGraph?: CurveSet | { type?: number; keys: number[][]; }; /** * - Same as * {@link ParticleSystemComponent#velocityGraph2}, also accepting plain `{ type, keys }` curve set * data. */ velocityGraph2?: CurveSet | { type?: number; keys: number[][]; }; /** * - Same as {@link ParticleSystemComponent#wrapBounds}, * also accepting an `[x, y, z]` array. */ wrapBounds?: Vec3 | number[]; }; /** * Manages the {@link ParticleSystemComponent}s of an application. Reach it through * `app.systems.particlesystem`; components are created with {@link Entity#addComponent}, never by * calling the system directly. * * @category Graphics */ declare class ParticleSystemComponentSystem extends ComponentSystem { id: string; ComponentType: typeof ParticleSystemComponent; initializeComponentData(component: any, _data: any): void; cloneComponent(entity: any, clone: any): Component; onUpdate(dt: any): void; onBeforeRemove(entity: any, component: any): void; } /** * @import { BoundingBox } from '../../../core/shape/bounding-box.js' * @import { Entity } from '../../entity.js' * @import { EventHandle } from '../../../core/event-handle.js' * @import { Material } from '../../../scene/materials/material.js' * @import { RenderComponentSystem } from './system.js' */ /** * The RenderComponent enables an {@link Entity} to render 3D meshes. The {@link type} property can * be set to one of several predefined shapes (such as `box`, `sphere`, `cone` and so on). * Alternatively, the component can be configured to manage an arbitrary array of * {@link MeshInstance}s. These can either be created programmatically or loaded from an * {@link Asset}. * * The {@link MeshInstance}s managed by this component are positioned, rotated, and scaled in world * space by the world transformation matrix of the owner {@link Entity}. This world matrix is * derived by combining the entity's local transformation (position, rotation, and scale) with the * world transformation matrix of its parent entity in the scene hierarchy. * * You should never need to use the RenderComponent constructor directly. To add a RenderComponent * to an Entity, use {@link Entity#addComponent}: * * ```javascript * const entity = new Entity(); * entity.addComponent('render', { * type: 'box' * }); * ``` * * Once the RenderComponent is added to the entity, you can access it via the {@link Entity#render} * property: * * ```javascript * entity.render.type = 'capsule'; // Set the render component's type * * console.log(entity.render.type); // Get the render component's type and print it * ``` * * Relevant Engine API examples: * * - [Loading Render Assets](https://playcanvas.github.io/#/graphics/render-asset) * - [Primitive Shapes](https://playcanvas.github.io/#/graphics/shapes) * - [Spinning Cube](https://playcanvas.github.io/#/misc/hello-world) * * @hideconstructor * @category Graphics */ declare class RenderComponent extends Component { /** * Create a new RenderComponent. * * @param {RenderComponentSystem} system - The ComponentSystem that created this Component. * @param {Entity} entity - The Entity that this Component is attached to. */ constructor(system: RenderComponentSystem, entity: Entity); /** * @type {'asset'|'box'|'capsule'|'cone'|'cylinder'|'plane'|'sphere'|'torus'} * @private */ private _type; /** @private */ private _castShadows; /** @private */ private _shadowCascadeMask; /** @private */ private _receiveShadows; /** @private */ private _castShadowsLightmap; /** @private */ private _lightmapped; /** @private */ private _lightmapSizeMultiplier; /** * Mark meshes as non-movable (optimization). */ isStatic: boolean; /** @private */ private _batchGroupId; /** @private */ private _layers; /** @private */ private _renderStyle; /** * @type {MeshInstance[]} * @private */ private _meshInstances; /** * @type {BoundingBox|null} * @private */ private _customAabb; /** * Used by lightmapper. * * @type {{x: number, y: number, z: number, uv: number}|null} * @ignore */ _area: { x: number; y: number; z: number; uv: number; } | null; /** * @type {AssetReference} * @private */ private _assetReference; /** * @type {AssetReference[]} * @private */ private _materialReferences; /** * Material used to render meshes other than asset type. It gets priority when set to * something else than defaultMaterial, otherwise materialASsets[0] is used. * * @type {Material} * @private */ private _material; /** * A reference to the entity to be used as the root bone for any skinned meshes that * are rendered by this component. * * @type {Entity|null} * @private */ private _rootBone; /** * @type {EventHandle|null} * @private */ private _evtLayersChanged; /** * @type {EventHandle|null} * @private */ private _evtLayerAdded; /** * @type {EventHandle|null} * @private */ private _evtLayerRemoved; /** * @type {EventHandle|null} * @private */ private _evtSetMeshes; /** * Sets the render style of this component's {@link MeshInstance}s. Can be: * * - {@link RENDERSTYLE_SOLID} * - {@link RENDERSTYLE_WIREFRAME} * - {@link RENDERSTYLE_POINTS} * * Defaults to {@link RENDERSTYLE_SOLID}. * * @type {number} */ set renderStyle(renderStyle: number); /** * Gets the render style of this component's {@link MeshInstance}s. * * @type {number} */ get renderStyle(): number; /** * Sets the custom object space bounding box that is used for visibility culling of attached * mesh instances. This is an optimization, allowing an oversized bounding box to be specified * for skinned characters in order to avoid per frame bounding box computations based on bone * positions. * * @type {BoundingBox|null} */ set customAabb(value: BoundingBox | null); /** * Gets the custom object space bounding box that is used for visibility culling of attached * mesh instances. * * @type {BoundingBox|null} */ get customAabb(): BoundingBox | null; /** * Sets the type of the component, determining the source of the geometry to be rendered. * The geometry, whether it's a primitive shape or originates from an asset, is rendered * using the owning entity's final world transform. This world transform is calculated by * concatenating (multiplying) the local transforms (position, rotation, scale) of the * entity and all its ancestors in the scene hierarchy. This process positions, orientates, * and scales the geometry in world space. * * Can be one of the following values: * * - **"asset"**: Renders geometry defined in an {@link Asset} of type `render`. This asset, * assigned to the {@link asset} property, contains one or more {@link MeshInstance}s. * Alternatively, {@link meshInstances} can be set programmatically. * - **"box"**: A unit cube (sides of length 1) centered at the local space origin. * - **"capsule"**: A shape composed of a cylinder and two hemispherical caps that is aligned * with the local Y-axis. It is centered at the local space origin and has an unscaled height * of 2 and a radius of 0.5. * - **"cone"**: A cone aligned with the local Y-axis. It is centered at the local space * origin, with its base in the local XZ plane at Y = -0.5 and its tip at Y = +0.5. It has * an unscaled height of 1 and a base radius of 0.5. * - **"cylinder"**: A cylinder aligned with the local Y-axis. It is centered at the local * space origin with an unscaled height of 1 and a radius of 0.5. * - **"plane"**: A flat plane in the local XZ plane at Y = 0 (normal along +Y). It is * centered at the local space origin with unscaled dimensions of 1x1 units along local X and * Z axes. * - **"sphere"**: A sphere with a radius of 0.5. It is centered at the local space origin and * has poles at Y = -0.5 and Y = +0.5. * - **"torus"**: A doughnut shape lying in the local XZ plane at Y = 0. It is centered at * the local space origin with a tube radius of 0.2 and a ring radius of 0.3. * * @type {'asset'|'box'|'capsule'|'cone'|'cylinder'|'plane'|'sphere'|'torus'} */ set type(value: "asset" | "box" | "capsule" | "cone" | "cylinder" | "plane" | "sphere" | "torus"); /** * Gets the type of the component. * * @type {'asset'|'box'|'capsule'|'cone'|'cylinder'|'plane'|'sphere'|'torus'} */ get type(): "asset" | "box" | "capsule" | "cone" | "cylinder" | "plane" | "sphere" | "torus"; /** * Sets the array of meshInstances contained in the component. * * @type {MeshInstance[]} */ set meshInstances(value: ReadonlyArray); /** * Gets the array of meshInstances contained in the component. Use the setter to replace the * array; do not mutate the returned array. * * @type {ReadonlyArray} */ get meshInstances(): ReadonlyArray; /** * Sets whether the component is affected by the runtime lightmapper. If true, the meshes will * be lightmapped after using lightmapper.bake(). * * @type {boolean} */ set lightmapped(value: boolean); /** * Gets whether the component is affected by the runtime lightmapper. * * @type {boolean} */ get lightmapped(): boolean; /** * Sets whether attached meshes will cast shadows for lights that have shadow casting enabled. * * @type {boolean} */ set castShadows(value: boolean); /** * Gets whether attached meshes will cast shadows for lights that have shadow casting enabled. * * @type {boolean} */ get castShadows(): boolean; /** * Sets a bitmask that controls which shadow cascades the attached meshes contribute to when * rendered with a {@link LIGHTTYPE_DIRECTIONAL} light source. Combine the * {@link SHADOW_CASCADE_0} .. {@link SHADOW_CASCADE_3} flags to select individual cascades. * This is only effective when {@link castShadows} is enabled. Defaults to * {@link SHADOW_CASCADE_ALL}, which contributes to all available cascades. * * Note that this filters the meshes per cascade at render time, it does not remove them from * the shadow casters of the {@link Layer} - use {@link castShadows} to disable shadow casting * completely. * * @type {number} * @example * // only cast shadows into the two cascades closest to the camera * entity.render.shadowCascadeMask = SHADOW_CASCADE_0 | SHADOW_CASCADE_1; */ set shadowCascadeMask(value: number); /** * Gets the bitmask that controls which shadow cascades the attached meshes contribute to. * * @type {number} */ get shadowCascadeMask(): number; /** * Sets whether shadows will be cast on attached meshes. * * @type {boolean} */ set receiveShadows(value: boolean); /** * Gets whether shadows will be cast on attached meshes. * * @type {boolean} */ get receiveShadows(): boolean; /** * Sets whether meshes instances will cast shadows when rendering lightmaps. * * @type {boolean} */ set castShadowsLightmap(value: boolean); /** * Gets whether meshes instances will cast shadows when rendering lightmaps. * * @type {boolean} */ get castShadowsLightmap(): boolean; /** * Sets the lightmap resolution multiplier. * * @type {number} */ set lightmapSizeMultiplier(value: number); /** * Gets the lightmap resolution multiplier. * * @type {number} */ get lightmapSizeMultiplier(): number; /** * Sets the array of layer IDs ({@link Layer#id}) to which the mesh instances belong. Don't * push, pop, splice or modify this array. If you want to change it, set a new one instead. * * @type {number[]} */ set layers(value: ReadonlyArray); /** * Gets the array of layer IDs ({@link Layer#id}) to which the mesh instances belong. * * @type {ReadonlyArray} */ get layers(): ReadonlyArray; /** * Sets the batch group for the mesh instances in this component (see {@link BatchGroup}). * Default is -1 (no group). * * @type {number} */ set batchGroupId(value: number); /** * Gets the batch group for the mesh instances in this component (see {@link BatchGroup}). * * @type {number} */ get batchGroupId(): number; /** * Sets the material {@link Material} that will be used to render the component. The material * is ignored for renders of type 'asset' — which is the type every entity produced by * `instantiateRenderEntity` carries, so this setter has no effect on models loaded from a * container. For those, assign `material` on each entry of * {@link RenderComponent#meshInstances} instead. * * @type {Material} */ set material(value: Material); /** * Gets the material {@link Material} that will be used to render the component. * * @type {Material} */ get material(): Material; /** * Sets the material assets that will be used to render the component. Each material * corresponds to the respective mesh instance. * * @type {Asset[]|number[]} */ set materialAssets(value: Asset[] | number[]); /** * Gets the material assets that will be used to render the component. * * @type {Asset[]|number[]} */ get materialAssets(): Asset[] | number[]; /** * Sets the render asset (or asset id) for the render component. This only applies to render components with * type 'asset'. * * @type {Asset|number|null} */ set asset(value: number | null); /** * Gets the render asset id for the render component. * * @type {number|null} */ get asset(): number | null; /** * Assign asset id to the component, without updating the component with the new asset. * This can be used to assign the asset id to already fully created component. * * @param {Asset|number} asset - The render asset or asset id to assign. * @ignore */ assignAsset(asset: Asset | number): void; /** * Sets the root bone entity (or entity guid) for the render component. * * @type {Entity|string|null} */ set rootBone(value: Entity | null); /** * Gets the root bone entity for the render component. * * @type {Entity|null} */ get rootBone(): Entity | null; /** @private */ private destroyMeshInstances; /** * Destroys the mesh instances without firing a change notification. Used by the meshInstances * setter, which notifies once the replacement mesh instances are in place. * * @private */ private _destroyMeshInstances; /** * Fires a notification that the set of mesh instances has changed, so that systems which * reference them can re-resolve. An anim component binds morph target weights and animated * material textures to specific mesh instances, and unlike a model component - which owns its * mesh instances on a private graph node hierarchy under its own entity - a render hierarchy is * a public entity hierarchy, so the anim component driving these mesh instances can live on any * ancestor entity. The notification is therefore broadcast rather than delivered directly. See * #5225. * * @private */ private _onMeshInstancesChanged; /** @private */ private addToLayers; removeFromLayers(): void; /** @private */ private onRemoveChild; /** @private */ private onInsertChild; onBeforeRemove(): void; materialAsset: any; onLayersChanged(oldComp: any, newComp: any): void; onLayerAdded(layer: any): void; onLayerRemoved(layer: any): void; /** * Stop rendering {@link MeshInstance}s without removing them from the scene hierarchy. This * method sets the {@link MeshInstance#visible} property of every MeshInstance to false. Note, * this does not remove the mesh instances from the scene hierarchy or draw call list. So the * render component still incurs some CPU overhead. */ hide(): void; /** * Enable rendering of the component's {@link MeshInstance}s if hidden using {@link hide}. This * method sets the {@link MeshInstance#visible} property on all mesh instances to true. */ show(): void; _onRenderAssetAdded(): void; _onRenderAssetLoad(): void; _onSetMeshes(meshes: any): void; _clearSkinInstances(): void; _cloneSkinInstances(): void; _cloneMeshes(meshes: any): void; _onRenderAssetUnload(): void; _onRenderAssetRemove(): void; _onMaterialAdded(index: any, component: any, asset: any): void; _updateMainMaterial(index: any, material: any): void; _onMaterialLoad(index: any, component: any, asset: any): void; _onMaterialRemove(index: any, component: any, asset: any): void; _onMaterialUnload(index: any, component: any, asset: any): void; resolveDuplicatedEntityReferenceProperties(oldRender: any, duplicatedIdsMap: any): void; } /** * Options of the `render` component accepted by {@link RenderComponentSystem} that differ from the * properties of {@link RenderComponent}. Each replaces the same-named property of the options that * {@link Entity#addComponent} derives from the component class; see * {@link ComponentOptionsOverrides}. */ type RenderComponentOptionsOverrides = { /** * - Center `[x, y, z]` of a custom bounding box; with * `aabbHalfExtents`, sets {@link RenderComponent#customAabb}. */ aabbCenter?: number[]; /** * - Half-extents `[x, y, z]` of a custom bounding box; with * `aabbCenter`, sets {@link RenderComponent#customAabb}. */ aabbHalfExtents?: number[]; /** * - Same as {@link RenderComponent#batchGroupId}. `null` * selects no batch group. */ batchGroupId?: number | null; }; /** * Allows an Entity to render a mesh or a primitive shape like a box, capsule, sphere, cylinder, * cone etc. * * @category Graphics */ declare class RenderComponentSystem extends ComponentSystem { id: string; ComponentType: typeof RenderComponent; defaultMaterial: StandardMaterial; initializeComponentData(component: any, _data: any, properties: any): void; cloneComponent(entity: any, clone: any): Component; onBeforeRemove(entity: any, component: any): void; } /** * The RigidBodyComponent, when combined with a {@link CollisionComponent}, allows your entities * to be simulated using realistic physics. A RigidBodyComponent will fall under gravity and * collide with other rigid bodies. Using scripts, you can apply forces and impulses to rigid * bodies. * * You should never need to use the RigidBodyComponent constructor directly. To add a * RigidBodyComponent to an {@link Entity}, use {@link Entity#addComponent}: * * ```javascript * // Create a static 1x1x1 box-shaped rigid body * const entity = new Entity(); * entity.addComponent('collision'); // Without options, this defaults to a 1x1x1 box shape * entity.addComponent('rigidbody'); // Without options, this defaults to a 'static' body * ``` * * To create a dynamic sphere with mass of 10, do: * * ```javascript * const entity = new Entity(); * entity.addComponent('collision', { * type: 'sphere' * }); * entity.addComponent('rigidbody', { * type: 'dynamic', * mass: 10 * }); * ``` * * Once the RigidBodyComponent is added to the entity, you can access it via the * {@link Entity#rigidbody} property: * * ```javascript * entity.rigidbody.mass = 10; * console.log(entity.rigidbody.mass); * ``` * * For player movement, `playcanvas/scripts/esm/first-person-controller.mjs` and * `playcanvas/scripts/esm/third-person-controller.mjs` ship complete rigidbody character * controllers with capsule collision, damped ground and air movement, sprinting, jumping and * camera control. Attach one instead of driving the body by hand. * * Relevant Engine API examples: * * - [Falling shapes](https://playcanvas.github.io/#/physics/falling-shapes) * - [Vehicle physics](https://playcanvas.github.io/#/physics/vehicle) * * @hideconstructor * @category Physics */ declare class RigidBodyComponent extends Component { /** * Fired when a contact occurs between two rigid bodies. The handler is passed a * {@link ContactResult} object containing details of the contact between the two rigid bodies. * * @event * @example * entity.rigidbody.on('contact', (result) => { * console.log(`Contact between ${entity.name} and ${result.other.name}`); * }); */ static EVENT_CONTACT: string; /** * Fired when two rigid bodies start touching. The handler is passed a {@link ContactResult} * object containing details of the contact between the two rigid bodies. * * @event * @example * entity.rigidbody.on('collisionstart', (result) => { * console.log(`Collision started between ${entity.name} and ${result.other.name}`); * }); */ static EVENT_COLLISIONSTART: string; /** * Fired when two rigid bodies stop touching. The handler is passed an {@link Entity} that * represents the other rigid body involved in the collision. * * @event * @example * entity.rigidbody.on('collisionend', (other) => { * console.log(`${entity.name} stopped touching ${other.name}`); * }); */ static EVENT_COLLISIONEND: string; /** * Fired when a rigid body enters a trigger volume. The handler is passed an {@link Entity} * representing the trigger volume that this rigid body entered. * * @event * @example * entity.rigidbody.on('triggerenter', (trigger) => { * console.log(`Entity ${entity.name} entered trigger volume ${trigger.name}`); * }); */ static EVENT_TRIGGERENTER: string; /** * Fired when a rigid body exits a trigger volume. The handler is passed an {@link Entity} * representing the trigger volume that this rigid body exited. * * @event * @example * entity.rigidbody.on('triggerleave', (trigger) => { * console.log(`Entity ${entity.name} exited trigger volume ${trigger.name}`); * }); */ static EVENT_TRIGGERLEAVE: string; /** @private */ private _angularDamping; /** @private */ private _angularFactor; /** @private */ private _angularVelocity; /** * The physics backend body, when created. * * @type {PhysicsBody|null} * @private */ private _body; /** @private */ private _friction; /** @private */ private _gravityScale; /** @private */ private _group; /** @private */ private _linearDamping; /** @private */ private _linearFactor; /** @private */ private _linearVelocity; /** @private */ private _mask; /** @private */ private _mass; /** @private */ private _restitution; /** @private */ private _rollingFriction; /** @private */ private _simulationEnabled; /** * @type {BODYTYPE_DYNAMIC|BODYTYPE_KINEMATIC|BODYTYPE_STATIC} * @private */ private _type; /** * Sets the rate at which a body loses angular velocity over time. * * @type {number} */ set angularDamping(damping: number); /** * Gets the rate at which a body loses angular velocity over time. * * @type {number} */ get angularDamping(): number; /** * Sets the scaling factor for angular movement of the body in each axis. Only valid for rigid * bodies of type {@link BODYTYPE_DYNAMIC}. Defaults to 1 in all axes (body can freely rotate). * * @type {Vec3} */ set angularFactor(factor: Readonly); /** * Gets the scaling factor for angular movement of the body in each axis. Use the setter to * update the physics body. * * @type {Readonly} */ get angularFactor(): Readonly; /** * Sets the rotational speed of the body around each world axis. Only valid for rigid bodies * of type {@link BODYTYPE_DYNAMIC}. * * @type {Vec3} */ set angularVelocity(velocity: Readonly); /** * Gets the rotational speed of the body around each world axis. Use the setter to update the * physics body. * * @type {Readonly} */ get angularVelocity(): Readonly; /** * @type {*} * @ignore */ set body(body: any); /** * The physics backend's native body - a btRigidBody with the Ammo backend - or null if the * body has not been created or the backend has no native bodies. An unsupported escape hatch * for native functionality the component does not expose: code that uses it only works with * that physics backend. The setter takes the backend {@link PhysicsBody} and is internal. * * @type {*} * @ignore */ get body(): any; /** * Sets the friction value used when contacts occur between two bodies. A higher value indicates * more friction. Should be set in the range 0 to 1. Defaults to 0.5. * * @type {number} */ set friction(friction: number); /** * Gets the friction value used when contacts occur between two bodies. * * @type {number} */ get friction(): number; /** * Sets the scale applied to the world gravity ({@link RigidBodyComponentSystem#gravity}) for * this body. Only valid for rigid bodies of type {@link BODYTYPE_DYNAMIC}. Defaults to 1, so * the body falls under the world gravity. Set to 0 to make the body ignore gravity, or to a * negative value to make it rise. To give a body its own gravity direction, set this to 0 and * apply the force yourself each frame with {@link applyForce}. * * @type {number} * @example * // A balloon that drifts slowly upwards * entity.rigidbody.gravityScale = -0.2; * @example * // A body that orbits a planet at the origin under its own gravity * entity.rigidbody.gravityScale = 0; * const force = new pc.Vec3(); * app.on('update', () => { * force.copy(entity.getPosition()).normalize().mulScalar(-entity.rigidbody.mass * 9.81); * entity.rigidbody.applyForce(force); * }); */ set gravityScale(scale: number); /** * Gets the scale applied to the world gravity for this body. * * @type {number} */ get gravityScale(): number; /** * Sets the collision group this body belongs to. Combine the group and the mask to prevent bodies * colliding with each other. The default depends on the body {@link RigidBodyComponent#type}: * 1 for dynamic bodies, 2 for static bodies and 4 for kinematic bodies. Setting the type * resets the group to the default for the new type, so set the group after the type. * * @type {number} */ set group(group: number); /** * Gets the collision group this body belongs to. * * @type {number} */ get group(): number; /** * Sets the rate at which a body loses linear velocity over time. Defaults to 0. * * @type {number} */ set linearDamping(damping: number); /** * Gets the rate at which a body loses linear velocity over time. * * @type {number} */ get linearDamping(): number; /** * Sets the scaling factor for linear movement of the body in each axis. Only valid for rigid * bodies of type {@link BODYTYPE_DYNAMIC}. Defaults to 1 in all axes (body can freely move). * * @type {Vec3} */ set linearFactor(factor: Readonly); /** * Gets the scaling factor for linear movement of the body in each axis. Use the setter to * update the physics body. * * @type {Readonly} */ get linearFactor(): Readonly; /** * Sets the speed of the body in a given direction. Only valid for rigid bodies of type * {@link BODYTYPE_DYNAMIC}. * * @type {Vec3} */ set linearVelocity(velocity: Readonly); /** * Gets the speed of the body in a given direction. Use the setter to update the physics body. * * @type {Readonly} */ get linearVelocity(): Readonly; /** * Sets the collision mask sets which groups this body collides with. It is a bit field of 16 * bits, the first 8 bits are reserved for engine use. The default depends on the body * {@link RigidBodyComponent#type}: 65533 for static bodies, which collides with everything * except other static bodies, and 65535 for dynamic and kinematic bodies, which collides with * everything. Setting the type resets the mask to the default for the new type, so set the * mask after the type. * * @type {number} */ set mask(mask: number); /** * Gets the collision mask sets which groups this body collides with. * * @type {number} */ get mask(): number; /** * Sets the mass of the body. This is only relevant for {@link BODYTYPE_DYNAMIC} bodies, other * types have infinite mass. Defaults to 1. * * @type {number} */ set mass(mass: number); /** * Gets the mass of the body. * * @type {number} */ get mass(): number; /** * Sets the value that controls the amount of energy lost when two rigid bodies collide. The * calculation multiplies the restitution values for both colliding bodies. A multiplied value * of 0 means that all energy is lost in the collision while a value of 1 means that no energy * is lost. Should be set in the range 0 to 1. Defaults to 0. * * @type {number} */ set restitution(restitution: number); /** * Gets the value that controls the amount of energy lost when two rigid bodies collide. * * @type {number} */ get restitution(): number; /** * Sets the torsional friction orthogonal to the contact point. Defaults to 0. * * @type {number} */ set rollingFriction(friction: number); /** * Gets the torsional friction orthogonal to the contact point. * * @type {number} */ get rollingFriction(): number; /** * Sets the rigid body type determines how the body is simulated. Can be: * * - {@link BODYTYPE_STATIC}: infinite mass and cannot move. * - {@link BODYTYPE_DYNAMIC}: simulated according to applied forces. * - {@link BODYTYPE_KINEMATIC}: infinite mass and does not respond to forces (can only be * moved by setting the position and rotation of component's {@link Entity}). * * Defaults to {@link BODYTYPE_STATIC}. Changing the type also resets * {@link RigidBodyComponent#group} and {@link RigidBodyComponent#mask} to the defaults for * the new type. * * @type {BODYTYPE_DYNAMIC|BODYTYPE_KINEMATIC|BODYTYPE_STATIC} */ set type(type: "dynamic" | "kinematic" | "static"); /** * Gets the rigid body type determines how the body is simulated. * * @type {BODYTYPE_DYNAMIC|BODYTYPE_KINEMATIC|BODYTYPE_STATIC} */ get type(): "dynamic" | "kinematic" | "static"; /** * If the Entity has a Collision shape attached then create a rigid body using this shape. This * method destroys the existing body. * * @private */ private createBody; /** * Returns true if the rigid body is currently actively being simulated. I.e. Not 'sleeping'. * * @returns {boolean} True if the body is active. */ isActive(): boolean; /** * Forcibly activate the rigid body simulation. Only affects rigid bodies of type * {@link BODYTYPE_DYNAMIC}. */ activate(): void; /** * Add a body to the simulation. * * @ignore */ enableSimulation(): void; /** * Remove a body from the simulation. * * @ignore */ disableSimulation(): void; /** * Apply a force to the body at a point. By default, the force is applied at the origin of the * body. However, the force can be applied at an offset from this point by specifying a world * space vector from the body's origin to the point of application. The body's origin is the * entity's world position, shifted by the collision component's * {@link CollisionComponent#linearOffset}. * * @overload * @param {number} x - X-component of the force in world space. * @param {number} y - Y-component of the force in world space. * @param {number} z - Z-component of the force in world space. * @param {number} [px] - X-component of the relative point at which to apply the force in * world space. * @param {number} [py] - Y-component of the relative point at which to apply the force in * world space. * @param {number} [pz] - Z-component of the relative point at which to apply the force in * world space. * @returns {void} * @example * // Apply an approximation of gravity at the body's center * this.entity.rigidbody.applyForce(0, -10, 0); * @example * // Apply an approximation of gravity at 1 unit down the world Z from the center of the body * this.entity.rigidbody.applyForce(0, -10, 0, 0, 0, 1); */ applyForce(x: number, y: number, z: number, px?: number, py?: number, pz?: number): void; /** * Apply a force to the body at a point. By default, the force is applied at the origin of the * body. However, the force can be applied at an offset from this point by specifying a world * space vector from the body's origin to the point of application. The body's origin is the * entity's world position, shifted by the collision component's * {@link CollisionComponent#linearOffset}. * * @overload * @param {Vec3} force - Vector representing the force in world space. * @param {Vec3} [relativePoint] - Optional vector representing the relative point at which to * apply the force in world space. * @returns {void} * @example * // Calculate a force vector pointing in the world space direction of the entity * const force = this.entity.forward.clone().mulScalar(100); * * // Apply the force at the body's center * this.entity.rigidbody.applyForce(force); * @example * // Apply a force at some relative offset from the body's center * // Calculate a force vector pointing in the world space direction of the entity * const force = this.entity.forward.clone().mulScalar(100); * * // Calculate the world space relative offset * const relativePoint = new Vec3(); * const childEntity = this.entity.findByName('Engine'); * relativePoint.sub2(childEntity.getPosition(), this.entity.getPosition()); * * // Apply the force * this.entity.rigidbody.applyForce(force, relativePoint); */ applyForce(force: Vec3, relativePoint?: Vec3): void; /** * Apply torque (rotational force) to the body. * * @overload * @param {number} x - The x-component of the torque force in world space. * @param {number} y - The y-component of the torque force in world space. * @param {number} z - The z-component of the torque force in world space. * @returns {void} * @example * entity.rigidbody.applyTorque(0, 10, 0); */ applyTorque(x: number, y: number, z: number): void; /** * Apply torque (rotational force) to the body. * * @overload * @param {Vec3} torque - Vector representing the torque force in world space. * @returns {void} * @example * const torque = new Vec3(0, 10, 0); * entity.rigidbody.applyTorque(torque); */ applyTorque(torque: Vec3): void; /** * Apply an impulse (instantaneous change of velocity) to the body at a point. By default, the * impulse is applied at the origin of the body. However, the impulse can be applied at an * offset from this point by specifying a world space vector from the body's origin to the * point of application. The body's origin is the entity's world position, shifted by the * collision component's {@link CollisionComponent#linearOffset}. * * @overload * @param {number} x - X-component of the impulse in world space. * @param {number} y - Y-component of the impulse in world space. * @param {number} z - Z-component of the impulse in world space. * @param {number} [px] - X-component of the relative point at which to apply the impulse in * world space. * @param {number} [py] - Y-component of the relative point at which to apply the impulse in * world space. * @param {number} [pz] - Z-component of the relative point at which to apply the impulse in * world space. * @returns {void} * @example * // Apply an impulse along the world space positive y-axis at the body's origin * entity.rigidbody.applyImpulse(0, 10, 0); * @example * // Apply an impulse along the world space positive y-axis at 1 unit along the world space * // positive z-axis from the body's origin * entity.rigidbody.applyImpulse(0, 10, 0, 0, 0, 1); */ applyImpulse(x: number, y: number, z: number, px?: number, py?: number, pz?: number): void; /** * Apply an impulse (instantaneous change of velocity) to the body at a point. By default, the * impulse is applied at the origin of the body. However, the impulse can be applied at an * offset from this point by specifying a world space vector from the body's origin to the * point of application. The body's origin is the entity's world position, shifted by the * collision component's {@link CollisionComponent#linearOffset}. * * @overload * @param {Vec3} impulse - Vector representing the impulse in world space. * @param {Vec3} [relativePoint] - Optional vector representing the relative point at which to * apply the impulse in world space. * @returns {void} * @example * // Apply an impulse along the world space positive y-axis at the body's origin * const impulse = new Vec3(0, 10, 0); * entity.rigidbody.applyImpulse(impulse); * @example * // Apply an impulse along the world space positive y-axis at 1 unit along the world space * // positive z-axis from the body's origin * const impulse = new Vec3(0, 10, 0); * const relativePoint = new Vec3(0, 0, 1); * entity.rigidbody.applyImpulse(impulse, relativePoint); * @example * // Apply an impulse at an offset given in the entity's local space, by first rotating the * // offset into world space * const impulse = new Vec3(0, 10, 0); * const relativePoint = entity.getRotation().transformVector(new Vec3(0, 0, 1)); * entity.rigidbody.applyImpulse(impulse, relativePoint); */ applyImpulse(impulse: Vec3, relativePoint?: Vec3): void; /** * Apply a torque impulse (rotational force applied instantaneously) to the body. * * @overload * @param {number} x - X-component of the torque impulse in world space. * @param {number} y - Y-component of the torque impulse in world space. * @param {number} z - Z-component of the torque impulse in world space. * @returns {void} * @example * entity.rigidbody.applyTorqueImpulse(0, 10, 0); */ applyTorqueImpulse(x: number, y: number, z: number): void; /** * Apply a torque impulse (rotational force applied instantaneously) to the body. * * @overload * @param {Vec3} torque - Vector representing the torque impulse in world space. * @returns {void} * @example * const torque = new Vec3(0, 10, 0); * entity.rigidbody.applyTorqueImpulse(torque); */ applyTorqueImpulse(torque: Vec3): void; /** * Returns true if the rigid body is of type {@link BODYTYPE_STATIC}. * * @returns {boolean} True if static. */ isStatic(): boolean; /** * Returns true if the rigid body is of type {@link BODYTYPE_STATIC} or {@link BODYTYPE_KINEMATIC}. * * @returns {boolean} True if static or kinematic. */ isStaticOrKinematic(): boolean; /** * Returns true if the rigid body is of type {@link BODYTYPE_KINEMATIC}. * * @returns {boolean} True if kinematic. */ isKinematic(): boolean; /** * Reads the entity transform (with any collision component offsets applied) but ignoring * scale. * * @param {Vec3} position - The vector to write the world space position to. * @param {Quat} rotation - The quaternion to write the world space rotation to. * @private */ private _getEntityTransform; /** * Set the rigid body transform to be the same as the Entity transform. This must be called * after any Entity transformation functions (e.g. {@link Entity#setPosition}) are called in * order to update the rigid body to match the Entity. * * @private */ private syncEntityToBody; /** * Sets an entity's transform to match that of the world transformation matrix of a dynamic * rigid body's motion state. * * @private */ private _updateDynamic; /** * Writes a body pose to an entity with a negative local scale or a mirrored world transform. * The rotation read from such an entity's world transform is not its rotation: a mirrored * basis has its X axis negated to make it a rotation, and a pair of negative scale factors * reads as a 180 degree turn. The body was created with that rotation, so writing the body * rotation back as the world rotation would bake the correction into the local rotation. * Instead, the rotation the body turned through since the entity was last synced is applied * to the local rotation. * * @param {Vec3} position - The world space position of the entity. * @param {Quat} rotation - The world space rotation of the body, without angular offset. * @private */ private _setMirroredTransform; /** * Writes the entity's world transform into the kinematic target of a kinematic body. * * @private */ private _updateKinematic; /** * Teleport an entity to a new world space position, optionally setting orientation. This * function should only be called for rigid bodies that are dynamic. * * @overload * @param {number} x - X-coordinate of the new world space position. * @param {number} y - Y-coordinate of the new world space position. * @param {number} z - Z-coordinate of the new world space position. * @param {number} [rx] - X-rotation of the world space Euler angles in degrees. * @param {number} [ry] - Y-rotation of the world space Euler angles in degrees. * @param {number} [rz] - Z-rotation of the world space Euler angles in degrees. * @returns {void} * @example * // Teleport the entity to the origin * entity.rigidbody.teleport(0, 0, 0); * @example * // Teleport the entity to world space coordinate [1, 2, 3] and reset orientation * entity.rigidbody.teleport(1, 2, 3, 0, 0, 0); */ teleport(x: number, y: number, z: number, rx?: number, ry?: number, rz?: number): void; /** * Teleport an entity to a new world space position, optionally setting orientation. This * function should only be called for rigid bodies that are dynamic. * * @overload * @param {Vec3} position - Vector holding the new world space position. * @param {Vec3} [angles] - Vector holding the new world space Euler angles in degrees. * @returns {void} * @example * // Teleport the entity to the origin * entity.rigidbody.teleport(Vec3.ZERO); * @example * // Teleport the entity to world space coordinate [1, 2, 3] and reset orientation * const position = new Vec3(1, 2, 3); * entity.rigidbody.teleport(position, Vec3.ZERO); */ teleport(position: Vec3, angles?: Vec3): void; /** * Teleport an entity to a new world space position, optionally setting orientation. This * function should only be called for rigid bodies that are dynamic. * * @overload * @param {Vec3} position - Vector holding the new world space position. * @param {Quat} [rotation] - Quaternion holding the new world space rotation. * @returns {void} * @example * // Teleport the entity to the origin * entity.rigidbody.teleport(Vec3.ZERO); * @example * // Teleport the entity to world space coordinate [1, 2, 3] and reset orientation * const position = new Vec3(1, 2, 3); * entity.rigidbody.teleport(position, Quat.IDENTITY); */ teleport(position: Vec3, rotation?: Quat): void; /** * Sets the rigid body type. * * @type {string} * @ignore * @deprecated Use {@link RigidBodyComponent#type} instead. */ set bodyType(type: string); /** * Gets the rigid body type. * * @type {string} * @ignore * @deprecated Use {@link RigidBodyComponent#type} instead. */ get bodyType(): string; /** * Writes the entity transform into the rigid body. * * @ignore * @deprecated Not public API. */ syncBodyToEntity(): void; } /** * Creates a trigger object used to create internal physics objects that interact with rigid bodies * and trigger collision events with no collision response. * * @category Physics */ declare class Trigger { /** * Create a new Trigger instance. * * @param {AppBase} app - The running {@link AppBase}. * @param {CollisionComponent} component - The component for which the trigger will be created. */ constructor(app: AppBase, component: CollisionComponent); entity: Entity; component: CollisionComponent; app: AppBase; initialize(): void; body: PhysicsBody; destroy(): void; _getEntityTransform(position: any, rotation: any): void; updateTransform(): void; enable(): void; disable(): void; } /** * Options of the `rigidbody` component accepted by {@link RigidBodyComponentSystem} that differ * from the properties of {@link RigidBodyComponent}. Each replaces the same-named property of the * options that {@link Entity#addComponent} derives from the component class; see * {@link ComponentOptionsOverrides}. */ type RigidBodyComponentOptionsOverrides = { /** * - Same as {@link RigidBodyComponent#angularFactor}, * also accepting an `[x, y, z]` array. */ angularFactor?: Vec3 | number[]; /** * - Same as {@link RigidBodyComponent#linearFactor}, * also accepting an `[x, y, z]` array. */ linearFactor?: Vec3 | number[]; }; /** * The RigidBodyComponentSystem manages the physics simulation for all rigid body components * in the application and is accessed as `app.systems.rigidbody`. It owns the physics world, * creates and destroys the bodies behind rigid body and collision components, steps the * simulation once per frame and writes the resulting transforms back to their entities. It also * holds global settings such as {@link RigidBodyComponentSystem#gravity}, performs raycasts * and reports collisions. * * The system is only functional once a physics backend is installed: either by supplying * {@link AppOptions#physicsWorld} when creating the application, or automatically when the * application has loaded the Ammo.js {@link WasmModule}. Use a recent Ammo.js build: mesh * colliders only follow entity scale with a build that exposes `btScaledBvhTriangleMeshShape`. * * Set {@link RigidBodyComponentSystem#timeScale} to slow the simulation down, speed it up or * pause it, for example while a pause menu is open, and call * {@link RigidBodyComponentSystem#step} to advance it manually. * * @category Physics */ declare class RigidBodyComponentSystem extends ComponentSystem { /** * Fired when a contact occurs between two rigid bodies. The handler is passed a * {@link SingleContactResult} object containing details of the contact between the two bodies. * * @event * @example * app.systems.rigidbody.on('contact', (result) => { * console.log(`Contact between ${result.a.name} and ${result.b.name}`); * }); */ static EVENT_CONTACT: string; /** @ignore */ maxSubSteps: number; /** * @type {number} * @ignore */ fixedTimeStep: number; /** * Scales the time the simulation is advanced by each frame. Defaults to 1. Values below 1 * run physics in slow motion and values above 1 speed it up. 0 pauses the simulation: the * system stops advancing it, bodies freeze in place, entity transforms are no longer driven * by their bodies and no contact or trigger events fire. The rest of the application keeps * running, so this suits a pause menu or inventory screen that must stay interactive while * the game world stands still. Negative values are treated as 0. * * This scale is applied on top of {@link AppBase#timeScale}. The simulation can still be * advanced manually with {@link RigidBodyComponentSystem#step} while paused, for example to * drive it from a custom time source. * * How slow motion below one fixed substep per frame looks depends on the backend: the Ammo * backend interpolates body transforms between substeps so motion stays smooth, while other * backends may only move bodies on the frames in which a substep runs. Fast forward is * limited by the maximum number of substeps the simulation may take per frame, beyond which * it runs slower than requested. * * Forces applied with {@link RigidBodyComponent#applyForce} while paused accumulate on the * body and are applied together on the next step, because forces are only cleared when the * simulation steps. Impulses and velocity changes take effect immediately. * * @example * // Freeze the game world while the pause menu is open * app.systems.rigidbody.timeScale = 0; * @example * // Run physics at quarter speed for a slow motion effect * app.systems.rigidbody.timeScale = 0.25; */ timeScale: number; /** * The world space vector representing global gravity in the physics simulation. Defaults to * [0, -9.81, 0] which is an approximation of the gravitational force on Earth. * * The value is applied to the physics backend at the start of the next step, whether the * vector is modified in place or replaced with a new one. * * @example * // Set the gravity in the physics world to simulate a planet with low gravity * app.systems.rigidbody.gravity = new Vec3(0, -3.7, 0); */ gravity: Vec3; /** * The gravity most recently applied to the physics backend. Compared against gravity each * step so the backend is only updated when the value changes. * * @type {Vec3} * @private */ private _appliedGravity; /** * @type {PhysicsWorld|null} * @private */ private _world; /** * @type {RigidBodyComponent[]} * @private */ private _dynamic; /** * @type {RigidBodyComponent[]} * @private */ private _kinematic; /** * @type {Trigger[]} * @private */ private _triggers; /** * @type {CollisionComponent[]} * @private */ private _compounds; /** * The contact listener installed on the physics backend. It forwards each contact pass to * this system, which keeps the listener methods private. * * @type {PhysicsContactListener} * @private */ private _contactListener; /** * The frame stats that record the duration of each physics step. * * @private */ private _stats; /** * @type {ObjectPool|null} * @private */ private contactPointPool; /** * @type {ObjectPool|null} * @private */ private contactResultPool; /** * @type {ObjectPool|null} * @private */ private singleContactResultPool; /** * The entities touched by each entity with contact or trigger events as of the last contact * pass, keyed by the GUID of the entity. * * @type {Object} * @private */ private collisions; /** * The entities touched by each entity in the contact pass in progress, keyed like * collisions. * * @type {Object} * @private */ private frameCollisions; id: string; ComponentType: typeof RigidBodyComponent; /** * Called once application libraries have loaded. Creates the Ammo backend when the Ammo * global is present and no backend was injected via {@link AppOptions#physicsWorld}. * * @ignore */ onLibraryLoaded(): void; /** * Installs a physics backend, applies the current gravity to it and registers the system's * contact listener with it. Called by * {@link AppBase#init} when {@link AppOptions#physicsWorld} is supplied, and internally by * Ammo auto-detection. A backend can be installed at most once. * * @param {PhysicsWorld} world - The physics backend. * @ignore */ setPhysicsWorld(world: PhysicsWorld): void; /** * Gets the installed physics backend, or null when no backend is installed. Supply a * backend via {@link AppOptions#physicsWorld}, or load the Ammo.js library to have one * installed automatically. * * @type {PhysicsWorld|null} * @alpha */ get physicsWorld(): PhysicsWorld | null; /** * The physics backend's native world - a btDiscreteDynamicsWorld with the Ammo backend - or * null if no backend is installed or it has no native world. Same as * {@link PhysicsWorld#nativeWorld}. An unsupported escape hatch for native functionality the * engine does not expose: code that uses it only works with that physics backend. * * @type {*} * @ignore */ get dynamicsWorld(): any; /** * The Ammo backend's native btDefaultCollisionConfiguration, or null with any other backend * or none. An unsupported escape hatch: code that uses it only works with the Ammo backend. * * @type {*} * @ignore */ get collisionConfiguration(): any; /** * The Ammo backend's native btCollisionDispatcher, or null with any other backend or none. * An unsupported escape hatch: code that uses it only works with the Ammo backend. * * @type {*} * @ignore */ get dispatcher(): any; /** * The Ammo backend's native btDbvtBroadphase, or null with any other backend or none. An * unsupported escape hatch: code that uses it only works with the Ammo backend. * * @type {*} * @ignore */ get overlappingPairCache(): any; /** * The Ammo backend's native btSequentialImpulseConstraintSolver, or null with any other * backend or none. An unsupported escape hatch: code that uses it only works with the Ammo * backend. * * @type {*} * @ignore */ get solver(): any; initializeComponentData(component: any, data: any): void; cloneComponent(entity: any, clone: any): Component; /** * Disables a component that is being removed and destroys its body. * * @param {Entity} entity - The entity the component is being removed from. * @param {RigidBodyComponent} component - The component being removed. * @private */ private onBeforeRemove; /** * Called once the component is gone from its entity. A collision component left behind * supplied the body's shape; without a body it is a trigger volume, or a child of an * enclosing compound, so it is rebuilt into that role. The pairs the body was touching are * forgotten first: they belong to the old role, and a trigger built over an overlap that is * still in progress has to report it as new. Nothing is rebuilt while the entity itself is * being destroyed, since the collision component is about to go as well. * * @param {Entity} entity - The entity the component was removed from. * @private */ private onRemove; /** * Adds a body to the simulation with the given collision group and mask. * * @param {PhysicsBody} body - The body to add. * @param {number} group - The collision group bits. * @param {number} mask - The collision mask bits. * @private */ private addBody; /** * Removes a body from the simulation. * * @param {PhysicsBody} body - The body to remove. * @private */ private removeBody; /** * Adds a component's body to the simulation and registers the component with the update * lists for its body type. Fires 'simulationenabled' on the component. No-op unless the * component has a body, an enabled collision component and is not already simulating. * * @param {RigidBodyComponent} component - The component to add to the simulation. * @ignore */ enableSimulation(component: RigidBodyComponent): void; /** * Removes a component's body from the simulation and unregisters the component from the * update lists. Fires 'simulationdisabled' on the component. No-op unless the component * has a body and is currently simulating. * * @param {RigidBodyComponent} component - The component to remove from the simulation. * @ignore */ disableSimulation(component: RigidBodyComponent): void; /** * Adds a trigger's body to the simulation and registers the trigger for per-frame * transform updates. No-op if the trigger is already registered. * * @param {Trigger} trigger - The trigger to add to the simulation. * @ignore */ addTrigger(trigger: Trigger): void; /** * Removes a trigger's body from the simulation and unregisters the trigger. No-op if the * trigger is not registered. * * @param {Trigger} trigger - The trigger to remove from the simulation. * @ignore */ removeTrigger(trigger: Trigger): void; /** * Raycast the world and return the first entity the ray hits. Fire a ray into the world from * start to end, if the ray hits an entity with a collision component, it returns a * {@link RaycastResult}, otherwise returns null. * * @param {Vec3} start - The world space point where the ray starts. * @param {Vec3} end - The world space point where the ray ends. * @param {object} [options] - The additional options for the raycasting. * @param {number} [options.filterCollisionGroup] - Collision group to apply to the raycast. * @param {number} [options.filterCollisionMask] - Collision mask to apply to the raycast. * @param {boolean} [options.hitBackFaces] - Whether the ray can hit the back faces of mesh * colliders, which face away from the ray: the far side of a closed mesh, or the first surface * met by a ray starting inside one. A back-face hit reports a normal flipped to face the start * of the ray. Other collision shapes never report back-face hits. Defaults to true. * @param {any[]} [options.filterTags] - Tags filters. Defined the same way as a {@link Tags#has} * query but within an array. * @param {Function} [options.filterCallback] - Custom function to use to filter entities. * Must return true to proceed with result. Takes one argument: the entity to evaluate. * * @returns {RaycastResult|null} The result of the raycasting, or null if there was no hit or * no physics backend is installed. */ raycastFirst(start: Vec3, end: Vec3, options?: { filterCollisionGroup?: number; filterCollisionMask?: number; hitBackFaces?: boolean; filterTags?: any[]; filterCallback?: Function; }): RaycastResult | null; /** * Raycast the world and return all entities the ray hits. It returns an array of * {@link RaycastResult}, one for each hit. If no hits are detected, the returned array will be * of length 0. Results are returned in no particular order unless `options.sort` is true, in * which case they are sorted by distance with the closest first. * * @param {Vec3} start - The world space point where the ray starts. * @param {Vec3} end - The world space point where the ray ends. * @param {object} [options] - The additional options for the raycasting. * @param {boolean} [options.sort] - Whether to sort raycast results based on distance with closest * first. Defaults to false. * @param {number} [options.filterCollisionGroup] - Collision group to apply to the raycast. * @param {number} [options.filterCollisionMask] - Collision mask to apply to the raycast. * @param {boolean} [options.hitBackFaces] - Whether the ray can hit the back faces of mesh * colliders, which face away from the ray: the far side of a closed mesh, or the first surface * met by a ray starting inside one. A back-face hit reports a normal flipped to face the start * of the ray. Other collision shapes never report back-face hits. Defaults to true. * @param {any[]} [options.filterTags] - Tags filters. Defined the same way as a {@link Tags#has} * query but within an array. * @param {Function} [options.filterCallback] - Custom function to use to filter entities. * Must return true to proceed with result. Takes the entity to evaluate as argument. * * @returns {RaycastResult[]} An array of raycast hit results (0 length if there were no hits * or no physics backend is installed). * * @example * // Return all results of a raycast between 0, 2, 2 and 0, -2, -2 * const hits = this.app.systems.rigidbody.raycastAll(new Vec3(0, 2, 2), new Vec3(0, -2, -2)); * @example * // Return all results of a raycast between 0, 2, 2 and 0, -2, -2 * // where hit entity is tagged with `bird` OR `mammal` * const hits = this.app.systems.rigidbody.raycastAll(new Vec3(0, 2, 2), new Vec3(0, -2, -2), { * filterTags: [ "bird", "mammal" ] * }); * @example * // Return all results of a raycast between 0, 2, 2 and 0, -2, -2 * // where hit entity has a `camera` component * const hits = this.app.systems.rigidbody.raycastAll(new Vec3(0, 2, 2), new Vec3(0, -2, -2), { * filterCallback: (entity) => entity && entity.camera * }); * @example * // Return all results of a raycast between 0, 2, 2 and 0, -2, -2, skipping the back faces * // of mesh colliders so a ray through a closed mesh hits it only where it enters * const hits = this.app.systems.rigidbody.raycastAll(new Vec3(0, 2, 2), new Vec3(0, -2, -2), { * hitBackFaces: false * }); * @example * // Return all results of a raycast between 0, 2, 2 and 0, -2, -2 * // where hit entity is tagged with (`carnivore` AND `mammal`) OR (`carnivore` AND `reptile`) * // and the entity has an `anim` component * const hits = this.app.systems.rigidbody.raycastAll(new Vec3(0, 2, 2), new Vec3(0, -2, -2), { * filterTags: [ * [ "carnivore", "mammal" ], * [ "carnivore", "reptile" ] * ], * filterCallback: (entity) => entity && entity.anim * }); */ raycastAll(start: Vec3, end: Vec3, options?: { sort?: boolean; filterCollisionGroup?: number; filterCollisionMask?: number; hitBackFaces?: boolean; filterTags?: any[]; filterCallback?: Function; }): RaycastResult[]; /** * Stores a collision between the entity and other in the contacts map and returns true if it * is a new collision. * * @param {Entity} entity - The entity. * @param {Entity} other - The entity that collides with the first entity. * @returns {boolean} True if this is a new collision, false otherwise. * @private */ private _storeCollision; /** * Allocates a pooled contact point that is the given one seen from the other body's * perspective: the points swap sides and the normal flips, so that it points away from body * A's surface just as the forward normal points away from body B's. * * @param {ContactPoint} forward - The contact point from body A's perspective. * @returns {ContactPoint} The reversed contact point. * @private */ private _createReverseContactPoint; /** * Allocates a pooled result for the global contact event from a contact point. * * @param {Entity} a - The first entity involved in the contact. * @param {Entity} b - The second entity involved in the contact. * @param {ContactPoint} contactPoint - The contact point, from the first entity's perspective. * @returns {SingleContactResult} The result. * @private */ private _createSingleContactResult; /** * Allocates a pooled result for the contact events of one entity. * * @param {Entity} other - The other entity involved in the contact. * @param {ContactPoint[]} contacts - The contact points, from the entity's perspective. * @returns {ContactResult} The result. * @private */ private _createContactResult; /** * Removes collisions that no longer exist from the collisions list and fires collisionend * events to the related entities. * * @private */ private _cleanOldCollisions; /** * Removes any stored collision keyed to the given entity. Called when a collision component is * removed so the persistent collisions map does not retain a destroyed entity. A new entity * that later reuses the same GUID (for example after reloading the same scene) would otherwise * inherit the stale entry and never fire `triggerleave` / `collisionend`, because the cached * entity no longer has a trigger or body. * * @param {Entity} entity - The entity whose stored collision should be removed. * @ignore */ clearEntityCollisions(entity: Entity): void; /** * Returns true if the entity has a contact event attached and false otherwise. * * @param {Entity} entity - Entity to test. * @returns {boolean} True if the entity has a contact and false otherwise. * @private */ private _hasContactEvent; /** * Called through the contact listener when the physics backend begins a contact pass. * * @private */ private onContactsBegin; /** * Called through the contact listener for each contacting pair the physics backend reports. * Fires the trigger and collision events. * * @param {PhysicsContactPair} pair - The contacting pair. Only valid during the call. * @private */ private onContactPair; /** * Called through the contact listener when the physics backend ends a contact pass. Fires * collisionend/triggerleave events for lost contacts and frees the pooled results. * * @private */ private onContactsEnd; /** * Advances the physics simulation by dt seconds. Synchronizes triggers, compound shapes and * kinematic bodies from their entities, steps the backend in fixed-length substeps (up to a * maximum number per call), writes the resulting transforms of dynamic bodies back to their * entities and fires contact and trigger events. * * The system calls this once per frame with the frame delta time multiplied by * {@link RigidBodyComponentSystem#timeScale}, unless that is 0. Call it directly to step the * simulation manually: to advance it while paused, to fast forward it by stepping several * times in one frame, or to drive it from a custom time source. Automatic stepping continues * while timeScale is above 0, so calling this every frame as well advances the simulation * twice per frame. Set timeScale to 0 first when taking over stepping entirely. The delta is * used as given, without applying timeScale. Does nothing when no physics backend is * installed. * * @param {number} dt - The amount of time to advance the simulation by, in seconds. * @example * // Pause automatic stepping and advance the simulation by 1/60 s per key press * const physics = app.systems.rigidbody; * physics.timeScale = 0; * app.keyboard.on('keydown', (event) => { * if (event.key === KEY_SPACE) { * physics.step(1 / 60); * } * }); */ step(dt: number): void; /** * Steps the simulation by the frame delta time scaled by * {@link RigidBodyComponentSystem#timeScale}, or skips the frame entirely when the scale is * 0. Registered on the application's update event when a physics backend is installed. * * @param {number} dt - The frame delta time in seconds. * @private */ private onUpdate; /** * Sets the world space gravity. Accepts either a Vec3 or three numbers. * * @param {number|Vec3} x - A Vec3 holding the gravity, or the x-component of the gravity. * @param {number} [y] - The y-component of the gravity. * @param {number} [z] - The z-component of the gravity. * @ignore * @deprecated Use {@link RigidBodyComponentSystem#gravity} instead. */ setGravity(x: number | Vec3, y?: number, z?: number): void; } /** * A ScreenComponent defines a rectangular area where user interfaces can be constructed. Screens * can either be 2D (screen space) or 3D (world space) - see {@link screenSpace}. It is possible to * create an {@link Entity} hierarchy underneath an Entity with a ScreenComponent to create complex * user interfaces using the following components: * * - {@link ButtonComponent} * - {@link ElementComponent} * - {@link LayoutChildComponent} * - {@link LayoutGroupComponent} * - {@link ScrollbarComponent} * - {@link ScrollViewComponent} * * You should never need to use the ScreenComponent constructor directly. To add a ScreenComponent * to an {@link Entity}, use {@link Entity#addComponent}: * * ```javascript * const entity = new Entity(); * entity.addComponent('screen', { * referenceResolution: new Vec2(1280, 720), * screenSpace: false * }); * ``` * * Once the ScreenComponent is added to the entity, you can access it via the {@link Entity#screen} * property: * * ```javascript * entity.screen.scaleBlend = 0.6; // Set the screen's scale blend to 0.6 * * console.log(entity.screen.scaleBlend); // Get the screen's scale blend and print it * ``` * * Relevant Engine API examples: * * - [Screen Space Screen](https://playcanvas.github.io/#/user-interface/screen-scaling) * - [World Space Screen](https://playcanvas.github.io/#/user-interface/world-ui) * * @hideconstructor * @category User Interface */ declare class ScreenComponent extends Component { /** * Create a new ScreenComponent. * * @param {ScreenComponentSystem} system - The ComponentSystem that created this Component. * @param {Entity} entity - The Entity that this Component is attached to. */ constructor(system: ScreenComponentSystem, entity: Entity); /** @private */ private _resolution; /** @private */ private _referenceResolution; /** @private */ private _scaleMode; /** @ignore */ scale: number; /** @private */ private _scaleBlend; /** @private */ private _priority; /** @private */ private _screenSpace; /** * If true, then elements inside this screen will not be rendered when outside of the screen * (only valid when {@link screenSpace} is true). * * @type {boolean} */ cull: boolean; /** @private */ private _screenMatrix; /** @private */ private _elements; /** * Set the drawOrder of each child {@link ElementComponent} so that ElementComponents which are * last in the hierarchy are rendered on top. Draw Order sync is queued and will be updated by * the next update loop. */ syncDrawOrder(): void; _recurseDrawOrderSync(e: any, i: any): any; _processDrawOrderSync(): void; _calcProjectionMatrix(): void; _updateScale(): void; _calcScale(resolution: any, referenceResolution: any): number; _onResize(width: any, height: any): void; /** * Sets the width and height of the ScreenComponent. When {@link screenSpace} is true, the * resolution will always be equal to {@link GraphicsDevice#width} by * {@link GraphicsDevice#height}. * * @type {Vec2} */ set resolution(value: Vec2); /** * Gets the width and height of the ScreenComponent. * * @type {Vec2} */ get resolution(): Vec2; _bindElement(element: any): void; _unbindElement(element: any): void; onBeforeRemove(): void; /** * Sets the resolution that the ScreenComponent is designed for. This is only taken into * account when {@link screenSpace} is true and {@link scaleMode} is {@link SCALEMODE_BLEND}. * If the actual resolution is different, then the ScreenComponent will be scaled according to * the {@link scaleBlend} value. * * @type {Vec2} */ set referenceResolution(value: Vec2); /** * Gets the resolution that the ScreenComponent is designed for. * * @type {Vec2} */ get referenceResolution(): Vec2; /** * Sets whether the ScreenComponent will render its child {@link ElementComponent}s in screen * space instead of world space. Enable this to create 2D user interfaces. Defaults to false. * * @type {boolean} */ set screenSpace(value: boolean); /** * Gets whether the ScreenComponent will render its child {@link ElementComponent}s in screen * space instead of world space. * * @type {boolean} */ get screenSpace(): boolean; /** * Sets the scale mode. Can either be {@link SCALEMODE_NONE} or {@link SCALEMODE_BLEND}. See * the description of {@link referenceResolution} for more information. Defaults to * {@link SCALEMODE_NONE}. * * @type {string} */ set scaleMode(value: string); /** * Gets the scale mode. * * @type {string} */ get scaleMode(): string; /** * Sets the scale blend. This is a value between 0 and 1 that is used when {@link scaleMode} is * equal to {@link SCALEMODE_BLEND}. Scales the ScreenComponent with width as a reference (when * value is 0), the height as a reference (when value is 1) or anything in between. Defaults to * 0.5. * * @type {number} */ set scaleBlend(value: number); /** * Gets the scale blend. * * @type {number} */ get scaleBlend(): number; /** * Sets the screen's render priority. Priority determines the order in which ScreenComponents * in the same layer are rendered. Number must be an integer between 0 and 127. Priority is set * into the top 8 bits of the {@link ElementComponent#drawOrder} property. Defaults to 0. * * @type {number} */ set priority(value: number); /** * Gets the screen's render priority. * * @type {number} */ get priority(): number; } /** * A ordered list-type data structure that can provide item look up by key and can also return a list. * * @ignore */ declare class IndexedList { /** * @type {object[]} * @private */ private _list; /** * @type {Object} * @private */ private _index; /** * Add a new item into the list with an index key. * * @param {string} key - Key used to look up item in index. * @param {object} item - Item to be stored. */ push(key: string, item: object): void; /** * Test whether a key has been added to the index. * * @param {string} key - The key to test. * @returns {boolean} Returns true if key is in the index, false if not. */ has(key: string): boolean; /** * Return the item indexed by a key. * * @param {string} key - The key of the item to retrieve. * @returns {object|null} The item stored at key. Returns null if key is not in the index. */ get(key: string): object | null; /** * Remove the item indexed by key from the list. * * @param {string} key - The key at which to remove the item. * @returns {boolean} Returns true if the key exists and an item was removed, returns false if * no item was removed. */ remove(key: string): boolean; /** * Returns the list of items. * * @returns {object[]} The list of items. */ list(): object[]; /** * Remove all items from the list. */ clear(): void; } /** * Options of the `screen` component accepted by {@link ScreenComponentSystem} that differ from the * properties of {@link ScreenComponent}. Each replaces the same-named property of the options that * {@link Entity#addComponent} derives from the component class; see * {@link ComponentOptionsOverrides}. */ type ScreenComponentOptionsOverrides = { /** * - Same as * {@link ScreenComponent#referenceResolution}, also accepting an `[width, height]` array. */ referenceResolution?: Vec2 | number[]; /** * - Same as {@link ScreenComponent#resolution}, also * accepting an `[width, height]` array. */ resolution?: Vec2 | number[]; }; /** * @import { AppBase } from '../../app-base.js' * @import { Entity } from '../../entity.js' */ /** * Options of the `screen` component accepted by {@link ScreenComponentSystem} that differ from the * properties of {@link ScreenComponent}. Each replaces the same-named property of the options that * {@link Entity#addComponent} derives from the component class; see * {@link ComponentOptionsOverrides}. * * @typedef {object} ScreenComponentOptionsOverrides * @property {Vec2 | number[]} [referenceResolution] - Same as * {@link ScreenComponent#referenceResolution}, also accepting an `[width, height]` array. * @property {Vec2 | number[]} [resolution] - Same as {@link ScreenComponent#resolution}, also * accepting an `[width, height]` array. * @ignore */ /** * Manages the {@link ScreenComponent}s of an application. Reach it through `app.systems.screen`; * components are created with {@link Entity#addComponent}, never by calling the system directly. * * @category User Interface */ declare class ScreenComponentSystem extends ComponentSystem { id: string; ComponentType: typeof ScreenComponent; windowResolution: Vec2; _drawOrderSyncQueue: IndexedList; initializeComponentData(component: any, data: any, properties: any): void; _updateDescendantElements(entity: any, screenEntity: any): void; _onUpdate(dt: any): void; _onResize(width: any, height: any): void; cloneComponent(entity: any, clone: any): Component; onBeforeRemove(entity: any, component: any): void; processDrawOrderSyncQueue(): void; queueDrawOrderSync(id: any, fn: any, scope: any): void; } /** * Helper class used to hold an array of items in a specific order. This array is safe to modify * while we loop through it. The class assumes that it holds objects that need to be sorted based * on one of their fields. * * @ignore */ declare class SortedLoopArray { /** * Create a new SortedLoopArray instance. * * @param {object} args - Arguments. * @param {string} args.sortBy - The name of the field that each element in the array is going * to be sorted by. * @example * const array = new SortedLoopArray({ sortBy: 'priority' }); * array.insert(item); // adds item to the right slot based on item.priority * array.append(item); // adds item to the end of the array * array.remove(item); // removes item from array * for (array.loopIndex = 0; array.loopIndex < array.length; array.loopIndex++) { * // do things with array elements * // safe to remove and add elements into the array while looping * } */ constructor(args: { sortBy: string; }); /** * The internal array that holds the actual array elements. * * @type {object[]} */ items: object[]; /** * The number of elements in the array. */ length: number; /** * The current index used to loop through the array. This gets modified if we add or remove * elements from the array while looping. See the example to see how to loop through this * array. */ loopIndex: number; /** @private */ private _sortBy; /** @private */ private _sortHandler; /** * Searches for the right spot to insert the specified item. * * @param {object} item - The item. * @returns {number} The index where to insert the item. * @private */ private _binarySearch; _doSort(a: any, b: any): number; /** * Inserts the specified item into the array at the right index based on the 'sortBy' field * passed into the constructor. This also adjusts the loopIndex accordingly. * * @param {object} item - The item to insert. */ insert(item: object): void; /** * Appends the specified item to the end of the array. Faster than insert() as it does not * binary search for the right index. This also adjusts the loopIndex accordingly. * * @param {object} item - The item to append. */ append(item: object): void; /** * Removes the specified item from the array. * * @param {object} item - The item to remove. */ remove(item: object): void; /** * Sorts elements in the array based on the 'sortBy' field passed into the constructor. This * also updates the loopIndex if we are currently looping. * * WARNING: Be careful if you are sorting while iterating because if after sorting the array * element that you are currently processing is moved behind other elements then you might end * up iterating over elements more than once! */ sort(): void; } /** * @import { ScriptComponentSystem } from './system.js' * @import { Script } from '../../script/script.js' */ /** * The ScriptComponent enables an {@link Entity} to have custom behavior by attaching scripts * written in JavaScript (or TypeScript). * * You should never need to use the ScriptComponent constructor directly. To add a * ScriptComponent to an {@link Entity}, use {@link Entity#addComponent}: * * ```javascript * const entity = new Entity(); * entity.addComponent('script'); * ``` * * Once the ScriptComponent is added to the entity, you can access it via the * {@link Entity#script} property: * * ```javascript * // Option 1: Add a script using the name registered in the ScriptRegistry * entity.script.create('cameraControls'); * * // Option 2: Add a script using the script class * entity.script.create(CameraControls); * ``` * * For more details on scripting see the [Scripting Section](https://developer.playcanvas.com/user-manual/scripting/) * of the User Manual. * * @hideconstructor * @category Script */ declare class ScriptComponent extends Component { /** * Fired when a {@link Script} instance is created and attached to the script component. * This event is available in two forms. They are as follows: * * 1. `create` - Fired when a script instance is created. The name of the script type and the * script type instance are passed as arguments. * 2. `create:[name]` - Fired when a script instance is created that has the specified script * type name. The script instance is passed as an argument to the handler. * * @event * @example * entity.script.on('create', (name, scriptInstance) => { * console.log(`Instance of script '${name}' created`); * }); * @example * entity.script.on('create:player', (scriptInstance) => { * console.log(`Instance of script 'player' created`); * }); */ static EVENT_CREATE: string; /** * Fired when a {@link Script} instance is destroyed and removed from the script component. * This event is available in two forms. They are as follows: * * 1. `destroy` - Fired when a script instance is destroyed. The name of the script type and * the script type instance are passed as arguments. * 2. `destroy:[name]` - Fired when a script instance is destroyed that has the specified * script type name. The script instance is passed as an argument. * * @event * @example * entity.script.on('destroy', (name, scriptInstance) => { * console.log(`Instance of script '${name}' destroyed`); * }); * @example * entity.script.on('destroy:player', (scriptInstance) => { * console.log(`Instance of script 'player' destroyed`); * }); */ static EVENT_DESTROY: string; /** * Fired when the script component becomes enabled. This event does not take into account the * enabled state of the entity or any of its ancestors. * * @event * @example * entity.script.on('enable', () => { * console.log(`Script component of entity '${entity.name}' has been enabled`); * }); */ static EVENT_ENABLE: string; /** * Fired when the script component becomes disabled. This event does not take into account the * enabled state of the entity or any of its ancestors. * * @event * @example * entity.script.on('disable', () => { * console.log(`Script component of entity '${entity.name}' has been disabled`); * }); */ static EVENT_DISABLE: string; /** * Fired when the script component has been removed from its entity. * * @event * @example * entity.script.on('remove', () => { * console.log(`Script component removed from entity '${entity.name}'`); * }); */ static EVENT_REMOVE: string; /** * Fired when the script component changes state to enabled or disabled. The handler is passed * the new boolean enabled state of the script component. This event does not take into account * the enabled state of the entity or any of its ancestors. * * @event * @example * entity.script.on('state', (enabled) => { * console.log(`Script component of entity '${entity.name}' changed state to '${enabled}'`); * }); */ static EVENT_STATE: string; /** * Fired when the index of a {@link Script} instance is changed in the script component. * This event is available in two forms. They are as follows: * * 1. `move` - Fired when a script instance is moved. The name of the script type, the script * type instance, the new index and the old index are passed as arguments. * 2. `move:[name]` - Fired when a specifically named script instance is moved. The script * instance, the new index and the old index are passed as arguments. * * @event * @example * entity.script.on('move', (name, scriptInstance, newIndex, oldIndex) => { * console.log(`Script '${name}' moved from index '${oldIndex}' to '${newIndex}'`); * }); * @example * entity.script.on('move:player', (scriptInstance, newIndex, oldIndex) => { * console.log(`Script 'player' moved from index '${oldIndex}' to '${newIndex}'`); * }); */ static EVENT_MOVE: string; /** * Fired when a {@link Script} instance had an exception. The handler is passed the script * instance, the exception and the method name that the exception originated from. * * @event * @example * entity.script.on('error', (scriptInstance, exception, methodName) => { * console.log(`Script error: ${exception} in method '${methodName}'`); * }); */ static EVENT_ERROR: string; /** * Create a new ScriptComponent instance. * * @param {ScriptComponentSystem} system - The ComponentSystem that created this Component. * @param {Entity} entity - The Entity that this Component is attached to. */ constructor(system: ScriptComponentSystem, entity: Entity); /** * A map of script name to initial component data. * * @type {Map} * @private */ private _attributeDataMap; /** * Holds all script instances for this component. * * @type {Script[]} * @private */ private _scripts; _updateList: SortedLoopArray; _postUpdateList: SortedLoopArray; _scriptsIndex: {}; _declarationOrder: any[]; _destroyedScripts: any[]; _destroyed: boolean; _scriptsData: readonly Script[]; _oldState: boolean; _beingEnabled: boolean; _isLoopingThroughScripts: boolean; _executionOrder: number; /** * Sets the array of all script instances attached to an entity. This array is read-only and * should not be modified by developer. * * @type {Script[]} */ set scripts(value: ReadonlyArray