Estella 0.113.0
A fast 2D and 3D game engine powered by WebAssembly and ECS
Loading...
Searching...
No Matches
GLDevice.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
13
14#include "./GLDevice.hpp"
15#include "./OpenGLHeaders.hpp"
16#include "./GlslLoopFloor.hpp"
17#include "../../core/Log.hpp"
19
20#ifdef __EMSCRIPTEN__
21#include <emscripten/html5.h>
22#include <webgl/webgl1_ext.h>
23#include <webgl/webgl2.h> // glGetBufferSubData: a readback's bytes out of its pixel-pack buffer
24#endif
25
26#include <chrono>
27#include <cstdlib>
28#include <cstring>
29
30#ifndef GL_DEPTH_STENCIL
31 #define GL_DEPTH_STENCIL 0x84F9
32#endif
33#ifndef GL_NUM_EXTENSIONS
34 #define GL_NUM_EXTENSIONS 0x821D
35#endif
36// Compressed-texture internal formats. ETC2/EAC is core in GLES3/WebGL2; ASTC and
37// S3TC are extension tokens that may be absent from the core gl3.h, so fall back to
38// the literal enum values.
39#ifndef GL_COMPRESSED_RGB8_ETC2
40 #define GL_COMPRESSED_RGB8_ETC2 0x9274
41#endif
42#ifndef GL_COMPRESSED_RGBA8_ETC2_EAC
43 #define GL_COMPRESSED_RGBA8_ETC2_EAC 0x9278
44#endif
45#ifndef GL_COMPRESSED_RGBA_ASTC_4x4_KHR
46 #define GL_COMPRESSED_RGBA_ASTC_4x4_KHR 0x93B0
47#endif
48#ifndef GL_COMPRESSED_RGBA_ASTC_8x8_KHR
49 #define GL_COMPRESSED_RGBA_ASTC_8x8_KHR 0x93B7
50#endif
51#ifndef GL_COMPRESSED_RGBA_S3TC_DXT1_EXT
52 #define GL_COMPRESSED_RGBA_S3TC_DXT1_EXT 0x83F1
53#endif
54#ifndef GL_COMPRESSED_RGBA_S3TC_DXT5_EXT
55 #define GL_COMPRESSED_RGBA_S3TC_DXT5_EXT 0x83F3
56#endif
57#ifndef GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC
58 #define GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC 0x9279
59#endif
60#ifndef GL_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR
61 #define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR 0x93D0
62#endif
63#ifndef GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT
64 #define GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT 0x8C4F
65#endif
66#ifndef GL_SRGB8_ALPHA8
67 #define GL_SRGB8_ALPHA8 0x8C43
68#endif
69#ifndef GL_RGBA16F
70 #define GL_RGBA16F 0x881A
71#endif
72#ifndef GL_RGBA32F
73 #define GL_RGBA32F 0x8814
74#endif
75#ifndef GL_HALF_FLOAT
76 #define GL_HALF_FLOAT 0x140B
77#endif
78#ifndef GL_UNSIGNED_INT_24_8
79 #define GL_UNSIGNED_INT_24_8 0x84FA
80#endif
81#ifndef GL_DEPTH_STENCIL_ATTACHMENT
82 #define GL_DEPTH_STENCIL_ATTACHMENT 0x821A
83#endif
84#ifndef GL_UNPACK_FLIP_Y_WEBGL
85 #define GL_UNPACK_FLIP_Y_WEBGL 0x9240
86#endif
87// EXT_disjoint_timer_query_webgl2 enums — not guaranteed in <GLES3/gl3.h>.
88#ifndef GL_TIME_ELAPSED_EXT
89 #define GL_TIME_ELAPSED_EXT 0x88BF
90#endif
91#ifndef GL_GPU_DISJOINT_EXT
92 #define GL_GPU_DISJOINT_EXT 0x8FBB
93#endif
94
95namespace esengine {
96
97// =============================================================================
98// Helper Conversions
99// =============================================================================
100
101namespace {
102
103GLenum toGLFilter(TextureFilter filter) {
104 switch (filter) {
105 case TextureFilter::Nearest: return GL_NEAREST;
106 case TextureFilter::Linear: return GL_LINEAR;
107 default: return GL_LINEAR;
108 }
109}
110
112GLenum toGLMinFilter(const TextureDesc& desc) {
113 if (!desc.mipmaps) return toGLFilter(desc.minFilter);
114 return desc.minFilter == TextureFilter::Nearest ? GL_NEAREST_MIPMAP_NEAREST : GL_LINEAR_MIPMAP_LINEAR;
115}
116
117GLenum toGLWrap(TextureWrap wrap) {
118 switch (wrap) {
119 case TextureWrap::Repeat: return GL_REPEAT;
120 case TextureWrap::ClampToEdge: return GL_CLAMP_TO_EDGE;
121 case TextureWrap::MirroredRepeat: return GL_MIRRORED_REPEAT;
122 default: return GL_REPEAT;
123 }
124}
125
126void setCapability(GLenum cap, bool enabled) {
127 if (enabled) {
128 glEnable(cap);
129 } else {
130 glDisable(cap);
131 }
132}
133
134GLenum toGLBufferTarget(GfxBufferUsage usage) {
135 switch (usage) {
136 case GfxBufferUsage::Vertex: return GL_ARRAY_BUFFER;
137 case GfxBufferUsage::Index: return GL_ELEMENT_ARRAY_BUFFER;
138 case GfxBufferUsage::Uniform: return GL_UNIFORM_BUFFER;
139 default: return GL_ARRAY_BUFFER;
140 }
141}
142
143GLenum toGLDataType(GfxDataType type) {
144 switch (type) {
145 case GfxDataType::Float: return GL_FLOAT;
146 case GfxDataType::Int: return GL_INT;
147 case GfxDataType::UnsignedByte: return GL_UNSIGNED_BYTE;
148 case GfxDataType::UnsignedShort: return GL_UNSIGNED_SHORT;
149 case GfxDataType::UnsignedInt: return GL_UNSIGNED_INT;
150 default: return GL_FLOAT;
151 }
152}
153
154GLenum toGLStencilFunc(GfxStencilFunc func) {
155 switch (func) {
156 case GfxStencilFunc::Never: return GL_NEVER;
157 case GfxStencilFunc::Less: return GL_LESS;
158 case GfxStencilFunc::Equal: return GL_EQUAL;
159 case GfxStencilFunc::LEqual: return GL_LEQUAL;
160 case GfxStencilFunc::Greater: return GL_GREATER;
161 case GfxStencilFunc::NotEqual: return GL_NOTEQUAL;
162 case GfxStencilFunc::GEqual: return GL_GEQUAL;
163 case GfxStencilFunc::Always: return GL_ALWAYS;
164 default: return GL_ALWAYS;
165 }
166}
167
168GLenum toGLStencilOp(GfxStencilOp op) {
169 switch (op) {
170 case GfxStencilOp::Keep: return GL_KEEP;
171 case GfxStencilOp::Zero: return GL_ZERO;
172 case GfxStencilOp::Replace: return GL_REPLACE;
173 case GfxStencilOp::Incr: return GL_INCR;
174 case GfxStencilOp::Decr: return GL_DECR;
175 case GfxStencilOp::Invert: return GL_INVERT;
178 default: return GL_KEEP;
179 }
180}
181
182struct GLPixelFormatInfo {
183 GLenum internalFormat;
184 GLenum format;
185 GLenum type;
186};
187
189bool isIntegerAttribute(GfxDataType type) {
191 || type == GfxDataType::UnsignedInt || type == GfxDataType::Int;
192}
193
194GLPixelFormatInfo toGLPixelFormat(GfxPixelFormat fmt) {
195 switch (fmt) {
196 case GfxPixelFormat::RGB8: return { GL_RGB8, GL_RGB, GL_UNSIGNED_BYTE };
197 case GfxPixelFormat::RGBA8: return { GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE };
198 case GfxPixelFormat::SRGB8_ALPHA8: return { GL_SRGB8_ALPHA8, GL_RGBA, GL_UNSIGNED_BYTE };
199 case GfxPixelFormat::RGBA16F: return { GL_RGBA16F, GL_RGBA, GL_HALF_FLOAT };
200 case GfxPixelFormat::RGBA32F: return { GL_RGBA32F, GL_RGBA, GL_FLOAT };
201 case GfxPixelFormat::DepthComponent24: return { GL_DEPTH_COMPONENT24, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT };
202 case GfxPixelFormat::Depth24Stencil8: return { GL_DEPTH24_STENCIL8, GL_DEPTH_STENCIL, GL_UNSIGNED_INT_24_8 };
203 default: return { GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE };
204 }
205}
206
210struct TightRowScope {
211 bool tightened;
212 TightRowScope(GfxPixelFormat fmt, u32 width)
213 : tightened((static_cast<u64>(width) * gfxBytesPerPixel(fmt)) % 4u != 0) {
214 if (tightened) glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
215 }
216 ~TightRowScope() { if (tightened) glPixelStorei(GL_UNPACK_ALIGNMENT, 4); }
217};
218
219GLenum toGLCompressedFormat(GfxCompressedFormat fmt) {
220 switch (fmt) {
230 default: return GL_COMPRESSED_RGBA8_ETC2_EAC;
231 }
232}
233
234// GLES3-correct extension probe (glGetString(GL_EXTENSIONS) returns null on a
235// core profile). Emscripten exposes WebGL extensions here under GL-style names.
236#ifdef __EMSCRIPTEN__
237// OES_draw_buffers_indexed is not in Emscripten's GL layer: the one call it is needed for goes to the context directly.
238EM_JS(void, es_gl_surface_blend, (int off), {
239 var ctx = GLctx;
240 var ext = ctx && (ctx.esIndexedBlend || (ctx.esIndexedBlend = ctx.getExtension('OES_draw_buffers_indexed')));
241 if (!ext) return;
242 if (off) { ext.disableiOES(ctx.BLEND, 1); ext.disableiOES(ctx.BLEND, 2); }
243 else { ext.enableiOES(ctx.BLEND, 1); ext.enableiOES(ctx.BLEND, 2); }
244});
245#endif
246
247bool glExtensionPresent(const char* name) {
248 GLint count = 0;
249 glGetIntegerv(GL_NUM_EXTENSIONS, &count);
250 for (GLint i = 0; i < count; ++i) {
251 const char* ext = reinterpret_cast<const char*>(glGetStringi(GL_EXTENSIONS, static_cast<GLuint>(i)));
252 if (ext && std::strcmp(ext, name) == 0) return true;
253 }
254 return false;
255}
256
262void setAnisotropy(const TextureDesc& desc, bool mipped, GLenum target = GL_TEXTURE_2D) {
263 static const GLfloat kMax = [] {
264 constexpr GLenum kMaxAnisotropy = 0x84FF; // GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT
265 if (!(glExtensionPresent("GL_EXT_texture_filter_anisotropic") || glExtensionPresent("EXT_texture_filter_anisotropic"))) return 1.0f;
266 GLfloat v = 1.0f;
267 glGetFloatv(kMaxAnisotropy, &v);
268 return v < 1.0f ? 1.0f : v;
269 }();
270 if (kMax <= 1.0f) return;
271 constexpr GLenum kTextureMaxAnisotropy = 0x84FE; // GL_TEXTURE_MAX_ANISOTROPY_EXT
272 const bool linear = desc.minFilter != TextureFilter::Nearest && desc.magFilter != TextureFilter::Nearest;
273 glTexParameterf(target, kTextureMaxAnisotropy, (mipped && linear) ? (kMax < 16.0f ? kMax : 16.0f) : 1.0f);
274}
275
276std::string readShaderInfoLog(GLuint shader) {
277 GLint logLength = 0;
278 glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &logLength);
279 if (logLength <= 0) return {};
280 std::string log(static_cast<size_t>(logLength), '\0');
281 glGetShaderInfoLog(shader, logLength, nullptr, log.data());
282 // Drop the trailing NUL glGetShaderInfoLog writes inside the buffer.
283 if (!log.empty() && log.back() == '\0') log.pop_back();
284 return log;
285}
286
287std::string readProgramInfoLog(GLuint program) {
288 GLint logLength = 0;
289 glGetProgramiv(program, GL_INFO_LOG_LENGTH, &logLength);
290 if (logLength <= 0) return {};
291 std::string log(static_cast<size_t>(logLength), '\0');
292 glGetProgramInfoLog(program, logLength, nullptr, log.data());
293 if (!log.empty() && log.back() == '\0') log.pop_back();
294 return log;
295}
296
297} // namespace
298
299// =============================================================================
300// Lifecycle
301// =============================================================================
302
303void GLDevice::resetDrawStateCaches() {
304 for (i8& state : cap_state_) state = -1;
305 depth_mask_ = -1;
306 color_mask_ = -1;
307 stencil_mask_ = -1;
308 uniform_bound_.clear();
309}
310
311void GLDevice::setCap(Cap cap, u32 glCap, bool enabled) {
312 const i8 want = enabled ? 1 : 0;
313 if (cap_state_[cap] == want) return;
314 cap_state_[cap] = want;
315 setCapability(static_cast<GLenum>(glCap), enabled);
316}
317
319 float_targets_ = -1;
320 framebuffer_complete_.clear();
321 glEnable(GL_DEPTH_TEST);
322 // GL's own default, stated because the second backend states it too: a rule
323 // one backend declares and the other inherits can drift with neither saying so.
324 glDepthFunc(GL_LESS);
325 glEnable(GL_BLEND);
326 glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
327 // Depth test and blend were just turned on, but a new context knows nothing the old one was told: nothing is assumed held.
328 resetDrawStateCaches();
330#ifdef __EMSCRIPTEN__
331 // Runs of mesh draws as one call: a scene's draws mostly differ by nothing but their geometry's range and their records,
332 // and each was a call of its own with a block bound for it. Before any program is assembled, which reads the same answer.
333 {
334 const EMSCRIPTEN_WEBGL_CONTEXT_HANDLE ctx = emscripten_webgl_get_current_context();
335 multi_draw_ = ctx != 0 && emscripten_webgl_enable_WEBGL_multi_draw(ctx);
336 glslMultiDraw() = multi_draw_;
337 }
338#endif
339 ES_LOG_DEBUG("GLDevice initialized");
340}
341
343 std::string vendor = getString(GfxStringName::Vendor);
344 std::string renderer = getString(GfxStringName::Renderer);
345#ifdef __EMSCRIPTEN__
346 // On the web GL_VENDOR/GL_RENDERER are MASKED — every Mac answers "WebKit
347 // WebGL", which names a browser, not a GPU. The real strings sit behind an
348 // extension that must be enabled before its enums resolve.
349 constexpr GLenum UNMASKED_VENDOR = 0x9245;
350 constexpr GLenum UNMASKED_RENDERER = 0x9246;
351 // A composing draw (water, glass) writes the surface record unblended while it blends its colour: see applySurfaceBlend.
352 indexed_blend_ = emscripten_webgl_enable_extension(emscripten_webgl_get_current_context(), "OES_draw_buffers_indexed") ? 1 : 0;
353 if (emscripten_webgl_enable_extension(emscripten_webgl_get_current_context(),
354 "WEBGL_debug_renderer_info")) {
355 const char* v = reinterpret_cast<const char*>(glGetString(UNMASKED_VENDOR));
356 const char* r = reinterpret_cast<const char*>(glGetString(UNMASKED_RENDERER));
357 // Kept only when the driver actually answered: a browser that refuses
358 // the extension leaves the masked pair, which is worse than nothing only
359 // if it is silently replaced by an empty string.
360 if (v && *v) vendor = v;
361 if (r && *r) renderer = r;
362 }
363#endif
364 loop_floor_ = renderer.find("Direct3D") != std::string::npos;
365 // Asked while the answer still exists: glGetString returns null on a lost
366 // context, so a report assembled after the loss would name no driver.
367 setDeviceIdentity("WebGL2", std::move(vendor), std::move(renderer),
369}
370
372#ifdef __EMSCRIPTEN__
373 // Only where the context is CONFIRMED gone: on a lost one these are silent
374 // no-ops that still free the host's wrapper — its tables are global, so a
375 // dead context otherwise leaks every id it minted. On a live one they delete.
376 const EMSCRIPTEN_WEBGL_CONTEXT_HANDLE ctx = emscripten_webgl_get_current_context();
377 if (ctx == 0 || !emscripten_is_webgl_context_lost(ctx)) return;
378
379 for (usize id = 0; id < buffer_names_.size(); ++id) {
380 GLuint name = buffer_names_[id];
381 if (name) glDeleteBuffers(1, &name);
382 }
383 for (usize id = 0; id < texture_names_.size(); ++id) {
384 GLuint name = texture_names_[id];
385 if (!name) continue;
386 if (isRenderbuffer(static_cast<u32>(id))) glDeleteRenderbuffers(1, &name);
387 else glDeleteTextures(1, &name);
388 }
389 for (usize id = 0; id < framebuffer_names_.size(); ++id) {
390 GLuint name = framebuffer_names_[id];
391 if (name) glDeleteFramebuffers(1, &name);
392 }
393 for (auto& [id, resolve] : framebuffer_resolve_) {
394 if (resolve.destFbo) glDeleteFramebuffers(1, &resolve.destFbo);
395 }
396 for (auto& [id, shaders] : pending_programs_) {
397 glDeleteShader(shaders.vertex);
398 glDeleteShader(shaders.fragment);
399 }
400 for (usize id = 0; id < program_names_.size(); ++id) {
401 if (program_names_[id]) glDeleteProgram(program_names_[id]);
402 }
403 for (usize id = 0; id < query_names_.size(); ++id) {
404 GLuint name = query_names_[id];
405 if (name) glDeleteQueries(1, &name);
406 }
407 for (auto& [id, cache] : vaos_) {
408 if (cache.vao) glDeleteVertexArrays(1, &cache.vao);
409 }
410#endif
411}
412
414#ifdef __EMSCRIPTEN__
415 // There is no device to build: the browser restores the context on the same
416 // handle, and until it does there is nothing to do but wait.
417 const EMSCRIPTEN_WEBGL_CONTEXT_HANDLE ctx = emscripten_webgl_get_current_context();
418 if (ctx == 0 || emscripten_is_webgl_context_lost(ctx)) return false;
419 // A restored context has no extension enabled, and the probes in init() read what is SUPPORTED: the float targets of an HDR
420 // frame would be judged renderable and every one of them come back incomplete. The hosts register the context with every
421 // extension enabled (enableExtensionsByDefault), so the restored one is given them all again first.
422 if (char* names = emscripten_webgl_get_supported_extensions()) {
423 for (char* name = names; *name;) {
424 char* end = name;
425 while (*end && *end != ' ') ++end;
426 const char next = *end;
427 *end = '\0';
428 if (end != name) emscripten_webgl_enable_extension(ctx, name);
429 name = next ? end + 1 : end;
430 }
431 free(names);
432 }
433 if (multi_draw_) multi_draw_ = emscripten_webgl_enable_WEBGL_multi_draw(ctx);
434#endif
435 // Every name belonged to the old context. The registry rebuilds each object
436 // behind its id; nothing here survives but the maps' shape.
437 buffer_names_.clear();
438 texture_names_.clear();
439 array_names_.clear();
440 volume_names_.clear();
441 program_names_.clear();
442 pending_programs_.clear();
443 failed_programs_.clear();
444 framebuffer_names_.clear();
445 query_names_.clear();
446 framebuffer_resolve_.clear();
447 vaos_.clear();
448 last_vao_ = nullptr;
449 readbacks_.clear();
450 max_samples_ = 0;
451 // A timer query in flight was begun on the old context, so the timings are
452 // disjoint; the extension itself is enabled per context and must be again.
453 timer_query_state_ = 0;
454 timer_disjoint_pending_ = true;
455
456 resetStateCache();
457 init();
458 return true;
459}
460
461void GLDevice::resetStateCache() {
462 sampler_units_.clear();
463 current_pipeline_id_ = 0;
464 current_stencil_mode_ = GfxStencilMode::Off;
465 current_program_name_ = 0;
466 current_blend_ = static_cast<BlendMode>(0xFF);
467 current_layout_ = 0;
468 active_texture_unit_ = 0;
469 for (u32 i = 0; i < kTextureSlots; ++i) bound_texture_[i] = 0;
470 for (u32 slot = 0; slot < MAX_VERTEX_BUFFER_SLOTS; ++slot) {
471 pending_vbo_[slot] = 0;
472 pending_vbo_offset_[slot] = 0;
473 }
474 pending_ibo_ = 0;
475 bound_vao_ = 0;
476 scissor_test_ = -1;
477 current_depth_bias_ = 0;
478 alpha_to_coverage_ = -1;
479 depth_equal_ = -1;
480 cull_front_ = -1;
481 surface_blend_off_ = false;
482 current_framebuffer_ = 0;
483 timer_query_state_ = 0;
484 resetDrawStateCaches();
485}
486
488 // Timer queries belong to the device; the frame timer only keeps their ids.
489 for (u32& query : query_names_) {
490 if (query) glDeleteQueries(1, &query);
491 query = 0;
492 }
493 query_names_.clear();
494 for (auto& entry : readbacks_) releaseReadback(entry.second, true);
495 readbacks_.clear();
496 ES_LOG_INFO("GLDevice shutdown");
497}
498
500 if (!isDeviceUsable()) return false;
501#ifdef __EMSCRIPTEN__
502 // Asked directly rather than waited for: a `webglcontextlost` listener
503 // attached after the loss never fires, and a renderer that missed the event
504 // would submit into a dead context forever.
505 //
506 // The handle has to be the CURRENT context, not 0. Zero is not "whichever
507 // context is bound" — it is no context, which reports itself lost, and every
508 // frame would then be thrown away as a loss that never happened.
509 const EMSCRIPTEN_WEBGL_CONTEXT_HANDLE ctx = emscripten_webgl_get_current_context();
510 if (ctx != 0 && emscripten_is_webgl_context_lost(ctx)) {
512 "WebGL reports the context is lost", "pollDeviceLost");
513 return true;
514 }
515#endif
516 return false;
517}
518
519bool GLDevice::isRenderbuffer(u32 textureId) const {
520 const TextureDesc* desc = textureDesc(TextureHandle{textureId});
521 return desc && desc->samples > 1;
522}
523
524// =============================================================================
525// Viewport & Clear
526// =============================================================================
527
529 viewport_ = {x, y, w, h};
530 glViewport(x, y, static_cast<GLsizei>(w), static_cast<GLsizei>(h));
531}
532
533void GLDevice::setClearColor(f32 r, f32 g, f32 b, f32 a) {
534 glClearColor(r, g, b, a);
535}
536
537void GLDevice::setClearStencil(i32 value) {
538 glClearStencil(value);
539}
540
541void GLDevice::clear(bool color, bool depth, bool stencil) {
542 GLbitfield mask = 0;
543 if (color) mask |= GL_COLOR_BUFFER_BIT;
544 if (depth) mask |= GL_DEPTH_BUFFER_BIT;
545 if (stencil) mask |= GL_STENCIL_BUFFER_BIT;
546 if (mask == 0) return;
547
548 // Load-op semantics, same as beginRenderPass: glClear honors write masks, so a
549 // restrictive mask left by the previous pipeline would silently veto the clear.
550 // Force the cleared attachments' masks open and drop the cached pipeline (the
551 // next setPipeline re-applies its own masks). The scissor rectangle is honored —
552 // the TS multi-camera flow clears per-camera regions through it.
553 if (color) setColorMask(true, true, true, true);
554 if (depth) setDepthWrite(true);
555 if (stencil) setStencilMask(0xFF);
556 glClear(mask);
558}
559
560// =============================================================================
561// Blend State
562// =============================================================================
563
564void GLDevice::setBlendEnabled(bool enabled) {
565 // Enable/Disable without an index sets every draw buffer: the surface record's own state is gone with it. So while that record's blending is
566 // off, asking for what the context holds still has to be made, and only the ask that changes nothing anywhere is skipped.
567 if (cap_state_[kCapBlend] == (enabled ? 1 : 0) && !surface_blend_off_) return;
568 setCapability(GL_BLEND, enabled);
569 cap_state_[kCapBlend] = enabled ? 1 : 0;
570 surface_blend_off_ = false;
571}
572
573void GLDevice::setBlendMode(BlendMode mode, bool layerAlpha) {
574 const bool addsOnly = layerAlpha && (mode == BlendMode::Additive || mode == BlendMode::PmaAdditive);
575 if (mode == current_blend_ && addsOnly == current_blend_adds_only_) return;
576 current_blend_ = mode;
577 current_blend_adds_only_ = addsOnly;
578 if (addsOnly) {
579 glBlendEquation(GL_FUNC_ADD);
580 glBlendFuncSeparate(mode == BlendMode::Additive ? GL_SRC_ALPHA : GL_ONE, GL_ONE, GL_ZERO, GL_ONE);
581 return;
582 }
583 switch (mode) {
585 glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
586 break;
588 glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE, GL_ONE, GL_ONE);
589 break;
591 glBlendFuncSeparate(GL_DST_COLOR, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
592 break;
594 glBlendFuncSeparate(GL_ONE, GL_ONE_MINUS_SRC_COLOR, GL_ONE, GL_ONE_MINUS_SRC_COLOR);
595 break;
597 glBlendFuncSeparate(GL_ONE, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
598 break;
600 glBlendFuncSeparate(GL_ONE, GL_ONE, GL_ONE, GL_ONE);
601 break;
603 glBlendEquation(GL_MAX);
604 glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE);
605 break;
607 glBlendEquation(GL_MIN);
608 glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE);
609 break;
611 glBlendFuncSeparate(GL_DST_COLOR, GL_SRC_COLOR, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
612 break;
613 case BlendMode::None:
614 // A pipeline asking for None disables GL_BLEND (PipelineDesc::blendEnabled),
615 // so this function is never sampled. Setting the default anyway keeps the
616 // cached state honest: current_blend_ is keyed on the mode, and a later
617 // pipeline that re-enables blending must not inherit whatever was left here.
618 glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
619 break;
620 }
621
622 if (mode != BlendMode::Lighten && mode != BlendMode::Darken) {
623 glBlendEquation(GL_FUNC_ADD);
624 }
625}
626
627// =============================================================================
628// Depth State
629// =============================================================================
630
631void GLDevice::setDepthTest(bool enabled) {
632 setCap(kCapDepthTest, GL_DEPTH_TEST, enabled);
633}
634
635void GLDevice::setDepthWrite(bool enabled) {
636 const i8 want = enabled ? 1 : 0;
637 if (depth_mask_ == want) return;
638 depth_mask_ = want;
639 glDepthMask(enabled ? GL_TRUE : GL_FALSE);
640}
641
642// =============================================================================
643// Stencil State
644// =============================================================================
645
646void GLDevice::setStencilTest(bool enabled) {
647 setCap(kCapStencilTest, GL_STENCIL_TEST, enabled);
648}
649
650void GLDevice::setStencilFunc(GfxStencilFunc func, i32 ref, u32 mask) {
651 glStencilFunc(toGLStencilFunc(func), ref, mask);
652}
653
654void GLDevice::setStencilOp(GfxStencilOp sfail, GfxStencilOp dpfail, GfxStencilOp dppass) {
655 glStencilOp(toGLStencilOp(sfail), toGLStencilOp(dpfail), toGLStencilOp(dppass));
656}
657
658void GLDevice::setStencilMask(u32 mask) {
659 if (stencil_mask_ == static_cast<i64>(mask)) return;
660 stencil_mask_ = static_cast<i64>(mask);
661 glStencilMask(mask);
662}
663
664void GLDevice::setColorMask(bool r, bool g, bool b, bool a) {
665 const i16 bits = static_cast<i16>((r ? 1 : 0) | (g ? 2 : 0) | (b ? 4 : 0) | (a ? 8 : 0));
666 if (color_mask_ == bits) return;
667 color_mask_ = bits;
668 glColorMask(r ? GL_TRUE : GL_FALSE, g ? GL_TRUE : GL_FALSE,
669 b ? GL_TRUE : GL_FALSE, a ? GL_TRUE : GL_FALSE);
670}
671
672// =============================================================================
673// Scissor State
674// =============================================================================
675
676void GLDevice::setScissorTest(bool enabled) {
677 const int want = enabled ? 1 : 0;
678 if (scissor_test_ == want) return; // DrawList toggles this every draw; most are no-ops
679 scissor_test_ = want;
680 setCapability(GL_SCISSOR_TEST, enabled);
681}
682
684 glScissor(x, y, w, h);
685}
686
687// =============================================================================
688// Culling
689// =============================================================================
690
691void GLDevice::setCulling(bool enabled) {
692 setCap(kCapCull, GL_CULL_FACE, enabled);
693}
694
695void GLDevice::setCullFace(bool front) {
696 // Set at every change of pipeline that culls, and nearly always to what it was: a GL call into the browser each time.
697 if (static_cast<i8>(front) == cull_front_) return;
698 glCullFace(front ? GL_FRONT : GL_BACK);
699 cull_front_ = static_cast<i8>(front);
700}
701
702// =============================================================================
703// Shader Program
704// =============================================================================
705
706namespace {
707
709constexpr double kSlowProgramMs = 40.0;
710
711double msSince(std::chrono::steady_clock::time_point start) {
712 return std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - start).count();
713}
714
716std::string describeProgram(const char* fragmentSrc, usize vertexBytes, usize fragmentBytes) {
717 std::string defines;
718 if (fragmentSrc) {
719 const char* p = fragmentSrc;
720 for (int lines = 0; *p && lines < 200 && defines.size() < 160; ++lines) {
721 const char* end = std::strchr(p, '\n');
722 const usize len = end ? static_cast<usize>(end - p) : std::strlen(p);
723 if (len > 8 && std::strncmp(p, "#define ", 8) == 0) {
724 std::string name(p + 8, len - 8);
725 const usize cut = name.find_first_of(" \r\t");
726 if (cut != std::string::npos) name.resize(cut);
727 if (!defines.empty()) defines += ',';
728 defines += name;
729 }
730 if (!end) break;
731 p = end + 1;
732 }
733 }
734 return "vs " + std::to_string(vertexBytes) + "B, fs " + std::to_string(fragmentBytes) + "B, defines [" + defines + "]";
735}
736
737} // namespace
738
740 const GfxAttribBinding* bindings, u32 bindingCount,
741 std::string* outLog, GfxShaderStage* outFailedStage) {
743 if (outLog) *outLog = "GLDevice compiles GLSL ES 300 only (got another language)";
744 if (outFailedStage) *outFailedStage = GfxShaderStage::Vertex;
745 ES_LOG_ERROR("GLDevice::createProgram: unsupported shader language");
746 return false;
747 }
748 const std::string flooredVertex = loop_floor_ ? gfx::floorConstantLoops(source.vertexSrc) : std::string();
749 const std::string flooredFragment = loop_floor_ ? gfx::floorConstantLoops(source.fragmentSrc) : std::string();
750 const char* vertexSrc = loop_floor_ ? flooredVertex.c_str() : source.vertexSrc;
751 const char* fragmentSrc = loop_floor_ ? flooredFragment.c_str() : source.fragmentSrc;
752 const auto createStart = std::chrono::steady_clock::now();
753 auto setFailure = [&](GfxShaderStage stage, std::string&& log) {
754 if (outLog) *outLog = std::move(log);
755 if (outFailedStage) *outFailedStage = stage;
756 };
757
758 // Deferred: compile and link are queued with no question asked in between, and the first thing that needs the program asks. A driver that
759 // compiles on its own threads (ANGLE does, once the page does not wait) then works on every program asked for in the meantime at once.
760 const bool defer = source.deferLink;
761 GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER);
762 glShaderSource(vertexShader, 1, &vertexSrc, nullptr);
763 glCompileShader(vertexShader);
764
765 GLint success = 0;
766 if (!defer) glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success);
767 if (!defer && !success) {
768 std::string log = readShaderInfoLog(vertexShader);
769 ES_LOG_ERROR("Vertex shader compilation failed: {}", log);
770 setFailure(GfxShaderStage::Vertex, std::move(log));
771 glDeleteShader(vertexShader);
772 return false;
773 }
774
775 GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
776 glShaderSource(fragmentShader, 1, &fragmentSrc, nullptr);
777 glCompileShader(fragmentShader);
778
779 if (!defer) glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &success);
780 if (!defer && !success) {
781 std::string log = readShaderInfoLog(fragmentShader);
782 ES_LOG_ERROR("Fragment shader compilation failed: {}", log);
783 setFailure(GfxShaderStage::Fragment, std::move(log));
784 glDeleteShader(vertexShader);
785 glDeleteShader(fragmentShader);
786 return false;
787 }
788
789 GLuint program = glCreateProgram();
790 glAttachShader(program, vertexShader);
791 glAttachShader(program, fragmentShader);
792
793 for (u32 i = 0; i < bindingCount; ++i) {
794 glBindAttribLocation(program, bindings[i].index, bindings[i].name);
795 }
796
797 glLinkProgram(program);
798
799 if (defer) {
800 pending_programs_[id] = PendingProgram{vertexShader, fragmentShader,
801 describeProgram(fragmentSrc, std::strlen(vertexSrc), std::strlen(fragmentSrc))};
802 if (outFailedStage) *outFailedStage = GfxShaderStage::None;
803 setName(program_names_, id, program);
804 return true;
805 }
806
807 glGetProgramiv(program, GL_LINK_STATUS, &success);
808 if (!success) {
809 std::string log = readProgramInfoLog(program);
810 ES_LOG_ERROR("Shader program linking failed: {}", log);
811 setFailure(GfxShaderStage::Link, std::move(log));
812 glDeleteShader(vertexShader);
813 glDeleteShader(fragmentShader);
814 glDeleteProgram(program);
815 return false;
816 }
817
818 glDeleteShader(vertexShader);
819 glDeleteShader(fragmentShader);
820
821 if (const double ms = msSince(createStart); ms >= kSlowProgramMs) {
822 ES_LOG_WARN("Slow shader program {} ({:.0f} ms, compiled in place): {}", id, ms,
823 describeProgram(fragmentSrc, std::strlen(vertexSrc), std::strlen(fragmentSrc)));
824 }
825
826 if (outFailedStage) *outFailedStage = GfxShaderStage::None;
827 setName(program_names_, id, program);
828 return true;
829}
830
831u32 GLDevice::programName(u32 id) {
832 if (!pending_programs_.empty() && pending_programs_.count(id)) backendFinishProgram(id);
833 return nameOf(program_names_, id);
834}
835
837 auto it = pending_programs_.find(id);
838 if (it == pending_programs_.end()) return nameOf(program_names_, id) != 0;
839 const PendingProgram shaders = it->second;
840 pending_programs_.erase(it);
841 const GLuint program = nameOf(program_names_, id);
842 GLint success = 0;
843 const auto waitStart = std::chrono::steady_clock::now();
844 glGetProgramiv(program, GL_LINK_STATUS, &success);
845 if (const double ms = msSince(waitStart); ms >= kSlowProgramMs) {
846 ES_LOG_WARN("Slow shader program {} ({:.0f} ms waited for at its first use): {}", id, ms, shaders.label);
847 }
848 if (!success) {
849 // Only now does anyone ask why: the stage that refused, then the link.
850 GLint vertexOk = 0, fragmentOk = 0;
851 glGetShaderiv(shaders.vertex, GL_COMPILE_STATUS, &vertexOk);
852 glGetShaderiv(shaders.fragment, GL_COMPILE_STATUS, &fragmentOk);
853 std::string why;
854 if (!vertexOk) why += "vertex: " + readShaderInfoLog(shaders.vertex) + " ";
855 if (!fragmentOk) why += "fragment: " + readShaderInfoLog(shaders.fragment) + " ";
856 why += readProgramInfoLog(program);
857 ES_LOG_ERROR("Deferred shader program {} failed to link: {}", id, why);
858 glDeleteShader(shaders.vertex);
859 glDeleteShader(shaders.fragment);
860 glDeleteProgram(program);
861 setName(program_names_, id, 0);
862 failed_programs_.insert(id);
863 return false;
864 }
865 glDeleteShader(shaders.vertex);
866 glDeleteShader(shaders.fragment);
868 return true;
869}
870
872 if (pending_programs_.empty()) return 0;
873 // Finishing erases from the map, so the ids are taken first.
874 std::vector<u32> ids;
875 ids.reserve(pending_programs_.size());
876 for (const auto& entry : pending_programs_) ids.push_back(entry.first);
877 u32 compiling = 0;
878 for (const u32 id : ids) {
879 if (!backendProgramReady(id) && !failed_programs_.count(id)) ++compiling;
880 }
881 return compiling;
882}
883
885 std::string out;
886 for (const auto& [id, shaders] : pending_programs_) {
887 if (failed_programs_.count(id)) continue;
888 out += std::to_string(id) + ' ' + shaders.label + '\n';
889 }
890 return out;
891}
892
894 if (failed_programs_.count(id)) return false;
895 if (!pending_programs_.count(id)) return true;
896#ifdef __EMSCRIPTEN__
897 if (completion_status_ == 0) {
898 const EMSCRIPTEN_WEBGL_CONTEXT_HANDLE ctx = emscripten_webgl_get_current_context();
899 completion_status_ = (ctx && emscripten_webgl_enable_extension(ctx, "KHR_parallel_shader_compile")) ? 1 : 2;
900 }
901 if (completion_status_ == 1) {
902 // The browser's answer to "is it done", which does not make the page wait for it.
903 constexpr GLenum kCompletionStatus = 0x91B1;
904 GLint done = 0;
905 glGetProgramiv(nameOf(program_names_, id), kCompletionStatus, &done);
906 if (!done) return false;
907 }
908#endif
909 // Done (or no way to tell, in which case the wait is the same one a draw would have made): finishing it now costs nothing.
910 return backendFinishProgram(id);
911}
912
914 const u32 name = nameOf(program_names_, id);
915 if (!name) return;
916 if (auto it = pending_programs_.find(id); it != pending_programs_.end()) {
917 glDeleteShader(it->second.vertex);
918 glDeleteShader(it->second.fragment);
919 pending_programs_.erase(it);
920 }
921 glDeleteProgram(name);
922 sampler_units_.erase(name);
923 if (current_program_name_ == name) current_program_name_ = 0;
924 setName(program_names_, id, 0);
925}
926
928 const u32 name = programName(id);
929 if (name == current_program_name_) return;
930 glUseProgram(name);
931 current_program_name_ = name;
932}
933
934i32 GLDevice::backendUniformLocation(u32 program, const char* name) {
935 const u32 glName = programName(program);
936 return glName ? glGetUniformLocation(glName, name) : -1;
937}
938
939i32 GLDevice::backendAttribLocation(u32 program, const char* name) {
940 const u32 glName = programName(program);
941 return glName ? glGetAttribLocation(glName, name) : -1;
942}
943
944void GLDevice::backendSetUniform(i32 location, const GfxUniformValue& value) {
945 if (location < 0) return;
946 switch (value.type) {
947 case GfxUniformValue::Type::Int: glUniform1i(location, value.i); break;
948 case GfxUniformValue::Type::Float: glUniform1f(location, value.f[0]); break;
949 case GfxUniformValue::Type::Vec2: glUniform2f(location, value.f[0], value.f[1]); break;
950 case GfxUniformValue::Type::Vec3: glUniform3f(location, value.f[0], value.f[1], value.f[2]); break;
952 glUniform4f(location, value.f[0], value.f[1], value.f[2], value.f[3]);
953 break;
954 case GfxUniformValue::Type::Mat3: glUniformMatrix3fv(location, 1, GL_FALSE, value.f); break;
955 case GfxUniformValue::Type::Mat4: glUniformMatrix4fv(location, 1, GL_FALSE, value.f); break;
956 case GfxUniformValue::Type::None: break;
957 }
958}
959
960namespace {
961
962bool isSamplerType(GLenum type) {
963 switch (type) {
964 case GL_SAMPLER_2D: case GL_SAMPLER_3D: case GL_SAMPLER_CUBE: case GL_SAMPLER_2D_SHADOW:
965 case GL_SAMPLER_2D_ARRAY: case GL_SAMPLER_2D_ARRAY_SHADOW: case GL_SAMPLER_CUBE_SHADOW:
966 case GL_INT_SAMPLER_2D: case GL_INT_SAMPLER_3D: case GL_INT_SAMPLER_CUBE: case GL_INT_SAMPLER_2D_ARRAY:
967 case GL_UNSIGNED_INT_SAMPLER_2D: case GL_UNSIGNED_INT_SAMPLER_3D: case GL_UNSIGNED_INT_SAMPLER_CUBE:
968 case GL_UNSIGNED_INT_SAMPLER_2D_ARRAY:
969 return true;
970 default:
971 return false;
972 }
973}
974
975} // namespace
976
978 const u32 program = current_program_name_;
979 if (program == 0) return 0xFFFFFFFFu;
980 if (const auto it = sampler_units_.find(program); it != sampler_units_.end()) return it->second;
981 // Read from the program as it stands, every element of a sampler array: the unit each active sampler was last set to,
982 // which is what a draw has to have bound there. Once a program, not once a draw.
983 u32 units = 0;
984 GLint count = 0;
985 glGetProgramiv(program, GL_ACTIVE_UNIFORMS, &count);
986 GLint maxNameLen = 0;
987 glGetProgramiv(program, GL_ACTIVE_UNIFORM_MAX_LENGTH, &maxNameLen);
988 std::string nameBuf(static_cast<size_t>(std::max(maxNameLen, 64)), '\0');
989 for (GLint i = 0; i < count; ++i) {
990 GLsizei nameLen = 0;
991 GLint size = 0;
992 GLenum type = 0;
993 glGetActiveUniform(program, static_cast<GLuint>(i), static_cast<GLsizei>(nameBuf.size()), &nameLen, &size, &type, nameBuf.data());
994 if (!isSamplerType(type)) continue;
995 std::string base(nameBuf.data(), static_cast<size_t>(nameLen));
996 if (const auto bracket = base.find('['); bracket != std::string::npos) base.erase(bracket);
997 for (GLint e = 0; e < std::max(size, 1); ++e) {
998 const std::string element = size > 1 ? base + "[" + std::to_string(e) + "]" : base;
999 const GLint location = glGetUniformLocation(program, element.c_str());
1000 if (location < 0) continue;
1001 GLint unit = 0;
1002 glGetUniformiv(program, location, &unit);
1003 if (unit >= 0 && unit < 32) units |= 1u << static_cast<u32>(unit);
1004 }
1005 }
1006 sampler_units_[program] = units;
1007 return units;
1008}
1009
1011 if (sampler_units_.empty()) return;
1012 const u32 name = nameOf(program_names_, program);
1013 if (name) sampler_units_.erase(name);
1014}
1015
1016namespace {
1017
1018GfxUniformType fromGLUniformType(GLenum type) {
1019 switch (type) {
1020 case GL_FLOAT: return GfxUniformType::Float;
1021 case GL_FLOAT_VEC2: return GfxUniformType::Vec2;
1022 case GL_FLOAT_VEC3: return GfxUniformType::Vec3;
1023 case GL_FLOAT_VEC4: return GfxUniformType::Vec4;
1024 case GL_INT: return GfxUniformType::Int;
1025 case GL_INT_VEC2: return GfxUniformType::IVec2;
1026 case GL_INT_VEC3: return GfxUniformType::IVec3;
1027 case GL_INT_VEC4: return GfxUniformType::IVec4;
1028 case GL_BOOL: return GfxUniformType::Bool;
1029 case GL_FLOAT_MAT2: return GfxUniformType::Mat2;
1030 case GL_FLOAT_MAT3: return GfxUniformType::Mat3;
1031 case GL_FLOAT_MAT4: return GfxUniformType::Mat4;
1032 case GL_SAMPLER_2D: return GfxUniformType::Sampler2D;
1033 case GL_SAMPLER_CUBE: return GfxUniformType::SamplerCube;
1034 case GL_SAMPLER_2D_ARRAY: return GfxUniformType::Sampler2DArray;
1035 default: return GfxUniformType::Unknown;
1036 }
1037}
1038
1039} // namespace
1040
1041std::vector<GfxUniformInfo> GLDevice::backendActiveUniforms(u32 program) {
1042 std::vector<GfxUniformInfo> result;
1043 const GLuint programId = programName(program);
1044 if (!programId) return result;
1045
1046 GLint count = 0;
1047 glGetProgramiv(programId, GL_ACTIVE_UNIFORMS, &count);
1048 if (count <= 0) return result;
1049
1050 GLint maxNameLen = 0;
1051 glGetProgramiv(programId, GL_ACTIVE_UNIFORM_MAX_LENGTH, &maxNameLen);
1052 if (maxNameLen <= 0) maxNameLen = 64;
1053
1054 std::string nameBuf(static_cast<size_t>(maxNameLen), '\0');
1055 result.reserve(static_cast<size_t>(count));
1056
1057 for (GLint i = 0; i < count; ++i) {
1058 GLsizei nameLen = 0;
1059 GLint size = 0;
1060 GLenum type = 0;
1061 glGetActiveUniform(programId, static_cast<GLuint>(i),
1062 static_cast<GLsizei>(maxNameLen), &nameLen,
1063 &size, &type, nameBuf.data());
1064
1065 std::string name(nameBuf.data(), static_cast<size_t>(nameLen));
1066 if (name == gfx::kLoopFloorUniform) continue;
1067 const auto bracket = name.find('[');
1068 if (bracket != std::string::npos) {
1069 name.erase(bracket);
1070 }
1071
1072 GfxUniformInfo info;
1073 info.name = std::move(name);
1074 info.type = fromGLUniformType(type);
1075 info.location = glGetUniformLocation(programId, info.name.c_str());
1076 info.arraySize = size > 0 ? static_cast<u32>(size) : 1u;
1077 result.push_back(std::move(info));
1078 }
1079
1080 return result;
1081}
1082
1083u32 GLDevice::backendUniformBlockIndex(u32 program, const char* name) {
1084 const u32 glName = programName(program);
1085 if (!glName) return GFX_INVALID_UNIFORM_BLOCK;
1086 return static_cast<u32>(glGetUniformBlockIndex(glName, name));
1087}
1088
1089void GLDevice::backendUniformBlockBinding(u32 program, u32 nativeBlockIndex, u32 bindingPoint) {
1090 const u32 glName = programName(program);
1091 if (glName) glUniformBlockBinding(glName, nativeBlockIndex, bindingPoint);
1092}
1093
1094// =============================================================================
1095// Buffer Operations
1096// =============================================================================
1097
1098void GLDevice::uploadBufferStore(u32 id, u32 offsetBytes, const void* data, u32 sizeBytes, bool respec) {
1099 const u32 name = nameOf(buffer_names_, id);
1100 const BufferDesc* desc = bufferDesc(BufferHandle{id});
1101 if (!name || !desc) return;
1102
1103 // GL_ELEMENT_ARRAY_BUFFER binding is VAO state: uploading through it while some
1104 // VAO is bound would silently rewire that VAO's index buffer. Detach first.
1105 if (desc->usage == GfxBufferUsage::Index) {
1106 glBindVertexArray(0);
1107 bound_vao_ = 0;
1108 }
1109
1110 const GLenum target = toGLBufferTarget(desc->usage);
1111 glBindBuffer(target, name);
1112 if (respec) {
1113 glBufferData(target, sizeBytes, data, desc->dynamic ? GL_DYNAMIC_DRAW : GL_STATIC_DRAW);
1114 } else {
1115 glBufferSubData(target, offsetBytes, sizeBytes, data);
1116 }
1117}
1118
1119bool GLDevice::backendCreateBuffer(u32 id, const BufferDesc& desc, const void* data) {
1120 GLuint name = 0;
1121 glGenBuffers(1, &name);
1122 if (!name) return false;
1123 setName(buffer_names_, id, name);
1124 uploadBufferStore(id, 0, data, desc.size, /*respec=*/true);
1125 // A slot keeps naming the buffer across a rebuild; the context it was bound in does not.
1126 for (usize slot = 0; slot < uniform_slots_.size(); ++slot) {
1127 if (uniform_slots_[slot] == id) bindUniformSlot(static_cast<u32>(slot), name);
1128 }
1129 return true;
1130}
1131
1133 GLuint name = nameOf(buffer_names_, id);
1134 if (!name) return;
1135 // The VAOs that read this buffer go with it: GL gives a deleted name to the next buffer made, and a VAO still keyed by it would be taken for that one.
1136 releaseVaosUsing(name);
1137 glDeleteBuffers(1, &name);
1138 setName(buffer_names_, id, 0);
1139 // The context unbinds a deleted buffer from the slots that held it; the record of those slots must not go on saying it is there.
1140 for (UniformBound& bound : uniform_bound_) {
1141 if (bound.known && bound.name == name) bound = {};
1142 }
1143}
1144
1145void GLDevice::backendUpdateBuffer(u32 id, u32 offsetBytes, const void* data, u32 sizeBytes) {
1146 uploadBufferStore(id, offsetBytes, data, sizeBytes, /*respec=*/false);
1147}
1148
1149void GLDevice::backendResizeBuffer(u32 id, const BufferDesc& desc, const void* data) {
1150 uploadBufferStore(id, 0, data, desc.size, /*respec=*/true);
1151}
1152
1153void GLDevice::backendSetUniformBuffer(u32 slot, BufferHandle buffer, u32 offsetBytes, u32 sizeBytes) {
1154 setName(uniform_slots_, slot, static_cast<u32>(buffer));
1155 if (slot >= uniform_ranges_.size()) uniform_ranges_.resize(static_cast<usize>(slot) + 1);
1156 uniform_ranges_[slot] = {offsetBytes, sizeBytes};
1157 bindUniformSlot(slot, nameOf(buffer_names_, static_cast<u32>(buffer)));
1158}
1159
1160void GLDevice::bindUniformSlot(u32 slot, u32 name) {
1161 const UniformRange range = slot < uniform_ranges_.size() ? uniform_ranges_[slot] : UniformRange{};
1162 // Most binds of a frame are to what the slot holds already: the same frame constants and the same material block, once per draw.
1163 if (slot >= uniform_bound_.size()) uniform_bound_.resize(static_cast<usize>(slot) + 1);
1164 UniformBound& held = uniform_bound_[slot];
1165 const u32 wantSize = name ? range.size : 0;
1166 const u32 wantOffset = (name && range.size) ? range.offset : 0;
1167 if (held.known && held.name == name && held.offset == wantOffset && held.size == wantSize) return;
1168 held = {name, wantOffset, wantSize, true};
1169 if (name && range.size) {
1170 glBindBufferRange(GL_UNIFORM_BUFFER, slot, name, range.offset, range.size);
1171 } else {
1172 glBindBufferBase(GL_UNIFORM_BUFFER, slot, name);
1173 }
1174}
1175
1176// =============================================================================
1177// Vertex Input
1178// =============================================================================
1179
1181 for (auto it = vaos_.begin(); it != vaos_.end();) {
1182 if (it->first.layout != id) {
1183 ++it;
1184 continue;
1185 }
1186 if (it->second.vao != 0) {
1187 if (bound_vao_ == it->second.vao) {
1188 glBindVertexArray(0);
1189 bound_vao_ = 0;
1190 }
1191 glDeleteVertexArrays(1, &it->second.vao);
1192 }
1193 last_vao_ = nullptr;
1194 it = vaos_.erase(it);
1195 }
1196}
1197
1198void GLDevice::releaseVaosUsing(u32 bufferName) {
1199 if (!bufferName) return;
1200 for (auto it = vaos_.begin(); it != vaos_.end();) {
1201 bool reads = it->first.ibo == bufferName;
1202 for (u32 slot = 0; slot < MAX_VERTEX_BUFFER_SLOTS; ++slot) reads = reads || it->first.vbo[slot] == bufferName;
1203 if (!reads) {
1204 ++it;
1205 continue;
1206 }
1207 if (it->second.vao != 0) {
1208 if (bound_vao_ == it->second.vao) {
1209 glBindVertexArray(0);
1210 bound_vao_ = 0;
1211 }
1212 glDeleteVertexArrays(1, &it->second.vao);
1213 }
1214 last_vao_ = nullptr;
1215 it = vaos_.erase(it);
1216 }
1217}
1218
1219void GLDevice::setVertexBuffer(u32 slot, BufferHandle buffer, u32 offsetBytes) {
1220 if (slot >= MAX_VERTEX_BUFFER_SLOTS) return;
1221 pending_vbo_[slot] = nameOf(buffer_names_, static_cast<u32>(buffer));
1222 pending_vbo_offset_[slot] = offsetBytes;
1223}
1224
1226 pending_ibo_ = nameOf(buffer_names_, static_cast<u32>(buffer));
1227}
1228
1229void GLDevice::prepareVertexState() {
1230 const VertexLayoutDesc* desc = vertexLayoutDesc(VertexLayoutHandle{current_layout_});
1231 if (!desc) return;
1232 VaoKey key;
1233 key.layout = current_layout_;
1234 key.ibo = pending_ibo_;
1235 for (u32 a = 0; a < desc->attributeCount; ++a) {
1236 const u32 slot = desc->attributes[a].bufferSlot;
1237 if (slot < MAX_VERTEX_BUFFER_SLOTS) key.vbo[slot] = pending_vbo_[slot];
1238 }
1239 if (!last_vao_ || !(key == last_vao_key_)) {
1240 last_vao_ = &vaos_[key];
1241 last_vao_key_ = key;
1242 }
1243 VaoCache& rec = *last_vao_;
1244
1245 if (rec.vao == 0) {
1246 glGenVertexArrays(1, &rec.vao);
1247 rec.configured = false;
1248 }
1249 if (bound_vao_ != rec.vao) {
1250 glBindVertexArray(rec.vao);
1251 bound_vao_ = rec.vao;
1252 }
1253
1254 if (!rec.configured || rec.bakedIbo != pending_ibo_) {
1255 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, pending_ibo_);
1256 rec.bakedIbo = pending_ibo_;
1257 }
1258
1259 for (u32 slot = 0; slot < MAX_VERTEX_BUFFER_SLOTS; ++slot) {
1260 bool slotUsed = false;
1261 for (u32 a = 0; a < desc->attributeCount; ++a) {
1262 if (desc->attributes[a].bufferSlot == slot) { slotUsed = true; break; }
1263 }
1264 if (!slotUsed) continue;
1265 if (rec.configured && rec.bakedVbo[slot] == pending_vbo_[slot]
1266 && rec.bakedOffset[slot] == pending_vbo_offset_[slot]) {
1267 continue;
1268 }
1269
1270 glBindBuffer(GL_ARRAY_BUFFER, pending_vbo_[slot]);
1271 for (u32 a = 0; a < desc->attributeCount; ++a) {
1272 const GfxVertexAttribute& attr = desc->attributes[a];
1273 if (attr.bufferSlot != slot) continue;
1274 glEnableVertexAttribArray(attr.location);
1275 const void* at = reinterpret_cast<const void*>(
1276 static_cast<uintptr_t>(pending_vbo_offset_[slot] + attr.offset));
1277 // An un-normalized integer attribute reaches the shader AS an
1278 // integer, through a different entry point: the float one converts,
1279 // and a converted joint index is not an index.
1280 if (!attr.normalized && isIntegerAttribute(attr.type)) {
1281 glVertexAttribIPointer(
1282 attr.location, attr.components, toGLDataType(attr.type),
1283 static_cast<GLsizei>(desc->strides[slot]), at);
1284 } else {
1285 glVertexAttribPointer(
1286 attr.location, attr.components, toGLDataType(attr.type),
1287 attr.normalized ? GL_TRUE : GL_FALSE,
1288 static_cast<GLsizei>(desc->strides[slot]), at);
1289 }
1290 glVertexAttribDivisor(attr.location, desc->instanceStep[slot] ? 1 : 0);
1291 }
1292 rec.bakedVbo[slot] = pending_vbo_[slot];
1293 rec.bakedOffset[slot] = pending_vbo_offset_[slot];
1294 }
1295 rec.configured = true;
1296}
1297
1298// =============================================================================
1299// Pipeline State
1300// =============================================================================
1301
1302void GLDevice::applyStencilMode(GfxStencilMode mode) {
1303 // Mirrors the former StateTracker stencil sequences. The reference value is applied
1304 // separately by setStencilReference (it is dynamic, not pipeline state).
1305 switch (mode) {
1307 setStencilTest(false);
1308 setStencilMask(0xFF);
1309 setColorMask(true, true, true, true);
1310 break;
1312 setStencilTest(true);
1314 setColorMask(false, false, false, false);
1315 setStencilMask(0xFF);
1316 break;
1320 setStencilTest(true);
1324 setColorMask(false, false, false, false);
1325 setStencilMask(0xFF);
1326 break;
1329 setStencilTest(true);
1331 setColorMask(true, true, true, true);
1332 setStencilMask(0x00);
1333 break;
1334 }
1335}
1336
1338 if (id == current_pipeline_id_) return;
1339 backendUseProgram(static_cast<u32>(desc.program));
1340 setBlendEnabled(desc.blendEnabled);
1341 setBlendMode(desc.blend, desc.layerAlpha);
1342 setDepthTest(desc.depthTest);
1343 setDepthWrite(desc.depthWrite);
1344 setCulling(desc.cullEnabled);
1345 if (desc.cullEnabled) setCullFace(desc.cullFront);
1346 setDepthBias(desc.depthBias);
1347 applyStencilMode(desc.stencil);
1348 // After the stencil mode, which states the colour mask for its own sake: a depth-only draw takes it away whatever the stencil said.
1349 if (!desc.colorWrite) setColorMask(false, false, false, false);
1350 if (static_cast<i8>(desc.depthEqual) != depth_equal_) {
1351 glDepthFunc(desc.depthEqual ? GL_LEQUAL : GL_LESS);
1352 depth_equal_ = static_cast<i8>(desc.depthEqual);
1353 }
1354 if (static_cast<i8>(desc.alphaToCoverage) != alpha_to_coverage_) {
1355 if (desc.alphaToCoverage) glEnable(GL_SAMPLE_ALPHA_TO_COVERAGE);
1356 else glDisable(GL_SAMPLE_ALPHA_TO_COVERAGE);
1357 alpha_to_coverage_ = static_cast<i8>(desc.alphaToCoverage);
1358 }
1359
1360 if (current_fbo_has_gbuffer_) applyDrawBuffers(desc.gbuffer, desc.albedo);
1361 applySurfaceBlend(desc.blendEnabled && desc.gbuffer && current_fbo_has_gbuffer_);
1362
1363 current_pipeline_id_ = id;
1364 current_topology_ = desc.topology;
1365 current_stencil_mode_ = desc.stencil;
1366 current_layout_ = static_cast<u32>(desc.vertexLayout);
1367}
1368
1376void GLDevice::setDepthBias(i16 bias) {
1377 if (bias == current_depth_bias_) return;
1378 if (bias == 0) {
1379 glDisable(GL_POLYGON_OFFSET_FILL);
1380 } else {
1381 glEnable(GL_POLYGON_OFFSET_FILL);
1382 glPolygonOffset(static_cast<f32>(bias), static_cast<f32>(bias));
1383 }
1384 current_depth_bias_ = bias;
1385}
1386
1388 switch (current_stencil_mode_) {
1390 setStencilFunc(GfxStencilFunc::Always, ref, 0xFF);
1391 break;
1393 setStencilFunc(GfxStencilFunc::Equal, ref, 0xFF);
1394 break;
1398 setStencilFunc(GfxStencilFunc::Equal, ref, 0xFF);
1399 break;
1401 setStencilFunc(GfxStencilFunc::NotEqual, ref, 0xFF);
1402 break;
1404 break;
1405 }
1406}
1407
1409 current_pipeline_id_ = 0;
1410 current_stencil_mode_ = GfxStencilMode::Off;
1411 current_program_name_ = 0;
1412 current_blend_ = static_cast<BlendMode>(0xFF);
1413}
1414
1415// =============================================================================
1416// Draw Calls
1417// =============================================================================
1418
1421 return current_topology_ == GfxTopology::Lines ? GL_LINES : GL_TRIANGLES;
1422}
1423
1424void GLDevice::drawElements(u32 indexCount, GfxDataType indexType, u32 byteOffset) {
1425 if (!isDeviceUsable()) return;
1426 prepareVertexState();
1427 countDraw();
1428 glDrawElements(primitiveMode(), static_cast<GLsizei>(indexCount), toGLDataType(indexType),
1429 reinterpret_cast<const void*>(static_cast<uintptr_t>(byteOffset)));
1430}
1431
1432void GLDevice::drawArrays(u32 first, u32 vertexCount) {
1433 if (!isDeviceUsable()) return;
1434 prepareVertexState();
1435 countDraw();
1436 glDrawArrays(primitiveMode(), static_cast<GLint>(first), static_cast<GLsizei>(vertexCount));
1437}
1438
1439void GLDevice::drawElementsInstancedMulti(GfxDataType indexType, const u32* counts, const u32* byteOffsets,
1440 const u32* instanceCounts, u32 drawCount) {
1441#ifdef __EMSCRIPTEN__
1442 if (!multi_draw_) {
1443 GfxDevice::drawElementsInstancedMulti(indexType, counts, byteOffsets, instanceCounts, drawCount);
1444 return;
1445 }
1446 if (!isDeviceUsable() || drawCount == 0) return;
1447 prepareVertexState();
1448 multi_counts_.resize(drawCount);
1449 multi_instances_.resize(drawCount);
1450 multi_offsets_.resize(drawCount);
1451 for (u32 k = 0; k < drawCount; ++k) {
1452 multi_counts_[k] = static_cast<i32>(counts[k]);
1453 multi_instances_[k] = static_cast<i32>(instanceCounts[k]);
1454 multi_offsets_[k] = reinterpret_cast<const void*>(static_cast<uintptr_t>(byteOffsets[k]));
1455 // Counted as the draws they are: a draw count that halved because they shared a call would read as work saved on the GPU.
1456 countDraw();
1457 }
1458 glMultiDrawElementsInstancedWEBGL(primitiveMode(), multi_counts_.data(), toGLDataType(indexType), multi_offsets_.data(),
1459 multi_instances_.data(), static_cast<GLsizei>(drawCount));
1460#else
1461 GfxDevice::drawElementsInstancedMulti(indexType, counts, byteOffsets, instanceCounts, drawCount);
1462#endif
1463}
1464
1465void GLDevice::drawElementsInstanced(u32 indexCount, GfxDataType indexType, u32 byteOffset, u32 instanceCount) {
1466 if (!isDeviceUsable()) return;
1467 prepareVertexState();
1468 countDraw();
1469 glDrawElementsInstanced(primitiveMode(), static_cast<GLsizei>(indexCount), toGLDataType(indexType),
1470 reinterpret_cast<const void*>(static_cast<uintptr_t>(byteOffset)),
1471 static_cast<GLsizei>(instanceCount));
1472}
1473
1474// =============================================================================
1475// Textures
1476// =============================================================================
1477
1478u32 GLDevice::textureTarget(u32 name) const {
1479 if (!array_names_.empty() && array_names_.count(name)) return GL_TEXTURE_2D_ARRAY;
1480 if (!volume_names_.empty() && volume_names_.count(name)) return GL_TEXTURE_3D;
1481 return GL_TEXTURE_2D;
1482}
1483
1484// A unit holds a 2D, an array and a 3D binding side by side; the sampler type of the program decides which is read.
1486 const u32 name = nameOf(texture_names_, static_cast<u32>(texture));
1487 if (slot >= kTextureSlots) { // beyond the cache — bind directly
1488 glActiveTexture(GL_TEXTURE0 + slot);
1489 glBindTexture(textureTarget(name), name);
1490 return;
1491 }
1492 if (bound_texture_[slot] == name) return; // already bound to this sampler unit
1493 if (active_texture_unit_ != slot) {
1494 glActiveTexture(GL_TEXTURE0 + slot);
1495 active_texture_unit_ = slot;
1496 }
1497 glBindTexture(textureTarget(name), name);
1498 bound_texture_[slot] = name;
1499}
1500
1501void GLDevice::bindTextureForEdit(u32 name) {
1502 glBindTexture(textureTarget(name), name);
1503 if (active_texture_unit_ < kTextureSlots) bound_texture_[active_texture_unit_] = name;
1504}
1505
1506void GLDevice::evictSamplerBinding(u32 name) {
1507 if (name == 0) return;
1508 for (u32 slot = 0; slot < kTextureSlots; ++slot) {
1509 if (bound_texture_[slot] != name) continue;
1510 if (active_texture_unit_ != slot) {
1511 glActiveTexture(GL_TEXTURE0 + slot);
1512 active_texture_unit_ = slot;
1513 }
1514 glBindTexture(textureTarget(name), 0);
1515 bound_texture_[slot] = 0;
1516 }
1517}
1518
1519bool GLDevice::backendCreateTexture(u32 id, const TextureDesc& desc, const void* pixels) {
1520 // Multisampled: a renderbuffer, never sampled, only drawn into and resolved
1521 // from. It takes no filter or wrap because nothing reads it through a sampler.
1522 if (desc.samples > 1) {
1523 GLuint rb = 0;
1524 glGenRenderbuffers(1, &rb);
1525 glBindRenderbuffer(GL_RENDERBUFFER, rb);
1526 auto glfmt = toGLPixelFormat(desc.format);
1527 glRenderbufferStorageMultisample(GL_RENDERBUFFER, static_cast<GLsizei>(desc.samples),
1528 glfmt.internalFormat,
1529 static_cast<GLsizei>(desc.width),
1530 static_cast<GLsizei>(desc.height));
1531 glBindRenderbuffer(GL_RENDERBUFFER, 0);
1532 if (rb == 0) return false;
1533 setName(texture_names_, id, rb);
1534 return true;
1535 }
1536
1537 GLuint name = 0;
1538 glGenTextures(1, &name);
1539 if (name == 0) return false;
1540 setName(texture_names_, id, name);
1541
1542 auto gl = toGLPixelFormat(desc.format);
1543 if (desc.volume) {
1544 // As an array's: the slices go up in the rows given, and nothing is mipmapped.
1545 volume_names_.insert(name);
1546 bindTextureForEdit(name);
1547 const TightRowScope rows(desc.format, desc.width);
1548 glTexImage3D(GL_TEXTURE_3D, 0, static_cast<GLint>(gl.internalFormat),
1549 static_cast<GLsizei>(desc.width), static_cast<GLsizei>(desc.height),
1550 static_cast<GLsizei>(std::max(1u, desc.layers)), 0, gl.format, gl.type, pixels);
1551 glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, toGLFilter(desc.minFilter));
1552 glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, toGLFilter(desc.magFilter));
1553 glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_S, toGLWrap(desc.wrapS));
1554 glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, toGLWrap(desc.wrapT));
1555 glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, toGLWrap(desc.wrapT));
1556 return true;
1557 }
1558 if (desc.layers > 1) {
1559 // WebGL2 refuses UNPACK_FLIP_Y for a 3D upload, so the layers go up in the rows given.
1560 array_names_.insert(name);
1561 bindTextureForEdit(name);
1562 const TightRowScope rows(desc.format, desc.width);
1563 glTexImage3D(GL_TEXTURE_2D_ARRAY, 0, static_cast<GLint>(gl.internalFormat),
1564 static_cast<GLsizei>(desc.width), static_cast<GLsizei>(desc.height),
1565 static_cast<GLsizei>(desc.layers), 0, gl.format, gl.type, pixels);
1566 glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MIN_FILTER, toGLMinFilter(desc));
1567 glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MAG_FILTER, toGLFilter(desc.magFilter));
1568 glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_WRAP_S, toGLWrap(desc.wrapS));
1569 glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_WRAP_T, toGLWrap(desc.wrapT));
1570 setAnisotropy(desc, desc.mipmaps, GL_TEXTURE_2D_ARRAY);
1571 if (desc.mipmaps && pixels) glGenerateMipmap(GL_TEXTURE_2D_ARRAY);
1572 return true;
1573 }
1574 bindTextureForEdit(name);
1575 const TightRowScope rows(desc.format, desc.width);
1576 if (pixels && desc.flipY) glPixelStorei(GL_UNPACK_FLIP_Y_WEBGL, GL_TRUE);
1577 glTexImage2D(GL_TEXTURE_2D, 0, static_cast<GLint>(gl.internalFormat),
1578 static_cast<GLsizei>(desc.width), static_cast<GLsizei>(desc.height),
1579 0, gl.format, gl.type, pixels);
1580 if (pixels && desc.flipY) glPixelStorei(GL_UNPACK_FLIP_Y_WEBGL, GL_FALSE);
1581
1582 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, toGLMinFilter(desc));
1583 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, toGLFilter(desc.magFilter));
1584 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, toGLWrap(desc.wrapS));
1585 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, toGLWrap(desc.wrapT));
1586 setAnisotropy(desc, desc.mipmaps);
1587
1588 if (desc.mipmaps && pixels) {
1589 glGenerateMipmap(GL_TEXTURE_2D);
1590 }
1591 return true;
1592}
1593
1595 const void* data, u32 byteLength, u32 mipLevels) {
1596 GLuint name = 0;
1597 glGenTextures(1, &name);
1598 if (name == 0) return false;
1599 setName(texture_names_, id, name);
1600 bindTextureForEdit(name);
1601
1602 // Upload each mip level from the concatenated, block-aligned pyramid.
1603 const u32 levels = mipLevels ? mipLevels : 1;
1604 const GfxBlockInfo bi = gfxCompressedBlockInfo(format);
1605 const GLenum glFmt = toGLCompressedFormat(format);
1606 const u8* ptr = static_cast<const u8*>(data);
1607 const u8* end = ptr + byteLength;
1608 for (u32 level = 0; level < levels; ++level) {
1609 const u32 lw = (desc.width >> level) ? (desc.width >> level) : 1u;
1610 const u32 lh = (desc.height >> level) ? (desc.height >> level) : 1u;
1611 const u32 blocksX = (lw + bi.blockWidth - 1) / bi.blockWidth;
1612 const u32 blocksY = (lh + bi.blockHeight - 1) / bi.blockHeight;
1613 const u32 levelBytes = blocksX * blocksY * bi.bytesPerBlock;
1614 if (levelBytes > static_cast<usize>(end - ptr)) break; // truncated pyramid
1615 glCompressedTexImage2D(GL_TEXTURE_2D, static_cast<GLint>(level), glFmt,
1616 static_cast<GLsizei>(lw), static_cast<GLsizei>(lh),
1617 0, static_cast<GLsizei>(levelBytes), ptr);
1618 ptr += levelBytes;
1619 }
1620
1621 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, static_cast<GLint>(levels - 1));
1622 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,
1623 levels > 1 ? GL_LINEAR_MIPMAP_LINEAR : toGLFilter(desc.minFilter));
1624 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, toGLFilter(desc.magFilter));
1625 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, toGLWrap(desc.wrapS));
1626 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, toGLWrap(desc.wrapT));
1627 setAnisotropy(desc, levels > 1);
1628 return true;
1629}
1630
1632 if (nativeId == 0) return false;
1633 setName(texture_names_, id, nativeId);
1634 return true;
1635}
1636
1638 GLuint name = nameOf(texture_names_, id);
1639 if (!name) return;
1640 if (isRenderbuffer(id)) {
1641 glDeleteRenderbuffers(1, &name);
1642 } else {
1643 evictSamplerBinding(name);
1644 glDeleteTextures(1, &name);
1645 array_names_.erase(name);
1646 volume_names_.erase(name);
1647 }
1648 setName(texture_names_, id, 0);
1649}
1650
1652 setName(texture_names_, into, nameOf(texture_names_, from));
1653 setName(texture_names_, from, 0);
1654}
1655
1656void GLDevice::backendUpdateTexture(u32 id, i32 x, i32 y, u32 width, u32 height,
1657 const void* pixels, bool flipY) {
1658 const TextureDesc* desc = textureDesc(TextureHandle{id});
1659 const GfxPixelFormat fmt = desc ? desc->format : GfxPixelFormat::RGBA8;
1660 auto gl = toGLPixelFormat(fmt);
1661 bindTextureForEdit(nameOf(texture_names_, id));
1662 const TightRowScope rows(fmt, width);
1663 if (flipY) glPixelStorei(GL_UNPACK_FLIP_Y_WEBGL, GL_TRUE);
1664 glTexSubImage2D(GL_TEXTURE_2D, 0, x, y,
1665 static_cast<GLsizei>(width), static_cast<GLsizei>(height),
1666 gl.format, gl.type, pixels);
1667 if (flipY) glPixelStorei(GL_UNPACK_FLIP_Y_WEBGL, GL_FALSE);
1668}
1669
1671 const u32 name = nameOf(texture_names_, id);
1672 const GLenum target = textureTarget(name);
1673 bindTextureForEdit(name);
1674 glTexParameteri(target, GL_TEXTURE_MIN_FILTER, toGLMinFilter(desc));
1675 glTexParameteri(target, GL_TEXTURE_MAG_FILTER, toGLFilter(desc.magFilter));
1676 glTexParameteri(target, GL_TEXTURE_WRAP_S, toGLWrap(desc.wrapS));
1677 glTexParameteri(target, GL_TEXTURE_WRAP_T, toGLWrap(desc.wrapT));
1678 setAnisotropy(desc, desc.mipmaps, target);
1679}
1680
1682 const u32 name = nameOf(texture_names_, id);
1683 const GLenum target = textureTarget(name);
1684 bindTextureForEdit(name);
1685 glGenerateMipmap(target);
1686 if (const TextureDesc* desc = textureDesc(TextureHandle{id})) {
1687 glTexParameteri(target, GL_TEXTURE_MIN_FILTER, toGLMinFilter(*desc));
1688 }
1689}
1690
1691// =============================================================================
1692// Framebuffer
1693// =============================================================================
1694
1695bool GLDevice::boundFramebufferComplete(std::initializer_list<TextureHandle> attachments) {
1696 std::string make;
1697 u32 width = 0, height = 0;
1698 bool sized = true;
1699 for (const TextureHandle texture : attachments) {
1700 const TextureDesc* d = texture != TextureHandle::Invalid ? textureDesc(texture) : nullptr;
1701 if (!d) {
1702 make += '-';
1703 continue;
1704 }
1705 if (width == 0) { width = d->width; height = d->height; }
1706 sized = sized && d->width == width && d->height == height;
1707 make += static_cast<char>('A' + static_cast<int>(d->format));
1708 make += isRenderbuffer(static_cast<u32>(texture)) ? 'r' : 't';
1709 make += std::to_string(d->samples);
1710 make += ',';
1711 }
1712 make += sized ? '=' : '~';
1713 if (const auto it = framebuffer_complete_.find(make); it != framebuffer_complete_.end()) return it->second;
1714 const bool complete = glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE;
1715 framebuffer_complete_.emplace(std::move(make), complete);
1716 return complete;
1717}
1718
1720 GLuint fbo = 0;
1721 glGenFramebuffers(1, &fbo);
1722 glBindFramebuffer(GL_FRAMEBUFFER, fbo);
1723
1724 auto attach = [&](GLenum point, TextureHandle texture) {
1725 const u32 textureId = static_cast<u32>(texture);
1726 const u32 name = nameOf(texture_names_, textureId);
1727 if (isRenderbuffer(textureId)) {
1728 glFramebufferRenderbuffer(GL_FRAMEBUFFER, point, GL_RENDERBUFFER, name);
1729 } else {
1730 glFramebufferTexture2D(GL_FRAMEBUFFER, point, GL_TEXTURE_2D, name, 0);
1731 }
1732 };
1733 auto depthPoint = [&](TextureHandle texture) {
1734 const TextureDesc* d = textureDesc(texture);
1735 return d && d->format == GfxPixelFormat::DepthComponent24 ? GL_DEPTH_ATTACHMENT
1737 };
1738
1739 if (desc.color0 != TextureHandle::Invalid) attach(GL_COLOR_ATTACHMENT0, desc.color0);
1740 if (desc.color1 != TextureHandle::Invalid) attach(GL_COLOR_ATTACHMENT1, desc.color1);
1741 if (desc.color2 != TextureHandle::Invalid) attach(GL_COLOR_ATTACHMENT2, desc.color2);
1743 // Attach point follows the texture's pixel format (depth-only vs packed depth+stencil).
1744 attach(depthPoint(desc.depthStencil), desc.depthStencil);
1745 }
1746
1747 const bool complete = boundFramebufferComplete({desc.color0, desc.color1, desc.color2, desc.depthStencil});
1748 glBindFramebuffer(GL_FRAMEBUFFER, 0);
1749 if (!complete) {
1750 glDeleteFramebuffers(1, &fbo);
1751 return false;
1752 }
1753 setName(framebuffer_names_, id, fbo);
1754
1755 // A multisampled target keeps a second, single-sample framebuffer of its own
1756 // to resolve into. It is the target's, not a pass's: whoever leaves the
1757 // target gets the resolve for free and never has to ask for it.
1759 GLuint dst = 0;
1760 glGenFramebuffers(1, &dst);
1761 glBindFramebuffer(GL_FRAMEBUFFER, dst);
1762 attach(GL_COLOR_ATTACHMENT0, desc.resolveColor0);
1763 if (desc.resolveColor1 != TextureHandle::Invalid) attach(GL_COLOR_ATTACHMENT1, desc.resolveColor1);
1764 if (desc.resolveColor2 != TextureHandle::Invalid) attach(GL_COLOR_ATTACHMENT2, desc.resolveColor2);
1766 attach(depthPoint(desc.resolveDepthStencil), desc.resolveDepthStencil);
1767 }
1768 const bool ok = boundFramebufferComplete({desc.resolveColor0, desc.resolveColor1, desc.resolveColor2, desc.resolveDepthStencil});
1769 glBindFramebuffer(GL_FRAMEBUFFER, 0);
1770 if (ok) {
1771 framebuffer_resolve_[id] = {dst, desc.width, desc.height,
1775 } else {
1776 glDeleteFramebuffers(1, &dst);
1777 ES_LOG_ERROR("GLDevice: multisample resolve target incomplete");
1778 }
1779 }
1780 return true;
1781}
1782
1789void GLDevice::resolveFramebuffer(u32 framebufferId) {
1790 auto it = framebuffer_resolve_.find(framebufferId);
1791 if (it == framebuffer_resolve_.end() || it->second.destFbo == 0) return;
1792 const auto& r = it->second;
1793 if (r.width == 0 || r.height == 0) return;
1794 glBindFramebuffer(GL_READ_FRAMEBUFFER, nameOf(framebuffer_names_, framebufferId));
1795 glBindFramebuffer(GL_DRAW_FRAMEBUFFER, r.destFbo);
1796 const GLsizei w = static_cast<GLsizei>(r.width), h = static_cast<GLsizei>(r.height);
1797 if (r.gbuffer) {
1798 // Each attachment on its own: a blit copies the read buffer into every live draw buffer,
1799 // and the two are different surfaces.
1800 const GLsizei count = r.albedo ? 3 : 2;
1801 const GLenum only0[3] = {GL_COLOR_ATTACHMENT0, GL_NONE, GL_NONE};
1802 const GLenum only1[3] = {GL_NONE, GL_COLOR_ATTACHMENT1, GL_NONE};
1803 const GLenum only2[3] = {GL_NONE, GL_NONE, GL_COLOR_ATTACHMENT2};
1804 glDrawBuffers(count, only0);
1805 glBlitFramebuffer(0, 0, w, h, 0, 0, w, h, GL_COLOR_BUFFER_BIT, GL_LINEAR);
1806 glReadBuffer(GL_COLOR_ATTACHMENT1);
1807 glDrawBuffers(count, only1);
1808 // Nearest: a normal or a roughness averaged with its neighbour's is neither's.
1809 glBlitFramebuffer(0, 0, w, h, 0, 0, w, h, GL_COLOR_BUFFER_BIT, GL_NEAREST);
1810 if (r.albedo) {
1811 glReadBuffer(GL_COLOR_ATTACHMENT2);
1812 glDrawBuffers(count, only2);
1813 glBlitFramebuffer(0, 0, w, h, 0, 0, w, h, GL_COLOR_BUFFER_BIT, GL_NEAREST);
1814 }
1815 glReadBuffer(GL_COLOR_ATTACHMENT0);
1816 } else {
1817 glBlitFramebuffer(0, 0, w, h, 0, 0, w, h, GL_COLOR_BUFFER_BIT, GL_LINEAR);
1818 }
1819 if (r.depth) {
1820 // A separate blit: depth and colour cannot share one when the filter
1821 // differs, and depth refuses anything but NEAREST.
1822 glBlitFramebuffer(0, 0, w, h, 0, 0, w, h, GL_DEPTH_BUFFER_BIT, GL_NEAREST);
1823 }
1824 if (pass_discard_msaa_) {
1825 // Resolved, and nothing draws on it again: a tile-based GPU need not write the samples out to memory.
1826 GLenum attachments[5];
1827 GLsizei n = 0;
1828 attachments[n++] = GL_COLOR_ATTACHMENT0;
1829 if (r.gbuffer) attachments[n++] = GL_COLOR_ATTACHMENT1;
1830 if (r.albedo) attachments[n++] = GL_COLOR_ATTACHMENT2;
1831 attachments[n++] = GL_DEPTH_ATTACHMENT;
1832 attachments[n++] = GL_STENCIL_ATTACHMENT;
1833 glInvalidateFramebuffer(GL_READ_FRAMEBUFFER, n, attachments);
1834 }
1835 glBindFramebuffer(GL_FRAMEBUFFER, nameOf(framebuffer_names_, current_framebuffer_));
1836}
1837
1838void GLDevice::discardLeftDepth() {
1839 if (!pass_discard_depth_ || current_framebuffer_ == 0) return;
1840 const GLenum depth = GL_DEPTH_ATTACHMENT;
1841 glBindFramebuffer(GL_FRAMEBUFFER, nameOf(framebuffer_names_, current_framebuffer_));
1842 glInvalidateFramebuffer(GL_FRAMEBUFFER, 1, &depth);
1843}
1844
1846 if (!frame_fence_) return false;
1847 if (!isDeviceUsable()) { frame_fence_ = nullptr; return false; }
1848 // A timeout of 0 asks without waiting (WebGL allows no other); the answer moves on between tasks.
1849 const GLenum state = glClientWaitSync(static_cast<GLsync>(frame_fence_), 0, 0);
1850 if (state == GL_TIMEOUT_EXPIRED) return true;
1851 glDeleteSync(static_cast<GLsync>(frame_fence_));
1852 frame_fence_ = nullptr;
1853 return false;
1854}
1855
1857 // Fenced first, before anything below may return: the frame's work is all submitted, whatever framebuffer is bound.
1858 if (isDeviceUsable()) {
1859 if (frame_fence_) glDeleteSync(static_cast<GLsync>(frame_fence_));
1860 frame_fence_ = glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0);
1861 // The fence only passes once the GPU has been handed what is before it.
1862 glFlush();
1863 }
1864 // The default framebuffer's depth and stencil are never read after the frame, which the page shows by its colour: a tile-based GPU that is told so
1865 // does not write them out. Only with that framebuffer bound, so nothing is rebound under whoever draws next.
1866 if (current_framebuffer_ != 0) return;
1867 if (default_depth_bits_ < 0) {
1868 GLint depth = 0, stencil = 0;
1869 glBindFramebuffer(GL_FRAMEBUFFER, 0);
1870 glGetIntegerv(GL_DEPTH_BITS, &depth);
1871 glGetIntegerv(GL_STENCIL_BITS, &stencil);
1872 default_depth_bits_ = depth > 0 ? 1 : 0;
1873 default_stencil_bits_ = stencil > 0 ? 1 : 0;
1874 }
1875 GLenum attachments[2];
1876 GLsizei n = 0;
1877 if (default_depth_bits_ > 0) attachments[n++] = GL_DEPTH;
1878 if (default_stencil_bits_ > 0) attachments[n++] = GL_STENCIL;
1879 if (n == 0) return;
1880 glBindFramebuffer(GL_FRAMEBUFFER, 0);
1881 glInvalidateFramebuffer(GL_FRAMEBUFFER, n, attachments);
1882}
1883
1885 if (auto it = framebuffer_resolve_.find(id); it != framebuffer_resolve_.end()) {
1886 if (it->second.destFbo != 0) glDeleteFramebuffers(1, &it->second.destFbo);
1887 framebuffer_resolve_.erase(it);
1888 }
1889 GLuint name = nameOf(framebuffer_names_, id);
1890 if (name != 0) glDeleteFramebuffers(1, &name);
1891 setName(framebuffer_names_, id, 0);
1892}
1893
1895 setClearStencil(value);
1896 clear(false, false, true);
1897}
1898
1900 const u32 target = static_cast<u32>(desc.target);
1901 // Retargeting LEAVES the previous target, and the model has no explicit pass
1902 // object to hang the resolve on — so leaving is the event, whether it comes
1903 // from endRenderPass or from being retargeted out from under.
1904 if (current_framebuffer_ != target) {
1905 resolveFramebuffer(current_framebuffer_);
1906 discardLeftDepth();
1907 }
1908 pass_discard_msaa_ = desc.discardMultisampled;
1909 pass_discard_depth_ = desc.discardDepth;
1910 current_framebuffer_ = target;
1911 glBindFramebuffer(GL_FRAMEBUFFER, nameOf(framebuffer_names_, target));
1912
1913 // A target's own attachment must not stay bound to a sampler while it is drawn
1914 // into: GL leaves that undefined and some drivers raise a feedback-loop error
1915 // (a minimap composited last frame and drawn into this one).
1916 if (const FramebufferDesc* fb = framebufferDesc(desc.target)) {
1917 evictSamplerBinding(nameOf(texture_names_, static_cast<u32>(fb->color0)));
1918 evictSamplerBinding(nameOf(texture_names_, static_cast<u32>(fb->depthStencil)));
1919 if (fb->color1 != TextureHandle::Invalid) {
1920 evictSamplerBinding(nameOf(texture_names_, static_cast<u32>(fb->color1)));
1921 }
1922 if (fb->color2 != TextureHandle::Invalid) {
1923 evictSamplerBinding(nameOf(texture_names_, static_cast<u32>(fb->color2)));
1924 }
1925 }
1926 // Which draw buffers are live is the framebuffer's own state and a pipeline decides it per draw,
1927 // so a pass starts by saying it is not yet known — and the pipeline cache forgets, or a pipeline
1928 // left bound by the last pass would skip the call that says it.
1929 const FramebufferDesc* passTarget = framebufferDesc(desc.target);
1930 const bool hasGBuffer = passTarget && passTarget->color1 != TextureHandle::Invalid;
1931 if (hasGBuffer || current_fbo_has_gbuffer_) {
1932 current_pipeline_id_ = 0;
1933 draw_buffers_ = -1;
1934 }
1935 current_fbo_has_gbuffer_ = hasGBuffer;
1936 current_fbo_has_albedo_ = hasGBuffer && passTarget->color2 != TextureHandle::Invalid;
1937
1938 if (!desc.clearColor && !desc.clearDepth && !desc.clearStencil) return;
1939
1940 // Load-op values ride the pass — no sticky device clear state to drift.
1941 if (desc.clearColor) {
1942 setClearColor(desc.clearColorValue[0], desc.clearColorValue[1],
1943 desc.clearColorValue[2], desc.clearColorValue[3]);
1944 }
1945 if (desc.clearStencil) setClearStencil(desc.clearStencilValue);
1946
1947 // Load-op clears are self-contained: a scoped clear rides its OWN scissor
1948 // rect, an unscoped one forces the scissor OFF (a real load-op covers the
1949 // whole attachment — it must not be vetoed by whatever scissor the previous
1950 // frame's last draw left enabled). Scissor ends disabled either way; the
1951 // next draw's command state re-applies its own.
1952 const bool scoped = desc.clearW != 0;
1953 if (scoped) {
1954 setScissorTest(true);
1955 setScissor(desc.clearX, desc.clearY,
1956 static_cast<i32>(desc.clearW), static_cast<i32>(desc.clearH));
1957 } else {
1958 setScissorTest(false);
1959 }
1960 // The first attachment takes the clear colour (the camera's background); the second records what a
1961 // surface is, and the background is not one, so it clears to zero — "nothing wrote here".
1962 if (hasGBuffer && desc.clearColor) applyDrawBuffers(false, false);
1963 clear(desc.clearColor, desc.clearDepth, desc.clearStencil);
1964 if (hasGBuffer && desc.clearColor) {
1965 applyDrawBuffers(true, current_fbo_has_albedo_);
1966 const GLfloat zero[4] = {0.0f, 0.0f, 0.0f, 0.0f};
1967 glClearBufferfv(GL_COLOR, 1, zero);
1968 if (current_fbo_has_albedo_) glClearBufferfv(GL_COLOR, 2, zero);
1969 }
1970 if (scoped) setScissorTest(false);
1971}
1972
1973void GLDevice::applySurfaceBlend(bool off) {
1974 if (off == surface_blend_off_ || indexed_blend_ != 1) return;
1975#ifdef __EMSCRIPTEN__
1976 es_gl_surface_blend(off ? 1 : 0);
1977#endif
1978 surface_blend_off_ = off;
1979}
1980
1981void GLDevice::applyDrawBuffers(bool gbuffer, bool albedo) {
1982 const i8 want = !gbuffer ? 0 : (albedo && current_fbo_has_albedo_) ? 2 : 1;
1983 if (draw_buffers_ == want) return;
1984 // A slot is NONE for a draw that does not write it, so a shader with fewer outputs does not leave an
1985 // undefined value in the surface record or the albedo.
1986 const GLenum sets[3][3] = {
1987 {GL_COLOR_ATTACHMENT0, GL_NONE, GL_NONE},
1988 {GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_NONE},
1989 {GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2},
1990 };
1991 glDrawBuffers(current_fbo_has_albedo_ ? 3 : 2, sets[want]);
1992 draw_buffers_ = want;
1993}
1994
1996 resolveFramebuffer(current_framebuffer_);
1997 discardLeftDepth();
1998 pass_discard_msaa_ = false;
1999 pass_discard_depth_ = false;
2000 current_framebuffer_ = 0;
2001 current_fbo_has_gbuffer_ = false;
2002 current_fbo_has_albedo_ = false;
2003 glBindFramebuffer(GL_FRAMEBUFFER, 0);
2004}
2005
2007 if (max_samples_ != 0) return max_samples_;
2008 GLint n = 0;
2009 glGetIntegerv(GL_MAX_SAMPLES, &n);
2010 max_samples_ = n > 1 ? static_cast<u32>(n) : 1u;
2011 return max_samples_;
2012}
2013
2014// =============================================================================
2015// Readback (async seam; GL resolves at request time)
2016// =============================================================================
2017
2020 if (w == 0 || h == 0) return ReadbackHandle::Invalid;
2021 Readback readback;
2022 readback.size = static_cast<usize>(w) * h * 4;
2023 readback.pixels.resize(readback.size);
2024 glBindFramebuffer(GL_FRAMEBUFFER, 0);
2025 auto gl = toGLPixelFormat(GfxPixelFormat::RGBA8);
2026 glReadPixels(0, 0, static_cast<GLsizei>(w), static_cast<GLsizei>(h), gl.format, gl.type, readback.pixels.data());
2027 const u32 id = next_readback_id_++;
2028 readbacks_[id] = std::move(readback);
2029 return static_cast<ReadbackHandle>(id);
2030}
2031
2034 if (w == 0 || h == 0) return ReadbackHandle::Invalid;
2035 Readback readback;
2036 readback.size = static_cast<usize>(w) * h * 4;
2037 // Called outside a pass (framebuffer 0 bound); bind the source, read, restore.
2038 glBindFramebuffer(GL_FRAMEBUFFER, nameOf(framebuffer_names_, static_cast<u32>(target)));
2039 auto gl = toGLPixelFormat(GfxPixelFormat::RGBA8);
2040#ifdef __EMSCRIPTEN__
2041 // Into a buffer, in the GPU's own time: nothing here waits for the frame to be drawn.
2042 GLuint buffer = 0;
2043 glGenBuffers(1, &buffer);
2044 glBindBuffer(GL_PIXEL_PACK_BUFFER, buffer);
2045 glBufferData(GL_PIXEL_PACK_BUFFER, static_cast<GLsizeiptr>(readback.size), nullptr, GL_STREAM_READ);
2046 glReadPixels(0, 0, static_cast<GLsizei>(w), static_cast<GLsizei>(h), gl.format, gl.type, nullptr);
2047 glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);
2048 readback.buffer = buffer;
2049 readback.fence = glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0);
2050 // The fence only passes once the GPU has been handed what is before it.
2051 glFlush();
2052#else
2053 readback.pixels.resize(readback.size);
2054 glReadPixels(0, 0, static_cast<GLsizei>(w), static_cast<GLsizei>(h), gl.format, gl.type,
2055 readback.pixels.data());
2056#endif
2057 glBindFramebuffer(GL_FRAMEBUFFER, 0);
2058 const u32 id = next_readback_id_++;
2059 readbacks_[id] = std::move(readback);
2060 return static_cast<ReadbackHandle>(id);
2061}
2062
2064 if (!isDeviceUsable()) return false;
2065 const TextureDesc* desc = textureDesc(dst);
2066 const u32 name = nameOf(texture_names_, static_cast<u32>(dst));
2067 if (!desc || name == 0 || desc->samples > 1 || desc->layered()) return false;
2068 glBindFramebuffer(GL_READ_FRAMEBUFFER, nameOf(framebuffer_names_, static_cast<u32>(source)));
2069 bindTextureForEdit(name);
2070 glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 0, 0, static_cast<GLsizei>(desc->width), static_cast<GLsizei>(desc->height));
2071 glBindFramebuffer(GL_READ_FRAMEBUFFER, 0);
2072 return true;
2073}
2074
2076 auto it = readbacks_.find(static_cast<u32>(handle));
2077 if (it == readbacks_.end()) return GfxReadbackStatus::Failed;
2078 Readback& readback = it->second;
2079 if (!readback.fence) return readback.buffer || !readback.pixels.empty() ? GfxReadbackStatus::Ready : GfxReadbackStatus::Failed;
2081 // A timeout of 0 asks without waiting (WebGL allows no other); the answer moves on between tasks, so a caller polls across them.
2082 const GLenum state = glClientWaitSync(static_cast<GLsync>(readback.fence), 0, 0);
2083 if (state == GL_WAIT_FAILED) return GfxReadbackStatus::Failed;
2084 if (state != GL_ALREADY_SIGNALED && state != GL_CONDITION_SATISFIED) return GfxReadbackStatus::Pending;
2085 glDeleteSync(static_cast<GLsync>(readback.fence));
2086 readback.fence = nullptr;
2088}
2089
2090bool GLDevice::takeReadback(ReadbackHandle handle, void* dest, usize destSize) {
2091 auto it = readbacks_.find(static_cast<u32>(handle));
2092 if (it == readbacks_.end() || destSize < it->second.size) return false;
2093 // A Pending readback stays alive: only a passed fence lets the bytes be read without waiting for them.
2094 if (it->second.fence && pollReadback(handle) != GfxReadbackStatus::Ready) return false;
2095 Readback& readback = it->second;
2096 if (readback.buffer) {
2097#ifdef __EMSCRIPTEN__
2098 glBindBuffer(GL_PIXEL_PACK_BUFFER, readback.buffer);
2099 glGetBufferSubData(GL_PIXEL_PACK_BUFFER, 0, static_cast<GLsizeiptr>(readback.size), dest);
2100 glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);
2101#endif
2102 } else {
2103 std::memcpy(dest, readback.pixels.data(), readback.size);
2104 }
2105 releaseReadback(readback, isDeviceUsable());
2106 readbacks_.erase(it);
2107 return true;
2108}
2109
2111 auto it = readbacks_.find(static_cast<u32>(handle));
2112 if (it == readbacks_.end()) return;
2113 releaseReadback(it->second, isDeviceUsable());
2114 readbacks_.erase(it);
2115}
2116
2117void GLDevice::releaseReadback(Readback& readback, bool live) {
2118 if (live && readback.fence) glDeleteSync(static_cast<GLsync>(readback.fence));
2119 if (live && readback.buffer) glDeleteBuffers(1, &readback.buffer);
2120 readback.fence = nullptr;
2121 readback.buffer = 0;
2122}
2123
2124// =============================================================================
2125// GPU Timing
2126// =============================================================================
2127
2129 if (timer_query_state_ == 0) {
2130#ifdef __EMSCRIPTEN__
2131 // Must ENABLE the extension (not just check presence) so emscripten routes the
2132 // TIME_ELAPSED query entry points.
2133 EMSCRIPTEN_WEBGL_CONTEXT_HANDLE ctx = emscripten_webgl_get_current_context();
2134 timer_query_state_ =
2135 (ctx && emscripten_webgl_enable_extension(ctx, "EXT_disjoint_timer_query_webgl2")) ? 1 : 2;
2136#else
2137 timer_query_state_ = 2;
2138#endif
2139 }
2140 if (timer_query_state_ != 1) return false;
2141 GLuint name = 0;
2142 glGenQueries(1, &name);
2143 if (name == 0) return false;
2144 setName(query_names_, id, name);
2145 return true;
2146}
2147
2149 glBeginQuery(GL_TIME_ELAPSED_EXT, nameOf(query_names_, query));
2150}
2151
2153 glEndQuery(GL_TIME_ELAPSED_EXT);
2154}
2155
2157 if (timer_disjoint_pending_) {
2158 timer_disjoint_pending_ = false;
2159 return true;
2160 }
2161 GLint disjoint = 0;
2162 glGetIntegerv(GL_GPU_DISJOINT_EXT, &disjoint);
2163 return disjoint != 0;
2164}
2165
2166bool GLDevice::getTimerQueryNs(u32 query, u64* outNanoseconds) {
2167 const u32 name = nameOf(query_names_, query);
2168 if (!name) return false;
2169 GLuint available = 0;
2170 glGetQueryObjectuiv(name, GL_QUERY_RESULT_AVAILABLE, &available);
2171 if (!available) return false;
2172 GLuint ns = 0;
2173 glGetQueryObjectuiv(name, GL_QUERY_RESULT, &ns);
2174 if (outNanoseconds) *outNanoseconds = ns;
2175 return true;
2176}
2177
2178// =============================================================================
2179// Debug
2180// =============================================================================
2181
2182void GLDevice::setWireframe(bool enabled) {
2183 // glPolygonMode is not available in WebGL2 / GLES3; wireframe is a no-op.
2184 (void)enabled;
2185}
2186
2188 const GLenum err = glGetError();
2189 // GL_CONTEXT_LOST is not an error to handle but the context announcing it is
2190 // gone; the two enums for it differ by header origin. Reporting it here lets
2191 // a build with error checking on notice in the same frame.
2192 if (err == GL_CONTEXT_LOST || err == GL_CONTEXT_LOST_WEBGL) {
2194 "glGetError returned GL_CONTEXT_LOST", "getError");
2195 }
2196 return static_cast<u32>(err);
2197}
2198
2200 GLenum e = GL_VERSION;
2201 switch (name) {
2202 case GfxStringName::Version: e = GL_VERSION; break;
2203 case GfxStringName::Renderer: e = GL_RENDERER; break;
2204 case GfxStringName::Vendor: e = GL_VENDOR; break;
2205 case GfxStringName::ShadingLanguageVersion: e = GL_SHADING_LANGUAGE_VERSION; break;
2206 }
2207 const char* s = reinterpret_cast<const char*>(glGetString(e));
2208 return s ? std::string(s) : std::string();
2209}
2210
2212 GLenum e = GL_MAX_TEXTURE_SIZE;
2213 switch (name) {
2214 case GfxIntParam::MaxTextureSize: e = GL_MAX_TEXTURE_SIZE; break;
2215 case GfxIntParam::MaxTextureImageUnits: e = GL_MAX_TEXTURE_IMAGE_UNITS; break;
2216 case GfxIntParam::MaxVertexAttribs: e = GL_MAX_VERTEX_ATTRIBS; break;
2217 }
2218 GLint v = 0;
2219 glGetIntegerv(e, &v);
2220 return static_cast<i32>(v);
2221}
2222
2224 switch (format) {
2227 return true; // ETC2/EAC is core in GLES3 / WebGL2 — no extension needed
2230 return glExtensionPresent("GL_KHR_texture_compression_astc_ldr")
2231 || glExtensionPresent("WEBGL_compressed_texture_astc");
2234 return glExtensionPresent("GL_EXT_texture_compression_s3tc")
2235 || glExtensionPresent("WEBGL_compressed_texture_s3tc");
2237 return true; // sRGB ETC2/EAC is core alongside the UNORM variant
2239 return glExtensionPresent("GL_KHR_texture_compression_astc_ldr")
2240 || glExtensionPresent("WEBGL_compressed_texture_astc");
2242 // Desktop GL ships sRGB DXT via EXT_texture_sRGB; WebGL splits it out.
2243 return glExtensionPresent("GL_EXT_texture_sRGB")
2244 || glExtensionPresent("WEBGL_compressed_texture_s3tc_srgb");
2245 }
2246 return false;
2247}
2248
2250 // Asked by the post-process chain several times a frame, and each ask walked the whole extension list across the wasm boundary (a call into the
2251 // browser for every extension the context has). What a context supports does not change while it lives; init() runs again for a new one.
2252 if (float_targets_ < 0) {
2253 // Rendering INTO RGBA16F needs EXT_color_buffer_float on WebGL2 (sampling
2254 // half-float textures is core; only attachment renderability is gated).
2255 float_targets_ = (glExtensionPresent("GL_EXT_color_buffer_float") || glExtensionPresent("EXT_color_buffer_float")) ? 1 : 0;
2256 }
2257 return float_targets_ == 1;
2258}
2259
2260} // namespace esengine
#define GL_GPU_DISJOINT_EXT
Definition GLDevice.cpp:92
#define GL_COMPRESSED_RGB8_ETC2
Definition GLDevice.cpp:40
#define GL_UNPACK_FLIP_Y_WEBGL
Definition GLDevice.cpp:85
#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR
Definition GLDevice.cpp:61
#define GL_RGBA16F
Definition GLDevice.cpp:70
#define GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT
Definition GLDevice.cpp:64
#define GL_COMPRESSED_RGBA8_ETC2_EAC
Definition GLDevice.cpp:43
#define GL_DEPTH_STENCIL_ATTACHMENT
Definition GLDevice.cpp:82
#define GL_COMPRESSED_RGBA_S3TC_DXT5_EXT
Definition GLDevice.cpp:55
#define GL_UNSIGNED_INT_24_8
Definition GLDevice.cpp:79
#define GL_COMPRESSED_RGBA_ASTC_4x4_KHR
Definition GLDevice.cpp:46
#define GL_SRGB8_ALPHA8
Definition GLDevice.cpp:67
#define GL_HALF_FLOAT
Definition GLDevice.cpp:76
#define GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC
Definition GLDevice.cpp:58
#define GL_DEPTH_STENCIL
Definition GLDevice.cpp:31
#define GL_COMPRESSED_RGBA_S3TC_DXT1_EXT
Definition GLDevice.cpp:52
#define GL_TIME_ELAPSED_EXT
Definition GLDevice.cpp:89
#define GL_RGBA32F
Definition GLDevice.cpp:73
#define GL_NUM_EXTENSIONS
Definition GLDevice.cpp:34
#define GL_COMPRESSED_RGBA_ASTC_8x8_KHR
Definition GLDevice.cpp:49
OpenGL ES / WebGL implementation of GfxDevice.
WHERE one draw's entry is in the frame's per-object record texture, and what an entry says.
Logging utilities for ESEngine.
#define ES_LOG_WARN(...)
Logs a warning message.
Definition Log.hpp:294
#define ES_LOG_ERROR(...)
Logs an error message.
Definition Log.hpp:296
#define ES_LOG_INFO(...)
Logs an info message.
Definition Log.hpp:292
#define ES_LOG_DEBUG(...)
Definition Log.hpp:282
Platform-specific OpenGL header includes.
#define GL_CONTEXT_LOST_WEBGL
#define GL_DECR
#define GL_MIN
#define GL_INCR
#define GL_MAX
#define GL_DECR_WRAP
#define GL_INCR_WRAP
#define GL_INVERT
#define GL_CONTEXT_LOST
#define GL_FUNC_ADD
void init() override
Initializes the graphics device.
Definition GLDevice.cpp:318
bool backendCreateBuffer(u32 id, const BufferDesc &desc, const void *data) override
void backendDeleteFramebuffer(u32 id) override
void setViewport(i32 x, i32 y, u32 w, u32 h) override
Sets the rendering viewport.
Definition GLDevice.cpp:528
bool framePending() override
Whether the GPU is still working on the frame last ended (see endFrame).
void backendUniformBlockBinding(u32 program, u32 nativeBlockIndex, u32 bindingPoint) override
void backendSetUniform(i32 nativeLocation, const GfxUniformValue &value) override
Definition GLDevice.cpp:944
void beginTimerQuery(u32 query) override
Starts timing GPU work into a query; one query may be active at a time.
void discardReadback(ReadbackHandle handle) override
Abandons a readback (any state); its resources are released.
void backendDeleteBuffer(u32 id) override
void backendUseProgram(u32 id) override
Definition GLDevice.cpp:927
std::vector< GfxUniformInfo > backendActiveUniforms(u32 program) override
bool recreateDevice() override
Backend half of recoverDevice: a working device again, with every id-to-native map and derived cache ...
Definition GLDevice.cpp:413
void backendInvalidatePipelineCache() override
void backendIntUniformSet(u32 program) override
void onDeviceLost() override
Release what only this backend can name, while the dead device is still the current one.
Definition GLDevice.cpp:371
void endRenderPass() override
Ends the current pass, restoring the default framebuffer.
void backendDeleteProgram(u32 id) override
Definition GLDevice.cpp:913
void setIndexBuffer(BufferHandle buffer) override
Binds the index buffer for subsequent indexed draws.
void backendResizeBuffer(u32 id, const BufferDesc &desc, const void *data) override
void backendDeleteTexture(u32 id) override
i32 getInt(GfxIntParam name) override
Queries a backend integer capability/limit.
u32 maxSamples() override
Most samples an offscreen colour attachment may carry; 1 = none.
void backendUpdateBuffer(u32 id, u32 offsetBytes, const void *data, u32 sizeBytes) override
bool backendCreateTexture(u32 id, const TextureDesc &desc, const void *pixels) override
bool supportsCompressedFormat(GfxCompressedFormat format) override
Reports whether the backend can sample the given compressed format.
bool backendCreateTimerQuery(u32 id) override
bool timerDisjoint() override
True when GPU timing was disturbed since the last check.
void setStencilReference(i32 ref) override
GL reads a framebuffer from the bottom up.
void drawElementsInstanced(u32 indexCount, GfxDataType indexType, u32 byteOffset, u32 instanceCount) override
Draws indexed triangles with instancing.
void backendGenerateMipmaps(u32 id) override
void drawElements(u32 indexCount, GfxDataType indexType, u32 byteOffset) override
Draws indexed triangles.
void captureDeviceIdentity() override
Records who this backend is, so a later loss report can name it.
Definition GLDevice.cpp:342
bool takeReadback(ReadbackHandle handle, void *dest, usize destSize) override
Copies a Ready readback's pixels (w*h*4 bytes) into dest and releases it.
void clearStencil(i32 value) override
Mid-pass stencil reset (the one clear that isn't a pass load-op).
u32 primitiveMode() const
bool backendCreateProgram(u32 id, const GfxShaderSource &source, const GfxAttribBinding *bindings, u32 bindingCount, std::string *outLog, GfxShaderStage *outFailedStage) override
Definition GLDevice.cpp:739
void endTimerQuery() override
Stops the active timer query.
ReadbackHandle requestReadback(FramebufferHandle target, u32 w, u32 h) override
Requests an RGBA8 readback of a framebuffer's color attachment.
u32 backendUniformBlockIndex(u32 program, const char *name) override
void shutdown() override
Shuts down the graphics device.
Definition GLDevice.cpp:487
void backendSetTextureParams(u32 id, const TextureDesc &desc) override
void setWireframe(bool enabled) override
Enables or disables wireframe rendering (desktop only).
bool backendCreateFramebuffer(u32 id, const FramebufferDesc &desc) override
bool backendAdoptTexture(u32 id, u32 nativeId, const TextureDesc &desc) override
Takes over a native texture the host created; false when this backend cannot.
void drawElementsInstancedMulti(GfxDataType indexType, const u32 *counts, const u32 *byteOffsets, const u32 *instanceCounts, u32 drawCount) override
drawCount indexed instanced draws through the bound pipeline and buffers, as one call where supportsM...
bool backendFinishProgram(u32 id) override
Waits for a deferred program, runs its onLinked callback; false when it failed to link....
Definition GLDevice.cpp:836
GfxReadbackStatus pollReadback(ReadbackHandle handle) override
The state of an in-flight readback; pumps backend completion events. A Failed readback is released by...
void backendUpdateTexture(u32 id, i32 x, i32 y, u32 width, u32 height, const void *pixels, bool flipY) override
std::string backendPendingProgramLabels() override
Definition GLDevice.cpp:884
bool getTimerQueryNs(u32 query, u64 *outNanoseconds) override
Fetches a completed query's elapsed nanoseconds; false while still pending.
void backendMoveTexture(u32 into, u32 from) override
Re-keys from's native texture under into; into holds none on entry.
void backendDeleteVertexLayout(u32 id) override
Drops what the backend derived from a layout (a GL VAO); the desc stays here.
bool supportsFloatTargets() override
Whether RGBA16F color attachments are renderable.
u32 backendPendingProgramCount() override
Definition GLDevice.cpp:871
u32 backendBoundSamplerUnits() override
Definition GLDevice.cpp:977
void bindTexture(u32 slot, TextureHandle texture) override
Activates a texture slot and binds a 2D texture.
void beginRenderPass(const RenderPassDesc &desc) override
Targets a framebuffer for subsequent draws and applies the pass's clears.
void drawArrays(u32 first, u32 vertexCount) override
Draws non-indexed triangles.
std::string getString(GfxStringName name) override
Queries a backend identification string (diagnostics).
ReadbackHandle captureNextFrame(u32 w, u32 h) override
void backendSetUniformBuffer(u32 slot, BufferHandle buffer, u32 offsetBytes, u32 sizeBytes) override
void backendSetPipeline(u32 id, const PipelineDesc &desc) override
bool backendCreateCompressedTexture(u32 id, const TextureDesc &desc, GfxCompressedFormat format, const void *data, u32 byteLength, u32 mipLevels) override
void setScissor(i32 x, i32 y, i32 w, i32 h) override
Sets the scissor rectangle.
Definition GLDevice.cpp:683
bool backendProgramReady(u32 id) override
Definition GLDevice.cpp:893
void endFrame() override
The frame is over — everything drawn for it has been submitted.
bool pollDeviceLost() override
Pumps backend-native loss detection.
Definition GLDevice.cpp:499
bool copyFramebufferColor(FramebufferHandle source, TextureHandle dst) override
i32 backendAttribLocation(u32 program, const char *name) override
Definition GLDevice.cpp:939
void setVertexBuffer(u32 slot, BufferHandle buffer, u32 offsetBytes) override
Binds a vertex buffer to a layout slot for subsequent draws.
u32 getError() override
Queries the last error.
i32 backendUniformLocation(u32 program, const char *name) override
The backend's own location this generation, -1 when absent.
Definition GLDevice.cpp:934
void setScissorTest(bool enabled) override
Enables or disables scissor test.
Definition GLDevice.cpp:676
bool markDeviceLost(GfxDeviceLostReason reason, std::string message={}, std::string context={})
The single transition into Lost. Backends call this on detection.
Definition GfxDevice.cpp:60
Viewport viewport_
Backends record what they were last handed; see viewport.
void invalidatePipelineCache()
Forces the next setPipeline to re-apply, dropping the cached current pipeline.
virtual void drawElementsInstancedMulti(GfxDataType indexType, const u32 *counts, const u32 *byteOffsets, const u32 *instanceCounts, u32 drawCount)
drawCount indexed instanced draws through the bound pipeline and buffers, as one call where supportsM...
const VertexLayoutDesc * vertexLayoutDesc(VertexLayoutHandle layout) const
A layout's description, or null for a handle that names none.
void notifyProgramLinked(u32 id)
For a backend finishing a deferred program: runs its onLinked callback, leaving the bound program as ...
bool isDeviceUsable() const
Whether work may be submitted — the one check the guards make.
void countDraw()
A backend has issued one draw (see takeDraws).
const FramebufferDesc * framebufferDesc(FramebufferHandle framebuffer) const
A framebuffer's description, or null for Default and unknown handles.
const BufferDesc * bufferDesc(BufferHandle buffer) const
A buffer's description as it stands, or null for a handle that names none.
const TextureDesc * textureDesc(TextureHandle texture) const
void setDeviceIdentity(std::string backend, std::string vendor, std::string renderer, std::string version)
Records the backend identity; see captureDeviceIdentity.
std::string floorConstantLoops(const std::string &src)
constexpr std::string_view kLoopFloorUniform
FramebufferHandle
Handle 0 is the default framebuffer (backbuffer); it cannot be created or deleted.
Definition GfxEnums.hpp:41
static constexpr u32 GFX_INVALID_UNIFORM_BLOCK
Sentinel returned by getUniformBlockIndex when a program has no such block (GL_INVALID_INDEX).
Definition GfxDevice.hpp:44
std::int32_t i32
Signed 32-bit integer.
Definition Types.hpp:54
@ MirroredRepeat
Tile with mirroring.
Definition GfxEnums.hpp:65
@ Repeat
Tile the texture.
Definition GfxEnums.hpp:63
@ ClampToEdge
Clamp to edge pixels.
Definition GfxEnums.hpp:64
GfxStringName
Backend identification strings.
Definition GfxEnums.hpp:509
std::uint64_t u64
Unsigned 64-bit integer.
Definition Types.hpp:47
@ ContextLost
The host took the context away (web webglcontextlost, surface teardown).
Definition GfxEnums.hpp:545
GfxStencilMode
Stencil behaviour baked into a pipeline. The reference value is dynamic (GfxDevice::setStencilReferen...
@ Test
Draw only INSIDE the mask: func Equal, op Keep.
@ Write
Write the reference where drawn (mask fill): func Always, op Replace, color write off.
@ Decrement
Restore the parent reference on leaving a nested mask.
@ Increment
Enter a nested mask only where the parent reference matches.
@ TestOutside
Draw only OUTSIDE it: func NotEqual, op Keep — a hole, not a window.
@ Off
No stencil test; full color write.
@ Zero
Retire a root mask without writing color.
std::size_t usize
Size type for indexing and sizes.
Definition Types.hpp:64
std::int16_t i16
Signed 16-bit integer.
Definition Types.hpp:52
@ Linear
Bilinear interpolation (smooth).
Definition GfxEnums.hpp:59
@ Nearest
No interpolation (pixelated look).
Definition GfxEnums.hpp:58
bool & glslMultiDraw()
Whether this process's GLSL mesh programs count through a run's entries by gl_DrawID.
GfxShaderStage
Which pipeline stage rejected a program during createProgram().
Definition GfxEnums.hpp:736
GfxCompressedFormat
GPU-compressed texture internal formats for createCompressedTexture.
Definition GfxEnums.hpp:326
@ ETC2_RGBA8_SRGB
GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC (core).
Definition GfxEnums.hpp:333
@ S3TC_DXT5
GL_COMPRESSED_RGBA_S3TC_DXT5_EXT (extension).
Definition GfxEnums.hpp:332
@ ETC2_RGB8
GL_COMPRESSED_RGB8_ETC2 (core).
Definition GfxEnums.hpp:327
@ S3TC_DXT5_SRGB
GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT (extension).
Definition GfxEnums.hpp:335
@ ASTC_8x8
GL_COMPRESSED_RGBA_ASTC_8x8_KHR (extension).
Definition GfxEnums.hpp:330
@ S3TC_DXT1
GL_COMPRESSED_RGBA_S3TC_DXT1_EXT (extension).
Definition GfxEnums.hpp:331
@ ASTC_4x4_SRGB
GL_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR (extension).
Definition GfxEnums.hpp:334
@ ETC2_RGBA8
GL_COMPRESSED_RGBA8_ETC2_EAC (core).
Definition GfxEnums.hpp:328
@ ASTC_4x4
GL_COMPRESSED_RGBA_ASTC_4x4_KHR (extension).
Definition GfxEnums.hpp:329
std::int8_t i8
Signed 8-bit integer.
Definition Types.hpp:50
GfxReadbackStatus
State of an in-flight readback. GL completes at request time (first poll reports Ready); WebGPU resol...
Definition GfxEnums.hpp:47
std::uint32_t u32
Unsigned 32-bit integer.
Definition Types.hpp:45
BlendMode
Predefined blend modes for rendering.
Definition BlendMode.hpp:22
std::uint8_t u8
Unsigned 8-bit integer.
Definition Types.hpp:41
std::int64_t i64
Signed 64-bit integer.
Definition Types.hpp:56
u32 gfxBytesPerPixel(GfxPixelFormat fmt)
Bytes one pixel occupies in the CALLER's upload buffer — the single source both backends size a read ...
Definition GfxEnums.hpp:299
static constexpr u32 MAX_VERTEX_BUFFER_SLOTS
Definition GfxEnums.hpp:218
static EstellaContext & ctx()
GfxBlockInfo gfxCompressedBlockInfo(GfxCompressedFormat fmt)
Definition GfxEnums.hpp:346
GfxIntParam
Backend integer capabilities/limits.
Definition GfxEnums.hpp:517
@ Lines
Every two indices a line segment: a mesh's edges, for a diagnostic view.
ReadbackHandle
An in-flight framebuffer readback (GfxDevice::requestReadback).
Definition GfxEnums.hpp:43
float f32
32-bit floating point
Definition Types.hpp:59
Immutable creation parameters of a GPU buffer.
Definition GfxEnums.hpp:403
GfxBufferUsage usage
Definition GfxEnums.hpp:404
Attachments of an offscreen render target. The attach point of depthStencil follows its texture's pix...
Definition GfxEnums.hpp:451
TextureHandle resolveColor2
Definition GfxEnums.hpp:468
TextureHandle resolveColor0
Definition GfxEnums.hpp:457
TextureHandle resolveDepthStencil
Definition GfxEnums.hpp:458
TextureHandle resolveColor1
Its single-sample twin, when the target is multisampled.
Definition GfxEnums.hpp:464
TextureHandle depthStencil
Definition GfxEnums.hpp:453
Vertex attribute location binding applied before a program is linked.
Definition GfxEnums.hpp:730
Block footprint of a compressed format, the single source both backends use to size each mip level's ...
Definition GfxEnums.hpp:341
A program's source pair, tagged with the language it is written in.
Definition GfxEnums.hpp:660
GfxShaderLanguage language
Definition GfxEnums.hpp:661
The last value a program was given for one uniform, replayed after a relink.
Immutable description of a draw pipeline. Equality keys the pipeline cache, so two draws with the sam...
bool colorWrite
False writes no colour, to either attachment: a depth-only pass, whose surfaces are then drawn again ...
VertexLayoutHandle vertexLayout
One render pass: a target, which attachments to clear on entry, and the clear values — full load-op s...
Definition GfxEnums.hpp:485
u32 clearH
Clear region size; 0 = the whole target.
Definition GfxEnums.hpp:493
i32 clearY
Clear region origin (pixels).
Definition GfxEnums.hpp:492
FramebufferHandle target
Definition GfxEnums.hpp:486
Immutable creation parameters of a 2D texture or 2D texture array.
Definition GfxEnums.hpp:414
TextureFilter minFilter
Definition GfxEnums.hpp:422
bool layered() const
An array or a volume: pixels given slice by slice, fixed at creation, never an attachment.
Definition GfxEnums.hpp:444
TextureFilter magFilter
Definition GfxEnums.hpp:423
GfxPixelFormat format
Definition GfxEnums.hpp:421
Describes how vertex-buffer bytes map to shader attributes.
Definition GfxEnums.hpp:235
GfxVertexAttribute attributes[MAX_VERTEX_ATTRIBUTES]
Definition GfxEnums.hpp:236
u32 strides[MAX_VERTEX_BUFFER_SLOTS]
Definition GfxEnums.hpp:238
bool instanceStep[MAX_VERTEX_BUFFER_SLOTS]
Definition GfxEnums.hpp:239