add missing Filament headers for Windows
This commit is contained in:
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -1,850 +0,0 @@
|
||||
#ifndef __wglext_h_
|
||||
#define __wglext_h_ 1
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/*
|
||||
** Copyright (c) 2013-2017 The Khronos Group Inc.
|
||||
**
|
||||
** Permission is hereby granted, free of charge, to any person obtaining a
|
||||
** copy of this software and/or associated documentation files (the
|
||||
** "Materials"), to deal in the Materials without restriction, including
|
||||
** without limitation the rights to use, copy, modify, merge, publish,
|
||||
** distribute, sublicense, and/or sell copies of the Materials, and to
|
||||
** permit persons to whom the Materials are furnished to do so, subject to
|
||||
** the following conditions:
|
||||
**
|
||||
** The above copyright notice and this permission notice shall be included
|
||||
** in all copies or substantial portions of the Materials.
|
||||
**
|
||||
** THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
|
||||
** IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
|
||||
** CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
|
||||
** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
|
||||
** MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS.
|
||||
*/
|
||||
/*
|
||||
** This header is generated from the Khronos OpenGL / OpenGL ES XML
|
||||
** API Registry. The current version of the Registry, generator scripts
|
||||
** used to make the header, and the header can be found at
|
||||
** https://github.com/KhronosGroup/OpenGL-Registry
|
||||
*/
|
||||
|
||||
#if defined(_WIN32) && !defined(APIENTRY) && !defined(__CYGWIN__) && !defined(__SCITECH_SNAP__)
|
||||
#define WIN32_LEAN_AND_MEAN 1
|
||||
#include <windows.h>
|
||||
#endif
|
||||
|
||||
#define WGL_WGLEXT_VERSION 20171125
|
||||
|
||||
/* Generated C header for:
|
||||
* API: wgl
|
||||
* Versions considered: .*
|
||||
* Versions emitted: _nomatch_^
|
||||
* Default extensions included: wgl
|
||||
* Additional extensions included: _nomatch_^
|
||||
* Extensions removed: _nomatch_^
|
||||
*/
|
||||
|
||||
#ifndef WGL_ARB_buffer_region
|
||||
#define WGL_ARB_buffer_region 1
|
||||
#define WGL_FRONT_COLOR_BUFFER_BIT_ARB 0x00000001
|
||||
#define WGL_BACK_COLOR_BUFFER_BIT_ARB 0x00000002
|
||||
#define WGL_DEPTH_BUFFER_BIT_ARB 0x00000004
|
||||
#define WGL_STENCIL_BUFFER_BIT_ARB 0x00000008
|
||||
typedef HANDLE (WINAPI * PFNWGLCREATEBUFFERREGIONARBPROC) (HDC hDC, int iLayerPlane, UINT uType);
|
||||
typedef VOID (WINAPI * PFNWGLDELETEBUFFERREGIONARBPROC) (HANDLE hRegion);
|
||||
typedef BOOL (WINAPI * PFNWGLSAVEBUFFERREGIONARBPROC) (HANDLE hRegion, int x, int y, int width, int height);
|
||||
typedef BOOL (WINAPI * PFNWGLRESTOREBUFFERREGIONARBPROC) (HANDLE hRegion, int x, int y, int width, int height, int xSrc, int ySrc);
|
||||
#ifdef WGL_WGLEXT_PROTOTYPES
|
||||
HANDLE WINAPI wglCreateBufferRegionARB (HDC hDC, int iLayerPlane, UINT uType);
|
||||
VOID WINAPI wglDeleteBufferRegionARB (HANDLE hRegion);
|
||||
BOOL WINAPI wglSaveBufferRegionARB (HANDLE hRegion, int x, int y, int width, int height);
|
||||
BOOL WINAPI wglRestoreBufferRegionARB (HANDLE hRegion, int x, int y, int width, int height, int xSrc, int ySrc);
|
||||
#endif
|
||||
#endif /* WGL_ARB_buffer_region */
|
||||
|
||||
#ifndef WGL_ARB_context_flush_control
|
||||
#define WGL_ARB_context_flush_control 1
|
||||
#define WGL_CONTEXT_RELEASE_BEHAVIOR_ARB 0x2097
|
||||
#define WGL_CONTEXT_RELEASE_BEHAVIOR_NONE_ARB 0
|
||||
#define WGL_CONTEXT_RELEASE_BEHAVIOR_FLUSH_ARB 0x2098
|
||||
#endif /* WGL_ARB_context_flush_control */
|
||||
|
||||
#ifndef WGL_ARB_create_context
|
||||
#define WGL_ARB_create_context 1
|
||||
#define WGL_CONTEXT_DEBUG_BIT_ARB 0x00000001
|
||||
#define WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB 0x00000002
|
||||
#define WGL_CONTEXT_MAJOR_VERSION_ARB 0x2091
|
||||
#define WGL_CONTEXT_MINOR_VERSION_ARB 0x2092
|
||||
#define WGL_CONTEXT_LAYER_PLANE_ARB 0x2093
|
||||
#define WGL_CONTEXT_FLAGS_ARB 0x2094
|
||||
#define ERROR_INVALID_VERSION_ARB 0x2095
|
||||
typedef HGLRC (WINAPI * PFNWGLCREATECONTEXTATTRIBSARBPROC) (HDC hDC, HGLRC hShareContext, const int *attribList);
|
||||
#ifdef WGL_WGLEXT_PROTOTYPES
|
||||
HGLRC WINAPI wglCreateContextAttribsARB (HDC hDC, HGLRC hShareContext, const int *attribList);
|
||||
#endif
|
||||
#endif /* WGL_ARB_create_context */
|
||||
|
||||
#ifndef WGL_ARB_create_context_no_error
|
||||
#define WGL_ARB_create_context_no_error 1
|
||||
#define WGL_CONTEXT_OPENGL_NO_ERROR_ARB 0x31B3
|
||||
#endif /* WGL_ARB_create_context_no_error */
|
||||
|
||||
#ifndef WGL_ARB_create_context_profile
|
||||
#define WGL_ARB_create_context_profile 1
|
||||
#define WGL_CONTEXT_PROFILE_MASK_ARB 0x9126
|
||||
#define WGL_CONTEXT_CORE_PROFILE_BIT_ARB 0x00000001
|
||||
#define WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB 0x00000002
|
||||
#define ERROR_INVALID_PROFILE_ARB 0x2096
|
||||
#endif /* WGL_ARB_create_context_profile */
|
||||
|
||||
#ifndef WGL_ARB_create_context_robustness
|
||||
#define WGL_ARB_create_context_robustness 1
|
||||
#define WGL_CONTEXT_ROBUST_ACCESS_BIT_ARB 0x00000004
|
||||
#define WGL_LOSE_CONTEXT_ON_RESET_ARB 0x8252
|
||||
#define WGL_CONTEXT_RESET_NOTIFICATION_STRATEGY_ARB 0x8256
|
||||
#define WGL_NO_RESET_NOTIFICATION_ARB 0x8261
|
||||
#endif /* WGL_ARB_create_context_robustness */
|
||||
|
||||
#ifndef WGL_ARB_extensions_string
|
||||
#define WGL_ARB_extensions_string 1
|
||||
typedef const char *(WINAPI * PFNWGLGETEXTENSIONSSTRINGARBPROC) (HDC hdc);
|
||||
#ifdef WGL_WGLEXT_PROTOTYPES
|
||||
const char *WINAPI wglGetExtensionsStringARB (HDC hdc);
|
||||
#endif
|
||||
#endif /* WGL_ARB_extensions_string */
|
||||
|
||||
#ifndef WGL_ARB_framebuffer_sRGB
|
||||
#define WGL_ARB_framebuffer_sRGB 1
|
||||
#define WGL_FRAMEBUFFER_SRGB_CAPABLE_ARB 0x20A9
|
||||
#endif /* WGL_ARB_framebuffer_sRGB */
|
||||
|
||||
#ifndef WGL_ARB_make_current_read
|
||||
#define WGL_ARB_make_current_read 1
|
||||
#define ERROR_INVALID_PIXEL_TYPE_ARB 0x2043
|
||||
#define ERROR_INCOMPATIBLE_DEVICE_CONTEXTS_ARB 0x2054
|
||||
typedef BOOL (WINAPI * PFNWGLMAKECONTEXTCURRENTARBPROC) (HDC hDrawDC, HDC hReadDC, HGLRC hglrc);
|
||||
typedef HDC (WINAPI * PFNWGLGETCURRENTREADDCARBPROC) (void);
|
||||
#ifdef WGL_WGLEXT_PROTOTYPES
|
||||
BOOL WINAPI wglMakeContextCurrentARB (HDC hDrawDC, HDC hReadDC, HGLRC hglrc);
|
||||
HDC WINAPI wglGetCurrentReadDCARB (void);
|
||||
#endif
|
||||
#endif /* WGL_ARB_make_current_read */
|
||||
|
||||
#ifndef WGL_ARB_multisample
|
||||
#define WGL_ARB_multisample 1
|
||||
#define WGL_SAMPLE_BUFFERS_ARB 0x2041
|
||||
#define WGL_SAMPLES_ARB 0x2042
|
||||
#endif /* WGL_ARB_multisample */
|
||||
|
||||
#ifndef WGL_ARB_pbuffer
|
||||
#define WGL_ARB_pbuffer 1
|
||||
DECLARE_HANDLE(HPBUFFERARB);
|
||||
#define WGL_DRAW_TO_PBUFFER_ARB 0x202D
|
||||
#define WGL_MAX_PBUFFER_PIXELS_ARB 0x202E
|
||||
#define WGL_MAX_PBUFFER_WIDTH_ARB 0x202F
|
||||
#define WGL_MAX_PBUFFER_HEIGHT_ARB 0x2030
|
||||
#define WGL_PBUFFER_LARGEST_ARB 0x2033
|
||||
#define WGL_PBUFFER_WIDTH_ARB 0x2034
|
||||
#define WGL_PBUFFER_HEIGHT_ARB 0x2035
|
||||
#define WGL_PBUFFER_LOST_ARB 0x2036
|
||||
typedef HPBUFFERARB (WINAPI * PFNWGLCREATEPBUFFERARBPROC) (HDC hDC, int iPixelFormat, int iWidth, int iHeight, const int *piAttribList);
|
||||
typedef HDC (WINAPI * PFNWGLGETPBUFFERDCARBPROC) (HPBUFFERARB hPbuffer);
|
||||
typedef int (WINAPI * PFNWGLRELEASEPBUFFERDCARBPROC) (HPBUFFERARB hPbuffer, HDC hDC);
|
||||
typedef BOOL (WINAPI * PFNWGLDESTROYPBUFFERARBPROC) (HPBUFFERARB hPbuffer);
|
||||
typedef BOOL (WINAPI * PFNWGLQUERYPBUFFERARBPROC) (HPBUFFERARB hPbuffer, int iAttribute, int *piValue);
|
||||
#ifdef WGL_WGLEXT_PROTOTYPES
|
||||
HPBUFFERARB WINAPI wglCreatePbufferARB (HDC hDC, int iPixelFormat, int iWidth, int iHeight, const int *piAttribList);
|
||||
HDC WINAPI wglGetPbufferDCARB (HPBUFFERARB hPbuffer);
|
||||
int WINAPI wglReleasePbufferDCARB (HPBUFFERARB hPbuffer, HDC hDC);
|
||||
BOOL WINAPI wglDestroyPbufferARB (HPBUFFERARB hPbuffer);
|
||||
BOOL WINAPI wglQueryPbufferARB (HPBUFFERARB hPbuffer, int iAttribute, int *piValue);
|
||||
#endif
|
||||
#endif /* WGL_ARB_pbuffer */
|
||||
|
||||
#ifndef WGL_ARB_pixel_format
|
||||
#define WGL_ARB_pixel_format 1
|
||||
#define WGL_NUMBER_PIXEL_FORMATS_ARB 0x2000
|
||||
#define WGL_DRAW_TO_WINDOW_ARB 0x2001
|
||||
#define WGL_DRAW_TO_BITMAP_ARB 0x2002
|
||||
#define WGL_ACCELERATION_ARB 0x2003
|
||||
#define WGL_NEED_PALETTE_ARB 0x2004
|
||||
#define WGL_NEED_SYSTEM_PALETTE_ARB 0x2005
|
||||
#define WGL_SWAP_LAYER_BUFFERS_ARB 0x2006
|
||||
#define WGL_SWAP_METHOD_ARB 0x2007
|
||||
#define WGL_NUMBER_OVERLAYS_ARB 0x2008
|
||||
#define WGL_NUMBER_UNDERLAYS_ARB 0x2009
|
||||
#define WGL_TRANSPARENT_ARB 0x200A
|
||||
#define WGL_TRANSPARENT_RED_VALUE_ARB 0x2037
|
||||
#define WGL_TRANSPARENT_GREEN_VALUE_ARB 0x2038
|
||||
#define WGL_TRANSPARENT_BLUE_VALUE_ARB 0x2039
|
||||
#define WGL_TRANSPARENT_ALPHA_VALUE_ARB 0x203A
|
||||
#define WGL_TRANSPARENT_INDEX_VALUE_ARB 0x203B
|
||||
#define WGL_SHARE_DEPTH_ARB 0x200C
|
||||
#define WGL_SHARE_STENCIL_ARB 0x200D
|
||||
#define WGL_SHARE_ACCUM_ARB 0x200E
|
||||
#define WGL_SUPPORT_GDI_ARB 0x200F
|
||||
#define WGL_SUPPORT_OPENGL_ARB 0x2010
|
||||
#define WGL_DOUBLE_BUFFER_ARB 0x2011
|
||||
#define WGL_STEREO_ARB 0x2012
|
||||
#define WGL_PIXEL_TYPE_ARB 0x2013
|
||||
#define WGL_COLOR_BITS_ARB 0x2014
|
||||
#define WGL_RED_BITS_ARB 0x2015
|
||||
#define WGL_RED_SHIFT_ARB 0x2016
|
||||
#define WGL_GREEN_BITS_ARB 0x2017
|
||||
#define WGL_GREEN_SHIFT_ARB 0x2018
|
||||
#define WGL_BLUE_BITS_ARB 0x2019
|
||||
#define WGL_BLUE_SHIFT_ARB 0x201A
|
||||
#define WGL_ALPHA_BITS_ARB 0x201B
|
||||
#define WGL_ALPHA_SHIFT_ARB 0x201C
|
||||
#define WGL_ACCUM_BITS_ARB 0x201D
|
||||
#define WGL_ACCUM_RED_BITS_ARB 0x201E
|
||||
#define WGL_ACCUM_GREEN_BITS_ARB 0x201F
|
||||
#define WGL_ACCUM_BLUE_BITS_ARB 0x2020
|
||||
#define WGL_ACCUM_ALPHA_BITS_ARB 0x2021
|
||||
#define WGL_DEPTH_BITS_ARB 0x2022
|
||||
#define WGL_STENCIL_BITS_ARB 0x2023
|
||||
#define WGL_AUX_BUFFERS_ARB 0x2024
|
||||
#define WGL_NO_ACCELERATION_ARB 0x2025
|
||||
#define WGL_GENERIC_ACCELERATION_ARB 0x2026
|
||||
#define WGL_FULL_ACCELERATION_ARB 0x2027
|
||||
#define WGL_SWAP_EXCHANGE_ARB 0x2028
|
||||
#define WGL_SWAP_COPY_ARB 0x2029
|
||||
#define WGL_SWAP_UNDEFINED_ARB 0x202A
|
||||
#define WGL_TYPE_RGBA_ARB 0x202B
|
||||
#define WGL_TYPE_COLORINDEX_ARB 0x202C
|
||||
typedef BOOL (WINAPI * PFNWGLGETPIXELFORMATATTRIBIVARBPROC) (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, int *piValues);
|
||||
typedef BOOL (WINAPI * PFNWGLGETPIXELFORMATATTRIBFVARBPROC) (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, FLOAT *pfValues);
|
||||
typedef BOOL (WINAPI * PFNWGLCHOOSEPIXELFORMATARBPROC) (HDC hdc, const int *piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats);
|
||||
#ifdef WGL_WGLEXT_PROTOTYPES
|
||||
BOOL WINAPI wglGetPixelFormatAttribivARB (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, int *piValues);
|
||||
BOOL WINAPI wglGetPixelFormatAttribfvARB (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, FLOAT *pfValues);
|
||||
BOOL WINAPI wglChoosePixelFormatARB (HDC hdc, const int *piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats);
|
||||
#endif
|
||||
#endif /* WGL_ARB_pixel_format */
|
||||
|
||||
#ifndef WGL_ARB_pixel_format_float
|
||||
#define WGL_ARB_pixel_format_float 1
|
||||
#define WGL_TYPE_RGBA_FLOAT_ARB 0x21A0
|
||||
#endif /* WGL_ARB_pixel_format_float */
|
||||
|
||||
#ifndef WGL_ARB_render_texture
|
||||
#define WGL_ARB_render_texture 1
|
||||
#define WGL_BIND_TO_TEXTURE_RGB_ARB 0x2070
|
||||
#define WGL_BIND_TO_TEXTURE_RGBA_ARB 0x2071
|
||||
#define WGL_TEXTURE_FORMAT_ARB 0x2072
|
||||
#define WGL_TEXTURE_TARGET_ARB 0x2073
|
||||
#define WGL_MIPMAP_TEXTURE_ARB 0x2074
|
||||
#define WGL_TEXTURE_RGB_ARB 0x2075
|
||||
#define WGL_TEXTURE_RGBA_ARB 0x2076
|
||||
#define WGL_NO_TEXTURE_ARB 0x2077
|
||||
#define WGL_TEXTURE_CUBE_MAP_ARB 0x2078
|
||||
#define WGL_TEXTURE_1D_ARB 0x2079
|
||||
#define WGL_TEXTURE_2D_ARB 0x207A
|
||||
#define WGL_MIPMAP_LEVEL_ARB 0x207B
|
||||
#define WGL_CUBE_MAP_FACE_ARB 0x207C
|
||||
#define WGL_TEXTURE_CUBE_MAP_POSITIVE_X_ARB 0x207D
|
||||
#define WGL_TEXTURE_CUBE_MAP_NEGATIVE_X_ARB 0x207E
|
||||
#define WGL_TEXTURE_CUBE_MAP_POSITIVE_Y_ARB 0x207F
|
||||
#define WGL_TEXTURE_CUBE_MAP_NEGATIVE_Y_ARB 0x2080
|
||||
#define WGL_TEXTURE_CUBE_MAP_POSITIVE_Z_ARB 0x2081
|
||||
#define WGL_TEXTURE_CUBE_MAP_NEGATIVE_Z_ARB 0x2082
|
||||
#define WGL_FRONT_LEFT_ARB 0x2083
|
||||
#define WGL_FRONT_RIGHT_ARB 0x2084
|
||||
#define WGL_BACK_LEFT_ARB 0x2085
|
||||
#define WGL_BACK_RIGHT_ARB 0x2086
|
||||
#define WGL_AUX0_ARB 0x2087
|
||||
#define WGL_AUX1_ARB 0x2088
|
||||
#define WGL_AUX2_ARB 0x2089
|
||||
#define WGL_AUX3_ARB 0x208A
|
||||
#define WGL_AUX4_ARB 0x208B
|
||||
#define WGL_AUX5_ARB 0x208C
|
||||
#define WGL_AUX6_ARB 0x208D
|
||||
#define WGL_AUX7_ARB 0x208E
|
||||
#define WGL_AUX8_ARB 0x208F
|
||||
#define WGL_AUX9_ARB 0x2090
|
||||
typedef BOOL (WINAPI * PFNWGLBINDTEXIMAGEARBPROC) (HPBUFFERARB hPbuffer, int iBuffer);
|
||||
typedef BOOL (WINAPI * PFNWGLRELEASETEXIMAGEARBPROC) (HPBUFFERARB hPbuffer, int iBuffer);
|
||||
typedef BOOL (WINAPI * PFNWGLSETPBUFFERATTRIBARBPROC) (HPBUFFERARB hPbuffer, const int *piAttribList);
|
||||
#ifdef WGL_WGLEXT_PROTOTYPES
|
||||
BOOL WINAPI wglBindTexImageARB (HPBUFFERARB hPbuffer, int iBuffer);
|
||||
BOOL WINAPI wglReleaseTexImageARB (HPBUFFERARB hPbuffer, int iBuffer);
|
||||
BOOL WINAPI wglSetPbufferAttribARB (HPBUFFERARB hPbuffer, const int *piAttribList);
|
||||
#endif
|
||||
#endif /* WGL_ARB_render_texture */
|
||||
|
||||
#ifndef WGL_ARB_robustness_application_isolation
|
||||
#define WGL_ARB_robustness_application_isolation 1
|
||||
#define WGL_CONTEXT_RESET_ISOLATION_BIT_ARB 0x00000008
|
||||
#endif /* WGL_ARB_robustness_application_isolation */
|
||||
|
||||
#ifndef WGL_ARB_robustness_share_group_isolation
|
||||
#define WGL_ARB_robustness_share_group_isolation 1
|
||||
#endif /* WGL_ARB_robustness_share_group_isolation */
|
||||
|
||||
#ifndef WGL_3DFX_multisample
|
||||
#define WGL_3DFX_multisample 1
|
||||
#define WGL_SAMPLE_BUFFERS_3DFX 0x2060
|
||||
#define WGL_SAMPLES_3DFX 0x2061
|
||||
#endif /* WGL_3DFX_multisample */
|
||||
|
||||
#ifndef WGL_3DL_stereo_control
|
||||
#define WGL_3DL_stereo_control 1
|
||||
#define WGL_STEREO_EMITTER_ENABLE_3DL 0x2055
|
||||
#define WGL_STEREO_EMITTER_DISABLE_3DL 0x2056
|
||||
#define WGL_STEREO_POLARITY_NORMAL_3DL 0x2057
|
||||
#define WGL_STEREO_POLARITY_INVERT_3DL 0x2058
|
||||
typedef BOOL (WINAPI * PFNWGLSETSTEREOEMITTERSTATE3DLPROC) (HDC hDC, UINT uState);
|
||||
#ifdef WGL_WGLEXT_PROTOTYPES
|
||||
BOOL WINAPI wglSetStereoEmitterState3DL (HDC hDC, UINT uState);
|
||||
#endif
|
||||
#endif /* WGL_3DL_stereo_control */
|
||||
|
||||
#ifndef WGL_AMD_gpu_association
|
||||
#define WGL_AMD_gpu_association 1
|
||||
#define WGL_GPU_VENDOR_AMD 0x1F00
|
||||
#define WGL_GPU_RENDERER_STRING_AMD 0x1F01
|
||||
#define WGL_GPU_OPENGL_VERSION_STRING_AMD 0x1F02
|
||||
#define WGL_GPU_FASTEST_TARGET_GPUS_AMD 0x21A2
|
||||
#define WGL_GPU_RAM_AMD 0x21A3
|
||||
#define WGL_GPU_CLOCK_AMD 0x21A4
|
||||
#define WGL_GPU_NUM_PIPES_AMD 0x21A5
|
||||
#define WGL_GPU_NUM_SIMD_AMD 0x21A6
|
||||
#define WGL_GPU_NUM_RB_AMD 0x21A7
|
||||
#define WGL_GPU_NUM_SPI_AMD 0x21A8
|
||||
typedef UINT (WINAPI * PFNWGLGETGPUIDSAMDPROC) (UINT maxCount, UINT *ids);
|
||||
typedef INT (WINAPI * PFNWGLGETGPUINFOAMDPROC) (UINT id, int property, GLenum dataType, UINT size, void *data);
|
||||
typedef UINT (WINAPI * PFNWGLGETCONTEXTGPUIDAMDPROC) (HGLRC hglrc);
|
||||
typedef HGLRC (WINAPI * PFNWGLCREATEASSOCIATEDCONTEXTAMDPROC) (UINT id);
|
||||
typedef HGLRC (WINAPI * PFNWGLCREATEASSOCIATEDCONTEXTATTRIBSAMDPROC) (UINT id, HGLRC hShareContext, const int *attribList);
|
||||
typedef BOOL (WINAPI * PFNWGLDELETEASSOCIATEDCONTEXTAMDPROC) (HGLRC hglrc);
|
||||
typedef BOOL (WINAPI * PFNWGLMAKEASSOCIATEDCONTEXTCURRENTAMDPROC) (HGLRC hglrc);
|
||||
typedef HGLRC (WINAPI * PFNWGLGETCURRENTASSOCIATEDCONTEXTAMDPROC) (void);
|
||||
typedef VOID (WINAPI * PFNWGLBLITCONTEXTFRAMEBUFFERAMDPROC) (HGLRC dstCtx, GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter);
|
||||
#ifdef WGL_WGLEXT_PROTOTYPES
|
||||
UINT WINAPI wglGetGPUIDsAMD (UINT maxCount, UINT *ids);
|
||||
INT WINAPI wglGetGPUInfoAMD (UINT id, int property, GLenum dataType, UINT size, void *data);
|
||||
UINT WINAPI wglGetContextGPUIDAMD (HGLRC hglrc);
|
||||
HGLRC WINAPI wglCreateAssociatedContextAMD (UINT id);
|
||||
HGLRC WINAPI wglCreateAssociatedContextAttribsAMD (UINT id, HGLRC hShareContext, const int *attribList);
|
||||
BOOL WINAPI wglDeleteAssociatedContextAMD (HGLRC hglrc);
|
||||
BOOL WINAPI wglMakeAssociatedContextCurrentAMD (HGLRC hglrc);
|
||||
HGLRC WINAPI wglGetCurrentAssociatedContextAMD (void);
|
||||
VOID WINAPI wglBlitContextFramebufferAMD (HGLRC dstCtx, GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter);
|
||||
#endif
|
||||
#endif /* WGL_AMD_gpu_association */
|
||||
|
||||
#ifndef WGL_ATI_pixel_format_float
|
||||
#define WGL_ATI_pixel_format_float 1
|
||||
#define WGL_TYPE_RGBA_FLOAT_ATI 0x21A0
|
||||
#endif /* WGL_ATI_pixel_format_float */
|
||||
|
||||
#ifndef WGL_EXT_colorspace
|
||||
#define WGL_EXT_colorspace 1
|
||||
#define WGL_COLORSPACE_EXT 0x3087
|
||||
#define WGL_COLORSPACE_SRGB_EXT 0x3089
|
||||
#define WGL_COLORSPACE_LINEAR_EXT 0x308A
|
||||
#endif /* WGL_EXT_colorspace */
|
||||
|
||||
#ifndef WGL_EXT_create_context_es2_profile
|
||||
#define WGL_EXT_create_context_es2_profile 1
|
||||
#define WGL_CONTEXT_ES2_PROFILE_BIT_EXT 0x00000004
|
||||
#endif /* WGL_EXT_create_context_es2_profile */
|
||||
|
||||
#ifndef WGL_EXT_create_context_es_profile
|
||||
#define WGL_EXT_create_context_es_profile 1
|
||||
#define WGL_CONTEXT_ES_PROFILE_BIT_EXT 0x00000004
|
||||
#endif /* WGL_EXT_create_context_es_profile */
|
||||
|
||||
#ifndef WGL_EXT_depth_float
|
||||
#define WGL_EXT_depth_float 1
|
||||
#define WGL_DEPTH_FLOAT_EXT 0x2040
|
||||
#endif /* WGL_EXT_depth_float */
|
||||
|
||||
#ifndef WGL_EXT_display_color_table
|
||||
#define WGL_EXT_display_color_table 1
|
||||
typedef GLboolean (WINAPI * PFNWGLCREATEDISPLAYCOLORTABLEEXTPROC) (GLushort id);
|
||||
typedef GLboolean (WINAPI * PFNWGLLOADDISPLAYCOLORTABLEEXTPROC) (const GLushort *table, GLuint length);
|
||||
typedef GLboolean (WINAPI * PFNWGLBINDDISPLAYCOLORTABLEEXTPROC) (GLushort id);
|
||||
typedef VOID (WINAPI * PFNWGLDESTROYDISPLAYCOLORTABLEEXTPROC) (GLushort id);
|
||||
#ifdef WGL_WGLEXT_PROTOTYPES
|
||||
GLboolean WINAPI wglCreateDisplayColorTableEXT (GLushort id);
|
||||
GLboolean WINAPI wglLoadDisplayColorTableEXT (const GLushort *table, GLuint length);
|
||||
GLboolean WINAPI wglBindDisplayColorTableEXT (GLushort id);
|
||||
VOID WINAPI wglDestroyDisplayColorTableEXT (GLushort id);
|
||||
#endif
|
||||
#endif /* WGL_EXT_display_color_table */
|
||||
|
||||
#ifndef WGL_EXT_extensions_string
|
||||
#define WGL_EXT_extensions_string 1
|
||||
typedef const char *(WINAPI * PFNWGLGETEXTENSIONSSTRINGEXTPROC) (void);
|
||||
#ifdef WGL_WGLEXT_PROTOTYPES
|
||||
const char *WINAPI wglGetExtensionsStringEXT (void);
|
||||
#endif
|
||||
#endif /* WGL_EXT_extensions_string */
|
||||
|
||||
#ifndef WGL_EXT_framebuffer_sRGB
|
||||
#define WGL_EXT_framebuffer_sRGB 1
|
||||
#define WGL_FRAMEBUFFER_SRGB_CAPABLE_EXT 0x20A9
|
||||
#endif /* WGL_EXT_framebuffer_sRGB */
|
||||
|
||||
#ifndef WGL_EXT_make_current_read
|
||||
#define WGL_EXT_make_current_read 1
|
||||
#define ERROR_INVALID_PIXEL_TYPE_EXT 0x2043
|
||||
typedef BOOL (WINAPI * PFNWGLMAKECONTEXTCURRENTEXTPROC) (HDC hDrawDC, HDC hReadDC, HGLRC hglrc);
|
||||
typedef HDC (WINAPI * PFNWGLGETCURRENTREADDCEXTPROC) (void);
|
||||
#ifdef WGL_WGLEXT_PROTOTYPES
|
||||
BOOL WINAPI wglMakeContextCurrentEXT (HDC hDrawDC, HDC hReadDC, HGLRC hglrc);
|
||||
HDC WINAPI wglGetCurrentReadDCEXT (void);
|
||||
#endif
|
||||
#endif /* WGL_EXT_make_current_read */
|
||||
|
||||
#ifndef WGL_EXT_multisample
|
||||
#define WGL_EXT_multisample 1
|
||||
#define WGL_SAMPLE_BUFFERS_EXT 0x2041
|
||||
#define WGL_SAMPLES_EXT 0x2042
|
||||
#endif /* WGL_EXT_multisample */
|
||||
|
||||
#ifndef WGL_EXT_pbuffer
|
||||
#define WGL_EXT_pbuffer 1
|
||||
DECLARE_HANDLE(HPBUFFEREXT);
|
||||
#define WGL_DRAW_TO_PBUFFER_EXT 0x202D
|
||||
#define WGL_MAX_PBUFFER_PIXELS_EXT 0x202E
|
||||
#define WGL_MAX_PBUFFER_WIDTH_EXT 0x202F
|
||||
#define WGL_MAX_PBUFFER_HEIGHT_EXT 0x2030
|
||||
#define WGL_OPTIMAL_PBUFFER_WIDTH_EXT 0x2031
|
||||
#define WGL_OPTIMAL_PBUFFER_HEIGHT_EXT 0x2032
|
||||
#define WGL_PBUFFER_LARGEST_EXT 0x2033
|
||||
#define WGL_PBUFFER_WIDTH_EXT 0x2034
|
||||
#define WGL_PBUFFER_HEIGHT_EXT 0x2035
|
||||
typedef HPBUFFEREXT (WINAPI * PFNWGLCREATEPBUFFEREXTPROC) (HDC hDC, int iPixelFormat, int iWidth, int iHeight, const int *piAttribList);
|
||||
typedef HDC (WINAPI * PFNWGLGETPBUFFERDCEXTPROC) (HPBUFFEREXT hPbuffer);
|
||||
typedef int (WINAPI * PFNWGLRELEASEPBUFFERDCEXTPROC) (HPBUFFEREXT hPbuffer, HDC hDC);
|
||||
typedef BOOL (WINAPI * PFNWGLDESTROYPBUFFEREXTPROC) (HPBUFFEREXT hPbuffer);
|
||||
typedef BOOL (WINAPI * PFNWGLQUERYPBUFFEREXTPROC) (HPBUFFEREXT hPbuffer, int iAttribute, int *piValue);
|
||||
#ifdef WGL_WGLEXT_PROTOTYPES
|
||||
HPBUFFEREXT WINAPI wglCreatePbufferEXT (HDC hDC, int iPixelFormat, int iWidth, int iHeight, const int *piAttribList);
|
||||
HDC WINAPI wglGetPbufferDCEXT (HPBUFFEREXT hPbuffer);
|
||||
int WINAPI wglReleasePbufferDCEXT (HPBUFFEREXT hPbuffer, HDC hDC);
|
||||
BOOL WINAPI wglDestroyPbufferEXT (HPBUFFEREXT hPbuffer);
|
||||
BOOL WINAPI wglQueryPbufferEXT (HPBUFFEREXT hPbuffer, int iAttribute, int *piValue);
|
||||
#endif
|
||||
#endif /* WGL_EXT_pbuffer */
|
||||
|
||||
#ifndef WGL_EXT_pixel_format
|
||||
#define WGL_EXT_pixel_format 1
|
||||
#define WGL_NUMBER_PIXEL_FORMATS_EXT 0x2000
|
||||
#define WGL_DRAW_TO_WINDOW_EXT 0x2001
|
||||
#define WGL_DRAW_TO_BITMAP_EXT 0x2002
|
||||
#define WGL_ACCELERATION_EXT 0x2003
|
||||
#define WGL_NEED_PALETTE_EXT 0x2004
|
||||
#define WGL_NEED_SYSTEM_PALETTE_EXT 0x2005
|
||||
#define WGL_SWAP_LAYER_BUFFERS_EXT 0x2006
|
||||
#define WGL_SWAP_METHOD_EXT 0x2007
|
||||
#define WGL_NUMBER_OVERLAYS_EXT 0x2008
|
||||
#define WGL_NUMBER_UNDERLAYS_EXT 0x2009
|
||||
#define WGL_TRANSPARENT_EXT 0x200A
|
||||
#define WGL_TRANSPARENT_VALUE_EXT 0x200B
|
||||
#define WGL_SHARE_DEPTH_EXT 0x200C
|
||||
#define WGL_SHARE_STENCIL_EXT 0x200D
|
||||
#define WGL_SHARE_ACCUM_EXT 0x200E
|
||||
#define WGL_SUPPORT_GDI_EXT 0x200F
|
||||
#define WGL_SUPPORT_OPENGL_EXT 0x2010
|
||||
#define WGL_DOUBLE_BUFFER_EXT 0x2011
|
||||
#define WGL_STEREO_EXT 0x2012
|
||||
#define WGL_PIXEL_TYPE_EXT 0x2013
|
||||
#define WGL_COLOR_BITS_EXT 0x2014
|
||||
#define WGL_RED_BITS_EXT 0x2015
|
||||
#define WGL_RED_SHIFT_EXT 0x2016
|
||||
#define WGL_GREEN_BITS_EXT 0x2017
|
||||
#define WGL_GREEN_SHIFT_EXT 0x2018
|
||||
#define WGL_BLUE_BITS_EXT 0x2019
|
||||
#define WGL_BLUE_SHIFT_EXT 0x201A
|
||||
#define WGL_ALPHA_BITS_EXT 0x201B
|
||||
#define WGL_ALPHA_SHIFT_EXT 0x201C
|
||||
#define WGL_ACCUM_BITS_EXT 0x201D
|
||||
#define WGL_ACCUM_RED_BITS_EXT 0x201E
|
||||
#define WGL_ACCUM_GREEN_BITS_EXT 0x201F
|
||||
#define WGL_ACCUM_BLUE_BITS_EXT 0x2020
|
||||
#define WGL_ACCUM_ALPHA_BITS_EXT 0x2021
|
||||
#define WGL_DEPTH_BITS_EXT 0x2022
|
||||
#define WGL_STENCIL_BITS_EXT 0x2023
|
||||
#define WGL_AUX_BUFFERS_EXT 0x2024
|
||||
#define WGL_NO_ACCELERATION_EXT 0x2025
|
||||
#define WGL_GENERIC_ACCELERATION_EXT 0x2026
|
||||
#define WGL_FULL_ACCELERATION_EXT 0x2027
|
||||
#define WGL_SWAP_EXCHANGE_EXT 0x2028
|
||||
#define WGL_SWAP_COPY_EXT 0x2029
|
||||
#define WGL_SWAP_UNDEFINED_EXT 0x202A
|
||||
#define WGL_TYPE_RGBA_EXT 0x202B
|
||||
#define WGL_TYPE_COLORINDEX_EXT 0x202C
|
||||
typedef BOOL (WINAPI * PFNWGLGETPIXELFORMATATTRIBIVEXTPROC) (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, int *piAttributes, int *piValues);
|
||||
typedef BOOL (WINAPI * PFNWGLGETPIXELFORMATATTRIBFVEXTPROC) (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, int *piAttributes, FLOAT *pfValues);
|
||||
typedef BOOL (WINAPI * PFNWGLCHOOSEPIXELFORMATEXTPROC) (HDC hdc, const int *piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats);
|
||||
#ifdef WGL_WGLEXT_PROTOTYPES
|
||||
BOOL WINAPI wglGetPixelFormatAttribivEXT (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, int *piAttributes, int *piValues);
|
||||
BOOL WINAPI wglGetPixelFormatAttribfvEXT (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, int *piAttributes, FLOAT *pfValues);
|
||||
BOOL WINAPI wglChoosePixelFormatEXT (HDC hdc, const int *piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats);
|
||||
#endif
|
||||
#endif /* WGL_EXT_pixel_format */
|
||||
|
||||
#ifndef WGL_EXT_pixel_format_packed_float
|
||||
#define WGL_EXT_pixel_format_packed_float 1
|
||||
#define WGL_TYPE_RGBA_UNSIGNED_FLOAT_EXT 0x20A8
|
||||
#endif /* WGL_EXT_pixel_format_packed_float */
|
||||
|
||||
#ifndef WGL_EXT_swap_control
|
||||
#define WGL_EXT_swap_control 1
|
||||
typedef BOOL (WINAPI * PFNWGLSWAPINTERVALEXTPROC) (int interval);
|
||||
typedef int (WINAPI * PFNWGLGETSWAPINTERVALEXTPROC) (void);
|
||||
#ifdef WGL_WGLEXT_PROTOTYPES
|
||||
BOOL WINAPI wglSwapIntervalEXT (int interval);
|
||||
int WINAPI wglGetSwapIntervalEXT (void);
|
||||
#endif
|
||||
#endif /* WGL_EXT_swap_control */
|
||||
|
||||
#ifndef WGL_EXT_swap_control_tear
|
||||
#define WGL_EXT_swap_control_tear 1
|
||||
#endif /* WGL_EXT_swap_control_tear */
|
||||
|
||||
#ifndef WGL_I3D_digital_video_control
|
||||
#define WGL_I3D_digital_video_control 1
|
||||
#define WGL_DIGITAL_VIDEO_CURSOR_ALPHA_FRAMEBUFFER_I3D 0x2050
|
||||
#define WGL_DIGITAL_VIDEO_CURSOR_ALPHA_VALUE_I3D 0x2051
|
||||
#define WGL_DIGITAL_VIDEO_CURSOR_INCLUDED_I3D 0x2052
|
||||
#define WGL_DIGITAL_VIDEO_GAMMA_CORRECTED_I3D 0x2053
|
||||
typedef BOOL (WINAPI * PFNWGLGETDIGITALVIDEOPARAMETERSI3DPROC) (HDC hDC, int iAttribute, int *piValue);
|
||||
typedef BOOL (WINAPI * PFNWGLSETDIGITALVIDEOPARAMETERSI3DPROC) (HDC hDC, int iAttribute, const int *piValue);
|
||||
#ifdef WGL_WGLEXT_PROTOTYPES
|
||||
BOOL WINAPI wglGetDigitalVideoParametersI3D (HDC hDC, int iAttribute, int *piValue);
|
||||
BOOL WINAPI wglSetDigitalVideoParametersI3D (HDC hDC, int iAttribute, const int *piValue);
|
||||
#endif
|
||||
#endif /* WGL_I3D_digital_video_control */
|
||||
|
||||
#ifndef WGL_I3D_gamma
|
||||
#define WGL_I3D_gamma 1
|
||||
#define WGL_GAMMA_TABLE_SIZE_I3D 0x204E
|
||||
#define WGL_GAMMA_EXCLUDE_DESKTOP_I3D 0x204F
|
||||
typedef BOOL (WINAPI * PFNWGLGETGAMMATABLEPARAMETERSI3DPROC) (HDC hDC, int iAttribute, int *piValue);
|
||||
typedef BOOL (WINAPI * PFNWGLSETGAMMATABLEPARAMETERSI3DPROC) (HDC hDC, int iAttribute, const int *piValue);
|
||||
typedef BOOL (WINAPI * PFNWGLGETGAMMATABLEI3DPROC) (HDC hDC, int iEntries, USHORT *puRed, USHORT *puGreen, USHORT *puBlue);
|
||||
typedef BOOL (WINAPI * PFNWGLSETGAMMATABLEI3DPROC) (HDC hDC, int iEntries, const USHORT *puRed, const USHORT *puGreen, const USHORT *puBlue);
|
||||
#ifdef WGL_WGLEXT_PROTOTYPES
|
||||
BOOL WINAPI wglGetGammaTableParametersI3D (HDC hDC, int iAttribute, int *piValue);
|
||||
BOOL WINAPI wglSetGammaTableParametersI3D (HDC hDC, int iAttribute, const int *piValue);
|
||||
BOOL WINAPI wglGetGammaTableI3D (HDC hDC, int iEntries, USHORT *puRed, USHORT *puGreen, USHORT *puBlue);
|
||||
BOOL WINAPI wglSetGammaTableI3D (HDC hDC, int iEntries, const USHORT *puRed, const USHORT *puGreen, const USHORT *puBlue);
|
||||
#endif
|
||||
#endif /* WGL_I3D_gamma */
|
||||
|
||||
#ifndef WGL_I3D_genlock
|
||||
#define WGL_I3D_genlock 1
|
||||
#define WGL_GENLOCK_SOURCE_MULTIVIEW_I3D 0x2044
|
||||
#define WGL_GENLOCK_SOURCE_EXTERNAL_SYNC_I3D 0x2045
|
||||
#define WGL_GENLOCK_SOURCE_EXTERNAL_FIELD_I3D 0x2046
|
||||
#define WGL_GENLOCK_SOURCE_EXTERNAL_TTL_I3D 0x2047
|
||||
#define WGL_GENLOCK_SOURCE_DIGITAL_SYNC_I3D 0x2048
|
||||
#define WGL_GENLOCK_SOURCE_DIGITAL_FIELD_I3D 0x2049
|
||||
#define WGL_GENLOCK_SOURCE_EDGE_FALLING_I3D 0x204A
|
||||
#define WGL_GENLOCK_SOURCE_EDGE_RISING_I3D 0x204B
|
||||
#define WGL_GENLOCK_SOURCE_EDGE_BOTH_I3D 0x204C
|
||||
typedef BOOL (WINAPI * PFNWGLENABLEGENLOCKI3DPROC) (HDC hDC);
|
||||
typedef BOOL (WINAPI * PFNWGLDISABLEGENLOCKI3DPROC) (HDC hDC);
|
||||
typedef BOOL (WINAPI * PFNWGLISENABLEDGENLOCKI3DPROC) (HDC hDC, BOOL *pFlag);
|
||||
typedef BOOL (WINAPI * PFNWGLGENLOCKSOURCEI3DPROC) (HDC hDC, UINT uSource);
|
||||
typedef BOOL (WINAPI * PFNWGLGETGENLOCKSOURCEI3DPROC) (HDC hDC, UINT *uSource);
|
||||
typedef BOOL (WINAPI * PFNWGLGENLOCKSOURCEEDGEI3DPROC) (HDC hDC, UINT uEdge);
|
||||
typedef BOOL (WINAPI * PFNWGLGETGENLOCKSOURCEEDGEI3DPROC) (HDC hDC, UINT *uEdge);
|
||||
typedef BOOL (WINAPI * PFNWGLGENLOCKSAMPLERATEI3DPROC) (HDC hDC, UINT uRate);
|
||||
typedef BOOL (WINAPI * PFNWGLGETGENLOCKSAMPLERATEI3DPROC) (HDC hDC, UINT *uRate);
|
||||
typedef BOOL (WINAPI * PFNWGLGENLOCKSOURCEDELAYI3DPROC) (HDC hDC, UINT uDelay);
|
||||
typedef BOOL (WINAPI * PFNWGLGETGENLOCKSOURCEDELAYI3DPROC) (HDC hDC, UINT *uDelay);
|
||||
typedef BOOL (WINAPI * PFNWGLQUERYGENLOCKMAXSOURCEDELAYI3DPROC) (HDC hDC, UINT *uMaxLineDelay, UINT *uMaxPixelDelay);
|
||||
#ifdef WGL_WGLEXT_PROTOTYPES
|
||||
BOOL WINAPI wglEnableGenlockI3D (HDC hDC);
|
||||
BOOL WINAPI wglDisableGenlockI3D (HDC hDC);
|
||||
BOOL WINAPI wglIsEnabledGenlockI3D (HDC hDC, BOOL *pFlag);
|
||||
BOOL WINAPI wglGenlockSourceI3D (HDC hDC, UINT uSource);
|
||||
BOOL WINAPI wglGetGenlockSourceI3D (HDC hDC, UINT *uSource);
|
||||
BOOL WINAPI wglGenlockSourceEdgeI3D (HDC hDC, UINT uEdge);
|
||||
BOOL WINAPI wglGetGenlockSourceEdgeI3D (HDC hDC, UINT *uEdge);
|
||||
BOOL WINAPI wglGenlockSampleRateI3D (HDC hDC, UINT uRate);
|
||||
BOOL WINAPI wglGetGenlockSampleRateI3D (HDC hDC, UINT *uRate);
|
||||
BOOL WINAPI wglGenlockSourceDelayI3D (HDC hDC, UINT uDelay);
|
||||
BOOL WINAPI wglGetGenlockSourceDelayI3D (HDC hDC, UINT *uDelay);
|
||||
BOOL WINAPI wglQueryGenlockMaxSourceDelayI3D (HDC hDC, UINT *uMaxLineDelay, UINT *uMaxPixelDelay);
|
||||
#endif
|
||||
#endif /* WGL_I3D_genlock */
|
||||
|
||||
#ifndef WGL_I3D_image_buffer
|
||||
#define WGL_I3D_image_buffer 1
|
||||
#define WGL_IMAGE_BUFFER_MIN_ACCESS_I3D 0x00000001
|
||||
#define WGL_IMAGE_BUFFER_LOCK_I3D 0x00000002
|
||||
typedef LPVOID (WINAPI * PFNWGLCREATEIMAGEBUFFERI3DPROC) (HDC hDC, DWORD dwSize, UINT uFlags);
|
||||
typedef BOOL (WINAPI * PFNWGLDESTROYIMAGEBUFFERI3DPROC) (HDC hDC, LPVOID pAddress);
|
||||
typedef BOOL (WINAPI * PFNWGLASSOCIATEIMAGEBUFFEREVENTSI3DPROC) (HDC hDC, const HANDLE *pEvent, const LPVOID *pAddress, const DWORD *pSize, UINT count);
|
||||
typedef BOOL (WINAPI * PFNWGLRELEASEIMAGEBUFFEREVENTSI3DPROC) (HDC hDC, const LPVOID *pAddress, UINT count);
|
||||
#ifdef WGL_WGLEXT_PROTOTYPES
|
||||
LPVOID WINAPI wglCreateImageBufferI3D (HDC hDC, DWORD dwSize, UINT uFlags);
|
||||
BOOL WINAPI wglDestroyImageBufferI3D (HDC hDC, LPVOID pAddress);
|
||||
BOOL WINAPI wglAssociateImageBufferEventsI3D (HDC hDC, const HANDLE *pEvent, const LPVOID *pAddress, const DWORD *pSize, UINT count);
|
||||
BOOL WINAPI wglReleaseImageBufferEventsI3D (HDC hDC, const LPVOID *pAddress, UINT count);
|
||||
#endif
|
||||
#endif /* WGL_I3D_image_buffer */
|
||||
|
||||
#ifndef WGL_I3D_swap_frame_lock
|
||||
#define WGL_I3D_swap_frame_lock 1
|
||||
typedef BOOL (WINAPI * PFNWGLENABLEFRAMELOCKI3DPROC) (void);
|
||||
typedef BOOL (WINAPI * PFNWGLDISABLEFRAMELOCKI3DPROC) (void);
|
||||
typedef BOOL (WINAPI * PFNWGLISENABLEDFRAMELOCKI3DPROC) (BOOL *pFlag);
|
||||
typedef BOOL (WINAPI * PFNWGLQUERYFRAMELOCKMASTERI3DPROC) (BOOL *pFlag);
|
||||
#ifdef WGL_WGLEXT_PROTOTYPES
|
||||
BOOL WINAPI wglEnableFrameLockI3D (void);
|
||||
BOOL WINAPI wglDisableFrameLockI3D (void);
|
||||
BOOL WINAPI wglIsEnabledFrameLockI3D (BOOL *pFlag);
|
||||
BOOL WINAPI wglQueryFrameLockMasterI3D (BOOL *pFlag);
|
||||
#endif
|
||||
#endif /* WGL_I3D_swap_frame_lock */
|
||||
|
||||
#ifndef WGL_I3D_swap_frame_usage
|
||||
#define WGL_I3D_swap_frame_usage 1
|
||||
typedef BOOL (WINAPI * PFNWGLGETFRAMEUSAGEI3DPROC) (float *pUsage);
|
||||
typedef BOOL (WINAPI * PFNWGLBEGINFRAMETRACKINGI3DPROC) (void);
|
||||
typedef BOOL (WINAPI * PFNWGLENDFRAMETRACKINGI3DPROC) (void);
|
||||
typedef BOOL (WINAPI * PFNWGLQUERYFRAMETRACKINGI3DPROC) (DWORD *pFrameCount, DWORD *pMissedFrames, float *pLastMissedUsage);
|
||||
#ifdef WGL_WGLEXT_PROTOTYPES
|
||||
BOOL WINAPI wglGetFrameUsageI3D (float *pUsage);
|
||||
BOOL WINAPI wglBeginFrameTrackingI3D (void);
|
||||
BOOL WINAPI wglEndFrameTrackingI3D (void);
|
||||
BOOL WINAPI wglQueryFrameTrackingI3D (DWORD *pFrameCount, DWORD *pMissedFrames, float *pLastMissedUsage);
|
||||
#endif
|
||||
#endif /* WGL_I3D_swap_frame_usage */
|
||||
|
||||
#ifndef WGL_NV_DX_interop
|
||||
#define WGL_NV_DX_interop 1
|
||||
#define WGL_ACCESS_READ_ONLY_NV 0x00000000
|
||||
#define WGL_ACCESS_READ_WRITE_NV 0x00000001
|
||||
#define WGL_ACCESS_WRITE_DISCARD_NV 0x00000002
|
||||
typedef BOOL (WINAPI * PFNWGLDXSETRESOURCESHAREHANDLENVPROC) (void *dxObject, HANDLE shareHandle);
|
||||
typedef HANDLE (WINAPI * PFNWGLDXOPENDEVICENVPROC) (void *dxDevice);
|
||||
typedef BOOL (WINAPI * PFNWGLDXCLOSEDEVICENVPROC) (HANDLE hDevice);
|
||||
typedef HANDLE (WINAPI * PFNWGLDXREGISTEROBJECTNVPROC) (HANDLE hDevice, void *dxObject, GLuint name, GLenum type, GLenum access);
|
||||
typedef BOOL (WINAPI * PFNWGLDXUNREGISTEROBJECTNVPROC) (HANDLE hDevice, HANDLE hObject);
|
||||
typedef BOOL (WINAPI * PFNWGLDXOBJECTACCESSNVPROC) (HANDLE hObject, GLenum access);
|
||||
typedef BOOL (WINAPI * PFNWGLDXLOCKOBJECTSNVPROC) (HANDLE hDevice, GLint count, HANDLE *hObjects);
|
||||
typedef BOOL (WINAPI * PFNWGLDXUNLOCKOBJECTSNVPROC) (HANDLE hDevice, GLint count, HANDLE *hObjects);
|
||||
#ifdef WGL_WGLEXT_PROTOTYPES
|
||||
BOOL WINAPI wglDXSetResourceShareHandleNV (void *dxObject, HANDLE shareHandle);
|
||||
HANDLE WINAPI wglDXOpenDeviceNV (void *dxDevice);
|
||||
BOOL WINAPI wglDXCloseDeviceNV (HANDLE hDevice);
|
||||
HANDLE WINAPI wglDXRegisterObjectNV (HANDLE hDevice, void *dxObject, GLuint name, GLenum type, GLenum access);
|
||||
BOOL WINAPI wglDXUnregisterObjectNV (HANDLE hDevice, HANDLE hObject);
|
||||
BOOL WINAPI wglDXObjectAccessNV (HANDLE hObject, GLenum access);
|
||||
BOOL WINAPI wglDXLockObjectsNV (HANDLE hDevice, GLint count, HANDLE *hObjects);
|
||||
BOOL WINAPI wglDXUnlockObjectsNV (HANDLE hDevice, GLint count, HANDLE *hObjects);
|
||||
#endif
|
||||
#endif /* WGL_NV_DX_interop */
|
||||
|
||||
#ifndef WGL_NV_DX_interop2
|
||||
#define WGL_NV_DX_interop2 1
|
||||
#endif /* WGL_NV_DX_interop2 */
|
||||
|
||||
#ifndef WGL_NV_copy_image
|
||||
#define WGL_NV_copy_image 1
|
||||
typedef BOOL (WINAPI * PFNWGLCOPYIMAGESUBDATANVPROC) (HGLRC hSrcRC, GLuint srcName, GLenum srcTarget, GLint srcLevel, GLint srcX, GLint srcY, GLint srcZ, HGLRC hDstRC, GLuint dstName, GLenum dstTarget, GLint dstLevel, GLint dstX, GLint dstY, GLint dstZ, GLsizei width, GLsizei height, GLsizei depth);
|
||||
#ifdef WGL_WGLEXT_PROTOTYPES
|
||||
BOOL WINAPI wglCopyImageSubDataNV (HGLRC hSrcRC, GLuint srcName, GLenum srcTarget, GLint srcLevel, GLint srcX, GLint srcY, GLint srcZ, HGLRC hDstRC, GLuint dstName, GLenum dstTarget, GLint dstLevel, GLint dstX, GLint dstY, GLint dstZ, GLsizei width, GLsizei height, GLsizei depth);
|
||||
#endif
|
||||
#endif /* WGL_NV_copy_image */
|
||||
|
||||
#ifndef WGL_NV_delay_before_swap
|
||||
#define WGL_NV_delay_before_swap 1
|
||||
typedef BOOL (WINAPI * PFNWGLDELAYBEFORESWAPNVPROC) (HDC hDC, GLfloat seconds);
|
||||
#ifdef WGL_WGLEXT_PROTOTYPES
|
||||
BOOL WINAPI wglDelayBeforeSwapNV (HDC hDC, GLfloat seconds);
|
||||
#endif
|
||||
#endif /* WGL_NV_delay_before_swap */
|
||||
|
||||
#ifndef WGL_NV_float_buffer
|
||||
#define WGL_NV_float_buffer 1
|
||||
#define WGL_FLOAT_COMPONENTS_NV 0x20B0
|
||||
#define WGL_BIND_TO_TEXTURE_RECTANGLE_FLOAT_R_NV 0x20B1
|
||||
#define WGL_BIND_TO_TEXTURE_RECTANGLE_FLOAT_RG_NV 0x20B2
|
||||
#define WGL_BIND_TO_TEXTURE_RECTANGLE_FLOAT_RGB_NV 0x20B3
|
||||
#define WGL_BIND_TO_TEXTURE_RECTANGLE_FLOAT_RGBA_NV 0x20B4
|
||||
#define WGL_TEXTURE_FLOAT_R_NV 0x20B5
|
||||
#define WGL_TEXTURE_FLOAT_RG_NV 0x20B6
|
||||
#define WGL_TEXTURE_FLOAT_RGB_NV 0x20B7
|
||||
#define WGL_TEXTURE_FLOAT_RGBA_NV 0x20B8
|
||||
#endif /* WGL_NV_float_buffer */
|
||||
|
||||
#ifndef WGL_NV_gpu_affinity
|
||||
#define WGL_NV_gpu_affinity 1
|
||||
DECLARE_HANDLE(HGPUNV);
|
||||
struct _GPU_DEVICE {
|
||||
DWORD cb;
|
||||
CHAR DeviceName[32];
|
||||
CHAR DeviceString[128];
|
||||
DWORD Flags;
|
||||
RECT rcVirtualScreen;
|
||||
};
|
||||
typedef struct _GPU_DEVICE *PGPU_DEVICE;
|
||||
#define ERROR_INCOMPATIBLE_AFFINITY_MASKS_NV 0x20D0
|
||||
#define ERROR_MISSING_AFFINITY_MASK_NV 0x20D1
|
||||
typedef BOOL (WINAPI * PFNWGLENUMGPUSNVPROC) (UINT iGpuIndex, HGPUNV *phGpu);
|
||||
typedef BOOL (WINAPI * PFNWGLENUMGPUDEVICESNVPROC) (HGPUNV hGpu, UINT iDeviceIndex, PGPU_DEVICE lpGpuDevice);
|
||||
typedef HDC (WINAPI * PFNWGLCREATEAFFINITYDCNVPROC) (const HGPUNV *phGpuList);
|
||||
typedef BOOL (WINAPI * PFNWGLENUMGPUSFROMAFFINITYDCNVPROC) (HDC hAffinityDC, UINT iGpuIndex, HGPUNV *hGpu);
|
||||
typedef BOOL (WINAPI * PFNWGLDELETEDCNVPROC) (HDC hdc);
|
||||
#ifdef WGL_WGLEXT_PROTOTYPES
|
||||
BOOL WINAPI wglEnumGpusNV (UINT iGpuIndex, HGPUNV *phGpu);
|
||||
BOOL WINAPI wglEnumGpuDevicesNV (HGPUNV hGpu, UINT iDeviceIndex, PGPU_DEVICE lpGpuDevice);
|
||||
HDC WINAPI wglCreateAffinityDCNV (const HGPUNV *phGpuList);
|
||||
BOOL WINAPI wglEnumGpusFromAffinityDCNV (HDC hAffinityDC, UINT iGpuIndex, HGPUNV *hGpu);
|
||||
BOOL WINAPI wglDeleteDCNV (HDC hdc);
|
||||
#endif
|
||||
#endif /* WGL_NV_gpu_affinity */
|
||||
|
||||
#ifndef WGL_NV_multisample_coverage
|
||||
#define WGL_NV_multisample_coverage 1
|
||||
#define WGL_COVERAGE_SAMPLES_NV 0x2042
|
||||
#define WGL_COLOR_SAMPLES_NV 0x20B9
|
||||
#endif /* WGL_NV_multisample_coverage */
|
||||
|
||||
#ifndef WGL_NV_present_video
|
||||
#define WGL_NV_present_video 1
|
||||
DECLARE_HANDLE(HVIDEOOUTPUTDEVICENV);
|
||||
#define WGL_NUM_VIDEO_SLOTS_NV 0x20F0
|
||||
typedef int (WINAPI * PFNWGLENUMERATEVIDEODEVICESNVPROC) (HDC hDC, HVIDEOOUTPUTDEVICENV *phDeviceList);
|
||||
typedef BOOL (WINAPI * PFNWGLBINDVIDEODEVICENVPROC) (HDC hDC, unsigned int uVideoSlot, HVIDEOOUTPUTDEVICENV hVideoDevice, const int *piAttribList);
|
||||
typedef BOOL (WINAPI * PFNWGLQUERYCURRENTCONTEXTNVPROC) (int iAttribute, int *piValue);
|
||||
#ifdef WGL_WGLEXT_PROTOTYPES
|
||||
int WINAPI wglEnumerateVideoDevicesNV (HDC hDC, HVIDEOOUTPUTDEVICENV *phDeviceList);
|
||||
BOOL WINAPI wglBindVideoDeviceNV (HDC hDC, unsigned int uVideoSlot, HVIDEOOUTPUTDEVICENV hVideoDevice, const int *piAttribList);
|
||||
BOOL WINAPI wglQueryCurrentContextNV (int iAttribute, int *piValue);
|
||||
#endif
|
||||
#endif /* WGL_NV_present_video */
|
||||
|
||||
#ifndef WGL_NV_render_depth_texture
|
||||
#define WGL_NV_render_depth_texture 1
|
||||
#define WGL_BIND_TO_TEXTURE_DEPTH_NV 0x20A3
|
||||
#define WGL_BIND_TO_TEXTURE_RECTANGLE_DEPTH_NV 0x20A4
|
||||
#define WGL_DEPTH_TEXTURE_FORMAT_NV 0x20A5
|
||||
#define WGL_TEXTURE_DEPTH_COMPONENT_NV 0x20A6
|
||||
#define WGL_DEPTH_COMPONENT_NV 0x20A7
|
||||
#endif /* WGL_NV_render_depth_texture */
|
||||
|
||||
#ifndef WGL_NV_render_texture_rectangle
|
||||
#define WGL_NV_render_texture_rectangle 1
|
||||
#define WGL_BIND_TO_TEXTURE_RECTANGLE_RGB_NV 0x20A0
|
||||
#define WGL_BIND_TO_TEXTURE_RECTANGLE_RGBA_NV 0x20A1
|
||||
#define WGL_TEXTURE_RECTANGLE_NV 0x20A2
|
||||
#endif /* WGL_NV_render_texture_rectangle */
|
||||
|
||||
#ifndef WGL_NV_swap_group
|
||||
#define WGL_NV_swap_group 1
|
||||
typedef BOOL (WINAPI * PFNWGLJOINSWAPGROUPNVPROC) (HDC hDC, GLuint group);
|
||||
typedef BOOL (WINAPI * PFNWGLBINDSWAPBARRIERNVPROC) (GLuint group, GLuint barrier);
|
||||
typedef BOOL (WINAPI * PFNWGLQUERYSWAPGROUPNVPROC) (HDC hDC, GLuint *group, GLuint *barrier);
|
||||
typedef BOOL (WINAPI * PFNWGLQUERYMAXSWAPGROUPSNVPROC) (HDC hDC, GLuint *maxGroups, GLuint *maxBarriers);
|
||||
typedef BOOL (WINAPI * PFNWGLQUERYFRAMECOUNTNVPROC) (HDC hDC, GLuint *count);
|
||||
typedef BOOL (WINAPI * PFNWGLRESETFRAMECOUNTNVPROC) (HDC hDC);
|
||||
#ifdef WGL_WGLEXT_PROTOTYPES
|
||||
BOOL WINAPI wglJoinSwapGroupNV (HDC hDC, GLuint group);
|
||||
BOOL WINAPI wglBindSwapBarrierNV (GLuint group, GLuint barrier);
|
||||
BOOL WINAPI wglQuerySwapGroupNV (HDC hDC, GLuint *group, GLuint *barrier);
|
||||
BOOL WINAPI wglQueryMaxSwapGroupsNV (HDC hDC, GLuint *maxGroups, GLuint *maxBarriers);
|
||||
BOOL WINAPI wglQueryFrameCountNV (HDC hDC, GLuint *count);
|
||||
BOOL WINAPI wglResetFrameCountNV (HDC hDC);
|
||||
#endif
|
||||
#endif /* WGL_NV_swap_group */
|
||||
|
||||
#ifndef WGL_NV_vertex_array_range
|
||||
#define WGL_NV_vertex_array_range 1
|
||||
typedef void *(WINAPI * PFNWGLALLOCATEMEMORYNVPROC) (GLsizei size, GLfloat readfreq, GLfloat writefreq, GLfloat priority);
|
||||
typedef void (WINAPI * PFNWGLFREEMEMORYNVPROC) (void *pointer);
|
||||
#ifdef WGL_WGLEXT_PROTOTYPES
|
||||
void *WINAPI wglAllocateMemoryNV (GLsizei size, GLfloat readfreq, GLfloat writefreq, GLfloat priority);
|
||||
void WINAPI wglFreeMemoryNV (void *pointer);
|
||||
#endif
|
||||
#endif /* WGL_NV_vertex_array_range */
|
||||
|
||||
#ifndef WGL_NV_video_capture
|
||||
#define WGL_NV_video_capture 1
|
||||
DECLARE_HANDLE(HVIDEOINPUTDEVICENV);
|
||||
#define WGL_UNIQUE_ID_NV 0x20CE
|
||||
#define WGL_NUM_VIDEO_CAPTURE_SLOTS_NV 0x20CF
|
||||
typedef BOOL (WINAPI * PFNWGLBINDVIDEOCAPTUREDEVICENVPROC) (UINT uVideoSlot, HVIDEOINPUTDEVICENV hDevice);
|
||||
typedef UINT (WINAPI * PFNWGLENUMERATEVIDEOCAPTUREDEVICESNVPROC) (HDC hDc, HVIDEOINPUTDEVICENV *phDeviceList);
|
||||
typedef BOOL (WINAPI * PFNWGLLOCKVIDEOCAPTUREDEVICENVPROC) (HDC hDc, HVIDEOINPUTDEVICENV hDevice);
|
||||
typedef BOOL (WINAPI * PFNWGLQUERYVIDEOCAPTUREDEVICENVPROC) (HDC hDc, HVIDEOINPUTDEVICENV hDevice, int iAttribute, int *piValue);
|
||||
typedef BOOL (WINAPI * PFNWGLRELEASEVIDEOCAPTUREDEVICENVPROC) (HDC hDc, HVIDEOINPUTDEVICENV hDevice);
|
||||
#ifdef WGL_WGLEXT_PROTOTYPES
|
||||
BOOL WINAPI wglBindVideoCaptureDeviceNV (UINT uVideoSlot, HVIDEOINPUTDEVICENV hDevice);
|
||||
UINT WINAPI wglEnumerateVideoCaptureDevicesNV (HDC hDc, HVIDEOINPUTDEVICENV *phDeviceList);
|
||||
BOOL WINAPI wglLockVideoCaptureDeviceNV (HDC hDc, HVIDEOINPUTDEVICENV hDevice);
|
||||
BOOL WINAPI wglQueryVideoCaptureDeviceNV (HDC hDc, HVIDEOINPUTDEVICENV hDevice, int iAttribute, int *piValue);
|
||||
BOOL WINAPI wglReleaseVideoCaptureDeviceNV (HDC hDc, HVIDEOINPUTDEVICENV hDevice);
|
||||
#endif
|
||||
#endif /* WGL_NV_video_capture */
|
||||
|
||||
#ifndef WGL_NV_video_output
|
||||
#define WGL_NV_video_output 1
|
||||
DECLARE_HANDLE(HPVIDEODEV);
|
||||
#define WGL_BIND_TO_VIDEO_RGB_NV 0x20C0
|
||||
#define WGL_BIND_TO_VIDEO_RGBA_NV 0x20C1
|
||||
#define WGL_BIND_TO_VIDEO_RGB_AND_DEPTH_NV 0x20C2
|
||||
#define WGL_VIDEO_OUT_COLOR_NV 0x20C3
|
||||
#define WGL_VIDEO_OUT_ALPHA_NV 0x20C4
|
||||
#define WGL_VIDEO_OUT_DEPTH_NV 0x20C5
|
||||
#define WGL_VIDEO_OUT_COLOR_AND_ALPHA_NV 0x20C6
|
||||
#define WGL_VIDEO_OUT_COLOR_AND_DEPTH_NV 0x20C7
|
||||
#define WGL_VIDEO_OUT_FRAME 0x20C8
|
||||
#define WGL_VIDEO_OUT_FIELD_1 0x20C9
|
||||
#define WGL_VIDEO_OUT_FIELD_2 0x20CA
|
||||
#define WGL_VIDEO_OUT_STACKED_FIELDS_1_2 0x20CB
|
||||
#define WGL_VIDEO_OUT_STACKED_FIELDS_2_1 0x20CC
|
||||
typedef BOOL (WINAPI * PFNWGLGETVIDEODEVICENVPROC) (HDC hDC, int numDevices, HPVIDEODEV *hVideoDevice);
|
||||
typedef BOOL (WINAPI * PFNWGLRELEASEVIDEODEVICENVPROC) (HPVIDEODEV hVideoDevice);
|
||||
typedef BOOL (WINAPI * PFNWGLBINDVIDEOIMAGENVPROC) (HPVIDEODEV hVideoDevice, HPBUFFERARB hPbuffer, int iVideoBuffer);
|
||||
typedef BOOL (WINAPI * PFNWGLRELEASEVIDEOIMAGENVPROC) (HPBUFFERARB hPbuffer, int iVideoBuffer);
|
||||
typedef BOOL (WINAPI * PFNWGLSENDPBUFFERTOVIDEONVPROC) (HPBUFFERARB hPbuffer, int iBufferType, unsigned long *pulCounterPbuffer, BOOL bBlock);
|
||||
typedef BOOL (WINAPI * PFNWGLGETVIDEOINFONVPROC) (HPVIDEODEV hpVideoDevice, unsigned long *pulCounterOutputPbuffer, unsigned long *pulCounterOutputVideo);
|
||||
#ifdef WGL_WGLEXT_PROTOTYPES
|
||||
BOOL WINAPI wglGetVideoDeviceNV (HDC hDC, int numDevices, HPVIDEODEV *hVideoDevice);
|
||||
BOOL WINAPI wglReleaseVideoDeviceNV (HPVIDEODEV hVideoDevice);
|
||||
BOOL WINAPI wglBindVideoImageNV (HPVIDEODEV hVideoDevice, HPBUFFERARB hPbuffer, int iVideoBuffer);
|
||||
BOOL WINAPI wglReleaseVideoImageNV (HPBUFFERARB hPbuffer, int iVideoBuffer);
|
||||
BOOL WINAPI wglSendPbufferToVideoNV (HPBUFFERARB hPbuffer, int iBufferType, unsigned long *pulCounterPbuffer, BOOL bBlock);
|
||||
BOOL WINAPI wglGetVideoInfoNV (HPVIDEODEV hpVideoDevice, unsigned long *pulCounterOutputPbuffer, unsigned long *pulCounterOutputVideo);
|
||||
#endif
|
||||
#endif /* WGL_NV_video_output */
|
||||
|
||||
#ifndef WGL_OML_sync_control
|
||||
#define WGL_OML_sync_control 1
|
||||
typedef BOOL (WINAPI * PFNWGLGETSYNCVALUESOMLPROC) (HDC hdc, INT64 *ust, INT64 *msc, INT64 *sbc);
|
||||
typedef BOOL (WINAPI * PFNWGLGETMSCRATEOMLPROC) (HDC hdc, INT32 *numerator, INT32 *denominator);
|
||||
typedef INT64 (WINAPI * PFNWGLSWAPBUFFERSMSCOMLPROC) (HDC hdc, INT64 target_msc, INT64 divisor, INT64 remainder);
|
||||
typedef INT64 (WINAPI * PFNWGLSWAPLAYERBUFFERSMSCOMLPROC) (HDC hdc, int fuPlanes, INT64 target_msc, INT64 divisor, INT64 remainder);
|
||||
typedef BOOL (WINAPI * PFNWGLWAITFORMSCOMLPROC) (HDC hdc, INT64 target_msc, INT64 divisor, INT64 remainder, INT64 *ust, INT64 *msc, INT64 *sbc);
|
||||
typedef BOOL (WINAPI * PFNWGLWAITFORSBCOMLPROC) (HDC hdc, INT64 target_sbc, INT64 *ust, INT64 *msc, INT64 *sbc);
|
||||
#ifdef WGL_WGLEXT_PROTOTYPES
|
||||
BOOL WINAPI wglGetSyncValuesOML (HDC hdc, INT64 *ust, INT64 *msc, INT64 *sbc);
|
||||
BOOL WINAPI wglGetMscRateOML (HDC hdc, INT32 *numerator, INT32 *denominator);
|
||||
INT64 WINAPI wglSwapBuffersMscOML (HDC hdc, INT64 target_msc, INT64 divisor, INT64 remainder);
|
||||
INT64 WINAPI wglSwapLayerBuffersMscOML (HDC hdc, int fuPlanes, INT64 target_msc, INT64 divisor, INT64 remainder);
|
||||
BOOL WINAPI wglWaitForMscOML (HDC hdc, INT64 target_msc, INT64 divisor, INT64 remainder, INT64 *ust, INT64 *msc, INT64 *sbc);
|
||||
BOOL WINAPI wglWaitForSbcOML (HDC hdc, INT64 target_sbc, INT64 *ust, INT64 *msc, INT64 *sbc);
|
||||
#endif
|
||||
#endif /* WGL_OML_sync_control */
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif
|
||||
@@ -1,2 +0,0 @@
|
||||
DisableFormat: true
|
||||
SortIncludes: false
|
||||
@@ -1,290 +0,0 @@
|
||||
#ifndef __khrplatform_h_
|
||||
#define __khrplatform_h_
|
||||
|
||||
/*
|
||||
** Copyright (c) 2008-2018 The Khronos Group Inc.
|
||||
**
|
||||
** Permission is hereby granted, free of charge, to any person obtaining a
|
||||
** copy of this software and/or associated documentation files (the
|
||||
** "Materials"), to deal in the Materials without restriction, including
|
||||
** without limitation the rights to use, copy, modify, merge, publish,
|
||||
** distribute, sublicense, and/or sell copies of the Materials, and to
|
||||
** permit persons to whom the Materials are furnished to do so, subject to
|
||||
** the following conditions:
|
||||
**
|
||||
** The above copyright notice and this permission notice shall be included
|
||||
** in all copies or substantial portions of the Materials.
|
||||
**
|
||||
** THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
|
||||
** IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
|
||||
** CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
|
||||
** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
|
||||
** MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS.
|
||||
*/
|
||||
|
||||
/* Khronos platform-specific types and definitions.
|
||||
*
|
||||
* The master copy of khrplatform.h is maintained in the Khronos EGL
|
||||
* Registry repository at https://github.com/KhronosGroup/EGL-Registry
|
||||
* The last semantic modification to khrplatform.h was at commit ID:
|
||||
* 67a3e0864c2d75ea5287b9f3d2eb74a745936692
|
||||
*
|
||||
* Adopters may modify this file to suit their platform. Adopters are
|
||||
* encouraged to submit platform specific modifications to the Khronos
|
||||
* group so that they can be included in future versions of this file.
|
||||
* Please submit changes by filing pull requests or issues on
|
||||
* the EGL Registry repository linked above.
|
||||
*
|
||||
*
|
||||
* See the Implementer's Guidelines for information about where this file
|
||||
* should be located on your system and for more details of its use:
|
||||
* http://www.khronos.org/registry/implementers_guide.pdf
|
||||
*
|
||||
* This file should be included as
|
||||
* #include <KHR/khrplatform.h>
|
||||
* by Khronos client API header files that use its types and defines.
|
||||
*
|
||||
* The types in khrplatform.h should only be used to define API-specific types.
|
||||
*
|
||||
* Types defined in khrplatform.h:
|
||||
* khronos_int8_t signed 8 bit
|
||||
* khronos_uint8_t unsigned 8 bit
|
||||
* khronos_int16_t signed 16 bit
|
||||
* khronos_uint16_t unsigned 16 bit
|
||||
* khronos_int32_t signed 32 bit
|
||||
* khronos_uint32_t unsigned 32 bit
|
||||
* khronos_int64_t signed 64 bit
|
||||
* khronos_uint64_t unsigned 64 bit
|
||||
* khronos_intptr_t signed same number of bits as a pointer
|
||||
* khronos_uintptr_t unsigned same number of bits as a pointer
|
||||
* khronos_ssize_t signed size
|
||||
* khronos_usize_t unsigned size
|
||||
* khronos_float_t signed 32 bit floating point
|
||||
* khronos_time_ns_t unsigned 64 bit time in nanoseconds
|
||||
* khronos_utime_nanoseconds_t unsigned time interval or absolute time in
|
||||
* nanoseconds
|
||||
* khronos_stime_nanoseconds_t signed time interval in nanoseconds
|
||||
* khronos_boolean_enum_t enumerated boolean type. This should
|
||||
* only be used as a base type when a client API's boolean type is
|
||||
* an enum. Client APIs which use an integer or other type for
|
||||
* booleans cannot use this as the base type for their boolean.
|
||||
*
|
||||
* Tokens defined in khrplatform.h:
|
||||
*
|
||||
* KHRONOS_FALSE, KHRONOS_TRUE Enumerated boolean false/true values.
|
||||
*
|
||||
* KHRONOS_SUPPORT_INT64 is 1 if 64 bit integers are supported; otherwise 0.
|
||||
* KHRONOS_SUPPORT_FLOAT is 1 if floats are supported; otherwise 0.
|
||||
*
|
||||
* Calling convention macros defined in this file:
|
||||
* KHRONOS_APICALL
|
||||
* KHRONOS_APIENTRY
|
||||
* KHRONOS_APIATTRIBUTES
|
||||
*
|
||||
* These may be used in function prototypes as:
|
||||
*
|
||||
* KHRONOS_APICALL void KHRONOS_APIENTRY funcname(
|
||||
* int arg1,
|
||||
* int arg2) KHRONOS_APIATTRIBUTES;
|
||||
*/
|
||||
|
||||
#if defined(__SCITECH_SNAP__) && !defined(KHRONOS_STATIC)
|
||||
# define KHRONOS_STATIC 1
|
||||
#endif
|
||||
|
||||
/*-------------------------------------------------------------------------
|
||||
* Definition of KHRONOS_APICALL
|
||||
*-------------------------------------------------------------------------
|
||||
* This precedes the return type of the function in the function prototype.
|
||||
*/
|
||||
#if defined(KHRONOS_STATIC)
|
||||
/* If the preprocessor constant KHRONOS_STATIC is defined, make the
|
||||
* header compatible with static linking. */
|
||||
# define KHRONOS_APICALL
|
||||
#elif defined(_WIN32)
|
||||
# define KHRONOS_APICALL __declspec(dllimport)
|
||||
#elif defined (__SYMBIAN32__)
|
||||
# define KHRONOS_APICALL IMPORT_C
|
||||
#elif defined(__ANDROID__)
|
||||
# define KHRONOS_APICALL __attribute__((visibility("default")))
|
||||
#else
|
||||
# define KHRONOS_APICALL
|
||||
#endif
|
||||
|
||||
/*-------------------------------------------------------------------------
|
||||
* Definition of KHRONOS_APIENTRY
|
||||
*-------------------------------------------------------------------------
|
||||
* This follows the return type of the function and precedes the function
|
||||
* name in the function prototype.
|
||||
*/
|
||||
#if defined(_WIN32) && !defined(_WIN32_WCE) && !defined(__SCITECH_SNAP__)
|
||||
/* Win32 but not WinCE */
|
||||
# define KHRONOS_APIENTRY __stdcall
|
||||
#else
|
||||
# define KHRONOS_APIENTRY
|
||||
#endif
|
||||
|
||||
/*-------------------------------------------------------------------------
|
||||
* Definition of KHRONOS_APIATTRIBUTES
|
||||
*-------------------------------------------------------------------------
|
||||
* This follows the closing parenthesis of the function prototype arguments.
|
||||
*/
|
||||
#if defined (__ARMCC_2__)
|
||||
#define KHRONOS_APIATTRIBUTES __softfp
|
||||
#else
|
||||
#define KHRONOS_APIATTRIBUTES
|
||||
#endif
|
||||
|
||||
/*-------------------------------------------------------------------------
|
||||
* basic type definitions
|
||||
*-----------------------------------------------------------------------*/
|
||||
#if (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L) || defined(__GNUC__) || defined(__SCO__) || defined(__USLC__)
|
||||
|
||||
|
||||
/*
|
||||
* Using <stdint.h>
|
||||
*/
|
||||
#include <stdint.h>
|
||||
typedef int32_t khronos_int32_t;
|
||||
typedef uint32_t khronos_uint32_t;
|
||||
typedef int64_t khronos_int64_t;
|
||||
typedef uint64_t khronos_uint64_t;
|
||||
#define KHRONOS_SUPPORT_INT64 1
|
||||
#define KHRONOS_SUPPORT_FLOAT 1
|
||||
|
||||
#elif defined(__VMS ) || defined(__sgi)
|
||||
|
||||
/*
|
||||
* Using <inttypes.h>
|
||||
*/
|
||||
#include <inttypes.h>
|
||||
typedef int32_t khronos_int32_t;
|
||||
typedef uint32_t khronos_uint32_t;
|
||||
typedef int64_t khronos_int64_t;
|
||||
typedef uint64_t khronos_uint64_t;
|
||||
#define KHRONOS_SUPPORT_INT64 1
|
||||
#define KHRONOS_SUPPORT_FLOAT 1
|
||||
|
||||
#elif defined(_WIN32) && !defined(__SCITECH_SNAP__)
|
||||
|
||||
/*
|
||||
* Win32
|
||||
*/
|
||||
typedef __int32 khronos_int32_t;
|
||||
typedef unsigned __int32 khronos_uint32_t;
|
||||
typedef __int64 khronos_int64_t;
|
||||
typedef unsigned __int64 khronos_uint64_t;
|
||||
#define KHRONOS_SUPPORT_INT64 1
|
||||
#define KHRONOS_SUPPORT_FLOAT 1
|
||||
|
||||
#elif defined(__sun__) || defined(__digital__)
|
||||
|
||||
/*
|
||||
* Sun or Digital
|
||||
*/
|
||||
typedef int khronos_int32_t;
|
||||
typedef unsigned int khronos_uint32_t;
|
||||
#if defined(__arch64__) || defined(_LP64)
|
||||
typedef long int khronos_int64_t;
|
||||
typedef unsigned long int khronos_uint64_t;
|
||||
#else
|
||||
typedef long long int khronos_int64_t;
|
||||
typedef unsigned long long int khronos_uint64_t;
|
||||
#endif /* __arch64__ */
|
||||
#define KHRONOS_SUPPORT_INT64 1
|
||||
#define KHRONOS_SUPPORT_FLOAT 1
|
||||
|
||||
#elif 0
|
||||
|
||||
/*
|
||||
* Hypothetical platform with no float or int64 support
|
||||
*/
|
||||
typedef int khronos_int32_t;
|
||||
typedef unsigned int khronos_uint32_t;
|
||||
#define KHRONOS_SUPPORT_INT64 0
|
||||
#define KHRONOS_SUPPORT_FLOAT 0
|
||||
|
||||
#else
|
||||
|
||||
/*
|
||||
* Generic fallback
|
||||
*/
|
||||
#include <stdint.h>
|
||||
typedef int32_t khronos_int32_t;
|
||||
typedef uint32_t khronos_uint32_t;
|
||||
typedef int64_t khronos_int64_t;
|
||||
typedef uint64_t khronos_uint64_t;
|
||||
#define KHRONOS_SUPPORT_INT64 1
|
||||
#define KHRONOS_SUPPORT_FLOAT 1
|
||||
|
||||
#endif
|
||||
|
||||
|
||||
/*
|
||||
* Types that are (so far) the same on all platforms
|
||||
*/
|
||||
typedef signed char khronos_int8_t;
|
||||
typedef unsigned char khronos_uint8_t;
|
||||
typedef signed short int khronos_int16_t;
|
||||
typedef unsigned short int khronos_uint16_t;
|
||||
|
||||
/*
|
||||
* Types that differ between LLP64 and LP64 architectures - in LLP64,
|
||||
* pointers are 64 bits, but 'long' is still 32 bits. Win64 appears
|
||||
* to be the only LLP64 architecture in current use.
|
||||
*/
|
||||
#ifdef _WIN64
|
||||
typedef signed long long int khronos_intptr_t;
|
||||
typedef unsigned long long int khronos_uintptr_t;
|
||||
typedef signed long long int khronos_ssize_t;
|
||||
typedef unsigned long long int khronos_usize_t;
|
||||
#else
|
||||
typedef signed long int khronos_intptr_t;
|
||||
typedef unsigned long int khronos_uintptr_t;
|
||||
typedef signed long int khronos_ssize_t;
|
||||
typedef unsigned long int khronos_usize_t;
|
||||
#endif
|
||||
|
||||
#if KHRONOS_SUPPORT_FLOAT
|
||||
/*
|
||||
* Float type
|
||||
*/
|
||||
typedef float khronos_float_t;
|
||||
#endif
|
||||
|
||||
#if KHRONOS_SUPPORT_INT64
|
||||
/* Time types
|
||||
*
|
||||
* These types can be used to represent a time interval in nanoseconds or
|
||||
* an absolute Unadjusted System Time. Unadjusted System Time is the number
|
||||
* of nanoseconds since some arbitrary system event (e.g. since the last
|
||||
* time the system booted). The Unadjusted System Time is an unsigned
|
||||
* 64 bit value that wraps back to 0 every 584 years. Time intervals
|
||||
* may be either signed or unsigned.
|
||||
*/
|
||||
typedef khronos_uint64_t khronos_utime_nanoseconds_t;
|
||||
typedef khronos_int64_t khronos_stime_nanoseconds_t;
|
||||
#endif
|
||||
|
||||
/*
|
||||
* Dummy value used to pad enum types to 32 bits.
|
||||
*/
|
||||
#ifndef KHRONOS_MAX_ENUM
|
||||
#define KHRONOS_MAX_ENUM 0x7FFFFFFF
|
||||
#endif
|
||||
|
||||
/*
|
||||
* Enumerated boolean type
|
||||
*
|
||||
* Values other than zero should be considered to be true. Therefore
|
||||
* comparisons should not be made against KHRONOS_TRUE.
|
||||
*/
|
||||
typedef enum {
|
||||
KHRONOS_FALSE = 0,
|
||||
KHRONOS_TRUE = 1,
|
||||
KHRONOS_BOOLEAN_ENUM_FORCE_SIZE = KHRONOS_MAX_ENUM
|
||||
} khronos_boolean_enum_t;
|
||||
|
||||
#endif /* __khrplatform_h_ */
|
||||
@@ -18,6 +18,7 @@
|
||||
#define TNT_FILAMENT_BACKEND_PRIVATE_ACQUIREDIMAGE_H
|
||||
|
||||
#include <backend/DriverEnums.h>
|
||||
#include <math/mat3.h>
|
||||
|
||||
namespace filament::backend {
|
||||
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
/*
|
||||
* Copyright (C) 2025 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#ifndef TNT_FILAMENT_BACKEND_BUFFEROBJECTSTREAMDESCRIPTOR_H
|
||||
#define TNT_FILAMENT_BACKEND_BUFFEROBJECTSTREAMDESCRIPTOR_H
|
||||
|
||||
#include <backend/Handle.h>
|
||||
|
||||
#include <vector>
|
||||
|
||||
namespace filament::backend {
|
||||
|
||||
/**
|
||||
* The type of association between a buffer object and a stream.
|
||||
*/
|
||||
enum class BufferObjectStreamAssociationType { TRANSFORM_MATRIX };
|
||||
|
||||
/**
|
||||
* A descriptor for a buffer object to stream association.
|
||||
*/
|
||||
class UTILS_PUBLIC BufferObjectStreamDescriptor {
|
||||
public:
|
||||
//! creates an empty descriptor
|
||||
BufferObjectStreamDescriptor() noexcept = default;
|
||||
|
||||
BufferObjectStreamDescriptor(const BufferObjectStreamDescriptor& rhs) = delete;
|
||||
BufferObjectStreamDescriptor& operator=(const BufferObjectStreamDescriptor& rhs) = delete;
|
||||
|
||||
BufferObjectStreamDescriptor(BufferObjectStreamDescriptor&& rhs) = default;
|
||||
BufferObjectStreamDescriptor& operator=(BufferObjectStreamDescriptor&& rhs) = default;
|
||||
|
||||
// --------------------------------------------------------------------------------------------
|
||||
|
||||
struct StreamDataDescriptor {
|
||||
uint32_t offset;
|
||||
Handle<HwStream> stream;
|
||||
BufferObjectStreamAssociationType associationType;
|
||||
};
|
||||
|
||||
std::vector<StreamDataDescriptor> mStreams;
|
||||
};
|
||||
|
||||
} // namespace filament::backend
|
||||
|
||||
#endif // TNT_FILAMENT_BACKEND_BUFFEROBJECTSTREAMDESCRIPTOR_H
|
||||
@@ -0,0 +1,107 @@
|
||||
/*
|
||||
* Copyright (C) 2024 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#ifndef TNT_FILAMENT_BACKEND_COMMANDSTREAMVECTOR_H
|
||||
#define TNT_FILAMENT_BACKEND_COMMANDSTREAMVECTOR_H
|
||||
|
||||
#include <backend/DriverApiForward.h>
|
||||
|
||||
#include <utils/ostream.h>
|
||||
|
||||
#include <initializer_list>
|
||||
#include <memory>
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
|
||||
namespace filament::backend {
|
||||
|
||||
void* allocateFromCommandStream(DriverApi& driver, size_t size, size_t alignment) noexcept;
|
||||
|
||||
class DescriptorSetOffsetArray {
|
||||
public:
|
||||
using value_type = uint32_t;
|
||||
using reference = value_type&;
|
||||
using const_reference = value_type const&;
|
||||
using size_type = uint32_t;
|
||||
using difference_type = int32_t;
|
||||
using pointer = value_type*;
|
||||
using const_pointer = value_type const*;
|
||||
using iterator = pointer;
|
||||
using const_iterator = const_pointer;
|
||||
|
||||
DescriptorSetOffsetArray() noexcept = default;
|
||||
|
||||
~DescriptorSetOffsetArray() noexcept = default;
|
||||
|
||||
DescriptorSetOffsetArray(size_type size, DriverApi& driver) noexcept {
|
||||
mOffsets = (value_type *)allocateFromCommandStream(driver,
|
||||
size * sizeof(value_type), alignof(value_type));
|
||||
std::uninitialized_fill_n(mOffsets, size, 0);
|
||||
}
|
||||
|
||||
DescriptorSetOffsetArray(std::initializer_list<uint32_t> list, DriverApi& driver) noexcept {
|
||||
mOffsets = (value_type *)allocateFromCommandStream(driver,
|
||||
list.size() * sizeof(value_type), alignof(value_type));
|
||||
std::uninitialized_copy(list.begin(), list.end(), mOffsets);
|
||||
}
|
||||
|
||||
DescriptorSetOffsetArray(DescriptorSetOffsetArray const&) = delete;
|
||||
DescriptorSetOffsetArray& operator=(DescriptorSetOffsetArray const&) = delete;
|
||||
|
||||
DescriptorSetOffsetArray(DescriptorSetOffsetArray&& rhs) noexcept
|
||||
: mOffsets(rhs.mOffsets) {
|
||||
rhs.mOffsets = nullptr;
|
||||
}
|
||||
|
||||
DescriptorSetOffsetArray& operator=(DescriptorSetOffsetArray&& rhs) noexcept {
|
||||
if (this != &rhs) {
|
||||
mOffsets = rhs.mOffsets;
|
||||
rhs.mOffsets = nullptr;
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
bool empty() const noexcept { return mOffsets == nullptr; }
|
||||
|
||||
value_type* data() noexcept { return mOffsets; }
|
||||
const value_type* data() const noexcept { return mOffsets; }
|
||||
|
||||
|
||||
reference operator[](size_type n) noexcept {
|
||||
return *(data() + n);
|
||||
}
|
||||
|
||||
const_reference operator[](size_type n) const noexcept {
|
||||
return *(data() + n);
|
||||
}
|
||||
|
||||
void clear() noexcept {
|
||||
mOffsets = nullptr;
|
||||
}
|
||||
|
||||
private:
|
||||
value_type *mOffsets = nullptr;
|
||||
};
|
||||
|
||||
} // namespace filament::backend
|
||||
|
||||
#if !defined(NDEBUG)
|
||||
utils::io::ostream& operator<<(utils::io::ostream& out, const filament::backend::DescriptorSetOffsetArray& rhs);
|
||||
#endif
|
||||
|
||||
#endif //TNT_FILAMENT_BACKEND_COMMANDSTREAMVECTOR_H
|
||||
@@ -19,17 +19,23 @@
|
||||
#ifndef TNT_FILAMENT_BACKEND_DRIVERENUMS_H
|
||||
#define TNT_FILAMENT_BACKEND_DRIVERENUMS_H
|
||||
|
||||
#include <utils/BitmaskEnum.h>
|
||||
#include <utils/unwindows.h> // Because we define ERROR in the FenceStatus enum.
|
||||
|
||||
#include <backend/Platform.h>
|
||||
#include <backend/PresentCallable.h>
|
||||
|
||||
#include <utils/BitmaskEnum.h>
|
||||
#include <utils/FixedCapacityVector.h>
|
||||
#include <utils/Invocable.h>
|
||||
#include <utils/compiler.h>
|
||||
#include <utils/debug.h>
|
||||
#include <utils/ostream.h>
|
||||
|
||||
#include <math/vec4.h>
|
||||
|
||||
#include <array> // FIXME: STL headers are not allowed in public headers
|
||||
#include <type_traits> // FIXME: STL headers are not allowed in public headers
|
||||
#include <array>
|
||||
#include <type_traits>
|
||||
#include <variant>
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
@@ -90,11 +96,16 @@ static constexpr uint64_t SWAP_CHAIN_HAS_STENCIL_BUFFER = SWAP_CHAIN_CON
|
||||
*/
|
||||
static constexpr uint64_t SWAP_CHAIN_CONFIG_PROTECTED_CONTENT = 0x40;
|
||||
|
||||
|
||||
static constexpr size_t MAX_VERTEX_ATTRIBUTE_COUNT = 16; // This is guaranteed by OpenGL ES.
|
||||
static constexpr size_t MAX_SAMPLER_COUNT = 62; // Maximum needed at feature level 3.
|
||||
static constexpr size_t MAX_VERTEX_BUFFER_COUNT = 16; // Max number of bound buffer objects.
|
||||
static constexpr size_t MAX_SSBO_COUNT = 4; // This is guaranteed by OpenGL ES.
|
||||
static constexpr size_t MAX_DESCRIPTOR_SET_COUNT = 4; // This is guaranteed by Vulkan.
|
||||
static constexpr size_t MAX_DESCRIPTOR_COUNT = 64; // per set
|
||||
|
||||
static constexpr size_t MAX_PUSH_CONSTANT_COUNT = 32; // Vulkan 1.1 spec allows for 128-byte
|
||||
// of push constant (we assume 4-byte
|
||||
// types).
|
||||
|
||||
// Per feature level caps
|
||||
// Use (int)FeatureLevel to index this array
|
||||
@@ -112,7 +123,7 @@ static_assert(MAX_VERTEX_BUFFER_COUNT <= MAX_VERTEX_ATTRIBUTE_COUNT,
|
||||
"The number of buffer objects that can be attached to a VertexBuffer must be "
|
||||
"less than or equal to the maximum number of vertex attributes.");
|
||||
|
||||
static constexpr size_t CONFIG_UNIFORM_BINDING_COUNT = 10; // This is guaranteed by OpenGL ES.
|
||||
static constexpr size_t CONFIG_UNIFORM_BINDING_COUNT = 9; // This is guaranteed by OpenGL ES.
|
||||
static constexpr size_t CONFIG_SAMPLER_BINDING_COUNT = 4; // This is guaranteed by OpenGL ES.
|
||||
|
||||
/**
|
||||
@@ -133,7 +144,8 @@ enum class Backend : uint8_t {
|
||||
OPENGL = 1, //!< Selects the OpenGL/ES driver (default on Android)
|
||||
VULKAN = 2, //!< Selects the Vulkan driver if the platform supports it (default on Linux/Windows)
|
||||
METAL = 3, //!< Selects the Metal driver if the platform supports it (default on MacOS/iOS).
|
||||
NOOP = 4, //!< Selects the no-op driver for testing purposes.
|
||||
WEBGPU = 4, //!< Selects the Webgpu driver if the platform supports webgpu.
|
||||
NOOP = 5, //!< Selects the no-op driver for testing purposes.
|
||||
};
|
||||
|
||||
enum class TimerQueryResult : int8_t {
|
||||
@@ -152,20 +164,24 @@ static constexpr const char* backendToString(Backend backend) {
|
||||
return "Vulkan";
|
||||
case Backend::METAL:
|
||||
return "Metal";
|
||||
case Backend::WEBGPU:
|
||||
return "WebGPU";
|
||||
default:
|
||||
return "Unknown";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Defines the shader language. Similar to the above backend enum, but the OpenGL backend can select
|
||||
* between two shader languages: ESSL 1.0 and ESSL 3.0.
|
||||
* Defines the shader language. Similar to the above backend enum, with some differences:
|
||||
* - The OpenGL backend can select between two shader languages: ESSL 1.0 and ESSL 3.0.
|
||||
* - The Metal backend can prefer precompiled Metal libraries, while falling back to MSL.
|
||||
*/
|
||||
enum class ShaderLanguage {
|
||||
ESSL1 = 0,
|
||||
ESSL3 = 1,
|
||||
SPIRV = 2,
|
||||
MSL = 3,
|
||||
METAL_LIBRARY = 4,
|
||||
};
|
||||
|
||||
static constexpr const char* shaderLanguageToString(ShaderLanguage shaderLanguage) {
|
||||
@@ -178,9 +194,76 @@ static constexpr const char* shaderLanguageToString(ShaderLanguage shaderLanguag
|
||||
return "SPIR-V";
|
||||
case ShaderLanguage::MSL:
|
||||
return "MSL";
|
||||
case ShaderLanguage::METAL_LIBRARY:
|
||||
return "Metal precompiled library";
|
||||
}
|
||||
}
|
||||
|
||||
enum class ShaderStage : uint8_t {
|
||||
VERTEX = 0,
|
||||
FRAGMENT = 1,
|
||||
COMPUTE = 2
|
||||
};
|
||||
|
||||
static constexpr size_t PIPELINE_STAGE_COUNT = 2;
|
||||
enum class ShaderStageFlags : uint8_t {
|
||||
NONE = 0,
|
||||
VERTEX = 0x1,
|
||||
FRAGMENT = 0x2,
|
||||
COMPUTE = 0x4,
|
||||
ALL_SHADER_STAGE_FLAGS = VERTEX | FRAGMENT | COMPUTE
|
||||
};
|
||||
|
||||
static inline constexpr bool hasShaderType(ShaderStageFlags flags, ShaderStage type) noexcept {
|
||||
switch (type) {
|
||||
case ShaderStage::VERTEX:
|
||||
return bool(uint8_t(flags) & uint8_t(ShaderStageFlags::VERTEX));
|
||||
case ShaderStage::FRAGMENT:
|
||||
return bool(uint8_t(flags) & uint8_t(ShaderStageFlags::FRAGMENT));
|
||||
case ShaderStage::COMPUTE:
|
||||
return bool(uint8_t(flags) & uint8_t(ShaderStageFlags::COMPUTE));
|
||||
}
|
||||
}
|
||||
|
||||
enum class DescriptorType : uint8_t {
|
||||
UNIFORM_BUFFER,
|
||||
SHADER_STORAGE_BUFFER,
|
||||
SAMPLER,
|
||||
INPUT_ATTACHMENT,
|
||||
SAMPLER_EXTERNAL
|
||||
};
|
||||
|
||||
enum class DescriptorFlags : uint8_t {
|
||||
NONE = 0x00,
|
||||
DYNAMIC_OFFSET = 0x01
|
||||
};
|
||||
|
||||
using descriptor_set_t = uint8_t;
|
||||
|
||||
using descriptor_binding_t = uint8_t;
|
||||
|
||||
struct DescriptorSetLayoutBinding {
|
||||
DescriptorType type;
|
||||
ShaderStageFlags stageFlags;
|
||||
descriptor_binding_t binding;
|
||||
DescriptorFlags flags = DescriptorFlags::NONE;
|
||||
uint16_t count = 0;
|
||||
|
||||
friend inline bool operator==(
|
||||
DescriptorSetLayoutBinding const& lhs,
|
||||
DescriptorSetLayoutBinding const& rhs) noexcept {
|
||||
return lhs.type == rhs.type &&
|
||||
lhs.flags == rhs.flags &&
|
||||
lhs.count == rhs.count &&
|
||||
lhs.stageFlags == rhs.stageFlags;
|
||||
}
|
||||
};
|
||||
|
||||
struct DescriptorSetLayout {
|
||||
utils::FixedCapacityVector<DescriptorSetLayoutBinding> bindings;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Bitmask for selecting render buffers
|
||||
*/
|
||||
@@ -239,8 +322,19 @@ struct Viewport {
|
||||
int32_t right() const noexcept { return left + int32_t(width); }
|
||||
//! get the top coordinate in window space of the viewport
|
||||
int32_t top() const noexcept { return bottom + int32_t(height); }
|
||||
};
|
||||
|
||||
friend bool operator==(Viewport const& lhs, Viewport const& rhs) noexcept {
|
||||
// clang can do this branchless with xor/or
|
||||
return lhs.left == rhs.left && lhs.bottom == rhs.bottom &&
|
||||
lhs.width == rhs.width && lhs.height == rhs.height;
|
||||
}
|
||||
|
||||
friend bool operator!=(Viewport const& lhs, Viewport const& rhs) noexcept {
|
||||
// clang is being dumb and uses branches
|
||||
return bool(((lhs.left ^ rhs.left) | (lhs.bottom ^ rhs.bottom)) |
|
||||
((lhs.width ^ rhs.width) | (lhs.height ^ rhs.height)));
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Specifies the mapping of the near and far clipping plane to window coordinates.
|
||||
@@ -260,15 +354,6 @@ enum class FenceStatus : int8_t {
|
||||
TIMEOUT_EXPIRED = 1, //!< wait()'s timeout expired. The Fence condition is not satisfied.
|
||||
};
|
||||
|
||||
/**
|
||||
* Status codes for sync objects
|
||||
*/
|
||||
enum class SyncStatus : int8_t {
|
||||
ERROR = -1, //!< An error occurred. The Sync is not signaled.
|
||||
SIGNALED = 0, //!< The Sync is signaled.
|
||||
NOT_SIGNALED = 1, //!< The Sync is not signaled yet
|
||||
};
|
||||
|
||||
static constexpr uint64_t FENCE_WAIT_FOR_EVER = uint64_t(-1);
|
||||
|
||||
/**
|
||||
@@ -327,7 +412,7 @@ enum class UniformType : uint8_t {
|
||||
/**
|
||||
* Supported constant parameter types
|
||||
*/
|
||||
enum class ConstantType : uint8_t {
|
||||
enum class ConstantType : uint8_t {
|
||||
INT,
|
||||
FLOAT,
|
||||
BOOL
|
||||
@@ -682,8 +767,9 @@ enum class TextureUsage : uint16_t {
|
||||
SUBPASS_INPUT = 0x0020, //!< Texture can be used as a subpass input
|
||||
BLIT_SRC = 0x0040, //!< Texture can be used the source of a blit()
|
||||
BLIT_DST = 0x0080, //!< Texture can be used the destination of a blit()
|
||||
PROTECTED = 0x0100, //!< Texture can be used the destination of a blit()
|
||||
DEFAULT = UPLOADABLE | SAMPLEABLE //!< Default texture usage
|
||||
PROTECTED = 0x0100, //!< Texture can be used for protected content
|
||||
DEFAULT = UPLOADABLE | SAMPLEABLE, //!< Default texture usage
|
||||
ALL_ATTACHMENTS = COLOR_ATTACHMENT | DEPTH_ATTACHMENT | STENCIL_ATTACHMENT | SUBPASS_INPUT, //!< Mask of all attachments
|
||||
};
|
||||
|
||||
//! Texture swizzle
|
||||
@@ -877,6 +963,9 @@ struct SamplerParams { // NOLINT
|
||||
|
||||
struct EqualTo {
|
||||
bool operator()(SamplerParams lhs, SamplerParams rhs) const noexcept {
|
||||
assert_invariant(lhs.padding0 == 0);
|
||||
assert_invariant(lhs.padding1 == 0);
|
||||
assert_invariant(lhs.padding2 == 0);
|
||||
auto* pLhs = reinterpret_cast<uint32_t const*>(reinterpret_cast<char const*>(&lhs));
|
||||
auto* pRhs = reinterpret_cast<uint32_t const*>(reinterpret_cast<char const*>(&rhs));
|
||||
return *pLhs == *pRhs;
|
||||
@@ -885,6 +974,9 @@ struct SamplerParams { // NOLINT
|
||||
|
||||
struct LessThan {
|
||||
bool operator()(SamplerParams lhs, SamplerParams rhs) const noexcept {
|
||||
assert_invariant(lhs.padding0 == 0);
|
||||
assert_invariant(lhs.padding1 == 0);
|
||||
assert_invariant(lhs.padding2 == 0);
|
||||
auto* pLhs = reinterpret_cast<uint32_t const*>(reinterpret_cast<char const*>(&lhs));
|
||||
auto* pRhs = reinterpret_cast<uint32_t const*>(reinterpret_cast<char const*>(&rhs));
|
||||
return *pLhs == *pRhs;
|
||||
@@ -892,6 +984,12 @@ struct SamplerParams { // NOLINT
|
||||
};
|
||||
|
||||
private:
|
||||
friend inline bool operator == (SamplerParams lhs, SamplerParams rhs) noexcept {
|
||||
return SamplerParams::EqualTo{}(lhs, rhs);
|
||||
}
|
||||
friend inline bool operator != (SamplerParams lhs, SamplerParams rhs) noexcept {
|
||||
return !SamplerParams::EqualTo{}(lhs, rhs);
|
||||
}
|
||||
friend inline bool operator < (SamplerParams lhs, SamplerParams rhs) noexcept {
|
||||
return SamplerParams::LessThan{}(lhs, rhs);
|
||||
}
|
||||
@@ -1048,7 +1146,7 @@ struct RasterState {
|
||||
bool inverseFrontFaces : 1; // 31
|
||||
|
||||
//! padding, must be 0
|
||||
uint8_t padding : 1; // 32
|
||||
bool depthClamp : 1; // 32
|
||||
};
|
||||
uint32_t u = 0;
|
||||
};
|
||||
@@ -1059,32 +1157,6 @@ struct RasterState {
|
||||
* \privatesection
|
||||
*/
|
||||
|
||||
enum class ShaderStage : uint8_t {
|
||||
VERTEX = 0,
|
||||
FRAGMENT = 1,
|
||||
COMPUTE = 2
|
||||
};
|
||||
|
||||
static constexpr size_t PIPELINE_STAGE_COUNT = 2;
|
||||
enum class ShaderStageFlags : uint8_t {
|
||||
NONE = 0,
|
||||
VERTEX = 0x1,
|
||||
FRAGMENT = 0x2,
|
||||
COMPUTE = 0x4,
|
||||
ALL_SHADER_STAGE_FLAGS = VERTEX | FRAGMENT | COMPUTE
|
||||
};
|
||||
|
||||
static inline constexpr bool hasShaderType(ShaderStageFlags flags, ShaderStage type) noexcept {
|
||||
switch (type) {
|
||||
case ShaderStage::VERTEX:
|
||||
return bool(uint8_t(flags) & uint8_t(ShaderStageFlags::VERTEX));
|
||||
case ShaderStage::FRAGMENT:
|
||||
return bool(uint8_t(flags) & uint8_t(ShaderStageFlags::FRAGMENT));
|
||||
case ShaderStage::COMPUTE:
|
||||
return bool(uint8_t(flags) & uint8_t(ShaderStageFlags::COMPUTE));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Selects which buffers to clear at the beginning of the render pass, as well as which buffers
|
||||
* can be discarded at the beginning and end of the render pass.
|
||||
@@ -1214,13 +1286,15 @@ struct StencilState {
|
||||
uint8_t padding = 0;
|
||||
};
|
||||
|
||||
using PushConstantVariant = std::variant<int32_t, float, bool>;
|
||||
|
||||
static_assert(sizeof(StencilState::StencilOperations) == 5u,
|
||||
"StencilOperations size not what was intended");
|
||||
|
||||
static_assert(sizeof(StencilState) == 12u,
|
||||
"StencilState size not what was intended");
|
||||
|
||||
using FrameScheduledCallback = void(*)(PresentCallable callable, void* user);
|
||||
using FrameScheduledCallback = utils::Invocable<void(backend::PresentCallable)>;
|
||||
|
||||
enum class Workaround : uint16_t {
|
||||
// The EASU pass must split because shader compiler flattens early-exit branch
|
||||
@@ -1231,24 +1305,15 @@ enum class Workaround : uint16_t {
|
||||
// for some uniform arrays, it's needed to do an initialization to avoid crash on adreno gpu
|
||||
ADRENO_UNIFORM_ARRAY_CRASH,
|
||||
// Workaround a Metal pipeline compilation error with the message:
|
||||
// "Could not statically determine the target of a texture". See light_indirect.fs
|
||||
A8X_STATIC_TEXTURE_TARGET_ERROR,
|
||||
// "Could not statically determine the target of a texture". See surface_light_indirect.fs
|
||||
METAL_STATIC_TEXTURE_TARGET_ERROR,
|
||||
// Adreno drivers sometimes aren't able to blit into a layer of a texture array.
|
||||
DISABLE_BLIT_INTO_TEXTURE_ARRAY,
|
||||
// Multiple workarounds needed for PowerVR GPUs
|
||||
POWER_VR_SHADER_WORKAROUNDS,
|
||||
// The driver has some threads pinned, and we can't easily know on which core, it can hurt
|
||||
// performance more if we end-up pinned on the same one.
|
||||
DISABLE_THREAD_AFFINITY
|
||||
};
|
||||
|
||||
//! The type of technique for stereoscopic rendering
|
||||
enum class StereoscopicType : uint8_t {
|
||||
// Stereoscopic rendering is performed using instanced rendering technique.
|
||||
INSTANCED,
|
||||
// Stereoscopic rendering is performed using the multiview feature from the graphics backend.
|
||||
MULTIVIEW,
|
||||
};
|
||||
using StereoscopicType = backend::Platform::StereoscopicType;
|
||||
|
||||
} // namespace filament::backend
|
||||
|
||||
@@ -1256,6 +1321,8 @@ template<> struct utils::EnableBitMaskOperators<filament::backend::ShaderStageFl
|
||||
: public std::true_type {};
|
||||
template<> struct utils::EnableBitMaskOperators<filament::backend::TargetBufferFlags>
|
||||
: public std::true_type {};
|
||||
template<> struct utils::EnableBitMaskOperators<filament::backend::DescriptorFlags>
|
||||
: public std::true_type {};
|
||||
template<> struct utils::EnableBitMaskOperators<filament::backend::TextureUsage>
|
||||
: public std::true_type {};
|
||||
template<> struct utils::EnableBitMaskOperators<filament::backend::StencilFace>
|
||||
@@ -1288,12 +1355,16 @@ utils::io::ostream& operator<<(utils::io::ostream& out, filament::backend::Textu
|
||||
utils::io::ostream& operator<<(utils::io::ostream& out, filament::backend::TextureUsage usage);
|
||||
utils::io::ostream& operator<<(utils::io::ostream& out, filament::backend::BufferObjectBinding binding);
|
||||
utils::io::ostream& operator<<(utils::io::ostream& out, filament::backend::TextureSwizzle swizzle);
|
||||
utils::io::ostream& operator<<(utils::io::ostream& out, filament::backend::ShaderStage shaderStage);
|
||||
utils::io::ostream& operator<<(utils::io::ostream& out, filament::backend::ShaderStageFlags stageFlags);
|
||||
utils::io::ostream& operator<<(utils::io::ostream& out, filament::backend::CompilerPriorityQueue compilerPriorityQueue);
|
||||
utils::io::ostream& operator<<(utils::io::ostream& out, filament::backend::PushConstantVariant pushConstantVariant);
|
||||
utils::io::ostream& operator<<(utils::io::ostream& out, const filament::backend::AttributeArray& type);
|
||||
utils::io::ostream& operator<<(utils::io::ostream& out, const filament::backend::DescriptorSetLayout& dsl);
|
||||
utils::io::ostream& operator<<(utils::io::ostream& out, const filament::backend::PolygonOffset& po);
|
||||
utils::io::ostream& operator<<(utils::io::ostream& out, const filament::backend::RasterState& rs);
|
||||
utils::io::ostream& operator<<(utils::io::ostream& out, const filament::backend::RenderPassParams& b);
|
||||
utils::io::ostream& operator<<(utils::io::ostream& out, const filament::backend::Viewport& v);
|
||||
utils::io::ostream& operator<<(utils::io::ostream& out, filament::backend::ShaderStageFlags stageFlags);
|
||||
#endif
|
||||
|
||||
#endif // TNT_FILAMENT_BACKEND_DRIVERENUMS_H
|
||||
|
||||
@@ -23,6 +23,7 @@
|
||||
#include <utils/debug.h>
|
||||
|
||||
#include <type_traits> // FIXME: STL headers are not allowed in public headers
|
||||
#include <utility>
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
@@ -34,13 +35,14 @@ struct HwIndexBuffer;
|
||||
struct HwProgram;
|
||||
struct HwRenderPrimitive;
|
||||
struct HwRenderTarget;
|
||||
struct HwSamplerGroup;
|
||||
struct HwStream;
|
||||
struct HwSwapChain;
|
||||
struct HwTexture;
|
||||
struct HwTimerQuery;
|
||||
struct HwVertexBufferInfo;
|
||||
struct HwVertexBuffer;
|
||||
struct HwDescriptorSetLayout;
|
||||
struct HwDescriptorSet;
|
||||
|
||||
/*
|
||||
* A handle to a backend resource. HandleBase is for internal use only.
|
||||
@@ -75,6 +77,19 @@ protected:
|
||||
HandleBase(HandleBase const& rhs) noexcept = default;
|
||||
HandleBase& operator=(HandleBase const& rhs) noexcept = default;
|
||||
|
||||
HandleBase(HandleBase&& rhs) noexcept
|
||||
: object(rhs.object) {
|
||||
rhs.object = nullid;
|
||||
}
|
||||
|
||||
HandleBase& operator=(HandleBase&& rhs) noexcept {
|
||||
if (this != &rhs) {
|
||||
object = rhs.object;
|
||||
rhs.object = nullid;
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
private:
|
||||
HandleId object;
|
||||
};
|
||||
@@ -89,8 +104,20 @@ struct Handle : public HandleBase {
|
||||
Handle() noexcept = default;
|
||||
|
||||
Handle(Handle const& rhs) noexcept = default;
|
||||
Handle(Handle&& rhs) noexcept = default;
|
||||
|
||||
Handle& operator=(Handle const& rhs) noexcept = default;
|
||||
// Explicitly redefine copy/move assignment operators rather than just using default here.
|
||||
// Because it doesn't make a call to the parent's method automatically during the std::move
|
||||
// function call(https://en.cppreference.com/w/cpp/algorithm/move) in certain compilers like
|
||||
// NDK 25.1.8937393 and below (see b/371980551)
|
||||
Handle& operator=(Handle const& rhs) noexcept {
|
||||
HandleBase::operator=(rhs);
|
||||
return *this;
|
||||
}
|
||||
Handle& operator=(Handle&& rhs) noexcept {
|
||||
HandleBase::operator=(std::move(rhs));
|
||||
return *this;
|
||||
}
|
||||
|
||||
explicit Handle(HandleId id) noexcept : HandleBase(id) { }
|
||||
|
||||
@@ -103,7 +130,7 @@ struct Handle : public HandleBase {
|
||||
bool operator>=(const Handle& rhs) const noexcept { return getId() >= rhs.getId(); }
|
||||
|
||||
// type-safe Handle cast
|
||||
template<typename B, typename = std::enable_if_t<std::is_base_of<T, B>::value> >
|
||||
template<typename B, typename = std::enable_if_t<std::is_base_of_v<T, B>> >
|
||||
Handle(Handle<B> const& base) noexcept : HandleBase(base) { } // NOLINT(hicpp-explicit-conversions,google-explicit-constructor)
|
||||
|
||||
private:
|
||||
@@ -115,19 +142,20 @@ private:
|
||||
|
||||
// Types used by the command stream
|
||||
// (we use this renaming because the macro-system doesn't deal well with "<" and ">")
|
||||
using BufferObjectHandle = Handle<HwBufferObject>;
|
||||
using FenceHandle = Handle<HwFence>;
|
||||
using IndexBufferHandle = Handle<HwIndexBuffer>;
|
||||
using ProgramHandle = Handle<HwProgram>;
|
||||
using RenderPrimitiveHandle = Handle<HwRenderPrimitive>;
|
||||
using RenderTargetHandle = Handle<HwRenderTarget>;
|
||||
using SamplerGroupHandle = Handle<HwSamplerGroup>;
|
||||
using StreamHandle = Handle<HwStream>;
|
||||
using SwapChainHandle = Handle<HwSwapChain>;
|
||||
using TextureHandle = Handle<HwTexture>;
|
||||
using TimerQueryHandle = Handle<HwTimerQuery>;
|
||||
using VertexBufferHandle = Handle<HwVertexBuffer>;
|
||||
using VertexBufferInfoHandle = Handle<HwVertexBufferInfo>;
|
||||
using BufferObjectHandle = Handle<HwBufferObject>;
|
||||
using FenceHandle = Handle<HwFence>;
|
||||
using IndexBufferHandle = Handle<HwIndexBuffer>;
|
||||
using ProgramHandle = Handle<HwProgram>;
|
||||
using RenderPrimitiveHandle = Handle<HwRenderPrimitive>;
|
||||
using RenderTargetHandle = Handle<HwRenderTarget>;
|
||||
using StreamHandle = Handle<HwStream>;
|
||||
using SwapChainHandle = Handle<HwSwapChain>;
|
||||
using TextureHandle = Handle<HwTexture>;
|
||||
using TimerQueryHandle = Handle<HwTimerQuery>;
|
||||
using VertexBufferHandle = Handle<HwVertexBuffer>;
|
||||
using VertexBufferInfoHandle = Handle<HwVertexBufferInfo>;
|
||||
using DescriptorSetLayoutHandle = Handle<HwDescriptorSetLayout>;
|
||||
using DescriptorSetHandle = Handle<HwDescriptorSet>;
|
||||
|
||||
} // namespace filament::backend
|
||||
|
||||
|
||||
@@ -22,15 +22,23 @@
|
||||
|
||||
#include <utils/ostream.h>
|
||||
|
||||
#include <array>
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
namespace filament::backend {
|
||||
|
||||
//! \privatesection
|
||||
|
||||
struct PipelineLayout {
|
||||
using SetLayout = std::array<Handle<HwDescriptorSetLayout>, MAX_DESCRIPTOR_SET_COUNT>;
|
||||
SetLayout setLayout; // 16
|
||||
};
|
||||
|
||||
struct PipelineState {
|
||||
Handle<HwProgram> program; // 4
|
||||
Handle<HwVertexBufferInfo> vertexBufferInfo; // 4
|
||||
PipelineLayout pipelineLayout; // 16
|
||||
RasterState rasterState; // 4
|
||||
StencilState stencilState; // 12
|
||||
PolygonOffset polygonOffset; // 8
|
||||
|
||||
@@ -25,6 +25,8 @@
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
#include <atomic>
|
||||
|
||||
namespace filament::backend {
|
||||
|
||||
class Driver;
|
||||
@@ -41,6 +43,70 @@ public:
|
||||
struct Fence {};
|
||||
struct Stream {};
|
||||
|
||||
class ExternalImageHandle;
|
||||
|
||||
class ExternalImage {
|
||||
friend class ExternalImageHandle;
|
||||
std::atomic_uint32_t mRefCount{0};
|
||||
protected:
|
||||
virtual ~ExternalImage() noexcept;
|
||||
};
|
||||
|
||||
class ExternalImageHandle {
|
||||
ExternalImage* UTILS_NULLABLE mTarget = nullptr;
|
||||
static void incref(ExternalImage* UTILS_NULLABLE p) noexcept;
|
||||
static void decref(ExternalImage* UTILS_NULLABLE p) noexcept;
|
||||
|
||||
public:
|
||||
ExternalImageHandle() noexcept;
|
||||
~ExternalImageHandle() noexcept;
|
||||
explicit ExternalImageHandle(ExternalImage* UTILS_NULLABLE p) noexcept;
|
||||
ExternalImageHandle(ExternalImageHandle const& rhs) noexcept;
|
||||
ExternalImageHandle(ExternalImageHandle&& rhs) noexcept;
|
||||
ExternalImageHandle& operator=(ExternalImageHandle const& rhs) noexcept;
|
||||
ExternalImageHandle& operator=(ExternalImageHandle&& rhs) noexcept;
|
||||
|
||||
explicit operator bool() const noexcept { return mTarget != nullptr; }
|
||||
|
||||
ExternalImage* UTILS_NULLABLE get() noexcept { return mTarget; }
|
||||
ExternalImage const* UTILS_NULLABLE get() const noexcept { return mTarget; }
|
||||
|
||||
ExternalImage* UTILS_NULLABLE operator->() noexcept { return mTarget; }
|
||||
ExternalImage const* UTILS_NULLABLE operator->() const noexcept { return mTarget; }
|
||||
|
||||
ExternalImage& operator*() noexcept { return *mTarget; }
|
||||
ExternalImage const& operator*() const noexcept { return *mTarget; }
|
||||
|
||||
void clear() noexcept;
|
||||
void reset(ExternalImage* UTILS_NULLABLE p) noexcept;
|
||||
|
||||
private:
|
||||
friend utils::io::ostream& operator<<(utils::io::ostream& out,
|
||||
ExternalImageHandle const& handle);
|
||||
};
|
||||
|
||||
using ExternalImageHandleRef = ExternalImageHandle const&;
|
||||
|
||||
/**
|
||||
* The type of technique for stereoscopic rendering. (Note that the materials used will need to
|
||||
* be compatible with the chosen technique.)
|
||||
*/
|
||||
enum class StereoscopicType : uint8_t {
|
||||
/**
|
||||
* No stereoscopic rendering
|
||||
*/
|
||||
NONE,
|
||||
/**
|
||||
* Stereoscopic rendering is performed using instanced rendering technique.
|
||||
*/
|
||||
INSTANCED,
|
||||
/**
|
||||
* Stereoscopic rendering is performed using the multiview feature from the graphics
|
||||
* backend.
|
||||
*/
|
||||
MULTIVIEW,
|
||||
};
|
||||
|
||||
struct DriverConfig {
|
||||
/**
|
||||
* Size of handle arena in bytes. Setting to 0 indicates default value is to be used.
|
||||
@@ -48,12 +114,7 @@ public:
|
||||
*/
|
||||
size_t handleArenaSize = 0;
|
||||
|
||||
/**
|
||||
* This number of most-recently destroyed textures will be tracked for use-after-free.
|
||||
* Throws an exception when a texture is freed but still bound to a SamplerGroup and used in
|
||||
* a draw call. 0 disables completely. Currently only respected by the Metal backend.
|
||||
*/
|
||||
size_t textureUseAfterFreePoolSize = 0;
|
||||
size_t metalUploadBufferSizeBytes = 512 * 1024;
|
||||
|
||||
/**
|
||||
* Set to `true` to forcibly disable parallel shader compilation in the backend.
|
||||
@@ -65,6 +126,29 @@ public:
|
||||
* Disable backend handles use-after-free checks.
|
||||
*/
|
||||
bool disableHandleUseAfterFreeCheck = false;
|
||||
|
||||
/**
|
||||
* Disable backend handles tags for heap allocated (fallback) handles
|
||||
*/
|
||||
bool disableHeapHandleTags = false;
|
||||
|
||||
/**
|
||||
* Force GLES2 context if supported, or pretend the context is ES2. Only meaningful on
|
||||
* GLES 3.x backends.
|
||||
*/
|
||||
bool forceGLES2Context = false;
|
||||
|
||||
/**
|
||||
* Sets the technique for stereoscopic rendering.
|
||||
*/
|
||||
StereoscopicType stereoscopicType = StereoscopicType::NONE;
|
||||
|
||||
/**
|
||||
* Assert the native window associated to a SwapChain is valid when calling makeCurrent().
|
||||
* This is only supported for:
|
||||
* - PlatformEGLAndroid
|
||||
*/
|
||||
bool assertNativeWindowIsValid = false;
|
||||
};
|
||||
|
||||
Platform() noexcept;
|
||||
@@ -90,7 +174,7 @@ public:
|
||||
*
|
||||
* @return nullptr on failure, or a pointer to the newly created driver.
|
||||
*/
|
||||
virtual backend::Driver* UTILS_NULLABLE createDriver(void* UTILS_NULLABLE sharedContext,
|
||||
virtual Driver* UTILS_NULLABLE createDriver(void* UTILS_NULLABLE sharedContext,
|
||||
const DriverConfig& driverConfig) noexcept = 0;
|
||||
|
||||
/**
|
||||
|
||||
@@ -48,7 +48,7 @@ namespace filament::backend {
|
||||
* and optional user data:
|
||||
*
|
||||
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
* swapChain->setFrameScheduledCallback(myFrameScheduledCallback, nullptr);
|
||||
* swapChain->setFrameScheduledCallback(nullptr, myFrameScheduledCallback);
|
||||
* if (renderer->beginFrame(swapChain)) {
|
||||
* renderer->render(view);
|
||||
* renderer->endFrame();
|
||||
@@ -58,8 +58,6 @@ namespace filament::backend {
|
||||
* @remark Only Filament's Metal backend supports PresentCallables and frame callbacks. Other
|
||||
* backends ignore the callback (which will never be called) and proceed normally.
|
||||
*
|
||||
* @remark The SwapChain::FrameScheduledCallback is called on an arbitrary thread.
|
||||
*
|
||||
* Applications *must* call each PresentCallable they receive. Each PresentCallable represents a
|
||||
* frame that is waiting to be presented. If an application fails to call a PresentCallable, a
|
||||
* memory leak could occur. To "cancel" the presentation of a frame, pass false to the
|
||||
|
||||
@@ -24,9 +24,11 @@
|
||||
|
||||
#include <backend/DriverEnums.h>
|
||||
|
||||
#include <array> // FIXME: STL headers are not allowed in public headers
|
||||
#include <utility> // FIXME: STL headers are not allowed in public headers
|
||||
#include <variant> // FIXME: STL headers are not allowed in public headers
|
||||
#include <array>
|
||||
#include <unordered_map>
|
||||
#include <tuple>
|
||||
#include <utility>
|
||||
#include <variant>
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
@@ -40,29 +42,36 @@ public:
|
||||
static constexpr size_t UNIFORM_BINDING_COUNT = CONFIG_UNIFORM_BINDING_COUNT;
|
||||
static constexpr size_t SAMPLER_BINDING_COUNT = CONFIG_SAMPLER_BINDING_COUNT;
|
||||
|
||||
struct Sampler {
|
||||
utils::CString name = {}; // name of the sampler in the shader
|
||||
uint32_t binding = 0; // binding point of the sampler in the shader
|
||||
struct Descriptor {
|
||||
utils::CString name;
|
||||
backend::DescriptorType type;
|
||||
backend::descriptor_binding_t binding;
|
||||
};
|
||||
|
||||
struct SamplerGroupData {
|
||||
utils::FixedCapacityVector<Sampler> samplers;
|
||||
ShaderStageFlags stageFlags = ShaderStageFlags::ALL_SHADER_STAGE_FLAGS;
|
||||
struct SpecializationConstant {
|
||||
using Type = std::variant<int32_t, float, bool>;
|
||||
uint32_t id; // id set in glsl
|
||||
Type value; // value and type
|
||||
};
|
||||
|
||||
struct Uniform {
|
||||
struct Uniform { // For ES2 support
|
||||
utils::CString name; // full qualified name of the uniform field
|
||||
uint16_t offset; // offset in 'uint32_t' into the uniform buffer
|
||||
uint8_t size; // >1 for arrays
|
||||
UniformType type; // uniform type
|
||||
};
|
||||
|
||||
using UniformBlockInfo = std::array<utils::CString, UNIFORM_BINDING_COUNT>;
|
||||
using UniformInfo = utils::FixedCapacityVector<Uniform>;
|
||||
using SamplerGroupInfo = std::array<SamplerGroupData, SAMPLER_BINDING_COUNT>;
|
||||
using DescriptorBindingsInfo = utils::FixedCapacityVector<Descriptor>;
|
||||
using DescriptorSetInfo = std::array<DescriptorBindingsInfo, MAX_DESCRIPTOR_SET_COUNT>;
|
||||
using SpecializationConstantsInfo = utils::FixedCapacityVector<SpecializationConstant>;
|
||||
using ShaderBlob = utils::FixedCapacityVector<uint8_t>;
|
||||
using ShaderSource = std::array<ShaderBlob, SHADER_TYPE_COUNT>;
|
||||
|
||||
using AttributesInfo = utils::FixedCapacityVector<std::pair<utils::CString, uint8_t>>;
|
||||
using UniformInfo = utils::FixedCapacityVector<Uniform>;
|
||||
using BindingUniformsInfo = utils::FixedCapacityVector<
|
||||
std::tuple<uint8_t, utils::CString, Program::UniformInfo>>;
|
||||
|
||||
Program() noexcept;
|
||||
|
||||
Program(const Program& rhs) = delete;
|
||||
@@ -79,69 +88,47 @@ public:
|
||||
Program& diagnostics(utils::CString const& name,
|
||||
utils::Invocable<utils::io::ostream&(utils::io::ostream& out)>&& logger);
|
||||
|
||||
// sets one of the program's shader (e.g. vertex, fragment)
|
||||
// Sets one of the program's shader (e.g. vertex, fragment)
|
||||
// string-based shaders are null terminated, consequently the size parameter must include the
|
||||
// null terminating character.
|
||||
Program& shader(ShaderStage shader, void const* data, size_t size);
|
||||
|
||||
// Note: This is only needed for GLES3.0 backends, because the layout(binding=) syntax is
|
||||
// not permitted in glsl. The backend needs a way to associate a uniform block
|
||||
// to a binding point.
|
||||
Program& uniformBlockBindings(
|
||||
utils::FixedCapacityVector<std::pair<utils::CString, uint8_t>> const& uniformBlockBindings) noexcept;
|
||||
// Sets the language of the shader sources provided with shader() (defaults to ESSL3)
|
||||
Program& shaderLanguage(ShaderLanguage shaderLanguage);
|
||||
|
||||
// Note: This is only needed for GLES2.0, this is used to emulate UBO. This function tells
|
||||
// the program everything it needs to know about the uniforms at a given binding
|
||||
Program& uniforms(uint32_t index, UniformInfo const& uniforms) noexcept;
|
||||
// Descriptor binding (set, binding, type -> shader name) info
|
||||
Program& descriptorBindings(backend::descriptor_set_t set,
|
||||
DescriptorBindingsInfo descriptorBindings) noexcept;
|
||||
|
||||
// Note: This is only needed for GLES2.0.
|
||||
Program& attributes(
|
||||
utils::FixedCapacityVector<std::pair<utils::CString, uint8_t>> attributes) noexcept;
|
||||
Program& specializationConstants(SpecializationConstantsInfo specConstants) noexcept;
|
||||
|
||||
// sets the 'bindingPoint' sampler group descriptor for this program.
|
||||
// 'samplers' can be destroyed after this call.
|
||||
// This effectively associates a set of (BindingPoints, index) to a texture unit in the shader.
|
||||
// Or more precisely, what layout(binding=) is set to in GLSL.
|
||||
Program& setSamplerGroup(size_t bindingPoint, ShaderStageFlags stageFlags,
|
||||
Sampler const* samplers, size_t count) noexcept;
|
||||
|
||||
struct SpecializationConstant {
|
||||
using Type = std::variant<int32_t, float, bool>;
|
||||
uint32_t id; // id set in glsl
|
||||
Type value; // value and type
|
||||
struct PushConstant {
|
||||
utils::CString name;
|
||||
ConstantType type;
|
||||
};
|
||||
|
||||
Program& specializationConstants(
|
||||
utils::FixedCapacityVector<SpecializationConstant> specConstants) noexcept;
|
||||
Program& pushConstants(ShaderStage stage,
|
||||
utils::FixedCapacityVector<PushConstant> constants) noexcept;
|
||||
|
||||
Program& cacheId(uint64_t cacheId) noexcept;
|
||||
|
||||
Program& multiview(bool multiview) noexcept;
|
||||
|
||||
// For ES2 support only...
|
||||
Program& uniforms(uint32_t index, utils::CString name, UniformInfo uniforms) noexcept;
|
||||
Program& attributes(AttributesInfo attributes) noexcept;
|
||||
|
||||
//
|
||||
// Getters for program construction...
|
||||
//
|
||||
|
||||
ShaderSource const& getShadersSource() const noexcept { return mShadersSource; }
|
||||
ShaderSource& getShadersSource() noexcept { return mShadersSource; }
|
||||
|
||||
UniformBlockInfo const& getUniformBlockBindings() const noexcept { return mUniformBlocks; }
|
||||
UniformBlockInfo& getUniformBlockBindings() noexcept { return mUniformBlocks; }
|
||||
|
||||
SamplerGroupInfo const& getSamplerGroupInfo() const { return mSamplerGroups; }
|
||||
SamplerGroupInfo& getSamplerGroupInfo() { return mSamplerGroups; }
|
||||
|
||||
auto const& getBindingUniformInfo() const { return mBindingUniformInfo; }
|
||||
auto& getBindingUniformInfo() { return mBindingUniformInfo; }
|
||||
|
||||
auto const& getAttributes() const { return mAttributes; }
|
||||
auto& getAttributes() { return mAttributes; }
|
||||
|
||||
utils::CString const& getName() const noexcept { return mName; }
|
||||
utils::CString& getName() noexcept { return mName; }
|
||||
|
||||
utils::FixedCapacityVector<SpecializationConstant> const& getSpecializationConstants() const noexcept {
|
||||
return mSpecializationConstants;
|
||||
}
|
||||
utils::FixedCapacityVector<SpecializationConstant>& getSpecializationConstants() noexcept {
|
||||
return mSpecializationConstants;
|
||||
}
|
||||
auto const& getShaderLanguage() const { return mShaderLanguage; }
|
||||
|
||||
uint64_t getCacheId() const noexcept { return mCacheId; }
|
||||
|
||||
@@ -149,19 +136,50 @@ public:
|
||||
|
||||
CompilerPriorityQueue getPriorityQueue() const noexcept { return mPriorityQueue; }
|
||||
|
||||
SpecializationConstantsInfo const& getSpecializationConstants() const noexcept {
|
||||
return mSpecializationConstants;
|
||||
}
|
||||
|
||||
SpecializationConstantsInfo& getSpecializationConstants() noexcept {
|
||||
return mSpecializationConstants;
|
||||
}
|
||||
|
||||
DescriptorSetInfo& getDescriptorBindings() noexcept {
|
||||
return mDescriptorBindings;
|
||||
}
|
||||
|
||||
utils::FixedCapacityVector<PushConstant> const& getPushConstants(
|
||||
ShaderStage stage) const noexcept {
|
||||
return mPushConstants[static_cast<uint8_t>(stage)];
|
||||
}
|
||||
|
||||
utils::FixedCapacityVector<PushConstant>& getPushConstants(ShaderStage stage) noexcept {
|
||||
return mPushConstants[static_cast<uint8_t>(stage)];
|
||||
}
|
||||
|
||||
auto const& getBindingUniformInfo() const { return mBindingUniformsInfo; }
|
||||
auto& getBindingUniformInfo() { return mBindingUniformsInfo; }
|
||||
|
||||
auto const& getAttributes() const { return mAttributes; }
|
||||
auto& getAttributes() { return mAttributes; }
|
||||
|
||||
private:
|
||||
friend utils::io::ostream& operator<<(utils::io::ostream& out, const Program& builder);
|
||||
|
||||
UniformBlockInfo mUniformBlocks = {};
|
||||
SamplerGroupInfo mSamplerGroups = {};
|
||||
ShaderSource mShadersSource;
|
||||
ShaderLanguage mShaderLanguage = ShaderLanguage::ESSL3;
|
||||
utils::CString mName;
|
||||
uint64_t mCacheId{};
|
||||
utils::Invocable<utils::io::ostream&(utils::io::ostream& out)> mLogger;
|
||||
utils::FixedCapacityVector<SpecializationConstant> mSpecializationConstants;
|
||||
utils::FixedCapacityVector<std::pair<utils::CString, uint8_t>> mAttributes;
|
||||
std::array<UniformInfo, Program::UNIFORM_BINDING_COUNT> mBindingUniformInfo;
|
||||
CompilerPriorityQueue mPriorityQueue = CompilerPriorityQueue::HIGH;
|
||||
utils::Invocable<utils::io::ostream&(utils::io::ostream& out)> mLogger;
|
||||
SpecializationConstantsInfo mSpecializationConstants;
|
||||
std::array<utils::FixedCapacityVector<PushConstant>, SHADER_TYPE_COUNT> mPushConstants;
|
||||
DescriptorSetInfo mDescriptorBindings;
|
||||
|
||||
// For ES2 support only
|
||||
AttributesInfo mAttributes;
|
||||
BindingUniformsInfo mBindingUniformsInfo;
|
||||
|
||||
// Indicates the current engine was initialized with multiview stereo, and the variant for this
|
||||
// program contains STE flag. This will be referred later for the OpenGL shader compiler to
|
||||
// determine whether shader code replacement for the num_views should be performed.
|
||||
|
||||
@@ -29,17 +29,33 @@ namespace filament::backend {
|
||||
//! \privatesection
|
||||
|
||||
struct TargetBufferInfo {
|
||||
// note: the parameters of this constructor are not in the order of this structure's fields
|
||||
TargetBufferInfo(Handle<HwTexture> handle, uint8_t level, uint16_t layer) noexcept
|
||||
: handle(handle), level(level), layer(layer) {
|
||||
}
|
||||
|
||||
TargetBufferInfo(Handle<HwTexture> handle, uint8_t level) noexcept
|
||||
: handle(handle), level(level) {
|
||||
}
|
||||
|
||||
TargetBufferInfo(Handle<HwTexture> handle) noexcept // NOLINT(*-explicit-constructor)
|
||||
: handle(handle) {
|
||||
}
|
||||
|
||||
TargetBufferInfo() noexcept = default;
|
||||
|
||||
// texture to be used as render target
|
||||
Handle<HwTexture> handle;
|
||||
|
||||
// starting layer index for multiview. This value is only used when the `layerCount` for the
|
||||
// render target is greater than 1.
|
||||
uint8_t baseViewIndex = 0;
|
||||
|
||||
// level to be used
|
||||
uint8_t level = 0;
|
||||
|
||||
// for cubemaps and 3D textures. See TextureCubemapFace for the face->layer mapping
|
||||
// - For cubemap textures, this indicates the face of the cubemap. See TextureCubemapFace for
|
||||
// the face->layer mapping)
|
||||
// - For 2d array, cubemap array, and 3d textures, this indicates an index of a single layer of
|
||||
// them.
|
||||
// - For multiview textures (i.e., layerCount for the RenderTarget is greater than 1), this
|
||||
// indicates a starting layer index of the current 2d array texture for multiview.
|
||||
uint16_t layer = 0;
|
||||
};
|
||||
|
||||
@@ -64,7 +80,7 @@ public:
|
||||
|
||||
MRT() noexcept = default;
|
||||
|
||||
MRT(TargetBufferInfo const& color) noexcept // NOLINT(hicpp-explicit-conversions)
|
||||
MRT(TargetBufferInfo const& color) noexcept // NOLINT(hicpp-explicit-conversions, *-explicit-constructor)
|
||||
: mInfos{ color } {
|
||||
}
|
||||
|
||||
@@ -84,7 +100,7 @@ public:
|
||||
|
||||
// this is here for backward compatibility
|
||||
MRT(Handle<HwTexture> handle, uint8_t level, uint16_t layer) noexcept
|
||||
: mInfos{{ handle, 0, level, layer }} {
|
||||
: mInfos{{ handle, level, layer }} {
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -23,9 +23,11 @@
|
||||
|
||||
#include <utils/compiler.h>
|
||||
#include <utils/Invocable.h>
|
||||
#include <utils/CString.h>
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
#include <math/mat3.h>
|
||||
|
||||
namespace filament::backend {
|
||||
|
||||
@@ -51,12 +53,23 @@ protected:
|
||||
~OpenGLPlatform() noexcept override;
|
||||
|
||||
public:
|
||||
|
||||
struct ExternalTexture {
|
||||
unsigned int target; // GLenum target
|
||||
unsigned int id; // GLuint id
|
||||
unsigned int target; // GLenum target
|
||||
unsigned int id; // GLuint id
|
||||
};
|
||||
|
||||
/**
|
||||
* Return the OpenGL vendor string of the specified Driver instance.
|
||||
* @return The GL_VENDOR string
|
||||
*/
|
||||
static utils::CString getVendorString(Driver const* UTILS_NONNULL driver);
|
||||
|
||||
/**
|
||||
* Return the OpenGL vendor string of the specified Driver instance
|
||||
* @return The GL_RENDERER string
|
||||
*/
|
||||
static utils::CString getRendererString(Driver const* UTILS_NONNULL driver);
|
||||
|
||||
/**
|
||||
* Called by the driver to destroy the OpenGL context. This should clean up any windows
|
||||
* or buffers from initialization. This is for instance where `eglDestroyContext` would be
|
||||
@@ -140,6 +153,23 @@ public:
|
||||
*/
|
||||
virtual uint32_t getDefaultFramebufferObject() noexcept;
|
||||
|
||||
/**
|
||||
* Called by the backend when a frame starts.
|
||||
* @param steady_clock_ns vsync time point on the monotonic clock
|
||||
* @param refreshIntervalNs refresh interval in nanosecond
|
||||
* @param frameId a frame id
|
||||
*/
|
||||
virtual void beginFrame(
|
||||
int64_t monotonic_clock_ns,
|
||||
int64_t refreshIntervalNs,
|
||||
uint32_t frameId) noexcept;
|
||||
|
||||
/**
|
||||
* Called by the backend when a frame ends.
|
||||
* @param frameId the frame id used in beginFrame
|
||||
*/
|
||||
virtual void endFrame(
|
||||
uint32_t frameId) noexcept;
|
||||
|
||||
/**
|
||||
* Type of contexts available
|
||||
@@ -191,6 +221,12 @@ public:
|
||||
utils::Invocable<void()> preContextChange,
|
||||
utils::Invocable<void(size_t index)> postContextChange) noexcept;
|
||||
|
||||
/**
|
||||
* Called by the backend just before calling commit()
|
||||
* @see commit()
|
||||
*/
|
||||
virtual void preCommit() noexcept;
|
||||
|
||||
/**
|
||||
* Called by the driver once the current frame finishes drawing. Typically, this should present
|
||||
* the drawSwapChain. This is for example where `eglMakeCurrent()` would be called.
|
||||
@@ -284,6 +320,13 @@ public:
|
||||
virtual void updateTexImage(Stream* UTILS_NONNULL stream,
|
||||
int64_t* UTILS_NONNULL timestamp) noexcept;
|
||||
|
||||
/**
|
||||
* Returns the transform matrix of the texture attached to the stream.
|
||||
* @param stream Stream to get the transform matrix from
|
||||
* @param uvTransform Output parameter: Transform matrix of the image bound to the texture. Returns identity if not supported.
|
||||
*/
|
||||
virtual math::mat3f getTransformMatrix(Stream* UTILS_NONNULL stream) noexcept;
|
||||
|
||||
|
||||
// --------------------------------------------------------------------------------------------
|
||||
// External Image support
|
||||
@@ -301,36 +344,45 @@ public:
|
||||
* Destroys an external texture handle and associated data.
|
||||
* @param texture a pointer to the handle to destroy.
|
||||
*/
|
||||
virtual void destroyExternalImage(ExternalTexture* UTILS_NONNULL texture) noexcept;
|
||||
virtual void destroyExternalImageTexture(ExternalTexture* UTILS_NONNULL texture) noexcept;
|
||||
|
||||
// called on the application thread to allow Filament to take ownership of the image
|
||||
|
||||
/**
|
||||
* Takes ownership of the externalImage. The externalImage parameter depends on the Platform's
|
||||
* concrete implementation. Ownership is released when destroyExternalImage() is called.
|
||||
* concrete implementation. Ownership is released when destroyExternalImageTexture() is called.
|
||||
*
|
||||
* WARNING: This is called synchronously from the application thread (NOT the Driver thread)
|
||||
*
|
||||
* @param externalImage A token representing the platform's external image.
|
||||
* @see destroyExternalImage
|
||||
* @{
|
||||
*/
|
||||
virtual void retainExternalImage(void* UTILS_NONNULL externalImage) noexcept;
|
||||
|
||||
virtual void retainExternalImage(ExternalImageHandleRef externalImage) noexcept;
|
||||
/** @}*/
|
||||
|
||||
/**
|
||||
* Called to bind the platform-specific externalImage to an ExternalTexture.
|
||||
* ExternalTexture::id is guaranteed to be bound when this method is called and ExternalTexture
|
||||
* is updated with new values for id/target if necessary.
|
||||
*
|
||||
* WARNING: this method is not allowed to change the bound texture, or must restore the previous
|
||||
* binding upon return. This is to avoid problem with a backend doing state caching.
|
||||
* binding upon return. This is to avoid a problem with a backend doing state caching.
|
||||
*
|
||||
* @param externalImage The platform-specific external image.
|
||||
* @param texture an in/out pointer to ExternalTexture, id and target can be updated if necessary.
|
||||
* @return true on success, false on error.
|
||||
* @{
|
||||
*/
|
||||
virtual bool setExternalImage(void* UTILS_NONNULL externalImage,
|
||||
ExternalTexture* UTILS_NONNULL texture) noexcept;
|
||||
|
||||
virtual bool setExternalImage(ExternalImageHandleRef externalImage,
|
||||
ExternalTexture* UTILS_NONNULL texture) noexcept;
|
||||
/** @}*/
|
||||
|
||||
/**
|
||||
* The method allows platforms to convert a user-supplied external image object into a new type
|
||||
* (e.g. HardwareBuffer => EGLImage). The default implementation returns source.
|
||||
|
||||
@@ -17,7 +17,6 @@
|
||||
#ifndef TNT_FILAMENT_BACKEND_OPENGL_OPENGL_PLATFORM_COCOA_GL_H
|
||||
#define TNT_FILAMENT_BACKEND_OPENGL_OPENGL_PLATFORM_COCOA_GL_H
|
||||
|
||||
#include <backend/DriverEnums.h>
|
||||
#include <backend/platforms/OpenGLPlatform.h>
|
||||
|
||||
#include <stdint.h>
|
||||
@@ -34,12 +33,14 @@ public:
|
||||
PlatformCocoaGL();
|
||||
~PlatformCocoaGL() noexcept override;
|
||||
|
||||
ExternalImageHandle createExternalImage(void* cvPixelBuffer) noexcept;
|
||||
|
||||
protected:
|
||||
// --------------------------------------------------------------------------------------------
|
||||
// Platform Interface
|
||||
|
||||
Driver* createDriver(void* sharedContext,
|
||||
const Platform::DriverConfig& driverConfig) noexcept override;
|
||||
const DriverConfig& driverConfig) noexcept override;
|
||||
|
||||
// Currently returns 0
|
||||
int getOSVersion() const noexcept override;
|
||||
@@ -59,10 +60,12 @@ protected:
|
||||
void destroySwapChain(SwapChain* swapChain) noexcept override;
|
||||
bool makeCurrent(ContextType type, SwapChain* drawSwapChain, SwapChain* readSwapChain) noexcept override;
|
||||
void commit(SwapChain* swapChain) noexcept override;
|
||||
OpenGLPlatform::ExternalTexture* createExternalImageTexture() noexcept override;
|
||||
void destroyExternalImage(ExternalTexture* texture) noexcept override;
|
||||
ExternalTexture* createExternalImageTexture() noexcept override;
|
||||
void destroyExternalImageTexture(ExternalTexture* texture) noexcept override;
|
||||
void retainExternalImage(void* externalImage) noexcept override;
|
||||
bool setExternalImage(void* externalImage, ExternalTexture* texture) noexcept override;
|
||||
void retainExternalImage(ExternalImageHandleRef externalImage) noexcept override;
|
||||
bool setExternalImage(ExternalImageHandleRef externalImage, ExternalTexture* texture) noexcept override;
|
||||
|
||||
private:
|
||||
PlatformCocoaGLImpl* pImpl = nullptr;
|
||||
|
||||
@@ -32,11 +32,13 @@ public:
|
||||
PlatformCocoaTouchGL();
|
||||
~PlatformCocoaTouchGL() noexcept override;
|
||||
|
||||
ExternalImageHandle createExternalImage(void* cvPixelBuffer) noexcept;
|
||||
|
||||
// --------------------------------------------------------------------------------------------
|
||||
// Platform Interface
|
||||
|
||||
Driver* createDriver(void* sharedGLContext,
|
||||
const Platform::DriverConfig& driverConfig) noexcept override;
|
||||
const DriverConfig& driverConfig) noexcept override;
|
||||
|
||||
int getOSVersion() const noexcept final { return 0; }
|
||||
|
||||
@@ -56,10 +58,12 @@ public:
|
||||
bool makeCurrent(ContextType type, SwapChain* drawSwapChain, SwapChain* readSwapChain) noexcept override;
|
||||
void commit(SwapChain* swapChain) noexcept override;
|
||||
|
||||
OpenGLPlatform::ExternalTexture* createExternalImageTexture() noexcept override;
|
||||
void destroyExternalImage(ExternalTexture* texture) noexcept override;
|
||||
ExternalTexture* createExternalImageTexture() noexcept override;
|
||||
void destroyExternalImageTexture(ExternalTexture* texture) noexcept override;
|
||||
void retainExternalImage(void* externalImage) noexcept override;
|
||||
bool setExternalImage(void* externalImage, ExternalTexture* texture) noexcept override;
|
||||
void retainExternalImage(ExternalImageHandleRef externalImage) noexcept override;
|
||||
bool setExternalImage(ExternalImageHandleRef externalImage, ExternalTexture* texture) noexcept override;
|
||||
|
||||
private:
|
||||
PlatformCocoaTouchGLImpl* pImpl = nullptr;
|
||||
|
||||
@@ -47,6 +47,11 @@ public:
|
||||
// Return true if we're on an OpenGL platform (as opposed to OpenGL ES). false by default.
|
||||
virtual bool isOpenGL() const noexcept;
|
||||
|
||||
/**
|
||||
* Creates an ExternalImage from a EGLImageKHR
|
||||
*/
|
||||
ExternalImageHandle createExternalImage(EGLImageKHR eglImage) noexcept;
|
||||
|
||||
protected:
|
||||
// --------------------------------------------------------------------------------------------
|
||||
// Helper for EGL configs and attributes parameters
|
||||
@@ -75,8 +80,7 @@ protected:
|
||||
* Initializes EGL, creates the OpenGL context and returns a concrete Driver implementation
|
||||
* that supports OpenGL/OpenGL ES.
|
||||
*/
|
||||
Driver* createDriver(void* sharedContext,
|
||||
const Platform::DriverConfig& driverConfig) noexcept override;
|
||||
Driver* createDriver(void* sharedContext, const DriverConfig& driverConfig) noexcept override;
|
||||
|
||||
/**
|
||||
* This returns zero. This method can be overridden to return something more useful.
|
||||
@@ -118,9 +122,10 @@ protected:
|
||||
void destroyFence(Fence* fence) noexcept override;
|
||||
FenceStatus waitFence(Fence* fence, uint64_t timeout) noexcept override;
|
||||
|
||||
OpenGLPlatform::ExternalTexture* createExternalImageTexture() noexcept override;
|
||||
void destroyExternalImage(ExternalTexture* texture) noexcept override;
|
||||
ExternalTexture* createExternalImageTexture() noexcept override;
|
||||
void destroyExternalImageTexture(ExternalTexture* texture) noexcept override;
|
||||
bool setExternalImage(void* externalImage, ExternalTexture* texture) noexcept override;
|
||||
bool setExternalImage(ExternalImageHandleRef externalImage, ExternalTexture* texture) noexcept override;
|
||||
|
||||
/**
|
||||
* Logs glGetError() to slog.e
|
||||
@@ -188,6 +193,12 @@ protected:
|
||||
|
||||
void initializeGlExtensions() noexcept;
|
||||
|
||||
struct ExternalImageEGL : public ExternalImage {
|
||||
EGLImageKHR eglImage = EGL_NO_IMAGE;
|
||||
protected:
|
||||
~ExternalImageEGL() override;
|
||||
};
|
||||
|
||||
protected:
|
||||
EGLConfig findSwapChainConfig(uint64_t flags, bool window, bool pbuffer) const;
|
||||
|
||||
|
||||
@@ -22,6 +22,10 @@
|
||||
#include <backend/platforms/OpenGLPlatform.h>
|
||||
#include <backend/platforms/PlatformEGL.h>
|
||||
|
||||
#include <utils/android/PerformanceHintManager.h>
|
||||
|
||||
#include <chrono>
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
@@ -53,11 +57,23 @@ protected:
|
||||
Driver* createDriver(void* sharedContext,
|
||||
const Platform::DriverConfig& driverConfig) noexcept override;
|
||||
|
||||
/**
|
||||
* Creates an ExternalImage from a EGLImageKHR
|
||||
*/
|
||||
ExternalImageHandle createExternalImage(AHardwareBuffer const *buffer, bool sRGB) noexcept;
|
||||
|
||||
// --------------------------------------------------------------------------------------------
|
||||
// OpenGLPlatform Interface
|
||||
|
||||
void terminate() noexcept override;
|
||||
|
||||
void beginFrame(
|
||||
int64_t monotonic_clock_ns,
|
||||
int64_t refreshIntervalNs,
|
||||
uint32_t frameId) noexcept override;
|
||||
|
||||
void preCommit() noexcept override;
|
||||
|
||||
/**
|
||||
* Set the presentation time using `eglPresentationTimeANDROID`
|
||||
* @param presentationTimeInNanosecond
|
||||
@@ -70,6 +86,7 @@ protected:
|
||||
void attach(Stream* stream, intptr_t tname) noexcept override;
|
||||
void detach(Stream* stream) noexcept override;
|
||||
void updateTexImage(Stream* stream, int64_t* timestamp) noexcept override;
|
||||
math::mat3f getTransformMatrix(Stream* stream) noexcept override;
|
||||
|
||||
/**
|
||||
* Converts a AHardwareBuffer to EGLImage
|
||||
@@ -78,9 +95,37 @@ protected:
|
||||
*/
|
||||
AcquiredImage transformAcquiredImage(AcquiredImage source) noexcept override;
|
||||
|
||||
bool setExternalImage(ExternalImageHandleRef externalImage, ExternalTexture* texture) noexcept override;
|
||||
|
||||
struct ExternalImageEGLAndroid : public ExternalImageEGL {
|
||||
AHardwareBuffer* aHardwareBuffer = nullptr;
|
||||
bool sRGB = false;
|
||||
protected:
|
||||
~ExternalImageEGLAndroid() override;
|
||||
};
|
||||
|
||||
protected:
|
||||
bool makeCurrent(ContextType type,
|
||||
SwapChain* drawSwapChain,
|
||||
SwapChain* readSwapChain) noexcept override;
|
||||
|
||||
private:
|
||||
struct InitializeJvmForPerformanceManagerIfNeeded {
|
||||
InitializeJvmForPerformanceManagerIfNeeded();
|
||||
};
|
||||
|
||||
int mOSVersion;
|
||||
ExternalStreamManagerAndroid& mExternalStreamManager;
|
||||
InitializeJvmForPerformanceManagerIfNeeded const mInitializeJvmForPerformanceManagerIfNeeded;
|
||||
utils::PerformanceHintManager mPerformanceHintManager;
|
||||
utils::PerformanceHintManager::Session mPerformanceHintSession;
|
||||
|
||||
using clock = std::chrono::high_resolution_clock;
|
||||
clock::time_point mStartTimeOfActualWork;
|
||||
|
||||
void* mNativeWindowLib = nullptr;
|
||||
int32_t (*ANativeWindow_getBuffersDefaultDataSpace)(ANativeWindow* window) = nullptr;
|
||||
bool mAssertNativeWindowIsValid = false;
|
||||
};
|
||||
|
||||
} // namespace filament::backend
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
/*
|
||||
* Copyright (C) 2025 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#ifndef TNT_FILAMENT_BACKEND_PRIVATE_PLATFORMMETAL_OBJC_H
|
||||
#define TNT_FILAMENT_BACKEND_PRIVATE_PLATFORMMETAL_OBJC_H
|
||||
|
||||
#import <Metal/Metal.h>
|
||||
|
||||
namespace filament::backend {
|
||||
|
||||
struct MetalDevice {
|
||||
id<MTLDevice> device;
|
||||
};
|
||||
|
||||
struct MetalCommandQueue {
|
||||
id<MTLCommandQueue> commandQueue;
|
||||
};
|
||||
|
||||
struct MetalCommandBuffer {
|
||||
id<MTLCommandBuffer> commandBuffer;
|
||||
};
|
||||
|
||||
} // namespace filament::backend
|
||||
|
||||
#endif // TNT_FILAMENT_BACKEND_PRIVATE_PLATFORMMETAL_OBJC_H
|
||||
@@ -0,0 +1,92 @@
|
||||
/*
|
||||
* Copyright (C) 2021 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#ifndef TNT_FILAMENT_BACKEND_PRIVATE_PLATFORMMETAL_H
|
||||
#define TNT_FILAMENT_BACKEND_PRIVATE_PLATFORMMETAL_H
|
||||
|
||||
#include <backend/DriverEnums.h>
|
||||
#include <backend/Platform.h>
|
||||
|
||||
namespace filament::backend {
|
||||
|
||||
struct PlatformMetalImpl;
|
||||
|
||||
// In order for this header to be compatible with Objective-C and C++, we use these wrappers around
|
||||
// id<MTL*> objects.
|
||||
// See PlatformMetal-Objc.h.
|
||||
struct MetalDevice;
|
||||
struct MetalCommandQueue;
|
||||
struct MetalCommandBuffer;
|
||||
|
||||
class PlatformMetal final : public Platform {
|
||||
public:
|
||||
PlatformMetal();
|
||||
~PlatformMetal() noexcept override;
|
||||
|
||||
Driver* createDriver(void* sharedContext, const Platform::DriverConfig& driverConfig) noexcept override;
|
||||
int getOSVersion() const noexcept override { return 0; }
|
||||
|
||||
/**
|
||||
* Obtain the preferred Metal device object for the backend to use.
|
||||
*
|
||||
* On desktop platforms, there may be multiple GPUs suitable for rendering, and this method is
|
||||
* free to decide which one to use. On mobile systems with a single GPU, implementations should
|
||||
* simply return the result of MTLCreateSystemDefaultDevice();
|
||||
*/
|
||||
virtual void createDevice(MetalDevice& outDevice) noexcept;
|
||||
|
||||
/**
|
||||
* Create a command submission queue on the Metal device object.
|
||||
*
|
||||
* @param device The device which was returned from createDevice()
|
||||
*/
|
||||
virtual void createCommandQueue(
|
||||
MetalDevice& device, MetalCommandQueue& outCommandQueue) noexcept;
|
||||
|
||||
/**
|
||||
* Obtain a MTLCommandBuffer enqueued on this Platform's MTLCommandQueue. The command buffer is
|
||||
* guaranteed to execute before all subsequent command buffers created either by Filament, or
|
||||
* further calls to this method.
|
||||
*/
|
||||
void createAndEnqueueCommandBuffer(MetalCommandBuffer& outCommandBuffer) noexcept;
|
||||
|
||||
/**
|
||||
* The action to take if a Drawable cannot be acquired.
|
||||
*
|
||||
* Each frame rendered requires a CAMetalDrawable texture, which is presented on-screen at the
|
||||
* completion of each frame. These are limited and provided round-robin style by the system.
|
||||
*/
|
||||
enum class DrawableFailureBehavior : uint8_t {
|
||||
/**
|
||||
* Terminates the application and reports an error message (default).
|
||||
*/
|
||||
PANIC,
|
||||
/*
|
||||
* Aborts execution of the current frame. The Metal backend will attempt to acquire a new
|
||||
* drawable at the next frame.
|
||||
*/
|
||||
ABORT_FRAME
|
||||
};
|
||||
void setDrawableFailureBehavior(DrawableFailureBehavior behavior) noexcept;
|
||||
DrawableFailureBehavior getDrawableFailureBehavior() const noexcept;
|
||||
|
||||
private:
|
||||
PlatformMetalImpl* pImpl = nullptr;
|
||||
};
|
||||
|
||||
} // namespace filament::backend
|
||||
|
||||
#endif // TNT_FILAMENT_BACKEND_PRIVATE_PLATFORMMETAL_H
|
||||
@@ -0,0 +1,64 @@
|
||||
/*
|
||||
* Copyright (C) 2024 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#ifndef TNT_FILAMENT_BACKEND_OPENGL_OPENGL_PLATFORM_OSMESA_H
|
||||
#define TNT_FILAMENT_BACKEND_OPENGL_OPENGL_PLATFORM_OSMESA_H
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
#include "bluegl/BlueGL.h"
|
||||
|
||||
#include <osmesa.h>
|
||||
|
||||
#include <backend/platforms/OpenGLPlatform.h>
|
||||
#include <backend/DriverEnums.h>
|
||||
|
||||
namespace filament::backend {
|
||||
|
||||
/**
|
||||
* A concrete implementation of OpenGLPlatform that uses OSMesa, which is an offscreen
|
||||
* context that can be used in conjunction with Mesa for software rasterization.
|
||||
* See https://docs.mesa3d.org/osmesa.html for more information.
|
||||
*/
|
||||
class PlatformOSMesa : public OpenGLPlatform {
|
||||
protected:
|
||||
// --------------------------------------------------------------------------------------------
|
||||
// Platform Interface
|
||||
|
||||
Driver* createDriver(void* sharedGLContext, const DriverConfig& driverConfig) noexcept override;
|
||||
|
||||
int getOSVersion() const noexcept final override { return 0; }
|
||||
|
||||
// --------------------------------------------------------------------------------------------
|
||||
// OpenGLPlatform Interface
|
||||
|
||||
void terminate() noexcept override;
|
||||
|
||||
SwapChain* createSwapChain(void* nativewindow, uint64_t flags) noexcept override;
|
||||
SwapChain* createSwapChain(uint32_t width, uint32_t height, uint64_t flags) noexcept override;
|
||||
void destroySwapChain(SwapChain* swapChain) noexcept override;
|
||||
bool makeCurrent(ContextType type, SwapChain* drawSwapChain,
|
||||
SwapChain* readSwapChain) noexcept override;
|
||||
void commit(SwapChain* swapChain) noexcept override;
|
||||
|
||||
private:
|
||||
OSMesaContext mContext;
|
||||
void* mOsMesaApi = nullptr;
|
||||
};
|
||||
|
||||
} // namespace filament::backend
|
||||
|
||||
#endif // TNT_FILAMENT_BACKEND_OPENGL_OPENGL_PLATFORM_OSMESA_H
|
||||
@@ -23,9 +23,9 @@
|
||||
|
||||
#include <utils/CString.h>
|
||||
#include <utils/FixedCapacityVector.h>
|
||||
#include <utils/Hash.h>
|
||||
#include <utils/PrivateImplementation.h>
|
||||
|
||||
#include <string_view>
|
||||
#include <tuple>
|
||||
#include <unordered_set>
|
||||
|
||||
@@ -47,6 +47,14 @@ struct VulkanPlatformPrivate;
|
||||
class VulkanPlatform : public Platform, utils::PrivateImplementation<VulkanPlatformPrivate> {
|
||||
public:
|
||||
|
||||
struct ExtensionHashFn {
|
||||
std::size_t operator()(utils::CString const& s) const noexcept {
|
||||
return std::hash<std::string>{}(s.data());
|
||||
}
|
||||
};
|
||||
// Utility for managing device or instance extensions during initialization.
|
||||
using ExtensionSet = std::unordered_set<utils::CString, ExtensionHashFn>;
|
||||
|
||||
/**
|
||||
* A collection of handles to objects and metadata that comprises a Vulkan context. The client
|
||||
* can instantiate this struct and pass to Engine::Builder::sharedContext if they wishes to
|
||||
@@ -63,6 +71,9 @@ public:
|
||||
// where the gpu only has one graphics queue. Then the client needs to ensure that no
|
||||
// concurrent access can occur.
|
||||
uint32_t graphicsQueueIndex = 0xFFFFFFFF;
|
||||
bool debugUtilsSupported = false;
|
||||
bool debugMarkersSupported = false;
|
||||
bool multiviewSupported = false;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -80,6 +91,22 @@ public:
|
||||
VkFormat colorFormat = VK_FORMAT_UNDEFINED;
|
||||
VkFormat depthFormat = VK_FORMAT_UNDEFINED;
|
||||
VkExtent2D extent = {0, 0};
|
||||
uint32_t layerCount = 1;
|
||||
bool isProtected = false;
|
||||
};
|
||||
|
||||
struct ImageSyncData {
|
||||
static constexpr uint32_t INVALID_IMAGE_INDEX = UINT32_MAX;
|
||||
|
||||
// The index of the next image as returned by vkAcquireNextImage or equivalent.
|
||||
uint32_t imageIndex = INVALID_IMAGE_INDEX;
|
||||
|
||||
// Semaphore to be signaled once the image is available.
|
||||
VkSemaphore imageReadySemaphore = VK_NULL_HANDLE;
|
||||
|
||||
// A function called right before vkQueueSubmit. After this call, the image must be
|
||||
// available. This pointer can be null if imageReadySemaphore is not VK_NULL_HANDLE.
|
||||
std::function<void(SwapChainPtr handle)> explicitImageReadyWait = nullptr;
|
||||
};
|
||||
|
||||
VulkanPlatform();
|
||||
@@ -119,6 +146,12 @@ public:
|
||||
* before recreating the swapchain. Default is true.
|
||||
*/
|
||||
bool flushAndWaitOnWindowResize = true;
|
||||
|
||||
/**
|
||||
* Whether the swapchain image should be transitioned to a layout suitable for
|
||||
* presentation. Default is true.
|
||||
*/
|
||||
bool transitionSwapChainImageLayoutForPresent = true;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -147,13 +180,10 @@ public:
|
||||
* corresponding VkImage will be used as the output color attachment. The client should signal
|
||||
* the `clientSignal` semaphore when the image is ready to be used by the backend.
|
||||
* @param handle The handle returned by createSwapChain()
|
||||
* @param clientSignal The semaphore that the client will signal to indicate that the backend
|
||||
* may render into the image.
|
||||
* @param index Pointer to memory that will be filled with the index that corresponding
|
||||
* to an image in the `SwapChainBundle.colors` array.
|
||||
* @param outImageSyncData The synchronization data used for image readiness
|
||||
* @return Result of acquire
|
||||
*/
|
||||
virtual VkResult acquire(SwapChainPtr handle, VkSemaphore clientSignal, uint32_t* index);
|
||||
virtual VkResult acquire(SwapChainPtr handle, ImageSyncData* outImageSyncData);
|
||||
|
||||
/**
|
||||
* Present the image corresponding to `index` to the display. The client should wait on
|
||||
@@ -174,6 +204,13 @@ public:
|
||||
*/
|
||||
virtual bool hasResized(SwapChainPtr handle);
|
||||
|
||||
/**
|
||||
* Check if the surface is protected.
|
||||
* @param handle The handle returned by createSwapChain()
|
||||
* @return Whether the swapchain is protected
|
||||
*/
|
||||
virtual bool isProtected(SwapChainPtr handle);
|
||||
|
||||
/**
|
||||
* Carry out a recreation of the swapchain.
|
||||
* @param handle The handle returned by createSwapChain()
|
||||
@@ -192,6 +229,13 @@ public:
|
||||
virtual SwapChainPtr createSwapChain(void* nativeWindow, uint64_t flags = 0,
|
||||
VkExtent2D extent = {0, 0});
|
||||
|
||||
/**
|
||||
* Allows implementers to provide instance extensions that they'd like to include in the
|
||||
* instance creation.
|
||||
* @return A set of extensions to enable for the instance.
|
||||
*/
|
||||
virtual ExtensionSet getRequiredInstanceExtensions() { return {}; }
|
||||
|
||||
/**
|
||||
* Destroy the swapchain.
|
||||
* @param handle The handle returned by createSwapChain()
|
||||
@@ -235,11 +279,88 @@ public:
|
||||
*/
|
||||
VkQueue getGraphicsQueue() const noexcept;
|
||||
|
||||
private:
|
||||
// Platform dependent helper methods
|
||||
using ExtensionSet = std::unordered_set<std::string_view>;
|
||||
static ExtensionSet getRequiredInstanceExtensions();
|
||||
/**
|
||||
* @return The family index of the protected graphics queue selected for the
|
||||
* Vulkan backend.
|
||||
*/
|
||||
uint32_t getProtectedGraphicsQueueFamilyIndex() const noexcept;
|
||||
|
||||
/**
|
||||
* @return The index of the protected graphics queue (if there are multiple
|
||||
* graphics queues) selected for the Vulkan backend.
|
||||
*/
|
||||
uint32_t getProtectedGraphicsQueueIndex() const noexcept;
|
||||
|
||||
/**
|
||||
* @return The protected queue that was selected for the Vulkan backend.
|
||||
*/
|
||||
VkQueue getProtectedGraphicsQueue() const noexcept;
|
||||
|
||||
struct ExternalImageMetadata {
|
||||
/**
|
||||
* The width of the external image
|
||||
*/
|
||||
uint32_t width;
|
||||
|
||||
/**
|
||||
* The height of the external image
|
||||
*/
|
||||
uint32_t height;
|
||||
|
||||
/**
|
||||
* The layerCount of the external image
|
||||
*/
|
||||
uint32_t layerCount;
|
||||
|
||||
/**
|
||||
* The layer count of the external image
|
||||
*/
|
||||
uint32_t layers;
|
||||
|
||||
/**
|
||||
* The format of the external image
|
||||
*/
|
||||
VkFormat format;
|
||||
|
||||
/**
|
||||
* An external buffer can be protected. This tells you if it is.
|
||||
*/
|
||||
bool isProtected;
|
||||
|
||||
/**
|
||||
* The type of external format (opaque int) if used.
|
||||
*/
|
||||
uint64_t externalFormat;
|
||||
|
||||
/**
|
||||
* Image usage
|
||||
*/
|
||||
VkImageUsageFlags usage;
|
||||
|
||||
/**
|
||||
* Allocation size
|
||||
*/
|
||||
VkDeviceSize allocationSize;
|
||||
|
||||
/**
|
||||
* Heap information
|
||||
*/
|
||||
uint32_t memoryTypeBits;
|
||||
};
|
||||
virtual ExternalImageMetadata getExternalImageMetadata(void* externalImage);
|
||||
|
||||
using ImageData = std::pair<VkImage, VkDeviceMemory>;
|
||||
virtual ImageData createExternalImage(void* externalImage,
|
||||
const ExternalImageMetadata& metadata);
|
||||
|
||||
private:
|
||||
static ExtensionSet getSwapchainInstanceExtensions();
|
||||
static ExternalImageMetadata getExternalImageMetadataImpl(void* externalImage,
|
||||
VkDevice device);
|
||||
static ImageData createExternalImageImpl(void* externalImage, VkDevice device,
|
||||
const VkAllocationCallbacks* allocator, const ExternalImageMetadata& metadata);
|
||||
|
||||
// Platform dependent helper methods
|
||||
using SurfaceBundle = std::tuple<VkSurfaceKHR, VkExtent2D>;
|
||||
static SurfaceBundle createVkSurfaceKHR(void* nativeWindow, VkInstance instance,
|
||||
uint64_t flags) noexcept;
|
||||
|
||||
@@ -1,96 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2023 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
/**********************************************************************************************
|
||||
* Generated by bluegl/bluegl-gen.py
|
||||
* DO NOT EDIT
|
||||
**********************************************************************************************/
|
||||
|
||||
#ifndef TNT_FILAMENT_BLUEGL__H
|
||||
#define TNT_FILAMENT_BLUEGL__H
|
||||
|
||||
|
||||
// MSVC includes .../Windows Kits\10\Include\10.0.17763.0\um\GL/gl.h, with gl APIs conflicting with
|
||||
// bluegl\include\GL/glcorearb.h, causing errors for OpenGL APIs such as:
|
||||
// error C2375: 'glBindTexture': redefinition; different linkage
|
||||
#ifndef FILAMENT_PLATFORM_WGL
|
||||
#define GL_GLEXT_PROTOTYPES 1
|
||||
#endif
|
||||
|
||||
|
||||
#include <GL/glcorearb.h>
|
||||
#include <GL/glext.h>
|
||||
|
||||
#if defined(WIN32)
|
||||
|
||||
#ifdef max
|
||||
#undef max
|
||||
#endif
|
||||
|
||||
#ifdef min
|
||||
#undef min
|
||||
#endif
|
||||
|
||||
#ifdef far
|
||||
#undef far
|
||||
#endif
|
||||
|
||||
#ifdef near
|
||||
#undef near
|
||||
#endif
|
||||
|
||||
#ifdef ERROR
|
||||
#undef ERROR
|
||||
#endif
|
||||
|
||||
#ifdef OPAQUE
|
||||
#undef OPAQUE
|
||||
#endif
|
||||
|
||||
#ifdef TRANSPARENT
|
||||
#undef TRANSPARENT
|
||||
#endif
|
||||
|
||||
#ifdef PURE
|
||||
#undef PURE
|
||||
#endif
|
||||
|
||||
#endif
|
||||
|
||||
namespace bluegl {
|
||||
|
||||
/**
|
||||
* Looks up and binds all available OpenGL Core functions.
|
||||
* Every call to this function will increase an internal reference
|
||||
* counter that can be decreased by calling unbind().
|
||||
*
|
||||
* @return 0 on success or -1 if an error occurred.
|
||||
*/
|
||||
int bind();
|
||||
|
||||
/**
|
||||
* Unbinds all available OpenGL Core functions.
|
||||
* Every call to this function will decrease an internal reference
|
||||
* counter and unbind all OpenGL functions when the counter reaches 0.
|
||||
* As such you should assume that no OpenGL calls can be made after
|
||||
* calling this function.
|
||||
*/
|
||||
void unbind();
|
||||
|
||||
|
||||
} // namespace bluegl
|
||||
|
||||
#endif // TNT_FILAMENT_BLUEGL__H
|
||||
File diff suppressed because it is too large
Load Diff
@@ -40,7 +40,7 @@
|
||||
|
||||
#if defined(__ANDROID__)
|
||||
#define VK_USE_PLATFORM_ANDROID_KHR 1
|
||||
#elif defined(IOS)
|
||||
#elif defined(FILAMENT_IOS)
|
||||
#define VK_USE_PLATFORM_IOS_MVK 1
|
||||
#elif defined(__linux__)
|
||||
#if defined(FILAMENT_SUPPORTS_XCB)
|
||||
|
||||
@@ -109,6 +109,7 @@ public:
|
||||
vec4 groundPlane;
|
||||
RayCallback raycastCallback;
|
||||
void* raycastUserdata;
|
||||
bool panning = true;
|
||||
};
|
||||
|
||||
struct Builder {
|
||||
@@ -143,6 +144,8 @@ public:
|
||||
Builder& groundPlane(FLOAT a, FLOAT b, FLOAT c, FLOAT d); //! Plane equation used as a raycast fallback
|
||||
Builder& raycastCallback(RayCallback cb, void* userdata); //! Raycast function for accurate grab-and-pan
|
||||
|
||||
Builder& panning(bool enabled); //! Sets whether panning is enabled
|
||||
|
||||
/**
|
||||
* Creates a new camera manipulator, either ORBIT, MAP, or FREE_FLIGHT.
|
||||
*
|
||||
|
||||
@@ -80,7 +80,8 @@ public:
|
||||
OPENGL = 0x01u,
|
||||
VULKAN = 0x02u,
|
||||
METAL = 0x04u,
|
||||
ALL = OPENGL | VULKAN | METAL
|
||||
WEBGPU = 0x08u,
|
||||
ALL = OPENGL | VULKAN | METAL | WEBGPU
|
||||
};
|
||||
|
||||
/*
|
||||
@@ -134,6 +135,7 @@ protected:
|
||||
TargetApi mTargetApi = (TargetApi) 0;
|
||||
Optimization mOptimization = Optimization::PERFORMANCE;
|
||||
bool mPrintShaders = false;
|
||||
bool mSaveRawVariants = false;
|
||||
bool mGenerateDebugInfo = false;
|
||||
bool mIncludeEssl1 = true;
|
||||
utils::bitset32 mShaderModels;
|
||||
@@ -162,6 +164,7 @@ inline constexpr MaterialBuilderBase::TargetApi targetApiFromBackend(
|
||||
case Backend::OPENGL: return TargetApi::OPENGL;
|
||||
case Backend::VULKAN: return TargetApi::VULKAN;
|
||||
case Backend::METAL: return TargetApi::METAL;
|
||||
case Backend::WEBGPU: return TargetApi::WEBGPU;
|
||||
case Backend::NOOP: return TargetApi::OPENGL;
|
||||
}
|
||||
}
|
||||
@@ -227,6 +230,7 @@ public:
|
||||
|
||||
using ShaderQuality = filament::ShaderQuality;
|
||||
using BlendingMode = filament::BlendingMode;
|
||||
using BlendFunction = filament::backend::BlendFunction;
|
||||
using Shading = filament::Shading;
|
||||
using Interpolation = filament::Interpolation;
|
||||
using VertexDomain = filament::VertexDomain;
|
||||
@@ -244,6 +248,7 @@ public:
|
||||
using CullingMode = filament::backend::CullingMode;
|
||||
using FeatureLevel = filament::backend::FeatureLevel;
|
||||
using StereoscopicType = filament::backend::StereoscopicType;
|
||||
using ShaderStage = filament::backend::ShaderStage;
|
||||
|
||||
enum class VariableQualifier : uint8_t {
|
||||
OUT
|
||||
@@ -313,13 +318,17 @@ public:
|
||||
MaterialBuilder& parameter(const char* name, SamplerType samplerType,
|
||||
SamplerFormat format = SamplerFormat::FLOAT,
|
||||
ParameterPrecision precision = ParameterPrecision::DEFAULT,
|
||||
bool multisample = false) noexcept;
|
||||
bool multisample = false,
|
||||
const char* transformName = "") noexcept;
|
||||
|
||||
MaterialBuilder& buffer(filament::BufferInterfaceBlock bib) noexcept;
|
||||
|
||||
//! Custom variables (all float4).
|
||||
MaterialBuilder& variable(Variable v, const char* name) noexcept;
|
||||
|
||||
MaterialBuilder& variable(Variable v, const char* name,
|
||||
ParameterPrecision precision) noexcept;
|
||||
|
||||
/**
|
||||
* Require a specified attribute.
|
||||
*
|
||||
@@ -407,6 +416,15 @@ public:
|
||||
*/
|
||||
MaterialBuilder& blending(BlendingMode blending) noexcept;
|
||||
|
||||
/**
|
||||
* Set the blend function for this material. blending must be et to CUSTOM.
|
||||
*/
|
||||
MaterialBuilder& customBlendFunctions(
|
||||
BlendFunction srcRGB,
|
||||
BlendFunction srcA,
|
||||
BlendFunction dstRGB,
|
||||
BlendFunction dstA) noexcept;
|
||||
|
||||
/**
|
||||
* Set the blending mode of the post-lighting color for this material.
|
||||
* Only OPAQUE, TRANSPARENT and ADD are supported, the default is TRANSPARENT.
|
||||
@@ -570,11 +588,18 @@ public:
|
||||
*/
|
||||
MaterialBuilder& optimization(Optimization optimization) noexcept;
|
||||
|
||||
// TODO: this is present here for matc's "--print" flag, but ideally does not belong inside
|
||||
// MaterialBuilder.
|
||||
// TODO: this is present here for matc's "--print" flag, but ideally does not belong inside MaterialBuilder.
|
||||
//! If true, will output the generated GLSL shader code to stdout.
|
||||
MaterialBuilder& printShaders(bool printShaders) noexcept;
|
||||
|
||||
/**
|
||||
* If true, this will write the raw generated GLSL for each variant to a text file in the
|
||||
* current directory. The file will be named after the material name and the variant name. Its
|
||||
* extension will be derived from the shader stage. For example, mymaterial_0x0e.frag,
|
||||
* mymaterial_0x18.vert, etc.
|
||||
*/
|
||||
MaterialBuilder& saveRawVariants(bool saveVariants) noexcept;
|
||||
|
||||
//! If true, will include debugging information in generated SPIRV.
|
||||
MaterialBuilder& generateDebugInfo(bool generateDebugInfo) noexcept;
|
||||
|
||||
@@ -626,8 +651,8 @@ public:
|
||||
Parameter() noexcept: parameterType(INVALID) {}
|
||||
|
||||
// Sampler
|
||||
Parameter(const char* paramName, SamplerType t, SamplerFormat f, ParameterPrecision p, bool ms)
|
||||
: name(paramName), size(1), precision(p), samplerType(t), format(f), parameterType(SAMPLER), multisample(ms) { }
|
||||
Parameter(const char* paramName, SamplerType t, SamplerFormat f, ParameterPrecision p, bool ms, const char* tn)
|
||||
: name(paramName), size(1), precision(p), samplerType(t), format(f), parameterType(SAMPLER), multisample(ms), transformName(tn) { }
|
||||
|
||||
// Uniform
|
||||
Parameter(const char* paramName, UniformType t, size_t typeSize, ParameterPrecision p)
|
||||
@@ -645,6 +670,7 @@ public:
|
||||
SubpassType subpassType;
|
||||
SamplerFormat format;
|
||||
bool multisample;
|
||||
utils::CString transformName;
|
||||
enum {
|
||||
INVALID,
|
||||
UNIFORM,
|
||||
@@ -682,18 +708,30 @@ public:
|
||||
} defaultValue;
|
||||
};
|
||||
|
||||
struct PushConstant {
|
||||
utils::CString name;
|
||||
ConstantType type;
|
||||
ShaderStage stage;
|
||||
};
|
||||
|
||||
struct CustomVariable {
|
||||
utils::CString name;
|
||||
Precision precision = Precision::DEFAULT;
|
||||
bool hasPrecision = false;
|
||||
};
|
||||
|
||||
static constexpr size_t MATERIAL_PROPERTIES_COUNT = filament::MATERIAL_PROPERTIES_COUNT;
|
||||
using Property = filament::Property;
|
||||
|
||||
using PropertyList = bool[MATERIAL_PROPERTIES_COUNT];
|
||||
using VariableList = utils::CString[MATERIAL_VARIABLES_COUNT];
|
||||
using VariableList = CustomVariable[MATERIAL_VARIABLES_COUNT];
|
||||
using OutputList = std::vector<Output>;
|
||||
|
||||
static constexpr size_t MAX_COLOR_OUTPUT = filament::backend::MRT::MAX_SUPPORTED_RENDER_TARGET_COUNT;
|
||||
static constexpr size_t MAX_DEPTH_OUTPUT = 1;
|
||||
static_assert(MAX_COLOR_OUTPUT == 8,
|
||||
"When updating MRT::MAX_SUPPORTED_RENDER_TARGET_COUNT, manually update post_process_inputs.fs"
|
||||
" and post_process.fs");
|
||||
" and post_process_main.fs");
|
||||
|
||||
// Preview the first shader generated by the given CodeGenParams.
|
||||
// This is used to run Static Code Analysis before generating a package.
|
||||
@@ -710,6 +748,7 @@ public:
|
||||
using SubpassList = Parameter[MAX_SUBPASS_COUNT];
|
||||
using BufferList = std::vector<std::unique_ptr<filament::BufferInterfaceBlock>>;
|
||||
using ConstantList = std::vector<Constant>;
|
||||
using PushConstantList = std::vector<PushConstant>;
|
||||
|
||||
// returns the number of parameters declared in this material
|
||||
uint8_t getParameterCount() const noexcept { return mParameterCount; }
|
||||
@@ -753,6 +792,10 @@ private:
|
||||
|
||||
void prepareToBuild(MaterialInfo& info) noexcept;
|
||||
|
||||
// Initialize internal push constants that will both be written to the shaders and material
|
||||
// chunks (like user-defined spec constants).
|
||||
void initPushConstants() noexcept;
|
||||
|
||||
// Return true if the shader is syntactically and semantically valid.
|
||||
// This method finds all the properties defined in the fragment and
|
||||
// vertex shaders of the material.
|
||||
@@ -819,6 +862,7 @@ private:
|
||||
PropertyList mProperties;
|
||||
ParameterList mParameters;
|
||||
ConstantList mConstants;
|
||||
PushConstantList mPushConstants;
|
||||
SubpassList mSubpasses;
|
||||
VariableList mVariables;
|
||||
OutputList mOutputs;
|
||||
@@ -828,6 +872,7 @@ private:
|
||||
FeatureLevel mFeatureLevel = FeatureLevel::FEATURE_LEVEL_1;
|
||||
BlendingMode mBlendingMode = BlendingMode::OPAQUE;
|
||||
BlendingMode mPostLightingBlendingMode = BlendingMode::TRANSPARENT;
|
||||
std::array<BlendFunction, 4> mCustomBlendFunctions = {};
|
||||
CullingMode mCullingMode = CullingMode::BACK;
|
||||
Shading mShading = Shading::LIT;
|
||||
MaterialDomain mMaterialDomain = MaterialDomain::SURFACE;
|
||||
|
||||
@@ -183,7 +183,7 @@ struct UTILS_PUBLIC Aabb {
|
||||
* Returns the 8 corner vertices of the AABB.
|
||||
*/
|
||||
Corners getCorners() const {
|
||||
return Aabb::Corners{ .vertices = {
|
||||
return Corners{ .vertices = {
|
||||
{ min.x, min.y, min.z },
|
||||
{ max.x, min.y, min.z },
|
||||
{ min.x, max.y, min.z },
|
||||
|
||||
@@ -54,7 +54,7 @@ public:
|
||||
using BufferDescriptor = backend::BufferDescriptor;
|
||||
using BindingType = backend::BufferObjectBinding;
|
||||
|
||||
class Builder : public BuilderBase<BuilderDetails> {
|
||||
class Builder : public BuilderBase<BuilderDetails>, public BuilderNameMixin<Builder> {
|
||||
friend struct BuilderDetails;
|
||||
public:
|
||||
Builder() noexcept;
|
||||
@@ -73,11 +73,26 @@ public:
|
||||
|
||||
/**
|
||||
* The binding type for this buffer object. (defaults to VERTEX)
|
||||
* @param BindingType Distinguishes between SSBO, VBO, etc. For now this must be VERTEX.
|
||||
* @param bindingType Distinguishes between SSBO, VBO, etc. For now this must be VERTEX.
|
||||
* @return A reference to this Builder for chaining calls.
|
||||
*/
|
||||
Builder& bindingType(BindingType bindingType) noexcept;
|
||||
|
||||
/**
|
||||
* Associate an optional name with this BufferObject for debugging purposes.
|
||||
*
|
||||
* name will show in error messages and should be kept as short as possible. The name is
|
||||
* truncated to a maximum of 128 characters.
|
||||
*
|
||||
* The name string is copied during this method so clients may free its memory after
|
||||
* the function returns.
|
||||
*
|
||||
* @param name A string to identify this BufferObject
|
||||
* @param len Length of name, should be less than or equal to 128
|
||||
* @return This Builder, for chaining calls.
|
||||
*/
|
||||
Builder& name(const char* UTILS_NONNULL name, size_t len) noexcept;
|
||||
|
||||
/**
|
||||
* Creates the BufferObject and returns a pointer to it. After creation, the buffer
|
||||
* object is uninitialized. Use BufferObject::setBuffer() to initialize it.
|
||||
|
||||
@@ -61,7 +61,7 @@ namespace filament {
|
||||
* filament::Camera* myCamera = engine->createCamera(myCameraEntity);
|
||||
* myCamera->setProjection(45, 16.0/9.0, 0.1, 1.0);
|
||||
* myCamera->lookAt({0, 1.60, 1}, {0, 0, 0});
|
||||
* engine->destroyCameraComponent(myCamera);
|
||||
* engine->destroyCameraComponent(myCameraEntity);
|
||||
* ~~~~~~~~~~~
|
||||
*
|
||||
*
|
||||
@@ -400,14 +400,14 @@ public:
|
||||
* engine.getTransformManager().getInstance(camera->getEntity()), model);
|
||||
* ~~~~~~~~~~~
|
||||
*
|
||||
* @param model The camera position and orientation provided as a rigid transform matrix.
|
||||
* @param modelMatrix The camera position and orientation provided as a rigid transform matrix.
|
||||
*
|
||||
* @note The Camera "looks" towards its -z axis
|
||||
*
|
||||
* @warning \p model must be a rigid transform
|
||||
*/
|
||||
void setModelMatrix(const math::mat4& model) noexcept;
|
||||
void setModelMatrix(const math::mat4f& model) noexcept; //!< @overload
|
||||
void setModelMatrix(const math::mat4& modelMatrix) noexcept;
|
||||
void setModelMatrix(const math::mat4f& modelMatrix) noexcept; //!< @overload
|
||||
|
||||
/** Set the position of an eye relative to this Camera (head).
|
||||
*
|
||||
|
||||
@@ -194,7 +194,7 @@ inline sRGBColorA Color::toSRGB<ACCURATE>(LinearColorA const& color) {
|
||||
}
|
||||
|
||||
inline LinearColor Color::toLinear(RgbType type, math::float3 color) {
|
||||
return (type == RgbType::LINEAR) ? color : Color::toLinear<ACCURATE>(color);
|
||||
return (type == RgbType::LINEAR) ? color : toLinear<ACCURATE>(color);
|
||||
}
|
||||
|
||||
// converts an RGBA color to linear space
|
||||
@@ -202,11 +202,11 @@ inline LinearColor Color::toLinear(RgbType type, math::float3 color) {
|
||||
inline LinearColorA Color::toLinear(RgbaType type, math::float4 color) {
|
||||
switch (type) {
|
||||
case RgbaType::sRGB:
|
||||
return Color::toLinear<ACCURATE>(color) * math::float4{color.a, color.a, color.a, 1.0f};
|
||||
return toLinear<ACCURATE>(color) * math::float4{color.a, color.a, color.a, 1.0f};
|
||||
case RgbaType::LINEAR:
|
||||
return color * math::float4{color.a, color.a, color.a, 1.0f};
|
||||
case RgbaType::PREMULTIPLIED_sRGB:
|
||||
return Color::toLinear<ACCURATE>(color);
|
||||
return toLinear<ACCURATE>(color);
|
||||
case RgbaType::PREMULTIPLIED_LINEAR:
|
||||
return color;
|
||||
}
|
||||
|
||||
@@ -17,6 +17,7 @@
|
||||
#ifndef TNT_FILAMENT_ENGINE_H
|
||||
#define TNT_FILAMENT_ENGINE_H
|
||||
|
||||
|
||||
#include <filament/FilamentAPI.h>
|
||||
|
||||
#include <backend/DriverEnums.h>
|
||||
@@ -24,10 +25,15 @@
|
||||
|
||||
#include <utils/compiler.h>
|
||||
#include <utils/Invocable.h>
|
||||
#include <utils/Slice.h>
|
||||
|
||||
#include <initializer_list>
|
||||
#include <optional>
|
||||
|
||||
#include <stdint.h>
|
||||
#include <stddef.h>
|
||||
|
||||
|
||||
namespace utils {
|
||||
class Entity;
|
||||
class EntityManager;
|
||||
@@ -36,6 +42,10 @@ class JobSystem;
|
||||
|
||||
namespace filament {
|
||||
|
||||
namespace backend {
|
||||
class Driver;
|
||||
} // backend
|
||||
|
||||
class BufferObject;
|
||||
class Camera;
|
||||
class ColorGrading;
|
||||
@@ -179,6 +189,7 @@ public:
|
||||
using DriverConfig = backend::Platform::DriverConfig;
|
||||
using FeatureLevel = backend::FeatureLevel;
|
||||
using StereoscopicType = backend::StereoscopicType;
|
||||
using Driver = backend::Driver;
|
||||
|
||||
/**
|
||||
* Config is used to define the memory footprint used by the engine, such as the
|
||||
@@ -288,19 +299,28 @@ public:
|
||||
*/
|
||||
uint32_t jobSystemThreadCount = 0;
|
||||
|
||||
/*
|
||||
* Number of most-recently destroyed textures to track for use-after-free.
|
||||
/**
|
||||
* When uploading vertex or index data, the Filament Metal backend copies data
|
||||
* into a shared staging area before transferring it to the GPU. This setting controls
|
||||
* the total size of the buffer used to perform these allocations.
|
||||
*
|
||||
* This will cause the backend to throw an exception when a texture is freed but still bound
|
||||
* to a SamplerGroup and used in a draw call. 0 disables completely.
|
||||
* Higher values can improve performance when performing many uploads across a small
|
||||
* number of frames.
|
||||
*
|
||||
* Currently only respected by the Metal backend.
|
||||
* This buffer remains alive throughout the lifetime of the Engine, so this size adds to the
|
||||
* memory footprint of the app and should be set as conservative as possible.
|
||||
*
|
||||
* A value of 0 disables the shared staging buffer entirely; uploads will acquire an
|
||||
* individual buffer from a pool of shared buffers.
|
||||
*
|
||||
* Only respected by the Metal backend.
|
||||
*/
|
||||
size_t textureUseAfterFreePoolSize = 0;
|
||||
size_t metalUploadBufferSizeBytes = 512 * 1024;
|
||||
|
||||
/**
|
||||
* Set to `true` to forcibly disable parallel shader compilation in the backend.
|
||||
* Currently only honored by the GL and Metal backends.
|
||||
* @deprecated use "backend.disable_parallel_shader_compile" feature flag instead
|
||||
*/
|
||||
bool disableParallelShaderCompile = false;
|
||||
|
||||
@@ -315,7 +335,7 @@ public:
|
||||
*
|
||||
* @see View::setStereoscopicOptions
|
||||
*/
|
||||
StereoscopicType stereoscopicType = StereoscopicType::INSTANCED;
|
||||
StereoscopicType stereoscopicType = StereoscopicType::NONE;
|
||||
|
||||
/*
|
||||
* The number of eyes to render when stereoscopic rendering is enabled. Supported values are
|
||||
@@ -332,17 +352,78 @@ public:
|
||||
uint32_t resourceAllocatorCacheSizeMB = 64;
|
||||
|
||||
/*
|
||||
* This value determines for how many frames are texture entries kept in the cache.
|
||||
* This value determines how many frames texture entries are kept for in the cache. This
|
||||
* is a soft limit, meaning some texture older than this are allowed to stay in the cache.
|
||||
* Typically only one texture is evicted per frame.
|
||||
* The default is 1.
|
||||
*/
|
||||
uint32_t resourceAllocatorCacheMaxAge = 2;
|
||||
uint32_t resourceAllocatorCacheMaxAge = 1;
|
||||
|
||||
/*
|
||||
* Disable backend handles use-after-free checks.
|
||||
* @deprecated use "backend.disable_handle_use_after_free_check" feature flag instead
|
||||
*/
|
||||
bool disableHandleUseAfterFreeCheck = false;
|
||||
|
||||
/*
|
||||
* Sets a preferred shader language for Filament to use.
|
||||
*
|
||||
* The Metal backend supports two shader languages: MSL (Metal Shading Language) and
|
||||
* METAL_LIBRARY (precompiled .metallib). This option controls which shader language is
|
||||
* used when materials contain both.
|
||||
*
|
||||
* By default, when preferredShaderLanguage is unset, Filament will prefer METAL_LIBRARY
|
||||
* shaders if present within a material, falling back to MSL. Setting
|
||||
* preferredShaderLanguage to ShaderLanguage::MSL will instead instruct Filament to check
|
||||
* for the presence of MSL in a material first, falling back to METAL_LIBRARY if MSL is not
|
||||
* present.
|
||||
*
|
||||
* When using a non-Metal backend, setting this has no effect.
|
||||
*/
|
||||
enum class ShaderLanguage {
|
||||
DEFAULT = 0,
|
||||
MSL = 1,
|
||||
METAL_LIBRARY = 2,
|
||||
};
|
||||
ShaderLanguage preferredShaderLanguage = ShaderLanguage::DEFAULT;
|
||||
|
||||
/*
|
||||
* When the OpenGL ES backend is used, setting this value to true will force a GLES2.0
|
||||
* context if supported by the Platform, or if not, will have the backend pretend
|
||||
* it's a GLES2 context. Ignored on other backends.
|
||||
*/
|
||||
bool forceGLES2Context = false;
|
||||
|
||||
/**
|
||||
* Assert the native window associated to a SwapChain is valid when calling makeCurrent().
|
||||
* This is only supported for:
|
||||
* - PlatformEGLAndroid
|
||||
* @deprecated use "backend.opengl.assert_native_window_is_valid" feature flag instead
|
||||
*/
|
||||
bool assertNativeWindowIsValid = false;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Feature flags can be enabled or disabled when the Engine is built. Some Feature flags can
|
||||
* also be toggled at any time. Feature flags should alawys use their default value unless
|
||||
* the feature enabled by the flag is faulty. Feature flags provide a last resort way to
|
||||
* disable problematic features.
|
||||
* Feature flags are intended to have a short life-time and are regularly removed as features
|
||||
* mature.
|
||||
*/
|
||||
struct FeatureFlag {
|
||||
char const* UTILS_NONNULL name; //!< name of the feature flag
|
||||
char const* UTILS_NONNULL description; //!< short description
|
||||
bool const* UTILS_NONNULL value; //!< pointer to the value of the flag
|
||||
bool constant; //!< whether the flag is constant after construction
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns the list of available feature flags
|
||||
*/
|
||||
utils::Slice<const FeatureFlag> getFeatureFlags() const noexcept;
|
||||
|
||||
#if UTILS_HAS_THREADING
|
||||
using CreateCallback = void(void* UTILS_NULLABLE user, void* UTILS_NONNULL token);
|
||||
#endif
|
||||
@@ -415,6 +496,21 @@ public:
|
||||
*/
|
||||
Builder& paused(bool paused) noexcept;
|
||||
|
||||
/**
|
||||
* Set a feature flag value. This is the only way to set constant feature flags.
|
||||
* @param name feature name
|
||||
* @param value true to enable, false to disable
|
||||
* @return A reference to this Builder for chaining calls.
|
||||
*/
|
||||
Builder& feature(char const* UTILS_NONNULL name, bool value) noexcept;
|
||||
|
||||
/**
|
||||
* Enables a list of features.
|
||||
* @param list list of feature names to enable.
|
||||
* @return A reference to this Builder for chaining calls.
|
||||
*/
|
||||
Builder& features(std::initializer_list<char const *> list) noexcept;
|
||||
|
||||
#if UTILS_HAS_THREADING
|
||||
/**
|
||||
* Creates the filament Engine asynchronously.
|
||||
@@ -448,7 +544,7 @@ public:
|
||||
Platform* UTILS_NULLABLE platform = nullptr,
|
||||
void* UTILS_NULLABLE sharedContext = nullptr,
|
||||
const Config* UTILS_NULLABLE config = nullptr) {
|
||||
return Engine::Builder()
|
||||
return Builder()
|
||||
.backend(backend)
|
||||
.platform(platform)
|
||||
.sharedContext(sharedContext)
|
||||
@@ -468,7 +564,7 @@ public:
|
||||
Platform* UTILS_NULLABLE platform = nullptr,
|
||||
void* UTILS_NULLABLE sharedContext = nullptr,
|
||||
const Config* UTILS_NULLABLE config = nullptr) {
|
||||
Engine::Builder()
|
||||
Builder()
|
||||
.backend(backend)
|
||||
.platform(platform)
|
||||
.sharedContext(sharedContext)
|
||||
@@ -493,6 +589,11 @@ public:
|
||||
static Engine* UTILS_NULLABLE getEngine(void* UTILS_NONNULL token);
|
||||
#endif
|
||||
|
||||
/**
|
||||
* @return the Driver instance used by this Engine.
|
||||
* @see OpenGLPlatform
|
||||
*/
|
||||
backend::Driver const* UTILS_NONNULL getDriver() const noexcept;
|
||||
|
||||
/**
|
||||
* Destroy the Engine instance and all associated resources.
|
||||
@@ -800,24 +901,74 @@ public:
|
||||
bool destroy(const InstanceBuffer* UTILS_NULLABLE p); //!< Destroys an InstanceBuffer object.
|
||||
void destroy(utils::Entity e); //!< Destroys all filament-known components from this entity
|
||||
|
||||
bool isValid(const BufferObject* UTILS_NULLABLE p); //!< Tells whether a BufferObject object is valid
|
||||
bool isValid(const VertexBuffer* UTILS_NULLABLE p); //!< Tells whether an VertexBuffer object is valid
|
||||
bool isValid(const Fence* UTILS_NULLABLE p); //!< Tells whether a Fence object is valid
|
||||
bool isValid(const IndexBuffer* UTILS_NULLABLE p); //!< Tells whether an IndexBuffer object is valid
|
||||
bool isValid(const SkinningBuffer* UTILS_NULLABLE p); //!< Tells whether a SkinningBuffer object is valid
|
||||
bool isValid(const MorphTargetBuffer* UTILS_NULLABLE p); //!< Tells whether a MorphTargetBuffer object is valid
|
||||
bool isValid(const IndirectLight* UTILS_NULLABLE p); //!< Tells whether an IndirectLight object is valid
|
||||
bool isValid(const Material* UTILS_NULLABLE p); //!< Tells whether an IndirectLight object is valid
|
||||
bool isValid(const Renderer* UTILS_NULLABLE p); //!< Tells whether a Renderer object is valid
|
||||
bool isValid(const Scene* UTILS_NULLABLE p); //!< Tells whether a Scene object is valid
|
||||
bool isValid(const Skybox* UTILS_NULLABLE p); //!< Tells whether a SkyBox object is valid
|
||||
bool isValid(const ColorGrading* UTILS_NULLABLE p); //!< Tells whether a ColorGrading object is valid
|
||||
bool isValid(const SwapChain* UTILS_NULLABLE p); //!< Tells whether a SwapChain object is valid
|
||||
bool isValid(const Stream* UTILS_NULLABLE p); //!< Tells whether a Stream object is valid
|
||||
bool isValid(const Texture* UTILS_NULLABLE p); //!< Tells whether a Texture object is valid
|
||||
bool isValid(const RenderTarget* UTILS_NULLABLE p); //!< Tells whether a RenderTarget object is valid
|
||||
bool isValid(const View* UTILS_NULLABLE p); //!< Tells whether a View object is valid
|
||||
bool isValid(const InstanceBuffer* UTILS_NULLABLE p); //!< Tells whether an InstanceBuffer object is valid
|
||||
/** Tells whether a BufferObject object is valid */
|
||||
bool isValid(const BufferObject* UTILS_NULLABLE p) const;
|
||||
/** Tells whether an VertexBuffer object is valid */
|
||||
bool isValid(const VertexBuffer* UTILS_NULLABLE p) const;
|
||||
/** Tells whether a Fence object is valid */
|
||||
bool isValid(const Fence* UTILS_NULLABLE p) const;
|
||||
/** Tells whether an IndexBuffer object is valid */
|
||||
bool isValid(const IndexBuffer* UTILS_NULLABLE p) const;
|
||||
/** Tells whether a SkinningBuffer object is valid */
|
||||
bool isValid(const SkinningBuffer* UTILS_NULLABLE p) const;
|
||||
/** Tells whether a MorphTargetBuffer object is valid */
|
||||
bool isValid(const MorphTargetBuffer* UTILS_NULLABLE p) const;
|
||||
/** Tells whether an IndirectLight object is valid */
|
||||
bool isValid(const IndirectLight* UTILS_NULLABLE p) const;
|
||||
/** Tells whether an Material object is valid */
|
||||
bool isValid(const Material* UTILS_NULLABLE p) const;
|
||||
/** Tells whether an MaterialInstance object is valid. Use this if you already know
|
||||
* which Material this MaterialInstance belongs to. DO NOT USE getMaterial(), this would
|
||||
* defeat the purpose of validating the MaterialInstance.
|
||||
*/
|
||||
bool isValid(const Material* UTILS_NONNULL m, const MaterialInstance* UTILS_NULLABLE p) const;
|
||||
/** Tells whether an MaterialInstance object is valid. Use this if the Material the
|
||||
* MaterialInstance belongs to is not known. This method can be expensive.
|
||||
*/
|
||||
bool isValidExpensive(const MaterialInstance* UTILS_NULLABLE p) const;
|
||||
/** Tells whether a Renderer object is valid */
|
||||
bool isValid(const Renderer* UTILS_NULLABLE p) const;
|
||||
/** Tells whether a Scene object is valid */
|
||||
bool isValid(const Scene* UTILS_NULLABLE p) const;
|
||||
/** Tells whether a SkyBox object is valid */
|
||||
bool isValid(const Skybox* UTILS_NULLABLE p) const;
|
||||
/** Tells whether a ColorGrading object is valid */
|
||||
bool isValid(const ColorGrading* UTILS_NULLABLE p) const;
|
||||
/** Tells whether a SwapChain object is valid */
|
||||
bool isValid(const SwapChain* UTILS_NULLABLE p) const;
|
||||
/** Tells whether a Stream object is valid */
|
||||
bool isValid(const Stream* UTILS_NULLABLE p) const;
|
||||
/** Tells whether a Texture object is valid */
|
||||
bool isValid(const Texture* UTILS_NULLABLE p) const;
|
||||
/** Tells whether a RenderTarget object is valid */
|
||||
bool isValid(const RenderTarget* UTILS_NULLABLE p) const;
|
||||
/** Tells whether a View object is valid */
|
||||
bool isValid(const View* UTILS_NULLABLE p) const;
|
||||
/** Tells whether an InstanceBuffer object is valid */
|
||||
bool isValid(const InstanceBuffer* UTILS_NULLABLE p) const;
|
||||
|
||||
/**
|
||||
* Retrieve the count of each resource tracked by Engine.
|
||||
* This is intended for debugging.
|
||||
* @{
|
||||
*/
|
||||
size_t getBufferObjectCount() const noexcept;
|
||||
size_t getViewCount() const noexcept;
|
||||
size_t getSceneCount() const noexcept;
|
||||
size_t getSwapChainCount() const noexcept;
|
||||
size_t getStreamCount() const noexcept;
|
||||
size_t getIndexBufferCount() const noexcept;
|
||||
size_t getSkinningBufferCount() const noexcept;
|
||||
size_t getMorphTargetBufferCount() const noexcept;
|
||||
size_t getInstanceBufferCount() const noexcept;
|
||||
size_t getVertexBufferCount() const noexcept;
|
||||
size_t getIndirectLightCount() const noexcept;
|
||||
size_t getMaterialCount() const noexcept;
|
||||
size_t getTextureCount() const noexcept;
|
||||
size_t getSkyboxeCount() const noexcept;
|
||||
size_t getColorGradingCount() const noexcept;
|
||||
size_t getRenderTargetCount() const noexcept;
|
||||
/** @} */
|
||||
|
||||
/**
|
||||
* Kicks the hardware thread (e.g. the OpenGL, Vulkan or Metal thread) and blocks until
|
||||
@@ -831,6 +982,25 @@ public:
|
||||
*/
|
||||
void flushAndWait();
|
||||
|
||||
/**
|
||||
* Kicks the hardware thread (e.g. the OpenGL, Vulkan or Metal thread) and blocks until
|
||||
* all commands to this point are executed. Note that does guarantee that the
|
||||
* hardware is actually finished.
|
||||
*
|
||||
* A timeout can be specified, if for some reason this flushAndWait doesn't complete before the timeout, it will
|
||||
* return false, true otherwise.
|
||||
*
|
||||
* <p>This is typically used right after destroying the <code>SwapChain</code>,
|
||||
* in cases where a guarantee about the <code>SwapChain</code> destruction is needed in a
|
||||
* timely fashion, such as when responding to Android's
|
||||
* <code>android.view.SurfaceHolder.Callback.surfaceDestroyed</code></p>
|
||||
*
|
||||
* @param timeout A timeout in nanoseconds
|
||||
* @return true if successful, false if flushAndWait timed out, in which case it wasn't successful and commands
|
||||
* might still be executing on both the CPU and GPU sides.
|
||||
*/
|
||||
bool flushAndWait(uint64_t timeout);
|
||||
|
||||
/**
|
||||
* Kicks the hardware thread (e.g. the OpenGL, Vulkan or Metal thread) but does not wait
|
||||
* for commands to be either executed or the hardware finished.
|
||||
@@ -840,6 +1010,15 @@ public:
|
||||
*/
|
||||
void flush();
|
||||
|
||||
/**
|
||||
* Get paused state of rendering thread.
|
||||
*
|
||||
* <p>Warning: This is an experimental API.
|
||||
*
|
||||
* @see setPaused
|
||||
*/
|
||||
bool isPaused() const noexcept;
|
||||
|
||||
/**
|
||||
* Pause or resume rendering thread.
|
||||
*
|
||||
@@ -865,6 +1044,14 @@ public:
|
||||
*/
|
||||
void pumpMessageQueues();
|
||||
|
||||
/**
|
||||
* Switch the command queue to unprotected mode. Protected mode can be activated via
|
||||
* Renderer::beginFrame() using a protected SwapChain.
|
||||
* @see Renderer
|
||||
* @see SwapChain
|
||||
*/
|
||||
void unprotected() noexcept;
|
||||
|
||||
/**
|
||||
* Returns the default Material.
|
||||
*
|
||||
@@ -948,8 +1135,54 @@ public:
|
||||
void resetBackendState() noexcept;
|
||||
#endif
|
||||
|
||||
/**
|
||||
* Get the current time. This is a convenience function that simply returns the
|
||||
* time in nanosecond since epoch of std::chrono::steady_clock.
|
||||
* A possible implementation is:
|
||||
*
|
||||
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
* return std::chrono::steady_clock::now().time_since_epoch().count();
|
||||
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
*
|
||||
* @return current time in nanosecond since epoch of std::chrono::steady_clock.
|
||||
* @see Renderer::beginFrame()
|
||||
*/
|
||||
static uint64_t getSteadyClockTimeNano() noexcept;
|
||||
|
||||
|
||||
DebugRegistry& getDebugRegistry() noexcept;
|
||||
|
||||
/**
|
||||
* Check if a feature flag exists
|
||||
* @param name name of the feature flag to check
|
||||
* @return true if the feature flag exists, false otherwise
|
||||
*/
|
||||
inline bool hasFeatureFlag(char const* UTILS_NONNULL name) noexcept {
|
||||
return getFeatureFlag(name).has_value();
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the value of a non-constant feature flag.
|
||||
* @param name name of the feature flag to set
|
||||
* @param value value to set
|
||||
* @return true if the value was set, false if the feature flag is constant or doesn't exist.
|
||||
*/
|
||||
bool setFeatureFlag(char const* UTILS_NONNULL name, bool value) noexcept;
|
||||
|
||||
/**
|
||||
* Retrieves the value of any feature flag.
|
||||
* @param name name of the feature flag
|
||||
* @return the value of the flag if it exists
|
||||
*/
|
||||
std::optional<bool> getFeatureFlag(char const* UTILS_NONNULL name) const noexcept;
|
||||
|
||||
/**
|
||||
* Returns a pointer to a non-constant feature flag value.
|
||||
* @param name name of the feature flag
|
||||
* @return a pointer to the feature flag value, or nullptr if the feature flag is constant or doesn't exist
|
||||
*/
|
||||
bool* UTILS_NULLABLE getFeatureFlagPtr(char const* UTILS_NONNULL name) const noexcept;
|
||||
|
||||
protected:
|
||||
//! \privatesection
|
||||
Engine() noexcept = default;
|
||||
|
||||
@@ -19,6 +19,7 @@
|
||||
|
||||
#include <utils/compiler.h>
|
||||
#include <utils/PrivateImplementation.h>
|
||||
#include <utils/CString.h>
|
||||
|
||||
#include <stddef.h>
|
||||
|
||||
@@ -54,6 +55,23 @@ public:
|
||||
template<typename T>
|
||||
using BuilderBase = utils::PrivateImplementation<T>;
|
||||
|
||||
// This needs to be public because it is used in the following template.
|
||||
UTILS_PUBLIC void builderMakeName(utils::CString& outName, const char* name, size_t len) noexcept;
|
||||
|
||||
template <typename Builder>
|
||||
class UTILS_PUBLIC BuilderNameMixin {
|
||||
public:
|
||||
Builder& name(const char* name, size_t len) noexcept {
|
||||
builderMakeName(mName, name, len);
|
||||
return static_cast<Builder&>(*this);
|
||||
}
|
||||
|
||||
utils::CString const& getName() const noexcept { return mName; }
|
||||
|
||||
private:
|
||||
utils::CString mName;
|
||||
};
|
||||
|
||||
} // namespace filament
|
||||
|
||||
#endif // TNT_FILAMENT_FILAMENTAPI_H
|
||||
|
||||
@@ -59,7 +59,7 @@ public:
|
||||
UINT = uint8_t(backend::ElementType::UINT), //!< 32-bit indices
|
||||
};
|
||||
|
||||
class Builder : public BuilderBase<BuilderDetails> {
|
||||
class Builder : public BuilderBase<BuilderDetails>, public BuilderNameMixin<Builder> {
|
||||
friend struct BuilderDetails;
|
||||
public:
|
||||
Builder() noexcept;
|
||||
@@ -83,6 +83,21 @@ public:
|
||||
*/
|
||||
Builder& bufferType(IndexType indexType) noexcept;
|
||||
|
||||
/**
|
||||
* Associate an optional name with this IndexBuffer for debugging purposes.
|
||||
*
|
||||
* name will show in error messages and should be kept as short as possible. The name is
|
||||
* truncated to a maximum of 128 characters.
|
||||
*
|
||||
* The name string is copied during this method so clients may free its memory after
|
||||
* the function returns.
|
||||
*
|
||||
* @param name A string to identify this IndexBuffer
|
||||
* @param len Length of name, should be less than or equal to 128
|
||||
* @return This Builder, for chaining calls.
|
||||
*/
|
||||
Builder& name(const char* UTILS_NONNULL name, size_t len) noexcept;
|
||||
|
||||
/**
|
||||
* Creates the IndexBuffer object and returns a pointer to it. After creation, the index
|
||||
* buffer is uninitialized. Use IndexBuffer::setBuffer() to initialize the IndexBuffer.
|
||||
|
||||
@@ -158,6 +158,8 @@ public:
|
||||
*
|
||||
* @return This Builder, for chaining calls.
|
||||
*
|
||||
* @see Material::Builder::sphericalHarmonicsBandCount()
|
||||
*
|
||||
* @note
|
||||
* Because the coefficients are pre-scaled, `sh[0]` is the environment's
|
||||
* average irradiance.
|
||||
|
||||
@@ -38,7 +38,7 @@ class UTILS_PUBLIC InstanceBuffer : public FilamentAPI {
|
||||
struct BuilderDetails;
|
||||
|
||||
public:
|
||||
class Builder : public BuilderBase<BuilderDetails> {
|
||||
class Builder : public BuilderBase<BuilderDetails>, public BuilderNameMixin<Builder> {
|
||||
friend struct BuilderDetails;
|
||||
|
||||
public:
|
||||
@@ -70,6 +70,21 @@ public:
|
||||
*/
|
||||
Builder& localTransforms(math::mat4f const* UTILS_NULLABLE localTransforms) noexcept;
|
||||
|
||||
/**
|
||||
* Associate an optional name with this InstanceBuffer for debugging purposes.
|
||||
*
|
||||
* name will show in error messages and should be kept as short as possible. The name is
|
||||
* truncated to a maximum of 128 characters.
|
||||
*
|
||||
* The name string is copied during this method so clients may free its memory after
|
||||
* the function returns.
|
||||
*
|
||||
* @param name A string to identify this InstanceBuffer
|
||||
* @param len Length of name, should be less than or equal to 128
|
||||
* @return This Builder, for chaining calls.
|
||||
*/
|
||||
Builder& name(const char* UTILS_NONNULL name, size_t len) noexcept;
|
||||
|
||||
/**
|
||||
* Creates the InstanceBuffer object and returns a pointer to it.
|
||||
*/
|
||||
|
||||
@@ -103,6 +103,11 @@ public:
|
||||
Builder& operator=(Builder const& rhs) noexcept;
|
||||
Builder& operator=(Builder&& rhs) noexcept;
|
||||
|
||||
enum class ShadowSamplingQuality : uint8_t {
|
||||
HARD, // 2x2 PCF
|
||||
LOW // 3x3 gaussian filter
|
||||
};
|
||||
|
||||
/**
|
||||
* Specifies the material data. The material data is a binary blob produced by
|
||||
* libfilamat or by matc.
|
||||
@@ -113,10 +118,10 @@ public:
|
||||
Builder& package(const void* UTILS_NONNULL payload, size_t size);
|
||||
|
||||
template<typename T>
|
||||
using is_supported_constant_parameter_t = typename std::enable_if<
|
||||
std::is_same<int32_t, T>::value ||
|
||||
std::is_same<float, T>::value ||
|
||||
std::is_same<bool, T>::value>::type;
|
||||
using is_supported_constant_parameter_t = std::enable_if_t<
|
||||
std::is_same_v<int32_t, T> ||
|
||||
std::is_same_v<float, T> ||
|
||||
std::is_same_v<bool, T>>;
|
||||
|
||||
/**
|
||||
* Specialize a constant parameter specified in the material definition with a concrete
|
||||
@@ -140,6 +145,26 @@ public:
|
||||
return constant(name, strlen(name), value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the quality of the indirect lights computations. This is only taken into account
|
||||
* if this material is lit and in the surface domain. This setting will affect the
|
||||
* IndirectLight computation if one is specified on the Scene and Spherical Harmonics
|
||||
* are used for the irradiance.
|
||||
*
|
||||
* @param shBandCount Number of spherical harmonic bands. Must be 1, 2 or 3 (default).
|
||||
* @return Reference to this Builder for chaining calls.
|
||||
* @see IndirectLight
|
||||
*/
|
||||
Builder& sphericalHarmonicsBandCount(size_t shBandCount) noexcept;
|
||||
|
||||
/**
|
||||
* Set the quality of shadow sampling. This is only taken into account
|
||||
* if this material is lit and in the surface domain.
|
||||
* @param quality
|
||||
* @return
|
||||
*/
|
||||
Builder& shadowSamplingQuality(ShadowSamplingQuality quality) noexcept;
|
||||
|
||||
/**
|
||||
* Creates the Material object and returns a pointer to it.
|
||||
*
|
||||
@@ -152,7 +177,7 @@ public:
|
||||
* memory or other resources.
|
||||
* @exception utils::PreConditionPanic if a parameter to a builder function was invalid.
|
||||
*/
|
||||
Material* UTILS_NULLABLE build(Engine& engine);
|
||||
Material* UTILS_NULLABLE build(Engine& engine) const;
|
||||
private:
|
||||
friend class FMaterial;
|
||||
};
|
||||
|
||||
@@ -45,13 +45,15 @@ enum UTILS_PUBLIC ChunkType : uint64_t {
|
||||
MaterialEssl1 = charTo64bitNum("MAT_ESS1"),
|
||||
MaterialSpirv = charTo64bitNum("MAT_SPIR"),
|
||||
MaterialMetal = charTo64bitNum("MAT_METL"),
|
||||
MaterialMetalLibrary = charTo64bitNum("MAT_MLIB"),
|
||||
MaterialShaderModels = charTo64bitNum("MAT_SMDL"),
|
||||
MaterialSamplerBindings = charTo64bitNum("MAT_SAMP"),
|
||||
MaterialUniformBindings = charTo64bitNum("MAT_UNIF"),
|
||||
MaterialBindingUniformInfo = charTo64bitNum("MAT_UFRM"),
|
||||
MaterialAttributeInfo = charTo64bitNum("MAT_ATTR"),
|
||||
MaterialDescriptorBindingsInfo = charTo64bitNum("MAT_DBDI"),
|
||||
MaterialDescriptorSetLayoutInfo = charTo64bitNum("MAT_DSLI"),
|
||||
MaterialProperties = charTo64bitNum("MAT_PROP"),
|
||||
MaterialConstants = charTo64bitNum("MAT_CONS"),
|
||||
MaterialPushConstants = charTo64bitNum("MAT_PCON"),
|
||||
|
||||
MaterialName = charTo64bitNum("MAT_NAME"),
|
||||
MaterialVersion = charTo64bitNum("MAT_VERS"),
|
||||
@@ -59,6 +61,7 @@ enum UTILS_PUBLIC ChunkType : uint64_t {
|
||||
MaterialFeatureLevel = charTo64bitNum("MAT_FEAT"),
|
||||
MaterialShading = charTo64bitNum("MAT_SHAD"),
|
||||
MaterialBlendingMode = charTo64bitNum("MAT_BLEN"),
|
||||
MaterialBlendFunction = charTo64bitNum("MAT_BLFN"),
|
||||
MaterialTransparencyMode = charTo64bitNum("MAT_TRMD"),
|
||||
MaterialMaskThreshold = charTo64bitNum("MAT_THRS"),
|
||||
MaterialShadowMultiplier = charTo64bitNum("MAT_SHML"),
|
||||
@@ -89,9 +92,11 @@ enum UTILS_PUBLIC ChunkType : uint64_t {
|
||||
|
||||
MaterialVertexDomain = charTo64bitNum("MAT_VEDO"),
|
||||
MaterialInterpolation = charTo64bitNum("MAT_INTR"),
|
||||
MaterialStereoscopicType = charTo64bitNum("MAT_STER"),
|
||||
|
||||
DictionaryText = charTo64bitNum("DIC_TEXT"),
|
||||
DictionarySpirv = charTo64bitNum("DIC_SPIR"),
|
||||
DictionaryMetalLibrary = charTo64bitNum("DIC_MLIB"),
|
||||
};
|
||||
|
||||
} // namespace filamat
|
||||
|
||||
@@ -28,7 +28,7 @@
|
||||
namespace filament {
|
||||
|
||||
// update this when a new version of filament wouldn't work with older materials
|
||||
static constexpr size_t MATERIAL_VERSION = 51;
|
||||
static constexpr size_t MATERIAL_VERSION = 58;
|
||||
|
||||
/**
|
||||
* Supported shading models
|
||||
@@ -80,6 +80,8 @@ enum class BlendingMode : uint8_t {
|
||||
MULTIPLY,
|
||||
//! material brightens what's behind it
|
||||
SCREEN,
|
||||
//! custom blending function
|
||||
CUSTOM,
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -201,7 +203,7 @@ enum class ReflectionMode : uint8_t {
|
||||
// can't really use std::underlying_type<AttributeIndex>::type because the driver takes a uint32_t
|
||||
using AttributeBitset = utils::bitset32;
|
||||
|
||||
static constexpr size_t MATERIAL_PROPERTIES_COUNT = 27;
|
||||
static constexpr size_t MATERIAL_PROPERTIES_COUNT = 29;
|
||||
enum class Property : uint8_t {
|
||||
BASE_COLOR, //!< float4, all shading models
|
||||
ROUGHNESS, //!< float, lit shading models only
|
||||
@@ -230,6 +232,8 @@ enum class Property : uint8_t {
|
||||
IOR, //!< float, material's index of refraction
|
||||
MICRO_THICKNESS, //!< float, thickness of the thin layer
|
||||
BENT_NORMAL, //!< float3, all shading models only, except unlit
|
||||
SPECULAR_FACTOR, //!< float, lit shading models only, except subsurface and cloth
|
||||
SPECULAR_COLOR_FACTOR, //!< float3, lit shading models only, except subsurface and cloth
|
||||
|
||||
// when adding new Properties, make sure to update MATERIAL_PROPERTIES_COUNT
|
||||
};
|
||||
@@ -253,4 +257,7 @@ enum class UserVariantFilterBit : UserVariantFilterMask {
|
||||
template<> struct utils::EnableBitMaskOperators<filament::UserVariantFilterBit>
|
||||
: public std::true_type {};
|
||||
|
||||
template<> struct utils::EnableIntegerOperators<filament::UserVariantFilterBit>
|
||||
: public std::true_type {};
|
||||
|
||||
#endif
|
||||
|
||||
@@ -56,35 +56,35 @@ class UTILS_PUBLIC MaterialInstance : public FilamentAPI {
|
||||
};
|
||||
|
||||
public:
|
||||
using CullingMode = filament::backend::CullingMode;
|
||||
using TransparencyMode = filament::TransparencyMode;
|
||||
using DepthFunc = filament::backend::SamplerCompareFunc;
|
||||
using StencilCompareFunc = filament::backend::SamplerCompareFunc;
|
||||
using StencilOperation = filament::backend::StencilOperation;
|
||||
using StencilFace = filament::backend::StencilFace;
|
||||
using CullingMode = backend::CullingMode;
|
||||
using TransparencyMode = TransparencyMode;
|
||||
using DepthFunc = backend::SamplerCompareFunc;
|
||||
using StencilCompareFunc = backend::SamplerCompareFunc;
|
||||
using StencilOperation = backend::StencilOperation;
|
||||
using StencilFace = backend::StencilFace;
|
||||
|
||||
template<typename T>
|
||||
using is_supported_parameter_t = typename std::enable_if<
|
||||
std::is_same<float, T>::value ||
|
||||
std::is_same<int32_t, T>::value ||
|
||||
std::is_same<uint32_t, T>::value ||
|
||||
std::is_same<math::int2, T>::value ||
|
||||
std::is_same<math::int3, T>::value ||
|
||||
std::is_same<math::int4, T>::value ||
|
||||
std::is_same<math::uint2, T>::value ||
|
||||
std::is_same<math::uint3, T>::value ||
|
||||
std::is_same<math::uint4, T>::value ||
|
||||
std::is_same<math::float2, T>::value ||
|
||||
std::is_same<math::float3, T>::value ||
|
||||
std::is_same<math::float4, T>::value ||
|
||||
std::is_same<math::mat4f, T>::value ||
|
||||
using is_supported_parameter_t = std::enable_if_t<
|
||||
std::is_same_v<float, T> ||
|
||||
std::is_same_v<int32_t, T> ||
|
||||
std::is_same_v<uint32_t, T> ||
|
||||
std::is_same_v<math::int2, T> ||
|
||||
std::is_same_v<math::int3, T> ||
|
||||
std::is_same_v<math::int4, T> ||
|
||||
std::is_same_v<math::uint2, T> ||
|
||||
std::is_same_v<math::uint3, T> ||
|
||||
std::is_same_v<math::uint4, T> ||
|
||||
std::is_same_v<math::float2, T> ||
|
||||
std::is_same_v<math::float3, T> ||
|
||||
std::is_same_v<math::float4, T> ||
|
||||
std::is_same_v<math::mat4f, T> ||
|
||||
// these types are slower as they need a layout conversion
|
||||
std::is_same<bool, T>::value ||
|
||||
std::is_same<math::bool2, T>::value ||
|
||||
std::is_same<math::bool3, T>::value ||
|
||||
std::is_same<math::bool4, T>::value ||
|
||||
std::is_same<math::mat3f, T>::value
|
||||
>::type;
|
||||
std::is_same_v<bool, T> ||
|
||||
std::is_same_v<math::bool2, T> ||
|
||||
std::is_same_v<math::bool3, T> ||
|
||||
std::is_same_v<math::bool4, T> ||
|
||||
std::is_same_v<math::mat3f, T>
|
||||
>;
|
||||
|
||||
/**
|
||||
* Creates a new MaterialInstance using another MaterialInstance as a template for initialization.
|
||||
@@ -121,13 +121,13 @@ public:
|
||||
|
||||
/** inline helper to provide the name as a null-terminated string literal */
|
||||
template<typename T, typename = is_supported_parameter_t<T>>
|
||||
inline void setParameter(StringLiteral name, T const& value) {
|
||||
void setParameter(StringLiteral const name, T const& value) {
|
||||
setParameter<T>(name.data, name.size, value);
|
||||
}
|
||||
|
||||
/** inline helper to provide the name as a null-terminated C string */
|
||||
template<typename T, typename = is_supported_parameter_t<T>>
|
||||
inline void setParameter(const char* UTILS_NONNULL name, T const& value) {
|
||||
void setParameter(const char* UTILS_NONNULL name, T const& value) {
|
||||
setParameter<T>(name, strlen(name), value);
|
||||
}
|
||||
|
||||
@@ -140,6 +140,7 @@ public:
|
||||
* @param values Array of values to set to the named parameter array.
|
||||
* @param count Size of the array to set.
|
||||
* @throws utils::PreConditionPanic if name doesn't exist or no-op if exceptions are disabled.
|
||||
* @see Material::hasParameter
|
||||
*/
|
||||
template<typename T, typename = is_supported_parameter_t<T>>
|
||||
void setParameter(const char* UTILS_NONNULL name, size_t nameLength,
|
||||
@@ -147,14 +148,14 @@ public:
|
||||
|
||||
/** inline helper to provide the name as a null-terminated string literal */
|
||||
template<typename T, typename = is_supported_parameter_t<T>>
|
||||
inline void setParameter(StringLiteral name, const T* UTILS_NONNULL values, size_t count) {
|
||||
void setParameter(StringLiteral const name, const T* UTILS_NONNULL values, size_t const count) {
|
||||
setParameter<T>(name.data, name.size, values, count);
|
||||
}
|
||||
|
||||
/** inline helper to provide the name as a null-terminated C string */
|
||||
template<typename T, typename = is_supported_parameter_t<T>>
|
||||
inline void setParameter(const char* UTILS_NONNULL name,
|
||||
const T* UTILS_NONNULL values, size_t count) {
|
||||
void setParameter(const char* UTILS_NONNULL name,
|
||||
const T* UTILS_NONNULL values, size_t const count) {
|
||||
setParameter<T>(name, strlen(name), values, count);
|
||||
}
|
||||
|
||||
@@ -175,14 +176,14 @@ public:
|
||||
Texture const* UTILS_NULLABLE texture, TextureSampler const& sampler);
|
||||
|
||||
/** inline helper to provide the name as a null-terminated string literal */
|
||||
inline void setParameter(StringLiteral name,
|
||||
Texture const* UTILS_NULLABLE texture, TextureSampler const& sampler) {
|
||||
void setParameter(StringLiteral const name,
|
||||
Texture const* UTILS_NULLABLE texture, TextureSampler const& sampler) {
|
||||
setParameter(name.data, name.size, texture, sampler);
|
||||
}
|
||||
|
||||
/** inline helper to provide the name as a null-terminated C string */
|
||||
inline void setParameter(const char* UTILS_NONNULL name,
|
||||
Texture const* UTILS_NULLABLE texture, TextureSampler const& sampler) {
|
||||
void setParameter(const char* UTILS_NONNULL name,
|
||||
Texture const* UTILS_NULLABLE texture, TextureSampler const& sampler) {
|
||||
setParameter(name, strlen(name), texture, sampler);
|
||||
}
|
||||
|
||||
@@ -201,12 +202,12 @@ public:
|
||||
RgbType type, math::float3 color);
|
||||
|
||||
/** inline helper to provide the name as a null-terminated string literal */
|
||||
inline void setParameter(StringLiteral name, RgbType type, math::float3 color) {
|
||||
void setParameter(StringLiteral const name, RgbType const type, math::float3 const color) {
|
||||
setParameter(name.data, name.size, type, color);
|
||||
}
|
||||
|
||||
/** inline helper to provide the name as a null-terminated C string */
|
||||
inline void setParameter(const char* UTILS_NONNULL name, RgbType type, math::float3 color) {
|
||||
void setParameter(const char* UTILS_NONNULL name, RgbType const type, math::float3 const color) {
|
||||
setParameter(name, strlen(name), type, color);
|
||||
}
|
||||
|
||||
@@ -225,15 +226,41 @@ public:
|
||||
RgbaType type, math::float4 color);
|
||||
|
||||
/** inline helper to provide the name as a null-terminated string literal */
|
||||
inline void setParameter(StringLiteral name, RgbaType type, math::float4 color) {
|
||||
void setParameter(StringLiteral const name, RgbaType const type, math::float4 const color) {
|
||||
setParameter(name.data, name.size, type, color);
|
||||
}
|
||||
|
||||
/** inline helper to provide the name as a null-terminated C string */
|
||||
inline void setParameter(const char* UTILS_NONNULL name, RgbaType type, math::float4 color) {
|
||||
void setParameter(const char* UTILS_NONNULL name, RgbaType const type, math::float4 const color) {
|
||||
setParameter(name, strlen(name), type, color);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the value of a parameter by name.
|
||||
*
|
||||
* Note: Only supports non-texture parameters such as numeric and math types.
|
||||
*
|
||||
* @param name Name of the parameter as defined by Material. Cannot be nullptr.
|
||||
* @param nameLength Length in `char` of the name parameter.
|
||||
* @throws utils::PreConditionPanic if name doesn't exist or no-op if exceptions are disabled.
|
||||
*
|
||||
* @see Material::hasParameter
|
||||
*/
|
||||
template<typename T>
|
||||
T getParameter(const char* UTILS_NONNULL name, size_t nameLength) const;
|
||||
|
||||
/** inline helper to provide the name as a null-terminated C string */
|
||||
template<typename T, typename = is_supported_parameter_t<T>>
|
||||
T getParameter(StringLiteral const name) const {
|
||||
return getParameter<T>(name.data, name.size);
|
||||
}
|
||||
|
||||
/** inline helper to provide the name as a null-terminated C string */
|
||||
template<typename T, typename = is_supported_parameter_t<T>>
|
||||
T getParameter(const char* UTILS_NONNULL name) const {
|
||||
return getParameter<T>(name, strlen(name));
|
||||
}
|
||||
|
||||
/**
|
||||
* Set-up a custom scissor rectangle; by default it is disabled.
|
||||
*
|
||||
@@ -349,11 +376,22 @@ public:
|
||||
*/
|
||||
void setCullingMode(CullingMode culling) noexcept;
|
||||
|
||||
/**
|
||||
* Overrides the default triangle culling state that was set on the material separately for the
|
||||
* color and shadow passes
|
||||
*/
|
||||
void setCullingMode(CullingMode colorPassCullingMode, CullingMode shadowPassCullingMode) noexcept;
|
||||
|
||||
/**
|
||||
* Returns the face culling mode.
|
||||
*/
|
||||
CullingMode getCullingMode() const noexcept;
|
||||
|
||||
/**
|
||||
* Returns the face culling mode for the shadow passes.
|
||||
*/
|
||||
CullingMode getShadowCullingMode() const noexcept;
|
||||
|
||||
/**
|
||||
* Overrides the default color-buffer write state that was set on the material.
|
||||
*/
|
||||
|
||||
@@ -39,7 +39,7 @@ class UTILS_PUBLIC MorphTargetBuffer : public FilamentAPI {
|
||||
struct BuilderDetails;
|
||||
|
||||
public:
|
||||
class Builder : public BuilderBase<BuilderDetails> {
|
||||
class Builder : public BuilderBase<BuilderDetails>, public BuilderNameMixin<Builder> {
|
||||
friend struct BuilderDetails;
|
||||
public:
|
||||
Builder() noexcept;
|
||||
@@ -63,6 +63,21 @@ public:
|
||||
*/
|
||||
Builder& count(size_t count) noexcept;
|
||||
|
||||
/**
|
||||
* Associate an optional name with this MorphTargetBuffer for debugging purposes.
|
||||
*
|
||||
* name will show in error messages and should be kept as short as possible. The name is
|
||||
* truncated to a maximum of 128 characters.
|
||||
*
|
||||
* The name string is copied during this method so clients may free its memory after
|
||||
* the function returns.
|
||||
*
|
||||
* @param name A string to identify this MorphTargetBuffer
|
||||
* @param len Length of name, should be less than or equal to 128
|
||||
* @return This Builder, for chaining calls.
|
||||
*/
|
||||
Builder& name(const char* UTILS_NONNULL name, size_t len) noexcept;
|
||||
|
||||
/**
|
||||
* Creates the MorphTargetBuffer object and returns a pointer to it.
|
||||
*
|
||||
|
||||
@@ -86,10 +86,10 @@ struct DynamicResolutionOptions {
|
||||
/**
|
||||
* Upscaling quality
|
||||
* LOW: bilinear filtered blit. Fastest, poor quality
|
||||
* MEDIUM: AMD FidelityFX FSR1 w/ mobile optimizations
|
||||
* MEDIUM: Qualcomm Snapdragon Game Super Resolution (SGSR) 1.0
|
||||
* HIGH: AMD FidelityFX FSR1 w/ mobile optimizations
|
||||
* ULTRA: AMD FidelityFX FSR1
|
||||
* FSR1 require a well anti-aliased (MSAA or TAA), noise free scene.
|
||||
* FSR1 and SGSR require a well anti-aliased (MSAA or TAA), noise free scene. Avoid FXAA and dithering.
|
||||
*
|
||||
* The default upscaling quality is set to LOW.
|
||||
*/
|
||||
@@ -438,7 +438,7 @@ struct MultiSampleAntiAliasingOptions {
|
||||
* @see setTemporalAntiAliasingOptions()
|
||||
*/
|
||||
struct TemporalAntiAliasingOptions {
|
||||
float filterWidth = 1.0f; //!< reconstruction filter width typically between 0.2 (sharper, aliased) and 1.5 (smoother)
|
||||
float filterWidth = 1.0f; //!< reconstruction filter width typically between 1 (sharper) and 2 (smoother)
|
||||
float feedback = 0.12f; //!< history feedback, between 0 (maximum temporal AA) and 1 (no temporal AA).
|
||||
float lodBias = -1.0f; //!< texturing lod bias (typically -1 or -2)
|
||||
float sharpness = 0.0f; //!< post-TAA sharpen, especially useful when upscaling is true.
|
||||
|
||||
@@ -118,7 +118,7 @@ public:
|
||||
Builder& mipLevel(AttachmentPoint attachment, uint8_t level) noexcept;
|
||||
|
||||
/**
|
||||
* Sets the cubemap face for a given attachment point.
|
||||
* Sets the face for cubemap textures at the given attachment point.
|
||||
*
|
||||
* @param attachment The attachment point.
|
||||
* @param face The associated cubemap face.
|
||||
@@ -127,7 +127,12 @@ public:
|
||||
Builder& face(AttachmentPoint attachment, CubemapFace face) noexcept;
|
||||
|
||||
/**
|
||||
* Sets the layer for a given attachment point (for 3D textures).
|
||||
* Sets an index of a single layer for 2d array, cubemap array, and 3d textures at the given
|
||||
* attachment point.
|
||||
*
|
||||
* For cubemap array textures, layer is translated into an array index and face according to
|
||||
* - index: layer / 6
|
||||
* - face: layer % 6
|
||||
*
|
||||
* @param attachment The attachment point.
|
||||
* @param layer The associated cubemap layer.
|
||||
@@ -135,6 +140,19 @@ public:
|
||||
*/
|
||||
Builder& layer(AttachmentPoint attachment, uint32_t layer) noexcept;
|
||||
|
||||
/**
|
||||
* Sets the starting index of the 2d array textures for multiview at the given attachment
|
||||
* point.
|
||||
*
|
||||
* This requires COLOR and DEPTH attachments (if set) to be of 2D array textures.
|
||||
*
|
||||
* @param attachment The attachment point.
|
||||
* @param layerCount The number of layers used for multiview, starting from baseLayer.
|
||||
* @param baseLayer The starting index of the 2d array texture.
|
||||
* @return A reference to this Builder for chaining calls.
|
||||
*/
|
||||
Builder& multiview(AttachmentPoint attachment, uint8_t layerCount, uint8_t baseLayer = 0) noexcept;
|
||||
|
||||
/**
|
||||
* Creates the RenderTarget object and returns a pointer to it.
|
||||
*
|
||||
|
||||
@@ -220,7 +220,7 @@ public:
|
||||
* the renderable are immutable.
|
||||
* STATIC geometry has the same restrictions as STATIC_BOUNDS, but in addition disallows
|
||||
* skinning, morphing and changing the VertexBuffer or IndexBuffer in any way.
|
||||
* @param enable whether this renderable has static bounds. false by default.
|
||||
* @param type type of geometry.
|
||||
*/
|
||||
Builder& geometryType(GeometryType type) noexcept;
|
||||
|
||||
@@ -454,7 +454,7 @@ public:
|
||||
*
|
||||
* @param primitiveIndex zero-based index of the primitive, must be less than the primitive
|
||||
* count passed to Builder constructor
|
||||
* @param indicesAndWeightsVectors pairs of bone index and bone weight for all vertices of
|
||||
* @param indicesAndWeightsVector pairs of bone index and bone weight for all vertices of
|
||||
* the primitive sequentially
|
||||
*
|
||||
* @return Builder reference for chaining calls.
|
||||
@@ -464,16 +464,11 @@ public:
|
||||
Builder& boneIndicesAndWeights(size_t primitiveIndex,
|
||||
utils::FixedCapacityVector<
|
||||
utils::FixedCapacityVector<math::float2>> indicesAndWeightsVector) noexcept;
|
||||
|
||||
/**
|
||||
* Controls if the renderable has vertex morphing targets, zero by default. This is
|
||||
* Controls if the renderable has legacy vertex morphing targets, zero by default. This is
|
||||
* required to enable GPU morphing.
|
||||
*
|
||||
* Filament supports two morphing modes: standard (default) and legacy.
|
||||
*
|
||||
* For standard morphing, A MorphTargetBuffer must be created and provided via
|
||||
* RenderableManager::setMorphTargetBufferAt(). Standard morphing supports up to
|
||||
* \c CONFIG_MAX_MORPH_TARGET_COUNT morph targets.
|
||||
*
|
||||
* For legacy morphing, the attached VertexBuffer must provide data in the
|
||||
* appropriate VertexAttribute slots (\c MORPH_POSITION_0 etc). Legacy morphing only
|
||||
* supports up to 4 morph targets and will be deprecated in the future. Legacy morphing must
|
||||
@@ -486,26 +481,29 @@ public:
|
||||
Builder& morphing(size_t targetCount) noexcept;
|
||||
|
||||
/**
|
||||
* Specifies the morph target buffer for a primitive.
|
||||
* Controls if the renderable has vertex morphing targets, zero by default. This is
|
||||
* required to enable GPU morphing.
|
||||
*
|
||||
* The morph target buffer must have an associated renderable and geometry. Two conditions
|
||||
* must be met:
|
||||
* 1. The number of morph targets in the buffer must equal the renderable's morph target
|
||||
* count.
|
||||
* 2. The vertex count of each morph target must equal the geometry's vertex count.
|
||||
* Filament supports two morphing modes: standard (default) and legacy.
|
||||
*
|
||||
* For standard morphing, A MorphTargetBuffer must be provided.
|
||||
* Standard morphing supports up to \c CONFIG_MAX_MORPH_TARGET_COUNT morph targets.
|
||||
*
|
||||
* See also RenderableManager::setMorphWeights(), which can be called on a per-frame basis
|
||||
* to advance the animation.
|
||||
*/
|
||||
Builder& morphing(MorphTargetBuffer* UTILS_NONNULL morphTargetBuffer) noexcept;
|
||||
|
||||
/**
|
||||
* Specifies the the range of the MorphTargetBuffer to use with this primitive.
|
||||
*
|
||||
* @param level the level of detail (lod), only 0 can be specified
|
||||
* @param primitiveIndex zero-based index of the primitive, must be less than the count passed to Builder constructor
|
||||
* @param morphTargetBuffer specifies the morph target buffer
|
||||
* @param offset specifies where in the morph target buffer to start reading (expressed as a number of vertices)
|
||||
* @param count number of vertices in the morph target buffer to read, must equal the geometry's count (for triangles, this should be a multiple of 3)
|
||||
*/
|
||||
Builder& morphing(uint8_t level, size_t primitiveIndex,
|
||||
MorphTargetBuffer* UTILS_NONNULL morphTargetBuffer,
|
||||
size_t offset, size_t count) noexcept;
|
||||
Builder& morphing(uint8_t level,
|
||||
size_t primitiveIndex, size_t offset) noexcept;
|
||||
|
||||
inline Builder& morphing(uint8_t level, size_t primitiveIndex,
|
||||
MorphTargetBuffer* UTILS_NONNULL morphTargetBuffer) noexcept;
|
||||
|
||||
/**
|
||||
* Sets the drawing order for blended primitives. The drawing order is either global or
|
||||
@@ -599,21 +597,6 @@ public:
|
||||
friend class FEngine;
|
||||
friend class FRenderPrimitive;
|
||||
friend class FRenderableManager;
|
||||
struct Entry {
|
||||
VertexBuffer* UTILS_NULLABLE vertices = nullptr;
|
||||
IndexBuffer* UTILS_NULLABLE indices = nullptr;
|
||||
size_t offset = 0;
|
||||
size_t count = 0;
|
||||
MaterialInstance const* UTILS_NULLABLE materialInstance = nullptr;
|
||||
PrimitiveType type = PrimitiveType::TRIANGLES;
|
||||
uint16_t blendOrder = 0;
|
||||
bool globalBlendOrderEnabled = false;
|
||||
struct {
|
||||
MorphTargetBuffer* UTILS_NULLABLE buffer = nullptr;
|
||||
size_t offset = 0;
|
||||
size_t count = 0;
|
||||
} morphing;
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -765,20 +748,13 @@ public:
|
||||
/**
|
||||
* Associates a MorphTargetBuffer to the given primitive.
|
||||
*/
|
||||
void setMorphTargetBufferAt(Instance instance, uint8_t level, size_t primitiveIndex,
|
||||
MorphTargetBuffer* UTILS_NONNULL morphTargetBuffer, size_t offset, size_t count);
|
||||
void setMorphTargetBufferOffsetAt(Instance instance, uint8_t level, size_t primitiveIndex,
|
||||
size_t offset);
|
||||
|
||||
/**
|
||||
* Utility method to change a MorphTargetBuffer to the given primitive
|
||||
* Get a MorphTargetBuffer to the given renderable or null if it doesn't exist.
|
||||
*/
|
||||
inline void setMorphTargetBufferAt(Instance instance, uint8_t level, size_t primitiveIndex,
|
||||
MorphTargetBuffer* UTILS_NONNULL morphTargetBuffer);
|
||||
|
||||
/**
|
||||
* Get a MorphTargetBuffer to the given primitive or null if it doesn't exist.
|
||||
*/
|
||||
MorphTargetBuffer* UTILS_NULLABLE getMorphTargetBufferAt(Instance instance,
|
||||
uint8_t level, size_t primitiveIndex) const noexcept;
|
||||
MorphTargetBuffer* UTILS_NULLABLE getMorphTargetBuffer(Instance instance) const noexcept;
|
||||
|
||||
/**
|
||||
* Gets the number of morphing in the given entity.
|
||||
@@ -822,6 +798,13 @@ public:
|
||||
void setMaterialInstanceAt(Instance instance,
|
||||
size_t primitiveIndex, MaterialInstance const* UTILS_NONNULL materialInstance);
|
||||
|
||||
/**
|
||||
* Clear the MaterialInstance for the given primitive.
|
||||
* @param instance Renderable's instance
|
||||
* @param primitiveIndex Primitive index
|
||||
*/
|
||||
void clearMaterialInstanceAt(Instance instance, size_t primitiveIndex);
|
||||
|
||||
/**
|
||||
* Retrieves the material instance that is bound to the given primitive.
|
||||
*/
|
||||
@@ -869,20 +852,20 @@ public:
|
||||
/*! \cond PRIVATE */
|
||||
template<typename T>
|
||||
struct is_supported_vector_type {
|
||||
using type = typename std::enable_if<
|
||||
std::is_same<math::float4, T>::value ||
|
||||
std::is_same<math::half4, T>::value ||
|
||||
std::is_same<math::float3, T>::value ||
|
||||
std::is_same<math::half3, T>::value
|
||||
>::type;
|
||||
using type = std::enable_if_t<
|
||||
std::is_same_v<math::float4, T> ||
|
||||
std::is_same_v<math::half4, T> ||
|
||||
std::is_same_v<math::float3, T> ||
|
||||
std::is_same_v<math::half3, T>
|
||||
>;
|
||||
};
|
||||
|
||||
template<typename T>
|
||||
struct is_supported_index_type {
|
||||
using type = typename std::enable_if<
|
||||
std::is_same<uint16_t, T>::value ||
|
||||
std::is_same<uint32_t, T>::value
|
||||
>::type;
|
||||
using type = std::enable_if_t<
|
||||
std::is_same_v<uint16_t, T> ||
|
||||
std::is_same_v<uint32_t, T>
|
||||
>;
|
||||
};
|
||||
/*! \endcond */
|
||||
|
||||
@@ -906,20 +889,6 @@ protected:
|
||||
~RenderableManager() = default;
|
||||
};
|
||||
|
||||
RenderableManager::Builder& RenderableManager::Builder::morphing(
|
||||
uint8_t level, size_t primitiveIndex,
|
||||
MorphTargetBuffer* UTILS_NONNULL morphTargetBuffer) noexcept {
|
||||
return morphing(level, primitiveIndex, morphTargetBuffer, 0,
|
||||
morphTargetBuffer->getVertexCount());
|
||||
}
|
||||
|
||||
void RenderableManager::setMorphTargetBufferAt(
|
||||
Instance instance, uint8_t level, size_t primitiveIndex,
|
||||
MorphTargetBuffer* UTILS_NONNULL morphTargetBuffer) {
|
||||
setMorphTargetBufferAt(instance, level, primitiveIndex, morphTargetBuffer, 0,
|
||||
morphTargetBuffer->getVertexCount());
|
||||
}
|
||||
|
||||
template<typename VECTOR, typename INDEX, typename, typename>
|
||||
Box RenderableManager::computeAABB(
|
||||
VECTOR const* UTILS_NONNULL vertices,
|
||||
|
||||
@@ -22,9 +22,11 @@
|
||||
#include <filament/FilamentAPI.h>
|
||||
|
||||
#include <utils/compiler.h>
|
||||
#include <utils/FixedCapacityVector.h>
|
||||
|
||||
#include <math/vec4.h>
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
namespace filament {
|
||||
@@ -81,6 +83,37 @@ public:
|
||||
UTILS_DEPRECATED uint64_t vsyncOffsetNanos = 0;
|
||||
};
|
||||
|
||||
/**
|
||||
* Timing information about a frame
|
||||
* @see getFrameInfoHistory()
|
||||
*/
|
||||
struct FrameInfo {
|
||||
using time_point_ns = int64_t;
|
||||
using duration_ns = int64_t;
|
||||
uint32_t frameId; //!< monotonically increasing frame identifier
|
||||
duration_ns frameTime; //!< frame duration on the GPU in nanosecond [ns]
|
||||
duration_ns denoisedFrameTime; //!< denoised frame duration on the GPU in [ns]
|
||||
time_point_ns beginFrame; //!< Renderer::beginFrame() time since epoch [ns]
|
||||
time_point_ns endFrame; //!< Renderer::endFrame() time since epoch [ns]
|
||||
time_point_ns backendBeginFrame; //!< Backend thread time of frame start since epoch [ns]
|
||||
time_point_ns backendEndFrame; //!< Backend thread time of frame end since epoch [ns]
|
||||
};
|
||||
|
||||
/**
|
||||
* Retrieve an historic of frame timing information. The maximum frame history size is
|
||||
* given by getMaxFrameHistorySize().
|
||||
* @param historySize requested history size. The returned vector could be smaller.
|
||||
* @return A vector of FrameInfo.
|
||||
*/
|
||||
utils::FixedCapacityVector<FrameInfo> getFrameInfoHistory(
|
||||
size_t historySize = 1) const noexcept;
|
||||
|
||||
/**
|
||||
* @return the maximum supported frame history size.
|
||||
* @see getFrameInfoHistory()
|
||||
*/
|
||||
size_t getMaxFrameHistorySize() const noexcept;
|
||||
|
||||
/**
|
||||
* Use FrameRateOptions to set the desired frame rate and control how quickly the system
|
||||
* reacts to GPU load changes.
|
||||
@@ -227,6 +260,25 @@ public:
|
||||
static constexpr CopyFrameFlag CLEAR = 0x4;
|
||||
|
||||
|
||||
/**
|
||||
* The use of this method is optional. It sets the VSYNC time expressed as the duration in
|
||||
* nanosecond since epoch of std::chrono::steady_clock.
|
||||
* If called, passing 0 to vsyncSteadyClockTimeNano in Renderer::BeginFrame will use this
|
||||
* time instead.
|
||||
* @param steadyClockTimeNano duration in nanosecond since epoch of std::chrono::steady_clock
|
||||
* @see Engine::getSteadyClockTimeNano()
|
||||
* @see Renderer::BeginFrame()
|
||||
*/
|
||||
void setVsyncTime(uint64_t steadyClockTimeNano) noexcept;
|
||||
|
||||
/**
|
||||
* Call skipFrame when momentarily skipping frames, for instance if the content of the
|
||||
* scene doesn't change.
|
||||
*
|
||||
* @param vsyncSteadyClockTimeNano
|
||||
*/
|
||||
void skipFrame(uint64_t vsyncSteadyClockTimeNano = 0u);
|
||||
|
||||
/**
|
||||
* Set-up a frame for this Renderer.
|
||||
*
|
||||
@@ -456,7 +508,7 @@ public:
|
||||
*
|
||||
* Framebuffer as seen on User buffer (PixelBufferDescriptor&)
|
||||
* screen
|
||||
*
|
||||
*
|
||||
* +--------------------+
|
||||
* | | .stride .alignment
|
||||
* | | ----------------------->-->
|
||||
@@ -486,6 +538,9 @@ public:
|
||||
* uploaded to it via setImage, the data returned from readPixels will be y-flipped with respect
|
||||
* to the setImage call.
|
||||
*
|
||||
* Note: the texture that backs the COLOR attachment for `renderTarget` must have
|
||||
* TextureUsage::BLIT_SRC as part of its usage.
|
||||
*
|
||||
* @remark
|
||||
* readPixels() is intended for debugging and testing. It will impact performance significantly.
|
||||
*
|
||||
|
||||
@@ -141,6 +141,11 @@ public:
|
||||
*/
|
||||
void removeEntities(const utils::Entity* UTILS_NONNULL entities, size_t count);
|
||||
|
||||
/**
|
||||
* Remove all entities to the Scene.
|
||||
*/
|
||||
void removeAllEntities() noexcept;
|
||||
|
||||
/**
|
||||
* Returns the total number of Entities in the Scene, whether alive or not.
|
||||
* @return Total number of Entities in the Scene.
|
||||
|
||||
@@ -39,7 +39,7 @@ class UTILS_PUBLIC SkinningBuffer : public FilamentAPI {
|
||||
struct BuilderDetails;
|
||||
|
||||
public:
|
||||
class Builder : public BuilderBase<BuilderDetails> {
|
||||
class Builder : public BuilderBase<BuilderDetails>, public BuilderNameMixin<Builder> {
|
||||
friend struct BuilderDetails;
|
||||
public:
|
||||
Builder() noexcept;
|
||||
@@ -69,6 +69,21 @@ public:
|
||||
*/
|
||||
Builder& initialize(bool initialize = true) noexcept;
|
||||
|
||||
/**
|
||||
* Associate an optional name with this SkinningBuffer for debugging purposes.
|
||||
*
|
||||
* name will show in error messages and should be kept as short as possible. The name is
|
||||
* truncated to a maximum of 128 characters.
|
||||
*
|
||||
* The name string is copied during this method so clients may free its memory after
|
||||
* the function returns.
|
||||
*
|
||||
* @param name A string to identify this SkinningBuffer
|
||||
* @param len Length of name, should be less than or equal to 128
|
||||
* @return This Builder, for chaining calls.
|
||||
*/
|
||||
Builder& name(const char* UTILS_NONNULL name, size_t len) noexcept;
|
||||
|
||||
/**
|
||||
* Creates the SkinningBuffer object and returns a pointer to it.
|
||||
*
|
||||
|
||||
@@ -24,6 +24,8 @@
|
||||
|
||||
#include <utils/compiler.h>
|
||||
|
||||
#include <math/mat3.h>
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
namespace filament {
|
||||
@@ -94,7 +96,7 @@ public:
|
||||
*
|
||||
* To create a NATIVE stream, call the <pre>stream</pre> method on the builder.
|
||||
*/
|
||||
class Builder : public BuilderBase<BuilderDetails> {
|
||||
class Builder : public BuilderBase<BuilderDetails>, public BuilderNameMixin<Builder> {
|
||||
friend struct BuilderDetails;
|
||||
public:
|
||||
Builder() noexcept;
|
||||
@@ -136,6 +138,21 @@ public:
|
||||
*/
|
||||
Builder& height(uint32_t height) noexcept;
|
||||
|
||||
/**
|
||||
* Associate an optional name with this Stream for debugging purposes.
|
||||
*
|
||||
* name will show in error messages and should be kept as short as possible. The name is
|
||||
* truncated to a maximum of 128 characters.
|
||||
*
|
||||
* The name string is copied during this method so clients may free its memory after
|
||||
* the function returns.
|
||||
*
|
||||
* @param name A string to identify this Stream
|
||||
* @param len Length of name, should be less than or equal to 128
|
||||
* @return This Builder, for chaining calls.
|
||||
*/
|
||||
Builder& name(const char* UTILS_NONNULL name, size_t len) noexcept;
|
||||
|
||||
/**
|
||||
* Creates the Stream object and returns a pointer to it.
|
||||
*
|
||||
@@ -174,9 +191,10 @@ public:
|
||||
* The callback tales two arguments: the AHardwareBuffer and the userdata.
|
||||
* @param userdata Optional closure data. Filament will pass this into the callback when it
|
||||
* releases the image.
|
||||
* @param transform Optional transform matrix to apply to the image.
|
||||
*/
|
||||
void setAcquiredImage(void* UTILS_NONNULL image,
|
||||
Callback UTILS_NONNULL callback, void* UTILS_NULLABLE userdata) noexcept;
|
||||
Callback UTILS_NONNULL callback, void* UTILS_NULLABLE userdata, math::mat3f const& transform = math::mat3f()) noexcept;
|
||||
|
||||
/**
|
||||
* @see setAcquiredImage(void*, Callback, void*)
|
||||
@@ -187,10 +205,11 @@ public:
|
||||
* It callback tales two arguments: the AHardwareBuffer and the userdata.
|
||||
* @param userdata Optional closure data. Filament will pass this into the callback when it
|
||||
* releases the image.
|
||||
* @param transform Optional transform matrix to apply to the image.
|
||||
*/
|
||||
void setAcquiredImage(void* UTILS_NONNULL image,
|
||||
backend::CallbackHandler* UTILS_NULLABLE handler,
|
||||
Callback UTILS_NONNULL callback, void* UTILS_NULLABLE userdata) noexcept;
|
||||
Callback UTILS_NONNULL callback, void* UTILS_NULLABLE userdata, math::mat3f const& transform = math::mat3f()) noexcept;
|
||||
|
||||
/**
|
||||
* Updates the size of the incoming stream. Whether this value is used is
|
||||
|
||||
@@ -21,6 +21,7 @@
|
||||
|
||||
#include <backend/CallbackHandler.h>
|
||||
#include <backend/DriverEnums.h>
|
||||
#include <backend/PresentCallable.h>
|
||||
|
||||
#include <utils/compiler.h>
|
||||
#include <utils/Invocable.h>
|
||||
@@ -115,7 +116,7 @@ class Engine;
|
||||
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
* SDL_SysWMinfo wmi;
|
||||
* SDL_VERSION(&wmi.version);
|
||||
* ASSERT_POSTCONDITION(SDL_GetWindowWMInfo(sdlWindow, &wmi), "SDL version unsupported!");
|
||||
* FILAMENT_CHECK_POSTCONDITION(SDL_GetWindowWMInfo(sdlWindow, &wmi)) << "SDL version unsupported!";
|
||||
* HDC nativeWindow = (HDC) wmi.info.win.hdc;
|
||||
*
|
||||
* using namespace filament;
|
||||
@@ -253,6 +254,19 @@ public:
|
||||
|
||||
void* UTILS_NULLABLE getNativeWindow() const noexcept;
|
||||
|
||||
/**
|
||||
* If this flag is passed to setFrameScheduledCallback, then the behavior of the default
|
||||
* CallbackHandler (when nullptr is passed as the handler argument) is altered to call the
|
||||
* callback on the Metal completion handler thread (as opposed to the main Filament thread).
|
||||
* This flag also instructs the Metal backend to release the associated CAMetalDrawable on the
|
||||
* completion handler thread.
|
||||
*
|
||||
* This flag has no effect if a custom CallbackHandler is passed.
|
||||
*
|
||||
* @see setFrameScheduledCallback
|
||||
*/
|
||||
static constexpr uint64_t CALLBACK_DEFAULT_USE_METAL_COMPLETION_HANDLER = 1;
|
||||
|
||||
/**
|
||||
* FrameScheduledCallback is a callback function that notifies an application when Filament has
|
||||
* completed processing a frame and that frame is ready to be scheduled for presentation.
|
||||
@@ -264,13 +278,22 @@ public:
|
||||
* backend.
|
||||
*
|
||||
* A FrameScheduledCallback can be set on an individual SwapChain through
|
||||
* SwapChain::setFrameScheduledCallback. If the callback is set, then the SwapChain will *not*
|
||||
* automatically schedule itself for presentation. Instead, the application must call the
|
||||
* PresentCallable passed to the FrameScheduledCallback.
|
||||
* SwapChain::setFrameScheduledCallback. If the callback is set for a given frame, then the
|
||||
* SwapChain will *not* automatically schedule itself for presentation. Instead, the application
|
||||
* must call the PresentCallable passed to the FrameScheduledCallback.
|
||||
*
|
||||
* There may be only one FrameScheduledCallback set per SwapChain. A call to
|
||||
* SwapChain::setFrameScheduledCallback will overwrite any previous FrameScheduledCallbacks set
|
||||
* on the same SwapChain.
|
||||
* Each SwapChain can have only one FrameScheduledCallback set per frame. If
|
||||
* setFrameScheduledCallback is called multiple times on the same SwapChain before
|
||||
* Renderer::endFrame(), the most recent call effectively overwrites any previously set
|
||||
* callback. This allows the callback to be updated as needed before the frame has finished
|
||||
* encoding.
|
||||
*
|
||||
* The "last" callback set by setFrameScheduledCallback gets "latched" when Renderer::endFrame()
|
||||
* is executed. At this point, the state of the callback is fixed and is the one used for the
|
||||
* frame that was just encoded. Subsequent changes to the callback using
|
||||
* setFrameScheduledCallback after endFrame() apply to the next frame.
|
||||
*
|
||||
* Use \c setFrameScheduledCallback() (with default arguments) to unset the callback.
|
||||
*
|
||||
* If your application delays the call to the PresentCallable by, for example, calling it on a
|
||||
* separate thread, you must ensure all PresentCallables have been called before shutting down
|
||||
@@ -278,28 +301,26 @@ public:
|
||||
* Engine::shutdown. This is necessary to ensure the Filament Engine has had a chance to clean
|
||||
* up all memory related to frame presentation.
|
||||
*
|
||||
* @param callback A callback, or nullptr to unset.
|
||||
* @param user An optional pointer to user data passed to the callback function.
|
||||
* @param handler Handler to dispatch the callback or nullptr for the default handler.
|
||||
* @param callback Callback called when the frame is scheduled.
|
||||
*
|
||||
* @remark Only Filament's Metal backend supports PresentCallables and frame callbacks. Other
|
||||
* backends ignore the callback (which will never be called) and proceed normally.
|
||||
*
|
||||
* @remark The SwapChain::FrameScheduledCallback is called on an arbitrary thread.
|
||||
*
|
||||
* @see CallbackHandler
|
||||
* @see PresentCallable
|
||||
*/
|
||||
void setFrameScheduledCallback(FrameScheduledCallback UTILS_NULLABLE callback,
|
||||
void* UTILS_NULLABLE user = nullptr);
|
||||
void setFrameScheduledCallback(backend::CallbackHandler* UTILS_NULLABLE handler = nullptr,
|
||||
FrameScheduledCallback&& callback = {}, uint64_t flags = 0);
|
||||
|
||||
/**
|
||||
* Returns the SwapChain::FrameScheduledCallback that was previously set with
|
||||
* SwapChain::setFrameScheduledCallback, or nullptr if one is not set.
|
||||
* Returns whether or not this SwapChain currently has a FrameScheduledCallback set.
|
||||
*
|
||||
* @return the previously-set FrameScheduledCallback, or nullptr
|
||||
* @return true, if the last call to setFrameScheduledCallback set a callback
|
||||
*
|
||||
* @see SwapChain::setFrameCompletedCallback
|
||||
*/
|
||||
UTILS_NULLABLE FrameScheduledCallback getFrameScheduledCallback() const noexcept;
|
||||
bool isFrameScheduledCallbackSet() const noexcept;
|
||||
|
||||
/**
|
||||
* FrameCompletedCallback is a callback function that notifies an application when a frame's
|
||||
|
||||
@@ -23,6 +23,7 @@
|
||||
|
||||
#include <backend/DriverEnums.h>
|
||||
#include <backend/PixelBufferDescriptor.h>
|
||||
#include <backend/Platform.h>
|
||||
|
||||
#include <utils/compiler.h>
|
||||
|
||||
@@ -70,7 +71,7 @@ class UTILS_PUBLIC Texture : public FilamentAPI {
|
||||
struct BuilderDetails;
|
||||
|
||||
public:
|
||||
static constexpr const size_t BASE_LEVEL = 0;
|
||||
static constexpr size_t BASE_LEVEL = 0;
|
||||
|
||||
//! Face offsets for all faces of a cubemap
|
||||
struct FaceOffsets;
|
||||
@@ -84,19 +85,26 @@ public:
|
||||
using CompressedType = backend::CompressedPixelDataType; //!< Compressed pixel data format
|
||||
using Usage = backend::TextureUsage; //!< Usage affects texel layout
|
||||
using Swizzle = backend::TextureSwizzle; //!< Texture swizzle
|
||||
using ExternalImageHandle = backend::Platform::ExternalImageHandle;
|
||||
using ExternalImageHandleRef = backend::Platform::ExternalImageHandleRef;
|
||||
|
||||
/** @return whether a backend supports a particular format. */
|
||||
/** @return Whether a backend supports a particular format. */
|
||||
static bool isTextureFormatSupported(Engine& engine, InternalFormat format) noexcept;
|
||||
|
||||
/** @return whether this backend supports protected textures. */
|
||||
/** @return Whether a backend supports mipmapping of a particular format. */
|
||||
static bool isTextureFormatMipmappable(Engine& engine, InternalFormat format) noexcept;
|
||||
|
||||
/** @return Whether this backend supports protected textures. */
|
||||
static bool isProtectedTexturesSupported(Engine& engine) noexcept;
|
||||
|
||||
/** @return whether a backend supports texture swizzling. */
|
||||
/** @return Whether a backend supports texture swizzling. */
|
||||
static bool isTextureSwizzleSupported(Engine& engine) noexcept;
|
||||
|
||||
static size_t computeTextureDataSize(Texture::Format format, Texture::Type type,
|
||||
static size_t computeTextureDataSize(Format format, Type type,
|
||||
size_t stride, size_t height, size_t alignment) noexcept;
|
||||
|
||||
/** @return Whether a combination of texture format, pixel format and type is valid. */
|
||||
static bool validatePixelFormatAndType(InternalFormat internalFormat, Format format, Type type) noexcept;
|
||||
|
||||
/**
|
||||
* Options for environment prefiltering into reflection map
|
||||
@@ -112,7 +120,7 @@ public:
|
||||
|
||||
|
||||
//! Use Builder to construct a Texture object instance
|
||||
class Builder : public BuilderBase<BuilderDetails> {
|
||||
class Builder : public BuilderBase<BuilderDetails>, public BuilderNameMixin<Builder> {
|
||||
friend struct BuilderDetails;
|
||||
public:
|
||||
Builder() noexcept;
|
||||
@@ -202,6 +210,33 @@ public:
|
||||
*/
|
||||
Builder& swizzle(Swizzle r, Swizzle g, Swizzle b, Swizzle a) noexcept;
|
||||
|
||||
/**
|
||||
* Associate an optional name with this Texture for debugging purposes.
|
||||
*
|
||||
* name will show in error messages and should be kept as short as possible. The name is
|
||||
* truncated to a maximum of 128 characters.
|
||||
*
|
||||
* The name string is copied during this method so clients may free its memory after
|
||||
* the function returns.
|
||||
*
|
||||
* @param name A string to identify this Texture
|
||||
* @param len Length of name, should be less than or equal to 128
|
||||
* @return This Builder, for chaining calls.
|
||||
*/
|
||||
Builder& name(const char* UTILS_NONNULL name, size_t len) noexcept;
|
||||
|
||||
/**
|
||||
* Creates an external texture. The content must be set using setExternalImage().
|
||||
* The sampler can be SAMPLER_EXTERNAL or SAMPLER_2D depending on the format. Generally
|
||||
* YUV formats must use SAMPLER_EXTERNAL. This depends on the backend features and is not
|
||||
* validated.
|
||||
*
|
||||
* If the Sampler is set to SAMPLER_EXTERNAL, external() is implied.
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
Builder& external() noexcept;
|
||||
|
||||
/**
|
||||
* Creates the Texture object and returns a pointer to it.
|
||||
*
|
||||
@@ -332,7 +367,7 @@ public:
|
||||
* uint32_t width, uint32_t height, uint32_t depth,
|
||||
* PixelBufferDescriptor&& buffer)
|
||||
*/
|
||||
inline void setImage(Engine& engine, size_t level, PixelBufferDescriptor&& buffer) const {
|
||||
void setImage(Engine& engine, size_t level, PixelBufferDescriptor&& buffer) const {
|
||||
setImage(engine, level, 0, 0, 0,
|
||||
uint32_t(getWidth(level)), uint32_t(getHeight(level)), 1, std::move(buffer));
|
||||
}
|
||||
@@ -345,7 +380,7 @@ public:
|
||||
* uint32_t width, uint32_t height, uint32_t depth,
|
||||
* PixelBufferDescriptor&& buffer)
|
||||
*/
|
||||
inline void setImage(Engine& engine, size_t level,
|
||||
void setImage(Engine& engine, size_t level,
|
||||
uint32_t xoffset, uint32_t yoffset, uint32_t width, uint32_t height,
|
||||
PixelBufferDescriptor&& buffer) const {
|
||||
setImage(engine, level, xoffset, yoffset, 0, width, height, 1, std::move(buffer));
|
||||
@@ -380,7 +415,27 @@ public:
|
||||
|
||||
|
||||
/**
|
||||
* Specify the external image to associate with this Texture. Typically the external
|
||||
* Specify the external image to associate with this Texture. Typically, the external
|
||||
* image is OS specific, and can be a video or camera frame.
|
||||
* There are many restrictions when using an external image as a texture, such as:
|
||||
* - only the level of detail (lod) 0 can be specified
|
||||
* - only nearest or linear filtering is supported
|
||||
* - the size and format of the texture is defined by the external image
|
||||
* - only the CLAMP_TO_EDGE wrap mode is supported
|
||||
*
|
||||
* @param engine Engine this texture is associated to.
|
||||
* @param image An opaque handle to a platform specific image. It must be created using Platform
|
||||
* specific APIs. For example PlatformEGL::createExternalImage(EGLImageKHR eglImage)
|
||||
*
|
||||
* @see PlatformEGL::createExternalImage
|
||||
* @see PlatformEGLAndroid::createExternalImage
|
||||
* @see PlatformCocoaGL::createExternalImage
|
||||
* @see PlatformCocoaTouchGL::createExternalImage
|
||||
*/
|
||||
void setExternalImage(Engine& engine, ExternalImageHandleRef image) noexcept;
|
||||
|
||||
/**
|
||||
* Specify the external image to associate with this Texture. Typically, the external
|
||||
* image is OS specific, and can be a video or camera frame.
|
||||
* There are many restrictions when using an external image as a texture, such as:
|
||||
* - only the level of detail (lod) 0 can be specified
|
||||
@@ -401,11 +456,13 @@ public:
|
||||
*
|
||||
* @see Builder::sampler()
|
||||
*
|
||||
* @deprecated Instead, use setExternalImage(Engine& engine, ExternalImageHandleRef image)
|
||||
*/
|
||||
UTILS_DEPRECATED
|
||||
void setExternalImage(Engine& engine, void* UTILS_NONNULL image) noexcept;
|
||||
|
||||
/**
|
||||
* Specify the external image and plane to associate with this Texture. Typically the external
|
||||
* Specify the external image and plane to associate with this Texture. Typically, the external
|
||||
* image is OS specific, and can be a video or camera frame. When using this method, the
|
||||
* external image must be a planar type (such as a YUV camera frame). The plane parameter
|
||||
* selects which image plane is bound to this texture.
|
||||
@@ -436,7 +493,7 @@ public:
|
||||
void setExternalImage(Engine& engine, void* UTILS_NONNULL image, size_t plane) noexcept;
|
||||
|
||||
/**
|
||||
* Specify the external stream to associate with this Texture. Typically the external
|
||||
* Specify the external stream to associate with this Texture. Typically, the external
|
||||
* stream is OS specific, and can be a video or camera stream.
|
||||
* There are many restrictions when using an external stream as a texture, such as:
|
||||
* - only the level of detail (lod) 0 can be specified
|
||||
@@ -447,7 +504,7 @@ public:
|
||||
* @param stream A Stream object
|
||||
*
|
||||
* @attention \p engine must be the instance passed to Builder::build()
|
||||
* @attention This Texture instance must use Sampler::SAMPLER_EXTERNAL or it has no effect
|
||||
* @attention This Texture instance must use Sampler::SAMPLER_EXTERNAL, or it has no effect
|
||||
*
|
||||
* @see Builder::sampler(), Stream
|
||||
*
|
||||
@@ -495,9 +552,9 @@ public:
|
||||
* @param buffer Client-side buffer containing the images to set.
|
||||
* @param faceOffsets Offsets in bytes into \p buffer for all six images. The offsets
|
||||
* are specified in the following order: +x, -x, +y, -y, +z, -z
|
||||
* @param options Optional parameter to controlling user-specified quality and options.
|
||||
* @param options Optional parameter controlling user-specified quality and options.
|
||||
*
|
||||
* @exception utils::PreConditionPanic if the source data constraints are not respected.
|
||||
* @exception utils::PreConditionPanic If the source data constraints are not respected.
|
||||
*
|
||||
*/
|
||||
void generatePrefilterMipmap(Engine& engine,
|
||||
|
||||
@@ -61,7 +61,7 @@ public:
|
||||
using AttributeType = backend::ElementType;
|
||||
using BufferDescriptor = backend::BufferDescriptor;
|
||||
|
||||
class Builder : public BuilderBase<BuilderDetails> {
|
||||
class Builder : public BuilderBase<BuilderDetails>, public BuilderNameMixin<Builder> {
|
||||
friend struct BuilderDetails;
|
||||
public:
|
||||
Builder() noexcept;
|
||||
@@ -158,6 +158,21 @@ public:
|
||||
*/
|
||||
Builder& advancedSkinning(bool enabled) noexcept;
|
||||
|
||||
/**
|
||||
* Associate an optional name with this VertexBuffer for debugging purposes.
|
||||
*
|
||||
* name will show in error messages and should be kept as short as possible. The name is
|
||||
* truncated to a maximum of 128 characters.
|
||||
*
|
||||
* The name string is copied during this method so clients may free its memory after
|
||||
* the function returns.
|
||||
*
|
||||
* @param name A string to identify this VertexBuffer
|
||||
* @param len Length of name, should be less than or equal to 128
|
||||
* @return This Builder, for chaining calls.
|
||||
*/
|
||||
Builder& name(const char* UTILS_NONNULL name, size_t len) noexcept;
|
||||
|
||||
/**
|
||||
* Creates the VertexBuffer object and returns a pointer to it.
|
||||
*
|
||||
|
||||
@@ -24,6 +24,7 @@
|
||||
|
||||
#include <utils/compiler.h>
|
||||
#include <utils/Entity.h>
|
||||
#include <utils/FixedCapacityVector.h>
|
||||
|
||||
#include <math/mathfwd.h>
|
||||
|
||||
@@ -40,6 +41,7 @@ class CallbackHandler;
|
||||
|
||||
class Camera;
|
||||
class ColorGrading;
|
||||
class Engine;
|
||||
class MaterialInstance;
|
||||
class RenderTarget;
|
||||
class Scene;
|
||||
@@ -189,6 +191,13 @@ public:
|
||||
*/
|
||||
void setCamera(Camera* UTILS_NONNULL camera) noexcept;
|
||||
|
||||
/**
|
||||
* Returns whether a Camera is set.
|
||||
* @return true if a camera is set.
|
||||
* @see setCamera()
|
||||
*/
|
||||
bool hasCamera() const noexcept;
|
||||
|
||||
/**
|
||||
* Returns the Camera currently associated with this View.
|
||||
* @return A reference to the Camera associated to this View.
|
||||
@@ -561,6 +570,13 @@ public:
|
||||
*/
|
||||
void setShadowType(ShadowType shadow) noexcept;
|
||||
|
||||
/**
|
||||
* Returns the shadow mapping technique used by this View.
|
||||
*
|
||||
* @return value set by setShadowType().
|
||||
*/
|
||||
ShadowType getShadowType() const noexcept;
|
||||
|
||||
/**
|
||||
* Sets VSM shadowing options that apply across the entire View.
|
||||
*
|
||||
@@ -652,6 +668,26 @@ public:
|
||||
*/
|
||||
bool isFrontFaceWindingInverted() const noexcept;
|
||||
|
||||
/**
|
||||
* Enables or disables transparent picking. Disabled by default.
|
||||
*
|
||||
* When transparent picking is enabled, View::pick() will pick from both
|
||||
* transparent and opaque renderables. When disabled, View::pick() will only
|
||||
* pick from opaque renderables.
|
||||
*
|
||||
* @param enabled true enables transparent picking, false disables it.
|
||||
*
|
||||
* @note Transparent picking will create an extra pass for rendering depth
|
||||
* from both transparent and opaque renderables.
|
||||
*/
|
||||
void setTransparentPickingEnabled(bool enabled) noexcept;
|
||||
|
||||
/**
|
||||
* Returns true if transparent picking is enabled.
|
||||
* See setTransparentPickingEnabled() for more information.
|
||||
*/
|
||||
bool isTransparentPickingEnabled() const noexcept;
|
||||
|
||||
/**
|
||||
* Enables use of the stencil buffer.
|
||||
*
|
||||
@@ -719,7 +755,7 @@ public:
|
||||
void setDebugCamera(Camera* UTILS_NULLABLE camera) noexcept;
|
||||
|
||||
//! debugging: returns a Camera from the point of view of *the* dominant directional light used for shadowing.
|
||||
Camera const* UTILS_NULLABLE getDirectionalShadowCamera() const noexcept;
|
||||
utils::FixedCapacityVector<Camera const*> getDirectionalShadowCameras() const noexcept;
|
||||
|
||||
|
||||
/** Result of a picking query */
|
||||
@@ -871,6 +907,17 @@ public:
|
||||
*/
|
||||
utils::Entity getFogEntity() const noexcept;
|
||||
|
||||
|
||||
/**
|
||||
* When certain temporal features are used (e.g.: TAA or Screen-space reflections), the view
|
||||
* keeps a history of previous frame renders associated with the Renderer the view was last
|
||||
* used with. When switching Renderer, it may be necessary to clear that history by calling
|
||||
* this method. Similarly, if the whole content of the screen change, like when a cut-scene
|
||||
* starts, clearing the history might be needed to avoid artifacts due to the previous frame
|
||||
* being very different.
|
||||
*/
|
||||
void clearFrameHistory(Engine& engine) noexcept;
|
||||
|
||||
/**
|
||||
* List of available ambient occlusion techniques
|
||||
* @deprecated use AmbientOcclusionOptions::enabled instead
|
||||
|
||||
@@ -38,6 +38,23 @@ namespace filament::gltfio {
|
||||
|
||||
class NodeManager;
|
||||
|
||||
// Use this struct to enable mikktspace-based tangent-space computation.
|
||||
/**
|
||||
* \struct AssetConfigurationExtended AssetLoader.h gltfio/AssetLoader.h
|
||||
* \brief extends struct AssetConfiguration
|
||||
* Useful if client needs mikktspace tangent space computation.
|
||||
* NOTE: Android, iOS, Web are not supported. And only disk-local glTF resources are supported.
|
||||
*/
|
||||
struct AssetConfigurationExtended {
|
||||
//! Optional The same parameter as provided to \struct ResourceConfiguration ResourceLoader.h
|
||||
//! gltfio/ResourceLoader.h
|
||||
char const* gltfPath;
|
||||
|
||||
//! Client can use this method to check if the extended implementation is supported on their
|
||||
//! platform or not.
|
||||
static bool isSupported();
|
||||
};
|
||||
|
||||
/**
|
||||
* \struct AssetConfiguration AssetLoader.h gltfio/AssetLoader.h
|
||||
* \brief Construction parameters for AssetLoader.
|
||||
@@ -62,6 +79,10 @@ struct AssetConfiguration {
|
||||
|
||||
//! Optional default node name for anonymous nodes
|
||||
char* defaultNodeName = nullptr;
|
||||
|
||||
//! Optional to enable mikktspace tangents. Lifetime of struct only needs to be maintained for
|
||||
// the duration of the constructor of AssetLoader.
|
||||
AssetConfigurationExtended* ext = nullptr;
|
||||
};
|
||||
|
||||
/**
|
||||
|
||||
@@ -93,10 +93,17 @@ struct alignas(4) MaterialKey {
|
||||
bool hasSheen : 1;
|
||||
bool hasIOR : 1;
|
||||
bool hasVolume : 1;
|
||||
uint8_t padding : 5;
|
||||
bool hasSpecular : 1;
|
||||
bool hasSpecularTexture : 1;
|
||||
bool hasSpecularColorTexture : 1;
|
||||
bool padding : 2;
|
||||
// -- 32 bit boundary --
|
||||
uint8_t specularTextureUV;
|
||||
uint8_t specularColorTextureUV;
|
||||
uint16_t padding2;
|
||||
};
|
||||
|
||||
static_assert(sizeof(MaterialKey) == 16, "MaterialKey has unexpected size.");
|
||||
static_assert(sizeof(MaterialKey) == 20, "MaterialKey has unexpected size.");
|
||||
|
||||
UTILS_WARNING_POP
|
||||
|
||||
|
||||
@@ -259,7 +259,7 @@ public:
|
||||
return normalize(lerp(d < 0 ? -p : p, q, t));
|
||||
}
|
||||
const T npq = std::sqrt(dot(p, p) * dot(q, q)); // ||p|| * ||q||
|
||||
const T a = std::acos(filament::math::clamp(absd / npq, T(-1), T(1)));
|
||||
const T a = std::acos(math::clamp(absd / npq, T(-1), T(1)));
|
||||
const T a0 = a * (1 - t);
|
||||
const T a1 = a * t;
|
||||
const T sina = sin(a);
|
||||
|
||||
@@ -50,7 +50,7 @@ constexpr T MATH_PURE cos(T x) noexcept {
|
||||
// x between -pi and pi
|
||||
template<typename T, typename = std::enable_if_t<std::is_floating_point<T>::value>>
|
||||
constexpr T MATH_PURE sin(T x) noexcept {
|
||||
return filament::math::fast::cos<T>(x - T(F_PI_2));
|
||||
return fast::cos<T>(x - T(F_PI_2));
|
||||
}
|
||||
|
||||
constexpr inline float MATH_PURE ilog2(float x) noexcept {
|
||||
|
||||
@@ -164,7 +164,7 @@ inline constexpr half operator""_h(long double v) {
|
||||
return half( static_cast<float>(v) );
|
||||
}
|
||||
|
||||
template<> struct is_arithmetic<filament::math::half> : public std::true_type {};
|
||||
template<> struct is_arithmetic<half> : public std::true_type {};
|
||||
|
||||
} // namespace math
|
||||
} // namespace filament
|
||||
|
||||
@@ -225,7 +225,7 @@ public:
|
||||
* Rotate by radians in the 2D plane
|
||||
*/
|
||||
static TMat22<T> rotate(T radian) noexcept {
|
||||
TMat22<T> r(TMat22<T>::NO_INIT);
|
||||
TMat22<T> r(NO_INIT);
|
||||
T c = std::cos(radian);
|
||||
T s = std::sin(radian);
|
||||
r[0][0] = c;
|
||||
|
||||
@@ -256,7 +256,7 @@ public:
|
||||
*/
|
||||
friend inline
|
||||
constexpr TMat33 orthogonalize(const TMat33& m) noexcept {
|
||||
TMat33 ret(TMat33::NO_INIT);
|
||||
TMat33 ret(NO_INIT);
|
||||
ret[0] = normalize(m[0]);
|
||||
ret[2] = normalize(cross(ret[0], m[1]));
|
||||
ret[1] = normalize(cross(ret[2], ret[0]));
|
||||
|
||||
@@ -498,10 +498,10 @@ constexpr TMat44<T> TMat44<T>::frustum(T left, T right, T bottom, T top, T near,
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
TMat44<T> TMat44<T>::perspective(T fov, T aspect, T near, T far, TMat44::Fov direction) noexcept {
|
||||
TMat44<T> TMat44<T>::perspective(T fov, T aspect, T near, T far, Fov direction) noexcept {
|
||||
T h, w;
|
||||
|
||||
if (direction == TMat44::Fov::VERTICAL) {
|
||||
if (direction == Fov::VERTICAL) {
|
||||
h = std::tan(fov * F_PI / 360.0f) * near;
|
||||
w = h * aspect;
|
||||
} else {
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,404 @@
|
||||
// Copyright (c) 2016 Google Inc.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#ifndef INCLUDE_SPIRV_TOOLS_LIBSPIRV_HPP_
|
||||
#define INCLUDE_SPIRV_TOOLS_LIBSPIRV_HPP_
|
||||
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "libspirv.h"
|
||||
|
||||
namespace spvtools {
|
||||
|
||||
// Message consumer. The C strings for source and message are only alive for the
|
||||
// specific invocation.
|
||||
using MessageConsumer = std::function<void(
|
||||
spv_message_level_t /* level */, const char* /* source */,
|
||||
const spv_position_t& /* position */, const char* /* message */
|
||||
)>;
|
||||
|
||||
using HeaderParser = std::function<spv_result_t(
|
||||
const spv_endianness_t endianess, const spv_parsed_header_t& instruction)>;
|
||||
using InstructionParser =
|
||||
std::function<spv_result_t(const spv_parsed_instruction_t& instruction)>;
|
||||
|
||||
// C++ RAII wrapper around the C context object spv_context.
|
||||
class SPIRV_TOOLS_EXPORT Context {
|
||||
public:
|
||||
// Constructs a context targeting the given environment |env|.
|
||||
//
|
||||
// See specific API calls for how the target environment is interpreted
|
||||
// (particularly assembly and validation).
|
||||
//
|
||||
// The constructed instance will have an empty message consumer, which just
|
||||
// ignores all messages from the library. Use SetMessageConsumer() to supply
|
||||
// one if messages are of concern.
|
||||
explicit Context(spv_target_env env);
|
||||
|
||||
// Enables move constructor/assignment operations.
|
||||
Context(Context&& other);
|
||||
Context& operator=(Context&& other);
|
||||
|
||||
// Disables copy constructor/assignment operations.
|
||||
Context(const Context&) = delete;
|
||||
Context& operator=(const Context&) = delete;
|
||||
|
||||
// Destructs this instance.
|
||||
~Context();
|
||||
|
||||
// Sets the message consumer to the given |consumer|. The |consumer| will be
|
||||
// invoked once for each message communicated from the library.
|
||||
void SetMessageConsumer(MessageConsumer consumer);
|
||||
|
||||
// Returns the underlying spv_context.
|
||||
spv_context& CContext();
|
||||
const spv_context& CContext() const;
|
||||
|
||||
private:
|
||||
spv_context context_;
|
||||
};
|
||||
|
||||
// A RAII wrapper around a validator options object.
|
||||
class SPIRV_TOOLS_EXPORT ValidatorOptions {
|
||||
public:
|
||||
ValidatorOptions() : options_(spvValidatorOptionsCreate()) {}
|
||||
~ValidatorOptions() { spvValidatorOptionsDestroy(options_); }
|
||||
// Allow implicit conversion to the underlying object.
|
||||
operator spv_validator_options() const { return options_; }
|
||||
|
||||
// Sets a limit.
|
||||
void SetUniversalLimit(spv_validator_limit limit_type, uint32_t limit) {
|
||||
spvValidatorOptionsSetUniversalLimit(options_, limit_type, limit);
|
||||
}
|
||||
|
||||
void SetRelaxStructStore(bool val) {
|
||||
spvValidatorOptionsSetRelaxStoreStruct(options_, val);
|
||||
}
|
||||
|
||||
// Enables VK_KHR_relaxed_block_layout when validating standard
|
||||
// uniform/storage buffer/push-constant layout. If true, disables
|
||||
// scalar block layout rules.
|
||||
void SetRelaxBlockLayout(bool val) {
|
||||
spvValidatorOptionsSetRelaxBlockLayout(options_, val);
|
||||
}
|
||||
|
||||
// Enables VK_KHR_uniform_buffer_standard_layout when validating standard
|
||||
// uniform layout. If true, disables scalar block layout rules.
|
||||
void SetUniformBufferStandardLayout(bool val) {
|
||||
spvValidatorOptionsSetUniformBufferStandardLayout(options_, val);
|
||||
}
|
||||
|
||||
// Enables VK_EXT_scalar_block_layout when validating standard
|
||||
// uniform/storage buffer/push-constant layout. If true, disables
|
||||
// relaxed block layout rules.
|
||||
void SetScalarBlockLayout(bool val) {
|
||||
spvValidatorOptionsSetScalarBlockLayout(options_, val);
|
||||
}
|
||||
|
||||
// Enables scalar layout when validating Workgroup blocks. See
|
||||
// VK_KHR_workgroup_memory_explicit_layout.
|
||||
void SetWorkgroupScalarBlockLayout(bool val) {
|
||||
spvValidatorOptionsSetWorkgroupScalarBlockLayout(options_, val);
|
||||
}
|
||||
|
||||
// Skips validating standard uniform/storage buffer/push-constant layout.
|
||||
void SetSkipBlockLayout(bool val) {
|
||||
spvValidatorOptionsSetSkipBlockLayout(options_, val);
|
||||
}
|
||||
|
||||
// Enables LocalSizeId decorations where the environment would not otherwise
|
||||
// allow them.
|
||||
void SetAllowLocalSizeId(bool val) {
|
||||
spvValidatorOptionsSetAllowLocalSizeId(options_, val);
|
||||
}
|
||||
|
||||
// Allow Offset (in addition to ConstOffset) for texture
|
||||
// operations. Was added for VK_KHR_maintenance8
|
||||
void SetAllowOffsetTextureOperand(bool val) {
|
||||
spvValidatorOptionsSetAllowOffsetTextureOperand(options_, val);
|
||||
}
|
||||
|
||||
// Records whether or not the validator should relax the rules on pointer
|
||||
// usage in logical addressing mode.
|
||||
//
|
||||
// When relaxed, it will allow the following usage cases of pointers:
|
||||
// 1) OpVariable allocating an object whose type is a pointer type
|
||||
// 2) OpReturnValue returning a pointer value
|
||||
void SetRelaxLogicalPointer(bool val) {
|
||||
spvValidatorOptionsSetRelaxLogicalPointer(options_, val);
|
||||
}
|
||||
|
||||
// Records whether or not the validator should relax the rules because it is
|
||||
// expected that the optimizations will make the code legal.
|
||||
//
|
||||
// When relaxed, it will allow the following:
|
||||
// 1) It will allow relaxed logical pointers. Setting this option will also
|
||||
// set that option.
|
||||
// 2) Pointers that are pass as parameters to function calls do not have to
|
||||
// match the storage class of the formal parameter.
|
||||
// 3) Pointers that are actual parameters on function calls do not have to
|
||||
// point to the same type pointed as the formal parameter. The types just
|
||||
// need to logically match.
|
||||
// 4) GLSLstd450 Interpolate* instructions can have a load of an interpolant
|
||||
// for a first argument.
|
||||
void SetBeforeHlslLegalization(bool val) {
|
||||
spvValidatorOptionsSetBeforeHlslLegalization(options_, val);
|
||||
}
|
||||
|
||||
// Whether friendly names should be used in validation error messages.
|
||||
void SetFriendlyNames(bool val) {
|
||||
spvValidatorOptionsSetFriendlyNames(options_, val);
|
||||
}
|
||||
|
||||
private:
|
||||
spv_validator_options options_;
|
||||
};
|
||||
|
||||
// A C++ wrapper around an optimization options object.
|
||||
class SPIRV_TOOLS_EXPORT OptimizerOptions {
|
||||
public:
|
||||
OptimizerOptions() : options_(spvOptimizerOptionsCreate()) {}
|
||||
~OptimizerOptions() { spvOptimizerOptionsDestroy(options_); }
|
||||
|
||||
// Allow implicit conversion to the underlying object.
|
||||
operator spv_optimizer_options() const { return options_; }
|
||||
|
||||
// Records whether or not the optimizer should run the validator before
|
||||
// optimizing. If |run| is true, the validator will be run.
|
||||
void set_run_validator(bool run) {
|
||||
spvOptimizerOptionsSetRunValidator(options_, run);
|
||||
}
|
||||
|
||||
// Records the validator options that should be passed to the validator if it
|
||||
// is run.
|
||||
void set_validator_options(const ValidatorOptions& val_options) {
|
||||
spvOptimizerOptionsSetValidatorOptions(options_, val_options);
|
||||
}
|
||||
|
||||
// Records the maximum possible value for the id bound.
|
||||
void set_max_id_bound(uint32_t new_bound) {
|
||||
spvOptimizerOptionsSetMaxIdBound(options_, new_bound);
|
||||
}
|
||||
|
||||
// Records whether all bindings within the module should be preserved.
|
||||
void set_preserve_bindings(bool preserve_bindings) {
|
||||
spvOptimizerOptionsSetPreserveBindings(options_, preserve_bindings);
|
||||
}
|
||||
|
||||
// Records whether all specialization constants within the module
|
||||
// should be preserved.
|
||||
void set_preserve_spec_constants(bool preserve_spec_constants) {
|
||||
spvOptimizerOptionsSetPreserveSpecConstants(options_,
|
||||
preserve_spec_constants);
|
||||
}
|
||||
|
||||
private:
|
||||
spv_optimizer_options options_;
|
||||
};
|
||||
|
||||
// A C++ wrapper around a reducer options object.
|
||||
class SPIRV_TOOLS_EXPORT ReducerOptions {
|
||||
public:
|
||||
ReducerOptions() : options_(spvReducerOptionsCreate()) {}
|
||||
~ReducerOptions() { spvReducerOptionsDestroy(options_); }
|
||||
|
||||
// Allow implicit conversion to the underlying object.
|
||||
operator spv_reducer_options() const { // NOLINT(google-explicit-constructor)
|
||||
return options_;
|
||||
}
|
||||
|
||||
// See spvReducerOptionsSetStepLimit.
|
||||
void set_step_limit(uint32_t step_limit) {
|
||||
spvReducerOptionsSetStepLimit(options_, step_limit);
|
||||
}
|
||||
|
||||
// See spvReducerOptionsSetFailOnValidationError.
|
||||
void set_fail_on_validation_error(bool fail_on_validation_error) {
|
||||
spvReducerOptionsSetFailOnValidationError(options_,
|
||||
fail_on_validation_error);
|
||||
}
|
||||
|
||||
// See spvReducerOptionsSetTargetFunction.
|
||||
void set_target_function(uint32_t target_function) {
|
||||
spvReducerOptionsSetTargetFunction(options_, target_function);
|
||||
}
|
||||
|
||||
private:
|
||||
spv_reducer_options options_;
|
||||
};
|
||||
|
||||
// A C++ wrapper around a fuzzer options object.
|
||||
class SPIRV_TOOLS_EXPORT FuzzerOptions {
|
||||
public:
|
||||
FuzzerOptions() : options_(spvFuzzerOptionsCreate()) {}
|
||||
~FuzzerOptions() { spvFuzzerOptionsDestroy(options_); }
|
||||
|
||||
// Allow implicit conversion to the underlying object.
|
||||
operator spv_fuzzer_options() const { // NOLINT(google-explicit-constructor)
|
||||
return options_;
|
||||
}
|
||||
|
||||
// See spvFuzzerOptionsEnableReplayValidation.
|
||||
void enable_replay_validation() {
|
||||
spvFuzzerOptionsEnableReplayValidation(options_);
|
||||
}
|
||||
|
||||
// See spvFuzzerOptionsSetRandomSeed.
|
||||
void set_random_seed(uint32_t seed) {
|
||||
spvFuzzerOptionsSetRandomSeed(options_, seed);
|
||||
}
|
||||
|
||||
// See spvFuzzerOptionsSetReplayRange.
|
||||
void set_replay_range(int32_t replay_range) {
|
||||
spvFuzzerOptionsSetReplayRange(options_, replay_range);
|
||||
}
|
||||
|
||||
// See spvFuzzerOptionsSetShrinkerStepLimit.
|
||||
void set_shrinker_step_limit(uint32_t shrinker_step_limit) {
|
||||
spvFuzzerOptionsSetShrinkerStepLimit(options_, shrinker_step_limit);
|
||||
}
|
||||
|
||||
// See spvFuzzerOptionsEnableFuzzerPassValidation.
|
||||
void enable_fuzzer_pass_validation() {
|
||||
spvFuzzerOptionsEnableFuzzerPassValidation(options_);
|
||||
}
|
||||
|
||||
// See spvFuzzerOptionsEnableAllPasses.
|
||||
void enable_all_passes() { spvFuzzerOptionsEnableAllPasses(options_); }
|
||||
|
||||
private:
|
||||
spv_fuzzer_options options_;
|
||||
};
|
||||
|
||||
// C++ interface for SPIRV-Tools functionalities. It wraps the context
|
||||
// (including target environment and the corresponding SPIR-V grammar) and
|
||||
// provides methods for assembling, disassembling, and validating.
|
||||
//
|
||||
// Instances of this class provide basic thread-safety guarantee.
|
||||
class SPIRV_TOOLS_EXPORT SpirvTools {
|
||||
public:
|
||||
enum {
|
||||
// Default assembling option used by assemble():
|
||||
kDefaultAssembleOption = SPV_TEXT_TO_BINARY_OPTION_NONE,
|
||||
|
||||
// Default disassembling option used by Disassemble():
|
||||
// * Avoid prefix comments from decoding the SPIR-V module header, and
|
||||
// * Use friendly names for variables.
|
||||
kDefaultDisassembleOption = SPV_BINARY_TO_TEXT_OPTION_NO_HEADER |
|
||||
SPV_BINARY_TO_TEXT_OPTION_FRIENDLY_NAMES
|
||||
};
|
||||
|
||||
// Constructs an instance targeting the given environment |env|.
|
||||
//
|
||||
// The constructed instance will have an empty message consumer, which just
|
||||
// ignores all messages from the library. Use SetMessageConsumer() to supply
|
||||
// one if messages are of concern.
|
||||
explicit SpirvTools(spv_target_env env);
|
||||
|
||||
// Disables copy/move constructor/assignment operations.
|
||||
SpirvTools(const SpirvTools&) = delete;
|
||||
SpirvTools(SpirvTools&&) = delete;
|
||||
SpirvTools& operator=(const SpirvTools&) = delete;
|
||||
SpirvTools& operator=(SpirvTools&&) = delete;
|
||||
|
||||
// Destructs this instance.
|
||||
~SpirvTools();
|
||||
|
||||
// Sets the message consumer to the given |consumer|. The |consumer| will be
|
||||
// invoked once for each message communicated from the library.
|
||||
void SetMessageConsumer(MessageConsumer consumer);
|
||||
|
||||
// Assembles the given assembly |text| and writes the result to |binary|.
|
||||
// Returns true on successful assembling. |binary| will be kept untouched if
|
||||
// assembling is unsuccessful.
|
||||
// The SPIR-V binary version is set to the highest version of SPIR-V supported
|
||||
// by the target environment with which this SpirvTools object was created.
|
||||
bool Assemble(const std::string& text, std::vector<uint32_t>* binary,
|
||||
uint32_t options = kDefaultAssembleOption) const;
|
||||
// |text_size| specifies the number of bytes in |text|. A terminating null
|
||||
// character is not required to present in |text| as long as |text| is valid.
|
||||
// The SPIR-V binary version is set to the highest version of SPIR-V supported
|
||||
// by the target environment with which this SpirvTools object was created.
|
||||
bool Assemble(const char* text, size_t text_size,
|
||||
std::vector<uint32_t>* binary,
|
||||
uint32_t options = kDefaultAssembleOption) const;
|
||||
|
||||
// Disassembles the given SPIR-V |binary| with the given |options| and writes
|
||||
// the assembly to |text|. Returns true on successful disassembling. |text|
|
||||
// will be kept untouched if diassembling is unsuccessful.
|
||||
bool Disassemble(const std::vector<uint32_t>& binary, std::string* text,
|
||||
uint32_t options = kDefaultDisassembleOption) const;
|
||||
// |binary_size| specifies the number of words in |binary|.
|
||||
bool Disassemble(const uint32_t* binary, size_t binary_size,
|
||||
std::string* text,
|
||||
uint32_t options = kDefaultDisassembleOption) const;
|
||||
|
||||
// Parses a SPIR-V binary, specified as counted sequence of 32-bit words.
|
||||
// Parsing feedback is provided via two callbacks provided as std::function.
|
||||
// In a valid parse the parsed-header callback is called once, and
|
||||
// then the parsed-instruction callback is called once for each instruction
|
||||
// in the stream.
|
||||
// Returns true on successful parsing.
|
||||
// If diagnostic is non-null, a diagnostic is emitted on failed parsing.
|
||||
// If diagnostic is null the context's message consumer
|
||||
// will be used to emit any errors. If a callback returns anything other than
|
||||
// SPV_SUCCESS, then that status code is returned, no further callbacks are
|
||||
// issued, and no additional diagnostics are emitted.
|
||||
// This is a wrapper around the C API spvBinaryParse.
|
||||
bool Parse(const std::vector<uint32_t>& binary,
|
||||
const HeaderParser& header_parser,
|
||||
const InstructionParser& instruction_parser,
|
||||
spv_diagnostic* diagnostic = nullptr);
|
||||
|
||||
// Validates the given SPIR-V |binary|. Returns true if no issues are found.
|
||||
// Otherwise, returns false and communicates issues via the message consumer
|
||||
// registered.
|
||||
// Validates for SPIR-V spec rules for the SPIR-V version named in the
|
||||
// binary's header (at word offset 1). Additionally, if the target
|
||||
// environment is a client API (such as Vulkan 1.1), then validate for that
|
||||
// client API version, to the extent that it is verifiable from data in the
|
||||
// binary itself.
|
||||
bool Validate(const std::vector<uint32_t>& binary) const;
|
||||
// Like the previous overload, but provides the binary as a pointer and size:
|
||||
// |binary_size| specifies the number of words in |binary|.
|
||||
// Validates for SPIR-V spec rules for the SPIR-V version named in the
|
||||
// binary's header (at word offset 1). Additionally, if the target
|
||||
// environment is a client API (such as Vulkan 1.1), then validate for that
|
||||
// client API version, to the extent that it is verifiable from data in the
|
||||
// binary itself.
|
||||
bool Validate(const uint32_t* binary, size_t binary_size) const;
|
||||
// Like the previous overload, but takes an options object.
|
||||
// Validates for SPIR-V spec rules for the SPIR-V version named in the
|
||||
// binary's header (at word offset 1). Additionally, if the target
|
||||
// environment is a client API (such as Vulkan 1.1), then validate for that
|
||||
// client API version, to the extent that it is verifiable from data in the
|
||||
// binary itself, or in the validator options.
|
||||
bool Validate(const uint32_t* binary, size_t binary_size,
|
||||
spv_validator_options options) const;
|
||||
|
||||
// Was this object successfully constructed.
|
||||
bool IsValid() const;
|
||||
|
||||
private:
|
||||
struct SPIRV_TOOLS_LOCAL
|
||||
Impl; // Opaque struct for holding the data fields used by this class.
|
||||
std::unique_ptr<Impl> impl_; // Unique pointer to implementation data.
|
||||
};
|
||||
|
||||
} // namespace spvtools
|
||||
|
||||
#endif // INCLUDE_SPIRV_TOOLS_LIBSPIRV_HPP_
|
||||
@@ -0,0 +1,104 @@
|
||||
// Copyright (c) 2017 Pierre Moreau
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#ifndef INCLUDE_SPIRV_TOOLS_LINKER_HPP_
|
||||
#define INCLUDE_SPIRV_TOOLS_LINKER_HPP_
|
||||
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
#include <vector>
|
||||
|
||||
#include "libspirv.hpp"
|
||||
|
||||
namespace spvtools {
|
||||
|
||||
class SPIRV_TOOLS_EXPORT LinkerOptions {
|
||||
public:
|
||||
// Returns whether a library or an executable should be produced by the
|
||||
// linking phase.
|
||||
//
|
||||
// All exported symbols are kept when creating a library, whereas they will
|
||||
// be removed when creating an executable.
|
||||
// The returned value will be true if creating a library, and false if
|
||||
// creating an executable.
|
||||
bool GetCreateLibrary() const { return create_library_; }
|
||||
|
||||
// Sets whether a library or an executable should be produced.
|
||||
void SetCreateLibrary(bool create_library) {
|
||||
create_library_ = create_library;
|
||||
}
|
||||
|
||||
// Returns whether to verify the uniqueness of the unique ids in the merged
|
||||
// context.
|
||||
bool GetVerifyIds() const { return verify_ids_; }
|
||||
|
||||
// Sets whether to verify the uniqueness of the unique ids in the merged
|
||||
// context.
|
||||
void SetVerifyIds(bool verify_ids) { verify_ids_ = verify_ids; }
|
||||
|
||||
// Returns whether to allow for imported symbols to have no corresponding
|
||||
// exported symbols
|
||||
bool GetAllowPartialLinkage() const { return allow_partial_linkage_; }
|
||||
|
||||
// Sets whether to allow for imported symbols to have no corresponding
|
||||
// exported symbols
|
||||
void SetAllowPartialLinkage(bool allow_partial_linkage) {
|
||||
allow_partial_linkage_ = allow_partial_linkage;
|
||||
}
|
||||
|
||||
bool GetUseHighestVersion() const { return use_highest_version_; }
|
||||
void SetUseHighestVersion(bool use_highest_vers) {
|
||||
use_highest_version_ = use_highest_vers;
|
||||
}
|
||||
|
||||
bool GetAllowPtrTypeMismatch() const { return allow_ptr_type_mismatch_; }
|
||||
void SetAllowPtrTypeMismatch(bool allow_ptr_type_mismatch) {
|
||||
allow_ptr_type_mismatch_ = allow_ptr_type_mismatch;
|
||||
}
|
||||
|
||||
private:
|
||||
bool create_library_{false};
|
||||
bool verify_ids_{false};
|
||||
bool allow_partial_linkage_{false};
|
||||
bool use_highest_version_{false};
|
||||
bool allow_ptr_type_mismatch_{false};
|
||||
};
|
||||
|
||||
// Links one or more SPIR-V modules into a new SPIR-V module. That is, combine
|
||||
// several SPIR-V modules into one, resolving link dependencies between them.
|
||||
//
|
||||
// At least one binary has to be provided in |binaries|. Those binaries do not
|
||||
// have to be valid, but they should be at least parseable.
|
||||
// The functions can fail due to the following:
|
||||
// * The given context was not initialised using `spvContextCreate()`;
|
||||
// * No input modules were given;
|
||||
// * One or more of those modules were not parseable;
|
||||
// * The input modules used different addressing or memory models;
|
||||
// * The ID or global variable number limit were exceeded;
|
||||
// * Some entry points were defined multiple times;
|
||||
// * Some imported symbols did not have an exported counterpart;
|
||||
// * Possibly other reasons.
|
||||
SPIRV_TOOLS_EXPORT spv_result_t
|
||||
Link(const Context& context, const std::vector<std::vector<uint32_t>>& binaries,
|
||||
std::vector<uint32_t>* linked_binary,
|
||||
const LinkerOptions& options = LinkerOptions());
|
||||
SPIRV_TOOLS_EXPORT spv_result_t
|
||||
Link(const Context& context, const uint32_t* const* binaries,
|
||||
const size_t* binary_sizes, size_t num_binaries,
|
||||
std::vector<uint32_t>* linked_binary,
|
||||
const LinkerOptions& options = LinkerOptions());
|
||||
|
||||
} // namespace spvtools
|
||||
|
||||
#endif // INCLUDE_SPIRV_TOOLS_LINKER_HPP_
|
||||
@@ -0,0 +1,973 @@
|
||||
// Copyright (c) 2016 Google Inc.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#ifndef INCLUDE_SPIRV_TOOLS_OPTIMIZER_HPP_
|
||||
#define INCLUDE_SPIRV_TOOLS_OPTIMIZER_HPP_
|
||||
|
||||
#include <memory>
|
||||
#include <ostream>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <unordered_set>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
#include "libspirv.hpp"
|
||||
|
||||
namespace spvtools {
|
||||
|
||||
namespace opt {
|
||||
class Pass;
|
||||
struct DescriptorSetAndBinding;
|
||||
} // namespace opt
|
||||
|
||||
// C++ interface for SPIR-V optimization functionalities. It wraps the context
|
||||
// (including target environment and the corresponding SPIR-V grammar) and
|
||||
// provides methods for registering optimization passes and optimizing.
|
||||
//
|
||||
// Instances of this class provides basic thread-safety guarantee.
|
||||
class SPIRV_TOOLS_EXPORT Optimizer {
|
||||
public:
|
||||
// The token for an optimization pass. It is returned via one of the
|
||||
// Create*Pass() standalone functions at the end of this header file and
|
||||
// consumed by the RegisterPass() method. Tokens are one-time objects that
|
||||
// only support move; copying is not allowed.
|
||||
struct PassToken {
|
||||
struct SPIRV_TOOLS_LOCAL Impl; // Opaque struct for holding internal data.
|
||||
|
||||
PassToken(std::unique_ptr<Impl>);
|
||||
|
||||
// Tokens for built-in passes should be created using Create*Pass functions
|
||||
// below; for out-of-tree passes, use this constructor instead.
|
||||
// Note that this API isn't guaranteed to be stable and may change without
|
||||
// preserving source or binary compatibility in the future.
|
||||
PassToken(std::unique_ptr<opt::Pass>&& pass);
|
||||
|
||||
// Tokens can only be moved. Copying is disabled.
|
||||
PassToken(const PassToken&) = delete;
|
||||
PassToken(PassToken&&);
|
||||
PassToken& operator=(const PassToken&) = delete;
|
||||
PassToken& operator=(PassToken&&);
|
||||
|
||||
~PassToken();
|
||||
|
||||
std::unique_ptr<Impl> impl_; // Unique pointer to internal data.
|
||||
};
|
||||
|
||||
// Constructs an instance with the given target |env|, which is used to decode
|
||||
// the binaries to be optimized later.
|
||||
//
|
||||
// The instance will have an empty message consumer, which ignores all
|
||||
// messages from the library. Use SetMessageConsumer() to supply a consumer
|
||||
// if messages are of concern.
|
||||
explicit Optimizer(spv_target_env env);
|
||||
|
||||
// Disables copy/move constructor/assignment operations.
|
||||
Optimizer(const Optimizer&) = delete;
|
||||
Optimizer(Optimizer&&) = delete;
|
||||
Optimizer& operator=(const Optimizer&) = delete;
|
||||
Optimizer& operator=(Optimizer&&) = delete;
|
||||
|
||||
// Destructs this instance.
|
||||
~Optimizer();
|
||||
|
||||
// Sets the message consumer to the given |consumer|. The |consumer| will be
|
||||
// invoked once for each message communicated from the library.
|
||||
void SetMessageConsumer(MessageConsumer consumer);
|
||||
|
||||
// Returns a reference to the registered message consumer.
|
||||
const MessageConsumer& consumer() const;
|
||||
|
||||
// Registers the given |pass| to this optimizer. Passes will be run in the
|
||||
// exact order of registration. The token passed in will be consumed by this
|
||||
// method.
|
||||
Optimizer& RegisterPass(PassToken&& pass);
|
||||
|
||||
// Registers passes that attempt to improve performance of generated code.
|
||||
// This sequence of passes is subject to constant review and will change
|
||||
// from time to time.
|
||||
//
|
||||
// If |preserve_interface| is true, all non-io variables in the entry point
|
||||
// interface are considered live and are not eliminated.
|
||||
Optimizer& RegisterPerformancePasses();
|
||||
Optimizer& RegisterPerformancePasses(bool preserve_interface);
|
||||
|
||||
// Registers passes that attempt to improve the size of generated code.
|
||||
// This sequence of passes is subject to constant review and will change
|
||||
// from time to time.
|
||||
//
|
||||
// If |preserve_interface| is true, all non-io variables in the entry point
|
||||
// interface are considered live and are not eliminated.
|
||||
Optimizer& RegisterSizePasses();
|
||||
Optimizer& RegisterSizePasses(bool preserve_interface);
|
||||
|
||||
// Registers passes that attempt to legalize the generated code.
|
||||
//
|
||||
// Note: this recipe is specially designed for legalizing SPIR-V. It should be
|
||||
// used by compilers after translating HLSL source code literally. It should
|
||||
// *not* be used by general workloads for performance or size improvement.
|
||||
//
|
||||
// This sequence of passes is subject to constant review and will change
|
||||
// from time to time.
|
||||
//
|
||||
// If |preserve_interface| is true, all non-io variables in the entry point
|
||||
// interface are considered live and are not eliminated.
|
||||
Optimizer& RegisterLegalizationPasses();
|
||||
Optimizer& RegisterLegalizationPasses(bool preserve_interface);
|
||||
|
||||
// Register passes specified in the list of |flags|. Each flag must be a
|
||||
// string of a form accepted by Optimizer::FlagHasValidForm().
|
||||
//
|
||||
// If the list of flags contains an invalid entry, it returns false and an
|
||||
// error message is emitted to the MessageConsumer object (use
|
||||
// Optimizer::SetMessageConsumer to define a message consumer, if needed).
|
||||
//
|
||||
// If |preserve_interface| is true, all non-io variables in the entry point
|
||||
// interface are considered live and are not eliminated.
|
||||
//
|
||||
// If all the passes are registered successfully, it returns true.
|
||||
bool RegisterPassesFromFlags(const std::vector<std::string>& flags);
|
||||
bool RegisterPassesFromFlags(const std::vector<std::string>& flags,
|
||||
bool preserve_interface);
|
||||
|
||||
// Registers the optimization pass associated with |flag|. This only accepts
|
||||
// |flag| values of the form "--pass_name[=pass_args]". If no such pass
|
||||
// exists, it returns false. Otherwise, the pass is registered and it returns
|
||||
// true.
|
||||
//
|
||||
// The following flags have special meaning:
|
||||
//
|
||||
// -O: Registers all performance optimization passes
|
||||
// (Optimizer::RegisterPerformancePasses)
|
||||
//
|
||||
// -Os: Registers all size optimization passes
|
||||
// (Optimizer::RegisterSizePasses).
|
||||
//
|
||||
// --legalize-hlsl: Registers all passes that legalize SPIR-V generated by an
|
||||
// HLSL front-end.
|
||||
//
|
||||
// If |preserve_interface| is true, all non-io variables in the entry point
|
||||
// interface are considered live and are not eliminated.
|
||||
bool RegisterPassFromFlag(const std::string& flag);
|
||||
bool RegisterPassFromFlag(const std::string& flag, bool preserve_interface);
|
||||
|
||||
// Validates that |flag| has a valid format. Strings accepted:
|
||||
//
|
||||
// --pass_name[=pass_args]
|
||||
// -O
|
||||
// -Os
|
||||
//
|
||||
// If |flag| takes one of the forms above, it returns true. Otherwise, it
|
||||
// returns false.
|
||||
bool FlagHasValidForm(const std::string& flag) const;
|
||||
|
||||
// Allows changing, after creation time, the target environment to be
|
||||
// optimized for and validated. Should be called before calling Run().
|
||||
void SetTargetEnv(const spv_target_env env);
|
||||
|
||||
// Optimizes the given SPIR-V module |original_binary| and writes the
|
||||
// optimized binary into |optimized_binary|. The optimized binary uses
|
||||
// the same SPIR-V version as the original binary.
|
||||
//
|
||||
// Returns true on successful optimization, whether or not the module is
|
||||
// modified. Returns false if |original_binary| fails to validate or if errors
|
||||
// occur when processing |original_binary| using any of the registered passes.
|
||||
// In that case, no further passes are executed and the contents in
|
||||
// |optimized_binary| may be invalid.
|
||||
//
|
||||
// By default, the binary is validated before any transforms are performed,
|
||||
// and optionally after each transform. Validation uses SPIR-V spec rules
|
||||
// for the SPIR-V version named in the binary's header (at word offset 1).
|
||||
// Additionally, if the target environment is a client API (such as
|
||||
// Vulkan 1.1), then validate for that client API version, to the extent
|
||||
// that it is verifiable from data in the binary itself.
|
||||
//
|
||||
// It's allowed to alias |original_binary| to the start of |optimized_binary|.
|
||||
bool Run(const uint32_t* original_binary, size_t original_binary_size,
|
||||
std::vector<uint32_t>* optimized_binary) const;
|
||||
|
||||
// DEPRECATED: Same as above, except passes |options| to the validator when
|
||||
// trying to validate the binary. If |skip_validation| is true, then the
|
||||
// caller is guaranteeing that |original_binary| is valid, and the validator
|
||||
// will not be run. The |max_id_bound| is the limit on the max id in the
|
||||
// module.
|
||||
bool Run(const uint32_t* original_binary, const size_t original_binary_size,
|
||||
std::vector<uint32_t>* optimized_binary,
|
||||
const ValidatorOptions& options, bool skip_validation) const;
|
||||
|
||||
// Same as above, except it takes an options object. See the documentation
|
||||
// for |OptimizerOptions| to see which options can be set.
|
||||
//
|
||||
// By default, the binary is validated before any transforms are performed,
|
||||
// and optionally after each transform. Validation uses SPIR-V spec rules
|
||||
// for the SPIR-V version named in the binary's header (at word offset 1).
|
||||
// Additionally, if the target environment is a client API (such as
|
||||
// Vulkan 1.1), then validate for that client API version, to the extent
|
||||
// that it is verifiable from data in the binary itself, or from the
|
||||
// validator options set on the optimizer options.
|
||||
bool Run(const uint32_t* original_binary, const size_t original_binary_size,
|
||||
std::vector<uint32_t>* optimized_binary,
|
||||
const spv_optimizer_options opt_options) const;
|
||||
|
||||
// Returns a vector of strings with all the pass names added to this
|
||||
// optimizer's pass manager. These strings are valid until the associated
|
||||
// pass manager is destroyed.
|
||||
std::vector<const char*> GetPassNames() const;
|
||||
|
||||
// Sets the option to print the disassembly before each pass and after the
|
||||
// last pass. If |out| is null, then no output is generated. Otherwise,
|
||||
// output is sent to the |out| output stream.
|
||||
Optimizer& SetPrintAll(std::ostream* out);
|
||||
|
||||
// Sets the option to print the resource utilization of each pass. If |out|
|
||||
// is null, then no output is generated. Otherwise, output is sent to the
|
||||
// |out| output stream.
|
||||
Optimizer& SetTimeReport(std::ostream* out);
|
||||
|
||||
// Sets the option to validate the module after each pass.
|
||||
Optimizer& SetValidateAfterAll(bool validate);
|
||||
|
||||
private:
|
||||
struct SPIRV_TOOLS_LOCAL Impl; // Opaque struct for holding internal data.
|
||||
std::unique_ptr<Impl> impl_; // Unique pointer to internal data.
|
||||
};
|
||||
|
||||
// Creates a null pass.
|
||||
// A null pass does nothing to the SPIR-V module to be optimized.
|
||||
Optimizer::PassToken CreateNullPass();
|
||||
|
||||
// Creates a strip-debug-info pass.
|
||||
// A strip-debug-info pass removes all debug instructions (as documented in
|
||||
// Section 3.42.2 of the SPIR-V spec) of the SPIR-V module to be optimized.
|
||||
Optimizer::PassToken CreateStripDebugInfoPass();
|
||||
|
||||
// [Deprecated] This will create a strip-nonsemantic-info pass. See below.
|
||||
Optimizer::PassToken CreateStripReflectInfoPass();
|
||||
|
||||
// Creates a strip-nonsemantic-info pass.
|
||||
// A strip-nonsemantic-info pass removes all reflections and explicitly
|
||||
// non-semantic instructions.
|
||||
Optimizer::PassToken CreateStripNonSemanticInfoPass();
|
||||
|
||||
// Creates an eliminate-dead-functions pass.
|
||||
// An eliminate-dead-functions pass will remove all functions that are not in
|
||||
// the call trees rooted at entry points and exported functions. These
|
||||
// functions are not needed because they will never be called.
|
||||
Optimizer::PassToken CreateEliminateDeadFunctionsPass();
|
||||
|
||||
// Creates an eliminate-dead-members pass.
|
||||
// An eliminate-dead-members pass will remove all unused members of structures.
|
||||
// This will not affect the data layout of the remaining members.
|
||||
Optimizer::PassToken CreateEliminateDeadMembersPass();
|
||||
|
||||
// Creates a set-spec-constant-default-value pass from a mapping from spec-ids
|
||||
// to the default values in the form of string.
|
||||
// A set-spec-constant-default-value pass sets the default values for the
|
||||
// spec constants that have SpecId decorations (i.e., those defined by
|
||||
// OpSpecConstant{|True|False} instructions).
|
||||
Optimizer::PassToken CreateSetSpecConstantDefaultValuePass(
|
||||
const std::unordered_map<uint32_t, std::string>& id_value_map);
|
||||
|
||||
// Creates a set-spec-constant-default-value pass from a mapping from spec-ids
|
||||
// to the default values in the form of bit pattern.
|
||||
// A set-spec-constant-default-value pass sets the default values for the
|
||||
// spec constants that have SpecId decorations (i.e., those defined by
|
||||
// OpSpecConstant{|True|False} instructions).
|
||||
Optimizer::PassToken CreateSetSpecConstantDefaultValuePass(
|
||||
const std::unordered_map<uint32_t, std::vector<uint32_t>>& id_value_map);
|
||||
|
||||
// Creates a flatten-decoration pass.
|
||||
// A flatten-decoration pass replaces grouped decorations with equivalent
|
||||
// ungrouped decorations. That is, it replaces each OpDecorationGroup
|
||||
// instruction and associated OpGroupDecorate and OpGroupMemberDecorate
|
||||
// instructions with equivalent OpDecorate and OpMemberDecorate instructions.
|
||||
// The pass does not attempt to preserve debug information for instructions
|
||||
// it removes.
|
||||
Optimizer::PassToken CreateFlattenDecorationPass();
|
||||
|
||||
// Creates a freeze-spec-constant-value pass.
|
||||
// A freeze-spec-constant pass specializes the value of spec constants to
|
||||
// their default values. This pass only processes the spec constants that have
|
||||
// SpecId decorations (defined by OpSpecConstant, OpSpecConstantTrue, or
|
||||
// OpSpecConstantFalse instructions) and replaces them with their normal
|
||||
// counterparts (OpConstant, OpConstantTrue, or OpConstantFalse). The
|
||||
// corresponding SpecId annotation instructions will also be removed. This
|
||||
// pass does not fold the newly added normal constants and does not process
|
||||
// other spec constants defined by OpSpecConstantComposite or
|
||||
// OpSpecConstantOp.
|
||||
Optimizer::PassToken CreateFreezeSpecConstantValuePass();
|
||||
|
||||
// Creates a fold-spec-constant-op-and-composite pass.
|
||||
// A fold-spec-constant-op-and-composite pass folds spec constants defined by
|
||||
// OpSpecConstantOp or OpSpecConstantComposite instruction, to normal Constants
|
||||
// defined by OpConstantTrue, OpConstantFalse, OpConstant, OpConstantNull, or
|
||||
// OpConstantComposite instructions. Note that spec constants defined with
|
||||
// OpSpecConstant, OpSpecConstantTrue, or OpSpecConstantFalse instructions are
|
||||
// not handled, as these instructions indicate their value are not determined
|
||||
// and can be changed in future. A spec constant is foldable if all of its
|
||||
// value(s) can be determined from the module. E.g., an integer spec constant
|
||||
// defined with OpSpecConstantOp instruction can be folded if its value won't
|
||||
// change later. This pass will replace the original OpSpecConstantOp
|
||||
// instruction with an OpConstant instruction. When folding composite spec
|
||||
// constants, new instructions may be inserted to define the components of the
|
||||
// composite constant first, then the original spec constants will be replaced
|
||||
// by OpConstantComposite instructions.
|
||||
//
|
||||
// There are some operations not supported yet:
|
||||
// OpSConvert, OpFConvert, OpQuantizeToF16 and
|
||||
// all the operations under Kernel capability.
|
||||
// TODO(qining): Add support for the operations listed above.
|
||||
Optimizer::PassToken CreateFoldSpecConstantOpAndCompositePass();
|
||||
|
||||
// Creates a unify-constant pass.
|
||||
// A unify-constant pass de-duplicates the constants. Constants with the exact
|
||||
// same value and identical form will be unified and only one constant will
|
||||
// be kept for each unique pair of type and value.
|
||||
// There are several cases not handled by this pass:
|
||||
// 1) Constants defined by OpConstantNull instructions (null constants) and
|
||||
// constants defined by OpConstantFalse, OpConstant or OpConstantComposite
|
||||
// with value 0 (zero-valued normal constants) are not considered equivalent.
|
||||
// So null constants won't be used to replace zero-valued normal constants,
|
||||
// vice versa.
|
||||
// 2) Whenever there are decorations to the constant's result id id, the
|
||||
// constant won't be handled, which means, it won't be used to replace any
|
||||
// other constants, neither can other constants replace it.
|
||||
// 3) NaN in float point format with different bit patterns are not unified.
|
||||
Optimizer::PassToken CreateUnifyConstantPass();
|
||||
|
||||
// Creates a eliminate-dead-constant pass.
|
||||
// A eliminate-dead-constant pass removes dead constants, including normal
|
||||
// constants defined by OpConstant, OpConstantComposite, OpConstantTrue, or
|
||||
// OpConstantFalse and spec constants defined by OpSpecConstant,
|
||||
// OpSpecConstantComposite, OpSpecConstantTrue, OpSpecConstantFalse or
|
||||
// OpSpecConstantOp.
|
||||
Optimizer::PassToken CreateEliminateDeadConstantPass();
|
||||
|
||||
// Creates a strength-reduction pass.
|
||||
// A strength-reduction pass will look for opportunities to replace an
|
||||
// instruction with an equivalent and less expensive one. For example,
|
||||
// multiplying by a power of 2 can be replaced by a bit shift.
|
||||
Optimizer::PassToken CreateStrengthReductionPass();
|
||||
|
||||
// Creates a block merge pass.
|
||||
// This pass searches for blocks with a single Branch to a block with no
|
||||
// other predecessors and merges the blocks into a single block. Continue
|
||||
// blocks and Merge blocks are not candidates for the second block.
|
||||
//
|
||||
// The pass is most useful after Dead Branch Elimination, which can leave
|
||||
// such sequences of blocks. Merging them makes subsequent passes more
|
||||
// effective, such as single block local store-load elimination.
|
||||
//
|
||||
// While this pass reduces the number of occurrences of this sequence, at
|
||||
// this time it does not guarantee all such sequences are eliminated.
|
||||
//
|
||||
// Presence of phi instructions can inhibit this optimization. Handling
|
||||
// these is left for future improvements.
|
||||
Optimizer::PassToken CreateBlockMergePass();
|
||||
|
||||
// Creates an exhaustive inline pass.
|
||||
// An exhaustive inline pass attempts to exhaustively inline all function
|
||||
// calls in all functions in an entry point call tree. The intent is to enable,
|
||||
// albeit through brute force, analysis and optimization across function
|
||||
// calls by subsequent optimization passes. As the inlining is exhaustive,
|
||||
// there is no attempt to optimize for size or runtime performance. Functions
|
||||
// that are not in the call tree of an entry point are not changed.
|
||||
Optimizer::PassToken CreateInlineExhaustivePass();
|
||||
|
||||
// Creates an opaque inline pass.
|
||||
// An opaque inline pass inlines all function calls in all functions in all
|
||||
// entry point call trees where the called function contains an opaque type
|
||||
// in either its parameter types or return type. An opaque type is currently
|
||||
// defined as Image, Sampler or SampledImage. The intent is to enable, albeit
|
||||
// through brute force, analysis and optimization across these function calls
|
||||
// by subsequent passes in order to remove the storing of opaque types which is
|
||||
// not legal in Vulkan. Functions that are not in the call tree of an entry
|
||||
// point are not changed.
|
||||
Optimizer::PassToken CreateInlineOpaquePass();
|
||||
|
||||
// Creates a single-block local variable load/store elimination pass.
|
||||
// For every entry point function, do single block memory optimization of
|
||||
// function variables referenced only with non-access-chain loads and stores.
|
||||
// For each targeted variable load, if previous store to that variable in the
|
||||
// block, replace the load's result id with the value id of the store.
|
||||
// If previous load within the block, replace the current load's result id
|
||||
// with the previous load's result id. In either case, delete the current
|
||||
// load. Finally, check if any remaining stores are useless, and delete store
|
||||
// and variable if possible.
|
||||
//
|
||||
// The presence of access chain references and function calls can inhibit
|
||||
// the above optimization.
|
||||
//
|
||||
// Only modules with relaxed logical addressing (see opt/instruction.h) are
|
||||
// currently processed.
|
||||
//
|
||||
// This pass is most effective if preceded by Inlining and
|
||||
// LocalAccessChainConvert. This pass will reduce the work needed to be done
|
||||
// by LocalSingleStoreElim and LocalMultiStoreElim.
|
||||
//
|
||||
// Only functions in the call tree of an entry point are processed.
|
||||
Optimizer::PassToken CreateLocalSingleBlockLoadStoreElimPass();
|
||||
|
||||
// Create dead branch elimination pass.
|
||||
// For each entry point function, this pass will look for SelectionMerge
|
||||
// BranchConditionals with constant condition and convert to a Branch to
|
||||
// the indicated label. It will delete resulting dead blocks.
|
||||
//
|
||||
// For all phi functions in merge block, replace all uses with the id
|
||||
// corresponding to the living predecessor.
|
||||
//
|
||||
// Note that some branches and blocks may be left to avoid creating invalid
|
||||
// control flow. Improving this is left to future work.
|
||||
//
|
||||
// This pass is most effective when preceded by passes which eliminate
|
||||
// local loads and stores, effectively propagating constant values where
|
||||
// possible.
|
||||
Optimizer::PassToken CreateDeadBranchElimPass();
|
||||
|
||||
// Creates an SSA local variable load/store elimination pass.
|
||||
// For every entry point function, eliminate all loads and stores of function
|
||||
// scope variables only referenced with non-access-chain loads and stores.
|
||||
// Eliminate the variables as well.
|
||||
//
|
||||
// The presence of access chain references and function calls can inhibit
|
||||
// the above optimization.
|
||||
//
|
||||
// Only shader modules with relaxed logical addressing (see opt/instruction.h)
|
||||
// are currently processed. Currently modules with any extensions enabled are
|
||||
// not processed. This is left for future work.
|
||||
//
|
||||
// This pass is most effective if preceded by Inlining and
|
||||
// LocalAccessChainConvert. LocalSingleStoreElim and LocalSingleBlockElim
|
||||
// will reduce the work that this pass has to do.
|
||||
Optimizer::PassToken CreateLocalMultiStoreElimPass();
|
||||
|
||||
// Creates a local access chain conversion pass.
|
||||
// A local access chain conversion pass identifies all function scope
|
||||
// variables which are accessed only with loads, stores and access chains
|
||||
// with constant indices. It then converts all loads and stores of such
|
||||
// variables into equivalent sequences of loads, stores, extracts and inserts.
|
||||
//
|
||||
// This pass only processes entry point functions. It currently only converts
|
||||
// non-nested, non-ptr access chains. It does not process modules with
|
||||
// non-32-bit integer types present. Optional memory access options on loads
|
||||
// and stores are ignored as we are only processing function scope variables.
|
||||
//
|
||||
// This pass unifies access to these variables to a single mode and simplifies
|
||||
// subsequent analysis and elimination of these variables along with their
|
||||
// loads and stores allowing values to propagate to their points of use where
|
||||
// possible.
|
||||
Optimizer::PassToken CreateLocalAccessChainConvertPass();
|
||||
|
||||
// Creates a local single store elimination pass.
|
||||
// For each entry point function, this pass eliminates loads and stores for
|
||||
// function scope variable that are stored to only once, where possible. Only
|
||||
// whole variable loads and stores are eliminated; access-chain references are
|
||||
// not optimized. Replace all loads of such variables with the value that is
|
||||
// stored and eliminate any resulting dead code.
|
||||
//
|
||||
// Currently, the presence of access chains and function calls can inhibit this
|
||||
// pass, however the Inlining and LocalAccessChainConvert passes can make it
|
||||
// more effective. In additional, many non-load/store memory operations are
|
||||
// not supported and will prohibit optimization of a function. Support of
|
||||
// these operations are future work.
|
||||
//
|
||||
// Only shader modules with relaxed logical addressing (see opt/instruction.h)
|
||||
// are currently processed.
|
||||
//
|
||||
// This pass will reduce the work needed to be done by LocalSingleBlockElim
|
||||
// and LocalMultiStoreElim and can improve the effectiveness of other passes
|
||||
// such as DeadBranchElimination which depend on values for their analysis.
|
||||
Optimizer::PassToken CreateLocalSingleStoreElimPass();
|
||||
|
||||
// Creates an insert/extract elimination pass.
|
||||
// This pass processes each entry point function in the module, searching for
|
||||
// extracts on a sequence of inserts. It further searches the sequence for an
|
||||
// insert with indices identical to the extract. If such an insert can be
|
||||
// found before hitting a conflicting insert, the extract's result id is
|
||||
// replaced with the id of the values from the insert.
|
||||
//
|
||||
// Besides removing extracts this pass enables subsequent dead code elimination
|
||||
// passes to delete the inserts. This pass performs best after access chains are
|
||||
// converted to inserts and extracts and local loads and stores are eliminated.
|
||||
Optimizer::PassToken CreateInsertExtractElimPass();
|
||||
|
||||
// Creates a dead insert elimination pass.
|
||||
// This pass processes each entry point function in the module, searching for
|
||||
// unreferenced inserts into composite types. These are most often unused
|
||||
// stores to vector components. They are unused because they are never
|
||||
// referenced, or because there is another insert to the same component between
|
||||
// the insert and the reference. After removing the inserts, dead code
|
||||
// elimination is attempted on the inserted values.
|
||||
//
|
||||
// This pass performs best after access chains are converted to inserts and
|
||||
// extracts and local loads and stores are eliminated. While executing this
|
||||
// pass can be advantageous on its own, it is also advantageous to execute
|
||||
// this pass after CreateInsertExtractPass() as it will remove any unused
|
||||
// inserts created by that pass.
|
||||
Optimizer::PassToken CreateDeadInsertElimPass();
|
||||
|
||||
// Create aggressive dead code elimination pass
|
||||
// This pass eliminates unused code from the module. In addition,
|
||||
// it detects and eliminates code which may have spurious uses but which do
|
||||
// not contribute to the output of the function. The most common cause of
|
||||
// such code sequences is summations in loops whose result is no longer used
|
||||
// due to dead code elimination. This optimization has additional compile
|
||||
// time cost over standard dead code elimination.
|
||||
//
|
||||
// This pass only processes entry point functions. It also only processes
|
||||
// shaders with relaxed logical addressing (see opt/instruction.h). It
|
||||
// currently will not process functions with function calls. Unreachable
|
||||
// functions are deleted.
|
||||
//
|
||||
// This pass will be made more effective by first running passes that remove
|
||||
// dead control flow and inlines function calls.
|
||||
//
|
||||
// This pass can be especially useful after running Local Access Chain
|
||||
// Conversion, which tends to cause cycles of dead code to be left after
|
||||
// Store/Load elimination passes are completed. These cycles cannot be
|
||||
// eliminated with standard dead code elimination.
|
||||
//
|
||||
// If |preserve_interface| is true, all non-io variables in the entry point
|
||||
// interface are considered live and are not eliminated. This mode is needed
|
||||
// by GPU-Assisted validation instrumentation, where a change in the interface
|
||||
// is not allowed.
|
||||
//
|
||||
// If |remove_outputs| is true, allow outputs to be removed from the interface.
|
||||
// This is only safe if the caller knows that there is no corresponding input
|
||||
// variable in the following shader. It is false by default.
|
||||
Optimizer::PassToken CreateAggressiveDCEPass();
|
||||
Optimizer::PassToken CreateAggressiveDCEPass(bool preserve_interface);
|
||||
Optimizer::PassToken CreateAggressiveDCEPass(bool preserve_interface,
|
||||
bool remove_outputs);
|
||||
|
||||
// Creates a remove-unused-interface-variables pass.
|
||||
// Removes variables referenced on the |OpEntryPoint| instruction that are not
|
||||
// referenced in the entry point function or any function in its call tree. Note
|
||||
// that this could cause the shader interface to no longer match other shader
|
||||
// stages.
|
||||
Optimizer::PassToken CreateRemoveUnusedInterfaceVariablesPass();
|
||||
|
||||
// Creates an empty pass.
|
||||
// This is deprecated and will be removed.
|
||||
// TODO(jaebaek): remove this pass after handling glslang's broken unit tests.
|
||||
// https://github.com/KhronosGroup/glslang/pull/2440
|
||||
Optimizer::PassToken CreatePropagateLineInfoPass();
|
||||
|
||||
// Creates an empty pass.
|
||||
// This is deprecated and will be removed.
|
||||
// TODO(jaebaek): remove this pass after handling glslang's broken unit tests.
|
||||
// https://github.com/KhronosGroup/glslang/pull/2440
|
||||
Optimizer::PassToken CreateRedundantLineInfoElimPass();
|
||||
|
||||
// Creates a compact ids pass.
|
||||
// The pass remaps result ids to a compact and gapless range starting from %1.
|
||||
Optimizer::PassToken CreateCompactIdsPass();
|
||||
|
||||
// Creates a remove duplicate pass.
|
||||
// This pass removes various duplicates:
|
||||
// * duplicate capabilities;
|
||||
// * duplicate extended instruction imports;
|
||||
// * duplicate types;
|
||||
// * duplicate decorations.
|
||||
Optimizer::PassToken CreateRemoveDuplicatesPass();
|
||||
|
||||
// Creates a CFG cleanup pass.
|
||||
// This pass removes cruft from the control flow graph of functions that are
|
||||
// reachable from entry points and exported functions. It currently includes the
|
||||
// following functionality:
|
||||
//
|
||||
// - Removal of unreachable basic blocks.
|
||||
Optimizer::PassToken CreateCFGCleanupPass();
|
||||
|
||||
// Create dead variable elimination pass.
|
||||
// This pass will delete module scope variables, along with their decorations,
|
||||
// that are not referenced.
|
||||
Optimizer::PassToken CreateDeadVariableEliminationPass();
|
||||
|
||||
// create merge return pass.
|
||||
// changes functions that have multiple return statements so they have a single
|
||||
// return statement.
|
||||
//
|
||||
// for structured control flow it is assumed that the only unreachable blocks in
|
||||
// the function are trivial merge and continue blocks.
|
||||
//
|
||||
// a trivial merge block contains the label and an opunreachable instructions,
|
||||
// nothing else. a trivial continue block contain a label and an opbranch to
|
||||
// the header, nothing else.
|
||||
//
|
||||
// these conditions are guaranteed to be met after running dead-branch
|
||||
// elimination.
|
||||
Optimizer::PassToken CreateMergeReturnPass();
|
||||
|
||||
// Create value numbering pass.
|
||||
// This pass will look for instructions in the same basic block that compute the
|
||||
// same value, and remove the redundant ones.
|
||||
Optimizer::PassToken CreateLocalRedundancyEliminationPass();
|
||||
|
||||
// Create LICM pass.
|
||||
// This pass will look for invariant instructions inside loops and hoist them to
|
||||
// the loops preheader.
|
||||
Optimizer::PassToken CreateLoopInvariantCodeMotionPass();
|
||||
|
||||
// Creates a loop fission pass.
|
||||
// This pass will split all top level loops whose register pressure exceedes the
|
||||
// given |threshold|.
|
||||
Optimizer::PassToken CreateLoopFissionPass(size_t threshold);
|
||||
|
||||
// Creates a loop fusion pass.
|
||||
// This pass will look for adjacent loops that are compatible and legal to be
|
||||
// fused. The fuse all such loops as long as the register usage for the fused
|
||||
// loop stays under the threshold defined by |max_registers_per_loop|.
|
||||
Optimizer::PassToken CreateLoopFusionPass(size_t max_registers_per_loop);
|
||||
|
||||
// Creates a loop peeling pass.
|
||||
// This pass will look for conditions inside a loop that are true or false only
|
||||
// for the N first or last iteration. For loop with such condition, those N
|
||||
// iterations of the loop will be executed outside of the main loop.
|
||||
// To limit code size explosion, the loop peeling can only happen if the code
|
||||
// size growth for each loop is under |code_growth_threshold|.
|
||||
Optimizer::PassToken CreateLoopPeelingPass();
|
||||
|
||||
// Creates a loop unswitch pass.
|
||||
// This pass will look for loop independent branch conditions and move the
|
||||
// condition out of the loop and version the loop based on the taken branch.
|
||||
// Works best after LICM and local multi store elimination pass.
|
||||
Optimizer::PassToken CreateLoopUnswitchPass();
|
||||
|
||||
// Create global value numbering pass.
|
||||
// This pass will look for instructions where the same value is computed on all
|
||||
// paths leading to the instruction. Those instructions are deleted.
|
||||
Optimizer::PassToken CreateRedundancyEliminationPass();
|
||||
|
||||
// Create scalar replacement pass.
|
||||
// This pass replaces composite function scope variables with variables for each
|
||||
// element if those elements are accessed individually. The parameter is a
|
||||
// limit on the number of members in the composite variable that the pass will
|
||||
// consider replacing.
|
||||
Optimizer::PassToken CreateScalarReplacementPass(uint32_t size_limit = 100);
|
||||
|
||||
// Create a private to local pass.
|
||||
// This pass looks for variables declared in the private storage class that are
|
||||
// used in only one function. Those variables are moved to the function storage
|
||||
// class in the function that they are used.
|
||||
Optimizer::PassToken CreatePrivateToLocalPass();
|
||||
|
||||
// Creates a conditional constant propagation (CCP) pass.
|
||||
// This pass implements the SSA-CCP algorithm in
|
||||
//
|
||||
// Constant propagation with conditional branches,
|
||||
// Wegman and Zadeck, ACM TOPLAS 13(2):181-210.
|
||||
//
|
||||
// Constant values in expressions and conditional jumps are folded and
|
||||
// simplified. This may reduce code size by removing never executed jump targets
|
||||
// and computations with constant operands.
|
||||
Optimizer::PassToken CreateCCPPass();
|
||||
|
||||
// Creates a workaround driver bugs pass. This pass attempts to work around
|
||||
// a known driver bug (issue #1209) by identifying the bad code sequences and
|
||||
// rewriting them.
|
||||
//
|
||||
// Current workaround: Avoid OpUnreachable instructions in loops.
|
||||
Optimizer::PassToken CreateWorkaround1209Pass();
|
||||
|
||||
// Creates a pass that converts if-then-else like assignments into OpSelect.
|
||||
Optimizer::PassToken CreateIfConversionPass();
|
||||
|
||||
// Creates a pass that will replace instructions that are not valid for the
|
||||
// current shader stage by constants. Has no effect on non-shader modules.
|
||||
Optimizer::PassToken CreateReplaceInvalidOpcodePass();
|
||||
|
||||
// Creates a pass that simplifies instructions using the instruction folder.
|
||||
Optimizer::PassToken CreateSimplificationPass();
|
||||
|
||||
// Create loop unroller pass.
|
||||
// Creates a pass to unroll loops which have the "Unroll" loop control
|
||||
// mask set. The loops must meet a specific criteria in order to be unrolled
|
||||
// safely this criteria is checked before doing the unroll by the
|
||||
// LoopUtils::CanPerformUnroll method. Any loop that does not meet the criteria
|
||||
// won't be unrolled. See CanPerformUnroll LoopUtils.h for more information.
|
||||
Optimizer::PassToken CreateLoopUnrollPass(bool fully_unroll, int factor = 0);
|
||||
|
||||
// Create the SSA rewrite pass.
|
||||
// This pass converts load/store operations on function local variables into
|
||||
// operations on SSA IDs. This allows SSA optimizers to act on these variables.
|
||||
// Only variables that are local to the function and of supported types are
|
||||
// processed (see IsSSATargetVar for details).
|
||||
Optimizer::PassToken CreateSSARewritePass();
|
||||
|
||||
// Create pass to convert relaxed precision instructions to half precision.
|
||||
// This pass converts as many relaxed float32 arithmetic operations to half as
|
||||
// possible. It converts any float32 operands to half if needed. It converts
|
||||
// any resulting half precision values back to float32 as needed. No variables
|
||||
// are changed. No image operations are changed.
|
||||
//
|
||||
// Best if run after function scope store/load and composite operation
|
||||
// eliminations are run. Also best if followed by instruction simplification,
|
||||
// redundancy elimination and DCE.
|
||||
Optimizer::PassToken CreateConvertRelaxedToHalfPass();
|
||||
|
||||
// Create relax float ops pass.
|
||||
// This pass decorates all float32 result instructions with RelaxedPrecision
|
||||
// if not already so decorated.
|
||||
Optimizer::PassToken CreateRelaxFloatOpsPass();
|
||||
|
||||
// Create copy propagate arrays pass.
|
||||
// This pass looks to copy propagate memory references for arrays. It looks
|
||||
// for specific code patterns to recognize array copies.
|
||||
Optimizer::PassToken CreateCopyPropagateArraysPass();
|
||||
|
||||
// Create a vector dce pass.
|
||||
// This pass looks for components of vectors that are unused, and removes them
|
||||
// from the vector. Note this would still leave around lots of dead code that
|
||||
// a pass of ADCE will be able to remove.
|
||||
Optimizer::PassToken CreateVectorDCEPass();
|
||||
|
||||
// Create a pass to reduce the size of loads.
|
||||
// This pass looks for loads of structures where only a few of its members are
|
||||
// used. It replaces the loads feeding an OpExtract with an OpAccessChain and
|
||||
// a load of the specific elements. The parameter is a threshold to determine
|
||||
// whether we have to replace the load or not. If the ratio of the used
|
||||
// components of the load is less than the threshold, we replace the load.
|
||||
Optimizer::PassToken CreateReduceLoadSizePass(
|
||||
double load_replacement_threshold = 0.9);
|
||||
|
||||
// Create a pass to combine chained access chains.
|
||||
// This pass looks for access chains fed by other access chains and combines
|
||||
// them into a single instruction where possible.
|
||||
Optimizer::PassToken CreateCombineAccessChainsPass();
|
||||
|
||||
// Create a pass to upgrade to the VulkanKHR memory model.
|
||||
// This pass upgrades the Logical GLSL450 memory model to Logical VulkanKHR.
|
||||
// Additionally, it modifies memory, image, atomic and barrier operations to
|
||||
// conform to that model's requirements.
|
||||
Optimizer::PassToken CreateUpgradeMemoryModelPass();
|
||||
|
||||
// Create a pass to do code sinking. Code sinking is a transformation
|
||||
// where an instruction is moved into a more deeply nested construct.
|
||||
Optimizer::PassToken CreateCodeSinkingPass();
|
||||
|
||||
// Create a pass to fix incorrect storage classes. In order to make code
|
||||
// generation simpler, DXC may generate code where the storage classes do not
|
||||
// match up correctly. This pass will fix the errors that it can.
|
||||
Optimizer::PassToken CreateFixStorageClassPass();
|
||||
|
||||
// Creates a graphics robust access pass.
|
||||
//
|
||||
// This pass injects code to clamp indexed accesses to buffers and internal
|
||||
// arrays, providing guarantees satisfying Vulkan's robustBufferAccess rules.
|
||||
//
|
||||
// TODO(dneto): Clamps coordinates and sample index for pointer calculations
|
||||
// into storage images (OpImageTexelPointer). For an cube array image, it
|
||||
// assumes the maximum layer count times 6 is at most 0xffffffff.
|
||||
//
|
||||
// NOTE: This pass will fail with a message if:
|
||||
// - The module is not a Shader module.
|
||||
// - The module declares VariablePointers, VariablePointersStorageBuffer, or
|
||||
// RuntimeDescriptorArrayEXT capabilities.
|
||||
// - The module uses an addressing model other than Logical
|
||||
// - Access chain indices are wider than 64 bits.
|
||||
// - Access chain index for a struct is not an OpConstant integer or is out
|
||||
// of range. (The module is already invalid if that is the case.)
|
||||
// - TODO(dneto): The OpImageTexelPointer coordinate component is not 32-bits
|
||||
// wide.
|
||||
//
|
||||
// NOTE: Access chain indices are always treated as signed integers. So
|
||||
// if an array has a fixed size of more than 2^31 elements, then elements
|
||||
// from 2^31 and above are never accessible with a 32-bit index,
|
||||
// signed or unsigned. For this case, this pass will clamp the index
|
||||
// between 0 and at 2^31-1, inclusive.
|
||||
// Similarly, if an array has more then 2^15 element and is accessed with
|
||||
// a 16-bit index, then elements from 2^15 and above are not accessible.
|
||||
// In this case, the pass will clamp the index between 0 and 2^15-1
|
||||
// inclusive.
|
||||
Optimizer::PassToken CreateGraphicsRobustAccessPass();
|
||||
|
||||
// Create a pass to spread Volatile semantics to variables with SMIDNV,
|
||||
// WarpIDNV, SubgroupSize, SubgroupLocalInvocationId, SubgroupEqMask,
|
||||
// SubgroupGeMask, SubgroupGtMask, SubgroupLeMask, or SubgroupLtMask BuiltIn
|
||||
// decorations or OpLoad for them when the shader model is the ray generation,
|
||||
// closest hit, miss, intersection, or callable. This pass can be used for
|
||||
// VUID-StandaloneSpirv-VulkanMemoryModel-04678 and
|
||||
// VUID-StandaloneSpirv-VulkanMemoryModel-04679 (See "Standalone SPIR-V
|
||||
// Validation" section of Vulkan spec "Appendix A: Vulkan Environment for
|
||||
// SPIR-V"). When the SPIR-V version is 1.6 or above, the pass also spreads
|
||||
// the Volatile semantics to a variable with HelperInvocation BuiltIn decoration
|
||||
// in the fragement shader.
|
||||
Optimizer::PassToken CreateSpreadVolatileSemanticsPass();
|
||||
|
||||
// Create a pass to replace a descriptor access using variable index.
|
||||
// This pass replaces every access using a variable index to array variable
|
||||
// |desc| that has a DescriptorSet and Binding decorations with a constant
|
||||
// element of the array. In order to replace the access using a variable index
|
||||
// with the constant element, it uses a switch statement.
|
||||
Optimizer::PassToken CreateReplaceDescArrayAccessUsingVarIndexPass();
|
||||
|
||||
// Create descriptor scalar replacement pass.
|
||||
// This pass replaces every array variable |desc| that has a DescriptorSet and
|
||||
// Binding decorations with a new variable for each element of the
|
||||
// array/composite. Suppose |desc| was bound at binding |b|. Then the variable
|
||||
// corresponding to |desc[i]| will have binding |b+i|. The descriptor set will
|
||||
// be the same. It is assumed that no other variable already has a binding that
|
||||
// will used by one of the new variables. If not, the pass will generate
|
||||
// invalid Spir-V. All accesses to |desc| must be OpAccessChain instructions
|
||||
// with a literal index for the first index. This variant flattens both
|
||||
// composites and arrays.
|
||||
Optimizer::PassToken CreateDescriptorScalarReplacementPass();
|
||||
// This variant flattens only composites.
|
||||
Optimizer::PassToken CreateDescriptorCompositeScalarReplacementPass();
|
||||
// This variant flattens only arrays.
|
||||
Optimizer::PassToken CreateDescriptorArrayScalarReplacementPass();
|
||||
|
||||
// Create a pass to replace each OpKill instruction with a function call to a
|
||||
// function that has a single OpKill. Also replace each OpTerminateInvocation
|
||||
// instruction with a function call to a function that has a single
|
||||
// OpTerminateInvocation. This allows more code to be inlined.
|
||||
Optimizer::PassToken CreateWrapOpKillPass();
|
||||
|
||||
// Replaces the extensions VK_AMD_shader_ballot,VK_AMD_gcn_shader, and
|
||||
// VK_AMD_shader_trinary_minmax with equivalent code using core instructions and
|
||||
// capabilities.
|
||||
Optimizer::PassToken CreateAmdExtToKhrPass();
|
||||
|
||||
// Replaces the internal version of GLSLstd450 InterpolateAt* extended
|
||||
// instructions with the externally valid version. The internal version allows
|
||||
// an OpLoad of the interpolant for the first argument. This pass removes the
|
||||
// OpLoad and replaces it with its pointer. glslang and possibly other
|
||||
// frontends will create the internal version for HLSL. This pass will be part
|
||||
// of HLSL legalization and should be called after interpolants have been
|
||||
// propagated into their final positions.
|
||||
Optimizer::PassToken CreateInterpolateFixupPass();
|
||||
|
||||
// Replace OpExtInst instructions with OpExtInstWithForwardRefsKHR when
|
||||
// the instruction contains a forward reference to another debug instuction.
|
||||
// Replace OpExtInstWithForwardRefsKHR with OpExtInst when there are no forward
|
||||
// reference to another debug instruction.
|
||||
Optimizer::PassToken CreateOpExtInstWithForwardReferenceFixupPass();
|
||||
|
||||
// Removes unused components from composite input variables. Current
|
||||
// implementation just removes trailing unused components from input arrays
|
||||
// and structs. The pass performs best after maximizing dead code removal.
|
||||
// A subsequent dead code elimination pass would be beneficial in removing
|
||||
// newly unused component types.
|
||||
//
|
||||
// WARNING: This pass can only be safely applied standalone to vertex shaders
|
||||
// as it can otherwise cause interface incompatibilities with the preceding
|
||||
// shader in the pipeline. If applied to non-vertex shaders, the user should
|
||||
// follow by applying EliminateDeadOutputStores and
|
||||
// EliminateDeadOutputComponents to the preceding shader.
|
||||
Optimizer::PassToken CreateEliminateDeadInputComponentsPass();
|
||||
|
||||
// Removes unused components from composite output variables. Current
|
||||
// implementation just removes trailing unused components from output arrays
|
||||
// and structs. The pass performs best after eliminating dead output stores.
|
||||
// A subsequent dead code elimination pass would be beneficial in removing
|
||||
// newly unused component types. Currently only supports vertex and fragment
|
||||
// shaders.
|
||||
//
|
||||
// WARNING: This pass cannot be safely applied standalone as it can cause
|
||||
// interface incompatibility with the following shader in the pipeline. The
|
||||
// user should first apply EliminateDeadInputComponents to the following
|
||||
// shader, then apply EliminateDeadOutputStores to this shader.
|
||||
Optimizer::PassToken CreateEliminateDeadOutputComponentsPass();
|
||||
|
||||
// Removes unused components from composite input variables. This safe
|
||||
// version will not cause interface incompatibilities since it only changes
|
||||
// vertex shaders. The current implementation just removes trailing unused
|
||||
// components from input structs and input arrays. The pass performs best
|
||||
// after maximizing dead code removal. A subsequent dead code elimination
|
||||
// pass would be beneficial in removing newly unused component types.
|
||||
Optimizer::PassToken CreateEliminateDeadInputComponentsSafePass();
|
||||
|
||||
// Analyzes shader and populates |live_locs| and |live_builtins|. Best results
|
||||
// will be obtained if shader has all dead code eliminated first. |live_locs|
|
||||
// and |live_builtins| are subsequently used when calling
|
||||
// CreateEliminateDeadOutputStoresPass on the preceding shader. Currently only
|
||||
// supports tesc, tese, geom, and frag shaders.
|
||||
Optimizer::PassToken CreateAnalyzeLiveInputPass(
|
||||
std::unordered_set<uint32_t>* live_locs,
|
||||
std::unordered_set<uint32_t>* live_builtins);
|
||||
|
||||
// Removes stores to output locations not listed in |live_locs| or
|
||||
// |live_builtins|. Best results are obtained if constant propagation is
|
||||
// performed first. A subsequent call to ADCE will eliminate any dead code
|
||||
// created by the removal of the stores. A subsequent call to
|
||||
// CreateEliminateDeadOutputComponentsPass will eliminate any dead output
|
||||
// components created by the elimination of the stores. Currently only supports
|
||||
// vert, tesc, tese, and geom shaders.
|
||||
Optimizer::PassToken CreateEliminateDeadOutputStoresPass(
|
||||
std::unordered_set<uint32_t>* live_locs,
|
||||
std::unordered_set<uint32_t>* live_builtins);
|
||||
|
||||
// Creates a convert-to-sampled-image pass to convert images and/or
|
||||
// samplers with given pairs of descriptor set and binding to sampled image.
|
||||
// If a pair of an image and a sampler have the same pair of descriptor set and
|
||||
// binding that is one of the given pairs, they will be converted to a sampled
|
||||
// image. In addition, if only an image has the descriptor set and binding that
|
||||
// is one of the given pairs, it will be converted to a sampled image as well.
|
||||
Optimizer::PassToken CreateConvertToSampledImagePass(
|
||||
const std::vector<opt::DescriptorSetAndBinding>&
|
||||
descriptor_set_binding_pairs);
|
||||
|
||||
// Create an interface-variable-scalar-replacement pass that replaces array or
|
||||
// matrix interface variables with a series of scalar or vector interface
|
||||
// variables. For example, it replaces `float3 foo[2]` with `float3 foo0, foo1`.
|
||||
Optimizer::PassToken CreateInterfaceVariableScalarReplacementPass();
|
||||
|
||||
// Creates a remove-dont-inline pass to remove the |DontInline| function control
|
||||
// from every function in the module. This is useful if you want the inliner to
|
||||
// inline these functions some reason.
|
||||
Optimizer::PassToken CreateRemoveDontInlinePass();
|
||||
// Create a fix-func-call-param pass to fix non memory argument for the function
|
||||
// call, as spirv-validation requires function parameters to be an memory
|
||||
// object, currently the pass would remove accesschain pointer argument passed
|
||||
// to the function
|
||||
Optimizer::PassToken CreateFixFuncCallArgumentsPass();
|
||||
|
||||
// Creates a trim-capabilities pass.
|
||||
// This pass removes unused capabilities for a given module, and if possible,
|
||||
// associated extensions.
|
||||
// See `trim_capabilities.h` for the list of supported capabilities.
|
||||
//
|
||||
// If the module contains unsupported capabilities, this pass will ignore them.
|
||||
// This should be fine in most cases, but could yield to incorrect results if
|
||||
// the unknown capability interacts with one of the trimmed capabilities.
|
||||
Optimizer::PassToken CreateTrimCapabilitiesPass();
|
||||
|
||||
// Creates a struct-packing pass.
|
||||
// This pass re-assigns all offset layout decorators to tightly pack
|
||||
// the struct with OpName matching `structToPack` according to the given packing
|
||||
// rule. Accepted packing rules are: std140, std140EnhancedLayout, std430,
|
||||
// std430EnhancedLayout, hlslCbuffer, hlslCbufferPackOffset, scalar,
|
||||
// scalarEnhancedLayout.
|
||||
Optimizer::PassToken CreateStructPackingPass(const char* structToPack,
|
||||
const char* packingRule);
|
||||
|
||||
// Creates a switch-descriptorset pass.
|
||||
// This pass changes any DescriptorSet decorations with the value |ds_from| to
|
||||
// use the new value |ds_to|.
|
||||
Optimizer::PassToken CreateSwitchDescriptorSetPass(uint32_t ds_from,
|
||||
uint32_t ds_to);
|
||||
|
||||
// Creates an invocation interlock placement pass.
|
||||
// This pass ensures that an entry point will have at most one
|
||||
// OpBeginInterlockInvocationEXT and one OpEndInterlockInvocationEXT, in that
|
||||
// order.
|
||||
Optimizer::PassToken CreateInvocationInterlockPlacementPass();
|
||||
|
||||
// Creates a pass to add/remove maximal reconvergence execution mode.
|
||||
// This pass either adds or removes maximal reconvergence from all entry points.
|
||||
Optimizer::PassToken CreateModifyMaximalReconvergencePass(bool add);
|
||||
} // namespace spvtools
|
||||
|
||||
#endif // INCLUDE_SPIRV_TOOLS_OPTIMIZER_HPP_
|
||||
@@ -194,7 +194,7 @@ public:
|
||||
}
|
||||
|
||||
~LinearAllocatorWithFallback() noexcept {
|
||||
LinearAllocatorWithFallback::reset();
|
||||
reset();
|
||||
}
|
||||
|
||||
void* alloc(size_t size, size_t alignment = alignof(std::max_align_t));
|
||||
@@ -204,7 +204,7 @@ public:
|
||||
}
|
||||
|
||||
void rewind(void* p) noexcept {
|
||||
if (p >= LinearAllocator::base() && p < LinearAllocator::end()) {
|
||||
if (p >= base() && p < end()) {
|
||||
LinearAllocator::rewind(p);
|
||||
}
|
||||
}
|
||||
@@ -214,7 +214,7 @@ public:
|
||||
void free(void*, size_t) noexcept { }
|
||||
|
||||
bool isHeapAllocation(void* p) const noexcept {
|
||||
return p < LinearAllocator::base() || p >= LinearAllocator::end();
|
||||
return p < base() || p >= end();
|
||||
}
|
||||
};
|
||||
|
||||
@@ -240,7 +240,6 @@ public:
|
||||
void push(void* p) noexcept {
|
||||
assert_invariant(p);
|
||||
assert_invariant(p >= mBegin && p < mEnd);
|
||||
// TODO: assert this is one of our pointer (i.e.: it's address match one of ours)
|
||||
Node* const head = static_cast<Node*>(p);
|
||||
head->next = mHead;
|
||||
mHead = head;
|
||||
@@ -278,18 +277,23 @@ public:
|
||||
void* pop() noexcept {
|
||||
Node* const pStorage = mStorage;
|
||||
|
||||
HeadPtr currentHead = mHead.load();
|
||||
HeadPtr currentHead = mHead.load(std::memory_order_relaxed);
|
||||
while (currentHead.offset >= 0) {
|
||||
// The value of "pNext" we load here might already contain application data if another
|
||||
// thread raced ahead of us. But in that case, the computed "newHead" will be discarded
|
||||
// since compare_exchange_weak fails. Then this thread will loop with the updated
|
||||
// since compare_exchange_weak() fails. Then this thread will loop with the updated
|
||||
// value of currentHead, and try again.
|
||||
Node* const pNext = pStorage[currentHead.offset].next.load(std::memory_order_relaxed);
|
||||
// TSAN complains if we don't use a local variable here.
|
||||
Node const node = pStorage[currentHead.offset];
|
||||
Node const* const pNext = node.next;
|
||||
const HeadPtr newHead{ pNext ? int32_t(pNext - pStorage) : -1, currentHead.tag + 1 };
|
||||
// In the rare case that the other thread that raced ahead of us already returned the
|
||||
// same mHead we just loaded, but it now has a different "next" value, the tag field will not
|
||||
// match, and compare_exchange_weak will fail and prevent that particular race condition.
|
||||
if (mHead.compare_exchange_weak(currentHead, newHead)) {
|
||||
// In the rare case that the other thread that raced ahead of us already returned the
|
||||
// same mHead we just loaded, but it now has a different "next" value, the tag field
|
||||
// will not match, and compare_exchange_weak() will fail and prevent that particular
|
||||
// race condition.
|
||||
// acquire: no read/write can be reordered before this
|
||||
if (mHead.compare_exchange_weak(currentHead, newHead,
|
||||
std::memory_order_acquire, std::memory_order_relaxed)) {
|
||||
// This assert needs to occur after we have validated that there was no race condition
|
||||
// Otherwise, next might already contain application data, if another thread
|
||||
// raced ahead of us after we loaded mHead, but before we loaded mHead->next.
|
||||
@@ -306,13 +310,15 @@ public:
|
||||
Node* const storage = mStorage;
|
||||
assert_invariant(p && p >= storage);
|
||||
Node* const node = static_cast<Node*>(p);
|
||||
HeadPtr currentHead = mHead.load();
|
||||
HeadPtr currentHead = mHead.load(std::memory_order_relaxed);
|
||||
HeadPtr newHead = { int32_t(node - storage), currentHead.tag + 1 };
|
||||
do {
|
||||
newHead.tag = currentHead.tag + 1;
|
||||
Node* const n = (currentHead.offset >= 0) ? (storage + currentHead.offset) : nullptr;
|
||||
node->next.store(n, std::memory_order_relaxed);
|
||||
} while(!mHead.compare_exchange_weak(currentHead, newHead));
|
||||
Node* const pNext = (currentHead.offset >= 0) ? (storage + currentHead.offset) : nullptr;
|
||||
node->next = pNext; // could be a race with pop, corrected by CAS
|
||||
} while(!mHead.compare_exchange_weak(currentHead, newHead,
|
||||
std::memory_order_release, std::memory_order_relaxed));
|
||||
// release: no read/write can be reordered after this
|
||||
}
|
||||
|
||||
void* getFirst() noexcept {
|
||||
@@ -320,10 +326,7 @@ public:
|
||||
}
|
||||
|
||||
struct Node {
|
||||
// This should be a regular (non-atomic) pointer, but this causes TSAN to complain
|
||||
// about a data-race that exists but is benin. We always use this atomic<> in
|
||||
// relaxed mode.
|
||||
// The data race TSAN complains about is when a pop() is interrupted by a
|
||||
// There is a benign data race when a pop() is interrupted by a
|
||||
// pop() + push() just after mHead->next is read -- it appears as though it is written
|
||||
// without synchronization (by the push), however in that case, the pop's CAS will fail
|
||||
// and things will auto-correct.
|
||||
@@ -346,7 +349,7 @@ public:
|
||||
// |
|
||||
// CAS, tag++
|
||||
//
|
||||
std::atomic<Node*> next;
|
||||
Node* next = nullptr;
|
||||
};
|
||||
|
||||
private:
|
||||
@@ -714,13 +717,13 @@ public:
|
||||
// trivially destructible, since free() won't call the destructor and this is allocating
|
||||
// an array.
|
||||
template <typename T,
|
||||
typename = typename std::enable_if<std::is_trivially_destructible<T>::value>::type>
|
||||
typename = std::enable_if_t<std::is_trivially_destructible_v<T>>>
|
||||
T* alloc(size_t count, size_t alignment, size_t extra) noexcept {
|
||||
return (T*)alloc(count * sizeof(T), alignment, extra);
|
||||
}
|
||||
|
||||
template <typename T,
|
||||
typename = typename std::enable_if<std::is_trivially_destructible<T>::value>::type>
|
||||
typename = std::enable_if_t<std::is_trivially_destructible_v<T>>>
|
||||
T* alloc(size_t count, size_t alignment = alignof(T)) noexcept {
|
||||
return (T*)alloc(count * sizeof(T), alignment);
|
||||
}
|
||||
@@ -876,7 +879,7 @@ public:
|
||||
template<typename T, size_t ALIGN = alignof(T), typename... ARGS>
|
||||
T* make(ARGS&& ... args) noexcept {
|
||||
T* o = nullptr;
|
||||
if (std::is_trivially_destructible<T>::value) {
|
||||
if (std::is_trivially_destructible_v<T>) {
|
||||
o = mArena.template make<T, ALIGN>(std::forward<ARGS>(args)...);
|
||||
} else {
|
||||
void* const p = (Finalizer*)mArena.alloc(sizeof(T), ALIGN, sizeof(Finalizer));
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
/*
|
||||
* Copyright (C) 2018 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#ifndef TNT_UTILS_BINARYTREEARRAY_H
|
||||
#define TNT_UTILS_BINARYTREEARRAY_H
|
||||
|
||||
#include <utils/compiler.h>
|
||||
|
||||
#include <type_traits>
|
||||
|
||||
#include <assert.h>
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
namespace utils {
|
||||
|
||||
class BinaryTreeArray {
|
||||
|
||||
// Simple fixed capacity stack
|
||||
template<typename TYPE, size_t CAPACITY,
|
||||
typename = std::enable_if_t<std::is_trivial_v<TYPE>>>
|
||||
class stack {
|
||||
TYPE mElements[CAPACITY];
|
||||
size_t mSize = 0;
|
||||
public:
|
||||
bool empty() const noexcept { return mSize == 0; }
|
||||
void push(TYPE const& v) noexcept {
|
||||
assert(mSize < CAPACITY);
|
||||
mElements[mSize++] = v;
|
||||
}
|
||||
void pop() noexcept {
|
||||
assert(mSize > 0);
|
||||
--mSize;
|
||||
}
|
||||
const TYPE& back() const noexcept {
|
||||
return mElements[mSize - 1];
|
||||
}
|
||||
};
|
||||
|
||||
public:
|
||||
static size_t count(size_t height) noexcept { return (1u << height) - 1; }
|
||||
static size_t left(size_t i, size_t /*height*/) noexcept { return i + 1; }
|
||||
static size_t right(size_t i, size_t height) noexcept {
|
||||
return i + (size_t(1) << (height - 1));
|
||||
}
|
||||
|
||||
// this builds the depth-first binary tree array top down (post-order)
|
||||
template<typename Leaf, typename Node>
|
||||
static void traverse(size_t height, Leaf leaf, Node node) noexcept {
|
||||
|
||||
struct TNode {
|
||||
uint32_t index;
|
||||
uint32_t col;
|
||||
uint32_t height;
|
||||
uint32_t next;
|
||||
|
||||
bool isLeaf() const noexcept { return height == 1; }
|
||||
size_t left() const noexcept { return BinaryTreeArray::left(index, height); }
|
||||
size_t right() const noexcept { return BinaryTreeArray::right(index, height); }
|
||||
};
|
||||
|
||||
stack<TNode, 16> stack;
|
||||
stack.push(TNode{ 0, 0, (uint32_t)height, (uint32_t)count(height) });
|
||||
|
||||
uint32_t prevLeft = 0;
|
||||
uint32_t prevRight = 0;
|
||||
uint32_t prevIndex = 0;
|
||||
while (!stack.empty()) {
|
||||
TNode const* const UTILS_RESTRICT curr = &stack.back();
|
||||
const bool isLeaf = curr->isLeaf();
|
||||
const uint32_t index = curr->index;
|
||||
const uint32_t l = (uint32_t)curr->left();
|
||||
const uint32_t r = (uint32_t)curr->right();
|
||||
|
||||
if (prevLeft == index || prevRight == index) {
|
||||
if (!isLeaf) {
|
||||
// the 'next' node of our left node's right descendants is our right child
|
||||
stack.push({ l, 2 * curr->col, curr->height - 1, r });
|
||||
}
|
||||
} else if (l == prevIndex) {
|
||||
if (!isLeaf) {
|
||||
// the 'next' node of our right child is our own 'next' sibling
|
||||
stack.push({ r, 2 * curr->col + 1, curr->height - 1, curr->next });
|
||||
}
|
||||
} else {
|
||||
if (!isLeaf) {
|
||||
node(index, l, r, curr->next);
|
||||
} else {
|
||||
leaf(index, curr->col, curr->next);
|
||||
}
|
||||
stack.pop();
|
||||
}
|
||||
|
||||
prevLeft = l;
|
||||
prevRight = r;
|
||||
prevIndex = index;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace utils
|
||||
|
||||
#endif //TNT_UTILS_BINARYTREEARRAY_H
|
||||
@@ -41,32 +41,32 @@ size_t count();
|
||||
// ------------------------------------------------------------------------------------------------
|
||||
|
||||
template<typename Enum, typename std::enable_if_t<
|
||||
std::is_enum<Enum>::value && utils::EnableIntegerOperators<Enum>::value, int> = 0>
|
||||
std::is_enum_v<Enum> && utils::EnableIntegerOperators<Enum>::value, int> = 0>
|
||||
inline constexpr int operator+(Enum value) noexcept {
|
||||
return int(value);
|
||||
}
|
||||
|
||||
template<typename Enum, typename std::enable_if_t<
|
||||
std::is_enum<Enum>::value && utils::EnableIntegerOperators<Enum>::value, int> = 0>
|
||||
std::is_enum_v<Enum> && utils::EnableIntegerOperators<Enum>::value, int> = 0>
|
||||
inline constexpr bool operator==(Enum lhs, size_t rhs) noexcept {
|
||||
using underlying_t = std::underlying_type_t<Enum>;
|
||||
return underlying_t(lhs) == rhs;
|
||||
}
|
||||
|
||||
template<typename Enum, typename std::enable_if_t<
|
||||
std::is_enum<Enum>::value && utils::EnableIntegerOperators<Enum>::value, int> = 0>
|
||||
std::is_enum_v<Enum> && utils::EnableIntegerOperators<Enum>::value, int> = 0>
|
||||
inline constexpr bool operator==(size_t lhs, Enum rhs) noexcept {
|
||||
return rhs == lhs;
|
||||
}
|
||||
|
||||
template<typename Enum, typename std::enable_if_t<
|
||||
std::is_enum<Enum>::value && utils::EnableIntegerOperators<Enum>::value, int> = 0>
|
||||
std::is_enum_v<Enum> && utils::EnableIntegerOperators<Enum>::value, int> = 0>
|
||||
inline constexpr bool operator!=(Enum lhs, size_t rhs) noexcept {
|
||||
return !(rhs == lhs);
|
||||
}
|
||||
|
||||
template<typename Enum, typename std::enable_if_t<
|
||||
std::is_enum<Enum>::value && utils::EnableIntegerOperators<Enum>::value, int> = 0>
|
||||
std::is_enum_v<Enum> && utils::EnableIntegerOperators<Enum>::value, int> = 0>
|
||||
inline constexpr bool operator!=(size_t lhs, Enum rhs) noexcept {
|
||||
return rhs != lhs;
|
||||
}
|
||||
@@ -74,66 +74,66 @@ inline constexpr bool operator!=(size_t lhs, Enum rhs) noexcept {
|
||||
// ------------------------------------------------------------------------------------------------
|
||||
|
||||
template<typename Enum, typename std::enable_if_t<
|
||||
std::is_enum<Enum>::value && utils::EnableBitMaskOperators<Enum>::value, int> = 0>
|
||||
std::is_enum_v<Enum> && utils::EnableBitMaskOperators<Enum>::value, int> = 0>
|
||||
inline constexpr bool operator!(Enum rhs) noexcept {
|
||||
using underlying = std::underlying_type_t<Enum>;
|
||||
return underlying(rhs) == 0;
|
||||
}
|
||||
|
||||
template<typename Enum, typename std::enable_if_t<
|
||||
std::is_enum<Enum>::value && utils::EnableBitMaskOperators<Enum>::value, int> = 0>
|
||||
std::is_enum_v<Enum> && utils::EnableBitMaskOperators<Enum>::value, int> = 0>
|
||||
inline constexpr Enum operator~(Enum rhs) noexcept {
|
||||
using underlying = std::underlying_type_t<Enum>;
|
||||
return Enum(~underlying(rhs));
|
||||
}
|
||||
|
||||
template<typename Enum, typename std::enable_if_t<
|
||||
std::is_enum<Enum>::value && utils::EnableBitMaskOperators<Enum>::value, int> = 0>
|
||||
std::is_enum_v<Enum> && utils::EnableBitMaskOperators<Enum>::value, int> = 0>
|
||||
inline constexpr Enum operator|(Enum lhs, Enum rhs) noexcept {
|
||||
using underlying = std::underlying_type_t<Enum>;
|
||||
return Enum(underlying(lhs) | underlying(rhs));
|
||||
}
|
||||
|
||||
template<typename Enum, typename std::enable_if_t<
|
||||
std::is_enum<Enum>::value && utils::EnableBitMaskOperators<Enum>::value, int> = 0>
|
||||
std::is_enum_v<Enum> && utils::EnableBitMaskOperators<Enum>::value, int> = 0>
|
||||
inline constexpr Enum operator&(Enum lhs, Enum rhs) noexcept {
|
||||
using underlying = std::underlying_type_t<Enum>;
|
||||
return Enum(underlying(lhs) & underlying(rhs));
|
||||
}
|
||||
|
||||
template<typename Enum, typename std::enable_if_t<
|
||||
std::is_enum<Enum>::value && utils::EnableBitMaskOperators<Enum>::value, int> = 0>
|
||||
std::is_enum_v<Enum> && utils::EnableBitMaskOperators<Enum>::value, int> = 0>
|
||||
inline constexpr Enum operator^(Enum lhs, Enum rhs) noexcept {
|
||||
using underlying = std::underlying_type_t<Enum>;
|
||||
return Enum(underlying(lhs) ^ underlying(rhs));
|
||||
}
|
||||
|
||||
template<typename Enum, typename std::enable_if_t<
|
||||
std::is_enum<Enum>::value && utils::EnableBitMaskOperators<Enum>::value, int> = 0>
|
||||
std::is_enum_v<Enum> && utils::EnableBitMaskOperators<Enum>::value, int> = 0>
|
||||
inline constexpr Enum operator|=(Enum& lhs, Enum rhs) noexcept {
|
||||
return lhs = lhs | rhs;
|
||||
}
|
||||
|
||||
template<typename Enum, typename std::enable_if_t<
|
||||
std::is_enum<Enum>::value && utils::EnableBitMaskOperators<Enum>::value, int> = 0>
|
||||
std::is_enum_v<Enum> && utils::EnableBitMaskOperators<Enum>::value, int> = 0>
|
||||
inline constexpr Enum operator&=(Enum& lhs, Enum rhs) noexcept {
|
||||
return lhs = lhs & rhs;
|
||||
}
|
||||
|
||||
template<typename Enum, typename std::enable_if_t<
|
||||
std::is_enum<Enum>::value && utils::EnableBitMaskOperators<Enum>::value, int> = 0>
|
||||
std::is_enum_v<Enum> && utils::EnableBitMaskOperators<Enum>::value, int> = 0>
|
||||
inline constexpr Enum operator^=(Enum& lhs, Enum rhs) noexcept {
|
||||
return lhs = lhs ^ rhs;
|
||||
}
|
||||
|
||||
template<typename Enum, typename std::enable_if_t<
|
||||
std::is_enum<Enum>::value && utils::EnableBitMaskOperators<Enum>::value, int> = 0>
|
||||
std::is_enum_v<Enum> && utils::EnableBitMaskOperators<Enum>::value, int> = 0>
|
||||
inline constexpr bool none(Enum lhs) noexcept {
|
||||
return !lhs;
|
||||
}
|
||||
|
||||
template<typename Enum, typename std::enable_if_t<
|
||||
std::is_enum<Enum>::value && utils::EnableBitMaskOperators<Enum>::value, int> = 0>
|
||||
std::is_enum_v<Enum> && utils::EnableBitMaskOperators<Enum>::value, int> = 0>
|
||||
inline constexpr bool any(Enum lhs) noexcept {
|
||||
return !none(lhs);
|
||||
}
|
||||
|
||||
@@ -20,6 +20,7 @@
|
||||
// NOTE: this header should not include STL headers
|
||||
|
||||
#include <utils/compiler.h>
|
||||
#include <utils/ostream.h>
|
||||
|
||||
#include <assert.h>
|
||||
#include <stddef.h>
|
||||
@@ -181,6 +182,10 @@ public:
|
||||
};
|
||||
|
||||
private:
|
||||
#if !defined(NDEBUG)
|
||||
friend io::ostream& operator<<(io::ostream& out, const CString& rhs);
|
||||
#endif
|
||||
|
||||
struct Data {
|
||||
size_type length;
|
||||
};
|
||||
|
||||
@@ -68,10 +68,10 @@ public:
|
||||
intptr_t operator [](size_t index) const;
|
||||
|
||||
/** Demangles a C++ type name */
|
||||
static utils::CString demangleTypeName(const char* mangled);
|
||||
static CString demangleTypeName(const char* mangled);
|
||||
|
||||
template<typename T>
|
||||
static utils::CString typeName() {
|
||||
static CString typeName() {
|
||||
#if UTILS_HAS_RTTI
|
||||
return demangleTypeName(typeid(T).name());
|
||||
#else
|
||||
@@ -84,7 +84,7 @@ public:
|
||||
* This will print, when possible, the demangled names of functions corresponding to the
|
||||
* program-counter recorded.
|
||||
*/
|
||||
friend utils::io::ostream& operator <<(utils::io::ostream& stream, const CallStack& callstack);
|
||||
friend io::ostream& operator <<(io::ostream& stream, const CallStack& callstack);
|
||||
|
||||
bool operator <(const CallStack& rhs) const;
|
||||
|
||||
@@ -111,7 +111,7 @@ public:
|
||||
private:
|
||||
void update_gcc(size_t ignore) noexcept;
|
||||
|
||||
static utils::CString demangle(const char* mangled);
|
||||
static CString demangle(const char* mangled);
|
||||
|
||||
static constexpr size_t NUM_FRAMES = 20;
|
||||
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
/*
|
||||
* Copyright (C) 2016 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#ifndef TNT_UTILS_CONDITION_H
|
||||
#define TNT_UTILS_CONDITION_H
|
||||
|
||||
#if defined(__ANDROID__)
|
||||
#include <utils/linux/Condition.h>
|
||||
#else
|
||||
#include <utils/generic/Condition.h>
|
||||
#endif
|
||||
|
||||
#endif // TNT_UTILS_CONDITION_H
|
||||
@@ -0,0 +1,92 @@
|
||||
/*
|
||||
* Copyright (C) 2015 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#ifndef TNT_UTILS_COUNTDOWNLATCH_H
|
||||
#define TNT_UTILS_COUNTDOWNLATCH_H
|
||||
|
||||
// note: we use our version of mutex/condition to keep this public header STL free
|
||||
#include <utils/Condition.h>
|
||||
#include <utils/Mutex.h>
|
||||
|
||||
#include <stdint.h>
|
||||
#include <stddef.h>
|
||||
|
||||
namespace utils {
|
||||
|
||||
/**
|
||||
* A count down latch is used to block one or several threads until the latch is signaled
|
||||
* a certain number of times.
|
||||
*
|
||||
* Threads entering the latch are blocked until the latch is signaled enough times.
|
||||
*
|
||||
* @see CyclicBarrier
|
||||
*/
|
||||
class CountDownLatch {
|
||||
public:
|
||||
/**
|
||||
* Creates a count down latch with a specified count. The minimum useful value is 1.
|
||||
* @param count the latch counter initial value
|
||||
*/
|
||||
explicit CountDownLatch(size_t count) noexcept;
|
||||
~CountDownLatch() = default;
|
||||
|
||||
/**
|
||||
* Blocks until latch() is called \p count times.
|
||||
* @see CountDownLatch(size_t count)
|
||||
*/
|
||||
void await() noexcept;
|
||||
|
||||
/**
|
||||
* Releases threads blocked in await() when called \p count times. Calling latch() more than
|
||||
* \p count times has no effect.
|
||||
* @see reset()
|
||||
*/
|
||||
void latch() noexcept;
|
||||
|
||||
/**
|
||||
* Resets the count-down latch to the given value.
|
||||
*
|
||||
* @param new_count New latch count. A value of zero will immediately unblock all waiting
|
||||
* threads.
|
||||
*
|
||||
* @warning Use with caution. It's only safe to reset the latch count when you're sure
|
||||
* that no threads are waiting in await(). This can be guaranteed in various ways, for
|
||||
* instance, if you have a single thread calling await(), you could call reset() from that
|
||||
* thread, or you could use a CyclicBarrier to make sure all threads using the CountDownLatch
|
||||
* are at a known place (i.e.: not in await()) when reset() is called.
|
||||
*/
|
||||
void reset(size_t new_count) noexcept;
|
||||
|
||||
/**
|
||||
* @return the number of times latch() has been called since construction or reset.
|
||||
* @see reset(), CountDownLatch(size_t count)
|
||||
*/
|
||||
size_t getCount() const noexcept;
|
||||
|
||||
CountDownLatch() = delete;
|
||||
CountDownLatch(const CountDownLatch&) = delete;
|
||||
CountDownLatch& operator=(const CountDownLatch&) = delete;
|
||||
|
||||
private:
|
||||
uint32_t m_initial_count;
|
||||
uint32_t m_remaining_count;
|
||||
mutable Mutex m_lock;
|
||||
mutable Condition m_cv;
|
||||
};
|
||||
|
||||
} // namespace utils
|
||||
|
||||
#endif // TNT_UTILS_COUNTDOWNLATCH_H
|
||||
@@ -0,0 +1,84 @@
|
||||
/*
|
||||
* Copyright (C) 2015 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#ifndef TNT_UTILS_CYCLIC_BARRIER_H
|
||||
#define TNT_UTILS_CYCLIC_BARRIER_H
|
||||
|
||||
#include <stddef.h>
|
||||
|
||||
// note: we use our version of mutex/condition to keep this public header STL free
|
||||
#include <utils/Condition.h>
|
||||
#include <utils/Mutex.h>
|
||||
|
||||
namespace utils {
|
||||
|
||||
/**
|
||||
* A cyclic barrier is used to synchronize several threads to a particular execution point.
|
||||
*
|
||||
* Threads entering the barrier are halted until all threads reach the barrier.
|
||||
*
|
||||
* @see CountDownLatch
|
||||
*/
|
||||
class CyclicBarrier {
|
||||
public:
|
||||
/**
|
||||
* Creates a cyclic barrier with a specified number of threads to synchronize. The minimum
|
||||
* useful value is 2. A value of 0 is invalid and is silently changed to 1.
|
||||
* @param num_threads Number of threads to synchronize.
|
||||
*/
|
||||
explicit CyclicBarrier(size_t num_threads) noexcept;
|
||||
|
||||
/**
|
||||
* @return The number of thread that are synchronized.
|
||||
*/
|
||||
size_t getThreadCount() const noexcept;
|
||||
|
||||
/**
|
||||
* @return Number of threads currently waiting on the barrier.
|
||||
*/
|
||||
size_t getWaitingThreadCount() const noexcept;
|
||||
|
||||
/**
|
||||
* Blocks until getThreadCount()-1 other threads reach await().
|
||||
*/
|
||||
void await() noexcept;
|
||||
|
||||
/**
|
||||
* Resets the cyclic barrier to its original state and releases all waiting threads.
|
||||
*/
|
||||
void reset() noexcept;
|
||||
|
||||
CyclicBarrier() = delete;
|
||||
CyclicBarrier(const CyclicBarrier&) = delete;
|
||||
CyclicBarrier& operator=(const CyclicBarrier&) = delete;
|
||||
|
||||
private:
|
||||
enum class State {
|
||||
TRAP, RELEASE
|
||||
};
|
||||
|
||||
const size_t m_num_threads;
|
||||
mutable Mutex m_lock;
|
||||
mutable Condition m_cv;
|
||||
|
||||
State m_state = State::TRAP;
|
||||
size_t m_trapped_threads = 0;
|
||||
size_t m_released_threads = 0;
|
||||
};
|
||||
|
||||
} // namespace utils
|
||||
|
||||
#endif // TNT_UTILS_CYCLIC_BARRIER_H
|
||||
@@ -84,7 +84,7 @@ public:
|
||||
FixedCapacityVector() = default;
|
||||
|
||||
explicit FixedCapacityVector(const allocator_type& allocator) noexcept
|
||||
: mCapacityAllocator({}, allocator) {
|
||||
: mCapacityAllocator(0, allocator) {
|
||||
}
|
||||
|
||||
explicit FixedCapacityVector(size_type size, const allocator_type& allocator = allocator_type())
|
||||
@@ -299,6 +299,16 @@ public:
|
||||
}
|
||||
}
|
||||
|
||||
UTILS_NOINLINE
|
||||
void shrink_to_fit() {
|
||||
if (size() < capacity()) {
|
||||
FixedCapacityVector t(construct_with_capacity, size(), allocator());
|
||||
t.mSize = size();
|
||||
std::uninitialized_move(begin(), end(), t.begin());
|
||||
this->swap(t);
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
enum construct_with_capacity_tag{ construct_with_capacity };
|
||||
|
||||
@@ -318,9 +328,9 @@ private:
|
||||
|
||||
iterator assertCapacityForSize(size_type s) {
|
||||
if constexpr(CapacityCheck || FILAMENT_FORCE_CAPACITY_CHECK) {
|
||||
ASSERT_PRECONDITION(capacity() >= s,
|
||||
"capacity exceeded: requested size %lu, available capacity %lu.",
|
||||
(unsigned long)s, (unsigned long)capacity());
|
||||
FILAMENT_CHECK_PRECONDITION(capacity() >= s)
|
||||
<< "capacity exceeded: requested size " << (unsigned long)s
|
||||
<< "u, available capacity " << (unsigned long)capacity() << "u.";
|
||||
}
|
||||
return end();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
/*
|
||||
* Copyright (C) 2023 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*
|
||||
*/
|
||||
|
||||
#ifndef TNT_UTILS_FIXEDCIRCULARBUFFER_H
|
||||
#define TNT_UTILS_FIXEDCIRCULARBUFFER_H
|
||||
|
||||
#include <utils/debug.h>
|
||||
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <type_traits>
|
||||
|
||||
#include <stddef.h>
|
||||
|
||||
namespace utils {
|
||||
|
||||
template<typename T>
|
||||
class FixedCircularBuffer {
|
||||
public:
|
||||
explicit FixedCircularBuffer(size_t capacity)
|
||||
: mData(std::make_unique<T[]>(capacity)), mCapacity(capacity) {}
|
||||
|
||||
size_t size() const noexcept { return mSize; }
|
||||
size_t capacity() const noexcept { return mCapacity; }
|
||||
bool full() const noexcept { return mCapacity > 0 && mSize == mCapacity; }
|
||||
bool empty() const noexcept { return mSize == 0; }
|
||||
|
||||
/**
|
||||
* Push v into the buffer. If the buffer is already full, removes the oldest item and returns
|
||||
* it. If this buffer has no capacity, simply returns v.
|
||||
* @param v the new value to push into the buffer
|
||||
* @return if the buffer was full, the oldest value which was displaced
|
||||
*/
|
||||
std::optional<T> push(T v) noexcept {
|
||||
if (mCapacity == 0) {
|
||||
return v;
|
||||
}
|
||||
std::optional<T> displaced = full() ? pop() : std::optional<T>{};
|
||||
mData[mEnd] = v;
|
||||
mEnd = (mEnd + 1) % mCapacity;
|
||||
mSize++;
|
||||
return displaced;
|
||||
}
|
||||
|
||||
T pop() noexcept {
|
||||
assert_invariant(mSize > 0);
|
||||
T result = mData[mBegin];
|
||||
mBegin = (mBegin + 1) % mCapacity;
|
||||
mSize--;
|
||||
return result;
|
||||
}
|
||||
|
||||
private:
|
||||
std::unique_ptr<T[]> mData;
|
||||
|
||||
size_t mBegin = 0;
|
||||
size_t mEnd = 0;
|
||||
size_t mSize = 0;
|
||||
size_t mCapacity;
|
||||
};
|
||||
|
||||
} // namespace utils
|
||||
|
||||
#endif // TNT_UTILS_FIXEDCIRCULARBUFFER_H
|
||||
@@ -0,0 +1,110 @@
|
||||
/*
|
||||
* Copyright (C) 2018 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#ifndef TNT_UTILS_HASH_H
|
||||
#define TNT_UTILS_HASH_H
|
||||
|
||||
#include <functional> // for std::hash
|
||||
#include <string_view>
|
||||
#include <utility>
|
||||
|
||||
#include <stdint.h>
|
||||
#include <stddef.h>
|
||||
|
||||
namespace utils::hash {
|
||||
|
||||
inline size_t combine(size_t lhs, size_t rhs) noexcept {
|
||||
std::pair<size_t, size_t> const p{ lhs, rhs };
|
||||
return std::hash<std::string_view>{}({ (char*)&p, sizeof(p) });
|
||||
}
|
||||
|
||||
// Hash function that takes an arbitrary swath of word-aligned data.
|
||||
inline uint32_t murmur3(const uint32_t* key, size_t wordCount, uint32_t seed) noexcept {
|
||||
uint32_t h = seed;
|
||||
size_t i = wordCount;
|
||||
do {
|
||||
uint32_t k = *key++;
|
||||
k *= 0xcc9e2d51u;
|
||||
k = (k << 15u) | (k >> 17u);
|
||||
k *= 0x1b873593u;
|
||||
h ^= k;
|
||||
h = (h << 13u) | (h >> 19u);
|
||||
h = (h * 5u) + 0xe6546b64u;
|
||||
} while (--i);
|
||||
h ^= wordCount;
|
||||
h ^= h >> 16u;
|
||||
h *= 0x85ebca6bu;
|
||||
h ^= h >> 13u;
|
||||
h *= 0xc2b2ae35u;
|
||||
h ^= h >> 16u;
|
||||
return h;
|
||||
}
|
||||
|
||||
// The hash yields the same result for a given byte sequence regardless of alignment.
|
||||
inline uint32_t murmurSlow(const uint8_t* key, size_t byteCount, uint32_t seed) noexcept {
|
||||
const size_t wordCount = (byteCount + 3) / 4;
|
||||
const uint8_t* const last = key + byteCount;
|
||||
|
||||
// The remainder is identical to murmur3() except an inner loop safely "reads" an entire word.
|
||||
uint32_t h = seed;
|
||||
size_t wc = wordCount;
|
||||
do {
|
||||
uint32_t k = 0;
|
||||
for (int i = 0; i < 4 && key < last; ++i, ++key) {
|
||||
k >>= 8;
|
||||
k |= uint32_t(*key) << 24;
|
||||
}
|
||||
k *= 0xcc9e2d51u;
|
||||
k = (k << 15u) | (k >> 17u);
|
||||
k *= 0x1b873593u;
|
||||
h ^= k;
|
||||
h = (h << 13u) | (h >> 19u);
|
||||
h = (h * 5u) + 0xe6546b64u;
|
||||
} while (--wc);
|
||||
h ^= wordCount;
|
||||
h ^= h >> 16u;
|
||||
h *= 0x85ebca6bu;
|
||||
h ^= h >> 13u;
|
||||
h *= 0xc2b2ae35u;
|
||||
h ^= h >> 16u;
|
||||
return h;
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
struct MurmurHashFn {
|
||||
uint32_t operator()(const T& key) const noexcept {
|
||||
static_assert(0 == (sizeof(key) & 3u), "Hashing requires a size that is a multiple of 4.");
|
||||
return murmur3((const uint32_t*) &key, sizeof(key) / 4, 0);
|
||||
}
|
||||
};
|
||||
|
||||
// combines two hashes together
|
||||
template<class T>
|
||||
inline void combine(size_t& seed, const T& v) noexcept {
|
||||
std::hash<T> hasher;
|
||||
seed ^= hasher(v) + 0x9e3779b9u + (seed << 6u) + (seed >> 2u);
|
||||
}
|
||||
|
||||
// combines two hashes together, faster but less good
|
||||
template<class T>
|
||||
inline void combine_fast(size_t& seed, const T& v) noexcept {
|
||||
std::hash<T> hasher;
|
||||
seed ^= hasher(v) << 1u;
|
||||
}
|
||||
|
||||
} // namespace utils::hash
|
||||
|
||||
#endif // TNT_UTILS_HASH_H
|
||||
@@ -17,6 +17,8 @@
|
||||
#ifndef TNT_UTILS_INVOKABLE_H
|
||||
#define TNT_UTILS_INVOKABLE_H
|
||||
|
||||
#include <utils/ostream.h>
|
||||
|
||||
#include <type_traits>
|
||||
#include <utility>
|
||||
|
||||
@@ -81,6 +83,11 @@ public:
|
||||
explicit operator bool() const noexcept;
|
||||
|
||||
private:
|
||||
#if !defined(NDEBUG)
|
||||
friend io::ostream& operator<<(io::ostream& out, const Invocable&) {
|
||||
return out << "Invocable<>"; // TODO: is there a way to do better here?
|
||||
}
|
||||
#endif
|
||||
void* mInvocable = nullptr;
|
||||
void (*mDeleter)(void*) = nullptr;
|
||||
R (* mInvoker)(void*, Args...) = nullptr;
|
||||
|
||||
@@ -0,0 +1,615 @@
|
||||
/*
|
||||
* Copyright (C) 2016 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#ifndef TNT_UTILS_JOBSYSTEM_H
|
||||
#define TNT_UTILS_JOBSYSTEM_H
|
||||
|
||||
#include <utils/Allocator.h>
|
||||
#include <utils/architecture.h>
|
||||
#include <utils/compiler.h>
|
||||
#include <utils/Condition.h>
|
||||
#include <utils/debug.h>
|
||||
#include <utils/memalign.h>
|
||||
#include <utils/Mutex.h>
|
||||
#include <utils/Slice.h>
|
||||
#include <utils/ostream.h>
|
||||
#include <utils/WorkStealingDequeue.h>
|
||||
|
||||
#include <tsl/robin_map.h>
|
||||
|
||||
#include <atomic>
|
||||
#include <functional>
|
||||
#include <mutex>
|
||||
#include <type_traits>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
#include <assert.h>
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
namespace utils {
|
||||
|
||||
class JobSystem {
|
||||
static constexpr size_t MAX_JOB_COUNT = 1 << 14; // 16384
|
||||
static constexpr uint32_t JOB_COUNT_MASK = MAX_JOB_COUNT - 1;
|
||||
static constexpr uint32_t WAITER_COUNT_SHIFT = 24;
|
||||
static_assert(MAX_JOB_COUNT <= 0x7FFE, "MAX_JOB_COUNT must be <= 0x7FFE");
|
||||
using WorkQueue = WorkStealingDequeue<uint16_t, MAX_JOB_COUNT>;
|
||||
using Mutex = utils::Mutex;
|
||||
using Condition = utils::Condition;
|
||||
|
||||
public:
|
||||
class Job;
|
||||
|
||||
using ThreadId = uint8_t;
|
||||
|
||||
using JobFunc = void(*)(void*, JobSystem&, Job*);
|
||||
|
||||
static constexpr ThreadId invalidThreadId = 0xff;
|
||||
|
||||
class alignas(CACHELINE_SIZE) Job {
|
||||
public:
|
||||
Job() noexcept {} /* = default; */ /* clang bug */ // NOLINT(modernize-use-equals-default,cppcoreguidelines-pro-type-member-init)
|
||||
Job(const Job&) = delete;
|
||||
Job(Job&&) = delete;
|
||||
|
||||
private:
|
||||
friend class JobSystem;
|
||||
|
||||
// Size is chosen so that we can store at least std::function<>
|
||||
// the alignas() qualifier ensures we're multiple of a cache-line.
|
||||
static constexpr size_t JOB_STORAGE_SIZE_BYTES =
|
||||
sizeof(std::function<void()>) > 48 ? sizeof(std::function<void()>) : 48;
|
||||
static constexpr size_t JOB_STORAGE_SIZE_WORDS =
|
||||
(JOB_STORAGE_SIZE_BYTES + sizeof(void*) - 1) / sizeof(void*);
|
||||
|
||||
// keep it first, so it's correctly aligned with all architectures
|
||||
// this is where we store the job's data, typically a std::function<>
|
||||
// v7 | v8
|
||||
void* storage[JOB_STORAGE_SIZE_WORDS]; // 48 | 48
|
||||
JobFunc function; // 4 | 8
|
||||
uint16_t parent; // 2 | 2
|
||||
mutable ThreadId id = invalidThreadId; // 1 | 1
|
||||
mutable std::atomic<uint8_t> refCount = { 1 }; // 1 | 1
|
||||
std::atomic<uint32_t> runningJobCount = { 1 }; // 4 | 4
|
||||
// 4 | 0 (padding)
|
||||
// 64 | 64
|
||||
};
|
||||
|
||||
#ifndef WIN32
|
||||
// on windows std::function<void()> is bigger and forces the whole structure to be larger
|
||||
static_assert(sizeof(Job) == 64);
|
||||
#endif
|
||||
|
||||
explicit JobSystem(size_t threadCount = 0, size_t adoptableThreadsCount = 1) noexcept;
|
||||
|
||||
~JobSystem();
|
||||
|
||||
// Make the current thread part of the thread pool.
|
||||
void adopt();
|
||||
|
||||
// Remove this adopted thread from the parent. This is intended to be used for
|
||||
// shutting down a JobSystem. In particular, this doesn't allow the parent to
|
||||
// adopt more thread.
|
||||
void emancipate();
|
||||
|
||||
|
||||
// If a parent is not specified when creating a job, that job will automatically take the
|
||||
// root job as a parent.
|
||||
// The root job is reset when waited on.
|
||||
Job* setRootJob(Job* job) noexcept { return mRootJob = job; }
|
||||
|
||||
// use setRootJob() instead
|
||||
UTILS_DEPRECATED
|
||||
Job* setMasterJob(Job* job) noexcept { return setRootJob(job); }
|
||||
|
||||
|
||||
Job* create(Job* parent, JobFunc func) noexcept;
|
||||
|
||||
// NOTE: All methods below must be called from the same thread and that thread must be
|
||||
// owned by JobSystem's thread pool.
|
||||
|
||||
/*
|
||||
* Job creation examples:
|
||||
* ----------------------
|
||||
*
|
||||
* struct Functor {
|
||||
* uintptr_t storage[6];
|
||||
* void operator()(JobSystem&, Jobsystem::Job*);
|
||||
* } functor;
|
||||
*
|
||||
* struct Foo {
|
||||
* uintptr_t storage[6];
|
||||
* void method(JobSystem&, Jobsystem::Job*);
|
||||
* } foo;
|
||||
*
|
||||
* Functor and Foo size muse be <= uintptr_t[6]
|
||||
*
|
||||
* createJob()
|
||||
* createJob(parent)
|
||||
* createJob<Foo, &Foo::method>(parent, &foo)
|
||||
* createJob<Foo, &Foo::method>(parent, foo)
|
||||
* createJob<Foo, &Foo::method>(parent, std::ref(foo))
|
||||
* createJob(parent, functor)
|
||||
* createJob(parent, std::ref(functor))
|
||||
* createJob(parent, [ up-to 6 uintptr_t ](JobSystem*, Jobsystem::Job*){ })
|
||||
*
|
||||
* Utility functions:
|
||||
* ------------------
|
||||
* These are less efficient, but handle any size objects using the heap if needed.
|
||||
* (internally uses std::function<>), and don't require the callee to take
|
||||
* a (JobSystem&, Jobsystem::Job*) as parameter.
|
||||
*
|
||||
* struct BigFoo {
|
||||
* uintptr_t large[16];
|
||||
* void operator()();
|
||||
* void method(int answerToEverything);
|
||||
* static void exec(BigFoo&) { }
|
||||
* } bigFoo;
|
||||
*
|
||||
* jobs::createJob(js, parent, [ any-capture ](int answerToEverything){}, 42);
|
||||
* jobs::createJob(js, parent, &BigFoo::method, &bigFoo, 42);
|
||||
* jobs::createJob(js, parent, &BigFoo::exec, std::ref(bigFoo));
|
||||
* jobs::createJob(js, parent, bigFoo);
|
||||
* jobs::createJob(js, parent, std::ref(bigFoo));
|
||||
* etc...
|
||||
*
|
||||
* struct SmallFunctor {
|
||||
* uintptr_t storage[3];
|
||||
* void operator()(T* data, size_t count);
|
||||
* } smallFunctor;
|
||||
*
|
||||
* jobs::parallel_for(js, data, count, [ up-to 3 uintptr_t ](T* data, size_t count) { });
|
||||
* jobs::parallel_for(js, data, count, smallFunctor);
|
||||
* jobs::parallel_for(js, data, count, std::ref(smallFunctor));
|
||||
*
|
||||
*/
|
||||
|
||||
// creates an empty (no-op) job with an optional parent
|
||||
Job* createJob(Job* parent = nullptr) noexcept {
|
||||
return create(parent, nullptr);
|
||||
}
|
||||
|
||||
// creates a job from a KNOWN method pointer w/ object passed by pointer
|
||||
// the caller must ensure the object will outlive the Job
|
||||
template<typename T, void(T::*method)(JobSystem&, Job*)>
|
||||
Job* createJob(Job* parent, T* data) noexcept {
|
||||
Job* job = create(parent, +[](void* storage, JobSystem& js, Job* job) {
|
||||
T* const that = static_cast<T*>(reinterpret_cast<void**>(storage)[0]);
|
||||
(that->*method)(js, job);
|
||||
});
|
||||
if (job) {
|
||||
job->storage[0] = data;
|
||||
}
|
||||
return job;
|
||||
}
|
||||
|
||||
// creates a job from a KNOWN method pointer w/ object passed by value
|
||||
template<typename T, void(T::*method)(JobSystem&, Job*)>
|
||||
Job* createJob(Job* parent, T data) noexcept {
|
||||
static_assert(sizeof(data) <= sizeof(Job::storage), "user data too large");
|
||||
Job* job = create(parent, [](void* storage, JobSystem& js, Job* job) {
|
||||
T* const that = static_cast<T*>(storage);
|
||||
(that->*method)(js, job);
|
||||
that->~T();
|
||||
});
|
||||
if (job) {
|
||||
new(job->storage) T(std::move(data));
|
||||
}
|
||||
return job;
|
||||
}
|
||||
|
||||
// creates a job from a KNOWN method pointer w/ object passed by value
|
||||
template<typename T, void(T::*method)(JobSystem&, Job*), typename ... ARGS>
|
||||
Job* emplaceJob(Job* parent, ARGS&& ... args) noexcept {
|
||||
static_assert(sizeof(T) <= sizeof(Job::storage), "user data too large");
|
||||
Job* job = create(parent, [](void* storage, JobSystem& js, Job* job) {
|
||||
T* const that = static_cast<T*>(storage);
|
||||
(that->*method)(js, job);
|
||||
that->~T();
|
||||
});
|
||||
if (job) {
|
||||
new(job->storage) T(std::forward<ARGS>(args)...);
|
||||
}
|
||||
return job;
|
||||
}
|
||||
|
||||
// creates a job from a functor passed by value
|
||||
template<typename T>
|
||||
Job* createJob(Job* parent, T functor) noexcept {
|
||||
static_assert(sizeof(functor) <= sizeof(Job::storage), "functor too large");
|
||||
Job* job = create(parent, [](void* storage, JobSystem& js, Job* job){
|
||||
T* const that = static_cast<T*>(storage);
|
||||
that->operator()(js, job);
|
||||
that->~T();
|
||||
});
|
||||
if (job) {
|
||||
new(job->storage) T(std::move(functor));
|
||||
}
|
||||
return job;
|
||||
}
|
||||
|
||||
// creates a job from a functor passed by value
|
||||
template<typename T, typename ... ARGS>
|
||||
Job* emplaceJob(Job* parent, ARGS&& ... args) noexcept {
|
||||
static_assert(sizeof(T) <= sizeof(Job::storage), "functor too large");
|
||||
Job* job = create(parent, [](void* storage, JobSystem& js, Job* job){
|
||||
T* const that = static_cast<T*>(storage);
|
||||
that->operator()(js, job);
|
||||
that->~T();
|
||||
});
|
||||
if (job) {
|
||||
new(job->storage) T(std::forward<ARGS>(args)...);
|
||||
}
|
||||
return job;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* Jobs are normally finished automatically, this can be used to cancel a job before it is run.
|
||||
*
|
||||
* Never use this once a flavor of run() has been called.
|
||||
*/
|
||||
void cancel(Job*& job) noexcept;
|
||||
|
||||
/*
|
||||
* Adds a reference to a Job.
|
||||
*
|
||||
* This allows the caller to waitAndRelease() on this job from multiple threads.
|
||||
* Use runAndWait() if waiting from multiple threads is not needed.
|
||||
*
|
||||
* This job MUST BE waited on with waitAndRelease(), or released with release().
|
||||
*/
|
||||
static Job* retain(Job* job) noexcept;
|
||||
|
||||
/*
|
||||
* Releases a reference from a Job obtained with runAndRetain() or a call to retain().
|
||||
*
|
||||
* The job can't be used after this call.
|
||||
*/
|
||||
void release(Job*& job) noexcept;
|
||||
void release(Job*&& job) noexcept {
|
||||
Job* p = job;
|
||||
release(p);
|
||||
}
|
||||
|
||||
/*
|
||||
* Add job to this thread's execution queue. Its reference will drop automatically.
|
||||
* The current thread must be owned by JobSystem's thread pool. See adopt().
|
||||
*
|
||||
* The job can't be used after this call.
|
||||
*/
|
||||
void run(Job*& job) noexcept;
|
||||
void run(Job*&& job) noexcept { // allows run(createJob(...));
|
||||
Job* p = job;
|
||||
run(p);
|
||||
}
|
||||
|
||||
/*
|
||||
* Add job to this thread's execution queue. Its reference will drop automatically.
|
||||
* The current thread must be owned by JobSystem's thread pool. See adopt().
|
||||
* id must be the current thread id obtained with JobSystem::getThreadId(Job*). This
|
||||
* API is more efficient than the methods above.
|
||||
*
|
||||
* The job can't be used after this call.
|
||||
*/
|
||||
void run(Job*& job, ThreadId id) noexcept;
|
||||
void run(Job*&& job, ThreadId id) noexcept { // allows run(createJob(...));
|
||||
Job* p = job;
|
||||
run(p, id);
|
||||
}
|
||||
|
||||
/*
|
||||
* Add job to this thread's execution queue and keep a reference to it.
|
||||
* The current thread must be owned by JobSystem's thread pool. See adopt().
|
||||
*
|
||||
* This job MUST BE waited on with wait(), or released with release().
|
||||
*/
|
||||
Job* runAndRetain(Job* job) noexcept;
|
||||
|
||||
/*
|
||||
* Wait on a job and destroys it.
|
||||
* The current thread must be owned by JobSystem's thread pool. See adopt().
|
||||
*
|
||||
* The job must first be obtained from runAndRetain() or retain().
|
||||
* The job can't be used after this call.
|
||||
*/
|
||||
void waitAndRelease(Job*& job) noexcept;
|
||||
|
||||
/*
|
||||
* Runs and wait for a job. This is equivalent to calling
|
||||
* runAndRetain(job);
|
||||
* wait(job);
|
||||
*
|
||||
* The job can't be used after this call.
|
||||
*/
|
||||
void runAndWait(Job*& job) noexcept;
|
||||
void runAndWait(Job*&& job) noexcept { // allows runAndWait(createJob(...));
|
||||
Job* p = job;
|
||||
runAndWait(p);
|
||||
}
|
||||
|
||||
// for debugging
|
||||
friend io::ostream& operator << (io::ostream& out, JobSystem const& js);
|
||||
|
||||
|
||||
// utility functions...
|
||||
|
||||
// set the name of the current thread (on OSes that support it)
|
||||
static void setThreadName(const char* threadName) noexcept;
|
||||
|
||||
enum class Priority {
|
||||
NORMAL,
|
||||
DISPLAY,
|
||||
URGENT_DISPLAY,
|
||||
BACKGROUND
|
||||
};
|
||||
|
||||
static void setThreadPriority(Priority priority) noexcept;
|
||||
static void setThreadAffinityById(size_t id) noexcept;
|
||||
|
||||
size_t getParallelSplitCount() const noexcept {
|
||||
return mParallelSplitCount;
|
||||
}
|
||||
|
||||
size_t getThreadCount() const { return mThreadCount; }
|
||||
|
||||
// returns the current ThreadId, which can be used with run(). This method can only be
|
||||
// called from a job's function.
|
||||
static ThreadId getThreadId(Job const* job) noexcept {
|
||||
assert_invariant(job->id != invalidThreadId);
|
||||
return job->id;
|
||||
}
|
||||
|
||||
private:
|
||||
// this is just to avoid using std::default_random_engine, since we're in a public header.
|
||||
class default_random_engine {
|
||||
static constexpr uint32_t m = 0x7fffffffu;
|
||||
uint32_t mState; // must be 0 < seed < 0x7fffffff
|
||||
public:
|
||||
using result_type = uint32_t;
|
||||
|
||||
static constexpr result_type min() noexcept {
|
||||
return 1;
|
||||
}
|
||||
|
||||
static constexpr result_type max() noexcept {
|
||||
return m - 1;
|
||||
}
|
||||
|
||||
inline constexpr explicit default_random_engine(uint32_t seed = 1u) noexcept
|
||||
: mState(((seed % m) == 0u) ? 1u : seed % m) {
|
||||
}
|
||||
inline uint32_t operator()() noexcept {
|
||||
return mState = uint32_t((uint64_t(mState) * 48271u) % m);
|
||||
}
|
||||
};
|
||||
|
||||
struct alignas(CACHELINE_SIZE) ThreadState { // this causes 40-bytes padding
|
||||
// make sure storage is cache-line aligned
|
||||
WorkQueue workQueue;
|
||||
|
||||
// these are not accessed by the worker threads
|
||||
alignas(CACHELINE_SIZE) // this causes 56-bytes padding
|
||||
JobSystem* js; // this is in fact const and always initialized
|
||||
std::thread thread; // unused for adopted threads
|
||||
default_random_engine rndGen;
|
||||
};
|
||||
|
||||
static_assert(sizeof(ThreadState) % CACHELINE_SIZE == 0,
|
||||
"ThreadState doesn't align to a cache line");
|
||||
|
||||
ThreadState& getState() noexcept;
|
||||
|
||||
static void incRef(Job const* job) noexcept;
|
||||
void decRef(Job const* job) noexcept;
|
||||
|
||||
Job* allocateJob() noexcept;
|
||||
ThreadState* getStateToStealFrom(ThreadState& state) noexcept;
|
||||
static bool hasJobCompleted(Job const* job) noexcept;
|
||||
|
||||
void requestExit() noexcept;
|
||||
bool exitRequested() const noexcept;
|
||||
bool hasActiveJobs() const noexcept;
|
||||
|
||||
void loop(ThreadState* state) noexcept;
|
||||
bool execute(ThreadState& state) noexcept;
|
||||
Job* steal(ThreadState& state) noexcept;
|
||||
void finish(Job* job) noexcept;
|
||||
|
||||
void put(WorkQueue& workQueue, Job* job) noexcept;
|
||||
Job* pop(WorkQueue& workQueue) noexcept;
|
||||
Job* steal(WorkQueue& workQueue) noexcept;
|
||||
|
||||
[[nodiscard]]
|
||||
uint32_t wait(std::unique_lock<Mutex>& lock, Job* job) noexcept;
|
||||
void wait(std::unique_lock<Mutex>& lock) noexcept;
|
||||
void wakeAll() noexcept;
|
||||
void wakeOne() noexcept;
|
||||
|
||||
// these have thread contention, keep them together
|
||||
Mutex mWaiterLock;
|
||||
Condition mWaiterCondition;
|
||||
|
||||
std::atomic<int32_t> mActiveJobs = { 0 };
|
||||
Arena<ObjectPoolAllocator<Job>, LockingPolicy::Mutex> mJobPool;
|
||||
|
||||
template <typename T>
|
||||
using aligned_vector = std::vector<T, STLAlignedAllocator<T>>;
|
||||
|
||||
// These are essentially const, make sure they're on a different cache-lines than the
|
||||
// read-write atomics.
|
||||
// We can't use "alignas(CACHELINE_SIZE)" because the standard allocator can't make this
|
||||
// guarantee.
|
||||
char padding[CACHELINE_SIZE];
|
||||
|
||||
alignas(16) // at least we align to half (or quarter) cache-line
|
||||
aligned_vector<ThreadState> mThreadStates; // actual data is stored offline
|
||||
std::atomic<bool> mExitRequested = { false }; // this one is almost never written
|
||||
std::atomic<uint16_t> mAdoptedThreads = { 0 }; // this one is almost never written
|
||||
Job* const mJobStorageBase; // Base for conversion to indices
|
||||
uint16_t mThreadCount = 0; // total # of threads in the pool
|
||||
uint8_t mParallelSplitCount = 0; // # of split allowable in parallel_for
|
||||
Job* mRootJob = nullptr;
|
||||
|
||||
Mutex mThreadMapLock; // this should have very little contention
|
||||
tsl::robin_map<std::thread::id, ThreadState *> mThreadMap;
|
||||
};
|
||||
|
||||
// -------------------------------------------------------------------------------------------------
|
||||
// Utility functions built on top of JobSystem
|
||||
|
||||
namespace jobs {
|
||||
|
||||
// These are convenience C++11 style job creation methods that support lambdas
|
||||
//
|
||||
// IMPORTANT: these are less efficient to call and may perform heap allocation
|
||||
// depending on the capture and parameters
|
||||
//
|
||||
template<typename CALLABLE, typename ... ARGS>
|
||||
JobSystem::Job* createJob(JobSystem& js, JobSystem::Job* parent,
|
||||
CALLABLE&& func, ARGS&&... args) noexcept {
|
||||
struct Data {
|
||||
explicit Data(std::function<void()> f) noexcept: f(std::move(f)) {}
|
||||
std::function<void()> f;
|
||||
// Renaming the method below could cause an Arrested Development.
|
||||
void gob(JobSystem&, JobSystem::Job*) noexcept { f(); }
|
||||
};
|
||||
return js.emplaceJob<Data, &Data::gob>(parent,
|
||||
std::bind(std::forward<CALLABLE>(func), std::forward<ARGS>(args)...));
|
||||
}
|
||||
|
||||
template<typename CALLABLE, typename T, typename ... ARGS,
|
||||
typename = std::enable_if_t<
|
||||
std::is_member_function_pointer_v<std::remove_reference_t<CALLABLE>>
|
||||
>
|
||||
>
|
||||
JobSystem::Job* createJob(JobSystem& js, JobSystem::Job* parent,
|
||||
CALLABLE&& func, T&& o, ARGS&&... args) noexcept {
|
||||
struct Data {
|
||||
explicit Data(std::function<void()> f) noexcept: f(std::move(f)) {}
|
||||
std::function<void()> f;
|
||||
// Renaming the method below could cause an Arrested Development.
|
||||
void gob(JobSystem&, JobSystem::Job*) noexcept { f(); }
|
||||
};
|
||||
return js.emplaceJob<Data, &Data::gob>(parent,
|
||||
std::bind(std::forward<CALLABLE>(func), std::forward<T>(o), std::forward<ARGS>(args)...));
|
||||
}
|
||||
|
||||
|
||||
namespace details {
|
||||
|
||||
template<typename S, typename F>
|
||||
struct ParallelForJobData {
|
||||
using SplitterType = S;
|
||||
using Functor = F;
|
||||
using JobData = ParallelForJobData;
|
||||
using size_type = uint32_t;
|
||||
|
||||
ParallelForJobData(size_type start, size_type count, uint8_t splits,
|
||||
Functor functor,
|
||||
const SplitterType& splitter) noexcept
|
||||
: start(start), count(count),
|
||||
functor(std::move(functor)),
|
||||
splits(splits),
|
||||
splitter(splitter) {
|
||||
}
|
||||
|
||||
void parallelWithJobs(JobSystem& js, JobSystem::Job* parent) noexcept {
|
||||
assert(parent);
|
||||
|
||||
// this branch is often miss-predicted (it both sides happen 50% of the calls)
|
||||
right_side:
|
||||
if (splitter.split(splits, count)) {
|
||||
const size_type lc = count / 2;
|
||||
JobSystem::Job* l = js.emplaceJob<JobData, &JobData::parallelWithJobs>(parent,
|
||||
start, lc, splits + uint8_t(1), functor, splitter);
|
||||
if (UTILS_UNLIKELY(l == nullptr)) {
|
||||
// couldn't create a job, just pretend we're done splitting
|
||||
goto execute;
|
||||
}
|
||||
|
||||
// start the left side before attempting the right side, so we parallelize in case
|
||||
// of job creation failure -- rare, but still.
|
||||
js.run(l, JobSystem::getThreadId(parent));
|
||||
|
||||
// don't spawn a job for the right side, just reuse us -- spawning jobs is more
|
||||
// costly than we'd like.
|
||||
start += lc;
|
||||
count -= lc;
|
||||
++splits;
|
||||
goto right_side;
|
||||
|
||||
} else {
|
||||
execute:
|
||||
// we're done splitting, do the real work here!
|
||||
functor(start, count);
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
size_type start; // 4
|
||||
size_type count; // 4
|
||||
Functor functor; // ?
|
||||
uint8_t splits; // 1
|
||||
SplitterType splitter; // 1
|
||||
};
|
||||
|
||||
} // namespace details
|
||||
|
||||
|
||||
// parallel jobs with start/count indices
|
||||
template<typename S, typename F>
|
||||
JobSystem::Job* parallel_for(JobSystem& js, JobSystem::Job* parent,
|
||||
uint32_t start, uint32_t count, F functor, const S& splitter) noexcept {
|
||||
using JobData = details::ParallelForJobData<S, F>;
|
||||
return js.emplaceJob<JobData, &JobData::parallelWithJobs>(parent,
|
||||
start, count, 0, std::move(functor), splitter);
|
||||
}
|
||||
|
||||
// parallel jobs with pointer/count
|
||||
template<typename T, typename S, typename F>
|
||||
JobSystem::Job* parallel_for(JobSystem& js, JobSystem::Job* parent,
|
||||
T* data, uint32_t count, F functor, const S& splitter) noexcept {
|
||||
auto user = [data, f = std::move(functor)](uint32_t s, uint32_t c) {
|
||||
f(data + s, c);
|
||||
};
|
||||
using JobData = details::ParallelForJobData<S, decltype(user)>;
|
||||
return js.emplaceJob<JobData, &JobData::parallelWithJobs>(parent,
|
||||
0, count, 0, std::move(user), splitter);
|
||||
}
|
||||
|
||||
// parallel jobs on a Slice<>
|
||||
template<typename T, typename S, typename F>
|
||||
JobSystem::Job* parallel_for(JobSystem& js, JobSystem::Job* parent,
|
||||
Slice<T> slice, F functor, const S& splitter) noexcept {
|
||||
return parallel_for(js, parent, slice.data(), slice.size(), functor, splitter);
|
||||
}
|
||||
|
||||
|
||||
template<size_t COUNT, size_t MAX_SPLITS = 12>
|
||||
class CountSplitter {
|
||||
public:
|
||||
bool split(size_t splits, size_t count) const noexcept {
|
||||
return (splits < MAX_SPLITS && count >= COUNT * 2);
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace jobs
|
||||
} // namespace utils
|
||||
|
||||
#endif // TNT_UTILS_JOBSYSTEM_H
|
||||
@@ -47,7 +47,7 @@ class EntityManager;
|
||||
* printf("%s\n", names->getName(names->getInstance(myEntity));
|
||||
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
*/
|
||||
class UTILS_PUBLIC NameComponentManager : private SingleInstanceComponentManager<utils::CString> {
|
||||
class UTILS_PUBLIC NameComponentManager : private SingleInstanceComponentManager<CString> {
|
||||
public:
|
||||
using Instance = EntityInstance<NameComponentManager>;
|
||||
|
||||
@@ -97,7 +97,7 @@ public:
|
||||
const char* getName(Instance instance) const noexcept;
|
||||
|
||||
void gc(EntityManager& em) noexcept {
|
||||
SingleInstanceComponentManager<utils::CString>::gc(em, [this](Entity e) {
|
||||
SingleInstanceComponentManager<CString>::gc(em, [this](Entity e) {
|
||||
removeComponent(e);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -17,14 +17,28 @@
|
||||
#ifndef TNT_UTILS_PANIC_H
|
||||
#define TNT_UTILS_PANIC_H
|
||||
|
||||
#ifdef FILAMENT_PANIC_USES_ABSL
|
||||
# if FILAMENT_PANIC_USES_ABSL
|
||||
# include "absl/log/log.h"
|
||||
# define FILAMENT_CHECK_PRECONDITION CHECK
|
||||
# define FILAMENT_CHECK_POSTCONDITION CHECK
|
||||
# define FILAMENT_CHECK_ARITHMETIC CHECK
|
||||
# endif
|
||||
#endif
|
||||
|
||||
#include <utils/CallStack.h>
|
||||
#include <utils/compiler.h>
|
||||
#include <utils/sstream.h>
|
||||
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
|
||||
#ifdef __EXCEPTIONS
|
||||
# define UTILS_EXCEPTIONS 1
|
||||
#else
|
||||
# ifdef UTILS_EXCEPTIONS
|
||||
# error UTILS_EXCEPTIONS is already defined!
|
||||
# endif
|
||||
#endif
|
||||
|
||||
/**
|
||||
@@ -250,42 +264,83 @@ namespace utils {
|
||||
*/
|
||||
class UTILS_PUBLIC Panic {
|
||||
public:
|
||||
|
||||
using PanicHandlerCallback = void(*)(void* user, Panic const& panic);
|
||||
|
||||
/**
|
||||
* Sets a user-defined handler for the Panic. If exceptions are enabled, the concrete Panic
|
||||
* object will be thrown upon return; moreover it is acceptable to throw from the provided
|
||||
* callback, but it is unsafe to throw the Panic object itself, since it's just an interface.
|
||||
* It is also acceptable to abort from the callback. If exceptions are not enabled, std::abort()
|
||||
* will be automatically called upon return.
|
||||
*
|
||||
* The PanicHandlerCallback can be called from any thread.
|
||||
*
|
||||
* Caveat: this API can misbehave if is used as a static library in multiple translation units,
|
||||
* some of these translation units might not see the callback.
|
||||
*
|
||||
* @param handler pointer to the user defined handler for the Panic
|
||||
* @param user user pointer given back to the callback
|
||||
*/
|
||||
static void setPanicHandler(PanicHandlerCallback handler, void* user) noexcept;
|
||||
|
||||
|
||||
virtual ~Panic() noexcept;
|
||||
|
||||
/**
|
||||
* @return a detailed description of the error
|
||||
* @return a formatted and detailed description of the error including all available
|
||||
* information.
|
||||
* @see std::exception
|
||||
*/
|
||||
virtual const char* what() const noexcept = 0;
|
||||
|
||||
/**
|
||||
* Get the function name where the panic was detected
|
||||
* Get the type of the panic (e.g. "Precondition")
|
||||
* @return a C string containing the type of panic
|
||||
*/
|
||||
virtual const char* getType() const noexcept = 0;
|
||||
|
||||
/**
|
||||
* Get the reason string for the panic
|
||||
* @return a C string containing the reason for the panic
|
||||
*/
|
||||
virtual const char* getReason() const noexcept = 0;
|
||||
|
||||
/**
|
||||
* Get a version of the reason string that is guaranteed to be constructed from literal
|
||||
* strings only; it will contain no runtime information.
|
||||
*/
|
||||
virtual const char* getReasonLiteral() const noexcept = 0;
|
||||
|
||||
/**
|
||||
* Get the function name where the panic was detected. On debug build the fully qualified
|
||||
* function name is returned; on release builds only the function name is.
|
||||
* @return a C string containing the function name where the panic was detected
|
||||
*/
|
||||
virtual const char* getFunction() const noexcept = 0;
|
||||
|
||||
/**
|
||||
* Get the file name where the panic was detected
|
||||
* Get the file name where the panic was detected. Only available on debug builds.
|
||||
* @return a C string containing the file name where the panic was detected
|
||||
*/
|
||||
virtual const char* getFile() const noexcept = 0;
|
||||
|
||||
/**
|
||||
* Get the line number in the file where the panic was detected
|
||||
* Get the line number in the file where the panic was detected. Only available on debug builds.
|
||||
* @return an integer containing the line number in the file where the panic was detected
|
||||
*/
|
||||
virtual int getLine() const noexcept = 0;
|
||||
|
||||
/**
|
||||
* Logs this exception to the system-log
|
||||
*/
|
||||
virtual void log() const noexcept = 0;
|
||||
|
||||
/**
|
||||
* Get the CallStack when the panic was detected
|
||||
* Get the CallStack when the panic was detected if available.
|
||||
* @return the CallStack when the panic was detected
|
||||
*/
|
||||
virtual const CallStack& getCallStack() const noexcept = 0;
|
||||
|
||||
/**
|
||||
* Logs this exception to the system-log
|
||||
*/
|
||||
virtual void log() const noexcept = 0;
|
||||
};
|
||||
|
||||
// -----------------------------------------------------------------------------------------------
|
||||
@@ -305,6 +360,9 @@ public:
|
||||
const char* what() const noexcept override;
|
||||
|
||||
// Panic interface
|
||||
const char* getType() const noexcept override;
|
||||
const char* getReason() const noexcept override;
|
||||
const char* getReasonLiteral() const noexcept override;
|
||||
const char* getFunction() const noexcept override;
|
||||
const char* getFile() const noexcept override;
|
||||
int getLine() const noexcept override;
|
||||
@@ -318,13 +376,14 @@ public:
|
||||
* @param function the name of the function where the error was detected
|
||||
* @param file the file where the above function in implemented
|
||||
* @param line the line in the above file where the error was detected
|
||||
* @param literal a literal version of the error message
|
||||
* @param format printf style string describing the error
|
||||
* @see ASSERT_PRECONDITION, ASSERT_POSTCONDITION, ASSERT_ARITHMETIC
|
||||
* @see PANIC_PRECONDITION, PANIC_POSTCONDITION, PANIC_ARITHMETIC
|
||||
* @see setMode()
|
||||
*/
|
||||
static void panic(char const* function, char const* file, int line, const char* format, ...)
|
||||
UTILS_NORETURN;
|
||||
static void panic(char const* function, char const* file, int line, char const* literal,
|
||||
const char* format, ...) UTILS_NORETURN;
|
||||
|
||||
/**
|
||||
* Depending on the mode set, either throws an exception of type T with the given reason plus
|
||||
@@ -333,43 +392,41 @@ public:
|
||||
* @param function the name of the function where the error was detected
|
||||
* @param file the file where the above function in implemented
|
||||
* @param line the line in the above file where the error was detected
|
||||
* @param s std::string describing the error
|
||||
* @param literal a literal version of the error message
|
||||
* @param reason std::string describing the error
|
||||
* @see ASSERT_PRECONDITION, ASSERT_POSTCONDITION, ASSERT_ARITHMETIC
|
||||
* @see PANIC_PRECONDITION, PANIC_POSTCONDITION, PANIC_ARITHMETIC
|
||||
* @see setMode()
|
||||
*/
|
||||
static inline void panic(char const* function, char const* file, int line, const std::string& s)
|
||||
UTILS_NORETURN {
|
||||
panic(function, file, line, s.c_str());
|
||||
}
|
||||
static inline void panic(
|
||||
char const* function, char const* file, int line, char const* literal,
|
||||
std::string reason) UTILS_NORETURN;
|
||||
|
||||
protected:
|
||||
/**
|
||||
* Creates a Panic.
|
||||
* @param reason a description of the cause of the error
|
||||
*/
|
||||
explicit TPanic(std::string reason);
|
||||
|
||||
/**
|
||||
* Creates a Panic with extra information about the error-site.
|
||||
* @param function the name of the function where the error was detected
|
||||
* @param file the file where the above function in implemented
|
||||
* @param line the line in the above file where the error was detected
|
||||
* @param literal a literal version of the error message
|
||||
* @param reason a description of the cause of the error
|
||||
*/
|
||||
TPanic(char const* function, char const* file, int line, std::string reason);
|
||||
TPanic(char const* function, char const* file, int line, char const* literal,
|
||||
std::string reason);
|
||||
|
||||
~TPanic() override;
|
||||
|
||||
private:
|
||||
void buildMessage();
|
||||
|
||||
CallStack m_callstack;
|
||||
std::string m_reason;
|
||||
char const* const m_function = nullptr;
|
||||
char const* const m_file = nullptr;
|
||||
const int m_line = -1;
|
||||
mutable std::string m_msg;
|
||||
char const* const mFile = nullptr; // file where the panic happened
|
||||
char const* const mFunction = nullptr; // function where the panic happened
|
||||
int const mLine = -1; // line where the panic happened
|
||||
std::string mLiteral; // reason for the panic, built only from literals
|
||||
std::string mReason; // reason for the panic
|
||||
mutable std::string mWhat; // fully formatted reason
|
||||
CallStack mCallstack;
|
||||
};
|
||||
|
||||
namespace details {
|
||||
@@ -391,6 +448,7 @@ class UTILS_PUBLIC PreconditionPanic : public TPanic<PreconditionPanic> {
|
||||
// e.g.: invalid arguments
|
||||
using TPanic<PreconditionPanic>::TPanic;
|
||||
friend class TPanic<PreconditionPanic>;
|
||||
constexpr static auto type = "Precondition";
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -404,6 +462,7 @@ class UTILS_PUBLIC PostconditionPanic : public TPanic<PostconditionPanic> {
|
||||
// e.g.: dead-lock would occur, arithmetic errors
|
||||
using TPanic<PostconditionPanic>::TPanic;
|
||||
friend class TPanic<PostconditionPanic>;
|
||||
constexpr static auto type = "Postcondition";
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -417,8 +476,74 @@ class UTILS_PUBLIC ArithmeticPanic : public TPanic<ArithmeticPanic> {
|
||||
// e.g.: underflow, overflow, internal computations errors
|
||||
using TPanic<ArithmeticPanic>::TPanic;
|
||||
friend class TPanic<ArithmeticPanic>;
|
||||
constexpr static auto type = "Arithmetic";
|
||||
};
|
||||
|
||||
namespace details {
|
||||
|
||||
struct Voidify final {
|
||||
template<typename T>
|
||||
void operator&&(const T&) const&& {}
|
||||
};
|
||||
|
||||
class UTILS_PUBLIC PanicStream {
|
||||
public:
|
||||
PanicStream(
|
||||
char const* function,
|
||||
char const* file,
|
||||
int line,
|
||||
char const* message) noexcept;
|
||||
|
||||
~PanicStream();
|
||||
|
||||
PanicStream& operator<<(short value) noexcept;
|
||||
PanicStream& operator<<(unsigned short value) noexcept;
|
||||
|
||||
PanicStream& operator<<(char value) noexcept;
|
||||
PanicStream& operator<<(unsigned char value) noexcept;
|
||||
|
||||
PanicStream& operator<<(int value) noexcept;
|
||||
PanicStream& operator<<(unsigned int value) noexcept;
|
||||
|
||||
PanicStream& operator<<(long value) noexcept;
|
||||
PanicStream& operator<<(unsigned long value) noexcept;
|
||||
|
||||
PanicStream& operator<<(long long value) noexcept;
|
||||
PanicStream& operator<<(unsigned long long value) noexcept;
|
||||
|
||||
PanicStream& operator<<(float value) noexcept;
|
||||
PanicStream& operator<<(double value) noexcept;
|
||||
PanicStream& operator<<(long double value) noexcept;
|
||||
|
||||
PanicStream& operator<<(bool value) noexcept;
|
||||
|
||||
PanicStream& operator<<(const void* value) noexcept;
|
||||
|
||||
PanicStream& operator<<(const char* string) noexcept;
|
||||
PanicStream& operator<<(const unsigned char* string) noexcept;
|
||||
|
||||
PanicStream& operator<<(std::string const& s) noexcept;
|
||||
PanicStream& operator<<(std::string_view const& s) noexcept;
|
||||
|
||||
protected:
|
||||
io::sstream mStream;
|
||||
char const* mFunction;
|
||||
char const* mFile;
|
||||
int mLine;
|
||||
char const* mLiteral;
|
||||
};
|
||||
|
||||
template<typename T>
|
||||
class TPanicStream : public PanicStream {
|
||||
public:
|
||||
using PanicStream::PanicStream;
|
||||
~TPanicStream() noexcept(false) UTILS_NORETURN {
|
||||
T::panic(mFunction, mFile, mLine, mLiteral, mStream.c_str());
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace details
|
||||
|
||||
// -----------------------------------------------------------------------------------------------
|
||||
} // namespace utils
|
||||
|
||||
@@ -430,37 +555,70 @@ class UTILS_PUBLIC ArithmeticPanic : public TPanic<ArithmeticPanic> {
|
||||
# define PANIC_FUNCTION __func__
|
||||
#endif
|
||||
|
||||
|
||||
#define FILAMENT_CHECK_CONDITION_IMPL(cond) \
|
||||
switch (0) \
|
||||
case 0: \
|
||||
default: \
|
||||
UTILS_LIKELY(cond) ? (void)0 : ::utils::details::Voidify()&&
|
||||
|
||||
#define FILAMENT_PANIC_IMPL(message, TYPE) \
|
||||
::utils::details::TPanicStream<::utils::TYPE>(PANIC_FUNCTION, PANIC_FILE(__FILE__), __LINE__, message)
|
||||
|
||||
#ifndef FILAMENT_CHECK_PRECONDITION
|
||||
#define FILAMENT_CHECK_PRECONDITION(condition) \
|
||||
FILAMENT_CHECK_CONDITION_IMPL(condition) FILAMENT_PANIC_IMPL(#condition, PreconditionPanic)
|
||||
#endif
|
||||
|
||||
#ifndef FILAMENT_CHECK_POSTCONDITION
|
||||
#define FILAMENT_CHECK_POSTCONDITION(condition) \
|
||||
FILAMENT_CHECK_CONDITION_IMPL(condition) FILAMENT_PANIC_IMPL(#condition, PostconditionPanic)
|
||||
#endif
|
||||
|
||||
#ifndef FILAMENT_CHECK_ARITHMETIC
|
||||
#define FILAMENT_CHECK_ARITHMETIC(condition) \
|
||||
FILAMENT_CHECK_CONDITION_IMPL(condition) FILAMENT_PANIC_IMPL(#condition, ArithmeticPanic)
|
||||
#endif
|
||||
|
||||
#define PANIC_PRECONDITION_IMPL(cond, format, ...) \
|
||||
::utils::PreconditionPanic::panic(PANIC_FUNCTION, \
|
||||
PANIC_FILE(__FILE__), __LINE__, #cond, format, ##__VA_ARGS__)
|
||||
|
||||
#define PANIC_POSTCONDITION_IMPL(cond, format, ...) \
|
||||
::utils::PostconditionPanic::panic(PANIC_FUNCTION, \
|
||||
PANIC_FILE(__FILE__), __LINE__, #cond, format, ##__VA_ARGS__)
|
||||
|
||||
#define PANIC_ARITHMETIC_IMPL(cond, format, ...) \
|
||||
::utils::ArithmeticPanic::panic(PANIC_FUNCTION, \
|
||||
PANIC_FILE(__FILE__), __LINE__, #cond, format, ##__VA_ARGS__)
|
||||
|
||||
#define PANIC_LOG_IMPL(cond, format, ...) \
|
||||
::utils::details::panicLog(PANIC_FUNCTION, \
|
||||
PANIC_FILE(__FILE__), __LINE__, format, ##__VA_ARGS__)
|
||||
|
||||
/**
|
||||
* PANIC_PRECONDITION is a macro that reports a PreconditionPanic
|
||||
* @param format printf-style string describing the error in more details
|
||||
*/
|
||||
#define PANIC_PRECONDITION(format, ...) \
|
||||
::utils::PreconditionPanic::panic(PANIC_FUNCTION, \
|
||||
PANIC_FILE(__FILE__), __LINE__, format, ##__VA_ARGS__)
|
||||
#define PANIC_PRECONDITION(format, ...) PANIC_PRECONDITION_IMPL(format, format, ##__VA_ARGS__)
|
||||
|
||||
/**
|
||||
* PANIC_POSTCONDITION is a macro that reports a PostconditionPanic
|
||||
* @param format printf-style string describing the error in more details
|
||||
*/
|
||||
#define PANIC_POSTCONDITION(format, ...) \
|
||||
::utils::PostconditionPanic::panic(PANIC_FUNCTION, \
|
||||
PANIC_FILE(__FILE__), __LINE__, format, ##__VA_ARGS__)
|
||||
#define PANIC_POSTCONDITION(format, ...) PANIC_POSTCONDITION_IMPL(format, format, ##__VA_ARGS__)
|
||||
|
||||
/**
|
||||
* PANIC_ARITHMETIC is a macro that reports a ArithmeticPanic
|
||||
* @param format printf-style string describing the error in more details
|
||||
*/
|
||||
#define PANIC_ARITHMETIC(format, ...) \
|
||||
::utils::ArithmeticPanic::panic(PANIC_FUNCTION, \
|
||||
PANIC_FILE(__FILE__), __LINE__, format, ##__VA_ARGS__)
|
||||
#define PANIC_ARITHMETIC(format, ...) PANIC_ARITHMETIC_IMPL(format, format, ##__VA_ARGS__)
|
||||
|
||||
/**
|
||||
* PANIC_LOG is a macro that logs a Panic, and continues as usual.
|
||||
* @param format printf-style string describing the error in more details
|
||||
*/
|
||||
#define PANIC_LOG(format, ...) \
|
||||
::utils::details::panicLog(PANIC_FUNCTION, \
|
||||
PANIC_FILE(__FILE__), __LINE__, format, ##__VA_ARGS__)
|
||||
#define PANIC_LOG(format, ...) PANIC_LOG_IMPL(format, format, ##__VA_ARGS__)
|
||||
|
||||
/**
|
||||
* @ingroup errors
|
||||
@@ -471,14 +629,14 @@ class UTILS_PUBLIC ArithmeticPanic : public TPanic<ArithmeticPanic> {
|
||||
* @param format printf-style string describing the error in more details
|
||||
*/
|
||||
#define ASSERT_PRECONDITION(cond, format, ...) \
|
||||
(!UTILS_LIKELY(cond) ? PANIC_PRECONDITION(format, ##__VA_ARGS__) : (void)0)
|
||||
(!UTILS_LIKELY(cond) ? PANIC_PRECONDITION_IMPL(cond, format, ##__VA_ARGS__) : (void)0)
|
||||
|
||||
#if defined(UTILS_EXCEPTIONS) || !defined(NDEBUG)
|
||||
#define ASSERT_PRECONDITION_NON_FATAL(cond, format, ...) \
|
||||
(!UTILS_LIKELY(cond) ? PANIC_PRECONDITION(format, ##__VA_ARGS__), false : true)
|
||||
(!UTILS_LIKELY(cond) ? PANIC_PRECONDITION_IMPL(cond, format, ##__VA_ARGS__), false : true)
|
||||
#else
|
||||
#define ASSERT_PRECONDITION_NON_FATAL(cond, format, ...) \
|
||||
(!UTILS_LIKELY(cond) ? PANIC_LOG(format, ##__VA_ARGS__), false : true)
|
||||
(!UTILS_LIKELY(cond) ? PANIC_LOG_IMPL(cond, format, ##__VA_ARGS__), false : true)
|
||||
#endif
|
||||
|
||||
|
||||
@@ -499,14 +657,14 @@ class UTILS_PUBLIC ArithmeticPanic : public TPanic<ArithmeticPanic> {
|
||||
* @endcode
|
||||
*/
|
||||
#define ASSERT_POSTCONDITION(cond, format, ...) \
|
||||
(!UTILS_LIKELY(cond) ? PANIC_POSTCONDITION(format, ##__VA_ARGS__) : (void)0)
|
||||
(!UTILS_LIKELY(cond) ? PANIC_POSTCONDITION_IMPL(cond, format, ##__VA_ARGS__) : (void)0)
|
||||
|
||||
#if defined(UTILS_EXCEPTIONS) || !defined(NDEBUG)
|
||||
#define ASSERT_POSTCONDITION_NON_FATAL(cond, format, ...) \
|
||||
(!UTILS_LIKELY(cond) ? PANIC_POSTCONDITION(format, ##__VA_ARGS__), false : true)
|
||||
(!UTILS_LIKELY(cond) ? PANIC_POSTCONDITION_IMPL(cond, format, ##__VA_ARGS__), false : true)
|
||||
#else
|
||||
#define ASSERT_POSTCONDITION_NON_FATAL(cond, format, ...) \
|
||||
(!UTILS_LIKELY(cond) ? PANIC_LOG(format, ##__VA_ARGS__), false : true)
|
||||
(!UTILS_LIKELY(cond) ? PANIC_LOG_IMPL(cond, format, ##__VA_ARGS__), false : true)
|
||||
#endif
|
||||
|
||||
/**
|
||||
@@ -527,14 +685,14 @@ class UTILS_PUBLIC ArithmeticPanic : public TPanic<ArithmeticPanic> {
|
||||
* @endcode
|
||||
*/
|
||||
#define ASSERT_ARITHMETIC(cond, format, ...) \
|
||||
(!(cond) ? PANIC_ARITHMETIC(format, ##__VA_ARGS__) : (void)0)
|
||||
(!(cond) ? PANIC_ARITHMETIC_IMPL(cond, format, ##__VA_ARGS__) : (void)0)
|
||||
|
||||
#if defined(UTILS_EXCEPTIONS) || !defined(NDEBUG)
|
||||
#define ASSERT_ARITHMETIC_NON_FATAL(cond, format, ...) \
|
||||
(!UTILS_LIKELY(cond) ? PANIC_ARITHMETIC(format, ##__VA_ARGS__), false : true)
|
||||
(!UTILS_LIKELY(cond) ? PANIC_ARITHMETIC_IMPL(cond, format, ##__VA_ARGS__), false : true)
|
||||
#else
|
||||
#define ASSERT_ARITHMETIC_NON_FATAL(cond, format, ...) \
|
||||
(!UTILS_LIKELY(cond) ? PANIC_LOG(format, ##__VA_ARGS__), false : true)
|
||||
(!UTILS_LIKELY(cond) ? PANIC_LOG_IMPL(cond, format, ##__VA_ARGS__), false : true)
|
||||
#endif
|
||||
|
||||
/**
|
||||
@@ -558,6 +716,7 @@ class UTILS_PUBLIC ArithmeticPanic : public TPanic<ArithmeticPanic> {
|
||||
* }
|
||||
* @endcode
|
||||
*/
|
||||
#define ASSERT_DESTRUCTOR(cond, format, ...) (!(cond) ? PANIC_LOG(format, ##__VA_ARGS__) : (void)0)
|
||||
#define ASSERT_DESTRUCTOR(cond, format, ...) \
|
||||
(!UTILS_LIKELY(cond) ? PANIC_LOG_IMPL(cond, format, ##__VA_ARGS__) : (void)0)
|
||||
|
||||
#endif // TNT_UTILS_PANIC_H
|
||||
|
||||
@@ -0,0 +1,215 @@
|
||||
/*
|
||||
* Copyright (C) 2016 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#ifndef TNT_UTILS_PROFILER_H
|
||||
#define TNT_UTILS_PROFILER_H
|
||||
|
||||
#include <ratio>
|
||||
#include <chrono> // note: This is safe (only used inline)
|
||||
|
||||
#include <assert.h>
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
#include <string.h>
|
||||
|
||||
#if defined(__linux__)
|
||||
# include <unistd.h>
|
||||
# include <sys/ioctl.h>
|
||||
# include <linux/perf_event.h>
|
||||
#endif
|
||||
|
||||
#include <utils/compiler.h>
|
||||
|
||||
namespace utils {
|
||||
|
||||
class Profiler {
|
||||
public:
|
||||
enum {
|
||||
INSTRUCTIONS = 0, // must be zero
|
||||
CPU_CYCLES = 1,
|
||||
DCACHE_REFS = 2,
|
||||
DCACHE_MISSES = 3,
|
||||
BRANCHES = 4,
|
||||
BRANCH_MISSES = 5,
|
||||
ICACHE_REFS = 6,
|
||||
ICACHE_MISSES = 7,
|
||||
|
||||
// Must be last one
|
||||
EVENT_COUNT
|
||||
};
|
||||
|
||||
enum {
|
||||
EV_CPU_CYCLES = 1u << CPU_CYCLES,
|
||||
EV_L1D_REFS = 1u << DCACHE_REFS,
|
||||
EV_L1D_MISSES = 1u << DCACHE_MISSES,
|
||||
EV_BPU_REFS = 1u << BRANCHES,
|
||||
EV_BPU_MISSES = 1u << BRANCH_MISSES,
|
||||
EV_L1I_REFS = 1u << ICACHE_REFS,
|
||||
EV_L1I_MISSES = 1u << ICACHE_MISSES,
|
||||
// helpers
|
||||
EV_L1D_RATES = EV_L1D_REFS | EV_L1D_MISSES,
|
||||
EV_L1I_RATES = EV_L1I_REFS | EV_L1I_MISSES,
|
||||
EV_BPU_RATES = EV_BPU_REFS | EV_BPU_MISSES,
|
||||
};
|
||||
|
||||
Profiler() noexcept; // must call resetEvents()
|
||||
explicit Profiler(uint32_t eventMask) noexcept;
|
||||
~Profiler() noexcept;
|
||||
|
||||
Profiler(const Profiler& rhs) = delete;
|
||||
Profiler(Profiler&& rhs) = delete;
|
||||
Profiler& operator=(const Profiler& rhs) = delete;
|
||||
Profiler& operator=(Profiler&& rhs) = delete;
|
||||
|
||||
// selects which events are enabled.
|
||||
uint32_t resetEvents(uint32_t eventMask) noexcept;
|
||||
|
||||
uint32_t getEnabledEvents() const noexcept { return mEnabledEvents; }
|
||||
|
||||
// could return false if performance counters are not supported/enabled
|
||||
bool isValid() const { return mCountersFd[0] >= 0; }
|
||||
|
||||
class Counters {
|
||||
friend class Profiler;
|
||||
|
||||
uint64_t nr;
|
||||
uint64_t time_enabled;
|
||||
uint64_t time_running;
|
||||
struct {
|
||||
uint64_t value;
|
||||
uint64_t id;
|
||||
} counters[EVENT_COUNT];
|
||||
|
||||
friend Counters operator-(Counters lhs, const Counters& rhs) noexcept {
|
||||
lhs.nr -= rhs.nr;
|
||||
lhs.time_enabled -= rhs.time_enabled;
|
||||
lhs.time_running -= rhs.time_running;
|
||||
for (size_t i = 0; i < EVENT_COUNT; ++i) {
|
||||
lhs.counters[i].value -= rhs.counters[i].value;
|
||||
}
|
||||
return lhs;
|
||||
}
|
||||
|
||||
public:
|
||||
uint64_t getInstructions() const { return counters[INSTRUCTIONS].value; }
|
||||
uint64_t getCpuCycles() const { return counters[CPU_CYCLES].value; }
|
||||
uint64_t getL1DReferences() const { return counters[DCACHE_REFS].value; }
|
||||
uint64_t getL1DMisses() const { return counters[DCACHE_MISSES].value; }
|
||||
uint64_t getL1IReferences() const { return counters[ICACHE_REFS].value; }
|
||||
uint64_t getL1IMisses() const { return counters[ICACHE_MISSES].value; }
|
||||
uint64_t getBranchInstructions() const { return counters[BRANCHES].value; }
|
||||
uint64_t getBranchMisses() const { return counters[BRANCH_MISSES].value; }
|
||||
|
||||
std::chrono::duration<uint64_t, std::nano> getWallTime() const {
|
||||
return std::chrono::duration<uint64_t, std::nano>(time_enabled);
|
||||
}
|
||||
|
||||
std::chrono::duration<uint64_t, std::nano> getRunningTime() const {
|
||||
return std::chrono::duration<uint64_t, std::nano>(time_running);
|
||||
}
|
||||
|
||||
double getIPC() const noexcept {
|
||||
uint64_t cpuCycles = getCpuCycles();
|
||||
uint64_t instructions = getInstructions();
|
||||
return double(instructions) / double(cpuCycles);
|
||||
}
|
||||
|
||||
double getCPI() const noexcept {
|
||||
uint64_t cpuCycles = getCpuCycles();
|
||||
uint64_t instructions = getInstructions();
|
||||
return double(cpuCycles) / double(instructions);
|
||||
}
|
||||
|
||||
double getL1DMissRate() const noexcept {
|
||||
uint64_t cacheReferences = getL1DReferences();
|
||||
uint64_t cacheMisses = getL1DMisses();
|
||||
return double(cacheMisses) / double(cacheReferences);
|
||||
}
|
||||
|
||||
double getL1DHitRate() const noexcept {
|
||||
return 1.0 - getL1DMissRate();
|
||||
}
|
||||
|
||||
double getL1IMissRate() const noexcept {
|
||||
uint64_t cacheReferences = getL1IReferences();
|
||||
uint64_t cacheMisses = getL1IMisses();
|
||||
return double(cacheMisses) / double(cacheReferences);
|
||||
}
|
||||
|
||||
double getL1IHitRate() const noexcept {
|
||||
return 1.0 - getL1IMissRate();
|
||||
}
|
||||
|
||||
double getBranchMissRate() const noexcept {
|
||||
uint64_t branchReferences = getBranchInstructions();
|
||||
uint64_t branchMisses = getBranchMisses();
|
||||
return double(branchMisses) / double(branchReferences);
|
||||
}
|
||||
|
||||
double getBranchHitRate() const noexcept {
|
||||
return 1.0 - getBranchMissRate();
|
||||
}
|
||||
|
||||
double getMPKI(uint64_t misses) const noexcept {
|
||||
return (misses * 1000.0) / getInstructions();
|
||||
}
|
||||
};
|
||||
|
||||
#if defined(__linux__)
|
||||
|
||||
void reset() noexcept {
|
||||
int fd = mCountersFd[0];
|
||||
ioctl(fd, PERF_EVENT_IOC_RESET, PERF_IOC_FLAG_GROUP);
|
||||
}
|
||||
|
||||
void start() noexcept {
|
||||
int fd = mCountersFd[0];
|
||||
ioctl(fd, PERF_EVENT_IOC_ENABLE, PERF_IOC_FLAG_GROUP);
|
||||
}
|
||||
|
||||
void stop() noexcept {
|
||||
int fd = mCountersFd[0];
|
||||
ioctl(fd, PERF_EVENT_IOC_DISABLE, PERF_IOC_FLAG_GROUP);
|
||||
}
|
||||
|
||||
Counters readCounters() noexcept;
|
||||
|
||||
#else // !__linux__
|
||||
|
||||
void reset() noexcept { }
|
||||
void start() noexcept { }
|
||||
void stop() noexcept { }
|
||||
Counters readCounters() noexcept { return {}; }
|
||||
|
||||
#endif // __linux__
|
||||
|
||||
bool hasBranchRates() const noexcept {
|
||||
return (mCountersFd[BRANCHES] >= 0) && (mCountersFd[BRANCH_MISSES] >= 0);
|
||||
}
|
||||
|
||||
bool hasICacheRates() const noexcept {
|
||||
return (mCountersFd[ICACHE_REFS] >= 0) && (mCountersFd[ICACHE_MISSES] >= 0);
|
||||
}
|
||||
|
||||
private:
|
||||
UTILS_UNUSED uint8_t mIds[EVENT_COUNT] = {};
|
||||
int mCountersFd[EVENT_COUNT];
|
||||
uint32_t mEnabledEvents = 0;
|
||||
};
|
||||
|
||||
} // namespace utils
|
||||
|
||||
#endif // TNT_UTILS_PROFILER_H
|
||||
@@ -0,0 +1,185 @@
|
||||
/*
|
||||
* Copyright (C) 2022 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#ifndef TNT_UTILS_QUADTREE_H
|
||||
#define TNT_UTILS_QUADTREE_H
|
||||
|
||||
#include <utils/debug.h>
|
||||
|
||||
#include <array>
|
||||
#include <type_traits>
|
||||
|
||||
#include <assert.h>
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
namespace utils {
|
||||
|
||||
namespace QuadTreeUtils {
|
||||
|
||||
/**
|
||||
* 16-bits morton encoding
|
||||
* @param x 8-bits horizontal coordinate
|
||||
* @param y 8-bits vertical coordinate
|
||||
* @return morton encoding of (x,y)
|
||||
*/
|
||||
static inline constexpr uint16_t morton(uint8_t x, uint8_t y) noexcept {
|
||||
uint32_t r = x | (uint32_t(y) << 16);
|
||||
r = (r | (r << 4u)) & 0x0f0f0f0fu;
|
||||
r = (r | (r << 2u)) & 0x33333333u;
|
||||
r = (r | (r << 1u)) & 0x55555555u;
|
||||
return uint16_t(r | (r >> 15u));
|
||||
}
|
||||
|
||||
/**
|
||||
* size of a quad-tree of height `height`
|
||||
* @param height height of the Quad-tree
|
||||
* @return the number of elements in the tree
|
||||
*/
|
||||
static inline constexpr size_t size(size_t height) noexcept {
|
||||
return morton(uint8_t((1u << height) - 1u), 0u);
|
||||
}
|
||||
|
||||
/**
|
||||
* Index in the QuadTreeArray of a Quad-tree node referenced by its height and code
|
||||
* @param l height of the node
|
||||
* @param code morton code of the node
|
||||
* @return index in the QuadTreeArray of this node
|
||||
*/
|
||||
static inline constexpr size_t index(size_t l, size_t code) noexcept {
|
||||
return size(l) + code;
|
||||
}
|
||||
|
||||
/**
|
||||
* Index in the QuadTreeArray of the parent of the specified node
|
||||
* @param l height of the node
|
||||
* @param code morton code of the node
|
||||
* @return index in the QuadTreeArray of this node's parent
|
||||
*/
|
||||
static inline constexpr size_t parent(size_t l, size_t code) noexcept {
|
||||
assert_invariant(l > 0);
|
||||
return index(l - 1u, code >> 2u);
|
||||
}
|
||||
|
||||
// integrated unit-tests!
|
||||
static_assert(size(0) == 0);
|
||||
static_assert(size(1) == 1);
|
||||
static_assert(size(2) == 5);
|
||||
static_assert(size(3) == 21);
|
||||
static_assert(size(4) == 85);
|
||||
static_assert(size(5) == 341);
|
||||
static_assert(size(6) == 1365);
|
||||
static_assert(size(7) == 5461);
|
||||
|
||||
} // namespace QuadTreeUtils
|
||||
|
||||
/**
|
||||
* A Quad-tree encoded as an array.
|
||||
* @tparam T Type of the quad-tree nodes
|
||||
* @tparam HEIGHT Height of the quad-tree
|
||||
*/
|
||||
template<typename T, size_t HEIGHT>
|
||||
class QuadTreeArray : public std::array<T, QuadTreeUtils::size(HEIGHT)> {
|
||||
static_assert(HEIGHT <= 7, "QuadTreeArray height must be <= 7 (16-bits morton)");
|
||||
|
||||
// Simple fixed capacity stack
|
||||
template<typename TYPE, size_t CAPACITY,
|
||||
typename = std::enable_if_t<std::is_trivial_v<TYPE>>>
|
||||
class stack {
|
||||
TYPE mElements[CAPACITY];
|
||||
size_t mSize = 0;
|
||||
public:
|
||||
bool empty() const noexcept { return mSize == 0; }
|
||||
void push(TYPE const& v) noexcept {
|
||||
assert_invariant(mSize < CAPACITY);
|
||||
mElements[mSize++] = v;
|
||||
}
|
||||
void pop() noexcept {
|
||||
assert_invariant(mSize > 0);
|
||||
--mSize;
|
||||
}
|
||||
const TYPE& back() const noexcept {
|
||||
return mElements[mSize - 1];
|
||||
}
|
||||
};
|
||||
|
||||
public:
|
||||
// code_t needs to be able to encode the # of entries for the largest level supported
|
||||
// the tree. With 7 levels, the largest one as 4096 entries, 0 to 4095 so 12 bits suffice.
|
||||
using code_t = uint16_t;
|
||||
|
||||
struct NodeId {
|
||||
int8_t l : 4; // height of the node or -1 if invalid
|
||||
code_t code : 12; // morton code of the node
|
||||
static_assert(12 >= (HEIGHT - 1) * 2);
|
||||
};
|
||||
|
||||
enum class TraversalResult {
|
||||
EXIT, // end traversal
|
||||
RECURSE, // proceed with the children
|
||||
SKIP_CHILDREN // skip children
|
||||
};
|
||||
|
||||
static inline constexpr size_t height() noexcept {
|
||||
return HEIGHT;
|
||||
}
|
||||
|
||||
/**
|
||||
* non-recursive depth-first traversal
|
||||
*
|
||||
* @tparam Process closure to process each visited node
|
||||
* @param l height of the node to start with
|
||||
* @param code code of the node to start with
|
||||
* @param h maximum height to visit, must be < height()
|
||||
* @param process closure to process each visited node
|
||||
*/
|
||||
template<typename Process,
|
||||
typename = std::enable_if_t<
|
||||
std::is_invocable_r_v<TraversalResult, Process, NodeId>>>
|
||||
static void traverse(int8_t l, code_t code, size_t maxHeight, Process&& process) noexcept {
|
||||
assert_invariant(maxHeight < height());
|
||||
const int8_t h = int8_t(maxHeight);
|
||||
stack<NodeId, 4 * height()> stack;
|
||||
stack.push({ l, code });
|
||||
while (!stack.empty()) {
|
||||
NodeId curr = stack.back();
|
||||
stack.pop();
|
||||
TraversalResult r = process(curr);
|
||||
if (r == TraversalResult::EXIT) {
|
||||
break;
|
||||
}
|
||||
if (r == TraversalResult::RECURSE && curr.l < h) {
|
||||
for (size_t c = 0; c < 4; c++) {
|
||||
stack.push({
|
||||
int8_t(curr.l + 1u),
|
||||
code_t((curr.code << 2u) | (3u - c))
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
template<typename Node,
|
||||
typename = std::enable_if_t<
|
||||
std::is_invocable_r_v<TraversalResult, Node, NodeId>>>
|
||||
static void traverse(int8_t l, code_t code, Node&& process) noexcept {
|
||||
traverse(l, code, height() - 1, std::forward<Node>(process));
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace utils
|
||||
|
||||
#endif //TNT_UTILS_QUADTREE_H
|
||||
@@ -0,0 +1,88 @@
|
||||
/*
|
||||
* Copyright (C) 2018 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#ifndef TNT_UTILS_RANGE_H
|
||||
#define TNT_UTILS_RANGE_H
|
||||
|
||||
#include <iterator>
|
||||
|
||||
#include <stddef.h>
|
||||
|
||||
namespace utils {
|
||||
|
||||
template<typename T>
|
||||
struct Range {
|
||||
using value_type = T;
|
||||
T first = 0;
|
||||
T last = 0; // this actually refers to one past the last
|
||||
|
||||
size_t size() const noexcept { return last - first; }
|
||||
bool empty() const noexcept { return !size(); }
|
||||
bool contains(const T& t) const noexcept { return first <= t && t < last; }
|
||||
|
||||
bool overlaps(const Range<T>& that) const noexcept {
|
||||
return (that.first < this->last) && (that.last > this->first);
|
||||
}
|
||||
|
||||
class const_iterator {
|
||||
friend struct Range;
|
||||
T value = {};
|
||||
|
||||
public:
|
||||
const_iterator() noexcept = default;
|
||||
explicit const_iterator(T value) noexcept : value(value) {}
|
||||
|
||||
using value_type = T;
|
||||
using pointer = value_type*;
|
||||
using difference_type = ptrdiff_t;
|
||||
using iterator_category = std::random_access_iterator_tag;
|
||||
|
||||
|
||||
const value_type operator*() const { return value; }
|
||||
const value_type operator[](size_t n) const { return value + n; }
|
||||
|
||||
const_iterator& operator++() { ++value; return *this; }
|
||||
const_iterator& operator--() { --value; return *this; }
|
||||
|
||||
const const_iterator operator++(int) { const_iterator t(value); value++; return t; }
|
||||
const const_iterator operator--(int) { const_iterator t(value); value--; return t; }
|
||||
|
||||
const_iterator operator+(size_t rhs) const { return { value + rhs }; }
|
||||
const_iterator operator+(size_t rhs) { return { value + rhs }; }
|
||||
const_iterator operator-(size_t rhs) const { return { value - rhs }; }
|
||||
|
||||
difference_type operator-(const_iterator const& rhs) const { return value - rhs.value; }
|
||||
|
||||
bool operator==(const_iterator const& rhs) const { return (value == rhs.value); }
|
||||
bool operator!=(const_iterator const& rhs) const { return (value != rhs.value); }
|
||||
bool operator>=(const_iterator const& rhs) const { return (value >= rhs.value); }
|
||||
bool operator> (const_iterator const& rhs) const { return (value > rhs.value); }
|
||||
bool operator<=(const_iterator const& rhs) const { return (value <= rhs.value); }
|
||||
bool operator< (const_iterator const& rhs) const { return (value < rhs.value); }
|
||||
};
|
||||
|
||||
const_iterator begin() noexcept { return const_iterator{ first }; }
|
||||
const_iterator end() noexcept { return const_iterator{ last }; }
|
||||
const_iterator begin() const noexcept { return const_iterator{ first }; }
|
||||
const_iterator end() const noexcept { return const_iterator{ last }; }
|
||||
|
||||
const_iterator front() const noexcept { return const_iterator{ first }; }
|
||||
const_iterator back() const noexcept { return const_iterator{ last - 1 }; }
|
||||
};
|
||||
|
||||
} // namespace utils
|
||||
|
||||
#endif // TNT_UTILS_RANGE_H
|
||||
@@ -0,0 +1,312 @@
|
||||
/*
|
||||
* Copyright (C) 2022 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#ifndef TNT_UTILS_RANGEMAP_H
|
||||
#define TNT_UTILS_RANGEMAP_H
|
||||
|
||||
#include <utils/Panic.h>
|
||||
#include <utils/Range.h>
|
||||
#include <utils/debug.h>
|
||||
|
||||
#include <map>
|
||||
#include <utility>
|
||||
|
||||
#include <stddef.h>
|
||||
|
||||
namespace utils {
|
||||
|
||||
/**
|
||||
* Sparse container for a series of ordered non-overlapping intervals.
|
||||
*
|
||||
* RangeMap has a low memory footprint if it contains fairly homogeneous data. Internally, the
|
||||
* intervals are automatically split and merged as elements are added or removed.
|
||||
*
|
||||
* Each interval maps to an instance of ValueType, which should support cheap equality checks
|
||||
* and copy assignment. (simple concrete types are ideal)
|
||||
*
|
||||
* KeyType should support operator< because intervals are internally sorted using std::map.
|
||||
*/
|
||||
template<typename KeyType, typename ValueType>
|
||||
class RangeMap {
|
||||
public:
|
||||
/**
|
||||
* Replaces all slots between first (inclusive) and last (exclusive).
|
||||
*/
|
||||
void add(KeyType first, KeyType last, const ValueType& value) noexcept {
|
||||
// First check if an existing range contains "first".
|
||||
Iterator iter = findRange(first);
|
||||
if (iter != end()) {
|
||||
const Range<KeyType> existing = getRange(iter);
|
||||
// Check if the existing range be extended.
|
||||
if (getValue(iter) == value) {
|
||||
if (existing.last < last) {
|
||||
wipe(existing.last, last);
|
||||
iter = shrink(iter, existing.first, last);
|
||||
mergeRight(iter);
|
||||
}
|
||||
return;
|
||||
}
|
||||
// Split the existing range into two ranges.
|
||||
if (last < existing.last && first > existing.first) {
|
||||
iter = shrink(iter, existing.first, first);
|
||||
insert(first, last, value);
|
||||
insert(last, existing.last, getValue(iter));
|
||||
return;
|
||||
}
|
||||
clear(first, last);
|
||||
insert(first, last, value);
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if an existing range contains the end of the new range.
|
||||
KeyType back = last;
|
||||
iter = findRange(--back);
|
||||
if (iter == end()) {
|
||||
wipe(first, last);
|
||||
insert(first, last, value);
|
||||
return;
|
||||
}
|
||||
const Range<KeyType> existing = getRange(iter);
|
||||
|
||||
// Check if the existing range be extended.
|
||||
if (getValue(iter) == value) {
|
||||
if (existing.first > first) {
|
||||
wipe(first, existing.first);
|
||||
iter = shrink(iter, first, existing.last);
|
||||
mergeLeft(iter);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Clip the beginning of the existing range and potentially remove it.
|
||||
if (last < existing.last) {
|
||||
shrink(iter, last, existing.last);
|
||||
}
|
||||
wipe(first, last);
|
||||
insert(first, last, value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Shorthand for the "add" method that inserts a single element.
|
||||
*/
|
||||
void set(KeyType key, const ValueType& value) noexcept {
|
||||
KeyType begin = key;
|
||||
add(begin, ++key, value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if a range exists that encompasses the given key.
|
||||
*/
|
||||
bool has(KeyType key) const noexcept {
|
||||
return findRange(key) != mMap.end();
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves the element at the given location, panics if no element exists.
|
||||
*/
|
||||
const ValueType& get(KeyType key) const {
|
||||
ConstIterator iter = findRange(key);
|
||||
FILAMENT_CHECK_PRECONDITION(iter != end())
|
||||
<< "RangeMap: No element exists at the given key.";
|
||||
return getValue(iter);
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes all elements between begin (inclusive) and end (exclusive).
|
||||
*/
|
||||
void clear(KeyType first, KeyType last) noexcept {
|
||||
// Check if an existing range contains "first".
|
||||
Iterator iter = findRange(first);
|
||||
if (iter != end()) {
|
||||
const Range<KeyType> existing = getRange(iter);
|
||||
// Split the existing range into two ranges.
|
||||
if (last < existing.last && first > existing.first) {
|
||||
iter = shrink(iter, existing.first, first);
|
||||
insert(last, existing.last, getValue(iter));
|
||||
return;
|
||||
}
|
||||
// Clip one of the ends of the existing range or remove it.
|
||||
if (first > existing.first) {
|
||||
shrink(iter, existing.first, first);
|
||||
} else if (last < existing.last) {
|
||||
shrink(iter, last, existing.last);
|
||||
} else {
|
||||
wipe(first, last);
|
||||
}
|
||||
// There might be another range that intersects the cleared range, so try again.
|
||||
clear(first, last);
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if an existing range contains the end of the new range.
|
||||
KeyType back = last;
|
||||
iter = findRange(--back);
|
||||
if (iter == end()) {
|
||||
wipe(first, last);
|
||||
return;
|
||||
}
|
||||
const Range<KeyType> existing = getRange(iter);
|
||||
|
||||
// Clip the beginning of the existing range and potentially remove it.
|
||||
if (last < existing.last) {
|
||||
shrink(iter, last, existing.last);
|
||||
}
|
||||
wipe(first, last);
|
||||
}
|
||||
|
||||
/**
|
||||
* Shorthand for the "clear" method that clears a single element.
|
||||
*/
|
||||
void reset(KeyType key) noexcept {
|
||||
KeyType begin = key;
|
||||
clear(begin, ++key);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the number of internal interval objects (rarely used).
|
||||
*/
|
||||
size_t rangeCount() const noexcept { return mMap.size(); }
|
||||
|
||||
private:
|
||||
|
||||
using Map = std::map<KeyType, std::pair<Range<KeyType>, ValueType>>;
|
||||
using Iterator = typename Map::iterator;
|
||||
using ConstIterator = typename Map::const_iterator;
|
||||
|
||||
ConstIterator begin() const noexcept { return mMap.begin(); }
|
||||
ConstIterator end() const noexcept { return mMap.end(); }
|
||||
|
||||
Iterator begin() noexcept { return mMap.begin(); }
|
||||
Iterator end() noexcept { return mMap.end(); }
|
||||
|
||||
Range<KeyType>& getRange(Iterator iter) const { return iter->second.first; }
|
||||
ValueType& getValue(Iterator iter) const { return iter->second.second; }
|
||||
|
||||
const Range<KeyType>& getRange(ConstIterator iter) const { return iter->second.first; }
|
||||
const ValueType& getValue(ConstIterator iter) const { return iter->second.second; }
|
||||
|
||||
// Private helper that assumes there is no existing range that overlaps the given range.
|
||||
void insert(KeyType first, KeyType last, const ValueType& value) noexcept {
|
||||
assert_invariant(!has(first));
|
||||
assert_invariant(!has(last - 1));
|
||||
|
||||
// Check if there is an adjacent range to the left than can be extended.
|
||||
KeyType previous = first;
|
||||
if (Iterator iter = findRange(--previous); iter != end() && getValue(iter) == value) {
|
||||
getRange(iter).last = last;
|
||||
mergeRight(iter);
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if there is an adjacent range to the right than can be extended.
|
||||
if (Iterator iter = findRange(last); iter != end() && getValue(iter) == value) {
|
||||
getRange(iter).first = first;
|
||||
return;
|
||||
}
|
||||
|
||||
mMap[first] = {Range<KeyType> { first, last }, value};
|
||||
}
|
||||
|
||||
// Private helper that erases all intervals that are wholly contained within the given range.
|
||||
// Note that this is quite different from the public "clear" method.
|
||||
void wipe(KeyType first, KeyType last) noexcept {
|
||||
// Find the first range whose beginning is greater than or equal to "first".
|
||||
Iterator iter = mMap.lower_bound(first);
|
||||
while (iter != end() && getRange(iter).first < last) {
|
||||
KeyType existing_last = getRange(iter).last;
|
||||
if (existing_last > last) {
|
||||
break;
|
||||
}
|
||||
iter = mMap.erase(iter);
|
||||
}
|
||||
}
|
||||
|
||||
// Checks if there is range to the right that touches the given range.
|
||||
// If so, erases it, extends the given range rightwards, and returns true.
|
||||
bool mergeRight(Iterator iter) {
|
||||
Iterator next = iter;
|
||||
if (++next == end() || getValue(next) != getValue(iter)) {
|
||||
return false;
|
||||
}
|
||||
if (getRange(next).first != getRange(iter).last) {
|
||||
return false;
|
||||
}
|
||||
getRange(iter).last = getRange(next).last;
|
||||
mMap.erase(next);
|
||||
return true;
|
||||
}
|
||||
|
||||
// Checks if there is range to the left that touches the given range.
|
||||
// If so, erases it, extends the given range leftwards, and returns true.
|
||||
bool mergeLeft(Iterator iter) {
|
||||
Iterator prev = iter;
|
||||
if (--prev == end() || getValue(prev) != getValue(iter)) {
|
||||
return false;
|
||||
}
|
||||
if (getRange(prev).last != getRange(iter).first) {
|
||||
return false;
|
||||
}
|
||||
getRange(iter).first = getRange(prev).first;
|
||||
mMap.erase(prev);
|
||||
return true;
|
||||
}
|
||||
|
||||
// Private helper that clips one end of an existing range.
|
||||
Iterator shrink(Iterator iter, KeyType first, KeyType last) {
|
||||
assert_invariant(first < last);
|
||||
assert_invariant(getRange(iter).first == first || getRange(iter).last == last);
|
||||
std::pair<Range<KeyType>, ValueType> value = {{first, last}, iter->second.second};
|
||||
mMap.erase(iter);
|
||||
return mMap.insert({first, value}).first;
|
||||
}
|
||||
|
||||
// If the given key is encompassed by an existing range, returns an iterator for that range.
|
||||
// If no encompassing range exists, returns end().
|
||||
ConstIterator findRange(KeyType key) const noexcept {
|
||||
return findRangeT<ConstIterator>(*this, key);
|
||||
}
|
||||
|
||||
// If the given key is encompassed by an existing range, returns an iterator for that range.
|
||||
// If no encompassing range exists, returns end().
|
||||
Iterator findRange(KeyType key) noexcept {
|
||||
return findRangeT<Iterator>(*this, key);
|
||||
}
|
||||
|
||||
// This template method allows us to avoid code duplication for const and non-const variants of
|
||||
// findRange. C++17 has "std::as_const()" but that would not be helpful here, as we would still
|
||||
// need to convert a const iterator to a non-const iterator.
|
||||
template<typename IteratorType, typename SelfType>
|
||||
static IteratorType findRangeT(SelfType& instance, KeyType key) noexcept {
|
||||
// Find the first range whose beginning is greater than or equal to the given key.
|
||||
IteratorType iter = instance.mMap.lower_bound(key);
|
||||
if (iter != instance.end() && instance.getRange(iter).contains(key)) {
|
||||
return iter;
|
||||
}
|
||||
// If that was the first range, or if the map is empty, return false.
|
||||
if (iter == instance.begin()) {
|
||||
return instance.end();
|
||||
}
|
||||
// Check the range immediately previous to the one that was found.
|
||||
return instance.getRange(--iter).contains(key) ? iter : instance.end();
|
||||
}
|
||||
|
||||
// This maps from the start value of each range to the range itself.
|
||||
Map mMap;
|
||||
};
|
||||
|
||||
} // namespace utils
|
||||
|
||||
#endif // TNT_UTILS_RANGEMAP_H
|
||||
@@ -108,7 +108,7 @@ public:
|
||||
return getComponentCount() == 0;
|
||||
}
|
||||
|
||||
utils::Entity const* getEntities() const noexcept {
|
||||
Entity const* getEntities() const noexcept {
|
||||
return data<ENTITY_INDEX>() + 1;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
/*
|
||||
* Copyright (C) 2022 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#ifndef TNT_UTILS_STOPWATCH_H
|
||||
#define TNT_UTILS_STOPWATCH_H
|
||||
|
||||
#include <utils/Log.h>
|
||||
#include <utils/ostream.h>
|
||||
|
||||
#include <chrono>
|
||||
#include <limits>
|
||||
#include <ratio>
|
||||
|
||||
#include <stddef.h>
|
||||
|
||||
namespace utils {
|
||||
|
||||
/*
|
||||
* A very basic Stopwatch class
|
||||
*/
|
||||
|
||||
template<typename Clock = std::chrono::steady_clock>
|
||||
class Stopwatch {
|
||||
public:
|
||||
using duration = typename Clock::duration;
|
||||
using time_point = typename Clock::time_point;
|
||||
|
||||
private:
|
||||
time_point mStart;
|
||||
duration mMinLap = std::numeric_limits<duration>::max();
|
||||
duration mMaxLap{};
|
||||
std::chrono::duration<double, std::nano> mAvgLap{};
|
||||
size_t mCount = 0;
|
||||
const char* mName = nullptr;
|
||||
|
||||
public:
|
||||
// Create a Stopwatch with a name and clock
|
||||
explicit Stopwatch(const char* name) noexcept: mName(name) {}
|
||||
|
||||
// Logs min/avg/max lap time
|
||||
~Stopwatch() noexcept;
|
||||
|
||||
// start the stopwatch
|
||||
inline void start() noexcept {
|
||||
mStart = Clock::now();
|
||||
}
|
||||
|
||||
// stop the stopwatch
|
||||
inline void stop() noexcept {
|
||||
auto d = Clock::now() - mStart;
|
||||
mMinLap = std::min(mMinLap, d);
|
||||
mMaxLap = std::max(mMaxLap, d);
|
||||
mAvgLap = (mAvgLap * mCount + d) / (mCount + 1);
|
||||
mCount++;
|
||||
}
|
||||
|
||||
// get the minimum lap time recorded
|
||||
duration getMinLapTime() const noexcept { return mMinLap; }
|
||||
|
||||
// get the maximum lap time recorded
|
||||
duration getMaxLapTime() const noexcept { return mMaxLap; }
|
||||
|
||||
// get the average lap time
|
||||
duration getAverageLapTime() const noexcept { return mAvgLap; }
|
||||
};
|
||||
|
||||
template<typename Clock>
|
||||
Stopwatch<Clock>::~Stopwatch() noexcept {
|
||||
slog.d << "Stopwatch \"" << mName << "\" : ["
|
||||
<< mMinLap.count() << ", "
|
||||
<< std::chrono::duration_cast<duration>(mAvgLap).count() << ", "
|
||||
<< mMaxLap.count() << "] ns" << io::endl;
|
||||
}
|
||||
|
||||
/*
|
||||
* AutoStopwatch can be used to start and stop a Stopwatch automatically
|
||||
* when entering and exiting a scope.
|
||||
*/
|
||||
template<typename Stopwatch>
|
||||
class AutoStopwatch {
|
||||
Stopwatch& stopwatch;
|
||||
public:
|
||||
inline explicit AutoStopwatch(Stopwatch& stopwatch) noexcept: stopwatch(stopwatch) {
|
||||
stopwatch.start();
|
||||
}
|
||||
|
||||
inline ~AutoStopwatch() noexcept { stopwatch.stop(); }
|
||||
};
|
||||
|
||||
} // namespace utils
|
||||
|
||||
#endif // TNT_UTILS_STOPWATCH_H
|
||||
@@ -130,7 +130,7 @@ public:
|
||||
friend class IteratorValueRef;
|
||||
friend iterator;
|
||||
friend const_iterator;
|
||||
using Type = std::tuple<typename std::decay<Elements>::type...>;
|
||||
using Type = std::tuple<std::decay_t<Elements>...>;
|
||||
Type elements;
|
||||
|
||||
template<size_t ... Is>
|
||||
@@ -368,7 +368,7 @@ public:
|
||||
size_t last = mSize++;
|
||||
// Fold expression on the comma operator
|
||||
([&]{
|
||||
new(std::get<Indices>(mArrays) + last) Elements{std::get<Indices>(args)};
|
||||
new(std::get<Indices>(mArrays) + last) Elements{std::get<Indices>(std::forward<Structure>(args))};
|
||||
}() , ...);
|
||||
}
|
||||
|
||||
@@ -513,7 +513,7 @@ public:
|
||||
return (soa.elementAt<E>(i) = other);
|
||||
}
|
||||
UTILS_ALWAYS_INLINE Type const& operator = (Type&& other) noexcept {
|
||||
return (soa.elementAt<E>(i) = other);
|
||||
return (soa.elementAt<E>(i) = std::forward<Type>(other));
|
||||
}
|
||||
// comparisons
|
||||
UTILS_ALWAYS_INLINE bool operator==(Type const& other) const {
|
||||
@@ -535,22 +535,22 @@ public:
|
||||
|
||||
private:
|
||||
template<std::size_t I = 0, typename FuncT, typename... Tp>
|
||||
inline typename std::enable_if<I == sizeof...(Tp), void>::type
|
||||
inline std::enable_if_t<I == sizeof...(Tp), void>
|
||||
for_each(std::tuple<Tp...>&, FuncT) {}
|
||||
|
||||
template<std::size_t I = 0, typename FuncT, typename... Tp>
|
||||
inline typename std::enable_if<I < sizeof...(Tp), void>::type
|
||||
inline std::enable_if_t<I < sizeof...(Tp), void>
|
||||
for_each(std::tuple<Tp...>& t, FuncT f) {
|
||||
f(I, std::get<I>(t));
|
||||
for_each<I + 1, FuncT, Tp...>(t, f);
|
||||
}
|
||||
|
||||
template<std::size_t I = 0, typename FuncT, typename... Tp>
|
||||
inline typename std::enable_if<I == sizeof...(Tp), void>::type
|
||||
inline std::enable_if_t<I == sizeof...(Tp), void>
|
||||
for_each_index(std::tuple<Tp...>&, FuncT) {}
|
||||
|
||||
template<std::size_t I = 0, typename FuncT, typename... Tp>
|
||||
inline typename std::enable_if<I < sizeof...(Tp), void>::type
|
||||
inline std::enable_if_t<I < sizeof...(Tp), void>
|
||||
for_each_index(std::tuple<Tp...>& t, FuncT f) {
|
||||
f.template operator()<I>(std::get<I>(t));
|
||||
for_each_index<I + 1, FuncT, Tp...>(t, f);
|
||||
@@ -597,7 +597,7 @@ private:
|
||||
|
||||
void construct_each(size_t from, size_t to) noexcept {
|
||||
forEach([from, to](auto p) {
|
||||
using T = typename std::decay<decltype(*p)>::type;
|
||||
using T = std::decay_t<decltype(*p)>;
|
||||
// note: scalar types like int/float get initialized to zero
|
||||
if constexpr (!std::is_trivially_default_constructible_v<T>) {
|
||||
for (size_t i = from; i < to; i++) {
|
||||
@@ -609,7 +609,7 @@ private:
|
||||
|
||||
void destroy_each(size_t from, size_t to) noexcept {
|
||||
forEach([from, to](auto p) {
|
||||
using T = typename std::decay<decltype(*p)>::type;
|
||||
using T = std::decay_t<decltype(*p)>;
|
||||
if constexpr (!std::is_trivially_destructible_v<T>) {
|
||||
for (size_t i = from; i < to; i++) {
|
||||
p[i].~T();
|
||||
@@ -624,7 +624,7 @@ private:
|
||||
if (mSize) {
|
||||
auto size = mSize; // placate a compiler warning
|
||||
forEach([buffer, &index, &offsets, size](auto p) {
|
||||
using T = typename std::decay<decltype(*p)>::type;
|
||||
using T = std::decay_t<decltype(*p)>;
|
||||
T* UTILS_RESTRICT b = static_cast<T*>(buffer);
|
||||
|
||||
// go through each element and move them from the old array to the new
|
||||
@@ -671,7 +671,7 @@ template<typename Allocator, typename... Elements>
|
||||
inline
|
||||
typename StructureOfArraysBase<Allocator, Elements...>::IteratorValueRef&
|
||||
StructureOfArraysBase<Allocator, Elements...>::IteratorValueRef::operator=(
|
||||
StructureOfArraysBase::IteratorValueRef const& rhs) {
|
||||
IteratorValueRef const& rhs) {
|
||||
return operator=(IteratorValue(rhs));
|
||||
}
|
||||
|
||||
@@ -679,7 +679,7 @@ template<typename Allocator, typename... Elements>
|
||||
inline
|
||||
typename StructureOfArraysBase<Allocator, Elements...>::IteratorValueRef&
|
||||
StructureOfArraysBase<Allocator, Elements...>::IteratorValueRef::operator=(
|
||||
StructureOfArraysBase::IteratorValueRef&& rhs) noexcept {
|
||||
IteratorValueRef&& rhs) noexcept {
|
||||
return operator=(IteratorValue(rhs));
|
||||
}
|
||||
|
||||
@@ -688,7 +688,7 @@ template<size_t... Is>
|
||||
inline
|
||||
typename StructureOfArraysBase<Allocator, Elements...>::IteratorValueRef&
|
||||
StructureOfArraysBase<Allocator, Elements...>::IteratorValueRef::assign(
|
||||
StructureOfArraysBase::IteratorValue const& rhs, std::index_sequence<Is...>) {
|
||||
IteratorValue const& rhs, std::index_sequence<Is...>) {
|
||||
// implements IteratorValueRef& IteratorValueRef::operator=(IteratorValue const& rhs)
|
||||
auto UTILS_UNUSED l = { (soa->elementAt<Is>(index) = std::get<Is>(rhs.elements), 0)... };
|
||||
return *this;
|
||||
@@ -699,7 +699,7 @@ template<size_t... Is>
|
||||
inline
|
||||
typename StructureOfArraysBase<Allocator, Elements...>::IteratorValueRef&
|
||||
StructureOfArraysBase<Allocator, Elements...>::IteratorValueRef::assign(
|
||||
StructureOfArraysBase::IteratorValue&& rhs, std::index_sequence<Is...>) noexcept {
|
||||
IteratorValue&& rhs, std::index_sequence<Is...>) noexcept {
|
||||
// implements IteratorValueRef& IteratorValueRef::operator=(IteratorValue&& rhs) noexcept
|
||||
auto UTILS_UNUSED l = {
|
||||
(soa->elementAt<Is>(index) = std::move(std::get<Is>(rhs.elements)), 0)... };
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
/*
|
||||
* Copyright (C) 2016 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#ifndef TNT_UTILS_SYSTRACE_H
|
||||
#define TNT_UTILS_SYSTRACE_H
|
||||
|
||||
|
||||
#define SYSTRACE_TAG_NEVER (0)
|
||||
#define SYSTRACE_TAG_ALWAYS (1<<0)
|
||||
#define SYSTRACE_TAG_FILAMENT (1<<1) // don't change, used in makefiles
|
||||
#define SYSTRACE_TAG_JOBSYSTEM (1<<2)
|
||||
|
||||
/*
|
||||
* The SYSTRACE_ macros use SYSTRACE_TAG as a the TAG, which should be defined
|
||||
* before this file is included. If not, the SYSTRACE_TAG_ALWAYS tag will be used.
|
||||
*/
|
||||
|
||||
#ifndef SYSTRACE_TAG
|
||||
#define SYSTRACE_TAG (SYSTRACE_TAG_ALWAYS)
|
||||
#endif
|
||||
|
||||
// Systrace on Apple platforms is fragile and adds overhead, should only be enabled in dev builds.
|
||||
#ifndef FILAMENT_APPLE_SYSTRACE
|
||||
#define FILAMENT_APPLE_SYSTRACE 0
|
||||
#endif
|
||||
|
||||
#if defined(__ANDROID__)
|
||||
#include <utils/android/Systrace.h>
|
||||
#elif defined(__APPLE__) && FILAMENT_APPLE_SYSTRACE
|
||||
#include <utils/darwin/Systrace.h>
|
||||
#else
|
||||
|
||||
#define SYSTRACE_ENABLE()
|
||||
#define SYSTRACE_DISABLE()
|
||||
#define SYSTRACE_CONTEXT()
|
||||
#define SYSTRACE_NAME(name)
|
||||
#define SYSTRACE_FRAME_ID(frame)
|
||||
#define SYSTRACE_NAME_BEGIN(name)
|
||||
#define SYSTRACE_NAME_END()
|
||||
#define SYSTRACE_CALL()
|
||||
#define SYSTRACE_ASYNC_BEGIN(name, cookie)
|
||||
#define SYSTRACE_ASYNC_END(name, cookie)
|
||||
#define SYSTRACE_VALUE32(name, val)
|
||||
#define SYSTRACE_VALUE64(name, val)
|
||||
|
||||
#endif // ANDROID
|
||||
|
||||
#endif // TNT_UTILS_SYSTRACE_H
|
||||
@@ -0,0 +1,26 @@
|
||||
/*
|
||||
* Copyright (C) 2022 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#ifndef TNT_UTILS_THERMALMANAGER_H
|
||||
#define TNT_UTILS_THERMALMANAGER_H
|
||||
|
||||
#if defined(__ANDROID__)
|
||||
#include <utils/android/ThermalManager.h>
|
||||
#else
|
||||
#include <utils/generic/ThermalManager.h>
|
||||
#endif
|
||||
|
||||
#endif // TNT_UTILS_THERMALMANAGER_H
|
||||
@@ -0,0 +1,32 @@
|
||||
/*
|
||||
* Copyright (C) 2022 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#ifndef TNT_UTILS_THREADUTILS_H
|
||||
#define TNT_UTILS_THREADUTILS_H
|
||||
|
||||
#include <thread>
|
||||
|
||||
namespace utils {
|
||||
|
||||
class ThreadUtils {
|
||||
public:
|
||||
static std::thread::id getThreadId() noexcept;
|
||||
static bool isThisThread(std::thread::id id) noexcept;
|
||||
};
|
||||
|
||||
} // namespace utils
|
||||
|
||||
#endif // TNT_UTILS_THREADUTILS_H
|
||||
@@ -0,0 +1,216 @@
|
||||
/*
|
||||
* Copyright (C) 2016 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#ifndef TNT_UTILS_WORKSTEALINGDEQUEUE_H
|
||||
#define TNT_UTILS_WORKSTEALINGDEQUEUE_H
|
||||
|
||||
#include <atomic>
|
||||
#include <type_traits>
|
||||
|
||||
#include <assert.h>
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
namespace utils {
|
||||
|
||||
/*
|
||||
* A templated, lockless, fixed-size work-stealing dequeue
|
||||
*
|
||||
*
|
||||
* top bottom
|
||||
* v v
|
||||
* |----|----|----|----|----|----|
|
||||
* steal() push(), pop()
|
||||
* any thread main thread
|
||||
*
|
||||
* References:
|
||||
* - This code is largely inspired from
|
||||
* https://blog.molecular-matters.com/2015/09/25/job-system-2-0-lock-free-work-stealing-part-3-going-lock-free/
|
||||
* - other implementations
|
||||
* https://github.com/ConorWilliams/ConcurrentDeque/blob/main/include/riften/deque.hpp
|
||||
* https://github.com/ssbl/concurrent-deque/blob/master/include/deque.hpp
|
||||
* https://github.com/taskflow/work-stealing-queue/blob/master/wsq.hpp
|
||||
*/
|
||||
template <typename TYPE, size_t COUNT>
|
||||
class WorkStealingDequeue {
|
||||
static_assert(!(COUNT & (COUNT - 1)), "COUNT must be a power of two");
|
||||
static constexpr size_t MASK = COUNT - 1;
|
||||
|
||||
// mTop and mBottom must be signed integers. We use 64-bits atomics so we don't have
|
||||
// to worry about wrapping around.
|
||||
using index_t = int64_t;
|
||||
|
||||
std::atomic<index_t> mTop = { 0 }; // written/read in pop()/steal()
|
||||
std::atomic<index_t> mBottom = { 0 }; // written only in pop(), read in push(), steal()
|
||||
|
||||
TYPE mItems[COUNT];
|
||||
|
||||
// NOTE: it's not safe to return a reference because getItemAt() can be called
|
||||
// concurrently and the caller could std::move() the item unsafely.
|
||||
TYPE getItemAt(index_t index) noexcept { return mItems[index & MASK]; }
|
||||
|
||||
void setItemAt(index_t index, TYPE item) noexcept { mItems[index & MASK] = item; }
|
||||
|
||||
public:
|
||||
using value_type = TYPE;
|
||||
|
||||
inline void push(TYPE item) noexcept;
|
||||
inline TYPE pop() noexcept;
|
||||
inline TYPE steal() noexcept;
|
||||
|
||||
size_t getSize() const noexcept { return COUNT; }
|
||||
|
||||
// for debugging only...
|
||||
size_t getCount() const noexcept {
|
||||
index_t bottom = mBottom.load(std::memory_order_relaxed);
|
||||
index_t top = mTop.load(std::memory_order_relaxed);
|
||||
return bottom - top;
|
||||
}
|
||||
};
|
||||
|
||||
/*
|
||||
* Adds an item at the BOTTOM of the queue.
|
||||
*
|
||||
* Must be called from the main thread.
|
||||
*/
|
||||
template <typename TYPE, size_t COUNT>
|
||||
void WorkStealingDequeue<TYPE, COUNT>::push(TYPE item) noexcept {
|
||||
// std::memory_order_relaxed is sufficient because this load doesn't acquire anything from
|
||||
// another thread. mBottom is only written in pop() which cannot be concurrent with push()
|
||||
index_t bottom = mBottom.load(std::memory_order_relaxed);
|
||||
setItemAt(bottom, item);
|
||||
|
||||
// Here we need std::memory_order_release because we release, the item we just pushed, to other
|
||||
// threads which are calling steal().
|
||||
// However, generally seq_cst cannot be mixed with other memory orders. So we must use seq_cst.
|
||||
// see: https://plv.mpi-sws.org/scfix/paper.pdf
|
||||
mBottom.store(bottom + 1, std::memory_order_seq_cst);
|
||||
}
|
||||
|
||||
/*
|
||||
* Removes an item from the BOTTOM of the queue.
|
||||
*
|
||||
* Must be called from the main thread.
|
||||
*/
|
||||
template <typename TYPE, size_t COUNT>
|
||||
TYPE WorkStealingDequeue<TYPE, COUNT>::pop() noexcept {
|
||||
// std::memory_order_seq_cst is needed to guarantee ordering in steal()
|
||||
// Note however that this is not a typical acquire/release operation:
|
||||
// - not acquire because mBottom is only written in push() which is not concurrent
|
||||
// - not release because we're not publishing anything to steal() here
|
||||
//
|
||||
// QUESTION: does this prevent mTop load below to be reordered before the "store" part of
|
||||
// fetch_sub()? Hopefully it does. If not we'd need a full memory barrier.
|
||||
//
|
||||
index_t bottom = mBottom.fetch_sub(1, std::memory_order_seq_cst) - 1;
|
||||
|
||||
// bottom could be -1 if we tried to pop() from an empty queue. This will be corrected below.
|
||||
assert( bottom >= -1 );
|
||||
|
||||
// std::memory_order_seq_cst is needed to guarantee ordering in steal()
|
||||
// Note however that this is not a typical acquire operation
|
||||
// (i.e. other thread's writes of mTop don't publish data)
|
||||
index_t top = mTop.load(std::memory_order_seq_cst);
|
||||
|
||||
if (top < bottom) {
|
||||
// Queue isn't empty, and it's not the last item, just return it, this is the common case.
|
||||
return getItemAt(bottom);
|
||||
}
|
||||
|
||||
TYPE item{};
|
||||
if (top == bottom) {
|
||||
// we just took the last item
|
||||
item = getItemAt(bottom);
|
||||
|
||||
// Because we know we took the last item, we could be racing with steal() -- the last
|
||||
// item being both at the top and bottom of the queue.
|
||||
// We resolve this potential race by also stealing that item from ourselves.
|
||||
if (mTop.compare_exchange_strong(top, top + 1,
|
||||
std::memory_order_seq_cst,
|
||||
std::memory_order_relaxed)) {
|
||||
// Success: we stole our last item from ourselves, meaning that a concurrent steal()
|
||||
// would have failed.
|
||||
// mTop now equals top + 1, we adjust top to make the queue empty.
|
||||
top++;
|
||||
} else {
|
||||
// Failure: mTop was not equal to top, which means the item was stolen under our feet.
|
||||
// `top` now equals to mTop. Simply discard the item we just popped.
|
||||
// The queue is now empty.
|
||||
item = TYPE();
|
||||
}
|
||||
} else {
|
||||
// We could be here if the item was stolen just before we read mTop, we'll adjust
|
||||
// mBottom below.
|
||||
assert(top - bottom == 1);
|
||||
}
|
||||
|
||||
// Here, we only need std::memory_order_relaxed because we're not publishing any data.
|
||||
// No concurrent writes to mBottom possible, it's always safe to write mBottom.
|
||||
// However, generally seq_cst cannot be mixed with other memory orders. So we must use seq_cst.
|
||||
// see: https://plv.mpi-sws.org/scfix/paper.pdf
|
||||
mBottom.store(top, std::memory_order_seq_cst);
|
||||
return item;
|
||||
}
|
||||
|
||||
/*
|
||||
* Steals an item from the TOP of another thread's queue.
|
||||
*
|
||||
* This can be called concurrently with steal(), push() or pop()
|
||||
*
|
||||
* steal() never fails, either there is an item and it atomically takes it, or there isn't and
|
||||
* it returns an empty item.
|
||||
*/
|
||||
template <typename TYPE, size_t COUNT>
|
||||
TYPE WorkStealingDequeue<TYPE, COUNT>::steal() noexcept {
|
||||
while (true) {
|
||||
/*
|
||||
* Note: A Key component of this algorithm is that mTop is read before mBottom here
|
||||
* (and observed as such in other threads)
|
||||
*/
|
||||
|
||||
// std::memory_order_seq_cst is needed to guarantee ordering in pop()
|
||||
// Note however that this is not a typical acquire operation
|
||||
// (i.e. other thread's writes of mTop don't publish data)
|
||||
index_t top = mTop.load(std::memory_order_seq_cst);
|
||||
|
||||
// std::memory_order_acquire is needed because we're acquiring items published in push().
|
||||
// std::memory_order_seq_cst is needed to guarantee ordering in pop()
|
||||
index_t bottom = mBottom.load(std::memory_order_seq_cst);
|
||||
|
||||
if (top >= bottom) {
|
||||
// queue is empty
|
||||
return TYPE();
|
||||
}
|
||||
|
||||
// The queue isn't empty
|
||||
TYPE item(getItemAt(top));
|
||||
if (mTop.compare_exchange_strong(top, top + 1,
|
||||
std::memory_order_seq_cst,
|
||||
std::memory_order_relaxed)) {
|
||||
// success: we stole an item, just return it.
|
||||
return item;
|
||||
}
|
||||
// failure: the item we just tried to steal was pop()'ed under our feet,
|
||||
// simply discard it; nothing to do -- it's okay to try again.
|
||||
// However, item might be corrupted, so it must be trivially destructible
|
||||
static_assert(std::is_trivially_destructible_v<TYPE>);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
} // namespace utils
|
||||
|
||||
#endif // TNT_UTILS_WORKSTEALINGDEQUEUE_H
|
||||
@@ -0,0 +1,123 @@
|
||||
/*
|
||||
* Copyright (C) 2018 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#ifndef TNT_UTILS_ZIP2ITERATOR_H
|
||||
#define TNT_UTILS_ZIP2ITERATOR_H
|
||||
|
||||
#include <iterator>
|
||||
#include <type_traits>
|
||||
#include <utility>
|
||||
|
||||
#include <stddef.h>
|
||||
|
||||
namespace utils {
|
||||
|
||||
/*
|
||||
* A random access iterator that wraps two other random access iterators.
|
||||
* This mostly exists so that one can sort an array using values from another.
|
||||
*/
|
||||
|
||||
template<typename It1, typename It2>
|
||||
class Zip2Iterator {
|
||||
std::pair<It1, It2> mIt;
|
||||
using Ref1 = typename std::iterator_traits<It1>::reference;
|
||||
using Ref2 = typename std::iterator_traits<It2>::reference;
|
||||
using Val1 = typename std::iterator_traits<It1>::value_type;
|
||||
using Val2 = typename std::iterator_traits<It2>::value_type;
|
||||
|
||||
public:
|
||||
struct Ref : public std::pair<Ref1, Ref2> {
|
||||
using std::pair<Ref1, Ref2>::pair;
|
||||
using std::pair<Ref1, Ref2>::operator=;
|
||||
private:
|
||||
friend void swap(Ref lhs, Ref rhs) {
|
||||
using std::swap;
|
||||
swap(lhs.first, rhs.first);
|
||||
swap(lhs.second, rhs.second);
|
||||
}
|
||||
};
|
||||
|
||||
using value_type = std::pair<Val1, Val2>;
|
||||
using reference = Ref;
|
||||
using pointer = value_type*;
|
||||
using difference_type = ptrdiff_t;
|
||||
using iterator_category = std::random_access_iterator_tag;
|
||||
|
||||
Zip2Iterator() = default;
|
||||
Zip2Iterator(It1 first, It2 second) : mIt({first, second}) {}
|
||||
Zip2Iterator(Zip2Iterator const& rhs) noexcept = default;
|
||||
Zip2Iterator& operator=(Zip2Iterator const& rhs) = default;
|
||||
|
||||
reference operator*() const { return { *mIt.first, *mIt.second }; }
|
||||
|
||||
reference operator[](size_t n) const { return *(*this + n); }
|
||||
|
||||
Zip2Iterator& operator++() {
|
||||
++mIt.first;
|
||||
++mIt.second;
|
||||
return *this;
|
||||
}
|
||||
|
||||
Zip2Iterator& operator--() {
|
||||
--mIt.first;
|
||||
--mIt.second;
|
||||
return *this;
|
||||
}
|
||||
|
||||
// Postfix operator needed by Microsoft C++
|
||||
const Zip2Iterator operator++(int) {
|
||||
Zip2Iterator t(*this);
|
||||
mIt.first++;
|
||||
mIt.second++;
|
||||
return t;
|
||||
}
|
||||
|
||||
const Zip2Iterator operator--(int) {
|
||||
Zip2Iterator t(*this);
|
||||
mIt.first--;
|
||||
mIt.second--;
|
||||
return t;
|
||||
}
|
||||
|
||||
Zip2Iterator& operator+=(size_t v) {
|
||||
mIt.first += v;
|
||||
mIt.second += v;
|
||||
return *this;
|
||||
}
|
||||
|
||||
Zip2Iterator& operator-=(size_t v) {
|
||||
mIt.first -= v;
|
||||
mIt.second -= v;
|
||||
return *this;
|
||||
}
|
||||
|
||||
Zip2Iterator operator+(size_t rhs) const { return { mIt.first + rhs, mIt.second + rhs }; }
|
||||
Zip2Iterator operator+(size_t rhs) { return { mIt.first + rhs, mIt.second + rhs }; }
|
||||
Zip2Iterator operator-(size_t rhs) const { return { mIt.first - rhs, mIt.second - rhs }; }
|
||||
|
||||
difference_type operator-(Zip2Iterator const& rhs) const { return mIt.first - rhs.mIt.first; }
|
||||
|
||||
bool operator==(Zip2Iterator const& rhs) const { return (mIt.first == rhs.mIt.first); }
|
||||
bool operator!=(Zip2Iterator const& rhs) const { return (mIt.first != rhs.mIt.first); }
|
||||
bool operator>=(Zip2Iterator const& rhs) const { return (mIt.first >= rhs.mIt.first); }
|
||||
bool operator> (Zip2Iterator const& rhs) const { return (mIt.first > rhs.mIt.first); }
|
||||
bool operator<=(Zip2Iterator const& rhs) const { return (mIt.first <= rhs.mIt.first); }
|
||||
bool operator< (Zip2Iterator const& rhs) const { return (mIt.first < rhs.mIt.first); }
|
||||
};
|
||||
|
||||
} // namespace utils
|
||||
|
||||
#endif // TNT_UTILS_ZIP2ITERATOR_H
|
||||
@@ -22,6 +22,7 @@
|
||||
#include <type_traits> // for std::enable_if
|
||||
|
||||
#include <limits.h>
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
namespace utils {
|
||||
@@ -38,14 +39,20 @@ constexpr inline T popcount(T v) noexcept {
|
||||
return (T) (v * (ONES / 255)) >> (sizeof(T) - 1) * CHAR_BIT;
|
||||
}
|
||||
|
||||
template<typename T, typename = std::enable_if_t<std::is_unsigned<T>::value>>
|
||||
template<typename T, typename = std::enable_if_t<std::is_unsigned_v<T>>>
|
||||
constexpr inline T clz(T x) noexcept {
|
||||
static_assert(sizeof(T) * CHAR_BIT <= 128, "details::clz() only support up to 128 bits");
|
||||
x |= (x >> 1u);
|
||||
x |= (x >> 2u);
|
||||
x |= (x >> 4u);
|
||||
x |= (x >> 8u);
|
||||
x |= (x >> 16u);
|
||||
if constexpr (sizeof(T) * CHAR_BIT >= 8) { // just to silence compiler warning
|
||||
x |= (x >> 4u);
|
||||
}
|
||||
if constexpr (sizeof(T) * CHAR_BIT >= 16) { // just to silence compiler warning
|
||||
x |= (x >> 8u);
|
||||
}
|
||||
if constexpr (sizeof(T) * CHAR_BIT >= 32) { // just to silence compiler warning
|
||||
x |= (x >> 16u);
|
||||
}
|
||||
if constexpr (sizeof(T) * CHAR_BIT >= 64) { // just to silence compiler warning
|
||||
x |= (x >> 32u);
|
||||
}
|
||||
@@ -55,7 +62,7 @@ constexpr inline T clz(T x) noexcept {
|
||||
return T(sizeof(T) * CHAR_BIT) - details::popcount(x);
|
||||
}
|
||||
|
||||
template<typename T, typename = std::enable_if_t<std::is_unsigned<T>::value>>
|
||||
template<typename T, typename = std::enable_if_t<std::is_unsigned_v<T>>>
|
||||
constexpr inline T ctz(T x) noexcept {
|
||||
static_assert(sizeof(T) * CHAR_BIT <= 64, "details::ctz() only support up to 64 bits");
|
||||
T c = sizeof(T) * CHAR_BIT;
|
||||
@@ -67,11 +74,15 @@ constexpr inline T ctz(T x) noexcept {
|
||||
x &= -x;
|
||||
#endif
|
||||
if (x) c--;
|
||||
if (sizeof(T) * CHAR_BIT >= 64) {
|
||||
if constexpr (sizeof(T) * CHAR_BIT >= 64) {
|
||||
if (x & T(0x00000000FFFFFFFF)) c -= 32;
|
||||
}
|
||||
if (x & T(0x0000FFFF0000FFFF)) c -= 16;
|
||||
if (x & T(0x00FF00FF00FF00FF)) c -= 8;
|
||||
if constexpr (sizeof(T) * CHAR_BIT >= 32) {
|
||||
if (x & T(0x0000FFFF0000FFFF)) c -= 16;
|
||||
}
|
||||
if constexpr (sizeof(T) * CHAR_BIT >= 16) {
|
||||
if (x & T(0x00FF00FF00FF00FF)) c -= 8;
|
||||
}
|
||||
if (x & T(0x0F0F0F0F0F0F0F0F)) c -= 4;
|
||||
if (x & T(0x3333333333333333)) c -= 2;
|
||||
if (x & T(0x5555555555555555)) c -= 1;
|
||||
@@ -80,6 +91,24 @@ constexpr inline T ctz(T x) noexcept {
|
||||
|
||||
} // namespace details
|
||||
|
||||
constexpr inline UTILS_PUBLIC UTILS_PURE
|
||||
unsigned int UTILS_ALWAYS_INLINE clz(unsigned char x) noexcept {
|
||||
#if __has_builtin(__builtin_clz)
|
||||
return __builtin_clz((unsigned int)x) - 24;
|
||||
#else
|
||||
return details::clz(x);
|
||||
#endif
|
||||
}
|
||||
|
||||
constexpr inline UTILS_PUBLIC UTILS_PURE
|
||||
unsigned int UTILS_ALWAYS_INLINE clz(unsigned short x) noexcept {
|
||||
#if __has_builtin(__builtin_clz)
|
||||
return __builtin_clz((unsigned int)x) - 16;
|
||||
#else
|
||||
return details::clz(x);
|
||||
#endif
|
||||
}
|
||||
|
||||
constexpr inline UTILS_PUBLIC UTILS_PURE
|
||||
unsigned int UTILS_ALWAYS_INLINE clz(unsigned int x) noexcept {
|
||||
#if __has_builtin(__builtin_clz)
|
||||
@@ -107,6 +136,24 @@ unsigned long long UTILS_ALWAYS_INLINE clz(unsigned long long x) noexcept {
|
||||
#endif
|
||||
}
|
||||
|
||||
constexpr inline UTILS_PUBLIC UTILS_PURE
|
||||
unsigned int UTILS_ALWAYS_INLINE ctz(unsigned char x) noexcept {
|
||||
#if __has_builtin(__builtin_ctz)
|
||||
return __builtin_ctz(x);
|
||||
#else
|
||||
return details::ctz(x);
|
||||
#endif
|
||||
}
|
||||
|
||||
constexpr inline UTILS_PUBLIC UTILS_PURE
|
||||
unsigned int UTILS_ALWAYS_INLINE ctz(unsigned short x) noexcept {
|
||||
#if __has_builtin(__builtin_ctz)
|
||||
return __builtin_ctz(x);
|
||||
#else
|
||||
return details::ctz(x);
|
||||
#endif
|
||||
}
|
||||
|
||||
constexpr inline UTILS_PUBLIC UTILS_PURE
|
||||
unsigned int UTILS_ALWAYS_INLINE ctz(unsigned int x) noexcept {
|
||||
#if __has_builtin(__builtin_ctz)
|
||||
@@ -134,6 +181,24 @@ unsigned long long UTILS_ALWAYS_INLINE ctz(unsigned long long x) noexcept {
|
||||
#endif
|
||||
}
|
||||
|
||||
constexpr inline UTILS_PUBLIC UTILS_PURE
|
||||
unsigned int UTILS_ALWAYS_INLINE popcount(unsigned char x) noexcept {
|
||||
#if __has_builtin(__builtin_popcount)
|
||||
return __builtin_popcount(x);
|
||||
#else
|
||||
return details::popcount(x);
|
||||
#endif
|
||||
}
|
||||
|
||||
constexpr inline UTILS_PUBLIC UTILS_PURE
|
||||
unsigned int UTILS_ALWAYS_INLINE popcount(unsigned short x) noexcept {
|
||||
#if __has_builtin(__builtin_popcount)
|
||||
return __builtin_popcount(x);
|
||||
#else
|
||||
return details::popcount(x);
|
||||
#endif
|
||||
}
|
||||
|
||||
constexpr inline UTILS_PUBLIC UTILS_PURE
|
||||
unsigned int UTILS_ALWAYS_INLINE popcount(unsigned int x) noexcept {
|
||||
#if __has_builtin(__builtin_popcount)
|
||||
@@ -161,13 +226,8 @@ unsigned long long UTILS_ALWAYS_INLINE popcount(unsigned long long x) noexcept {
|
||||
#endif
|
||||
}
|
||||
|
||||
constexpr inline UTILS_PUBLIC UTILS_PURE
|
||||
uint8_t UTILS_ALWAYS_INLINE popcount(uint8_t x) noexcept {
|
||||
return (uint8_t)popcount((unsigned int)x);
|
||||
}
|
||||
|
||||
template<typename T,
|
||||
typename = std::enable_if_t<std::is_integral<T>::value && std::is_unsigned<T>::value>>
|
||||
typename = std::enable_if_t<std::is_integral_v<T> && std::is_unsigned_v<T>>>
|
||||
constexpr inline UTILS_PUBLIC UTILS_PURE
|
||||
T log2i(T x) noexcept {
|
||||
return (sizeof(x) * 8 - 1u) - clz(x);
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
/*
|
||||
* Copyright (C) 2024 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#ifndef TNT_UTILS_ANDROID_PERFORMANCEHINTMANAGER_H
|
||||
#define TNT_UTILS_ANDROID_PERFORMANCEHINTMANAGER_H
|
||||
|
||||
#include <utils/compiler.h>
|
||||
#include <utils/PrivateImplementation.h>
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
namespace utils {
|
||||
|
||||
namespace details {
|
||||
struct PerformanceHintManager;
|
||||
} // namespace details
|
||||
|
||||
class UTILS_PUBLIC PerformanceHintManager :
|
||||
private PrivateImplementation<details::PerformanceHintManager> {
|
||||
friend struct details::PerformanceHintManager;
|
||||
struct SessionDetails;
|
||||
|
||||
public:
|
||||
class UTILS_PUBLIC Session : PrivateImplementation<SessionDetails> {
|
||||
friend class PerformanceHintManager;
|
||||
friend struct SessionDetails;
|
||||
public:
|
||||
Session() noexcept;
|
||||
Session(PerformanceHintManager& manager,
|
||||
int32_t const* threadIds, size_t size,
|
||||
int64_t initialTargetWorkDurationNanos) noexcept;
|
||||
~Session() noexcept;
|
||||
|
||||
Session(Session&& rhs) noexcept;
|
||||
Session& operator=(Session&& rhs) noexcept;
|
||||
Session(Session const& rhs) = delete;
|
||||
Session& operator=(Session const& rhs) = delete;
|
||||
|
||||
bool isValid() const;
|
||||
int updateTargetWorkDuration(int64_t targetDurationNanos) noexcept;
|
||||
int reportActualWorkDuration(int64_t actualDurationNanos) noexcept;
|
||||
};
|
||||
|
||||
// caveat: This must be called on a Java thread
|
||||
PerformanceHintManager() noexcept;
|
||||
~PerformanceHintManager() noexcept;
|
||||
|
||||
// Whether PerformanceHintManager APIs are supported (which doesn't mean PerformanceHintManager
|
||||
// itself is, use isValid()).
|
||||
static bool isSupported() noexcept;
|
||||
|
||||
// Whether PerformanceHintManager can be used.
|
||||
bool isValid() const;
|
||||
|
||||
int64_t getPreferredUpdateRateNanos() const noexcept;
|
||||
};
|
||||
|
||||
} // namespace utils
|
||||
|
||||
#endif //TNT_UTILS_ANDROID_PERFORMANCEHINTMANAGER_H
|
||||
@@ -0,0 +1,242 @@
|
||||
/*
|
||||
* Copyright (C) 2023 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#ifndef TNT_UTILS_ANDROID_SYSTRACE_H
|
||||
#define TNT_UTILS_ANDROID_SYSTRACE_H
|
||||
|
||||
#include <atomic>
|
||||
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include <utils/compiler.h>
|
||||
|
||||
// enable tracing
|
||||
#define SYSTRACE_ENABLE() ::utils::details::Systrace::enable(SYSTRACE_TAG)
|
||||
|
||||
// disable tracing
|
||||
#define SYSTRACE_DISABLE() ::utils::details::Systrace::disable(SYSTRACE_TAG)
|
||||
|
||||
|
||||
/**
|
||||
* Creates a Systrace context in the current scope. needed for calling all other systrace
|
||||
* commands below.
|
||||
*/
|
||||
#define SYSTRACE_CONTEXT() ::utils::details::Systrace ___trctx(SYSTRACE_TAG)
|
||||
|
||||
|
||||
// SYSTRACE_NAME traces the beginning and end of the current scope. To trace
|
||||
// the correct start and end times this macro should be declared first in the
|
||||
// scope body.
|
||||
// It also automatically creates a Systrace context
|
||||
#define SYSTRACE_NAME(name) ::utils::details::ScopedTrace ___tracer(SYSTRACE_TAG, name)
|
||||
|
||||
// Denotes that a new frame has started processing.
|
||||
#define SYSTRACE_FRAME_ID(frame) \
|
||||
{ /* scope for frame id trace */ \
|
||||
char buf[64]; \
|
||||
snprintf(buf, 64, "frame %u", frame); \
|
||||
SYSTRACE_NAME(buf); \
|
||||
}
|
||||
|
||||
// SYSTRACE_CALL is an SYSTRACE_NAME that uses the current function name.
|
||||
#define SYSTRACE_CALL() SYSTRACE_NAME(__FUNCTION__)
|
||||
|
||||
#define SYSTRACE_NAME_BEGIN(name) \
|
||||
___trctx.traceBegin(SYSTRACE_TAG, name)
|
||||
|
||||
#define SYSTRACE_NAME_END() \
|
||||
___trctx.traceEnd(SYSTRACE_TAG)
|
||||
|
||||
|
||||
/**
|
||||
* Trace the beginning of an asynchronous event. Unlike ATRACE_BEGIN/ATRACE_END
|
||||
* contexts, asynchronous events do not need to be nested. The name describes
|
||||
* the event, and the cookie provides a unique identifier for distinguishing
|
||||
* simultaneous events. The name and cookie used to begin an event must be
|
||||
* used to end it.
|
||||
*/
|
||||
#define SYSTRACE_ASYNC_BEGIN(name, cookie) \
|
||||
___trctx.asyncBegin(SYSTRACE_TAG, name, cookie)
|
||||
|
||||
/**
|
||||
* Trace the end of an asynchronous event.
|
||||
* This should have a corresponding SYSTRACE_ASYNC_BEGIN.
|
||||
*/
|
||||
#define SYSTRACE_ASYNC_END(name, cookie) \
|
||||
___trctx.asyncEnd(SYSTRACE_TAG, name, cookie)
|
||||
|
||||
/**
|
||||
* Traces an integer counter value. name is used to identify the counter.
|
||||
* This can be used to track how a value changes over time.
|
||||
*/
|
||||
#define SYSTRACE_VALUE32(name, val) \
|
||||
___trctx.value(SYSTRACE_TAG, name, int32_t(val))
|
||||
|
||||
#define SYSTRACE_VALUE64(name, val) \
|
||||
___trctx.value(SYSTRACE_TAG, name, int64_t(val))
|
||||
|
||||
// ------------------------------------------------------------------------------------------------
|
||||
// No user serviceable code below...
|
||||
// ------------------------------------------------------------------------------------------------
|
||||
|
||||
namespace utils {
|
||||
namespace details {
|
||||
|
||||
class UTILS_PUBLIC Systrace {
|
||||
public:
|
||||
|
||||
enum tags {
|
||||
NEVER = SYSTRACE_TAG_NEVER,
|
||||
ALWAYS = SYSTRACE_TAG_ALWAYS,
|
||||
FILAMENT = SYSTRACE_TAG_FILAMENT,
|
||||
JOBSYSTEM = SYSTRACE_TAG_JOBSYSTEM
|
||||
// we could define more TAGS here, as we need them.
|
||||
};
|
||||
|
||||
explicit Systrace(uint32_t tag) noexcept {
|
||||
if (tag) init(tag);
|
||||
}
|
||||
|
||||
static void enable(uint32_t tags) noexcept;
|
||||
static void disable(uint32_t tags) noexcept;
|
||||
|
||||
|
||||
inline void traceBegin(uint32_t tag, const char* name) noexcept {
|
||||
if (tag && UTILS_UNLIKELY(mIsTracingEnabled)) {
|
||||
beginSection(this, name);
|
||||
}
|
||||
}
|
||||
|
||||
inline void traceEnd(uint32_t tag) noexcept {
|
||||
if (tag && UTILS_UNLIKELY(mIsTracingEnabled)) {
|
||||
endSection(this);
|
||||
}
|
||||
}
|
||||
|
||||
inline void asyncBegin(uint32_t tag, const char* name, int32_t cookie) noexcept {
|
||||
if (tag && UTILS_UNLIKELY(mIsTracingEnabled)) {
|
||||
beginAsyncSection(this, name, cookie);
|
||||
}
|
||||
}
|
||||
|
||||
inline void asyncEnd(uint32_t tag, const char* name, int32_t cookie) noexcept {
|
||||
if (tag && UTILS_UNLIKELY(mIsTracingEnabled)) {
|
||||
endAsyncSection(this, name, cookie);
|
||||
}
|
||||
}
|
||||
|
||||
inline void value(uint32_t tag, const char* name, int32_t value) noexcept {
|
||||
if (tag && UTILS_UNLIKELY(mIsTracingEnabled)) {
|
||||
setCounter(this, name, value);
|
||||
}
|
||||
}
|
||||
|
||||
inline void value(uint32_t tag, const char* name, int64_t value) noexcept {
|
||||
if (tag && UTILS_UNLIKELY(mIsTracingEnabled)) {
|
||||
setCounter(this, name, value);
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
friend class ScopedTrace;
|
||||
|
||||
// whether tracing is supported at all by the platform
|
||||
|
||||
using ATrace_isEnabled_t = bool (*)();
|
||||
using ATrace_beginSection_t = void (*)(const char* sectionName);
|
||||
using ATrace_endSection_t = void (*)();
|
||||
using ATrace_beginAsyncSection_t = void (*)(const char* sectionName, int32_t cookie);
|
||||
using ATrace_endAsyncSection_t = void (*)(const char* sectionName, int32_t cookie);
|
||||
using ATrace_setCounter_t = void (*)(const char* counterName, int64_t counterValue);
|
||||
|
||||
struct GlobalState {
|
||||
bool isTracingAvailable;
|
||||
std::atomic<uint32_t> isTracingEnabled;
|
||||
int markerFd;
|
||||
|
||||
ATrace_isEnabled_t ATrace_isEnabled;
|
||||
ATrace_beginSection_t ATrace_beginSection;
|
||||
ATrace_endSection_t ATrace_endSection;
|
||||
ATrace_beginAsyncSection_t ATrace_beginAsyncSection;
|
||||
ATrace_endAsyncSection_t ATrace_endAsyncSection;
|
||||
ATrace_setCounter_t ATrace_setCounter;
|
||||
|
||||
void (*beginSection)(Systrace* that, const char* name);
|
||||
void (*endSection)(Systrace* that);
|
||||
void (*beginAsyncSection)(Systrace* that, const char* name, int32_t cookie);
|
||||
void (*endAsyncSection)(Systrace* that, const char* name, int32_t cookie);
|
||||
void (*setCounter)(Systrace* that, const char* name, int64_t value);
|
||||
};
|
||||
|
||||
static GlobalState sGlobalState;
|
||||
|
||||
|
||||
// per-instance versions for better performance
|
||||
ATrace_isEnabled_t ATrace_isEnabled;
|
||||
ATrace_beginSection_t ATrace_beginSection;
|
||||
ATrace_endSection_t ATrace_endSection;
|
||||
ATrace_beginAsyncSection_t ATrace_beginAsyncSection;
|
||||
ATrace_endAsyncSection_t ATrace_endAsyncSection;
|
||||
ATrace_setCounter_t ATrace_setCounter;
|
||||
|
||||
void (*beginSection)(Systrace* that, const char* name);
|
||||
void (*endSection)(Systrace* that);
|
||||
void (*beginAsyncSection)(Systrace* that, const char* name, int32_t cookie);
|
||||
void (*endAsyncSection)(Systrace* that, const char* name, int32_t cookie);
|
||||
void (*setCounter)(Systrace* that, const char* name, int64_t value);
|
||||
|
||||
void init(uint32_t tag) noexcept;
|
||||
|
||||
// cached values for faster access, no need to be initialized
|
||||
bool mIsTracingEnabled;
|
||||
int mMarkerFd = -1;
|
||||
pid_t mPid;
|
||||
|
||||
static void setup() noexcept;
|
||||
static void init_once() noexcept;
|
||||
static bool isTracingEnabled(uint32_t tag) noexcept;
|
||||
|
||||
static void begin_body(int fd, int pid, const char* name) noexcept;
|
||||
static void end_body(int fd, int pid) noexcept;
|
||||
static void async_begin_body(int fd, int pid, const char* name, int32_t cookie) noexcept;
|
||||
static void async_end_body(int fd, int pid, const char* name, int32_t cookie) noexcept;
|
||||
static void int64_body(int fd, int pid, const char* name, int64_t value) noexcept;
|
||||
};
|
||||
|
||||
// ------------------------------------------------------------------------------------------------
|
||||
|
||||
class UTILS_PUBLIC ScopedTrace {
|
||||
public:
|
||||
// we don't inline this because it's relatively heavy due to a global check
|
||||
ScopedTrace(uint32_t tag, const char* name) noexcept: mTrace(tag), mTag(tag) {
|
||||
mTrace.traceBegin(tag, name);
|
||||
}
|
||||
|
||||
inline ~ScopedTrace() noexcept {
|
||||
mTrace.traceEnd(mTag);
|
||||
}
|
||||
|
||||
private:
|
||||
Systrace mTrace;
|
||||
const uint32_t mTag;
|
||||
};
|
||||
|
||||
} // namespace details
|
||||
} // namespace utils
|
||||
|
||||
#endif // TNT_UTILS_ANDROID_SYSTRACE_H
|
||||
@@ -0,0 +1,58 @@
|
||||
/*
|
||||
* Copyright (C) 2022 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#ifndef TNT_UTILS_ANDROID_THERMALMANAGER_H
|
||||
#define TNT_UTILS_ANDROID_THERMALMANAGER_H
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
struct AThermalManager;
|
||||
|
||||
namespace utils {
|
||||
|
||||
class ThermalManager {
|
||||
public:
|
||||
enum class ThermalStatus : int8_t {
|
||||
ERROR = -1,
|
||||
NONE,
|
||||
LIGHT,
|
||||
MODERATE,
|
||||
SEVERE,
|
||||
CRITICAL,
|
||||
EMERGENCY,
|
||||
SHUTDOWN
|
||||
};
|
||||
|
||||
ThermalManager();
|
||||
~ThermalManager();
|
||||
|
||||
// Movable
|
||||
ThermalManager(ThermalManager&& rhs) noexcept;
|
||||
ThermalManager& operator=(ThermalManager&& rhs) noexcept;
|
||||
|
||||
// not copiable
|
||||
ThermalManager(ThermalManager const& rhs) = delete;
|
||||
ThermalManager& operator=(ThermalManager const& rhs) = delete;
|
||||
|
||||
ThermalStatus getCurrentThermalStatus() const noexcept;
|
||||
|
||||
private:
|
||||
AThermalManager* mThermalManager = nullptr;
|
||||
};
|
||||
|
||||
} // namespace utils
|
||||
|
||||
#endif // TNT_UTILS_ANDROID_THERMALMANAGER_H
|
||||
@@ -0,0 +1,34 @@
|
||||
/*
|
||||
* Copyright (C) 2019 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#ifndef TNT_UTILS_APILEVEL_H
|
||||
#define TNT_UTILS_APILEVEL_H
|
||||
|
||||
#include <utils/compiler.h>
|
||||
|
||||
namespace utils {
|
||||
|
||||
/**
|
||||
* Returns this platform's API level. On Android this function will return
|
||||
* the API level as defined by the SDK API level version. If a platform does
|
||||
* not have an API level, this function returns 0.
|
||||
*/
|
||||
UTILS_PUBLIC
|
||||
int api_level();
|
||||
|
||||
} // namespace utils
|
||||
|
||||
#endif // TNT_UTILS_APILEVEL_H
|
||||
@@ -0,0 +1,33 @@
|
||||
/*
|
||||
* Copyright (C) 2016 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#ifndef TNT_UTILS_ARCHITECTURE_H
|
||||
#define TNT_UTILS_ARCHITECTURE_H
|
||||
|
||||
#include <stddef.h>
|
||||
|
||||
namespace utils {
|
||||
|
||||
constexpr size_t CACHELINE_SIZE = 64;
|
||||
|
||||
namespace arch {
|
||||
|
||||
size_t getPageSize() noexcept;
|
||||
|
||||
} // namespace arch
|
||||
} // namespace utils
|
||||
|
||||
#endif // TNT_UTILS_ARCHITECTURE_H
|
||||
@@ -0,0 +1,28 @@
|
||||
/*
|
||||
* Copyright (C) 2016 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#ifndef TNT_UTILS_ASHMEM_H
|
||||
#define TNT_UTILS_ASHMEM_H
|
||||
|
||||
#include <stddef.h>
|
||||
|
||||
namespace utils {
|
||||
|
||||
int ashmem_create_region(const char *name, size_t size);
|
||||
|
||||
} // namespace utils
|
||||
|
||||
#endif // TNT_UTILS_ASHMEM_H
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user