Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
  • gamedev/fggl
  • onuralpsezer/fggl
2 results
Show changes
Showing
with 1842 additions and 1754 deletions
......@@ -26,29 +26,27 @@ namespace fggl::audio {
class NullAudioService : public AudioService {
public:
NullAudioService() = default;
virtual ~NullAudioService() = default;
~NullAudioService() override = default;
void play(const std::string& filename, bool looping = false) override {}
void play(AudioClip& clip, bool looping = false) override {}
NullAudioService(NullAudioService&) = delete;
NullAudioService(NullAudioService&&) = delete;
NullAudioService& operator=(const NullAudioService&) = delete;
NullAudioService& operator=(NullAudioService&&) = delete;
void play(const std::string & /*filename*/, bool /*looping = false*/) override;
void play(const AudioClipShort & /*clip*/, bool /*looping = false*/) override;
};
//! A dummy audio module that does nothing
struct NullAudio {
constexpr static const char* name = "fggl::audio::NULL";
constexpr static const std::array<modules::ModuleService, 1> provides = {
constexpr static const char *name = "fggl::audio::NULL";
constexpr static const std::array<modules::ServiceName, 1> provides = {
SERVICE_AUDIO_PLAYBACK
};
constexpr static const std::array<modules::ModuleService, 0> depends = {};
static const modules::ServiceFactory factory;
constexpr static const std::array<modules::ServiceName, 0> depends = {};
bool factory(modules::ServiceName, modules::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
......
......@@ -23,6 +23,8 @@
#include <AL/alc.h>
#include "fggl/audio/audio.hpp"
#include "fggl/assets/manager.hpp"
#include "fggl/data/storage.hpp"
#include "fggl/math/types.hpp"
......@@ -30,8 +32,16 @@
#include <iostream>
#include <memory>
//! Audio backed by openal-soft
namespace fggl::audio::openal {
constexpr uint32_t NULL_BUFFER_ID = 0;
assets::AssetRefRaw load_vorbis(assets::Loader* loader, const assets::AssetID &, const assets::LoaderContext &, void* userPtr);
bool load_vorbis_short(std::filesystem::path path, assets::MemoryBlock& block);
assets::AssetTypeID check_vorbis( const std::filesystem::path& path );
enum class AudioType {
MONO_8 = AL_FORMAT_MONO8,
MONO_16 = AL_FORMAT_MONO16,
......@@ -39,69 +49,78 @@ namespace fggl::audio::openal {
STEREO_16 = AL_FORMAT_STEREO16
};
static void checkError(std::string context) {
static void check_error(const 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";
switch (code) {
case ALC_INVALID_DEVICE: error = "Invalid Device";
break;
case ALC_INVALID_CONTEXT:
error = "Invalid Context";
case ALC_INVALID_CONTEXT: error = "Invalid Context";
break;
case ALC_INVALID_ENUM:
error = "Invalid enum";
case ALC_INVALID_ENUM: error = "Invalid enum";
break;
case ALC_INVALID_VALUE:
error = "Invalid value";
case ALC_INVALID_VALUE: error = "Invalid value";
break;
case ALC_OUT_OF_MEMORY:
error = "Out of memory";
case ALC_OUT_OF_MEMORY: error = "Out of memory";
break;
default:
error = "unknown error";
default: error = "unknown error";
}
std::cerr << "OpenAL error: " << context << ": " << error << std::endl;
debug::error("OpenAL error: context={}, error={}", context, error);
}
class AudioBuffer {
public:
AudioBuffer() : m_buffer(0) {
AudioBuffer() : m_buffer(NULL_BUFFER_ID) {
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);
AudioBuffer(const AudioBuffer&) = delete;
AudioBuffer(const AudioBuffer&&) = delete;
AudioBuffer& operator=(const AudioBuffer&) = delete;
AudioBuffer& operator=(const AudioBuffer&&) = delete;
inline void setData(AudioType type, void *data, ALsizei size, ALsizei frequency) {
assert( m_buffer != 0 );
assert( data != nullptr );
alBufferData(m_buffer, (ALenum) type, data, size, frequency);
}
inline ALuint value() {
inline ALuint value() const {
return m_buffer;
}
private:
ALuint m_buffer;
ALuint m_buffer = 0;
};
class AudioSource {
public:
AudioSource() : m_source(0), m_splat() {
alGenSources(1, &m_source);
}
~AudioSource(){
~AudioSource() {
alDeleteSources(1, &m_source);
}
AudioSource(const AudioSource& source) = delete;
AudioSource(const AudioSource&& source) = delete;
AudioSource& operator=(const AudioSource&) = delete;
AudioSource& operator=(AudioSource&&) = delete;
inline void play() {
alSourcePlay( m_source );
alSourcePlay(m_source);
}
inline void stop() {
......@@ -109,40 +128,30 @@ 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);
alSourcePlay(m_source);
}
inline void play(AudioClip& clip, bool looping) {
checkError("pre play");
AudioType format = clip.channels == 1 ? AudioType::MONO_8 : AudioType::STEREO_8;
m_splat.setData(format, clip.data, clip.sampleCount, clip.sampleRate);
checkError("saving to buffer");
alSourcei(m_source, AL_BUFFER, m_splat.value());
alSourcei( m_source, AL_LOOPING, looping ? AL_TRUE : AL_FALSE);
checkError("setting parameters");
play();
}
inline void play(const AudioClipShort &clip, bool looping = false);
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,37 +160,36 @@ 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(assets::AssetManager *assets) : m_device(alcOpenDevice(nullptr)), m_assets(assets) {
if (m_device != nullptr) {
m_context = alcCreateContext(m_device, nullptr);
alcMakeContextCurrent(m_context);
checkError("context setup");
check_error("context setup");
m_defaultSource = std::make_unique<AudioSource>();
checkError("default source setup");
check_error("default source setup");
}
}
~AudioServiceOAL() override {
if ( m_device != nullptr ) {
alcDestroyContext(m_context);
alcCloseDevice(m_device);
if (m_device != nullptr) {
release();
}
}
void play(const std::string& filename, bool looping = false) override;
void play(AudioClip& clip, bool looping = false) override;
void play(const assets::AssetGUID &filename, bool looping = false) override;
void play(const AudioClipShort &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;
};
assets::AssetManager* m_assets;
void release();
};
} // namespace fggl::audio::openal
......
......@@ -21,31 +21,31 @@
#include <array>
#include <string>
#include "fggl/assets/module.hpp"
#include "fggl/assets/packed/module.hpp"
#include "fggl/audio/audio.hpp"
#include "fggl/audio/openal/audio.hpp"
namespace fggl::audio {
constexpr auto OGG_VORBIS = assets::AssetType::make("audio/vorbis");
constexpr auto RES_OGG_VORBIS = assets::from_mime("audio/vorbis");
//! an audio module which uses openal(-soft) as a backend.
struct OpenAL {
constexpr static const char* name = "fggl::audio::OpenAL";
constexpr static const std::array<modules::ModuleService, 1> provides = {
constexpr static const char *name = "fggl::audio::OpenAL";
constexpr static const std::array<modules::ServiceName, 1> provides = {
SERVICE_AUDIO_PLAYBACK
};
constexpr static const std::array<modules::ModuleService, 1> depends = {
modules::make_service("fggl::data::Storage")
constexpr static const std::array<modules::ServiceName, 2> depends = {
assets::AssetManager::service,
assets::CheckinAdapted::service
};
static const modules::ServiceFactory factory;
static bool factory(modules::ServiceName name, modules::Services &serviceManager);
};
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);
return true;
}
return false;
}
const modules::ServiceFactory OpenAL::factory = openal_factory;
} // namespace fggl::audio
......
/*
* This file is part of FGGL.
*
* FGGL is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any
* later version.
*
* FGGL is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with FGGL.
* If not, see <https://www.gnu.org/licenses/>.
*/
//
// Created by webpigeon on 18/10/22.
//
#ifndef FGGL_DATA_ASSIMP_MODULE_HPP
#define FGGL_DATA_ASSIMP_MODULE_HPP
#include "fggl/modules/module.hpp"
#include "fggl/assets/loader.hpp"
#include "fggl/assets/packed/module.hpp"
#include "fggl/data/texture.hpp"
namespace fggl::data::models {
constexpr auto MODEL_PROVIDER = modules::make_service("fggl::data::Model");
constexpr auto ASSIMP_MODEL = assets::AssetType::make("model::assimp");
constexpr auto MIME_JPG = assets::from_mime("image/jpeg");
constexpr auto MIME_PNG = assets::from_mime("image/png");
constexpr auto MIME_OBJ = assets::from_mime("model/obj");
constexpr auto MIME_FBX = assets::from_mime("model/fbx");
constexpr auto MODEL_MULTI3D = assets::make_asset_type("model/multi3D");
constexpr auto TEXTURE_RGBA = assets::make_asset_type("texture/rgba");
// old-style loaders
assets::AssetRefRaw load_assimp_model(assets::Loader* loader, const assets::AssetID& guid, const assets::LoaderContext& data, void* userPtr);
assets::AssetRefRaw load_assimp_texture(assets::Loader* loader, const assets::AssetID& guid, const assets::LoaderContext& data, void* userPtr);
// new style loaders (textures)
bool load_tex_stb(const std::filesystem::path& filePath, assets::MemoryBlock& block);
assets::AssetTypeID is_tex_stb(const std::filesystem::path& filePath);
// new style loaders (models)
assets::AssetTypeID is_model_assimp(const std::filesystem::path& filePath);
bool extract_requirements(const std::string& packName, const std::filesystem::path& packRoot, assets::ResourceRecord& rr);
struct AssimpModule {
constexpr static const char *name = "fggl::data::Assimp";
constexpr static const std::array<modules::ServiceName, 1> provides = {
MODEL_PROVIDER
};
constexpr static const std::array<modules::ServiceName, 2> depends = {
assets::Loader::service,
assets::CheckinAdapted::service
};
static bool factory(modules::ServiceName service, modules::Services &serviceManager);
};
}
namespace fggl::data {
using AssimpLoader = models::AssimpModule;
}
#endif //FGGL_DATA_ASSIMP_MODULE_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;
......
......@@ -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
......@@ -27,10 +27,11 @@ namespace fggl::data {
constexpr math::vec3 ILLEGAL_NORMAL{0.0F, 0.0F, 0.F};
constexpr math::vec3 DEFAULT_COLOUR{1.0F, 1.0F, 1.0F};
struct Vertex {
math::vec3 posititon;
math::vec3 normal;
math::vec3 colour;
math::vec3 normal = ILLEGAL_NORMAL;
math::vec3 colour = DEFAULT_COLOUR;
math::vec2 texPos;
inline static Vertex from_pos(math::vec3 pos) {
......@@ -43,6 +44,22 @@ namespace fggl::data {
}
};
// comparison operators
inline bool operator<(const Vertex &lhs, const Vertex &rhs) {
return std::tie(lhs.posititon, lhs.normal, lhs.colour)
< std::tie(rhs.posititon, rhs.normal, rhs.colour);
}
inline bool operator==(const Vertex &lhs, const Vertex &rhs) {
return lhs.posititon == rhs.posititon
&& lhs.colour == rhs.colour
&& lhs.normal == rhs.normal;
}
inline bool operator!=(const Vertex &lhs, const Vertex &rhs) {
return !(lhs == rhs);
}
struct Vertex2D {
fggl::math::vec2 position;
fggl::math::vec3 colour;
......@@ -64,23 +81,6 @@ namespace fggl::data {
};
// comparison operators
inline bool operator<(const Vertex &lhs, const Vertex &rhs) {
return std::tie(lhs.posititon, lhs.normal, lhs.colour)
< std::tie(rhs.posititon, rhs.normal, rhs.colour);
}
inline bool operator==(const Vertex &lhs, const Vertex &rhs) {
return lhs.posititon == rhs.posititon
&& lhs.colour == rhs.colour
&& lhs.normal == rhs.normal;
}
inline bool operator!=(const Vertex &lhs, const Vertex &rhs) {
return !(lhs == rhs);
}
class Mesh {
public:
using IndexType = unsigned int;
......@@ -134,19 +134,19 @@ namespace fggl::data {
*/
IndexType indexOf(Vertex vert);
inline std::vector<Vertex> &vertexList() {
inline const std::vector<Vertex> &vertexList() const {
return m_verts;
}
inline std::size_t vertexCount() {
inline std::size_t vertexCount() const {
return m_verts.size();
}
inline std::vector<IndexType> &indexList() {
inline const std::vector<IndexType> &indexList() const {
return m_index;
}
inline std::size_t indexCount() {
inline std::size_t indexCount() const {
return m_index.size();
}
......@@ -167,25 +167,11 @@ namespace fggl::data {
data::Mesh mesh;
std::string pipeline;
inline StaticMesh() : mesh(), pipeline() {}
inline StaticMesh() = default;
inline StaticMesh(const data::Mesh &aMesh, std::string aPipeline) :
mesh(aMesh), pipeline(std::move(aPipeline)) {}
};
class Model {
public:
Model() = default;
~Model() = default;
inline void append(const Mesh &mesh) {
m_meshes.push_back(mesh);
}
private:
std::vector<Mesh> m_meshes;
};
}
#endif
......@@ -25,27 +25,15 @@
namespace fggl::data {
struct LocalStorage {
constexpr static const char* name = "fggl::data::Storage";
constexpr static const std::array<modules::ModuleService, 1> provides = {
constexpr static const char *name = "fggl::data::Storage";
constexpr static const std::array<modules::ServiceName, 1> provides = {
SERVICE_STORAGE
};
constexpr static const std::array<modules::ModuleService, 0> depends = {};
static const modules::ServiceFactory factory;
constexpr static const std::array<modules::ServiceName, 0> depends = {};
static bool factory(modules::ServiceName service, modules::Services &serviceManager);
};
bool storage_factory(modules::ModuleService service, modules::Services& data) {
if (service == SERVICE_STORAGE) {
// FIXME: no easy way to set the application name
auto pathConfig = fggl::platform::calc_engine_paths("fggl-demo");
data.create<Storage>(pathConfig);
return true;
}
return false;
}
const modules::ServiceFactory LocalStorage::factory = storage_factory;
} // namespace fggl::data
#endif //FGGL_DATA_MODULE_HPP
......@@ -16,6 +16,7 @@
#define FGGL_DATA_PROCEDURAL_HPP
#include "model.hpp"
#include "fggl/mesh/mesh.hpp"
namespace fggl::data {
......@@ -27,24 +28,24 @@ namespace fggl::data {
Mesh make_quad_xz();
// platonic solids
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_tetrahedron(Mesh &mesh, const math::mat4 &offset = OFFSET_NONE);
mesh::Mesh3D make_cube(mesh::Mesh3D &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);
Mesh make_ditch(Mesh &mesh, const math::mat4 &offset = OFFSET_NONE);
Mesh make_point(Mesh &mesh, const math::mat4 &offset = OFFSET_NONE);
mesh::Mesh3D make_slope(mesh::Mesh3D &mesh, const math::mat4 &offset = OFFSET_NONE);
mesh::Mesh3D make_ditch(mesh::Mesh3D &mesh, const math::mat4 &offset = OFFSET_NONE);
mesh::Mesh3D make_point(mesh::Mesh3D &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::Mesh3D &mesh, const math::mat4 &offset = OFFSET_NONE, uint32_t stacks = 16U, uint32_t slices = 16U);
}
#endif
\ No newline at end of file
......@@ -35,12 +35,13 @@ namespace fggl::data {
enum StorageType { Data, Config, Cache };
constexpr const modules::ModuleService SERVICE_STORAGE = modules::make_service("fggl::data::Storage");
constexpr const auto SERVICE_STORAGE = modules::make_service("fggl::data::Storage");
class Storage {
public:
constexpr static modules::ModuleService service = SERVICE_STORAGE;
Storage( fggl::platform::EnginePaths paths ) : m_paths(std::move( paths )) {}
constexpr static auto service = SERVICE_STORAGE;
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());
}
}
......
/*
* This file is part of FGGL.
*
* FGGL is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any
* later version.
*
* FGGL is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with FGGL.
* If not, see <https://www.gnu.org/licenses/>.
*/
//
// Created by webpigeon on 22/10/22.
//
#ifndef FGGL_DATA_TEXTURE_HPP
#define FGGL_DATA_TEXTURE_HPP
#include "fggl/assets/module.hpp"
#include "fggl/math/types.hpp"
namespace fggl::data {
constexpr auto DATA_TEXTURE2D = assets::AssetType::make("gfx::texture");
struct Texture2D {
math::vec2i size;
int channels;
unsigned char* data;
Texture2D() = default;
Texture2D(const Texture2D& other) = delete;
inline ~Texture2D() {
delete data;
}
};
}
#endif //FGGL_DATA_TEXTURE_HPP
......@@ -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) {
......
......@@ -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);
}
}
// ========================================================
......
......@@ -16,10 +16,12 @@
// Created by webpigeon on 11/06/22.
//
#ifndef FGGL_DEBUG_IMPL_LOGGING_STD20_HPP
#define FGGL_DEBUG_IMPL_LOGGING_STD20_HPP
#ifndef FGGL_DEBUG_IMPL_LOGGING_FMT_HPP
#define FGGL_DEBUG_IMPL_LOGGING_FMT_HPP
#include <fmt/format.h>
#include <fmt/color.h>
#include <iostream>
#include <string>
#include <string_view>
......@@ -44,35 +46,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_format_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) {
......@@ -85,13 +80,13 @@ namespace fggl::debug {
template<typename ...T>
inline void error(FmtType fmt, T &&...args) {
auto fmtStr = fmt::format(fmt::runtime(fmt), args...);
fmt::print(CERR_FMT, level_to_string(Level::error), fmtStr);
fmt::print(fg(fmt::color::red), CERR_FMT, level_to_string(Level::error), fmtStr);
}
template<typename ...T>
inline void warning(FmtType fmt, T &&...args) {
auto fmtStr = fmt::format(fmt::runtime(fmt), args...);
fmt::print(CERR_FMT, level_to_string(Level::warning), fmtStr);
fmt::print(fg(fmt::color::orange), CERR_FMT, level_to_string(Level::warning), fmtStr);
}
template<typename ...T>
......@@ -114,4 +109,4 @@ namespace fggl::debug {
}
#endif //FGGL_DEBUG_IMPL_LOGGING_STD20_HPP
#endif //FGGL_DEBUG_IMPL_LOGGING_FMT_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
......@@ -21,33 +21,37 @@
#include <string_view>
namespace fggl::debug {
std::string demangle(const char* name);
using FmtType = const std::string_view;
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_std20.hpp"
#include "fggl/debug/impl/logging_fmt.hpp"
#endif //FGGL_DEBUG_LOGGING_HPP
......@@ -28,18 +28,19 @@
namespace fggl::display {
struct GLFW {
constexpr static const char* name = "fggl::display::glfw";
constexpr static const std::array<modules::ModuleService, 1> provides = {
constexpr static const char *name = "fggl::display::glfw";
constexpr static const std::array<modules::ServiceName, 1> provides = {
WindowService::service
};
constexpr static const std::array<modules::ModuleService, 2> depends = {
constexpr static const std::array<modules::ServiceName, 2> depends = {
fggl::input::Input::service,
fggl::gfx::WindowGraphics::service
};
static const modules::ServiceFactory factory;
static bool factory(modules::ServiceName name, modules::Services &serviceManager);
};
bool glfw_factory(modules::ModuleService service, modules::Services& services) {
bool GLFW::factory(modules::ServiceName service, modules::Services &services) {
if (service == WindowService::service) {
auto input = services.get<input::Input>();
auto graphics = services.get<gfx::WindowGraphics>();
......@@ -50,7 +51,6 @@ namespace fggl::display {
}
return false;
}
const modules::ServiceFactory GLFW::factory = glfw_factory;
} // namespace fggl::display
......
......@@ -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;
};
......
......@@ -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);
}
......
......@@ -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;
};
......