Estella 0.113.0
A fast 2D and 3D game engine powered by WebAssembly and ECS
Loading...
Searching...
No Matches
ImmediateDraw.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
16
17#include "./ImmediateDraw.hpp"
18#include "../rhi/GfxDevice.hpp"
20#include "../rhi/Shader.hpp"
22#include "./BatchVertex.hpp"
25#include "../../core/Log.hpp"
26
27#include <glm/gtc/constants.hpp>
28#include <glm/gtc/type_ptr.hpp>
29#include <algorithm>
30#include <array>
31#include <cmath>
32#include <cstring>
33#include <string>
34
35namespace esengine {
36
37namespace {
38
39constexpr glm::vec2 QUAD_LOCAL[4] = {
40 {-0.5f, -0.5f}, {0.5f, -0.5f}, {0.5f, 0.5f}, {-0.5f, 0.5f}
41};
42constexpr glm::vec2 QUAD_UV[4] = {
43 {0.0f, 0.0f}, {1.0f, 0.0f}, {1.0f, 1.0f}, {0.0f, 1.0f}
44};
45
46constexpr f32 NEAR_CLIP_NUDGE = 1e-4f;
47
49constexpr u32 INITIAL_INSTANCE_RECORDS = 4096;
50
52bool clipLineToNearPlane(glm::vec3& from, glm::vec3& to, const glm::mat4& viewProjection) {
53 const auto side = [&viewProjection](const glm::vec3& point) {
54 const glm::vec4 clip = viewProjection * glm::vec4(point, 1.0f);
55 return clip.z + clip.w;
56 };
57 const f32 fromSide = side(from);
58 const f32 toSide = side(to);
59 if (!std::isfinite(fromSide) || !std::isfinite(toSide)) return false;
60 if (fromSide >= 0.0f && toSide >= 0.0f) return true;
61 if (fromSide < 0.0f && toSide < 0.0f) return false;
62
63 const f32 crossing = fromSide / (fromSide - toSide);
64 const f32 t = fromSide >= 0.0f
65 ? crossing * (1.0f - NEAR_CLIP_NUDGE)
66 : crossing + (1.0f - crossing) * NEAR_CLIP_NUDGE;
67 const glm::vec3 cut = glm::mix(from, to, t);
68 if (fromSide >= 0.0f) to = cut;
69 else from = cut;
70 return true;
71}
72
74bool screenOffsetPoint(const glm::mat4& inverseViewProjection,
75 const glm::vec4& clipAnchor,
76 const glm::vec2& offset,
77 f32 viewportWidth, f32 viewportHeight,
78 glm::vec3& point) {
79 const glm::vec4 clip = clipAnchor + glm::vec4(
80 2.0f * offset.x * clipAnchor.w / viewportWidth,
81 2.0f * offset.y * clipAnchor.w / viewportHeight,
82 0.0f, 0.0f);
83 const glm::vec4 world = inverseViewProjection * clip;
84 if (!std::isfinite(world.x) || !std::isfinite(world.y)
85 || !std::isfinite(world.z) || !std::isfinite(world.w)
86 || std::abs(world.w) < 1e-9f) {
87 return false;
88 }
89 point = glm::vec3(world) / world.w;
90 return std::isfinite(point.x) && std::isfinite(point.y) && std::isfinite(point.z);
91}
92
93} // namespace
94
96 resource::ResourceManager& resource_manager)
97 : device_(device)
98 , context_(context)
99 , resource_manager_(resource_manager)
100 , pool_(device) {
101}
102
104 if (initialized_) {
105 shutdown();
106 }
107}
108
110 if (initialized_) return;
111
112 pool_.init();
113 white_texture_id_ = context_.getWhiteTextureId();
114
115 // Reuses the batch shader's default variant — one .esshader, both languages.
116 const auto target = resource_manager_.preferredShaderTarget();
118 resource::ShaderHandle handle = resource_manager_.createShaderWithBindings(
121 {{0, "a_position"}, {1, "a_color"}, {2, "a_texCoord"}},
122 resource_manager_.preferredShaderLanguage());
123 batch_shader_ref_ = handle;
124 Shader* shader = resource_manager_.getShader(handle);
125 if (shader && shader->isValid()) {
126 batch_shader_ = shader->handle();
127 device_.useProgram(batch_shader_);
128 // Immediate draw is single-texture (slot 0), but bind all 8 samplers for parity
129 // with the world batch shader.
130 for (i32 i = 0; i < 8; ++i) {
131 i32 loc = device_.getUniformLocation(batch_shader_, ("u_textures[" + std::to_string(i) + "]").c_str());
132 if (loc >= 0) device_.setUniform1i(loc, i);
133 }
134 device_.useProgram(ShaderHandle::Invalid);
135
136 // The base pipeline: the batch shader, Batch layout, normal blend, depth
137 // test off (write on, matching the world batch path), no stencil, no culling.
138 // setBlendMode/setDepthTest swap in cached sibling pipelines per state.
139 base_desc_ = PipelineDesc{};
140 base_desc_.program = batch_shader_;
141 base_desc_.vertexLayout = pool_.layoutHandle(LayoutId::Batch);
142 base_desc_.blend = BlendMode::Normal;
143 base_desc_.blendEnabled = true;
144 base_desc_.depthTest = false;
145 base_desc_.depthWrite = true;
146 base_desc_.stencil = GfxStencilMode::Off;
147 base_desc_.cullEnabled = false;
148 current_desc_ = base_desc_;
149 pipeline_ = device_.createPipeline(current_desc_);
150 } else {
151 ES_LOG_ERROR("ImmediateDraw: failed to create batch shader");
152 }
153
154 initialized_ = true;
155}
156
158 if (!initialized_) return;
159 for (auto& mesh : meshes_) {
160 if (mesh.vbo != BufferHandle::Invalid) device_.deleteBuffer(mesh.vbo);
161 if (mesh.ebo != BufferHandle::Invalid) device_.deleteBuffer(mesh.ebo);
162 }
163 meshes_.clear();
164 freeMeshes_.clear();
165 doomedMeshes_.clear();
166 liveMeshes_ = 0;
167 if (instanceVbo_ != BufferHandle::Invalid) device_.deleteBuffer(instanceVbo_);
168 instanceVbo_ = BufferHandle::Invalid;
169 instanceCapacity_ = 0;
170 if (instanceLayout_ != VertexLayoutHandle::Invalid) device_.deleteVertexLayout(instanceLayout_);
171 instanceLayout_ = VertexLayoutHandle::Invalid;
172 instances_.clear();
173 instancesUploaded_ = 0;
174 pendingRun_ = {};
175 pool_.shutdown();
176 initialized_ = false;
177 ES_LOG_INFO("ImmediateDraw shutdown");
178}
179
180void ImmediateDraw::begin(const glm::mat4& viewProjection, i32 viewportWidth, i32 viewportHeight) {
181 if (!initialized_) return;
182
183 viewProjection_ = viewProjection;
184 viewportWidth_ = static_cast<f32>(std::max(viewportWidth, 1));
185 viewportHeight_ = static_cast<f32>(std::max(viewportHeight, 1));
186
187 // The batch shader reads u_projection from the shared FrameConstants UBO; update it
188 // for this pass rather than uploading a loose uniform per flush. A camera's, so it
189 // is converted for the device — Draw.line3D places geometry in the world.
190 context_.updateCameraConstants(viewProjection);
191 // A prior phase may have left another pipeline bound; force our pipeline to re-apply.
192 device_.invalidatePipelineCache();
193
194 // Near-centre to far-centre through the inverse: one direction that works for
195 // both projections, where a perspective camera's own position does not.
196 inverseViewProjection_ = glm::inverse(viewProjection);
197 const glm::vec4 nearPoint = inverseViewProjection_ * glm::vec4(0.0f, 0.0f, -1.0f, 1.0f);
198 const glm::vec4 farPoint = inverseViewProjection_ * glm::vec4(0.0f, 0.0f, 1.0f, 1.0f);
199 const glm::vec3 forward = glm::vec3(farPoint) / farPoint.w - glm::vec3(nearPoint) / nearPoint.w;
200 if (glm::length(forward) > 0.0001f) viewForward_ = glm::normalize(forward);
201
202 pool_.beginFrame();
203 deferredBatches_.clear();
204 recordedIndices_ = 0;
205 instances_.clear();
206 instancesUploaded_ = 0;
207 pendingRun_ = {};
208 // Last frame's draws are behind us: what was destroyed during it can go now.
209 for (const u32 id : doomedMeshes_) {
210 ResidentMesh& mesh = meshes_[id - 1];
211 if (mesh.vbo != BufferHandle::Invalid) device_.deleteBuffer(mesh.vbo);
212 if (mesh.ebo != BufferHandle::Invalid) device_.deleteBuffer(mesh.ebo);
213 mesh = {};
214 freeMeshes_.push_back(id);
215 }
216 doomedMeshes_.clear();
217 recording_ = false;
218 deferredGeometry_ = false;
219 currentTexture_ = white_texture_id_;
220 pendingGeometry_ = false;
221 primitiveCount_ = 0;
222 drawCallCount_ = 0;
223 inFrame_ = true;
224
225 // Each session starts from the base state; a prior session's blend/depth
226 // overrides do not leak across frames.
227 dither_ = false;
228 ditherPhase_ = false;
229 if (!(current_desc_ == base_desc_)) {
230 current_desc_ = base_desc_;
231 pipeline_ = device_.createPipeline(current_desc_);
232 }
233}
234
235u32 ImmediateDraw::appendBatch(const BatchVertex* vertices, usize count) {
236 if (!dither_) return pool_.appendVertices(LayoutId::Batch, vertices, static_cast<u32>(sizeof(BatchVertex) * count));
237 ditherScratch_.assign(vertices, vertices + count);
238 const i32 bits = BATCH_DITHER_BIT | (ditherPhase_ ? BATCH_DITHER_PHASE_BIT : 0);
239 for (BatchVertex& v : ditherScratch_) v.texIndex = static_cast<f32>(static_cast<i32>(v.texIndex) | bits);
240 return pool_.appendVertices(LayoutId::Batch, ditherScratch_.data(), static_cast<u32>(sizeof(BatchVertex) * count));
241}
242
244 if (current_desc_.blend == mode) return;
245 if (pendingGeometry_ || pendingRun_.count) flush();
246 current_desc_.blend = mode;
247 pipeline_ = device_.createPipeline(current_desc_);
248}
249
250void ImmediateDraw::setDepthTest(bool enabled) {
251 setDepthState(enabled, current_desc_.depthWrite);
252}
253
254void ImmediateDraw::setDepthState(bool test, bool write) {
255 if (current_desc_.depthTest == test && current_desc_.depthWrite == write) return;
256 if (pendingGeometry_ || pendingRun_.count) flush();
257 current_desc_.depthTest = test;
258 current_desc_.depthWrite = write;
259 pipeline_ = device_.createPipeline(current_desc_);
260}
261
263 if (!initialized_ || !inFrame_) return;
264 if (pendingRun_.count) flushRun();
265 if (!pendingGeometry_) return;
266
267 if (recording_) {
268 const u32 end = pool_.indicesUsed(LayoutId::Batch);
269 deferredBatches_.push_back({pipeline_, currentTexture_, recordedIndices_, end - recordedIndices_});
270 recordedIndices_ = end;
271 pendingGeometry_ = false;
272 return;
273 }
274
275 pool_.upload();
276
277 device_.setPipeline(pipeline_);
278 device_.bindTexture(0, TextureHandle{currentTexture_});
279
280 pool_.bindLayout(LayoutId::Batch);
281 device_.drawElements(pool_.indicesUsed(LayoutId::Batch), GfxDataType::UnsignedInt, 0);
282 ++drawCallCount_;
283
284 pool_.beginFrame(); // reset staging for the next batch
285 pendingGeometry_ = false;
286}
287
289 if (!inFrame_) return;
290
291 if (recording_) {
292 deferEnd();
294 return;
295 }
296
297 flush();
298 // No state restore needed: the next render phase invalidates the pipeline cache and
299 // binds its own pipeline, which sets blend/depth/stencil afresh.
300 inFrame_ = false;
301}
302
304 if (!inFrame_) return;
305 if (recording_) flush();
306 deferredGeometry_ = pendingGeometry_ || pendingRun_.count || !deferredBatches_.empty();
307 recording_ = false;
308 inFrame_ = false;
309}
310
314
316 if (!deferredGeometry_) return;
317 if (!deferredBatches_.empty()) {
318 pool_.upload();
319 uploadInstances();
320 device_.invalidatePipelineCache();
321 for (const auto& batch : deferredBatches_) {
322 if (batch.mesh != 0) {
323 PipelineHandle pipeline = batch.pipeline;
324 if (program != ShaderHandle::Invalid) {
325 if (const PipelineDesc* desc = device_.pipelineDesc(pipeline)) pipeline = instancedPipeline(*desc, true);
326 }
327 drawRun(pipeline, batch.mesh, batch.firstInstance, batch.instanceCount);
328 continue;
329 }
330 PipelineHandle pipeline = batch.pipeline;
331 if (program != ShaderHandle::Invalid) {
332 if (const PipelineDesc* desc = device_.pipelineDesc(pipeline)) {
333 PipelineDesc display = *desc;
334 display.program = program;
335 pipeline = device_.createPipeline(display);
336 }
337 }
338 device_.setPipeline(pipeline);
339 device_.bindTexture(0, TextureHandle{batch.texture});
340 pool_.bindLayout(LayoutId::Batch);
341 device_.drawElements(batch.indexCount, GfxDataType::UnsignedInt, batch.firstIndex * sizeof(u32));
342 ++drawCallCount_;
343 }
344 deferredBatches_.clear();
345 pool_.beginFrame();
346 instances_.clear();
347 instancesUploaded_ = 0;
348 deferredGeometry_ = false;
349 return;
350 }
351 inFrame_ = true;
352 flush();
353 inFrame_ = false;
354 deferredGeometry_ = false;
355}
356
357void ImmediateDraw::useTexture(u32 textureId) {
358 // Every batch primitive comes through here: a run of copies before it is drawn first, so the order holds.
359 if (pendingRun_.count) flush();
360 if (textureId != currentTexture_) {
361 if (pendingGeometry_) flush();
362 currentTexture_ = textureId;
363 }
364}
365
366void ImmediateDraw::emitQuad(const glm::vec2& center, const glm::vec2& size, f32 rotation,
367 const glm::vec4& color, u32 textureId,
368 const glm::vec2& uvOffset, const glm::vec2& uvScale) {
369 useTexture(textureId);
370
371 const u32 packed = packColor(color);
372 const f32 cosR = rotation != 0.0f ? std::cos(rotation) : 1.0f;
373 const f32 sinR = rotation != 0.0f ? std::sin(rotation) : 0.0f;
374
375 std::array<BatchVertex, 4> verts{};
376 for (u32 i = 0; i < 4; ++i) {
377 glm::vec2 scaled = QUAD_LOCAL[i] * size;
378 glm::vec2 rotated = rotation != 0.0f
379 ? glm::vec2(scaled.x * cosR - scaled.y * sinR, scaled.x * sinR + scaled.y * cosR)
380 : scaled;
381 // Immediate geometry bypasses the sort key and draws with the depth test
382 // off, so it has no depth of its own to carry — it lands on the z=0 plane.
383 verts[i].position = glm::vec3(center + rotated, 0.0f);
384 verts[i].color = packed;
385 verts[i].texCoord = QUAD_UV[i] * uvScale + uvOffset;
386 }
387
388 u32 base = appendBatch(verts.data(), verts.size()) / sizeof(BatchVertex);
389 u32 idx[6] = { base + 0, base + 1, base + 2, base + 2, base + 3, base + 0 };
390 pool_.appendIndices(LayoutId::Batch, idx, 6);
391 pendingGeometry_ = true;
392}
393
394void ImmediateDraw::emitTriangle(const glm::vec2& p0, const glm::vec2& p1, const glm::vec2& p2,
395 const glm::vec4& color) {
396 useTexture(white_texture_id_);
397
398 const u32 packed = packColor(color);
399 std::array<BatchVertex, 3> verts{
400 BatchVertex{ {p0, 0.0f}, packed, {0.0f, 0.0f} },
401 BatchVertex{ {p1, 0.0f}, packed, {1.0f, 0.0f} },
402 BatchVertex{ {p2, 0.0f}, packed, {1.0f, 1.0f} },
403 };
404
405 u32 base = appendBatch(verts.data(), verts.size()) / sizeof(BatchVertex);
406 u32 idx[3] = { base + 0, base + 1, base + 2 };
407 pool_.appendIndices(LayoutId::Batch, idx, 3);
408 pendingGeometry_ = true;
409}
410
411void ImmediateDraw::line(const glm::vec2& from, const glm::vec2& to,
412 const glm::vec4& color, f32 thickness) {
413 if (!inFrame_) return;
414
415 glm::vec2 delta = to - from;
416 f32 length = glm::length(delta);
417 if (length < 0.0001f) return;
418
419 glm::vec2 dir = delta / length;
420 glm::vec2 center = (from + to) * 0.5f;
421 f32 angle = std::atan2(dir.y, dir.x);
422
423 emitQuad(center, glm::vec2(length, thickness), angle, color, white_texture_id_);
424 ++primitiveCount_;
425}
426
427void ImmediateDraw::line3D(const glm::vec3& from, const glm::vec3& to,
428 const glm::vec4& color, f32 thickness) {
429 if (!inFrame_) return;
430
431 glm::vec3 clippedFrom = from;
432 glm::vec3 clippedTo = to;
433 if (!clipLineToNearPlane(clippedFrom, clippedTo, viewProjection_)) return;
434
435 const glm::vec3 delta = clippedTo - clippedFrom;
436 const f32 length = glm::length(delta);
437 if (length < 0.0001f) return;
438 const glm::vec3 dir = delta / length;
439
440 glm::vec3 side = glm::cross(dir, viewForward_);
441 f32 sideLength = glm::length(side);
442 if (sideLength < 0.0001f) {
443 // Looking straight down the line: any perpendicular reads the same.
444 side = glm::cross(dir, std::abs(dir.y) < 0.9f ? glm::vec3(0.0f, 1.0f, 0.0f)
445 : glm::vec3(1.0f, 0.0f, 0.0f));
446 sideLength = glm::length(side);
447 if (sideLength < 0.0001f) return;
448 }
449 side *= (thickness * 0.5f) / sideLength;
450
451 useTexture(white_texture_id_);
452 const u32 packed = packColor(color);
453 const std::array<BatchVertex, 4> verts{
454 BatchVertex{ clippedFrom - side, packed, {0.0f, 0.0f} },
455 BatchVertex{ clippedFrom + side, packed, {1.0f, 0.0f} },
456 BatchVertex{ clippedTo + side, packed, {1.0f, 1.0f} },
457 BatchVertex{ clippedTo - side, packed, {0.0f, 1.0f} },
458 };
459 const u32 base =
460 appendBatch(verts.data(), verts.size()) / sizeof(BatchVertex);
461 const u32 idx[6] = { base + 0, base + 1, base + 2, base + 2, base + 3, base + 0 };
462 pool_.appendIndices(LayoutId::Batch, idx, 6);
463 pendingGeometry_ = true;
464 ++primitiveCount_;
465}
466
467void ImmediateDraw::line3DScreen(const glm::vec3& from, const glm::vec3& to,
468 const glm::vec4& color, f32 thickness) {
469 if (!inFrame_ || !(thickness > 0.0f)) return;
470
471 glm::vec3 clippedFrom = from;
472 glm::vec3 clippedTo = to;
473 if (!clipLineToNearPlane(clippedFrom, clippedTo, viewProjection_)) return;
474
475 const glm::vec4 clipFrom = viewProjection_ * glm::vec4(clippedFrom, 1.0f);
476 const glm::vec4 clipTo = viewProjection_ * glm::vec4(clippedTo, 1.0f);
477 if (std::abs(clipFrom.w) < 1e-9f || std::abs(clipTo.w) < 1e-9f) return;
478 const glm::vec2 ndcFrom = glm::vec2(clipFrom) / clipFrom.w;
479 const glm::vec2 ndcTo = glm::vec2(clipTo) / clipTo.w;
480 const glm::vec2 pixelDelta{
481 (ndcTo.x - ndcFrom.x) * viewportWidth_,
482 (ndcTo.y - ndcFrom.y) * viewportHeight_,
483 };
484 const f32 pixelLength = glm::length(pixelDelta);
485 if (!(pixelLength > 1e-6f) || !std::isfinite(pixelLength)) return;
486 const glm::vec2 normal{-pixelDelta.y / pixelLength, pixelDelta.x / pixelLength};
487 const glm::vec2 ndcOffset{
488 normal.x * thickness / viewportWidth_,
489 normal.y * thickness / viewportHeight_,
490 };
491
492 const auto unproject = [this](const glm::vec4& clip, glm::vec3& point) {
493 const glm::vec4 world = inverseViewProjection_ * clip;
494 if (!std::isfinite(world.x) || !std::isfinite(world.y) ||
495 !std::isfinite(world.z) || !std::isfinite(world.w) ||
496 std::abs(world.w) < 1e-9f) {
497 return false;
498 }
499 point = glm::vec3(world) / world.w;
500 return std::isfinite(point.x) && std::isfinite(point.y) && std::isfinite(point.z);
501 };
502 const glm::vec4 fromOffset{ndcOffset * clipFrom.w, 0.0f, 0.0f};
503 const glm::vec4 toOffset{ndcOffset * clipTo.w, 0.0f, 0.0f};
504 std::array<glm::vec3, 4> points;
505 if (!unproject(clipFrom - fromOffset, points[0]) ||
506 !unproject(clipFrom + fromOffset, points[1]) ||
507 !unproject(clipTo + toOffset, points[2]) ||
508 !unproject(clipTo - toOffset, points[3])) {
509 return;
510 }
511 const u32 packed = packColor(color);
512 const std::array<BatchVertex, 4> verts{
513 BatchVertex{ points[0], packed, {0.0f, 0.0f} },
514 BatchVertex{ points[1], packed, {1.0f, 0.0f} },
515 BatchVertex{ points[2], packed, {1.0f, 1.0f} },
516 BatchVertex{ points[3], packed, {0.0f, 1.0f} },
517 };
518
519 useTexture(white_texture_id_);
520 const u32 base =
521 appendBatch(verts.data(), verts.size()) / sizeof(BatchVertex);
522 const u32 idx[6] = { base + 0, base + 1, base + 2, base + 2, base + 3, base + 0 };
523 pool_.appendIndices(LayoutId::Batch, idx, 6);
524 pendingGeometry_ = true;
525 ++primitiveCount_;
526}
527
528void ImmediateDraw::line3DScreenOffset(const glm::vec3& anchor,
529 const glm::vec2& fromOffset,
530 const glm::vec2& toOffset,
531 const glm::vec4& color, f32 thickness) {
532 if (!inFrame_ || !(thickness > 0.0f)) return;
533
534 const glm::vec4 clipAnchor = viewProjection_ * glm::vec4(anchor, 1.0f);
535 if (!std::isfinite(clipAnchor.x) || !std::isfinite(clipAnchor.y)
536 || !std::isfinite(clipAnchor.z) || !std::isfinite(clipAnchor.w)
537 || std::abs(clipAnchor.w) < 1e-9f || clipAnchor.z + clipAnchor.w < 0.0f) {
538 return;
539 }
540
541 glm::vec3 from;
542 glm::vec3 to;
543 if (!screenOffsetPoint(inverseViewProjection_, clipAnchor, fromOffset,
544 viewportWidth_, viewportHeight_, from)
545 || !screenOffsetPoint(inverseViewProjection_, clipAnchor, toOffset,
546 viewportWidth_, viewportHeight_, to)) return;
547 line3DScreen(from, to, color, thickness);
548}
549
550void ImmediateDraw::polyline(std::span<const glm::vec2> vertices,
551 const glm::vec4& color, f32 thickness, bool closed) {
552 if (!inFrame_ || vertices.size() < 2) return;
553
554 for (size_t i = 0; i < vertices.size() - 1; ++i) {
555 line(vertices[i], vertices[i + 1], color, thickness);
556 }
557 if (closed && vertices.size() > 2) {
558 line(vertices.back(), vertices.front(), color, thickness);
559 }
560}
561
562void ImmediateDraw::rect(const glm::vec2& position, const glm::vec2& size,
563 const glm::vec4& color, bool filled) {
564 if (!inFrame_) return;
565
566 if (filled) {
567 emitQuad(position, size, 0.0f, color, white_texture_id_);
568 ++primitiveCount_;
569 } else {
570 rectOutline(position, size, color, 1.0f);
571 }
572}
573
574void ImmediateDraw::rectOutline(const glm::vec2& position, const glm::vec2& size,
575 const glm::vec4& color, f32 thickness) {
576 if (!inFrame_) return;
577
578 f32 halfW = size.x * 0.5f;
579 f32 halfH = size.y * 0.5f;
580
581 glm::vec2 tl(position.x - halfW, position.y + halfH);
582 glm::vec2 tr(position.x + halfW, position.y + halfH);
583 glm::vec2 br(position.x + halfW, position.y - halfH);
584 glm::vec2 bl(position.x - halfW, position.y - halfH);
585
586 line(tl, tr, color, thickness);
587 line(tr, br, color, thickness);
588 line(br, bl, color, thickness);
589 line(bl, tl, color, thickness);
590}
591
592void ImmediateDraw::circle(const glm::vec2& center, f32 radius,
593 const glm::vec4& color, bool filled, i32 segments) {
594 if (!inFrame_ || segments < 3) return;
595
596 if (filled) {
597 for (i32 i = 0; i < segments; ++i) {
598 f32 a1 = static_cast<f32>(i) / static_cast<f32>(segments) * glm::two_pi<f32>();
599 f32 a2 = static_cast<f32>(i + 1) / static_cast<f32>(segments) * glm::two_pi<f32>();
600 glm::vec2 p1 = center + glm::vec2(std::cos(a1), std::sin(a1)) * radius;
601 glm::vec2 p2 = center + glm::vec2(std::cos(a2), std::sin(a2)) * radius;
602 emitTriangle(center, p1, p2, color);
603 ++primitiveCount_;
604 }
605 } else {
606 circleOutline(center, radius, color, 1.0f, segments);
607 }
608}
609
610void ImmediateDraw::circleOutline(const glm::vec2& center, f32 radius,
611 const glm::vec4& color, f32 thickness, i32 segments) {
612 if (!inFrame_ || segments < 3) return;
613
614 for (i32 i = 0; i < segments; ++i) {
615 f32 a1 = static_cast<f32>(i) / static_cast<f32>(segments) * glm::two_pi<f32>();
616 f32 a2 = static_cast<f32>(i + 1) / static_cast<f32>(segments) * glm::two_pi<f32>();
617 glm::vec2 p1 = center + glm::vec2(std::cos(a1), std::sin(a1)) * radius;
618 glm::vec2 p2 = center + glm::vec2(std::cos(a2), std::sin(a2)) * radius;
619 line(p1, p2, color, thickness);
620 }
621}
622
623void ImmediateDraw::polygon(std::span<const glm::vec2> vertices, const glm::vec4& color) {
624 if (!inFrame_ || vertices.size() < 3) return;
625
626 for (size_t i = 1; i + 1 < vertices.size(); ++i) {
627 emitTriangle(vertices[0], vertices[i], vertices[i + 1], color);
628 ++primitiveCount_;
629 }
630}
631
632void ImmediateDraw::triangles(const f32* positions, u32 vertexCount, const f32* colors, const u32* indices, u32 indexCount,
633 const glm::vec4& tint, const f32 xform[6]) {
634 if (!inFrame_ || !positions || !indices || vertexCount == 0 || indexCount < 3) return;
635 const u32 used = indexCount - indexCount % 3;
636 // Checked before anything is written: an index past the vertices would read whatever the batch holds there.
637 for (u32 i = 0; i < used; ++i) {
638 if (indices[i] >= vertexCount) return;
639 }
640 useTexture(white_texture_id_);
641
642 triangleVertices_.resize(vertexCount);
643 for (u32 v = 0; v < vertexCount; ++v) {
644 const f32 x = positions[v * 2], y = positions[v * 2 + 1];
645 const glm::vec4 colour = colors
646 ? glm::vec4(colors[v * 4], colors[v * 4 + 1], colors[v * 4 + 2], colors[v * 4 + 3]) * tint
647 : tint;
648 triangleVertices_[v] = BatchVertex{
649 {xform[0] * x + xform[2] * y + xform[4], xform[1] * x + xform[3] * y + xform[5], 0.0f},
650 packColor(colour),
651 {0.0f, 0.0f},
652 };
653 }
654 const u32 base = appendBatch(triangleVertices_.data(), vertexCount) / sizeof(BatchVertex);
655 triangleIndices_.resize(used);
656 for (u32 i = 0; i < used; ++i) triangleIndices_[i] = base + indices[i];
657 pool_.appendIndices(LayoutId::Batch, triangleIndices_.data(), used);
658 pendingGeometry_ = true;
659 primitiveCount_ += used / 3;
660}
661
662u32 ImmediateDraw::createShape(const f32* positions, u32 vertexCount, const f32* colors, const u32* indices, u32 indexCount) {
663 if (!initialized_ || !positions || !indices || vertexCount == 0 || indexCount < 3) return 0;
664 const u32 used = indexCount - indexCount % 3;
665 for (u32 i = 0; i < used; ++i) {
666 if (indices[i] >= vertexCount) return 0;
667 }
668 std::vector<BatchVertex> vertices(vertexCount);
669 for (u32 v = 0; v < vertexCount; ++v) {
670 const u32 colour = colors
671 ? packColor(colors[v * 4], colors[v * 4 + 1], colors[v * 4 + 2], colors[v * 4 + 3])
672 : 0xFFFFFFFFu;
673 vertices[v] = BatchVertex{{positions[v * 2], positions[v * 2 + 1], 0.0f}, colour, {0.0f, 0.0f}};
674 }
675 ResidentMesh mesh;
676 mesh.vbo = device_.createBuffer({GfxBufferUsage::Vertex, static_cast<u32>(sizeof(BatchVertex) * vertexCount), false},
677 GfxContent::retained(), vertices.data());
678 mesh.ebo = device_.createBuffer({GfxBufferUsage::Index, static_cast<u32>(sizeof(u32) * used), false},
679 GfxContent::retained(), indices);
680 if (mesh.vbo == BufferHandle::Invalid || mesh.ebo == BufferHandle::Invalid) {
681 if (mesh.vbo != BufferHandle::Invalid) device_.deleteBuffer(mesh.vbo);
682 if (mesh.ebo != BufferHandle::Invalid) device_.deleteBuffer(mesh.ebo);
683 return 0;
684 }
685 mesh.indexCount = used;
686 mesh.live = true;
687 u32 id;
688 if (!freeMeshes_.empty()) {
689 id = freeMeshes_.back();
690 freeMeshes_.pop_back();
691 meshes_[id - 1] = mesh;
692 } else {
693 meshes_.push_back(mesh);
694 id = static_cast<u32>(meshes_.size());
695 }
696 ++liveMeshes_;
697 return id;
698}
699
701 if (id == 0 || id > meshes_.size() || !meshes_[id - 1].live) return;
702 meshes_[id - 1].live = false;
703 --liveMeshes_;
704 doomedMeshes_.push_back(id);
705}
706
707void ImmediateDraw::drawMesh(u32 id, const glm::vec4& tint, const f32 xform[6]) {
708 if (!inFrame_ || id == 0 || id > meshes_.size() || !meshes_[id - 1].live) return;
709 // What was drawn before keeps its place: the batch so far, or a run of another mesh, goes first.
710 if (pendingGeometry_ || (pendingRun_.count && pendingRun_.mesh != id)) flush();
711 if (pendingRun_.count == 0) pendingRun_ = {id, static_cast<u32>(instances_.size()), 0};
712 InstanceRecord record;
713 std::copy(xform, xform + 6, record.xform);
714 record.tint = packColor(tint);
715 instances_.push_back(record);
716 ++pendingRun_.count;
717 primitiveCount_ += meshes_[id - 1].indexCount / 3;
718}
719
720void ImmediateDraw::drawMeshMany(u32 id, const void* records, u32 count) {
721 if (!inFrame_ || !records || count == 0 || id == 0 || id > meshes_.size() || !meshes_[id - 1].live) return;
722 if (pendingGeometry_ || (pendingRun_.count && pendingRun_.mesh != id)) flush();
723 const usize first = instances_.size();
724 if (pendingRun_.count == 0) pendingRun_ = {id, static_cast<u32>(first), 0};
725 instances_.resize(first + count);
726 std::memcpy(instances_.data() + first, records, sizeof(InstanceRecord) * count);
727 pendingRun_.count += count;
728 primitiveCount_ += (meshes_[id - 1].indexCount / 3) * count;
729}
730
731void ImmediateDraw::flushRun() {
732 const Run run = pendingRun_;
733 pendingRun_ = {};
734 if (run.count == 0) return;
735 const PipelineHandle pipeline = instancedPipeline(current_desc_, false);
736 if (pipeline == PipelineHandle::Invalid) return;
737 if (recording_) {
738 deferredBatches_.push_back({pipeline, white_texture_id_, 0, 0, run.mesh, run.first, run.count});
739 return;
740 }
741 uploadInstances();
742 drawRun(pipeline, run.mesh, run.first, run.count);
743}
744
745void ImmediateDraw::uploadInstances() {
746 const u32 used = static_cast<u32>(instances_.size());
747 if (used == instancesUploaded_) return;
748 constexpr u32 stride = sizeof(InstanceRecord);
749 if (used > instanceCapacity_) {
750 // Doubling, as the batch stream grows; the whole frame goes up again, since the store is made anew.
751 instanceCapacity_ = std::max({used, instanceCapacity_ * 2, INITIAL_INSTANCE_RECORDS});
752 if (instanceVbo_ == BufferHandle::Invalid) {
753 instanceVbo_ = device_.createBuffer({GfxBufferUsage::Vertex, instanceCapacity_ * stride, true},
754 GfxContent::transient(), nullptr);
755 } else {
756 device_.resizeBuffer(instanceVbo_, instanceCapacity_ * stride, nullptr);
757 }
758 instancesUploaded_ = 0;
759 }
760 // Only what is new, at its own offset: a run already drawn keeps reading the records it was drawn with.
761 device_.updateBuffer(instanceVbo_, instancesUploaded_ * stride, instances_.data() + instancesUploaded_,
762 (used - instancesUploaded_) * stride);
763 instancesUploaded_ = used;
764}
765
766void ImmediateDraw::drawRun(PipelineHandle pipeline, u32 id, u32 first, u32 count) {
767 if (pipeline == PipelineHandle::Invalid || id == 0 || id > meshes_.size() || instanceVbo_ == BufferHandle::Invalid) return;
768 const ResidentMesh& mesh = meshes_[id - 1];
769 if (mesh.vbo == BufferHandle::Invalid) return;
770 device_.setPipeline(pipeline);
771 device_.bindTexture(0, TextureHandle{white_texture_id_});
772 device_.setVertexBuffer(0, mesh.vbo, 0);
773 // GLES3 has no baseInstance: the run's first record is where the instance stream is bound from.
774 device_.setVertexBuffer(1, instanceVbo_, first * static_cast<u32>(sizeof(InstanceRecord)));
775 device_.setIndexBuffer(mesh.ebo);
776 device_.drawElementsInstanced(mesh.indexCount, GfxDataType::UnsignedInt, 0, count);
777 ++drawCallCount_;
778}
779
780resource::ShaderHandle ImmediateDraw::compileVariant(const std::vector<std::string>& features) {
781 const auto target = resource_manager_.preferredShaderTarget();
783 resource::ShaderHandle handle = resource_manager_.createShaderWithBindings(
786 {{0, "a_position"}, {1, "a_color"}, {2, "a_texCoord"}},
787 resource_manager_.preferredShaderLanguage());
788 Shader* shader = resource_manager_.getShader(handle);
789 if (!shader || !shader->isValid()) {
790 ES_LOG_ERROR("ImmediateDraw: failed to create the instanced batch shader");
791 return {};
792 }
793 if (shader->language() == GfxShaderLanguage::GLSL_ES300) shader->whenLinked([](Shader& s) {
794 s.bind();
795 for (i32 i = 0; i < 8; ++i) s.setUniform("u_textures[" + std::to_string(i) + "]", i);
796 s.unbind();
797 });
798 return handle;
799}
800
801PipelineHandle ImmediateDraw::instancedPipeline(const PipelineDesc& state, bool display) {
802 // A colour-space flip changes what the variants assemble to: compile them again for the new one.
803 const bool linear = resource::ShaderParser::linearColorSpace();
804 if (linear != instancedLinear_) {
805 instancedLinear_ = linear;
806 instancedCompiled_ = instancedDisplayCompiled_ = false;
807 }
808 if (!instancedCompiled_) {
809 instancedCompiled_ = true;
810 instancedShader_ = compileVariant({"INSTANCED"});
811 }
812 if (display && !instancedDisplayCompiled_) {
813 instancedDisplayCompiled_ = true;
814 instancedDisplayShader_ = compileVariant({"INSTANCED", "DISPLAY_OUTPUT"});
815 }
816 Shader* shader = resource_manager_.getShader(display ? instancedDisplayShader_ : instancedShader_);
817 if (!shader || !shader->isValid()) return PipelineHandle::Invalid;
818 if (instanceLayout_ == VertexLayoutHandle::Invalid) {
819 // Slot 0: the mesh's own BatchVertex vertices, read as the batch stream's are. Slot 1: one record a copy.
820 VertexLayoutDesc desc;
821 desc.attributeCount = 8;
822 desc.strides[0] = sizeof(BatchVertex);
823 desc.strides[1] = sizeof(InstanceRecord);
824 desc.instanceStep[1] = true;
825 desc.attributes[0] = {0, 3, GfxDataType::Float, false, 0, 0};
826 desc.attributes[1] = {1, 4, GfxDataType::UnsignedByte, true, 12, 0};
827 desc.attributes[2] = {2, 2, GfxDataType::Float, false, 16, 0};
828 desc.attributes[3] = {3, 1, GfxDataType::Float, false, 24, 0};
829 desc.attributes[4] = {4, 1, GfxDataType::Float, false, 28, 0};
830 desc.attributes[5] = {5, 4, GfxDataType::Float, false, 0, 1};
831 desc.attributes[6] = {6, 2, GfxDataType::Float, false, 16, 1};
832 desc.attributes[7] = {7, 4, GfxDataType::UnsignedByte, true, 24, 1};
833 instanceLayout_ = device_.createVertexLayout(desc);
834 }
835 PipelineDesc desc = state;
836 desc.program = shader->handle();
837 desc.vertexLayout = instanceLayout_;
838 return device_.createPipeline(desc);
839}
840
841void ImmediateDraw::texture(const glm::vec2& position, const glm::vec2& size,
842 u32 textureId, const glm::vec4& tint) {
843 if (!inFrame_) return;
844 emitQuad(position, size, 0.0f, tint, textureId);
845 ++primitiveCount_;
846}
847
848void ImmediateDraw::textureRotated(const glm::vec2& position, const glm::vec2& size,
849 f32 rotation, u32 textureId, const glm::vec4& tint) {
850 if (!inFrame_) return;
851 emitQuad(position, size, rotation, tint, textureId);
852 ++primitiveCount_;
853}
854
855} // namespace esengine
Abstract graphics device interface.
Immediate mode 2D drawing API.
Logging utilities for ESEngine.
#define ES_LOG_ERROR(...)
Logs an error message.
Definition Log.hpp:296
#define ES_LOG_INFO(...)
Logs an info message.
Definition Log.hpp:292
Rendering context containing all renderer state.
Central resource management system.
Parser for unified .esshader file format.
GPU shader program abstraction.
static constexpr GfxContent transient()
static constexpr GfxContent retained()
Abstract graphics device interface.
Definition GfxDevice.hpp:75
void polygon(std::span< const glm::vec2 > vertices, const glm::vec4 &color)
void line3DScreenOffset(const glm::vec3 &anchor, const glm::vec2 &fromOffset, const glm::vec2 &toOffset, const glm::vec4 &color, f32 thickness=1.0f)
A framebuffer-sized line attached to one world-space anchor.
void rect(const glm::vec2 &position, const glm::vec2 &size, const glm::vec4 &color, bool filled=true)
void drawMeshMany(u32 id, const void *records, u32 count)
count copies of a mesh in one call: drawMesh for each, without a call a copy.
void line3D(const glm::vec3 &from, const glm::vec3 &to, const glm::vec4 &color, f32 thickness=1.0f)
A line between two points in SPACE, widened across the view.
void drawMesh(u32 id, const glm::vec4 &tint, const f32 xform[6])
void texture(const glm::vec2 &position, const glm::vec2 &size, u32 textureId, const glm::vec4 &tint=glm::vec4(1.0f))
void setDepthState(bool test, bool write)
ImmediateDraw(GfxDevice &device, RenderContext &context, resource::ResourceManager &resource_manager)
Constructs an immediate draw instance.
void circleOutline(const glm::vec2 &center, f32 radius, const glm::vec4 &color, f32 thickness=1.0f, i32 segments=32)
const glm::mat4 & viewProjection() const
void setDepthTest(bool enabled)
void end()
Ends the frame and submits all draw commands.
u32 createShape(const f32 *positions, u32 vertexCount, const f32 *colors, const u32 *indices, u32 indexCount)
Puts a shape on the GPU once, for drawMesh to draw any number of times without sending its vertices a...
void begin(const glm::mat4 &viewProjection, i32 viewportWidth=0, i32 viewportHeight=0)
Begins a new draw frame.
void triangles(const f32 *positions, u32 vertexCount, const f32 *colors, const u32 *indices, u32 indexCount, const glm::vec4 &tint, const f32 xform[6])
Triangles with a colour at every vertex, in one call: a shape tessellated once and drawn as often as ...
void setBlendMode(BlendMode mode)
void rectOutline(const glm::vec2 &position, const glm::vec2 &size, const glm::vec4 &color, f32 thickness=1.0f)
void line(const glm::vec2 &from, const glm::vec2 &to, const glm::vec4 &color, f32 thickness=1.0f)
void flush()
Flushes pending draw commands without ending the frame.
void textureRotated(const glm::vec2 &position, const glm::vec2 &size, f32 rotation, u32 textureId, const glm::vec4 &tint=glm::vec4(1.0f))
void polyline(std::span< const glm::vec2 > vertices, const glm::vec4 &color, f32 thickness=1.0f, bool closed=false)
void line3DScreen(const glm::vec3 &from, const glm::vec3 &to, const glm::vec4 &color, f32 thickness=1.0f)
void circle(const glm::vec2 &center, f32 radius, const glm::vec4 &color, bool filled=true, i32 segments=32)
GPU shader program for rendering.
Definition Shader.hpp:86
bool isValid() const
Checks if the shader compiled and linked successfully.
Definition Shader.hpp:251
ShaderHandle handle() const
Gets the device program handle.
Definition Shader.hpp:254
u32 appendVertices(LayoutId layout, const void *data, u32 byteSize)
Central manager for GPU resources.
static ParsedShader parse(const std::string &source)
Parses shader source into structured format (no include support).
static std::string assembleStage(const ParsedShader &parsed, ShaderStage stage, const std::string &platform="", const std::vector< std::string > &features={}, ShaderTargetLanguage target=ShaderTargetLanguage::GLSL_ES300)
Assembles final GLSL source for a specific stage.
constexpr const char * BATCH
std::span< const EsCmd > run(SystemFn fn, std::span< const std::uint32_t > fallback, std::span< const QuerySpec > queries, std::span< void *const > resources, CallArena &arena, WorldStamp world={})
Definition AotHost.hpp:181
Handle< esengine::Shader > ShaderHandle
Handle to a shader resource.
Definition Handle.hpp:214
std::int32_t i32
Signed 32-bit integer.
Definition Types.hpp:54
@ Off
No stencil test; full color write.
std::size_t usize
Size type for indexing and sizes.
Definition Types.hpp:64
constexpr i32 BATCH_DITHER_BIT
constexpr i32 BATCH_DITHER_PHASE_BIT
PipelineHandle
Opaque handle to a cached pipeline; PipelineHandle{0} is the null/invalid handle.
u32 packColor(f32 r, f32 g, f32 b, f32 a)
std::uint32_t u32
Unsigned 32-bit integer.
Definition Types.hpp:45
BlendMode
Predefined blend modes for rendering.
Definition BlendMode.hpp:22
float f32
32-bit floating point
Definition Types.hpp:59
One vertex of the shared batch stream.
Immutable description of a draw pipeline. Equality keys the pipeline cache, so two draws with the sam...