SuperTuxKart 1.5 upstream source (from official release tarball)

This commit is contained in:
Benjamin
2026-06-11 20:04:02 +02:00
commit 2957e51aaa
8551 changed files with 1801800 additions and 0 deletions
@@ -0,0 +1,290 @@
#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_ */
@@ -0,0 +1,266 @@
/* ==========================================================================
* Copyright (c) 2022 SuperTuxKart-Team
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to permit
* persons to whom the Software is 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 Software.
*
* THE SOFTWARE IS 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 SOFTWARE OR THE
* USE OR OTHER DEALINGS IN THE SOFTWARE.
* ==========================================================================
*/
#ifndef HEADER_GE_ANIMATION_HPP
#define HEADER_GE_ANIMATION_HPP
#include <IReadFile.h>
#include <matrix4.h>
#include <quaternion.h>
#include <cassert>
#include <cstdint>
#include <cstdlib>
#include <vector>
#include <string>
using namespace irr;
namespace GE
{
struct LocRotScale
{
core::vector3df m_loc;
core::quaternion m_rot;
core::vector3df m_scale;
// ------------------------------------------------------------------------
inline core::matrix4 toMatrix() const
{
core::matrix4 lm, sm, rm;
lm.setTranslation(m_loc);
sm.setScale(m_scale);
m_rot.getMatrix(rm);
return lm * rm * sm;
}
// ------------------------------------------------------------------------
void read(irr::io::IReadFile* spm)
{
float tmp[10];
spm->read(&tmp, 40);
m_loc = core::vector3df(tmp[0], tmp[1], tmp[2]);
m_rot = core::quaternion(tmp[3], tmp[4], tmp[5], tmp[6]);
m_rot.normalize();
m_scale = core::vector3df(tmp[7], tmp[8], tmp[9]);
}
};
struct Armature
{
unsigned m_joint_used;
std::vector<std::string> m_joint_names;
std::vector<core::matrix4> m_joint_matrices;
std::vector<LocRotScale> m_interpolated_matrices;
std::vector<std::pair<core::matrix4, bool> > m_world_matrices;
std::vector<int> m_parent_infos;
std::vector<std::pair<int, std::vector<LocRotScale> > >
m_frame_pose_matrices;
// ------------------------------------------------------------------------
void read(irr::io::IReadFile* spm)
{
LocRotScale lrs;
spm->read(&m_joint_used, 2);
assert(m_joint_used > 0);
unsigned all_joints_size = 0;
spm->read(&all_joints_size, 2);
assert(all_joints_size > 0);
m_joint_names.resize(all_joints_size);
for (unsigned i = 0; i < all_joints_size; i++)
{
unsigned str_len = 0;
spm->read(&str_len, 1);
m_joint_names[i].resize(str_len);
spm->read(&m_joint_names[i].front(), str_len);
}
m_joint_matrices.resize(all_joints_size);
m_interpolated_matrices.resize(all_joints_size);
for (unsigned i = 0; i < all_joints_size; i++)
{
lrs.read(spm);
m_joint_matrices[i] = lrs.toMatrix();
}
m_world_matrices.resize(m_interpolated_matrices.size(),
std::make_pair(core::matrix4(), false));
m_parent_infos.resize(all_joints_size);
bool non_parent_bone = false;
for (unsigned i = 0; i < all_joints_size; i++)
{
int16_t info = 0;
spm->read(&info, 2);
if (info == -1)
{
non_parent_bone = true;
}
m_parent_infos[i] = info;
}
if (!non_parent_bone)
{
printf("SPMeshLoader::Armature: Non-parent bone missing in armature");
exit(-1);
}
unsigned frame_size = 0;
spm->read(&frame_size, 2);
m_frame_pose_matrices.resize(frame_size);
for (unsigned i = 0; i < frame_size; i++)
{
m_frame_pose_matrices[i].second.resize(all_joints_size);
unsigned frame_index = 0;
spm->read(&frame_index, 2);
m_frame_pose_matrices[i].first = frame_index;
for (unsigned j = 0; j < m_frame_pose_matrices[i].second.size(); j++)
{
m_frame_pose_matrices[i].second[j].read(spm);
}
}
}
// ------------------------------------------------------------------------
void getPose(float frame, core::matrix4* dest,
float frame_interpolating = -1.0f, float rate = -1.0f)
{
getInterpolatedMatrices(frame);
if (frame_interpolating != -1.0f && rate != -1.0f)
{
auto copied = m_interpolated_matrices;
getInterpolatedMatrices(frame_interpolating);
for (unsigned i = 0; i < m_interpolated_matrices.size(); i++)
{
m_interpolated_matrices[i].m_loc =
copied[i].m_loc.getInterpolated(
m_interpolated_matrices[i].m_loc, rate);
m_interpolated_matrices[i].m_rot =
m_interpolated_matrices[i].m_rot.slerp(
m_interpolated_matrices[i].m_rot, copied[i].m_rot, rate);
m_interpolated_matrices[i].m_scale =
copied[i].m_scale.getInterpolated(
m_interpolated_matrices[i].m_scale, rate);
}
}
for (auto& p : m_world_matrices)
{
p.second = false;
}
for (unsigned i = 0; i < m_joint_used; i++)
{
dest[i] = getWorldMatrix(m_interpolated_matrices, i) *
m_joint_matrices[i];
}
}
// ------------------------------------------------------------------------
void getPose(core::matrix4* dest, float frame)
{
getInterpolatedMatrices(frame);
for (auto& p : m_world_matrices)
{
p.second = false;
}
for (unsigned i = 0; i < m_joint_used; i++)
{
dest[i] = getWorldMatrix(m_interpolated_matrices, i) *
m_joint_matrices[i];
}
}
// ------------------------------------------------------------------------
void getInterpolatedMatrices(float frame)
{
if (frame < float(m_frame_pose_matrices.front().first) ||
frame >= float(m_frame_pose_matrices.back().first))
{
for (unsigned i = 0; i < m_interpolated_matrices.size(); i++)
{
m_interpolated_matrices[i] =
frame >= float(m_frame_pose_matrices.back().first) ?
m_frame_pose_matrices.back().second[i] :
m_frame_pose_matrices.front().second[i];
}
return;
}
int frame_1 = -1;
int frame_2 = -1;
float interpolation = 0.0f;
for (unsigned i = 0; i < m_frame_pose_matrices.size(); i++)
{
assert(i + 1 < m_frame_pose_matrices.size());
if (frame >= float(m_frame_pose_matrices[i].first) &&
frame < float(m_frame_pose_matrices[i + 1].first))
{
frame_1 = i;
frame_2 = i + 1;
interpolation =
(frame - float(m_frame_pose_matrices[i].first)) /
float(m_frame_pose_matrices[i + 1].first -
m_frame_pose_matrices[i].first);
break;
}
}
assert(frame_1 != -1);
assert(frame_2 != -1);
for (unsigned i = 0; i < m_interpolated_matrices.size(); i++)
{
LocRotScale interpolated;
interpolated.m_loc =
m_frame_pose_matrices[frame_2].second[i].m_loc.getInterpolated
(m_frame_pose_matrices[frame_1].second[i].m_loc, interpolation);
interpolated.m_rot.slerp
(m_frame_pose_matrices[frame_1].second[i].m_rot,
m_frame_pose_matrices[frame_2].second[i].m_rot, interpolation);
interpolated.m_scale =
m_frame_pose_matrices[frame_2].second[i].m_scale.getInterpolated
(m_frame_pose_matrices[frame_1].second[i].m_scale, interpolation);
m_interpolated_matrices[i] = interpolated;
}
}
// ------------------------------------------------------------------------
core::matrix4 getWorldMatrix(const std::vector<LocRotScale>& lrs,
unsigned id)
{
core::matrix4 mat = lrs[id].toMatrix();
int parent_id = m_parent_infos[id];
if (parent_id == -1)
{
m_world_matrices[id] = std::make_pair(mat, true);
return mat;
}
if (!m_world_matrices[parent_id].second)
{
m_world_matrices[parent_id] = std::make_pair
(getWorldMatrix(lrs, parent_id), true);
}
m_world_matrices[id] =
std::make_pair(m_world_matrices[parent_id].first * mat, true);
return m_world_matrices[id].first;
}
};
}
#endif
@@ -0,0 +1,47 @@
#ifndef HEADER_GE_GL_UTILS_HPP
#define HEADER_GE_GL_UTILS_HPP
#include <glad/gl.h>
#include <set>
#include <sstream>
#include <string>
namespace GE
{
inline bool hasGLExtension(const std::string& extension)
{
if (glGetStringi)
{
int num = 0;
glGetIntegerv(GL_NUM_EXTENSIONS, &num);
for (int i = 0; i < num; i++)
{
char* ext = (char*)glGetStringi(GL_EXTENSIONS, i);
if (ext && extension == ext)
return true;
}
return false;
}
static std::set<std::string> extensions;
if (extensions.empty())
{
char* all_ext = (char*)glGetString(GL_EXTENSIONS);
if (all_ext)
{
std::stringstream ss(all_ext);
while (true)
{
std::string ext;
if (ss >> ext)
extensions.insert(ext);
else
break;
}
}
}
return extensions.find(extension) != extensions.end();
} // hasGLExtension
}
#endif
+130
View File
@@ -0,0 +1,130 @@
#ifndef HEADER_GE_MAIN_HPP
#define HEADER_GE_MAIN_HPP
#include <IVideoDriver.h>
#include <matrix4.h>
#include <SColor.h>
#include <array>
#include <cstdint>
#include <string>
#include <unordered_set>
namespace irr
{
namespace scene
{
class IMesh; class IAnimatedMesh;
}
}
namespace GE
{
class GEOcclusionCulling;
class GESPMBuffer;
class GEVulkanDriver;
enum GEAutoDeferredType : unsigned
{
GADT_DISABLED = 0,
GADT_SINGLE_PASS,
GADT_DISPLACE
};
enum GEScreenSpaceReflectionType : unsigned
{
GSSRT_DISABLED = 0,
GSSRT_FAST,
GSSRT_HIZ,
GSSRT_HIZ100 = GSSRT_HIZ,
GSSRT_HIZ200,
GSSRT_HIZ400,
GSSRT_COUNT,
};
struct GEConfig
{
bool m_disable_npot_texture;
bool m_convert_irrlicht_mesh;
bool m_texture_compression;
bool m_fullscreen_desktop;
bool m_enable_draw_call_cache;
bool m_pbr;
bool m_ibl;
GEAutoDeferredType m_auto_deferred_type;
GEScreenSpaceReflectionType m_screen_space_reflection_type;
bool m_force_deferred;
std::unordered_set<std::string> m_ondemand_load_texture_paths;
float m_render_scale;
};
void setVideoDriver(irr::video::IVideoDriver* driver);
void setShaderFolder(const std::string& path);
irr::video::IVideoDriver* getDriver();
GE::GEVulkanDriver* getVKDriver();
const std::string& getShaderFolder();
GEConfig* getGEConfig();
void deinit();
uint64_t getMonoTimeMs();
void mathPlaneFrustumf(float* out, const irr::core::matrix4& pvm);
inline size_t getPadding(size_t in, size_t alignment)
{
if (in == 0 || alignment == 0)
return 0;
size_t mod = in % alignment;
if (mod == 0)
return 0;
else
return alignment - mod;
}
inline int get4x4CompressedTextureSize(int width, int height)
{
int blockcount = ((width + 3) / 4) * ((height + 3) / 4);
int blocksize = 4 * 4;
return blockcount * blocksize;
}
irr::scene::IAnimatedMesh* convertIrrlichtMeshToSPM(irr::scene::IMesh* mesh);
inline uint8_t srgb255ToLinear(unsigned color_srgb_255)
{
static unsigned srgb_linear_map[256] =
{
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2,
2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4,
4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7,
7, 8, 8, 8, 9, 9, 9, 10, 10, 10, 11, 11,
11, 12, 12, 13, 13, 13, 14, 14, 15, 15, 16, 16,
16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 22, 22,
23, 23, 24, 24, 25, 26, 26, 27, 27, 28, 29, 29,
30, 31, 31, 32, 33, 33, 34, 35, 36, 36, 37, 38,
38, 39, 40, 41, 42, 42, 43, 44, 45, 46, 47, 47,
48, 49, 50, 51, 52, 53, 54, 55, 55, 56, 57, 58,
59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 70, 71,
72, 73, 74, 75, 76, 77, 78, 80, 81, 82, 83, 84,
85, 87, 88, 89, 90, 92, 93, 94, 95, 97, 98, 99,
101, 102, 103, 105, 106, 107, 109, 110, 112, 113, 114, 116,
117, 119, 120, 122, 123, 125, 126, 128, 129, 131, 132, 134,
135, 137, 139, 140, 142, 144, 145, 147, 148, 150, 152, 153,
155, 157, 159, 160, 162, 164, 166, 167, 169, 171, 173, 175,
176, 178, 180, 182, 184, 186, 188, 190, 192, 193, 195, 197,
199, 201, 203, 205, 207, 209, 211, 213, 215, 218, 220, 222,
224, 226, 228, 230, 232, 235, 237, 239, 241, 243, 245, 248,
250, 252, 255
};
return uint8_t(srgb_linear_map[color_srgb_255]);
}
inline irr::video::SColor srgb255ToLinearFromSColor(irr::video::SColor scolor_srgb)
{
irr::video::SColor out = scolor_srgb;
out.setRed(srgb255ToLinear(scolor_srgb.getRed()));
out.setGreen(srgb255ToLinear(scolor_srgb.getGreen()));
out.setBlue(srgb255ToLinear(scolor_srgb.getBlue()));
return out;
}
void copyToMappedBuffer(uint32_t* mapped, GESPMBuffer* spmb, size_t offset = 0);
GEOcclusionCulling* getOcclusionCulling();
void resetOcclusionCulling();
bool hasOcclusionCulling();
bool needsDeferredRendering(bool auto_deferred = true);
std::array<float, 4>& getDisplaceDirection();
}
#endif
@@ -0,0 +1,72 @@
#ifndef HEADER_GE_MATERIAL_MANAGER_HPP
#define HEADER_GE_MATERIAL_MANAGER_HPP
#include <cstdint>
#include <functional>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include <EMaterialTypes.h>
namespace GE
{
struct GEMaterial
{
std::string m_vertex_shader;
std::string m_skinning_vertex_shader;
std::string m_fragment_shader;
std::string m_depth_only_fragment_shader;
std::function<void(uint32_t*, void**)> m_push_constants;
// Fallback material used when PBR is disabled
std::string m_nonpbr_fallback;
bool m_alphablend;
bool m_additive;
bool m_backface_culling;
bool m_depth_test;
bool m_depth_write;
std::vector<bool> m_srgb_settings;
// ------------------------------------------------------------------------
GEMaterial()
{
m_alphablend = false;
m_additive = false;
m_backface_culling = true;
m_depth_test = true;
m_depth_write = true;
m_srgb_settings =
{ true, true, false, false, false, false, false, false };
}
// ------------------------------------------------------------------------
bool texturelessDepth() const
{
return m_depth_only_fragment_shader.empty() ||
m_depth_only_fragment_shader == "depth_only.frag";
}
// ------------------------------------------------------------------------
bool isTransparent() const { return m_alphablend || m_additive; }
}; // GEMaterial
namespace GEMaterialManager
{
// ----------------------------------------------------------------------------
extern std::vector<std::pair<std::string, std::shared_ptr<const GEMaterial> > >
g_materials;
// ----------------------------------------------------------------------------
void init();
// ----------------------------------------------------------------------------
void update();
// ----------------------------------------------------------------------------
irr::video::E_MATERIAL_TYPE getIrrMaterialType(const std::string& shader_name);
// ----------------------------------------------------------------------------
const std::string& getShader(irr::video::E_MATERIAL_TYPE mt);
// ----------------------------------------------------------------------------
std::shared_ptr<const GEMaterial> getMaterial(const std::string& shader_name);
}; // GEMaterialManager
}
#endif
@@ -0,0 +1,80 @@
#ifndef HEADER_GE_OCCLUSION_CULLING_HPP
#define HEADER_GE_OCCLUSION_CULLING_HPP
#include <aabbox3d.h>
#include <vector3d.h>
#include <LinearMath/btVector3.h>
#include <array>
#include <vector>
class btCollisionShape;
class btCollisionObject;
class btTriangleMesh;
namespace GE
{
class GEOcclusionCulling
{
private:
btTriangleMesh* m_triangle_mesh;
btCollisionShape* m_occluder_shape;
btCollisionObject* m_occluder_object;
// Point generators that yield one point at a time
class PointGenerator
{
public:
virtual ~PointGenerator() {}
virtual bool getNextPoint(btVector3& point) = 0;
};
class SpherePointGenerator : public PointGenerator
{
private:
btVector3 m_center;
float m_radius;
int m_num_points;
int m_current_point;
public:
// --------------------------------------------------------------------
SpherePointGenerator(const btVector3& center, float radius,
int num_points)
{
m_center = center;
m_radius = radius;
m_num_points = num_points;
m_current_point = 0;
}
// --------------------------------------------------------------------
bool getNextPoint(btVector3& point);
};
public:
// ------------------------------------------------------------------------
GEOcclusionCulling();
// ------------------------------------------------------------------------
~GEOcclusionCulling();
// ------------------------------------------------------------------------
void addOccluderMesh(const std::vector<std::array<btVector3, 3> >& tris);
// ------------------------------------------------------------------------
bool isOccluded(const irr::core::vector3df& cam_pos,
const irr::core::aabbox3df& aabbox)
{
// Use sphere test for now, testing the aabbox against the frustum
// should be done first.
float radius = aabbox.getExtent().getLength() / 2.0f;
return isOccluded(cam_pos, aabbox.getCenter(), radius);
}
// ------------------------------------------------------------------------
bool isOccluded(const irr::core::vector3df& cam_pos,
const irr::core::vector3df& irr_center, float radius);
};
}
#endif
@@ -0,0 +1,64 @@
/* ==========================================================================
* Copyright (c) 2022 SuperTuxKart-Team
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to permit
* persons to whom the Software is 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 Software.
*
* THE SOFTWARE IS 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 SOFTWARE OR THE
* USE OR OTHER DEALINGS IN THE SOFTWARE.
* ==========================================================================
*/
#ifndef HEADER_GE_RENDER_INFO_HPP
#define HEADER_GE_RENDER_INFO_HPP
#include "SColor.h"
namespace GE
{
class GERenderInfo
{
private:
float m_hue;
bool m_transparent;
irr::video::SColor m_vertex_color;
public:
// ------------------------------------------------------------------------
GERenderInfo(float hue = 0.0f, bool transparent = false)
{
m_hue = hue;
m_transparent = transparent;
m_vertex_color = (irr::video::SColor)-1;
}
// ------------------------------------------------------------------------
void setHue(float hue) { m_hue = hue; }
// ------------------------------------------------------------------------
void setTransparent(bool transparent) { m_transparent = transparent; }
// ------------------------------------------------------------------------
float getHue() const { return m_hue; }
// ------------------------------------------------------------------------
bool isTransparent() const { return m_transparent; }
// ------------------------------------------------------------------------
irr::video::SColor& getVertexColor() { return m_vertex_color; }
}; // GERenderInfo
} // namespace GE
#endif
@@ -0,0 +1,14 @@
#ifndef HEADER_GE_SPIN_LOCK_HPP
#define HEADER_GE_SPIN_LOCK_HPP
#include <atomic>
class GESpinLock
{
mutable std::atomic_flag m_locked = ATOMIC_FLAG_INIT;
public:
void lock() const
{ while (m_locked.test_and_set(std::memory_order_acquire)); }
void unlock() const { m_locked.clear(std::memory_order_release); }
};
#endif
+92
View File
@@ -0,0 +1,92 @@
#ifndef HEADER_GE_SPM_HPP
#define HEADER_GE_SPM_HPP
#include <array>
#include <cassert>
#include <IAnimatedMesh.h>
#include <vector>
using namespace irr;
using namespace scene;
class B3DMeshLoader;
class SPMeshLoader;
namespace GE
{
struct Armature;
class GESPMBuffer;
class GESPM : public IAnimatedMesh
{
friend class ::B3DMeshLoader;
friend class ::SPMeshLoader;
private:
std::vector<GESPMBuffer*> m_buffer;
core::aabbox3d<f32> m_bounding_box;
float m_fps;
unsigned m_bind_frame, m_total_joints, m_joint_using, m_frame_count;
std::vector<Armature> m_all_armatures;
public:
// ------------------------------------------------------------------------
GESPM();
// ------------------------------------------------------------------------
virtual ~GESPM();
// ------------------------------------------------------------------------
virtual u32 getFrameCount() const { return m_frame_count; }
// ------------------------------------------------------------------------
virtual f32 getAnimationSpeed() const { return m_fps; }
// ------------------------------------------------------------------------
virtual void setAnimationSpeed(f32 fps) { m_fps = fps; }
// ------------------------------------------------------------------------
virtual IMesh* getMesh(s32 frame, s32 detailLevel=255,
s32 startFrameLoop=-1, s32 endFrameLoop=-1)
{ return this; }
// ------------------------------------------------------------------------
virtual u32 getMeshBufferCount() const
{ return (unsigned)m_buffer.size(); }
// ------------------------------------------------------------------------
virtual IMeshBuffer* getMeshBuffer(u32 nr) const;
// ------------------------------------------------------------------------
virtual IMeshBuffer* getMeshBuffer(const video::SMaterial &material) const;
// ------------------------------------------------------------------------
virtual const core::aabbox3d<f32>& getBoundingBox() const
{ return m_bounding_box; }
// ------------------------------------------------------------------------
virtual void setBoundingBox(const core::aabbox3df& box)
{ m_bounding_box = box; }
// ------------------------------------------------------------------------
virtual void setMaterialFlag(video::E_MATERIAL_FLAG flag, bool newvalue) {}
// ------------------------------------------------------------------------
virtual void setHardwareMappingHint(E_HARDWARE_MAPPING newMappingHint,
E_BUFFER_TYPE buffer) {}
// ------------------------------------------------------------------------
virtual void setDirty(E_BUFFER_TYPE buffer=EBT_VERTEX_AND_INDEX) {}
// ------------------------------------------------------------------------
virtual E_ANIMATED_MESH_TYPE getMeshType() const { return EAMT_SPM; }
// ------------------------------------------------------------------------
virtual void finalize();
// ------------------------------------------------------------------------
std::vector<Armature>& getArmatures() { return m_all_armatures; }
// ------------------------------------------------------------------------
void getSkinningMatrices(f32 frame, std::vector<core::matrix4>& dest,
float frame_interpolating = -1.0f, float rate = -1.0f);
// ------------------------------------------------------------------------
s32 getJointIDWithArm(const c8* name, unsigned* arm_id) const;
// ------------------------------------------------------------------------
bool isStatic() const { return m_all_armatures.empty(); }
// ------------------------------------------------------------------------
unsigned getJointCount() const { return m_joint_using; }
// ------------------------------------------------------------------------
void addMeshBuffer(GESPMBuffer* mb) { m_buffer.push_back(mb); }
// ------------------------------------------------------------------------
void removeMeshBuffer(u32 nr);
};
}
#endif
@@ -0,0 +1,216 @@
#ifndef HEADER_GE_SPM_BUFFER_HPP
#define HEADER_GE_SPM_BUFFER_HPP
#include <array>
#include <cstddef>
#include <vector>
#include "IMeshBuffer.h"
#include "ge_vma.hpp"
#include "vulkan_wrapper.h"
namespace GE
{
class GESPMBuffer : public irr::scene::IMeshBuffer
{
protected:
irr::video::SMaterial m_material;
std::vector<irr::video::S3DVertexSkinnedMesh> m_vertices;
std::vector<irr::u16> m_indices;
private:
irr::core::aabbox3d<irr::f32> m_bounding_box;
size_t m_vbo_offset;
size_t m_ibo_offset;
size_t m_skinning_vbo_offset;
VkBuffer m_buffer;
VmaAllocation m_memory;
bool m_has_skinning;
public:
// ------------------------------------------------------------------------
GESPMBuffer()
{
m_vbo_offset = 0;
m_ibo_offset = 0;
m_skinning_vbo_offset = 0;
m_buffer = VK_NULL_HANDLE;
m_memory = VK_NULL_HANDLE;
m_has_skinning = false;
}
// ------------------------------------------------------------------------
~GESPMBuffer() { destroyVertexIndexBuffer(); }
// ------------------------------------------------------------------------
virtual const irr::video::SMaterial& getMaterial() const
{ return m_material; }
// ------------------------------------------------------------------------
virtual irr::video::SMaterial& getMaterial() { return m_material; }
// ------------------------------------------------------------------------
virtual const void* getVertices() const { return m_vertices.data(); }
// ------------------------------------------------------------------------
virtual void* getVertices() { return m_vertices.data(); }
// ------------------------------------------------------------------------
virtual irr::u32 getVertexCount() const { return m_vertices.size(); }
// ------------------------------------------------------------------------
virtual irr::video::E_INDEX_TYPE getIndexType() const
{ return irr::video::EIT_16BIT; }
// ------------------------------------------------------------------------
virtual const irr::u16* getIndices() const { return m_indices.data(); }
// ------------------------------------------------------------------------
virtual irr::u16* getIndices() { return m_indices.data(); }
// ------------------------------------------------------------------------
virtual irr::u32 getIndexCount() const { return m_indices.size(); }
// ------------------------------------------------------------------------
virtual const irr::core::aabbox3d<irr::f32>& getBoundingBox() const
{ return m_bounding_box; }
// ------------------------------------------------------------------------
virtual void setBoundingBox(const irr::core::aabbox3df& box)
{ m_bounding_box = box; }
// ------------------------------------------------------------------------
virtual void recalculateBoundingBox()
{
if (m_vertices.empty())
m_bounding_box.reset(0, 0, 0);
else
{
m_bounding_box.reset(m_vertices[0].m_position);
for (irr::u32 i = 1; i < m_vertices.size(); i++)
m_bounding_box.addInternalPoint(m_vertices[i].m_position);
}
}
// ------------------------------------------------------------------------
virtual irr::video::E_VERTEX_TYPE getVertexType() const
{ return irr::video::EVT_SKINNED_MESH; }
// ------------------------------------------------------------------------
virtual const irr::core::vector3df& getPosition(irr::u32 i) const
{ return m_vertices[i].m_position; }
// ------------------------------------------------------------------------
virtual irr::core::vector3df& getPosition(irr::u32 i)
{ return m_vertices[i].m_position; }
// ------------------------------------------------------------------------
virtual const irr::core::vector3df& getNormal(irr::u32 i) const
{
static irr::core::vector3df unused;
return unused;
}
// ------------------------------------------------------------------------
virtual irr::core::vector3df& getNormal(irr::u32 i)
{
static irr::core::vector3df unused;
return unused;
}
// ------------------------------------------------------------------------
virtual void setNormal(irr::u32 i, const irr::core::vector3df& normal);
// ------------------------------------------------------------------------
virtual const irr::core::vector2df& getTCoords(irr::u32 i) const
{
static irr::core::vector2df unused;
return unused;
}
// ------------------------------------------------------------------------
virtual irr::core::vector2df& getTCoords(irr::u32 i)
{
static irr::core::vector2df unused;
return unused;
}
// ------------------------------------------------------------------------
virtual void setTCoords(irr::u32 i, const irr::core::vector2df& tcoords);
// ------------------------------------------------------------------------
virtual irr::scene::E_PRIMITIVE_TYPE getPrimitiveType() const
{ return irr::scene::EPT_TRIANGLES; }
// ------------------------------------------------------------------------
virtual void append(const void* const vertices, irr::u32 num_vertices,
const irr::u16* const indices, irr::u32 num_indices)
{
if (vertices == getVertices())
return;
irr::u32 vertex_count = getVertexCount();
m_vertices.reserve(vertex_count + num_vertices);
for (irr::u32 i = 0; i < num_vertices; i++)
{
m_vertices.push_back(reinterpret_cast<
const irr::video::S3DVertexSkinnedMesh*>(vertices)[i]);
m_bounding_box.addInternalPoint(reinterpret_cast<
const irr::video::S3DVertexSkinnedMesh*>(vertices)[i].m_position);
}
m_indices.reserve(getIndexCount() + num_indices);
for (irr::u32 i = 0; i < num_indices; i++)
m_indices.push_back(indices[i] + vertex_count);
}
// ------------------------------------------------------------------------
virtual void append(const IMeshBuffer* const other) {}
// ------------------------------------------------------------------------
virtual irr::scene::E_HARDWARE_MAPPING getHardwareMappingHint_Vertex() const
{ return irr::scene::EHM_NEVER; }
// ------------------------------------------------------------------------
virtual irr::scene::E_HARDWARE_MAPPING getHardwareMappingHint_Index() const
{ return irr::scene::EHM_NEVER; }
// ------------------------------------------------------------------------
virtual void setHardwareMappingHint(irr::scene::E_HARDWARE_MAPPING NewMappingHint,
irr::scene::E_BUFFER_TYPE Buffer = irr::scene::EBT_VERTEX_AND_INDEX)
{}
// ------------------------------------------------------------------------
virtual void setDirty(irr::scene::E_BUFFER_TYPE Buffer = irr::scene::EBT_VERTEX_AND_INDEX)
{}
// ------------------------------------------------------------------------
virtual irr::u32 getChangedID_Vertex() const { return 0; }
// ------------------------------------------------------------------------
virtual irr::u32 getChangedID_Index() const { return 0; }
// ------------------------------------------------------------------------
void setVBOOffset(size_t offset) { m_vbo_offset = offset; }
// ------------------------------------------------------------------------
virtual size_t getVBOOffset() const { return m_vbo_offset; }
// ------------------------------------------------------------------------
void setIBOOffset(size_t offset) { m_ibo_offset = offset; }
// ------------------------------------------------------------------------
virtual size_t getIBOOffset() const { return m_ibo_offset; }
// ------------------------------------------------------------------------
bool hasSkinning() const { return m_has_skinning; }
// ------------------------------------------------------------------------
void setHasSkinning(bool val) { m_has_skinning = val; }
// ------------------------------------------------------------------------
virtual void bindVertexIndexBuffer(VkCommandBuffer cmd)
{
VkBuffer buffer = getVkBuffer();
std::array<VkBuffer, 2> vertex_buffer =
{{
buffer,
buffer
}};
std::array<VkDeviceSize, 2> offsets =
{{
0,
m_skinning_vbo_offset
}};
vkCmdBindVertexBuffers(cmd, 0, vertex_buffer.size(),
vertex_buffer.data(), offsets.data());
vkCmdBindIndexBuffer(cmd, buffer, getIBOOffset(),
VK_INDEX_TYPE_UINT16);
}
// ------------------------------------------------------------------------
virtual void createVertexIndexBuffer();
// ------------------------------------------------------------------------
virtual void destroyVertexIndexBuffer();
// ------------------------------------------------------------------------
std::vector<irr::video::S3DVertexSkinnedMesh>& getVerticesVector()
{ return m_vertices; }
// ------------------------------------------------------------------------
std::vector<irr::u16>& getIndicesVector() { return m_indices; }
// ------------------------------------------------------------------------
virtual VkBuffer getVkBuffer() const { return m_buffer; }
};
} // end namespace GE
#endif
@@ -0,0 +1,35 @@
#ifndef HEADER_GE_TEXTURE_HPP
#define HEADER_GE_TEXTURE_HPP
#include <functional>
#include <string>
#include <ITexture.h>
#include <IImage.h>
#include <IReadFile.h>
namespace GE
{
irr::video::ITexture* createFontTexture(const std::string& name,
unsigned size, bool single_channel);
irr::video::ITexture* createTexture(irr::video::IImage* img,
const std::string& name);
irr::core::dimension2d<irr::u32> getResizingTarget(
const irr::core::dimension2d<irr::u32>& orig_size,
const irr::core::dimension2d<irr::u32>& max_size);
irr::video::IImage* getResizedImage(const std::string& path,
const irr::core::dimension2d<irr::u32>& max_size,
irr::core::dimension2d<irr::u32>* orig_size = NULL,
const irr::core::dimension2d<irr::u32>* target_size = NULL);
irr::video::IImage* getResizedImageFullPath(const irr::io::path& fullpath,
const irr::core::dimension2d<irr::u32>& max_size,
irr::core::dimension2d<irr::u32>* orig_size = NULL,
const irr::core::dimension2d<irr::u32>* target_size = NULL);
irr::video::IImage* getResizedImage(irr::io::IReadFile* file,
const irr::core::dimension2d<irr::u32>& max_size,
irr::core::dimension2d<irr::u32>* orig_size = NULL,
const irr::core::dimension2d<irr::u32>* target_size = NULL);
irr::video::ITexture* createTexture(const std::string& path,
std::function<void(irr::video::IImage*)> image_mani = nullptr);
}; // GE
#endif
+19
View File
@@ -0,0 +1,19 @@
#ifndef HEADER_GE_VMA_HPP
#define HEADER_GE_VMA_HPP
#include "vulkan_wrapper.h"
// Remove clang warnings
#define VMA_NULLABLE
#define VMA_NOT_NULL
#if !defined(__APPLE__) || defined(DLOPEN_MOLTENVK)
#define VMA_STATIC_VULKAN_FUNCTIONS 0
#define VMA_DYNAMIC_VULKAN_FUNCTIONS 1
#elif defined(IOS_STK)
// MoltenVK doesn't provide full 1.3 support, which will lead to linking errors
#define VMA_VULKAN_VERSION 1002000
#endif
#include "vk_mem_alloc.h"
#endif
@@ -0,0 +1,561 @@
#ifndef __VULKAN_DRIVER_INCLUDED__
#define __VULKAN_DRIVER_INCLUDED__
#include "IrrCompileConfig.h"
#ifdef _IRR_COMPILE_WITH_VULKAN_
#include "vulkan_wrapper.h"
#include "ge_vma.hpp"
#include "SDL_video.h"
#include "../source/Irrlicht/CNullDriver.h"
#include "SIrrCreationParameters.h"
#include "SColor.h"
#include <array>
#include <memory>
#include <mutex>
#include <set>
#include <string>
#include <vector>
using namespace irr;
using namespace video;
namespace GE
{
class GESPM;
class GEVulkanAttachmentTexture;
class GEVulkanCameraSceneNode;
class GEVulkanDrawCall;
class GEVulkanDynamicSPMBuffer;
class GEVulkanFBOTexture;
class GEVulkanMeshCache;
class GEVulkanSkyBoxRenderer;
class GEVulkanTextureDescriptor;
enum GEVulkanSampler : unsigned
{
GVS_MIN = 0,
GVS_NEAREST = GVS_MIN,
GVS_SKYBOX,
GVS_3D_MESH_MIPMAP_2,
GVS_3D_MESH_MIPMAP_4,
GVS_3D_MESH_MIPMAP_16,
GVS_2D_RENDER,
GVS_SHADOW,
GVS_COUNT,
};
class GEVulkanDriver : public video::CNullDriver
{
public:
//! constructor
GEVulkanDriver(const SIrrlichtCreationParameters& params, io::IFileSystem* io, SDL_Window* window,
IrrlichtDevice* device);
//! destructor
virtual ~GEVulkanDriver();
//! applications must call this method before performing any rendering. returns false if failed.
virtual bool beginScene(bool backBuffer=true, bool zBuffer=true,
SColor color=SColor(255,0,0,0),
const SExposedVideoData& videoData=SExposedVideoData(),
core::rect<s32>* sourceRect=0);
//! applications must call this method after performing any rendering. returns false if failed.
virtual bool endScene();
//! queries the features of the driver, returns true if feature is available
virtual bool queryFeature(E_VIDEO_DRIVER_FEATURE feature) const { return true; }
//! sets transformation
virtual void setTransform(E_TRANSFORMATION_STATE state, const core::matrix4& mat) {}
//! sets a material
virtual void setMaterial(const SMaterial& material) { Material = material; }
//! sets a render target
virtual bool setRenderTarget(video::ITexture* texture,
bool clearBackBuffer=true, bool clearZBuffer=true,
SColor color=video::SColor(0,0,0,0));
//! Sets multiple render targets
virtual bool setRenderTarget(const core::array<video::IRenderTarget>& texture,
bool clearBackBuffer=true, bool clearZBuffer=true,
SColor color=video::SColor(0,0,0,0)) { return true; }
//! sets a viewport
virtual void setViewPort(const core::rect<s32>& area);
//! updates hardware buffer if needed
virtual bool updateHardwareBuffer(SHWBufferLink *HWBuffer) { return false; }
//! Create hardware buffer from mesh
virtual SHWBufferLink *createHardwareBuffer(const scene::IMeshBuffer* mb) { return NULL; }
//! Delete hardware buffer (only some drivers can)
virtual void deleteHardwareBuffer(SHWBufferLink *HWBuffer) {}
//! Draw hardware buffer
virtual void drawHardwareBuffer(SHWBufferLink *HWBuffer) {}
//! Create occlusion query.
/** Use node for identification and mesh for occlusion test. */
virtual void addOcclusionQuery(scene::ISceneNode* node,
const scene::IMesh* mesh=0) {}
//! Remove occlusion query.
virtual void removeOcclusionQuery(scene::ISceneNode* node) {}
//! Run occlusion query. Draws mesh stored in query.
/** If the mesh shall not be rendered visible, use
overrideMaterial to disable the color and depth buffer. */
virtual void runOcclusionQuery(scene::ISceneNode* node, bool visible=false) {}
//! Update occlusion query. Retrieves results from GPU.
/** If the query shall not block, set the flag to false.
Update might not occur in this case, though */
virtual void updateOcclusionQuery(scene::ISceneNode* node, bool block=true) {}
//! Return query result.
/** Return value is the number of visible pixels/fragments.
The value is a safe approximation, i.e. can be larger then the
actual value of pixels. */
virtual u32 getOcclusionQueryResult(scene::ISceneNode* node) const { return 0; }
//! draws a vertex primitive list
virtual void drawVertexPrimitiveList(const void* vertices, u32 vertexCount,
const void* indexList, u32 primitiveCount,
E_VERTEX_TYPE vType, scene::E_PRIMITIVE_TYPE pType,
E_INDEX_TYPE iType) {}
//! draws a vertex primitive list in 2d
virtual void draw2DVertexPrimitiveList(const void* vertices, u32 vertexCount,
const void* indexList, u32 primitiveCount,
E_VERTEX_TYPE vType, scene::E_PRIMITIVE_TYPE pType,
E_INDEX_TYPE iType);
//! draws an 2d image, using a color (if color is other then Color(255,255,255,255)) and the alpha channel of the texture if wanted.
virtual void draw2DImage(const video::ITexture* texture, const core::position2d<s32>& destPos,
const core::rect<s32>& sourceRect, const core::rect<s32>* clipRect = 0,
SColor color=SColor(255,255,255,255), bool useAlphaChannelOfTexture=false);
//! Draws a part of the texture into the rectangle.
virtual void draw2DImage(const video::ITexture* texture, const core::rect<s32>& destRect,
const core::rect<s32>& sourceRect, const core::rect<s32>* clipRect = 0,
const video::SColor* const colors=0, bool useAlphaChannelOfTexture=false);
//! Draws a set of 2d images, using a color and the alpha channel of the texture.
virtual void draw2DImageBatch(const video::ITexture* texture,
const core::array<core::position2d<s32> >& positions,
const core::array<core::rect<s32> >& sourceRects,
const core::rect<s32>* clipRect=0,
SColor color=SColor(255,255,255,255),
bool useAlphaChannelOfTexture=false);
//!Draws an 2d rectangle with a gradient.
virtual void draw2DRectangle(const core::rect<s32>& pos,
SColor colorLeftUp, SColor colorRightUp, SColor colorLeftDown, SColor colorRightDown,
const core::rect<s32>* clip)
{
SColor color[4] = { colorLeftUp, colorLeftDown, colorRightDown, colorRightUp };
draw2DImage(m_white_texture, pos, core::recti(0, 0, 2, 2), clip, color, true);
}
//! Draws a 2d line.
virtual void draw2DLine(const core::position2d<s32>& start,
const core::position2d<s32>& end,
SColor color=SColor(255,255,255,255)) {}
//! Draws a pixel.
virtual void drawPixel(u32 x, u32 y, const SColor & color) {}
//! Draws a 3d line.
virtual void draw3DLine(const core::vector3df& start,
const core::vector3df& end, SColor color = SColor(255,255,255,255)) {}
//! \return Returns the name of the video driver. Example: In case of the DIRECT3D8
//! driver, it would return "Direct3D8.1".
virtual const wchar_t* getName() const { return L""; }
//! deletes all dynamic lights there are
virtual void deleteAllDynamicLights() {}
//! adds a dynamic light, returning an index to the light
//! \param light: the light data to use to create the light
//! \return An index to the light, or -1 if an error occurs
virtual s32 addDynamicLight(const SLight& light) { return -1; }
//! Turns a dynamic light on or off
//! \param lightIndex: the index returned by addDynamicLight
//! \param turnOn: true to turn the light on, false to turn it off
virtual void turnLightOn(s32 lightIndex, bool turnOn) {}
//! returns the maximal amount of dynamic lights the device can handle
virtual u32 getMaximalDynamicLightAmount() const { return (u32)-1; }
//! Sets the dynamic ambient light color. The default color is
//! (0,0,0,0) which means it is dark.
//! \param color: New color of the ambient light.
virtual void setAmbientLight(const SColorf& color) { CNullDriver::setAmbientLight(color); }
//! Draws a shadow volume into the stencil buffer.
virtual void drawStencilShadowVolume(const core::array<core::vector3df>& triangles, bool zfail=true, u32 debugDataVisible=0) {}
//! Fills the stencil shadow with color.
virtual void drawStencilShadow(bool clearStencilBuffer=false,
video::SColor leftUpEdge = video::SColor(0,0,0,0),
video::SColor rightUpEdge = video::SColor(0,0,0,0),
video::SColor leftDownEdge = video::SColor(0,0,0,0),
video::SColor rightDownEdge = video::SColor(0,0,0,0)) {}
//! Returns the maximum amount of primitives (mostly vertices) which
//! the device is able to render with one drawIndexedTriangleList
//! call.
virtual u32 getMaximalPrimitiveCount() const { return (u32)-1; }
//! Enables or disables a texture creation flag.
virtual void setTextureCreationFlag(E_TEXTURE_CREATION_FLAG flag, bool enabled) {}
//! Sets the fog mode.
virtual void setFog(SColor color, E_FOG_TYPE fogType, f32 start,
f32 end, f32 density, bool pixelFog, bool rangeFog) {}
//! Only used by the internal engine. Used to notify the driver that
//! the window was resized.
virtual void OnResize(const core::dimension2d<u32>& size);
//! Returns type of video driver
virtual E_DRIVER_TYPE getDriverType() const { return video::EDT_VULKAN; }
//! Returns the transformation set by setTransform
virtual const core::matrix4& getTransform(E_TRANSFORMATION_STATE state) const
{
static core::matrix4 unused;
return unused;
}
//! Creates a render target texture.
virtual ITexture* addRenderTargetTexture(const core::dimension2d<u32>& size,
const io::path& name, const ECOLOR_FORMAT format = ECF_UNKNOWN, const bool useStencil = false);
//! Clears the ZBuffer.
virtual void clearZBuffer() {}
//! Returns an image created from the last rendered frame.
virtual IImage* createScreenShot(video::ECOLOR_FORMAT format=video::ECF_UNKNOWN, video::E_RENDER_TARGET target=video::ERT_FRAME_BUFFER) { return NULL; }
//! Set/unset a clipping plane.
virtual bool setClipPlane(u32 index, const core::plane3df& plane, bool enable=false) { return true; }
//! Enable/disable a clipping plane.
virtual void enableClipPlane(u32 index, bool enable) {}
//! Returns the graphics card vendor name.
virtual core::stringc getVendorInfo()
{
switch (m_properties.vendorID)
{
case 0x1002: return "AMD";
case 0x1010: return "ImgTec";
case 0x106B: return "Apple";
case 0x10DE: return "NVIDIA";
case 0x13B5: return "ARM";
case 0x14e4: return "Broadcom";
case 0x5143: return "Qualcomm";
case 0x8086: return "INTEL";
// llvmpipe
case 0x10005: return "Mesa";
default: return "Unknown";
}
}
//! Enable the 2d override material
virtual void enableMaterial2D(bool enable=true) {}
//! Check if the driver was recently reset.
virtual bool checkDriverReset() { return false; }
//! Get the current color format of the color buffer
/** \return Color format of the color buffer. */
virtual ECOLOR_FORMAT getColorFormat() const { return ECF_A8R8G8B8; }
//! Returns the maximum texture size supported.
virtual core::dimension2du getMaxTextureSize() const { return core::dimension2du(16384, 16384); }
virtual void enableScissorTest(const core::rect<s32>& r) { m_clip = r; }
core::rect<s32> getFullscreenClip() const
{
return core::rect<s32>(0, 0, ScreenSize.Width, ScreenSize.Height);
}
virtual void disableScissorTest() { m_clip = getFullscreenClip(); }
virtual const core::dimension2d<u32>& getCurrentRenderTargetSize() const { return ScreenSize; }
VkSampler getSampler(GEVulkanSampler s) const
{
if (s >= GVS_COUNT)
return VK_NULL_HANDLE;
return m_vk->samplers[s];
}
VkDevice getDevice() const { return m_vk->device; }
void destroyVulkan();
bool createBuffer(VkDeviceSize size, VkBufferUsageFlags usage,
VmaAllocationCreateInfo& alloc_create_info,
VkBuffer& buffer, VmaAllocation& buffer_allocation);
VkPhysicalDevice getPhysicalDevice() const { return m_physical_device; }
const VkPhysicalDeviceFeatures& getPhysicalDeviceFeatures() const
{ return m_features; }
const VkPhysicalDeviceProperties& getPhysicalDeviceProperties() const
{ return m_properties; }
VkExtent2D getSwapChainExtent() const { return m_swap_chain_extent; }
size_t getSwapChainImagesCount() const
{ return m_vk->swap_chain_images.size(); }
VkRenderPass getRenderPass() const { return m_vk->render_pass; }
void copyBuffer(VkBuffer src_buffer, VkBuffer dst_buffer, VkDeviceSize size);
VkCommandBuffer getCurrentCommandBuffer()
{ return m_vk->command_buffers[m_current_frame]; }
std::vector<VkImage>& getSwapChainImages()
{ return m_vk->swap_chain_images; }
std::vector<VkImageView>& getSwapChainImageViews()
{ return m_vk->swap_chain_image_views; }
VkFormat getSwapChainImageFormat() { return m_swap_chain_image_format; }
std::vector<VkFramebuffer>& getSwapChainFramebuffers()
{ return m_vk->swap_chain_framebuffers; }
unsigned int getCurrentFrame() const { return m_current_frame; }
unsigned int getCurrentImageIndex() const { return m_image_index; }
constexpr static unsigned getMaxFrameInFlight() { return 2; }
video::SColor getClearColor() const { return m_clear_color; }
video::SColor getRTTClearColor() const { return m_rtt_clear_color; }
const core::rect<s32>& getCurrentClip() const { return m_clip; }
video::ITexture* getWhiteTexture() const { return m_white_texture; }
video::ITexture* getTransparentTexture() const
{ return m_transparent_texture; }
void getRotatedRect2D(VkRect2D* rect);
void getRotatedViewport(VkViewport* vp, bool handle_rtt);
const core::matrix4& getPreRotationMatrix()
{ return m_pre_rotation_matrix; }
virtual void pauseRendering();
virtual void unpauseRendering();
void updateSwapInterval(int value)
{
if (m_params.SwapInterval == value)
return;
m_params.SwapInterval = value;
destroySwapChainRelated(false/*handle_surface*/);
createSwapChainRelated(false/*handle_surface*/);
}
void updateDriver(bool scale_changed = true, bool pbr_changed = false,
bool ibl_changed = false);
void reloadShaders();
uint32_t getGraphicsFamily() const { return m_graphics_family; }
unsigned getGraphicsQueueCount() const
{ return m_graphics_queue_count; }
std::unique_lock<std::mutex> getGraphicsQueue(VkQueue* queue) const;
void waitIdle(bool flush_command_loader = false);
void setDisableWaitIdle(bool val) { m_disable_wait_idle = val; }
IrrlichtDevice* getIrrlichtDevice() const { return m_irrlicht_device; }
GEVulkanAttachmentTexture* getDepthTexture() const
{ return m_depth_texture; }
VkFormat findSupportedFormat(const std::vector<VkFormat>& candidates,
VkImageTiling tiling,
VkFormatFeatureFlags features);
VmaAllocator getVmaAllocator() const { return m_vk->allocator; }
GEVulkanMeshCache* getVulkanMeshCache() const;
GEVulkanSkyBoxRenderer* getSkyBoxRenderer() const
{ return m_skybox_renderer; }
GEVulkanTextureDescriptor* getMeshTextureDescriptor() const
{ return m_mesh_texture_descriptor; }
GEVulkanFBOTexture* getRTTTexture() const { return m_rtt_texture; }
GEVulkanFBOTexture* getSeparateRTTTexture() const
{ return m_separate_rtt_texture; }
void handleDeletedTextures();
void addRTTPolyCount(unsigned count) { m_rtt_polycount += count; }
SDL_Window* getSDLWindow() const { return m_params.m_sdl_window; }
void clearDrawCallsCache();
void addDrawCallToCache(std::unique_ptr<GEVulkanDrawCall>& dc);
std::unique_ptr<GEVulkanDrawCall> getDrawCallFromCache();
GESPM* getBillboardQuad() const { return m_billboard_quad; }
int getCurrentBufferIdx() const { return m_current_buffer_idx; }
void addDynamicSPMBuffer(GEVulkanDynamicSPMBuffer* buffer)
{ m_dynamic_spm_buffers.insert(buffer); }
void removeDynamicSPMBuffer(GEVulkanDynamicSPMBuffer* buffer)
{ m_dynamic_spm_buffers.erase(buffer); }
void renderDrawCalls(const std::vector<std::pair<GEVulkanDrawCall*, GEVulkanCameraSceneNode*> >& p,
VkCommandBuffer cmd);
private:
struct SwapChainSupportDetails
{
VkSurfaceCapabilitiesKHR capabilities;
std::vector<VkSurfaceFormatKHR> formats;
std::vector<VkPresentModeKHR> presentModes;
};
//! returns a device dependent texture from a software surface (IImage)
//! THIS METHOD HAS TO BE OVERRIDDEN BY DERIVED DRIVERS WITH OWN TEXTURES
virtual video::ITexture* createDeviceDependentTexture(IImage* surface, const io::path& name, void* mipmapData=0) { return NULL; }
//! Adds a new material renderer to the VideoDriver, based on a high level shading
//! language.
virtual s32 addHighLevelShaderMaterial(
const c8* vertexShaderProgram,
const c8* vertexShaderEntryPointName,
E_VERTEX_SHADER_TYPE vsCompileTarget,
const c8* pixelShaderProgram,
const c8* pixelShaderEntryPointName,
E_PIXEL_SHADER_TYPE psCompileTarget,
const c8* geometryShaderProgram,
const c8* geometryShaderEntryPointName = "main",
E_GEOMETRY_SHADER_TYPE gsCompileTarget = EGST_GS_4_0,
scene::E_PRIMITIVE_TYPE inType = scene::EPT_TRIANGLES,
scene::E_PRIMITIVE_TYPE outType = scene::EPT_TRIANGLE_STRIP,
u32 verticesOut = 0,
IShaderConstantSetCallBack* callback = 0,
E_MATERIAL_TYPE baseMaterial = video::EMT_SOLID,
s32 userData = 0,
E_GPU_SHADING_LANGUAGE shadingLang = EGSL_DEFAULT) { return 0; }
SIrrlichtCreationParameters m_params;
SMaterial Material;
// RAII to auto cleanup
struct VK
{
VkInstance instance;
VkDebugUtilsMessengerEXT debug;
VkSurfaceKHR surface;
VkDevice device;
VmaAllocator allocator;
VkSwapchainKHR swap_chain;
std::vector<VkImage> swap_chain_images;
std::vector<VkImageView> swap_chain_image_views;
std::vector<VkSemaphore> image_available_semaphores;
std::vector<VkSemaphore> render_finished_semaphores;
std::vector<VkFence> in_flight_fences;
std::vector<VkCommandPool> command_pools;
std::vector<VkCommandBuffer> command_buffers;
std::array<VkSampler, GVS_COUNT> samplers;
VkRenderPass render_pass;
std::vector<VkFramebuffer> swap_chain_framebuffers;
VK()
{
instance = VK_NULL_HANDLE;
debug = VK_NULL_HANDLE;
surface = VK_NULL_HANDLE;
device = VK_NULL_HANDLE;
allocator = VK_NULL_HANDLE;
swap_chain = VK_NULL_HANDLE;
samplers = {{}};
render_pass = VK_NULL_HANDLE;
}
~VK()
{
for (unsigned i = 0; i < command_buffers.size(); i++)
{
vkFreeCommandBuffers(device, command_pools[i], 1,
&command_buffers[i]);
vkDestroyCommandPool(device, command_pools[i], NULL);
}
for (VkFramebuffer& framebuffer : swap_chain_framebuffers)
vkDestroyFramebuffer(device, framebuffer, NULL);
if (render_pass != VK_NULL_HANDLE)
vkDestroyRenderPass(device, render_pass, NULL);
if (device != VK_NULL_HANDLE)
{
for (unsigned i = 0; i < GVS_COUNT; i++)
vkDestroySampler(device, samplers[i], NULL);
}
for (VkSemaphore& semaphore : image_available_semaphores)
vkDestroySemaphore(device, semaphore, NULL);
for (VkSemaphore& semaphore : render_finished_semaphores)
vkDestroySemaphore(device, semaphore, NULL);
for (VkFence& fence : in_flight_fences)
vkDestroyFence(device, fence, NULL);
for (VkImageView& image_view : swap_chain_image_views)
vkDestroyImageView(device, image_view, NULL);
if (swap_chain != VK_NULL_HANDLE)
vkDestroySwapchainKHR(device, swap_chain, NULL);
if (allocator != VK_NULL_HANDLE)
vmaDestroyAllocator(allocator);
if (device != VK_NULL_HANDLE)
vkDestroyDevice(device, NULL);
if (surface != VK_NULL_HANDLE)
vkDestroySurfaceKHR(instance, surface, NULL);
if (vkDestroyDebugUtilsMessengerEXT && debug != VK_NULL_HANDLE)
vkDestroyDebugUtilsMessengerEXT(instance, debug, NULL);
if (instance != VK_NULL_HANDLE)
vkDestroyInstance(instance, NULL);
}
};
std::unique_ptr<VK> m_vk;
VkFormat m_swap_chain_image_format;
VkExtent2D m_swap_chain_extent;
VkPhysicalDevice m_physical_device;
std::vector<const char*> m_device_extensions;
VkSurfaceCapabilitiesKHR m_surface_capabilities;
std::vector<VkSurfaceFormatKHR> m_surface_formats;
std::vector<VkPresentModeKHR> m_present_modes;
std::vector<VkQueue> m_graphics_queue;
VkQueue m_present_queue;
mutable std::vector<std::mutex*> m_graphics_queue_mutexes;
uint32_t m_graphics_family;
uint32_t m_present_family;
unsigned m_graphics_queue_count;
VkPhysicalDeviceProperties m_properties;
VkPhysicalDeviceFeatures m_features;
unsigned int m_current_frame;
uint32_t m_image_index;
unsigned int m_current_semaphore;
video::SColor m_clear_color, m_rtt_clear_color;
core::rect<s32> m_clip;
core::matrix4 m_pre_rotation_matrix;
video::ITexture* m_white_texture;
video::ITexture* m_transparent_texture;
bool m_disable_wait_idle;
IrrlichtDevice* m_irrlicht_device;
GEVulkanAttachmentTexture* m_depth_texture;
GEVulkanSkyBoxRenderer* m_skybox_renderer;
GEVulkanTextureDescriptor* m_mesh_texture_descriptor;
GEVulkanFBOTexture* m_rtt_texture;
GEVulkanFBOTexture* m_prev_rtt_texture;
GEVulkanFBOTexture* m_separate_rtt_texture;
u32 m_rtt_polycount;
std::vector<std::unique_ptr<GEVulkanDrawCall> > m_draw_calls_cache;
GESPM* m_billboard_quad;
int m_current_buffer_idx;
std::set<GEVulkanDynamicSPMBuffer*> m_dynamic_spm_buffers;
void createInstance(SDL_Window* window);
void findPhysicalDevice();
bool checkDeviceExtensions(VkPhysicalDevice device);
bool findQueueFamilies(VkPhysicalDevice device, uint32_t* graphics_family, unsigned* graphics_queue_count, uint32_t* present_family);
bool updateSurfaceInformation(VkPhysicalDevice device,
VkSurfaceCapabilitiesKHR* surface_capabilities,
std::vector<VkSurfaceFormatKHR>* surface_formats,
std::vector<VkPresentModeKHR>* present_modes);
void createDevice();
void createSwapChain();
void createSyncObjects();
void createCommandBuffers();
void createSamplers();
void createRenderPass();
void createFramebuffers();
void createUnicolorTextures();
void initPreRotationMatrix();
std::string getVulkanVersionString() const;
std::string getDriverVersionString() const;
void destroySwapChainRelated(bool handle_surface);
void createSwapChainRelated(bool handle_surface);
void buildCommandBuffers();
void createBillboardQuad();
};
}
#endif // _IRR_COMPILE_WITH_VULKAN_
#endif // __VULKAN_DRIVER_INCLUDED__
@@ -0,0 +1,51 @@
#ifndef HEADER_GE_VULKAN_DYNAMIC_SPM_BUFFER_HPP
#define HEADER_GE_VULKAN_DYNAMIC_SPM_BUFFER_HPP
#include "ge_spm_buffer.hpp"
namespace GE
{
class GEVulkanDriver;
class GEVulkanDynamicBuffer;
class GEVulkanDynamicSPMBuffer : public GESPMBuffer
{
private:
GEVulkanDynamicBuffer* m_vertex_buffer;
GEVulkanDynamicBuffer* m_index_buffer;
GEVulkanDriver* m_vk;
uint32_t* m_vertex_update_offsets;
uint32_t* m_index_update_offsets;
public:
// ------------------------------------------------------------------------
GEVulkanDynamicSPMBuffer();
// ------------------------------------------------------------------------
~GEVulkanDynamicSPMBuffer();
// ------------------------------------------------------------------------
virtual irr::scene::E_HARDWARE_MAPPING getHardwareMappingHint_Vertex() const
{ return irr::scene::EHM_STREAM; }
// ------------------------------------------------------------------------
virtual irr::scene::E_HARDWARE_MAPPING getHardwareMappingHint_Index() const
{ return irr::scene::EHM_STREAM; }
// ------------------------------------------------------------------------
virtual void bindVertexIndexBuffer(VkCommandBuffer cmd) {}
// ------------------------------------------------------------------------
virtual void createVertexIndexBuffer() {}
// ------------------------------------------------------------------------
virtual void destroyVertexIndexBuffer() {}
// ------------------------------------------------------------------------
void updateVertexIndexBuffer(int buffer_index);
// ------------------------------------------------------------------------
void drawDynamicVertexIndexBuffer(VkCommandBuffer cmd, int buffer_index);
// ------------------------------------------------------------------------
void setDirtyOffset(irr::u32 offset,
irr::scene::E_BUFFER_TYPE buffer = irr::scene::EBT_VERTEX_AND_INDEX);
};
} // end namespace GE
#endif
@@ -0,0 +1,51 @@
#ifndef HEADER_GE_VULKAN_FEATURES_HPP
#define HEADER_GE_VULKAN_FEATURES_HPP
#include "vulkan_wrapper.h"
namespace GE
{
class GEVulkanDriver;
namespace GEVulkanFeatures
{
// ----------------------------------------------------------------------------
void init(GEVulkanDriver*);
// ----------------------------------------------------------------------------
void printStats();
// ----------------------------------------------------------------------------
bool supportsBindTexturesAtOnce();
// ----------------------------------------------------------------------------
bool supportsRGBA8Blit();
// ----------------------------------------------------------------------------
bool supportsR8Blit();
// ----------------------------------------------------------------------------
bool supportsDescriptorIndexing();
// ----------------------------------------------------------------------------
bool supportsNonUniformIndexing();
// ----------------------------------------------------------------------------
bool supportsDifferentTexturePerDraw();
// ----------------------------------------------------------------------------
bool supportsPartiallyBound();
// ----------------------------------------------------------------------------
bool supportsBindMeshTexturesAtOnce();
// ----------------------------------------------------------------------------
bool supportsMultiDrawIndirect();
// ----------------------------------------------------------------------------
bool supportsBaseVertexRendering();
// ----------------------------------------------------------------------------
bool supportsComputeInMainQueue();
// ----------------------------------------------------------------------------
bool supportsShaderDrawParameters();
// ----------------------------------------------------------------------------
bool supportsS3TCBC3();
// ----------------------------------------------------------------------------
bool supportsBPTCBC7();
// ----------------------------------------------------------------------------
bool supportsASTC4x4();
// ----------------------------------------------------------------------------
bool supportsShaderStorageImageExtendedFormats();
}; // GEVulkanFeatures
}
#endif
@@ -0,0 +1,79 @@
#ifndef HEADER_GE_VULKAN_SCENE_MANAGER_HPP
#define HEADER_GE_VULKAN_SCENE_MANAGER_HPP
#include "../source/Irrlicht/CSceneManager.h"
#include <memory>
#include <map>
namespace GE
{
class GEVulkanCameraSceneNode;
class GEVulkanDrawCall;
enum GEAutoDeferredType : unsigned;
class GEVulkanSceneManager : public irr::scene::CSceneManager
{
private:
unsigned m_pointlight_count, m_spotlight_count, m_displace_count;
std::map<GEVulkanCameraSceneNode*, std::unique_ptr<GEVulkanDrawCall> > m_draw_calls;
// ------------------------------------------------------------------------
void drawAllInternal();
// ------------------------------------------------------------------------
void resetDetectDeferred()
{
m_pointlight_count = m_spotlight_count = m_displace_count = 0;
}
// ------------------------------------------------------------------------
GEAutoDeferredType getDetectDeferredResult() const;
// ------------------------------------------------------------------------
void detectDeferred(irr::scene::ISceneNode* node);
public:
// ------------------------------------------------------------------------
GEVulkanSceneManager(irr::video::IVideoDriver* driver,
irr::io::IFileSystem* fs,
irr::gui::ICursorControl* cursor_control,
irr::gui::IGUIEnvironment* gui_environment);
// ------------------------------------------------------------------------
~GEVulkanSceneManager();
// ------------------------------------------------------------------------
virtual irr::scene::ICameraSceneNode* addCameraSceneNode(
irr::scene::ISceneNode* parent = 0,
const irr::core::vector3df& position = irr::core::vector3df(0, 0, 0),
const irr::core::vector3df& lookat = irr::core::vector3df(0, 0, 100),
irr::s32 id = -1, bool make_active = true);
// ------------------------------------------------------------------------
virtual irr::scene::IAnimatedMeshSceneNode* addAnimatedMeshSceneNode(
irr::scene::IAnimatedMesh* mesh, irr::scene::ISceneNode* parent = NULL,
irr::s32 id = -1,
const irr::core::vector3df& position = irr::core::vector3df(0, 0, 0),
const irr::core::vector3df& rotation = irr::core::vector3df(0, 0, 0),
const irr::core::vector3df& scale = irr::core::vector3df(1.0f, 1.0f, 1.0f),
bool alsoAddIfMeshPointerZero = false);
// ------------------------------------------------------------------------
virtual irr::scene::IMeshSceneNode* addMeshSceneNode(irr::scene::IMesh* mesh,
irr::scene::ISceneNode* parent = NULL, irr::s32 id = -1,
const irr::core::vector3df& position = irr::core::vector3df(0, 0, 0),
const irr::core::vector3df& rotation = irr::core::vector3df(0, 0, 0),
const irr::core::vector3df& scale = irr::core::vector3df(1.0f, 1.0f, 1.0f),
bool alsoAddIfMeshPointerZero = false);
// ------------------------------------------------------------------------
virtual void clear();
// ------------------------------------------------------------------------
virtual void drawAll(irr::u32 flags = 0xFFFFFFFF);
// ------------------------------------------------------------------------
virtual irr::u32 registerNodeForRendering(irr::scene::ISceneNode* node,
irr::scene::E_SCENE_NODE_RENDER_PASS pass = irr::scene::ESNRP_AUTOMATIC);
// ------------------------------------------------------------------------
void addDrawCall(GEVulkanCameraSceneNode* cam);
// ------------------------------------------------------------------------
void removeDrawCall(GEVulkanCameraSceneNode* cam);
// ------------------------------------------------------------------------
std::map<GEVulkanCameraSceneNode*, std::unique_ptr<GEVulkanDrawCall> >&
getDrawCalls() { return m_draw_calls; }
}; // GEVulkanSceneManager
}
#endif
@@ -0,0 +1,114 @@
#ifndef HEADER_GE_VULKAN_TEXTURE_DESCRIPTOR_HPP
#define HEADER_GE_VULKAN_TEXTURE_DESCRIPTOR_HPP
#include "vulkan_wrapper.h"
#include "IrrCompileConfig.h"
namespace irr
{
namespace video { class ITexture; }
}
#include <array>
#include <atomic>
#include <map>
#include <memory>
#include <string>
#include <vector>
namespace GE
{
class GEVulkanDriver;
enum GEVulkanSampler : unsigned;
class GEVulkanTextureDescriptor
{
typedef std::array<std::shared_ptr<std::atomic<VkImageView> >,
_IRR_MATERIAL_MAX_TEXTURES_> TextureList;
std::map<TextureList, int> m_texture_list;
std::shared_ptr<std::atomic<VkImageView> > m_white_image;
std::shared_ptr<std::atomic<VkImageView> > m_transparent_image;
VkDescriptorSetLayout m_descriptor_set_layout;
VkDescriptorPool m_descriptor_pool;
std::vector<VkDescriptorSet> m_descriptor_sets;
const unsigned m_max_texture_list;
const unsigned m_max_layer;
const unsigned m_binding;
GEVulkanSampler m_sampler_use;
GEVulkanDriver* m_vk;
bool m_recreate_next_frame;
bool m_needs_update_descriptor;
public:
// ------------------------------------------------------------------------
GEVulkanTextureDescriptor(unsigned max_texture_list, unsigned max_layer,
bool single_descriptor, unsigned binding = 0);
// ------------------------------------------------------------------------
~GEVulkanTextureDescriptor();
// ------------------------------------------------------------------------
void clear()
{
m_texture_list.clear();
m_needs_update_descriptor = true;
m_recreate_next_frame = false;
}
// ------------------------------------------------------------------------
void handleDeletedTextures()
{
bool has_deleted_image_view = false;
for (auto& p : m_texture_list)
{
for (auto& t : p.first)
{
if (t.get()->load() == VK_NULL_HANDLE)
{
has_deleted_image_view = true;
break;
}
}
}
if (has_deleted_image_view || m_recreate_next_frame)
clear();
}
// ------------------------------------------------------------------------
int getTextureID(const irr::video::ITexture** list,
const std::string& shader = std::string());
// ------------------------------------------------------------------------
void setSamplerUse(GEVulkanSampler sampler)
{
if (m_sampler_use == sampler)
return;
m_sampler_use = sampler;
m_needs_update_descriptor = true;
}
// ------------------------------------------------------------------------
void updateDescriptor();
// ------------------------------------------------------------------------
unsigned getMaxTextureList() const { return m_max_texture_list; }
// ------------------------------------------------------------------------
unsigned getMaxLayer() const { return m_max_layer; }
// ------------------------------------------------------------------------
VkDescriptorSetLayout* getDescriptorSetLayout()
{ return &m_descriptor_set_layout; }
// ------------------------------------------------------------------------
VkDescriptorSet* getDescriptorSet()
{ return m_descriptor_sets.data(); }
// ------------------------------------------------------------------------
GEVulkanSampler getSamplerUse() const { return m_sampler_use; }
}; // GEVulkanTextureDescriptor
}
#endif
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+636
View File
@@ -0,0 +1,636 @@
/* ==========================================================================
* Copyright (c) 2022 SuperTuxKart-Team
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to permit
* persons to whom the Software is 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 Software.
*
* THE SOFTWARE IS 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 SOFTWARE OR THE
* USE OR OTHER DEALINGS IN THE SOFTWARE.
* ==========================================================================
*/
#ifndef HEADER_MINI_GLM_HPP
#define HEADER_MINI_GLM_HPP
#include "LinearMath/btQuaternion.h"
#include "LinearMath/btTransform.h"
#include "LinearMath/btVector3.h"
#include <algorithm>
#include <array>
#include <cassert>
#include <cmath>
#include <cstdint>
#include <quaternion.h>
#include <vector3d.h>
#include "irrMath.h"
using namespace irr;
// GLM without template
namespace MiniGLM
{
// ------------------------------------------------------------------------
inline float overflow()
{
volatile float f = 1e10;
for (int i = 0; i < 10; i++)
f *= f; // this will overflow before the for loop terminates
return f;
} // overflow
// ------------------------------------------------------------------------
inline float toFloat32(short value)
{
int s = (value >> 15) & 0x00000001;
int e = (value >> 10) & 0x0000001f;
int m = value & 0x000003ff;
if (e == 0)
{
if (m == 0)
{
//
// Plus or minus zero
//
uint32_t tmp_data = (unsigned int)(s << 31);
float ret;
memcpy(&ret, &tmp_data, 4);
return ret;
}
else
{
//
// Denormalized number -- renormalize it
//
while(!(m & 0x00000400))
{
m <<= 1;
e -= 1;
}
e += 1;
m &= ~0x00000400;
}
}
else if (e == 31)
{
if (m == 0)
{
//
// Positive or negative infinity
//
uint32_t tmp_data = (unsigned int)((s << 31) | 0x7f800000);
float ret;
memcpy(&ret, &tmp_data, 4);
return ret;
}
else
{
//
// Nan -- preserve sign and significand bits
//
uint32_t tmp_data = (unsigned int)((s << 31) | 0x7f800000 |
(m << 13));
float ret;
memcpy(&ret, &tmp_data, 4);
return ret;
}
}
//
// Normalized number
//
e = e + (127 - 15);
m = m << 13;
//
// Assemble s, e and m.
//
uint32_t tmp_data = (unsigned int)((s << 31) | (e << 23) | m);
float ret;
memcpy(&ret, &tmp_data, 4);
return ret;
} // toFloat32
// ------------------------------------------------------------------------
inline short toFloat16(float const & f)
{
int i;
memcpy(&i, &f, 4);
//
// Our floating point number, f, is represented by the bit
// pattern in integer i. Disassemble that bit pattern into
// the sign, s, the exponent, e, and the significand, m.
// Shift s into the position where it will go in in the
// resulting half number.
// Adjust e, accounting for the different exponent bias
// of float and half (127 versus 15).
//
int s = (i >> 16) & 0x00008000;
int e = ((i >> 23) & 0x000000ff) - (127 - 15);
int m = i & 0x007fffff;
//
// Now reassemble s, e and m into a half:
//
if (e <= 0)
{
if (e < -10)
{
//
// E is less than -10. The absolute value of f is
// less than half_MIN (f may be a small normalized
// float, a denormalized float or a zero).
//
// We convert f to a half zero.
//
return short(s);
}
//
// E is between -10 and 0. F is a normalized float,
// whose magnitude is less than __half_NRM_MIN.
//
// We convert f to a denormalized half.
//
m = (m | 0x00800000) >> (1 - e);
//
// Round to nearest, round "0.5" up.
//
// Rounding may cause the significand to overflow and make
// our number normalized. Because of the way a half's bits
// are laid out, we don't have to treat this case separately;
// the code below will handle it correctly.
//
if (m & 0x00001000)
m += 0x00002000;
//
// Assemble the half from s, e (zero) and m.
//
return short(s | (m >> 13));
}
else if (e == 0xff - (127 - 15))
{
if (m == 0)
{
//
// F is an infinity; convert f to a half
// infinity with the same sign as f.
//
return short(s | 0x7c00);
}
else
{
//
// F is a NAN; we produce a half NAN that preserves
// the sign bit and the 10 leftmost bits of the
// significand of f, with one exception: If the 10
// leftmost bits are all zero, the NAN would turn
// into an infinity, so we have to set at least one
// bit in the significand.
//
m >>= 13;
return short(s | 0x7c00 | m | (m == 0));
}
}
else
{
//
// E is greater than zero. F is a normalized float.
// We try to convert f to a normalized half.
//
//
// Round to nearest, round "0.5" up
//
if (m & 0x00001000)
{
m += 0x00002000;
if (m & 0x00800000)
{
m = 0; // overflow in significand,
e += 1; // adjust exponent
}
}
//
// Handle exponent overflow
//
if (e > 30)
{
overflow(); // Cause a hardware floating point overflow;
return short(s | 0x7c00);
// if this returns, the half becomes an
} // infinity with the same sign as f.
//
// Assemble the half from s, e and m.
//
return short(s | (e << 10) | (m >> 13));
}
} // toFloat16
// ------------------------------------------------------------------------
inline uint32_t normalizedSignedFloatsTo1010102
(const std::array<float, 3>& src, int extra_2_bit = -1)
{
int part = 0;
uint32_t packed = 0;
float v = fminf(1.0f, fmaxf(-1.0f, src[0]));
if (v > 0.0f)
{
part = (int)((v * 511.0f) + 0.5f);
}
else
{
part = (int)((v * 512.0f) - 0.5f);
}
packed |= ((uint32_t)part & 1023) << 0;
v = fminf(1.0f, fmaxf(-1.0f, src[1]));
if (v > 0.0f)
{
part = (int)((v * 511.0f) + 0.5f);
}
else
{
part = (int)((v * 512.0f) - 0.5f);
}
packed |= ((uint32_t)part & 1023) << 10;
v = fminf(1.0f, fmaxf(-1.0f, src[2]));
if (v > 0.0f)
{
part = (int)((v * 511.0f) + 0.5f);
}
else
{
part = (int)((v * 512.0f) - 0.5f);
}
packed |= ((uint32_t)part & 1023) << 20;
if (extra_2_bit >= 0)
{
part = extra_2_bit;
}
else
{
part = (int)(-0.5f);
}
packed |= ((uint32_t)part & 3) << 30;
return packed;
} // normalizedSignedFloatsTo1010102
// ------------------------------------------------------------------------
inline std::array<short, 4> vertexType2101010RevTo4HF(uint32_t packed)
{
std::array<float, 4> ret;
int part = packed & 1023;
if (part & 512)
{
ret[0] = (float)(1024 - part) * (-1.0f / 512.0f);
}
else
{
ret[0] = (float)part * (1.0f / 511.0f);
}
part = (packed >> 10) & 1023;
if (part & 512)
{
ret[1] = (float)(1024 - part) * (-1.0f / 512.0f);
}
else
{
ret[1] = (float)part * (1.0f / 511.0f);
}
part = (packed >> 20) & 1023;
if (part & 512)
{
ret[2] = (float)(1024 - part) * (-1.0f / 512.0f);
}
else
{
ret[2] = (float)part * (1.0f / 511.0f);
}
part = (packed >> 30) & 3;
if (part & 2)
{
ret[3] = (float)(4 - part) * (-1.0f / 2.0f);
}
else
{
ret[3] = (float)part;
}
std::array<short, 4> result;
for (int i = 0; i < 4; i++)
{
result[i] = toFloat16(ret[i]);
}
return result;
} // vertexType2101010RevTo4HF
// ------------------------------------------------------------------------
inline std::array<float, 4> extractNormalizedSignedFloats(uint32_t packed,
bool calculate_w = false)
{
std::array<float, 4> ret = {};
int part = packed & 1023;
if (part & 512)
{
ret[0] = (float)(1024 - part) * (-1.0f / 512.0f);
}
else
{
ret[0] = (float)part * (1.0f / 511.0f);
}
part = (packed >> 10) & 1023;
if (part & 512)
{
ret[1] = (float)(1024 - part) * (-1.0f / 512.0f);
}
else
{
ret[1] = (float)part * (1.0f / 511.0f);
}
part = (packed >> 20) & 1023;
if (part & 512)
{
ret[2] = (float)(1024 - part) * (-1.0f / 512.0f);
}
else
{
ret[2] = (float)part * (1.0f / 511.0f);
}
if (calculate_w)
{
float inv_sqrt_2 = 1.0f / sqrtf(2.0f);
ret[0] *= inv_sqrt_2;
ret[1] *= inv_sqrt_2;
ret[2] *= inv_sqrt_2;
float largest_val = sqrtf(fmaxf(0.0f, 1.0f -
(ret[0] * ret[0]) - (ret[1] * ret[1]) - (ret[2] * ret[2])));
part = (packed >> 30) & 3;
switch(part)
{
case 0:
{
auto tmp = ret;
ret[0] = largest_val;
ret[1] = tmp[0];
ret[2] = tmp[1];
ret[3] = tmp[2];
break;
}
case 1:
{
auto tmp = ret;
ret[0] = tmp[0];
ret[1] = largest_val;
ret[2] = tmp[1];
ret[3] = tmp[2];
break;
}
case 2:
{
auto tmp = ret;
ret[0] = tmp[0];
ret[1] = tmp[1];
ret[2] = largest_val;
ret[3] = tmp[2];
break;
}
case 3:
ret[3] = largest_val;
break;
default:
assert(false);
break;
}
}
return ret;
} // extractNormalizedSignedFloats
// ------------------------------------------------------------------------
// Please normalize vector before compressing
// ------------------------------------------------------------------------
inline uint32_t compressVector3(const irr::core::vector3df& vec)
{
return normalizedSignedFloatsTo1010102({{vec.X, vec.Y, vec.Z}});
} // compressVector3
// ------------------------------------------------------------------------
inline core::vector3df decompressVector3(uint32_t packed)
{
const std::array<float, 4> out = extractNormalizedSignedFloats(packed);
core::vector3df ret(out[0], out[1], out[2]);
return ret.normalize();
} // decompressVector3
// ------------------------------------------------------------------------
inline uint32_t compressQuaternion(const btQuaternion& q)
{
const float length = q.length();
assert(length != 0.0f);
std::array<float, 4> tmp_2 =
{{
q.x() / length,
q.y() / length,
q.z() / length,
q.w() / length
}};
std::array<float, 3> tmp_3 = {};
auto ret = std::max_element(tmp_2.begin(), tmp_2.end(),
[](float a, float b) { return std::abs(a) < std::abs(b); });
int extra_2_bit = int(std::distance(tmp_2.begin(), ret));
float sqrt_2 = sqrtf(2.0f);
switch (extra_2_bit)
{
case 0:
{
float neg = tmp_2[0] < 0.0f ? -1.0f : 1.0f;
tmp_3[0] = tmp_2[1] * neg * sqrt_2;
tmp_3[1] = tmp_2[2] * neg * sqrt_2;
tmp_3[2] = tmp_2[3] * neg * sqrt_2;
break;
}
case 1:
{
float neg = tmp_2[1] < 0.0f ? -1.0f : 1.0f;
tmp_3[0] = tmp_2[0] * neg * sqrt_2;
tmp_3[1] = tmp_2[2] * neg * sqrt_2;
tmp_3[2] = tmp_2[3] * neg * sqrt_2;
break;
}
case 2:
{
float neg = tmp_2[2] < 0.0f ? -1.0f : 1.0f;
tmp_3[0] = tmp_2[0] * neg * sqrt_2;
tmp_3[1] = tmp_2[1] * neg * sqrt_2;
tmp_3[2] = tmp_2[3] * neg * sqrt_2;
break;
}
case 3:
{
float neg = tmp_2[3] < 0.0f ? -1.0f : 1.0f;
tmp_3[0] = tmp_2[0] * neg * sqrt_2;
tmp_3[1] = tmp_2[1] * neg * sqrt_2;
tmp_3[2] = tmp_2[2] * neg * sqrt_2;
break;
}
default:
assert(false);
break;
}
return normalizedSignedFloatsTo1010102(tmp_3, extra_2_bit);
} // compressQuaternion
// ------------------------------------------------------------------------
inline uint32_t compressIrrQuaternion(const core::quaternion& q)
{
return compressQuaternion(btQuaternion(q.X, q.Y, q.Z, q.W));
}
// ------------------------------------------------------------------------
inline core::quaternion decompressQuaternion(uint32_t packed)
{
const std::array<float, 4> out = extractNormalizedSignedFloats(packed,
true/*calculate_w*/);
core::quaternion ret(out[0], out[1], out[2], out[3]);
return ret.normalize();
} // decompressQuaternion
// ------------------------------------------------------------------------
inline btQuaternion decompressbtQuaternion(uint32_t packed)
{
const std::array<float, 4> out = extractNormalizedSignedFloats(packed,
true/*calculate_w*/);
btQuaternion ret(out[0], out[1], out[2], out[3]);
return ret.normalize();
} // decompressbtQuaternion
// ------------------------------------------------------------------------
inline std::array<float, 4> getQuaternionInternal(const core::matrix4& m)
{
btVector3 row[3];
memcpy(&row[0][0], &m[0], 12);
memcpy(&row[1][0], &m[4], 12);
memcpy(&row[2][0], &m[8], 12);
std::array<float, 4> q;
float root = row[0].x() + row[1].y() + row[2].z();
const float trace = root;
if (trace > 0.0f)
{
root = sqrtf(trace + 1.0f);
q[3] = 0.5f * root;
root = 0.5f / root;
q[0] = root * (row[1].z() - row[2].y());
q[1] = root * (row[2].x() - row[0].z());
q[2] = root * (row[0].y() - row[1].x());
}
else
{
static int next[3] = {1, 2, 0};
int i = 0;
int j = 0;
int k = 0;
if (row[1].y() > row[0].x())
{
i = 1;
}
if (row[2].z() > row[i][i])
{
i = 2;
}
j = next[i];
k = next[j];
root = sqrtf(row[i][i] - row[j][j] - row[k][k] + 1.0f);
q[i] = 0.5f * root;
root = 0.5f / root;
q[j] = root * (row[i][j] + row[j][i]);
q[k] = root * (row[i][k] + row[k][i]);
q[3] = root * (row[j][k] - row[k][j]);
}
return q;
}
// ------------------------------------------------------------------------
inline core::quaternion getQuaternion(const core::matrix4& m)
{
std::array<float, 4> q = getQuaternionInternal(m);
return core::quaternion(q[0], q[1], q[2], q[3]).normalize();
}
// ------------------------------------------------------------------------
inline btQuaternion getBulletQuaternion(const core::matrix4& m)
{
std::array<float, 4> q = getQuaternionInternal(m);
return btQuaternion(q[0], q[1], q[2], q[3]).normalize();
}
// ------------------------------------------------------------------------
inline uint32_t quickTangent(uint32_t packed_normal)
{
core::vector3df normal = decompressVector3(packed_normal);
core::vector3df tangent;
core::vector3df c1 =
normal.crossProduct(core::vector3df(0.0f, 0.0f, 1.0f));
core::vector3df c2 =
normal.crossProduct(core::vector3df(0.0f, 1.0f, 0.0f));
if (c1.getLengthSQ() > c2.getLengthSQ())
{
tangent = c1;
}
else
{
tangent = c2;
}
tangent.normalize();
// Assume bitangent sign is positive 1.0f
return compressVector3(tangent) | 1 << 30;
} // quickTangent
// ------------------------------------------------------------------------
/** Round and save compressed values (optionally) btTransform.
* It will round with 2 digits with min / max +/- 2^23 / 100 for origin in
* btTransform and call compressQuaternion above to compress the rotation
* part, if compressed_data is provided, 3 24 bits and 1 32 bits of
* compressed data will be written in an int[4] array.
*/
inline void compressbtTransform(btTransform& cur_t,
int* compressed_data = NULL)
{
int x = (int)(cur_t.getOrigin().x() * 100.0f);
int y = (int)(cur_t.getOrigin().y() * 100.0f);
int z = (int)(cur_t.getOrigin().z() * 100.0f);
x = core::clamp(x, -0x800000, 0x7fffff);
y = core::clamp(y, -0x800000, 0x7fffff);
z = core::clamp(z, -0x800000, 0x7fffff);
uint32_t compressed_q = compressQuaternion(cur_t.getRotation());
cur_t.setOrigin(btVector3(
(float)x / 100.0f,
(float)y / 100.0f,
(float)z / 100.0f));
cur_t.setRotation(decompressbtQuaternion(compressed_q));
if (compressed_data)
{
compressed_data[0] = x;
compressed_data[1] = y;
compressed_data[2] = z;
compressed_data[3] = (int)compressed_q;
}
} // compressbtTransform
// ------------------------------------------------------------------------
inline btTransform decompressbtTransform(int* compressed_data)
{
btTransform trans;
trans.setOrigin(btVector3(
(float)compressed_data[0] / 100.0f,
(float)compressed_data[1] / 100.0f,
(float)compressed_data[2] / 100.0f));
trans.setRotation(decompressbtQuaternion(
(uint32_t)compressed_data[3]));
return trans;
} // decompressbtTransform
// ------------------------------------------------------------------------
void unitTesting();
}
#endif
@@ -0,0 +1,294 @@
/*
* mvk_private_api.h
*
* Copyright (c) 2015-2023 The Brenwill Workshop Ltd. (http://www.brenwill.com)
*
* 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 __mvk_private_api_h_
#define __mvk_private_api_h_ 1
#ifdef __cplusplus
extern "C" {
#endif // __cplusplus
#ifdef __OBJC__
#import <Metal/Metal.h>
#else
typedef unsigned long MTLLanguageVersion;
typedef unsigned long MTLArgumentBuffersTier;
#endif
/**
* This header contains functions to query MoltenVK about
* available Metal features, and runtime performance information.
*
* NOTE: THE FUNCTIONS BELOW SHOULD BE USED WITH CARE. THESE FUNCTIONS ARE
* NOT PART OF VULKAN, AND ARE NOT SUPPORTED BY THE VULKAN LOADER AND LAYERS.
* THE VULKAN OBJECTS PASSED IN THESE FUNCTIONS MUST HAVE BEEN RETRIEVED
* DIRECTLY FROM MOLTENVK, WITHOUT LINKING THROUGH THE VULKAN LOADER AND LAYERS.
*/
#define MVK_PRIVATE_API_VERSION 37
/** Identifies the type of rounding Metal uses for float to integer conversions in particular calculatons. */
typedef enum MVKFloatRounding {
MVK_FLOAT_ROUNDING_NEAREST = 0, /**< Metal rounds to nearest. */
MVK_FLOAT_ROUNDING_UP = 1, /**< Metal rounds towards positive infinity. */
MVK_FLOAT_ROUNDING_DOWN = 2, /**< Metal rounds towards negative infinity. */
MVK_FLOAT_ROUNDING_UP_MAX_ENUM = 0x7FFFFFFF
} MVKFloatRounding;
/** Identifies the pipeline points where GPU counter sampling can occur. Maps to MTLCounterSamplingPoint. */
typedef enum MVKCounterSamplingBits {
MVK_COUNTER_SAMPLING_AT_DRAW = 0x00000001,
MVK_COUNTER_SAMPLING_AT_DISPATCH = 0x00000002,
MVK_COUNTER_SAMPLING_AT_BLIT = 0x00000004,
MVK_COUNTER_SAMPLING_AT_PIPELINE_STAGE = 0x00000008,
MVK_COUNTER_SAMPLING_MAX_ENUM = 0X7FFFFFFF
} MVKCounterSamplingBits;
typedef VkFlags MVKCounterSamplingFlags;
/**
* Features provided by the current implementation of Metal on the current device. You can
* retrieve a copy of this structure using the vkGetPhysicalDeviceMetalFeaturesMVK() function.
*
* This structure may be extended as new features are added to MoltenVK. If you are linking to
* an implementation of MoltenVK that was compiled from a different MVK_PRIVATE_API_VERSION
* than your app was, the size of this structure in your app may be larger or smaller than the
* struct in MoltenVK. See the description of the vkGetPhysicalDeviceMetalFeaturesMVK() function
* for information about how to handle this.
*
* TO SUPPORT DYNAMIC LINKING TO THIS STRUCTURE AS DESCRIBED ABOVE, THIS STRUCTURE SHOULD NOT
* BE CHANGED EXCEPT TO ADD ADDITIONAL MEMBERS ON THE END. EXISTING MEMBERS, AND THEIR ORDER,
* SHOULD NOT BE CHANGED.
*/
typedef struct {
uint32_t mslVersion; /**< The version of the Metal Shading Language available on this device. The format of the integer is MMmmpp, with two decimal digts each for Major, minor, and patch version values (eg. MSL 1.2 would appear as 010200). */
VkBool32 indirectDrawing; /**< If true, draw calls support parameters held in a GPU buffer. */
VkBool32 baseVertexInstanceDrawing; /**< If true, draw calls support specifiying the base vertex and instance. */
uint32_t dynamicMTLBufferSize; /**< If greater than zero, dynamic MTLBuffers for setting vertex, fragment, and compute bytes are supported, and their content must be below this value. */
VkBool32 shaderSpecialization; /**< If true, shader specialization (aka Metal function constants) is supported. */
VkBool32 ioSurfaces; /**< If true, VkImages can be underlaid by IOSurfaces via the vkUseIOSurfaceMVK() function, to support inter-process image transfers. */
VkBool32 texelBuffers; /**< If true, texel buffers are supported, allowing the contents of a buffer to be interpreted as an image via a VkBufferView. */
VkBool32 layeredRendering; /**< If true, layered rendering to multiple cube or texture array layers is supported. */
VkBool32 presentModeImmediate; /**< If true, immediate surface present mode (VK_PRESENT_MODE_IMMEDIATE_KHR), allowing a swapchain image to be presented immediately, without waiting for the vertical sync period of the display, is supported. */
VkBool32 stencilViews; /**< If true, stencil aspect views are supported through the MTLPixelFormatX24_Stencil8 and MTLPixelFormatX32_Stencil8 formats. */
VkBool32 multisampleArrayTextures; /**< If true, MTLTextureType2DMultisampleArray is supported. */
VkBool32 samplerClampToBorder; /**< If true, the border color set when creating a sampler will be respected. */
uint32_t maxTextureDimension; /**< The maximum size of each texture dimension (width, height, or depth). */
uint32_t maxPerStageBufferCount; /**< The total number of per-stage Metal buffers available for shader uniform content and attributes. */
uint32_t maxPerStageTextureCount; /**< The total number of per-stage Metal textures available for shader uniform content. */
uint32_t maxPerStageSamplerCount; /**< The total number of per-stage Metal samplers available for shader uniform content. */
VkDeviceSize maxMTLBufferSize; /**< The max size of a MTLBuffer (in bytes). */
VkDeviceSize mtlBufferAlignment; /**< The alignment used when allocating memory for MTLBuffers. Must be PoT. */
VkDeviceSize maxQueryBufferSize; /**< The maximum size of an occlusion query buffer (in bytes). */
VkDeviceSize mtlCopyBufferAlignment; /**< The alignment required during buffer copy operations (in bytes). */
VkSampleCountFlags supportedSampleCounts; /**< A bitmask identifying the sample counts supported by the device. */
uint32_t minSwapchainImageCount; /**< The minimum number of swapchain images that can be supported by a surface. */
uint32_t maxSwapchainImageCount; /**< The maximum number of swapchain images that can be supported by a surface. */
VkBool32 combinedStoreResolveAction; /**< If true, the device supports VK_ATTACHMENT_STORE_OP_STORE with a simultaneous resolve attachment. */
VkBool32 arrayOfTextures; /**< If true, arrays of textures is supported. */
VkBool32 arrayOfSamplers; /**< If true, arrays of texture samplers is supported. */
MTLLanguageVersion mslVersionEnum; /**< The version of the Metal Shading Language available on this device, as a Metal enumeration. */
VkBool32 depthSampleCompare; /**< If true, depth texture samplers support the comparison of the pixel value against a reference value. */
VkBool32 events; /**< If true, Metal synchronization events (MTLEvent) are supported. */
VkBool32 memoryBarriers; /**< If true, full memory barriers within Metal render passes are supported. */
VkBool32 multisampleLayeredRendering; /**< If true, layered rendering to multiple multi-sampled cube or texture array layers is supported. */
VkBool32 stencilFeedback; /**< If true, fragment shaders that write to [[stencil]] outputs are supported. */
VkBool32 textureBuffers; /**< If true, textures of type MTLTextureTypeBuffer are supported. */
VkBool32 postDepthCoverage; /**< If true, coverage masks in fragment shaders post-depth-test are supported. */
VkBool32 fences; /**< If true, Metal synchronization fences (MTLFence) are supported. */
VkBool32 rasterOrderGroups; /**< If true, Raster order groups in fragment shaders are supported. */
VkBool32 native3DCompressedTextures; /**< If true, 3D compressed images are supported natively, without manual decompression. */
VkBool32 nativeTextureSwizzle; /**< If true, component swizzle is supported natively, without manual swizzling in shaders. */
VkBool32 placementHeaps; /**< If true, MTLHeap objects support placement of resources. */
VkDeviceSize pushConstantSizeAlignment; /**< The alignment used internally when allocating memory for push constants. Must be PoT. */
uint32_t maxTextureLayers; /**< The maximum number of layers in an array texture. */
uint32_t maxSubgroupSize; /**< The maximum number of threads in a SIMD-group. */
VkDeviceSize vertexStrideAlignment; /**< The alignment used for the stride of vertex attribute bindings. */
VkBool32 indirectTessellationDrawing; /**< If true, tessellation draw calls support parameters held in a GPU buffer. */
VkBool32 nonUniformThreadgroups; /**< If true, the device supports arbitrary-sized grids in compute workloads. */
VkBool32 renderWithoutAttachments; /**< If true, we don't have to create a dummy attachment for a render pass if there isn't one. */
VkBool32 deferredStoreActions; /**< If true, render pass store actions can be specified after the render encoder is created. */
VkBool32 sharedLinearTextures; /**< If true, linear textures and texture buffers can be created from buffers in Shared storage. */
VkBool32 depthResolve; /**< If true, resolving depth textures with filters other than Sample0 is supported. */
VkBool32 stencilResolve; /**< If true, resolving stencil textures with filters other than Sample0 is supported. */
uint32_t maxPerStageDynamicMTLBufferCount; /**< The maximum number of inline buffers that can be set on a command buffer. */
uint32_t maxPerStageStorageTextureCount; /**< The total number of per-stage Metal textures with read-write access available for writing to from a shader. */
VkBool32 astcHDRTextures; /**< If true, ASTC HDR pixel formats are supported. */
VkBool32 renderLinearTextures; /**< If true, linear textures are renderable. */
VkBool32 pullModelInterpolation; /**< If true, explicit interpolation functions are supported. */
VkBool32 samplerMirrorClampToEdge; /**< If true, the mirrored clamp to edge address mode is supported in samplers. */
VkBool32 quadPermute; /**< If true, quadgroup permutation functions (vote, ballot, shuffle) are supported in shaders. */
VkBool32 simdPermute; /**< If true, SIMD-group permutation functions (vote, ballot, shuffle) are supported in shaders. */
VkBool32 simdReduction; /**< If true, SIMD-group reduction functions (arithmetic) are supported in shaders. */
uint32_t minSubgroupSize; /**< The minimum number of threads in a SIMD-group. */
VkBool32 textureBarriers; /**< If true, texture barriers are supported within Metal render passes. */
VkBool32 tileBasedDeferredRendering; /**< If true, this device uses tile-based deferred rendering. */
VkBool32 argumentBuffers; /**< If true, Metal argument buffers are supported. */
VkBool32 descriptorSetArgumentBuffers; /**< If true, a Metal argument buffer can be assigned to a descriptor set, and used on any pipeline and pipeline stage. If false, a different Metal argument buffer must be used for each pipeline-stage/descriptor-set combination. */
MVKFloatRounding clearColorFloatRounding; /**< Identifies the type of rounding Metal uses for MTLClearColor float to integer conversions. */
MVKCounterSamplingFlags counterSamplingPoints; /**< Identifies the points where pipeline GPU counter sampling may occur. */
VkBool32 programmableSamplePositions; /**< If true, programmable MSAA sample positions are supported. */
VkBool32 shaderBarycentricCoordinates; /**< If true, fragment shader barycentric coordinates are supported. */
MTLArgumentBuffersTier argumentBuffersTier; /**< The argument buffer tier available on this device, as a Metal enumeration. */
VkBool32 needsSampleDrefLodArrayWorkaround; /**< If true, sampling from arrayed depth images with explicit LoD is broken and needs a workaround. */
VkDeviceSize hostMemoryPageSize; /**< The size of a page of host memory on this platform. */
} MVKPhysicalDeviceMetalFeatures;
/** MoltenVK performance of a particular type of activity. */
typedef struct {
uint32_t count; /**< The number of activities of this type. */
double latestDuration; /**< The latest (most recent) duration of the activity, in milliseconds. */
double averageDuration; /**< The average duration of the activity, in milliseconds. */
double minimumDuration; /**< The minimum duration of the activity, in milliseconds. */
double maximumDuration; /**< The maximum duration of the activity, in milliseconds. */
} MVKPerformanceTracker;
/** MoltenVK performance of shader compilation activities. */
typedef struct {
MVKPerformanceTracker hashShaderCode; /** Create a hash from the incoming shader code. */
MVKPerformanceTracker spirvToMSL; /** Convert SPIR-V to MSL source code. */
MVKPerformanceTracker mslCompile; /** Compile MSL source code into a MTLLibrary. */
MVKPerformanceTracker mslLoad; /** Load pre-compiled MSL code into a MTLLibrary. */
MVKPerformanceTracker mslCompress; /** Compress MSL source code after compiling a MTLLibrary, to hold it in a pipeline cache. */
MVKPerformanceTracker mslDecompress; /** Decompress MSL source code to write the MSL when serializing a pipeline cache. */
MVKPerformanceTracker shaderLibraryFromCache; /** Retrieve a shader library from the cache, lazily creating it if needed. */
MVKPerformanceTracker functionRetrieval; /** Retrieve a MTLFunction from a MTLLibrary. */
MVKPerformanceTracker functionSpecialization; /** Specialize a retrieved MTLFunction. */
MVKPerformanceTracker pipelineCompile; /** Compile MTLFunctions into a pipeline. */
MVKPerformanceTracker glslToSPRIV; /** Convert GLSL to SPIR-V code. */
} MVKShaderCompilationPerformance;
/** MoltenVK performance of pipeline cache activities. */
typedef struct {
MVKPerformanceTracker sizePipelineCache; /** Calculate the size of cache data required to write MSL to pipeline cache data stream. */
MVKPerformanceTracker writePipelineCache; /** Write MSL to pipeline cache data stream. */
MVKPerformanceTracker readPipelineCache; /** Read MSL from pipeline cache data stream. */
} MVKPipelineCachePerformance;
/** MoltenVK performance of queue activities. */
typedef struct {
MVKPerformanceTracker mtlQueueAccess; /** Create an MTLCommandQueue or access an existing cached instance. */
MVKPerformanceTracker mtlCommandBufferCompletion; /** Completion of a MTLCommandBuffer on the GPU, from commit to completion callback. */
MVKPerformanceTracker nextCAMetalDrawable; /** Retrieve next CAMetalDrawable from CAMetalLayer during presentation. */
MVKPerformanceTracker frameInterval; /** Frame presentation interval (1000/FPS). */
} MVKQueuePerformance;
/**
* MoltenVK performance. You can retrieve a copy of this structure using the vkGetPerformanceStatisticsMVK() function.
*
* This structure may be extended as new features are added to MoltenVK. If you are linking to
* an implementation of MoltenVK that was compiled from a different MVK_PRIVATE_API_VERSION
* than your app was, the size of this structure in your app may be larger or smaller than the
* struct in MoltenVK. See the description of the vkGetPerformanceStatisticsMVK() function for
* information about how to handle this.
*
* TO SUPPORT DYNAMIC LINKING TO THIS STRUCTURE AS DESCRIBED ABOVE, THIS STRUCTURE SHOULD NOT
* BE CHANGED EXCEPT TO ADD ADDITIONAL MEMBERS ON THE END. EXISTING MEMBERS, AND THEIR ORDER,
* SHOULD NOT BE CHANGED.
*/
typedef struct {
MVKShaderCompilationPerformance shaderCompilation; /** Shader compilations activities. */
MVKPipelineCachePerformance pipelineCache; /** Pipeline cache activities. */
MVKQueuePerformance queue; /** Queue activities. */
} MVKPerformanceStatistics;
#pragma mark -
#pragma mark Function types
typedef VkResult (VKAPI_PTR *PFN_vkGetPhysicalDeviceMetalFeaturesMVK)(VkPhysicalDevice physicalDevice, MVKPhysicalDeviceMetalFeatures* pMetalFeatures, size_t* pMetalFeaturesSize);
typedef VkResult (VKAPI_PTR *PFN_vkGetPerformanceStatisticsMVK)(VkDevice device, MVKPerformanceStatistics* pPerf, size_t* pPerfSize);
#pragma mark -
#pragma mark Function prototypes
#ifndef VK_NO_PROTOTYPES
/**
* Populates the pMetalFeatures structure with the Metal-specific features
* supported by the specified physical device.
*
* If you are linking to an implementation of MoltenVK that was compiled from a different
* MVK_PRIVATE_API_VERSION than your app was, the size of the MVKPhysicalDeviceMetalFeatures
* structure in your app may be larger or smaller than the same struct as expected by MoltenVK.
*
* When calling this function, set the value of *pMetalFeaturesSize to sizeof(MVKPhysicalDeviceMetalFeatures),
* to tell MoltenVK the limit of the size of your MVKPhysicalDeviceMetalFeatures structure. Upon return from
* this function, the value of *pMetalFeaturesSize will hold the actual number of bytes copied into your
* passed MVKPhysicalDeviceMetalFeatures structure, which will be the smaller of what your app thinks is the
* size of MVKPhysicalDeviceMetalFeatures, and what MoltenVK thinks it is. This represents the safe access
* area within the structure for both MoltenVK and your app.
*
* If the size that MoltenVK expects for MVKPhysicalDeviceMetalFeatures is different than the value passed in
* *pMetalFeaturesSize, this function will return VK_INCOMPLETE, otherwise it will return VK_SUCCESS.
*
* Although it is not necessary, you can use this function to determine in advance the value that MoltenVK
* expects the size of MVKPhysicalDeviceMetalFeatures to be by setting the value of pMetalFeatures to NULL.
* In that case, this function will set *pMetalFeaturesSize to the size that MoltenVK expects
* MVKPhysicalDeviceMetalFeatures to be.
*
* This function is not supported by the Vulkan SDK Loader and Layers framework
* and is unavailable when using the Vulkan SDK Loader and Layers framework.
*/
VKAPI_ATTR VkResult VKAPI_CALL vkGetPhysicalDeviceMetalFeaturesMVK(
VkPhysicalDevice physicalDevice,
MVKPhysicalDeviceMetalFeatures* pMetalFeatures,
size_t* pMetalFeaturesSize);
/**
* Populates the pPerf structure with the current performance statistics for the device.
*
* If you are linking to an implementation of MoltenVK that was compiled from a different
* MVK_PRIVATE_API_VERSION than your app was, the size of the MVKPerformanceStatistics
* structure in your app may be larger or smaller than the same struct as expected by MoltenVK.
*
* When calling this function, set the value of *pPerfSize to sizeof(MVKPerformanceStatistics),
* to tell MoltenVK the limit of the size of your MVKPerformanceStatistics structure. Upon return
* from this function, the value of *pPerfSize will hold the actual number of bytes copied into
* your passed MVKPerformanceStatistics structure, which will be the smaller of what your app
* thinks is the size of MVKPerformanceStatistics, and what MoltenVK thinks it is. This
* represents the safe access area within the structure for both MoltenVK and your app.
*
* If the size that MoltenVK expects for MVKPerformanceStatistics is different than the value passed
* in *pPerfSize, this function will return VK_INCOMPLETE, otherwise it will return VK_SUCCESS.
*
* Although it is not necessary, you can use this function to determine in advance the value
* that MoltenVK expects the size of MVKPerformanceStatistics to be by setting the value of
* pPerf to NULL. In that case, this function will set *pPerfSize to the size that MoltenVK
* expects MVKPerformanceStatistics to be.
*
* This function is not supported by the Vulkan SDK Loader and Layers framework
* and is unavailable when using the Vulkan SDK Loader and Layers framework.
*/
VKAPI_ATTR VkResult VKAPI_CALL vkGetPerformanceStatisticsMVK(
VkDevice device,
MVKPerformanceStatistics* pPerf,
size_t* pPerfSize);
#endif // VK_NO_PROTOTYPES
#ifdef __cplusplus
}
#endif // __cplusplus
#endif
File diff suppressed because it is too large Load Diff
+84
View File
@@ -0,0 +1,84 @@
/* */
/* File: vk_platform.h */
/* */
/*
** Copyright 2014-2025 The Khronos Group Inc.
**
** SPDX-License-Identifier: Apache-2.0
*/
#ifndef VK_PLATFORM_H_
#define VK_PLATFORM_H_
#ifdef __cplusplus
extern "C"
{
#endif /* __cplusplus */
/*
***************************************************************************************************
* Platform-specific directives and type declarations
***************************************************************************************************
*/
/* Platform-specific calling convention macros.
*
* Platforms should define these so that Vulkan clients call Vulkan commands
* with the same calling conventions that the Vulkan implementation expects.
*
* VKAPI_ATTR - Placed before the return type in function declarations.
* Useful for C++11 and GCC/Clang-style function attribute syntax.
* VKAPI_CALL - Placed after the return type in function declarations.
* Useful for MSVC-style calling convention syntax.
* VKAPI_PTR - Placed between the '(' and '*' in function pointer types.
*
* Function declaration: VKAPI_ATTR void VKAPI_CALL vkCommand(void);
* Function pointer type: typedef void (VKAPI_PTR *PFN_vkCommand)(void);
*/
#if defined(_WIN32)
/* On Windows, Vulkan commands use the stdcall convention */
#define VKAPI_ATTR
#define VKAPI_CALL __stdcall
#define VKAPI_PTR VKAPI_CALL
#elif defined(__ANDROID__) && defined(__ARM_ARCH) && __ARM_ARCH < 7
#error "Vulkan is not supported for the 'armeabi' NDK ABI"
#elif defined(__ANDROID__) && defined(__ARM_ARCH) && __ARM_ARCH >= 7 && defined(__ARM_32BIT_STATE)
/* On Android 32-bit ARM targets, Vulkan functions use the "hardfloat" */
/* calling convention, i.e. float parameters are passed in registers. This */
/* is true even if the rest of the application passes floats on the stack, */
/* as it does by default when compiling for the armeabi-v7a NDK ABI. */
#define VKAPI_ATTR __attribute__((pcs("aapcs-vfp")))
#define VKAPI_CALL
#define VKAPI_PTR VKAPI_ATTR
#else
/* On other platforms, use the default calling convention */
#define VKAPI_ATTR
#define VKAPI_CALL
#define VKAPI_PTR
#endif
#if !defined(VK_NO_STDDEF_H)
#include <stddef.h>
#endif /* !defined(VK_NO_STDDEF_H) */
#if !defined(VK_NO_STDINT_H)
#if defined(_MSC_VER) && (_MSC_VER < 1600)
typedef signed __int8 int8_t;
typedef unsigned __int8 uint8_t;
typedef signed __int16 int16_t;
typedef unsigned __int16 uint16_t;
typedef signed __int32 int32_t;
typedef unsigned __int32 uint32_t;
typedef signed __int64 int64_t;
typedef unsigned __int64 uint64_t;
#else
#include <stdint.h>
#endif
#endif /* !defined(VK_NO_STDINT_H) */
#ifdef __cplusplus
} /* extern "C" */
#endif /* __cplusplus */
#endif
@@ -0,0 +1,30 @@
#ifndef HEADER_VULKAN_WRAPPER_HPP
#define HEADER_VULKAN_WRAPPER_HPP
#if !defined(__APPLE__) || defined(DLOPEN_MOLTENVK)
#include <glad/vulkan.h>
#ifdef DLOPEN_MOLTENVK
#define VK_NO_PROTOTYPES 1
// We copy mvk_private_api.h with #include <vulkan/vulkan.h>
// removed
#include <mvk_private_api.h>
extern PFN_vkGetPhysicalDeviceMetalFeaturesMVK vkGetPhysicalDeviceMetalFeaturesMVK;
#endif
#else
#include <vulkan/vulkan.h>
#if defined(__APPLE__)
#include <MoltenVK/mvk_private_api.h>
#endif
#endif
#endif
#ifndef TILED_GPU
#if defined(__arm__) || defined(__aarch64__) || defined(_M_ARM) || defined (_M_ARM64)
#define TILED_GPU 1
#endif
#endif