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 715 additions and 1474 deletions
......@@ -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) {
......@@ -80,36 +75,38 @@ namespace fggl::debug {
fmt::print(CERR_FMT, level_to_string(level), fmtStr);
}
template<typename ...T>
void error(FmtType fmt, T &&...args) {
log( Level::error, fmt, args...);
}
// inlined, pre-set level versions of the log function above
template<typename ...T>
void warning(FmtType fmt, T &&...args) {
log( Level::warning, fmt, args...);
inline void error(FmtType fmt, T &&...args) {
auto fmtStr = fmt::format(fmt::runtime(fmt), args...);
fmt::print(fg(fmt::color::red), CERR_FMT, level_to_string(Level::error), fmtStr);
}
template<typename ...T>
void info(FmtType fmt, T &&...args) {
log( Level::info, fmt, args... );
inline void warning(FmtType fmt, T &&...args) {
auto fmtStr = fmt::format(fmt::runtime(fmt), args...);
fmt::print(fg(fmt::color::orange), CERR_FMT, level_to_string(Level::warning), fmtStr);
}
template<typename ...T>
void log(FmtType fmt, T &&...args) {
log( Level::info, fmt, args...);
inline void info(FmtType fmt, T &&...args) {
auto fmtStr = fmt::format(fmt::runtime(fmt), args...);
fmt::print(CERR_FMT, level_to_string(Level::info), fmtStr);
}
template<typename ...T>
void debug(FmtType fmt, T &&...args) {
log( Level::debug, fmt, args...);
inline void debug(FmtType fmt, T &&...args) {
auto fmtStr = fmt::format(fmt::runtime(fmt), args...);
fmt::print(CERR_FMT, level_to_string(Level::debug), fmtStr);
}
template<typename ...T>
void trace(FmtType fmt, T &&...args) {
log( Level::trace, fmt, args...);
inline void trace(FmtType fmt, T &&...args) {
auto fmtStr = fmt::format(fmt::runtime(fmt), args...);
fmt::print(CERR_FMT, level_to_string(Level::trace), fmtStr);
}
}
#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;
};
......
......@@ -21,8 +21,10 @@
#include "fggl/modules/module.hpp"
#include "fggl/math/types.hpp"
#include "fggl/gfx/interfaces.hpp"
//! Classes responsible for interacting with display managers
namespace fggl::display {
class Window {
......@@ -30,12 +32,6 @@ namespace fggl::display {
virtual ~Window() = default;
virtual void activate() const = 0;
template<typename T, typename ...Args>
void make_graphics(Args... args) {
activate();
m_graphics = std::make_unique<T>(*this, args...);
}
// window-related getters
[[nodiscard]]
virtual math::vec2i frameSize() const = 0;
......@@ -51,7 +47,7 @@ namespace fggl::display {
return *m_graphics;
}
virtual void setTitle(const char* title) = 0;
virtual void setTitle(const char *title) = 0;
virtual void setFullscreen(bool state) = 0;
......@@ -59,14 +55,15 @@ namespace fggl::display {
virtual bool isFullscreen() const = 0;
protected:
std::unique_ptr<gfx::Graphics> m_graphics;
gfx::Graphics* m_graphics;
};
class WindowService {
public:
constexpr static const modules::ModuleService service = modules::make_service("fggl::display::WindowService");
constexpr static const auto
service = modules::make_service("fggl::display::WindowService");
virtual Window* create() = 0;
virtual Window *create() = 0;
virtual void pollEvents() = 0;
};
......
/*
* 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 25/03/23.
//
#ifndef FGGL_DS_GRAPH_HPP
#define FGGL_DS_GRAPH_HPP
#include <map>
#include <vector>
#include <queue>
#include <stack>
#include <set>
namespace fggl::ds {
template<typename T>
class DirectedGraph {
public:
/**
* Add a single edge to the graph.
*
* If the entry does not already exist, this will create the entry before adding the dependencies to it.
* If the entry already exists, this will append the provided dependencies to its existing list.
*
* @param start the entry which depends something else
* @param end the thing it depends on
*/
inline void addEdge(const T start, const T end) {
m_edges[start].push_back(end);
m_edges[end];
}
/**
* Add a single vertex to the graph.
*/
inline void addVertex(const T vertex) {
m_edges[vertex];
}
/**
* Add a series of dependencies for an entry.
*
* If the entry does not already exist, this will create the entry before adding the dependencies to it.
* If the entry already exists, this will append the provided dependencies to its existing list.
*
* @param name the entry having dependencies added
* @param dependencies the things it depends on
*/
void addEdges(const T name, const std::vector<T> &dependencies) {
auto existing = m_edges.find(name);
if (existing == m_edges.end()) {
m_edges[name] = dependencies;
} else {
existing->second.insert(existing->second.end(), dependencies.begin(), dependencies.end());
}
}
/**
* Clear all currently stored dependencies.
*
* This method will result in the dependency graph being empty, with no known modules.
*/
inline void clear() {
m_edges.clear();
}
inline auto begin() const {
return m_edges.begin();
}
inline auto end() const {
return m_edges.end();
}
bool getOrder(std::stack<T> &stack) {
std::set<T> visited{};
for (const auto &module : m_edges) {
if (!visited.contains(module.first)) {
sortUtil(module.first, visited, stack);
}
}
return true;
}
bool getOrderPartial(T first, std::stack<T> &stack) {
std::set<T> visited{};
sortUtil(first, visited, stack);
return true;
}
bool getOrderRev(std::queue<T> &stack) {
std::set<T> visited{};
for (const auto &module : m_edges) {
if (!visited.contains(module.first)) {
sortUtilRev(module.first, visited, stack);
}
}
return true;
}
bool getOrderPartialRev(T first, std::queue<T>& queue) {
std::set<T> visited{};
sortUtilRev(first, visited, queue);
return true;
}
private:
std::map<T, std::vector<T>> m_edges;
void sortUtil(T idx, std::set<T> &visited, std::stack<T> &stack) {
visited.emplace(idx);
for (auto dep : m_edges.at(idx)) {
if (!visited.contains(dep))
sortUtil(dep, visited, stack);
}
stack.push(idx);
}
void sortUtilRev(T idx, std::set<T> &visited, std::queue<T> &stack) {
visited.emplace(idx);
for (auto dep : m_edges.at(idx)) {
if (!visited.contains(dep))
sortUtilRev(dep, visited, stack);
}
stack.push(idx);
}
};
} // namespace fggl::ds
#endif //FGGL_DS_GRAPH_HPP
......@@ -32,12 +32,12 @@ namespace fggl::ds {
using WeakRef = std::size_t;
constexpr static WeakRef BAD_INDEX = 0;
bool valid(WeakRef idx) const {
inline bool valid(WeakRef idx) const {
return m_data.find(idx) != m_data.end();
}
WeakRef allocate() {
if ( N <= m_data.size() ) {
if (N <= m_data.size()) {
assert(0 && "Fake slot map emulated out of space");
return BAD_INDEX;
}
......@@ -50,13 +50,13 @@ namespace fggl::ds {
m_data.erase(idx);
}
T& get(WeakRef idx) const {
assert( valid(idx) );
T &get(WeakRef idx) const {
assert(valid(idx));
return m_data[idx];
}
T* tryGet(WeakRef idx) const {
if( valid(idx) ) {
T *tryGet(WeakRef idx) const {
if (valid(idx)) {
return &m_data[idx];
}
return nullptr;
......@@ -67,9 +67,6 @@ namespace fggl::ds {
std::size_t m_nextIdx = 1;
};
template<typename T, std::size_t N>
using SlotMap = FakeSlotMap<T, N>;
} // namespace fggl::ds
#endif //FGGL_DS_PLACEHOLDER_HPP
......@@ -12,19 +12,20 @@
* If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef FGGL_DATA_PROCEDURE_HPP
#define FGGL_DATA_PROCEDURE_HPP
//
// Created by webpigeon on 23/07/22.
//
namespace fggl::data {
#ifndef FGGL_DS_SLOT_MAP_HPP
#define FGGL_DS_SLOT_MAP_HPP
class DataRegistry {
#include "fggl/ds/placeholder.hpp"
public:
DataRegistry();
~DataRegistry();
namespace fggl::ds {
};
template<typename T, std::size_t N>
using SlotMap = FakeSlotMap<T, N>;
}
} // namespace fggl::ds
#endif
#endif //FGGL_DS_SLOT_MAP_HPP
/*
* 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/>.
*/
#ifndef FGGL_ECS_COMPONENT_HPP
#define FGGL_ECS_COMPONENT_HPP
#include "utility.hpp"
#include "fggl/debug/logging.hpp"
#include <cassert>
#include <cstring>
#include <string>
#include <new>
#include <utility>
#include <iostream>
#include <typeinfo>
#include <vector>
#include <unordered_map>
#include "yaml-cpp/yaml.h"
namespace fggl::ecs {
template<typename T>
bool restore_config(T* comp, const YAML::Node& node);
class ComponentBase {
public:
using data_t = unsigned char;
virtual ~ComponentBase() {};
// in place
virtual void destroy(data_t *data) const = 0;
virtual void move(data_t *src, data_t *dest) const = 0;
virtual void bulkMove(data_t *src, data_t *dest, std::size_t count) = 0;
virtual void construct(data_t *data) const = 0;
// virtual
virtual void *construct() const = 0;
virtual void *restore(const YAML::Node& config) const = 0;
virtual void *copyConstruct(const void *src) = 0;
virtual const char *name() const = 0;
virtual const component_type_t id() const = 0;
virtual std::size_t size() const = 0;
};
template<class C>
class Component : public ComponentBase {
public:
virtual void destroy(data_t *data) const override {
C *location = std::launder(reinterpret_cast<C *>(data));
location->~C();
}
virtual const char *name() const override {
return C::name;
}
virtual const component_type_t id() const {
return Component<C>::typeID();
}
virtual void construct(unsigned char *data) const override {
new(data) C();
}
virtual void* restore(const YAML::Node& config) const override {
C* ptr = new C();
bool restored = restore_config<C>(ptr, config);
if ( !restored ) {
debug::error("error restoring {}", C::name);
assert( false && "failed to restore configuration when loading type!" );
}
return ptr;
}
void *copyConstruct(const void *src) override {
const C *srcPtr = (C *) src;
return new C(*srcPtr);
}
void *construct() const override {
return new C();
}
virtual void move(data_t *src, data_t *dest) const override {
assert(src != nullptr);
assert(dest != nullptr);
new(&dest[0]) C(std::move(*reinterpret_cast<C *>(src)));
}
virtual void bulkMove(data_t *src, data_t *dest, std::size_t count) {
if (std::is_trivially_copyable<C>::value) {
std::memcpy(dest, src, count * size());
} else {
unsigned char *srcPtr = src;
unsigned char *destPtr = dest;
for (std::size_t i = 0; i < count; ++i) {
new(destPtr) C(std::move(*reinterpret_cast<C *>(srcPtr)));
srcPtr += sizeof(C);
destPtr += sizeof(C);
}
}
}
virtual std::size_t size() const {
return sizeof(C);
}
static component_type_t typeID() {
return TypeIdGenerator<ComponentBase>::GetNewID<C>();
}
};
}
#endif
/*
* 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/07/22.
//
#ifndef FGGL_ECS_COMPONENT_FWD_HPP
#define FGGL_ECS_COMPONENT_FWD_HPP
#include "fggl/ecs/component.hpp"
#include "fggl/math/types.hpp"
#include "fggl/gfx/phong.hpp"
#include "fggl/data/model.hpp"
#include "fggl/phys/types.hpp"
#ifdef __GNUC__
#include <cxxabi.h>
#endif
namespace fggl::ecs {
template<typename T>
bool restore_config(T* comp, const YAML::Node& node) {
char* realName;
#ifdef __GNUC__
int status;
realName = abi::__cxa_demangle(typeid(T).name(), 0, 0, &status);
#endif
debug::log(debug::Level::warning, "restore_config is not implemented for {}", realName);
return false;
}
template<>
bool restore_config(math::Transform* comp, const YAML::Node& node);
template<>
bool restore_config(gfx::PhongMaterial* comp, const YAML::Node& node);
template<>
bool restore_config(data::StaticMesh* meshComp, const YAML::Node& node);
template<>
bool restore_config(phys::RigidBody* body, const YAML::Node& node);
template<>
bool restore_config(phys::CollisionCallbacks* callbacks, const YAML::Node& node);
template<>
bool restore_config(phys::CollisionCache* cache, const YAML::Node& node);
} // namespace fggl::ecs
#endif //FGGL_ECS_COMPONENT_FWD_HPP
/*
* 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/>.
*/
#ifndef FGGL_ECS_ECS_HPP
#define FGGL_ECS_ECS_HPP
#include "utility.hpp"
#include "component.hpp"
#include <iostream>
#include <algorithm>
#include <cassert>
#include <string>
#include <vector>
#include <unordered_map>
namespace fggl::ecs {
using archToken_t = std::vector<component_type_t>;
struct Archetype {
constexpr static unsigned int default_cap = 0;
const archToken_t type;
std::vector<ComponentBase::data_t *> data;
std::vector<std::size_t> dataSizes;
std::vector<entity_t> entities;
Archetype(const archToken_t &type_a);
inline archToken_t create(const component_type_t cid) const {
assert(!contains(cid));
// create the new type
auto newType = type;
newType.push_back(cid);
std::sort(newType.begin(), newType.end());
return newType;
}
inline bool contains(const component_type_t cid) const {
return (std::find(type.begin(), type.end(), cid) != type.end());
}
};
class ECS {
struct Record {
Archetype *archetype;
std::size_t index;
};
using componentmap_t = std::unordered_map<component_type_t, ComponentBase *>;
using entitymap_t = std::unordered_map<entity_t, Record>;
using archetype_t = std::vector<Archetype *>;
public:
ECS();
~ECS();
entity_t getNewID();
entity_t createEntity();
void removeEntity(const entity_t eid);
template<class C>
void registerComponent() {
component_type_t type = Component<C>::typeID();
if (m_componentMap.find(type) != m_componentMap.end())
return;
m_componentMap.emplace(type, new Component<C>);
}
template<class C>
bool isComponentRegistered() {
component_type_t type = Component<C>::typeID();
return (m_componentMap.find(type) != m_componentMap.end());
}
template<class C, typename... Args>
C *addComponent(const entity_t &id, Args &&... args) {
component_type_t type = Component<C>::typeID();
assert(isComponentRegistered<C>());
Record &record = m_entityArchtypes[id];
Archetype *oldArch = record.archetype;
C *newComp = nullptr;
Archetype *newArch = nullptr;
if (!oldArch) {
archToken_t newID(1, type);
const ComponentBase *const newCompType = m_componentMap[type];
// fetch type
newArch = getArchetype(newID);
assert(newArch->type.size() == 1);
// calculate if we have enouph space to allocate
std::size_t emplacementPos = ensureCapacity(newArch, 0, newCompType);
newComp = new(&newArch->data[0][emplacementPos])C(std::forward<Args>(args)...);
} else {
// check if the arch contains the component
if (oldArch->contains(type)) {
return nullptr;
}
// create a new archetype with the component
auto newID = oldArch->create(type);
newArch = getArchetype(newID);
// relocate the old data to the new archetype
for (std::size_t j = 0; j < newID.size(); ++j) {
const component_type_t compType = newID[j];
const ComponentBase *const comp = m_componentMap.at(compType);
// TODO this seems a little suspect - surely we could allocate all blocks at once?
// if per component the arrays could become out of sync...
int newOffset = ensureCapacity(newArch, j, comp);
int oldIdx = getComponentIdx(oldArch, compType);
if (oldIdx != -1) {
assert(oldArch->contains(compType));
const std::size_t compSize = comp->size();
const std::size_t oldOffset = record.index * compSize;
comp->move(&oldArch->data[oldIdx][oldOffset],
&newArch->data[j][newOffset]);
comp->destroy(&oldArch->data[oldIdx][oldOffset]);
} else {
assert(!oldArch->contains(compType));
newComp = new(&newArch->data[j][newOffset])
C(std::forward<Args>(args)...);
}
}
// ensure the old archetype is still contigious
const int lastEnt = oldArch->entities.size() - 1;
if (lastEnt != record.index) {
for (std::size_t i = 0; i < oldArch->type.size(); ++i) {
const component_type_t typeID = oldArch->type[i];
const ComponentBase *const comp = m_componentMap[typeID];
const std::size_t &compSize = comp->size();
// shift the empty record to the end of the list
std::size_t slotOffset = record.index * compSize;
std::size_t lastOffset = lastEnt * compSize;
// if we're not the last entity, swap
if (slotOffset != lastOffset) {
comp->move(&oldArch->data[i][lastOffset],
&oldArch->data[i][slotOffset]);
comp->destroy(&oldArch->data[i][lastOffset]);
}
}
// fix the position
oldArch->entities[record.index] = oldArch->entities[lastEnt];
}
oldArch->entities.pop_back();
}
// register the new data with the new archetype
newArch->entities.push_back(id);
record.index = newArch->entities.size() - 1;
record.archetype = newArch;
return newComp;
}
template<class C>
void removeComponent(const entity_t &entityId);
template<class C>
bool hasComponent(const entity_t &entityId) const {
const component_type_t componentID = Component<C>::typeID();
const auto *arch = m_entityArchtypes.at(entityId).archetype;
if (arch == nullptr) {
return false;
}
return (std::find(arch->type.begin(), arch->type.end(), componentID) !=
arch->type.end());
}
template<class C>
C *getComponent(const entity_t &entityId) {
assert(hasComponent<C>(entityId));
const auto type = Component<C>::typeID();
const ComponentBase *const newComp = m_componentMap[type];
const auto record = m_entityArchtypes.at(entityId);
const auto *arch = record.archetype;
// JWR: linear search... seems a little suspect, they're ordered after all
for (std::size_t i = 0; i < arch->type.size(); ++i) {
if (arch->type[i] == type) {
return reinterpret_cast<C *>(&(arch->data[i][record.index * newComp->size()]));
}
}
return nullptr;
}
template<class C>
const C *getComponent(const entity_t &entityId) const {
assert(hasComponent<C>(entityId));
const auto type = Component<C>::typeID();
const ComponentBase *const newComp = m_componentMap.at(type);
const auto record = m_entityArchtypes.at(entityId);
const auto *arch = record.archetype;
// JWR: linear search... seems a little suspect, they're ordered after all
for (std::size_t i = 0; i < arch->type.size(); ++i) {
if (arch->type[i] == type) {
return reinterpret_cast<C *>(&(arch->data[i][record.index * newComp->size()]));
}
}
return nullptr;
}
template<class... Cs>
std::vector<entity_t> getEntityWith() const {
// construct the key
archToken_t key;
(key.push_back(Component<Cs>::typeID()), ...);
// entities
std::vector<entity_t> entities;
for (Archetype *arch : m_archetypes) {
if (std::includes(arch->type.begin(), arch->type.end(), key.begin(), key.end())) {
if (!arch->entities.empty()) {
entities.insert(entities.begin(), arch->entities.begin(), arch->entities.end());
}
}
}
return entities;
}
private:
entitymap_t m_entityArchtypes;
archetype_t m_archetypes;
entity_t m_entityIDCounter;
componentmap_t m_componentMap;
Archetype *getArchetype(const archToken_t &id);
inline std::string arch2str(Archetype *arch) {
std::string str;
for (const auto &type : arch->type) {
str += std::to_string(type);
}
return str;
}
inline std::size_t ensureCapacity(Archetype *arch, const int idx, const ComponentBase *const comp) {
const std::size_t &compSize = comp->size();
std::size_t currSize = arch->entities.size() * compSize;
std::size_t newSize = currSize + compSize;
std::size_t cap = arch->dataSizes[idx];
if (newSize > arch->dataSizes[idx]) {
arch->dataSizes[idx] *= 2;
arch->dataSizes[idx] += compSize;
// copy data over
unsigned char *newData = new unsigned char[arch->dataSizes[idx]];
for (std::size_t e = 0; e < arch->entities.size(); ++e) {
const int offset = e * compSize;
comp->move(&arch->data[idx][offset], &newData[offset]);
comp->destroy(&arch->data[idx][offset]);
}
// free the old data and swap the pointers
delete[] arch->data[idx];
arch->data[idx] = newData;
}
return currSize;
}
inline int getComponentIdx(const Archetype *arch, const component_type_t goal) {
// JWR could do binary search for speedup
for (std::size_t i = 0; i < arch->type.size(); ++i) {
if (arch->type[i] == goal)
return i;
}
return -1;
}
};
}
#endif
/*
* 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 23/10/2021.
//
#ifndef FGGL_ECS3_FAST_CONTAINER_HPP
#define FGGL_ECS3_FAST_CONTAINER_HPP
#include <cstdint>
#include <cstdarg>
#include <cassert>
#include <fggl/ecs3/types.hpp>
namespace fggl::ecs3 {
class Container {
public:
const RecordIdentifier m_identifier;
Container(const TypeRegistry &reg, RecordIdentifier id) :
m_identifier(id),
m_types(reg),
backingStore(nullptr),
m_size(0),
m_capacity(0) {};
~Container() {
delete[] backingStore;
}
std::size_t create();
void remove(std::size_t pos);
std::size_t expand(Container &other, std::size_t otherPos, component_type_t newComp);
void contract(Container &other, std::size_t otherPos);
void ensure(std::size_t size);
inline unsigned char *data_raw(component_type_t type) {
auto seek_id = m_identifier.idx(type);
// you asked for something I don't contain...
if (seek_id == m_identifier.count) {
std::cerr << "asked for " << type << " from " << m_identifier << std::endl;
assert(seek_id != m_identifier.count);
return nullptr;
}
// figure out the offset
return backingStore + offsets[seek_id];
}
template<typename T>
inline T *data() {
auto comp_id = Component<T>::typeID();
return (T *) data_raw(comp_id);
}
template<typename T>
T *set(std::size_t entity, T *compData) {
auto *comps = data<T>();
auto entityPos = idx(entity);
auto compMeta = m_types.template meta<T>();
unsigned char *usrPtr = (unsigned char *) &comps[entityPos];
compMeta->destroy(usrPtr);
compMeta->move((unsigned char *) compData, usrPtr);
return &comps[entityPos];
}
[[nodiscard]]
inline std::size_t size() const {
return m_size;
}
inline std::size_t idx(entity_t entity) {
auto *entityData = data<EntityMeta>();
for (std::size_t i = 0; i < m_size; i++) {
if (entityData[i].id == entity) {
return i;
}
}
return m_size;
}
private:
const TypeRegistry &m_types;
unsigned char *backingStore;
std::size_t offsets[RecordIdentifier::MAX_COMPS]{};
std::size_t m_size;
std::size_t m_capacity;
void move(std::size_t newPos, Container &oldContainer, std::size_t oldPos);
};
}
#endif //FGGL_ECS3_FAST_CONTAINER_HPP
/*
* 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/>.
*/
#ifndef FGGL_ECS3_FAST_ECS_HPP
#define FGGL_ECS3_FAST_ECS_HPP
#include <cstddef>
#include <cstdarg>
#include <cassert>
#include <cstring>
#include <map>
#include <algorithm>
#include <iostream>
#include <type_traits>
#include <fggl/ecs3/utils.hpp>
#include <fggl/ecs3/types.hpp>
#include <fggl/ecs3/fast/Container.hpp>
namespace fggl::ecs3::fast {
using entity_t = unsigned int;
constexpr entity_t NULL_ENTITY = 0;
class World {
public:
explicit World(TypeRegistry &reg) : m_registry(reg), m_last(NULL_ENTITY) {}
entity_t create() {
auto next = m_last++;
auto arch = make_id(1, Component<EntityMeta>::typeID());
auto &container = getContainer(arch);
m_entities[next] = container.m_identifier;
auto pos = container.create();
auto *entityMeta = container.data<EntityMeta>();
entityMeta[pos].id = next;
return next;
}
void remove(entity_t entity) {
auto arch = m_entities.at(entity);
auto container = m_records.at(arch);
auto entPos = container.idx(entity);
container.remove(entPos);
}
inline Container &getContainer(RecordIdentifier &arch) {
try {
return m_records.at(arch);
} catch (std::out_of_range &e) {
auto v = m_records.emplace(std::pair<RecordIdentifier, Container>(arch, {m_registry, arch}));
return v.first->second;
}
}
template<typename T>
T *add(const entity_t entity) {
auto currArch = m_entities.at(entity);
auto newArch = currArch.with<T>();
m_entities[entity] = newArch;
auto &oldContainer = m_records.at(currArch);
auto &newContainer = getContainer(newArch);
auto oldPos = oldContainer.idx(entity);
auto newPos = newContainer.expand(oldContainer, oldPos, Component<T>::typeID());
auto *data = newContainer.template data<T>();
return &data[newPos];
}
template<typename T>
T *set(const entity_t entity, T *record) {
auto currArch = m_entities.at(entity);
// check we already have that component type...
if (currArch.idx(Component<T>::typeID()) == currArch.count) {
add<T>(entity);
currArch = m_entities.at(entity);
}
auto &container = m_records.at(currArch);
auto pos = container.idx(entity);
return container.set<T>(pos, record);
}
template<typename T>
T *get(entity_t entity) {
auto currArch = m_entities.at(entity);
auto pos = currArch.idx(entity);
auto &container = m_records.at(currArch);
auto *data = container.template data<T>();
return &data[pos];
}
template<typename T>
const T *get(entity_t entity) const {
auto currArch = m_entities.at(entity);
auto pos = currArch.idx(entity);
auto &container = m_records.at(currArch);
auto *data = container.template data<T>();
return &data[pos];
}
template<typename T>
void remove(entity_t entity) {
auto currArch = m_entities.at(entity);
auto newArch = currArch.without<T>();
auto &oldContainer = m_records[currArch];
auto &newContainer = m_records[newArch];
auto oldPos = oldContainer.idx(entity);
auto newPos = newContainer.create();
m_records[newArch].contract(newPos, oldContainer, oldPos);
}
template<typename... T>
std::vector<entity_t> findMatching() const {
return {};
}
private:
TypeRegistry &m_registry;
std::map<RecordIdentifier, Container> m_records;
std::map<entity_t, RecordIdentifier> m_entities;
entity_t m_last{};
};
}
#endif
/*
* 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 23/10/2021.
//
#ifndef FGGL_ECS3_PROTOTYPE_WORLD_HPP
#define FGGL_ECS3_PROTOTYPE_WORLD_HPP
#include <map>
#include <functional>
#include <unordered_set>
#include "fggl/ecs3/types.hpp"
#include "fggl/debug/logging.hpp"
#include <yaml-cpp/yaml.h>
/**
* A component based implementation of a game world.
*
* This is not a true ECS but exposes a similar API to it for testing (with a lot less headaches).
*/
namespace fggl::ecs3::prototype {
using EntityCallback = std::function<void(const entity_t)>;
class Entity {
public:
bool m_abstract;
explicit Entity(entity_t id) : m_abstract(false), m_id(id) {};
Entity(const Entity &entity) : m_id(entity.m_id), m_components(entity.m_components) {
//spdlog::info("entity created fro copy: {}", m_id);
}
~Entity() = default;
template<typename C>
C *add() {
C *ptr = new C();
m_components[Component<C>::typeID()] = ptr;
return ptr;
}
void *add(std::shared_ptr<ComponentBase> t) {
void *ptr = t->construct();
m_components[t->id()] = ptr;
return ptr;
}
void* add(const std::shared_ptr<ComponentBase>& compMeta, const YAML::Node& config) {
void* ptr = compMeta->restore(config);
m_components[ compMeta->id() ] = ptr;
return ptr;
}
template<typename C>
C *set(const C *ptr) {
C *newPtr = new C(*ptr);
m_components[Component<C>::typeID()] = newPtr;
return newPtr;
}
void *set(const std::shared_ptr<ComponentBase> &t, const void *ptr) {
void *newPtr = t->copyConstruct(ptr);
m_components[t->id()] = newPtr;
return newPtr;
}
template<typename C>
C *get() const {
void *ptr = m_components.at(Component<C>::typeID());
return (C *) ptr;
}
template<typename C>
void remove(){
m_components.erase(Component<C>::typeID());
}
inline void *get(component_type_t t) {
return m_components.at(t);
}
std::vector<component_type_t> getComponentIDs() {
std::vector<component_type_t> comps{};
for (auto &[k, _] : m_components) {
comps.push_back(k);
}
return comps;
}
bool hasComponents(std::vector<component_type_t> &Cs) const {
for (auto c : Cs) {
if (m_components.find(c) == m_components.end()) {
return false;
}
}
return true;
}
private:
entity_t m_id;
std::map<component_type_t, void *> m_components;
};
class World {
public:
explicit World(TypeRegistry &reg) : m_types(reg), m_next(1), m_entities() {};
~World() = default;
entity_t create(bool abstract) {
auto nextID = m_next++;
m_entities.emplace(nextID, nextID);
auto &entity = m_entities.at(nextID);
entity.m_abstract = abstract;
// meta data
auto *meta = entity.add<ecs3::EntityMeta>();
meta->id = nextID;
meta->abstract = abstract;
meta->typeName = "";
return nextID;
}
inline entity_t createFromPrototype(const std::string& name) {
auto prototype = findPrototype(name);
if ( prototype == NULL_ENTITY) {
debug::log(debug::Level::warning, "attempted to create from non-existant prototype: {}", name);
return NULL_ENTITY;
}
return copy( prototype );
}
entity_t copy(entity_t prototype) {
auto clone = create(false);
auto components = getComponents(prototype);
for (auto component : components) {
auto protoComp = get(prototype, component);
set(clone, component, protoComp);
}
return clone;
}
void addFromConfig(entity_t entity, component_type_t type, const YAML::Node& node) {
auto meta = m_types.meta(type);
auto& entityObj = m_entities.at(entity);
entityObj.add(meta, node);
m_types.fireAdd(this, entity, meta->id());
}
void createFromSpec(entity_t entity, const YAML::Node& compConfig) {
if ( compConfig ) {
for (const auto& itr : compConfig ) {
const auto name = itr.first.as<std::string>();
const auto& config = itr.second;
auto compType = m_types.find( name.c_str() );
addFromConfig(entity, compType, config);
}
}
}
inline auto alive(entity_t entity) const -> bool {
return entity != NULL_ENTITY
&& m_killList.find( entity ) == m_killList.end()
&& m_entities.find( entity ) != m_entities.end();
}
inline auto exists(entity_t entity) const -> bool {
return entity != NULL_ENTITY
&& m_entities.find( entity ) != m_entities.end();
}
void destroy(entity_t entity) {
assert( alive(entity) && "attempted to kill null entity" );
// TOOD resolve and clean components
//m_entities.erase(entity);
m_killList.insert(entity);
}
void reapEntities() {
for (const auto& entity : m_killList) {
//auto& entityObj = m_entities.at(entity);
//entityObj.clear();
for (auto& listener : m_deathListeners) {
listener( entity );
}
m_entities.erase(entity);
}
m_killList.clear();
}
inline TypeRegistry &types() {
return m_types;
}
std::vector<entity_t> all() {
std::vector<entity_t> entities{};
for (auto &[eid, entity] : m_entities) {
entities.push_back(eid);
}
return entities;
}
std::vector<component_type_t> getComponents(entity_t entityID) {
assert(alive(entityID) && "attempted to get components on dead entity");
std::vector<component_type_t> components{};
auto &entity = m_entities.at(entityID);
auto comps = entity.getComponentIDs();
for (auto id : comps) {
components.push_back(id);
}
return components;
}
template<typename... Cs>
std::vector<entity_t> findMatching() const {
// construct the key
std::vector<ecs::component_type_t> key;
(key.push_back(Component<Cs>::typeID()), ...);
// entities
std::vector<entity_t> entities{};
for (auto &[eid, entity] : m_entities) {
if (entity.hasComponents(key) && !entity.m_abstract) {
entities.push_back(eid);
}
}
return entities;
}
template<typename ...Cs>
bool has(entity_t entityIdx) const {
if ( !alive(entityIdx)) {
return false;
}
std::vector<ecs::component_type_t> key;
(key.push_back(Component<Cs>::typeID()), ...);
return m_entities.at(entityIdx).hasComponents(key);
}
template<typename C>
C *add(entity_t entity_id) {
assert( alive(entity_id) && "attempted to add component on null entity" );
//spdlog::info("component '{}' added to '{}'", C::name, entity_id);
auto &entity = m_entities.at(entity_id);
auto comp = entity.template add<C>();
m_types.fireAdd(this, entity_id, Component<C>::typeID());
return comp;
}
void *add(entity_t entity_id, component_type_t component_id) {
assert( alive(entity_id) && "attempted to add component on null entity" );
auto meta = m_types.meta(component_id);
auto &entity = m_entities.at(entity_id);
void *ptr = entity.add(meta);
m_types.fireAdd(this, entity_id, meta->id());
return ptr;
}
template<typename C>
C *set(entity_t entity_id, const C *ptr) {
assert( alive( entity_id ) && "attempted to set component on null entity" );
//spdlog::info("component '{}' set on '{}'", C::name, entity_id);
auto &entity = m_entities.at(entity_id);
auto comp = entity.set<C>(ptr);
m_types.fireAdd(this, entity_id, Component<C>::typeID());
return comp;
}
void *set(entity_t entity_id, component_type_t cid, const void *ptr) {
assert( alive( entity_id ) && "attempted to set component on null entity" );
auto &entity = m_entities.at(entity_id);
auto cMeta = m_types.meta(cid);
auto comp = entity.set(cMeta, ptr);
m_types.fireAdd(this, entity_id, cid);
return comp;
}
template<typename C>
C* tryGet(entity_t entity_id) const {
if ( entity_id == NULL_ENTITY) {
return nullptr;
}
try {
return get<C>(entity_id);
} catch ( std::out_of_range& e) {
fggl::debug::info("component {} on {} did not exist", C::name, entity_id);
return nullptr;
}
}
template<typename C>
C *get(entity_t entity_id) const {
assert( exists(entity_id) && "attempted to get component on null entity" );
const auto& entity = m_entities.at(entity_id);
return entity.get<C>();
}
template<typename C>
void remove(entity_t entity_id) {
assert( alive(entity_id) && "attempted to remove component on null entity" );
try {
auto &entity = m_entities.at(entity_id);
try {
return entity.remove<C>();
} catch ( std::out_of_range& e ) {
std::cerr << "entity " << entity_id << " does not have component "<< C::name << std::endl;
}
} catch ( std::out_of_range& e) {
std::cerr << "tried to delete component on entity that didn't exist, entity was: " << entity_id << std::endl;
}
}
void *get(entity_t entity_id, component_type_t componentType) {
assert( exists(entity_id) && "attempted to get component on null entity" );
auto &entity = m_entities.at(entity_id);
return entity.get(componentType);
}
void addDeathListener(const EntityCallback& callback) {
m_deathListeners.emplace_back(callback);
}
entity_t findPrototype(const std::string& name) const {
for ( const auto& [entity, obj] : m_entities ) {
if ( !obj.m_abstract ){
continue;
}
auto* metaData = obj.get<EntityMeta>();
if ( metaData->typeName == name){
return entity;
}
}
return NULL_ENTITY;
}
private:
std::vector<EntityCallback > m_deathListeners;
TypeRegistry &m_types;
entity_t m_next;
std::map<entity_t, Entity> m_entities;
std::unordered_set<entity_t> m_killList;
};
}
#endif //FGGL_ECS3_PROTOTYPE_WORLD_HPP
/*
* 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/>.
*/
#ifndef FGGL_ECS3_TYPES_HPP
#define FGGL_ECS3_TYPES_HPP
#include <cstdarg>
#include <utility>
#include <functional>
#include <fggl/ecs/component.hpp>
#include <fggl/ecs3/utils.hpp>
#include <iostream>
#include <memory>
#include <algorithm>
#include <map>
#include <unordered_map>
namespace fggl::ecs3 {
namespace {
using namespace fggl::ecs;
};
namespace prototype {
class World;
}
using fggl::ecs::component_type_t;
class ModuleManager;
using callback_t = std::function<void(prototype::World *, ecs3::entity_t)>;
struct TypeCallbacks {
std::vector<callback_t> add;
};
// core component types
struct EntityMeta {
constexpr static const char name[] = "meta";
entity_t id;
bool abstract;
std::string typeName;
};
struct RecordIdentifier {
constexpr static std::size_t MAX_COMPS = 32;
component_type_t types[MAX_COMPS];
std::size_t count;
[[nodiscard]]
inline std::size_t idx(component_type_t t) const {
return utils::search(types, count, t);
}
template<typename T>
[[nodiscard]]
RecordIdentifier with() const {
// check the caller wasn't a muppet
const auto typeID = ecs::Component<T>::typeID();
if (idx(typeID) != count) {
return *this;
}
RecordIdentifier re{};
re.count = count + 1;
re.types[count] = ecs::Component<T>::typeID();
// add old types
for (std::size_t i = 0; i < count; ++i) {
re.types[i] = types[i];
}
std::sort(re.types, re.types + re.count);
return re;
}
template<typename T>
[[nodiscard]]
RecordIdentifier without() const {
// check the caller wasn't a muppet
const auto typeID = ecs::Component<T>::typeID();
const auto typeIdx = idx(typeID);
if (typeIdx == count) {
return *this;
}
RecordIdentifier re{};
re.count = count - 1;
// add old types
for (std::size_t i = 0, j = 0; i < count; ++i) {
if (typeIdx != i) {
re.types[j] = types[i];
j++;
}
}
std::sort(re.types, re.types + re.count);
return re;
}
bool operator<(const RecordIdentifier &other) const {
if (count < other.count) {
return true;
} else if (count > other.count) {
return false;
} else {
for (std::size_t i = 0; i < count; i++) {
if (types[i] != other.types[i]) {
return types[i] < other.types[i];
}
}
return false;
}
}
bool operator==(const RecordIdentifier &arg) const {
if (arg.count != count) {
return false;
}
for (std::size_t i = 0; i < count; i++) {
if (types[i] != arg.types[i]) {
return false;
}
}
return true;
}
bool operator!=(const RecordIdentifier &arg) const {
return !(*this == arg);
}
};
std::ostream &operator<<(std::ostream &out, RecordIdentifier const &curr);
inline RecordIdentifier make_id(std::size_t count, ...) {
assert(count < RecordIdentifier::MAX_COMPS);
RecordIdentifier re{};
std::va_list args;
va_start(args, count);
for (std::size_t i = 0; i < count; ++i) {
re.types[i] = va_arg(args, component_type_t);
}
va_end(args);
re.count = count;
std::sort(re.types, re.types + count);
return re;
}
class TypeRegistry {
public:
TypeRegistry() : m_last_virtual(9000), m_callbacks() {
// core types always exist
make<EntityMeta>();
}
template<typename T>
void make() {
auto type_id = Component<T>::typeID();
if (m_types.find(type_id) != m_types.end())
return;
m_types[type_id] = std::make_shared<Component<T>>();
}
template<typename T>
bool exists() {
auto type_id = Component<T>::typeID();
return m_types.find(type_id) != m_types.end();
}
template<typename T>
std::shared_ptr<fggl::ecs::ComponentBase> meta() const {
auto type_id = Component<T>::typeID();
return m_types.at(type_id);
}
inline std::shared_ptr<fggl::ecs::ComponentBase> meta(component_type_t type_id) const {
try {
return m_types.at(type_id);
} catch (std::out_of_range& err) {
std::cerr << "asked for metadata on type " << type_id << " but no such type is in the type system" << std::endl;
return nullptr;
}
}
inline component_type_t find(const char *name) const {
for (const auto &[type, meta] : m_types) {
if (std::strcmp(name, meta->name()) == 0) {
return type;
}
}
debug::warning("asked for unknown/unregistered component type: {}", name);
assert(false && "unknown component type, are you sure it was registered?");
return 0;
}
inline void make_virtual(std::shared_ptr<ComponentBase> vtype) {
auto type_id = m_last_virtual++;
m_types[type_id] = std::move(vtype);
}
void callbackAdd(component_type_t component, const callback_t &callback) {
m_callbacks[component].add.push_back(callback);
}
void fireAdd(prototype::World *world, entity_t entity, component_type_t type) {
try {
auto &callbacks = m_callbacks.at(type).add;
for (auto &callback : callbacks) {
callback(world, entity);
}
} catch (std::out_of_range &e) {
//spdlog::debug("no callbacks for {}", m_types[type]->name());
}
}
private:
std::unordered_map<component_type_t, std::shared_ptr<fggl::ecs::ComponentBase>> m_types;
component_type_t m_last_virtual;
std::map<component_type_t, TypeCallbacks> m_callbacks;
};
};
#endif
/*
* 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 24/07/22.
//
#ifndef FGGL_ENTITY_ENTITY_HPP
#define FGGL_ENTITY_ENTITY_HPP
#include <cstdint>
#include <map>
#include <vector>
#include "fggl/debug/logging.hpp"
#include "fggl/vendor/entt.hpp"
namespace fggl::entity {
using EntityID = entt::entity;
constexpr EntityID INVALID = entt::null;
class EntityManager {
public:
inline EntityID create() {
return m_registry.create();
}
inline void destroy(EntityID entity) {
m_registry.destroy(entity);
}
template<typename Component, typename... Args>
inline Component &add(EntityID entity, Args &&... args) {
return m_registry.get_or_emplace<Component>(entity, std::forward<Args>(args)...);
}
template<typename Component>
Component &get(EntityID entity) {
#ifndef NDEBUG
if (!has<Component>(entity)) {
debug::error("Entity {} has no component of type {}", (uint64_t) entity, debug::demangle(typeid(Component).name()));
assert(false && "Entity was missing component - use tryGet or fix definition");
}
#endif
return m_registry.get<Component>(entity);
}
template<typename Component>
const Component &get(EntityID entity) const {
return m_registry.get<Component>(entity);
}
template<typename Component>
Component *tryGet(EntityID entity) {
return m_registry.try_get<Component>(entity);
}
template<typename Component>
const Component *tryGet(EntityID entity, const Component* defaultValue = nullptr) const {
auto* comp = m_registry.try_get<Component>(entity);
return comp == nullptr ? defaultValue : comp;
}
template<typename ...Components>
auto find() const {
return m_registry.view<Components...>();
}
EntityID findByName(const std::string& name) const {
auto itr = m_names.find(name);
if ( itr == m_names.end() ){
return INVALID;
}
return m_registry.valid(itr->second) ? itr->second : INVALID;
}
inline void setName(const std::string& name, EntityID eid ) {
if ( eid == INVALID ) {
m_names.erase(name);
} else {
assert(m_registry.valid(eid));
m_names[name] = eid;
}
}
template<typename ...Components>
bool has(EntityID idx) const {
return m_registry.template all_of<Components...>(idx);
}
bool hasTag(EntityID entity, fggl::util::GUID tag) {
const auto mapItr = m_tags.find( tag );
if ( mapItr == m_tags.end() || !m_registry.valid(entity) ) {
return false;
}
return std::find(mapItr->second.begin(), mapItr->second.end(), entity) != mapItr->second.end();
}
void addTag(const EntityID entity, const fggl::util::GUID tag) {
assert( m_registry.valid(entity) );
auto& tagged = m_tags[ tag ];
tagged.push_back( entity );
}
void removeTag(const EntityID entity, const fggl::util::GUID tag) {
auto mapItr = m_tags.find(tag);
if ( mapItr == m_tags.end() ) {
return;
}
std::remove_if( mapItr->second.begin(), mapItr->second.end(), [entity](auto other) { return other == entity;} );
}
inline std::vector<EntityID> findByTag(const char* tag) {
return findByTag( util::make_guid_rt(tag) );
}
std::vector<EntityID> findByTag(const fggl::util::GUID tag){
auto mapItr = m_tags.find(tag);
if ( mapItr == m_tags.end() ) {
return {};
}
return mapItr->second;
}
inline bool exists(EntityID idx) const {
return m_registry.valid(idx);
}
inline bool alive(EntityID idx) const {
return m_registry.valid(idx);
}
private:
entt::registry m_registry;
std::map<std::string, EntityID> m_names;
std::map<fggl::util::GUID, std::vector<EntityID>> m_tags;
};
struct Entity {
static Entity make(EntityManager &manager, EntityID idx) {
return Entity{idx, manager};
}
EntityID id;
EntityManager &manager;
template<typename Component>
Component &get() {
return manager.get<Component>(id);
}
template<typename Component>
const Component &get() const {
return manager.get<Component>(id);
}
};
} // namespace fggl::entity
#endif //FGGL_ENTITY_ENTITY_HPP
/*
* 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 20/08/22.
//
#ifndef FGGL_ENTITY_GRIDWORLD_ZONE_HPP
#define FGGL_ENTITY_GRIDWORLD_ZONE_HPP
#include <array>
#include <vector>
#include "fggl/math/types.hpp"
#include "fggl/assets/types.hpp"
#include "fggl/entity/entity.hpp"
namespace fggl::entity::grid {
using GridPos = math::vec2i;
constexpr auto ASSET_TILESET = assets::AssetType::make("tileset");
template<typename T, uint32_t width, uint32_t height>
struct Grid {
public:
Grid() = default;
inline T& get(GridPos pos) {
assert(inBounds(pos));
return m_cells[getCellIndex(pos)];
}
const T& get(GridPos pos) const {
assert(inBounds(pos));
return m_cells[getCellIndex(pos)];
}
inline void set(GridPos pos, T value) {
assert(inBounds(pos));
m_cells[getCellIndex(pos)] = value;
}
inline bool inBounds(GridPos pos) const {
return 0 <= pos.x && pos.x <= size.x &&
0 <= pos.y && pos.y <= size.y;
}
private:
constexpr static math::vec2i size = math::vec2ui(width, height);
std::array<T, size.x * size.y> m_cells;
inline uint32_t getCellIndex(GridPos pos) const {
assert( inBounds(pos));
return pos.y * size.x + pos.x;
}
};
struct FloorTile {
constexpr static uint8_t IMPOSSIBLE = 0;
uint8_t moveCost = IMPOSSIBLE;
math::vec3 colour = gfx::colours::CYAN;
};
struct WallTile {
bool render = false;
math::vec3 colour = gfx::colours::CYAN;
};
struct WallState {
uint32_t north = 0;
uint32_t west = 0;
};
struct TileSet {
std::vector<FloorTile> m_floors;
std::vector<WallTile> m_walls;
};
/**
* A 2D representation of a space.
*
* @tparam width the grid width in units
* @tparam height the grid height in units
*/
template<uint32_t width, uint32_t height>
struct Area2D {
public:
constexpr static std::array<math::vec2i, 4> DIRECTIONS{{ {-1, 0}, {0, -1}, {1, 0}, {0, 1} }};
inline explicit Area2D(TileSet& tiles) : m_tiles(tiles) {
clear();
}
[[nodiscard]]
inline bool inBounds(GridPos pos) const {
return 0 <= pos.x && pos.x <= width
&& 0 <= pos.y && pos.y <= height;
}
void clear() {
WallState noWall;
for (auto xPos = 0U; xPos<width; ++xPos) {
for (auto yPos=0U; yPos<height; ++yPos) {
m_floors.set({xPos, yPos}, 0);
m_walls.set({xPos, yPos}, noWall);
}
}
}
inline FloorTile& floorAt(uint32_t xPos, uint32_t yPos) {
return m_tiles.m_floors.at( m_floors.get({xPos, yPos}) );
}
inline void setFloorAt(uint32_t xPos, uint32_t yPos, uint32_t floor) {
m_floors.set({xPos, yPos}, floor);
}
inline WallTile& wallAt(uint32_t xPos, uint32_t yPos, bool north) {
if (north) {
return m_tiles.m_walls.at(m_walls.get({xPos, yPos}).north);
} else {
return m_tiles.m_walls.at(m_walls.get({xPos, yPos}).west);
}
}
inline void setWallAt(uint32_t xPos, uint32_t yPos, bool north, uint32_t wall) {
auto& state = m_walls.get({xPos, yPos});
if (north) {
state.north = wall;
} else {
state.west = wall;
}
}
inline bool canMove(GridPos pos) const {
if ( !inBounds(pos) ) {
return false;
}
return m_tiles.m_floors[m_floors.get(pos)].moveCost != FloorTile::IMPOSSIBLE;
}
inline bool canMove(GridPos pos, math::vec2i dir) const {
return canMove(pos + dir) && !blocked(pos, dir);
}
inline bool blocked(GridPos pos, math::vec2i dir) const;
EntityManager& entities() {
return m_entities;
}
inline void neighbours(math::vec2i pos, std::vector<math::vec2i> &neighbours) const {
for (auto direction : DIRECTIONS) {
if ( canMove(pos, direction) ) {
auto result = pos + direction;
neighbours.push_back(result);
}
}
}
private:
TileSet& m_tiles;
Grid<uint32_t, width, height> m_floors;
Grid<WallState, width + 1, height + 1> m_walls;
EntityManager m_entities;
};
template<uint32_t width, uint32_t height>
bool Area2D<width, height>::blocked(GridPos pos, math::vec2i dir) const {
auto targetPos = pos;
if ( dir.x == 1 || dir.y == 1 ) {
targetPos = pos + dir;
}
if ( !inBounds(targetPos) ) {
return true;
}
auto& wallObj = m_walls.get(targetPos);
if ( dir.y != 0 ) {
return wallObj.north != 0;
}
if (dir.x != 0) {
return wallObj.west != 0;
}
return true;
}
} // namespace fggl::entity::gridworld
#endif //FGGL_ENTITY_GRIDWORLD_ZONE_HPP