diff --git a/include/fggl/animation/skeleton.hpp b/include/fggl/animation/skeleton.hpp index 7a4169bd4ea5defb6f33cc6772701ba5128cb86a..315ebaa9cd234d5e31373064395f65b1893153e8 100644 --- a/include/fggl/animation/skeleton.hpp +++ b/include/fggl/animation/skeleton.hpp @@ -42,9 +42,9 @@ namespace fggl::anim { }; struct SkeletonPose { - Skeleton* m_skel; - JointPose* m_localPose; - math::mat4* m_globalPose; + Skeleton *m_skel; + JointPose *m_localPose; + math::mat4 *m_globalPose; }; struct SkinnedVertex { diff --git a/include/fggl/app.hpp b/include/fggl/app.hpp index b66846e69cafb2d996eaf0ce3e21e845aa7986c0..13019167c54e170cead9995396eed5a6a814da31 100644 --- a/include/fggl/app.hpp +++ b/include/fggl/app.hpp @@ -48,6 +48,7 @@ namespace fggl { * @param owner a non-owned reference to the owner of the state. */ explicit AppState(App &owner) : m_owner(owner) {} + virtual ~AppState() = default; /** @@ -81,17 +82,17 @@ namespace fggl { class App { public: - explicit App(modules::Manager* serivces, const Identifer &name); - App(modules::Manager* services, const Identifer &name, const Identifer &folderName); + explicit App(modules::Manager *serivces, const Identifer &name); + App(modules::Manager *services, const Identifer &name, const Identifer &folderName); // class is non copy-able App(const App &app) = delete; App(const App &&app) = delete; - App &operator=(const App& other) = delete; - App &operator=(App&& other) = delete; + App &operator=(const App &other) = delete; + App &operator=(App &&other) = delete; - inline void setWindow(display::Window* window) { + inline void setWindow(display::Window *window) { m_window = window; } @@ -118,7 +119,7 @@ namespace fggl { } template<typename T> - inline T* service() { + inline T *service() { try { return m_subsystems->template get<T>(); } catch (std::out_of_range &e) { @@ -137,10 +138,10 @@ namespace fggl { private: bool m_running; - display::Window* m_window; + display::Window *m_window; AppMachine m_states; Identifer m_expectedScene; - modules::Manager* m_subsystems; + modules::Manager *m_subsystems; }; } diff --git a/include/fggl/assets/loader.hpp b/include/fggl/assets/loader.hpp index 044b7a22a4c249075a9ed7e4e4ba376918f7e86c..a0cd15d39bf082924e6edba535849e512f169320 100644 --- a/include/fggl/assets/loader.hpp +++ b/include/fggl/assets/loader.hpp @@ -46,42 +46,43 @@ namespace fggl::assets { public: constexpr const static modules::ModuleService service = modules::make_service("fggl::assets::Loader"); - explicit inline Loader(data::Storage* storage) : m_storage(storage) {} - explicit Loader(Loader* parent, data::Storage* storage) : m_parent(parent), m_storage(storage) {}; + explicit inline Loader(data::Storage *storage) : m_storage(storage) {} + + explicit Loader(Loader *parent, data::Storage *storage) : m_parent(parent), m_storage(storage) {}; // no move, no copy. - Loader(const Loader&) = delete; - Loader& operator=(const Loader&) = delete; - Loader(Loader&&) = delete; - Loader& operator=(Loader&&) = delete; + Loader(const Loader &) = delete; + Loader &operator=(const Loader &) = delete; + Loader(Loader &&) = delete; + Loader &operator=(Loader &&) = delete; inline void setFactory(AssetType type, Checkin fn, LoadType loading = LoadType::DIRECT) { m_factories[type] = std::make_pair(fn, loading); } + inline void unsetFactory(AssetType type) { m_factories.erase(type); } - inline void request(const AssetGUID& guid, const AssetType& type) { + inline void request(const AssetGUID &guid, const AssetType &type) { m_requests.push(ResourceRequest{guid, type}); } - void load(const AssetGUID& guid, const AssetType& type) { + void load(const AssetGUID &guid, const AssetType &type) { auto path = m_storage->resolvePath(data::StorageType::Data, guid); - auto& config = m_factories.at(type); + auto &config = m_factories.at(type); switch (config.second) { - case LoadType::DIRECT: - // TODO we load the data into main memory and give a pointer to it. - debug::log(debug::Level::error, "Tried to load direct asset - no one wrote that yet!"); - break; - case LoadType::STAGED: - // TODO we load the data into temp memory and give a pointer to it. - debug::log(debug::Level::error, "Tried to load staged asset - no one wrote that yet!"); - break; - case LoadType::PATH: - config.first(guid, AssetData(&path)); - break; + case LoadType::DIRECT: + // TODO we load the data into main memory and give a pointer to it. + debug::log(debug::Level::error, "Tried to load direct asset - no one wrote that yet!"); + break; + case LoadType::STAGED: + // TODO we load the data into temp memory and give a pointer to it. + debug::log(debug::Level::error, "Tried to load staged asset - no one wrote that yet!"); + break; + case LoadType::PATH: config.first(guid, AssetData(&path)); + break; } } @@ -89,7 +90,7 @@ namespace fggl::assets { if (m_requests.empty()) { return; } - auto& request = m_requests.front(); + auto &request = m_requests.front(); load(request.m_guid, request.m_type); m_requests.pop(); } @@ -103,15 +104,15 @@ namespace fggl::assets { * Complete all remaining loading requests, blocking until complete. */ inline void finish() { - while ( !done() ) { + while (!done()) { progress(); } } private: - Loader* m_parent = nullptr; + Loader *m_parent = nullptr; using Config = std::pair<Checkin, LoadType>; - data::Storage* m_storage; + data::Storage *m_storage; std::queue<ResourceRequest> m_requests; std::map<AssetType, Config> m_factories; }; diff --git a/include/fggl/assets/manager.hpp b/include/fggl/assets/manager.hpp index 400a473df7fda0e6b039b94ede8628134e2efaae..0872282bbde35064630b0a803a88299a1d36d567 100644 --- a/include/fggl/assets/manager.hpp +++ b/include/fggl/assets/manager.hpp @@ -38,25 +38,25 @@ namespace fggl::assets { virtual ~AssetManager() = default; // no move, no copy. - AssetManager(const AssetManager&) = delete; - AssetManager& operator=(const AssetManager&) = delete; - AssetManager(AssetManager&&) = delete; - AssetManager& operator=(AssetManager&&) = delete; + AssetManager(const AssetManager &) = delete; + AssetManager &operator=(const AssetManager &) = delete; + AssetManager(AssetManager &&) = delete; + AssetManager &operator=(AssetManager &&) = delete; - inline AssetRefRaw getRaw(const AssetGUID& guid) const { + inline AssetRefRaw getRaw(const AssetGUID &guid) const { return m_registry.at(guid).asset; } template<typename T> - AssetRef<T> get(const AssetGUID& guid) const { + AssetRef<T> get(const AssetGUID &guid) const { return std::dynamic_pointer_cast<T>(getRaw(guid)); } - inline void require(const AssetGUID& guid) { + inline void require(const AssetGUID &guid) { m_registry.at(guid).refCount++; } - inline void release(const AssetGUID& guid) { + inline void release(const AssetGUID &guid) { m_registry.at(guid).refCount--; } @@ -65,16 +65,16 @@ namespace fggl::assets { std::shared_ptr<Asset> asset = nullptr; std::size_t refCount; - inline ~AssetRecord(){ - if ( asset != nullptr ) { + inline ~AssetRecord() { + if (asset != nullptr) { asset->release(); } } }; + std::map<AssetGUID, AssetRecord> m_registry; }; - } // namespace fggl::assets #endif //FGGL_ASSETS_MANAGER_HPP diff --git a/include/fggl/assets/module.hpp b/include/fggl/assets/module.hpp index 206c537764aa82d4b110939bb21b71730d262825..1c61f2d7724dd0b7195078b2eb58f1e766951ed1 100644 --- a/include/fggl/assets/module.hpp +++ b/include/fggl/assets/module.hpp @@ -27,7 +27,7 @@ namespace fggl::assets { struct AssetFolders { - constexpr static const char* name = "fggl::assets::Folders"; + constexpr static const char *name = "fggl::assets::Folders"; constexpr static const std::array<modules::ModuleService, 2> provides = { Loader::service, AssetManager::service @@ -35,7 +35,7 @@ namespace fggl::assets { constexpr static const std::array<modules::ModuleService, 1> depends = { data::Storage::service }; - static bool factory(modules::ModuleService name, modules::Services& serviceManager); + static bool factory(modules::ModuleService name, modules::Services &serviceManager); }; } // namespace fggl::assets diff --git a/include/fggl/assets/types.hpp b/include/fggl/assets/types.hpp index 7eb06066466e4ec8d4982c1d7c79f73f4fc9c94d..f31cd1b037ba22ebe1a0096af17f1441a3db008f 100644 --- a/include/fggl/assets/types.hpp +++ b/include/fggl/assets/types.hpp @@ -25,7 +25,7 @@ #include "fggl/util/safety.hpp" -namespace fggl::assets{ +namespace fggl::assets { using AssetType = util::OpaqueName<std::string_view, struct AssetTag>; using AssetGUID = std::string; using AssetPath = std::filesystem::path; @@ -37,7 +37,7 @@ namespace fggl::assets{ }; struct MemoryBlock { - void* data; + void *data; std::size_t size; }; @@ -46,8 +46,8 @@ namespace fggl::assets{ template<typename T> using AssetRef = std::shared_ptr<T>; - using AssetData = std::variant<MemoryBlock, AssetPath*, FILE*>; - using Checkin = std::function<AssetRefRaw(const AssetGUID&, const AssetData&)>; + using AssetData = std::variant<MemoryBlock, AssetPath *, FILE *>; + using Checkin = std::function<AssetRefRaw(const AssetGUID &, const AssetData &)>; } #endif //FGGL_ASSETS_TYPES_HPP diff --git a/include/fggl/audio/audio.hpp b/include/fggl/audio/audio.hpp index 4f733d2aa733fb391ba04bf42e71f3b029eeeb55..8b77de4eb577dbde591bce0da250f053967f7479 100644 --- a/include/fggl/audio/audio.hpp +++ b/include/fggl/audio/audio.hpp @@ -31,7 +31,7 @@ namespace fggl::audio { int channels = 0; int sampleRate = 0; int sampleCount = -1; - short* data = nullptr; + short *data = nullptr; }; constexpr modules::ModuleService SERVICE_AUDIO_PLAYBACK = modules::make_service("fggl::audio::AudioService"); @@ -43,8 +43,8 @@ namespace fggl::audio { class AudioService { public: constexpr static const modules::ModuleService service = SERVICE_AUDIO_PLAYBACK; - virtual void play(const std::string& filename, bool looping = false) = 0; - virtual void play(AudioClip& clip, bool looping = false) = 0; + virtual void play(const std::string &filename, bool looping = false) = 0; + virtual void play(AudioClip &clip, bool looping = false) = 0; virtual ~AudioService() = default; }; diff --git a/include/fggl/audio/null_audio.hpp b/include/fggl/audio/null_audio.hpp index b5d293fa555c93535570535498e66136351062d2..fb2bfd8ed40968bcd8c1b934225e383ffafed3f2 100644 --- a/include/fggl/audio/null_audio.hpp +++ b/include/fggl/audio/null_audio.hpp @@ -28,12 +28,13 @@ namespace fggl::audio { NullAudioService() = default; virtual ~NullAudioService() = default; - void play(const std::string& /*filename*/, bool /*looping = false*/) override {} - void play(AudioClip& /*clip*/, bool /*looping = false*/) override {} + void play(const std::string & /*filename*/, bool /*looping = false*/) override {} + + void play(AudioClip & /*clip*/, bool /*looping = false*/) override {} }; struct NullAudio { - constexpr static const char* name = "fggl::audio::NULL"; + constexpr static const char *name = "fggl::audio::NULL"; constexpr static const std::array<modules::ModuleService, 1> provides = { SERVICE_AUDIO_PLAYBACK }; @@ -41,13 +42,14 @@ namespace fggl::audio { static const modules::ServiceFactory factory; }; - bool null_factory(modules::ModuleService service, modules::Services& services) { + bool null_factory(modules::ModuleService service, modules::Services &services) { if (service == SERVICE_AUDIO_PLAYBACK) { services.bind<audio::AudioService, audio::NullAudioService>(); return true; } return false; } + const modules::ServiceFactory NullAudio::factory = null_factory; } // namespace fggl::audio diff --git a/include/fggl/audio/openal/audio.hpp b/include/fggl/audio/openal/audio.hpp index 4834c97ddc372e456945cb37957aa9248df8ed2f..9727ad8397a15092ab833183c110947d10d9c646 100644 --- a/include/fggl/audio/openal/audio.hpp +++ b/include/fggl/audio/openal/audio.hpp @@ -41,30 +41,24 @@ namespace fggl::audio::openal { static void checkError(std::string context) { auto code = alGetError(); - if ( code == AL_NO_ERROR) { + if (code == AL_NO_ERROR) { return; } // now we check the error message std::string error = "unknown"; - switch ( code ) { - case ALC_INVALID_DEVICE: - error = "Invalid Device"; - break; - case ALC_INVALID_CONTEXT: - error = "Invalid Context"; - break; - case ALC_INVALID_ENUM: - error = "Invalid enum"; - break; - case ALC_INVALID_VALUE: - error = "Invalid value"; - break; - case ALC_OUT_OF_MEMORY: - error = "Out of memory"; - break; - default: - error = "unknown error"; + switch (code) { + case ALC_INVALID_DEVICE: error = "Invalid Device"; + break; + case ALC_INVALID_CONTEXT: error = "Invalid Context"; + break; + case ALC_INVALID_ENUM: error = "Invalid enum"; + break; + case ALC_INVALID_VALUE: error = "Invalid value"; + break; + case ALC_OUT_OF_MEMORY: error = "Out of memory"; + break; + default: error = "unknown error"; } std::cerr << "OpenAL error: " << context << ": " << error << std::endl; @@ -75,33 +69,35 @@ namespace fggl::audio::openal { AudioBuffer() : m_buffer(0) { alGenBuffers(1, &m_buffer); } + ~AudioBuffer() { alDeleteBuffers(1, &m_buffer); } - inline void setData(AudioType type, void* data, ALsizei size, ALsizei frequency) { - alBufferData(m_buffer, (ALenum)type, data, size, frequency); + inline void setData(AudioType type, void *data, ALsizei size, ALsizei frequency) { + alBufferData(m_buffer, (ALenum) type, data, size, frequency); } inline ALuint value() { return m_buffer; } + private: ALuint m_buffer; }; - class AudioSource { public: AudioSource() : m_source(0), m_splat() { alGenSources(1, &m_source); } - ~AudioSource(){ + + ~AudioSource() { alDeleteSources(1, &m_source); } inline void play() { - alSourcePlay( m_source ); + alSourcePlay(m_source); } inline void stop() { @@ -109,19 +105,19 @@ namespace fggl::audio::openal { } inline void pause() { - alSourcePause( m_source ); + alSourcePause(m_source); } inline void rewind() { - alSourceRewind( m_source ); + alSourceRewind(m_source); } - inline void play(AudioBuffer& buffer, bool looping) { + inline void play(AudioBuffer &buffer, bool looping) { alSourcei(m_source, AL_BUFFER, buffer.value()); - alSourcei( m_source, AL_LOOPING, looping ? AL_TRUE : AL_FALSE); + alSourcei(m_source, AL_LOOPING, looping ? AL_TRUE : AL_FALSE); } - inline void play(AudioClip& clip, bool looping) { + inline void play(AudioClip &clip, bool looping) { checkError("pre play"); AudioType format = clip.channels == 1 ? AudioType::MONO_8 : AudioType::STEREO_8; @@ -129,20 +125,21 @@ namespace fggl::audio::openal { checkError("saving to buffer"); alSourcei(m_source, AL_BUFFER, m_splat.value()); - alSourcei( m_source, AL_LOOPING, looping ? AL_TRUE : AL_FALSE); + alSourcei(m_source, AL_LOOPING, looping ? AL_TRUE : AL_FALSE); checkError("setting parameters"); play(); } - inline void velocity(math::vec3& value) { + inline void velocity(math::vec3 &value) { alSource3f(m_source, AL_VELOCITY, value.x, value.y, value.z); } - inline void position(math::vec3& value) { + + inline void position(math::vec3 &value) { alSource3f(m_source, AL_POSITION, value.x, value.y, value.z); } - void direction(math::vec3& value) { + void direction(math::vec3 &value) { alSource3f(m_source, AL_DIRECTION, value.x, value.y, value.z); } @@ -151,11 +148,10 @@ namespace fggl::audio::openal { AudioBuffer m_splat; }; - class AudioServiceOAL : public AudioService { public: - explicit AudioServiceOAL(data::Storage* storage) : m_device(alcOpenDevice(nullptr)), m_storage(storage) { - if ( m_device != nullptr ) { + explicit AudioServiceOAL(data::Storage *storage) : m_device(alcOpenDevice(nullptr)), m_storage(storage) { + if (m_device != nullptr) { m_context = alcCreateContext(m_device, nullptr); alcMakeContextCurrent(m_context); checkError("context setup"); @@ -166,23 +162,22 @@ namespace fggl::audio::openal { } ~AudioServiceOAL() override { - if ( m_device != nullptr ) { + if (m_device != nullptr) { alcDestroyContext(m_context); alcCloseDevice(m_device); } } - void play(const std::string& filename, bool looping = false) override; - void play(AudioClip& clip, bool looping = false) override; + void play(const std::string &filename, bool looping = false) override; + void play(AudioClip &clip, bool looping = false) override; private: - ALCdevice* m_device; - ALCcontext* m_context{nullptr}; + ALCdevice *m_device; + ALCcontext *m_context{nullptr}; std::unique_ptr<AudioSource> m_defaultSource{nullptr}; - data::Storage* m_storage = nullptr; + data::Storage *m_storage = nullptr; }; - } // namespace fggl::audio::openal namespace fggl::audio { diff --git a/include/fggl/audio/openal/module.hpp b/include/fggl/audio/openal/module.hpp index 0468fa64667a9ae8d09e9f2b1f23150265ae0aba..238e4b702ead0352fb9e6bfd79467063ef004055 100644 --- a/include/fggl/audio/openal/module.hpp +++ b/include/fggl/audio/openal/module.hpp @@ -27,17 +27,17 @@ namespace fggl::audio { struct OpenAL { - constexpr static const char* name = "fggl::audio::OpenAL"; + constexpr static const char *name = "fggl::audio::OpenAL"; constexpr static const std::array<modules::ModuleService, 1> provides = { SERVICE_AUDIO_PLAYBACK }; constexpr static const std::array<modules::ModuleService, 1> depends = { modules::make_service("fggl::data::Storage") }; - static bool factory(modules::ModuleService name, modules::Services& serviceManager); + static bool factory(modules::ModuleService name, modules::Services &serviceManager); }; - bool OpenAL::factory(modules::ModuleService service, modules::Services& services) { + bool OpenAL::factory(modules::ModuleService service, modules::Services &services) { if (service == SERVICE_AUDIO_PLAYBACK) { auto storage = services.get<data::Storage>(); services.bind<audio::AudioService, openal::AudioServiceOAL>(storage); diff --git a/include/fggl/data/geom.hpp b/include/fggl/data/geom.hpp index 3bef04798a13dd184a28694d695ff3b503db8c5f..16635205565a152a4b99d5753ec29097aa64ab26 100644 --- a/include/fggl/data/geom.hpp +++ b/include/fggl/data/geom.hpp @@ -37,21 +37,21 @@ namespace fggl::data { return {vec.x, vec.y}; } - static void process_mesh(aiMesh* mesh, data::Mesh& meshRecord) { + static void process_mesh(aiMesh *mesh, data::Mesh &meshRecord) { // process vertices - std::vector< data::Mesh::IndexType > indexList; - for ( auto idx = 0; idx < mesh->mNumVertices; ++idx ) { - auto idxVal = meshRecord.pushVertex( { - .posititon = aiVec3ToFggl(mesh->mVertices[idx]), - .normal = aiVec3ToFggl( mesh->mNormals[idx] ), - .texPos = aiVec2ToFggl( mesh->mTextureCoords[0][idx] ) - } ); - indexList.push_back( idxVal ); + std::vector<data::Mesh::IndexType> indexList; + for (auto idx = 0; idx < mesh->mNumVertices; ++idx) { + auto idxVal = meshRecord.pushVertex({ + .posititon = aiVec3ToFggl(mesh->mVertices[idx]), + .normal = aiVec3ToFggl(mesh->mNormals[idx]), + .texPos = aiVec2ToFggl(mesh->mTextureCoords[0][idx]) + }); + indexList.push_back(idxVal); } - if ( mesh->HasFaces() ) { + if (mesh->HasFaces()) { // if there is face data, that's our index list - for ( auto face = 0; face < mesh->mNumFaces; ++face ) { + for (auto face = 0; face < mesh->mNumFaces; ++face) { auto &facePtr = mesh->mFaces[face]; meshRecord.pushIndex(indexList[facePtr.mIndices[0]]); meshRecord.pushIndex(indexList[facePtr.mIndices[1]]); @@ -60,29 +60,29 @@ namespace fggl::data { } } - static void process_model(aiScene* scene, aiNode* node, data::Mesh& mesh) { + static void process_model(aiScene *scene, aiNode *node, data::Mesh &mesh) { auto ptr = node->mMeshes; - for ( auto j=0; j < node->mNumMeshes; ++j ) { + for (auto j = 0; j < node->mNumMeshes; ++j) { for (int meshCount = 0; node->mNumMeshes; ++meshCount) { auto aiMeshIdx = node->mMeshes[meshCount]; data::Mesh mesh; - auto* aiMesh = scene->mMeshes[aiMeshIdx]; - process_mesh( aiMesh, mesh); + auto *aiMesh = scene->mMeshes[aiMeshIdx]; + process_mesh(aiMesh, mesh); } } // process child meshes - for ( int i = 0; i < node->mNumChildren; ++i ) { - auto* child = node->mChildren[i]; - process_model( child ); + for (int i = 0; i < node->mNumChildren; ++i) { + auto *child = node->mChildren[i]; + process_model(child); } } template<> bool fggl_deserialize(std::filesystem::path &data, StaticMesh *out) { Assimp::Importer importer; - const aiScene* scene = importer.ReadFile( data.c_str(), aiProcess_Triangulate | aiProcess_FlipUVs ); + const aiScene *scene = importer.ReadFile(data.c_str(), aiProcess_Triangulate | aiProcess_FlipUVs); // check if the import worked if (scene == nullptr || scene->mFlags & AI_SCENE_FLAGS_INCOMPLETE || !scene->mRootNode) { @@ -90,7 +90,7 @@ namespace fggl::data { } // figure out the meshes - process_model( scene->mRootNode ); + process_model(scene->mRootNode); //TODO implement the rest of this return false; diff --git a/include/fggl/data/heightmap.hpp b/include/fggl/data/heightmap.hpp index d541368fd48b88fc6fd0c778c5842aff78e33a81..6f3c84b8a2b9a0e21278f91d09a36f9dfe2e7f3f 100644 --- a/include/fggl/data/heightmap.hpp +++ b/include/fggl/data/heightmap.hpp @@ -54,7 +54,7 @@ namespace fggl::data { return x * zMax + z; } - void generateHeightMesh(const data::HeightMap& heights, data::Mesh &mesh); + void generateHeightMesh(const data::HeightMap &heights, data::Mesh &mesh); } #endif //FGGL_DATA_HEIGHTMAP_HPP diff --git a/include/fggl/data/module.hpp b/include/fggl/data/module.hpp index b9f51c118babc273b36b3b178cf4557d34119018..f4c9c43db705c4dafdddf0ffde1f8e6c0bf2c054 100644 --- a/include/fggl/data/module.hpp +++ b/include/fggl/data/module.hpp @@ -26,15 +26,14 @@ namespace fggl::data { struct LocalStorage { - constexpr static const char* name = "fggl::data::Storage"; + constexpr static const char *name = "fggl::data::Storage"; constexpr static const std::array<modules::ModuleService, 1> provides = { SERVICE_STORAGE }; constexpr static const std::array<modules::ModuleService, 0> depends = {}; - static bool factory(modules::ModuleService service, modules::Services& serviceManager); + static bool factory(modules::ModuleService service, modules::Services &serviceManager); }; - } // namespace fggl::data #endif //FGGL_DATA_MODULE_HPP diff --git a/include/fggl/data/procedural.hpp b/include/fggl/data/procedural.hpp index 522ea0434377286cd3e1f3446830ea0c858761b1..53ec3e6ececa559c8f86c7d62511e109634419c9 100644 --- a/include/fggl/data/procedural.hpp +++ b/include/fggl/data/procedural.hpp @@ -27,15 +27,15 @@ namespace fggl::data { Mesh make_quad_xz(); // platonic solids - void make_tetrahedron(Mesh& mesh, const math::mat4& offset = OFFSET_NONE); + void make_tetrahedron(Mesh &mesh, const math::mat4 &offset = OFFSET_NONE); Mesh make_cube(Mesh &mesh, const math::mat4 &offset = OFFSET_NONE); - void make_octahedron(Mesh& mesh, const math::mat4& offset = OFFSET_NONE); - void make_icosahedron(Mesh& mesh, const math::mat4& offset = OFFSET_NONE); - void make_dodecahedron(Mesh& mesh, const math::mat4& offset = OFFSET_NONE); + void make_octahedron(Mesh &mesh, const math::mat4 &offset = OFFSET_NONE); + void make_icosahedron(Mesh &mesh, const math::mat4 &offset = OFFSET_NONE); + void make_dodecahedron(Mesh &mesh, const math::mat4 &offset = OFFSET_NONE); // useful shapes - void make_sphere_uv(Mesh &mesh, const math::mat4& offset = OFFSET_NONE); - void make_sphere_iso(Mesh &mesh, const math::mat4& offset = OFFSET_NONE); + void make_sphere_uv(Mesh &mesh, const math::mat4 &offset = OFFSET_NONE); + void make_sphere_iso(Mesh &mesh, const math::mat4 &offset = OFFSET_NONE); // level block-out shapes Mesh make_slope(Mesh &mesh, const math::mat4 &offset = OFFSET_NONE); @@ -43,8 +43,8 @@ namespace fggl::data { Mesh make_point(Mesh &mesh, const math::mat4 &offset = OFFSET_NONE); // other useful types people expect - void make_capsule(Mesh& mesh); - void make_sphere(Mesh &mesh, const math::mat4& offset = OFFSET_NONE, uint32_t stacks = 16U, uint32_t slices = 16U); + void make_capsule(Mesh &mesh); + void make_sphere(Mesh &mesh, const math::mat4 &offset = OFFSET_NONE, uint32_t stacks = 16U, uint32_t slices = 16U); } #endif \ No newline at end of file diff --git a/include/fggl/data/storage.hpp b/include/fggl/data/storage.hpp index 2704ec0080b45ac17e614b425e606d86fd459b3b..0b992595ecac218d4c58ba4de2390e76e7ebb5ea 100644 --- a/include/fggl/data/storage.hpp +++ b/include/fggl/data/storage.hpp @@ -40,7 +40,8 @@ namespace fggl::data { class Storage { public: constexpr static modules::ModuleService service = SERVICE_STORAGE; - Storage( fggl::platform::EnginePaths paths ) : m_paths(std::move( paths )) {} + + Storage(fggl::platform::EnginePaths paths) : m_paths(std::move(paths)) {} template<typename T> bool load(StorageType pool, const std::string &name, T *out) { @@ -53,14 +54,14 @@ namespace fggl::data { } std::vector<std::filesystem::path> findResources(std::filesystem::path root, const std::string ext) { - if ( !std::filesystem::exists(root) ) { + if (!std::filesystem::exists(root)) { return {}; } std::vector<std::filesystem::path> paths; - for ( const auto& entry : std::filesystem::recursive_directory_iterator(root) ) { - if ( entry.is_regular_file() && entry.path().extension() == ext ) { - paths.push_back( entry ); + for (const auto &entry : std::filesystem::recursive_directory_iterator(root)) { + if (entry.is_regular_file() && entry.path().extension() == ext) { + paths.push_back(entry); } } return paths; @@ -72,22 +73,21 @@ namespace fggl::data { fggl_serialize<T>(path, out); } - inline std::filesystem::path resolvePath(StorageType pool, const std::string &name, bool createParents = false) { + inline std::filesystem::path resolvePath(StorageType pool, + const std::string &name, + bool createParents = false) { std::filesystem::path path; switch (pool) { - case Data: - path = fggl::platform::locate_data(m_paths, name); - break; - case Config: - path = fggl::platform::locate_config(m_paths, name); - break; - case Cache: - path = fggl::platform::locate_cache(m_paths, name); - break; + case Data: path = fggl::platform::locate_data(m_paths, name); + break; + case Config: path = fggl::platform::locate_config(m_paths, name); + break; + case Cache: path = fggl::platform::locate_cache(m_paths, name); + break; } - if ( createParents ){ - if ( !std::filesystem::exists(path.parent_path()) ) { + if (createParents) { + if (!std::filesystem::exists(path.parent_path())) { std::filesystem::create_directories(path.parent_path()); } } diff --git a/include/fggl/debug/debug.h b/include/fggl/debug/debug.h index e1d9cb64b265ac86bed26f6ad4f1c5a86df2d378..0ef6c6d2ab97f5113e1ade21f36525d7d9773b9e 100644 --- a/include/fggl/debug/debug.h +++ b/include/fggl/debug/debug.h @@ -41,7 +41,7 @@ namespace fggl::debug { void draw(); inline void addWindow(const std::string &name, DebugUIDraw window) { - m_windows[name] = DebugWindow{true, std::move(window) }; + m_windows[name] = DebugWindow{true, std::move(window)}; } inline void visible(bool state) { diff --git a/include/fggl/debug/draw.hpp b/include/fggl/debug/draw.hpp index 4ddfa7f8e7bf58ecda610982f5ef81e08f0306b9..901f20c17305db6a292f5804893ec841d5a9b482 100644 --- a/include/fggl/debug/draw.hpp +++ b/include/fggl/debug/draw.hpp @@ -230,6 +230,7 @@ // #ifndef DEBUG_DRAW_OVERFLOWED #include <cstdio> + #define DEBUG_DRAW_OVERFLOWED(message) std::fprintf(stderr, "%s\n", message) #endif // DEBUG_DRAW_OVERFLOWED @@ -275,7 +276,7 @@ typedef float ddVec3[3]; // passing by const reference instead, however, some platforms have optimized // hardware registers for vec3s/vec4s, so passing by value might also be efficient. typedef const ddVec3 ddVec3_In; -typedef ddVec3 ddVec3_Out; +typedef ddVec3 ddVec3_Out; #define DEBUG_DRAW_VEC3_TYPE_DEFINED 1 #endif // DEBUG_DRAW_VEC3_TYPE_DEFINED @@ -302,7 +303,7 @@ typedef float ddMat4x4[4 * 4]; // If you change it to some structured type, it might be more efficient // passing by const reference instead. typedef const ddMat4x4 ddMat4x4_In; -typedef ddMat4x4 ddMat4x4_Out; +typedef ddMat4x4 ddMat4x4_Out; #define DEBUG_DRAW_MAT4X4_TYPE_DEFINED 1 #endif // DEBUG_DRAW_MAT4X4_TYPE_DEFINED @@ -315,23 +316,22 @@ typedef ddMat4x4 ddMat4x4_Out; // null-terminated const char* string pointer. That's it. // An array subscript operator [] is not required for ddStr. #include <string> -typedef std::string ddStr; -typedef const ddStr & ddStr_In; -typedef ddStr & ddStr_Out; + +typedef std::string ddStr; +typedef const ddStr &ddStr_In; +typedef ddStr &ddStr_Out; #define DEBUG_DRAW_STRING_TYPE_DEFINED 1 #endif // DEBUG_DRAW_STRING_TYPE_DEFINED -namespace dd -{ +namespace dd { // ======================================================== // Optional built-in colors in RGB float format: // ======================================================== #ifndef DEBUG_DRAW_NO_DEFAULT_COLORS - namespace colors - { + namespace colors { extern const ddVec3 AliceBlue; extern const ddVec3 AntiqueWhite; extern const ddVec3 Aquamarine; @@ -480,8 +480,8 @@ namespace dd #ifdef DEBUG_DRAW_EXPLICIT_CONTEXT struct OpaqueContextType { }; - typedef OpaqueContextType * ContextHandle; - #define DD_EXPLICIT_CONTEXT_ONLY(...) __VA_ARGS__ + typedef OpaqueContextType * ContextHandle; + #define DD_EXPLICIT_CONTEXT_ONLY(...) __VA_ARGS__ #else // !DEBUG_DRAW_EXPLICIT_CONTEXT #define DD_EXPLICIT_CONTEXT_ONLY(...) /* nothing */ #endif // DEBUG_DRAW_EXPLICIT_CONTEXT @@ -519,7 +519,7 @@ namespace dd // The third element (Z) of the position vector is ignored. // Note: Newlines and tabs are handled (1 tab = 4 spaces). void screenText(DD_EXPLICIT_CONTEXT_ONLY(ContextHandle ctx,) - const char * str, + const char *str, ddVec3_In pos, ddVec3_In color, float scaling = 1.0f, @@ -530,7 +530,7 @@ namespace dd // sx/sy, sw/sh are the viewport coordinates/size, in pixels. // 'vpMatrix' is the view * projection transform to map the text from 3D to 2D. void projectedText(DD_EXPLICIT_CONTEXT_ONLY(ContextHandle ctx,) - const char * str, + const char *str, ddVec3_In pos, ddVec3_In color, ddMat4x4_In vpMatrix, @@ -684,23 +684,19 @@ namespace dd // The only drawing type the user has to interface with. // ======================================================== - union DrawVertex - { - struct - { + union DrawVertex { + struct { float x, y, z; float r, g, b; float size; } point; - struct - { + struct { float x, y, z; float r, g, b; } line; - struct - { + struct { float x, y; float u, v; float r, g, b; @@ -711,8 +707,8 @@ namespace dd // Opaque handle to a texture object. // Used by the debug text drawing functions. // - struct OpaqueTextureType { }; - typedef OpaqueTextureType * GlyphTextureHandle; + struct OpaqueTextureType {}; + typedef OpaqueTextureType *GlyphTextureHandle; // ======================================================== // Debug Draw rendering callbacks: @@ -720,8 +716,7 @@ namespace dd // tie this code directly to a specific rendering API. // ======================================================== - class RenderInterface - { + class RenderInterface { public: // @@ -743,16 +738,16 @@ namespace dd // The pixel values range from 255 for a pixel within a glyph to 0 for a transparent pixel. // If createGlyphTexture() returns null, the renderer will disable all text drawing functions. // - virtual GlyphTextureHandle createGlyphTexture(int width, int height, const void * pixels); + virtual GlyphTextureHandle createGlyphTexture(int width, int height, const void *pixels); virtual void destroyGlyphTexture(GlyphTextureHandle glyphTex); // // Batch drawing methods for the primitives used by the debug renderer. // If you don't wish to support a given primitive type, don't override the method. // - virtual void drawPointList(const DrawVertex * points, int count, bool depthEnabled); - virtual void drawLineList(const DrawVertex * lines, int count, bool depthEnabled); - virtual void drawGlyphList(const DrawVertex * glyphs, int count, GlyphTextureHandle glyphTex); + virtual void drawPointList(const DrawVertex *points, int count, bool depthEnabled); + virtual void drawLineList(const DrawVertex *lines, int count, bool depthEnabled); + virtual void drawGlyphList(const DrawVertex *glyphs, int count, GlyphTextureHandle glyphTex); // User defined cleanup. Nothing by default. virtual ~RenderInterface() = 0; @@ -763,19 +758,18 @@ namespace dd // ======================================================== // Flags for dd::flush() - enum FlushFlags - { + enum FlushFlags { FlushPoints = 1 << 1, - FlushLines = 1 << 2, - FlushText = 1 << 3, - FlushAll = (FlushPoints | FlushLines | FlushText) + FlushLines = 1 << 2, + FlushText = 1 << 3, + FlushAll = (FlushPoints | FlushLines | FlushText) }; // Initialize with the user-supplied renderer interface. // Given object must remain valid until after dd::shutdown() is called! // If 'renderer' is null, the Debug Draw functions become no-ops, but // can still be safely called. - bool initialize(DD_EXPLICIT_CONTEXT_ONLY(ContextHandle * outCtx,) RenderInterface * renderer); + bool initialize(DD_EXPLICIT_CONTEXT_ONLY(ContextHandle * outCtx,) RenderInterface *renderer); // After this is called, it is safe to dispose the dd::RenderInterface instance // you passed to dd::initialize(). Shutdown will also attempt to free the glyph texture. @@ -814,29 +808,29 @@ namespace dd #ifdef DEBUG_DRAW_IMPLEMENTATION #ifndef DD_MALLOC - #include <cstdlib> - #define DD_MALLOC std::malloc - #define DD_MFREE std::free + #include <cstdlib> + #define DD_MALLOC std::malloc + #define DD_MFREE std::free #endif // DD_MALLOC #if DEBUG_DRAW_USE_STD_MATH - #include <math.h> - #include <float.h> + #include <math.h> + #include <float.h> #endif // DEBUG_DRAW_USE_STD_MATH namespace dd { #if defined(FLT_EPSILON) && DEBUG_DRAW_USE_STD_MATH - static const float FloatEpsilon = FLT_EPSILON; + static const float FloatEpsilon = FLT_EPSILON; #else // !FLT_EPSILON || !DEBUG_DRAW_USE_STD_MATH - static const float FloatEpsilon = 1e-14; + static const float FloatEpsilon = 1e-14; #endif // FLT_EPSILON && DEBUG_DRAW_USE_STD_MATH #if defined(M_PI) && DEBUG_DRAW_USE_STD_MATH - static const float PI = static_cast<float>(M_PI); + static const float PI = static_cast<float>(M_PI); #else // !M_PI || !DEBUG_DRAW_USE_STD_MATH - static const float PI = 3.1415926535897931f; + static const float PI = 3.1415926535897931f; #endif // M_PI && DEBUG_DRAW_USE_STD_MATH static const float HalfPI = PI * 0.5f; @@ -845,13 +839,13 @@ static const float TAU = PI * 2.0f; template<typename T> static inline float degreesToRadians(const T degrees) { - return (static_cast<float>(degrees) * PI / 180.0f); + return (static_cast<float>(degrees) * PI / 180.0f); } template<typename T, int Size> static inline int arrayLength(const T (&)[Size]) { - return Size; + return Size; } // ======================================================== @@ -1009,35 +1003,35 @@ const ddVec3 YellowGreen = {0.603922f, 0.803922f, 0.196078f}; struct FontChar { - std::uint16_t x; - std::uint16_t y; + std::uint16_t x; + std::uint16_t y; }; struct FontCharSet { - enum { MaxChars = 256 }; - const std::uint8_t * bitmap; - int bitmapWidth; - int bitmapHeight; - int bitmapColorChannels; - int bitmapDecompressSize; - int charBaseHeight; - int charWidth; - int charHeight; - int charCount; - FontChar chars[MaxChars]; + enum { MaxChars = 256 }; + const std::uint8_t * bitmap; + int bitmapWidth; + int bitmapHeight; + int bitmapColorChannels; + int bitmapDecompressSize; + int charBaseHeight; + int charWidth; + int charHeight; + int charCount; + FontChar chars[MaxChars]; }; #if DEBUG_DRAW_CXX11_SUPPORTED - #define DD_ALIGNED_BUFFER(name) alignas(16) static const std::uint8_t name[] + #define DD_ALIGNED_BUFFER(name) alignas(16) static const std::uint8_t name[] #else // !C++11 - #if defined(__GNUC__) // Clang & GCC - #define DD_ALIGNED_BUFFER(name) static const std::uint8_t name[] __attribute__((aligned(16))) - #elif defined(_MSC_VER) // Visual Studio - #define DD_ALIGNED_BUFFER(name) __declspec(align(16)) static const std::uint8_t name[] - #else // Unknown compiler - #define DD_ALIGNED_BUFFER(name) static const std::uint8_t name[] /* hope for the best! */ - #endif // Compiler id + #if defined(__GNUC__) // Clang & GCC + #define DD_ALIGNED_BUFFER(name) static const std::uint8_t name[] __attribute__((aligned(16))) + #elif defined(_MSC_VER) // Visual Studio + #define DD_ALIGNED_BUFFER(name) __declspec(align(16)) static const std::uint8_t name[] + #else // Unknown compiler + #define DD_ALIGNED_BUFFER(name) static const std::uint8_t name[] /* hope for the best! */ + #endif // Compiler id #endif // DEBUG_DRAW_CXX11_SUPPORTED // @@ -1502,34 +1496,34 @@ static const int LzwMaxDictEntries = (1 << LzwMaxDictBits); // 4096 struct LzwDictionary { - // Dictionary entries 0-255 are always reserved to the byte/ASCII range. - struct Entry - { - int code; - int value; - }; + // Dictionary entries 0-255 are always reserved to the byte/ASCII range. + struct Entry + { + int code; + int value; + }; - int size; - Entry entries[LzwMaxDictEntries]; + int size; + Entry entries[LzwMaxDictEntries]; - LzwDictionary(); - int findIndex(int code, int value) const; - bool add(int code, int value); - bool flush(int & codeBitsWidth); + LzwDictionary(); + int findIndex(int code, int value) const; + bool add(int code, int value); + bool flush(int & codeBitsWidth); }; struct LzwBitStreamReader { - const std::uint8_t * stream; // Pointer to the external bit stream. Not owned by the reader. - int sizeInBytes; // Size of the stream in bytes. Might include padding. - int sizeInBits; // Size of the stream in bits, padding not include. - int currBytePos; // Current byte being read in the stream. - int nextBitPos; // Bit position within the current byte to access next. 0 to 7. - int numBitsRead; // Total bits read from the stream so far. Never includes byte-rounding. + const std::uint8_t * stream; // Pointer to the external bit stream. Not owned by the reader. + int sizeInBytes; // Size of the stream in bytes. Might include padding. + int sizeInBits; // Size of the stream in bits, padding not include. + int currBytePos; // Current byte being read in the stream. + int nextBitPos; // Bit position within the current byte to access next. 0 to 7. + int numBitsRead; // Total bits read from the stream so far. Never includes byte-rounding. - LzwBitStreamReader(const std::uint8_t * bitStream, int byteCount, int bitCount); - bool readNextBit(int & outBit); - int readBits(int bitCount); + LzwBitStreamReader(const std::uint8_t * bitStream, int byteCount, int bitCount); + bool readNextBit(int & outBit); + int readBits(int bitCount); }; // ======================================================== @@ -1538,59 +1532,59 @@ struct LzwBitStreamReader LzwDictionary::LzwDictionary() { - // First 256 dictionary entries are reserved to the byte/ASCII - // range. Additional entries follow for the character sequences - // found in the input. Up to 4096 - 256 (LzwMaxDictEntries - LzwFirstCode). - size = LzwFirstCode; - for (int i = 0; i < size; ++i) - { - entries[i].code = LzwNil; - entries[i].value = i; - } + // First 256 dictionary entries are reserved to the byte/ASCII + // range. Additional entries follow for the character sequences + // found in the input. Up to 4096 - 256 (LzwMaxDictEntries - LzwFirstCode). + size = LzwFirstCode; + for (int i = 0; i < size; ++i) + { + entries[i].code = LzwNil; + entries[i].value = i; + } } int LzwDictionary::findIndex(const int code, const int value) const { - if (code == LzwNil) - { - return value; - } - for (int i = 0; i < size; ++i) - { - if (entries[i].code == code && entries[i].value == value) - { - return i; - } - } - return LzwNil; + if (code == LzwNil) + { + return value; + } + for (int i = 0; i < size; ++i) + { + if (entries[i].code == code && entries[i].value == value) + { + return i; + } + } + return LzwNil; } bool LzwDictionary::add(const int code, const int value) { - if (size == LzwMaxDictEntries) - { - return false; - } - entries[size].code = code; - entries[size].value = value; - ++size; - return true; + if (size == LzwMaxDictEntries) + { + return false; + } + entries[size].code = code; + entries[size].value = value; + ++size; + return true; } bool LzwDictionary::flush(int & codeBitsWidth) { - if (size == (1 << codeBitsWidth)) - { - ++codeBitsWidth; - if (codeBitsWidth > LzwMaxDictBits) - { - // Clear the dictionary (except the first 256 byte entries). - codeBitsWidth = LzwStartBits; - size = LzwFirstCode; - return true; - } - } - return false; + if (size == (1 << codeBitsWidth)) + { + ++codeBitsWidth; + if (codeBitsWidth > LzwMaxDictBits) + { + // Clear the dictionary (except the first 256 byte entries). + codeBitsWidth = LzwStartBits; + size = LzwFirstCode; + return true; + } + } + return false; } // ======================================================== @@ -1598,47 +1592,47 @@ bool LzwDictionary::flush(int & codeBitsWidth) // ======================================================== LzwBitStreamReader::LzwBitStreamReader(const std::uint8_t * bitStream, const int byteCount, const int bitCount) - : stream(bitStream) - , sizeInBytes(byteCount) - , sizeInBits(bitCount) - , currBytePos(0) - , nextBitPos(0) - , numBitsRead(0) + : stream(bitStream) + , sizeInBytes(byteCount) + , sizeInBits(bitCount) + , currBytePos(0) + , nextBitPos(0) + , numBitsRead(0) { } bool LzwBitStreamReader::readNextBit(int & outBit) { - if (numBitsRead >= sizeInBits) - { - return false; // We are done. - } - - const int mask = 1 << nextBitPos; - outBit = !!(stream[currBytePos] & mask); - ++numBitsRead; - - if (++nextBitPos == 8) - { - nextBitPos = 0; - ++currBytePos; - } - return true; + if (numBitsRead >= sizeInBits) + { + return false; // We are done. + } + + const int mask = 1 << nextBitPos; + outBit = !!(stream[currBytePos] & mask); + ++numBitsRead; + + if (++nextBitPos == 8) + { + nextBitPos = 0; + ++currBytePos; + } + return true; } int LzwBitStreamReader::readBits(const int bitCount) { - int num = 0; - for (int b = 0; b < bitCount; ++b) - { - int bit; - if (!readNextBit(bit)) - { - break; - } - const int mask = 1 << b; - num = (num & ~mask) | (-bit & mask); - } - return num; + int num = 0; + for (int b = 0; b < bitCount; ++b) + { + int bit; + if (!readNextBit(bit)) + { + break; + } + const int mask = 1 << b; + num = (num & ~mask) | (-bit & mask); + } + return num; } // ======================================================== @@ -1647,129 +1641,129 @@ int LzwBitStreamReader::readBits(const int bitCount) static bool lzwOutputByte(int code, std::uint8_t *& output, int outputSizeBytes, int & bytesDecodedSoFar) { - if (code < 0 || code >= 256) - { - return false; - } - if (bytesDecodedSoFar >= outputSizeBytes) - { - return false; - } - *output++ = static_cast<std::uint8_t>(code); - ++bytesDecodedSoFar; - return true; + if (code < 0 || code >= 256) + { + return false; + } + if (bytesDecodedSoFar >= outputSizeBytes) + { + return false; + } + *output++ = static_cast<std::uint8_t>(code); + ++bytesDecodedSoFar; + return true; } static bool lzwOutputSequence(const LzwDictionary & dict, int code, - std::uint8_t *& output, int outputSizeBytes, - int & bytesDecodedSoFar, int & firstByte) -{ - // A sequence is stored backwards, so we have to write - // it to a temp then output the buffer in reverse. - int i = 0; - std::uint8_t sequence[LzwMaxDictEntries]; - do - { - sequence[i++] = dict.entries[code].value & 0xFF; - code = dict.entries[code].code; - } while (code >= 0); - - firstByte = sequence[--i]; - for (; i >= 0; --i) - { - if (!lzwOutputByte(sequence[i], output, outputSizeBytes, bytesDecodedSoFar)) - { - return false; - } - } - return true; + std::uint8_t *& output, int outputSizeBytes, + int & bytesDecodedSoFar, int & firstByte) +{ + // A sequence is stored backwards, so we have to write + // it to a temp then output the buffer in reverse. + int i = 0; + std::uint8_t sequence[LzwMaxDictEntries]; + do + { + sequence[i++] = dict.entries[code].value & 0xFF; + code = dict.entries[code].code; + } while (code >= 0); + + firstByte = sequence[--i]; + for (; i >= 0; --i) + { + if (!lzwOutputByte(sequence[i], output, outputSizeBytes, bytesDecodedSoFar)) + { + return false; + } + } + return true; } static int lzwDecompress(const void * compressedData, int compressedSizeBytes, - int compressedSizeBits, void * uncompressedData, - int uncompressedSizeBytes) -{ - if (compressedData == nullptr || uncompressedData == nullptr) - { - return 0; - } - if (compressedSizeBytes <= 0 || compressedSizeBits <= 0 || uncompressedSizeBytes <= 0) - { - return 0; - } - - int code = LzwNil; - int prevCode = LzwNil; - int codeBitsWidth = LzwStartBits; - int firstByte = 0; - int bytesDecoded = 0; - - const std::uint8_t * compressedPtr = reinterpret_cast<const std::uint8_t *>(compressedData); - std::uint8_t * uncompressedPtr = reinterpret_cast<std::uint8_t *>(uncompressedData); - - // We'll reconstruct the dictionary based on the bit stream codes. - LzwBitStreamReader bitStream(compressedPtr, compressedSizeBytes, compressedSizeBits); - LzwDictionary dictionary; - - // We check to avoid an overflow of the user buffer. - // If the buffer is smaller than the decompressed size, we - // break the loop and return the current decompression count. - while (bitStream.numBitsRead < bitStream.sizeInBits) - { - if (codeBitsWidth > LzwMaxDictBits) - { - break; - } - code = bitStream.readBits(codeBitsWidth); - - if (prevCode == LzwNil) - { - if (!lzwOutputByte(code, uncompressedPtr, uncompressedSizeBytes, bytesDecoded)) - { - break; - } - firstByte = code; - prevCode = code; - continue; - } - - if (code >= dictionary.size) - { - if (!lzwOutputSequence(dictionary, prevCode, uncompressedPtr, - uncompressedSizeBytes, bytesDecoded, firstByte)) - { - break; - } - if (!lzwOutputByte(firstByte, uncompressedPtr, uncompressedSizeBytes, bytesDecoded)) - { - break; - } - } - else - { - if (!lzwOutputSequence(dictionary, code, uncompressedPtr, - uncompressedSizeBytes, bytesDecoded, firstByte)) - { - break; - } - } - - if (!dictionary.add(prevCode, firstByte)) - { - break; - } - - if (dictionary.flush(codeBitsWidth)) - { - prevCode = LzwNil; - } - else - { - prevCode = code; - } - } - - return bytesDecoded; + int compressedSizeBits, void * uncompressedData, + int uncompressedSizeBytes) +{ + if (compressedData == nullptr || uncompressedData == nullptr) + { + return 0; + } + if (compressedSizeBytes <= 0 || compressedSizeBits <= 0 || uncompressedSizeBytes <= 0) + { + return 0; + } + + int code = LzwNil; + int prevCode = LzwNil; + int codeBitsWidth = LzwStartBits; + int firstByte = 0; + int bytesDecoded = 0; + + const std::uint8_t * compressedPtr = reinterpret_cast<const std::uint8_t *>(compressedData); + std::uint8_t * uncompressedPtr = reinterpret_cast<std::uint8_t *>(uncompressedData); + + // We'll reconstruct the dictionary based on the bit stream codes. + LzwBitStreamReader bitStream(compressedPtr, compressedSizeBytes, compressedSizeBits); + LzwDictionary dictionary; + + // We check to avoid an overflow of the user buffer. + // If the buffer is smaller than the decompressed size, we + // break the loop and return the current decompression count. + while (bitStream.numBitsRead < bitStream.sizeInBits) + { + if (codeBitsWidth > LzwMaxDictBits) + { + break; + } + code = bitStream.readBits(codeBitsWidth); + + if (prevCode == LzwNil) + { + if (!lzwOutputByte(code, uncompressedPtr, uncompressedSizeBytes, bytesDecoded)) + { + break; + } + firstByte = code; + prevCode = code; + continue; + } + + if (code >= dictionary.size) + { + if (!lzwOutputSequence(dictionary, prevCode, uncompressedPtr, + uncompressedSizeBytes, bytesDecoded, firstByte)) + { + break; + } + if (!lzwOutputByte(firstByte, uncompressedPtr, uncompressedSizeBytes, bytesDecoded)) + { + break; + } + } + else + { + if (!lzwOutputSequence(dictionary, code, uncompressedPtr, + uncompressedSizeBytes, bytesDecoded, firstByte)) + { + break; + } + } + + if (!dictionary.add(prevCode, firstByte)) + { + break; + } + + if (dictionary.flush(codeBitsWidth)) + { + prevCode = LzwNil; + } + else + { + prevCode = code; + } + } + + return bytesDecoded; } // ======================================================== @@ -1784,39 +1778,39 @@ static inline const FontCharSet & getFontCharSet() { return s_fontMonoid1 static std::uint8_t * decompressFontBitmap() { - const std::uint32_t * compressedData = reinterpret_cast<const std::uint32_t *>(getRawFontBitmapData()); - - // First two uint32s are the compressed size in - // bytes followed by the compressed size in bits. - const int compressedSizeBytes = *compressedData++; - const int compressedSizeBits = *compressedData++; - - // Allocate the decompression buffer: - const int uncompressedSizeBytes = getFontCharSet().bitmapDecompressSize; - std::uint8_t * uncompressedData = static_cast<std::uint8_t *>(DD_MALLOC(uncompressedSizeBytes)); - - // Out of memory? Font rendering will be disable. - if (uncompressedData == nullptr) - { - return nullptr; - } - - // Decode the bitmap pixels (stored with an LZW-flavor of compression): - const int bytesDecoded = lzwDecompress(compressedData, - compressedSizeBytes, - compressedSizeBits, - uncompressedData, - uncompressedSizeBytes); - - // Unexpected decompression size? Probably a data mismatch in the font-tool. - if (bytesDecoded != uncompressedSizeBytes) - { - DD_MFREE(uncompressedData); - return nullptr; - } - - // Must later free with DD_MFREE(). - return uncompressedData; + const std::uint32_t * compressedData = reinterpret_cast<const std::uint32_t *>(getRawFontBitmapData()); + + // First two uint32s are the compressed size in + // bytes followed by the compressed size in bits. + const int compressedSizeBytes = *compressedData++; + const int compressedSizeBits = *compressedData++; + + // Allocate the decompression buffer: + const int uncompressedSizeBytes = getFontCharSet().bitmapDecompressSize; + std::uint8_t * uncompressedData = static_cast<std::uint8_t *>(DD_MALLOC(uncompressedSizeBytes)); + + // Out of memory? Font rendering will be disable. + if (uncompressedData == nullptr) + { + return nullptr; + } + + // Decode the bitmap pixels (stored with an LZW-flavor of compression): + const int bytesDecoded = lzwDecompress(compressedData, + compressedSizeBytes, + compressedSizeBits, + uncompressedData, + uncompressedSizeBytes); + + // Unexpected decompression size? Probably a data mismatch in the font-tool. + if (bytesDecoded != uncompressedSizeBytes) + { + DD_MFREE(uncompressedData); + return nullptr; + } + + // Must later free with DD_MFREE(). + return uncompressedData; } // ======================================================== @@ -1825,56 +1819,56 @@ static std::uint8_t * decompressFontBitmap() struct DebugString { - std::int64_t expiryDateMillis; - ddVec3 color; - float posX; - float posY; - float scaling; - ddStr text; - bool centered; + std::int64_t expiryDateMillis; + ddVec3 color; + float posX; + float posY; + float scaling; + ddStr text; + bool centered; }; struct DebugPoint { - std::int64_t expiryDateMillis; - ddVec3 position; - ddVec3 color; - float size; - bool depthEnabled; + std::int64_t expiryDateMillis; + ddVec3 position; + ddVec3 color; + float size; + bool depthEnabled; }; struct DebugLine { - std::int64_t expiryDateMillis; - ddVec3 posFrom; - ddVec3 posTo; - ddVec3 color; - bool depthEnabled; + std::int64_t expiryDateMillis; + ddVec3 posFrom; + ddVec3 posTo; + ddVec3 color; + bool depthEnabled; }; struct InternalContext DD_EXPLICIT_CONTEXT_ONLY(: public OpaqueContextType) { - int vertexBufferUsed; - int debugStringsCount; - int debugPointsCount; - int debugLinesCount; - std::int64_t currentTimeMillis; // Latest time value (in milliseconds) from dd::flush(). - GlyphTextureHandle glyphTexHandle; // Our built-in glyph bitmap. If kept null, no text is rendered. - RenderInterface * renderInterface; // Ref to the external renderer. Can be null for a no-op debug draw. - DrawVertex vertexBuffer[DEBUG_DRAW_VERTEX_BUFFER_SIZE]; // Vertex buffer we use to expand the lines/points before calling on RenderInterface. - DebugString debugStrings[DEBUG_DRAW_MAX_STRINGS]; // Debug strings queue (2D screen-space strings + 3D projected labels). - DebugPoint debugPoints[DEBUG_DRAW_MAX_POINTS]; // 3D debug points queue. - DebugLine debugLines[DEBUG_DRAW_MAX_LINES]; // 3D debug lines queue. - - InternalContext(RenderInterface * renderer) - : vertexBufferUsed(0) - , debugStringsCount(0) - , debugPointsCount(0) - , debugLinesCount(0) - , currentTimeMillis(0) - , glyphTexHandle(nullptr) - , renderInterface(renderer) - { } + int vertexBufferUsed; + int debugStringsCount; + int debugPointsCount; + int debugLinesCount; + std::int64_t currentTimeMillis; // Latest time value (in milliseconds) from dd::flush(). + GlyphTextureHandle glyphTexHandle; // Our built-in glyph bitmap. If kept null, no text is rendered. + RenderInterface * renderInterface; // Ref to the external renderer. Can be null for a no-op debug draw. + DrawVertex vertexBuffer[DEBUG_DRAW_VERTEX_BUFFER_SIZE]; // Vertex buffer we use to expand the lines/points before calling on RenderInterface. + DebugString debugStrings[DEBUG_DRAW_MAX_STRINGS]; // Debug strings queue (2D screen-space strings + 3D projected labels). + DebugPoint debugPoints[DEBUG_DRAW_MAX_POINTS]; // 3D debug points queue. + DebugLine debugLines[DEBUG_DRAW_MAX_LINES]; // 3D debug lines queue. + + InternalContext(RenderInterface * renderer) + : vertexBufferUsed(0) + , debugStringsCount(0) + , debugPointsCount(0) + , debugLinesCount(0) + , currentTimeMillis(0) + , glyphTexHandle(nullptr) + , renderInterface(renderer) + { } }; // ======================================================== @@ -1882,38 +1876,38 @@ struct InternalContext DD_EXPLICIT_CONTEXT_ONLY(: public OpaqueContextType) // ======================================================== #if (defined(DEBUG_DRAW_PER_THREAD_CONTEXT) && defined(DEBUG_DRAW_EXPLICIT_CONTEXT)) - #error "DEBUG_DRAW_PER_THREAD_CONTEXT and DEBUG_DRAW_EXPLICIT_CONTEXT are mutually exclusive!" + #error "DEBUG_DRAW_PER_THREAD_CONTEXT and DEBUG_DRAW_EXPLICIT_CONTEXT are mutually exclusive!" #endif // DEBUG_DRAW_PER_THREAD_CONTEXT && DEBUG_DRAW_EXPLICIT_CONTEXT #if defined(DEBUG_DRAW_EXPLICIT_CONTEXT) - // - // Explicit context passed as argument - // - #define DD_CONTEXT static_cast<InternalContext *>(ctx) + // + // Explicit context passed as argument + // + #define DD_CONTEXT static_cast<InternalContext *>(ctx) #elif defined(DEBUG_DRAW_PER_THREAD_CONTEXT) - // - // Per-thread global context (MT safe) - // - #if defined(__GNUC__) || defined(__clang__) // GCC/Clang - #define DD_THREAD_LOCAL static __thread - #elif defined(_MSC_VER) // Visual Studio - #define DD_THREAD_LOCAL static __declspec(thread) - #else // Try C++11 thread_local - #if DEBUG_DRAW_CXX11_SUPPORTED - #define DD_THREAD_LOCAL static thread_local - #else // !DEBUG_DRAW_CXX11_SUPPORTED - #error "Unsupported compiler - unknown TLS model" - #endif // DEBUG_DRAW_CXX11_SUPPORTED - #endif // TLS model - DD_THREAD_LOCAL InternalContext * s_threadContext = nullptr; - #define DD_CONTEXT s_threadContext - #undef DD_THREAD_LOCAL + // + // Per-thread global context (MT safe) + // + #if defined(__GNUC__) || defined(__clang__) // GCC/Clang + #define DD_THREAD_LOCAL static __thread + #elif defined(_MSC_VER) // Visual Studio + #define DD_THREAD_LOCAL static __declspec(thread) + #else // Try C++11 thread_local + #if DEBUG_DRAW_CXX11_SUPPORTED + #define DD_THREAD_LOCAL static thread_local + #else // !DEBUG_DRAW_CXX11_SUPPORTED + #error "Unsupported compiler - unknown TLS model" + #endif // DEBUG_DRAW_CXX11_SUPPORTED + #endif // TLS model + DD_THREAD_LOCAL InternalContext * s_threadContext = nullptr; + #define DD_CONTEXT s_threadContext + #undef DD_THREAD_LOCAL #else // Debug Draw context selection - // - // Global static context (single threaded operation) - // - static InternalContext * s_globalContext = nullptr; - #define DD_CONTEXT s_globalContext + // + // Global static context (single threaded operation) + // + static InternalContext * s_globalContext = nullptr; + #define DD_CONTEXT s_globalContext #endif // Debug Draw context selection // ======================================================== @@ -1933,112 +1927,112 @@ static inline float floatInvSqrt(float x) { return (1.0f / sqrtf(x)); } union Float2UInt { - float asFloat; - std::uint32_t asUInt; + float asFloat; + std::uint32_t asUInt; }; static inline float floatRound(float x) { - // Probably slower than std::floor(), also depends of FPU settings, - // but we only need this for that special sin/cos() case anyways... - const int i = static_cast<int>(x); - return (x >= 0.0f) ? static_cast<float>(i) : static_cast<float>(i - 1); + // Probably slower than std::floor(), also depends of FPU settings, + // but we only need this for that special sin/cos() case anyways... + const int i = static_cast<int>(x); + return (x >= 0.0f) ? static_cast<float>(i) : static_cast<float>(i - 1); } static inline float floatAbs(float x) { - // Mask-off the sign bit - Float2UInt i; - i.asFloat = x; - i.asUInt &= 0x7FFFFFFF; - return i.asFloat; + // Mask-off the sign bit + Float2UInt i; + i.asFloat = x; + i.asUInt &= 0x7FFFFFFF; + return i.asFloat; } static inline float floatInvSqrt(float x) { - // Modified version of the emblematic Q_rsqrt() from Quake 3. - // See: http://en.wikipedia.org/wiki/Fast_inverse_square_root - Float2UInt i; - float y, r; - y = x * 0.5f; - i.asFloat = x; - i.asUInt = 0x5F3759DF - (i.asUInt >> 1); - r = i.asFloat; - r = r * (1.5f - (r * r * y)); - return r; + // Modified version of the emblematic Q_rsqrt() from Quake 3. + // See: http://en.wikipedia.org/wiki/Fast_inverse_square_root + Float2UInt i; + float y, r; + y = x * 0.5f; + i.asFloat = x; + i.asUInt = 0x5F3759DF - (i.asUInt >> 1); + r = i.asFloat; + r = r * (1.5f - (r * r * y)); + return r; } static inline float floatSin(float radians) { - static const float A = -2.39e-08; - static const float B = 2.7526e-06; - static const float C = 1.98409e-04; - static const float D = 8.3333315e-03; - static const float E = 1.666666664e-01; - - if (radians < 0.0f || radians >= TAU) - { - radians -= floatRound(radians / TAU) * TAU; - } - - if (radians < PI) - { - if (radians > HalfPI) - { - radians = PI - radians; - } - } - else - { - radians = (radians > (PI + HalfPI)) ? (radians - TAU) : (PI - radians); - } - - const float s = radians * radians; - return radians * (((((A * s + B) * s - C) * s + D) * s - E) * s + 1.0f); + static const float A = -2.39e-08; + static const float B = 2.7526e-06; + static const float C = 1.98409e-04; + static const float D = 8.3333315e-03; + static const float E = 1.666666664e-01; + + if (radians < 0.0f || radians >= TAU) + { + radians -= floatRound(radians / TAU) * TAU; + } + + if (radians < PI) + { + if (radians > HalfPI) + { + radians = PI - radians; + } + } + else + { + radians = (radians > (PI + HalfPI)) ? (radians - TAU) : (PI - radians); + } + + const float s = radians * radians; + return radians * (((((A * s + B) * s - C) * s + D) * s - E) * s + 1.0f); } static inline float floatCos(float radians) { - static const float A = -2.605e-07; - static const float B = 2.47609e-05; - static const float C = 1.3888397e-03; - static const float D = 4.16666418e-02; - static const float E = 4.999999963e-01; - - if (radians < 0.0f || radians >= TAU) - { - radians -= floatRound(radians / TAU) * TAU; - } - - float d; - if (radians < PI) - { - if (radians > HalfPI) - { - radians = PI - radians; - d = -1.0f; - } - else - { - d = 1.0f; - } - } - else - { - if (radians > (PI + HalfPI)) - { - radians = radians - TAU; - d = 1.0f; - } - else - { - radians = PI - radians; - d = -1.0f; - } - } - - const float s = radians * radians; - return d * (((((A * s + B) * s - C) * s + D) * s - E) * s + 1.0f); + static const float A = -2.605e-07; + static const float B = 2.47609e-05; + static const float C = 1.3888397e-03; + static const float D = 4.16666418e-02; + static const float E = 4.999999963e-01; + + if (radians < 0.0f || radians >= TAU) + { + radians -= floatRound(radians / TAU) * TAU; + } + + float d; + if (radians < PI) + { + if (radians > HalfPI) + { + radians = PI - radians; + d = -1.0f; + } + else + { + d = 1.0f; + } + } + else + { + if (radians > (PI + HalfPI)) + { + radians = radians - TAU; + d = 1.0f; + } + else + { + radians = PI - radians; + d = -1.0f; + } + } + + const float s = radians * radians; + return d * (((((A * s + B) * s - C) * s + D) * s - E) * s + 1.0f); } #endif // DEBUG_DRAW_USE_STD_MATH @@ -2051,74 +2045,74 @@ enum VecElements { X, Y, Z, W }; static inline void vecSet(ddVec3_Out dest, const float x, const float y, const float z) { - dest[X] = x; - dest[Y] = y; - dest[Z] = z; + dest[X] = x; + dest[Y] = y; + dest[Z] = z; } static inline void vecCopy(ddVec3_Out dest, ddVec3_In src) { - dest[X] = src[X]; - dest[Y] = src[Y]; - dest[Z] = src[Z]; + dest[X] = src[X]; + dest[Y] = src[Y]; + dest[Z] = src[Z]; } static inline void vecAdd(ddVec3_Out result, ddVec3_In a, ddVec3_In b) { - result[X] = a[X] + b[X]; - result[Y] = a[Y] + b[Y]; - result[Z] = a[Z] + b[Z]; + result[X] = a[X] + b[X]; + result[Y] = a[Y] + b[Y]; + result[Z] = a[Z] + b[Z]; } static inline void vecSub(ddVec3_Out result, ddVec3_In a, ddVec3_In b) { - result[X] = a[X] - b[X]; - result[Y] = a[Y] - b[Y]; - result[Z] = a[Z] - b[Z]; + result[X] = a[X] - b[X]; + result[Y] = a[Y] - b[Y]; + result[Z] = a[Z] - b[Z]; } static inline void vecScale(ddVec3_Out result, ddVec3_In v, const float s) { - result[X] = v[X] * s; - result[Y] = v[Y] * s; - result[Z] = v[Z] * s; + result[X] = v[X] * s; + result[Y] = v[Y] * s; + result[Z] = v[Z] * s; } static inline void vecNormalize(ddVec3_Out result, ddVec3_In v) { - const float lenSqr = v[X] * v[X] + v[Y] * v[Y] + v[Z] * v[Z]; - const float invLen = floatInvSqrt(lenSqr); - result[X] = v[X] * invLen; - result[Y] = v[Y] * invLen; - result[Z] = v[Z] * invLen; + const float lenSqr = v[X] * v[X] + v[Y] * v[Y] + v[Z] * v[Z]; + const float invLen = floatInvSqrt(lenSqr); + result[X] = v[X] * invLen; + result[Y] = v[Y] * invLen; + result[Z] = v[Z] * invLen; } static inline void vecOrthogonalBasis(ddVec3_Out left, ddVec3_Out up, ddVec3_In v) { - // Produces two orthogonal vectors for normalized vector v. - float lenSqr, invLen; - if (floatAbs(v[Z]) > 0.7f) - { - lenSqr = v[Y] * v[Y] + v[Z] * v[Z]; - invLen = floatInvSqrt(lenSqr); - up[X] = 0.0f; - up[Y] = v[Z] * invLen; - up[Z] = -v[Y] * invLen; - left[X] = lenSqr * invLen; - left[Y] = -v[X] * up[Z]; - left[Z] = v[X] * up[Y]; - } - else - { - lenSqr = v[X] * v[X] + v[Y] * v[Y]; - invLen = floatInvSqrt(lenSqr); - left[X] = -v[Y] * invLen; - left[Y] = v[X] * invLen; - left[Z] = 0.0f; - up[X] = -v[Z] * left[Y]; - up[Y] = v[Z] * left[X]; - up[Z] = lenSqr * invLen; - } + // Produces two orthogonal vectors for normalized vector v. + float lenSqr, invLen; + if (floatAbs(v[Z]) > 0.7f) + { + lenSqr = v[Y] * v[Y] + v[Z] * v[Z]; + invLen = floatInvSqrt(lenSqr); + up[X] = 0.0f; + up[Y] = v[Z] * invLen; + up[Z] = -v[Y] * invLen; + left[X] = lenSqr * invLen; + left[Y] = -v[X] * up[Z]; + left[Z] = v[X] * up[Y]; + } + else + { + lenSqr = v[X] * v[X] + v[Y] * v[Y]; + invLen = floatInvSqrt(lenSqr); + left[X] = -v[Y] * invLen; + left[Y] = v[X] * invLen; + left[Z] = 0.0f; + up[X] = -v[Z] * left[Y]; + up[Y] = v[Z] * left[X]; + up[Z] = lenSqr * invLen; + } } // ======================================================== @@ -2127,26 +2121,26 @@ static inline void vecOrthogonalBasis(ddVec3_Out left, ddVec3_Out up, ddVec3_In static inline void matTransformPointXYZ(ddVec3_Out result, ddVec3_In p, ddMat4x4_In m) { - result[X] = (m[0] * p[X]) + (m[4] * p[Y]) + (m[8] * p[Z]) + m[12]; // p[W] assumed to be 1 - result[Y] = (m[1] * p[X]) + (m[5] * p[Y]) + (m[9] * p[Z]) + m[13]; - result[Z] = (m[2] * p[X]) + (m[6] * p[Y]) + (m[10] * p[Z]) + m[14]; + result[X] = (m[0] * p[X]) + (m[4] * p[Y]) + (m[8] * p[Z]) + m[12]; // p[W] assumed to be 1 + result[Y] = (m[1] * p[X]) + (m[5] * p[Y]) + (m[9] * p[Z]) + m[13]; + result[Z] = (m[2] * p[X]) + (m[6] * p[Y]) + (m[10] * p[Z]) + m[14]; } static inline void matTransformPointXYZW(float result[4], ddVec3_In p, ddMat4x4_In m) { - result[X] = (m[0] * p[X]) + (m[4] * p[Y]) + (m[8] * p[Z]) + m[12]; // p[W] assumed to be 1 - result[Y] = (m[1] * p[X]) + (m[5] * p[Y]) + (m[9] * p[Z]) + m[13]; - result[Z] = (m[2] * p[X]) + (m[6] * p[Y]) + (m[10] * p[Z]) + m[14]; - result[W] = (m[3] * p[X]) + (m[7] * p[Y]) + (m[11] * p[Z]) + m[15]; + result[X] = (m[0] * p[X]) + (m[4] * p[Y]) + (m[8] * p[Z]) + m[12]; // p[W] assumed to be 1 + result[Y] = (m[1] * p[X]) + (m[5] * p[Y]) + (m[9] * p[Z]) + m[13]; + result[Z] = (m[2] * p[X]) + (m[6] * p[Y]) + (m[10] * p[Z]) + m[14]; + result[W] = (m[3] * p[X]) + (m[7] * p[Y]) + (m[11] * p[Z]) + m[15]; } static inline float matTransformPointXYZW2(ddVec3_Out result, const float p[3], ddMat4x4_In m) { - result[X] = (m[0] * p[X]) + (m[4] * p[Y]) + (m[8] * p[Z]) + m[12]; // p[W] assumed to be 1 - result[Y] = (m[1] * p[X]) + (m[5] * p[Y]) + (m[9] * p[Z]) + m[13]; - result[Z] = (m[2] * p[X]) + (m[6] * p[Y]) + (m[10] * p[Z]) + m[14]; - float rw = (m[3] * p[X]) + (m[7] * p[Y]) + (m[11] * p[Z]) + m[15]; - return rw; + result[X] = (m[0] * p[X]) + (m[4] * p[Y]) + (m[8] * p[Z]) + m[12]; // p[W] assumed to be 1 + result[Y] = (m[1] * p[X]) + (m[5] * p[Y]) + (m[9] * p[Z]) + m[13]; + result[Z] = (m[2] * p[X]) + (m[6] * p[Y]) + (m[10] * p[Z]) + m[14]; + float rw = (m[3] * p[X]) + (m[7] * p[Y]) + (m[11] * p[Z]) + m[15]; + return rw; } // ======================================================== @@ -2155,369 +2149,369 @@ static inline float matTransformPointXYZW2(ddVec3_Out result, const float p[3], enum DrawMode { - DrawModePoints, - DrawModeLines, - DrawModeText + DrawModePoints, + DrawModeLines, + DrawModeText }; static void flushDebugVerts(DD_EXPLICIT_CONTEXT_ONLY(ContextHandle ctx,) const DrawMode mode, const bool depthEnabled) { - if (DD_CONTEXT->vertexBufferUsed == 0) - { - return; - } - - switch (mode) - { - case DrawModePoints : - DD_CONTEXT->renderInterface->drawPointList(DD_CONTEXT->vertexBuffer, - DD_CONTEXT->vertexBufferUsed, - depthEnabled); - break; - case DrawModeLines : - DD_CONTEXT->renderInterface->drawLineList(DD_CONTEXT->vertexBuffer, - DD_CONTEXT->vertexBufferUsed, - depthEnabled); - break; - case DrawModeText : - DD_CONTEXT->renderInterface->drawGlyphList(DD_CONTEXT->vertexBuffer, - DD_CONTEXT->vertexBufferUsed, - DD_CONTEXT->glyphTexHandle); - break; - } // switch (mode) - - DD_CONTEXT->vertexBufferUsed = 0; + if (DD_CONTEXT->vertexBufferUsed == 0) + { + return; + } + + switch (mode) + { + case DrawModePoints : + DD_CONTEXT->renderInterface->drawPointList(DD_CONTEXT->vertexBuffer, + DD_CONTEXT->vertexBufferUsed, + depthEnabled); + break; + case DrawModeLines : + DD_CONTEXT->renderInterface->drawLineList(DD_CONTEXT->vertexBuffer, + DD_CONTEXT->vertexBufferUsed, + depthEnabled); + break; + case DrawModeText : + DD_CONTEXT->renderInterface->drawGlyphList(DD_CONTEXT->vertexBuffer, + DD_CONTEXT->vertexBufferUsed, + DD_CONTEXT->glyphTexHandle); + break; + } // switch (mode) + + DD_CONTEXT->vertexBufferUsed = 0; } static void pushPointVert(DD_EXPLICIT_CONTEXT_ONLY(ContextHandle ctx,) const DebugPoint & point) { - // Make room for one more vert: - if ((DD_CONTEXT->vertexBufferUsed + 1) >= DEBUG_DRAW_VERTEX_BUFFER_SIZE) - { - flushDebugVerts(DD_EXPLICIT_CONTEXT_ONLY(ctx,) DrawModePoints, point.depthEnabled); - } - - DrawVertex & v = DD_CONTEXT->vertexBuffer[DD_CONTEXT->vertexBufferUsed++]; - v.point.x = point.position[X]; - v.point.y = point.position[Y]; - v.point.z = point.position[Z]; - v.point.r = point.color[X]; - v.point.g = point.color[Y]; - v.point.b = point.color[Z]; - v.point.size = point.size; + // Make room for one more vert: + if ((DD_CONTEXT->vertexBufferUsed + 1) >= DEBUG_DRAW_VERTEX_BUFFER_SIZE) + { + flushDebugVerts(DD_EXPLICIT_CONTEXT_ONLY(ctx,) DrawModePoints, point.depthEnabled); + } + + DrawVertex & v = DD_CONTEXT->vertexBuffer[DD_CONTEXT->vertexBufferUsed++]; + v.point.x = point.position[X]; + v.point.y = point.position[Y]; + v.point.z = point.position[Z]; + v.point.r = point.color[X]; + v.point.g = point.color[Y]; + v.point.b = point.color[Z]; + v.point.size = point.size; } static void pushLineVert(DD_EXPLICIT_CONTEXT_ONLY(ContextHandle ctx,) const DebugLine & line) { - // Make room for two more verts: - if ((DD_CONTEXT->vertexBufferUsed + 2) >= DEBUG_DRAW_VERTEX_BUFFER_SIZE) - { - flushDebugVerts(DD_EXPLICIT_CONTEXT_ONLY(ctx,) DrawModeLines, line.depthEnabled); - } - - DrawVertex & v0 = DD_CONTEXT->vertexBuffer[DD_CONTEXT->vertexBufferUsed++]; - DrawVertex & v1 = DD_CONTEXT->vertexBuffer[DD_CONTEXT->vertexBufferUsed++]; - - v0.line.x = line.posFrom[X]; - v0.line.y = line.posFrom[Y]; - v0.line.z = line.posFrom[Z]; - v0.line.r = line.color[X]; - v0.line.g = line.color[Y]; - v0.line.b = line.color[Z]; - - v1.line.x = line.posTo[X]; - v1.line.y = line.posTo[Y]; - v1.line.z = line.posTo[Z]; - v1.line.r = line.color[X]; - v1.line.g = line.color[Y]; - v1.line.b = line.color[Z]; + // Make room for two more verts: + if ((DD_CONTEXT->vertexBufferUsed + 2) >= DEBUG_DRAW_VERTEX_BUFFER_SIZE) + { + flushDebugVerts(DD_EXPLICIT_CONTEXT_ONLY(ctx,) DrawModeLines, line.depthEnabled); + } + + DrawVertex & v0 = DD_CONTEXT->vertexBuffer[DD_CONTEXT->vertexBufferUsed++]; + DrawVertex & v1 = DD_CONTEXT->vertexBuffer[DD_CONTEXT->vertexBufferUsed++]; + + v0.line.x = line.posFrom[X]; + v0.line.y = line.posFrom[Y]; + v0.line.z = line.posFrom[Z]; + v0.line.r = line.color[X]; + v0.line.g = line.color[Y]; + v0.line.b = line.color[Z]; + + v1.line.x = line.posTo[X]; + v1.line.y = line.posTo[Y]; + v1.line.z = line.posTo[Z]; + v1.line.r = line.color[X]; + v1.line.g = line.color[Y]; + v1.line.b = line.color[Z]; } static void pushGlyphVerts(DD_EXPLICIT_CONTEXT_ONLY(ContextHandle ctx,) const DrawVertex verts[4]) { - static const int indexes[6] = { 0, 1, 2, 2, 1, 3 }; + static const int indexes[6] = { 0, 1, 2, 2, 1, 3 }; - // Make room for one more glyph (2 tris): - if ((DD_CONTEXT->vertexBufferUsed + 6) >= DEBUG_DRAW_VERTEX_BUFFER_SIZE) - { - flushDebugVerts(DD_EXPLICIT_CONTEXT_ONLY(ctx,) DrawModeText, false); - } + // Make room for one more glyph (2 tris): + if ((DD_CONTEXT->vertexBufferUsed + 6) >= DEBUG_DRAW_VERTEX_BUFFER_SIZE) + { + flushDebugVerts(DD_EXPLICIT_CONTEXT_ONLY(ctx,) DrawModeText, false); + } - for (int i = 0; i < 6; ++i) - { - DD_CONTEXT->vertexBuffer[DD_CONTEXT->vertexBufferUsed++].glyph = verts[indexes[i]].glyph; - } + for (int i = 0; i < 6; ++i) + { + DD_CONTEXT->vertexBuffer[DD_CONTEXT->vertexBufferUsed++].glyph = verts[indexes[i]].glyph; + } } static void pushStringGlyphs(DD_EXPLICIT_CONTEXT_ONLY(ContextHandle ctx,) float x, float y, - const char * text, ddVec3_In color, const float scaling) -{ - // Invariants for all characters: - const float initialX = x; - const float scaleU = static_cast<float>(getFontCharSet().bitmapWidth); - const float scaleV = static_cast<float>(getFontCharSet().bitmapHeight); - const float fixedWidth = static_cast<float>(getFontCharSet().charWidth); - const float fixedHeight = static_cast<float>(getFontCharSet().charHeight); - const float tabW = fixedWidth * 4.0f * scaling; // TAB = 4 spaces. - const float chrW = fixedWidth * scaling; - const float chrH = fixedHeight * scaling; - - for (; *text != '\0'; ++text) - { - const int charVal = *text; - if (charVal >= FontCharSet::MaxChars) - { - continue; - } - if (charVal == ' ') - { - x += chrW; - continue; - } - if (charVal == '\t') - { - x += tabW; - continue; - } - if (charVal == '\n') - { - y += chrH; - x = initialX; - continue; - } - - const FontChar fontChar = getFontCharSet().chars[charVal]; - const float u0 = (fontChar.x + 0.5f) / scaleU; - const float v0 = (fontChar.y + 0.5f) / scaleV; - const float u1 = u0 + (fixedWidth / scaleU); - const float v1 = v0 + (fixedHeight / scaleV); - - DrawVertex verts[4]; - verts[0].glyph.x = x; - verts[0].glyph.y = y; - verts[0].glyph.u = u0; - verts[0].glyph.v = v0; - verts[0].glyph.r = color[X]; - verts[0].glyph.g = color[Y]; - verts[0].glyph.b = color[Z]; - verts[1].glyph.x = x; - verts[1].glyph.y = y + chrH; - verts[1].glyph.u = u0; - verts[1].glyph.v = v1; - verts[1].glyph.r = color[X]; - verts[1].glyph.g = color[Y]; - verts[1].glyph.b = color[Z]; - verts[2].glyph.x = x + chrW; - verts[2].glyph.y = y; - verts[2].glyph.u = u1; - verts[2].glyph.v = v0; - verts[2].glyph.r = color[X]; - verts[2].glyph.g = color[Y]; - verts[2].glyph.b = color[Z]; - verts[3].glyph.x = x + chrW; - verts[3].glyph.y = y + chrH; - verts[3].glyph.u = u1; - verts[3].glyph.v = v1; - verts[3].glyph.r = color[X]; - verts[3].glyph.g = color[Y]; - verts[3].glyph.b = color[Z]; - - pushGlyphVerts(DD_EXPLICIT_CONTEXT_ONLY(ctx,) verts); - x += chrW; - } + const char * text, ddVec3_In color, const float scaling) +{ + // Invariants for all characters: + const float initialX = x; + const float scaleU = static_cast<float>(getFontCharSet().bitmapWidth); + const float scaleV = static_cast<float>(getFontCharSet().bitmapHeight); + const float fixedWidth = static_cast<float>(getFontCharSet().charWidth); + const float fixedHeight = static_cast<float>(getFontCharSet().charHeight); + const float tabW = fixedWidth * 4.0f * scaling; // TAB = 4 spaces. + const float chrW = fixedWidth * scaling; + const float chrH = fixedHeight * scaling; + + for (; *text != '\0'; ++text) + { + const int charVal = *text; + if (charVal >= FontCharSet::MaxChars) + { + continue; + } + if (charVal == ' ') + { + x += chrW; + continue; + } + if (charVal == '\t') + { + x += tabW; + continue; + } + if (charVal == '\n') + { + y += chrH; + x = initialX; + continue; + } + + const FontChar fontChar = getFontCharSet().chars[charVal]; + const float u0 = (fontChar.x + 0.5f) / scaleU; + const float v0 = (fontChar.y + 0.5f) / scaleV; + const float u1 = u0 + (fixedWidth / scaleU); + const float v1 = v0 + (fixedHeight / scaleV); + + DrawVertex verts[4]; + verts[0].glyph.x = x; + verts[0].glyph.y = y; + verts[0].glyph.u = u0; + verts[0].glyph.v = v0; + verts[0].glyph.r = color[X]; + verts[0].glyph.g = color[Y]; + verts[0].glyph.b = color[Z]; + verts[1].glyph.x = x; + verts[1].glyph.y = y + chrH; + verts[1].glyph.u = u0; + verts[1].glyph.v = v1; + verts[1].glyph.r = color[X]; + verts[1].glyph.g = color[Y]; + verts[1].glyph.b = color[Z]; + verts[2].glyph.x = x + chrW; + verts[2].glyph.y = y; + verts[2].glyph.u = u1; + verts[2].glyph.v = v0; + verts[2].glyph.r = color[X]; + verts[2].glyph.g = color[Y]; + verts[2].glyph.b = color[Z]; + verts[3].glyph.x = x + chrW; + verts[3].glyph.y = y + chrH; + verts[3].glyph.u = u1; + verts[3].glyph.v = v1; + verts[3].glyph.r = color[X]; + verts[3].glyph.g = color[Y]; + verts[3].glyph.b = color[Z]; + + pushGlyphVerts(DD_EXPLICIT_CONTEXT_ONLY(ctx,) verts); + x += chrW; + } } static float calcTextWidth(const char * text, const float scaling) { - const float fixedWidth = static_cast<float>(getFontCharSet().charWidth); - const float tabW = fixedWidth * 4.0f * scaling; // TAB = 4 spaces. - const float chrW = fixedWidth * scaling; - - float x = 0.0f; - for (; *text != '\0'; ++text) - { - // Tabs are handled differently (4 spaces) - if (*text == '\t') - { - x += tabW; - } - else // Non-tab char (including whitespace) - { - x += chrW; - } - } - - return x; + const float fixedWidth = static_cast<float>(getFontCharSet().charWidth); + const float tabW = fixedWidth * 4.0f * scaling; // TAB = 4 spaces. + const float chrW = fixedWidth * scaling; + + float x = 0.0f; + for (; *text != '\0'; ++text) + { + // Tabs are handled differently (4 spaces) + if (*text == '\t') + { + x += tabW; + } + else // Non-tab char (including whitespace) + { + x += chrW; + } + } + + return x; } static void drawDebugStrings(DD_EXPLICIT_CONTEXT_ONLY(ContextHandle ctx)) { - const int count = DD_CONTEXT->debugStringsCount; - if (count == 0) - { - return; - } - - const DebugString * const debugStrings = DD_CONTEXT->debugStrings; - - for (int i = 0; i < count; ++i) - { - const DebugString & dstr = debugStrings[i]; - if (dstr.centered) - { - // 3D Labels are centered at the point of origin, e.g. center-aligned. - const float offset = calcTextWidth(dstr.text.c_str(), dstr.scaling) * 0.5f; - pushStringGlyphs(DD_EXPLICIT_CONTEXT_ONLY(ctx,) dstr.posX - offset, dstr.posY, dstr.text.c_str(), dstr.color, dstr.scaling); - } - else - { - // Left-aligned - pushStringGlyphs(DD_EXPLICIT_CONTEXT_ONLY(ctx,) dstr.posX, dstr.posY, dstr.text.c_str(), dstr.color, dstr.scaling); - } - } - - flushDebugVerts(DD_EXPLICIT_CONTEXT_ONLY(ctx,) DrawModeText, false); + const int count = DD_CONTEXT->debugStringsCount; + if (count == 0) + { + return; + } + + const DebugString * const debugStrings = DD_CONTEXT->debugStrings; + + for (int i = 0; i < count; ++i) + { + const DebugString & dstr = debugStrings[i]; + if (dstr.centered) + { + // 3D Labels are centered at the point of origin, e.g. center-aligned. + const float offset = calcTextWidth(dstr.text.c_str(), dstr.scaling) * 0.5f; + pushStringGlyphs(DD_EXPLICIT_CONTEXT_ONLY(ctx,) dstr.posX - offset, dstr.posY, dstr.text.c_str(), dstr.color, dstr.scaling); + } + else + { + // Left-aligned + pushStringGlyphs(DD_EXPLICIT_CONTEXT_ONLY(ctx,) dstr.posX, dstr.posY, dstr.text.c_str(), dstr.color, dstr.scaling); + } + } + + flushDebugVerts(DD_EXPLICIT_CONTEXT_ONLY(ctx,) DrawModeText, false); } static void drawDebugPoints(DD_EXPLICIT_CONTEXT_ONLY(ContextHandle ctx)) { - const int count = DD_CONTEXT->debugPointsCount; - if (count == 0) - { - return; - } - - const DebugPoint * const debugPoints = DD_CONTEXT->debugPoints; - - // - // First pass, points with depth test ENABLED: - // - int numDepthlessPoints = 0; - for (int i = 0; i < count; ++i) - { - const DebugPoint & point = debugPoints[i]; - if (point.depthEnabled) - { - pushPointVert(DD_EXPLICIT_CONTEXT_ONLY(ctx,) point); - } - numDepthlessPoints += !point.depthEnabled; - } - flushDebugVerts(DD_EXPLICIT_CONTEXT_ONLY(ctx,) DrawModePoints, true); - - // - // Second pass draws points with depth DISABLED: - // - if (numDepthlessPoints > 0) - { - for (int i = 0; i < count; ++i) - { - const DebugPoint & point = debugPoints[i]; - if (!point.depthEnabled) - { - pushPointVert(DD_EXPLICIT_CONTEXT_ONLY(ctx,) point); - } - } - flushDebugVerts(DD_EXPLICIT_CONTEXT_ONLY(ctx,) DrawModePoints, false); - } + const int count = DD_CONTEXT->debugPointsCount; + if (count == 0) + { + return; + } + + const DebugPoint * const debugPoints = DD_CONTEXT->debugPoints; + + // + // First pass, points with depth test ENABLED: + // + int numDepthlessPoints = 0; + for (int i = 0; i < count; ++i) + { + const DebugPoint & point = debugPoints[i]; + if (point.depthEnabled) + { + pushPointVert(DD_EXPLICIT_CONTEXT_ONLY(ctx,) point); + } + numDepthlessPoints += !point.depthEnabled; + } + flushDebugVerts(DD_EXPLICIT_CONTEXT_ONLY(ctx,) DrawModePoints, true); + + // + // Second pass draws points with depth DISABLED: + // + if (numDepthlessPoints > 0) + { + for (int i = 0; i < count; ++i) + { + const DebugPoint & point = debugPoints[i]; + if (!point.depthEnabled) + { + pushPointVert(DD_EXPLICIT_CONTEXT_ONLY(ctx,) point); + } + } + flushDebugVerts(DD_EXPLICIT_CONTEXT_ONLY(ctx,) DrawModePoints, false); + } } static void drawDebugLines(DD_EXPLICIT_CONTEXT_ONLY(ContextHandle ctx)) { - const int count = DD_CONTEXT->debugLinesCount; - if (count == 0) - { - return; - } - - const DebugLine * const debugLines = DD_CONTEXT->debugLines; - - // - // First pass, lines with depth test ENABLED: - // - int numDepthlessLines = 0; - for (int i = 0; i < count; ++i) - { - const DebugLine & line = debugLines[i]; - if (line.depthEnabled) - { - pushLineVert(DD_EXPLICIT_CONTEXT_ONLY(ctx,) line); - } - numDepthlessLines += !line.depthEnabled; - } - flushDebugVerts(DD_EXPLICIT_CONTEXT_ONLY(ctx,) DrawModeLines, true); - - // - // Second pass draws lines with depth DISABLED: - // - if (numDepthlessLines > 0) - { - for (int i = 0; i < count; ++i) - { - const DebugLine & line = debugLines[i]; - if (!line.depthEnabled) - { - pushLineVert(DD_EXPLICIT_CONTEXT_ONLY(ctx,) line); - } - } - flushDebugVerts(DD_EXPLICIT_CONTEXT_ONLY(ctx,) DrawModeLines, false); - } + const int count = DD_CONTEXT->debugLinesCount; + if (count == 0) + { + return; + } + + const DebugLine * const debugLines = DD_CONTEXT->debugLines; + + // + // First pass, lines with depth test ENABLED: + // + int numDepthlessLines = 0; + for (int i = 0; i < count; ++i) + { + const DebugLine & line = debugLines[i]; + if (line.depthEnabled) + { + pushLineVert(DD_EXPLICIT_CONTEXT_ONLY(ctx,) line); + } + numDepthlessLines += !line.depthEnabled; + } + flushDebugVerts(DD_EXPLICIT_CONTEXT_ONLY(ctx,) DrawModeLines, true); + + // + // Second pass draws lines with depth DISABLED: + // + if (numDepthlessLines > 0) + { + for (int i = 0; i < count; ++i) + { + const DebugLine & line = debugLines[i]; + if (!line.depthEnabled) + { + pushLineVert(DD_EXPLICIT_CONTEXT_ONLY(ctx,) line); + } + } + flushDebugVerts(DD_EXPLICIT_CONTEXT_ONLY(ctx,) DrawModeLines, false); + } } template<typename T> static void clearDebugQueue(DD_EXPLICIT_CONTEXT_ONLY(ContextHandle ctx,) T * queue, int & queueCount) { - const std::int64_t time = DD_CONTEXT->currentTimeMillis; - if (time == 0) - { - queueCount = 0; - return; - } - - int index = 0; - T * pElem = queue; - - // Concatenate elements that still need to be draw on future frames: - for (int i = 0; i < queueCount; ++i, ++pElem) - { - if (pElem->expiryDateMillis > time) - { - if (index != i) - { - queue[index] = *pElem; - } - ++index; - } - } - - queueCount = index; + const std::int64_t time = DD_CONTEXT->currentTimeMillis; + if (time == 0) + { + queueCount = 0; + return; + } + + int index = 0; + T * pElem = queue; + + // Concatenate elements that still need to be draw on future frames: + for (int i = 0; i < queueCount; ++i, ++pElem) + { + if (pElem->expiryDateMillis > time) + { + if (index != i) + { + queue[index] = *pElem; + } + ++index; + } + } + + queueCount = index; } static void setupGlyphTexture(DD_EXPLICIT_CONTEXT_ONLY(ContextHandle ctx)) { - if (DD_CONTEXT->renderInterface == nullptr) - { - return; - } - - if (DD_CONTEXT->glyphTexHandle != nullptr) - { - DD_CONTEXT->renderInterface->destroyGlyphTexture(DD_CONTEXT->glyphTexHandle); - DD_CONTEXT->glyphTexHandle = nullptr; - } - - std::uint8_t * decompressedBitmap = decompressFontBitmap(); - if (decompressedBitmap == nullptr) - { - return; // Failed to decompressed. No font rendering available. - } - - DD_CONTEXT->glyphTexHandle = DD_CONTEXT->renderInterface->createGlyphTexture( - getFontCharSet().bitmapWidth, - getFontCharSet().bitmapHeight, - decompressedBitmap); - - // No longer needed. - DD_MFREE(decompressedBitmap); + if (DD_CONTEXT->renderInterface == nullptr) + { + return; + } + + if (DD_CONTEXT->glyphTexHandle != nullptr) + { + DD_CONTEXT->renderInterface->destroyGlyphTexture(DD_CONTEXT->glyphTexHandle); + DD_CONTEXT->glyphTexHandle = nullptr; + } + + std::uint8_t * decompressedBitmap = decompressFontBitmap(); + if (decompressedBitmap == nullptr) + { + return; // Failed to decompressed. No font rendering available. + } + + DD_CONTEXT->glyphTexHandle = DD_CONTEXT->renderInterface->createGlyphTexture( + getFontCharSet().bitmapWidth, + getFontCharSet().bitmapHeight, + decompressedBitmap); + + // No longer needed. + DD_MFREE(decompressedBitmap); } // ======================================================== @@ -2526,766 +2520,766 @@ static void setupGlyphTexture(DD_EXPLICIT_CONTEXT_ONLY(ContextHandle ctx)) bool initialize(DD_EXPLICIT_CONTEXT_ONLY(ContextHandle * outCtx,) RenderInterface * renderer) { - if (renderer == nullptr) - { - return false; - } - - void * buffer = DD_MALLOC(sizeof(InternalContext)); - if (buffer == nullptr) - { - return false; - } - - InternalContext * newCtx = ::new(buffer) InternalContext(renderer); - - #ifdef DEBUG_DRAW_EXPLICIT_CONTEXT - if ((*outCtx) != nullptr) { shutdown(*outCtx); } - (*outCtx) = newCtx; - #else // !DEBUG_DRAW_EXPLICIT_CONTEXT - if (DD_CONTEXT != nullptr) { shutdown(); } - DD_CONTEXT = newCtx; - #endif // DEBUG_DRAW_EXPLICIT_CONTEXT - - setupGlyphTexture(DD_EXPLICIT_CONTEXT_ONLY(*outCtx)); - return true; + if (renderer == nullptr) + { + return false; + } + + void * buffer = DD_MALLOC(sizeof(InternalContext)); + if (buffer == nullptr) + { + return false; + } + + InternalContext * newCtx = ::new(buffer) InternalContext(renderer); + +#ifdef DEBUG_DRAW_EXPLICIT_CONTEXT + if ((*outCtx) != nullptr) { shutdown(*outCtx); } + (*outCtx) = newCtx; +#else // !DEBUG_DRAW_EXPLICIT_CONTEXT + if (DD_CONTEXT != nullptr) { shutdown(); } + DD_CONTEXT = newCtx; +#endif // DEBUG_DRAW_EXPLICIT_CONTEXT + + setupGlyphTexture(DD_EXPLICIT_CONTEXT_ONLY(*outCtx)); + return true; } void shutdown(DD_EXPLICIT_CONTEXT_ONLY(ContextHandle ctx)) { - if (DD_CONTEXT != nullptr) - { - // If this macro is defined, the user-provided ddStr type - // needs some extra cleanup before shutdown, so we run for - // all entries in the debugStrings[] array. - // - // We could call std::string::clear() here, but clear() - // doesn't deallocate memory in std string, so we might - // as well let the default destructor do the cleanup, - // when using the default (AKA std::string) ddStr. - #ifdef DEBUG_DRAW_STR_DEALLOC_FUNC - for (int i = 0; i < DEBUG_DRAW_MAX_STRINGS; ++i) - { - DEBUG_DRAW_STR_DEALLOC_FUNC(DD_CONTEXT->debugStrings[i].text); - } - #endif // DEBUG_DRAW_STR_DEALLOC_FUNC - - if (DD_CONTEXT->renderInterface != nullptr && DD_CONTEXT->glyphTexHandle != nullptr) - { - DD_CONTEXT->renderInterface->destroyGlyphTexture(DD_CONTEXT->glyphTexHandle); - } - - DD_CONTEXT->~InternalContext(); // Destroy first - DD_MFREE(DD_CONTEXT); - - #ifndef DEBUG_DRAW_EXPLICIT_CONTEXT - DD_CONTEXT = nullptr; - #endif // DEBUG_DRAW_EXPLICIT_CONTEXT - } + if (DD_CONTEXT != nullptr) + { + // If this macro is defined, the user-provided ddStr type + // needs some extra cleanup before shutdown, so we run for + // all entries in the debugStrings[] array. + // + // We could call std::string::clear() here, but clear() + // doesn't deallocate memory in std string, so we might + // as well let the default destructor do the cleanup, + // when using the default (AKA std::string) ddStr. +#ifdef DEBUG_DRAW_STR_DEALLOC_FUNC + for (int i = 0; i < DEBUG_DRAW_MAX_STRINGS; ++i) + { + DEBUG_DRAW_STR_DEALLOC_FUNC(DD_CONTEXT->debugStrings[i].text); + } +#endif // DEBUG_DRAW_STR_DEALLOC_FUNC + + if (DD_CONTEXT->renderInterface != nullptr && DD_CONTEXT->glyphTexHandle != nullptr) + { + DD_CONTEXT->renderInterface->destroyGlyphTexture(DD_CONTEXT->glyphTexHandle); + } + + DD_CONTEXT->~InternalContext(); // Destroy first + DD_MFREE(DD_CONTEXT); + +#ifndef DEBUG_DRAW_EXPLICIT_CONTEXT + DD_CONTEXT = nullptr; +#endif // DEBUG_DRAW_EXPLICIT_CONTEXT + } } bool isInitialized(DD_EXPLICIT_CONTEXT_ONLY(ContextHandle ctx)) { - return (DD_CONTEXT != nullptr && DD_CONTEXT->renderInterface != nullptr); + return (DD_CONTEXT != nullptr && DD_CONTEXT->renderInterface != nullptr); } bool hasPendingDraws(DD_EXPLICIT_CONTEXT_ONLY(ContextHandle ctx)) { - if (!isInitialized(DD_EXPLICIT_CONTEXT_ONLY(ctx))) - { - return false; - } - return (DD_CONTEXT->debugStringsCount + DD_CONTEXT->debugPointsCount + DD_CONTEXT->debugLinesCount) > 0; + if (!isInitialized(DD_EXPLICIT_CONTEXT_ONLY(ctx))) + { + return false; + } + return (DD_CONTEXT->debugStringsCount + DD_CONTEXT->debugPointsCount + DD_CONTEXT->debugLinesCount) > 0; } void flush(DD_EXPLICIT_CONTEXT_ONLY(ContextHandle ctx,) const std::int64_t currTimeMillis, const std::uint32_t flags) { - if (!hasPendingDraws(DD_EXPLICIT_CONTEXT_ONLY(ctx))) - { - return; - } + if (!hasPendingDraws(DD_EXPLICIT_CONTEXT_ONLY(ctx))) + { + return; + } - // Save the last know time value for next dd::line/dd::point calls. - DD_CONTEXT->currentTimeMillis = currTimeMillis; + // Save the last know time value for next dd::line/dd::point calls. + DD_CONTEXT->currentTimeMillis = currTimeMillis; - // Let the user set common render states. - DD_CONTEXT->renderInterface->beginDraw(); + // Let the user set common render states. + DD_CONTEXT->renderInterface->beginDraw(); - // Issue the render calls: - if (flags & FlushLines) { drawDebugLines(DD_EXPLICIT_CONTEXT_ONLY(ctx)); } - if (flags & FlushPoints) { drawDebugPoints(DD_EXPLICIT_CONTEXT_ONLY(ctx)); } - if (flags & FlushText) { drawDebugStrings(DD_EXPLICIT_CONTEXT_ONLY(ctx)); } + // Issue the render calls: + if (flags & FlushLines) { drawDebugLines(DD_EXPLICIT_CONTEXT_ONLY(ctx)); } + if (flags & FlushPoints) { drawDebugPoints(DD_EXPLICIT_CONTEXT_ONLY(ctx)); } + if (flags & FlushText) { drawDebugStrings(DD_EXPLICIT_CONTEXT_ONLY(ctx)); } - // And cleanup if needed. - DD_CONTEXT->renderInterface->endDraw(); + // And cleanup if needed. + DD_CONTEXT->renderInterface->endDraw(); - // Remove all expired objects, regardless of draw flags: - clearDebugQueue(DD_EXPLICIT_CONTEXT_ONLY(ctx,) DD_CONTEXT->debugStrings, DD_CONTEXT->debugStringsCount); - clearDebugQueue(DD_EXPLICIT_CONTEXT_ONLY(ctx,) DD_CONTEXT->debugPoints, DD_CONTEXT->debugPointsCount); - clearDebugQueue(DD_EXPLICIT_CONTEXT_ONLY(ctx,) DD_CONTEXT->debugLines, DD_CONTEXT->debugLinesCount); + // Remove all expired objects, regardless of draw flags: + clearDebugQueue(DD_EXPLICIT_CONTEXT_ONLY(ctx,) DD_CONTEXT->debugStrings, DD_CONTEXT->debugStringsCount); + clearDebugQueue(DD_EXPLICIT_CONTEXT_ONLY(ctx,) DD_CONTEXT->debugPoints, DD_CONTEXT->debugPointsCount); + clearDebugQueue(DD_EXPLICIT_CONTEXT_ONLY(ctx,) DD_CONTEXT->debugLines, DD_CONTEXT->debugLinesCount); } void clear(DD_EXPLICIT_CONTEXT_ONLY(ContextHandle ctx)) { - if (!isInitialized(DD_EXPLICIT_CONTEXT_ONLY(ctx))) - { - return; - } - - // Let the user cleanup the debug strings: - #ifdef DEBUG_DRAW_STR_DEALLOC_FUNC - for (int i = 0; i < DEBUG_DRAW_MAX_STRINGS; ++i) - { - DEBUG_DRAW_STR_DEALLOC_FUNC(DD_CONTEXT->debugStrings[i].text); - } - #endif // DEBUG_DRAW_STR_DEALLOC_FUNC - - DD_CONTEXT->vertexBufferUsed = 0; - DD_CONTEXT->debugStringsCount = 0; - DD_CONTEXT->debugPointsCount = 0; - DD_CONTEXT->debugLinesCount = 0; + if (!isInitialized(DD_EXPLICIT_CONTEXT_ONLY(ctx))) + { + return; + } + + // Let the user cleanup the debug strings: +#ifdef DEBUG_DRAW_STR_DEALLOC_FUNC + for (int i = 0; i < DEBUG_DRAW_MAX_STRINGS; ++i) + { + DEBUG_DRAW_STR_DEALLOC_FUNC(DD_CONTEXT->debugStrings[i].text); + } +#endif // DEBUG_DRAW_STR_DEALLOC_FUNC + + DD_CONTEXT->vertexBufferUsed = 0; + DD_CONTEXT->debugStringsCount = 0; + DD_CONTEXT->debugPointsCount = 0; + DD_CONTEXT->debugLinesCount = 0; } void point(DD_EXPLICIT_CONTEXT_ONLY(ContextHandle ctx,) ddVec3_In pos, ddVec3_In color, - const float size, const int durationMillis, const bool depthEnabled) -{ - if (!isInitialized(DD_EXPLICIT_CONTEXT_ONLY(ctx))) - { - return; - } - - if (DD_CONTEXT->debugPointsCount == DEBUG_DRAW_MAX_POINTS) - { - DEBUG_DRAW_OVERFLOWED("DEBUG_DRAW_MAX_POINTS limit reached! Dropping further debug point draws."); - return; - } - - DebugPoint & point = DD_CONTEXT->debugPoints[DD_CONTEXT->debugPointsCount++]; - point.expiryDateMillis = DD_CONTEXT->currentTimeMillis + durationMillis; - point.depthEnabled = depthEnabled; - point.size = size; - - vecCopy(point.position, pos); - vecCopy(point.color, color); + const float size, const int durationMillis, const bool depthEnabled) +{ + if (!isInitialized(DD_EXPLICIT_CONTEXT_ONLY(ctx))) + { + return; + } + + if (DD_CONTEXT->debugPointsCount == DEBUG_DRAW_MAX_POINTS) + { + DEBUG_DRAW_OVERFLOWED("DEBUG_DRAW_MAX_POINTS limit reached! Dropping further debug point draws."); + return; + } + + DebugPoint & point = DD_CONTEXT->debugPoints[DD_CONTEXT->debugPointsCount++]; + point.expiryDateMillis = DD_CONTEXT->currentTimeMillis + durationMillis; + point.depthEnabled = depthEnabled; + point.size = size; + + vecCopy(point.position, pos); + vecCopy(point.color, color); } void line(DD_EXPLICIT_CONTEXT_ONLY(ContextHandle ctx,) ddVec3_In from, ddVec3_In to, - ddVec3_In color, const int durationMillis, const bool depthEnabled) -{ - if (!isInitialized(DD_EXPLICIT_CONTEXT_ONLY(ctx))) - { - return; - } - - if (DD_CONTEXT->debugLinesCount == DEBUG_DRAW_MAX_LINES) - { - DEBUG_DRAW_OVERFLOWED("DEBUG_DRAW_MAX_LINES limit reached! Dropping further debug line draws."); - return; - } - - DebugLine & line = DD_CONTEXT->debugLines[DD_CONTEXT->debugLinesCount++]; - line.expiryDateMillis = DD_CONTEXT->currentTimeMillis + durationMillis; - line.depthEnabled = depthEnabled; - - vecCopy(line.posFrom, from); - vecCopy(line.posTo, to); - vecCopy(line.color, color); + ddVec3_In color, const int durationMillis, const bool depthEnabled) +{ + if (!isInitialized(DD_EXPLICIT_CONTEXT_ONLY(ctx))) + { + return; + } + + if (DD_CONTEXT->debugLinesCount == DEBUG_DRAW_MAX_LINES) + { + DEBUG_DRAW_OVERFLOWED("DEBUG_DRAW_MAX_LINES limit reached! Dropping further debug line draws."); + return; + } + + DebugLine & line = DD_CONTEXT->debugLines[DD_CONTEXT->debugLinesCount++]; + line.expiryDateMillis = DD_CONTEXT->currentTimeMillis + durationMillis; + line.depthEnabled = depthEnabled; + + vecCopy(line.posFrom, from); + vecCopy(line.posTo, to); + vecCopy(line.color, color); } void screenText(DD_EXPLICIT_CONTEXT_ONLY(ContextHandle ctx,) const char * const str, ddVec3_In pos, - ddVec3_In color, const float scaling, const int durationMillis) -{ - if (!isInitialized(DD_EXPLICIT_CONTEXT_ONLY(ctx))) - { - return; - } - - if (DD_CONTEXT->glyphTexHandle == nullptr) - { - return; - } - - if (DD_CONTEXT->debugStringsCount == DEBUG_DRAW_MAX_STRINGS) - { - DEBUG_DRAW_OVERFLOWED("DEBUG_DRAW_MAX_STRINGS limit reached! Dropping further debug string draws."); - return; - } - - DebugString & dstr = DD_CONTEXT->debugStrings[DD_CONTEXT->debugStringsCount++]; - dstr.expiryDateMillis = DD_CONTEXT->currentTimeMillis + durationMillis; - dstr.posX = pos[X]; - dstr.posY = pos[Y]; - dstr.scaling = scaling; - dstr.text = str; - dstr.centered = false; - vecCopy(dstr.color, color); + ddVec3_In color, const float scaling, const int durationMillis) +{ + if (!isInitialized(DD_EXPLICIT_CONTEXT_ONLY(ctx))) + { + return; + } + + if (DD_CONTEXT->glyphTexHandle == nullptr) + { + return; + } + + if (DD_CONTEXT->debugStringsCount == DEBUG_DRAW_MAX_STRINGS) + { + DEBUG_DRAW_OVERFLOWED("DEBUG_DRAW_MAX_STRINGS limit reached! Dropping further debug string draws."); + return; + } + + DebugString & dstr = DD_CONTEXT->debugStrings[DD_CONTEXT->debugStringsCount++]; + dstr.expiryDateMillis = DD_CONTEXT->currentTimeMillis + durationMillis; + dstr.posX = pos[X]; + dstr.posY = pos[Y]; + dstr.scaling = scaling; + dstr.text = str; + dstr.centered = false; + vecCopy(dstr.color, color); } void projectedText(DD_EXPLICIT_CONTEXT_ONLY(ContextHandle ctx,) const char * const str, ddVec3_In pos, ddVec3_In color, - ddMat4x4_In vpMatrix, const int sx, const int sy, const int sw, const int sh, const float scaling, - const int durationMillis) -{ - if (!isInitialized(DD_EXPLICIT_CONTEXT_ONLY(ctx))) - { - return; - } - - if (DD_CONTEXT->glyphTexHandle == nullptr) - { - return; - } - - if (DD_CONTEXT->debugStringsCount == DEBUG_DRAW_MAX_STRINGS) - { - DEBUG_DRAW_OVERFLOWED("DEBUG_DRAW_MAX_STRINGS limit reached! Dropping further debug string draws."); - return; - } - - float tempPoint[4]; - matTransformPointXYZW(tempPoint, pos, vpMatrix); - - // Bail if W ended up as zero. - if (floatAbs(tempPoint[W]) < FloatEpsilon) - { - return; - } - - // Bail if point is behind camera. - if (tempPoint[Z] < -tempPoint[W] || tempPoint[Z] > tempPoint[W]) - { - return; - } - - // Perspective divide (we only care about the 2D part now): - tempPoint[X] /= tempPoint[W]; - tempPoint[Y] /= tempPoint[W]; - - // Map to window coordinates: - float scrX = ((tempPoint[X] * 0.5f) + 0.5f) * sw + sx; - float scrY = ((tempPoint[Y] * 0.5f) + 0.5f) * sh + sy; - - // Need to invert the direction because on OGL the screen origin is the bottom-left corner. - // NOTE: This is not renderer agnostic, I think... Should add a #define or something! - scrY = static_cast<float>(sh) - scrY; - - DebugString & dstr = DD_CONTEXT->debugStrings[DD_CONTEXT->debugStringsCount++]; - dstr.expiryDateMillis = DD_CONTEXT->currentTimeMillis + durationMillis; - dstr.posX = scrX; - dstr.posY = scrY; - dstr.scaling = scaling; - dstr.text = str; - dstr.centered = true; - vecCopy(dstr.color, color); + ddMat4x4_In vpMatrix, const int sx, const int sy, const int sw, const int sh, const float scaling, + const int durationMillis) +{ + if (!isInitialized(DD_EXPLICIT_CONTEXT_ONLY(ctx))) + { + return; + } + + if (DD_CONTEXT->glyphTexHandle == nullptr) + { + return; + } + + if (DD_CONTEXT->debugStringsCount == DEBUG_DRAW_MAX_STRINGS) + { + DEBUG_DRAW_OVERFLOWED("DEBUG_DRAW_MAX_STRINGS limit reached! Dropping further debug string draws."); + return; + } + + float tempPoint[4]; + matTransformPointXYZW(tempPoint, pos, vpMatrix); + + // Bail if W ended up as zero. + if (floatAbs(tempPoint[W]) < FloatEpsilon) + { + return; + } + + // Bail if point is behind camera. + if (tempPoint[Z] < -tempPoint[W] || tempPoint[Z] > tempPoint[W]) + { + return; + } + + // Perspective divide (we only care about the 2D part now): + tempPoint[X] /= tempPoint[W]; + tempPoint[Y] /= tempPoint[W]; + + // Map to window coordinates: + float scrX = ((tempPoint[X] * 0.5f) + 0.5f) * sw + sx; + float scrY = ((tempPoint[Y] * 0.5f) + 0.5f) * sh + sy; + + // Need to invert the direction because on OGL the screen origin is the bottom-left corner. + // NOTE: This is not renderer agnostic, I think... Should add a #define or something! + scrY = static_cast<float>(sh) - scrY; + + DebugString & dstr = DD_CONTEXT->debugStrings[DD_CONTEXT->debugStringsCount++]; + dstr.expiryDateMillis = DD_CONTEXT->currentTimeMillis + durationMillis; + dstr.posX = scrX; + dstr.posY = scrY; + dstr.scaling = scaling; + dstr.text = str; + dstr.centered = true; + vecCopy(dstr.color, color); } void axisTriad(DD_EXPLICIT_CONTEXT_ONLY(ContextHandle ctx,) ddMat4x4_In transform, const float size, - const float length, const int durationMillis, const bool depthEnabled) -{ - if (!isInitialized(DD_EXPLICIT_CONTEXT_ONLY(ctx))) - { - return; - } - - ddVec3 p0, p1, p2, p3; - ddVec3 xEnd, yEnd, zEnd; - ddVec3 origin, cR, cG, cB; - - vecSet(cR, 1.0f, 0.0f, 0.0f); - vecSet(cG, 0.0f, 1.0f, 0.0f); - vecSet(cB, 0.0f, 0.0f, 1.0f); - - vecSet(origin, 0.0f, 0.0f, 0.0f); - vecSet(xEnd, length, 0.0f, 0.0f); - vecSet(yEnd, 0.0f, length, 0.0f); - vecSet(zEnd, 0.0f, 0.0f, length); - - matTransformPointXYZ(p0, origin, transform); - matTransformPointXYZ(p1, xEnd, transform); - matTransformPointXYZ(p2, yEnd, transform); - matTransformPointXYZ(p3, zEnd, transform); - - arrow(DD_EXPLICIT_CONTEXT_ONLY(ctx,) p0, p1, cR, size, durationMillis, depthEnabled); // X: red axis - arrow(DD_EXPLICIT_CONTEXT_ONLY(ctx,) p0, p2, cG, size, durationMillis, depthEnabled); // Y: green axis - arrow(DD_EXPLICIT_CONTEXT_ONLY(ctx,) p0, p3, cB, size, durationMillis, depthEnabled); // Z: blue axis + const float length, const int durationMillis, const bool depthEnabled) +{ + if (!isInitialized(DD_EXPLICIT_CONTEXT_ONLY(ctx))) + { + return; + } + + ddVec3 p0, p1, p2, p3; + ddVec3 xEnd, yEnd, zEnd; + ddVec3 origin, cR, cG, cB; + + vecSet(cR, 1.0f, 0.0f, 0.0f); + vecSet(cG, 0.0f, 1.0f, 0.0f); + vecSet(cB, 0.0f, 0.0f, 1.0f); + + vecSet(origin, 0.0f, 0.0f, 0.0f); + vecSet(xEnd, length, 0.0f, 0.0f); + vecSet(yEnd, 0.0f, length, 0.0f); + vecSet(zEnd, 0.0f, 0.0f, length); + + matTransformPointXYZ(p0, origin, transform); + matTransformPointXYZ(p1, xEnd, transform); + matTransformPointXYZ(p2, yEnd, transform); + matTransformPointXYZ(p3, zEnd, transform); + + arrow(DD_EXPLICIT_CONTEXT_ONLY(ctx,) p0, p1, cR, size, durationMillis, depthEnabled); // X: red axis + arrow(DD_EXPLICIT_CONTEXT_ONLY(ctx,) p0, p2, cG, size, durationMillis, depthEnabled); // Y: green axis + arrow(DD_EXPLICIT_CONTEXT_ONLY(ctx,) p0, p3, cB, size, durationMillis, depthEnabled); // Z: blue axis } void arrow(DD_EXPLICIT_CONTEXT_ONLY(ContextHandle ctx,) ddVec3_In from, ddVec3_In to, ddVec3_In color, - const float size, const int durationMillis, const bool depthEnabled) -{ - if (!isInitialized(DD_EXPLICIT_CONTEXT_ONLY(ctx))) - { - return; - } - - static const float arrowStep = 30.0f; // In degrees - static const float arrowSin[45] = { - 0.0f, 0.5f, 0.866025f, 1.0f, 0.866025f, 0.5f, -0.0f, -0.5f, -0.866025f, - -1.0f, -0.866025f, -0.5f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, - 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, - 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f - }; - static const float arrowCos[45] = { - 1.0f, 0.866025f, 0.5f, -0.0f, -0.5f, -0.866026f, -1.0f, -0.866025f, -0.5f, 0.0f, - 0.5f, 0.866026f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, - 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, - 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f - }; - - // Body line: - line(DD_EXPLICIT_CONTEXT_ONLY(ctx,) from, to, color, durationMillis, depthEnabled); - - // Aux vectors to compute the arrowhead: - ddVec3 up, right, forward; - vecSub(forward, to, from); - vecNormalize(forward, forward); - vecOrthogonalBasis(right, up, forward); - vecScale(forward, forward, size); - - // Arrowhead is a cone (sin/cos tables used here): - float degrees = 0.0f; - for (int i = 0; degrees < 360.0f; degrees += arrowStep, ++i) - { - float scale; - ddVec3 v1, v2, temp; - - scale = 0.5f * size * arrowCos[i]; - vecScale(temp, right, scale); - vecSub(v1, to, forward); - vecAdd(v1, v1, temp); - - scale = 0.5f * size * arrowSin[i]; - vecScale(temp, up, scale); - vecAdd(v1, v1, temp); - - scale = 0.5f * size * arrowCos[i + 1]; - vecScale(temp, right, scale); - vecSub(v2, to, forward); - vecAdd(v2, v2, temp); - - scale = 0.5f * size * arrowSin[i + 1]; - vecScale(temp, up, scale); - vecAdd(v2, v2, temp); - - line(DD_EXPLICIT_CONTEXT_ONLY(ctx,) v1, to, color, durationMillis, depthEnabled); - line(DD_EXPLICIT_CONTEXT_ONLY(ctx,) v1, v2, color, durationMillis, depthEnabled); - } + const float size, const int durationMillis, const bool depthEnabled) +{ + if (!isInitialized(DD_EXPLICIT_CONTEXT_ONLY(ctx))) + { + return; + } + + static const float arrowStep = 30.0f; // In degrees + static const float arrowSin[45] = { + 0.0f, 0.5f, 0.866025f, 1.0f, 0.866025f, 0.5f, -0.0f, -0.5f, -0.866025f, + -1.0f, -0.866025f, -0.5f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, + 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, + 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f + }; + static const float arrowCos[45] = { + 1.0f, 0.866025f, 0.5f, -0.0f, -0.5f, -0.866026f, -1.0f, -0.866025f, -0.5f, 0.0f, + 0.5f, 0.866026f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, + 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, + 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f + }; + + // Body line: + line(DD_EXPLICIT_CONTEXT_ONLY(ctx,) from, to, color, durationMillis, depthEnabled); + + // Aux vectors to compute the arrowhead: + ddVec3 up, right, forward; + vecSub(forward, to, from); + vecNormalize(forward, forward); + vecOrthogonalBasis(right, up, forward); + vecScale(forward, forward, size); + + // Arrowhead is a cone (sin/cos tables used here): + float degrees = 0.0f; + for (int i = 0; degrees < 360.0f; degrees += arrowStep, ++i) + { + float scale; + ddVec3 v1, v2, temp; + + scale = 0.5f * size * arrowCos[i]; + vecScale(temp, right, scale); + vecSub(v1, to, forward); + vecAdd(v1, v1, temp); + + scale = 0.5f * size * arrowSin[i]; + vecScale(temp, up, scale); + vecAdd(v1, v1, temp); + + scale = 0.5f * size * arrowCos[i + 1]; + vecScale(temp, right, scale); + vecSub(v2, to, forward); + vecAdd(v2, v2, temp); + + scale = 0.5f * size * arrowSin[i + 1]; + vecScale(temp, up, scale); + vecAdd(v2, v2, temp); + + line(DD_EXPLICIT_CONTEXT_ONLY(ctx,) v1, to, color, durationMillis, depthEnabled); + line(DD_EXPLICIT_CONTEXT_ONLY(ctx,) v1, v2, color, durationMillis, depthEnabled); + } } void cross(DD_EXPLICIT_CONTEXT_ONLY(ContextHandle ctx,) ddVec3_In center, const float length, - const int durationMillis, const bool depthEnabled) -{ - if (!isInitialized(DD_EXPLICIT_CONTEXT_ONLY(ctx))) - { - return; - } - - ddVec3 from, to; - ddVec3 cR, cG, cB; - - vecSet(cR, 1.0f, 0.0f, 0.0f); - vecSet(cG, 0.0f, 1.0f, 0.0f); - vecSet(cB, 0.0f, 0.0f, 1.0f); - - const float cx = center[X]; - const float cy = center[Y]; - const float cz = center[Z]; - const float hl = length * 0.5f; // Half on each side. - - // Red line: X - length/2 to X + length/2 - vecSet(from, cx - hl, cy, cz); - vecSet(to, cx + hl, cy, cz); - line(DD_EXPLICIT_CONTEXT_ONLY(ctx,) from, to, cR, durationMillis, depthEnabled); - - // Green line: Y - length/2 to Y + length/2 - vecSet(from, cx, cy - hl, cz); - vecSet(to, cx, cy + hl, cz); - line(DD_EXPLICIT_CONTEXT_ONLY(ctx,) from, to, cG, durationMillis, depthEnabled); - - // Blue line: Z - length/2 to Z + length/2 - vecSet(from, cx, cy, cz - hl); - vecSet(to, cx, cy, cz + hl); - line(DD_EXPLICIT_CONTEXT_ONLY(ctx,) from, to, cB, durationMillis, depthEnabled); + const int durationMillis, const bool depthEnabled) +{ + if (!isInitialized(DD_EXPLICIT_CONTEXT_ONLY(ctx))) + { + return; + } + + ddVec3 from, to; + ddVec3 cR, cG, cB; + + vecSet(cR, 1.0f, 0.0f, 0.0f); + vecSet(cG, 0.0f, 1.0f, 0.0f); + vecSet(cB, 0.0f, 0.0f, 1.0f); + + const float cx = center[X]; + const float cy = center[Y]; + const float cz = center[Z]; + const float hl = length * 0.5f; // Half on each side. + + // Red line: X - length/2 to X + length/2 + vecSet(from, cx - hl, cy, cz); + vecSet(to, cx + hl, cy, cz); + line(DD_EXPLICIT_CONTEXT_ONLY(ctx,) from, to, cR, durationMillis, depthEnabled); + + // Green line: Y - length/2 to Y + length/2 + vecSet(from, cx, cy - hl, cz); + vecSet(to, cx, cy + hl, cz); + line(DD_EXPLICIT_CONTEXT_ONLY(ctx,) from, to, cG, durationMillis, depthEnabled); + + // Blue line: Z - length/2 to Z + length/2 + vecSet(from, cx, cy, cz - hl); + vecSet(to, cx, cy, cz + hl); + line(DD_EXPLICIT_CONTEXT_ONLY(ctx,) from, to, cB, durationMillis, depthEnabled); } void circle(DD_EXPLICIT_CONTEXT_ONLY(ContextHandle ctx,) ddVec3_In center, ddVec3_In planeNormal, ddVec3_In color, - const float radius, const float numSteps, const int durationMillis, const bool depthEnabled) + const float radius, const float numSteps, const int durationMillis, const bool depthEnabled) { - if (!isInitialized(DD_EXPLICIT_CONTEXT_ONLY(ctx))) - { - return; - } + if (!isInitialized(DD_EXPLICIT_CONTEXT_ONLY(ctx))) + { + return; + } - ddVec3 left, up; - ddVec3 point, lastPoint; + ddVec3 left, up; + ddVec3 point, lastPoint; - vecOrthogonalBasis(left, up, planeNormal); + vecOrthogonalBasis(left, up, planeNormal); - vecScale(up, up, radius); - vecScale(left, left, radius); - vecAdd(lastPoint, center, up); + vecScale(up, up, radius); + vecScale(left, left, radius); + vecAdd(lastPoint, center, up); - for (int i = 1; i <= numSteps; ++i) - { - const float radians = TAU * i / numSteps; + for (int i = 1; i <= numSteps; ++i) + { + const float radians = TAU * i / numSteps; - ddVec3 vs, vc; - vecScale(vs, left, floatSin(radians)); - vecScale(vc, up, floatCos(radians)); + ddVec3 vs, vc; + vecScale(vs, left, floatSin(radians)); + vecScale(vc, up, floatCos(radians)); - vecAdd(point, center, vs); - vecAdd(point, point, vc); + vecAdd(point, center, vs); + vecAdd(point, point, vc); - line(DD_EXPLICIT_CONTEXT_ONLY(ctx,) lastPoint, point, color, durationMillis, depthEnabled); - vecCopy(lastPoint, point); - } + line(DD_EXPLICIT_CONTEXT_ONLY(ctx,) lastPoint, point, color, durationMillis, depthEnabled); + vecCopy(lastPoint, point); + } } void plane(DD_EXPLICIT_CONTEXT_ONLY(ContextHandle ctx,) ddVec3_In center, ddVec3_In planeNormal, ddVec3_In planeColor, - ddVec3_In normalVecColor, const float planeScale, const float normalVecScale, const int durationMillis, - const bool depthEnabled) -{ - if (!isInitialized(DD_EXPLICIT_CONTEXT_ONLY(ctx))) - { - return; - } - - ddVec3 v1, v2, v3, v4; - ddVec3 tangent, bitangent; - vecOrthogonalBasis(tangent, bitangent, planeNormal); - - // A little bit of preprocessor voodoo to make things more interesting :P - #define DD_PLANE_V(v, op1, op2) \ - v[X] = (center[X] op1 (tangent[X] * planeScale) op2 (bitangent[X] * planeScale)); \ - v[Y] = (center[Y] op1 (tangent[Y] * planeScale) op2 (bitangent[Y] * planeScale)); \ - v[Z] = (center[Z] op1 (tangent[Z] * planeScale) op2 (bitangent[Z] * planeScale)) - DD_PLANE_V(v1, -, -); - DD_PLANE_V(v2, +, -); - DD_PLANE_V(v3, +, +); - DD_PLANE_V(v4, -, +); - #undef DD_PLANE_V - - // Draw the wireframe plane quadrilateral: - line(DD_EXPLICIT_CONTEXT_ONLY(ctx,) v1, v2, planeColor, durationMillis, depthEnabled); - line(DD_EXPLICIT_CONTEXT_ONLY(ctx,) v2, v3, planeColor, durationMillis, depthEnabled); - line(DD_EXPLICIT_CONTEXT_ONLY(ctx,) v3, v4, planeColor, durationMillis, depthEnabled); - line(DD_EXPLICIT_CONTEXT_ONLY(ctx,) v4, v1, planeColor, durationMillis, depthEnabled); - - // Optionally add a line depicting the plane normal: - if (normalVecScale != 0.0f) - { - ddVec3 normalVec; - normalVec[X] = (planeNormal[X] * normalVecScale) + center[X]; - normalVec[Y] = (planeNormal[Y] * normalVecScale) + center[Y]; - normalVec[Z] = (planeNormal[Z] * normalVecScale) + center[Z]; - line(DD_EXPLICIT_CONTEXT_ONLY(ctx,) center, normalVec, normalVecColor, durationMillis, depthEnabled); - } + ddVec3_In normalVecColor, const float planeScale, const float normalVecScale, const int durationMillis, + const bool depthEnabled) +{ + if (!isInitialized(DD_EXPLICIT_CONTEXT_ONLY(ctx))) + { + return; + } + + ddVec3 v1, v2, v3, v4; + ddVec3 tangent, bitangent; + vecOrthogonalBasis(tangent, bitangent, planeNormal); + + // A little bit of preprocessor voodoo to make things more interesting :P +#define DD_PLANE_V(v, op1, op2) \ + v[X] = (center[X] op1 (tangent[X] * planeScale) op2 (bitangent[X] * planeScale)); \ + v[Y] = (center[Y] op1 (tangent[Y] * planeScale) op2 (bitangent[Y] * planeScale)); \ + v[Z] = (center[Z] op1 (tangent[Z] * planeScale) op2 (bitangent[Z] * planeScale)) + DD_PLANE_V(v1, -, -); + DD_PLANE_V(v2, +, -); + DD_PLANE_V(v3, +, +); + DD_PLANE_V(v4, -, +); + #undef DD_PLANE_V + + // Draw the wireframe plane quadrilateral: + line(DD_EXPLICIT_CONTEXT_ONLY(ctx,) v1, v2, planeColor, durationMillis, depthEnabled); + line(DD_EXPLICIT_CONTEXT_ONLY(ctx,) v2, v3, planeColor, durationMillis, depthEnabled); + line(DD_EXPLICIT_CONTEXT_ONLY(ctx,) v3, v4, planeColor, durationMillis, depthEnabled); + line(DD_EXPLICIT_CONTEXT_ONLY(ctx,) v4, v1, planeColor, durationMillis, depthEnabled); + + // Optionally add a line depicting the plane normal: + if (normalVecScale != 0.0f) + { + ddVec3 normalVec; + normalVec[X] = (planeNormal[X] * normalVecScale) + center[X]; + normalVec[Y] = (planeNormal[Y] * normalVecScale) + center[Y]; + normalVec[Z] = (planeNormal[Z] * normalVecScale) + center[Z]; + line(DD_EXPLICIT_CONTEXT_ONLY(ctx,) center, normalVec, normalVecColor, durationMillis, depthEnabled); + } } void sphere(DD_EXPLICIT_CONTEXT_ONLY(ContextHandle ctx,) ddVec3_In center, ddVec3_In color, - const float radius, const int durationMillis, const bool depthEnabled) -{ - if (!isInitialized(DD_EXPLICIT_CONTEXT_ONLY(ctx))) - { - return; - } - - static const int stepSize = 15; - ddVec3 cache[360 / stepSize]; - ddVec3 radiusVec; - - vecSet(radiusVec, 0.0f, 0.0f, radius); - vecAdd(cache[0], center, radiusVec); - - for (int n = 1; n < arrayLength(cache); ++n) - { - vecCopy(cache[n], cache[0]); - } - - ddVec3 lastPoint, temp; - for (int i = stepSize; i <= 360; i += stepSize) - { - const float s = floatSin(degreesToRadians(i)); - const float c = floatCos(degreesToRadians(i)); - - lastPoint[X] = center[X]; - lastPoint[Y] = center[Y] + radius * s; - lastPoint[Z] = center[Z] + radius * c; - - for (int n = 0, j = stepSize; j <= 360; j += stepSize, ++n) - { - temp[X] = center[X] + floatSin(degreesToRadians(j)) * radius * s; - temp[Y] = center[Y] + floatCos(degreesToRadians(j)) * radius * s; - temp[Z] = lastPoint[Z]; - - line(DD_EXPLICIT_CONTEXT_ONLY(ctx,) lastPoint, temp, color, durationMillis, depthEnabled); - line(DD_EXPLICIT_CONTEXT_ONLY(ctx,) lastPoint, cache[n], color, durationMillis, depthEnabled); - - vecCopy(cache[n], lastPoint); - vecCopy(lastPoint, temp); - } - } + const float radius, const int durationMillis, const bool depthEnabled) +{ + if (!isInitialized(DD_EXPLICIT_CONTEXT_ONLY(ctx))) + { + return; + } + + static const int stepSize = 15; + ddVec3 cache[360 / stepSize]; + ddVec3 radiusVec; + + vecSet(radiusVec, 0.0f, 0.0f, radius); + vecAdd(cache[0], center, radiusVec); + + for (int n = 1; n < arrayLength(cache); ++n) + { + vecCopy(cache[n], cache[0]); + } + + ddVec3 lastPoint, temp; + for (int i = stepSize; i <= 360; i += stepSize) + { + const float s = floatSin(degreesToRadians(i)); + const float c = floatCos(degreesToRadians(i)); + + lastPoint[X] = center[X]; + lastPoint[Y] = center[Y] + radius * s; + lastPoint[Z] = center[Z] + radius * c; + + for (int n = 0, j = stepSize; j <= 360; j += stepSize, ++n) + { + temp[X] = center[X] + floatSin(degreesToRadians(j)) * radius * s; + temp[Y] = center[Y] + floatCos(degreesToRadians(j)) * radius * s; + temp[Z] = lastPoint[Z]; + + line(DD_EXPLICIT_CONTEXT_ONLY(ctx,) lastPoint, temp, color, durationMillis, depthEnabled); + line(DD_EXPLICIT_CONTEXT_ONLY(ctx,) lastPoint, cache[n], color, durationMillis, depthEnabled); + + vecCopy(cache[n], lastPoint); + vecCopy(lastPoint, temp); + } + } } void cone(DD_EXPLICIT_CONTEXT_ONLY(ContextHandle ctx,) ddVec3_In apex, ddVec3_In dir, ddVec3_In color, - const float baseRadius, const float apexRadius, const int durationMillis, const bool depthEnabled) -{ - if (!isInitialized(DD_EXPLICIT_CONTEXT_ONLY(ctx))) - { - return; - } - - static const int stepSize = 20; - ddVec3 axis[3]; - ddVec3 top, temp0, temp1, temp2; - ddVec3 p1, p2, lastP1, lastP2; - - vecCopy(axis[2], dir); - vecNormalize(axis[2], axis[2]); - vecOrthogonalBasis(axis[0], axis[1], axis[2]); - - axis[1][X] = -axis[1][X]; - axis[1][Y] = -axis[1][Y]; - axis[1][Z] = -axis[1][Z]; - - vecAdd(top, apex, dir); - vecScale(temp1, axis[1], baseRadius); - vecAdd(lastP2, top, temp1); - - if (apexRadius == 0.0f) - { - for (int i = stepSize; i <= 360; i += stepSize) - { - vecScale(temp1, axis[0], floatSin(degreesToRadians(i))); - vecScale(temp2, axis[1], floatCos(degreesToRadians(i))); - vecAdd(temp0, temp1, temp2); - - vecScale(temp0, temp0, baseRadius); - vecAdd(p2, top, temp0); - - line(DD_EXPLICIT_CONTEXT_ONLY(ctx,) lastP2, p2, color, durationMillis, depthEnabled); - line(DD_EXPLICIT_CONTEXT_ONLY(ctx,) p2, apex, color, durationMillis, depthEnabled); - - vecCopy(lastP2, p2); - } - } - else // A degenerate cone with open apex: - { - vecScale(temp1, axis[1], apexRadius); - vecAdd(lastP1, apex, temp1); - - for (int i = stepSize; i <= 360; i += stepSize) - { - vecScale(temp1, axis[0], floatSin(degreesToRadians(i))); - vecScale(temp2, axis[1], floatCos(degreesToRadians(i))); - vecAdd(temp0, temp1, temp2); - - vecScale(temp1, temp0, apexRadius); - vecScale(temp2, temp0, baseRadius); - - vecAdd(p1, apex, temp1); - vecAdd(p2, top, temp2); - - line(DD_EXPLICIT_CONTEXT_ONLY(ctx,) lastP1, p1, color, durationMillis, depthEnabled); - line(DD_EXPLICIT_CONTEXT_ONLY(ctx,) lastP2, p2, color, durationMillis, depthEnabled); - line(DD_EXPLICIT_CONTEXT_ONLY(ctx,) p1, p2, color, durationMillis, depthEnabled); - - vecCopy(lastP1, p1); - vecCopy(lastP2, p2); - } - } + const float baseRadius, const float apexRadius, const int durationMillis, const bool depthEnabled) +{ + if (!isInitialized(DD_EXPLICIT_CONTEXT_ONLY(ctx))) + { + return; + } + + static const int stepSize = 20; + ddVec3 axis[3]; + ddVec3 top, temp0, temp1, temp2; + ddVec3 p1, p2, lastP1, lastP2; + + vecCopy(axis[2], dir); + vecNormalize(axis[2], axis[2]); + vecOrthogonalBasis(axis[0], axis[1], axis[2]); + + axis[1][X] = -axis[1][X]; + axis[1][Y] = -axis[1][Y]; + axis[1][Z] = -axis[1][Z]; + + vecAdd(top, apex, dir); + vecScale(temp1, axis[1], baseRadius); + vecAdd(lastP2, top, temp1); + + if (apexRadius == 0.0f) + { + for (int i = stepSize; i <= 360; i += stepSize) + { + vecScale(temp1, axis[0], floatSin(degreesToRadians(i))); + vecScale(temp2, axis[1], floatCos(degreesToRadians(i))); + vecAdd(temp0, temp1, temp2); + + vecScale(temp0, temp0, baseRadius); + vecAdd(p2, top, temp0); + + line(DD_EXPLICIT_CONTEXT_ONLY(ctx,) lastP2, p2, color, durationMillis, depthEnabled); + line(DD_EXPLICIT_CONTEXT_ONLY(ctx,) p2, apex, color, durationMillis, depthEnabled); + + vecCopy(lastP2, p2); + } + } + else // A degenerate cone with open apex: + { + vecScale(temp1, axis[1], apexRadius); + vecAdd(lastP1, apex, temp1); + + for (int i = stepSize; i <= 360; i += stepSize) + { + vecScale(temp1, axis[0], floatSin(degreesToRadians(i))); + vecScale(temp2, axis[1], floatCos(degreesToRadians(i))); + vecAdd(temp0, temp1, temp2); + + vecScale(temp1, temp0, apexRadius); + vecScale(temp2, temp0, baseRadius); + + vecAdd(p1, apex, temp1); + vecAdd(p2, top, temp2); + + line(DD_EXPLICIT_CONTEXT_ONLY(ctx,) lastP1, p1, color, durationMillis, depthEnabled); + line(DD_EXPLICIT_CONTEXT_ONLY(ctx,) lastP2, p2, color, durationMillis, depthEnabled); + line(DD_EXPLICIT_CONTEXT_ONLY(ctx,) p1, p2, color, durationMillis, depthEnabled); + + vecCopy(lastP1, p1); + vecCopy(lastP2, p2); + } + } } void box(DD_EXPLICIT_CONTEXT_ONLY(ContextHandle ctx,) const ddVec3 points[8], ddVec3_In color, - const int durationMillis, const bool depthEnabled) -{ - // Build the lines from points using clever indexing tricks: - // (& 3 is a fancy way of doing % 4, but avoids the expensive modulo operation) - for (int i = 0; i < 4; ++i) - { - line(DD_EXPLICIT_CONTEXT_ONLY(ctx,) points[i], points[(i + 1) & 3], color, durationMillis, depthEnabled); - line(DD_EXPLICIT_CONTEXT_ONLY(ctx,) points[4 + i], points[4 + ((i + 1) & 3)], color, durationMillis, depthEnabled); - line(DD_EXPLICIT_CONTEXT_ONLY(ctx,) points[i], points[4 + i], color, durationMillis, depthEnabled); - } + const int durationMillis, const bool depthEnabled) +{ + // Build the lines from points using clever indexing tricks: + // (& 3 is a fancy way of doing % 4, but avoids the expensive modulo operation) + for (int i = 0; i < 4; ++i) + { + line(DD_EXPLICIT_CONTEXT_ONLY(ctx,) points[i], points[(i + 1) & 3], color, durationMillis, depthEnabled); + line(DD_EXPLICIT_CONTEXT_ONLY(ctx,) points[4 + i], points[4 + ((i + 1) & 3)], color, durationMillis, depthEnabled); + line(DD_EXPLICIT_CONTEXT_ONLY(ctx,) points[i], points[4 + i], color, durationMillis, depthEnabled); + } } void box(DD_EXPLICIT_CONTEXT_ONLY(ContextHandle ctx,) ddVec3_In center, ddVec3_In color, const float width, - const float height, const float depth, const int durationMillis, const bool depthEnabled) -{ - if (!isInitialized(DD_EXPLICIT_CONTEXT_ONLY(ctx))) - { - return; - } - - const float cx = center[X]; - const float cy = center[Y]; - const float cz = center[Z]; - const float w = width * 0.5f; - const float h = height * 0.5f; - const float d = depth * 0.5f; - - // Create all the 8 points: - ddVec3 points[8]; - #define DD_BOX_V(v, op1, op2, op3) \ - v[X] = cx op1 w; \ - v[Y] = cy op2 h; \ - v[Z] = cz op3 d - DD_BOX_V(points[0], -, +, +); - DD_BOX_V(points[1], -, +, -); - DD_BOX_V(points[2], +, +, -); - DD_BOX_V(points[3], +, +, +); - DD_BOX_V(points[4], -, -, +); - DD_BOX_V(points[5], -, -, -); - DD_BOX_V(points[6], +, -, -); - DD_BOX_V(points[7], +, -, +); - #undef DD_BOX_V - - box(DD_EXPLICIT_CONTEXT_ONLY(ctx,) points, color, durationMillis, depthEnabled); + const float height, const float depth, const int durationMillis, const bool depthEnabled) +{ + if (!isInitialized(DD_EXPLICIT_CONTEXT_ONLY(ctx))) + { + return; + } + + const float cx = center[X]; + const float cy = center[Y]; + const float cz = center[Z]; + const float w = width * 0.5f; + const float h = height * 0.5f; + const float d = depth * 0.5f; + + // Create all the 8 points: + ddVec3 points[8]; +#define DD_BOX_V(v, op1, op2, op3) \ + v[X] = cx op1 w; \ + v[Y] = cy op2 h; \ + v[Z] = cz op3 d + DD_BOX_V(points[0], -, +, +); + DD_BOX_V(points[1], -, +, -); + DD_BOX_V(points[2], +, +, -); + DD_BOX_V(points[3], +, +, +); + DD_BOX_V(points[4], -, -, +); + DD_BOX_V(points[5], -, -, -); + DD_BOX_V(points[6], +, -, -); + DD_BOX_V(points[7], +, -, +); + #undef DD_BOX_V + + box(DD_EXPLICIT_CONTEXT_ONLY(ctx,) points, color, durationMillis, depthEnabled); } void aabb(DD_EXPLICIT_CONTEXT_ONLY(ContextHandle ctx,) ddVec3_In mins, ddVec3_In maxs, - ddVec3_In color, const int durationMillis, const bool depthEnabled) + ddVec3_In color, const int durationMillis, const bool depthEnabled) { - if (!isInitialized(DD_EXPLICIT_CONTEXT_ONLY(ctx))) - { - return; - } + if (!isInitialized(DD_EXPLICIT_CONTEXT_ONLY(ctx))) + { + return; + } - ddVec3 bb[2]; - ddVec3 points[8]; + ddVec3 bb[2]; + ddVec3 points[8]; - vecCopy(bb[0], mins); - vecCopy(bb[1], maxs); + vecCopy(bb[0], mins); + vecCopy(bb[1], maxs); - // Expand min/max bounds: - for (int i = 0; i < arrayLength(points); ++i) - { - points[i][X] = bb[(i ^ (i >> 1)) & 1][X]; - points[i][Y] = bb[(i >> 1) & 1][Y]; - points[i][Z] = bb[(i >> 2) & 1][Z]; - } + // Expand min/max bounds: + for (int i = 0; i < arrayLength(points); ++i) + { + points[i][X] = bb[(i ^ (i >> 1)) & 1][X]; + points[i][Y] = bb[(i >> 1) & 1][Y]; + points[i][Z] = bb[(i >> 2) & 1][Z]; + } - // Build the lines: - box(DD_EXPLICIT_CONTEXT_ONLY(ctx,) points, color, durationMillis, depthEnabled); + // Build the lines: + box(DD_EXPLICIT_CONTEXT_ONLY(ctx,) points, color, durationMillis, depthEnabled); } void frustum(DD_EXPLICIT_CONTEXT_ONLY(ContextHandle ctx,) ddMat4x4_In invClipMatrix, - ddVec3_In color, const int durationMillis, const bool depthEnabled) -{ - if (!isInitialized(DD_EXPLICIT_CONTEXT_ONLY(ctx))) - { - return; - } - - // Start with the standard clip volume, then bring it back to world space. - static const float planes[8][3] = { - // near plane - { -1.0f, -1.0f, -1.0f }, { 1.0f, -1.0f, -1.0f }, - { 1.0f, 1.0f, -1.0f }, { -1.0f, 1.0f, -1.0f }, - // far plane - { -1.0f, -1.0f, 1.0f }, { 1.0f, -1.0f, 1.0f }, - { 1.0f, 1.0f, 1.0f }, { -1.0f, 1.0f, 1.0f } - }; - - ddVec3 points[8]; - float wCoords[8]; - - // Transform the planes by the inverse clip matrix: - for (int i = 0; i < arrayLength(planes); ++i) - { - wCoords[i] = matTransformPointXYZW2(points[i], planes[i], invClipMatrix); - } - - // Divide by the W component of each: - for (int i = 0; i < arrayLength(planes); ++i) - { - // But bail if any W ended up as zero. - if (floatAbs(wCoords[W]) < FloatEpsilon) - { - return; - } - - points[i][X] /= wCoords[i]; - points[i][Y] /= wCoords[i]; - points[i][Z] /= wCoords[i]; - } - - // Connect the dots: - box(DD_EXPLICIT_CONTEXT_ONLY(ctx,) points, color, durationMillis, depthEnabled); + ddVec3_In color, const int durationMillis, const bool depthEnabled) +{ + if (!isInitialized(DD_EXPLICIT_CONTEXT_ONLY(ctx))) + { + return; + } + + // Start with the standard clip volume, then bring it back to world space. + static const float planes[8][3] = { + // near plane + { -1.0f, -1.0f, -1.0f }, { 1.0f, -1.0f, -1.0f }, + { 1.0f, 1.0f, -1.0f }, { -1.0f, 1.0f, -1.0f }, + // far plane + { -1.0f, -1.0f, 1.0f }, { 1.0f, -1.0f, 1.0f }, + { 1.0f, 1.0f, 1.0f }, { -1.0f, 1.0f, 1.0f } + }; + + ddVec3 points[8]; + float wCoords[8]; + + // Transform the planes by the inverse clip matrix: + for (int i = 0; i < arrayLength(planes); ++i) + { + wCoords[i] = matTransformPointXYZW2(points[i], planes[i], invClipMatrix); + } + + // Divide by the W component of each: + for (int i = 0; i < arrayLength(planes); ++i) + { + // But bail if any W ended up as zero. + if (floatAbs(wCoords[W]) < FloatEpsilon) + { + return; + } + + points[i][X] /= wCoords[i]; + points[i][Y] /= wCoords[i]; + points[i][Z] /= wCoords[i]; + } + + // Connect the dots: + box(DD_EXPLICIT_CONTEXT_ONLY(ctx,) points, color, durationMillis, depthEnabled); } void vertexNormal(DD_EXPLICIT_CONTEXT_ONLY(ContextHandle ctx,) ddVec3_In origin, ddVec3_In normal, - const float length, const int durationMillis, const bool depthEnabled) + const float length, const int durationMillis, const bool depthEnabled) { - if (!isInitialized(DD_EXPLICIT_CONTEXT_ONLY(ctx))) - { - return; - } + if (!isInitialized(DD_EXPLICIT_CONTEXT_ONLY(ctx))) + { + return; + } - ddVec3 normalVec; - ddVec3 normalColor; + ddVec3 normalVec; + ddVec3 normalColor; - vecSet(normalColor, 1.0f, 1.0f, 1.0f); + vecSet(normalColor, 1.0f, 1.0f, 1.0f); - normalVec[X] = (normal[X] * length) + origin[X]; - normalVec[Y] = (normal[Y] * length) + origin[Y]; - normalVec[Z] = (normal[Z] * length) + origin[Z]; + normalVec[X] = (normal[X] * length) + origin[X]; + normalVec[Y] = (normal[Y] * length) + origin[Y]; + normalVec[Z] = (normal[Z] * length) + origin[Z]; - line(DD_EXPLICIT_CONTEXT_ONLY(ctx,) origin, normalVec, normalColor, durationMillis, depthEnabled); + line(DD_EXPLICIT_CONTEXT_ONLY(ctx,) origin, normalVec, normalColor, durationMillis, depthEnabled); } void tangentBasis(DD_EXPLICIT_CONTEXT_ONLY(ContextHandle ctx,) ddVec3_In origin, ddVec3_In normal, ddVec3_In tangent, - ddVec3_In bitangent, const float lengths, const int durationMillis, const bool depthEnabled) + ddVec3_In bitangent, const float lengths, const int durationMillis, const bool depthEnabled) { - if (!isInitialized(DD_EXPLICIT_CONTEXT_ONLY(ctx))) - { - return; - } + if (!isInitialized(DD_EXPLICIT_CONTEXT_ONLY(ctx))) + { + return; + } - ddVec3 cN, cT, cB; - ddVec3 vN, vT, vB; + ddVec3 cN, cT, cB; + ddVec3 vN, vT, vB; - vecSet(cN, 1.0f, 1.0f, 1.0f); // Vertex normals are WHITE - vecSet(cT, 1.0f, 1.0f, 0.0f); // Tangents are YELLOW - vecSet(cB, 1.0f, 0.0f, 1.0f); // Bi-tangents are MAGENTA + vecSet(cN, 1.0f, 1.0f, 1.0f); // Vertex normals are WHITE + vecSet(cT, 1.0f, 1.0f, 0.0f); // Tangents are YELLOW + vecSet(cB, 1.0f, 0.0f, 1.0f); // Bi-tangents are MAGENTA - vN[X] = (normal[X] * lengths) + origin[X]; - vN[Y] = (normal[Y] * lengths) + origin[Y]; - vN[Z] = (normal[Z] * lengths) + origin[Z]; + vN[X] = (normal[X] * lengths) + origin[X]; + vN[Y] = (normal[Y] * lengths) + origin[Y]; + vN[Z] = (normal[Z] * lengths) + origin[Z]; - vT[X] = (tangent[X] * lengths) + origin[X]; - vT[Y] = (tangent[Y] * lengths) + origin[Y]; - vT[Z] = (tangent[Z] * lengths) + origin[Z]; + vT[X] = (tangent[X] * lengths) + origin[X]; + vT[Y] = (tangent[Y] * lengths) + origin[Y]; + vT[Z] = (tangent[Z] * lengths) + origin[Z]; - vB[X] = (bitangent[X] * lengths) + origin[X]; - vB[Y] = (bitangent[Y] * lengths) + origin[Y]; - vB[Z] = (bitangent[Z] * lengths) + origin[Z]; + vB[X] = (bitangent[X] * lengths) + origin[X]; + vB[Y] = (bitangent[Y] * lengths) + origin[Y]; + vB[Z] = (bitangent[Z] * lengths) + origin[Z]; - line(DD_EXPLICIT_CONTEXT_ONLY(ctx,) origin, vN, cN, durationMillis, depthEnabled); - line(DD_EXPLICIT_CONTEXT_ONLY(ctx,) origin, vT, cT, durationMillis, depthEnabled); - line(DD_EXPLICIT_CONTEXT_ONLY(ctx,) origin, vB, cB, durationMillis, depthEnabled); + line(DD_EXPLICIT_CONTEXT_ONLY(ctx,) origin, vN, cN, durationMillis, depthEnabled); + line(DD_EXPLICIT_CONTEXT_ONLY(ctx,) origin, vT, cT, durationMillis, depthEnabled); + line(DD_EXPLICIT_CONTEXT_ONLY(ctx,) origin, vB, cB, durationMillis, depthEnabled); } void xzSquareGrid(DD_EXPLICIT_CONTEXT_ONLY(ContextHandle ctx,) const float mins, const float maxs, const float y, - const float step, ddVec3_In color, const int durationMillis, const bool depthEnabled) -{ - if (!isInitialized(DD_EXPLICIT_CONTEXT_ONLY(ctx))) - { - return; - } - - ddVec3 from, to; - for (float i = mins; i <= maxs; i += step) - { - // Horizontal line (along the X) - vecSet(from, mins, y, i); - vecSet(to, maxs, y, i); - line(DD_EXPLICIT_CONTEXT_ONLY(ctx,) from, to, color, durationMillis, depthEnabled); - - // Vertical line (along the Z) - vecSet(from, i, y, mins); - vecSet(to, i, y, maxs); - line(DD_EXPLICIT_CONTEXT_ONLY(ctx,) from, to, color, durationMillis, depthEnabled); - } + const float step, ddVec3_In color, const int durationMillis, const bool depthEnabled) +{ + if (!isInitialized(DD_EXPLICIT_CONTEXT_ONLY(ctx))) + { + return; + } + + ddVec3 from, to; + for (float i = mins; i <= maxs; i += step) + { + // Horizontal line (along the X) + vecSet(from, mins, y, i); + vecSet(to, maxs, y, i); + line(DD_EXPLICIT_CONTEXT_ONLY(ctx,) from, to, color, durationMillis, depthEnabled); + + // Vertical line (along the Z) + vecSet(from, i, y, mins); + vecSet(to, i, y, maxs); + line(DD_EXPLICIT_CONTEXT_ONLY(ctx,) from, to, color, durationMillis, depthEnabled); + } } // ======================================================== diff --git a/include/fggl/debug/impl/logging_fmt.hpp b/include/fggl/debug/impl/logging_fmt.hpp index 4f2224778e88b4c7ccadc284931effa951a41ea4..1c0fddbd36b5f252a7a0c2113c31b8ea34eb190c 100644 --- a/include/fggl/debug/impl/logging_fmt.hpp +++ b/include/fggl/debug/impl/logging_fmt.hpp @@ -44,35 +44,28 @@ namespace fggl::debug { constexpr std::string_view level_to_string(Level level) { switch (level) { - case Level::critical: - return "CRITICAL"; - case Level::error: - return "ERROR"; - case Level::warning: - return "WARNING"; - case Level::info: - return "INFO"; - case Level::debug: - return "DEBUG"; - case Level::trace: - return "TRACE"; - default: - return "UNKNOWN"; + case Level::critical: return "CRITICAL"; + case Level::error: return "ERROR"; + case Level::warning: return "WARNING"; + case Level::info: return "INFO"; + case Level::debug: return "DEBUG"; + case Level::trace: return "TRACE"; + default: return "UNKNOWN"; } } - inline void vlog(const char* file, int line, fmt::string_view format, fmt::format_args args) { + inline void vlog(const char *file, int line, fmt::string_view format, fmt::format_args args) { fmt::print("{}: {}", file, line); fmt::vprint(format, args); } - template <typename S, typename... Args> - void logf(const char* file, int line, const S& format, Args&&... args) { - vlog( file, line, format, fmt::make_args_checked<Args...>(format, args...)); + template<typename S, typename... Args> + void logf(const char *file, int line, const S &format, Args &&... args) { + vlog(file, line, format, fmt::make_args_checked<Args...>(format, args...)); } #define info_va(format, ...) \ - logf(__FILE__, __LINE__, FMT_STRING(format), __VA_ARGS__) + logf(__FILE__, __LINE__, FMT_STRING(format), __VA_ARGS__) template<typename ...T> void log(Level level, FmtType fmt, T &&...args) { diff --git a/include/fggl/debug/impl/logging_spdlog.hpp b/include/fggl/debug/impl/logging_spdlog.hpp index a108b8e133f7844bd6a186ae75c1a31746fd6903..056c74f902302c253bd027a34f372e4bd25e0c0f 100644 --- a/include/fggl/debug/impl/logging_spdlog.hpp +++ b/include/fggl/debug/impl/logging_spdlog.hpp @@ -34,60 +34,59 @@ namespace fggl::debug { * Logging levels */ enum class Level { - critical = spdlog::level::critical, - error = spdlog::level::err, - warning = spdlog::level::warn, - info = spdlog::level::info, - debug = spdlog::level::debug, - trace = spdlog::level::trace + critical = spdlog::level::critical, + error = spdlog::level::err, + warning = spdlog::level::warn, + info = spdlog::level::info, + debug = spdlog::level::debug, + trace = spdlog::level::trace }; template<typename ...T> - void error(const FmtType& fmt, T&& ...args) { + void error(const FmtType &fmt, T &&...args) { spdlog::error(fmt, args...); } template<typename ...T> - void warning(const FmtType& fmt, T&& ...args ){ + void warning(const FmtType &fmt, T &&...args) { spdlog::warn(fmt, args...); } template<typename ...T> - void info(const FmtType& fmt, T&& ...args ) { + void info(const FmtType &fmt, T &&...args) { spdlog::info(fmt, args...); } template<typename ...T> - void debug(const FmtType& fmt, T&& ...args ) { + void debug(const FmtType &fmt, T &&...args) { spdlog::debug(fmt, args...); } template<typename ...T> - void trace(const FmtType& fmt, T&& ...args ) { + void trace(const FmtType &fmt, T &&...args) { spdlog::trace(fmt, args...); } template<typename ...T> - void log(const FmtType& fmt, T&& ...args) { + void log(const FmtType &fmt, T &&...args) { spdlog::log(Level::info, fmt, args...); } template<typename ...T> - void log(Level level, const FmtType& fmt, T&& ...args) { + void log(Level level, const FmtType &fmt, T &&...args) { spdlog::log(level, fmt, args...); } class Logger { - public: - Logger(); + public: + Logger(); - template<typename ...Args> - void log(Level level, const FmtType& fmt, Args&& ...args) { - spdlog::log(level, fmt, args...); - } + template<typename ...Args> + void log(Level level, const FmtType &fmt, Args &&...args) { + spdlog::log(level, fmt, args...); + } }; } - #endif //FGGL_DEBUG_IMPL_LOGGING_SPDLOG_HPP diff --git a/include/fggl/debug/logging.hpp b/include/fggl/debug/logging.hpp index a146c9cc1d3cd1254ff8ab4e37a1c7e249a5738e..ef4955fc2ed8e70f7eac0b48cbcdb2ee5de0435c 100644 --- a/include/fggl/debug/logging.hpp +++ b/include/fggl/debug/logging.hpp @@ -27,25 +27,25 @@ namespace fggl::debug { enum class Level; template<typename ...T> - void error(FmtType fmt, T&& ...args); + void error(FmtType fmt, T &&...args); template<typename ...T> - void warning(FmtType fmt, T&& ...args ); + void warning(FmtType fmt, T &&...args); template<typename ...T> - void info(FmtType fmt, T&& ...args ); + void info(FmtType fmt, T &&...args); template<typename ...T> - void debug(FmtType fmt, T&& ...args ); + void debug(FmtType fmt, T &&...args); template<typename ...T> - void trace(FmtType fmt, T&& ...args ); + void trace(FmtType fmt, T &&...args); template<typename ...T> - void log(FmtType fmt, T&& ...args); + void log(FmtType fmt, T &&...args); template<typename ...T> - void log(Level level, FmtType fmt, T&& ...args); + void log(Level level, FmtType fmt, T &&...args); } #include "fggl/debug/impl/logging_fmt.hpp" diff --git a/include/fggl/display/glfw/module.hpp b/include/fggl/display/glfw/module.hpp index e4499dfc71d90685fdec72d6f85c570e21ed6b2e..8b0940f187ea4278c1a4c833261a3826eb67f993 100644 --- a/include/fggl/display/glfw/module.hpp +++ b/include/fggl/display/glfw/module.hpp @@ -28,7 +28,7 @@ namespace fggl::display { struct GLFW { - constexpr static const char* name = "fggl::display::glfw"; + constexpr static const char *name = "fggl::display::glfw"; constexpr static const std::array<modules::ModuleService, 1> provides = { WindowService::service }; @@ -37,10 +37,10 @@ namespace fggl::display { fggl::gfx::WindowGraphics::service }; - static bool factory(modules::ModuleService name, modules::Services& serviceManager); + static bool factory(modules::ModuleService name, modules::Services &serviceManager); }; - bool GLFW::factory(modules::ModuleService service, modules::Services& services) { + bool GLFW::factory(modules::ModuleService service, modules::Services &services) { if (service == WindowService::service) { auto input = services.get<input::Input>(); auto graphics = services.get<gfx::WindowGraphics>(); diff --git a/include/fggl/display/glfw/services.hpp b/include/fggl/display/glfw/services.hpp index 6661f0332b413b11ab938786360ace20c1d46594..71ca9f5813b98257b84b65323887df1624147d4d 100644 --- a/include/fggl/display/glfw/services.hpp +++ b/include/fggl/display/glfw/services.hpp @@ -29,10 +29,12 @@ namespace fggl::display::glfw { class WindowService : public display::WindowService { public: - explicit WindowService(std::shared_ptr<GlfwContext> context, gfx::WindowGraphics* gfx) : m_context(std::move(context)), m_gfx(gfx), m_windows() {} + explicit WindowService(std::shared_ptr<GlfwContext> context, gfx::WindowGraphics *gfx) + : m_context(std::move(context)), m_gfx(gfx), m_windows() {} + virtual ~WindowService() = default; - display::Window* create() override { + display::Window *create() override { m_windows.push_back(std::make_unique<Window>(m_context, m_gfx)); return m_windows.back().get(); } @@ -43,7 +45,7 @@ namespace fggl::display::glfw { private: std::shared_ptr<GlfwContext> m_context; - gfx::WindowGraphics* m_gfx; + gfx::WindowGraphics *m_gfx; std::vector<std::unique_ptr<Window>> m_windows; }; diff --git a/include/fggl/display/glfw/window.hpp b/include/fggl/display/glfw/window.hpp index d570298da159a29cf3e3c481d7e0bb6edf74680a..357fb9725110a40f756bfb07e51ae96f102e33e7 100644 --- a/include/fggl/display/glfw/window.hpp +++ b/include/fggl/display/glfw/window.hpp @@ -45,7 +45,7 @@ namespace fggl::display::glfw { class GlfwContext { public: - explicit GlfwContext(fggl::input::Input* input); + explicit GlfwContext(fggl::input::Input *input); ~GlfwContext(); void pollEvents(); @@ -77,7 +77,7 @@ namespace fggl::display::glfw { class Window : public display::Window { public: - explicit Window(std::shared_ptr<GlfwContext> context, gfx::WindowGraphics*); + explicit Window(std::shared_ptr<GlfwContext> context, gfx::WindowGraphics *); ~Window() override; Window(Window &) = delete; @@ -105,8 +105,8 @@ namespace fggl::display::glfw { inline void framesize(int width, int height) { m_framesize = math::vec2(width, height); - if ( m_graphics != nullptr ) { - m_graphics->resize( width, height ); + if (m_graphics != nullptr) { + m_graphics->resize(width, height); } } @@ -117,7 +117,7 @@ namespace fggl::display::glfw { return glfwWindowShouldClose(m_window); } - inline void setTitle(const char* title) override { + inline void setTitle(const char *title) override { assert(m_window != nullptr); glfwSetWindowTitle(m_window, title); } diff --git a/include/fggl/display/glfw/window_input.hpp b/include/fggl/display/glfw/window_input.hpp index 6fb7efbf6ed0effb2b531226567731228b8a9c74..2ace61ffc4044bda3c19ca7910e66744e07b59fb 100644 --- a/include/fggl/display/glfw/window_input.hpp +++ b/include/fggl/display/glfw/window_input.hpp @@ -44,7 +44,7 @@ namespace fggl::display::glfw { return *instance; } - inline void setup(input::Input* input) { + inline void setup(input::Input *input) { m_inputs = input; } @@ -95,7 +95,7 @@ namespace fggl::display::glfw { } private: - input::Input* m_inputs; + input::Input *m_inputs; }; diff --git a/include/fggl/display/window.hpp b/include/fggl/display/window.hpp index f044a5447a1d93f266afdf7aa04f1d30facd48a3..194ffaf3ace43819247b5ef43877afedfce13feb 100644 --- a/include/fggl/display/window.hpp +++ b/include/fggl/display/window.hpp @@ -51,7 +51,7 @@ namespace fggl::display { return *m_graphics; } - virtual void setTitle(const char* title) = 0; + virtual void setTitle(const char *title) = 0; virtual void setFullscreen(bool state) = 0; @@ -64,9 +64,10 @@ namespace fggl::display { class WindowService { public: - constexpr static const modules::ModuleService service = modules::make_service("fggl::display::WindowService"); + constexpr static const modules::ModuleService + service = modules::make_service("fggl::display::WindowService"); - virtual Window* create() = 0; + virtual Window *create() = 0; virtual void pollEvents() = 0; }; diff --git a/include/fggl/ds/placeholder.hpp b/include/fggl/ds/placeholder.hpp index a4623a19aa6eb40e99426466a82ac2a30b04873a..f241e746e2db24eb24a2a6b452e56a3b99a15df8 100644 --- a/include/fggl/ds/placeholder.hpp +++ b/include/fggl/ds/placeholder.hpp @@ -37,7 +37,7 @@ namespace fggl::ds { } WeakRef allocate() { - if ( N <= m_data.size() ) { + if (N <= m_data.size()) { assert(0 && "Fake slot map emulated out of space"); return BAD_INDEX; } @@ -50,13 +50,13 @@ namespace fggl::ds { m_data.erase(idx); } - T& get(WeakRef idx) const { - assert( valid(idx) ); + T &get(WeakRef idx) const { + assert(valid(idx)); return m_data[idx]; } - T* tryGet(WeakRef idx) const { - if( valid(idx) ) { + T *tryGet(WeakRef idx) const { + if (valid(idx)) { return &m_data[idx]; } return nullptr; @@ -67,7 +67,6 @@ namespace fggl::ds { std::size_t m_nextIdx = 1; }; - } // namespace fggl::ds #endif //FGGL_DS_PLACEHOLDER_HPP diff --git a/include/fggl/entity/entity.hpp b/include/fggl/entity/entity.hpp index 72d2d4a56a59ae1b65f4d9c12543b7252f7f0b32..b4a3d17940b8654622232148f06634952eab5abf 100644 --- a/include/fggl/entity/entity.hpp +++ b/include/fggl/entity/entity.hpp @@ -34,37 +34,38 @@ namespace fggl::entity { inline EntityID create() { return m_registry.create(); } + inline void destroy(EntityID entity) { m_registry.destroy(entity); } template<typename Component, typename... Args> - inline Component& add(EntityID entity, Args&&... args) { + inline Component &add(EntityID entity, Args &&... args) { return m_registry.emplace<Component>(entity, std::forward<Args>(args)...); } template<typename Component> - Component& get(EntityID entity) { + Component &get(EntityID entity) { #ifndef NDEBUG - if ( !has<Component>(entity) ) { - debug::error("Entity {} has no component of type {}", (uint64_t)entity, typeid(Component).name()); - } + if (!has<Component>(entity)) { + debug::error("Entity {} has no component of type {}", (uint64_t) entity, typeid(Component).name()); + } #endif return m_registry.get<Component>(entity); } template<typename Component> - const Component& get(EntityID entity) const { + const Component &get(EntityID entity) const { return m_registry.get<Component>(entity); } template<typename Component> - Component* tryGet(EntityID entity) { + Component *tryGet(EntityID entity) { return m_registry.try_get<Component>(entity); } template<typename Component> - const Component* tryGet(EntityID entity) const { + const Component *tryGet(EntityID entity) const { return m_registry.try_get<Component>(entity); } @@ -86,26 +87,25 @@ namespace fggl::entity { return m_registry.valid(idx); } - private: entt::registry m_registry; }; struct Entity { - static Entity make(EntityManager& manager, EntityID idx) { + static Entity make(EntityManager &manager, EntityID idx) { return Entity{idx, manager}; } EntityID id; - EntityManager& manager; + EntityManager &manager; template<typename Component> - Component& get() { + Component &get() { return manager.get<Component>(id); } template<typename Component> - const Component& get() const { + const Component &get() const { return manager.get<Component>(id); } }; diff --git a/include/fggl/entity/loader/loader.hpp b/include/fggl/entity/loader/loader.hpp index 598ee625477ff51c790f6b2bdf9bdcb09ac219be..cdcc10f50ac8af633af64055c30ec74dcdceb61e 100644 --- a/include/fggl/entity/loader/loader.hpp +++ b/include/fggl/entity/loader/loader.hpp @@ -32,8 +32,8 @@ namespace fggl::entity { constexpr auto PROTOTYPE_ASSET = assets::AssetType::make("entity_prototype"); - using FactoryFunc = std::function<void(const ComponentSpec& config, EntityManager&, const EntityID&)>; - using CustomiseFunc = std::function<void(EntityManager&, const EntityID&)>; + using FactoryFunc = std::function<void(const ComponentSpec &config, EntityManager &, const EntityID &)>; + using CustomiseFunc = std::function<void(EntityManager &, const EntityID &)>; struct FactoryInfo { FactoryFunc factory; @@ -44,14 +44,14 @@ namespace fggl::entity { public: constexpr static const modules::ModuleService service = modules::make_service("fggl::entity:Factory"); - EntityID create(const EntityType& spec, EntityManager& manager, const CustomiseFunc& customise = nullptr) { + EntityID create(const EntityType &spec, EntityManager &manager, const CustomiseFunc &customise = nullptr) { try { std::vector<CustomiseFunc> finishers; // set up the components for the entity auto entity = setupComponents(spec, manager, finishers); - if ( entity == entity::INVALID ) { - debug::error("Error attempting to create entity with type {}", std::to_string(spec.get()) ); + if (entity == entity::INVALID) { + debug::error("Error attempting to create entity with type {}", std::to_string(spec.get())); return entity::INVALID; } @@ -61,30 +61,32 @@ namespace fggl::entity { } // finally, we run any cleanup/init setups required by the component factories - for( auto& finisher : finishers ) { + for (auto &finisher : finishers) { finisher(manager, entity); } return entity; - } catch (std::out_of_range& ex) { + } catch (std::out_of_range &ex) { #ifndef NDEBUG - debug::log(debug::Level::error, "EntityFactory: Unknown entity type '{}'", fggl::util::guidToString(spec)); + debug::log(debug::Level::error, + "EntityFactory: Unknown entity type '{}'", + fggl::util::guidToString(spec)); #endif return fggl::entity::INVALID; } } - void define(EntityType type, const EntitySpec& spec) { + void define(EntityType type, const EntitySpec &spec) { m_prototypes[type] = spec; } // ability to set and unset factory functions - inline void bind(const ComponentID& configNode, FactoryFunc factory, CustomiseFunc finalise = nullptr) { + inline void bind(const ComponentID &configNode, FactoryFunc factory, CustomiseFunc finalise = nullptr) { m_factories[configNode].factory = std::move(factory); m_factories[configNode].finalise = std::move(finalise); } - inline void unbind(const ComponentID& configNode) { + inline void unbind(const ComponentID &configNode) { m_factories.erase(configNode); } @@ -92,33 +94,37 @@ namespace fggl::entity { std::map<ComponentID, FactoryInfo> m_factories; std::map<EntityType, EntitySpec> m_prototypes; - entity::EntityID setupComponents(EntityType entityType, EntityManager& manager, std::vector<CustomiseFunc>& finishers) { + entity::EntityID setupComponents(EntityType entityType, + EntityManager &manager, + std::vector<CustomiseFunc> &finishers) { auto entity = manager.create(); std::vector<ComponentID> loadedComps; auto currentType = entityType; - while ( currentType != NO_PARENT ) { - auto& entitySpec = m_prototypes.at(currentType); + while (currentType != NO_PARENT) { + auto &entitySpec = m_prototypes.at(currentType); - for ( auto& component : entitySpec.ordering ) { + for (auto &component : entitySpec.ordering) { // skip comps loaded by children if (std::find(loadedComps.begin(), loadedComps.end(), component) != loadedComps.end()) { continue; } try { - auto& data = getComponent(entitySpec, component); + auto &data = getComponent(entitySpec, component); loadedComps.push_back(component); - auto& info = m_factories.at(component); + auto &info = m_factories.at(component); info.factory(data, manager, entity); - if ( info.finalise != nullptr ) { + if (info.finalise != nullptr) { finishers.push_back(info.finalise); } - } catch (std::out_of_range& ex) { + } catch (std::out_of_range &ex) { #ifndef NDEBUG - debug::log(debug::Level::error, "EntityFactory: Unknown component factory type '{}'", fggl::util::guidToString(component)); + debug::log(debug::Level::error, + "EntityFactory: Unknown component factory type '{}'", + fggl::util::guidToString(component)); #endif manager.destroy(entity); return entity::INVALID; @@ -130,20 +136,20 @@ namespace fggl::entity { return entity; } - ComponentSpec& getComponent(EntitySpec& prototype, util::GUID compToken) { + ComponentSpec &getComponent(EntitySpec &prototype, util::GUID compToken) { auto compItr = prototype.components.find(compToken); - if ( compItr != prototype.components.end() ) { + if (compItr != prototype.components.end()) { return compItr->second; } - if ( prototype.parent == NO_PARENT ) { + if (prototype.parent == NO_PARENT) { throw std::out_of_range("EntityFactory: no such component!"); } return getComponent(m_prototypes.at(prototype.parent), compToken); } }; - assets::AssetRefRaw load_prototype(EntityFactory* factory, const assets::AssetGUID& guid, assets::AssetData data); + assets::AssetRefRaw load_prototype(EntityFactory *factory, const assets::AssetGUID &guid, assets::AssetData data); } // namespace fggl::entity diff --git a/include/fggl/entity/loader/serialise.hpp b/include/fggl/entity/loader/serialise.hpp index 85783c4c368e24ec932a225be57d7264f1f517d8..12d9b9f0276ac03851fc14bbda24f03cb4acdf79 100644 --- a/include/fggl/entity/loader/serialise.hpp +++ b/include/fggl/entity/loader/serialise.hpp @@ -29,7 +29,7 @@ namespace YAML { template<> struct convert<fggl::math::vec3> { - static Node encode(const fggl::math::vec3& rhs) { + static Node encode(const fggl::math::vec3 &rhs) { Node node; node.push_back(rhs.x); node.push_back(rhs.y); @@ -37,7 +37,7 @@ namespace YAML { return node; } - static bool decode(const Node& node, fggl::math::vec3& rhs) { + static bool decode(const Node &node, fggl::math::vec3 &rhs) { if (!node.IsSequence() || node.size() != 3) { return false; } @@ -51,14 +51,14 @@ namespace YAML { template<> struct convert<fggl::math::vec2> { - static Node encode(const fggl::math::vec2& rhs) { + static Node encode(const fggl::math::vec2 &rhs) { Node node; node.push_back(rhs.x); node.push_back(rhs.y); return node; } - static bool decode(const Node& node, fggl::math::vec2& rhs) { + static bool decode(const Node &node, fggl::math::vec2 &rhs) { if (!node.IsSequence() || node.size() != 2) { return false; } @@ -71,7 +71,7 @@ namespace YAML { template<> struct convert<fggl::data::Vertex> { - static Node encode(const fggl::data::Vertex& rhs) { + static Node encode(const fggl::data::Vertex &rhs) { Node node; node["position"] = rhs.posititon; node["normal"] = rhs.normal; @@ -80,7 +80,7 @@ namespace YAML { return node; } - static bool decode(const Node& node, fggl::data::Vertex& rhs) { + static bool decode(const Node &node, fggl::data::Vertex &rhs) { if (!node.IsSequence() || node.size() != 2) { return false; } @@ -95,31 +95,31 @@ namespace YAML { template<> struct convert<fggl::phys::BodyType> { - static Node encode(const fggl::phys::BodyType& rhs) { + static Node encode(const fggl::phys::BodyType &rhs) { Node node; - if ( rhs == fggl::phys::BodyType::STATIC ) { + if (rhs == fggl::phys::BodyType::STATIC) { node = "static"; - } else if ( rhs == fggl::phys::BodyType::DYNAMIC ) { + } else if (rhs == fggl::phys::BodyType::DYNAMIC) { node = "dynamic"; - } else if ( rhs == fggl::phys::BodyType::KINEMATIC ) { + } else if (rhs == fggl::phys::BodyType::KINEMATIC) { node = "kinematic"; } return node; } - static bool decode(const Node& node, fggl::phys::BodyType& rhs) { + static bool decode(const Node &node, fggl::phys::BodyType &rhs) { auto strVal = node.as<std::string>(); - if ( strVal == "static" ) { + if (strVal == "static") { rhs = fggl::phys::BodyType::STATIC; return true; } - if ( strVal == "dynamic" ) { + if (strVal == "dynamic") { rhs = fggl::phys::BodyType::DYNAMIC; return true; } - if ( strVal == "kinematic" ) { + if (strVal == "kinematic") { rhs = fggl::phys::BodyType::KINEMATIC; return true; } @@ -130,16 +130,16 @@ namespace YAML { template<> struct convert<fggl::util::GUID> { - static Node encode(const fggl::util::GUID& rhs) { + static Node encode(const fggl::util::GUID &rhs) { Node node; node = rhs.get(); return node; } - static bool decode(const Node& node, fggl::util::GUID& rhs) { + static bool decode(const Node &node, fggl::util::GUID &rhs) { auto longVal = node.as<uint64_t>(0); - if ( longVal == 0 ) { + if (longVal == 0) { // probably meant to hash it... auto stringVal = node.as<std::string>(); rhs = fggl::util::make_guid_rt(stringVal); diff --git a/include/fggl/entity/loader/spec.hpp b/include/fggl/entity/loader/spec.hpp index b5f50eed7f3fbcaababe86efef77ce6020aff4c6..e78ccfeac3785ab187b96af5d8f45f3f3df9997c 100644 --- a/include/fggl/entity/loader/spec.hpp +++ b/include/fggl/entity/loader/spec.hpp @@ -33,17 +33,17 @@ namespace fggl::entity { struct ComponentSpec { template<typename T> - T get(const std::string& key, const T& fallback) const { + T get(const std::string &key, const T &fallback) const { return config[key].template as<T>(fallback); } template<typename T> - void set(const std::string& key, const T& value) { + void set(const std::string &key, const T &value) { config[key] = value; } - inline bool has(const std::string& key) const { - return (bool)(config[key]); + inline bool has(const std::string &key) const { + return (bool) (config[key]); } YAML::Node config; diff --git a/include/fggl/entity/module.hpp b/include/fggl/entity/module.hpp index b5d66d2b93e50c3efa62263fb0eb830f1cba4a4f..6df19447ae75e2898d55e725dc8d79290767a903 100644 --- a/include/fggl/entity/module.hpp +++ b/include/fggl/entity/module.hpp @@ -27,18 +27,17 @@ namespace fggl::entity { struct ECS { - constexpr static const char* name = "fggl::entity::ECS"; + constexpr static const char *name = "fggl::entity::ECS"; constexpr static const std::array<modules::ModuleService, 1> provides = { EntityFactory::service }; constexpr static const std::array<modules::ModuleService, 1> depends = { assets::Loader::service }; - static bool factory(modules::ModuleService name, modules::Services& serviceManager); + static bool factory(modules::ModuleService name, modules::Services &serviceManager); }; - void install_component_factories(EntityFactory* factory); - + void install_component_factories(EntityFactory *factory); } // namespace fggl::entity diff --git a/include/fggl/gfx/camera.hpp b/include/fggl/gfx/camera.hpp index 0968899ecbe1dce006040c713d9224f9d7290d50..8a14da3776a3c467bbcfe085ddd18a30ab389230 100644 --- a/include/fggl/gfx/camera.hpp +++ b/include/fggl/gfx/camera.hpp @@ -29,34 +29,36 @@ namespace fggl::gfx { float farPlane = 100.0f; }; - inline math::mat4 calc_proj_matrix(const Camera& camera) { + inline math::mat4 calc_proj_matrix(const Camera &camera) { return glm::perspective(camera.fov, camera.aspectRatio, camera.nearPlane, camera.farPlane); } - inline math::Ray get_camera_ray(const entity::EntityManager& world, const entity::EntityID camera, math::vec2 position) { - auto& camTransform = world.get<fggl::math::Transform>(camera); - auto& camComp = world.get<fggl::gfx::Camera>(camera); + inline math::Ray get_camera_ray(const entity::EntityManager &world, + const entity::EntityID camera, + math::vec2 position) { + auto &camTransform = world.get<fggl::math::Transform>(camera); + auto &camComp = world.get<fggl::gfx::Camera>(camera); const auto projMatrix = fggl::gfx::calc_proj_matrix(camComp); const auto viewMatrix = fggl::math::calc_view_matrix(camTransform); - glm::vec4 startNDC { + glm::vec4 startNDC{ position.x, position.y, -1.0f, 1.0f }; - glm::vec4 endNDC { + glm::vec4 endNDC{ position.x, position.y, 0.0f, 1.0f }; - fggl::math::mat4 M = glm::inverse( projMatrix * viewMatrix ); + fggl::math::mat4 M = glm::inverse(projMatrix * viewMatrix); glm::vec3 start = M * startNDC; glm::vec3 end = M * endNDC; - return { start, glm::normalize(end - start) }; + return {start, glm::normalize(end - start)}; } }; diff --git a/include/fggl/gfx/interfaces.hpp b/include/fggl/gfx/interfaces.hpp index 2e22ed15adfdc23a4e9cb37bf48f5efb4f1a28a4..52150c2bd771bc442e8cc989feacafaa161340b0 100644 --- a/include/fggl/gfx/interfaces.hpp +++ b/include/fggl/gfx/interfaces.hpp @@ -43,10 +43,9 @@ namespace fggl::gfx { virtual Bounds canvasBounds() = 0; virtual void draw2D(const Paint &paint) = 0; - virtual void drawScene(entity::EntityManager&) = 0; + virtual void drawScene(entity::EntityManager &) = 0; }; - } // namespace fggl::gfx #endif //FGGL_GFX_INTERFACES_HPP diff --git a/include/fggl/gfx/ogl/common.hpp b/include/fggl/gfx/ogl/common.hpp index b58e8a1180530af6a473dc1c1952d2c0d4ee9461..059052c181184ace20e40c0ad749f212dba17164 100644 --- a/include/fggl/gfx/ogl/common.hpp +++ b/include/fggl/gfx/ogl/common.hpp @@ -24,6 +24,7 @@ #endif #include <glad/glad.h> -typedef void* (* GLADloadproc)(const char *name); + +typedef void *(*GLADloadproc)(const char *name); #endif diff --git a/include/fggl/gfx/ogl/renderer.hpp b/include/fggl/gfx/ogl/renderer.hpp index 4b5311e30281d651c41adb261f240b2d544f3af8..3928154eb57adf25d5d3c67f21a95aa57e72e8c4 100644 --- a/include/fggl/gfx/ogl/renderer.hpp +++ b/include/fggl/gfx/ogl/renderer.hpp @@ -55,16 +55,16 @@ namespace fggl::gfx { */ class OpenGL4Backend : public Graphics { public: - explicit OpenGL4Backend(data::Storage* storage, gui::FontLibrary* fonts); + explicit OpenGL4Backend(data::Storage *storage, gui::FontLibrary *fonts); ~OpenGL4Backend() override = default; // copy bad - OpenGL4Backend(const OpenGL4Backend&) = delete; - OpenGL4Backend& operator=(const OpenGL4Backend&) = delete; + OpenGL4Backend(const OpenGL4Backend &) = delete; + OpenGL4Backend &operator=(const OpenGL4Backend &) = delete; // move (probably) bad - OpenGL4Backend(OpenGL4Backend&&) = delete; - OpenGL4Backend&& operator=(OpenGL4Backend&&) = delete; + OpenGL4Backend(OpenGL4Backend &&) = delete; + OpenGL4Backend &&operator=(OpenGL4Backend &&) = delete; /** * Clear the backing buffer. @@ -91,7 +91,7 @@ namespace fggl::gfx { * * @param world the world to render */ - void drawScene(entity::EntityManager& world) override; + void drawScene(entity::EntityManager &world) override; /** * Get the 2D canvas bounds. @@ -108,8 +108,8 @@ namespace fggl::gfx { std::unique_ptr<ogl4::DebugRenderer> m_debugRenderer; std::unique_ptr<ShaderCache> m_cache; GLuint m_canvasPipeline; - data::Storage* m_storage; - gui::FontLibrary* m_fontLibrary; + data::Storage *m_storage; + gui::FontLibrary *m_fontLibrary; }; }; // namespace fggl::gfx diff --git a/include/fggl/gfx/ogl/shader.hpp b/include/fggl/gfx/ogl/shader.hpp index f1fef1f8dc68b18188dd43a2795f37f32b9a5633..5ac1877938a85bbcb13cff0a95f99d9b62d43e81 100644 --- a/include/fggl/gfx/ogl/shader.hpp +++ b/include/fggl/gfx/ogl/shader.hpp @@ -37,7 +37,7 @@ namespace fggl::gfx { std::string geometry; bool hasGeom = false; - constexpr static ShaderConfig named(const std::string& name, bool hasGeom = false) { + constexpr static ShaderConfig named(const std::string &name, bool hasGeom = false) { return { .name = name, .vertex = name + "_vert.glsl", @@ -63,7 +63,7 @@ namespace fggl::gfx { class ShaderCache { public: - ShaderCache(fggl::data::Storage* storage); + ShaderCache(fggl::data::Storage *storage); ~ShaderCache() = default; GLuint load(const ShaderConfig &config); @@ -89,8 +89,8 @@ namespace fggl::gfx { void setupIncludes(); // opengl operations - bool readAndCompileShader(const std::string& filename, GLuint shader); - bool compileShaderFromSource(const std::string& source, GLuint); + bool readAndCompileShader(const std::string &filename, GLuint shader); + bool compileShaderFromSource(const std::string &source, GLuint); // file io operations bool loadFromDisk(GLuint pid, const std::string &pipelineName); diff --git a/include/fggl/gfx/ogl/types.hpp b/include/fggl/gfx/ogl/types.hpp index aefb536be486e0f239ae69f8e8d072405720c1b8..832cda43d569adaacf114ca0f43311dc4ad66a64 100644 --- a/include/fggl/gfx/ogl/types.hpp +++ b/include/fggl/gfx/ogl/types.hpp @@ -45,28 +45,29 @@ namespace fggl::gfx::ogl { public: Shader() = default; + inline Shader(GLuint obj) : m_obj(obj) {} // copy constructor bad - Shader(const Shader&) = delete; - Shader& operator=(const Shader&) = delete; + Shader(const Shader &) = delete; + Shader &operator=(const Shader &) = delete; // Move ok - if handled properly - Shader(Shader&& other); - Shader& operator=(Shader&& other); + Shader(Shader &&other); + Shader &operator=(Shader &&other); void use() { - glUseProgram( m_obj ); + glUseProgram(m_obj); } - inline bool hasUniform(const std::string_view& name) const { - auto location = glGetUniformLocation( m_obj, name.data() ); + inline bool hasUniform(const std::string_view &name) const { + auto location = glGetUniformLocation(m_obj, name.data()); return location != -1; } - inline Location uniform(const std::string_view& name) const { - auto location = glGetUniformLocation( m_obj, name.data() ); - if ( location == -1 ) { + inline Location uniform(const std::string_view &name) const { + auto location = glGetUniformLocation(m_obj, name.data()); + if (location == -1) { std::cerr << "error: " << name << " does not exist" << std::endl; } return location; @@ -76,6 +77,7 @@ namespace fggl::gfx::ogl { inline void setUniformF(Location name, GLfloat value) { glProgramUniform1f(m_obj, name, value); } + inline void setUniformI(Location name, GLint value) { glProgramUniform1i(m_obj, name, value); } @@ -85,15 +87,15 @@ namespace fggl::gfx::ogl { } // vector versions (float) - inline void setUniformF(Location name, const math::vec2f& value) { + inline void setUniformF(Location name, const math::vec2f &value) { glProgramUniform2f(m_obj, name, value.x, value.y); } - inline void setUniformF(Location name, const math::vec3f& value) { + inline void setUniformF(Location name, const math::vec3f &value) { glProgramUniform3f(m_obj, name, value.x, value.y, value.z); } - inline void setUniformF(Location name, const math::vec4f& value) { + inline void setUniformF(Location name, const math::vec4f &value) { glProgramUniform4f(m_obj, name, value.x, value.y, value.z, value.w); } @@ -111,15 +113,15 @@ namespace fggl::gfx::ogl { } // matrix versions - inline void setUniformMtx(Location name, const math::mat2& mtx) { + inline void setUniformMtx(Location name, const math::mat2 &mtx) { glProgramUniformMatrix2fv(m_obj, name, 1, GL_FALSE, glm::value_ptr(mtx)); } - void setUniformMtx(Location name, const math::mat3& mtx) { + void setUniformMtx(Location name, const math::mat3 &mtx) { glProgramUniformMatrix3fv(m_obj, name, 1, GL_FALSE, glm::value_ptr(mtx)); } - void setUniformMtx(Location name, const math::mat4& mtx) { + void setUniformMtx(Location name, const math::mat4 &mtx) { glProgramUniformMatrix4fv(m_obj, name, 1, GL_FALSE, glm::value_ptr(mtx)); } }; @@ -165,61 +167,61 @@ namespace fggl::gfx::ogl { }; enum class PixelFormat { - UNSIGNED_BYTE = GL_UNSIGNED_BYTE, - BYTE, - UNSIGNED_SHORT, - SHORT, - UNSIGNED_INT, - INT, - HALF_FLOAT, - FLOAT, - - UNSIGNED_BYTE_3_3_2, - UNSIGNED_BYTE_2_3_3_REV, - UNSIGNED_SHORT_5_6_5, - UNSIGNED_SHORT_5_6_5_REV, - UNSINGED_SHORT_4_4_4_4, - UNSIGNED_SHORT_4_4_4_4_REV, - UNSIGNED_SHORT_5_5_5_1, - UNSIGNED_SHORT_1_5_5_5_REV, - UNSIGNED_INT_8_8_8_8, - UNSIGNED_INT_8_8_8_8_REV, - UNSIGNED_INT_10_10_10_10_2, - UNSIGNED_INT_10_10_10_10_2_REV, + UNSIGNED_BYTE = GL_UNSIGNED_BYTE, + BYTE, + UNSIGNED_SHORT, + SHORT, + UNSIGNED_INT, + INT, + HALF_FLOAT, + FLOAT, + + UNSIGNED_BYTE_3_3_2, + UNSIGNED_BYTE_2_3_3_REV, + UNSIGNED_SHORT_5_6_5, + UNSIGNED_SHORT_5_6_5_REV, + UNSINGED_SHORT_4_4_4_4, + UNSIGNED_SHORT_4_4_4_4_REV, + UNSIGNED_SHORT_5_5_5_1, + UNSIGNED_SHORT_1_5_5_5_REV, + UNSIGNED_INT_8_8_8_8, + UNSIGNED_INT_8_8_8_8_REV, + UNSIGNED_INT_10_10_10_10_2, + UNSIGNED_INT_10_10_10_10_2_REV, }; enum class InternalImageFormat { - DepthComponent = GL_DEPTH_COMPONENT, - DepthStencil = GL_DEPTH_STENCIL, - Red = GL_RED, - RedGreen = GL_RG, - RedGreenBlue = GL_RGB, - RedGreenBlueAlpha = GL_RGBA + DepthComponent = GL_DEPTH_COMPONENT, + DepthStencil = GL_DEPTH_STENCIL, + Red = GL_RED, + RedGreen = GL_RG, + RedGreenBlue = GL_RGB, + RedGreenBlueAlpha = GL_RGBA }; enum class ImageFormat { - R = GL_RED, - RG, - RGB, - RGBA, - R_INT, - RG_INT, - RGB_INT, - RGBA_INT, - BGR, - BGRA, - BGR_INT, - BGRA_INT, - STENTICL_INDEX, - DEPTH_COMPONENT, - DEPTH_STENCIL + R = GL_RED, + RG, + RGB, + RGBA, + R_INT, + RG_INT, + RGB_INT, + RGBA_INT, + BGR, + BGRA, + BGR_INT, + BGRA_INT, + STENTICL_INDEX, + DEPTH_COMPONENT, + DEPTH_STENCIL }; struct Image { PixelFormat type; ImageFormat format; math::vec2i size; - void* data; + void *data; }; class Texture { @@ -227,30 +229,55 @@ namespace fggl::gfx::ogl { inline explicit Texture(TextureType type) : m_type(type) { glGenTextures(1, &m_obj); } + ~Texture() { glDeleteTextures(1, &m_obj); } void setup(InternalImageFormat iFmt, math::vec2i size) { //bind(); - glBindTexture( (GLenum)m_type, m_obj ); - if ( iFmt == InternalImageFormat::DepthComponent ) { + glBindTexture((GLenum) m_type, m_obj); + if (iFmt == InternalImageFormat::DepthComponent) { glTexImage2D((GLenum) - m_type, 0, (GLint) iFmt, size.x, size.y, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE, nullptr); + m_type, + 0, + (GLint) iFmt, + size.x, + size.y, + 0, + GL_DEPTH_COMPONENT, + GL_UNSIGNED_BYTE, + nullptr); } else { glTexImage2D((GLenum) - m_type, 0, (GLint) iFmt, size.x, size.y, 0, GL_RGB, GL_UNSIGNED_BYTE, nullptr); + m_type, 0, (GLint) iFmt, size.x, size.y, 0, GL_RGB, GL_UNSIGNED_BYTE, nullptr); } } - void setData(InternalImageFormat iFmt, Image& image) { + void setData(InternalImageFormat iFmt, Image &image) { //bind(); - glBindTexture( (GLenum)m_type, m_obj ); - glTexImage2D( (GLenum)m_type, 0, (GLint)iFmt, image.size.x, image.size.y, 0, (GLenum)image.format, (GLenum)image.type, image.data); + glBindTexture((GLenum) m_type, m_obj); + glTexImage2D((GLenum) m_type, + 0, + (GLint) iFmt, + image.size.x, + image.size.y, + 0, + (GLenum) image.format, + (GLenum) image.type, + image.data); } - void setDataPart(math::vec2i offset, Image& image) { - glTexImage2D( (GLenum)m_type, 0, offset.x, offset.y, image.size.x, image.size.y, (GLenum)image.format, (GLenum)image.type, image.data); + void setDataPart(math::vec2i offset, Image &image) { + glTexImage2D((GLenum) m_type, + 0, + offset.x, + offset.y, + image.size.x, + image.size.y, + (GLenum) image.format, + (GLenum) image.type, + image.data); } void wrapMode(Wrapping wrap); @@ -263,9 +290,9 @@ namespace fggl::gfx::ogl { * @param textureUnit the texture unit to bind to */ inline void bind(unsigned int textureUnit) { - assert( textureUnit < GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS ); - glActiveTexture( GL_TEXTURE0 + textureUnit ); - glBindTexture( (GLenum) m_type, m_obj ); + assert(textureUnit < GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS); + glActiveTexture(GL_TEXTURE0 + textureUnit); + glBindTexture((GLenum) m_type, m_obj); } private: @@ -282,7 +309,7 @@ namespace fggl::gfx::ogl { FIXED = GL_FIXED }; - enum class BuffAttrI{ + enum class BuffAttrI { BYTE = GL_BYTE, UBYTE = GL_UNSIGNED_BYTE, SHORT = GL_SHORT, @@ -365,51 +392,51 @@ namespace fggl::gfx::ogl { } // copy constructor bad - Buffer(const Buffer&) = delete; - Buffer& operator=(const Buffer&) = delete; + Buffer(const Buffer &) = delete; + Buffer &operator=(const Buffer &) = delete; - Buffer(Buffer&& other) : m_obj(other.m_obj), m_capacity(other.m_capacity) { + Buffer(Buffer &&other) : m_obj(other.m_obj), m_capacity(other.m_capacity) { other.obj_ = 0; other.m_capacity = 0; } - Buffer& operator=(Buffer&& other) { - if ( this != &other) { + Buffer &operator=(Buffer &&other) { + if (this != &other) { release(); - std::swap( m_obj, other.m_obj ); - std::swap( m_capacity, other.m_capacity ); + std::swap(m_obj, other.m_obj); + std::swap(m_capacity, other.m_capacity); } } void bind() const { - assert( m_obj != 0 ); - glBindBuffer( (GLenum)T, m_obj ); + assert(m_obj != 0); + glBindBuffer((GLenum) T, m_obj); } inline bool isValid() const { return m_obj != 0; }; - void write(GLsizeiptr size, const GLvoid* data, BufUsage usage) { + void write(GLsizeiptr size, const GLvoid *data, BufUsage usage) { bind(); - glBufferData( (GLenum)T, size, data, (GLenum)usage); + glBufferData((GLenum) T, size, data, (GLenum) usage); } - void update(GLintptr offset, GLsizeiptr size, const void* data) { + void update(GLintptr offset, GLsizeiptr size, const void *data) { } template<typename D> - void replace(std::size_t size, const D* data) { + void replace(std::size_t size, const D *data) { bind(); GLsizeiptr sizePtr = size * sizeof(D); - if ( sizePtr > m_capacity) { - glBufferData( (GLenum)T, sizePtr, data, GL_STREAM_DRAW ); + if (sizePtr > m_capacity) { + glBufferData((GLenum) T, sizePtr, data, GL_STREAM_DRAW); m_capacity = sizePtr; } else { - glBufferSubData((GLenum)T, 0, sizePtr, data); + glBufferSubData((GLenum) T, 0, sizePtr, data); } - glBindBuffer( (GLenum)T, 0 ); + glBindBuffer((GLenum) T, 0); } }; @@ -434,7 +461,7 @@ namespace fggl::gfx::ogl { // type intrincs to make interface nicer template<typename T> - struct attr_type{ + struct attr_type { const static BuffAttrF attr; const static GLint size; }; @@ -465,32 +492,32 @@ namespace fggl::gfx::ogl { ~VertexArray(); // copy constructors bad - VertexArray(const VertexArray&) = delete; - VertexArray& operator=(const VertexArray) = delete; + VertexArray(const VertexArray &) = delete; + VertexArray &operator=(const VertexArray) = delete; // move constructors might be ok - VertexArray(VertexArray&& other) noexcept; - VertexArray& operator=(VertexArray&& other); + VertexArray(VertexArray &&other) noexcept; + VertexArray &operator=(VertexArray &&other); inline void bind() const { - assert( m_obj != 0); - glBindVertexArray( m_obj ); + assert(m_obj != 0); + glBindVertexArray(m_obj); } - void setAttribute(const ArrayBuffer& buffer, GLuint idx, AttributeF& attr); - void setAttribute(const ArrayBuffer& buffer, GLuint idx, AttributeI& attr, bool normalized); - void setAttributeI(const ArrayBuffer& buffer, GLuint idx, AttributeI& attr); + void setAttribute(const ArrayBuffer &buffer, GLuint idx, AttributeF &attr); + void setAttribute(const ArrayBuffer &buffer, GLuint idx, AttributeI &attr, bool normalized); + void setAttributeI(const ArrayBuffer &buffer, GLuint idx, AttributeI &attr); - void drawElements(const ElementBuffer& buff, Primative drawType, std::size_t size); + void drawElements(const ElementBuffer &buff, Primative drawType, std::size_t size); void draw(Primative drawType, int first, std::size_t count); }; // paranoid functions - void bind_vertex_array(GLuint& marker); - void unbind_vertex_array(GLuint& marker); + void bind_vertex_array(GLuint &marker); + void unbind_vertex_array(GLuint &marker); template<BufType T> - void bind_buffer(GLuint* marker, const Buffer<T>& buff) { + void bind_buffer(GLuint *marker, const Buffer<T> &buff) { #ifdef FGGL_GL_PARANOID assert( marker != nullptr ); glGetIntegerv( (GLenum)T, (GLint*) marker ); @@ -499,7 +526,7 @@ namespace fggl::gfx::ogl { } template<BufType T> - void unbind_buffer(GLuint* marker, const Buffer<T>& buff) { + void unbind_buffer(GLuint *marker, const Buffer<T> &buff) { #ifdef GL_FGGL_PARANOID assert( marker != nullptr ); glBindVertexArray(marker); diff --git a/include/fggl/gfx/ogl4/canvas.hpp b/include/fggl/gfx/ogl4/canvas.hpp index 74a9c477426ddbbc80c291d9f09515f2f9ec910c..f546a0affcb85e239cfecbcd6f069a7b1d17bb68 100644 --- a/include/fggl/gfx/ogl4/canvas.hpp +++ b/include/fggl/gfx/ogl4/canvas.hpp @@ -29,8 +29,8 @@ namespace fggl::gfx::ogl4 { class CanvasRenderer { public: - CanvasRenderer(gui::FontLibrary* fonts); - void render(GLuint shader, const gfx::Paint& paint); + CanvasRenderer(gui::FontLibrary *fonts); + void render(GLuint shader, const gfx::Paint &paint); inline gfx::Bounds bounds() const { return m_bounds; @@ -41,11 +41,11 @@ namespace fggl::gfx::ogl4 { ogl::VertexArray m_vao; ogl::ArrayBuffer m_vertexList; ogl::ElementBuffer m_indexList; - gui::FontLibrary* m_fonts; + gui::FontLibrary *m_fonts; ogl::Texture m_fontTex; void renderShapes(const Paint &paint, GLuint shader); - void renderText(const Paint&, GLuint shader); + void renderText(const Paint &, GLuint shader); }; } // namespace fggl::gfx::ogl4 diff --git a/include/fggl/gfx/ogl4/debug.hpp b/include/fggl/gfx/ogl4/debug.hpp index 36647e4ddf4088a708c350ece40dec670da5882c..b4b1f19fa5b4c1c24e2ae0161831d9447746c3df 100644 --- a/include/fggl/gfx/ogl4/debug.hpp +++ b/include/fggl/gfx/ogl4/debug.hpp @@ -27,7 +27,7 @@ namespace fggl::gfx::ogl4 { public: explicit DebugRenderer(GLuint shader); ~DebugRenderer() override = default; - void drawLineList(const dd::DrawVertex * lines, int count, bool depthEnabled) override; + void drawLineList(const dd::DrawVertex *lines, int count, bool depthEnabled) override; math::mat4 mvpMatrix; private: diff --git a/include/fggl/gfx/ogl4/fallback.hpp b/include/fggl/gfx/ogl4/fallback.hpp index b2fe7e444319bb30ce528690d31d18c36128031c..ff37beb066b05318b23aa9b98190a6d36d31c86b 100644 --- a/include/fggl/gfx/ogl4/fallback.hpp +++ b/include/fggl/gfx/ogl4/fallback.hpp @@ -26,9 +26,9 @@ */ namespace fggl::gfx::ogl4 { - constexpr const char* FALLBACK_CANVAS_PIPELINE = "fallback_canvas"; + constexpr const char *FALLBACK_CANVAS_PIPELINE = "fallback_canvas"; - constexpr const char* FALLBACK_CANVAS_VERTEX_SHADER = R"glsl( + constexpr const char *FALLBACK_CANVAS_VERTEX_SHADER = R"glsl( #version 330 core layout (location = 0) in vec2 aPos; layout (location = 1) in vec3 aColour; @@ -45,7 +45,7 @@ namespace fggl::gfx::ogl4 { texPos = aTexPos; })glsl"; - constexpr const char* FALLBACK_CANVAS_FRAGMENT_SHADER = R"glsl( + constexpr const char *FALLBACK_CANVAS_FRAGMENT_SHADER = R"glsl( #version 330 core uniform sampler2D tex; diff --git a/include/fggl/gfx/ogl4/models.hpp b/include/fggl/gfx/ogl4/models.hpp index 1a722430ce5d49f5c6436cd1090950d61589b363..ec12ed03746c526df8a903fa640756c069c888b7 100644 --- a/include/fggl/gfx/ogl4/models.hpp +++ b/include/fggl/gfx/ogl4/models.hpp @@ -47,18 +47,20 @@ namespace fggl::gfx::ogl4 { class StaticModelRenderer { public: - inline StaticModelRenderer(gfx::ShaderCache* cache) : m_shaders(cache), m_phong(nullptr), m_vao(), m_vertexList(), m_indexList() { - m_phong = std::make_shared<ogl::Shader>( cache->get("phong") ); + inline StaticModelRenderer(gfx::ShaderCache *cache) + : m_shaders(cache), m_phong(nullptr), m_vao(), m_vertexList(), m_indexList() { + m_phong = std::make_shared<ogl::Shader>(cache->get("phong")); } + ~StaticModelRenderer() = default; - StaticModelRenderer(const StaticModelRenderer& other) = delete; - StaticModelRenderer(StaticModelRenderer&& other) = delete; + StaticModelRenderer(const StaticModelRenderer &other) = delete; + StaticModelRenderer(StaticModelRenderer &&other) = delete; - StaticModelRenderer& operator=(const StaticModelRenderer& other) = delete; - StaticModelRenderer& operator=(StaticModelRenderer&& other) = delete; + StaticModelRenderer &operator=(const StaticModelRenderer &other) = delete; + StaticModelRenderer &operator=(StaticModelRenderer &&other) = delete; - void render(entity::EntityManager& world) { + void render(entity::EntityManager &world) { resolveModels(world); renderModelsForward(world); } @@ -67,15 +69,15 @@ namespace fggl::gfx::ogl4 { /** * Attach any missing rendering components to models. */ - void resolveModels(entity::EntityManager& world); + void resolveModels(entity::EntityManager &world); /** * Render all visible objects according to their render tokens. */ - void renderModelsForward(const entity::EntityManager& world); + void renderModelsForward(const entity::EntityManager &world); - gfx::ShaderCache* m_shaders; - std::shared_ptr< ogl::Shader > m_phong; + gfx::ShaderCache *m_shaders; + std::shared_ptr<ogl::Shader> m_phong; ogl::VertexArray m_vao; ogl::ArrayBuffer m_vertexList; ogl::ElementBuffer m_indexList; diff --git a/include/fggl/gfx/ogl4/module.hpp b/include/fggl/gfx/ogl4/module.hpp index 7bd50ca18f3f9e58499a8b3a7b14fe3a44f34dc4..47d1dfacf36f82704eafeadf13b4d1babfc4293c 100644 --- a/include/fggl/gfx/ogl4/module.hpp +++ b/include/fggl/gfx/ogl4/module.hpp @@ -32,7 +32,7 @@ namespace fggl::gfx { struct OpenGL4 { - constexpr static const char* name = "fggl::gfx::OpenGL4"; + constexpr static const char *name = "fggl::gfx::OpenGL4"; constexpr static const std::array<modules::ModuleService, 1> provides = { WindowGraphics::service }; @@ -42,7 +42,7 @@ namespace fggl::gfx { entity::EntityFactory::service }; - static bool factory(modules::ModuleService name, modules::Services& serviceManager); + static bool factory(modules::ModuleService name, modules::Services &serviceManager); }; } //namespace fggl::gfx diff --git a/include/fggl/gfx/ogl4/setup.hpp b/include/fggl/gfx/ogl4/setup.hpp index 9c0f64d766383dac31da418ffdad1c57fc10a113..d6ab931b0c9b29ae76d490bca3b35daa07211580 100644 --- a/include/fggl/gfx/ogl4/setup.hpp +++ b/include/fggl/gfx/ogl4/setup.hpp @@ -24,7 +24,7 @@ namespace fggl::gfx::ogl4 { - constexpr GraphicsDetails openGL4Details { + constexpr GraphicsDetails openGL4Details{ GraphicsAPI::OpenGL, 4, 3, @@ -33,21 +33,21 @@ namespace fggl::gfx::ogl4 { class WindowGraphics : public gfx::WindowGraphics { public: - WindowGraphics(data::Storage* storage, gui::FontLibrary* fonts) : m_storage(storage), m_fonts(fonts) {}; + WindowGraphics(data::Storage *storage, gui::FontLibrary *fonts) : m_storage(storage), m_fonts(fonts) {}; virtual ~WindowGraphics() = default; - fggl::gfx::Graphics* create(display::Window& window) override; + fggl::gfx::Graphics *create(display::Window &window) override; [[nodiscard]] inline GraphicsDetails config() const override { return openGL4Details; } + private: - data::Storage* m_storage; - gui::FontLibrary* m_fonts; + data::Storage *m_storage; + gui::FontLibrary *m_fonts; }; - } // namespace fggl::gfx::ogl4 #endif //FGGL_GFX_OGL4_SETUP_HPP diff --git a/include/fggl/gfx/paint.hpp b/include/fggl/gfx/paint.hpp index fe8dbfe8ae8aad49e3adb9af63311dbd64b686bb..58d94c604bc8f6738ef229eb2c41471e210705ae 100644 --- a/include/fggl/gfx/paint.hpp +++ b/include/fggl/gfx/paint.hpp @@ -103,7 +103,7 @@ namespace fggl::gfx { return m_cmds; } - const std::vector<TextCmd>& textCmds() const { + const std::vector<TextCmd> &textCmds() const { return m_text; } diff --git a/include/fggl/gfx/phong.hpp b/include/fggl/gfx/phong.hpp index 0dc5f822d9f32cfabe5c4d54344e7194758a403e..e0852eec4e21727b6e472dc82592ad542d38af58 100644 --- a/include/fggl/gfx/phong.hpp +++ b/include/fggl/gfx/phong.hpp @@ -25,7 +25,7 @@ namespace fggl::gfx { struct PhongMaterial { - constexpr static const char* name = "gfx::material"; + constexpr static const char *name = "gfx::material"; constexpr static const util::GUID guid = util::make_guid("gfx::material"); math::vec3 emission; math::vec3 ambient; @@ -34,14 +34,14 @@ namespace fggl::gfx { float shininess; }; - constexpr math::vec3 DEFAULT_EMISSION {0.0F, 0.0F, 0.0F}; - constexpr math::vec3 DEFAULT_AMBIENT { 0.05F, 0.05F, 0.05F}; - constexpr math::vec3 DEFAULT_DIFFUSE { 0.5F, 0.5F, 0.5F}; - constexpr math::vec3 DEFAULT_SPECULAR { 0.7F, 0.7F, 0.7F}; + constexpr math::vec3 DEFAULT_EMISSION{0.0F, 0.0F, 0.0F}; + constexpr math::vec3 DEFAULT_AMBIENT{0.05F, 0.05F, 0.05F}; + constexpr math::vec3 DEFAULT_DIFFUSE{0.5F, 0.5F, 0.5F}; + constexpr math::vec3 DEFAULT_SPECULAR{0.7F, 0.7F, 0.7F}; //constexpr float DEFAULT_SHININESS = .078125F; constexpr float DEFAULT_SHININESS = 16.0F; - constexpr PhongMaterial DEFAULT_MATERIAL { + constexpr PhongMaterial DEFAULT_MATERIAL{ DEFAULT_EMISSION, DEFAULT_AMBIENT, DEFAULT_DIFFUSE, @@ -50,7 +50,7 @@ namespace fggl::gfx { }; struct Light { - constexpr static const char* name = "gfx::light"; + constexpr static const char *name = "gfx::light"; constexpr static const util::GUID guid = util::make_guid("gfx::light"); bool enabled; bool local; diff --git a/include/fggl/gfx/setup.hpp b/include/fggl/gfx/setup.hpp index 6a580051e0449999c6abe05a8c36bf8ec309c49e..908d02dea468b7456afe08fc2301208c80b79130 100644 --- a/include/fggl/gfx/setup.hpp +++ b/include/fggl/gfx/setup.hpp @@ -40,7 +40,7 @@ namespace fggl::gfx { constexpr const static modules::ModuleService service = modules::make_service("fggl::gfx::WindowGraphics"); virtual GraphicsDetails config() const = 0; - virtual Graphics* create(display::Window& window) = 0; + virtual Graphics *create(display::Window &window) = 0; }; } // namespace fggl::gfx diff --git a/include/fggl/gui/containers.hpp b/include/fggl/gui/containers.hpp index fdc5795f0592897a50c26270939073c20702d2a6..005f0bff4ec980255a2380dcafabddb18581b0aa 100644 --- a/include/fggl/gui/containers.hpp +++ b/include/fggl/gui/containers.hpp @@ -29,6 +29,7 @@ namespace fggl::gui { } void add(std::unique_ptr<Widget> widget); + virtual inline void layout() {} bool contains(const math::vec2 &point) override; @@ -47,7 +48,7 @@ namespace fggl::gui { Panel() = default; ~Panel() = default; - void render(gfx::Paint& paint) override; + void render(gfx::Paint &paint) override; }; diff --git a/include/fggl/gui/fonts.hpp b/include/fggl/gui/fonts.hpp index 00cae278eb518b8e62d821ab7d87b7efa13b73c9..2aa44a41e83e0141fa3b7c01abe6b61b0dabbaf5 100644 --- a/include/fggl/gui/fonts.hpp +++ b/include/fggl/gui/fonts.hpp @@ -43,45 +43,45 @@ namespace fggl::gui { explicit FontFace(FT_Face face); ~FontFace(); - FontFace(const FontFace&) = delete; - FontFace(FontFace&&) = delete; - FontFace& operator=(const FontFace&) = delete; - FontFace& operator=(FontFace&&) = delete; + FontFace(const FontFace &) = delete; + FontFace(FontFace &&) = delete; + FontFace &operator=(const FontFace &) = delete; + FontFace &operator=(FontFace &&) = delete; - inline GlyphMetrics& metrics(char letter){ + inline GlyphMetrics &metrics(char letter) { auto itr = m_metrics.find(letter); - if ( itr == m_metrics.end() ) { + if (itr == m_metrics.end()) { return populateMetrics(letter); } return itr->second; } - math::vec2 stringSize(const std::string& text); - void texture(char letter, int& width, int& height, void** buff); + math::vec2 stringSize(const std::string &text); + void texture(char letter, int &width, int &height, void **buff); private: FT_Face m_face; std::map<char, GlyphMetrics> m_metrics; - GlyphMetrics& populateMetrics(char letter); + GlyphMetrics &populateMetrics(char letter); }; class FontLibrary { public: constexpr static const modules::ModuleService service = modules::make_service("fggl::gui::font"); - FontLibrary(data::Storage* storage); + FontLibrary(data::Storage *storage); ~FontLibrary(); // copy and moving not needed - FontLibrary(const FontLibrary&) = delete; - FontLibrary(FontLibrary&&) = delete; - FontLibrary& operator=(const FontLibrary&) = delete; - FontLibrary& operator=(FontLibrary&&) = delete; + FontLibrary(const FontLibrary &) = delete; + FontLibrary(FontLibrary &&) = delete; + FontLibrary &operator=(const FontLibrary &) = delete; + FontLibrary &operator=(FontLibrary &&) = delete; - inline std::shared_ptr<FontFace> getFont(const std::string& name) { + inline std::shared_ptr<FontFace> getFont(const std::string &name) { auto fontItr = m_cache.find(name); - if ( fontItr != m_cache.end() ) { + if (fontItr != m_cache.end()) { return fontItr->second; } @@ -89,7 +89,7 @@ namespace fggl::gui { auto path = m_storage->resolvePath(data::StorageType::Data, name); FT_Face face; - if ( FT_New_Face(m_context, path.string().c_str(), 0, &face) ) { + if (FT_New_Face(m_context, path.string().c_str(), 0, &face)) { return nullptr; } FT_Set_Pixel_Sizes(face, 0, 18); @@ -102,7 +102,7 @@ namespace fggl::gui { private: FT_Library m_context; - data::Storage* m_storage; + data::Storage *m_storage; std::map<const std::string, std::shared_ptr<FontFace>> m_cache; }; diff --git a/include/fggl/gui/module.hpp b/include/fggl/gui/module.hpp index 4fb81270d46cb66816e0b16a9184fbd4c2e290b5..e2abbd15f81dde1c8fd52118c02ef5ac4b8a8b7c 100644 --- a/include/fggl/gui/module.hpp +++ b/include/fggl/gui/module.hpp @@ -25,20 +25,20 @@ namespace fggl::gui { struct FreeType { - constexpr static const char* name = "fggl::gui::FreeType"; + constexpr static const char *name = "fggl::gui::FreeType"; constexpr static const std::array<modules::ModuleService, 1> provides = { FontLibrary::service }; constexpr static const std::array<modules::ModuleService, 1> depends = { data::Storage::service }; - static bool factory(modules::ModuleService name, modules::Services& serviceManager); + static bool factory(modules::ModuleService name, modules::Services &serviceManager); }; - bool FreeType::factory(modules::ModuleService service, modules::Services& services) { - if ( service == FontLibrary::service ) { + bool FreeType::factory(modules::ModuleService service, modules::Services &services) { + if (service == FontLibrary::service) { auto storage = services.get<data::Storage>(); - services.create< FontLibrary >(storage); + services.create<FontLibrary>(storage); return true; } return false; diff --git a/include/fggl/gui/widget.hpp b/include/fggl/gui/widget.hpp index 217b31b072d683ae0f48dfb3d725a9c41c9f20ac..9ef5147c2fcb6489c62ee2f7e2fb7456c26dffad 100644 --- a/include/fggl/gui/widget.hpp +++ b/include/fggl/gui/widget.hpp @@ -45,53 +45,55 @@ namespace fggl::gui { * @return RGB, in the range 0,1 for each component */ inline math::vec3 HSVtoNormal(float hue, float saturation, float value) { - assert( 0 < hue && hue <= 360); - assert( 0 < saturation && saturation <= 1); - assert( 0 < value && value <= 1); + assert(0 < hue && hue <= 360); + assert(0 < saturation && saturation <= 1); + assert(0 < value && value <= 1); const float chroma = value * saturation; - const float x = chroma * (1 - std::fabs( std::fmod(hue / 60.0F, 2.0F) - 1.0F) ); - math::vec3 tmp{0,0,0}; - if ( 0 <= hue && hue < 60 ) { - tmp = {chroma,x,0}; - } else if ( 60 <= hue && hue < 120 ) { + const float x = chroma * (1 - std::fabs(std::fmod(hue / 60.0F, 2.0F) - 1.0F)); + math::vec3 tmp{0, 0, 0}; + if (0 <= hue && hue < 60) { + tmp = {chroma, x, 0}; + } else if (60 <= hue && hue < 120) { tmp = {x, chroma, 0}; - } else if (120 <= hue && hue < 180 ) { + } else if (120 <= hue && hue < 180) { tmp = {0, chroma, x}; - } else if ( 180 <= hue && hue < 240 ) { + } else if (180 <= hue && hue < 240) { tmp = {0, x, chroma}; - } else if ( 240 <= hue && hue < 300) { + } else if (240 <= hue && hue < 300) { tmp = {x, 0, chroma}; - } else if ( 300 <= hue && hue < 360) { + } else if (300 <= hue && hue < 360) { tmp = {chroma, 0, x}; } return tmp + (value - chroma); } - void draw_box( gfx::Path2D& path, math::vec2 topLeft, math::vec2 bottomRight); - void draw_progress( gfx::Path2D& path, math::vec2 topLeft, math::vec2 size, float value); - void draw_slider( gfx::Path2D& path, math::vec2 topLeft, math::vec2 size, float value); - void draw_button( gfx::Path2D& path, math::vec2 topLeft, math::vec2 size, bool active, bool pressed); + void draw_box(gfx::Path2D &path, math::vec2 topLeft, math::vec2 bottomRight); + void draw_progress(gfx::Path2D &path, math::vec2 topLeft, math::vec2 size, float value); + void draw_slider(gfx::Path2D &path, math::vec2 topLeft, math::vec2 size, float value); + void draw_button(gfx::Path2D &path, math::vec2 topLeft, math::vec2 size, bool active, bool pressed); struct Bounds2D { math::vec2 topLeft; math::vec2 size; Bounds2D() = default; + inline Bounds2D(math::vec2 pos, math::vec2 a_size) : topLeft(pos), size(a_size) {} inline bool contains(math::vec2 point) { - return ! ( (point.x > topLeft.x + size.x) || - (point.x < topLeft.x ) || - (point.y > topLeft.y + size.y) || - (point.y < topLeft.y) - ); + return !((point.x > topLeft.x + size.x) || + (point.x < topLeft.x) || + (point.y > topLeft.y + size.y) || + (point.y < topLeft.y) + ); } }; class Widget { public: Widget() = default; + inline Widget(math::vec2 pos, math::vec2 size) : m_bounds(pos, size) {} virtual ~Widget() = default; @@ -113,28 +115,29 @@ namespace fggl::gui { return m_bounds.size; } - virtual inline bool contains(const math::vec2 &point){ + virtual inline bool contains(const math::vec2 &point) { return m_bounds.contains(point); }; virtual inline Widget *getChildAt(const math::vec2 &point) { - if ( !contains(point) ) { + if (!contains(point)) { return nullptr; } return this; } virtual void render(gfx::Paint &paint) = 0; + inline virtual void activate() {}; inline virtual void onEnter() {} + inline virtual void onExit() {} private: Bounds2D m_bounds; }; - }; //namespace fggl::gui #endif diff --git a/include/fggl/gui/widgets.hpp b/include/fggl/gui/widgets.hpp index 783b60edda86222837d37eb3e3607c385f2967f0..ac42a16993c04c2f94e76bb2a129cff12942228f 100644 --- a/include/fggl/gui/widgets.hpp +++ b/include/fggl/gui/widgets.hpp @@ -35,8 +35,8 @@ namespace fggl::gui { void render(gfx::Paint &paint) override { auto pos = topLeft(); auto size2 = size(); - math::vec2 baseLine{pos.x + 10, pos.y + size2.y/2 + 5}; - paint.text(m_value,baseLine); + math::vec2 baseLine{pos.x + 10, pos.y + size2.y / 2 + 5}; + paint.text(m_value, baseLine); } inline void font(std::shared_ptr<FontFace> font) { @@ -44,7 +44,7 @@ namespace fggl::gui { m_needsLayout = true; } - inline void text(const std::string& value) { + inline void text(const std::string &value) { m_value = value; m_needsLayout = true; } @@ -54,7 +54,7 @@ namespace fggl::gui { } math::vec2 naturalSize() { - if ( m_needsLayout ) { + if (m_needsLayout) { layout(); } return m_naturalSize; @@ -80,7 +80,7 @@ namespace fggl::gui { void onEnter() override; void onExit() override; - void label(const std::string& value); + void label(const std::string &value); [[nodiscard]] std::string label() const; @@ -94,7 +94,6 @@ namespace fggl::gui { bool m_active; }; - class Toggle : public Button { public: Toggle() = default; diff --git a/include/fggl/input/basics.hpp b/include/fggl/input/basics.hpp index 78036f6d68ba889b94165b9b798c829dbf1dafa7..0e8db971b8b96b7e9a928c59148ed646140c5512 100644 --- a/include/fggl/input/basics.hpp +++ b/include/fggl/input/basics.hpp @@ -22,10 +22,10 @@ namespace fggl::input { enum class InputType { - BUTTON, // 0 || 1 - UNIDIRECTIONAL_AXIS, // [0,1], absolute - BIDIRECTIONAL_AXIS, // [-1, 1], absolute - RELATIVE_AXIS // [-1, 1], relative + BUTTON, // 0 || 1 + UNIDIRECTIONAL_AXIS, // [0,1], absolute + BIDIRECTIONAL_AXIS, // [-1, 1], absolute + RELATIVE_AXIS // [-1, 1], relative }; } // namespace fggl::input diff --git a/include/fggl/input/camera_input.hpp b/include/fggl/input/camera_input.hpp index 6b549761e26a1f7abd897e79ed08c013e44a63cf..ea5fc4a7805a5365f93fa6ba4026b8094df095f5 100644 --- a/include/fggl/input/camera_input.hpp +++ b/include/fggl/input/camera_input.hpp @@ -38,7 +38,11 @@ namespace fggl::input { scancode_t rotate_ccw; }; - void process_scroll(entity::EntityManager &ecs, const Input &input, entity::EntityID cam, float minZoom = 10.0F, float maxZoom = 50.0F); + void process_scroll(entity::EntityManager &ecs, + const Input &input, + entity::EntityID cam, + float minZoom = 10.0F, + float maxZoom = 50.0F); /** * Process the camera based on rotation around a fixed point. diff --git a/include/fggl/input/module.hpp b/include/fggl/input/module.hpp index 12ed9e6db4e677330cf6827267d4d65466031585..224e402b9d2c17f421b10b0ad3ee98c19f104043 100644 --- a/include/fggl/input/module.hpp +++ b/include/fggl/input/module.hpp @@ -26,15 +26,15 @@ namespace fggl::input { struct Generic { - constexpr static const char* name = "fggl::input::Generic"; + constexpr static const char *name = "fggl::input::Generic"; constexpr static const std::array<modules::ModuleService, 1> provides = { SERVICE_INPUT }; constexpr static const std::array<modules::ModuleService, 0> depends = {}; - static bool factory(modules::ModuleService service, modules::Services& services); + static bool factory(modules::ModuleService service, modules::Services &services); }; - bool Generic::factory(modules::ModuleService service, modules::Services& services) { + bool Generic::factory(modules::ModuleService service, modules::Services &services) { if (service == SERVICE_INPUT) { services.create<input::Input>(); return true; diff --git a/include/fggl/math/easing.hpp b/include/fggl/math/easing.hpp index 5ee64ca1cb35fd9f13aa4562e02044a1ebca5a00..f31eb909d01b288add03a359da9949e809651ab4 100644 --- a/include/fggl/math/easing.hpp +++ b/include/fggl/math/easing.hpp @@ -37,7 +37,7 @@ namespace fggl::math { // using transformF = std::function<float(float)>; - inline float scaleFilter(float in, float inMin, float inMax, float outMin, float outMax, const transformF& filter) { + inline float scaleFilter(float in, float inMin, float inMax, float outMin, float outMax, const transformF &filter) { float out = in - inMin; out /= (inMax - inMin); out = filter(out); @@ -45,7 +45,7 @@ namespace fggl::math { return out + outMin; } - inline float mix(const transformF& funcA, const transformF& funcB, float weightB, float t) { + inline float mix(const transformF &funcA, const transformF &funcB, float weightB, float t) { return ((1 - weightB) * funcA(t)) + (weightB * funcB(t)); } diff --git a/include/fggl/math/fmath.hpp b/include/fggl/math/fmath.hpp index 9f16a9bd890985cc754904a49a15df50d7d5ee90..8deee12ab1d0368bfe46d711af86456e400dcd35 100644 --- a/include/fggl/math/fmath.hpp +++ b/include/fggl/math/fmath.hpp @@ -35,9 +35,9 @@ namespace fggl::math { */ using vec2f = glm::vec2; - constexpr static const math::vec2f VEC2_ZERO {0.0F, 0.0F}; - constexpr static const math::vec3f VEC3_ZERO {0.0F, 0.0F, 0.0F}; - constexpr static const math::vec3f VEC3_ONES {1.0F, 1.0F, 1.0F}; + constexpr static const math::vec2f VEC2_ZERO{0.0F, 0.0F}; + constexpr static const math::vec3f VEC3_ZERO{0.0F, 0.0F, 0.0F}; + constexpr static const math::vec3f VEC3_ONES{1.0F, 1.0F, 1.0F}; /** * return the remainder (modulo) of value / maximum. @@ -61,10 +61,12 @@ namespace fggl::math { * @param max the maximum allowable value */ inline float wrap(float value, float min, float max) { - if ( min > max ){ std::swap(min, max); }; + if (min > max) { + std::swap(min, max); + }; value -= min; float rangeSize = max - min; - return value - (rangeSize * std::floor(value/rangeSize)) + min; + return value - (rangeSize * std::floor(value / rangeSize)) + min; } /** diff --git a/include/fggl/math/imath.hpp b/include/fggl/math/imath.hpp index 7f533f87305538edef3d926f232e79bb886e9555..4c3996fd5b21111cdaf09840010a7f6b11cf46f3 100644 --- a/include/fggl/math/imath.hpp +++ b/include/fggl/math/imath.hpp @@ -23,16 +23,18 @@ namespace fggl::math { // wrap value in range [0, max) inline int wrap(int value, int max) { - if ( value < 0 ) return (value-1)-(-1-value) % value; - if ( value >= max ) return value % max; + if (value < 0) + return (value - 1) - (-1 - value) % value; + if (value >= max) + return value % max; return value; } // wrap value in range [min, max) inline int wrap(int value, int const min, int const max) { int range = max - min + 1; - if ( value < min) { - value += range * ( (min - value) / range + 1 ); + if (value < min) { + value += range * ((min - value) / range + 1); } return min + (value - min) % range; } diff --git a/include/fggl/math/shapes.hpp b/include/fggl/math/shapes.hpp index e30eae42f9feb246fbefd596a5d6e2f86bce6c59..51060ac23084914a2732ff019d34b1f406993bf5 100644 --- a/include/fggl/math/shapes.hpp +++ b/include/fggl/math/shapes.hpp @@ -57,9 +57,9 @@ namespace fggl::math::phs3d { math::vec3 min; math::vec3 max; - void add(const math::vec3& p); + void add(const math::vec3 &p); void emtpy(); - void set(const AABB& other, const math::mat4& m); + void set(const AABB &other, const math::mat4 &m); inline math::vec3 center() const { return (min + max) / 2.0F; @@ -73,23 +73,23 @@ namespace fggl::math::phs3d { return max - center(); } - static AABB fromPoints(const std::vector<math::vec3>& points); + static AABB fromPoints(const std::vector<math::vec3> &points); }; struct Plane { glm::vec3 normal; float d; // distance to origin - inline bool contains(const math::vec3& point) { + inline bool contains(const math::vec3 &point) { return glm::dot(point, normal) == d; } - inline float distance(const math::vec3& q) { + inline float distance(const math::vec3 &q) { return glm::dot(q, normal) - d; } static Plane fromPoints(const math::vec3, const math::vec3, const math::vec3); - static Plane bestFit(const std::vector<math::vec3>& points); + static Plane bestFit(const std::vector<math::vec3> &points); }; struct Barycentric { @@ -98,8 +98,8 @@ namespace fggl::math::phs3d { bool inTriangle() { return 0 <= b[0] && b[0] <= 1 && - 0 <= b[1] && b[1] <= 1 && - 0 <= b[2] && b[2] <= 1; + 0 <= b[1] && b[1] <= 1 && + 0 <= b[2] && b[2] <= 1; } inline bool isLegal() const { @@ -107,8 +107,8 @@ namespace fggl::math::phs3d { } }; - constexpr float THIRD = 1.0F/3.0F; - const Barycentric cGrav = { {THIRD, THIRD, THIRD}}; + constexpr float THIRD = 1.0F / 3.0F; + const Barycentric cGrav = {{THIRD, THIRD, THIRD}}; struct Triangle { std::array<math::vec3, 3> v; @@ -130,11 +130,11 @@ namespace fggl::math::phs3d { } inline float length(int a, int b) const { - return glm::length( edge(a, b)); + return glm::length(edge(a, b)); } inline float perimeter() const { - return length(3, 2) + length(1,3) + length(2, 1); + return length(3, 2) + length(1, 3) + length(2, 1); } inline float area() const { @@ -190,13 +190,13 @@ namespace fggl::math::phs3d { return 0.0F; } - bool CartToBarycentric(const math::vec3& cart, Barycentric& outVal); - bool CartToBarycentric2(const math::vec3& cart, Barycentric& outVal); + bool CartToBarycentric(const math::vec3 &cart, Barycentric &outVal); + bool CartToBarycentric2(const math::vec3 &cart, Barycentric &outVal); - math::vec3 BarycentricToCart(const Barycentric& p) const { + math::vec3 BarycentricToCart(const Barycentric &p) const { return v[0] * p.b[0] + - v[1] * p.b[1] + - v[2] * p.b[2]; + v[1] * p.b[1] + + v[2] * p.b[2]; } }; diff --git a/include/fggl/math/triangulation.hpp b/include/fggl/math/triangulation.hpp index e3136492d20921ffbb1980fcd1cb7a760b7897c6..06f6daaa49bb1b7bf40ab8946508851804252cce 100644 --- a/include/fggl/math/triangulation.hpp +++ b/include/fggl/math/triangulation.hpp @@ -127,13 +127,13 @@ namespace fggl::math { } static data::Vertex2D pointToVertex(const math::vec2 &point) { - return data::Vertex2D{ point, {1.0f, 1.0f, 1.0f} }; + return data::Vertex2D{point, {1.0f, 1.0f, 1.0f}}; } /** * Fast Triangulation for convex polygons. */ - void fan_triangulation(const PolygonVertex& polygon, data::Mesh2D &mesh); + void fan_triangulation(const PolygonVertex &polygon, data::Mesh2D &mesh); } // namespace fggl::util diff --git a/include/fggl/math/types.hpp b/include/fggl/math/types.hpp index a649056fa717dd4e1d228a836090c156baff0661..8899ab983558d022e14ea824adc760ccc1696fc8 100644 --- a/include/fggl/math/types.hpp +++ b/include/fggl/math/types.hpp @@ -29,11 +29,11 @@ #include "fggl/util/guid.hpp" #ifndef M_PI - #define M_PI 3.14159265358979323846 + #define M_PI 3.14159265358979323846 #endif #ifndef M_PI_2 - #define M_PI_2 1.57079632679489661923 + #define M_PI_2 1.57079632679489661923 #endif namespace fggl::math { @@ -112,12 +112,12 @@ namespace fggl::math { */ using quat = glm::quat; - constexpr static const math::mat4 IDENTITY_M4 {1.0F}; - constexpr static const math::quat IDENTITY_Q {1.0F, 0.0, 0.0, 0.0}; + constexpr static const math::mat4 IDENTITY_M4{1.0F}; + constexpr static const math::quat IDENTITY_Q{1.0F, 0.0, 0.0, 0.0}; - constexpr static const math::vec3 AXIS_X { 1.0F, 0.0F, 0.0F }; - constexpr static const math::vec3 AXIS_Y { 0.0F, 1.0F, 0.0F }; - constexpr static const math::vec3 AXIS_Z { 0.0F, 0.0F, 1.0F }; + constexpr static const math::vec3 AXIS_X{1.0F, 0.0F, 0.0F}; + constexpr static const math::vec3 AXIS_Y{0.0F, 1.0F, 0.0F}; + constexpr static const math::vec3 AXIS_Z{0.0F, 0.0F, 1.0F}; // fastFloor from OpenSimplex2 inline int fastFloor(double x) { @@ -159,7 +159,7 @@ namespace fggl::math { * @param newMax the new maximum value * @return the rescaled value, [newMin, newMax] */ - constexpr float rescale_ndc(float value, float newMin, float newMax){ + constexpr float rescale_ndc(float value, float newMin, float newMax) { return rescale_norm(value, -1, 1, newMin, newMax); } @@ -171,7 +171,7 @@ namespace fggl::math { * @param newMax the new maximum value * @return the rescaled value, [newMin, newMax] */ - constexpr float rescale_01(float value, float newMin, float newMax){ + constexpr float rescale_01(float value, float newMin, float newMax) { return rescale_norm(value, 0, 1, newMin, newMax); } @@ -179,7 +179,6 @@ namespace fggl::math { return (value - avg) / (max - min); } - // reference vectors constexpr vec3f UP{0.0f, 1.0f, 0.0f}; constexpr vec3f FORWARD{1.0f, 0.0f, 0.0f}; @@ -268,14 +267,14 @@ namespace fggl::math { [[nodiscard]] inline mat4 local() const { - const glm::mat4 transformX = glm::rotate( math::IDENTITY_M4,glm::radians(m_euler.x), AXIS_X ); - const glm::mat4 transformY = glm::rotate( math::IDENTITY_M4, glm::radians(m_euler.y), AXIS_Y ); - const glm::mat4 transformZ = glm::rotate( math::IDENTITY_M4, glm::radians(m_euler.z), AXIS_Z ); + const glm::mat4 transformX = glm::rotate(math::IDENTITY_M4, glm::radians(m_euler.x), AXIS_X); + const glm::mat4 transformY = glm::rotate(math::IDENTITY_M4, glm::radians(m_euler.y), AXIS_Y); + const glm::mat4 transformZ = glm::rotate(math::IDENTITY_M4, glm::radians(m_euler.z), AXIS_Z); const auto rotation = transformY * transformX * transformZ; return glm::translate(math::IDENTITY_M4, m_origin) * rotation - * glm::scale( math::IDENTITY_M4, m_scale ); + * glm::scale(math::IDENTITY_M4, m_scale); } [[nodiscard]] @@ -283,7 +282,7 @@ namespace fggl::math { return local(); } - inline void update(const math::mat4& parent) { + inline void update(const math::mat4 &parent) { m_model = parent * local(); } @@ -303,12 +302,11 @@ namespace fggl::math { vec3 m_scale; }; - - inline math::mat4 calc_view_matrix(const Transform& transform) { + inline math::mat4 calc_view_matrix(const Transform &transform) { return glm::lookAt(transform.origin(), transform.origin() + transform.forward(), transform.up()); } - inline math::mat4 calc_view_matrix(const Transform& transform, vec3 target) { + inline math::mat4 calc_view_matrix(const Transform &transform, vec3 target) { return glm::lookAt(transform.origin(), target, transform.up()); } diff --git a/include/fggl/math/vector.hpp b/include/fggl/math/vector.hpp index 29b117b70470a46f4973ba9cf590b0df35891842..20a9a25180b65a6ef5b5a92a86d4e1e471b6fc88 100644 --- a/include/fggl/math/vector.hpp +++ b/include/fggl/math/vector.hpp @@ -41,18 +41,18 @@ namespace glm { } // output stream operators - inline std::ostream& operator<<(std::ostream& os, const vec2& v) { + inline std::ostream &operator<<(std::ostream &os, const vec2 &v) { os << "(" << v.x << ", " << v.y << ")"; return os; } - inline std::ostream& operator<<(std::ostream& os, const vec3& v) { - os << "(" << v.x << ", " << v.y << "," << v.z << ")"; + inline std::ostream &operator<<(std::ostream &os, const vec3 &v) { + os << "(" << v.x << ", " << v.y << "," << v.z << ")"; return os; } - inline std::ostream& operator<<(std::ostream& os, const vec4& v) { - os << "(" << v.x << ", " << v.y << "," << v.z << "," << v.w << ")"; + inline std::ostream &operator<<(std::ostream &os, const vec4 &v) { + os << "(" << v.x << ", " << v.y << "," << v.z << "," << v.w << ")"; return os; } } diff --git a/include/fggl/modules/manager.hpp b/include/fggl/modules/manager.hpp index d804da6f368400025c2b8a2a1c13eaac1d94eb1d..23db222dfb1ec325ef328801331099355be39808 100644 --- a/include/fggl/modules/manager.hpp +++ b/include/fggl/modules/manager.hpp @@ -40,7 +40,7 @@ namespace fggl::modules { m_dependencies.clear(); } - void addAll(const T& name, const std::vector<T>& dependencies) { + void addAll(const T &name, const std::vector<T> &dependencies) { auto existing = m_dependencies.find(name); if (existing == m_dependencies.end()) { m_dependencies[name] = dependencies; @@ -49,52 +49,53 @@ namespace fggl::modules { } } - void add(const T& name, const T& depends) { + void add(const T &name, const T &depends) { m_dependencies[name].push_back(depends); } - bool getOrder(std::stack<T>& stack) { + bool getOrder(std::stack<T> &stack) { std::set<T> visited{}; - for (const auto& module : m_dependencies) { + for (const auto &module : m_dependencies) { if (!visited.contains(module.first)) { - sortUtil( module.first, visited, stack); + sortUtil(module.first, visited, stack); } } return true; } - bool getOrderRev(std::queue<T>& stack) { + bool getOrderRev(std::queue<T> &stack) { std::set<T> visited{}; - for (const auto& module : m_dependencies) { + for (const auto &module : m_dependencies) { if (!visited.contains(module.first)) { - sortUtilRev( module.first, visited, stack); + sortUtilRev(module.first, visited, stack); } } return true; } + private: std::map<T, std::vector<T>> m_dependencies; - void sortUtil(T idx, std::set<T>& visited, std::stack<T>& stack) { + void sortUtil(T idx, std::set<T> &visited, std::stack<T> &stack) { visited.emplace(idx); - for ( auto dep : m_dependencies.at(idx)) { - if ( !visited.contains(dep) ) + for (auto dep : m_dependencies.at(idx)) { + if (!visited.contains(dep)) sortUtil(dep, visited, stack); } stack.push(idx); } - void sortUtilRev(T idx, std::set<T>& visited, std::queue<T>& stack) { + void sortUtilRev(T idx, std::set<T> &visited, std::queue<T> &stack) { visited.emplace(idx); - for ( auto dep : m_dependencies.at(idx)) { - if ( !visited.contains(dep) ) + for (auto dep : m_dependencies.at(idx)) { + if (!visited.contains(dep)) sortUtilRev(dep, visited, stack); } @@ -102,30 +103,29 @@ namespace fggl::modules { } }; - class Manager { public: Manager() = default; - inline void addVirtual(const Config& config) { - assert( !m_locked ); + inline void addVirtual(const Config &config) { + assert(!m_locked); m_modules[config.name] = config; - for ( const auto& service : config.provides ) { + for (const auto &service : config.provides) { m_serviceProviders[service] = config.name; } } template<typename T> void use() { - assert( !m_locked ); + assert(!m_locked); - Config config { .name = T::name, .provides = {}, .depends = {} }; - for ( auto service : T::provides ) { + Config config{.name = T::name, .provides = {}, .depends = {}}; + for (auto service : T::provides) { config.provides.push_back(service); } - for ( auto service : T::depends ) { + for (auto service : T::depends) { config.depends.push_back(service); } config.factory = T::factory; @@ -135,17 +135,20 @@ namespace fggl::modules { bool buildGraph() { // resolve links between modules - for (auto& moduleItr : m_modules) { - if ( moduleItr.second.depends.empty() ) { + for (auto &moduleItr : m_modules) { + if (moduleItr.second.depends.empty()) { m_dependencies.addAll(moduleItr.first, {}); continue; } - for (auto& service : moduleItr.second.depends) { + for (auto &service : moduleItr.second.depends) { auto provider = m_serviceProviders.find(service); - if ( provider == m_serviceProviders.end() ) { - debug::log(debug::Level::warning, "{} depends on {}, but nothing provides it", moduleItr.first, service); + if (provider == m_serviceProviders.end()) { + debug::log(debug::Level::warning, + "{} depends on {}, but nothing provides it", + moduleItr.first, + service); // nothing can provide the service requested, setup is invalid. return false; } @@ -157,29 +160,32 @@ namespace fggl::modules { } template<typename T> - T* get() const { - assert( m_locked ); + T *get() const { + assert(m_locked); return m_services.template get<T>(); } void resolve() { - if ( !buildGraph() ) { + if (!buildGraph()) { return; } std::queue<ModuleIdentifier> stack; m_dependencies.getOrderRev(stack); - while ( !stack.empty() ) { + while (!stack.empty()) { auto nextToInit = stack.front(); debug::log(debug::Level::info, "Initializing {}", nextToInit); - auto& module = m_modules.at(nextToInit); - if ( module.factory != nullptr ) { - for (auto& service : module.provides) { + auto &module = m_modules.at(nextToInit); + if (module.factory != nullptr) { + for (auto &service : module.provides) { bool result = module.factory(service, m_services); - if ( !result ) { - debug::log(debug::Level::warning, "{} could not create service {}", nextToInit, service); + if (!result) { + debug::log(debug::Level::warning, + "{} could not create service {}", + nextToInit, + service); } } } else { diff --git a/include/fggl/modules/module.hpp b/include/fggl/modules/module.hpp index 1c8c8eeaf9705e1a4221236f85db9ce73d6791de..e3ba6c2c83eb3e7c379f5c77ea834474d7a726e7 100644 --- a/include/fggl/modules/module.hpp +++ b/include/fggl/modules/module.hpp @@ -40,12 +40,12 @@ namespace fggl::modules { public: template<typename Svc, typename Impl, typename ...Args> void bind(Args... args) { - static_assert( std::is_base_of_v<Svc, Impl>, "Service type must be assignable from implementation type" ); + static_assert(std::is_base_of_v<Svc, Impl>, "Service type must be assignable from implementation type"); m_services[Svc::service] = std::make_shared<Impl>(args...); } template<typename Svc, typename ...Args> - Svc* create(Args... args){ + Svc *create(Args... args) { auto svc = std::make_shared<Svc>(args...); m_services[Svc::service] = svc; return svc.get(); @@ -57,16 +57,17 @@ namespace fggl::modules { } template<typename S> - S* get() const { + S *get() const { auto serviceWrapper = m_services.at(S::service); auto ptr = std::static_pointer_cast<S>(serviceWrapper); return ptr.get(); } + private: std::map<ModuleService, std::shared_ptr<void>> m_services; }; - using ServiceFactory = std::function<bool(ModuleService, Services&)>; + using ServiceFactory = std::function<bool(ModuleService, Services &)>; struct Config { ModuleIdentifier name; std::vector<ModuleService> provides; diff --git a/include/fggl/phys/callbacks.hpp b/include/fggl/phys/callbacks.hpp index 856be21bd24e42943694cf0ea69140f24a5a82cb..afc23b426da81392357426d2096a16cc7db66b08 100644 --- a/include/fggl/phys/callbacks.hpp +++ b/include/fggl/phys/callbacks.hpp @@ -25,17 +25,17 @@ namespace fggl::phys { - using CollisionCB = std::function<void(entity::EntityID , entity::EntityID)>; + using CollisionCB = std::function<void(entity::EntityID, entity::EntityID)>; struct CollisionCallbacks { - constexpr static const char* name = "phys::Callbacks"; + constexpr static const char *name = "phys::Callbacks"; CollisionCB onEnter = nullptr; CollisionCB onExit = nullptr; CollisionCB onStay = nullptr; }; struct CollisionCache { - constexpr static const char* name = "phys::Cache"; + constexpr static const char *name = "phys::Cache"; std::unordered_set<entity::EntityID> collisions; std::unordered_set<entity::EntityID> lastFrame; }; diff --git a/include/fggl/phys/null.hpp b/include/fggl/phys/null.hpp index 5fe79230a0742cedfbb39221da869cdd160944d0..2cc7dfa629772a3267a1b3ce32344a50a31520e4 100644 --- a/include/fggl/phys/null.hpp +++ b/include/fggl/phys/null.hpp @@ -24,13 +24,14 @@ namespace fggl::phys { - inline void build_noop(const entity::ComponentSpec& /*config*/, - entity::EntityManager& /*manager*/, - const entity::EntityID& /*entity*/) {} + inline void build_noop(const entity::ComponentSpec & /*config*/, + entity::EntityManager & /*manager*/, + const entity::EntityID & /*entity*/) {} class NullPhysicsEngine : public PhysicsEngine { public: inline void step() override {} + void setDebugDraw(bool /* enable */) override {} inline std::vector<ContactPoint> scanCollisions(entity::EntityID /*entity*/) override { @@ -45,7 +46,9 @@ namespace fggl::phys { return {}; } - inline std::vector<entity::EntityID> sweep(PhyShape& /*shape*/, math::Transform& /*from*/, math::Transform& /*to*/) override { + inline std::vector<entity::EntityID> sweep(PhyShape & /*shape*/, + math::Transform & /*from*/, + math::Transform & /*to*/) override { return {}; } }; @@ -53,21 +56,23 @@ namespace fggl::phys { class NullPhysicsProvider : public PhysicsProvider { public: virtual ~NullPhysicsProvider() = default; - inline PhysicsEngine* create(entity::EntityManager* /*entityManager*/, entity::EntityFactory* factory) override { - factory->bind(util::make_guid("phys::Body"), build_noop ); + + inline PhysicsEngine *create(entity::EntityManager * /*entityManager*/, + entity::EntityFactory *factory) override { + factory->bind(util::make_guid("phys::Body"), build_noop); return new NullPhysicsEngine(); } }; struct NullPhysics { - constexpr static const char* name = "fggl::phys::null"; + constexpr static const char *name = "fggl::phys::null"; constexpr static const std::array<modules::ModuleService, 1> provides = { phys::PhysicsProvider::service }; constexpr static const std::array<modules::ModuleService, 1> depends = { entity::EntityFactory::service }; - static bool factory(modules::ModuleService serviceName, modules::Services& serviceManager); + static bool factory(modules::ModuleService serviceName, modules::Services &serviceManager); }; } // namespace fggl::phys diff --git a/include/fggl/phys/service.hpp b/include/fggl/phys/service.hpp index b4974651f385b87ac470f65d25ab4bd551dbb739..496529f328cf24bd9b57fda2404722a50bee4eec 100644 --- a/include/fggl/phys/service.hpp +++ b/include/fggl/phys/service.hpp @@ -29,7 +29,7 @@ namespace fggl::phys { public: constexpr static const modules::ModuleService service = modules::make_service("fggl::phys::service"); virtual ~PhysicsProvider() = default; - virtual PhysicsEngine* create(entity::EntityManager* entityManager, entity::EntityFactory* factory) = 0; + virtual PhysicsEngine *create(entity::EntityManager *entityManager, entity::EntityFactory *factory) = 0; }; } diff --git a/include/fggl/phys/types.hpp b/include/fggl/phys/types.hpp index 9d8c558ba66a9477af3c1e5476731c46f7b0c3f4..d02b8392007f9004c641de476b07d31bf70be302 100644 --- a/include/fggl/phys/types.hpp +++ b/include/fggl/phys/types.hpp @@ -28,9 +28,9 @@ namespace fggl::phys { constexpr math::vec3 UNIT_EXTENTS{0.5F, 0.5F, 0.5F}; enum class ShapeType { - UNSET, - BOX, - SPHERE + UNSET, + BOX, + SPHERE }; struct PhyShape { @@ -42,22 +42,24 @@ namespace fggl::phys { struct Box : public PhyShape { math::vec3 extents; + explicit inline Box(math::vec3 ext) : PhyShape(ShapeType::BOX), extents(ext) {} }; struct Sphere : public PhyShape { float radius = 1.0F; + explicit inline Sphere(float rad) : PhyShape(ShapeType::SPHERE), radius(rad) {} }; enum class BodyType { - STATIC, KINEMATIC, DYNAMIC + STATIC, KINEMATIC, DYNAMIC }; struct RigidBody { - constexpr static const char* name = "phys::Body"; + constexpr static const char *name = "phys::Body"; float mass = MASS_DEFAULT; - PhyShape* shape = nullptr; + PhyShape *shape = nullptr; BodyType type = BodyType::DYNAMIC; [[nodiscard]] @@ -67,7 +69,7 @@ namespace fggl::phys { }; struct Dynamics { - constexpr static const char* name = "phys::Dynamics"; + constexpr static const char *name = "phys::Dynamics"; math::vec3 force = math::VEC3_ZERO; }; @@ -98,21 +100,24 @@ namespace fggl::phys { virtual ~PhysicsEngine() = default; // no copy and no move - PhysicsEngine(PhysicsEngine&) = delete; - PhysicsEngine(PhysicsEngine&&) = delete; - PhysicsEngine& operator=(PhysicsEngine&) = delete; - PhysicsEngine& operator=(PhysicsEngine&&) = delete; + PhysicsEngine(PhysicsEngine &) = delete; + PhysicsEngine(PhysicsEngine &&) = delete; + PhysicsEngine &operator=(PhysicsEngine &) = delete; + PhysicsEngine &operator=(PhysicsEngine &&) = delete; // query methods (first cut - unstable APIs) virtual std::vector<ContactPoint> scanCollisions(entity::EntityID entity) = 0; virtual entity::EntityID raycast(math::vec3 from, math::vec3 to) = 0; + inline entity::EntityID raycast(math::Ray ray, float maxDist = 1000.0F) { return raycast(ray.origin, ray.origin + ray.direction * maxDist); } virtual std::vector<entity::EntityID> raycastAll(math::vec3 from, math::vec3 to) = 0; - virtual std::vector<entity::EntityID> sweep(PhyShape& shape, math::Transform& from, math::Transform& to) = 0; + virtual std::vector<entity::EntityID> sweep(PhyShape &shape, + math::Transform &from, + math::Transform &to) = 0; // update virtual void step() = 0; diff --git a/include/fggl/platform/fallback/paths.hpp b/include/fggl/platform/fallback/paths.hpp index 9a74a9b31d7cc88a7ecf582c52741b2fab1e92aa..f4c3a1ea4d44dcf3ee6f829aebc0ea5a7ea2b0b6 100644 --- a/include/fggl/platform/fallback/paths.hpp +++ b/include/fggl/platform/fallback/paths.hpp @@ -30,13 +30,13 @@ namespace fggl::platform { - constexpr const char* ENV_USER_CONFIG = "FGGL_CONFIG_HOME"; - constexpr const char* ENV_USER_DATA = "FGGL_DATA_HOME"; - constexpr const char* ENV_USER_CACHE = "FGGL_CACHE_HOME"; + constexpr const char *ENV_USER_CONFIG = "FGGL_CONFIG_HOME"; + constexpr const char *ENV_USER_DATA = "FGGL_DATA_HOME"; + constexpr const char *ENV_USER_CACHE = "FGGL_CACHE_HOME"; // fallback user paths defined in the XDG spec - constexpr const char* DEFAULT_USER_CONFIG = "user_config"; - constexpr const char* DEFAULT_USER_DATA = "user_data"; + constexpr const char *DEFAULT_USER_CONFIG = "user_config"; + constexpr const char *DEFAULT_USER_DATA = "user_data"; struct EnginePaths { std::filesystem::path userConfig; @@ -44,12 +44,12 @@ namespace fggl::platform { std::filesystem::path userCache; }; - EnginePaths calc_engine_paths(const char* base); + EnginePaths calc_engine_paths(const char *base); // search routines for finding data and configuration files - std::filesystem::path locate_data(const EnginePaths& paths, const std::filesystem::path& relPath); - std::filesystem::path locate_config(const EnginePaths& paths, const std::filesystem::path& relPath); - std::filesystem::path locate_cache(const EnginePaths& paths, const std::filesystem::path& relPath); + std::filesystem::path locate_data(const EnginePaths &paths, const std::filesystem::path &relPath); + std::filesystem::path locate_config(const EnginePaths &paths, const std::filesystem::path &relPath); + std::filesystem::path locate_cache(const EnginePaths &paths, const std::filesystem::path &relPath); } diff --git a/include/fggl/platform/linux/paths.hpp b/include/fggl/platform/linux/paths.hpp index 2c2b783b5201e394d3cf587c05a928846d552910..6fe48aca28acdda0e6c73347dcb47a38530786fd 100644 --- a/include/fggl/platform/linux/paths.hpp +++ b/include/fggl/platform/linux/paths.hpp @@ -30,21 +30,21 @@ namespace fggl::platform { - constexpr const char* ENV_USER_CONFIG = "XDG_CONFIG_HOME"; - constexpr const char* ENV_USER_DATA = "XDG_DATA_HOME"; - constexpr const char* ENV_USER_CACHE = "XDG_CACHE_HOME"; + constexpr const char *ENV_USER_CONFIG = "XDG_CONFIG_HOME"; + constexpr const char *ENV_USER_DATA = "XDG_DATA_HOME"; + constexpr const char *ENV_USER_CACHE = "XDG_CACHE_HOME"; - constexpr const char* ENV_DATA_DIRS = "XDG_DATA_DIRS"; - constexpr const char* ENV_CONFIG_DIRS = "XDG_CONFIG_DIRS"; + constexpr const char *ENV_DATA_DIRS = "XDG_DATA_DIRS"; + constexpr const char *ENV_CONFIG_DIRS = "XDG_CONFIG_DIRS"; // fallback user paths defined in the XDG spec - constexpr const char* DEFAULT_USER_CONFIG = "~/.config"; - constexpr const char* DEFAULT_USER_DATA = "~/.local/share"; - constexpr const char* DEFAULT_USER_CACHE = "~/.cache"; + constexpr const char *DEFAULT_USER_CONFIG = "~/.config"; + constexpr const char *DEFAULT_USER_DATA = "~/.local/share"; + constexpr const char *DEFAULT_USER_CACHE = "~/.cache"; // fallback search paths defined in the XDG spec - constexpr const std::array<const char*, 2> DEFAULT_DATA_DIRS = {"/usr/local/share/", "/usr/share/"}; - constexpr const std::array<const char*, 1> DEFAULT_CONFIG_DIRS = {"/etc/xdg"}; + constexpr const std::array<const char *, 2> DEFAULT_DATA_DIRS = {"/usr/local/share/", "/usr/share/"}; + constexpr const std::array<const char *, 1> DEFAULT_CONFIG_DIRS = {"/etc/xdg"}; struct EnginePaths { std::filesystem::path userConfig; @@ -54,12 +54,12 @@ namespace fggl::platform { std::vector<std::filesystem::path> configDirs; }; - EnginePaths calc_engine_paths(const char* base); + EnginePaths calc_engine_paths(const char *base); // search routines for finding data and configuration files - std::filesystem::path locate_data(const EnginePaths& paths, const std::filesystem::path& relPath); - std::filesystem::path locate_config(const EnginePaths& paths, const std::filesystem::path& relPath); - std::filesystem::path locate_cache(const EnginePaths& paths, const std::filesystem::path& relPath); + std::filesystem::path locate_data(const EnginePaths &paths, const std::filesystem::path &relPath); + std::filesystem::path locate_config(const EnginePaths &paths, const std::filesystem::path &relPath); + std::filesystem::path locate_cache(const EnginePaths &paths, const std::filesystem::path &relPath); } diff --git a/include/fggl/platform/paths.hpp b/include/fggl/platform/paths.hpp index 5265b53822537eb158c5d5f629f2e2800ac35f24..6fe099e9762e1cddd121daffc74c90ba5b0e90fe 100644 --- a/include/fggl/platform/paths.hpp +++ b/include/fggl/platform/paths.hpp @@ -24,6 +24,7 @@ #ifdef __linux__ #include "fggl/platform/linux/paths.hpp" + #else #include "fggl/platform/fallback/paths.hpp" #endif diff --git a/include/fggl/scenes/game.hpp b/include/fggl/scenes/game.hpp index 2b1ad8145e206f7c7c2c2abfe5c7961ec41fde91..07be3050cdf5d2007e09da2c2ec9a6d5681d3a0f 100644 --- a/include/fggl/scenes/game.hpp +++ b/include/fggl/scenes/game.hpp @@ -28,29 +28,29 @@ namespace fggl::scenes { class Game : public fggl::AppState { public: - explicit Game(fggl::App& app); + explicit Game(fggl::App &app); void activate() override; void deactivate() override; void update() override; - void render(fggl::gfx::Graphics& gfx) override; + void render(fggl::gfx::Graphics &gfx) override; protected: - inline auto world() -> entity::EntityManager& { + inline auto world() -> entity::EntityManager & { return *m_world; } - inline auto phys() -> phys::PhysicsEngine& { + inline auto phys() -> phys::PhysicsEngine & { return *m_phys; } - inline auto input() -> input::Input& { + inline auto input() -> input::Input & { return *m_input; } private: - input::Input* m_input; + input::Input *m_input; std::unique_ptr<entity::EntityManager> m_world; std::unique_ptr<phys::PhysicsEngine> m_phys; std::string m_previous = "menu"; diff --git a/include/fggl/scenes/menu.hpp b/include/fggl/scenes/menu.hpp index ecc06eab8a818f72c703dcf6dd4f651fca356f05..5c6220c5aab446f352e7153ff7edf12b0ec97714 100644 --- a/include/fggl/scenes/menu.hpp +++ b/include/fggl/scenes/menu.hpp @@ -41,14 +41,14 @@ namespace fggl::scenes { void add(const std::string &label, callback cb); private: - input::Input* m_inputs; + input::Input *m_inputs; std::map<const std::string, callback> m_items; // menu state std::string m_active; math::vec2 m_cursorPos; gui::Container m_canvas; - gui::Widget* m_hover; + gui::Widget *m_hover; }; } // namepace fggl::scenes diff --git a/include/fggl/util/guid.hpp b/include/fggl/util/guid.hpp index 5feca83726357effedc4d2417fe2cd7847c186a6..99902435ef2390f2a44cb5032c3777ab9149fc1a 100644 --- a/include/fggl/util/guid.hpp +++ b/include/fggl/util/guid.hpp @@ -40,7 +40,7 @@ namespace fggl::util { * @param str the string to hash. * @return the hashed value */ - constexpr uint32_t hash_fnv1a_32(const char* str) { + constexpr uint32_t hash_fnv1a_32(const char *str) { assert(str != nullptr); uint32_t hash = FNV_OFFSET_BASIS_32; for (int i = 0; str[i] != '\0'; i++) { @@ -56,7 +56,7 @@ namespace fggl::util { * @param str the string to be hashed * @return the hashed value */ - constexpr uint64_t hash_fnv1a_64(const char* str) { + constexpr uint64_t hash_fnv1a_64(const char *str) { assert(str != nullptr); uint64_t hash = FNV_OFFSET_BASIS_64; for (int i = 0; str[i] != '\0'; i++) { @@ -68,25 +68,25 @@ namespace fggl::util { // debug-only functions #ifndef NDEBUG - GUID internString(const char* str); - std::string guidToString(GUID guid); + GUID internString(const char *str); + std::string guidToString(GUID guid); #endif - constexpr GUID make_guid(const char* str) { + constexpr GUID make_guid(const char *str) { return GUID::make(hash_fnv1a_64(str)); } - inline GUID make_guid_rt(const std::string& str) { + inline GUID make_guid_rt(const std::string &str) { #ifndef NDEBUG - return internString(str.c_str()); + return internString(str.c_str()); #else - return make_guid(str.c_str()); + return make_guid(str.c_str()); #endif } } // namespace fggl::util -fggl::util::GUID operator "" _fid(const char* str); -fggl::util::GUID operator "" _fid(const char* str, std::size_t); +fggl::util::GUID operator "" _fid(const char *str); +fggl::util::GUID operator "" _fid(const char *str, std::size_t); #endif //FGGL_UTIL_GUID_HPP diff --git a/include/fggl/util/safety.hpp b/include/fggl/util/safety.hpp index e11a5723555cc17669fa8b1c354d7032dee0c35e..1daf295d1df7de35889e143bc37d6d3adf4e0e83 100644 --- a/include/fggl/util/safety.hpp +++ b/include/fggl/util/safety.hpp @@ -40,6 +40,7 @@ namespace fggl::util { public: explicit constexpr OpaqueName(T value) : m_value(value) {} + constexpr OpaqueName() : m_value() {} constexpr T get() const { diff --git a/include/fggl/util/states.hpp b/include/fggl/util/states.hpp index e5b81ccf2f2778f7c2788e9b13b4c917c48c48c7..943ffb851311680d23f44c12c1f9a9c86920005f 100644 --- a/include/fggl/util/states.hpp +++ b/include/fggl/util/states.hpp @@ -51,7 +51,7 @@ namespace fggl::util { } bool change(const Identifer &name) { - if ( m_states.find(name) == m_states.end() ) { + if (m_states.find(name) == m_states.end()) { debug::error("attempted to change to non-existent state {}, ignoring you.", name); return false; }