Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

refactor: introduce GfxDevice abstraction layer, isolate GL calls into GLDevice

esengined7b49094cb02
diff --git a/CMakeLists.txt b/CMakeLists.txt
index dd140603c..029ddfe0c 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -52,6 +52,7 @@ set(ESENGINE_SOURCES
src/esengine/renderer/RenderTarget.cpp
src/esengine/renderer/ImmediateDraw.cpp
src/esengine/renderer/CustomGeometry.cpp
+ src/esengine/renderer/GLDevice.cpp
src/esengine/renderer/StateTracker.cpp
src/esengine/renderer/TransientBufferPool.cpp
src/esengine/renderer/DrawList.cpp
@@ -147,6 +148,8 @@ set(ESENGINE_HEADERS
src/esengine/renderer/ImmediateDraw.hpp
src/esengine/renderer/BlendMode.hpp
src/esengine/renderer/CustomGeometry.hpp
+ src/esengine/renderer/GfxDevice.hpp
+ src/esengine/renderer/GLDevice.hpp
src/esengine/renderer/StateTracker.hpp
src/esengine/renderer/TransientBufferPool.hpp
src/esengine/renderer/DrawCommand.hpp
diff --git a/src/esengine/app/App.cpp b/src/esengine/app/App.cpp
index 18349ec3f..bf8174c3f 100644
--- a/src/esengine/app/App.cpp
+++ b/src/esengine/app/App.cpp
@@ -13,6 +13,8 @@
#include "../core/Log.hpp"
#include "../platform/FileSystem.hpp"
#include "../ecs/components/Canvas.hpp"
+#include "../renderer/GLDevice.hpp"
+#include "../renderer/RenderCommand.hpp"
#include <glm/gtc/matrix_transform.hpp>
@@ -24,24 +26,18 @@
namespace esengine {
-App* App::instance_ = nullptr;
-
// =============================================================================
// Constructor / Destructor
// =============================================================================
App::App() : App(AppConfig{}) {}
-App::App(const AppConfig& config) : config_(config) {
- ES_ASSERT(instance_ == nullptr, "Only one App instance allowed");
- instance_ = this;
-}
+App::App(const AppConfig& config) : config_(config) {}
App::~App() {
if (initialized_) {
shutdown();
}
- instance_ = nullptr;
}
// =============================================================================
@@ -58,8 +54,10 @@ App& App::addPlugin(Unique<Plugin> plugin) {
return *this;
}
-App& App::addSystem(Schedule schedule, SystemFn system) {
- systems_[static_cast<usize>(schedule)].push_back(std::move(system));
+App& App::addSystem(Schedule schedule, SystemFn system, i32 priority) {
+ auto lambdaSys = makeUnique<LambdaSystem>(std::move(system));
+ lambdaSys->setPriority(priority);
+ system_groups_[static_cast<usize>(schedule)].addSystem(std::move(lambdaSys));
return *this;
}
@@ -110,15 +108,20 @@ void App::init() {
resourceManager_.init();
+ gfxDevice_ = makeUnique<GLDevice>();
+ RenderCommand::setDevice(gfxDevice_.get());
+
renderContext_ = makeUnique<RenderContext>();
renderContext_->init();
renderer_ = makeUnique<Renderer>(*renderContext_);
renderer_->setViewport(0, 0, config_.width, config_.height);
+ services_.registerService<Platform>(platform_.get());
services_.registerService<ecs::Registry>(&registry_);
services_.registerService<resource::ResourceManager>(&resourceManager_);
services_.registerService<Input>(&input_);
+ services_.registerService<GfxDevice>(gfxDevice_.get());
services_.registerService<RenderContext>(renderContext_.get());
services_.registerService<Renderer>(renderer_.get());
@@ -126,6 +129,10 @@ void App::init() {
plugin->build(*this);
}
+ for (auto& group : system_groups_) {
+ group.init(registry_);
+ }
+
initialized_ = true;
ES_LOG_INFO("App initialized");
}
@@ -135,11 +142,18 @@ void App::shutdown() {
ES_LOG_INFO("App shutting down...");
+ for (auto& group : system_groups_) {
+ group.shutdown(registry_);
+ }
+
renderer_.reset();
renderContext_->shutdown();
renderContext_.reset();
+ RenderCommand::setDevice(nullptr);
+ gfxDevice_.reset();
+
resourceManager_.shutdown();
registry_.clear();
@@ -184,10 +198,9 @@ void App::quit() {
}
void App::runFrame() {
- static f64 lastTime = 0.0;
f64 currentTime = platform_->getTime();
- f32 dt = static_cast<f32>(currentTime - lastTime);
- lastTime = currentTime;
+ f32 dt = static_cast<f32>(currentTime - last_frame_time_);
+ last_frame_time_ = currentTime;
if (dt > 0.1f) dt = 0.1f;
@@ -241,10 +254,8 @@ void App::runFrame() {
}
void App::runSystems(Schedule schedule) {
- auto& systems = systems_[static_cast<usize>(schedule)];
- for (auto& system : systems) {
- system(registry_, time_.delta);
- }
+ World world{registry_, services_, time_.delta};
+ system_groups_[static_cast<usize>(schedule)].update(world);
}
#ifdef ES_PLATFORM_WEB
diff --git a/src/esengine/app/App.hpp b/src/esengine/app/App.hpp
index 6b83b935d..e44897848 100644
--- a/src/esengine/app/App.hpp
+++ b/src/esengine/app/App.hpp
@@ -12,11 +12,14 @@
#include "Schedule.hpp"
#include "../core/Types.hpp"
+#include "../core/World.hpp"
#include "../core/ServiceRegistry.hpp"
#include "../ecs/Registry.hpp"
+#include "../ecs/System.hpp"
#include "../platform/Platform.hpp"
#include "../platform/input/Input.hpp"
#include "../resource/ResourceManager.hpp"
+#include "../renderer/GfxDevice.hpp"
#include "../renderer/RenderContext.hpp"
#include "../renderer/Renderer.hpp"
@@ -37,7 +40,7 @@ class Plugin;
// Type Aliases
// =============================================================================
-using SystemFn = std::function<void(ecs::Registry&, f32)>;
+using SystemFn = std::function<void(World&)>;
// =============================================================================
// App Configuration
@@ -95,7 +98,7 @@ public:
return addPlugin(makeUnique<T>(std::forward<Args>(args)...));
}
- App& addSystem(Schedule schedule, SystemFn system);
+ App& addSystem(Schedule schedule, SystemFn system, i32 priority = 0);
App& addStartupSystem(SystemFn system);
// =========================================================================
@@ -109,22 +112,20 @@ public:
// Accessors
// =========================================================================
- ecs::Registry& registry() { return registry_; }
- const ecs::Registry& registry() const { return registry_; }
-
- resource::ResourceManager& resources() { return resourceManager_; }
- Input& input() { return input_; }
- const Time& time() const { return time_; }
- Renderer& renderer() { return *renderer_; }
- RenderContext& renderContext() { return *renderContext_; }
+ /**
+ * @brief Convenience accessor via ServiceRegistry
+ * @tparam T The service type
+ * @return Reference to the service
+ */
+ template<typename T>
+ T& require() { return services_.require<T>(); }
ServiceRegistry& services() { return services_; }
+ const Time& time() const { return time_; }
u32 width() const { return config_.width; }
u32 height() const { return config_.height; }
- static App& get() { return *instance_; }
-
// =========================================================================
// JS Interop
// =========================================================================
@@ -142,6 +143,15 @@ private:
void runSystems(Schedule schedule);
+ /** @brief Wraps a SystemFn lambda as a System for unified scheduling */
+ class LambdaSystem : public ecs::System {
+ public:
+ explicit LambdaSystem(SystemFn fn) : fn_(std::move(fn)) {}
+ void update(World& world) override { fn_(world); }
+ private:
+ SystemFn fn_;
+ };
+
AppConfig config_;
ServiceRegistry services_;
@@ -149,19 +159,19 @@ private:
Input input_;
ecs::Registry registry_;
resource::ResourceManager resourceManager_;
+ Unique<GfxDevice> gfxDevice_;
Unique<RenderContext> renderContext_;
Unique<Renderer> renderer_;
Time time_;
std::vector<Unique<Plugin>> plugins_;
- std::vector<SystemFn> systems_[SCHEDULE_COUNT];
+ ecs::SystemGroup system_groups_[SCHEDULE_COUNT];
bool running_ = false;
bool initialized_ = false;
bool startupRan_ = false;
-
- static App* instance_;
+ f64 last_frame_time_ = 0.0;
};
} // namespace esengine
diff --git a/src/esengine/bindings/EngineContext.hpp b/src/esengine/bindings/EngineContext.hpp
index bc2e42c89..da3d46a65 100644
--- a/src/esengine/bindings/EngineContext.hpp
+++ b/src/esengine/bindings/EngineContext.hpp
@@ -27,6 +27,7 @@
namespace esengine {
+class GfxDevice;
class RenderContext;
class RenderFrame;
class ImmediateDraw;
@@ -73,6 +74,7 @@ public:
// Subsystem Accessors
// =========================================================================
+ GfxDevice* gfxDevice() { return services_.getService<GfxDevice>(); }
RenderContext* renderContext() { return services_.getService<RenderContext>(); }
RenderFrame* renderFrame() { return services_.getService<RenderFrame>(); }
ImmediateDraw* immediateDraw() { return services_.getService<ImmediateDraw>(); }
diff --git a/src/esengine/bindings/GeometryBindings.cpp b/src/esengine/bindings/GeometryBindings.cpp
index 7848d9125..c25a13b74 100644
--- a/src/esengine/bindings/GeometryBindings.cpp
+++ b/src/esengine/bindings/GeometryBindings.cpp
@@ -3,6 +3,7 @@
#include "GeometryBindings.hpp"
#include "EngineContext.hpp"
#include "../renderer/OpenGLHeaders.hpp"
+#include "../renderer/RenderCommand.hpp"
#include "../renderer/CustomGeometry.hpp"
#include "../renderer/Buffer.hpp"
#include "../renderer/RenderContext.hpp"
@@ -39,10 +40,11 @@ static void flushImmediateDrawIfActive() {
static void restoreImmediateDrawState() {
if (g_immediateDrawActive) {
- glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
- glEnable(GL_BLEND);
- glDisable(GL_DEPTH_TEST);
- glActiveTexture(GL_TEXTURE0);
+ auto* dev = RenderCommand::getDevice();
+ dev->setBlendEnabled(true);
+ dev->setBlendMode(BlendMode::Normal);
+ dev->setDepthTest(false);
+ dev->bindTexture(0, 0);
}
}
@@ -145,10 +147,10 @@ void draw_mesh(u32 geometryHandle, u32 shaderHandle, uintptr_t transformPtr) {
auto* ib = geom->getVAO() ? geom->getVAO()->getIndexBuffer().get() : nullptr;
if (ib) {
GLenum type = ib->is16Bit() ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT;
- glDrawElements(GL_TRIANGLES, static_cast<GLsizei>(geom->getIndexCount()), type, nullptr);
+ RenderCommand::getDevice()->drawElements(geom->getIndexCount(), type, 0);
}
} else {
- glDrawArrays(GL_TRIANGLES, 0, static_cast<GLsizei>(geom->getVertexCount()));
+ RenderCommand::getDevice()->drawArrays(0, geom->getVertexCount());
}
geom->unbind();
@@ -220,8 +222,7 @@ void draw_meshWithUniforms(u32 geometryHandle, u32 shaderHandle, uintptr_t trans
case 10: {
i32 slot = static_cast<i32>(uniforms[idx++]);
u32 textureId = static_cast<u32>(uniforms[idx++]);
- glActiveTexture(GL_TEXTURE0 + slot);
- glBindTexture(GL_TEXTURE_2D, textureId);
+ RenderCommand::getDevice()->bindTexture(static_cast<u32>(slot), textureId);
shader->setUniform(name, slot);
break;
}
@@ -236,10 +237,10 @@ void draw_meshWithUniforms(u32 geometryHandle, u32 shaderHandle, uintptr_t trans
auto* ib = geom->getVAO() ? geom->getVAO()->getIndexBuffer().get() : nullptr;
if (ib) {
GLenum type = ib->is16Bit() ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT;
- glDrawElements(GL_TRIANGLES, static_cast<GLsizei>(geom->getIndexCount()), type, nullptr);
+ RenderCommand::getDevice()->drawElements(geom->getIndexCount(), type, 0);
}
} else {
- glDrawArrays(GL_TRIANGLES, 0, static_cast<GLsizei>(geom->getVertexCount()));
+ RenderCommand::getDevice()->drawArrays(0, geom->getVertexCount());
}
geom->unbind();
diff --git a/src/esengine/bindings/ImmediateDrawBindings.cpp b/src/esengine/bindings/ImmediateDrawBindings.cpp
index 65e738ee9..a9cc49602 100644
--- a/src/esengine/bindings/ImmediateDrawBindings.cpp
+++ b/src/esengine/bindings/ImmediateDrawBindings.cpp
@@ -39,7 +39,7 @@ static void flushImmediateDrawIfActive() {
void draw_begin(uintptr_t matrixPtr) {
if (!g_initialized || !g_immediateDraw) return;
- glViewport(0, 0, g_viewportWidth, g_viewportHeight);
+ RenderCommand::getDevice()->setViewport(0, 0, g_viewportWidth, g_viewportHeight);
const f32* matrixData = reinterpret_cast<const f32*>(matrixPtr);
ctx().setCurrentViewProjection(glm::make_mat4(matrixData));
diff --git a/src/esengine/bindings/PostProcessBindings.cpp b/src/esengine/bindings/PostProcessBindings.cpp
index 566ba9feb..0a1f08ede 100644
--- a/src/esengine/bindings/PostProcessBindings.cpp
+++ b/src/esengine/bindings/PostProcessBindings.cpp
@@ -4,6 +4,7 @@
#include "PostProcessBindings.hpp"
#include "EngineContext.hpp"
#include "../renderer/OpenGLHeaders.hpp"
+#include "../renderer/RenderCommand.hpp"
#include "../renderer/PostProcessPipeline.hpp"
#include "../renderer/RenderContext.hpp"
#include "../renderer/RenderFrame.hpp"
@@ -36,7 +37,7 @@ bool postprocess_init(u32 width, u32 height) {
}
g_postProcessPipeline->init(width, height);
- glBindFramebuffer(GL_FRAMEBUFFER, 0);
+ RenderCommand::getDevice()->bindFramebuffer(0);
return g_postProcessPipeline->isInitialized();
}
diff --git a/src/esengine/bindings/RendererBindings.cpp b/src/esengine/bindings/RendererBindings.cpp
index 8c01abd1c..5586798b7 100644
--- a/src/esengine/bindings/RendererBindings.cpp
+++ b/src/esengine/bindings/RendererBindings.cpp
@@ -3,6 +3,7 @@
#include "RendererBindings.hpp"
#include "EngineContext.hpp"
#include "../renderer/OpenGLHeaders.hpp"
+#include "../renderer/RenderCommand.hpp"
#include "../renderer/RenderFrame.hpp"
#include "../renderer/RenderContext.hpp"
#include "../renderer/RenderStage.hpp"
@@ -47,7 +48,7 @@ static u32 checkGLErrors(const char* context) {
if (!g_glErrorCheckEnabled) return 0;
u32 errorCount = 0;
GLenum err;
- while ((err = glGetError()) != GL_NO_ERROR) {
+ while ((err = static_cast<GLenum>(RenderCommand::getDevice()->getError())) != GL_NO_ERROR) {
const char* errStr = "UNKNOWN";
switch (err) {
case GL_INVALID_ENUM: errStr = "INVALID_ENUM"; break;
@@ -302,10 +303,11 @@ void renderFrame(ecs::Registry& registry, i32 viewportWidth, i32 viewportHeight)
ctx().setViewport(static_cast<u32>(viewportWidth), static_cast<u32>(viewportHeight));
g_renderFrame->resize(g_viewportWidth, g_viewportHeight);
- glViewport(0, 0, viewportWidth, viewportHeight);
+ auto* dev = RenderCommand::getDevice();
+ dev->setViewport(0, 0, static_cast<u32>(viewportWidth), static_cast<u32>(viewportHeight));
const auto& cc = ctx().clearColor();
- glClearColor(cc.r, cc.g, cc.b, cc.a);
- glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
+ dev->setClearColor(cc.r, cc.g, cc.b, cc.a);
+ dev->clear(true, true, false);
glm::mat4 viewProjection = glm::mat4(1.0f);
@@ -364,10 +366,11 @@ void renderFrameWithMatrix(ecs::Registry& registry, i32 viewportWidth, i32 viewp
ctx().setViewport(static_cast<u32>(viewportWidth), static_cast<u32>(viewportHeight));
g_renderFrame->resize(g_viewportWidth, g_viewportHeight);
- glViewport(0, 0, viewportWidth, viewportHeight);
+ auto* dev = RenderCommand::getDevice();
+ dev->setViewport(0, 0, static_cast<u32>(viewportWidth), static_cast<u32>(viewportHeight));
const auto& cc = ctx().clearColor();
- glClearColor(cc.r, cc.g, cc.b, cc.a);
- glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
+ dev->setClearColor(cc.r, cc.g, cc.b, cc.a);
+ dev->clear(true, true, false);
const f32* matrixData = reinterpret_cast<const f32*>(matrixPtr);
glm::mat4 viewProjection = glm::make_mat4(matrixData);
@@ -568,23 +571,25 @@ void renderer_setClearColor(f32 r, f32 g, f32 b, f32 a) {
}
void renderer_setViewport(i32 x, i32 y, i32 w, i32 h) {
- glViewport(x, y, w, h);
+ RenderCommand::getDevice()->setViewport(x, y, static_cast<u32>(w), static_cast<u32>(h));
}
void renderer_setScissor(i32 x, i32 y, i32 w, i32 h, bool enable) {
+ auto* dev = RenderCommand::getDevice();
if (enable) {
- glEnable(GL_SCISSOR_TEST);
- glScissor(x, y, w, h);
+ dev->setScissorTest(true);
+ dev->setScissor(x, y, w, h);
} else {
- glDisable(GL_SCISSOR_TEST);
+ dev->setScissorTest(false);
}
}
void renderer_clearBuffers(i32 flags) {
- GLbitfield mask = 0;
- if (flags & 1) mask |= GL_COLOR_BUFFER_BIT;
- if (flags & 2) mask |= GL_DEPTH_BUFFER_BIT;
- if (mask) glClear(mask);
+ bool color = (flags & 1) != 0;
+ bool depth = (flags & 2) != 0;
+ if (color || depth) {
+ RenderCommand::getDevice()->clear(color, depth, false);
+ }
}
void renderer_diagnose() {
@@ -639,7 +644,7 @@ void renderer_clearAllClipRects() {
void renderer_clearStencil() {
glClearStencil(0);
- glClear(GL_STENCIL_BUFFER_BIT);
+ RenderCommand::getDevice()->clear(false, false, true);
}
void renderer_setEntityStencilMask(u32 entity, i32 refValue) {
@@ -669,7 +674,7 @@ void renderer_clearAllStencilMasks() {
void gl_enableErrorCheck(bool enabled) {
ctx().setGlErrorCheckEnabled(enabled);
if (enabled) {
- while (glGetError() != GL_NO_ERROR) {}
+ while (RenderCommand::getDevice()->getError() != 0) {}
ES_LOG_INFO("[GL] Error checking enabled");
}
}
@@ -720,7 +725,7 @@ emscripten::val getChildEntities(ecs::Registry& registry, u32 entity) {
}
u32 registry_getGeneration(ecs::Registry& registry, u32 entity) {
- return registry.generation(static_cast<Entity>(entity));
+ return Entity(entity).generation();
}
u32 registry_getSchemaPoolVersion(ecs::Registry& registry, u32 poolId) {
diff --git a/src/esengine/bindings/WebSDKEntry.cpp b/src/esengine/bindings/WebSDKEntry.cpp
index 7efe32c2b..b79dd7434 100644
--- a/src/esengine/bindings/WebSDKEntry.cpp
+++ b/src/esengine/bindings/WebSDKEntry.cpp
@@ -30,6 +30,8 @@
#include "../ecs/UIFlexLayoutSystem.hpp"
#include "../renderer/OpenGLHeaders.hpp"
+#include "../renderer/GLDevice.hpp"
+#include "../renderer/RenderCommand.hpp"
#include "../renderer/RenderContext.hpp"
#include "../renderer/RenderFrame.hpp"
#include "../renderer/ImmediateDraw.hpp"
@@ -203,6 +205,10 @@ static void initSubsystems() {
resourceManager->init();
svc.registerOwned<resource::ResourceManager>(std::move(resourceManager));
+ auto gfxDevice = makeUnique<GLDevice>();
+ RenderCommand::setDevice(gfxDevice.get());
+ svc.registerOwned<GfxDevice>(std::move(gfxDevice));
+
auto renderContext = makeUnique<RenderContext>();
renderContext->init();
svc.registerOwned<RenderContext>(std::move(renderContext));
@@ -229,7 +235,7 @@ static void initSubsystems() {
svc.registerOwned<GeometryManager>(makeUnique<GeometryManager>());
- auto renderFrame = makeUnique<RenderFrame>(*g_renderContext, *g_resourceManager);
+ auto renderFrame = makeUnique<RenderFrame>(*ctx().gfxDevice(), *g_renderContext, *g_resourceManager);
renderFrame->addPlugin(std::make_unique<SpritePlugin>());
renderFrame->addPlugin(std::make_unique<UIElementPlugin>());
@@ -262,8 +268,9 @@ static void initSubsystems() {
ctx().setInitialized(true);
const auto& cc = ctx().clearColor();
- glClearColor(cc.r, cc.g, cc.b, cc.a);
- glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
+ auto* dev = ctx().gfxDevice();
+ dev->setClearColor(cc.r, cc.g, cc.b, cc.a);
+ dev->clear(true, true, false);
}
bool initRendererInternal(const char* canvasSelector) {
diff --git a/src/esengine/renderer/CustomGeometry.cpp b/src/esengine/renderer/CustomGeometry.cpp
index ef79f11fa..f73cf5065 100644
--- a/src/esengine/renderer/CustomGeometry.cpp
+++ b/src/esengine/renderer/CustomGeometry.cpp
@@ -12,6 +12,7 @@
#include "CustomGeometry.hpp"
#include "OpenGLHeaders.hpp"
+#include "RenderCommand.hpp"
#include "../core/Log.hpp"
namespace esengine {
@@ -90,14 +91,15 @@ void CustomGeometry::bind() const {
glType = GL_FLOAT;
break;
}
- glEnableVertexAttribArray(index);
- glVertexAttribPointer(
+ auto* device = RenderCommand::getDevice();
+ device->enableVertexAttrib(index);
+ device->vertexAttribPointer(
index,
- static_cast<GLint>(shaderDataTypeComponentCount(attr.type)),
+ static_cast<i32>(shaderDataTypeComponentCount(attr.type)),
glType,
- attr.normalized ? GL_TRUE : GL_FALSE,
- static_cast<GLsizei>(layout.getStride()),
- reinterpret_cast<const void*>(static_cast<uintptr_t>(attr.offset))
+ attr.normalized,
+ static_cast<i32>(layout.getStride()),
+ attr.offset
);
++index;
}
diff --git a/src/esengine/renderer/DrawList.cpp b/src/esengine/renderer/DrawList.cpp
index 9a8633d7e..0895c77cf 100644
--- a/src/esengine/renderer/DrawList.cpp
+++ b/src/esengine/renderer/DrawList.cpp
@@ -1,16 +1,7 @@
#include "DrawList.hpp"
+#include "OpenGLHeaders.hpp"
#include <glm/glm.hpp>
-
-#ifdef ES_PLATFORM_WEB
- #include <GLES3/gl3.h>
-#else
- #ifdef _WIN32
- #include <windows.h>
- #endif
- #include <glad/glad.h>
-#endif
-
#include <algorithm>
namespace esengine {
@@ -67,7 +58,7 @@ void DrawList::finalize() {
merged_draw_calls_ = writeIdx;
}
-void DrawList::execute(StateTracker& state, TransientBufferPool& buffers,
+void DrawList::execute(GfxDevice& device, StateTracker& state, TransientBufferPool& buffers,
const glm::mat4& viewProjection,
FrameCapture* capture,
const CustomDrawFn& customDraw) {
@@ -77,9 +68,9 @@ void DrawList::execute(StateTracker& state, TransientBufferPool& buffers,
if (cmd.shader_id != lastShader) {
state.useProgram(cmd.shader_id);
- GLint loc = glGetUniformLocation(cmd.shader_id, "u_projection");
+ i32 loc = device.getUniformLocation(cmd.shader_id, "u_projection");
if (loc >= 0) {
- glUniformMatrix4fv(loc, 1, GL_FALSE, &viewProjection[0][0]);
+ device.setUniformMat4(loc, &viewProjection[0][0]);
}
lastShader = cmd.shader_id;
}
@@ -111,11 +102,10 @@ void DrawList::execute(StateTracker& state, TransientBufferPool& buffers,
} else {
buffers.bindLayout(cmd.layout_id);
- glDrawElements(GL_TRIANGLES,
- static_cast<GLsizei>(cmd.index_count),
- GL_UNSIGNED_SHORT,
- reinterpret_cast<void*>(
- static_cast<uintptr_t>(cmd.index_offset) * sizeof(u16)));
+ device.drawElements(
+ cmd.index_count,
+ GL_UNSIGNED_SHORT,
+ static_cast<u32>(static_cast<uintptr_t>(cmd.index_offset) * sizeof(u16)));
}
if (capture && capture->isCapturing()) {
diff --git a/src/esengine/renderer/DrawList.hpp b/src/esengine/renderer/DrawList.hpp
index 52b037373..eb7dac076 100644
--- a/src/esengine/renderer/DrawList.hpp
+++ b/src/esengine/renderer/DrawList.hpp
@@ -2,6 +2,7 @@
#include "../core/Types.hpp"
#include "DrawCommand.hpp"
+#include "GfxDevice.hpp"
#include "StateTracker.hpp"
#include "TransientBufferPool.hpp"
#include "FrameCapture.hpp"
@@ -24,7 +25,7 @@ public:
void finalize();
- void execute(StateTracker& state, TransientBufferPool& buffers,
+ void execute(GfxDevice& device, StateTracker& state, TransientBufferPool& buffers,
const glm::mat4& viewProjection,
FrameCapture* capture = nullptr,
const CustomDrawFn& customDraw = nullptr);
diff --git a/src/esengine/renderer/GLDevice.cpp b/src/esengine/renderer/GLDevice.cpp
new file mode 100644
index 000000000..0a708e75e
--- /dev/null
+++ b/src/esengine/renderer/GLDevice.cpp
@@ -0,0 +1,419 @@
+/**
+ * @file GLDevice.cpp
+ * @brief OpenGL ES / WebGL implementation of GfxDevice
+ *
+ * @author ESEngine Team
+ * @date 2026
+ *
+ * @copyright Copyright (c) 2026 ESEngine Team
+ * Licensed under the MIT License.
+ */
+
+#include "GLDevice.hpp"
+#include "OpenGLHeaders.hpp"
+#include "../core/Log.hpp"
+
+namespace esengine {
+
+// =============================================================================
+// Helper Conversions
+// =============================================================================
+
+namespace {
+
+GLenum toGLFilter(TextureFilter filter) {
+ switch (filter) {
+ case TextureFilter::Nearest: return GL_NEAREST;
+ case TextureFilter::Linear: return GL_LINEAR;
+ default: return GL_LINEAR;
+ }
+}
+
+GLenum toGLWrap(TextureWrap wrap) {
+ switch (wrap) {
+ case TextureWrap::Repeat: return GL_REPEAT;
+ case TextureWrap::ClampToEdge: return GL_CLAMP_TO_EDGE;
+ case TextureWrap::MirroredRepeat: return GL_MIRRORED_REPEAT;
+ default: return GL_REPEAT;
+ }
+}
+
+void setCapability(GLenum cap, bool enabled) {
+ if (enabled) {
+ glEnable(cap);
+ } else {
+ glDisable(cap);
+ }
+}
+
+} // namespace
+
+// =============================================================================
+// Lifecycle
+// =============================================================================
+
+void GLDevice::init() {
+ glEnable(GL_DEPTH_TEST);
+ glEnable(GL_BLEND);
+ glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
+ ES_LOG_DEBUG("GLDevice initialized");
+}
+
+void GLDevice::shutdown() {
+ ES_LOG_INFO("GLDevice shutdown");
+}
+
+// =============================================================================
+// Viewport & Clear
+// =============================================================================
+
+void GLDevice::setViewport(i32 x, i32 y, u32 w, u32 h) {
+ glViewport(x, y, static_cast<GLsizei>(w), static_cast<GLsizei>(h));
+}
+
+void GLDevice::setClearColor(f32 r, f32 g, f32 b, f32 a) {
+ glClearColor(r, g, b, a);
+}
+
+void GLDevice::clear(bool color, bool depth, bool stencil) {
+ GLbitfield mask = 0;
+ if (color) mask |= GL_COLOR_BUFFER_BIT;
+ if (depth) mask |= GL_DEPTH_BUFFER_BIT;
+ if (stencil) mask |= GL_STENCIL_BUFFER_BIT;
+ if (mask != 0) {
+ glClear(mask);
+ }
+}
+
+// =============================================================================
+// Blend State
+// =============================================================================
+
+void GLDevice::setBlendEnabled(bool enabled) {
+ setCapability(GL_BLEND, enabled);
+}
+
+void GLDevice::setBlendMode(BlendMode mode) {
+ switch (mode) {
+ case BlendMode::Normal:
+ glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
+ break;
+ case BlendMode::Additive:
+ glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE, GL_ONE, GL_ONE);
+ break;
+ case BlendMode::Multiply:
+ glBlendFuncSeparate(GL_DST_COLOR, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
+ break;
+ case BlendMode::Screen:
+ glBlendFuncSeparate(GL_ONE, GL_ONE_MINUS_SRC_COLOR, GL_ONE, GL_ONE_MINUS_SRC_COLOR);
+ break;
+ case BlendMode::PremultipliedAlpha:
+ glBlendFuncSeparate(GL_ONE, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
+ break;
+ case BlendMode::PmaAdditive:
+ glBlendFuncSeparate(GL_ONE, GL_ONE, GL_ONE, GL_ONE);
+ break;
+ }
+}
+
+void GLDevice::setBlendFunc(u32 srcFactor, u32 dstFactor, u32 srcAlphaFactor, u32 dstAlphaFactor) {
+ glBlendFuncSeparate(srcFactor, dstFactor, srcAlphaFactor, dstAlphaFactor);
+}
+
+// =============================================================================
+// Depth State
+// =============================================================================
+
+void GLDevice::setDepthTest(bool enabled) {
+ setCapability(GL_DEPTH_TEST, enabled);
+}
+
+void GLDevice::setDepthWrite(bool enabled) {
+ glDepthMask(enabled ? GL_TRUE : GL_FALSE);
+}
+
+// =============================================================================
+// Stencil State
+// =============================================================================
+
+void GLDevice::setStencilTest(bool enabled) {
+ setCapability(GL_STENCIL_TEST, enabled);
+}
+
+void GLDevice::setStencilFunc(u32 func, i32 ref, u32 mask) {
+ glStencilFunc(func, ref, mask);
+}
+
+void GLDevice::setStencilOp(u32 sfail, u32 dpfail, u32 dppass) {
+ glStencilOp(sfail, dpfail, dppass);
+}
+
+void GLDevice::setStencilMask(u32 mask) {
+ glStencilMask(mask);
+}
+
+void GLDevice::setColorMask(bool r, bool g, bool b, bool a) {
+ glColorMask(r ? GL_TRUE : GL_FALSE, g ? GL_TRUE : GL_FALSE,
+ b ? GL_TRUE : GL_FALSE, a ? GL_TRUE : GL_FALSE);
+}
+
+// =============================================================================
+// Scissor State
+// =============================================================================
+
+void GLDevice::setScissorTest(bool enabled) {
+ setCapability(GL_SCISSOR_TEST, enabled);
+}
+
+void GLDevice::setScissor(i32 x, i32 y, i32 w, i32 h) {
+ glScissor(x, y, w, h);
+}
+
+// =============================================================================
+// Culling
+// =============================================================================
+
+void GLDevice::setCulling(bool enabled) {
+ setCapability(GL_CULL_FACE, enabled);
+}
+
+void GLDevice::setCullFace(bool front) {
+ glCullFace(front ? GL_FRONT : GL_BACK);
+}
+
+// =============================================================================
+// Texture Binding
+// =============================================================================
+
+void GLDevice::bindTexture(u32 slot, u32 textureId) {
+ glActiveTexture(GL_TEXTURE0 + slot);
+ glBindTexture(GL_TEXTURE_2D, textureId);
+}
+
+// =============================================================================
+// Shader Program
+// =============================================================================
+
+void GLDevice::useProgram(u32 programId) {
+ glUseProgram(programId);
+}
+
+i32 GLDevice::getUniformLocation(u32 programId, const char* name) {
+ return glGetUniformLocation(programId, name);
+}
+
+void GLDevice::setUniform1i(i32 location, i32 value) {
+ if (location >= 0) glUniform1i(location, value);
+}
+
+void GLDevice::setUniform1f(i32 location, f32 value) {
+ if (location >= 0) glUniform1f(location, value);
+}
+
+void GLDevice::setUniform2f(i32 location, f32 x, f32 y) {
+ if (location >= 0) glUniform2f(location, x, y);
+}
+
+void GLDevice::setUniform3f(i32 location, f32 x, f32 y, f32 z) {
+ if (location >= 0) glUniform3f(location, x, y, z);
+}
+
+void GLDevice::setUniform4f(i32 location, f32 x, f32 y, f32 z, f32 w) {
+ if (location >= 0) glUniform4f(location, x, y, z, w);
+}
+
+void GLDevice::setUniformMat3(i32 location, const f32* data) {
+ if (location >= 0) glUniformMatrix3fv(location, 1, GL_FALSE, data);
+}
+
+void GLDevice::setUniformMat4(i32 location, const f32* data) {
+ if (location >= 0) glUniformMatrix4fv(location, 1, GL_FALSE, data);
+}
+
+// =============================================================================
+// Buffer Operations
+// =============================================================================
+
+u32 GLDevice::createBuffer() {
+ GLuint id = 0;
+ glGenBuffers(1, &id);
+ return static_cast<u32>(id);
+}
+
+void GLDevice::deleteBuffer(u32 bufferId) {
+ GLuint id = static_cast<GLuint>(bufferId);
+ glDeleteBuffers(1, &id);
+}
+
+void GLDevice::bindVertexBuffer(u32 bufferId) {
+ glBindBuffer(GL_ARRAY_BUFFER, bufferId);
+}
+
+void GLDevice::bindIndexBuffer(u32 bufferId) {
+ glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, bufferId);
+}
+
+void GLDevice::bufferData(u32 target, const void* data, u32 sizeBytes, bool dynamic) {
+ glBufferData(target, sizeBytes, data, dynamic ? GL_DYNAMIC_DRAW : GL_STATIC_DRAW);
+}
+
+void GLDevice::bufferSubData(u32 target, u32 offset, const void* data, u32 sizeBytes) {
+ glBufferSubData(target, offset, sizeBytes, data);
+}
+
+// =============================================================================
+// VAO Operations
+// =============================================================================
+
+u32 GLDevice::createVertexArray() {
+ GLuint id = 0;
+ glGenVertexArrays(1, &id);
+ return static_cast<u32>(id);
+}
+
+void GLDevice::deleteVertexArray(u32 vaoId) {
+ GLuint id = static_cast<GLuint>(vaoId);
+ glDeleteVertexArrays(1, &id);
+}
+
+void GLDevice::bindVertexArray(u32 vaoId) {
+ glBindVertexArray(vaoId);
+}
+
+void GLDevice::enableVertexAttrib(u32 index) {
+ glEnableVertexAttribArray(index);
+}
+
+void GLDevice::vertexAttribPointer(u32 index, i32 size, u32 type,
+ bool normalized, i32 stride, u32 offset) {
+ glVertexAttribPointer(index, size, type, normalized ? GL_TRUE : GL_FALSE,
+ stride, reinterpret_cast<const void*>(static_cast<uintptr_t>(offset)));
+}
+
+void GLDevice::vertexAttribDivisor(u32 index, u32 divisor) {
+ glVertexAttribDivisor(index, divisor);
+}
+
+// =============================================================================
+// Draw Calls
+// =============================================================================
+
+void GLDevice::drawElements(u32 indexCount, u32 indexType, u32 byteOffset) {
+ glDrawElements(GL_TRIANGLES, static_cast<GLsizei>(indexCount), indexType,
+ reinterpret_cast<const void*>(static_cast<uintptr_t>(byteOffset)));
+}
+
+void GLDevice::drawArrays(u32 first, u32 vertexCount) {
+ glDrawArrays(GL_TRIANGLES, static_cast<GLint>(first), static_cast<GLsizei>(vertexCount));
+}
+
+void GLDevice::drawElementsInstanced(u32 indexCount, u32 indexType, u32 byteOffset, u32 instanceCount) {
+ glDrawElementsInstanced(GL_TRIANGLES, static_cast<GLsizei>(indexCount), indexType,
+ reinterpret_cast<const void*>(static_cast<uintptr_t>(byteOffset)),
+ static_cast<GLsizei>(instanceCount));
+}
+
+// =============================================================================
+// Texture Creation
+// =============================================================================
+
+u32 GLDevice::createTexture() {
+ GLuint id = 0;
+ glGenTextures(1, &id);
+ return static_cast<u32>(id);
+}
+
+void GLDevice::deleteTexture(u32 textureId) {
+ GLuint id = static_cast<GLuint>(textureId);
+ glDeleteTextures(1, &id);
+}
+
+void GLDevice::texImage2D(u32 textureId, u32 width, u32 height,
+ u32 internalFormat, u32 format, u32 type,
+ const void* data) {
+ glBindTexture(GL_TEXTURE_2D, textureId);
+ glTexImage2D(GL_TEXTURE_2D, 0, static_cast<GLint>(internalFormat),
+ static_cast<GLsizei>(width), static_cast<GLsizei>(height),
+ 0, format, type, data);
+}
+
+void GLDevice::texSubImage2D(u32 textureId, i32 xoffset, i32 yoffset,
+ u32 width, u32 height,
+ u32 format, u32 type, const void* data) {
+ glBindTexture(GL_TEXTURE_2D, textureId);
+ glTexSubImage2D(GL_TEXTURE_2D, 0, xoffset, yoffset,
+ static_cast<GLsizei>(width), static_cast<GLsizei>(height),
+ format, type, data);
+}
+
+void GLDevice::setTextureParams(u32 textureId, TextureFilter min, TextureFilter mag,
+ TextureWrap wrapS, TextureWrap wrapT) {
+ glBindTexture(GL_TEXTURE_2D, textureId);
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, toGLFilter(min));
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, toGLFilter(mag));
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, toGLWrap(wrapS));
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, toGLWrap(wrapT));
+}
+
+void GLDevice::generateMipmaps(u32 textureId) {
+ glBindTexture(GL_TEXTURE_2D, textureId);
+ glGenerateMipmap(GL_TEXTURE_2D);
+}
+
+void GLDevice::pixelStorei(u32 pname, i32 param) {
+ glPixelStorei(pname, param);
+}
+
+// =============================================================================
+// Framebuffer
+// =============================================================================
+
+u32 GLDevice::createFramebuffer() {
+ GLuint id = 0;
+ glGenFramebuffers(1, &id);
+ return static_cast<u32>(id);
+}
+
+void GLDevice::deleteFramebuffer(u32 fboId) {
+ GLuint id = static_cast<GLuint>(fboId);
+ glDeleteFramebuffers(1, &id);
+}
+
+void GLDevice::bindFramebuffer(u32 fboId) {
+ glBindFramebuffer(GL_FRAMEBUFFER, fboId);
+}
+
+void GLDevice::framebufferTexture2D(u32 fboId, u32 attachment, u32 textureId) {
+ glBindFramebuffer(GL_FRAMEBUFFER, fboId);
+ glFramebufferTexture2D(GL_FRAMEBUFFER, attachment, GL_TEXTURE_2D, textureId, 0);
+}
+
+bool GLDevice::checkFramebufferStatus() {
+ return glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE;
+}
+
+// =============================================================================
+// Readback
+// =============================================================================
+
+void GLDevice::readPixels(i32 x, i32 y, u32 w, u32 h, u32 format, u32 type, void* data) {
+ glReadPixels(x, y, static_cast<GLsizei>(w), static_cast<GLsizei>(h), format, type, data);
+}
+
+// =============================================================================
+// Debug
+// =============================================================================
+
+void GLDevice::setWireframe(bool enabled) {
+#ifndef ES_PLATFORM_WEB
+ glPolygonMode(GL_FRONT_AND_BACK, enabled ? GL_LINE : GL_FILL);
+#else
+ (void)enabled;
+#endif
+}
+
+u32 GLDevice::getError() {
+ return static_cast<u32>(glGetError());
+}
+
+} // namespace esengine
diff --git a/src/esengine/renderer/GLDevice.hpp b/src/esengine/renderer/GLDevice.hpp
new file mode 100644
index 000000000..bd4aa660a
--- /dev/null
+++ b/src/esengine/renderer/GLDevice.hpp
@@ -0,0 +1,180 @@
+/**
+ * @file GLDevice.hpp
+ * @brief OpenGL ES / WebGL implementation of GfxDevice
+ * @details Implements all GfxDevice virtual methods using OpenGL ES 3.0 calls.
+ *
+ * @author ESEngine Team
+ * @date 2026
+ *
+ * @copyright Copyright (c) 2026 ESEngine Team
+ * Licensed under the MIT License.
+ */
+#pragma once
+
+// =============================================================================
+// Includes
+// =============================================================================
+
+#include "GfxDevice.hpp"
+
+namespace esengine {
+
+// =============================================================================
+// GLDevice Class
+// =============================================================================
+
+/**
+ * @brief OpenGL ES 3.0 / WebGL 2.0 implementation of GfxDevice
+ */
+class GLDevice final : public GfxDevice {
+public:
+ GLDevice() = default;
+ ~GLDevice() override = default;
+
+ // =========================================================================
+ // Lifecycle
+ // =========================================================================
+
+ void init() override;
+ void shutdown() override;
+
+ // =========================================================================
+ // Viewport & Clear
+ // =========================================================================
+
+ void setViewport(i32 x, i32 y, u32 w, u32 h) override;
+ void setClearColor(f32 r, f32 g, f32 b, f32 a) override;
+ void clear(bool color, bool depth, bool stencil) override;
+
+ // =========================================================================
+ // Blend State
+ // =========================================================================
+
+ void setBlendEnabled(bool enabled) override;
+ void setBlendMode(BlendMode mode) override;
+ void setBlendFunc(u32 srcFactor, u32 dstFactor, u32 srcAlphaFactor, u32 dstAlphaFactor) override;
+
+ // =========================================================================
+ // Depth State
+ // =========================================================================
+
+ void setDepthTest(bool enabled) override;
+ void setDepthWrite(bool enabled) override;
+
+ // =========================================================================
+ // Stencil State
+ // =========================================================================
+
+ void setStencilTest(bool enabled) override;
+ void setStencilFunc(u32 func, i32 ref, u32 mask) override;
+ void setStencilOp(u32 sfail, u32 dpfail, u32 dppass) override;
+ void setStencilMask(u32 mask) override;
+ void setColorMask(bool r, bool g, bool b, bool a) override;
+
+ // =========================================================================
+ // Scissor State
+ // =========================================================================
+
+ void setScissorTest(bool enabled) override;
+ void setScissor(i32 x, i32 y, i32 w, i32 h) override;
+
+ // =========================================================================
+ // Culling
+ // =========================================================================
+
+ void setCulling(bool enabled) override;
+ void setCullFace(bool front) override;
+
+ // =========================================================================
+ // Texture Binding
+ // =========================================================================
+
+ void bindTexture(u32 slot, u32 textureId) override;
+
+ // =========================================================================
+ // Shader Program
+ // =========================================================================
+
+ void useProgram(u32 programId) override;
+ i32 getUniformLocation(u32 programId, const char* name) override;
+ void setUniform1i(i32 location, i32 value) override;
+ void setUniform1f(i32 location, f32 value) override;
+ void setUniform2f(i32 location, f32 x, f32 y) override;
+ void setUniform3f(i32 location, f32 x, f32 y, f32 z) override;
+ void setUniform4f(i32 location, f32 x, f32 y, f32 z, f32 w) override;
+ void setUniformMat3(i32 location, const f32* data) override;
+ void setUniformMat4(i32 location, const f32* data) override;
+
+ // =========================================================================
+ // Buffer Operations
+ // =========================================================================
+
+ u32 createBuffer() override;
+ void deleteBuffer(u32 bufferId) override;
+ void bindVertexBuffer(u32 bufferId) override;
+ void bindIndexBuffer(u32 bufferId) override;
+ void bufferData(u32 target, const void* data, u32 sizeBytes, bool dynamic) override;
+ void bufferSubData(u32 target, u32 offset, const void* data, u32 sizeBytes) override;
+
+ // =========================================================================
+ // VAO Operations
+ // =========================================================================
+
+ u32 createVertexArray() override;
+ void deleteVertexArray(u32 vaoId) override;
+ void bindVertexArray(u32 vaoId) override;
+ void enableVertexAttrib(u32 index) override;
+ void vertexAttribPointer(u32 index, i32 size, u32 type,
+ bool normalized, i32 stride, u32 offset) override;
+ void vertexAttribDivisor(u32 index, u32 divisor) override;
+
+ // =========================================================================
+ // Draw Calls
+ // =========================================================================
+
+ void drawElements(u32 indexCount, u32 indexType, u32 byteOffset) override;
+ void drawArrays(u32 first, u32 vertexCount) override;
+ void drawElementsInstanced(u32 indexCount, u32 indexType, u32 byteOffset, u32 instanceCount) override;
+
+ // =========================================================================
+ // Texture Creation
+ // =========================================================================
+
+ u32 createTexture() override;
+ void deleteTexture(u32 textureId) override;
+ void texImage2D(u32 textureId, u32 width, u32 height,
+ u32 internalFormat, u32 format, u32 type,
+ const void* data) override;
+ void texSubImage2D(u32 textureId, i32 xoffset, i32 yoffset,
+ u32 width, u32 height,
+ u32 format, u32 type, const void* data) override;
+ void setTextureParams(u32 textureId, TextureFilter min, TextureFilter mag,
+ TextureWrap wrapS, TextureWrap wrapT) override;
+ void generateMipmaps(u32 textureId) override;
+ void pixelStorei(u32 pname, i32 param) override;
+
+ // =========================================================================
+ // Framebuffer
+ // =========================================================================
+
+ u32 createFramebuffer() override;
+ void deleteFramebuffer(u32 fboId) override;
+ void bindFramebuffer(u32 fboId) override;
+ void framebufferTexture2D(u32 fboId, u32 attachment, u32 textureId) override;
+ bool checkFramebufferStatus() override;
+
+ // =========================================================================
+ // Readback
+ // =========================================================================
+
+ void readPixels(i32 x, i32 y, u32 w, u32 h, u32 format, u32 type, void* data) override;
+
+ // =========================================================================
+ // Debug
+ // =========================================================================
+
+ void setWireframe(bool enabled) override;
+ u32 getError() override;
+};
+
+} // namespace esengine
diff --git a/src/esengine/renderer/GfxDevice.hpp b/src/esengine/renderer/GfxDevice.hpp
new file mode 100644
index 000000000..d3ba33e09
--- /dev/null
+++ b/src/esengine/renderer/GfxDevice.hpp
@@ -0,0 +1,288 @@
+/**
+ * @file GfxDevice.hpp
+ * @brief Abstract graphics device interface
+ * @details Thin abstraction layer over graphics APIs (OpenGL ES, WebGPU, Vulkan).
+ * Upper-layer code (DrawList, RenderFrame, plugins) depends only on this
+ * interface, isolating all API-specific calls into concrete implementations.
+ *
+ * @author ESEngine Team
+ * @date 2026
+ *
+ * @copyright Copyright (c) 2026 ESEngine Team
+ * Licensed under the MIT License.
+ */
+#pragma once
+
+// =============================================================================
+// Includes
+// =============================================================================
+
+#include "../core/Types.hpp"
+#include "BlendMode.hpp"
+#include "Texture.hpp"
+
+namespace esengine {
+
+// =============================================================================
+// GfxDevice Interface
+// =============================================================================
+
+/**
+ * @brief Abstract graphics device interface
+ *
+ * @details Stateless command interface — each method maps 1:1 to a GPU API call.
+ * StateTracker wraps this with caching to eliminate redundant state changes.
+ */
+class GfxDevice {
+public:
+ virtual ~GfxDevice() = default;
+
+ // =========================================================================
+ // Lifecycle
+ // =========================================================================
+
+ /** @brief Initializes the graphics device */
+ virtual void init() = 0;
+
+ /** @brief Shuts down the graphics device */
+ virtual void shutdown() = 0;
+
+ // =========================================================================
+ // Viewport & Clear
+ // =========================================================================
+
+ /** @brief Sets the rendering viewport */
+ virtual void setViewport(i32 x, i32 y, u32 w, u32 h) = 0;
+
+ /** @brief Sets the clear color */
+ virtual void setClearColor(f32 r, f32 g, f32 b, f32 a) = 0;
+
+ /** @brief Clears framebuffer attachments */
+ virtual void clear(bool color, bool depth, bool stencil) = 0;
+
+ // =========================================================================
+ // Blend State
+ // =========================================================================
+
+ /** @brief Enables or disables blending */
+ virtual void setBlendEnabled(bool enabled) = 0;
+
+ /** @brief Sets blend mode using predefined BlendMode */
+ virtual void setBlendMode(BlendMode mode) = 0;
+
+ /** @brief Sets custom blend function (src, dst, srcAlpha, dstAlpha as GL enums) */
+ virtual void setBlendFunc(u32 srcFactor, u32 dstFactor, u32 srcAlphaFactor, u32 dstAlphaFactor) = 0;
+
+ // =========================================================================
+ // Depth State
+ // =========================================================================
+
+ /** @brief Enables or disables depth testing */
+ virtual void setDepthTest(bool enabled) = 0;
+
+ /** @brief Enables or disables depth buffer writes */
+ virtual void setDepthWrite(bool enabled) = 0;
+
+ // =========================================================================
+ // Stencil State
+ // =========================================================================
+
+ /** @brief Enables or disables stencil testing */
+ virtual void setStencilTest(bool enabled) = 0;
+
+ /** @brief Sets stencil function (func, ref, mask as GL enums) */
+ virtual void setStencilFunc(u32 func, i32 ref, u32 mask) = 0;
+
+ /** @brief Sets stencil operations (sfail, dpfail, dppass as GL enums) */
+ virtual void setStencilOp(u32 sfail, u32 dpfail, u32 dppass) = 0;
+
+ /** @brief Sets stencil write mask */
+ virtual void setStencilMask(u32 mask) = 0;
+
+ /** @brief Sets color write mask */
+ virtual void setColorMask(bool r, bool g, bool b, bool a) = 0;
+
+ // =========================================================================
+ // Scissor State
+ // =========================================================================
+
+ /** @brief Enables or disables scissor test */
+ virtual void setScissorTest(bool enabled) = 0;
+
+ /** @brief Sets the scissor rectangle */
+ virtual void setScissor(i32 x, i32 y, i32 w, i32 h) = 0;
+
+ // =========================================================================
+ // Culling
+ // =========================================================================
+
+ /** @brief Enables or disables face culling */
+ virtual void setCulling(bool enabled) = 0;
+
+ /** @brief Sets which face to cull (true = front, false = back) */
+ virtual void setCullFace(bool front) = 0;
+
+ // =========================================================================
+ // Texture Binding
+ // =========================================================================
+
+ /** @brief Activates a texture slot and binds a 2D texture */
+ virtual void bindTexture(u32 slot, u32 textureId) = 0;
+
+ // =========================================================================
+ // Shader Program
+ // =========================================================================
+
+ /** @brief Binds a shader program */
+ virtual void useProgram(u32 programId) = 0;
+
+ /** @brief Gets a uniform location by name */
+ virtual i32 getUniformLocation(u32 programId, const char* name) = 0;
+
+ /** @brief Sets an integer uniform */
+ virtual void setUniform1i(i32 location, i32 value) = 0;
+
+ /** @brief Sets a float uniform */
+ virtual void setUniform1f(i32 location, f32 value) = 0;
+
+ /** @brief Sets a vec2 uniform */
+ virtual void setUniform2f(i32 location, f32 x, f32 y) = 0;
+
+ /** @brief Sets a vec3 uniform */
+ virtual void setUniform3f(i32 location, f32 x, f32 y, f32 z) = 0;
+
+ /** @brief Sets a vec4 uniform */
+ virtual void setUniform4f(i32 location, f32 x, f32 y, f32 z, f32 w) = 0;
+
+ /** @brief Sets a mat3 uniform */
+ virtual void setUniformMat3(i32 location, const f32* data) = 0;
+
+ /** @brief Sets a mat4 uniform */
+ virtual void setUniformMat4(i32 location, const f32* data) = 0;
+
+ // =========================================================================
+ // Buffer Operations
+ // =========================================================================
+
+ /** @brief Creates a new buffer and returns its ID */
+ virtual u32 createBuffer() = 0;
+
+ /** @brief Deletes a buffer */
+ virtual void deleteBuffer(u32 bufferId) = 0;
+
+ /** @brief Binds a buffer to GL_ARRAY_BUFFER */
+ virtual void bindVertexBuffer(u32 bufferId) = 0;
+
+ /** @brief Binds a buffer to GL_ELEMENT_ARRAY_BUFFER */
+ virtual void bindIndexBuffer(u32 bufferId) = 0;
+
+ /** @brief Uploads data to the currently bound buffer target */
+ virtual void bufferData(u32 target, const void* data, u32 sizeBytes, bool dynamic) = 0;
+
+ /** @brief Updates a sub-region of the currently bound buffer */
+ virtual void bufferSubData(u32 target, u32 offset, const void* data, u32 sizeBytes) = 0;
+
+ // =========================================================================
+ // VAO Operations
+ // =========================================================================
+
+ /** @brief Creates a vertex array object */
+ virtual u32 createVertexArray() = 0;
+
+ /** @brief Deletes a vertex array object */
+ virtual void deleteVertexArray(u32 vaoId) = 0;
+
+ /** @brief Binds a vertex array object */
+ virtual void bindVertexArray(u32 vaoId) = 0;
+
+ /** @brief Enables a vertex attribute */
+ virtual void enableVertexAttrib(u32 index) = 0;
+
+ /** @brief Configures a vertex attribute pointer */
+ virtual void vertexAttribPointer(u32 index, i32 size, u32 type,
+ bool normalized, i32 stride, u32 offset) = 0;
+
+ /** @brief Sets vertex attribute divisor for instanced rendering */
+ virtual void vertexAttribDivisor(u32 index, u32 divisor) = 0;
+
+ // =========================================================================
+ // Draw Calls
+ // =========================================================================
+
+ /** @brief Draws indexed primitives (GL_TRIANGLES) */
+ virtual void drawElements(u32 indexCount, u32 indexType, u32 byteOffset) = 0;
+
+ /** @brief Draws non-indexed primitives (GL_TRIANGLES) */
+ virtual void drawArrays(u32 first, u32 vertexCount) = 0;
+
+ /** @brief Draws indexed primitives with instancing */
+ virtual void drawElementsInstanced(u32 indexCount, u32 indexType, u32 byteOffset, u32 instanceCount) = 0;
+
+ // =========================================================================
+ // Texture Creation
+ // =========================================================================
+
+ /** @brief Creates a new texture and returns its ID */
+ virtual u32 createTexture() = 0;
+
+ /** @brief Deletes a texture */
+ virtual void deleteTexture(u32 textureId) = 0;
+
+ /** @brief Allocates texture storage with optional initial data */
+ virtual void texImage2D(u32 textureId, u32 width, u32 height,
+ u32 internalFormat, u32 format, u32 type,
+ const void* data) = 0;
+
+ /** @brief Updates a sub-region of a texture */
+ virtual void texSubImage2D(u32 textureId, i32 xoffset, i32 yoffset,
+ u32 width, u32 height,
+ u32 format, u32 type, const void* data) = 0;
+
+ /** @brief Sets texture filtering and wrap parameters */
+ virtual void setTextureParams(u32 textureId, TextureFilter min, TextureFilter mag,
+ TextureWrap wrapS, TextureWrap wrapT) = 0;
+
+ /** @brief Generates mipmaps for a texture */
+ virtual void generateMipmaps(u32 textureId) = 0;
+
+ /** @brief Sets pixel store parameter */
+ virtual void pixelStorei(u32 pname, i32 param) = 0;
+
+ // =========================================================================
+ // Framebuffer
+ // =========================================================================
+
+ /** @brief Creates a framebuffer and returns its ID */
+ virtual u32 createFramebuffer() = 0;
+
+ /** @brief Deletes a framebuffer */
+ virtual void deleteFramebuffer(u32 fboId) = 0;
+
+ /** @brief Binds a framebuffer (0 = default) */
+ virtual void bindFramebuffer(u32 fboId) = 0;
+
+ /** @brief Attaches a texture to a framebuffer */
+ virtual void framebufferTexture2D(u32 fboId, u32 attachment, u32 textureId) = 0;
+
+ /** @brief Checks framebuffer completeness */
+ virtual bool checkFramebufferStatus() = 0;
+
+ // =========================================================================
+ // Readback
+ // =========================================================================
+
+ /** @brief Reads pixels from the current framebuffer */
+ virtual void readPixels(i32 x, i32 y, u32 w, u32 h, u32 format, u32 type, void* data) = 0;
+
+ // =========================================================================
+ // Debug
+ // =========================================================================
+
+ /** @brief Enables or disables wireframe rendering (desktop only) */
+ virtual void setWireframe(bool enabled) = 0;
+
+ /** @brief Queries the last error */
+ virtual u32 getError() = 0;
+};
+
+} // namespace esengine
diff --git a/src/esengine/renderer/ImmediateDraw.cpp b/src/esengine/renderer/ImmediateDraw.cpp
index 71d52b807..ab98afdbf 100644
--- a/src/esengine/renderer/ImmediateDraw.cpp
+++ b/src/esengine/renderer/ImmediateDraw.cpp
@@ -11,19 +11,11 @@
#include "ImmediateDraw.hpp"
#include "Renderer.hpp"
+#include "RenderCommand.hpp"
#include "RenderContext.hpp"
#include "../resource/ResourceManager.hpp"
#include "../core/Log.hpp"
-#ifdef ES_PLATFORM_WEB
- #include <GLES3/gl3.h>
-#else
- #ifdef _WIN32
- #include <windows.h>
- #endif
- #include <glad/glad.h>
-#endif
-
#include <glm/gtc/constants.hpp>
#include <cmath>
@@ -71,9 +63,10 @@ void ImmediateDraw::shutdown() {
void ImmediateDraw::begin(const glm::mat4& viewProjection) {
if (!initialized_) return;
- glEnable(GL_BLEND);
- glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
- glDisable(GL_DEPTH_TEST);
+ auto* device = RenderCommand::getDevice();
+ device->setBlendEnabled(true);
+ device->setBlendMode(BlendMode::Normal);
+ device->setDepthTest(false);
impl_->viewProjection = viewProjection;
impl_->batcher->setProjection(viewProjection);
@@ -87,8 +80,9 @@ void ImmediateDraw::end() {
if (!initialized_ || !inFrame_) return;
impl_->batcher->endBatch();
- glEnable(GL_DEPTH_TEST);
- glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
+ auto* device = RenderCommand::getDevice();
+ device->setDepthTest(true);
+ device->setBlendMode(BlendMode::Normal);
inFrame_ = false;
}
diff --git a/src/esengine/renderer/PostProcessPipeline.cpp b/src/esengine/renderer/PostProcessPipeline.cpp
index 3f55fe032..e1f55c632 100644
--- a/src/esengine/renderer/PostProcessPipeline.cpp
+++ b/src/esengine/renderer/PostProcessPipeline.cpp
@@ -11,20 +11,13 @@
#include "PostProcessPipeline.hpp"
#include "RenderContext.hpp"
-#include "RenderCommand.hpp"
+#include "RenderCommand.hpp" // for RenderCommand::getDevice()
#include "Shader.hpp"
#include "../resource/ResourceManager.hpp"
#include "../core/Log.hpp"
#include <algorithm>
-#ifdef ES_PLATFORM_WEB
- #include <GLES3/gl3.h>
-#else
- #ifdef _WIN32
- #include <windows.h>
- #endif
- #include <glad/glad.h>
-#endif
+#include "OpenGLHeaders.hpp"
namespace esengine {
@@ -120,14 +113,13 @@ void PostProcessPipeline::shutdown() {
passes_.clear();
screenPasses_.clear();
- if (screen_quad_vbo_ != 0) {
- GLuint vbo = static_cast<GLuint>(screen_quad_vbo_);
- glDeleteBuffers(1, &vbo);
+ auto* device = RenderCommand::getDevice();
+ if (screen_quad_vbo_ != 0 && device) {
+ device->deleteBuffer(screen_quad_vbo_);
screen_quad_vbo_ = 0;
}
- if (screen_quad_vao_ != 0) {
- GLuint vao = static_cast<GLuint>(screen_quad_vao_);
- glDeleteVertexArrays(1, &vao);
+ if (screen_quad_vao_ != 0 && device) {
+ device->deleteVertexArray(screen_quad_vao_);
screen_quad_vao_ = 0;
}
@@ -251,38 +243,39 @@ PostProcessPass* PostProcessPipeline::findPass(const std::string& name) {
void PostProcessPipeline::ensureScreenQuad() {
if (screen_quad_vao_ != 0) return;
- constexpr GLsizei STRIDE = 4 * static_cast<GLsizei>(sizeof(f32));
+ auto* device = RenderCommand::getDevice();
+
f32 vertices[] = {
-1.0f, -1.0f, 0.0f, 0.0f,
3.0f, -1.0f, 2.0f, 0.0f,
-1.0f, 3.0f, 0.0f, 2.0f,
};
- GLuint vao = 0, vbo = 0;
- glGenVertexArrays(1, &vao);
- glBindVertexArray(vao);
+ constexpr i32 STRIDE = 4 * static_cast<i32>(sizeof(f32));
+
+ u32 vao = device->createVertexArray();
+ device->bindVertexArray(vao);
- glGenBuffers(1, &vbo);
- glBindBuffer(GL_ARRAY_BUFFER, vbo);
- glBufferData(GL_ARRAY_BUFFER, static_cast<GLsizeiptr>(sizeof(vertices)), vertices, GL_STATIC_DRAW);
+ u32 vbo = device->createBuffer();
+ device->bindVertexBuffer(vbo);
+ device->bufferData(GL_ARRAY_BUFFER, vertices, static_cast<u32>(sizeof(vertices)), false);
- glEnableVertexAttribArray(0);
- glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, STRIDE,
- reinterpret_cast<const void*>(0));
- glEnableVertexAttribArray(1);
- glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, STRIDE,
- reinterpret_cast<const void*>(2 * sizeof(f32)));
+ device->enableVertexAttrib(0);
+ device->vertexAttribPointer(0, 2, GL_FLOAT, false, STRIDE, 0);
+ device->enableVertexAttrib(1);
+ device->vertexAttribPointer(1, 2, GL_FLOAT, false, STRIDE, 2 * sizeof(f32));
- glBindVertexArray(0);
+ device->bindVertexArray(0);
- screen_quad_vao_ = static_cast<u32>(vao);
- screen_quad_vbo_ = static_cast<u32>(vbo);
+ screen_quad_vao_ = vao;
+ screen_quad_vbo_ = vbo;
}
void PostProcessPipeline::drawScreenQuad() {
ensureScreenQuad();
- glBindVertexArray(static_cast<GLuint>(screen_quad_vao_));
- glDrawArrays(GL_TRIANGLES, 0, 3);
+ auto* device = RenderCommand::getDevice();
+ device->bindVertexArray(screen_quad_vao_);
+ device->drawArrays(0, 3);
}
void PostProcessPipeline::begin() {
@@ -291,9 +284,10 @@ void PostProcessPipeline::begin() {
ensureFBOs();
if (!fboOriginalCreated_) return;
+ auto* device = RenderCommand::getDevice();
fboOriginal_->bind();
- RenderCommand::setViewport(0, 0, width_, height_);
- RenderCommand::clear();
+ device->setViewport(0, 0, width_, height_);
+ device->clear(true, true, false);
inFrame_ = true;
currentFBO_ = 0;
@@ -302,16 +296,18 @@ void PostProcessPipeline::begin() {
void PostProcessPipeline::end() {
if (!initialized_ || !inFrame_ || bypass_) return;
+ auto* device = RenderCommand::getDevice();
+
u32 enabledCount = 0;
for (const auto& pass : passes_) {
if (pass.enabled) enabledCount++;
}
- RenderCommand::setDepthTest(false);
- RenderCommand::setBlending(false);
- glDisable(GL_SCISSOR_TEST);
- glDisable(GL_STENCIL_TEST);
- glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
+ device->setDepthTest(false);
+ device->setBlendEnabled(false);
+ device->setScissorTest(false);
+ device->setStencilTest(false);
+ device->setColorMask(true, true, true, true);
sceneTexture_ = fboOriginal_->getColorAttachment();
fboOriginal_->unbind();
@@ -322,16 +318,15 @@ void PostProcessPipeline::end() {
u32 inputTexture = sceneTexture_;
currentFBO_ = 0;
- glActiveTexture(GL_TEXTURE1);
- glBindTexture(GL_TEXTURE_2D, sceneTexture_);
- glActiveTexture(GL_TEXTURE0);
+ device->bindTexture(1, sceneTexture_);
+ device->bindTexture(0, 0);
for (const auto& pass : passes_) {
if (!pass.enabled) continue;
Framebuffer* targetFBO = (currentFBO_ == 0) ? fboA_.get() : fboB_.get();
targetFBO->bind();
- RenderCommand::setViewport(0, 0, width_, height_);
+ device->setViewport(0, 0, width_, height_);
renderPass(pass, inputTexture);
@@ -345,8 +340,8 @@ void PostProcessPipeline::end() {
blitToOutput(inputTexture);
}
- RenderCommand::setBlending(true);
- RenderCommand::setDepthTest(true);
+ device->setBlendEnabled(true);
+ device->setDepthTest(true);
inFrame_ = false;
output_target_fbo_ = 0;
}
@@ -355,8 +350,8 @@ void PostProcessPipeline::renderPass(const PostProcessPass& pass, u32 inputTextu
Shader* shader = resourceManager_.getShader(pass.shader);
if (!shader) return;
- glActiveTexture(GL_TEXTURE0);
- glBindTexture(GL_TEXTURE_2D, inputTexture);
+ auto* device = RenderCommand::getDevice();
+ device->bindTexture(0, inputTexture);
shader->bind();
shader->setUniform("u_texture", 0);
@@ -393,14 +388,14 @@ void PostProcessPipeline::blitToOutput(u32 texture) {
Shader* shader = resourceManager_.getShader(blitShader_);
if (!shader) return;
- glBindFramebuffer(GL_FRAMEBUFFER, output_target_fbo_);
+ auto* device = RenderCommand::getDevice();
+ device->bindFramebuffer(output_target_fbo_);
if (output_vp_w_ > 0 && output_vp_h_ > 0) {
- RenderCommand::setViewport(output_vp_x_, output_vp_y_, output_vp_w_, output_vp_h_);
+ device->setViewport(output_vp_x_, output_vp_y_, output_vp_w_, output_vp_h_);
}
- glActiveTexture(GL_TEXTURE0);
- glBindTexture(GL_TEXTURE_2D, texture);
+ device->bindTexture(0, texture);
shader->bind();
shader->setUniform("u_texture", 0);
@@ -440,9 +435,10 @@ void PostProcessPipeline::beginScreenCapture() {
ensureScreenFBO();
if (!screenFBOCreated_) return;
+ auto* device = RenderCommand::getDevice();
screenFBO_->bind();
- RenderCommand::setViewport(0, 0, width_, height_);
- RenderCommand::clear();
+ device->setViewport(0, 0, width_, height_);
+ device->clear(true, true, false);
screenCaptureActive_ = true;
}
@@ -457,6 +453,8 @@ void PostProcessPipeline::endScreenCapture() {
void PostProcessPipeline::executeScreenPasses() {
if (!initialized_ || !screenFBOCreated_) return;
+ auto* device = RenderCommand::getDevice();
+
u32 enabledCount = 0;
for (const auto& pass : screenPasses_) {
if (pass.enabled) enabledCount++;
@@ -467,11 +465,11 @@ void PostProcessPipeline::executeScreenPasses() {
return;
}
- RenderCommand::setDepthTest(false);
- RenderCommand::setBlending(false);
- glDisable(GL_SCISSOR_TEST);
- glDisable(GL_STENCIL_TEST);
- glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
+ device->setDepthTest(false);
+ device->setBlendEnabled(false);
+ device->setScissorTest(false);
+ device->setStencilTest(false);
+ device->setColorMask(true, true, true, true);
ensureFBOs();
if (!fbosCreated_) return;
@@ -481,16 +479,15 @@ void PostProcessPipeline::executeScreenPasses() {
u32 inputTexture = sceneTexture_;
u32 pingPong = 0;
- glActiveTexture(GL_TEXTURE1);
- glBindTexture(GL_TEXTURE_2D, sceneTexture_);
- glActiveTexture(GL_TEXTURE0);
+ device->bindTexture(1, sceneTexture_);
+ device->bindTexture(0, 0);
for (const auto& pass : screenPasses_) {
if (!pass.enabled) continue;
Framebuffer* targetFBO = (pingPong == 0) ? fboA_.get() : fboB_.get();
targetFBO->bind();
- RenderCommand::setViewport(0, 0, width_, height_);
+ device->setViewport(0, 0, width_, height_);
renderPass(pass, inputTexture);
@@ -501,12 +498,12 @@ void PostProcessPipeline::executeScreenPasses() {
Framebuffer* lastFBO = (pingPong == 0) ? fboA_.get() : fboB_.get();
lastFBO->unbind();
- glBindFramebuffer(GL_FRAMEBUFFER, 0);
- RenderCommand::setViewport(0, 0, width_, height_);
+ device->bindFramebuffer(0);
+ device->setViewport(0, 0, width_, height_);
blitToOutput(inputTexture);
- RenderCommand::setBlending(true);
- RenderCommand::setDepthTest(true);
+ device->setBlendEnabled(true);
+ device->setDepthTest(true);
}
u32 PostProcessPipeline::addScreenPass(const std::string& name, resource::ShaderHandle shader) {
diff --git a/src/esengine/renderer/RenderCommand.hpp b/src/esengine/renderer/RenderCommand.hpp
index 5a95306cc..cd06feb83 100644
--- a/src/esengine/renderer/RenderCommand.hpp
+++ b/src/esengine/renderer/RenderCommand.hpp
@@ -1,13 +1,13 @@
/**
* @file RenderCommand.hpp
- * @brief Low-level rendering commands
- * @details Provides a static interface for GPU state management and
- * draw call submission. Abstracts OpenGL/WebGL calls.
+ * @brief Low-level rendering commands (GfxDevice proxy)
+ * @details Provides a static interface that delegates to the active GfxDevice.
+ * Preserves the existing static API so callers need not change.
*
* @author ESEngine Team
- * @date 2025
+ * @date 2026
*
- * @copyright Copyright (c) 2025 ESEngine Team
+ * @copyright Copyright (c) 2026 ESEngine Team
* Licensed under the MIT License.
*/
#pragma once
@@ -16,14 +16,13 @@
// Includes
// =============================================================================
-// Project includes
#include "../core/Types.hpp"
#include "../math/Math.hpp"
#include "BlendMode.hpp"
+#include "GfxDevice.hpp"
namespace esengine {
-// Forward declaration
class VertexArray;
// =============================================================================
@@ -31,163 +30,43 @@ class VertexArray;
// =============================================================================
/**
- * @brief Static interface for low-level rendering operations
+ * @brief Static proxy to the active GfxDevice
*
- * @details Provides direct control over GPU state and draw calls.
- * All methods are static - no instance needed. Used internally
- * by the Renderer class and can be used directly for custom
- * rendering pipelines.
- *
- * @code
- * RenderCommand::init();
- * RenderCommand::setViewport(0, 0, 800, 600);
- * RenderCommand::setClearColor({0.1f, 0.1f, 0.1f, 1.0f});
- * RenderCommand::clear();
- *
- * // Enable alpha blending
- * RenderCommand::setBlending(true);
- * RenderCommand::setBlendFunc();
- *
- * // Draw indexed geometry
- * vao.bind();
- * RenderCommand::drawIndexed(vao);
- * @endcode
+ * @details All methods delegate to the GfxDevice set via setDevice().
+ * This keeps existing call-sites unchanged.
*/
class RenderCommand {
public:
- // =========================================================================
- // Initialization
- // =========================================================================
-
- /**
- * @brief Initializes the rendering subsystem
- * @details Must be called once before any other RenderCommand functions.
- * Sets up OpenGL/WebGL state and capabilities.
- */
- static void init();
+ /** @brief Sets the GfxDevice that all static methods delegate to */
+ static void setDevice(GfxDevice* device);
+
+ /** @brief Gets the current GfxDevice */
+ static GfxDevice* getDevice();
- /**
- * @brief Shuts down the rendering subsystem
- * @details Releases any allocated resources. Call once at application exit.
- */
+ static void init();
static void shutdown();
- // =========================================================================
- // Viewport and Clearing
- // =========================================================================
-
- /**
- * @brief Sets the rendering viewport
- * @param x Viewport X origin (pixels from left)
- * @param y Viewport Y origin (pixels from bottom)
- * @param width Viewport width in pixels
- * @param height Viewport height in pixels
- */
static void setViewport(i32 x, i32 y, u32 width, u32 height);
-
- /**
- * @brief Sets the color used by clear()
- * @param color RGBA color (0-1 range)
- */
static void setClearColor(const glm::vec4& color);
-
- /**
- * @brief Clears the framebuffer
- * @details Clears both color and depth buffers.
- */
static void clear();
- // =========================================================================
- // Draw Calls
- // =========================================================================
-
- /**
- * @brief Draws indexed geometry
- * @param vao Vertex array containing geometry and indices
- * @param indexCount Number of indices to draw (0 = all)
- *
- * @details The VAO must be bound and have an index buffer set.
- */
static void drawIndexed(const VertexArray& vao, u32 indexCount = 0);
-
- /**
- * @brief Draws non-indexed geometry
- * @param vertexCount Number of vertices to draw
- *
- * @details Draws vertices as triangles (GL_TRIANGLES).
- */
static void drawArrays(u32 vertexCount);
- // =========================================================================
- // Depth Testing
- // =========================================================================
-
- /**
- * @brief Enables or disables depth testing
- * @param enabled True to enable depth test
- */
static void setDepthTest(bool enabled);
-
- /**
- * @brief Enables or disables depth buffer writes
- * @param enabled True to allow depth writes
- */
static void setDepthWrite(bool enabled);
- // =========================================================================
- // Blending
- // =========================================================================
-
- /**
- * @brief Enables or disables alpha blending
- * @param enabled True to enable blending
- */
static void setBlending(bool enabled);
-
- /**
- * @brief Sets the blend function to standard alpha blending
- * @details Uses SrcAlpha and OneMinusSrcAlpha factors.
- */
static void setBlendFunc();
-
- /**
- * @brief Sets the blend mode to a predefined mode
- * @param mode The blend mode to use
- */
static void setBlendMode(BlendMode mode);
- static void resetBlendState();
-
- // =========================================================================
- // Face Culling
- // =========================================================================
-
- /**
- * @brief Enables or disables face culling
- * @param enabled True to enable culling
- */
static void setCulling(bool enabled);
-
- /**
- * @brief Sets which face to cull
- * @param front True to cull front faces, false for back faces
- */
static void setCullFace(bool front);
- // =========================================================================
- // Debug
- // =========================================================================
-
- /**
- * @brief Enables or disables wireframe rendering
- * @param enabled True for wireframe mode
- *
- * @note May not be supported on WebGL/OpenGL ES.
- */
static void setWireframe(bool enabled);
private:
- static BlendMode currentBlend_;
+ static GfxDevice* device_;
};
} // namespace esengine
diff --git a/src/esengine/renderer/RenderContext.cpp b/src/esengine/renderer/RenderContext.cpp
index 7f4981e76..5fa8568ee 100644
--- a/src/esengine/renderer/RenderContext.cpp
+++ b/src/esengine/renderer/RenderContext.cpp
@@ -43,8 +43,9 @@ void RenderContext::shutdown() {
return;
}
- if (whiteTextureId_ != 0) {
- glDeleteTextures(1, &whiteTextureId_);
+ auto* device = RenderCommand::getDevice();
+ if (whiteTextureId_ != 0 && device) {
+ device->deleteTexture(whiteTextureId_);
whiteTextureId_ = 0;
}
@@ -59,9 +60,7 @@ void RenderContext::shutdown() {
}
void RenderContext::initQuadData() {
- // Quad vertices with position and texture coordinates
float vertices[] = {
- // Position (x, y) TexCoord (u, v)
-0.5f, -0.5f, 0.0f, 0.0f,
0.5f, -0.5f, 1.0f, 0.0f,
0.5f, 0.5f, 1.0f, 1.0f,
@@ -109,16 +108,13 @@ void RenderContext::initShaders() {
}
void RenderContext::initWhiteTexture() {
- glGenTextures(1, &whiteTextureId_);
- glBindTexture(GL_TEXTURE_2D, whiteTextureId_);
+ auto* device = RenderCommand::getDevice();
+ whiteTextureId_ = device->createTexture();
u32 whiteData = 0xFFFFFFFF;
- glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 1, 1, 0, GL_RGBA, GL_UNSIGNED_BYTE, &whiteData);
-
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
+ device->texImage2D(whiteTextureId_, 1, 1, GL_RGBA, GL_RGBA, GL_UNSIGNED_BYTE, &whiteData);
+ device->setTextureParams(whiteTextureId_, TextureFilter::Nearest, TextureFilter::Nearest,
+ TextureWrap::ClampToEdge, TextureWrap::ClampToEdge);
ES_LOG_DEBUG("White texture created (ID: {})", whiteTextureId_);
}
diff --git a/src/esengine/renderer/RenderFrame.cpp b/src/esengine/renderer/RenderFrame.cpp
index 6f945fd92..ba7fe5773 100644
--- a/src/esengine/renderer/RenderFrame.cpp
+++ b/src/esengine/renderer/RenderFrame.cpp
@@ -1,18 +1,10 @@
#include "RenderFrame.hpp"
+#include "OpenGLHeaders.hpp"
#include "Shader.hpp"
#include "ShaderEmbeds.generated.hpp"
#include "../resource/ShaderParser.hpp"
#include "../core/Log.hpp"
-#ifdef ES_PLATFORM_WEB
- #include <GLES3/gl3.h>
-#else
- #ifdef _WIN32
- #include <windows.h>
- #endif
- #include <glad/glad.h>
-#endif
-
#include <glm/gtc/type_ptr.hpp>
#include <cmath>
@@ -66,9 +58,12 @@ bool Frustum::intersectsAABB(const glm::vec3& center, const glm::vec3& halfExten
return true;
}
-RenderFrame::RenderFrame(RenderContext& context, resource::ResourceManager& resource_manager)
- : context_(context)
- , resource_manager_(resource_manager) {
+RenderFrame::RenderFrame(GfxDevice& device, RenderContext& context, resource::ResourceManager& resource_manager)
+ : device_(device)
+ , context_(context)
+ , resource_manager_(resource_manager)
+ , state_tracker_(device)
+ , pool_(device) {
}
RenderFrame::~RenderFrame() {
@@ -194,7 +189,7 @@ void RenderFrame::flush() {
}
};
- draw_list_.execute(state_tracker_, pool_, view_projection_, &frame_capture_, customDrawFn);
+ draw_list_.execute(device_, state_tracker_, pool_, view_projection_, &frame_capture_, customDrawFn);
stats_.draw_calls = draw_list_.mergedDrawCallCount();
for (u32 i = 0; i < draw_list_.commandCount(); ++i) {
@@ -267,8 +262,8 @@ void RenderFrame::replayToDrawCall(i32 stopAtDrawCall) {
rt->bind();
state_tracker_.setViewport(0, 0, width_, height_);
- glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
- glClear(GL_COLOR_BUFFER_BIT);
+ device_.setClearColor(0.0f, 0.0f, 0.0f, 0.0f);
+ device_.clear(true, false, false);
state_tracker_.reset();
state_tracker_.setBlendEnabled(true);
@@ -277,7 +272,7 @@ void RenderFrame::replayToDrawCall(i32 stopAtDrawCall) {
frame_capture_.setReplayMode(stopAtDrawCall + 1);
- draw_list_.execute(state_tracker_, pool_, view_projection_, &frame_capture_);
+ draw_list_.execute(device_, state_tracker_, pool_, view_projection_, &frame_capture_);
state_tracker_.setScissorEnabled(false);
state_tracker_.endStencilTest();
@@ -286,8 +281,8 @@ void RenderFrame::replayToDrawCall(i32 stopAtDrawCall) {
u32 pixelCount = width_ * height_ * 4;
snapshot_pixels_.resize(pixelCount);
- glReadPixels(0, 0, static_cast<GLsizei>(width_), static_cast<GLsizei>(height_),
- GL_RGBA, GL_UNSIGNED_BYTE, snapshot_pixels_.data());
+ device_.readPixels(0, 0, width_, height_, GL_RGBA, GL_UNSIGNED_BYTE,
+ snapshot_pixels_.data());
rt->unbind();
}
@@ -422,9 +417,9 @@ u32 RenderFrame::initBatchShader() {
if (shader && shader->isValid()) {
shader->bind();
- GLint texLoc = glGetUniformLocation(shader->getProgramId(), "u_texture");
+ i32 texLoc = device_.getUniformLocation(shader->getProgramId(), "u_texture");
if (texLoc >= 0) {
- glUniform1i(texLoc, 0);
+ device_.setUniform1i(texLoc, 0);
}
shader->unbind();
return shader->getProgramId();
diff --git a/src/esengine/renderer/RenderFrame.hpp b/src/esengine/renderer/RenderFrame.hpp
index dca215e80..01e7ae9de 100644
--- a/src/esengine/renderer/RenderFrame.hpp
+++ b/src/esengine/renderer/RenderFrame.hpp
@@ -9,6 +9,7 @@
#include "PostProcessPipeline.hpp"
#endif
#include "FrameCapture.hpp"
+#include "GfxDevice.hpp"
#include "StateTracker.hpp"
#include "TransientBufferPool.hpp"
#include "DrawList.hpp"
@@ -51,7 +52,7 @@ public:
u32 culled = 0;
};
- RenderFrame(RenderContext& context, resource::ResourceManager& resource_manager);
+ RenderFrame(GfxDevice& device, RenderContext& context, resource::ResourceManager& resource_manager);
~RenderFrame();
RenderFrame(const RenderFrame&) = delete;
@@ -120,6 +121,7 @@ public:
static constexpr u32 STAGE_COUNT = 4;
private:
+ GfxDevice& device_;
RenderContext& context_;
resource::ResourceManager& resource_manager_;
StateTracker state_tracker_;
diff --git a/src/esengine/renderer/RenderFrameMask.cpp b/src/esengine/renderer/RenderFrameMask.cpp
index b93a9bd14..35e96df29 100644
--- a/src/esengine/renderer/RenderFrameMask.cpp
+++ b/src/esengine/renderer/RenderFrameMask.cpp
@@ -5,15 +5,6 @@
#include "../ecs/components/UIMask.hpp"
#include "../ecs/components/Hierarchy.hpp"
-#ifdef ES_PLATFORM_WEB
- #include <GLES3/gl3.h>
-#else
- #ifdef _WIN32
- #include <windows.h>
- #endif
- #include <glad/glad.h>
-#endif
-
#include <glm/glm.hpp>
#include <algorithm>
@@ -239,8 +230,7 @@ void RenderFrame::processMasks(ecs::Registry& registry, i32 vpX, i32 vpY, i32 vp
if (!stencilMasks.empty()) {
#ifdef ES_PLATFORM_WEB
- glClearStencil(0);
- glClear(GL_STENCIL_BUFFER_BIT);
+ device_.clear(false, false, true);
#endif
std::vector<Entity> rootStencils;
diff --git a/src/esengine/renderer/Renderer.cpp b/src/esengine/renderer/Renderer.cpp
index 2cac92185..44787d8cd 100644
--- a/src/esengine/renderer/Renderer.cpp
+++ b/src/esengine/renderer/Renderer.cpp
@@ -35,34 +35,42 @@
namespace esengine {
// ========================================
-// RenderCommand Implementation
+// RenderCommand Implementation (GfxDevice proxy)
// ========================================
-BlendMode RenderCommand::currentBlend_ = BlendMode::Normal;
+GfxDevice* RenderCommand::device_ = nullptr;
-void RenderCommand::init() {
- // Enable depth testing by default
- glEnable(GL_DEPTH_TEST);
+void RenderCommand::setDevice(GfxDevice* device) {
+ device_ = device;
+}
- // Enable blending
- glEnable(GL_BLEND);
- glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
+GfxDevice* RenderCommand::getDevice() {
+ return device_;
+}
+
+void RenderCommand::init() {
+ if (device_) {
+ device_->init();
+ }
}
void RenderCommand::shutdown() {
+ if (device_) {
+ device_->shutdown();
+ }
ES_LOG_INFO("RenderCommand shutdown");
}
void RenderCommand::setViewport(i32 x, i32 y, u32 width, u32 height) {
- glViewport(x, y, static_cast<GLsizei>(width), static_cast<GLsizei>(height));
+ device_->setViewport(x, y, width, height);
}
void RenderCommand::setClearColor(const glm::vec4& color) {
- glClearColor(color.r, color.g, color.b, color.a);
+ device_->setClearColor(color.r, color.g, color.b, color.a);
}
void RenderCommand::clear() {
- glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
+ device_->clear(true, true, false);
}
void RenderCommand::drawIndexed(const VertexArray& vao, u32 indexCount) {
@@ -71,85 +79,44 @@ void RenderCommand::drawIndexed(const VertexArray& vao, u32 indexCount) {
u32 count = indexCount ? indexCount : (ib ? ib->getCount() : 0);
if (count > 0 && ib) {
GLenum type = ib->is16Bit() ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT;
- glDrawElements(GL_TRIANGLES, static_cast<GLsizei>(count), type, nullptr);
+ device_->drawElements(count, type, 0);
}
}
void RenderCommand::drawArrays(u32 vertexCount) {
- glDrawArrays(GL_TRIANGLES, 0, static_cast<GLsizei>(vertexCount));
+ device_->drawArrays(0, vertexCount);
}
void RenderCommand::setDepthTest(bool enabled) {
- if (enabled) {
- glEnable(GL_DEPTH_TEST);
- } else {
- glDisable(GL_DEPTH_TEST);
- }
+ device_->setDepthTest(enabled);
}
void RenderCommand::setDepthWrite(bool enabled) {
- glDepthMask(enabled ? GL_TRUE : GL_FALSE);
+ device_->setDepthWrite(enabled);
}
void RenderCommand::setBlending(bool enabled) {
- if (enabled) {
- glEnable(GL_BLEND);
- } else {
- glDisable(GL_BLEND);
- }
+ device_->setBlendEnabled(enabled);
}
void RenderCommand::setBlendFunc() {
- glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
-}
-
-void RenderCommand::resetBlendState() {
- currentBlend_ = BlendMode::Normal;
+ device_->setBlendMode(BlendMode::Normal);
}
void RenderCommand::setBlendMode(BlendMode mode) {
- if (mode == currentBlend_) return;
- currentBlend_ = mode;
- switch (mode) {
- case BlendMode::Normal:
- glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
- break;
- case BlendMode::Additive:
- glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE, GL_ONE, GL_ONE);
- break;
- case BlendMode::Multiply:
- glBlendFuncSeparate(GL_DST_COLOR, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
- break;
- case BlendMode::Screen:
- glBlendFuncSeparate(GL_ONE, GL_ONE_MINUS_SRC_COLOR, GL_ONE, GL_ONE_MINUS_SRC_COLOR);
- break;
- case BlendMode::PremultipliedAlpha:
- glBlendFuncSeparate(GL_ONE, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
- break;
- case BlendMode::PmaAdditive:
- glBlendFuncSeparate(GL_ONE, GL_ONE, GL_ONE, GL_ONE);
- break;
- }
+ device_->setBlendMode(mode);
}
void RenderCommand::setCulling(bool enabled) {
- if (enabled) {
- glEnable(GL_CULL_FACE);
- } else {
- glDisable(GL_CULL_FACE);
- }
+ device_->setCulling(enabled);
}
void RenderCommand::setCullFace(bool front) {
- glCullFace(front ? GL_FRONT : GL_BACK);
+ device_->setCullFace(front);
}
void RenderCommand::setWireframe(bool enabled) {
-#ifndef ES_PLATFORM_WEB
- glPolygonMode(GL_FRONT_AND_BACK, enabled ? GL_LINE : GL_FILL);
-#else
- (void)enabled;
-#endif
+ device_->setWireframe(enabled);
}
// ========================================
@@ -388,9 +355,10 @@ void BatchRenderer2D::init() {
if (batchShader && batchShader->isValid()) {
batchShader->bind();
- GLint texLoc = glGetUniformLocation(batchShader->getProgramId(), "u_texture");
+ auto* dev = RenderCommand::getDevice();
+ i32 texLoc = dev->getUniformLocation(batchShader->getProgramId(), "u_texture");
if (texLoc >= 0) {
- glUniform1i(texLoc, 0);
+ dev->setUniform1i(texLoc, 0);
}
} else {
ES_LOG_ERROR("All batch shader variants FAILED!");
@@ -452,27 +420,27 @@ void BatchRenderer2D::flush() {
data_->vbo->setDataRaw(data_->triVertices.data(), triBytes);
}
- data_->texSlots.bindAll();
+ data_->texSlots.bindAll(*RenderCommand::getDevice());
shader->bind();
shader->setUniform(data_->projectionLoc, data_->projection);
data_->vao->bind();
+ auto* dev = RenderCommand::getDevice();
if (hasQuads) {
auto ib = data_->vao->getIndexBuffer();
if (ib) {
ib->bind();
GLenum type = ib->is16Bit() ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT;
- glDrawElements(GL_TRIANGLES, static_cast<GLsizei>(data_->indexCount), type, nullptr);
+ dev->drawElements(data_->indexCount, type, 0);
}
data_->drawCallCount++;
}
if (hasTris) {
- glDrawArrays(GL_TRIANGLES,
- static_cast<GLint>(data_->vertices.size()),
- static_cast<GLsizei>(data_->triVertices.size()));
+ dev->drawArrays(static_cast<u32>(data_->vertices.size()),
+ static_cast<u32>(data_->triVertices.size()));
data_->drawCallCount++;
}
diff --git a/src/esengine/renderer/StateTracker.cpp b/src/esengine/renderer/StateTracker.cpp
index 84ff26d6e..77637c2ea 100644
--- a/src/esengine/renderer/StateTracker.cpp
+++ b/src/esengine/renderer/StateTracker.cpp
@@ -1,45 +1,41 @@
#include "StateTracker.hpp"
-
-#ifdef ES_PLATFORM_WEB
- #include <GLES3/gl3.h>
-#else
- #ifdef _WIN32
- #include <windows.h>
- #endif
- #include <glad/glad.h>
-#endif
+#include "OpenGLHeaders.hpp"
namespace esengine {
+StateTracker::StateTracker(GfxDevice& device)
+ : device_(device) {
+}
+
void StateTracker::init() {
reset();
initialized_ = true;
}
void StateTracker::reset() {
- glEnable(GL_BLEND);
- glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
+ device_.setBlendEnabled(true);
+ device_.setBlendMode(BlendMode::Normal);
blend_mode_ = BlendMode::Normal;
blend_enabled_ = true;
- glDisable(GL_SCISSOR_TEST);
+ device_.setScissorTest(false);
scissor_enabled_ = false;
scissor_x_ = 0;
scissor_y_ = 0;
scissor_w_ = 0;
scissor_h_ = 0;
- glDisable(GL_STENCIL_TEST);
- glStencilMask(0xFF);
+ device_.setStencilTest(false);
+ device_.setStencilMask(0xFF);
stencil_state_ = StencilState::Off;
stencil_ref_ = 0;
- glDisable(GL_DEPTH_TEST);
- glDepthMask(GL_TRUE);
+ device_.setDepthTest(false);
+ device_.setDepthWrite(true);
depth_test_ = false;
depth_write_ = true;
- glDisable(GL_CULL_FACE);
+ device_.setCulling(false);
cull_enabled_ = false;
cull_front_ = false;
@@ -55,36 +51,13 @@ void StateTracker::reset() {
void StateTracker::setBlendEnabled(bool enabled) {
if (blend_enabled_ == enabled) return;
blend_enabled_ = enabled;
- if (enabled) {
- glEnable(GL_BLEND);
- } else {
- glDisable(GL_BLEND);
- }
+ device_.setBlendEnabled(enabled);
}
void StateTracker::setBlendMode(BlendMode mode) {
if (mode == blend_mode_) return;
blend_mode_ = mode;
- switch (mode) {
- case BlendMode::Normal:
- glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
- break;
- case BlendMode::Additive:
- glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE, GL_ONE, GL_ONE);
- break;
- case BlendMode::Multiply:
- glBlendFuncSeparate(GL_DST_COLOR, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
- break;
- case BlendMode::Screen:
- glBlendFuncSeparate(GL_ONE, GL_ONE_MINUS_SRC_COLOR, GL_ONE, GL_ONE_MINUS_SRC_COLOR);
- break;
- case BlendMode::PremultipliedAlpha:
- glBlendFuncSeparate(GL_ONE, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
- break;
- case BlendMode::PmaAdditive:
- glBlendFuncSeparate(GL_ONE, GL_ONE, GL_ONE, GL_ONE);
- break;
- }
+ device_.setBlendMode(mode);
}
void StateTracker::resetBlendState() {
@@ -94,11 +67,7 @@ void StateTracker::resetBlendState() {
void StateTracker::setScissorEnabled(bool enabled) {
if (scissor_enabled_ == enabled) return;
scissor_enabled_ = enabled;
- if (enabled) {
- glEnable(GL_SCISSOR_TEST);
- } else {
- glDisable(GL_SCISSOR_TEST);
- }
+ device_.setScissorTest(enabled);
}
void StateTracker::setScissor(i32 x, i32 y, i32 w, i32 h) {
@@ -107,41 +76,41 @@ void StateTracker::setScissor(i32 x, i32 y, i32 w, i32 h) {
scissor_y_ = y;
scissor_w_ = w;
scissor_h_ = h;
- glScissor(x, y, w, h);
+ device_.setScissor(x, y, w, h);
}
void StateTracker::beginStencilWrite(i32 refValue) {
if (stencil_state_ == StencilState::Write && stencil_ref_ == refValue) return;
stencil_state_ = StencilState::Write;
stencil_ref_ = refValue;
- glEnable(GL_STENCIL_TEST);
- glStencilFunc(GL_ALWAYS, refValue, 0xFF);
- glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);
- glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
- glStencilMask(0xFF);
+ device_.setStencilTest(true);
+ device_.setStencilFunc(GL_ALWAYS, refValue, 0xFF);
+ device_.setStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);
+ device_.setColorMask(false, false, false, false);
+ device_.setStencilMask(0xFF);
}
void StateTracker::endStencilWrite() {
- glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
- glStencilMask(0x00);
+ device_.setColorMask(true, true, true, true);
+ device_.setStencilMask(0x00);
}
void StateTracker::beginStencilTest(i32 refValue) {
if (stencil_state_ == StencilState::Test && stencil_ref_ == refValue) return;
stencil_state_ = StencilState::Test;
stencil_ref_ = refValue;
- glEnable(GL_STENCIL_TEST);
- glStencilFunc(GL_EQUAL, refValue, 0xFF);
- glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
- glStencilMask(0x00);
+ device_.setStencilTest(true);
+ device_.setStencilFunc(GL_EQUAL, refValue, 0xFF);
+ device_.setStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
+ device_.setStencilMask(0x00);
}
void StateTracker::endStencilTest() {
if (stencil_state_ == StencilState::Off) return;
stencil_state_ = StencilState::Off;
stencil_ref_ = 0;
- glDisable(GL_STENCIL_TEST);
- glStencilMask(0xFF);
+ device_.setStencilTest(false);
+ device_.setStencilMask(0xFF);
}
void StateTracker::bindTexture(u32 slot, u32 textureId) {
@@ -149,30 +118,25 @@ void StateTracker::bindTexture(u32 slot, u32 textureId) {
if (slot < MAX_TEXTURE_SLOTS) {
bound_textures_[slot] = textureId;
}
- glActiveTexture(GL_TEXTURE0 + slot);
- glBindTexture(GL_TEXTURE_2D, textureId);
+ device_.bindTexture(slot, textureId);
}
void StateTracker::useProgram(u32 programId) {
if (current_program_ == programId) return;
current_program_ = programId;
- glUseProgram(programId);
+ device_.useProgram(programId);
}
void StateTracker::setDepthTest(bool enabled) {
if (depth_test_ == enabled) return;
depth_test_ = enabled;
- if (enabled) {
- glEnable(GL_DEPTH_TEST);
- } else {
- glDisable(GL_DEPTH_TEST);
- }
+ device_.setDepthTest(enabled);
}
void StateTracker::setDepthWrite(bool enabled) {
if (depth_write_ == enabled) return;
depth_write_ = enabled;
- glDepthMask(enabled ? GL_TRUE : GL_FALSE);
+ device_.setDepthWrite(enabled);
}
void StateTracker::setViewport(i32 x, i32 y, u32 w, u32 h) {
@@ -181,23 +145,19 @@ void StateTracker::setViewport(i32 x, i32 y, u32 w, u32 h) {
vp_y_ = y;
vp_w_ = w;
vp_h_ = h;
- glViewport(x, y, static_cast<GLsizei>(w), static_cast<GLsizei>(h));
+ device_.setViewport(x, y, w, h);
}
void StateTracker::setCulling(bool enabled) {
if (cull_enabled_ == enabled) return;
cull_enabled_ = enabled;
- if (enabled) {
- glEnable(GL_CULL_FACE);
- } else {
- glDisable(GL_CULL_FACE);
- }
+ device_.setCulling(enabled);
}
void StateTracker::setCullFace(bool front) {
if (cull_front_ == front) return;
cull_front_ = front;
- glCullFace(front ? GL_FRONT : GL_BACK);
+ device_.setCullFace(front);
}
} // namespace esengine
diff --git a/src/esengine/renderer/StateTracker.hpp b/src/esengine/renderer/StateTracker.hpp
index aa96962dc..8b7265c43 100644
--- a/src/esengine/renderer/StateTracker.hpp
+++ b/src/esengine/renderer/StateTracker.hpp
@@ -2,6 +2,7 @@
#include "../core/Types.hpp"
#include "BlendMode.hpp"
+#include "GfxDevice.hpp"
#include <array>
@@ -9,6 +10,8 @@ namespace esengine {
class StateTracker {
public:
+ explicit StateTracker(GfxDevice& device);
+
void init();
void reset();
@@ -36,9 +39,14 @@ public:
void setCulling(bool enabled);
void setCullFace(bool front);
+ /** @brief Gets the underlying graphics device */
+ GfxDevice& device() { return device_; }
+
static constexpr u32 MAX_TEXTURE_SLOTS = 16;
private:
+ GfxDevice& device_;
+
BlendMode blend_mode_ = BlendMode::Normal;
bool blend_enabled_ = true;
diff --git a/src/esengine/renderer/TextureSlotAllocator.hpp b/src/esengine/renderer/TextureSlotAllocator.hpp
index 58bebe4cc..10d78a504 100644
--- a/src/esengine/renderer/TextureSlotAllocator.hpp
+++ b/src/esengine/renderer/TextureSlotAllocator.hpp
@@ -1,15 +1,7 @@
#pragma once
#include "../core/Types.hpp"
-
-#ifdef ES_PLATFORM_WEB
- #include <GLES3/gl3.h>
-#else
- #ifdef _WIN32
- #include <windows.h>
- #endif
- #include <glad/glad.h>
-#endif
+#include "GfxDevice.hpp"
#include <array>
@@ -50,10 +42,9 @@ public:
return slot_count_ >= MaxSlots;
}
- void bindAll() const {
- for (u32 i = 0; i < MaxSlots; ++i) {
- glActiveTexture(GL_TEXTURE0 + i);
- glBindTexture(GL_TEXTURE_2D, slots_[i]);
+ void bindAll(GfxDevice& device) const {
+ for (u32 i = 0; i < slot_count_; ++i) {
+ device.bindTexture(i, slots_[i]);
}
}
diff --git a/src/esengine/renderer/TransientBufferPool.cpp b/src/esengine/renderer/TransientBufferPool.cpp
index de733709a..5e36d82d5 100644
--- a/src/esengine/renderer/TransientBufferPool.cpp
+++ b/src/esengine/renderer/TransientBufferPool.cpp
@@ -1,20 +1,16 @@
#include "TransientBufferPool.hpp"
+#include "OpenGLHeaders.hpp"
#include "../core/Log.hpp"
-#ifdef ES_PLATFORM_WEB
- #include <GLES3/gl3.h>
-#else
- #ifdef _WIN32
- #include <windows.h>
- #endif
- #include <glad/glad.h>
-#endif
-
#include <cstring>
#include <algorithm>
namespace esengine {
+TransientBufferPool::TransientBufferPool(GfxDevice& device)
+ : device_(device) {
+}
+
void TransientBufferPool::init(u32 initialVertexBytes, u32 initialIndexCount) {
if (initialized_) return;
@@ -23,19 +19,19 @@ void TransientBufferPool::init(u32 initialVertexBytes, u32 initialIndexCount) {
vbo_capacity_ = initialVertexBytes;
ebo_capacity_ = initialIndexCount;
- glGenBuffers(1, &vbo_);
- glGenBuffers(1, &ebo_);
+ vbo_ = device_.createBuffer();
+ ebo_ = device_.createBuffer();
- glBindBuffer(GL_ARRAY_BUFFER, vbo_);
- glBufferData(GL_ARRAY_BUFFER, vbo_capacity_, nullptr, GL_DYNAMIC_DRAW);
- glBindBuffer(GL_ARRAY_BUFFER, 0);
+ device_.bindVertexBuffer(vbo_);
+ device_.bufferData(GL_ARRAY_BUFFER, nullptr, vbo_capacity_, true);
+ device_.bindVertexBuffer(0);
- glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo_);
- glBufferData(GL_ELEMENT_ARRAY_BUFFER, ebo_capacity_ * sizeof(u16), nullptr, GL_DYNAMIC_DRAW);
- glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
+ device_.bindIndexBuffer(ebo_);
+ device_.bufferData(GL_ELEMENT_ARRAY_BUFFER, nullptr, ebo_capacity_ * sizeof(u16), true);
+ device_.bindIndexBuffer(0);
- for (u32 i = 0; i < LAYOUT_COUNT; ++i) {
- setupLayoutVAO(static_cast<LayoutId>(i));
+ for (auto layout : {LayoutId::Batch, LayoutId::Shape, LayoutId::MatSprite}) {
+ setupLayoutVAO(layout);
}
vertex_write_pos_ = 0;
@@ -48,12 +44,12 @@ void TransientBufferPool::shutdown() {
for (u32 i = 0; i < LAYOUT_COUNT; ++i) {
if (vaos_[i]) {
- glDeleteVertexArrays(1, &vaos_[i]);
+ device_.deleteVertexArray(vaos_[i]);
vaos_[i] = 0;
}
}
- if (vbo_) { glDeleteBuffers(1, &vbo_); vbo_ = 0; }
- if (ebo_) { glDeleteBuffers(1, &ebo_); ebo_ = 0; }
+ if (vbo_) { device_.deleteBuffer(vbo_); vbo_ = 0; }
+ if (ebo_) { device_.deleteBuffer(ebo_); ebo_ = 0; }
vertex_staging_.clear();
index_staging_.clear();
@@ -108,79 +104,77 @@ u32 TransientBufferPool::appendIndices(const u16* data, u32 count) {
void TransientBufferPool::upload() {
if (vertex_write_pos_ == 0 && index_write_pos_ == 0) return;
- glBindBuffer(GL_ARRAY_BUFFER, vbo_);
+ device_.bindVertexBuffer(vbo_);
if (vertex_write_pos_ > vbo_capacity_) {
vbo_capacity_ = vertex_write_pos_;
- glBufferData(GL_ARRAY_BUFFER, vbo_capacity_, vertex_staging_.data(), GL_DYNAMIC_DRAW);
+ device_.bufferData(GL_ARRAY_BUFFER, vertex_staging_.data(), vbo_capacity_, true);
} else {
- glBufferSubData(GL_ARRAY_BUFFER, 0, vertex_write_pos_, vertex_staging_.data());
+ device_.bufferSubData(GL_ARRAY_BUFFER, 0, vertex_staging_.data(), vertex_write_pos_);
}
- glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo_);
+ device_.bindIndexBuffer(ebo_);
u32 eboBytes = index_write_pos_ * sizeof(u16);
u32 eboCapBytes = ebo_capacity_ * sizeof(u16);
if (eboBytes > eboCapBytes) {
ebo_capacity_ = index_write_pos_;
- glBufferData(GL_ELEMENT_ARRAY_BUFFER, ebo_capacity_ * sizeof(u16),
- index_staging_.data(), GL_DYNAMIC_DRAW);
+ device_.bufferData(GL_ELEMENT_ARRAY_BUFFER, index_staging_.data(),
+ ebo_capacity_ * sizeof(u16), true);
} else {
- glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, 0, eboBytes, index_staging_.data());
+ device_.bufferSubData(GL_ELEMENT_ARRAY_BUFFER, 0, index_staging_.data(), eboBytes);
}
}
void TransientBufferPool::bindLayout(LayoutId layout) {
u32 idx = static_cast<u32>(layout);
if (idx < LAYOUT_COUNT && vaos_[idx]) {
- glBindVertexArray(vaos_[idx]);
+ device_.bindVertexArray(vaos_[idx]);
}
}
void TransientBufferPool::setupLayoutVAO(LayoutId layout) {
u32 idx = static_cast<u32>(layout);
- glGenVertexArrays(1, &vaos_[idx]);
- glBindVertexArray(vaos_[idx]);
+ vaos_[idx] = device_.createVertexArray();
+ device_.bindVertexArray(vaos_[idx]);
- glBindBuffer(GL_ARRAY_BUFFER, vbo_);
- glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo_);
+ device_.bindVertexBuffer(vbo_);
+ device_.bindIndexBuffer(ebo_);
switch (layout) {
case LayoutId::Batch: {
constexpr u32 STRIDE = 20;
- glEnableVertexAttribArray(0);
- glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, STRIDE, reinterpret_cast<void*>(0));
- glEnableVertexAttribArray(1);
- glVertexAttribPointer(1, 4, GL_UNSIGNED_BYTE, GL_TRUE, STRIDE, reinterpret_cast<void*>(8));
- glEnableVertexAttribArray(2);
- glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, STRIDE, reinterpret_cast<void*>(12));
+ device_.enableVertexAttrib(0);
+ device_.vertexAttribPointer(0, 2, GL_FLOAT, false, STRIDE, 0);
+ device_.enableVertexAttrib(1);
+ device_.vertexAttribPointer(1, 4, GL_UNSIGNED_BYTE, true, STRIDE, 8);
+ device_.enableVertexAttrib(2);
+ device_.vertexAttribPointer(2, 2, GL_FLOAT, false, STRIDE, 12);
break;
}
case LayoutId::Shape: {
- // ShapeVertex: vec2 pos + vec2 uv + vec4 color + vec4 shapeInfo = 48B
constexpr u32 STRIDE = 48;
- glEnableVertexAttribArray(0);
- glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, STRIDE, reinterpret_cast<void*>(0));
- glEnableVertexAttribArray(1);
- glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, STRIDE, reinterpret_cast<void*>(8));
- glEnableVertexAttribArray(2);
- glVertexAttribPointer(2, 4, GL_FLOAT, GL_FALSE, STRIDE, reinterpret_cast<void*>(16));
- glEnableVertexAttribArray(3);
- glVertexAttribPointer(3, 4, GL_FLOAT, GL_FALSE, STRIDE, reinterpret_cast<void*>(32));
+ device_.enableVertexAttrib(0);
+ device_.vertexAttribPointer(0, 2, GL_FLOAT, false, STRIDE, 0);
+ device_.enableVertexAttrib(1);
+ device_.vertexAttribPointer(1, 2, GL_FLOAT, false, STRIDE, 8);
+ device_.enableVertexAttrib(2);
+ device_.vertexAttribPointer(2, 4, GL_FLOAT, false, STRIDE, 16);
+ device_.enableVertexAttrib(3);
+ device_.vertexAttribPointer(3, 4, GL_FLOAT, false, STRIDE, 32);
break;
}
case LayoutId::MatSprite: {
- // MatSpriteVertex: vec2 pos + vec2 uv + vec4 color = 32B
constexpr u32 STRIDE = 32;
- glEnableVertexAttribArray(0);
- glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, STRIDE, reinterpret_cast<void*>(0));
- glEnableVertexAttribArray(1);
- glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, STRIDE, reinterpret_cast<void*>(8));
- glEnableVertexAttribArray(2);
- glVertexAttribPointer(2, 4, GL_FLOAT, GL_FALSE, STRIDE, reinterpret_cast<void*>(16));
+ device_.enableVertexAttrib(0);
+ device_.vertexAttribPointer(0, 2, GL_FLOAT, false, STRIDE, 0);
+ device_.enableVertexAttrib(1);
+ device_.vertexAttribPointer(1, 2, GL_FLOAT, false, STRIDE, 8);
+ device_.enableVertexAttrib(2);
+ device_.vertexAttribPointer(2, 4, GL_FLOAT, false, STRIDE, 16);
break;
}
}
- glBindVertexArray(0);
+ device_.bindVertexArray(0);
}
void TransientBufferPool::growVertexBuffer(u32 requiredBytes) {
diff --git a/src/esengine/renderer/TransientBufferPool.hpp b/src/esengine/renderer/TransientBufferPool.hpp
index 0f5939cbb..06b07a357 100644
--- a/src/esengine/renderer/TransientBufferPool.hpp
+++ b/src/esengine/renderer/TransientBufferPool.hpp
@@ -1,6 +1,7 @@
#pragma once
#include "../core/Types.hpp"
+#include "GfxDevice.hpp"
#include <vector>
#include <array>
@@ -17,6 +18,8 @@ static constexpr u32 LAYOUT_COUNT = 4;
class TransientBufferPool {
public:
+ explicit TransientBufferPool(GfxDevice& device);
+
void init(u32 initialVertexBytes = 2 * 1024 * 1024,
u32 initialIndexCount = 256 * 1024);
void shutdown();
@@ -47,6 +50,8 @@ private:
void growVertexBuffer(u32 requiredBytes);
void growIndexBuffer(u32 requiredCount);
+ GfxDevice& device_;
+
std::array<u32, LAYOUT_COUNT> vaos_{};
u32 vbo_ = 0;
u32 ebo_ = 0;
diff --git a/src/esengine/renderer/plugins/ShapePlugin.cpp b/src/esengine/renderer/plugins/ShapePlugin.cpp
index 7ef5591cd..1b00d290b 100644
--- a/src/esengine/renderer/plugins/ShapePlugin.cpp
+++ b/src/esengine/renderer/plugins/ShapePlugin.cpp
@@ -1,5 +1,6 @@
#include "ShapePlugin.hpp"
#include "../OpenGLHeaders.hpp"
+#include "../RenderCommand.hpp"
#include "../RenderContext.hpp"
#include "../RenderFrame.hpp"
#include "../Shader.hpp"
@@ -138,10 +139,10 @@ void ShapePlugin::customDraw(
buffers.bindLayout(LayoutId::Shape);
- glDrawElements(GL_TRIANGLES,
- static_cast<GLsizei>(cmd.index_count),
+ RenderCommand::getDevice()->drawElements(
+ cmd.index_count,
GL_UNSIGNED_SHORT,
- reinterpret_cast<const void*>(static_cast<uintptr_t>(cmd.index_offset * sizeof(u16))));
+ static_cast<u32>(cmd.index_offset * sizeof(u16)));
}
} // namespace esengine