20#include <glm/gtc/type_ptr.hpp>
26#include <unordered_map>
30void RenderFrame::swapOverlayIn() {
31 if (overlay_swapped_)
return;
33 overlay_hold_ = std::make_unique<OverlayHold>(device_);
34 overlay_hold_->pool.init();
36 pool_.swap(overlay_hold_->pool);
37 std::swap(draw_list_, overlay_hold_->list);
39 draw_list_.copySettingsFrom(overlay_hold_->list);
40 overlay_swapped_ =
true;
43void RenderFrame::swapOverlayOut() {
44 if (!overlay_swapped_)
return;
45 pool_.swap(overlay_hold_->pool);
46 std::swap(draw_list_, overlay_hold_->list);
47 overlay_swapped_ =
false;
50void RenderFrame::resetOverlayContents() {
51 overlay_reset_pending_ =
false;
55 overlay_valid_ =
false;
60 if (overlay_active_ || !device_.isDeviceUsable())
return;
63 overlay_kept_ =
false;
64 overlay_reset_pending_ =
true;
65 overlay_would_keep_ =
false;
67 overlay_projection_ = projection;
72 overlay_active_ =
true;
77 draw_list_.setCullingMask(0xFFFFFFFFu);
78 draw_list_.setLayerlessVisible(
true);
88 mix(
static_cast<u32>(overlay_vp_x_));
89 mix(
static_cast<u32>(overlay_vp_y_));
97 mix(linear_color_ ? 1 : 0);
104 mix(batch_shader_id_);
106 if (!whole)
return h;
108 mix(retained_text_collected_ ? retained_text_.
revision() : 0);
111 if (screen_domain_) {
112 for (
const u32 id : *screen_domain_) domain +=
hash::combine(0x5bd1e995ull,
id);
113 mix(screen_domain_->size());
120bool RenderFrame::overlayRegistryMoved(
ecs::Registry& registry) {
121 const auto inDomain = [
this](
u32 id) {
return screen_domain_ && screen_domain_->count(
id) != 0; };
122 if (registry.anyComponentChangedSinceWhere(overlay_tick_, [&](Entity e) { return inDomain(e.id()); }))
return true;
125 const i32 count = registry.readEntityChanges(overlay_journal_, rows);
126 if (count < 0)
return true;
127 for (
i32 i = 0; i < count; ++i) {
128 const auto& row = rows[
static_cast<usize>(i)];
135 if (!overlay_active_ || !overlay_reset_pending_)
return false;
136 if (overlay_watched_ != registry.
identity()) {
137 overlay_watched_ = registry.
identity();
139 overlay_valid_ =
false;
141 overlay_registry_ = ®istry;
142 const bool segmentable = hostStill && retained_text_collected_ && overlay_passes_ == 1 && overlay_effect_ == 0
143 && screen_roots_ && screen_root_by_index_ && !screen_roots_->empty()
144 && !(segments_refused_ && segments_refused_roots_ == screenRootsHash());
145 if (segmentable)
return keepSegments(registry);
146 segments_trusted_ =
false;
147 retained_text_.takeChanged([](
u32) {});
150 const u64 key = overlayInputs(registry,
true);
151 if (!hostStill) why |= 1;
152 if (!overlay_valid_) why |= 2;
153 else if (key != overlay_key_) why |= 4;
154 if (overlay_passes_ > 1) why |= 8;
155 bool particles =
false;
156 if (screen_domain_ && !screen_domain_->empty()) {
158 if (screen_domain_->count(e.id()) != 0) particles =
true;
161 if (particles) why |= 32;
162 if (why == 0 && overlayRegistryMoved(registry)) why |= 16;
166 overlay_pending_key_ = key;
171 overlay_kept_ =
true;
172 overlay_reset_pending_ =
false;
173 overlay_tick_ = overlay_pending_tick_;
174 overlay_journal_ = overlay_pending_journal_;
175 ++overlay_kept_total_;
178 overlay_would_keep_ = why == 0;
179 resetOverlayContents();
184 if (!overlay_active_ || overlay_kept_)
return;
185 if (overlay_segmented_) {
187 processMasks(registry, overlay_projection_, overlay_vp_x_, overlay_vp_y_,
188 static_cast<i32>(overlay_vp_w_),
static_cast<i32>(overlay_vp_h_));
190 for (
auto& segment : segments_) {
191 if (!segment.dirty)
continue;
195 collectScreenOverlayInto(registry, segment.root);
200 if (overlay_reset_pending_) {
202 resetOverlayContents();
203 overlay_pending_key_ = 0;
205 overlay_pending_journal_ = -1;
213 processMasks(registry, overlay_projection_, overlay_vp_x_, overlay_vp_y_,
214 static_cast<i32>(overlay_vp_w_),
static_cast<i32>(overlay_vp_h_));
216 collectScreenOverlayInto(registry, 0);
220void RenderFrame::collectScreenOverlayInto(
ecs::Registry& registry,
u32 onlyRoot) {
221 auto ctx = makeContext();
222 ctx.view_projection = overlay_projection_;
240 for (
auto& plugin : plugins_) {
241 if (plugin->drawsScreenUI()) plugin->collect(collectCtx);
243 if (retained_text_collected_)
submitRetainedText(registry,
true, glm::value_ptr(overlay_projection_), onlyRoot);
244 stats_.culled += collectCtx.
culled;
247void RenderFrame::drawScreenOverlay() {
248 context_.updateCameraConstants(overlay_projection_);
251 draw_list_.execute(device_, pool_, context_.materials(), context_.getWhiteTextureId(),
252 &frame_capture_, context_.perDrawBlocks());
254 device_.invalidatePipelineCache();
255 device_.setScissorTest(
false);
259#ifdef ES_ENABLE_POSTPROCESS
260 if (!post_process_ || width_ == 0 || height_ == 0)
return false;
262 releaseOverlayBackdrop();
265 desc.height = height_;
268 FramebufferSpec spec;
270 spec.height = height_;
271 spec.depthStencil =
false;
272 spec.linearFilter =
true;
275 overlay_grab_w_ = width_;
276 overlay_grab_h_ = height_;
279 if (!device_.copyFramebufferColor(source, overlay_grab_))
return false;
281 device_.invalidatePipelineCache();
282 device_.setScissorTest(
false);
283 graph_.begin(width_, height_);
285 copy.name =
"screen-ui-grab";
286 copy.reads = {graph_.importTexture(overlay_grab_, width_, height_)};
287 copy.write = graph_.importTarget(overlay_backdrop_->handle(), width_, height_);
288 copy.execute = [
this](
const rg::PassContext&) { post_process_->grabScene(); };
289 graph_.addPass(std::move(copy));
290 executeOverlayGraph();
291 device_.endRenderPass();
292 device_.generateMipmaps(overlay_backdrop_->getColorAttachment());
293 device_.invalidatePipelineCache();
301void RenderFrame::executeOverlayGraph() {
302 rg::PassTimer* timer = gpu_frame_open_ && gpu_frame_passes_ ? pass_timer_.get() :
nullptr;
303 graph_.setPassTimer(timer);
305 graph_.setPassTimer(
nullptr);
308void RenderFrame::releaseOverlayBackdrop() {
311 overlay_backdrop_.reset();
312 overlay_grab_w_ = overlay_grab_h_ = 0;
316 if (!overlay_active_)
return;
317 overlay_effect_ = material;
318 draw_list_.setLayerlessVisible(material == 0);
322 if (!overlay_active_)
return;
323 if (overlay_segmented_) {
324 endSegmentedOverlay(target);
330 ~SwapBack() { frame.swapOverlayOut(); }
332 overlay_active_ =
false;
333 const u32 effect = overlay_effect_;
335 draw_list_.setLayerlessVisible(
true);
336 const bool kept = overlay_kept_;
337 overlay_kept_ =
false;
338 if (overlay_reset_pending_) {
340 resetOverlayContents();
341 overlay_pending_key_ = 0;
347 if (!device_.isDeviceUsable()) {
348 overlay_valid_ =
false;
354 std::unordered_map<u32, u32> shown;
355 draw_list_.remapPrograms([&](
u32 program) {
356 auto it = shown.find(program);
357 if (it == shown.end()) it = shown.emplace(program,
displayProgram(program)).first;
363 draw_list_.finalize(pool_);
367 overlay_valid_ = overlay_pending_key_ != 0;
368 overlay_key_ = overlay_pending_key_;
369 overlay_tick_ = overlay_pending_tick_;
370 overlay_journal_ = overlay_pending_journal_;
371 if (overlay_valid_) {
374 const auto layout =
static_cast<LayoutId>(l);
375 const u32 bytes = pool_.vertexBytesUsed(layout);
377 const u32 indices = pool_.indicesUsed(layout);
380 if (overlay_would_keep_ && content != overlay_content_) {
382 if (!warned_overlay_stale_) {
383 warned_overlay_stale_ =
true;
384 ES_LOG_WARN(
"change audit: the screen overlay would have been held while what it draws had changed");
387 overlay_content_ = content;
390 overlay_would_keep_ =
false;
394 if (draw_list_.commandCount() == 0)
return;
397 accumulateStats(draw_list_);
398 tallyPass(draw_list_);
402 if (
auto* rt = target_manager_.get(target)) fbo = rt->getFramebuffer();
405 device_.invalidatePipelineCache();
406 device_.setScissorTest(
false);
408 bool layered =
false;
409 bool backdrop =
false;
410#ifdef ES_ENABLE_POSTPROCESS
411 layered = effect != 0 && post_process_ && post_process_->canDrawMaterialOver(effect);
412 if (draw_list_.anyUsesScreenColor(context_.materials())
413 || (layered && context_.materials().usesScreenColor(effect))) {
415 backdrop = grabOverlayBackdrop(fbo);
420 draw_list_.setDeferScreenColor(
false);
421 draw_list_.setLayerAlpha(layered);
425 graph_.begin(width_, height_);
427 pass.
name = layered ?
"screen-ui-layer" :
"screen-ui";
428 pass.
viewportX =
static_cast<u32>(std::max(overlay_vp_x_, 0));
429 pass.
viewportY =
static_cast<u32>(std::max(overlay_vp_y_, 0));
436 layer = graph_.createTarget(desc);
442 pass.
write = graph_.importTarget(fbo, width_, height_);
446 if (layered) device_.clearStencil(0);
447 context_.materials().setScreenColor(behind);
451 graph_.addPass(std::move(pass));
452#ifdef ES_ENABLE_POSTPROCESS
455 compose.name =
"screen-ui-effect";
456 compose.reads = {layer};
457 compose.write = graph_.importTarget(fbo, width_, height_);
458 compose.clear =
false;
460 context_.materials().setScreenColor(behind);
461 post_process_->drawMaterialOver(effect);
464 graph_.addPass(std::move(compose));
467 executeOverlayGraph();
468 draw_list_.setLayerAlpha(
false);
470 device_.endRenderPass();
471 device_.invalidatePipelineCache();
472 runPendingReplay(overlay_projection_, overlay_vp_w_, overlay_vp_h_);
479u32 RenderFrame::screenRootAt(
u32 entity)
const {
480 if (!screen_root_by_index_)
return 0;
482 return index < screen_root_by_index_->size() ? (*screen_root_by_index_)[index] : 0;
485u64 RenderFrame::screenRootsHash()
const {
487 if (screen_roots_)
for (
const u32 root : *screen_roots_) h =
hash::combine(h, root);
491void RenderFrame::segmentIn(OverlaySegment& segment) {
493 segment.hold = std::make_unique<OverlayHold>(device_);
494 segment.hold->pool.init();
496 pool_.swap(segment.hold->pool);
497 std::swap(draw_list_, segment.hold->list);
499 draw_list_.copySettingsFrom(overlay_hold_->list);
502void RenderFrame::segmentOut(OverlaySegment& segment) {
503 pool_.swap(segment.hold->pool);
504 std::swap(draw_list_, segment.hold->list);
513 overlay_segmented_ =
true;
514 overlay_reset_pending_ =
false;
518 std::vector<OverlaySegment> next;
519 next.reserve(screen_roots_->size());
520 for (
const u32 root : *screen_roots_) {
521 OverlaySegment segment;
522 for (
auto& held : segments_) {
523 if (held.root == root && held.hold) { segment = std::move(held);
break; }
526 next.push_back(std::move(segment));
528 std::vector<std::unique_ptr<OverlayHold>> spare;
529 for (
auto& left : segments_)
if (left.hold) spare.push_back(std::move(left.hold));
530 for (
auto& segment : next) {
531 if (segment.hold || spare.empty())
continue;
532 segment.hold = std::move(spare.back());
535 for (
auto& hold : spare) hold->pool.shutdown();
536 segments_ = std::move(next);
538 std::unordered_map<u32, usize> index;
539 index.reserve(segments_.size());
540 for (
usize i = 0; i < segments_.size(); ++i) index.emplace(segments_[i].root, i);
541 const auto inDomain = [
this](
u32 id) {
return screen_domain_ && screen_domain_->count(
id) != 0; };
542 const auto mark = [&](
u32 id) {
543 if (!inDomain(
id))
return;
544 const auto found = index.find(screenRootAt(
id));
545 if (found != index.end()) segments_[found->second].dirty =
true;
548 const u64 key = overlayInputs(registry,
false);
549 const bool fresh = !segments_trusted_ || key != segments_key_;
550 std::vector<u64> domains(segments_.size(), 0);
551 std::vector<u64> counts(segments_.size(), 0);
552 if (screen_domain_) {
553 for (
const u32 id : *screen_domain_) {
554 const auto found = index.find(screenRootAt(
id));
555 if (found == index.end())
continue;
557 ++counts[found->second];
560 for (
usize i = 0; i < segments_.size(); ++i) {
561 auto& segment = segments_[i];
563 segment.dirty = fresh || !segment.valid || segment.domain != domain;
564 segment.domain = domain;
568 registry.anyComponentChangedSinceWhere(segments_tick_, [&](Entity e) { mark(e.id());
return false; });
570 const i32 count = registry.readEntityChanges(segments_journal_, rows);
571 if (count < 0) every =
true;
572 for (
i32 i = 0; i < count && !every; ++i) {
573 const auto& row = rows[
static_cast<usize>(i)];
575 else mark(row.entity);
578 if (!retained_text_.takeChanged(mark)) every =
true;
579 if (screen_domain_ && !screen_domain_->empty()) {
580 registry.each<ecs::ParticleEmitter>([&](Entity e, ecs::ParticleEmitter&) { mark(e.id()); });
582 const bool audit = registry.changeAuditEnabled();
583 overlay_segments_rebuilt_ = 0;
584 for (
auto& segment : segments_) {
585 if (every) segment.dirty =
true;
586 segment.wouldKeep = !segment.dirty;
587 if (audit) segment.dirty =
true;
588 if (segment.dirty) ++overlay_segments_rebuilt_;
593 segments_tick_ = registry.beginChangeRead();
594 segments_journal_ = registry.entityChangeSequence();
595 segments_trusted_ =
true;
596 overlay_why_ = overlay_segments_rebuilt_ ? 64u : 0u;
597 if (overlay_segments_rebuilt_ == 0) {
598 overlay_kept_ =
true;
599 ++overlay_kept_total_;
606 overlay_active_ =
false;
607 overlay_segmented_ =
false;
609 const bool kept = overlay_kept_;
610 overlay_kept_ =
false;
617 if (!kept) overlay_rebuilt_last_ = overlay_segments_rebuilt_;
619 if (!device_.isDeviceUsable()) {
620 segments_trusted_ =
false;
626 for (
auto& segment : segments_) {
627 if (!segment.dirty)
continue;
630 std::unordered_map<u32, u32> shown;
631 draw_list_.remapPrograms([&](
u32 program) {
632 auto it = shown.find(program);
633 if (it == shown.end()) it = shown.emplace(program,
displayProgram(program)).first;
637 draw_list_.finalize(pool_);
641 const auto layout =
static_cast<LayoutId>(l);
642 const u32 bytes = pool_.vertexBytesUsed(layout);
644 const u32 indices = pool_.indicesUsed(layout);
647 if (segment.wouldKeep && segment.valid && content != segment.content) {
649 if (!warned_overlay_stale_) {
650 warned_overlay_stale_ =
true;
651 ES_LOG_WARN(
"change audit: a screen root's overlay segment would have been held while what it draws had changed");
654 segment.content = content;
655 segment.valid =
true;
656 segment.dirty =
false;
666 for (
auto& segment : segments_) {
668 if (!segment.hold || !segment.hold->list.sortKeyRange(lo, hi))
continue;
669 if ((any && lo <= previous) || segment.hold->list.anyUsesScreenColor(context_.materials())) ordered =
false;
673 if (!ordered && overlay_registry_) {
674 segments_refused_ =
true;
675 segments_refused_roots_ = screenRootsHash();
676 segments_trusted_ =
false;
678 resetOverlayContents();
679 collectScreenOverlayInto(*overlay_registry_, 0);
680 overlay_pending_key_ = 0;
681 overlay_would_keep_ =
false;
682 overlay_active_ =
true;
689 for (
auto& segment : segments_)
if (segment.hold) commands += segment.hold->list.commandCount();
690 if (commands == 0)
return;
692 for (
auto& segment : segments_) {
693 if (!segment.hold)
continue;
694 accumulateStats(segment.hold->list);
695 tallyPass(segment.hold->list);
696 segment.hold->list.setDeferScreenColor(
false);
697 segment.hold->list.setLayerAlpha(
false);
702 if (
auto* rt = target_manager_.get(target)) fbo = rt->getFramebuffer();
704 device_.invalidatePipelineCache();
705 device_.setScissorTest(
false);
708 graph_.begin(width_, height_);
710 pass.name =
"screen-ui";
711 pass.viewportX =
static_cast<u32>(std::max(overlay_vp_x_, 0));
712 pass.viewportY =
static_cast<u32>(std::max(overlay_vp_y_, 0));
713 pass.viewportW = overlay_vp_w_;
714 pass.viewportH = overlay_vp_h_;
715 pass.write = graph_.importTarget(fbo, width_, height_);
717 pass.execute = [
this](
const rg::PassContext&) {
719 context_.updateCameraConstants(overlay_projection_);
722 for (
auto& segment : segments_) {
723 if (!segment.hold || segment.hold->list.commandCount() == 0)
continue;
724 segment.hold->list.execute(device_, segment.hold->pool, context_.materials(), context_.getWhiteTextureId(),
725 &frame_capture_, context_.perDrawBlocks());
727 device_.invalidatePipelineCache();
728 device_.setScissorTest(
false);
730 graph_.addPass(std::move(pass));
731 executeOverlayGraph();
732 device_.endRenderPass();
733 device_.invalidatePipelineCache();
734 runPendingReplay(overlay_projection_, overlay_vp_w_, overlay_vp_h_);
739 if (!draw || !draw->
hasDeferred() || !device_.isDeviceUsable() || vpW == 0 || vpH == 0)
return;
743 if (
auto* rt = target_manager_.get(target)) fbo = rt->getFramebuffer();
750 device_.invalidatePipelineCache();
751 device_.setScissorTest(
false);
752 graph_.begin(width_, height_);
754 pass.
name =
"over-screen";
759 pass.
write = graph_.importTarget(fbo, width_, height_);
762 context_.updateCameraConstants(viewProjection);
765 graph_.addPass(std::move(pass));
767 device_.endRenderPass();
768 device_.invalidatePipelineCache();
Per-frame CPU scope timing (ES_PROFILE_SCOPE) read by the editor profiler.
#define ES_PROFILE_SCOPE(name)
#define ES_PROFILE_COUNTER(name, value)
Logging utilities for ESEngine.
#define ES_LOG_WARN(...)
Logs a warning message.
Frame resources and the shared scene rendering contract.
Central resource management system.
static Unique< Framebuffer > create(GfxDevice &device, const FramebufferSpec &spec)
Creates a framebuffer from specification.
static constexpr GfxContent transient()
u64 textureShapes() const
Counts every texture made, deleted, or given new storage under its handle (a restore,...
u64 deviceGeneration() const
Which generation of the device the live GPU objects belong to.
u64 revision() const
Changes whenever any material does (revisionOf), or one is added or removed.
MaterialStore & materials()
The engine-side material registry (handle -> resolved render state).
void submitScreenOverlay(ecs::Registry ®istry)
Collects the screen's renderables. Between this and endScreenOverlay a host may submit its own screen...
void processMasks(ecs::Registry ®istry, i32 vpX, i32 vpY, i32 vpW, i32 vpH)
void endScreenOverlay(RenderTargetManager::Handle target)
void drawOverScreen(i32 vpX, i32 vpY, u32 vpW, u32 vpH, RenderTargetManager::Handle target)
Draws the immediate geometry collected since the screen overlay over everything the frame shows,...
bool keepScreenOverlay(ecs::Registry ®istry, bool hostStill)
Asked after beginScreenOverlay and the layers: true, and the host submits nothing and endScreenOverla...
u32 displayProgram(u32 program)
void submitRetainedText(ecs::Registry ®istry, bool screen, const f32 *projection, u32 onlyRoot=0)
Every retained label laid out for one domain into the open list, culled against projection (world,...
u32 batchProgram(BatchVariant variant)
RenderFrame(GfxDevice &device, RenderContext &context, resource::ResourceManager &resource_manager)
void beginScreenOverlay(const glm::mat4 &projection, i32 vpX, i32 vpY, u32 vpW, u32 vpH)
Opens the overlay: projection maps the layout domain onto the pixel rect vpX/vpY/vpW/vpH of the surfa...
void setScreenOverlayEffect(u32 material)
static constexpr Handle INVALID_HANDLE
u64 revision() const
Moves with every label laid out, given glyphs or let go: what a pass drawn from the store was drawn f...
Central container for all entities and components.
double entityChangeSequence() const
void each(Func &&func)
Executes a function for each entity with specified components.
u32 beginChangeRead()
For a reader about to look: the tick it is looking at, after which the clock moves on.
u64 identity() const
Which registry this is, never shared with another made in this process (a registry assigned over this...
bool changeAuditEnabled() const
u64 textureMetadataRevision() const
Moves whenever a texture's metadata (its nine-slice borders and the rest) is set or dropped.
u64 meshesRevision() const
Changes whenever any mesh is realized (each takes a new Mesh::revision) or released: while it holds,...
static constexpr u32 ENTITY_CHANGE_CAPACITY
static constexpr u32 ENTITY_CHANGE_RESET
constexpr u64 combine(u64 h, u64 v)
constexpr u64 kFnv64Offset
u64 combineWords(u64 h, const void *data, usize bytes)
constexpr ResourceId kNoResource
FramebufferHandle
Handle 0 is the default framebuffer (backbuffer); it cannot be created or deleted.
std::int32_t i32
Signed 32-bit integer.
std::uint64_t u64
Unsigned 64-bit integer.
std::size_t usize
Size type for indexing and sizes.
constexpr Entity INVALID_ENTITY
Invalid entity sentinel value.
static constexpr u32 LAYOUT_COUNT
std::uint32_t u32
Unsigned 32-bit integer.
CameraView computeCameraView(const glm::mat4 &viewProjection)
LayoutId
Identifies a transient vertex stream / vertex format. Each layout has its own VBO+EBO+VAO in Transien...
static EstellaContext & ctx()
Entity identifier with packed index + generation.
constexpr u32 id() const
Returns the raw packed value for FFI serialization.
static constexpr Entity fromRaw(u32 v)
Reconstructs an Entity from a raw packed value.
constexpr u32 index() const
Gets the entity index.
void extractFromMatrix(const glm::mat4 &vp)
u32 only_root
Nonzero: this collect is one screen root's, and an entity of the domain under any other root is not i...
u32 culled
How many renderables this collect's frustum rejected.
const std::vector< u32 > * screen_root_by_index
With only_root: by entity index, the screen root each entity of the domain draws under (ecs::UISystem...
const std::unordered_map< u32, i32 > * ui_tree_layers
The layer of each emitter and plain Sprite a Canvas holds, by entity id, or null.
const std::unordered_set< u32 > * screen_ui
The entities the SCREEN owns (UISystem::screenDomain), or null.
std::function< void(const PassContext &)> execute
u32 viewportX
The rect of its target this pass draws into. Zero width = all of it.
Shape of a target the graph allocates.