SleakEngine 0.1.0
C++23 multi-backend game engine
Loading...
Searching...
No Matches
RenderCommandQueue.cpp
Go to the documentation of this file.
2
3#include <Core/Logger.hpp>
6#include <algorithm>
7
11
12namespace Sleak {
13 namespace RenderEngine {
14 RenderCommandQueue* RenderCommandQueue::Instance = nullptr;
15
16
18 List<RefPtr<BufferBase>> constantBuffers,
19 uint32_t vertexCount,
20 uint32_t startVertexLocation) {
21 CurrentArena().Create<DrawCommand>(
22 std::move(vertexBuffer), std::move(constantBuffers),
23 vertexCount, startVertexLocation);
24 }
25
27 RefPtr<BufferBase> vertexBuffer, RefPtr<BufferBase> indexBuffer,
28 List<RefPtr<BufferBase>> constantBuffers, uint32_t indexCount,
29 uint32_t startIndexLocation, int32_t baseVertexLocation,
30 bool castsShadow) {
31 auto* command = CurrentArena().Create<DrawIndexedCommand>(
32 std::move(vertexBuffer), std::move(indexBuffer),
33 std::move(constantBuffers), indexCount, startIndexLocation,
34 baseVertexLocation);
35 command->SetCastsShadow(castsShadow);
36 }
37
39 CurrentArena().Create<BindConstantBufferCommand>(std::move(buffer),
40 slot);
41 }
42
44 CurrentArena().Create<UpdateConstantBufferCommand>(
45 std::move(buffer), Data, Size);
46 }
47
49 CurrentArena().Create<BindMaterialCommand>(material);
50 }
51
53 CurrentArena().Create<SetRenderModeCommand>(mode);
54 }
55
57 CurrentArena().Create<SetRenderFaceCommand>(face);
58 }
59
61 CurrentArena().Create<CustomCommand>(std::move(function));
62 }
63
65
68
69 const auto& commands = CurrentArena().Commands();
70
71 // Cache draw commands for shadow pass replay next frame,
72 // pairing each with the last-bound slot-0 (transform) buffer.
73 cachedShadowDraws.clear();
74 {
75 const RefPtr<BufferBase>* lastSlot0Buffer = nullptr;
76 const RefPtr<BufferBase>* lastSlot3Buffer = nullptr;
77 for (RenderCommandBase* cmd : commands) {
78 auto type = cmd->GetType();
80 auto* bindCmd =
81 static_cast<BindConstantBufferCommand*>(cmd);
82 if (bindCmd->GetSlot() == 0) {
83 lastSlot0Buffer = &bindCmd->GetBuffer();
84 } else if (bindCmd->GetSlot() == 3) {
85 lastSlot3Buffer = &bindCmd->GetBuffer();
86 }
87 }
88 if ((type == CommandType::Draw ||
89 type == CommandType::DrawIndexed) &&
90 lastSlot0Buffer && *lastSlot0Buffer &&
91 cmd->CastsShadow()) {
92 ShadowDrawEntry entry;
93 entry.command = cmd;
94 entry.transformBuffer = lastSlot0Buffer;
95 // Pair bone buffer only with skinned draws so non-skinned
96 // casters don't accidentally inherit a stale bone UBO.
97 if (cmd->IsSkinned())
98 entry.boneBuffer = lastSlot3Buffer;
99 cachedShadowDraws.push_back(entry);
100 }
101 }
102 }
103
104 // ---- Deferred rendering path ----
105 // Split commands into:
106 // - Opaque group → geometry pass (writes to GBuffer)
107 // - Forward group → forward transparent pass (after lighting)
108 //
109 // State commands (UpdateCB, BindCB, SetMode, SetFace) are accumulated
110 // per-group and flushed together with the draw command they precede.
111 // CustomCommands (skybox, debug lines) always go to the forward group.
112 if (context->IsDeferredEnabled()) {
113
114 // Per-group accumulator: state commands preceding the current draw.
115 auto& pendingState = m_pendingState;
116 auto& forwardCmds = m_forwardCmds;
117 pendingState.clear();
118 forwardCmds.clear();
119
120 ::Sleak::Material* lastMaterial = nullptr;
121 bool lastMaterialForward = false;
122
123 auto isStateCmd = [](CommandType t) {
127 || t == CommandType::SetFace;
128 };
129
130 for (RenderCommandBase* cmd : commands) {
131 auto type = cmd->GetType();
132
133 if (type == CommandType::BindMaterial) {
134 auto* bmc = static_cast<BindMaterialCommand*>(cmd);
135 lastMaterial = bmc->GetMaterial();
136 lastMaterialForward = lastMaterial && lastMaterial->IsForwardRendered();
137 // Always add material bind to pending state
138 pendingState.push_back(cmd);
139 continue;
140 }
141
142 if (type == CommandType::CustomCommand) {
143 // Skybox, debug lines — always rendered after the lighting pass.
144 // Flush any pending state to forward group first so state is correct.
145 forwardCmds.insert(forwardCmds.end(),
146 pendingState.begin(),
147 pendingState.end());
148 pendingState.clear();
149 forwardCmds.push_back(cmd);
150 lastMaterial = nullptr;
151 lastMaterialForward = false;
152 continue;
153 }
154
155 if (isStateCmd(type)) {
156 pendingState.push_back(cmd);
157 continue;
158 }
159
160 if (type == CommandType::Draw || type == CommandType::DrawIndexed) {
161 // Skinned meshes have no GBuffer pipeline variant — the
162 // skinned pipeline is render-pass-compatible only with
163 // the forward pass, so route them there even when opaque.
164 const bool isSkinned = cmd->IsSkinned();
165 if (lastMaterialForward || isSkinned) {
166 // Transparent/forward/skinned draw — defer to forward pass
167 forwardCmds.insert(forwardCmds.end(),
168 pendingState.begin(),
169 pendingState.end());
170 forwardCmds.push_back(cmd);
171 } else {
172 // Opaque draw — execute now in geometry pass
173 for (auto& s : pendingState) s->Execute(context);
174 cmd->Execute(context);
175 }
176 pendingState.clear();
177 continue;
178 }
179
180 // Any other command type: execute immediately (opaque path)
181 cmd->Execute(context);
182 }
183
184 // Transition: geometry pass → lighting pass → forward transparent pass
186
188 for (RenderCommandBase* cmd : forwardCmds)
189 cmd->Execute(context);
190 context->EndForwardTransparentPass();
191
192 AdvanceArena();
193 return;
194 }
195
196 // ---- Forward rendering path (unchanged behavior) ----
197 for (RenderCommandBase* cmd : commands) cmd->Execute(context);
198 AdvanceArena();
199 }
200
202 for (const ShadowDrawEntry& entry : cachedShadowDraws) {
203 // Bind the transform buffer (slot 0) before drawing — shadow mode
204 // in VulkanRenderer::BindConstantBuffer computes LightVP * World
205 if (entry.transformBuffer && *entry.transformBuffer) {
206 context->BindConstantBuffer(*entry.transformBuffer, 0);
207 }
208 // Skinned casters need their bone matrices bound so the shadow
209 // depth vert can transform verts into the posed skeleton space.
210 if (entry.boneBuffer && *entry.boneBuffer) {
211 context->BindBoneBuffer(*entry.boneBuffer);
212 }
213 entry.command->ExecuteShadow(context);
214 }
215 }
216
218 // Commands are submitted in the correct per-object order:
219 // UpdateCB → BindCB → BindMaterial → Draw for each object,
220 // with custom commands (skybox, debug lines) at their correct position.
221 // Preserve submission order to maintain correct state bindings.
222 // Future optimization: batch by material while preserving per-object groups.
223 }
224
226 // Batching is a technique to call render commands as single pass instead pf multiple draw calls. This significantly improves rendering efficiency
227 // TODO: Implement this method
228 }
229
230 void RenderCommandQueue::Clear() { CurrentArena().Reset(); }
231
233 cachedShadowDraws.clear();
234 m_pendingState.clear();
235 m_forwardCmds.clear();
236 for (CommandArena& arena : m_arenas) arena.Reset();
237 m_currentArena = 0;
238 }
239
240 void RenderCommandQueue::AdvanceArena() {
241 m_pendingState.clear();
242 m_forwardCmds.clear();
243 m_currentArena = (m_currentArena + 1) % ARENA_COUNT;
244 CurrentArena().Reset();
245 }
246
247 void* RenderCommandQueue::CommandArena::Allocate(size_t size,
248 size_t alignment) {
249 for (;;) {
250 if (m_blockIndex < m_blocks.size()) {
251 Block& block = m_blocks[m_blockIndex];
252 const size_t start =
253 (m_offset + alignment - 1) & ~(alignment - 1);
254 if (start + size <= block.size) {
255 m_offset = start + size;
256 return block.data.get() + start;
257 }
258 ++m_blockIndex;
259 m_offset = 0;
260 continue;
261 }
262 const size_t blockSize = std::max(BLOCK_SIZE, size + alignment);
263 m_blocks.push_back(
264 {std::make_unique<std::byte[]>(blockSize), blockSize});
265 }
266 }
267
268 void RenderCommandQueue::CommandArena::Reset() {
269 for (RenderCommandBase* command : m_commands)
270 command->~RenderCommandBase();
271 m_commands.clear();
272 m_blockIndex = 0;
273 m_offset = 0;
274 }
275
277 if (Instance) {
278 Instance->ClearAll();
279 delete Instance;
280 Instance = nullptr;
281 }
282 }
283 }
284}
285
Implements a dynamic array-like list for storing and managing a collection of elements.
Definition List.hpp:21
bool IsForwardRendered() const
True when this material must skip the GBuffer and render in the forward transparent pass.
Definition Material.cpp:108
Binds a constant buffer to a pipeline slot.
Binds a material's shader and textures for subsequent draws.
Wraps an arbitrary callback as a queueable render command.
std::function< void(RenderContext *)> ExecuteFunction
Non-indexed draw command with its vertex and constant buffers.
Indexed draw command with its vertex, index, and constant buffers.
One recorded draw plus the state it needs to replay into a command list.
Frame-scoped queue of recorded draw/state commands, replayed into a RenderContext at flush time.
void Clear()
Drops queued commands for the current frame, keeping the cached shadow draw list.
void SubmitUpdateConstantBuffer(RefPtr< BufferBase > buffer, void *Data, uint16_t Size)
Queues a constant buffer write with data captured at submit time.
void SubmitCustomCommand(CustomCommand::ExecuteFunction function)
Queues an arbitrary callback to run inline with other render commands.
void ExecuteCommands(RenderContext *context)
void SubmitBindMaterial(::Sleak::Material *material)
Queues a material bind, switching shader/texture state for subsequent draws.
void ExecuteShadowPass(RenderContext *context)
void SubmitDrawIndexed(RefPtr< BufferBase > vertexBuffer, RefPtr< BufferBase > indexBuffer, List< RefPtr< BufferBase > > constantBuffers, uint32_t indexCount, uint32_t startIndexLocation=0, int32_t baseVertexLocation=0, bool castsShadow=true)
Queues an indexed draw with its vertex/index buffers and constant buffers.
void ClearAll()
Drops queued commands and the cached shadow draw list.
void SubmitDraw(RefPtr< BufferBase > vertexBuffer, List< RefPtr< BufferBase > > constantBuffers, uint32_t vertexCount, uint32_t startVertexLocation=0)
Queues a non-indexed draw with its vertex buffer and constant buffers.
void SubmitBindConstantBuffer(RefPtr< BufferBase > buffer, uint8_t slot)
Queues a constant buffer bind at the given slot.
Abstract interface for high-level graphics command execution and resource management.
virtual void BindBoneBuffer(RefPtr< BufferBase > buffer)
virtual void BindConstantBuffer(RefPtr< BufferBase > buffer, uint32_t slot=0)=0
Switches the rasterizer fill mode.
Constant buffer write, captured by value into inline storage or a heap fallback for larger payloads.
Backend-facing rendering layer shared by the four graphics backends.
CommandType
Discriminator for RenderCommandBase subclasses, used for sorting and batching.
RenderMode
Rasterizer fill style for a draw.
RenderFace
Which triangle winding gets culled.
Root namespace for everything the engine exposes.
Definition Camera.hpp:10
A draw command paired with the transform/bone buffers it needs to replay in the shadow pass.