//////////////////////////////////////////////// //gl3D --Vlad Luta -- //built on 2024-01-16 //////////////////////////////////////////////// //////////////////////////////////////////////// //Core.h //////////////////////////////////////////////// #pragma region Core #pragma once #define GLM_ENABLE_EXPERIMENTAL #define TINYGLTF_NO_INCLUDE_STB_IMAGE #include #include #define GL3D_REMOVE_IOSTREAM 0 //you can remove this if neded to. It is just used for the default errorcallback #define GL3D_REMOVE_FSTREAM 0 //you can remove this if neded to. It is used for the default file callback, supply your own function for file oppening so the library still works :)) #define GL3D_REMOVE_ASSERTS 0 //you can remove asserts in production #define GL3D_OPTIMIZE_CACHED_SEARCH 1 //this was used by the dev to test some things, if you are using the library just keep it to 1. #if GL3D_REMOVE_IOSTREAM == 0 #include #endif #if GL3D_REMOVE_FSTREAM == 0 #include #endif #include #include #include #include #include #include #include #undef min #undef max #define GL3D_ADD_FLAG(NAME, SETNAME, VALUE) \ bool NAME() {return (flags & ((unsigned char)1 << VALUE) );} \ void SETNAME(bool s) \ { if (s) { flags = flags | ((unsigned char)1 << VALUE); } \ else { flags = flags & ~((unsigned char)1 << VALUE); } \ } namespace gl3d { //todo optimization also hold the last found position //todo why id isn't unsigned? #define CREATE_RENDERER_OBJECT_HANDLE(x) \ struct x \ { \ int id_ = {}; \ int lastFoundPos_ = {}; \ x (int id=0):id_(id){}; \ } CREATE_RENDERER_OBJECT_HANDLE(Material); CREATE_RENDERER_OBJECT_HANDLE(Entity); CREATE_RENDERER_OBJECT_HANDLE(Model); CREATE_RENDERER_OBJECT_HANDLE(Texture); CREATE_RENDERER_OBJECT_HANDLE(SpotLight); CREATE_RENDERER_OBJECT_HANDLE(PointLight); CREATE_RENDERER_OBJECT_HANDLE(DirectionalLight); #undef CREATE_RENDERER_OBJECT_HANDLE(x) struct PBRTexture { Texture texture = {}; //rough metalness ambient oclusion // (roughnessLoaded) -> 0b100 // (metallicLoaded) -> 0b010 // (ambientLoaded) -> 0b001 int RMA_loadedTextures = {}; }; struct TextureDataForMaterial { Texture albedoTexture = {}; Texture normalMapTexture = {}; Texture emissiveTexture= {}; PBRTexture pbrTexture = {}; bool operator==(const TextureDataForMaterial& other) { return (albedoTexture.id_ == other.albedoTexture.id_) && (normalMapTexture.id_ == other.normalMapTexture.id_) && (emissiveTexture.id_ == other.emissiveTexture.id_) && (pbrTexture.texture.id_ == other.pbrTexture.texture.id_) && (pbrTexture.RMA_loadedTextures == other.pbrTexture.RMA_loadedTextures) ; }; bool operator!=(const TextureDataForMaterial& other) { return !(*this == other); }; }; //note this is the gpu material struct MaterialValues { glm::vec4 kd = glm::vec4(1); //rma float roughness = 0.5f; float metallic = 0.1; float ao = 1; float emmisive = 0; //rma GLuint64 albedoSampler = 0; GLuint64 rmaSampler = 0; GLuint64 emmissiveSampler = 0; int rmaLoaded = {}; int notUsed; MaterialValues setDefaultMaterial() { *this = MaterialValues(); return *this; } bool operator==(const MaterialValues& other) { return (kd == other.kd) && (roughness == other.roughness) && (metallic == other.metallic) && (ao == other.ao) && (emmisive == other.emmisive) ; }; bool operator!=(const MaterialValues& other) { return !(*this == other); }; }; //todo move namespace internal { //todo move struct GpuPointLight { glm::vec3 position = {}; float dist = 20; glm::vec3 color = { 1,1,1 }; float attenuation = 2; int castShadowsIndex = 1; float hardness = 1; int castShadows = 1; int changedThisFrame = 1; }; struct GpuDirectionalLight { glm::vec3 direction = {0,-1,0}; int castShadowsIndex = 1; int changedThisFrame = 1; int castShadows = 1; int notUsed1 = 0; int notUsed2 = 0; glm::vec3 color = { 1,1,1 }; float hardness = 1; glm::mat4 lightSpaceMatrix[3]; //magic number (cascades) }; struct GpuSpotLight { glm::vec3 position = {}; float cosHalfAngle = std::cos(3.14159/4.f); glm::vec3 direction = { 0,-1,0 }; float dist = 20; glm::vec3 color = { 1, 1, 1 }; float attenuation = 2; float hardness = 1; int shadowIndex = 0; int castShadows = 1; int changedThisFrame = 1; //this is sent to the gpu but not used there float nearPlane = 0.1; float farPlane = 10; float notUsed1 = 0; float notUsed2 = 0; glm::mat4 lightSpaceMatrix; }; }; void GLAPIENTRY glDebugOutput(GLenum source, GLenum type, unsigned int id, GLenum severity, GLsizei length, const char *message, const void *userParam); void assertFunc(const char *expression, const char *file_name, unsigned const line_number, const char *comment = "---"); }; #if GL3D_REMOVE_ASSERTS == 0 #define gl3dAssert(expression) (void)( \ (!!(expression)) || \ (gl3d::assertFunc(#expression, __FILE__, (unsigned)(__LINE__)), 0) \ ) #define gl3dAssertComment(expression, comment) (void)( \ (!!(expression)) || \ (gl3d::assertFunc(#expression, __FILE__, (unsigned)(__LINE__), comment), 0)\ ) #else #define gl3dAssert(expression) #define gl3dAssertComment(expression, comment) #endif #pragma endregion //////////////////////////////////////////////// //ErrorReporting.h //////////////////////////////////////////////// #pragma region ErrorReporting #pragma once #include #include namespace gl3d { void defaultErrorCallback(std::string err, void *userData); std::string defaultReadEntireFile(const char *fileName, bool &couldNotOpen, void *userData); std::vector defaultReadEntireFileBinary(const char *fileName, bool &couldNotOpen, void *userData); bool defaultFileExists(const char *fileName, void *userData); using ErrorCallback_t = decltype(defaultErrorCallback); using ReadEntireFile_t = decltype(defaultReadEntireFile); using ReadEntireFileBinart_t = decltype(defaultReadEntireFileBinary); using FileExists_t = decltype(defaultFileExists); struct ErrorReporter { ErrorCallback_t *currentErrorCallback = defaultErrorCallback; void *userData = nullptr; void callErrorCallback(std::string s); }; struct FileOpener { ReadEntireFile_t *readEntireFileCallback = defaultReadEntireFile; ReadEntireFileBinart_t *readEntireFileBinaryCallback = defaultReadEntireFileBinary; FileExists_t *fileExistsCallback = defaultFileExists; void *userData = nullptr; std::string operator()(const char *fileName, bool &couldNotOpen) { return readEntireFileCallback(fileName, couldNotOpen, userData); } std::vector binary(const char *fileName, bool &couldNotOpen) { return readEntireFileBinaryCallback(fileName, couldNotOpen, userData); } bool exists(const char *fileName) { return fileExistsCallback(fileName, userData); } }; }; #pragma endregion //////////////////////////////////////////////// //Animations.h //////////////////////////////////////////////// #pragma region Animations #pragma once #include #include #include #include #include #include #include namespace gl3d { //glm::mat4 animatedTransform{ 1.f }; //transform current default state to desired pos (model space) struct Joint { glm::mat4 inverseBindTransform{ 1.f }; glm::mat4 localBindTransform{1.f}; std::string name{}; std::vector children; glm::quat rotation{ 0.f,0.f,0.f,1.f }; glm::vec3 trans{ 1.f,1.f,1.f }; glm::vec3 scale{ 1.f,1.f,1.f }; glm::mat4 worldMatrix; //for extracting position data per bone //int index{}; //int root = 0; }; struct KeyFrame { glm::quat rotation{0.f,0.f,0.f,1.f}; glm::vec3 translation{}; float timeStamp{}; glm::vec3 scale{1.f, 1.f, 1.f}; unsigned char rotationSet = 0; unsigned char translationSet = 0; unsigned char scaleSet = 0; unsigned char notUsed = 0; }; struct KeyFrameRotation { glm::quat rotation{ 0.f,0.f,0.f,1.f }; float timeStamp{}; }; struct KeyFrameTranslation { glm::vec3 translation{}; float timeStamp{}; }; struct KeyFrameScale { glm::vec3 scale{ 1.f, 1.f, 1.f }; float timeStamp{}; }; struct TimeStamps { float passedTimeRot = 0; float passedTimeTrans = 0; float passedTimeScale = 0; }; struct Animation { std::string name; //for each joint we have keyframes std::vector> keyFramesRot; std::vector> keyFramesTrans; std::vector> keyFramesScale; //std::vector timeStamps; float animationDuration=0; std::vector root = {}; //std::vector timePassed; //std::vector> keyFrames; }; }; #pragma endregion //////////////////////////////////////////////// //json.h //////////////////////////////////////////////// #pragma region json /* __ _____ _____ _____ __| | __| | | | JSON for Modern C++ | | |__ | | | | | | version 3.5.0 |_____|_____|_____|_|___| https://github.com/nlohmann/json Licensed under the MIT License . SPDX-License-Identifier: MIT Copyright (c) 2013-2018 Niels Lohmann . 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 NLOHMANN_JSON_HPP #define NLOHMANN_JSON_HPP #define NLOHMANN_JSON_VERSION_MAJOR 3 #define NLOHMANN_JSON_VERSION_MINOR 5 #define NLOHMANN_JSON_VERSION_PATCH 0 #include // all_of, find, for_each #include // assert #include // and, not, or #include // nullptr_t, ptrdiff_t, size_t #include // hash, less #include // initializer_list #include // istream, ostream #include // random_access_iterator_tag #include // accumulate #include // string, stoi, to_string #include // declval, forward, move, pair, swap // #include #ifndef NLOHMANN_JSON_FWD_HPP #define NLOHMANN_JSON_FWD_HPP #include // int64_t, uint64_t #include // map #include // allocator #include // string #include // vector /*! @brief namespace for Niels Lohmann @see https://github.com/nlohmann @since version 1.0.0 */ namespace nlohmann { /*! @brief default JSONSerializer template argument This serializer ignores the template arguments and uses ADL ([argument-dependent lookup](https://en.cppreference.com/w/cpp/language/adl)) for serialization. */ template struct adl_serializer; template class ObjectType = std::map, template class ArrayType = std::vector, class StringType = std::string, class BooleanType = bool, class NumberIntegerType = std::int64_t, class NumberUnsignedType = std::uint64_t, class NumberFloatType = double, template class AllocatorType = std::allocator, template class JSONSerializer = adl_serializer> class basic_json; /*! @brief JSON Pointer A JSON pointer defines a string syntax for identifying a specific value within a JSON document. It can be used with functions `at` and `operator[]`. Furthermore, JSON pointers are the base for JSON patches. @sa [RFC 6901](https://tools.ietf.org/html/rfc6901) @since version 2.0.0 */ template class json_pointer; /*! @brief default JSON class This type is the default specialization of the @ref basic_json class which uses the standard template types. @since version 1.0.0 */ using json = basic_json<>; } // namespace nlohmann #endif // #include // This file contains all internal macro definitions // You MUST include macro_unscope.hpp at the end of json.hpp to undef all of them // exclude unsupported compilers #if !defined(JSON_SKIP_UNSUPPORTED_COMPILER_CHECK) #if defined(__clang__) #if (__clang_major__ * 10000 + __clang_minor__ * 100 + __clang_patchlevel__) < 30400 #error "unsupported Clang version - see https://github.com/nlohmann/json#supported-compilers" #endif #elif defined(__GNUC__) && !(defined(__ICC) || defined(__INTEL_COMPILER)) #if (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) < 40800 #error "unsupported GCC version - see https://github.com/nlohmann/json#supported-compilers" #endif #endif #endif // disable float-equal warnings on GCC/clang #if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wfloat-equal" #endif // disable documentation warnings on clang #if defined(__clang__) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdocumentation" #endif // allow for portable deprecation warnings #if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__) #define JSON_DEPRECATED __attribute__((deprecated)) #elif defined(_MSC_VER) #define JSON_DEPRECATED __declspec(deprecated) #else #define JSON_DEPRECATED #endif // allow to disable exceptions #if (defined(__cpp_exceptions) || defined(__EXCEPTIONS) || defined(_CPPUNWIND)) && !defined(JSON_NOEXCEPTION) #define JSON_THROW(exception) throw exception #define JSON_TRY try #define JSON_CATCH(exception) catch(exception) #define JSON_INTERNAL_CATCH(exception) catch(exception) #else #define JSON_THROW(exception) std::abort() #define JSON_TRY if(true) #define JSON_CATCH(exception) if(false) #define JSON_INTERNAL_CATCH(exception) if(false) #endif // override exception macros #if defined(JSON_THROW_USER) #undef JSON_THROW #define JSON_THROW JSON_THROW_USER #endif #if defined(JSON_TRY_USER) #undef JSON_TRY #define JSON_TRY JSON_TRY_USER #endif #if defined(JSON_CATCH_USER) #undef JSON_CATCH #define JSON_CATCH JSON_CATCH_USER #undef JSON_INTERNAL_CATCH #define JSON_INTERNAL_CATCH JSON_CATCH_USER #endif #if defined(JSON_INTERNAL_CATCH_USER) #undef JSON_INTERNAL_CATCH #define JSON_INTERNAL_CATCH JSON_INTERNAL_CATCH_USER #endif // manual branch prediction #if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__) #define JSON_LIKELY(x) __builtin_expect(!!(x), 1) #define JSON_UNLIKELY(x) __builtin_expect(!!(x), 0) #else #define JSON_LIKELY(x) x #define JSON_UNLIKELY(x) x #endif // C++ language standard detection #if (defined(__cplusplus) && __cplusplus >= 201703L) || (defined(_HAS_CXX17) && _HAS_CXX17 == 1) // fix for issue #464 #define JSON_HAS_CPP_17 #define JSON_HAS_CPP_14 #elif (defined(__cplusplus) && __cplusplus >= 201402L) || (defined(_HAS_CXX14) && _HAS_CXX14 == 1) #define JSON_HAS_CPP_14 #endif /*! @brief macro to briefly define a mapping between an enum and JSON @def NLOHMANN_JSON_SERIALIZE_ENUM @since version 3.4.0 */ #define NLOHMANN_JSON_SERIALIZE_ENUM(ENUM_TYPE, ...) \ template \ inline void to_json(BasicJsonType& j, const ENUM_TYPE& e) \ { \ static_assert(std::is_enum::value, #ENUM_TYPE " must be an enum!"); \ static const std::pair m[] = __VA_ARGS__; \ auto it = std::find_if(std::begin(m), std::end(m), \ [e](const std::pair& ej_pair) -> bool \ { \ return ej_pair.first == e; \ }); \ j = ((it != std::end(m)) ? it : std::begin(m))->second; \ } \ template \ inline void from_json(const BasicJsonType& j, ENUM_TYPE& e) \ { \ static_assert(std::is_enum::value, #ENUM_TYPE " must be an enum!"); \ static const std::pair m[] = __VA_ARGS__; \ auto it = std::find_if(std::begin(m), std::end(m), \ [j](const std::pair& ej_pair) -> bool \ { \ return ej_pair.second == j; \ }); \ e = ((it != std::end(m)) ? it : std::begin(m))->first; \ } // Ugly macros to avoid uglier copy-paste when specializing basic_json. They // may be removed in the future once the class is split. #define NLOHMANN_BASIC_JSON_TPL_DECLARATION \ template class ObjectType, \ template class ArrayType, \ class StringType, class BooleanType, class NumberIntegerType, \ class NumberUnsignedType, class NumberFloatType, \ template class AllocatorType, \ template class JSONSerializer> #define NLOHMANN_BASIC_JSON_TPL \ basic_json // #include #include // not #include // size_t #include // conditional, enable_if, false_type, integral_constant, is_constructible, is_integral, is_same, remove_cv, remove_reference, true_type namespace nlohmann { namespace detail { // alias templates to reduce boilerplate template using enable_if_t = typename std::enable_if::type; template using uncvref_t = typename std::remove_cv::type>::type; // implementation of C++14 index_sequence and affiliates // source: https://stackoverflow.com/a/32223343 template struct index_sequence { using type = index_sequence; using value_type = std::size_t; static constexpr std::size_t size() noexcept { return sizeof...(Ints); } }; template struct merge_and_renumber; template struct merge_and_renumber, index_sequence> : index_sequence < I1..., (sizeof...(I1) + I2)... > {}; template struct make_index_sequence : merge_and_renumber < typename make_index_sequence < N / 2 >::type, typename make_index_sequence < N - N / 2 >::type > {}; template<> struct make_index_sequence<0> : index_sequence<> {}; template<> struct make_index_sequence<1> : index_sequence<0> {}; template using index_sequence_for = make_index_sequence; // dispatch utility (taken from ranges-v3) template struct priority_tag : priority_tag < N - 1 > {}; template<> struct priority_tag<0> {}; // taken from ranges-v3 template struct static_const { static constexpr T value{}; }; template constexpr T static_const::value; } // namespace detail } // namespace nlohmann // #include #include // not #include // numeric_limits #include // false_type, is_constructible, is_integral, is_same, true_type #include // declval // #include // #include #include // random_access_iterator_tag // #include namespace nlohmann { namespace detail { template struct make_void { using type = void; }; template using void_t = typename make_void::type; } // namespace detail } // namespace nlohmann // #include namespace nlohmann { namespace detail { template struct iterator_types {}; template struct iterator_types < It, void_t> { using difference_type = typename It::difference_type; using value_type = typename It::value_type; using pointer = typename It::pointer; using reference = typename It::reference; using iterator_category = typename It::iterator_category; }; // This is required as some compilers implement std::iterator_traits in a way that // doesn't work with SFINAE. See https://github.com/nlohmann/json/issues/1341. template struct iterator_traits { }; template struct iterator_traits < T, enable_if_t < !std::is_pointer::value >> : iterator_types { }; template struct iterator_traits::value>> { using iterator_category = std::random_access_iterator_tag; using value_type = T; using difference_type = ptrdiff_t; using pointer = T*; using reference = T&; }; } } // #include // #include #include // #include // http://en.cppreference.com/w/cpp/experimental/is_detected namespace nlohmann { namespace detail { struct nonesuch { nonesuch() = delete; ~nonesuch() = delete; nonesuch(nonesuch const&) = delete; void operator=(nonesuch const&) = delete; }; template class Op, class... Args> struct detector { using value_t = std::false_type; using type = Default; }; template class Op, class... Args> struct detector>, Op, Args...> { using value_t = std::true_type; using type = Op; }; template