Estella 0.113.0
A fast 2D and 3D game engine powered by WebAssembly and ECS
Loading...
Searching...
No Matches
GfxDevice.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
7
8#include "./GfxDevice.hpp"
9#include "../../core/Log.hpp"
10
11#include <algorithm>
12#include <cstring>
13#include <utility>
14
15namespace esengine {
16
17namespace {
18
19bool isDepthFormat(GfxPixelFormat format) {
21}
22
28void patchImage(std::vector<u8>& image, u32 imageWidth, u32 imageHeight, u32 bpp,
29 i32 x, i32 y, u32 width, u32 height, const u8* pixels, bool flipY) {
30 if (x < 0 || y < 0 || static_cast<u32>(x) + width > imageWidth
31 || static_cast<u32>(y) + height > imageHeight) {
32 return;
33 }
34 const usize rowBytes = static_cast<usize>(width) * bpp;
35 for (u32 row = 0; row < height; ++row) {
36 const u32 source = flipY ? height - 1 - row : row;
37 std::memcpy(&image[(static_cast<usize>(y) + row) * imageWidth * bpp + static_cast<usize>(x) * bpp],
38 pixels + static_cast<usize>(source) * rowBytes, rowBytes);
39 }
40}
41
42std::vector<u8> uploadOrderImage(const TextureDesc& desc, const void* pixels) {
43 const u32 bpp = gfxBytesPerPixel(desc.format);
44 std::vector<u8> image(static_cast<usize>(desc.width) * desc.height * bpp * std::max(1u, desc.layers), 0);
45 if (pixels && desc.layered()) {
46 std::memcpy(image.data(), pixels, image.size());
47 } else if (pixels) {
48 patchImage(image, desc.width, desc.height, bpp, 0, 0, desc.width, desc.height,
49 static_cast<const u8*>(pixels), desc.flipY);
50 }
51 return image;
52}
53
54} // namespace
55
56// =============================================================================
57// Loss and recovery
58// =============================================================================
59
60bool GfxDevice::markDeviceLost(GfxDeviceLostReason reason, std::string message, std::string context) {
61 if (device_status_ != GfxDeviceStatus::Live && device_status_ != GfxDeviceStatus::Recovering) {
62 return false;
63 }
64 compute_job_open_ = false;
65 pending_compute_fence_ = kNoAsyncComputeFence;
66 device_status_ = GfxDeviceStatus::Lost;
67 device_info_.reason = reason;
68 device_info_.identity = identity_;
69 device_info_.message = std::move(message);
70 device_info_.context = std::move(context);
71 device_info_.frame = device_frame_;
73
74 // Every object is rebuilt by the next recovery, owed or not.
75 for (auto& [id, record] : registry_.buffers.all()) { record.realized = false; record.owed = false; }
76 for (auto& [id, record] : registry_.textures.all()) { record.realized = false; record.owed = false; }
77 for (auto& [id, record] : registry_.programs.all()) record.realized = false;
78 for (auto& [id, record] : registry_.computes.all()) record.realized = false;
79 for (auto& [id, record] : registry_.framebuffers.all()) record.realized = false;
80 for (auto& [id, record] : registry_.timerQueries.all()) record.realized = false;
81 owed_count_ = 0;
82 native_locations_.clear();
83 current_pipeline_ = PipelineHandle::Invalid;
84
85 if (device_lost_handler_) device_lost_handler_(device_info_);
86 return true;
87}
88
90 if (device_status_ == GfxDeviceStatus::Live || device_status_ == GfxDeviceStatus::Recovering) {
91 return true;
92 }
93 if (device_status_ == GfxDeviceStatus::Dead) return false;
94
95 device_status_ = GfxDeviceStatus::Recovering;
96 if (!recreateDevice()) {
97 device_status_ = GfxDeviceStatus::Lost;
98 return false;
99 }
100 ++device_generation_;
101 realizeRegistry();
102 if (device_status_ != GfxDeviceStatus::Recovering) return isDeviceUsable();
103 settleRecovery();
104 return true;
105}
106
107void GfxDevice::realizeRegistry() {
108 for (auto& [id, record] : registry_.programs.all()) {
109 std::vector<GfxAttribBinding> bindings;
110 bindings.reserve(record.attribBindings.size());
111 for (const auto& [index, name] : record.attribBindings) bindings.push_back({index, name.c_str()});
112 const GfxShaderSource source{record.language, record.vertex.c_str(), record.fragment.c_str()};
113 std::string log;
115 record.realized = backendCreateProgram(id, source, bindings.data(),
116 static_cast<u32>(bindings.size()), &log, &stage);
117 if (record.realized) {
118 realizeProgramState(id, record);
119 // A program that was queued and never waited for before the loss has linked now, and what was owed to it (its block bindings,
120 // its pinned samplers) is done here rather than when a draw first asks.
121 if (record.onLinked) notifyProgramLinked(id);
122 } else {
123 ES_LOG_ERROR("Device recovery: program {} did not rebuild: {}", id, log);
124 }
125 }
126
127 for (auto& [id, record] : registry_.computes.all()) {
128 const GfxComputeSource source{GfxShaderLanguage::WGSL, record.source.c_str(), record.entry.c_str()};
129 std::string log;
130 record.realized = backendCreateCompute(id, source, &log);
131 if (!record.realized) ES_LOG_ERROR("Device recovery: compute program {} did not rebuild: {}", id, log);
132 }
133
134 for (auto& [id, record] : registry_.buffers.all()) {
135 const bool hasBytes = !record.bytes.empty();
136 record.realized = backendCreateBuffer(id, record.desc, hasBytes ? record.bytes.data() : nullptr);
137 record.owed = record.realized && !hasBytes && record.content.kind() == GfxContentKind::Sourced;
138 if (record.owed) ++owed_count_;
139 if (record.content.kind() != GfxContentKind::Retained) dropBytes(record.bytes);
140 }
141
142 for (auto& [id, record] : registry_.textures.all()) {
143 const bool hasBytes = !record.bytes.empty();
144 if (record.compressed && hasBytes) {
145 record.realized = backendCreateCompressedTexture(
146 id, record.desc, record.compressedFormat, record.bytes.data(),
147 static_cast<u32>(record.bytes.size()), record.mipLevels);
148 } else {
149 TextureDesc desc = record.desc;
150 desc.flipY = false;
151 if (record.compressed) desc.format = GfxPixelFormat::RGBA8;
152 record.realized = backendCreateTexture(id, desc, hasBytes ? record.bytes.data() : nullptr);
153 }
154 record.owed = record.realized && !hasBytes && record.content.kind() == GfxContentKind::Sourced;
155 if (record.owed) ++owed_count_;
156 if (record.content.kind() != GfxContentKind::Retained) dropBytes(record.bytes);
157 if (!record.realized) ES_LOG_ERROR("Device recovery: texture {} did not rebuild", id);
158 }
159
160 for (auto& [id, record] : registry_.framebuffers.all()) {
161 record.realized = backendCreateFramebuffer(id, record.desc);
162 }
163 for (auto& [id, record] : registry_.timerQueries.all()) {
164 record.realized = backendCreateTimerQuery(id);
165 }
166}
167
168void GfxDevice::realizeProgramState(u32 id, GfxProgramRecord& record) {
169 const bool anyValue = std::any_of(record.uniformValues.begin(), record.uniformValues.end(),
170 [](const GfxUniformValue& v) { return v.type != GfxUniformValue::Type::None; });
171 if (anyValue) {
173 for (usize i = 0; i < record.uniformValues.size(); ++i) {
174 if (record.uniformValues[i].type == GfxUniformValue::Type::None) continue;
175 const i32 native = nativeUniformLocation(record, id, static_cast<i32>(i));
176 if (native >= 0) backendSetUniform(native, record.uniformValues[i]);
177 }
178 }
179 for (usize i = 0; i < record.blockNames.size(); ++i) {
180 if (record.blockBindings[i] == GFX_UNBOUND_BLOCK) continue;
181 const u32 native = backendUniformBlockIndex(id, record.blockNames[i].c_str());
182 if (native != GFX_INVALID_UNIFORM_BLOCK) {
183 backendUniformBlockBinding(id, native, record.blockBindings[i]);
184 }
185 }
186}
187
188void GfxDevice::settleRecovery() {
189 if (device_status_ != GfxDeviceStatus::Recovering || owed_count_ != 0) return;
190 device_status_ = GfxDeviceStatus::Live;
191 device_info_ = GfxDeviceLostInfo{};
193}
194
195void GfxDevice::payTexture(u32 id, GfxTextureRecord& record) {
196 ++texture_shapes_;
197 if (!record.owed) return;
198 record.owed = false;
199 record.revision = nextRevision();
200 --owed_count_;
201 if (record.desc.mipmaps && record.realized) backendGenerateMipmaps(id);
202 settleRecovery();
203}
204
207 if (auto* record = registry_.buffers.find(owed.id); record && record->owed) {
208 record->owed = false;
209 --owed_count_;
210 }
211 } else if (auto* record = registry_.textures.find(owed.id); record && record->owed) {
212 record->owed = false;
213 --owed_count_;
214 }
215 settleRecovery();
216}
217
220 if (auto* record = registry_.textures.find(owed.id); record && record->owed) {
221 payTexture(owed.id, *record);
222 }
223 return;
224 }
225 forgoContent(owed);
226}
227
228// =============================================================================
229// Kept bytes
230// =============================================================================
231
232void GfxDevice::keepBytes(std::vector<u8>& slot, std::vector<u8> bytes) {
233 retained_bytes_ -= slot.size();
234 retained_bytes_ += bytes.size();
235 const usize grownBy = bytes.size() > slot.size() ? bytes.size() - slot.size() : 0;
236 slot = std::move(bytes);
237 judgeRetainedBudget(grownBy);
238}
239
240void GfxDevice::dropBytes(std::vector<u8>& slot) {
241 retained_bytes_ -= slot.size();
242 slot = {};
243 judgeRetainedBudget(0);
244}
245
246std::vector<u8> GfxDevice::takeBytes(std::vector<u8>& slot) {
247 retained_bytes_ -= slot.size();
248 judgeRetainedBudget(0);
249 return std::exchange(slot, {});
250}
251
252void GfxDevice::judgeRetainedBudget(usize grownBy) {
253 if (retained_budget_ == 0 || retained_bytes_ <= retained_budget_) {
254 over_retained_budget_ = false;
255 return;
256 }
257 if (over_retained_budget_ || grownBy == 0) return;
258 over_retained_budget_ = true;
259 constexpr f64 MiB = 1024.0 * 1024.0;
260 ES_LOG_WARN("The graphics device keeps {:.2f} MiB of CPU copies to restore content after a GPU loss, "
261 "past its {:.2f} MiB budget (the last copy was {} bytes). Content that can be loaded "
262 "or drawn again should say who refills it instead of being retained.",
263 static_cast<f64>(retained_bytes_) / MiB, static_cast<f64>(retained_budget_) / MiB, grownBy);
264}
265
266void GfxDevice::eraseBuffer(u32 id) {
267 if (auto* record = registry_.buffers.find(id)) dropBytes(record->bytes);
268 registry_.buffers.erase(id);
269}
270
271void GfxDevice::eraseTexture(u32 id) {
272 if (auto* record = registry_.textures.find(id)) dropBytes(record->bytes);
273 registry_.textures.erase(id);
274}
275
276// =============================================================================
277// Buffers
278// =============================================================================
279
280BufferHandle GfxDevice::createBuffer(const BufferDesc& desc, GfxContent content, const void* initialData) {
281 if (device_status_ == GfxDeviceStatus::Dead) return BufferHandle::Invalid;
282 const bool usable = isDeviceUsable();
283 GfxBufferRecord record{desc, content};
284 if (content.kind() == GfxContentKind::Retained || (!usable && initialData)) {
285 std::vector<u8> bytes(desc.size, 0);
286 if (initialData && desc.size > 0) std::memcpy(bytes.data(), initialData, desc.size);
287 keepBytes(record.bytes, std::move(bytes));
288 }
289 const u32 id = registry_.buffers.insert(std::move(record));
290 if (!usable) return BufferHandle{id};
291 if (!backendCreateBuffer(id, desc, initialData)) {
292 eraseBuffer(id);
294 }
295 registry_.buffers.find(id)->realized = true;
296 return BufferHandle{id};
297}
298
300 const u32 id = static_cast<u32>(buffer);
301 auto* record = registry_.buffers.find(id);
302 if (!record) return;
303 if (record->realized) backendDeleteBuffer(id);
304 if (record->owed) --owed_count_;
305 eraseBuffer(id);
306 settleRecovery();
307}
308
309void GfxDevice::updateBuffer(BufferHandle buffer, u32 offsetBytes, const void* data, u32 sizeBytes) {
310 const u32 id = static_cast<u32>(buffer);
311 auto* record = registry_.buffers.find(id);
312 if (!record || !data || sizeBytes == 0) return;
313 countGeometryWrite(record->desc);
314 const bool whole = offsetBytes == 0 && sizeBytes >= record->desc.size;
315 if (!record->bytes.empty() && static_cast<usize>(offsetBytes) + sizeBytes <= record->bytes.size()) {
316 std::memcpy(record->bytes.data() + offsetBytes, data, sizeBytes);
317 } else if (!record->realized && whole) {
318 const auto* first = static_cast<const u8*>(data);
319 keepBytes(record->bytes, std::vector<u8>(first, first + record->desc.size));
320 }
321 if (record->realized) backendUpdateBuffer(id, offsetBytes, data, sizeBytes);
322 if (record->owed && whole) {
323 record->owed = false;
324 --owed_count_;
325 settleRecovery();
326 }
327}
328
329void GfxDevice::resizeBuffer(BufferHandle buffer, u32 sizeBytes, const void* data) {
330 const u32 id = static_cast<u32>(buffer);
331 auto* record = registry_.buffers.find(id);
332 if (!record) return;
333 countGeometryWrite(record->desc);
334 record->desc.size = sizeBytes;
335 if (record->content.kind() == GfxContentKind::Retained || (!record->realized && data)) {
336 std::vector<u8> bytes(sizeBytes, 0);
337 if (data && sizeBytes > 0) std::memcpy(bytes.data(), data, sizeBytes);
338 keepBytes(record->bytes, std::move(bytes));
339 } else {
340 dropBytes(record->bytes);
341 }
342 if (record->realized) backendResizeBuffer(id, record->desc, data);
343 if (record->owed && data) {
344 record->owed = false;
345 --owed_count_;
346 settleRecovery();
347 }
348}
349
351 const auto* record = registry_.buffers.find(static_cast<u32>(buffer));
352 return record ? &record->desc : nullptr;
353}
354
355// =============================================================================
356// Vertex layouts and pipelines
357// =============================================================================
358
360 if (device_status_ == GfxDeviceStatus::Dead || !backendAcceptsVertexLayout(desc)) {
362 }
363 return VertexLayoutHandle{registry_.layouts.insert(GfxLayoutRecord{desc})};
364}
365
367 const u32 id = static_cast<u32>(layout);
368 if (!registry_.layouts.find(id)) return;
370 registry_.layouts.erase(id);
371}
372
374 const auto* record = registry_.layouts.find(static_cast<u32>(layout));
375 return record ? &record->desc : nullptr;
376}
377
379 if (device_status_ == GfxDeviceStatus::Dead) return PipelineHandle::Invalid;
380 return PipelineHandle{registry_.internPipeline(desc)};
381}
382
384 const auto* record = registry_.pipelines.find(static_cast<u32>(handle));
385 return record ? &record->desc : nullptr;
386}
387
389 if (handle == PipelineHandle::Invalid) return;
390 const auto* record = registry_.pipelines.find(static_cast<u32>(handle));
391 if (!record) return;
392 current_pipeline_ = handle;
393 current_program_ = record->desc.program;
394 backendSetPipeline(static_cast<u32>(handle), record->desc);
395}
396
401
402// =============================================================================
403// Textures
404// =============================================================================
405
406TextureHandle GfxDevice::createTexture(const TextureDesc& desc, GfxContent content, const void* pixels) {
407 ++texture_shapes_;
408 if (device_status_ == GfxDeviceStatus::Dead) return TextureHandle::Invalid;
409 if (desc.layered() && (desc.samples > 1 || desc.storage || (desc.volume && desc.mipmaps) || isDepthFormat(desc.format))) {
410 ES_LOG_ERROR("GfxDevice::createTexture: a texture array or volume is sampled colour only");
412 }
413 const bool usable = isDeviceUsable();
414 GfxTextureRecord record{desc, content};
415 if (content.kind() == GfxContentKind::Retained && (desc.samples > 1 || isDepthFormat(desc.format))) {
416 ES_LOG_ERROR("GfxDevice::createTexture: an attachment-only texture cannot keep its contents");
417 } else if (content.kind() == GfxContentKind::Retained || (!usable && pixels)) {
418 keepBytes(record.bytes, uploadOrderImage(desc, pixels));
419 record.desc.flipY = false;
420 }
421 const u32 id = registry_.textures.insert(std::move(record));
422 if (!usable) return TextureHandle{id};
423 if (!backendCreateTexture(id, desc, pixels)) {
424 eraseTexture(id);
426 }
427 registry_.textures.find(id)->realized = true;
428 return TextureHandle{id};
429}
430
432 GfxCompressedFormat format, const void* data,
433 u32 byteLength, u32 mipLevels) {
434 ++texture_shapes_;
435 if (device_status_ == GfxDeviceStatus::Dead) return TextureHandle::Invalid;
436 const bool usable = isDeviceUsable();
437 GfxTextureRecord record{desc, content};
438 record.compressed = true;
439 record.compressedFormat = format;
440 record.mipLevels = mipLevels ? mipLevels : 1;
441 if (data && (content.kind() == GfxContentKind::Retained || !usable)) {
442 const auto* first = static_cast<const u8*>(data);
443 keepBytes(record.bytes, std::vector<u8>(first, first + byteLength));
444 }
445 const u32 id = registry_.textures.insert(std::move(record));
446 if (!usable) return TextureHandle{id};
447 if (!backendCreateCompressedTexture(id, desc, format, data, byteLength, mipLevels)) {
448 eraseTexture(id);
450 }
451 registry_.textures.find(id)->realized = true;
452 return TextureHandle{id};
453}
454
456 const void* data, u32 byteLength, u32 mipLevels) {
457 ++texture_shapes_;
458 const u32 id = static_cast<u32>(texture);
459 auto* record = registry_.textures.find(id);
460 if (!record || !isDeviceUsable()) return false;
461 if (record->realized) backendDeleteTexture(id);
462 record->compressed = true;
463 record->compressedFormat = format;
464 record->mipLevels = mipLevels ? mipLevels : 1;
465 if (record->content.kind() == GfxContentKind::Retained) {
466 const auto* first = static_cast<const u8*>(data);
467 keepBytes(record->bytes, std::vector<u8>(first, first + byteLength));
468 }
469 record->realized = backendCreateCompressedTexture(id, record->desc, format, data, byteLength, mipLevels);
470 record->revision = nextRevision();
471 if (record->realized) payTexture(id, *record);
472 return record->realized;
473}
474
476 ++texture_shapes_;
477 if (device_status_ == GfxDeviceStatus::Dead) return TextureHandle::Invalid;
478 if (content.kind() == GfxContentKind::Retained) {
479 ES_LOG_ERROR("GfxDevice::importExternalTexture: the device never saw these pixels to keep them");
481 }
482 const u32 id = registry_.textures.insert(GfxTextureRecord{desc, content});
483 registry_.textures.find(id)->externallyWritable = true;
484 if (!isDeviceUsable()) return TextureHandle{id};
485 if (!backendAdoptTexture(id, nativeId, desc)) {
486 eraseTexture(id);
488 }
489 registry_.textures.find(id)->realized = true;
490 return TextureHandle{id};
491}
492
494 ++texture_shapes_;
495 const u32 id = static_cast<u32>(texture);
496 auto* record = registry_.textures.find(id);
497 if (!record || !isDeviceUsable()) return false;
498 if (record->realized) backendDeleteTexture(id);
499 record->externallyWritable = true;
500 record->realized = backendAdoptTexture(id, nativeId, record->desc);
501 record->revision = nextRevision();
502 if (record->realized) payTexture(id, *record);
503 return record->realized;
504}
505
507 ++texture_shapes_;
508 const u32 intoId = static_cast<u32>(into);
509 const u32 fromId = static_cast<u32>(from);
510 auto* target = registry_.textures.find(intoId);
511 auto* source = registry_.textures.find(fromId);
512 if (!target || !source || intoId == fromId || !source->realized) return false;
513 if (target->content.kind() == GfxContentKind::Retained && source->bytes.empty()) {
514 ES_LOG_ERROR("GfxDevice::adoptTextureContent: texture {} keeps its bytes and {} has none to give",
515 intoId, fromId);
516 return false;
517 }
518 if (target->realized) backendDeleteTexture(intoId);
519 backendMoveTexture(intoId, fromId);
520
521 target->desc = source->desc;
522 target->externallyWritable |= source->externallyWritable;
523 target->compressed = source->compressed;
524 target->compressedFormat = source->compressedFormat;
525 target->mipLevels = source->mipLevels;
526 target->realized = true;
527 target->revision = nextRevision();
528 std::vector<u8> sourceBytes = takeBytes(source->bytes);
529 if (target->content.kind() == GfxContentKind::Retained) {
530 keepBytes(target->bytes, std::move(sourceBytes));
531 } else {
532 dropBytes(target->bytes);
533 }
534 if (source->owed) --owed_count_;
535 const bool owed = target->owed;
536 eraseTexture(fromId);
537 if (owed) {
538 target->owed = false;
539 --owed_count_;
540 }
541 settleRecovery();
542 return true;
543}
544
546 ++texture_shapes_;
547 const u32 id = static_cast<u32>(texture);
548 auto* record = registry_.textures.find(id);
549 if (!record) return;
550 if (record->realized) backendDeleteTexture(id);
551 if (record->owed) --owed_count_;
552 eraseTexture(id);
553 settleRecovery();
554}
555
556void GfxDevice::updateTexture(TextureHandle texture, i32 x, i32 y, u32 width, u32 height,
557 const void* pixels, bool flipY) {
558 const u32 id = static_cast<u32>(texture);
559 auto* record = registry_.textures.find(id);
560 if (!record || !pixels || record->compressed) return;
561 if (record->desc.layered()) {
562 ES_LOG_ERROR("GfxDevice::updateTexture: texture {} is an array or volume, whose slices are fixed at creation", id);
563 return;
564 }
565 const TextureDesc& desc = record->desc;
566 const bool whole = x == 0 && y == 0 && width >= desc.width && height >= desc.height;
567 if (!record->bytes.empty()) {
568 patchImage(record->bytes, desc.width, desc.height, gfxBytesPerPixel(desc.format),
569 x, y, width, height, static_cast<const u8*>(pixels), flipY);
570 } else if (!record->realized && whole) {
571 TextureDesc upload = desc;
572 upload.flipY = flipY;
573 keepBytes(record->bytes, uploadOrderImage(upload, pixels));
574 }
575 if (record->realized) backendUpdateTexture(id, x, y, width, height, pixels, flipY);
576 record->revision = nextRevision();
577 // An owed texture's chain is rebuilt when it is paid.
578 const bool rebuildChain = record->realized && desc.mipmaps && !record->owed;
579 if (whole) payTexture(id, *record);
580 if (rebuildChain) backendGenerateMipmaps(id);
581}
582
584 TextureWrap wrapS, TextureWrap wrapT) {
585 const u32 id = static_cast<u32>(texture);
586 auto* record = registry_.textures.find(id);
587 if (!record) return;
588 record->desc.minFilter = min;
589 record->desc.magFilter = mag;
590 record->desc.wrapS = wrapS;
591 record->desc.wrapT = wrapT;
592 record->revision = nextRevision();
593 if (record->realized) backendSetTextureParams(id, record->desc);
594}
595
597 const u32 id = static_cast<u32>(texture);
598 auto* record = registry_.textures.find(id);
599 if (!record) return;
600 record->desc.mipmaps = true;
601 record->revision = nextRevision();
602 if (record->realized) backendGenerateMipmaps(id);
603}
604
606 const auto* record = registry_.textures.find(static_cast<u32>(texture));
607 return record ? record->revision : 0;
608}
609
611 const auto* record = registry_.textures.find(static_cast<u32>(texture));
612 return record && record->realized && !record->desc.storage && !record->externallyWritable ? record->revision : 0;
613}
614
616 const auto* record = registry_.textures.find(static_cast<u32>(texture));
617 return record ? &record->desc : nullptr;
618}
619
620// =============================================================================
621// Programs
622// =============================================================================
623
625 const GfxAttribBinding* bindings, u32 bindingCount,
626 std::string* outLog, GfxShaderStage* outFailedStage) {
627 if (device_status_ == GfxDeviceStatus::Dead) {
628 if (outLog) *outLog = "device dead";
630 }
631 GfxProgramRecord record;
632 record.language = source.language;
633 record.vertex = source.vertexSrc ? source.vertexSrc : "";
634 record.fragment = source.fragmentSrc ? source.fragmentSrc : "";
635 for (u32 i = 0; i < bindingCount; ++i) {
636 record.attribBindings.emplace_back(bindings[i].index, bindings[i].name ? bindings[i].name : "");
637 }
638 const u32 id = registry_.programs.insert(std::move(record));
639 if (!isDeviceUsable()) return ShaderHandle{id};
640 if (!backendCreateProgram(id, source, bindings, bindingCount, outLog, outFailedStage)) {
641 registry_.programs.erase(id);
643 }
644 registry_.programs.find(id)->realized = true;
645 return ShaderHandle{id};
646}
647
648void GfxDevice::onProgramLinked(ShaderHandle program, std::function<void()> callback) {
649 const u32 id = static_cast<u32>(program);
650 auto* record = registry_.programs.find(id);
651 if (!record || !callback) return;
652 if (backendProgramPending(id)) {
653 record->onLinked = std::move(callback);
654 return;
655 }
656 callback();
657}
658
660 auto* record = registry_.programs.find(id);
661 if (!record || !record->onLinked) return;
662 auto callback = std::move(record->onLinked);
663 record->onLinked = nullptr;
664 // The callback binds programs of its own (a sampler is pinned through the bound one); the draw that waited for this one has it bound.
665 const ShaderHandle bound = current_program_;
666 callback();
667 current_program_ = bound;
668 backendUseProgram(registry_.programs.find(static_cast<u32>(bound)) ? static_cast<u32>(bound) : 0u);
669}
670
672 const u32 id = static_cast<u32>(program);
673 auto* record = registry_.programs.find(id);
674 if (!record) return;
675 if (record->realized) backendDeleteProgram(id);
676 registry_.programs.erase(id);
677 native_locations_.erase(id);
678 if (current_program_ == program) current_program_ = ShaderHandle::Invalid;
679}
680
681ComputeHandle GfxDevice::createCompute(const GfxComputeSource& source, std::string* outLog) {
682 if (device_status_ == GfxDeviceStatus::Dead) {
683 if (outLog) *outLog = "device dead";
685 }
686 if (!supportsCompute()) {
687 if (outLog) *outLog = "this device has no compute stage";
689 }
690 if (source.language != GfxShaderLanguage::WGSL || !source.source) {
691 if (outLog) *outLog = "compute is WGSL only";
693 }
694 GfxComputeRecord record;
695 record.source = source.source;
696 record.entry = source.entry ? source.entry : "main";
697 const u32 id = registry_.computes.insert(std::move(record));
698 if (!isDeviceUsable()) return ComputeHandle{id};
699 if (!backendCreateCompute(id, source, outLog)) {
700 registry_.computes.erase(id);
702 }
703 registry_.computes.find(id)->realized = true;
704 return ComputeHandle{id};
705}
706
708 const u32 id = static_cast<u32>(program);
709 auto* record = registry_.computes.find(id);
710 if (!record) return;
711 if (record->realized) backendDeleteCompute(id);
712 registry_.computes.erase(id);
713}
714
716 if (!enabled) manualComputeBarrier();
717 async_compute_enabled_ = enabled;
719}
720
722 if (compute_job_open_ || !supportsCompute() || !isDeviceUsable() || !backendComputeScopeAvailable()) return false;
724 if (!isDeviceUsable()) return false;
725 compute_job_open_ = true;
726 compute_priority_ = priority;
727 return true;
728}
729
731 if (!compute_job_open_) return kNoAsyncComputeFence;
732 compute_job_open_ = false;
733 return pending_compute_fence_;
734}
735
737 if (fence == kNoAsyncComputeFence || fence != pending_compute_fence_) return;
738 pending_compute_fence_ = kNoAsyncComputeFence;
740}
741
743 graphicsWaitOnAsyncComputeJob(pending_compute_fence_);
744}
745
746bool GfxDevice::dispatchCompute(ComputeHandle program, const GfxComputeBinding* bindings, u32 bindingCount,
747 u32 groupsX, u32 groupsY, u32 groupsZ) {
748 if (!supportsCompute() || !isDeviceUsable()) return false;
749 const u32 id = static_cast<u32>(program);
750 const auto* record = registry_.computes.find(id);
751 if (!record || !record->realized) return false;
752 if (groupsX == 0 || groupsY == 0 || groupsZ == 0) return false;
753 if (bindingCount > 0 && !bindings) return false;
755 if (compute_job_open_ && async_compute_enabled_ && supportsAsyncCompute() &&
756 next_compute_fence_ < INT32_MAX &&
757 backendDispatchAsyncCompute(compute_priority_, id, bindings, bindingCount, groupsX, groupsY, groupsZ)) {
758 pending_compute_fence_ = ++next_compute_fence_;
759 return true;
760 }
761 return isDeviceUsable() && backendDispatchCompute(id, bindings, bindingCount, groupsX, groupsY, groupsZ);
762}
763
765 const u32 id = static_cast<u32>(program);
766 current_program_ = program;
767 if (!isDeviceUsable()) return;
768 const auto* record = registry_.programs.find(id);
769 if (!record) {
771 } else if (record->realized) {
773 }
774}
775
776i32 GfxDevice::nativeUniformLocation(GfxProgramRecord& record, u32 id, i32 location) {
777 auto& natives = native_locations_[id];
778 if (natives.size() < record.uniformNames.size()) natives.resize(record.uniformNames.size(), -2);
779 i32& native = natives[static_cast<usize>(location)];
780 if (native == -2) native = backendUniformLocation(id, record.uniformNames[static_cast<usize>(location)].c_str());
781 return native;
782}
783
785 const u32 id = static_cast<u32>(program);
786 auto* record = registry_.programs.find(id);
787 if (!record || !name) return -1;
788 auto it = std::find(record->uniformNames.begin(), record->uniformNames.end(), name);
789 if (it != record->uniformNames.end()) {
790 return static_cast<i32>(it - record->uniformNames.begin());
791 }
792 if (record->realized && backendUniformLocation(id, name) < 0) return -1;
793 record->uniformNames.emplace_back(name);
794 record->uniformValues.emplace_back();
795 return static_cast<i32>(record->uniformNames.size() - 1);
796}
797
799 const u32 id = static_cast<u32>(program);
800 const auto* record = registry_.programs.find(id);
801 return record && record->realized ? backendAttribLocation(id, name) : -1;
802}
803
804void GfxDevice::setUniformValue(i32 location, const GfxUniformValue& value) {
805 const u32 id = static_cast<u32>(current_program_);
806 auto* record = registry_.programs.find(id);
807 if (!record || location < 0 || static_cast<usize>(location) >= record->uniformValues.size()) return;
808 record->uniformValues[static_cast<usize>(location)] = value;
810 if (!record->realized) return;
811 const i32 native = nativeUniformLocation(*record, id, location);
812 if (native >= 0) backendSetUniform(native, value);
813}
814
815void GfxDevice::setUniform1i(i32 location, i32 value) {
818 v.i = value;
819 setUniformValue(location, v);
820}
821
822void GfxDevice::setUniform1f(i32 location, f32 value) {
825 v.f[0] = value;
826 setUniformValue(location, v);
827}
828
829void GfxDevice::setUniform2f(i32 location, f32 x, f32 y) {
832 v.f[0] = x;
833 v.f[1] = y;
834 setUniformValue(location, v);
835}
836
837void GfxDevice::setUniform3f(i32 location, f32 x, f32 y, f32 z) {
840 v.f[0] = x;
841 v.f[1] = y;
842 v.f[2] = z;
843 setUniformValue(location, v);
844}
845
846void GfxDevice::setUniform4f(i32 location, f32 x, f32 y, f32 z, f32 w) {
849 v.f[0] = x;
850 v.f[1] = y;
851 v.f[2] = z;
852 v.f[3] = w;
853 setUniformValue(location, v);
854}
855
856void GfxDevice::setUniformMat3(i32 location, const f32* data) {
857 if (!data) return;
860 std::memcpy(v.f, data, 9 * sizeof(f32));
861 setUniformValue(location, v);
862}
863
864void GfxDevice::setUniformMat4(i32 location, const f32* data) {
865 if (!data) return;
868 std::memcpy(v.f, data, 16 * sizeof(f32));
869 setUniformValue(location, v);
870}
871
872std::vector<GfxUniformInfo> GfxDevice::getActiveUniforms(ShaderHandle program) {
873 const u32 id = static_cast<u32>(program);
874 auto* record = registry_.programs.find(id);
875 if (!record || !record->realized) return {};
876 std::vector<GfxUniformInfo> infos = backendActiveUniforms(id);
877 for (GfxUniformInfo& info : infos) {
878 const i32 native = info.location;
879 info.location = getUniformLocation(program, info.name.c_str());
880 if (info.location >= 0) {
881 auto& natives = native_locations_[id];
882 if (natives.size() < record->uniformNames.size()) natives.resize(record->uniformNames.size(), -2);
883 natives[static_cast<usize>(info.location)] = native;
884 }
885 }
886 return infos;
887}
888
890 const u32 id = static_cast<u32>(program);
891 auto* record = registry_.programs.find(id);
892 if (!record || !name) return GFX_INVALID_UNIFORM_BLOCK;
893 auto it = std::find(record->blockNames.begin(), record->blockNames.end(), name);
894 if (it != record->blockNames.end()) return static_cast<u32>(it - record->blockNames.begin());
895 if (record->realized && backendUniformBlockIndex(id, name) == GFX_INVALID_UNIFORM_BLOCK) {
897 }
898 record->blockNames.emplace_back(name);
899 record->blockBindings.push_back(GFX_UNBOUND_BLOCK);
900 return static_cast<u32>(record->blockNames.size() - 1);
901}
902
903void GfxDevice::uniformBlockBinding(ShaderHandle program, u32 blockIndex, u32 bindingPoint) {
904 const u32 id = static_cast<u32>(program);
905 auto* record = registry_.programs.find(id);
906 if (!record || blockIndex >= record->blockNames.size()) return;
907 record->blockBindings[blockIndex] = bindingPoint;
908 if (!record->realized) return;
909 const u32 native = backendUniformBlockIndex(id, record->blockNames[blockIndex].c_str());
910 if (native != GFX_INVALID_UNIFORM_BLOCK) backendUniformBlockBinding(id, native, bindingPoint);
911}
912
913// =============================================================================
914// Framebuffers and queries
915// =============================================================================
916
918 if (device_status_ == GfxDeviceStatus::Dead) return FramebufferHandle::Default;
919 for (TextureHandle attachment : {desc.color0, desc.color1, desc.color2, desc.depthStencil,
921 if (auto* texture = registry_.textures.find(static_cast<u32>(attachment))) texture->externallyWritable = true;
922 }
923 const u32 id = registry_.framebuffers.insert(GfxFramebufferRecord{desc});
924 if (!isDeviceUsable()) return FramebufferHandle{id};
925 if (!backendCreateFramebuffer(id, desc)) {
926 registry_.framebuffers.erase(id);
928 }
929 registry_.framebuffers.find(id)->realized = true;
930 return FramebufferHandle{id};
931}
932
934 const u32 id = static_cast<u32>(framebuffer);
935 auto* record = registry_.framebuffers.find(id);
936 if (!record) return;
937 if (record->realized) backendDeleteFramebuffer(id);
938 registry_.framebuffers.erase(id);
939}
940
942 const auto* record = registry_.framebuffers.find(static_cast<u32>(framebuffer));
943 return record ? &record->desc : nullptr;
944}
945
947 if (!isDeviceUsable()) return 0;
948 const u32 id = registry_.timerQueries.insert(GfxTimerQueryRecord{});
949 if (!backendCreateTimerQuery(id)) {
950 registry_.timerQueries.erase(id);
951 return 0;
952 }
953 registry_.timerQueries.find(id)->realized = true;
954 return id;
955}
956
958 if (!isDeviceUsable()) return 0;
959 u64 bytes = 0;
960 for (const auto& [id, buffer] : registry_.buffers.all()) {
961 if (buffer.realized) bytes += buffer.desc.size;
962 }
963 // Framebuffers reference these textures; counting attachments again doubles them.
964 for (const auto& [id, texture] : registry_.textures.all()) {
965 if (!texture.realized) continue;
966 u32 width = texture.desc.width, height = texture.desc.height;
967 if (!width || !height) continue;
968 const auto block = gfxCompressedBlockInfo(texture.compressedFormat);
969 const u32 levels = texture.compressed ? texture.mipLevels
970 : texture.desc.mipmaps && texture.desc.samples <= 1 && !isDepthFormat(texture.desc.format) ? 32 : 1;
971 for (u32 level = 0; level < levels; ++level) {
972 if (texture.compressed) {
973 bytes += ((static_cast<u64>(width) + block.blockWidth - 1) / block.blockWidth)
974 * ((static_cast<u64>(height) + block.blockHeight - 1) / block.blockHeight) * block.bytesPerBlock;
975 } else {
976 bytes += static_cast<u64>(width) * height * gfxBytesPerPixel(texture.desc.format)
977 * std::max(1u, texture.desc.samples) * std::max(1u, texture.desc.layers);
978 }
979 if (width == 1 && height == 1) break;
980 width = std::max(1u, width / 2); height = std::max(1u, height / 2);
981 }
982 }
983 return bytes;
984}
985
987 return GfxLiveObjects{
988 registry_.buffers.size(),
989 registry_.textures.size(),
990 registry_.programs.size(),
991 registry_.layouts.size(),
992 registry_.pipelines.size(),
993 registry_.framebuffers.size(),
995 };
996}
997
998} // namespace esengine
Abstract graphics device interface.
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
A content policy. provider names who refills a Sourced object and key what it refills; both are the p...
constexpr GfxContentKind kind() const
virtual bool backendAcceptsVertexLayout(const VertexLayoutDesc &desc)
False for a layout this backend has no way to express.
bool markDeviceLost(GfxDeviceLostReason reason, std::string message={}, std::string context={})
The single transition into Lost. Backends call this on detection.
Definition GfxDevice.cpp:60
void deleteCompute(ComputeHandle program)
Deletes a compute program.
void deleteVertexLayout(VertexLayoutHandle layout)
Deletes a vertex layout (no pipeline may reference it afterwards).
void updateTexture(TextureHandle texture, i32 x, i32 y, u32 width, u32 height, const void *pixels, bool flipY)
Uploads pixels to a sub-rectangle of a texture (transfer format from its desc).
virtual bool backendCreateBuffer(u32 id, const BufferDesc &desc, const void *data)=0
virtual bool backendCreateTexture(u32 id, const TextureDesc &desc, const void *pixels)=0
virtual bool backendCreateCompute(u32 id, const GfxComputeSource &source, std::string *outLog)
void setUniform3f(i32 location, f32 x, f32 y, f32 z)
Sets a vec3 uniform.
virtual void backendSetAsyncComputeEnabled(bool)
virtual i32 backendUniformLocation(u32 program, const char *name)=0
The backend's own location this generation, -1 when absent.
void uniformBlockBinding(ShaderHandle program, u32 blockIndex, u32 bindingPoint)
Links a program's uniform block to an indexed binding slot.
virtual bool supportsAsyncCompute() const
Hardware with an independent queue. Individual bindings can still require the graphics queue.
virtual void backendUseProgram(u32 id)=0
BufferHandle createBuffer(const BufferDesc &desc, GfxContent content, const void *initialData)
Creates a buffer with fixed capacity and optional initial contents.
i32 getUniformLocation(ShaderHandle program, const char *name)
Gets a uniform location by name, -1 when the linked program has none.
virtual void backendUpdateTexture(u32 id, i32 x, i32 y, u32 width, u32 height, const void *pixels, bool flipY)=0
void setUniform2f(i32 location, f32 x, f32 y)
Sets a vec2 uniform.
virtual bool backendCreateFramebuffer(u32 id, const FramebufferDesc &desc)=0
void invalidatePipelineCache()
Forces the next setPipeline to re-apply, dropping the cached current pipeline.
virtual u64 estimatedGpuBytes() const
void forgoContent(const GfxOwedContent &owed)
Gives up on one owed object's contents: it keeps its placeholder.
void setUniform4f(i32 location, f32 x, f32 y, f32 z, f32 w)
Sets a vec4 uniform.
void useProgram(ShaderHandle program)
Binds a program directly, for setup-time uniform seeding.
void generateMipmaps(TextureHandle texture)
Generates mipmaps for a texture.
virtual bool backendCreateTimerQuery(u32 id)=0
FramebufferHandle createFramebuffer(const FramebufferDesc &desc)
Creates a framebuffer from its attachments and validates completeness.
const VertexLayoutDesc * vertexLayoutDesc(VertexLayoutHandle layout) const
A layout's description, or null for a handle that names none.
u32 createTimerQuery()
Creates a GPU elapsed-time query, or 0 when the backend cannot time GPU work.
virtual bool recreateDevice()
Backend half of recoverDevice: a working device again, with every id-to-native map and derived cache ...
virtual void backendUpdateBuffer(u32 id, u32 offsetBytes, const void *data, u32 sizeBytes)=0
virtual void captureDeviceIdentity()
Records who this backend is, so a later loss report can name it.
TextureHandle importExternalTexture(u32 nativeId, const TextureDesc &desc, GfxContent content)
Adopts a texture a host created with the device's own API (a JS-side WebGL upload).
virtual bool backendCreateCompressedTexture(u32 id, const TextureDesc &desc, GfxCompressedFormat format, const void *data, u32 byteLength, u32 mipLevels)=0
AsyncComputeFence endAsyncComputeJob()
A fence for submitted work, or -1 when it is already ordered on the graphics queue.
virtual void backendUniformBlockBinding(u32 program, u32 nativeBlockIndex, u32 bindingPoint)=0
virtual void backendWaitAsyncCompute()
virtual void backendResizeBuffer(u32 id, const BufferDesc &desc, const void *data)=0
i32 getAttribLocation(ShaderHandle program, const char *name)
Gets a vertex attribute location by name (-1 if not found).
virtual void backendDeleteProgram(u32 id)=0
virtual void backendInvalidatePipelineCache()=0
virtual u32 backendReadbackCount() const =0
Readbacks in flight, the one live object the registry does not hold.
void notifyProgramLinked(u32 id)
For a backend finishing a deferred program: runs its onLinked callback, leaving the bound program as ...
virtual void backendMoveTexture(u32 into, u32 from)=0
Re-keys from's native texture under into; into holds none on entry.
virtual i32 backendAttribLocation(u32 program, const char *name)=0
std::vector< GfxUniformInfo > getActiveUniforms(ShaderHandle program)
Enumerates all active uniforms of a linked shader program.
u64 trackedTextureRevision(TextureHandle texture) const
Zero for content that can change without an upload, including render targets and host textures.
virtual bool backendProgramPending(u32 id) const
True while a program created with deferLink has not been waited for.
bool restoreCompressedTexture(TextureHandle texture, GfxCompressedFormat format, const void *data, u32 byteLength, u32 mipLevels)
Puts compressed contents back behind an owed texture's handle.
void restoreContent(const GfxOwedContent &owed)
Settles one owed object whose provider wrote its contents itself.
void deleteTexture(TextureHandle texture)
Deletes a texture.
virtual bool backendAdoptTexture(u32 id, u32 nativeId, const TextureDesc &desc)=0
Takes over a native texture the host created; false when this backend cannot.
virtual void backendGenerateMipmaps(u32 id)=0
void setAsyncComputeEnabled(bool enabled)
virtual bool backendComputeScopeAvailable() const
void setUniformMat3(i32 location, const f32 *data)
Sets a mat3 uniform.
bool isDeviceUsable() const
Whether work may be submitted — the one check the guards make.
virtual bool backendCreateProgram(u32 id, const GfxShaderSource &source, const GfxAttribBinding *bindings, u32 bindingCount, std::string *outLog, GfxShaderStage *outFailedStage)=0
void setUniform1f(i32 location, f32 value)
Sets a float uniform.
TextureHandle createTexture(const TextureDesc &desc, GfxContent content, const void *pixels)
Creates a 2D texture; uploads pixels (tightly packed, desc-sized) when non-null.
void setPipeline(PipelineHandle handle)
Binds a pipeline: applies its program, blend, depth, stencil compare/op and culling.
ComputeHandle createCompute(const GfxComputeSource &source, std::string *outLog=nullptr)
Compiles a compute program.
void graphicsWaitOnAsyncComputeJob(AsyncComputeFence fence)
virtual void backendSetUniform(i32 nativeLocation, const GfxUniformValue &value)=0
void setUniformMat4(i32 location, const f32 *data)
Sets a mat4 uniform.
u32 getUniformBlockIndex(ShaderHandle program, const char *name)
Returns a program's uniform-block index by name, or GFX_INVALID_UNIFORM_BLOCK if absent.
void deleteBuffer(BufferHandle buffer)
Deletes a buffer.
VertexLayoutHandle createVertexLayout(const VertexLayoutDesc &desc)
Registers an immutable vertex layout; pipelines reference it by handle.
virtual void backendSetTextureParams(u32 id, const TextureDesc &desc)=0
ShaderHandle createProgram(const GfxShaderSource &source, const GfxAttribBinding *bindings, u32 bindingCount, std::string *outLog, GfxShaderStage *outFailedStage)
Compiles and links a GPU program from GLSL sources.
virtual bool backendDispatchCompute(u32 id, const GfxComputeBinding *bindings, u32 bindingCount, u32 groupsX, u32 groupsY, u32 groupsZ)
virtual void onDeviceLost()
Release what only this backend can name, while the dead device is still the current one.
const FramebufferDesc * framebufferDesc(FramebufferHandle framebuffer) const
A framebuffer's description, or null for Default and unknown handles.
PipelineHandle createPipeline(const PipelineDesc &desc)
Resolves a pipeline description to a cached handle (creating it on first use).
const BufferDesc * bufferDesc(BufferHandle buffer) const
A buffer's description as it stands, or null for a handle that names none.
virtual void backendDeleteFramebuffer(u32 id)=0
void manualComputeBarrier()
Order dispatches across queues. Each inline dispatch is already a complete compute pass.
virtual void backendDeleteTexture(u32 id)=0
bool beginAsyncComputeJob(AsyncComputePriority priority=AsyncComputePriority::Default)
Opens a compute-only scope, including on single-queue devices. Scopes cannot nest.
virtual void backendSetPipeline(u32 id, const PipelineDesc &desc)=0
void setTextureParams(TextureHandle texture, TextureFilter min, TextureFilter mag, TextureWrap wrapS, TextureWrap wrapT)
Sets texture filtering and wrap parameters.
virtual bool supportsCompute() const
Whether this device runs compute shaders.
virtual void backendIntUniformSet(u32 program)
bool adoptTextureContent(TextureHandle into, TextureHandle from)
Moves from's storage and description behind into, and ends from.
bool restoreTextureFromNative(TextureHandle texture, u32 nativeId)
Replaces the native texture behind texture with one the host created again.
virtual bool backendDispatchAsyncCompute(AsyncComputePriority, u32, const GfxComputeBinding *, u32, u32, u32, u32)
u64 textureRevision(TextureHandle texture) const
A texture's description as it stands, or null for a handle that names none.
TextureHandle createCompressedTexture(const TextureDesc &desc, GfxContent content, GfxCompressedFormat format, const void *data, u32 byteLength, u32 mipLevels)
Creates a texture from pre-compressed GPU block data.
const PipelineDesc * pipelineDesc(PipelineHandle handle) const
A pipeline's description, or null for a handle that names none.
GfxLiveObjects liveObjects() const
GPU objects alive right now (see GfxLiveObjects), read off the registry.
void deleteFramebuffer(FramebufferHandle framebuffer)
Deletes a framebuffer (its attachment textures are owned by the caller).
virtual u32 backendUniformBlockIndex(u32 program, const char *name)=0
virtual void backendDeleteBuffer(u32 id)=0
bool recoverDevice()
Rebuilds the device and every object it issued, behind the same handles.
Definition GfxDevice.cpp:89
void updateBuffer(BufferHandle buffer, u32 offsetBytes, const void *data, u32 sizeBytes)
Updates a sub-range of a buffer; must fit within its capacity.
void resizeBuffer(BufferHandle buffer, u32 sizeBytes, const void *data)
Re-specifies a buffer's store with a new capacity, discarding prior contents.
const TextureDesc * textureDesc(TextureHandle texture) const
void setUniform1i(i32 location, i32 value)
Sets an integer uniform of the bound program.
virtual void backendDeleteCompute(u32 id)
void deleteProgram(ShaderHandle program)
Deletes a shader program.
bool dispatchCompute(ComputeHandle program, const GfxComputeBinding *bindings, u32 bindingCount, u32 groupsX, u32 groupsY=1, u32 groupsZ=1)
Runs program over groupsX x groupsY x groupsZ workgroups, with these resources bound.
virtual void backendDeleteVertexLayout(u32 id)=0
Drops what the backend derived from a layout (a GL VAO); the desc stays here.
virtual std::vector< GfxUniformInfo > backendActiveUniforms(u32 program)=0
void onProgramLinked(ShaderHandle program, std::function< void()> callback)
Runs callback when program has linked, once: now if it already has, at the first thing that needs it ...
GfxRecordTable< GfxProgramRecord > programs
FramebufferHandle
Handle 0 is the default framebuffer (backbuffer); it cannot be created or deleted.
Definition GfxEnums.hpp:41
constexpr AsyncComputeFence kNoAsyncComputeFence
Definition GfxEnums.hpp:25
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
AsyncComputePriority
Definition GfxEnums.hpp:23
std::int32_t i32
Signed 32-bit integer.
Definition Types.hpp:54
std::uint64_t u64
Unsigned 64-bit integer.
Definition Types.hpp:47
GfxDeviceLostReason
Why the device was lost. The report leads with this.
Definition GfxEnums.hpp:543
std::size_t usize
Size type for indexing and sizes.
Definition Types.hpp:64
ComputeHandle
A compute program (GfxDevice::createCompute); only a device that supportsCompute() issues one.
Definition GfxEnums.hpp:39
GfxShaderStage
Which pipeline stage rejected a program during createProgram().
Definition GfxEnums.hpp:736
PipelineHandle
Opaque handle to a cached pipeline; PipelineHandle{0} is the null/invalid handle.
GfxCompressedFormat
GPU-compressed texture internal formats for createCompressedTexture.
Definition GfxEnums.hpp:326
@ Dead
Unrecoverable — the renderer will not draw again this run.
Definition GfxEnums.hpp:539
@ Recovering
A replacement device is being built; old handles stay dead.
Definition GfxEnums.hpp:538
@ Live
Normal operation.
Definition GfxEnums.hpp:536
@ Lost
Every handle issued before is dead; submission has stopped.
Definition GfxEnums.hpp:537
std::uint32_t u32
Unsigned 32-bit integer.
Definition Types.hpp:45
std::uint8_t u8
Unsigned 8-bit integer.
Definition Types.hpp:41
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
double f64
64-bit floating point
Definition Types.hpp:61
i32 AsyncComputeFence
Definition GfxEnums.hpp:24
constexpr u32 GFX_UNBOUND_BLOCK
GfxBlockInfo gfxCompressedBlockInfo(GfxCompressedFormat fmt)
Definition GfxEnums.hpp:346
@ Retained
The device keeps the last bytes it was given and uploads them again.
@ Sourced
A provider outside the device refills it; until then it is owed.
u64 nextRevision()
A revision no content has had before. Never 0, which reads as "none".
Definition Revision.hpp:24
float f32
32-bit floating point
Definition Types.hpp:59
Immutable creation parameters of a GPU buffer.
Definition GfxEnums.hpp:403
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
std::vector< u8 > bytes
Retained content, or the initial bytes of a buffer created while the device was lost.
One resource a compute dispatch binds, at @group(0) @binding(binding).
Definition GfxEnums.hpp:689
A compute program's source. Compute is WGSL only: GLSL ES 3.00 has no compute stage.
Definition GfxEnums.hpp:673
GfxShaderLanguage language
Definition GfxEnums.hpp:674
const char * entry
The @compute entry point.
Definition GfxEnums.hpp:677
GPU objects the device has created and not yet destroyed.
Definition GfxDevice.hpp:57
A Sourced object that has storage again and is waiting for its contents.
std::vector< std::string > uniformNames
A location handed out is an index here; the backend's own is resolved per generation.
std::vector< GfxUniformValue > uniformValues
std::vector< std::string > blockNames
std::vector< std::pair< u32, std::string > > attribBindings
std::vector< u32 > blockBindings
Binding point per block name, or GFX_UNBOUND_BLOCK.
A program's source pair, tagged with the language it is written in.
Definition GfxEnums.hpp:660
GfxShaderLanguage language
Definition GfxEnums.hpp:661
GfxCompressedFormat compressedFormat
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...
Immutable creation parameters of a 2D texture or 2D texture array.
Definition GfxEnums.hpp:414
bool layered() const
An array or a volume: pixels given slice by slice, fixed at creation, never an attachment.
Definition GfxEnums.hpp:444
GfxPixelFormat format
Definition GfxEnums.hpp:421
Describes how vertex-buffer bytes map to shader attributes.
Definition GfxEnums.hpp:235