Estella 0.113.0
A fast 2D and 3D game engine powered by WebAssembly and ECS
Loading...
Searching...
No Matches
RenderFrame.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#include "./RenderFrame.hpp"
8#ifdef ES_ENABLE_GPU_PARTICLES
9#include "./GpuParticles.hpp"
10#endif
11#include "../rhi/Shader.hpp"
29#include "../../core/Log.hpp"
31#include "../../core/Hash.hpp"
32
33#include <glm/gtc/matrix_transform.hpp>
34#include <glm/gtc/type_ptr.hpp>
35#include "../RenderOrigin.hpp"
36
37#include <algorithm>
38#ifdef __EMSCRIPTEN__
39#include <emscripten.h>
40#endif
41#include <cmath>
42#include <cstring>
43#include <limits>
44#include <utility>
45#include <vector>
46
47namespace esengine {
48
49glm::vec3 srgbToLinearCpu(const glm::vec3& c);
50
52 if (state_ == 0) {
53 // Lazy probe: the device reports timer support by whether it can create a query.
54 queries_[0] = device.createTimerQuery();
55 if (queries_[0] != 0) {
56 for (int i = 1; i < kRing; ++i) queries_[i] = device.createTimerQuery();
57 state_ = 1;
58 } else {
59 state_ = 2;
60 }
61 }
62 if (state_ != 1 || inflight_[write_]) return;
63 device.beginTimerQuery(queries_[write_]);
64 active_ = true;
65}
66
67void GpuTimer::end(GfxDevice& device) {
68 if (!active_) return;
69 device.endTimerQuery();
70 inflight_[write_] = true;
71 write_ = (write_ + 1) % kRing;
72 active_ = false;
73}
74
76 if (state_ != 1) return;
77 if (device.timerDisjoint()) { // timing disturbed — drop everything in flight
78 for (int i = 0; i < kRing; ++i) inflight_[i] = false;
79 read_ = write_;
80 return;
81 }
82 while (inflight_[read_]) {
83 u64 ns = 0;
84 if (!device.getTimerQueryNs(queries_[read_], &ns)) break;
85 last_ms_ = static_cast<f32>(ns) / 1.0e6f;
86 inflight_[read_] = false;
87 read_ = (read_ + 1) % kRing;
88 }
89}
90
91f32 Plane::signedDistance(const glm::vec3& point) const {
92 return glm::dot(normal, point) + distance;
93}
94
95void Frustum::extractFromMatrix(const glm::mat4& vp) {
96 const f32* m = glm::value_ptr(vp);
97
98 planes[0].normal = glm::vec3(m[3] + m[0], m[7] + m[4], m[11] + m[8]);
99 planes[0].distance = m[15] + m[12];
100
101 planes[1].normal = glm::vec3(m[3] - m[0], m[7] - m[4], m[11] - m[8]);
102 planes[1].distance = m[15] - m[12];
103
104 planes[2].normal = glm::vec3(m[3] + m[1], m[7] + m[5], m[11] + m[9]);
105 planes[2].distance = m[15] + m[13];
106
107 planes[3].normal = glm::vec3(m[3] - m[1], m[7] - m[5], m[11] - m[9]);
108 planes[3].distance = m[15] - m[13];
109
110 planes[4].normal = glm::vec3(m[3] + m[2], m[7] + m[6], m[11] + m[10]);
111 planes[4].distance = m[15] + m[14];
112
113 planes[5].normal = glm::vec3(m[3] - m[2], m[7] - m[6], m[11] - m[10]);
114 planes[5].distance = m[15] - m[14];
115
116 for (u32 i = 0; i < 6; ++i) {
117 f32 len = glm::length(planes[i].normal);
118 if (len > 1e-7f) {
119 planes[i].normal /= len;
120 planes[i].distance /= len;
121 }
122 }
123}
124
125bool Frustum::intersectsAABB(const glm::vec3& center, const glm::vec3& halfExtents) const {
126 for (u32 i = 0; i < 6; ++i) {
127 f32 r = halfExtents.x * std::abs(planes[i].normal.x) +
128 halfExtents.y * std::abs(planes[i].normal.y) +
129 halfExtents.z * std::abs(planes[i].normal.z);
130
131 f32 dist = planes[i].signedDistance(center);
132
133 if (dist < -r) {
134 return false;
135 }
136 }
137 return true;
138}
139
140bool Frustum::intersectsSweptSphere(const glm::vec3& a, const glm::vec3& b, f32 radius) const {
141 for (u32 i = 0; i < 6; ++i) {
142 if (planes[i].signedDistance(a) < -radius && planes[i].signedDistance(b) < -radius) return false;
143 }
144 return true;
145}
146
148 resource::ResourceManager& resource_manager)
149 : device_(device)
150 , context_(context)
151 , resource_manager_(resource_manager)
152 , pool_(device)
153 , target_pool_(device)
154 , graph_(device, target_pool_)
155 , shadow_pool_(device)
156 , velocity_pool_(device)
157 , selection_pool_(device)
158 , cover_pool_(device) {
159 target_manager_.setDevice(device);
160}
161
165
166void RenderFrame::init(u32 width, u32 height) {
167 width_ = width;
168 height_ = height;
169
170 // state_tracker_ is inited once by EstellaContext (its owner); flush()/replay
171 // reset() it each frame, so no per-RenderFrame init is needed here.
172
173 // Adopt the boot-declared color space before any shader compiles below —
174 // renderer_setColorSpace may run before this frame exists (pre-init).
176
177#ifdef ES_ENABLE_POSTPROCESS
178 post_process_ = makeUnique<PostProcessPipeline>(device_, context_, resource_manager_,
179 graph_);
180 post_process_->setLinearOutput(linear_color_);
181 // The requirement may have been declared before the pipeline existed (a depth
182 // layer arrives with the project, init happens on the first frame) — and until
183 // a frame has answered, the answer is that the capture carries depth.
184 applySceneDepthNeed();
185 post_process_->init(width, height);
186#endif
187
188#ifdef ES_ENABLE_GPU_PARTICLES
189 gpu_particles_ = makeUnique<GpuParticles>(device_);
190#endif
191 if (!skin_cache_) skin_cache_ = makeUnique<SkinCache>(device_);
192 pool_.init();
193 shadow_pool_.init();
194 velocity_pool_.init();
195 selection_pool_.init();
196 cover_pool_.init();
197 shadow_mover_pool_.init();
198 cover_mover_pool_.init();
199 planar_pool_.init();
200 probe_pool_.init();
201 batch_shader_id_ = initBatchShader();
202
203 RenderFrameContext initCtx{
204 context_,
205 resource_manager_,
206 context_.getWhiteTextureId(),
207 batch_shader_id_,
209 glm::mat4(1.0f),
210 nullptr,
211 this
212 };
213 for (auto& plugin : plugins_) {
214 plugin->init(initCtx);
215 }
216}
217
219 for (auto& plugin : plugins_) {
220 plugin->shutdown();
221 }
222 plugins_.clear();
223#ifdef ES_ENABLE_GPU_PARTICLES
224 if (gpu_particles_) {
225 gpu_particles_->release();
226 gpu_particles_.reset();
227 }
228#endif
229 pool_.shutdown();
230 shadow_pool_.shutdown();
231 velocity_pool_.shutdown();
232 selection_pool_.shutdown();
233 cover_pool_.shutdown();
234#ifdef ES_ENABLE_POSTPROCESS
235 receiver_captures_.clear();
236 water_sun_ = {};
237#endif
238 shadow_mover_pool_.shutdown();
239 cover_mover_pool_.shutdown();
240 if (cover_frame_ubo_ != BufferHandle::Invalid) {
241 device_.deleteBuffer(cover_frame_ubo_);
242 cover_frame_ubo_ = BufferHandle::Invalid;
243 }
244 planar_pool_.shutdown();
245 swapOverlayOut();
246 if (overlay_hold_) overlay_hold_->pool.shutdown();
247 overlay_hold_.reset();
248 for (auto& segment : segments_) if (segment.hold) segment.hold->pool.shutdown();
249 segments_.clear();
250 segments_trusted_ = false;
251 overlay_valid_ = false;
252 probe_pool_.shutdown();
253 if (probe_capture_.frameUbo != BufferHandle::Invalid) {
254 device_.deleteBuffer(probe_capture_.frameUbo);
255 probe_capture_.frameUbo = BufferHandle::Invalid;
256 }
257 releasePlanarCaptures();
258 releaseShadowFrameUbos();
259 releaseShadow2DResources();
260 releaseShape2DResources();
261 releaseOverlayBackdrop();
262 releaseFrameTargets();
263 target_pool_.clear();
264
265#ifdef ES_ENABLE_POSTPROCESS
266 if (post_process_) {
267 post_process_->shutdown();
268 post_process_.reset();
269 }
270#endif
271
272 ES_LOG_INFO("RenderFrame shutdown");
273}
274
275void RenderFrame::resize(u32 width, u32 height) {
276 width_ = width;
277 height_ = height;
278
279#ifdef ES_ENABLE_POSTPROCESS
280 if (post_process_) {
281 post_process_->resize(width, height);
282 }
283#endif
284}
285
286// The scene pass's body. The graph has bound the target and set the camera's
287// viewport; this is the draw and the constants it needs current.
288bool RenderFrame::gpuDetailWanted() const {
289#ifdef __EMSCRIPTEN__
290 // A harness's switch, read only while the profiler is on: `module.esGpuDetail = true` from the page.
291 return EM_ASM_INT({ return Module.esGpuDetail ? 1 : 0; }) != 0;
292#else
293 return false;
294#endif
295}
296
297void RenderFrame::submitColorList(DrawList& list, TransientBufferPool& buffers, FrameCapture* capture,
298 DrawList::Phase phase, const char* prepassCounter) {
299 const bool opaque = phase == DrawList::Phase::All || phase == DrawList::Phase::WithoutSceneColor || phase == DrawList::Phase::OpaqueOnly;
300 const u32 prepassDraws = depth_prepass_ && opaque ? list.depthPrepassDraws() : 0u;
301 const bool prepass = prepassDraws > 0;
302 if (opaque) ES_PROFILE_COUNTER(prepassCounter, prepassDraws);
303 const bool detail = running_pass_timer_ && gpuDetailWanted();
304 const auto sinkFor = [this, &list](const char* prefix) {
305 rg::PassTimer* timer = running_pass_timer_;
306 list.setShaderRunSink([timer, prefix](const char* shader) {
307 timer->segment(shader ? std::string(prefix) + shader : std::string("tail"));
308 });
309 };
310 if (prepass) {
311 ES_PROFILE_SCOPE("render.submit.prepass");
312 if (detail) sinkFor("prepass:");
313 list.execute(device_, buffers, context_.materials(), context_.getWhiteTextureId(),
314 nullptr, context_.perDrawBlocks(), phase, DrawList::DrawPass::DepthPrepass);
315 if (detail) list.setShaderRunSink(nullptr);
316 }
317 if (detail) sinkFor("");
318 list.execute(device_, buffers, context_.materials(), context_.getWhiteTextureId(),
319 capture, context_.perDrawBlocks(), phase,
321 if (detail) {
322 running_pass_timer_->segment("tail");
323 list.setShaderRunSink(nullptr);
324 }
325}
326
327void RenderFrame::drawScene(DrawList::Phase phase) {
328 // A temporal effect in the chain asks for the picture to be shifted by a different
329 // sub-pixel amount each frame, so its history samples what a single frame cannot.
330 // The scene only: the overlay and the shadow maps are drawn with constants of their own.
331 glm::vec2 jitter{0.0f};
332#ifdef ES_ENABLE_POSTPROCESS
333 // The atlas the meshes reflect, for an effect that adds a reflection of its own where the scene's ray found none.
334 if (post_process_) post_process_->setEnvironmentTexture(environment_texture_id_);
336 // The second half of a scene drawn in two: the same camera, shifted the same way, and a frame that must not step the
337 // temporal view a second time.
338 jitter = scene_jitter_;
339 } else if (post_process_ && post_process_->isEngaged() && post_process_->temporalActive()) {
340 jitter = post_process_->beginTemporalView(view_projection_, current_target_);
341 } else if (post_process_ && post_process_->isEngaged() && post_process_->cameraMotionWanted()) {
342 post_process_->trackView(view_projection_, current_target_);
343 }
344#endif
345 scene_jitter_ = jitter;
346 context_.updateCameraConstants(view_projection_, jitter);
347 // Where THIS camera's pixels sit inside the 2D shadow mask. Per camera because the
348 // mask is screen space: two cameras drew into two parts of one target, and a
349 // fragment has to read the part its own camera filled.
350 if ((shadow2DActive() || shape2DActive()) && width_ > 0 && height_ > 0) {
351 const f32 w = static_cast<f32>(width_);
352 const f32 h = static_cast<f32>(height_);
353 // Rows are bottom-up on every backend (WebGPU turns clip y over to lay them so).
354 context_.lights().setMask2DRect(glm::vec4(
355 static_cast<f32>(std::max(scene_viewport_.x, 0)) / w,
356 static_cast<f32>(std::max(scene_viewport_.y, 0)) / h,
357 static_cast<f32>(scene_viewport_.w) / w,
358 static_cast<f32>(scene_viewport_.h) / h));
359 } else {
360 context_.lights().setMask2DRect(glm::vec4(0.0f));
361 }
362 draw_list_.setMask2DTexture(SHADOW_2D_TEXTURE_UNIT, shadow_2d_masks_[0].textureId);
363 // Unit 6 is the shape mask's, or the second shadow mask's in a frame with no cookie (see MAX_SHADOW_2D_LIGHTS).
364 draw_list_.setMask2DTexture(SHAPE_2D_TEXTURE_UNIT, shape_2d_texture_id_ != 0 ? shape_2d_texture_id_ : shadow_2d_masks_[1].textureId);
365 // Here and not in flush(): the shadow pass runs before this one and decides
366 // which atlas tile each light reads, so the block has to go up after it.
367 // Multiple views and paused redraws can consume the last completed simulation step.
368 // Rebase its absolute window for this draw. Releasing its target invalidates the record.
369 WaterSunField field = water_sun_;
370 if (cloud_sun_slot_ < 0 || glm::dot(-cloud_sun_aim_, field.sunDirection) < 0.99999f) field = {};
371 const auto origin = renderOrigin();
372 field.rect.x = static_cast<f32>(field.rect.x - origin.x);
373 field.rect.y = static_cast<f32>(field.rect.y - origin.z);
374 field.depth.x = static_cast<f32>(field.depth.x - origin.y);
375 field.sun.z = static_cast<f32>(cloud_sun_slot_);
376 context_.lights().setWaterSun(field.rect, field.depth, field.sun);
377 device_.bindTexture(WATER_SUN_TEXTURE_UNIT, field.texture == TextureHandle::Invalid
378 ? TextureHandle{context_.getWhiteTextureId()} : field.texture);
379 context_.lights().uploadAndBind();
380
381 {
382 ES_PROFILE_SCOPE("render.submit");
383#ifdef ES_ENABLE_POSTPROCESS
384 draw_list_.setGBufferPass(post_process_ && post_process_->sceneHasGBuffer());
385#endif
386 draw_list_.setLayerAlpha(true);
387 submitColorList(draw_list_, pool_, &frame_capture_, phase, "render.prepass.draws");
388 draw_list_.setLayerAlpha(false);
389 draw_list_.setGBufferPass(false);
390 if (device_.skipPendingPrograms()) {
391 ES_PROFILE_COUNTER("render.draws.waitingForProgram", draw_list_.skippedForProgram());
392 stats_.waiting_for_program = draw_list_.skippedForProgram();
393 ES_PROFILE_COUNTER("render.programs.pending", device_.pendingProgramCount());
394 }
395 // What the probe volumes cost the frame: draws that read the brick atlas per pixel, draws that read one value,
396 // and what the atlas holds on the GPU (0 while nothing reads it per pixel).
397 {
398 const ProbeStore& probes = context_.probes();
399 ES_PROFILE_COUNTER("render.probes.perPixelDraws", probes.perPixelDraws());
400 ES_PROFILE_COUNTER("render.probes.perObjectDraws", probes.perObjectDraws());
401 ES_PROFILE_COUNTER("render.probes.atlasBytes", probes.atlasTexture() != 0 ? probes.atlasBytes() : 0);
402 }
403 }
404
405 // Handed over to whatever the graph runs next. Blend/depth/colour-mask come
406 // from each fullscreen pass's own pipeline, but scissor is dynamic state and
407 // a chain pass would inherit whatever the last scene draw left.
408 device_.invalidatePipelineCache();
409 device_.setScissorTest(false);
410}
411
412// The atlas texture this frame published, unpublished — the target behind it is
413// the graph's loan. Owed by a new frame, a device loss and shutdown, because the
414// id the receiving draws were keyed by names nothing once its device is gone.
415void RenderFrame::releaseFrameTargets() {
416 shadow_texture_id_ = 0;
417}
418
420 ++planar_frame_;
421 if (skin_cache_) skin_cache_->beginFrame(planar_frame_);
422 // An overlay left open by a host that never closed it gives the frame its pool and list back.
423 swapOverlayOut();
424 overlay_active_ = false;
425 overlay_segmented_ = false;
426 overlay_passes_ = 0;
427#ifdef ES_ENABLE_GPU_PARTICLES
428 if (gpu_particles_) gpu_particles_->beginFrame();
429#endif
430 for (auto it = planar_captures_.begin(); it != planar_captures_.end();) {
431 if (frame_collected_ && it->second.lastSeen + 1 < planar_frame_) {
432 if (it->second.frameUbo != BufferHandle::Invalid) device_.deleteBuffer(it->second.frameUbo);
433 it = planar_captures_.erase(it);
434 } else ++it;
435 }
436 // Here and not at end(), which runs once per CAMERA: every camera plans and
437 // renders its own maps, and the pool hands the same physical atlas to each in
438 // turn. Then one tick of the clock, by the frame that owns the pool.
439 releaseFrameTargets();
440 target_pool_.age();
441
442 // Last frame's answer becomes this frame's, once. A frame that collected
443 // nothing answered nothing — an editor frame that only blits, a frame the host
444 // skipped — so it neither latches nor releases.
445 if (frame_collected_) {
446 depth_answered_ = true;
447 if (frame_depth_seen_) depth_seen_ = true;
448 scene_picture_seen_ = frame_scene_picture_seen_;
449 }
450 frame_scene_picture_seen_ = false;
451 frame_collected_ = false;
452 frame_depth_seen_ = false;
453 applySceneDepthNeed();
454
455 // Counted over the whole frame rather than per camera, because a selection is
456 // one view's answer: the same object seen by two cameras is two selections, and
457 // that they can differ is the whole claim.
458 lod_counts_ = {};
459 lod_view_state_.beginFrame();
460
461 // The per-draw blocks go back at the FRAME boundary and not at each pass's:
462 // a frame reaches the device as several passes with one submission behind
463 // them, so a buffer reused between two of them is read by both.
464 context_.beginPerDrawBlocks();
465 frame_capture_.beginFrame();
466
467 // The frame's tally, over every camera and the overlay.
468 stats_ = Stats{};
469 frame_merged_ = 0;
470 std::fill(std::begin(frame_breaks_), std::end(frame_breaks_), 0u);
471}
472
473void RenderFrame::applySceneDepthNeed() {
474#ifdef ES_ENABLE_POSTPROCESS
475 if (!post_process_) return;
476 bool computeNeedsDepth = false;
477#ifdef ES_ENABLE_GPU_PARTICLES
478 computeNeedsDepth = gpu_particles_ && gpu_particles_->wantsDepth();
479#endif
480 post_process_->setComputeNeedsDepth(computeNeedsDepth || scene_picture_seen_);
481 // An editor selection is outlined over the scene's depth (declareSelectionMask), so it engages the chain and keeps that depth readable.
482 const bool outlining = !view_selection_.empty() && device_.supportsFloatTargets();
483 post_process_->setSelectionWanted(outlining);
484 post_process_->setSceneNeedsDepth(!depth_answered_ || depth_seen_ || computeNeedsDepth || scene_picture_seen_
485 || draw_list_.depthMask() != 0 || outlining);
486#endif
487}
488
489void RenderFrame::begin(const glm::mat4& view_projection, RenderTargetManager::Handle target) {
490 begin(view_projection, target, PassClear{});
491}
492
493void RenderFrame::begin(const glm::mat4& view_projection, RenderTargetManager::Handle target,
494 const PassClear& camera_clear) {
495 // A chain that is engaged draws the scene into a capture exactly as big as the camera's rect, and only its present lands at
496 // the rect's offset (setOutputViewport). So the camera's rect starts at the capture's origin: left at the camera's own x/y
497 // it names pixels outside the capture, and a camera that does not start at the window's corner (the right half of a split,
498 // a minimap) drew nothing at all whenever the frame was linear, tone mapped or post-processed.
499 PassClear clear = camera_clear;
500#ifdef ES_ENABLE_POSTPROCESS
501 if (post_process_) post_process_->setBackgroundSky(false);
502 if (post_process_ && post_process_->isEngaged()) {
503 clear.x = 0;
504 clear.y = 0;
505 }
506#endif
507 // Emptied before the device is asked, so a refused frame starts empty too: the host still submits text and skinned batches into
508 // it, and while a lost device waits for its content no end() ever ran to empty them, so the staging grew every frame until an
509 // allocation of gigabytes failed.
510 pool_.beginFrame();
511 projected_bake_resources_.clear();
512 draw_list_.clear();
513 clip_state_.clear();
514
515 // A lost device makes the whole frame meaningless, so it is refused here
516 // rather than discovered by each pass and readback failing separately.
517 // in_frame_ stays false, which makes end() a no-op too: no half-frame.
518 if (!device_.beginDeviceFrame()) {
519 in_frame_ = false;
520 return;
521 }
522
523 view_projection_ = view_projection;
524 frustum_.extractFromMatrix(view_projection);
525 // A camera that names no view looks from the shared default one rather than
526 // remembering the levels the previous camera settled on.
527 view_id_ = 0;
528 current_target_ = target;
529 current_stage_ = RenderStage::Transparent;
530 in_frame_ = true;
531 frame_capture_.beginPass(CapturePass::Scene);
532
533 openPass(clear, target);
534
535 // The rect this camera draws into, taken where the camera STATES it — a zero size
536 // means the whole target, as it does to a pass. Read off the device at flush it is
537 // whatever the collect between left there, and one camera covered the other.
538 scene_viewport_ = {clear.x, clear.y, clear.w, clear.h};
539
540 // What the scene pass writes. With a chain engaged the capture is already a
541 // graph resource (the pipeline declared it when it opened); without one the
542 // frame's own target is imported, and the graph culls back from it.
543 scene_resource_ = rg::kNoResource;
544#ifdef ES_ENABLE_POSTPROCESS
545 if (post_process_ && post_process_->isEngaged()) {
546 scene_resource_ = post_process_->sceneResource();
547 }
548#endif
549 if (scene_resource_ == rg::kNoResource) {
550 graph_.begin(width_, height_);
551 scene_resource_ = graph_.importTarget(scene_fbo_, width_, height_);
552 }
553}
554
555// Opening the frame's target: the load-op clear, the post-process capture when
556// one is engaged, the default surface otherwise. Bound EAGERLY, before the graph
557// runs, so a host draw between this call and end() lands in the scene.
558void RenderFrame::openPass(const PassClear& clear, RenderTargetManager::Handle target) {
559#ifdef ES_ENABLE_POSTPROCESS
560 const bool usePostProcess = post_process_ && post_process_->isEngaged();
561#else
562 const bool usePostProcess = false;
563#endif
564
565 // The pass's load-op clear, values carried in the desc (never sticky device
566 // state). Region-scoped when the caller renders one camera's viewport of a
567 // shared target.
568 RenderPassDesc pass{};
569 pass.clearColor = clear.color;
570 pass.clearDepth = clear.depth;
571 // Stencil shares depth's attachment, so it clears on the same terms and costs the same
572 // load-op. A frame keeping last frame's stencil cuts along a mask that has since moved;
573 // a camera deliberately keeping depth means to keep that cut too.
574 pass.clearStencil = clear.depth;
575 // Authored clear colors are sRGB; the linear frame clears in linear light.
576 const glm::vec3 clearRgb = linear_color_
577 ? srgbToLinearCpu({clear.colorValue.r, clear.colorValue.g, clear.colorValue.b})
578 : glm::vec3{clear.colorValue.r, clear.colorValue.g, clear.colorValue.b};
579 pass.clearColorValue[0] = clearRgb.r;
580 pass.clearColorValue[1] = clearRgb.g;
581 pass.clearColorValue[2] = clearRgb.b;
582 pass.clearColorValue[3] = clear.colorValue.a;
583 scene_clear_ = glm::make_vec4(pass.clearColorValue);
584#ifdef ES_ENABLE_POSTPROCESS
585 // An effect that lays a sky UNDER the scene needs the scene's alpha to be its coverage, which a clear to nothing makes it.
586 if (usePostProcess && post_process_->sceneCoverageWanted()) {
587 for (f32& channel : pass.clearColorValue) channel = 0.0f;
588 }
589 // A camera that keeps the colour under it still draws into a capture of its own when the frame is linear or has an
590 // output transform. The capture starts transparent and the present lays it over the camera beneath by coverage, rather
591 // than replacing that camera's picture with black around a held gun.
592 if (usePostProcess && !clear.color) {
593 for (f32& channel : pass.clearColorValue) channel = 0.0f;
594 post_process_->setPresentOver(true);
595 }
596#endif
597 pass.clearX = clear.x;
598 pass.clearY = clear.y;
599 pass.clearW = clear.w;
600 pass.clearH = clear.h;
601
602 if (usePostProcess) {
603#ifdef ES_ENABLE_POSTPROCESS
605 auto* rt = target_manager_.get(target);
606 if (rt) {
607 post_process_->setOutputTarget(rt->getFramebuffer());
608 }
609 }
610 // Fresh begin: colors the capture's own load-op clear. When TS already
611 // began the capture (renderCamera drives pp.begin first) this no-ops.
612 post_process_->begin(pass.clearColorValue);
613 // Then BIND it, clear or no clear: this is where the frame gets its target
614 // back after the shadow pass drew through one of its own. Skipping it for
615 // a camera with nothing to clear left the atlas current — a black frame.
616 pass.target = post_process_->currentSceneFBO();
617 device_.beginRenderPass(pass);
618#endif
619 } else if (target != RenderTargetManager::INVALID_HANDLE) {
620 auto* rt = target_manager_.get(target);
621 if (rt) {
622 pass.target = rt->getFramebuffer();
623 device_.beginRenderPass(pass);
624 }
625 } else {
626 // The scene may be rendering into the TS screen-capture FBO (screen post
627 // stack without a per-camera stack): the clear must land on that surface —
628 // blind-rebinding the default target here would break the capture.
629#ifdef ES_ENABLE_POSTPROCESS
630 if (post_process_) pass.target = post_process_->currentSceneFBO();
631#endif
632 device_.beginRenderPass(pass);
633 }
634
635 // What the scene pass will draw into. Bound already, because a host draw
636 // between this call and the graph's run (the editor's grid) has to land in
637 // the scene; the pass re-opens it with a load, so that work survives.
638 scene_fbo_ = pass.target;
639}
640
641// What a finalized list cost, added to the frame's tally. Accumulated rather
642// than assigned because a frame reports more than one list: the scene's, and the
643// screen overlay's after every camera.
644void RenderFrame::accumulateStats(const DrawList& list) {
645 stats_.draw_calls += list.mergedDrawCallCount();
646 for (u32 i = 0; i < list.commandCount(); ++i) {
647 const auto& cmd = list.command(i);
648 // An instanced command holds ONE copy of the geometry and draws it
649 // instance_count times; a batched one merged its indices in already. The
650 // multiply is what stops the number meaning two things on the two paths.
651 stats_.triangles += (cmd.index_count / 3) * (cmd.instance_count ? cmd.instance_count : 1);
652 }
653 stats_.sprites += list.sourceEntityCount(RenderType::Sprite) + list.sourceEntityCount(RenderType::UIElement);
654 stats_.text += list.sourceEntityCount(RenderType::Text);
655 stats_.meshes += list.sourceEntityCount(RenderType::Mesh) + list.sourceEntityCount(RenderType::ExternalMesh)
656 + list.sourceEntityCount(RenderType::Trail);
657#ifdef ES_ENABLE_PARTICLES
658 stats_.particles += list.sourceEntityCount(RenderType::Particle);
659#endif
660 stats_.shapes += list.sourceEntityCount(RenderType::Shape);
661 stats_.skeletal += list.sourceEntityCount(RenderType::Skeletal);
662}
663
665 if (!in_frame_ || flushed_) return;
666
667 flushed_ = true;
668
669 // The device can still die between begin() and here — a GL error check, a
670 // spontaneous WebGPU callback. Marked flushed above first, so end() does not
671 // come back for a second attempt at a frame that has nowhere to go.
672 if (!device_.isDeviceUsable()) return;
673
674 // Drop any pipeline a prior phase left bound, so the first draw re-applies its state.
675 device_.invalidatePipelineCache();
676
677 // finalize() sorts + coalesces and rewrites per-vertex texIndex into the staging, so it
678 // must run before upload() ships that staging to the GPU. Both stay here rather
679 // than riding the pass: the counters below read what finalize decided, and the
680 // host asks for them before the graph has run.
681 {
682 ES_PROFILE_SCOPE("render.finalize");
683 // Around the CALLS, which are synchronous: what the device does with an
684 // upload afterwards is its own clock and cannot be read off this one.
685 {
686 ES_PROFILE_SCOPE("render.finalize.drawList");
687 // Before the merge, which spends texture slots: a mask needs a top one and
688 // does not exist yet. The shape mask sits below the shadow one, so a frame
689 // with a shape keeps both whether anything casts or not.
690 draw_list_.reserveMask2DSlots(
691 (shape_2d_resource_ != rg::kNoResource || shadow_2d_masks_[1].resource != rg::kNoResource) ? 2u
692 : (shadow_2d_masks_[0].resource != rg::kNoResource ? 1u : 0u));
693 draw_list_.finalize(pool_);
694 }
695 {
696 ES_PROFILE_SCOPE("render.finalize.upload");
697 pool_.upload();
698 }
699 }
700
701 accumulateStats(draw_list_);
702
703 // What the frame's render targets cost. The atlas and every chain
704 // intermediate come out of one pool, so one number answers for all of them —
705 // and a pool that stopped giving targets back is visible in no pixel.
706 tallyPass(draw_list_);
707}
708
710 // The frame's GPU timing, closed over every graph it ran, before the device closes the frame.
711 if (gpu_frame_open_) {
712 gpu_frame_open_ = false;
713 if (gpu_frame_passes_ && pass_timer_) {
714 rg::PassTimer& passTimer = *pass_timer_;
715 passTimer.endFrame();
716 // Since the timer was made: frames read back, dropped before the device answered, and disturbed. A pass time that does
717 // not move while frames are drawn is explained by these.
718 ES_PROFILE_COUNTER("render.gpuTimer.read", passTimer.framesRead());
719 ES_PROFILE_COUNTER("render.gpuTimer.dropped", passTimer.framesDropped());
720 ES_PROFILE_COUNTER("render.gpuTimer.disjoint", passTimer.framesDisjoint());
721 ES_PROFILE_COUNTER("render.gpuTimer.skipped", passTimer.framesSkipped());
722 // The scope names are the passes' own, under pass/ so they cannot meet a scope of another kind; passes that share a
723 // name, in one graph or several, are one scope (PassTimer sums them).
724 for (const auto& e : passTimer.last()) {
725 pass_scope_names_.try_emplace(e.name, std::string("pass/") + e.name);
726 FrameProfiler::get().gpuScope(pass_scope_names_[e.name].c_str(), e.ms);
727 }
728 if (passTimer.lastTotalMs() >= 0.0f) {
729 pass_graph_ms_ = passTimer.lastTotalMs();
730 FrameProfiler::get().gpuScope("graph", pass_graph_ms_);
731 }
732 } else if (!gpu_frame_passes_) {
733 gpu_timer_.end(device_);
734 pass_graph_ms_ = -1.0f;
735 FrameProfiler::get().gpuScope("graph", gpu_timer_.lastMs());
736 }
737 }
738 frame_capture_.endFrame();
739 device_.endFrame();
740 stats_.gpu_draws = device_.takeDraws();
741 publishFrameCounters();
742 // Once per frame and not per camera: a commit at each camera's end kept only
743 // the last camera's scopes and counters.
745}
746
747// What one real pass's merge decided, added to the frame's tally. A preview
748// surface finalizes a list too, and is not part of the frame.
749void RenderFrame::tallyPass(const DrawList& list) {
750 frame_merged_ += list.mergedAwayCount();
751 for (u32 r = 1; r < static_cast<u32>(BatchBreak::Count); ++r) {
752 frame_breaks_[r] += list.breakCount(static_cast<BatchBreak>(r));
753 }
754}
755
756void RenderFrame::publishFrameCounters() {
757 if (!FrameProfiler::get().enabled()) return;
758 ES_PROFILE_COUNTER("batch.draws", stats_.draw_calls);
759 ES_PROFILE_COUNTER("render.gpu.draws", stats_.gpu_draws);
760 ES_PROFILE_COUNTER("batch.merged", frame_merged_);
761 // Every material bake drawn since the renderer started: a check that a baked surface was drawn at all, which no pixel of a correct
762 // one tells from the same surface drawn live.
763 ES_PROFILE_COUNTER("render.bakes.drawn", material_bakes_drawn_);
764 // Emitted per reason and only where it happened, so a clean frame publishes
765 // nothing rather than a wall of zeroes for a caller to read past.
766 for (u32 r = 1; r < static_cast<u32>(BatchBreak::Count); ++r) {
767 if (frame_breaks_[r] == 0) continue;
768 FrameProfiler::get().counter(batchBreakCounter(static_cast<BatchBreak>(r)), frame_breaks_[r]);
769 }
770 // The shadow atlas is the frame's own and kept, not pooled, and counted with the pool it used to come from: a colour and a
771 // depth texel per atlas texel, four bytes each, as the pool counts its own.
772 const u64 atlasSide = shadow_target_ ? shadow_target_->getWidth() : 0u;
773 ES_PROFILE_COUNTER("render.targets", target_pool_.count() + (shadow_target_ ? 1u : 0u));
774 ES_PROFILE_COUNTER("render.targets.bytes", target_pool_.bytes() + atlasSide * atlasSide * 8u);
775 // Memory on the other side: pixels and buffers the device copies so they
776 // survive a loss, which no GPU figure counts.
777 ES_PROFILE_COUNTER("render.retained.bytes", device_.retainedBytes());
778
779 ES_PROFILE_COUNTER("render.culled", stats_.culled);
780 // Which question did the culling, and how much was declared to do it with. A
781 // scene whose occluders stopped being taken — turned past the near plane, or
782 // authored to nothing — reads zero boxes here while render.culled says nothing.
783 ES_PROFILE_COUNTER("render.cull.occluded", stats_.occluded);
784 ES_PROFILE_COUNTER("render.cull.occluders", occlusion_.boxes());
785 ES_PROFILE_COUNTER("render.reflection.probes", context_.reflections().count());
786 ES_PROFILE_COUNTER("render.sprites", stats_.sprites);
787 // Light slots the lit quads were spared: a light out of reach added nothing before either, so no pixel says whether it is skipped.
788 ES_PROFILE_COUNTER("render.lights2d.spared", stats_.lightsSpared);
789 // The same for what has no quads of its own to say it (a tilemap's strips): how many (screen tile, loop light) pairs are left set.
790 ES_PROFILE_COUNTER("render.lights2d.tileBits", context_.lights().loopTileBits());
791 ES_PROFILE_COUNTER("render.lights3d.tileBits", context_.lights().loopTileBits3D());
792 ES_PROFILE_COUNTER("render.lights.loop", context_.lights().count());
793 ES_PROFILE_COUNTER("render.lights.tiled", context_.lights().tiledCount());
794 // The 3D path had no counter at all, and its cost is the one a pixel hides
795 // best: identical geometry drawn N times merges into ONE instanced call, so
796 // batch.draws does not move when a cull stops working. These two do.
797 ES_PROFILE_COUNTER("render.meshes", stats_.meshes);
798 ES_PROFILE_COUNTER("render.triangles", stats_.triangles);
799 ES_PROFILE_COUNTER("render.text", stats_.text);
800 ES_PROFILE_COUNTER("render.lod.groups", lod_counts_.selections);
801 ES_PROFILE_COUNTER("render.lod.level0", lod_counts_.level[0]);
802 ES_PROFILE_COUNTER("render.lod.level1", lod_counts_.level[1]);
803 ES_PROFILE_COUNTER("render.lod.level2", lod_counts_.level[2]);
804 ES_PROFILE_COUNTER("render.lod.level3", lod_counts_.level[3]);
805 ES_PROFILE_COUNTER("render.lod.culled", lod_counts_.culled);
806 ES_PROFILE_COUNTER("render.shapes", stats_.shapes);
807#ifdef ES_ENABLE_PARTICLES
808 ES_PROFILE_COUNTER("render.particles", stats_.particles);
809 // What the compute-simulated emitters asked of the GPU: a scene whose emitters fell back to the CPU reads zero here.
810#ifdef ES_ENABLE_GPU_PARTICLES
811 ES_PROFILE_COUNTER("render.particles.gpuSlots", gpu_particles_ ? gpu_particles_->drawnSlots() : 0u);
812#endif
813#endif
814}
815
817 if (!in_frame_) return;
818
819 if (!flushed_) {
820 flush();
821 }
822
823#ifdef ES_ENABLE_POSTPROCESS
824 const bool usePostProcess = post_process_ && post_process_->isEngaged();
825#else
826 const bool usePostProcess = false;
827#endif
828
829 // Everything this camera draws, declared in one place and run once. The
830 // scene is a pass like the effects that read it: the graph binds its target,
831 // sets the camera's rect and calls drawScene.
832 if (scene_resource_ != rg::kNoResource) {
833 rg::PassDesc scene;
834 scene.name = "scene";
835 scene.write = scene_resource_;
836 scene.viewportX = static_cast<u32>(std::max(scene_viewport_.x, 0));
837 scene.viewportY = static_cast<u32>(std::max(scene_viewport_.y, 0));
838 scene.viewportW = scene_viewport_.w;
839 scene.viewportH = scene_viewport_.h;
840 // Named, not read: every draw that receives a shadow carries the atlas in
841 // its own key, so the graph owes the scene ordering and lifetime but must
842 // not spend a texture unit on it.
843 if (shadow_resource_ != rg::kNoResource) {
844 scene.dependencies.push_back(shadow_resource_);
845 }
846 // The same terms for the 2D mask: every Lit draw samples it through a pinned
847 // unit, so the graph owes the scene its ordering and its lifetime, not a bind.
848 if (shape_2d_resource_ != rg::kNoResource) {
849 scene.dependencies.push_back(shape_2d_resource_);
850 }
851 for (const Shadow2DMask& mask : shadow_2d_masks_) {
852 if (mask.resource != rg::kNoResource) scene.dependencies.push_back(mask.resource);
853 }
854 if (planar_resource_ != rg::kNoResource) scene.dependencies.push_back(planar_resource_);
855 scene.dependencies.insert(scene.dependencies.end(), projected_bake_resources_.begin(), projected_bake_resources_.end());
856#ifdef ES_ENABLE_GPU_PARTICLES
857 // The particles a kernel advances this frame are drawn by the scene, so it runs first.
858 if (gpu_particles_) {
859 const rg::ResourceId simulated = gpu_particles_->declare(graph_);
860 if (simulated != rg::kNoResource) scene.dependencies.push_back(simulated);
861 }
862#endif
863 // A surface that refracts has to see what stands behind it, and what stands behind it is the opaque scene: the pass is
864 // drawn in two, with a copy of the picture taken between. Only where the scene is a texture a pass can read (a chain is
865 // engaged) and a draw in the list asks for the copy.
866 bool glass = false;
867#ifdef ES_ENABLE_POSTPROCESS
868 glass = usePostProcess && draw_list_.anyUsesSceneColor(context_.materials());
869#endif
870 // A blended surface (a pane, a particle, a leaf card) writes no depth, so drawn before the water it is covered by it wherever the water is in
871 // front of the pixel's opaque, whichever side of the surface it is on. So where there are any, the scene is built in layers: the opaque
872 // scene, then the blended draws over it (the picture the water refracts, so what is under the surface is seen through it), then the opaque
873 // scene put back and the water drawn, and last the blended draws once more, depth-tested against the water now: those in front of the
874 // surface land on it, those behind it fail and are only seen through it. The pixels the water does not cover were put back, so they are blended once.
875 bool layered = false;
876#ifdef ES_ENABLE_POSTPROCESS
877 layered = glass && draw_list_.anyBlendedWithoutSceneColor(context_.materials());
878#endif
879 bool screen = false;
880#ifdef ES_ENABLE_POSTPROCESS
881 screen = usePostProcess && draw_list_.anyUsesScreenColor(context_.materials());
882#endif
883 draw_list_.setDeferScreenColor(screen);
884 rg::PassDesc screenPass;
885 if (screen) screenPass = scene;
886 bool depthFade = false;
887#ifdef ES_ENABLE_POSTPROCESS
888 depthFade = usePostProcess && !glass && draw_list_.anyUsesSceneDepth(context_.materials()) && post_process_->canGrabDepth();
889#endif
890 rg::PassDesc glassPass;
891 rg::PassDesc blendedPass, overPass;
892 rg::ResourceId grabOpaque = rg::kNoResource;
895 if (depthFade) {
896#ifdef ES_ENABLE_POSTPROCESS
897 grabDepth = graph_.createTarget(post_process_->grabDepthTarget());
898 blendedPass = scene;
899 blendedPass.name = "scene-blended";
900 blendedPass.dependencies.push_back(grabDepth);
901 blendedPass.execute = [this, grabDepth, screen](const rg::PassContext&) {
902 context_.materials().setSceneDepth(graph_.textureOf(grabDepth));
904 context_.materials().setSceneDepth(TextureHandle::Invalid);
905 if (!screen && presented_overlay_draw_) presented_overlay_draw_->flushDeferred();
906 };
907#endif
908 }
909 if (glass) {
910#ifdef ES_ENABLE_POSTPROCESS
911 grab = graph_.createTarget(post_process_->grabTarget());
912 if (layered) grabOpaque = graph_.createTarget(post_process_->grabTarget());
913 // The distance to what stands behind, for a surface that measures the water in front of it: only when one asks, and
914 // only where a float target can hold distances.
915 if (draw_list_.anyUsesSceneDepth(context_.materials()) && post_process_->canGrabDepth()) {
916 grabDepth = graph_.createTarget(post_process_->grabDepthTarget());
917 }
918 glassPass = scene;
919 glassPass.name = "scene-glass";
920 glassPass.dependencies.push_back(grab);
921 if (grabDepth != rg::kNoResource) glassPass.dependencies.push_back(grabDepth);
922 if (layered) {
923 blendedPass = scene;
924 blendedPass.name = "scene-blended";
925 blendedPass.dependencies.push_back(grabOpaque);
926 if (grabDepth != rg::kNoResource) blendedPass.dependencies.push_back(grabDepth);
927 blendedPass.execute = [this, grabDepth](const rg::PassContext&) {
928 if (grabDepth != rg::kNoResource) context_.materials().setSceneDepth(graph_.textureOf(grabDepth));
930 context_.materials().setSceneDepth(TextureHandle::Invalid);
931 };
932 overPass = scene;
933 overPass.name = "scene-blended-over";
934 overPass.dependencies.push_back(grab);
935 if (grabDepth != rg::kNoResource) overPass.dependencies.push_back(grabDepth);
936 overPass.execute = [this, grabDepth, screen](const rg::PassContext&) {
937 if (grabDepth != rg::kNoResource) context_.materials().setSceneDepth(graph_.textureOf(grabDepth));
939 context_.materials().setSceneDepth(TextureHandle::Invalid);
940 if (!screen && presented_overlay_draw_) presented_overlay_draw_->flushDeferred();
941 };
942 }
943 glassPass.execute = [this, grab, grabDepth, layered, screen](const rg::PassContext&) {
944 context_.materials().setSceneColor(graph_.textureOf(grab));
945 if (grabDepth != rg::kNoResource) context_.materials().setSceneDepth(graph_.textureOf(grabDepth));
947 context_.materials().setSceneColor(TextureHandle::Invalid);
948 context_.materials().setSceneDepth(TextureHandle::Invalid);
949 if (!layered && !screen && presented_overlay_draw_) presented_overlay_draw_->flushDeferred();
950 };
951#endif
952 }
953 // With no chain to take the scene from, water and glass draw in the one pass, and the order the list sorts blended draws in (by
954 // where each object stands) put a water surface after every pane in front of it: the surface follows the camera, so it stands
955 // nearest of all. Ordered by the pixel instead, as the layers above do without the copies: the opaque scene, then the water, which
956 // writes depth, then the blended draws, depth-tested against it. Those in front of the surface land on it, those under it are hidden.
957 const bool ordered = !glass && draw_list_.anyUsesSceneColor(context_.materials())
958 && draw_list_.anyBlendedWithoutSceneColor(context_.materials());
959 scene.execute = [this, glass, layered, ordered, depthFade, screen](const rg::PassContext&) {
960 if (ordered) {
964 } else {
965 drawScene(layered || depthFade ? DrawList::Phase::OpaqueOnly : glass ? DrawList::Phase::WithoutSceneColor : DrawList::Phase::All);
966 }
967 if (!glass && !depthFade && !screen && presented_overlay_draw_) presented_overlay_draw_->flushDeferred();
968 };
969 graph_.addPass(std::move(scene));
970#ifdef ES_ENABLE_GPU_PARTICLES
971 if (gpu_particles_) {
972 gpu_particles_->declareDepthCopy(graph_, scene_resource_, width_, height_, toClipDepthRange(view_projection_, device_.clipDepthRange()));
973 }
974#endif
975 if (glass) {
976#ifdef ES_ENABLE_POSTPROCESS
977 rg::PassDesc copy;
978 copy.name = "scene-grab";
979 copy.reads = {scene_resource_};
980 copy.write = layered ? grabOpaque : grab;
981 // Layered, this copy is only ever put back (scene-restore): kept exact, alpha and all. Otherwise the water reads it, marked.
982 copy.execute = [this, layered](const rg::PassContext&) { post_process_->grabScene(/*marked=*/!layered); };
983 graph_.addPass(std::move(copy));
984 if (grabDepth != rg::kNoResource) {
985 rg::PassDesc copyDepth;
986 copyDepth.name = "scene-grab-depth";
987 copyDepth.reads = {scene_resource_};
988 copyDepth.write = grabDepth;
989 copyDepth.execute = [this](const rg::PassContext&) { post_process_->grabDepth(); };
990 graph_.addPass(std::move(copyDepth));
991 }
992 if (layered) {
993 graph_.addPass(std::move(blendedPass));
994 rg::PassDesc copyBlended;
995 copyBlended.name = "scene-grab-blended";
996 copyBlended.reads = {scene_resource_};
997 copyBlended.write = grab;
998 copyBlended.execute = [this](const rg::PassContext&) { post_process_->grabScene(); };
999 graph_.addPass(std::move(copyBlended));
1000 // The opaque scene put back: what the blended draws left in the pixels is theirs to leave again, in the pass after the water.
1001 rg::PassDesc restore;
1002 restore.name = "scene-restore";
1003 restore.reads = {grabOpaque};
1004 restore.write = scene_resource_;
1005 // Exact: the scene's alpha is how much of each pixel geometry covers, which the sky reads. Restored through the marked
1006 // copy, every pixel came back half covered and the sky showed through every wall, wherever water and a pane were both in view.
1007 restore.execute = [this](const rg::PassContext&) { post_process_->grabScene(/*marked=*/false); };
1008 graph_.addPass(std::move(restore));
1009 }
1010#endif
1011 graph_.addPass(std::move(glassPass));
1012 if (layered) graph_.addPass(std::move(overPass));
1013 }
1014 if (depthFade) {
1015#ifdef ES_ENABLE_POSTPROCESS
1016 rg::PassDesc copyDepth;
1017 copyDepth.name = "scene-grab-depth";
1018 copyDepth.reads = {scene_resource_};
1019 copyDepth.write = grabDepth;
1020 copyDepth.execute = [this](const rg::PassContext&) { post_process_->grabDepth(); };
1021 graph_.addPass(std::move(copyDepth));
1022 graph_.addPass(std::move(blendedPass));
1023#endif
1024 }
1025 if (screen) {
1026#ifdef ES_ENABLE_POSTPROCESS
1027 const rg::ResourceId grabScreen = graph_.createTarget(post_process_->grabTarget());
1028 rg::PassDesc copyScreen;
1029 copyScreen.name = "screen-grab";
1030 copyScreen.reads = {scene_resource_};
1031 copyScreen.write = grabScreen;
1032 copyScreen.execute = [this](const rg::PassContext&) { post_process_->grabScene(); };
1033 graph_.addPass(std::move(copyScreen));
1034 screenPass.name = "scene-screen";
1035 screenPass.dependencies.push_back(grabScreen);
1036 screenPass.execute = [this, grabScreen](const rg::PassContext&) {
1037 context_.materials().setScreenColor(graph_.textureOf(grabScreen));
1039 context_.materials().setScreenColor(TextureHandle::Invalid);
1040 if (presented_overlay_draw_) presented_overlay_draw_->flushDeferred();
1041 };
1042 graph_.addPass(std::move(screenPass));
1043#endif
1044 }
1045 }
1046
1047#ifdef ES_ENABLE_POSTPROCESS
1048 // What the scene drew, drawn again for how far each moving surface travelled: a temporal pass in the
1049 // chain reads it, and nothing else does, so a frame whose meshes all stood still declares nothing.
1050 if (usePostProcess && scene_resource_ != rg::kNoResource && velocity_list_.commandCount() > 0) {
1051 const rg::ResourceId velocity = post_process_->declareVelocity();
1052 if (velocity != rg::kNoResource) {
1053 rg::PassDesc motion;
1054 motion.name = "motion";
1055 motion.write = velocity;
1056 motion.clear = true;
1057 motion.clearDepth = true;
1058 // Nothing written is alpha 0: a reader treats it as "the camera's motion, not an object's".
1059 motion.clearColor[0] = motion.clearColor[1] = motion.clearColor[2] = motion.clearColor[3] = 0.0f;
1060 motion.execute = [this](const rg::PassContext&) { executeMotionPass(); };
1061 graph_.addPass(std::move(motion));
1062 }
1063 }
1064#endif
1065
1066#ifdef ES_ENABLE_POSTPROCESS
1067 // What stands over each place, for an effect that keeps rain off what is sheltered.
1068 if (usePostProcess && scene_resource_ != rg::kNoResource && cover_wanted_ && coverCommandCount() > 0) {
1069 const rg::ResourceId cover = post_process_->declareCover(1024);
1070 const bool standing = cover_drawn_valid_ && cover_trusted_ && cover_drawn_key_ == cover_key_
1071 && cover_drawn_target_ == post_process_->coverTargetId();
1072 ES_PROFILE_COUNTER("render.cover.reused", standing ? 1u : 0u);
1073 if (standing) ++cover_kept_total_;
1074 if (cover != rg::kNoResource) post_process_->setCoverMatrix(cover_view_projection_);
1075 if (cover != rg::kNoResource && !standing) {
1076 rg::PassDesc pass;
1077 pass.name = "rain-cover";
1078 pass.write = cover;
1079 pass.clear = true;
1080 pass.clearDepth = true;
1081 // White is depth 1: nothing above.
1082 pass.clearColor[0] = pass.clearColor[1] = pass.clearColor[2] = pass.clearColor[3] = 1.0f;
1083 pass.execute = [this](const rg::PassContext&) { executeCoverPass(); };
1084 graph_.addPass(std::move(pass));
1085 }
1086 }
1087#endif
1088
1089#ifdef ES_ENABLE_POSTPROCESS
1090 // The editor's selection outline (setViewSelection): the mask now, the ring after the chain's last pass. A selection
1091 // engages the chain (applySceneDepthNeed), so the scene's depth is a texture the mask can be laid on.
1092 if (usePostProcess && scene_resource_ != rg::kNoResource) {
1093 const rg::ResourceId selectionMask = declareSelectionMask();
1094 if (selectionMask != rg::kNoResource) post_process_->setSelectionMask(selectionMask);
1095 }
1096#endif
1097 if (usePostProcess) {
1098#ifdef ES_ENABLE_POSTPROCESS
1099 post_process_->setShadowAtlas(shadow_texture_id_, shadow_resource_);
1100 post_process_->declareChain();
1101#endif
1102 }
1103
1104 {
1105 ES_PROFILE_SCOPE("render.graph");
1106 // With the profiler on, each pass is timed and the graph is their sum; otherwise one query spans the graph.
1107 rg::PassTimer* passTimer = nullptr;
1108 if (FrameProfiler::get().enabled()) {
1109 if (!pass_timer_) pass_timer_ = makeUnique<rg::PassTimer>(device_);
1110 if (pass_timer_->available()) passTimer = pass_timer_.get();
1111 }
1112 // A frame runs a graph per camera and per chain, and is timed as one: opened by its first graph and closed in endFrame().
1113 // Timed a graph at a time, a frame of eight graphs went through a timer that keeps four in flight before the device had
1114 // answered for any, every one was dropped, and the times read were the first frame's for as long as the game ran.
1115 if (!gpu_frame_open_) {
1116 gpu_frame_open_ = true;
1117 gpu_frame_passes_ = passTimer != nullptr;
1118 if (passTimer) {
1119 passTimer->beginFrame();
1120 } else {
1121 gpu_timer_.poll(device_);
1122 gpu_timer_.begin(device_);
1123 }
1124 }
1125 if (gpu_frame_passes_ && passTimer) {
1126 graph_.setPassTimer(passTimer);
1127 running_pass_timer_ = passTimer;
1128 graph_.execute();
1129 running_pass_timer_ = nullptr;
1130 graph_.setPassTimer(nullptr);
1131 } else {
1132 graph_.execute();
1133 }
1134 }
1135#ifdef ES_ENABLE_GPU_PARTICLES
1136 // After the graph, which is where the kernels run: a frame that dispatched none (its emitters fell back to the CPU, or
1137 // nothing moved) says so.
1138 ES_PROFILE_COUNTER("render.particles.gpuDispatches", gpu_particles_ ? gpu_particles_->lastDispatches() : 0u);
1139 ES_PROFILE_COUNTER("render.particles.depthGridWidth", gpu_particles_ ? gpu_particles_->depthGridWidth() : 0u);
1140#endif
1141 scene_resource_ = rg::kNoResource;
1142 shadow_resource_ = rg::kNoResource;
1143 shadow_views_.clear();
1144
1145 if (usePostProcess) {
1146#ifdef ES_ENABLE_POSTPROCESS
1147 post_process_->chainDone();
1148#endif
1149 } else if (current_target_ != RenderTargetManager::INVALID_HANDLE) {
1150 auto* rt = target_manager_.get(current_target_);
1151 if (rt) {
1152 rt->unbind();
1153 }
1154 }
1155
1156 // The graph's own time is the whole frame's — the scene pass runs inside it.
1157 stats_.gpu_time_ms = pass_graph_ms_ >= 0.0f ? pass_graph_ms_ : gpu_timer_.lastMs();
1158
1159 // The frame's pass closes HERE, not at the next begin: a WebGPU backend
1160 // submits on endRenderPass, and a surface texture acquired this task must
1161 // not ride into the next one (the swapchain recycles it at task end). On
1162 // GL this is just the default-framebuffer rebind.
1163 device_.endRenderPass();
1164 runPendingReplay(view_projection_, scene_viewport_.w, scene_viewport_.h);
1165
1166 in_frame_ = false;
1167 flushed_ = false;
1168
1169}
1170
1172 if (drawIndex < 0 || static_cast<u32>(drawIndex) >= frame_capture_.getRecordCount()) return;
1173 const DrawCallRecord* records = frame_capture_.getRecords();
1174 const u32 pass = records[drawIndex].pass;
1175 i32 local = 0;
1176 for (i32 i = 0; i < drawIndex; ++i) {
1177 if (records[i].pass == pass) ++local;
1178 }
1179 replay_pass_ = static_cast<i32>(pass);
1180 replay_draw_ = local;
1181 if (snapshot_readback_ != ReadbackHandle::Invalid) device_.discardReadback(snapshot_readback_);
1182 snapshot_readback_ = ReadbackHandle::Invalid;
1183 snapshot_pixels_.clear();
1184}
1185
1186void RenderFrame::runPendingReplay(const glm::mat4& projection, u32 w, u32 h) {
1187 if (replay_draw_ < 0 || frame_capture_.currentPass() != replay_pass_) return;
1188 const i32 stopAt = replay_draw_;
1189 replay_pass_ = -1;
1190 replay_draw_ = -1;
1191 if (w == 0 || h == 0) {
1192 w = width_;
1193 h = height_;
1194 }
1195 snapshot_matches_ = draw_list_.mergedDrawCallCount()
1196 == frame_capture_.recordsInPass(frame_capture_.currentPass());
1197
1198 // With depth and stencil: a replayed 3D draw tests against the draws before
1199 // it, and a UI mask writes the stencil the draws after it read.
1200 if (replay_rt_ == 0) {
1201 replay_rt_ = target_manager_.create(w, h, /*depth=*/true, /*linearFilter=*/false);
1202 } else if (auto* existing = target_manager_.get(replay_rt_);
1203 existing && (existing->getWidth() != w || existing->getHeight() != h)) {
1204 existing->resize(w, h);
1205 }
1206 auto* rt = target_manager_.get(replay_rt_);
1207 if (!rt) return;
1208
1209 RenderPassDesc replayPass{rt->getFramebuffer(), /*clearColor=*/true};
1210 replayPass.clearDepth = true;
1211 replayPass.clearStencil = true;
1212 replayPass.clearColorValue[3] = 0.0f;
1213 device_.beginRenderPass(replayPass);
1214 device_.setViewport(0, 0, w, h);
1215
1216 frame_capture_.setReplayMode(stopAt + 1);
1217 context_.updateCameraConstants(projection);
1218 context_.lights().uploadAndBind();
1219 draw_list_.execute(device_, pool_, context_.materials(), context_.getWhiteTextureId(),
1220 &frame_capture_, context_.perDrawBlocks());
1221 frame_capture_.clearReplayMode();
1222
1223 device_.setScissorTest(false);
1224 device_.invalidatePipelineCache();
1225 device_.endRenderPass();
1226
1227 snapshot_w_ = w;
1228 snapshot_h_ = h;
1229 snapshot_pixels_.clear();
1230 snapshot_readback_ = device_.requestReadback(rt->getFramebuffer(), w, h);
1231}
1232
1233void RenderFrame::renderToTarget(ecs::Registry& registry, const glm::mat4& viewProjection, u32 w, u32 h) {
1234 renderSurface(registry, viewProjection, preview_, w, h, {});
1235}
1236
1237void RenderFrame::renderSurface(ecs::Registry& registry, const glm::mat4& viewProjection,
1238 PreviewSurface& surface, u32 w, u32 h,
1239 std::span<const PendingSkeletalBatch> extraSkeletalBatches) {
1240 if (w == 0 || h == 0) return;
1241 if (!device_.isDeviceUsable()) return;
1242
1243 if (surface.target == 0) {
1244 surface.target = target_manager_.create(w, h, /*depth=*/true, /*linearFilter=*/false);
1245 } else if (auto* existing = target_manager_.get(surface.target);
1246 existing && (existing->getWidth() != w || existing->getHeight() != h)) {
1247 existing->resize(w, h);
1248 }
1249 auto* rt = target_manager_.get(surface.target);
1250 if (!rt) return;
1251
1252 RenderPassDesc previewPass{rt->getFramebuffer(), /*clearColor=*/true};
1253 previewPass.clearDepth = true; // a mesh drawn here needs its near faces to win
1254 previewPass.clearStencil = true;
1255 previewPass.clearColorValue[3] = 0.0f; // transparent black
1256 device_.beginRenderPass(previewPass);
1257 device_.setViewport(0, 0, w, h);
1258
1259 // A self-contained collect (begin()'s setup minus post-process) + execute (flush()'s body),
1260 // drawn to the bound preview target. Reuses the real collect+material+execute path so a
1261 // preview is pixel-identical to the viewport.
1262 view_projection_ = viewProjection;
1263 frustum_.extractFromMatrix(viewProjection);
1264 view_id_ = kPreviewViewId;
1265 current_stage_ = RenderStage::Transparent;
1266 pool_.beginFrame();
1267 draw_list_.clear();
1268 clip_state_.clear();
1269
1270 // A preview target is a plain one, whatever the camera's chain is doing.
1271 collectAll(registry, /*sceneGBuffer=*/false);
1272
1273 // AFTER the collect, because the clear above would have eaten them. Geometry
1274 // a caller posed itself and handed over, replayed through the one skeletal
1275 // path a scene's batches take.
1276 for (const auto& batch : extraSkeletalBatches) {
1277 submitSkeletalBatch(batch.vertices.data(), static_cast<i32>(batch.vertices.size() / 8),
1278 batch.indices.data(), static_cast<i32>(batch.indices.size()),
1279 batch.textureId, batch.blendMode, &batch.transform[0][0],
1280 batch.entity, batch.layer, batch.depth, batch.materialId, batch.premultipliedColor);
1281 }
1282
1283 draw_list_.finalize(pool_);
1284 pool_.upload();
1285 context_.updateCameraConstants(viewProjection);
1286 context_.lights().uploadAndBind();
1287 draw_list_.execute(device_, pool_, context_.materials(), context_.getWhiteTextureId(),
1288 nullptr, context_.perDrawBlocks());
1289
1290 rt->unbind();
1291 device_.invalidatePipelineCache();
1292
1293 // Async readback seam (same shape as the replay snapshot above).
1294 if (surface.readback != ReadbackHandle::Invalid) device_.discardReadback(surface.readback);
1295 surface.width = w;
1296 surface.height = h;
1297 surface.pixels.clear();
1298 surface.readback = device_.requestReadback(rt->getFramebuffer(), w, h);
1299}
1300
1302 if (replay_draw_ >= 0) return 0;
1303 return pollReadback(snapshot_readback_, snapshot_pixels_, snapshot_w_, snapshot_h_);
1304}
1305
1306RenderFrame::SkeletalPreview* RenderFrame::skeletalPreview(SkeletalPreviewId id) {
1307 auto it = skeletal_previews_.find(id);
1308 return it == skeletal_previews_.end() ? nullptr : it->second.get();
1309}
1310
1311const RenderFrame::SkeletalPreview* RenderFrame::skeletalPreview(SkeletalPreviewId id) const {
1312 auto it = skeletal_previews_.find(id);
1313 return it == skeletal_previews_.end() ? nullptr : it->second.get();
1314}
1315
1317 if (w == 0 || h == 0) return 0;
1318 auto preview = std::make_unique<SkeletalPreview>();
1319 // Its own one-entity scene. The transform is identity and stays that way:
1320 // where a preview stands is the preview camera's business, and a batch
1321 // arrives with its own model matrix.
1322 preview->entity = preview->registry.create();
1323 preview->registry.emplace<ecs::Transform>(preview->entity);
1324 preview->surface.width = w;
1325 preview->surface.height = h;
1326 const SkeletalPreviewId id = next_skeletal_preview_++;
1327 skeletal_previews_.emplace(id, std::move(preview));
1328 return id;
1329}
1330
1333 const f32* vertices, i32 vertexCount,
1334 const u16* indices, i32 indexCount,
1335 u32 textureId, i32 blendMode, const f32* transform16,
1336 i32 layer, f32 depth, u32 materialId, bool premultipliedColor
1337) {
1338 auto* preview = skeletalPreview(id);
1339 if (!preview || !vertices || !indices || vertexCount < 0 || indexCount < 0) return false;
1341 // COPIED, not referenced: this sits until the next render call, and the
1342 // caller's scratch is gone the moment it returns.
1343 batch.vertices.assign(vertices, vertices + static_cast<usize>(vertexCount) * 8);
1344 batch.indices.assign(indices, indices + static_cast<usize>(indexCount));
1345 batch.textureId = textureId;
1346 batch.blendMode = blendMode;
1347 batch.premultipliedColor = premultipliedColor;
1348 if (transform16) std::memcpy(&batch.transform[0][0], transform16, sizeof(f32) * 16);
1349 batch.entity = preview->entity;
1350 batch.layer = layer;
1351 batch.depth = depth;
1352 batch.materialId = materialId;
1353 preview->pending.push_back(std::move(batch));
1354 return true;
1355}
1356
1357bool RenderFrame::renderSkeletalPreview(SkeletalPreviewId id, const glm::mat4& viewProjection) {
1358 auto* preview = skeletalPreview(id);
1359 if (!preview) return false;
1360 // One in flight per preview. A second render would land two images for one
1361 // camera and leave a caller no way to say which its overlay belongs to.
1362 if (preview->surface.readback != ReadbackHandle::Invalid) return false;
1363 // Taken before the draw: a render that throws or bails must not leave last
1364 // frame's geometry to be drawn again on top of the next one.
1365 const auto batches = std::exchange(preview->pending, {});
1366 renderSurface(preview->registry, viewProjection, preview->surface,
1367 preview->surface.width, preview->surface.height, batches);
1368 return true;
1369}
1370
1372 auto* preview = skeletalPreview(id);
1373 if (!preview) return 2;
1374 return pollReadback(preview->surface.readback, preview->surface.pixels,
1375 preview->surface.width, preview->surface.height);
1376}
1377
1379 const auto* preview = skeletalPreview(id);
1380 return preview ? preview->surface.pixels.data() : nullptr;
1381}
1382
1384 const auto* preview = skeletalPreview(id);
1385 return preview ? static_cast<u32>(preview->surface.pixels.size()) : 0;
1386}
1387
1389 const auto* preview = skeletalPreview(id);
1390 return preview ? preview->surface.width : 0;
1391}
1392
1394 const auto* preview = skeletalPreview(id);
1395 return preview ? preview->surface.height : 0;
1396}
1397
1399 auto it = skeletal_previews_.find(id);
1400 if (it == skeletal_previews_.end()) return;
1401 // Logical ownership ends now; the device's outstanding work is handed back
1402 // the same way every other readback is, so nothing lands in freed pixels.
1403 auto& surface = it->second->surface;
1404 if (surface.readback != ReadbackHandle::Invalid) {
1405 device_.discardReadback(surface.readback);
1406 surface.readback = ReadbackHandle::Invalid;
1407 }
1408 if (surface.target != 0) target_manager_.release(surface.target);
1409 skeletal_previews_.erase(it);
1410}
1411
1413 return pollReadback(preview_.readback, preview_.pixels, preview_.width, preview_.height);
1414}
1415
1416i32 RenderFrame::pollReadback(ReadbackHandle& handle, std::vector<u8>& pixels, u32 w, u32 h) {
1417 if (handle == ReadbackHandle::Invalid) {
1418 // No readback in flight: the last landed pixels (if any) stay available.
1419 return pixels.empty() ? 2 : 1;
1420 }
1421 switch (device_.pollReadback(handle)) {
1423 return 0;
1425 pixels.resize(static_cast<usize>(w) * h * 4);
1426 const bool ok = device_.takeReadback(handle, pixels.data(), pixels.size());
1427 handle = ReadbackHandle::Invalid;
1428 if (!ok) pixels.clear();
1429 return ok ? 1 : 2;
1430 }
1432 default:
1433 handle = ReadbackHandle::Invalid;
1434 pixels.clear();
1435 return 2;
1436 }
1437}
1438
1440 clip_rects_[entity] = ScissorRect{x, y, w, h};
1441}
1442
1444 clip_rects_.clear();
1445}
1446
1447void RenderFrame::setEntityStencilMask(u32 entity, i32 refValue, bool hierarchical) {
1448 stencil_masks_[entity] = {refValue, true, hierarchical};
1449}
1450
1451void RenderFrame::setEntityStencilTest(u32 entity, i32 refValue, bool hierarchical) {
1452 stencil_masks_[entity] = {refValue, false, hierarchical};
1453}
1454
1456 stencil_masks_.clear();
1457}
1458
1459// ─── Mask Processing ── see RenderFrameMask.cpp ─────────────────────────────
1460
1461// ─── Tile/Spine Submit ── see RenderFrameSubmit.cpp ──────────────────────────
1462
1463// ============================================================================
1464// Plugin Pipeline
1465// ============================================================================
1466
1467void RenderFrame::addPlugin(std::unique_ptr<RenderTypePlugin> plugin) {
1468 plugins_.push_back(std::move(plugin));
1469}
1470
1471void RenderFrame::buildClipState() {
1472 clip_state_.clear();
1473
1474 for (const auto& [entity, rect] : clip_rects_) {
1475 clip_state_.setScissor(entity, rect.x, rect.y, rect.w, rect.h);
1476 }
1477
1478 for (const auto& [entity, info] : stencil_masks_) {
1479 if (info.hierarchical) {
1480 if (info.is_mask) clip_state_.setUIStencilMask(entity, info.ref_value);
1481 else clip_state_.setUIStencilTest(entity, info.ref_value);
1482 continue;
1483 }
1484 if (info.is_mask) {
1485 clip_state_.setStencilMask(entity, info.ref_value);
1486 } else {
1487 clip_state_.setStencilTest(entity, info.ref_value);
1488 }
1489 }
1490}
1491
1492namespace {
1493
1501void assignSortingSubtree(ecs::Registry& registry, DrawList& list, Entity entity,
1502 DrawList::GroupIdentity identity) {
1503 list.setSortingGroup(entity.id(), identity);
1504 if (!registry.has<ecs::Children>(entity)) return;
1505 for (auto child : registry.get<ecs::Children>(entity).entities) {
1506 DrawList::GroupIdentity childIdentity = identity;
1507 // The FIRST nesting decides the block; deeper ones join it. A grandchild group
1508 // restating it would interleave its contents with a sibling of its own block.
1509 if (!childIdentity.blockOrder && registry.has<ecs::SortingGroup>(child)) {
1510 const auto& inner = registry.get<ecs::SortingGroup>(child);
1511 if (inner.enabled) {
1512 childIdentity.blockOrder = true;
1513 childIdentity.block = inner.order;
1514 }
1515 }
1516 assignSortingSubtree(registry, list, child, childIdentity);
1517 }
1518}
1519
1522bool hasEnclosingGroup(ecs::Registry& registry, Entity entity) {
1523 Entity current = entity;
1524 while (registry.has<ecs::Parent>(current)) {
1525 Entity parent = registry.get<ecs::Parent>(current).entity;
1526 if (parent == INVALID_ENTITY) break;
1527 if (registry.has<ecs::SortingGroup>(parent) &&
1528 registry.get<ecs::SortingGroup>(parent).enabled) {
1529 return true;
1530 }
1531 current = parent;
1532 }
1533 return false;
1534}
1535
1536} // namespace
1537
1538void RenderFrame::buildSortingGroups(ecs::Registry& registry) {
1539 draw_list_.clearSortingGroups();
1540
1541 auto groups = registry.activeView<ecs::SortingGroup>();
1542 for (auto entity : groups) {
1543 const auto& group = groups.get(entity);
1544 if (!group.enabled) continue;
1545 // Only the OUTERMOST group seeds an identity; the walk below reaches the inner
1546 // ones as blocks. Seeding from an inner group too would overwrite what the outer
1547 // one just wrote, and which of the two won would be view iteration order.
1548 if (hasEnclosingGroup(registry, entity)) continue;
1549 assignSortingSubtree(registry, draw_list_, entity,
1550 {group.layer, group.order, false, 0});
1551 }
1552}
1553
1554void RenderFrame::buildTreeSequence(ecs::Registry& registry) {
1555 std::vector<u32>& sequence = draw_list_.treeSequence();
1556 sequence.clear();
1557 if (draw_list_.treeMask() == 0) return;
1558 u32 counter = 1;
1559 auto walk = [&](Entity root) {
1560 tree_pending_.push_back(root);
1561 while (!tree_pending_.empty()) {
1562 const Entity entity = tree_pending_.back();
1563 tree_pending_.pop_back();
1564 if (!registry.valid(entity)) continue;
1565 const u32 index = entity.index();
1566 if (index >= sequence.size()) sequence.resize(index + 1, 0u);
1567 sequence[index] = counter++;
1568 const auto* children = registry.tryGet<ecs::Children>(entity);
1569 if (!children) continue;
1570 for (auto child = children->entities.rbegin(); child != children->entities.rend(); ++child) tree_pending_.push_back(*child);
1571 }
1572 };
1573 auto transforms = registry.view<ecs::Transform>();
1574 for (auto entity : transforms) {
1575 const auto* parent = registry.tryGet<ecs::Parent>(entity);
1576 if (parent && parent->entity != INVALID_ENTITY && registry.valid(parent->entity)) continue;
1577 walk(entity);
1578 }
1579}
1580
1581void RenderFrame::buildSpriteMasks(ecs::Registry& registry) {
1582 // 255 is the stencil attachment's, not a budget: refs are per FRAME and a mask past
1583 // the last one is dropped rather than aliased onto another mask's cut.
1584 static constexpr i32 MAX_MASK_REF = 255;
1585
1586 std::vector<ResolvedMask>& masks = sprite_mask_scratch_;
1587 masks.clear();
1588
1589 auto maskView = registry.activeView<ecs::SpriteMask>();
1590 for (auto entity : maskView) {
1591 const auto& mask = maskView.get(entity);
1592 if (!mask.enabled) continue;
1593 // The mask IS its sprite, so a sprite that will not be drawn cuts nothing. Without
1594 // this, hiding a mask makes everything it reached disappear instead of appear.
1595 if (!registry.has<ecs::Sprite>(entity)) continue;
1596 const auto& sprite = registry.get<ecs::Sprite>(entity);
1597 if (!sprite.enabled) continue;
1598
1599 masks.push_back({
1600 draw_list_.sortIdentity(entity.id(), sprite.layer, sprite.order),
1601 {mask.rangeEndLayer, mask.rangeEndOrder},
1602 mask.limitRange,
1603 0,
1604 });
1605 mask_entities_scratch_.push_back(entity);
1606 }
1607 if (masks.empty()) { mask_entities_scratch_.clear(); return; }
1608
1609 // Refs run in DRAW order so a later mask overwrites an earlier one where they overlap,
1610 // which is what the stencil does anyway — assigning them in view order would make which
1611 // mask wins depend on entity creation.
1612 std::vector<u32> byDraw(masks.size());
1613 for (u32 i = 0; i < masks.size(); ++i) byDraw[i] = i;
1614 std::sort(byDraw.begin(), byDraw.end(),
1615 [&](u32 a, u32 b) { return masks[a].at < masks[b].at; });
1616
1617 i32 nextRef = 1;
1618 for (u32 slot : byDraw) {
1619 if (nextRef > MAX_MASK_REF) {
1620 ES_LOG_WARN("SpriteMask: more than 255 masks in one frame; the rest cut nothing");
1621 break;
1622 }
1623 masks[slot].ref = nextRef++;
1624 clip_state_.setStencilMask(mask_entities_scratch_[slot].id(), masks[slot].ref);
1625 }
1626 if (clip_state_.reserveSpriteStencilReferences(nextRef - 1)) {
1627 ES_LOG_WARN("UI masks exceed remaining stencil references after SpriteMask allocation; overflowing subtrees are clipped");
1628 }
1629
1630 auto spriteView = registry.activeView<ecs::Sprite>();
1631 for (auto entity : spriteView) {
1632 const auto& sprite = spriteView.get(entity);
1633 if (sprite.maskInteraction == 0 || !sprite.enabled) continue;
1634 if (registry.has<ecs::SpriteMask>(entity)) continue; // a mask is not its own subject
1635
1636 const auto where = draw_list_.sortIdentity(entity.id(), sprite.layer, sprite.order);
1637 const ResolvedMask* nearest =
1638 nearestReachingMask(masks.data(), static_cast<u32>(masks.size()), where);
1639 if (!nearest) continue;
1640
1641 if (sprite.maskInteraction == static_cast<i32>(ecs::SpriteMaskInteraction::VisibleOutside)) {
1642 clip_state_.setStencilTestOutside(entity.id(), nearest->ref);
1643 } else {
1644 clip_state_.setStencilTest(entity.id(), nearest->ref);
1645 }
1646 }
1647 mask_entities_scratch_.clear();
1648}
1649
1651 std::string out;
1652 out.reserve(texture_wants_.size() * 12);
1653 for (const auto& [texture, side] : texture_wants_) {
1654 if (!out.empty()) out += ',';
1655 out += std::to_string(texture);
1656 out += ':';
1657 out += std::to_string(static_cast<u32>(std::ceil(side)));
1658 }
1659 texture_wants_.clear();
1660 return out;
1661}
1662
1663RenderFrameContext RenderFrame::makeContext() {
1665 context_,
1666 resource_manager_,
1667 context_.getWhiteTextureId(),
1668 batch_shader_id_,
1669 current_stage_,
1670 view_projection_,
1671 &context_.materials(),
1672 this,
1674 shadow_texture_id_,
1675 environment_texture_id_
1676 };
1677 ctx.lighting_direct = lighting_direct_;
1678 const glm::vec4 eye = cameraFromViewProjection(view_projection_);
1679 ctx.has_view_eye = eye.w > 0.5f;
1680 if (ctx.has_view_eye) ctx.view_eye = glm::vec3(eye);
1681 return ctx;
1682}
1683
1687static glm::vec3 lightForward(ecs::Transform* transform) {
1688 if (!transform) return glm::vec3(0.0f, 0.0f, -1.0f);
1689 transform->ensureDecomposed();
1690 return transform->worldRotation * glm::vec3(0.0f, 0.0f, -1.0f);
1691}
1692
1700void RenderFrame::collectProbes(ecs::Registry& registry) {
1701 ProbeStore& probes = context_.probes();
1702 probes.clear();
1703
1704 auto view = registry.activeView<ecs::LightProbeVolume>();
1705 for (auto entity : view) {
1706 const auto& volume = view.get(entity);
1707 if (!volume.enabled) continue;
1708 // A volume filled at run time (a capture's grid) reads that instead of what it was baked with.
1709 const auto overridden = probe_overrides_.find(static_cast<u32>(entity));
1710 const ProbeVolume* grid = resource_manager_.getProbeVolume(
1711 overridden != probe_overrides_.end() ? overridden->second : volume.probes);
1712 if (!grid) continue;
1713 // The box is axis-aligned around the entity's world position: a grid was
1714 // solved on world axes, so a turned volume would be read along axes it
1715 // never had. Scale is not read for the same reason.
1716 const auto* transform = registry.tryGet<ecs::Transform>(entity);
1717 const glm::vec3 centre = transform ? rebased(transform->worldPosition) : rebased(glm::vec3(0.0f));
1718 const glm::vec3 half = glm::abs(volume.halfExtents);
1719 probes.add(centre - half, centre + half, grid);
1720 }
1721
1722 // Per object only (a quality level for a weak GPU): no atlas is laid out or held, and every draw reads its one value.
1723 if (!probes_per_pixel_) {
1724 if (probe_atlas_) probe_atlas_.reset();
1725 probes.forgetAtlas();
1726 return;
1727 }
1728 // 256 is the 3D side WebGL2 guarantees; a grid past it keeps the per-object read rather than failing.
1729 if (probes.layoutAtlas(256) && probes.atlasWidth() > 0) {
1730 probes.fillAtlas(probe_atlas_texels_);
1731 probe_atlas_ = Texture::createVolume(device_, GfxContent::retained(), probes.atlasWidth(), probes.atlasHeight(),
1732 probes.atlasDepth(), probe_atlas_texels_.data(), TextureFormat::RGBA16F);
1733 }
1734 probes.setAtlasTexture(probes.atlasWidth() > 0 && probe_atlas_ ? probe_atlas_->getId() : 0);
1735}
1736
1745void RenderFrame::collectOccluders(ecs::Registry& registry) {
1746 occlusion_.begin(view_projection_);
1747 auto view = registry.activeView<ecs::Occluder>();
1748 for (auto entity : view) {
1749 const auto& occluder = view.get(entity);
1750 if (!occluder.enabled) continue;
1751 auto* transform = registry.tryGet<ecs::Transform>(entity);
1752 if (!transform) continue;
1753 transform->ensureDecomposed();
1754 // Scale is not read, matching every other authored extent and the box the
1755 // viewport draws: one value, two readers, and the picture an author places
1756 // the box by IS what the cull uses.
1757 occlusion_.addBox(rebased(transform->worldPosition), transform->worldRotation,
1758 glm::abs(occluder.halfExtents));
1759 }
1760 occlusion_.finish();
1761}
1762
1771void RenderFrame::collectReflections(ecs::Registry& registry) {
1772 ReflectionStore& store = context_.reflections();
1773 store.clear();
1774
1775 auto view = registry.activeView<ecs::ReflectionProbe>();
1776 for (auto entity : view) {
1777 const auto& probe = view.get(entity);
1778 if (!probe.enabled || !probe.reflection.isValid()) continue;
1779 const auto* transform = registry.tryGet<ecs::Transform>(entity);
1780 if (!transform) continue;
1781 const glm::vec3 centre = rebased(transform->worldPosition);
1782 const glm::vec3 half = glm::abs(probe.halfExtents);
1783 store.add(centre - half, centre + half, probe.slot, probe.reflection.id());
1784 }
1785 // Probe volumes filled at run time reflect their capture too, a column each of the atlas the SDK built from them;
1786 // the frame binds one atlas, so a scene with baked reflection probes keeps those.
1787 if (store.empty() && !probe_reflections_.empty()) {
1788 auto volumes = registry.activeView<ecs::LightProbeVolume>();
1789 for (auto entity : volumes) {
1790 const auto found = probe_reflections_.find(static_cast<u32>(entity));
1791 if (found == probe_reflections_.end() || !volumes.get(entity).enabled) continue;
1792 const auto* transform = registry.tryGet<ecs::Transform>(entity);
1793 if (!transform) continue;
1794 const glm::vec3 centre = rebased(transform->worldPosition);
1795 const glm::vec3 half = glm::abs(volumes.get(entity).halfExtents);
1796 store.add(centre - half, centre + half, found->second.slot, found->second.environment);
1797 }
1798 }
1799 if (store.empty()) return;
1800
1801 const Environment* baked =
1802 resource_manager_.getEnvironment(resource::EnvironmentHandle(store.environment()));
1803 if (!baked || !baked->hasSpecular()) return;
1804 Texture* atlas = resource_manager_.getTexture(baked->specular);
1805 if (!atlas) return;
1806
1807 // Boxes by COLUMN and not in the order the registry walked them: the shader
1808 // indexes by the number written on the probe, and a frame that packed them
1809 // tightly would project one room's reflection onto another's walls.
1810 glm::vec4 boxes[2 * MAX_REFLECTION_PROBES]{};
1811 u32 highest = 0;
1812 for (const ReflectionStore::Probe& probe : store.probes()) {
1813 const u32 at = (probe.slot - 1) * 2;
1814 boxes[at] = glm::vec4(probe.min, 0.0f);
1815 boxes[at + 1] = glm::vec4(probe.max, 0.0f);
1816 highest = std::max(highest, probe.slot);
1817 }
1818 environment_texture_id_ = atlas->getId();
1819 context_.lights().setReflections(
1820 glm::vec4(1.0f, baked->maxRange, static_cast<f32>(baked->mipCount) - 1.0f,
1821 baked->faceSize),
1822 boxes, highest);
1823}
1824
1827static glm::vec3 environmentToWorld(const glm::vec3& d, f32 yawDegrees) {
1828 const f32 a = glm::radians(yawDegrees);
1829 const f32 c = std::cos(a), s = std::sin(a);
1830 return {c * d.x + s * d.z, d.y, -s * d.x + c * d.z};
1831}
1832
1833void RenderFrame::collectLights(ecs::Registry& registry) {
1834 LightStore& lights = context_.lights();
1835 lights.clear();
1836 shadow_casters_.clear();
1837 cloud_sun_slot_ = -1;
1838 light_cap_.clear();
1839 environment_texture_id_ = 0;
1840 sky_texture_id_ = 0;
1841 draw_sky_ = false;
1842 scene_sky_available_ = false;
1843
1844 if (view_lighting_.studio) {
1845 collectStudioLights(registry);
1846 return;
1847 }
1848
1849 // The frame's environment is decided before any light is: a directional light
1850 // following its sun needs it, and whether one does decides which irradiance
1851 // the environment lights with — so the answer cannot depend on registry order.
1852 auto view = registry.activeView<ecs::Light>();
1853 Entity skyLight{};
1854 const Environment* sky = nullptr;
1855 glm::vec3 skyScale(0.0f);
1856 f32 skyYaw = 0.0f;
1857 bool sunFollowed = false;
1858 for (auto entity : view) {
1859 const auto& light = view.get(entity);
1860 if (!light.enabled || light.intensity <= 0.0f) continue;
1861 const auto type = static_cast<ecs::LightType>(light.type);
1862 if (type == ecs::LightType::Directional && light.followEnvironmentSun) sunFollowed = true;
1863 if (sky || type != ecs::LightType::Ambient || !environmentOf(light).isValid()) continue;
1864 if (const Environment* environment = resource_manager_.getEnvironment(environmentOf(light))) {
1865 sky = environment;
1866 skyLight = entity;
1867 const glm::vec3 rgb = linear_color_ ? srgbToLinearCpu(glm::vec3{light.color})
1868 : glm::vec3{light.color};
1869 skyScale = rgb * light.intensity;
1870 skyYaw = light.environmentRotation;
1871 }
1872 }
1873 // How the baked reflections are shown: the frame's environment light says, else the first ambient light does.
1874 {
1875 const ecs::Light* tone = nullptr;
1876 for (auto entity : view) {
1877 const auto& light = view.get(entity);
1878 if (!light.enabled || static_cast<ecs::LightType>(light.type) != ecs::LightType::Ambient) continue;
1879 if (entity == skyLight) { tone = &light; break; }
1880 if (!tone) tone = &light;
1881 }
1882 if (tone) context_.lights().setReflectionTone(tone->reflectionScale, tone->reflectionSaturation);
1883 context_.lights().setBakedTint(tone ? glm::vec3(tone->bakedTint) : glm::vec3(1.0f));
1884 }
1885 const bool sunCast = sunFollowed && sky && sky->hasSun;
1886 if (sunCast) {
1887 light_cap_.environmentSun = true;
1888 light_cap_.environmentSunAim = -environmentToWorld(sky->sunDirection, skyYaw);
1889 }
1890
1891 // Gather non-ambient lights, then (if over the UBO's cap) keep the most intense — the
1892 // brightest contribute most, and an explicit importance cull beats silently dropping
1893 // whichever happened to come last in iteration order. Ambient lights sum without a cap.
1894 std::vector<CollectedLight>& collected = light_scratch_;
1895 collected.clear();
1896 bool haveSun = false;
1897
1898 // A light's Transform need is type-dependent. Ambient is a flat scene-wide term and
1899 // reads none of it; Directional takes only the rotation, so it works without one and
1900 // aims into the screen; Point/Spot need a position and are skipped without one.
1901 for (auto entity : view) {
1902 const auto& light = view.get(entity);
1903 if (!light.enabled || light.intensity <= 0.0f) continue;
1904
1905 const auto type = static_cast<ecs::LightType>(light.type);
1906 // color.a is unused; intensity carries the strength. Authored sRGB ->
1907 // linear when the frame lights in linear space.
1908 const glm::vec3 rgb = linear_color_ ? srgbToLinearCpu(glm::vec3{light.color})
1909 : glm::vec3{light.color};
1910 if (type == ecs::LightType::Ambient) {
1911 // An environment REPLACES this light's flat term rather than adding to
1912 // it: its coefficients already carry the same colour, and summing both
1913 // would light the scene twice from one source.
1914 if (collectEnvironment(light, rgb * light.intensity,
1915 sunCast && entity == skyLight)) continue;
1916 lights.addAmbient(rgb * light.intensity);
1917 if (light.hemisphere) {
1918 const glm::vec3 ground = linear_color_ ? srgbToLinearCpu(glm::vec3{light.groundColor})
1919 : glm::vec3{light.groundColor};
1920 lights.addAmbientGround((ground - rgb) * light.intensity);
1921 }
1922 continue;
1923 }
1924
1925 const bool followsSun = type == ecs::LightType::Directional && light.followEnvironmentSun;
1926 if (followsSun && !sunCast) {
1927 light_cap_.refused.push_back({entity, static_cast<u8>(type), light.intensity,
1929 continue;
1930 }
1931
1932 GpuLight gpu;
1933 bool castsMeshShadow = false;
1934 ShadowCaster caster;
1935 caster.light = entity;
1936 caster.split = std::isfinite(light.cascadeSplit) ? std::clamp(light.cascadeSplit, 0.0f, 1.0f) : 0.75f;
1937 caster.bias = std::isfinite(light.shadowBias) ? std::clamp(light.shadowBias, 0.0f, 16.0f) : 1.5f;
1938 caster.slopeFloor = std::isfinite(light.shadowSlopeFloor) ? std::clamp(light.shadowSlopeFloor, 0.01f, 1.0f) : 0.15f;
1939 // The sun is the environment's, so the ambient light's colour and intensity
1940 // scale it as they scale the rest of the panorama; this light's own scale on top.
1941 gpu.color = glm::vec4(followsSun ? sky->sunColor * skyScale * rgb : rgb, light.intensity);
1942 // shadow.x = penumbra softness (all types); shadow.y = directional march distance (only the
1943 // directional branch of shadowFactor2D reads it; 0 keeps directional shadows off).
1944 gpu.shadow = glm::vec4(std::max(light.shadowSoftness, 0.0f),
1945 std::max(light.shadowDistance, 0.0f), 0.0f, 0.0f);
1946 // Clamped where it is PACKED: a shader given a negative exponent lights the far
1947 // side of the radius, and a fragment cannot say who authored it. The shader
1948 // floors the exponent too — pow(0, 0) is 1, which lights the whole screen.
1949 // y: the ramp's power, or for an inverse-square light minus the world units in a metre (a power is never
1950 // negative, so the sign says which; distanceFalloff reads both).
1951 gpu.falloff = glm::vec4(std::max(light.innerRadius, 0.0f),
1952 light.inverseSquare ? -world_units_per_meter_ : std::max(light.falloff, 0.0f),
1953 // w: the shape mask channel, -1 for a light with no shape of its own. A zero would read channel 0 of whatever sits on that unit.
1954 std::clamp(light.shadowStrength, 0.0f, 1.0f), -1.0f);
1955 // The sprite layers it reaches ride above the tile count the shadow atlas fills in later.
1956 gpu.shadowMap.y = LIGHT_TILE_BITS * packLightLayerRange(light.layerMin, light.layerMax);
1957 if (type == ecs::LightType::Directional) {
1958 // z=1 flags directional (no attenuation) in the shader; w carries the aim's third
1959 // component, which only a directional light has a use for — point and spot spend
1960 // that slot on their falloff radius.
1961 const glm::vec3 aim = followsSun && !light.aimFollowedSun ? light_cap_.environmentSunAim
1962 : lightForward(registry.tryGet<ecs::Transform>(entity));
1963 gpu.posDir = glm::vec4(aim.x, aim.y, 1.0f, aim.z);
1964 // A source infinitely far away has no half-extent a map can divide by a
1965 // distance, so what it carries is the angle it subtends — as its tangent,
1966 // which is what the penumbra is made of either way.
1967 gpu.shadowMap.z = std::tan(glm::radians(
1968 std::clamp(light.sourceAngle, 0.0f, 179.0f) * 0.5f));
1969 // One sun: a second set of cascades would claim the atlas a first one is
1970 // already spending, and two suns is not a scene anybody authors.
1971 if (light.meshShadows && !haveSun) {
1972 haveSun = true;
1973 castsMeshShadow = true;
1974 caster.shape = ShadowShape::Box;
1975 caster.dir = aim;
1976 caster.extent = std::max(light.shadowExtent, 0.0f);
1977 }
1978 } else { // Point / Spot — world position from the Transform, w=falloff radius.
1979 auto* transform = registry.tryGet<ecs::Transform>(entity);
1980 if (!transform) continue; // a positional light with no position casts nothing
1981 transform->ensureDecomposed();
1982 const glm::vec3 p = rebased(transform->worldPosition);
1983 const f32 typeId = (type == ecs::LightType::Spot) ? 2.0f : 0.0f;
1984 gpu.posDir = glm::vec4(p.x, p.y, typeId, light.radius);
1985 // The height a surface with real geometry measures against. A sprite has no
1986 // depth of its own and keeps the plane's convention, so this reaches only the
1987 // MESH_NORMALS half of the lighting loop.
1988 gpu.shadow.z = p.z;
1989 if (type == ecs::LightType::Spot) {
1990 // Split across two slots because the two shading halves read different
1991 // parts: the plane's xy, and the whole of it in three.
1992 const glm::vec3 aim = lightForward(transform);
1993 // The aim as it IS. A cone with no component in the plane needs a
1994 // substitute there, but that belongs where the plane's convention is
1995 // applied — stored, it tilts the three-dimensional axis as well.
1996 gpu.spot = glm::vec4(aim.x, aim.y,
1997 std::cos(glm::radians(light.innerAngle * 0.5f)),
1998 std::cos(glm::radians(light.outerAngle * 0.5f)));
1999 gpu.shadow.w = aim.z;
2000 caster.dir = aim;
2001 }
2002 // A cone's map is the cone it opens. A point opens none and lights every
2003 // direction, so its map is six cones at right angles — the same projection,
2004 // six times.
2005 if (light.meshShadows) {
2006 castsMeshShadow = true;
2007 caster.shape = type == ecs::LightType::Spot ? ShadowShape::Cone
2009 caster.pos = p;
2010 caster.range = std::max(light.radius, 0.0f);
2011 caster.outerAngle = light.outerAngle;
2012 }
2013 }
2014 collected.push_back({gpu, castsMeshShadow, caster});
2015 }
2016
2017 const QualityValues& quality = context_.qualityValues();
2018 const u32 loopLimit = std::clamp(quality.count(QualityValue::LoopLights), 1u, MAX_LIGHTS);
2019 const u32 tiledLimit = std::min(quality.count(QualityValue::TiledLights), MAX_TILED_LIGHTS);
2020 light_cap_.limit = loopLimit + tiledLimit;
2021 light_cap_.requested = static_cast<u32>(collected.size() + light_cap_.refused.size());
2022 std::vector<CollectedLight> tiled;
2023 if (collected.size() > loopLimit) {
2024 const auto rank = [](const CollectedLight& l) {
2025 const bool directional = l.gpu.posDir.z > 0.5f && l.gpu.posDir.z < 1.5f;
2026 return directional ? 0 : (l.castsMeshShadow ? 1 : 2);
2027 };
2028 std::stable_sort(collected.begin(), collected.end(), [&rank](const CollectedLight& a, const CollectedLight& b) {
2029 const int ra = rank(a), rb = rank(b);
2030 if (ra != rb) return ra < rb;
2031 return a.gpu.color.a > b.gpu.color.a;
2032 });
2033 for (usize i = loopLimit; i < collected.size(); ++i) {
2034 CollectedLight& rest = collected[i];
2035 const bool positional = rest.gpu.posDir.z < 0.5f || rest.gpu.posDir.z > 1.5f;
2036 if (positional && !rest.castsMeshShadow && tiled.size() < tiledLimit) {
2037 tiled.push_back(rest);
2038 continue;
2039 }
2040 light_cap_.refused.push_back({rest.caster.light, static_cast<u8>(rest.gpu.posDir.z),
2041 rest.gpu.color.a, LightRefusal::Capacity});
2042 if (loopLimit == MAX_LIGHTS && tiledLimit == MAX_TILED_LIGHTS) {
2043 ES_LOG_WARN("collectLights: light {} is not in this frame ({}); {} kept of {}, brightest first",
2044 rest.caster.light.raw, lightRefusalName(LightRefusal::Capacity),
2045 loopLimit + tiled.size(), collected.size());
2046 }
2047 }
2048 collected.resize(loopLimit);
2049 }
2050 light_cap_.accepted = static_cast<u32>(collected.size() + tiled.size());
2051 for (u32 slot = 0; slot < collected.size(); ++slot) {
2052 if (collected[slot].castsMeshShadow) {
2053 ShadowCaster caster = collected[slot].caster;
2054 caster.slot = slot;
2055 shadow_casters_.push_back(caster);
2056 }
2057 // The sun a sky's clouds shade is the first directional light, as the sky's own findSun takes it.
2058 const glm::vec4& pd = collected[slot].gpu.posDir;
2059 if (cloud_sun_slot_ < 0 && pd.z > 0.5f && pd.z < 1.5f) {
2060 const glm::vec3 aim(pd.x, pd.y, pd.w);
2061 if (glm::length(aim) > 1e-6f) {
2062 cloud_sun_slot_ = static_cast<i32>(slot);
2063 cloud_sun_aim_ = glm::normalize(aim);
2064 }
2065 }
2066 lights.addLight(collected[slot].gpu);
2067 }
2068 for (const CollectedLight& light : tiled) {
2069 lights.addTiledLight(light.gpu, view_projection_);
2070 }
2071 // ...and which screen tiles each of the loop's own lights can reach, for the flat lit surfaces (sprites, tilemap layers).
2072 lights.markLoopLights(view_projection_);
2073
2074 // Last, because which lights the mask can carry is a question about the array the
2075 // loop above just filled.
2076 collectShadow2D(registry);
2077 collectShape2D(registry);
2078}
2079
2084static void neutralSkyIrradiance(std::array<glm::vec3, 9>& sh) {
2085 constexpr f32 a = 0.45f;
2086 constexpr f32 b = 0.15f;
2087 sh.fill(glm::vec3(0.0f));
2088 sh[0] = glm::vec3(a / 0.282095f);
2089 sh[1] = glm::vec3((2.0f / 3.0f) * b / 0.488603f);
2090}
2091
2092void RenderFrame::collectStudioLights(ecs::Registry& registry) {
2093 LightStore& lights = context_.lights();
2094 const ViewLighting& view = view_lighting_;
2095
2096 // The scene's own environment, found by the same rule the scene frame uses, only
2097 // to be LOOKED AT: it never lights anything here.
2098 auto lightView = registry.activeView<ecs::Light>();
2099 for (auto entity : lightView) {
2100 const auto& light = lightView.get(entity);
2101 if (!light.enabled || light.intensity <= 0.0f) continue;
2102 if (static_cast<ecs::LightType>(light.type) != ecs::LightType::Ambient) continue;
2103 if (!light.environment.isValid()) continue;
2104 const Environment* environment = resource_manager_.getEnvironment(light.environment);
2105 if (!environment) continue;
2106 u32 textureId = 0;
2107 if (environment->hasSpecular()) {
2108 if (Texture* atlas = resource_manager_.getTexture(environment->specular)) {
2109 textureId = atlas->getId();
2110 }
2111 }
2112 u32 panorama = 0;
2113 if (environment->sky.isValid()) {
2114 if (Texture* sky = resource_manager_.getTexture(environment->sky)) panorama = sky->getId();
2115 }
2116 scene_sky_available_ = textureId != 0 || panorama != 0;
2117 if (view.showSky && scene_sky_available_) {
2118 environment_texture_id_ = textureId;
2119 sky_texture_id_ = panorama;
2120 draw_sky_ = true;
2121 }
2122 break;
2123 }
2124
2125 std::array<glm::vec3, 9> sh;
2127 // params.x = 0: no specular atlas, so the sky is a diffuse term only.
2128 lights.setEnvironment(sh.data(), glm::vec4(0.0f, 1.0f, 0.0f, 0.0f),
2129 glm::vec3(std::max(view.skyIntensity, 0.0f)), 0.0f);
2130
2131 auto rig = [&](f32 azimuthDeg, f32 elevationDeg, f32 intensity) {
2132 if (intensity <= 0.0f) return;
2133 const f32 az = glm::radians(azimuthDeg + view.rotation);
2134 const f32 el = glm::radians(elevationDeg);
2135 // Toward the light; a directional light's aim is the way it travels.
2136 const glm::vec3 toLight(std::sin(az) * std::cos(el), std::sin(el), std::cos(az) * std::cos(el));
2137 const glm::vec3 aim = -toLight;
2138 GpuLight gpu;
2139 gpu.color = glm::vec4(1.0f, 1.0f, 1.0f, intensity);
2140 gpu.posDir = glm::vec4(aim.x, aim.y, 1.0f, aim.z);
2141 lights.addLight(gpu);
2142 ++light_cap_.accepted;
2143 };
2144 light_cap_.limit = MAX_LIGHTS;
2145 // Key from the upper left of a viewer standing on +z; the fill low on the far side.
2146 rig(-35.0f, 40.0f, view.keyIntensity);
2147 rig(145.0f, 15.0f, view.fillIntensity);
2148 light_cap_.requested = light_cap_.accepted;
2149
2150 // Last, as in the scene path: the masks are a question about the array just filled,
2151 // and with none of the scene's lights in it they come back empty rather than stale.
2152 collectShadow2D(registry);
2153 collectShape2D(registry);
2154}
2155
2156resource::EnvironmentHandle RenderFrame::environmentOf(const ecs::Light& light) const {
2157 return light.environment.isValid() ? light.environment : sky_environment_;
2158}
2159
2160bool RenderFrame::collectEnvironment(const ecs::Light& light, const glm::vec3& scale,
2161 bool withoutSun) {
2162 const resource::EnvironmentHandle handle = environmentOf(light);
2163 if (!handle.isValid()) return false;
2164 const Environment* environment = resource_manager_.getEnvironment(handle);
2165 if (!environment) return false;
2166
2167 u32 textureId = 0;
2168 if (environment->hasSpecular()) {
2169 if (Texture* atlas = resource_manager_.getTexture(environment->specular)) {
2170 textureId = atlas->getId();
2171 }
2172 }
2173 const glm::vec4 params{textureId != 0 ? 1.0f : 0.0f, environment->maxRange,
2174 static_cast<f32>(environment->mipCount) - 1.0f,
2175 environment->faceSize};
2176 const auto& baked = withoutSun ? environment->skyIrradiance : environment->irradiance;
2177 // The diffuse half on its own: the nine coefficients carry only what a surface is lit by, and the tint the shader
2178 // applies (scale) covers what it reflects as well, so this light's diffuse colour goes on the coefficients alone.
2179 const glm::vec3 tint = linear_color_ ? srgbToLinearCpu(glm::vec3{light.diffuseTint}) : glm::vec3{light.diffuseTint};
2180 const glm::vec3 diffuse = tint * std::max(light.diffuseScale, 0.0f);
2181 auto irradiance = baked;
2182 if (diffuse != glm::vec3(1.0f)) {
2183 for (glm::vec3& c : irradiance) c *= diffuse;
2184 }
2185 if (!context_.lights().setEnvironment(irradiance.data(), params, scale,
2186 glm::radians(light.environmentRotation))) {
2187 return false;
2188 }
2189 environment_texture_id_ = textureId;
2190 sky_texture_id_ = 0;
2191 if (environment->sky.isValid()) {
2192 if (Texture* sky = resource_manager_.getTexture(environment->sky)) sky_texture_id_ = sky->getId();
2193 }
2194 // Only an image can be looked at directly: the nine coefficients are the sky
2195 // averaged over every direction, which as a background is one flat colour.
2196 draw_sky_ = light.drawEnvironment && (textureId != 0 || sky_texture_id_ != 0);
2197 return true;
2198}
2199
2200RenderFrame::ShadowBounds RenderFrame::gatherShadowBounds(ecs::Registry& registry, bool includeHair) {
2201 auto meshes = registry.activeView<ecs::Transform, ecs::MeshRenderer>();
2202 ShadowBounds bounds;
2203 for (auto entity : meshes) {
2204 const auto& mesh = meshes.get<ecs::MeshRenderer>(entity);
2205 if (!mesh.enabled || !mesh.mesh.isValid()) continue;
2206 const Mesh* resident = resource_manager_.getMesh(mesh.mesh);
2207 if (!resident) continue;
2208 const auto* placements = registry.tryGet<ecs::MeshInstances>(entity);
2209 if (placements && placements->transforms.empty()) continue;
2210 const auto& materials = context_.materials();
2211 const f32 bend = materials.vertexBounds(mesh.material);
2212 const bool hair = includeHair && materials.hairShadowDensity(mesh.material) > 0.0f;
2213 glm::vec3 lo, hi;
2214 meshLocalBounds(*resident, placements ? placementCoarseMesh(resource_manager_, *resident, *placements) : nullptr, bend, lo, hi);
2215 if (!placements) {
2216 const auto* group = registry.tryGet<ecs::LODGroup>(entity);
2217 LodLevels levels;
2218 if (group && group->enabled && gatherLodLevels(resource_manager_, *group, *resident, levels)) {
2219 lo = levels.localMin - glm::vec3(bend);
2220 hi = levels.localMax + glm::vec3(bend);
2221 }
2222 }
2223 auto& transform = meshes.get<ecs::Transform>(entity);
2224 transform.ensureDecomposed();
2225 const glm::vec3 position = rebased(transform.worldPosition);
2226 const auto include = [&](const glm::vec3& centre, const glm::vec3& half) {
2227 bounds.all.include(centre, half);
2228 if (mesh.castShadows) bounds.casters.include(centre, half);
2229 if (hair) bounds.hair.include(centre, half);
2230 };
2231 if (placements) {
2232 const glm::mat3 linear(glm::mat4_cast(transform.worldRotation) * glm::scale(glm::mat4(1.0f), transform.worldScale));
2233 const glm::vec3 localCentre = (lo + hi) * 0.5f, localHalf = (hi - lo) * 0.5f;
2234 for (usize i = 0; i + 16 <= placements->transforms.size(); i += 16) {
2235 const f32* r = placements->transforms.data() + i;
2236 const glm::vec3 origin = position + linear * glm::vec3(r[3], r[7], r[11]);
2237 glm::vec3 centre, half;
2238 placement_bounds::transformedBox(linear, r, origin, localCentre, localHalf, centre, half);
2239 include(centre, half);
2240 }
2241 } else {
2242 glm::vec3 centre, half;
2243 orientedWorldAabb(position, transform.worldRotation, transform.worldScale, lo, hi, centre, half);
2244 include(centre, half);
2245 }
2246 }
2247 return bounds;
2248}
2249
2252static void frustumCorners(const glm::mat4& invVP, glm::vec3 out[8]) {
2253 u32 at = 0;
2254 for (f32 z : {-1.0f, 1.0f}) {
2255 for (f32 y : {-1.0f, 1.0f}) {
2256 for (f32 x : {-1.0f, 1.0f}) {
2257 const glm::vec4 p = invVP * glm::vec4(x, y, z, 1.0f);
2258 out[at++] = glm::vec3(p) / p.w;
2259 }
2260 }
2261 }
2262}
2263
2264static f32 splitFraction(u32 i, u32 count, f32 nearDist, f32 farDist, f32 lambda) {
2265 const f32 t = static_cast<f32>(i) / static_cast<f32>(count);
2266 const f32 logSplit = nearDist * std::pow(farDist / nearDist, t);
2267 const f32 uniform = nearDist + (farDist - nearDist) * t;
2268 const f32 d = uniform + lambda * (logSplit - uniform);
2269 return (d - nearDist) / std::max(farDist - nearDist, 1e-6f);
2270}
2271
2279static glm::mat4 spotProjection(f32 fovDegrees, f32 nearDist, f32 farDist) {
2280 const f32 half = glm::radians(std::clamp(fovDegrees, 1.0f, 179.0f) * 0.5f);
2281 const f32 cot = 1.0f / std::tan(half);
2282 glm::mat4 proj(0.0f);
2283 proj[0][0] = cot;
2284 proj[1][1] = cot;
2285 proj[2][2] = farDist / (nearDist - farDist);
2286 proj[2][3] = -1.0f;
2287 proj[3][2] = (nearDist * farDist) / (nearDist - farDist);
2288 return proj;
2289}
2290
2292static glm::vec3 shadowUp(const glm::vec3& dir) {
2293 return std::abs(dir.z) > 0.99f ? glm::vec3(0.0f, 1.0f, 0.0f) : glm::vec3(0.0f, 0.0f, 1.0f);
2294}
2295
2303static glm::mat4 coneShadow(const glm::vec3& pos, const glm::vec3& dir, f32 fovDegrees,
2304 f32 reach) {
2305 // A fraction of the reach and not a constant: a perspective depth spends its
2306 // precision next to the near plane, and one fixed in world units would put that
2307 // wherever the scene's scale happened to be.
2308 const f32 farPlane = std::max(reach, 1e-3f);
2309 const f32 nearPlane = std::max(farPlane * 0.005f, 1e-3f);
2310 return spotProjection(fovDegrees, nearPlane, farPlane)
2311 * glm::lookAt(pos, pos + dir, shadowUp(dir));
2312}
2313
2317static glm::vec3 cubeFace(u32 index) {
2318 glm::vec3 dir(0.0f);
2319 dir[static_cast<i32>(index / 2)] = (index % 2 == 0) ? 1.0f : -1.0f;
2320 return dir;
2321}
2322
2323void RenderFrame::setShadowBudget(u32 atlasSize, u32 cellSize, u32 cascades) {
2324 const auto powerOfTwo = [](u32 n) { return n > 0 && (n & (n - 1)) == 0; };
2325 if (!powerOfTwo(atlasSize) || atlasSize < 512 || atlasSize > 4096
2326 || !powerOfTwo(cellSize) || cellSize < 128 || cellSize > atlasSize / 2) {
2327 ES_LOG_WARN("invalid shadow quality budget: atlas {}, cell {}", atlasSize, cellSize);
2328 return;
2329 }
2330 shadow_cascades_ = std::clamp(cascades, 1u, MAX_SHADOW_CASCADES);
2331 if (shadow_atlas_size_ == atlasSize && shadow_cell_size_ == cellSize) return;
2332 shadow_atlas_size_ = atlasSize;
2333 shadow_cell_size_ = cellSize;
2334 shadow_atlas_ = ShadowAtlas(atlasSize, cellSize);
2335}
2336
2338 shadow_distance_ = std::isfinite(distance) ? std::max(distance, 0.0f) : 0.0f;
2339}
2340
2342 lighting_direct_ = on;
2343 context_.materials().setLightingDirect(on);
2344}
2345
2346static_assert(qualityCap(QualityValue::LoopLights) == static_cast<f32>(MAX_LIGHTS), "the loop's cap is the light block's array");
2347static_assert(qualityCap(QualityValue::TiledLights) == static_cast<f32>(MAX_TILED_LIGHTS), "the tiled cap is the tiled array");
2348static_assert(qualityCap(QualityValue::ShadowTiles) == static_cast<f32>(MAX_SHADOW_TILES), "the tile cap is the shadow arrays");
2349
2350bool RenderFrame::setQualityValue(const std::string& name, f32 value) {
2351 return context_.qualityValues().set(name, value);
2352}
2353
2355 shadow_2d_soft_samples_ = std::clamp(samples, 1u, 32u);
2356}
2357
2358void RenderFrame::buildShadowPlan(ecs::Registry& registry) {
2359 shadow_texture_id_ = 0;
2360 shadow_resource_ = rg::kNoResource;
2361 shadow_views_.clear();
2362 cloud_tile_ = -1;
2363 // Zeroed first, and the atlas given back: a tile that outlived its map would
2364 // shadow the scene against geometry from a frame that no longer exists.
2365 shadow_atlas_.reset();
2367 std::swap(shadow_plan_, previous_shadow_plan_);
2368 shadow_plan_.clear();
2369 shadow_plan_.atlasSize = shadow_atlas_size_;
2370 shadow_plan_.cellSize = shadow_cell_size_;
2371 ES_PROFILE_COUNTER("render.shadow.atlasBudget", shadow_atlas_size_);
2372 ES_PROFILE_COUNTER("render.shadow.atlasSize", 0);
2373 context_.lights().setShadowTiles(nullptr, nullptr, 0, glm::vec4(0.0f));
2374 if (!in_frame_ || !device_.isDeviceUsable()) return;
2375 // How far the sun's cloud shadow map reaches each way, in world units: 0 where no sky casts one, or there is no sun to dim.
2376 f32 cloudExtent = 0.0f;
2377#ifdef ES_ENABLE_POSTPROCESS
2378 if (cloud_sun_slot_ >= 0 && post_process_ && post_process_->isEngaged()) {
2379 f32 km = 0.0f, unitsPerKm = 0.0f;
2380 if (post_process_->cloudShadowCaster(km, unitsPerKm)) {
2381 cloudExtent = km * (unitsPerKm > 0.0f ? unitsPerKm : 1000.0f * world_units_per_meter_);
2382 }
2383 }
2384#endif
2385 if (shadow_casters_.empty() && cloudExtent <= 0.0f) return;
2386
2387 const glm::mat4 invVP = glm::inverse(view_projection_);
2388 // Clip's z axis back in world: w != 0 is an eye point, w == 0 says the projection
2389 // is orthographic and there is none. Cascades only pay off under perspective —
2390 // an orthographic view already spends its texels evenly over what it can see.
2391 const glm::vec4 eye = invVP * glm::vec4(0.0f, 0.0f, 1.0f, 0.0f);
2392 const bool perspective = std::abs(eye.w) > 1e-6f;
2393
2394 glm::vec3 corners[8];
2395 frustumCorners(invVP, corners);
2396 const ShadowBounds sceneBounds = gatherShadowBounds(registry, perspective);
2397 const auto& boundsMin = sceneBounds.all.min;
2398 const auto& boundsMax = sceneBounds.all.max;
2399 const bool haveBounds = sceneBounds.all.valid;
2400 // A map of a fixed size goes where the shadows come from. Centred on everything, a backdrop far behind a character takes it away from her: a large
2401 // receiver says nothing of where a shadow can start.
2402 const auto& castersMin = sceneBounds.casters.min;
2403 const auto& castersMax = sceneBounds.casters.max;
2404 const bool haveCasters = sceneBounds.casters.valid;
2405 // Hair is layers of cards a few millimetres apart, which a cascade spread over the view cannot tell apart: its texel is as wide as the gap.
2406 // So a perspective sun with cascades of its own also gets one fitted to the hair alone, first in its list (the nearest tile covering a
2407 // fragment wins), and everything that falls inside it, the face under a fringe included, is shadowed at that resolution.
2408 const auto& hairMin = sceneBounds.hair.min;
2409 const auto& hairMax = sceneBounds.hair.max;
2410 const bool haveHair = sceneBounds.hair.valid;
2411
2412 f32 nearDist = 0.0f, farDist = 1.0f;
2413 if (perspective) {
2414 const glm::vec3 eyePos = glm::vec3(eye) / eye.w;
2415 nearDist = glm::length((corners[0] + corners[3]) * 0.5f - eyePos);
2416 farDist = glm::length((corners[4] + corners[7]) * 0.5f - eyePos);
2417 // A near plane at zero would make the logarithmic split infinite, and one far
2418 // behind the far plane is a camera nothing can be seen through.
2419 nearDist = std::max(nearDist, 1e-3f);
2420 farDist = std::max(farDist, nearDist * 1.001f);
2421 // Nothing past the farthest piece of geometry in the scene can receive a shadow, so the cascades are spread over what is there and
2422 // not over the whole view: a close shot of a character in a view that reaches fifty metres otherwise spends its first cascade on
2423 // three. Rounded up by quarter octaves so the split moves a few times as the camera does, not every frame (a continuously
2424 // changing split is shadow edges that swim).
2425 f32 reach = shadow_distance_ > 0.0f ? shadow_distance_ : farDist;
2426 if (haveBounds) {
2427 f32 farthest = 0.0f;
2428 for (u32 i = 0; i < 8; ++i) {
2429 const glm::vec3 corner((i & 1) ? boundsMax.x : boundsMin.x, (i & 2) ? boundsMax.y : boundsMin.y,
2430 (i & 4) ? boundsMax.z : boundsMin.z);
2431 farthest = std::max(farthest, glm::length(corner - eyePos));
2432 }
2433 const f32 stepped = std::exp2(std::ceil(std::log2(std::max(farthest, 1e-3f)) * 4.0f) / 4.0f);
2434 reach = std::min(reach, stepped);
2435 }
2436 if (reach < farDist) {
2437 const f32 limitedFar = std::max(reach, nearDist * 1.001f);
2438 const f32 fraction = (limitedFar - nearDist) / (farDist - nearDist);
2439 for (u32 i = 0; i < 4; ++i) {
2440 corners[i + 4] = corners[i] + (corners[i + 4] - corners[i]) * fraction;
2441 }
2442 farDist = limitedFar;
2443 }
2444 }
2445
2446 // Who gets what. A light that stands somewhere claims first, because a sun taking the
2447 // atlas whole would leave every other caster mapless; the sun then loses its farthest
2448 // cascade rather than costing a light whose map cannot be shortened.
2449 struct TilePlan {
2450 u32 first = 0;
2451 u32 count = 0;
2452 };
2453 std::vector<TilePlan> plan(shadow_casters_.size());
2454 for (usize i = 0; i < shadow_casters_.size(); ++i) {
2455 const ShadowCaster& caster = shadow_casters_[i];
2456 if (caster.shape == ShadowShape::Box) continue;
2457 const u32 want = caster.shape == ShadowShape::Cube ? SHADOW_CUBE_FACES : 1;
2458 i32 at = -1;
2459 const ShadowGrant grant = claimTiles(shadow_atlas_, caster.light, want, 1, at);
2460 if (at >= 0) plan[i] = {static_cast<u32>(at), grant.granted};
2461 shadow_plan_.grants.push_back(grant);
2462 }
2463 // The sun's cloud shadow, before its cascades: one tile for the whole of what the camera sees under the clouds, where a cascade
2464 // is the nearest stretch of it. With the atlas full a sun then gives up its farthest cascade, as it does for a light that stands somewhere.
2465 if (cloudExtent > 0.0f) {
2466 claimTiles(shadow_atlas_, INVALID_ENTITY, 1, 1, cloud_tile_);
2467 }
2468 for (usize i = 0; i < shadow_casters_.size(); ++i) {
2469 const ShadowCaster& caster = shadow_casters_[i];
2470 if (caster.shape != ShadowShape::Box) continue;
2471 // A fixed reach is the author saying what the map covers; splitting it would
2472 // hand the rest of the atlas to slices they never asked for.
2473 const bool focus = haveHair && caster.extent <= 0.0f;
2474 const u32 want = (perspective && caster.extent <= 0.0f) ? shadow_cascades_ + (focus ? 1u : 0u) : 1;
2475 i32 at = -1;
2476 const ShadowGrant grant = claimTiles(shadow_atlas_, caster.light, want,
2478 if (at >= 0) plan[i] = {static_cast<u32>(at), grant.granted};
2479 shadow_plan_.grants.push_back(grant);
2480 }
2481 for (const ShadowGrant& g : shadow_plan_.grants) {
2482 shadow_plan_.requestedTiles += g.requested;
2483 shadow_plan_.grantedTiles += g.granted;
2484 // The light cap two hundred lines up warns when it drops a light. This is the
2485 // same contention over the same frame and said nothing at all, which is how a
2486 // light that stopped casting became a question with no answer in the engine.
2487 // Keep the live report every frame, but only log a new denial. A stable
2488 // over-budget scene must not spend every frame formatting the same warning.
2489 if (g.denied() && !previous_shadow_plan_.hasSameDenial(g)) {
2490 ES_LOG_WARN("shadow atlas: light {} asked for {} tile(s) and got none ({})",
2491 g.light.raw, g.requested, refusalName(g.refusal));
2492 }
2493 }
2494
2495 const u32 atlasSize = shadow_atlas_.occupiedSize();
2496 glm::mat4 matrices[MAX_SHADOW_TILES];
2497 glm::vec4 tiles[MAX_SHADOW_TILES];
2498 bool anyTile = false;
2499 if (cloud_tile_ >= 0) {
2500 // Along the sun's rays, round the camera, snapped to the map's own texels so the shadows do not crawl as the camera moves.
2501 // Every point on one ray is under the same cloud, so where along it the map stands does not matter: only x and y are read.
2502 const ShadowTile& tile = shadow_atlas_.tile(static_cast<u32>(cloud_tile_));
2503 const glm::vec3 toLight = -cloud_sun_aim_;
2504 const glm::vec3 up = shadowUp(toLight);
2505 const glm::mat4 lightRot = glm::lookAt(glm::vec3(0.0f), -toLight, up);
2506 const glm::mat4 lightRotInv = glm::inverse(lightRot);
2507 const glm::vec3 seen = perspective ? glm::vec3(eye) / eye.w : (corners[0] + corners[7]) * 0.5f;
2508 const f32 texel = (cloudExtent * 2.0f) / static_cast<f32>(tile.size);
2509 glm::vec3 inLight = glm::vec3(lightRot * glm::vec4(seen, 1.0f));
2510 inLight.x = std::floor(inLight.x / texel) * texel;
2511 inLight.y = std::floor(inLight.y / texel) * texel;
2512 const glm::vec3 centre = glm::vec3(lightRotInv * glm::vec4(inLight, 1.0f));
2513 const glm::mat4 lightView = glm::lookAt(centre + toLight * cloudExtent, centre, up);
2514 glm::mat4 lightProj(1.0f);
2515 lightProj[0][0] = 1.0f / cloudExtent;
2516 lightProj[1][1] = 1.0f / cloudExtent;
2517 lightProj[2][2] = -0.5f / cloudExtent;
2518 lightProj[3][2] = 0.0f;
2519 cloud_matrix_ = lightProj * lightView;
2520 matrices[cloud_tile_] = cloud_matrix_;
2521 tiles[cloud_tile_] = shadow_atlas_.unitRect(static_cast<u32>(cloud_tile_), atlasSize);
2522 context_.lights().setLightCloudTile(static_cast<u32>(cloud_sun_slot_), static_cast<u32>(cloud_tile_));
2523 anyTile = true;
2524 }
2525
2526 for (usize ci = 0; ci < shadow_casters_.size(); ++ci) {
2527 const ShadowCaster& caster = shadow_casters_[ci];
2528 const TilePlan mine = plan[ci];
2529 if (mine.count == 0) continue;
2530 u32 plannedTiles = 0;
2531 // The first tile of a perspective sun with cascades is the hair's, when there is hair; the cascades follow it.
2532 const bool hasFocus = haveHair && caster.shape == ShadowShape::Box && caster.extent <= 0.0f && mine.count > 1;
2533 const u32 cascadeCount = mine.count - (hasFocus ? 1u : 0u);
2534
2535 for (u32 c = 0; c < mine.count; ++c) {
2536 const u32 tileIndex = mine.first + c;
2537 const ShadowTile& tile = shadow_atlas_.tile(tileIndex);
2538 glm::mat4 projection(1.0f);
2539
2540 if (caster.shape != ShadowShape::Box) {
2541 // A receiver resolves in exactly one face, and whatever stands between
2542 // it and the light is inside that same face: a face's frustum IS the
2543 // cone from the light through everything the face covers.
2544 const bool cube = caster.shape == ShadowShape::Cube;
2545 projection = coneShadow(caster.pos, cube ? cubeFace(c) : caster.dir,
2546 cube ? 90.0f : caster.outerAngle, caster.range);
2547 } else {
2548 // The shader lights a surface from normalize(-aim), so rays travel the
2549 // other way; the rotation alone snaps a centre to the map's own grid.
2550 const glm::vec3 toLight = glm::normalize(-caster.dir);
2551 const glm::vec3 up = shadowUp(toLight);
2552 const glm::mat4 lightRot = glm::lookAt(glm::vec3(0.0f), -toLight, up);
2553 const glm::mat4 lightRotInv = glm::inverse(lightRot);
2554 glm::vec3 centre(0.0f);
2555 f32 radius = 1.0f;
2556 if (!perspective || caster.extent > 0.0f) {
2557 // What the map covers: the 3D geometry, unless the light asked for a
2558 // fixed reach. A radius, so coverage does not change as the light turns.
2559 const CameraView view = computeCameraView(view_projection_);
2560 const f32 fitted = haveBounds
2561 ? 0.5f * glm::length(boundsMax - boundsMin)
2562 : 0.5f * glm::length(glm::vec2(view.right - view.left,
2563 view.top - view.bottom));
2564 radius = caster.extent > 0.0f ? caster.extent : std::max(fitted, 1.0f);
2565 centre = caster.extent > 0.0f && haveCasters ? (castersMin + castersMax) * 0.5f
2566 : haveBounds ? (boundsMin + boundsMax) * 0.5f
2567 : glm::vec3(view.center.x, view.center.y, 0.0f);
2568 } else if (hasFocus && c == 0) {
2569 // The hair, as a sphere a little wider than its box so the face under it is inside, its radius stepped by quarter octaves
2570 // so the texel does not change every frame, and the centre snapped to the map's grid so the edges do not crawl.
2571 centre = (hairMin + hairMax) * 0.5f;
2572 const f32 wanted = std::max(0.5f * glm::length(hairMax - hairMin) * 1.25f, 0.02f);
2573 radius = std::exp2(std::ceil(std::log2(wanted) * 4.0f) / 4.0f);
2574 const f32 texel = (radius * 2.0f) / static_cast<f32>(tile.size);
2575 glm::vec3 inLight = glm::vec3(lightRot * glm::vec4(centre, 1.0f));
2576 inLight.x = std::floor(inLight.x / texel) * texel;
2577 inLight.y = std::floor(inLight.y / texel) * texel;
2578 centre = glm::vec3(lightRotInv * glm::vec4(inLight, 1.0f));
2579 } else {
2580 // This slice of the view, as a sphere: a box would grow and shrink as
2581 // the light turns, and the texel density with it.
2582 const u32 slot = hasFocus ? c - 1 : c;
2583 const f32 t0 = splitFraction(slot, cascadeCount, nearDist, farDist, caster.split);
2584 const f32 t1 = splitFraction(slot + 1, cascadeCount, nearDist, farDist, caster.split);
2585 glm::vec3 slice[8];
2586 for (u32 i = 0; i < 4; ++i) {
2587 const glm::vec3 ray = corners[i + 4] - corners[i];
2588 slice[i] = corners[i] + ray * t0;
2589 slice[i + 4] = corners[i] + ray * t1;
2590 }
2591 for (const glm::vec3& p : slice) centre += p;
2592 centre *= 0.125f;
2593 for (const glm::vec3& p : slice) {
2594 radius = std::max(radius, glm::length(p - centre));
2595 }
2596 // Snap to the map's own texel grid, in the light's axes: without it the
2597 // cascade slides continuously with the camera and every shadow edge
2598 // crawls along the geometry a texel at a time.
2599 const f32 texel = (radius * 2.0f) / static_cast<f32>(tile.size);
2600 glm::vec3 inLight = glm::vec3(lightRot * glm::vec4(centre, 1.0f));
2601 inLight.x = std::floor(inLight.x / texel) * texel;
2602 inLight.y = std::floor(inLight.y / texel) * texel;
2603 centre = glm::vec3(lightRotInv * glm::vec4(inLight, 1.0f));
2604 }
2605
2606 // ★ How far back the near plane goes. A cascade covers a slice of the VIEW,
2607 // but what shadows it can stand anywhere between the slice and the light —
2608 // clip at the slice and the caster is not drawn, and nothing says why.
2609 f32 castDistance = radius * 2.0f;
2610 if (haveBounds) {
2611 for (u32 i = 0; i < 8; ++i) {
2612 const glm::vec3 corner((i & 1) ? boundsMax.x : boundsMin.x,
2613 (i & 2) ? boundsMax.y : boundsMin.y,
2614 (i & 4) ? boundsMax.z : boundsMin.z);
2615 castDistance = std::max(castDistance, glm::dot(corner - centre, toLight));
2616 }
2617 }
2618 const glm::mat4 lightView = glm::lookAt(centre + toLight * castDistance,
2619 centre, up);
2620 // Written out rather than built from math::ortho: this maps the occluders it
2621 // draws onto exactly [0,1], so it needs no conversion for either device —
2622 // which is what lets the depths it writes be compared against the receiver's.
2623 glm::mat4 lightProj(1.0f);
2624 const f32 range = castDistance + radius * 2.0f;
2625 lightProj[0][0] = 1.0f / radius;
2626 lightProj[1][1] = 1.0f / radius;
2627 lightProj[2][2] = -1.0f / range;
2628 lightProj[3][2] = 0.0f;
2629 projection = lightProj * lightView;
2630 }
2631
2632 matrices[tileIndex] = projection;
2633 // Where the tile sits, and nothing else. What a comparison against it has
2634 // to forgive is not a property of the tile but of the fragment asking, and
2635 // is derived there out of this matrix and the size of the square.
2636 tiles[tileIndex] = shadow_atlas_.unitRect(tileIndex, atlasSize);
2637 tiles[tileIndex].w = packShadowBias(caster.bias, caster.slopeFloor);
2638
2639 // A face whose frustum misses the whole of the geometry gathers nothing, and
2640 // asking each mesh in turn is the only way to find that out otherwise. The
2641 // box every mesh is inside answers it once, for the price of one test.
2642 Frustum tileFrustum;
2643 tileFrustum.extractFromMatrix(projection);
2644 if (haveBounds && !tileFrustum.intersectsAABB((boundsMin + boundsMax) * 0.5f,
2645 (boundsMax - boundsMin) * 0.5f)) {
2646 continue;
2647 }
2648
2649 ShadowView view{projection, tile.x, tile.y, tile.size};
2650 // A sun's rays are parallel, so what a caster shades is a segment along them, down to the lowest thing that can receive it. That is
2651 // worth drawing only where the camera sees some of it. Not with a planar reflection in the frame (it looks through a frustum
2652 // of its own, and receives from the same atlas), nor without bounds to say where the rays end.
2653 if (caster.shape == ShadowShape::Box && haveBounds && planar_captures_.empty() && glm::length(caster.dir) > 1e-6f) {
2654 view.sun = true;
2655 view.ray = glm::normalize(caster.dir);
2656 view.floorY = boundsMin.y;
2657 view.reachCap = glm::length(boundsMax - boundsMin);
2658 }
2659 shadow_views_.push_back(view);
2660 ++plannedTiles;
2661 }
2662
2663 // A caster whose every tile was rejected has no map to read. Published anyway,
2664 // its range would cost each of the fragments it lights a fetch that can only
2665 // answer "nothing here".
2666 if (plannedTiles == 0) {
2667 plan[ci].count = 0;
2668 } else {
2669 anyTile = true;
2670 }
2671 }
2672
2673 ES_PROFILE_COUNTER("render.shadow.collects", static_cast<u32>(shadow_views_.size()));
2674 // Asked for BESIDE handed out: the two being equal is the only reading under
2675 // which "16 tiles" says the frame got what it wanted.
2676 ES_PROFILE_COUNTER("render.shadow.requested", shadow_plan_.requestedTiles);
2677 ES_PROFILE_COUNTER("render.shadow.denied", shadow_plan_.deniedCasters());
2678 ES_PROFILE_COUNTER("render.shadow.reduced", shadow_plan_.reducedCasters());
2679 if (!anyTile) return;
2680
2681 // The texture must exist before scene collection puts it in receiver sort keys.
2682 // Owned and kept, not pooled: what was drawn into it last frame is what lets this frame skip drawing it.
2683 if (!shadow_target_ || shadow_target_->getWidth() != atlasSize) {
2684 FramebufferSpec spec;
2685 spec.width = atlasSize;
2686 spec.height = atlasSize;
2687 spec.depthStencil = true;
2688 spec.linearFilter = false;
2689 spec.colorFormat = GfxPixelFormat::RGBA8;
2690 shadow_target_ = Framebuffer::create(device_, spec);
2691 shadow_drawn_valid_ = false;
2692 shadow_tiles_known_ = false;
2693 }
2694 if (!shadow_target_) {
2695 shadow_views_.clear();
2696 return;
2697 }
2698 shadow_resource_ = graph_.importTarget(shadow_target_->handle(), atlasSize, atlasSize, /*output=*/false,
2699 shadow_target_->getColorAttachment());
2700 if (shadow_resource_ == rg::kNoResource) {
2701 shadow_views_.clear();
2702 return;
2703 }
2704
2705 shadow_texture_id_ = static_cast<u32>(graph_.textureOf(shadow_resource_));
2706 ES_PROFILE_COUNTER("render.shadow.atlasSize", atlasSize);
2707 context_.lights().setShadowTiles(
2708 matrices, tiles, shadow_atlas_.tileCount(),
2709 glm::vec4(1.0f, 1.0f / static_cast<f32>(atlasSize), 0.0f, 0.0f));
2710 // Which of them each light reads. Without it a fragment would test against
2711 // every map in the atlas, including ones rendered from where it cannot see.
2712 for (usize i = 0; i < shadow_casters_.size(); ++i) {
2713 if (plan[i].count == 0) continue;
2714 context_.lights().setLightShadowTiles(shadow_casters_[i].slot,
2715 plan[i].first, plan[i].count);
2716 }
2717}
2718
2719void RenderFrame::declareShadowPass(ecs::Registry& registry) {
2720 if (shadow_resource_ == rg::kNoResource) {
2721 // A frame that plans no map gives the atlas back, as the pool it came from gave back what no frame asked for.
2722 shadow_target_.reset();
2723 shadow_drawn_valid_ = false;
2724 shadow_held_valid_ = false;
2725 shadow_lists_valid_ = false;
2726 return;
2727 }
2728
2729 u64 inputs = 0, heldInputs = 0;
2730 bool heldVouched = false;
2731 const bool vouched = shadowInputs(registry, inputs, heldInputs, heldVouched);
2732 const bool inputsMatch = vouched && shadow_drawn_valid_ && shadow_drawn_inputs_valid_ && inputs == shadow_drawn_inputs_;
2733 const bool skipped = inputsMatch && !registry.changeAuditEnabled();
2734 if (skipped) {
2735 shadow_reused_ = true;
2736 } else {
2737 u64 key = 0;
2738 const bool trusted = collectShadowViews(registry, inputs, vouched, heldInputs, heldVouched, key);
2739 shadow_reused_ = trusted && shadow_drawn_valid_ && key == shadow_drawn_key_;
2740 if (inputsMatch && !shadow_reused_) {
2741 ++shadow_inputs_stale_;
2742 if (!warned_shadow_inputs_) {
2743 warned_shadow_inputs_ = true;
2744 ES_LOG_WARN("change audit: the shadow collect's inputs were those of the frame that drew the atlas, but it drew"
2745 " something else - it reads something its inputs do not say");
2746 }
2747 }
2748 if (shadow_reused_) {
2749 // The atlas stands, and now also for these inputs.
2750 shadow_drawn_inputs_ = inputs;
2751 shadow_drawn_inputs_valid_ = vouched;
2752 } else {
2753 shadow_pending_key_ = key;
2754 shadow_pending_trusted_ = trusted;
2755 shadow_pending_inputs_ = inputs;
2756 shadow_pending_inputs_valid_ = vouched;
2757 }
2758 }
2759 ES_PROFILE_COUNTER("render.shadow.collectSkipped", skipped ? 1u : 0u);
2760 // Why a frame could not skip it: 1 a caster could not vouch, 2 the atlas cannot be trusted to stand (a compute-written record, a
2761 // material that moves its vertices), 4 the inputs moved (the plugin says which of its own did: render.mesh.castChanged).
2762 ES_PROFILE_COUNTER("render.shadow.collectWhy", skipped ? 0u : (!vouched ? 1u : 0u) | (!shadow_drawn_valid_ ? 2u : 0u)
2763 | (vouched && shadow_drawn_inputs_valid_ && inputs != shadow_drawn_inputs_ ? 4u : 0u));
2764 ES_PROFILE_COUNTER("render.shadow.inputsStale", shadow_inputs_stale_);
2765 ES_PROFILE_COUNTER("render.shadow.reused", shadow_reused_ ? 1u : 0u);
2766 if (shadow_reused_) {
2767 // What this frame drew (nothing) and, apart from it, what the atlas it reads holds: the maps and draws of the frame that drew it.
2768 ES_PROFILE_COUNTER("render.shadow.tiles", 0u);
2769 ES_PROFILE_COUNTER("render.shadow.draws", 0u);
2770 ES_PROFILE_COUNTER("render.shadow.heldTiles", shadow_held_tiles_);
2771 ES_PROFILE_COUNTER("render.shadow.heldDraws", shadow_held_draws_);
2772 ES_PROFILE_COUNTER("render.shadow.castersCulled", shadow_casters_culled_);
2773 } else {
2774 // Recorded by the pass when it runs, not here: a pass the graph culls drew nothing, and its key would vouch for an atlas
2775 // that never held what it says.
2776 shadow_drawn_valid_ = false;
2777 }
2778
2779 shadow_frame_tiles_ = shadow_frame_draws_ = 0;
2780 shadow_tile_passes_left_ = 0;
2781 // The atlas already holds what this would draw: no pass, and every reader samples last frame's squares, which are this frame's.
2782 // Otherwise, square by square: under the layout the squares were drawn in, one whose key is what it holds stands, and only
2783 // the others are drawn, each in a pass that clears its own square. When every square changed, or the layout did, one pass
2784 // clears the atlas and draws them all.
2785 u32 kept = 0;
2786 if (!shadow_reused_) {
2787 const usize viewCount = shadow_views_.size();
2788 shadow_view_redraw_.assign(viewCount, 1);
2789 const bool bySquare = shadow_tiles_known_ && shadow_tile_layout_ == shadow_layout_ && shadow_tile_keys_.size() == viewCount;
2790 if (bySquare) {
2791 for (usize vi = 0; vi < viewCount; ++vi) {
2792 if (shadow_tile_held_[vi] && shadow_tile_keys_[vi] == shadow_view_keys_[vi]) {
2793 shadow_view_redraw_[vi] = 0;
2794 ++kept;
2795 }
2796 }
2797 }
2798 // White is depth 1 unpacked: nothing here. A square the plan kept but whose collect comes back empty reads as no occluder
2799 // rather than as a black wall. The map is the packed depth in its colour; the depth buffer beside it only orders the casters
2800 // while they are drawn.
2801 const auto square = [](rg::PassDesc& pass) {
2802 pass.discardDepth = true;
2803 pass.clear = true;
2804 pass.clearDepth = true;
2805 pass.clearColor[0] = pass.clearColor[1] = pass.clearColor[2] = pass.clearColor[3] = 1.0f;
2806 };
2807 if (kept == 0) {
2808 // One pass for every map, because they share an attachment: a point light's six faces are six viewports inside it
2809 // rather than six passes the device has to transition the atlas between.
2810 rg::PassDesc shadow;
2811 shadow.name = "shadow-atlas";
2812 shadow.write = shadow_resource_;
2813 square(shadow);
2814 shadow.execute = [this](const rg::PassContext&) { executeShadowPass(); };
2815 graph_.addPass(std::move(shadow));
2816 } else if (kept == viewCount) {
2817 // Every square holds what it would draw (the atlas as a whole differed only in what its key mixes beside them).
2818 recordShadowTiles(false);
2819 } else {
2820 shadow_tile_passes_left_ = static_cast<u32>(viewCount - kept);
2821 for (usize vi = 0; vi < viewCount; ++vi) {
2822 if (!shadow_view_redraw_[vi]) continue;
2823 const ShadowView& view = shadow_views_[vi];
2824 rg::PassDesc tile;
2825 tile.name = "shadow-square";
2826 tile.write = shadow_resource_;
2827 square(tile);
2828 tile.clearViewportOnly = true;
2829 tile.viewportX = view.x;
2830 tile.viewportY = view.y;
2831 tile.viewportW = view.size;
2832 tile.viewportH = view.size;
2833 tile.execute = [this, vi](const rg::PassContext&) { executeShadowTile(vi); };
2834 graph_.addPass(std::move(tile));
2835 }
2836 }
2837 }
2838 // Squares a frame that drew did not have to draw, because they hold what they would; and since the renderer started, those
2839 // and the squares drawn on their own beside them (a gate reads a frame after the one that did it).
2840 ES_PROFILE_COUNTER("render.shadow.tilesKept", kept);
2841 if (shadow_tile_passes_left_ > 0) {
2842 shadow_squares_kept_total_ += kept;
2843 shadow_squares_drawn_total_ += shadow_tile_passes_left_;
2844 }
2845 ES_PROFILE_COUNTER("render.shadow.squaresKeptTotal", shadow_squares_kept_total_);
2846 ES_PROFILE_COUNTER("render.shadow.squaresDrawnTotal", shadow_squares_drawn_total_);
2847#ifdef ES_ENABLE_POSTPROCESS
2848 if (cloud_tile_ < 0 || !post_process_) return;
2849 // The sky draws what of the sun its clouds leave into the sun's tile, before the scene reads it: white above, that in the alpha.
2850 rg::PassDesc cloud;
2851 cloud.name = "cloud-shadow";
2852 cloud.write = shadow_resource_;
2853 cloud.keep = true;
2854 cloud.discardDepth = true;
2855 const glm::vec4 rect = shadow_atlas_.unitRect(static_cast<u32>(cloud_tile_), shadow_atlas_.occupiedSize());
2856 const glm::mat4 inverse = glm::inverse(cloud_matrix_);
2857 cloud.execute = [this, rect, inverse](const rg::PassContext& ctx) { post_process_->drawCloudShadow(inverse, rect, ctx); };
2858 graph_.addPass(std::move(cloud));
2859#endif
2860}
2861
2862u32 RenderFrame::queueMaterialBake(u32 material, u32 shader, u32 target, u32 x, u32 y, u32 w, u32 h,
2863 const glm::vec4& a, const glm::vec4& b) {
2864 const u32 ticket = next_material_bake_++;
2865 if (next_material_bake_ == 0) next_material_bake_ = 1;
2866#ifdef ES_ENABLE_POSTPROCESS
2867 material_bakes_.push_back({ticket, material, shader, target, x, y, w, h, a, b});
2868 material_bake_states_[ticket] = 0;
2869#else
2870 material_bake_states_[ticket] = -1;
2871#endif
2872 return ticket;
2873}
2874
2876 if (!target) return;
2877#ifdef ES_ENABLE_POSTPROCESS
2878 if (water_sun_.target == target) water_sun_ = {};
2879 for (auto& capture : receiver_captures_) {
2880 if (capture && capture->bakeTarget == target) capture.reset();
2881 }
2882#endif
2883 material_bakes_.erase(std::remove_if(material_bakes_.begin(), material_bakes_.end(), [this, target](const MaterialBake& bake) {
2884 if (target != bake.target && target != bake.receiver) return false;
2885 material_bake_states_.erase(bake.ticket);
2886 return true;
2887 }), material_bakes_.end());
2888}
2889
2890bool RenderFrame::projectMaterialBake(u32 ticket, u32 material, u32 target, u32 instances) {
2891 if (material_bakes_.empty() || !material || !target || !instances || instances > 4194304) return false;
2892 auto& bake = material_bakes_.back();
2893 if (bake.ticket != ticket || bake.target == target || bake.projection) return false;
2894 bake.projection = material;
2895 bake.receiver = target;
2896 bake.instances = instances;
2897 return true;
2898}
2899
2901 auto it = material_bake_states_.find(ticket);
2902 if (it == material_bake_states_.end()) return -1;
2903 const i32 state = it->second;
2904 if (state != 0) material_bake_states_.erase(it);
2905 return state;
2906}
2907
2908void RenderFrame::declareMaterialBakes(ecs::Registry& registry) {
2909#ifdef ES_ENABLE_POSTPROCESS
2910 // Once a frame, by the first view that collects: the passes write textures of their own, not any view's picture.
2911 if (material_bakes_.empty() || material_bakes_frame_ == planar_frame_ || !post_process_) return;
2912 material_bakes_frame_ = planar_frame_;
2913 std::vector<MaterialBake> waiting;
2914 u32 scratch = 0;
2915 usize captureIndex = 0;
2916 for (const MaterialBake& bake : material_bakes_) {
2917 RenderTarget* target = target_manager_.get(bake.target);
2918 Shader* shader = resource_manager_.getShader(resource::ShaderHandle(bake.shader));
2919 RenderTarget* receiver = bake.projection ? target_manager_.get(bake.receiver) : nullptr;
2920 Shader* projector = bake.projection ? resource_manager_.getShader(context_.materials().shaderOf(bake.projection)) : nullptr;
2921 if (!target || !shader || bake.w == 0 || bake.h == 0 || (bake.projection && (!receiver || !projector))) {
2922 material_bake_states_[bake.ticket] = -1;
2923 continue;
2924 }
2925 // A program still compiling draws nothing: the bake waits a frame for it rather than leaving its rect as it was and saying done.
2926 if (!device_.programReady(shader->handle()) || (projector && !device_.programReady(projector->handle()))) {
2927 waiting.push_back(bake);
2928 continue;
2929 }
2930 glm::vec4 sun(0);
2931 ReceiverMaps maps;
2932 WaterSunField field;
2933 if (receiver) {
2934 sun = post_process_->bakeSun();
2935 const auto* layout = context_.materials().layoutFor(context_.materials().shaderOf(bake.projection));
2936 if (layout && layout->findTexture("u_bakeReceiverDepth") && sun.y > 0.0f) {
2937 maps = declareCausticReceivers(registry, bake, sun, captureIndex++);
2938 const glm::vec3 ray = -glm::refract(-glm::vec3(sun), glm::vec3(0,1,0), 1.0f / 1.333f);
2939 const f32 top = std::max(bake.b.x + bake.b.y - bake.b.z, 0.0f) + 0.01f * bake.b.w;
2940 field.texture = receiver->getColorTexture();
2941 field.target = bake.receiver;
2942 field.sunDirection = glm::vec3(sun);
2943 field.rect = {bake.a.x, bake.a.y, bake.a.z, bake.a.z / bake.w};
2944 field.depth = {bake.b.z, top, top + bake.b.w, bake.b.w / 15.0f};
2945 field.sun = {ray.x / ray.y, ray.z / ray.y, 0, 0};
2946 }
2947 }
2948 rg::PassDesc pass;
2949 pass.name = "material-bake";
2950 pass.keep = true;
2951 pass.write = graph_.importTarget(target->getFramebuffer(), target->getWidth(), target->getHeight(), /*output=*/false,
2952 target->getColorTexture());
2953 pass.viewportX = bake.x;
2954 pass.viewportY = bake.y;
2955 pass.viewportW = bake.w;
2956 pass.viewportH = bake.h;
2957 const u32 slot = scratch++;
2958 pass.execute = [this, bake, slot](const rg::PassContext&) {
2959 const std::vector<std::pair<std::string, glm::vec4>> overrides{{"u_bakeA", bake.a}, {"u_bakeB", bake.b}};
2960 const bool drawn = post_process_ && post_process_->drawMaterialThrough(bake.material, bake.shader, overrides, slot);
2961 material_bake_states_[bake.ticket] = drawn ? 1 : -1;
2962 if (drawn) ++material_bakes_drawn_;
2963 };
2964 const auto source = pass.write;
2965 graph_.addPass(std::move(pass));
2966 if (receiver) {
2967 rg::PassDesc projection;
2968 projection.name = "material-forward-projection";
2969 projection.keep = true;
2970 projection.dependencies = {source};
2971 if (maps.fixed != rg::kNoResource) projection.dependencies.push_back(maps.fixed);
2972 if (maps.moving != rg::kNoResource) projection.dependencies.push_back(maps.moving);
2973 projection.write = graph_.importTarget(receiver->getFramebuffer(), receiver->getWidth(), receiver->getHeight(),
2974 false, receiver->getColorTexture());
2975 projected_bake_resources_.push_back(projection.write);
2976 projection.clear = true;
2977 projection.clearColor[3] = 0.0f;
2978 const u32 projectionSlot = scratch++;
2979 projection.execute = [this, bake, projectionSlot, sun, maps, field](const rg::PassContext&) {
2980 if (material_bake_states_[bake.ticket] > 0)
2981 material_bake_states_[bake.ticket] = post_process_->drawProjectedMaterial(bake.projection, bake.instances, projectionSlot, sun,
2982 maps.window, graph_.textureOf(maps.fixed), graph_.textureOf(maps.moving)) ? 1 : -1;
2983 if (field.target || water_sun_.target == bake.receiver)
2984 water_sun_ = material_bake_states_[bake.ticket] > 0 ? field : WaterSunField{};
2985 };
2986 graph_.addPass(std::move(projection));
2987 }
2988 }
2989 material_bakes_ = std::move(waiting);
2990#else
2991 (void)registry;
2992#endif
2993}
2994
2995void RenderFrame::ensureShadowFrameUbos(u32 count) {
2996 const u32 bytes = RenderContext::frameConstantsSize();
2997 while (shadow_frame_ubos_.size() < count) {
2998 const BufferHandle ubo = device_.createBuffer(
2999 {GfxBufferUsage::Uniform, bytes, /*dynamic=*/true}, GfxContent::transient(), nullptr);
3000 if (ubo == BufferHandle::Invalid) break;
3001 shadow_frame_ubos_.push_back(ubo);
3002 }
3003}
3004
3005void RenderFrame::releaseShadowFrameUbos() {
3006 for (BufferHandle ubo : shadow_frame_ubos_) {
3007 if (ubo != BufferHandle::Invalid) device_.deleteBuffer(ubo);
3008 }
3009 shadow_frame_ubos_.clear();
3010}
3011
3012bool RenderFrame::shadowInputs(ecs::Registry& registry, u64& key, u64& heldKey, bool& heldVouched) {
3014 u64 held = hash::kFnv64Offset;
3015 const auto mix = [&h, &held](u64 v) { h = hash::combine(h, v); held = hash::combine(held, v); };
3016 const auto words = [&h, &held](const void* data, usize bytes) {
3017 h = hash::combineWords(h, data, bytes);
3018 held = hash::combineWords(held, data, bytes);
3019 };
3020 bool vouched = true;
3021 heldVouched = true;
3022 auto ctx = makeContext();
3024 for (auto& plugin : plugins_) {
3025 if (!plugin->castsShadows()) continue;
3026 u64 part = 0, heldPart = 0;
3027 if (!plugin->castInputs(ctx, registry, part)) vouched = false;
3028 if (!plugin->castHeldInputs(heldPart)) heldVouched = false;
3029 h = hash::combine(h, part);
3030 held = hash::combine(held, heldPart);
3031 }
3032 mix(device_.deviceGeneration());
3033 mix(device_.geometryWrites());
3034 mix(static_cast<u64>(shadow_target_ ? static_cast<u32>(shadow_target_->handle()) : 0u));
3035 mix(shadow_views_.size());
3036 for (const ShadowView& view : shadow_views_) {
3037 words(&view.view_projection, sizeof(glm::mat4));
3038 mix((static_cast<u64>(view.x) << 32) | view.y);
3039 mix(view.size);
3040 mix(view.sun ? 1u : 0u);
3041 words(&view.ray, sizeof(view.ray));
3042 words(&view.floorY, sizeof(view.floorY));
3043 words(&view.reachCap, sizeof(view.reachCap));
3044 }
3045 words(&view_projection_, sizeof(glm::mat4));
3046 mix(shadow_receiver_cull_ ? 1u : 0u);
3047 mix(view_id_);
3048 key = h;
3049 heldKey = held;
3050 heldVouched = heldVouched && vouched;
3051 return vouched;
3052}
3053
3054void RenderFrame::collectShadowLists(ecs::Registry& registry, CasterSplit split, TransientBufferPool& pool,
3055 std::vector<DrawList>& lists, u32& culled) {
3056 const usize viewCount = shadow_views_.size();
3057 pool.beginFrame();
3058 if (lists.size() < viewCount) lists.resize(viewCount);
3059 culled = 0;
3060 for (usize vi = 0; vi < viewCount; ++vi) {
3061 const ShadowView& view = shadow_views_[vi];
3062 DrawList& list = lists[vi];
3063 list.clear();
3064 Frustum viewFrustum;
3065 viewFrustum.extractFromMatrix(view.view_projection);
3066 auto ctx = makeContext();
3067 ctx.view_projection = view.view_projection;
3069 RenderCollectContext collectCtx{registry, viewFrustum, clip_state_, pool,
3070 list, ctx,
3071 computeCameraView(view.view_projection)};
3072 if (view.sun && shadow_receiver_cull_) {
3073 collectCtx.shadowReceivers = &frustum_;
3074 collectCtx.shadowRay = view.ray;
3075 collectCtx.shadowFloor = view.floorY;
3076 collectCtx.shadowReachCap = view.reachCap;
3077 }
3078 collectCtx.screen_ui = screen_domain_;
3079 collectCtx.ui_tree_layers = ui_tree_layers_;
3080 collectCtx.lod = {view_id_, &lod_view_state_, nullptr, true};
3081 collectCtx.casters = split;
3082 for (auto& plugin : plugins_) {
3083 if (plugin->castsShadows()) plugin->collect(collectCtx);
3084 }
3085 culled += collectCtx.shadowCulled;
3086 list.finalize(pool);
3087 }
3088}
3089
3090u32 RenderFrame::shadowViewDraws(usize vi) const {
3091 u32 draws = 0;
3092 if (vi < shadow_view_lists_.size() && shadow_view_lists_[vi].commandCount() > 0) draws += shadow_view_lists_[vi].mergedDrawCallCount();
3093 if (vi < shadow_mover_lists_.size() && shadow_mover_lists_[vi].commandCount() > 0) draws += shadow_mover_lists_[vi].mergedDrawCallCount();
3094 return draws;
3095}
3096
3097bool RenderFrame::collectShadowViews(ecs::Registry& registry, u64 inputs, bool vouched, u64 heldInputs, bool heldVouched,
3098 u64& key) {
3099 const usize viewCount = shadow_views_.size();
3100 ensureShadowFrameUbos(static_cast<u32>(viewCount));
3102 const auto mix = [&h](u64 v) { h = hash::combine(h, v); };
3103 mix(device_.deviceGeneration());
3104 mix(device_.geometryWrites());
3105 mix(static_cast<u64>(shadow_target_ ? static_cast<u32>(shadow_target_->handle()) : 0u));
3106 const u64 base = h;
3107 mix(viewCount);
3108 for (const ShadowView& view : shadow_views_) {
3109 mix((static_cast<u64>(view.x) << 32) | view.y);
3110 mix(view.size);
3111 }
3112 mix(static_cast<u64>(static_cast<i64>(cloud_tile_)));
3113 mix(shadow_target_ ? shadow_target_->getWidth() : 0u);
3114 shadow_layout_ = h;
3115 const bool audit = registry.changeAuditEnabled();
3116 const bool sized = shadow_view_lists_.size() >= viewCount && shadow_mover_lists_.size() >= viewCount
3117 && shadow_held_hash_.size() == viewCount;
3118 if (!audit && vouched && sized && shadow_lists_valid_ && inputs == shadow_lists_inputs_) {
3119 ++shadow_lists_kept_;
3120 ES_PROFILE_COUNTER("render.shadow.collectMode", 1u);
3121 key = shadow_lists_key_;
3122 return shadow_lists_trusted_;
3123 }
3124 const bool heldStands = heldVouched && sized && shadow_held_valid_ && heldInputs == shadow_held_inputs_;
3125 u32 moverCulled = 0;
3126 if (heldStands && !audit) {
3127 ES_PROFILE_COUNTER("render.shadow.collectMode", 2u);
3128 } else {
3129 const std::vector<u64> wasHashes = heldStands ? shadow_held_hash_ : std::vector<u64>{};
3130 collectShadowLists(registry, heldVouched ? CasterSplit::Held : CasterSplit::All, shadow_pool_, shadow_view_lists_,
3131 shadow_held_culled_);
3132 shadow_held_uploaded_ = false;
3133 ++shadow_held_builds_;
3134 ES_PROFILE_COUNTER("render.shadow.collectMode", heldVouched ? 3u : 4u);
3135 bool poolTrusted = true;
3136 for (u32 layout = 0; layout < LAYOUT_COUNT; ++layout) {
3137 if (shadow_pool_.indicesUsed(static_cast<LayoutId>(layout)) > 0) poolTrusted = false;
3138 }
3139 shadow_held_hash_.assign(viewCount, 0);
3140 shadow_held_trusted_.assign(viewCount, 0);
3141 for (usize vi = 0; vi < viewCount; ++vi) {
3142 bool viewTrusted = poolTrusted;
3143 shadow_held_hash_[vi] = shadow_view_lists_[vi].contentHashOfRecords(hash::kFnv64Offset, shadow_pool_, viewTrusted);
3144 shadow_held_trusted_[vi] = viewTrusted ? 1 : 0;
3145 }
3146 if (heldStands && wasHashes != shadow_held_hash_) {
3147 ++shadow_held_stale_;
3148 if (!warned_shadow_held_) {
3149 warned_shadow_held_ = true;
3150 ES_LOG_WARN("change audit: the shadow casters held from an earlier frame are not what they collect now - something"
3151 " they are derived from changed without moving their inputs");
3152 }
3153 }
3154 shadow_held_inputs_ = heldInputs;
3155 shadow_held_valid_ = heldVouched;
3156 }
3157 if (shadow_mover_lists_.size() < viewCount) shadow_mover_lists_.resize(viewCount);
3158 if (shadow_held_valid_) {
3159 collectShadowLists(registry, CasterSplit::Movers, shadow_mover_pool_, shadow_mover_lists_, moverCulled);
3160 ++shadow_mover_collects_;
3161 } else {
3162 shadow_mover_pool_.beginFrame();
3163 for (usize vi = 0; vi < viewCount; ++vi) shadow_mover_lists_[vi].clear();
3164 }
3165 shadow_pool_uploaded_ = false;
3166 shadow_casters_culled_ = shadow_held_culled_ + moverCulled;
3167 ES_PROFILE_COUNTER("render.shadow.heldBuilds", shadow_held_builds_);
3168 ES_PROFILE_COUNTER("render.shadow.heldStale", shadow_held_stale_);
3169
3170 bool moverPoolTrusted = true;
3171 for (u32 layout = 0; layout < LAYOUT_COUNT; ++layout) {
3172 if (shadow_mover_pool_.indicesUsed(static_cast<LayoutId>(layout)) > 0) moverPoolTrusted = false;
3173 }
3174 bool trusted = true;
3175 shadow_view_keys_.assign(viewCount, 0);
3176 shadow_view_trusted_.assign(viewCount, 0);
3177 const MaterialStore& materials = context_.materials();
3178 for (usize vi = 0; vi < viewCount; ++vi) {
3179 u64 v = base;
3180 const auto vmix = [&v](u64 x) { v = hash::combine(v, x); };
3181 const auto vwords = [&v](const void* data, usize bytes) { v = hash::combineWords(v, data, bytes); };
3182 const ShadowView& view = shadow_views_[vi];
3183 vwords(&view.view_projection, sizeof(glm::mat4));
3184 vmix((static_cast<u64>(view.x) << 32) | view.y);
3185 vmix(view.size);
3186 vmix(shadow_held_hash_[vi]);
3187 bool viewTrusted = shadow_held_trusted_[vi] != 0 && moverPoolTrusted;
3188 const DrawList& movers = shadow_mover_lists_[vi];
3189 v = movers.contentHashOfRecords(v, shadow_mover_pool_, viewTrusted);
3190 for (const DrawList* list : {static_cast<const DrawList*>(&shadow_view_lists_[vi]), &movers}) {
3191 for (u32 c = 0; c < list->commandCount(); ++c) {
3192 const DrawCommand& cmd = list->command(c);
3193 if (cmd.material_id == 0) continue;
3194 if (materials.hasVertexHook(cmd.material_id)) { viewTrusted = false; continue; }
3195 if (const MaterialRecord* m = materials.find(cmd.material_id)) {
3196 vwords(m->uboBytes.data(), m->uboBytes.size());
3197 for (const auto& binding : m->textures) vmix(binding.texture.id());
3198 }
3199 }
3200 }
3201 shadow_view_keys_[vi] = v;
3202 shadow_view_trusted_[vi] = viewTrusted ? 1 : 0;
3203 trusted = trusted && viewTrusted;
3204 mix(v);
3205 }
3206 key = h;
3207 shadow_lists_inputs_ = inputs;
3208 shadow_lists_valid_ = vouched && !audit;
3209 shadow_lists_key_ = key;
3210 shadow_lists_trusted_ = trusted;
3211 return trusted;
3212}
3213
3214void RenderFrame::drawShadowView(usize vi) {
3215 const ShadowView& view = shadow_views_[vi];
3216 DrawList& held = shadow_view_lists_[vi];
3217 DrawList* movers = vi < shadow_mover_lists_.size() ? &shadow_mover_lists_[vi] : nullptr;
3218 const bool anyHeld = held.commandCount() > 0;
3219 const bool anyMovers = movers && movers->commandCount() > 0;
3220 if (!anyHeld && !anyMovers) return;
3221 if (anyHeld && !shadow_held_uploaded_) {
3222 shadow_pool_.upload();
3223 shadow_held_uploaded_ = true;
3224 }
3225 if (anyMovers && !shadow_pool_uploaded_) {
3226 shadow_mover_pool_.upload();
3227 shadow_pool_uploaded_ = true;
3228 }
3229 device_.setViewport(view.x, view.y, view.size, view.size);
3230 context_.useFrameConstants(shadow_frame_ubos_[vi], view.view_projection);
3231 context_.lights().uploadAndBind();
3232 if (anyHeld) {
3233 held.execute(device_, shadow_pool_, context_.materials(), context_.getWhiteTextureId(), nullptr, context_.perDrawBlocks());
3234 }
3235 if (anyMovers) {
3236 movers->execute(device_, shadow_mover_pool_, context_.materials(), context_.getWhiteTextureId(), nullptr,
3237 context_.perDrawBlocks());
3238 }
3239 ++shadow_frame_tiles_;
3240 shadow_frame_draws_ += shadowViewDraws(vi);
3241}
3242
3243void RenderFrame::recordShadowTiles(bool all) {
3244 const usize viewCount = shadow_views_.size();
3245 if (all || !shadow_tiles_known_ || shadow_tile_keys_.size() != viewCount) {
3246 shadow_tile_keys_.assign(viewCount, 0);
3247 shadow_tile_held_.assign(viewCount, 0);
3248 shadow_tile_draws_.assign(viewCount, 0);
3249 }
3250 bool allDrawn = true;
3251 for (usize vi = 0; vi < viewCount; ++vi) {
3252 if (!all && !shadow_view_redraw_[vi]) continue;
3253 // A caster waiting for its depth shader still owes this tile a draw on a later frame.
3254 const bool complete = shadow_view_lists_[vi].skippedForProgram() == 0 && shadow_mover_lists_[vi].skippedForProgram() == 0;
3255 allDrawn = allDrawn && complete;
3256 shadow_tile_keys_[vi] = shadow_view_keys_[vi];
3257 shadow_tile_held_[vi] = shadow_view_trusted_[vi] && complete;
3258 shadow_tile_draws_[vi] = shadowViewDraws(vi);
3259 }
3260 shadow_tile_layout_ = shadow_layout_;
3261 shadow_tiles_known_ = true;
3262 // The atlas as a whole now holds this frame: the key (and the inputs) a frame with nothing changed compares with.
3263 shadow_drawn_key_ = shadow_pending_key_;
3264 shadow_drawn_valid_ = shadow_pending_trusted_ && allDrawn;
3265 shadow_drawn_inputs_ = shadow_pending_inputs_;
3266 shadow_drawn_inputs_valid_ = shadow_pending_inputs_valid_;
3267 u32 heldTiles = 0, heldDraws = 0;
3268 for (usize vi = 0; vi < viewCount; ++vi) {
3269 heldTiles += shadow_tile_draws_[vi] > 0 ? 1u : 0u;
3270 heldDraws += shadow_tile_draws_[vi];
3271 }
3272 shadow_held_tiles_ = heldTiles;
3273 shadow_held_draws_ = heldDraws;
3274 ES_PROFILE_COUNTER("render.shadow.tiles", shadow_frame_tiles_);
3275 ES_PROFILE_COUNTER("render.shadow.draws", shadow_frame_draws_);
3276 ES_PROFILE_COUNTER("render.shadow.heldTiles", shadow_held_tiles_);
3277 ES_PROFILE_COUNTER("render.shadow.heldDraws", shadow_held_draws_);
3278 ES_PROFILE_COUNTER("render.shadow.castersCulled", shadow_casters_culled_);
3279 ES_PROFILE_COUNTER("render.shadow.cullViews", [&] { u32 n = 0; for (const ShadowView& v : shadow_views_) n += v.sun ? 1u : 0u; return n; }());
3280}
3281
3282void RenderFrame::executeShadowTile(usize vi) {
3283 drawShadowView(vi);
3284 // The last square of the frame: the others stood, so the atlas now holds this frame whole.
3285 if (shadow_tile_passes_left_ > 0 && --shadow_tile_passes_left_ == 0) recordShadowTiles(false);
3286 device_.invalidatePipelineCache();
3287}
3288
3289void RenderFrame::executeShadowPass() {
3290 // What the pass cost, for a profiler and the gates that pin it: the maps it actually rendered and the draws they took. Neither
3291 // shows in a pixel, and a face that stopped being skipped would look exactly like one that never was.
3292 for (usize vi = 0; vi < shadow_views_.size(); ++vi) drawShadowView(vi);
3293 recordShadowTiles(true);
3294 // The scene draws next, through pipelines nothing here matches.
3295 device_.invalidatePipelineCache();
3296}
3297
3304void RenderFrame::collectSky(RenderCollectContext& ctx) {
3305 if (!draw_sky_) return;
3306 // The panorama where the environment carries one; the atlas' mip 0 is a
3307 // reflection's resolution, too coarse to look at, and only the fallback.
3308 const bool panorama = sky_texture_id_ != 0;
3309 if (!panorama && environment_texture_id_ == 0) return;
3310 u32& program = sky_programs_[panorama ? 1 : 0];
3311 bool& compiled = sky_compiled_[panorama ? 1 : 0];
3312 if (!compiled) {
3313 compiled = true;
3315 const auto target = resource_manager_.preferredShaderTarget();
3316 std::vector<std::string> features{"ES_ENV_MAP"};
3317 if (panorama) features.push_back("ES_SKY_PANORAMA");
3318 resource::ShaderHandle handle = resource_manager_.createShaderWithBindings(
3320 features, target),
3322 features, target),
3323 {}, resource_manager_.preferredShaderLanguage(), resource_manager_.deferLinks());
3324 if (auto* shader = resource_manager_.getShader(handle)) {
3325 program = shader->getProgramId();
3326 // After it links: at once, or (where shaders are not waited for) when it first draws.
3327 if (panorama && shader->language() == GfxShaderLanguage::GLSL_ES300) shader->whenLinked([](Shader& s) {
3328 s.bind();
3329 s.setUniform("u_texture", 0);
3330 s.unbind();
3331 });
3332 }
3333 }
3334 if (program == 0) return;
3335 // Still compiling in the background: the sky is drawn from the frame its program is ready, as any draw is.
3336 if (device_.skipPendingPrograms() && !device_.programReady(ShaderHandle{program})) return;
3337
3338 // The rays through the screen's corners, at a depth inside both backends'
3339 // ranges: a quad at clip z = 1 rounds past the far plane at some view angles and
3340 // is clipped whole. The depth does not change which rays are drawn.
3341 const glm::mat4 invVP = glm::inverse(ctx.frame_context.view_projection);
3342 glm::vec3 corners[4];
3343 const glm::vec2 ndc[4] = {{-1.0f, -1.0f}, {1.0f, -1.0f}, {1.0f, 1.0f}, {-1.0f, 1.0f}};
3344 for (u32 i = 0; i < 4; ++i) {
3345 const glm::vec4 p = invVP * glm::vec4(ndc[i], 0.5f, 1.0f);
3346 corners[i] = glm::vec3(p) / p.w;
3347 }
3348
3349 BatchDrawKey key{};
3350 key.stage = RenderStage::Background;
3351 key.layer = std::numeric_limits<i32>::min();
3352 key.shaderId = program;
3353 key.blend = BlendMode::None;
3354 key.layoutId = LayoutId::Sky;
3355 // Slot 0 is the panorama, or a white fill the atlas variant never samples: the
3356 // atlas rides the unit the shaders pin it to either way.
3357 key.textureId = panorama ? sky_texture_id_ : ctx.frame_context.white_texture_id;
3358 key.envTextureId = environment_texture_id_;
3359 key.type = RenderType::Mesh;
3360 // Neither tested nor written: the sky is behind everything by being first, and
3361 // depth of its own would fight the geometry that draws over it.
3362 key.depthTest = false;
3363 key.depthWrite = false;
3364 appendIndexedDraw(ctx.buffer_pool, ctx.draw_list, ctx.clip_state, corners, 4,
3365 BATCH_QUAD_INDICES, 6, key);
3366#ifdef ES_ENABLE_POSTPROCESS
3367 if (post_process_) post_process_->setBackgroundSky(true);
3368#endif
3369}
3370
3371bool RenderFrame::visibleToCamera(i32 layer, const glm::vec3& center,
3372 const glm::vec3& halfExtents) const {
3373 if (!draw_list_.layerVisible(DrawList::layerBit(layer))) return false;
3374 return frustum_.intersectsAABB(center, halfExtents);
3375}
3376
3378 const Entity* entities, u32 count) {
3379 auto ctx = makeContext();
3380 // What the SCENE renders, read from the plan the last frame built rather than
3381 // assumed: a world with no shadow caster needs no depth variant, and readying
3382 // one would be six milliseconds spent on a program nothing asks for.
3383 const bool shadowPasses = !shadow_casters_.empty();
3385 for (auto& plugin : plugins_) {
3386 out += plugin->prewarm(ctx, registry, entities, count, shadowPasses);
3387 }
3388 return out;
3389}
3390
3392 auto ctx = makeContext();
3393 const bool shadowPasses = !shadow_casters_.empty();
3395 for (auto& plugin : plugins_) out += plugin->prewarmDocument(ctx, rows, count, shadowPasses);
3396 return out;
3397}
3398
3399void RenderFrame::declareSkinCache(ecs::Registry& registry) {
3400 if (!skin_cache_ || !skin_cache_->active() || skin_cache_frame_ == planar_frame_) return;
3401 skin_cache_frame_ = planar_frame_;
3402 auto ctx = makeContext();
3403 for (auto& plugin : plugins_) plugin->scheduleSkins(ctx, registry, *skin_cache_);
3404 ES_PROFILE_COUNTER("render.skinCache.meshes", skin_cache_->entryCount());
3405 ES_PROFILE_COUNTER("render.skinCache.refused", skin_cache_->refusedThisFrame());
3406 if (!skin_cache_->hasWork()) return;
3407 // A compute pass, kept, its own token target: what it writes are vertex buffers the graph does not track, and the passes
3408 // after it in the frame read them.
3409 rg::TargetDesc token;
3410 token.width = 1;
3411 token.height = 1;
3413 token.storage = true;
3414 token.linearFilter = false;
3415 rg::PassDesc pass;
3416 pass.name = "skin-cache";
3417 pass.compute = true;
3418 pass.keep = true;
3419 pass.write = graph_.createTarget(token);
3420 pass.execute = [this](const rg::PassContext&) { skin_cache_->run(); };
3421 graph_.addPass(std::move(pass));
3422}
3423
3424void RenderFrame::collectAll(ecs::Registry& registry, bool sceneGBuffer) {
3425 ES_PROFILE_SCOPE("render.collect");
3426 // Split because "collect is expensive" names no mechanism: planning shadows,
3427 // gathering lights and walking one render type's population are different
3428 // work that a single total cannot be told apart by.
3429 { ES_PROFILE_SCOPE("render.collect.clip"); buildClipState(); }
3430 { ES_PROFILE_SCOPE("render.collect.sorting"); buildSortingGroups(registry); buildTreeSequence(registry); }
3431 // After the groups, because a mask's reach is stated in the order a group may own.
3432 { ES_PROFILE_SCOPE("render.collect.spriteMasks"); buildSpriteMasks(registry); }
3433 { ES_PROFILE_SCOPE("render.collect.lights"); collectLights(registry); }
3434 // Beside the lights and for the same reason: this answers what reaches a point
3435 // that no light can be asked about, and the mesh collect below reads both.
3436 { ES_PROFILE_SCOPE("render.collect.probes"); collectProbes(registry); }
3437 // After the lights: what a bake says a surface MIRRORS replaces what the
3438 // ambient light's own environment would have answered.
3439 { ES_PROFILE_SCOPE("render.collect.reflections"); collectReflections(registry); }
3440 // A view that shows one part of the light keeps only that part, for this camera alone.
3441 {
3442 const ShadingMode viewMode = view_shading_.get(view_id_);
3443 if (viewMode == ShadingMode::DirectLighting) context_.lights().isolate(true);
3444 else if (viewMode == ShadingMode::IndirectLighting) context_.lights().isolate(false);
3445 }
3446 // Before the plugins and after nothing: it reads the scene and this camera's
3447 // projection, both of which are already settled when the collect opens.
3448 { ES_PROFILE_SCOPE("render.collect.occluders"); collectOccluders(registry); }
3449 // Decided here, drawn by the graph. Nothing in this function may touch the
3450 // device: the frame reaches the host as several calls with its own draws
3451 // between them, and a pass opened here would swallow them.
3452 // Before the shadows: every pass of the frame draws the skins one dispatch posed.
3453 { ES_PROFILE_SCOPE("render.collect.skinCache"); declareSkinCache(registry); }
3454 { ES_PROFILE_SCOPE("render.collect.shadowPlan"); buildShadowPlan(registry); }
3455 { ES_PROFILE_SCOPE("render.collect.shadowDeclare"); declareShadowPass(registry); }
3456 declareMaterialBakes(registry);
3457 { ES_PROFILE_SCOPE("render.collect.shadow2dDeclare"); declareShadow2DPass(); }
3458 { ES_PROFILE_SCOPE("render.collect.shape2dDeclare"); declareShape2DPass(); }
3459 { ES_PROFILE_SCOPE("render.collect.planar"); declarePlanarReflection(registry); }
3460 { ES_PROFILE_SCOPE("render.collect.probeCapture"); declareProbeCapture(registry); }
3461
3462 auto ctx = makeContext();
3463#ifdef ES_ENABLE_POSTPROCESS
3464 // Asked at the collect, because it decides which program each material draw is compiled as; the
3465 // scene pass that executes them is the one the answer is about.
3466 ctx.gbuffer = sceneGBuffer && post_process_ && post_process_->sceneHasGBuffer();
3467 // A temporal effect that follows moving surfaces: the scene collect remembers where each mesh stands,
3468 // and the motion collect below compares.
3469 const bool followMotion = sceneGBuffer && post_process_ && post_process_->isEngaged()
3470 && post_process_->velocityWanted();
3471 ctx.track_motion = followMotion;
3472 ctx.motion_key = static_cast<u64>(current_target_);
3473 ctx.motion_frame = planar_frame_;
3474#else
3475 (void)sceneGBuffer;
3476#endif
3477
3478 RenderCollectContext collectCtx{registry, frustum_, clip_state_, pool_, draw_list_, ctx,
3479 computeCameraView(ctx.view_projection)};
3480 // What this collect must NOT draw. A camera's job is the world; the screen's
3481 // entities are laid out in pixels centred on the origin, and drawing them
3482 // through a view matrix puts a HUD wherever the view happens to be looking.
3483 collectCtx.screen_ui = screen_domain_;
3484 collectCtx.ui_tree_layers = ui_tree_layers_;
3485 collectCtx.lod = {view_id_, &lod_view_state_, &lod_counts_};
3486 collectCtx.shading = view_shading_.get(view_id_);
3487 collectCtx.weights = view_shading_.weights(view_id_);
3488 // Only the camera collect. The shadow collect above builds its own context and
3489 // leaves this null: what a player cannot see still casts, and a caster dropped
3490 // because the camera cannot see IT takes its shadow off the ground with it.
3491 collectCtx.occlusion = &occlusion_;
3492 { ES_PROFILE_SCOPE("render.collect.sky"); collectSky(collectCtx); }
3493 for (auto& plugin : plugins_) {
3494 ES_PROFILE_SCOPE(plugin->collectScope());
3495 plugin->collect(collectCtx);
3496 }
3497 // After every plugin, so a label draws over what shares its layer: the world's labels, culled in world space (the view is rebased).
3498 if (retained_text_collected_) {
3499 ES_PROFILE_SCOPE("render.collect.text");
3500 const glm::mat4 world = view_projection_ * glm::translate(glm::mat4(1.0f), -glm::vec3(renderOrigin()));
3501 submitRetainedText(registry, false, glm::value_ptr(world));
3502 }
3503
3504 // The other half of what the frame cost: what it did NOT draw. Accumulated
3505 // like the per-type counts beside it, so a frame composited from several
3506 // cameras reports every cull each of them made.
3507 stats_.culled += collectCtx.culled;
3508 stats_.occluded += collectCtx.occluded;
3509 stats_.lightsSpared += collectCtx.lightsSpared;
3510
3511 velocity_list_.clear();
3512 selection_list_.clear();
3513 cover_wanted_ = false;
3514#ifdef ES_ENABLE_POSTPROCESS
3515 if (followMotion) collectMotion(registry);
3516 // The editor's selection, for its outline: only a view that has one, on a device with float targets for the mask's depth.
3517 if (view_selection_.count(view_id_) && device_.supportsFloatTargets()) collectSelection(registry);
3518 if (sceneGBuffer && post_process_ && post_process_->isEngaged() && post_process_->coverWanted()) collectCover(registry);
3519#endif
3520
3521 // OR-ed across the frame's cameras, applied at the next beginFrame and never
3522 // mid-frame: the capture is scratch each camera composites out of, and the
3523 // editor's grid draws into it between begin() and this collect.
3524 frame_collected_ = true;
3525 frame_depth_seen_ = frame_depth_seen_ || draw_list_.needsDepth();
3526 frame_scene_picture_seen_ = frame_scene_picture_seen_ || draw_list_.anyNeedsScenePicture(context_.materials());
3527}
3528
3529void RenderFrame::collectSelection(ecs::Registry& registry) {
3530 ES_PROFILE_SCOPE("render.collect.selection");
3531#ifdef ES_ENABLE_POSTPROCESS
3532 selection_pool_.beginFrame();
3533 auto ctx = makeContext();
3534 // The motion program with no movement: "last frame" is this frame's camera, so it writes depth and coverage only.
3535 ctx.purpose = RenderPurpose::Motion;
3536 ctx.motion_key = static_cast<u64>(current_target_);
3537 ctx.motion_frame = planar_frame_;
3538 ctx.motion_prev_view_projection = ctx.view_projection;
3539 ctx.motion_prev_jitter = glm::vec2(0.0f);
3540 RenderCollectContext collectCtx{registry, frustum_, clip_state_, selection_pool_, selection_list_, ctx,
3541 computeCameraView(ctx.view_projection)};
3542 collectCtx.screen_ui = screen_domain_;
3543 collectCtx.ui_tree_layers = ui_tree_layers_;
3544 collectCtx.lod = {view_id_, &lod_view_state_, nullptr};
3545 collectCtx.selection = &view_selection_[view_id_];
3546 for (auto& plugin : plugins_) {
3547 if (plugin->drawsMotion()) plugin->collect(collectCtx);
3548 }
3549 selection_list_.finalize(selection_pool_);
3550#else
3551 (void)registry;
3552#endif
3553}
3554
3555rg::ResourceId RenderFrame::declareSelectionMask() {
3556 if (selection_list_.commandCount() == 0 || scene_viewport_.w <= 0 || scene_viewport_.h <= 0) return rg::kNoResource;
3557 const u32 w = static_cast<u32>(scene_viewport_.w), h = static_cast<u32>(scene_viewport_.h);
3558 if (!selection_fbo_ || selection_fbo_->getWidth() != w || selection_fbo_->getHeight() != h) {
3559 FramebufferSpec spec;
3560 spec.width = w;
3561 spec.height = h;
3562 // Depth in a 32-bit float, compared with the scene's to tell the selection in sight from the selection behind something.
3563 spec.colorFormat = GfxPixelFormat::RGBA32F;
3564 spec.depthStencil = true;
3565 spec.linearFilter = false;
3566 selection_fbo_ = Framebuffer::create(device_, spec);
3567 if (!selection_fbo_) return rg::kNoResource;
3568 }
3569 const rg::ResourceId mask = graph_.importTarget(selection_fbo_->handle(), w, h, /*output=*/false,
3570 selection_fbo_->getColorAttachment());
3571 rg::PassDesc pass;
3572 pass.name = "selection-mask";
3573 // The scene's depth is the mask's ground (see executeSelectionPass), so the scene is drawn first. Named, not read: a read
3574 // is bound at a unit as a colour, and the ground binds the depth itself.
3575 pass.dependencies = {scene_resource_};
3576 pass.write = mask;
3577 pass.clear = true;
3578 pass.clearDepth = true;
3579 // Alpha 0 is nothing selected there; g is the scene's distance from the eye, as far as a float goes where it has none to give.
3580 pass.clearColor[0] = pass.clearColor[2] = pass.clearColor[3] = 0.0f;
3581 pass.clearColor[1] = 1e30f;
3582 pass.execute = [this](const rg::PassContext&) { executeSelectionPass(); };
3583 graph_.addPass(std::move(pass));
3584 return mask;
3585}
3586
3587void RenderFrame::executeSelectionPass() {
3588 if (selection_list_.commandCount() == 0) return;
3589 ES_PROFILE_SCOPE("render.selection");
3590#ifdef ES_ENABLE_POSTPROCESS
3591 // The scene's depth where nothing selected covers: the outline tells at each of its pixels whether the scene stands in
3592 // front of the selection there. Read here, into the mask, because the pass that draws the ring may be drawing on the
3593 // very target that holds that depth.
3594 if (post_process_) post_process_->drawSelectionGround(graph_.depthTextureOf(scene_resource_));
3595#endif
3596 selection_pool_.upload();
3597 context_.updateCameraConstants(view_projection_, glm::vec2(0.0f));
3598 // The program is still a Lit shader and still declares the light block (see executeMotionPass).
3599 context_.lights().uploadAndBind();
3600 selection_list_.execute(device_, selection_pool_, context_.materials(), context_.getWhiteTextureId(),
3601 nullptr, context_.perDrawBlocks());
3602 device_.invalidatePipelineCache();
3603}
3604
3605void RenderFrame::collectMotion(ecs::Registry& registry) {
3606 ES_PROFILE_SCOPE("render.collect.motion");
3607#ifdef ES_ENABLE_POSTPROCESS
3608 const auto view = post_process_->peekTemporalView(view_projection_, static_cast<u64>(current_target_));
3609 // The shift is only there when something resolves it; a chain that follows motion without a history draws still.
3610 const bool shifted = post_process_->temporalActive();
3611 velocity_jitter_ = shifted ? view.jitter : glm::vec2(0.0f);
3612 velocity_pool_.beginFrame();
3613 velocity_list_.clear();
3614
3615 auto ctx = makeContext();
3616 ctx.purpose = RenderPurpose::Motion;
3617 ctx.track_motion = true;
3618 ctx.motion_key = static_cast<u64>(current_target_);
3619 ctx.motion_frame = planar_frame_;
3620 ctx.motion_prev_view_projection = view.previous;
3621 ctx.motion_prev_jitter = shifted ? view.previousJitter : glm::vec2(0.0f);
3622 RenderCollectContext collectCtx{registry, frustum_, clip_state_, velocity_pool_, velocity_list_, ctx,
3623 computeCameraView(ctx.view_projection)};
3624 collectCtx.screen_ui = screen_domain_;
3625 collectCtx.ui_tree_layers = ui_tree_layers_;
3626 // The level the scene settled on, not a new choice, and not counted a second time.
3627 collectCtx.lod = {view_id_, &lod_view_state_, nullptr};
3628 collectCtx.occlusion = &occlusion_;
3629 for (auto& plugin : plugins_) {
3630 if (plugin->drawsMotion()) plugin->collect(collectCtx);
3631 }
3632 velocity_list_.finalize(velocity_pool_);
3633#else
3634 (void)registry;
3635#endif
3636}
3637
3638bool RenderFrame::coverInputs(ecs::Registry& registry, u64& key, u64& heldKey, bool& heldVouched) {
3640 u64 held = hash::kFnv64Offset;
3641 const auto mix = [&h, &held](u64 v) { h = hash::combine(h, v); held = hash::combine(held, v); };
3642 bool vouched = true;
3643 heldVouched = true;
3644 auto ctx = makeContext();
3646 ctx.rainCover = true;
3647 for (auto& plugin : plugins_) {
3648 if (!plugin->castsShadows()) continue;
3649 u64 part = 0, heldPart = 0;
3650 if (!plugin->castInputs(ctx, registry, part)) vouched = false;
3651 if (!plugin->castHeldInputs(heldPart)) heldVouched = false;
3652 h = hash::combine(h, part);
3653 held = hash::combine(held, heldPart);
3654 }
3655 mix(device_.deviceGeneration());
3656 mix(device_.geometryWrites());
3657 h = hash::combineWords(h, &cover_view_projection_, sizeof(glm::mat4));
3658 held = hash::combineWords(held, &cover_view_projection_, sizeof(glm::mat4));
3659 mix(view_id_);
3660 key = h;
3661 heldKey = held;
3662 heldVouched = heldVouched && vouched;
3663 return vouched;
3664}
3665
3666void RenderFrame::collectCover(ecs::Registry& registry) {
3667 ES_PROFILE_SCOPE("render.collect.cover");
3668#ifdef ES_ENABLE_POSTPROCESS
3669 cover_wanted_ = true;
3670 const f32 range = post_process_->coverRange();
3671 const glm::vec4 eye4 = cameraFromViewProjection(view_projection_);
3672 const glm::vec3 eye = eye4.w > 0.5f ? glm::vec3(eye4) : glm::vec3(0.0f);
3673 const f32 texel = (range * 2.0f) / 1024.0f;
3674 const glm::vec3 centre(std::floor(eye.x / texel) * texel, eye.y, std::floor(eye.z / texel) * texel);
3675 const f32 depth = range * 2.0f;
3676 const glm::mat4 view = glm::lookAt(centre + glm::vec3(0.0f, range, 0.0f), centre, glm::vec3(0.0f, 0.0f, -1.0f));
3677 glm::mat4 proj(1.0f);
3678 proj[0][0] = 1.0f / range;
3679 proj[1][1] = 1.0f / range;
3680 proj[2][2] = -1.0f / depth;
3681 proj[3][2] = 0.0f;
3682 cover_view_projection_ = proj * view;
3683
3684 u64 inputs = 0, heldInputs = 0;
3685 bool heldVouched = false;
3686 const bool vouched = coverInputs(registry, inputs, heldInputs, heldVouched);
3687 const bool audit = registry.changeAuditEnabled();
3688 if (!audit && vouched && cover_lists_valid_ && inputs == cover_lists_inputs_) {
3689 ES_PROFILE_COUNTER("render.cover.collectMode", 1u);
3690 return;
3691 }
3692
3693 Frustum frustum;
3694 frustum.extractFromMatrix(cover_view_projection_);
3695 const auto collectInto = [&](CasterSplit split, TransientBufferPool& pool, DrawList& list) {
3696 pool.beginFrame();
3697 list.clear();
3698 auto ctx = makeContext();
3699 ctx.view_projection = cover_view_projection_;
3701 ctx.rainCover = true;
3702 RenderCollectContext collectCtx{registry, frustum, clip_state_, pool, list, ctx,
3703 computeCameraView(cover_view_projection_)};
3704 collectCtx.screen_ui = screen_domain_;
3705 collectCtx.ui_tree_layers = ui_tree_layers_;
3706 collectCtx.casters = split;
3707 for (auto& plugin : plugins_) {
3708 if (plugin->castsShadows()) plugin->collect(collectCtx);
3709 }
3710 list.finalize(pool);
3711 };
3712
3713 const bool heldStands = heldVouched && cover_held_valid_ && heldInputs == cover_held_inputs_;
3714 if (heldStands && !audit) {
3715 ES_PROFILE_COUNTER("render.cover.collectMode", 2u);
3716 } else {
3717 collectInto(heldVouched ? CasterSplit::Held : CasterSplit::All, cover_pool_, cover_list_);
3718 cover_held_uploaded_ = false;
3719 ++cover_builds_;
3720 ES_PROFILE_COUNTER("render.cover.collectMode", heldVouched ? 3u : 4u);
3721 bool trusted = true;
3722 for (u32 layout = 0; layout < LAYOUT_COUNT; ++layout) {
3723 if (cover_pool_.indicesUsed(static_cast<LayoutId>(layout)) > 0) trusted = false;
3724 }
3725 cover_held_hash_ = cover_list_.contentHashOfRecords(hash::kFnv64Offset, cover_pool_, trusted);
3726 cover_held_trusted_ = trusted;
3727 cover_held_inputs_ = heldInputs;
3728 cover_held_valid_ = heldVouched;
3729 }
3730 if (cover_held_valid_) {
3731 collectInto(CasterSplit::Movers, cover_mover_pool_, cover_mover_list_);
3732 ++cover_mover_collects_;
3733 } else {
3734 cover_mover_pool_.beginFrame();
3735 cover_mover_list_.clear();
3736 }
3737 cover_movers_uploaded_ = false;
3738
3739 u64 h = hash::combine(hash::kFnv64Offset, device_.deviceGeneration());
3740 h = hash::combine(h, device_.geometryWrites());
3741 h = hash::combineWords(h, &cover_view_projection_, sizeof(glm::mat4));
3742 h = hash::combine(h, cover_held_hash_);
3743 bool trusted = cover_held_trusted_;
3744 for (u32 layout = 0; layout < LAYOUT_COUNT; ++layout) {
3745 if (cover_mover_pool_.indicesUsed(static_cast<LayoutId>(layout)) > 0) trusted = false;
3746 }
3747 h = cover_mover_list_.contentHashOfRecords(h, cover_mover_pool_, trusted);
3748 const MaterialStore& materials = context_.materials();
3749 for (const DrawList* list : {&cover_list_, &cover_mover_list_}) {
3750 for (u32 c = 0; c < list->commandCount(); ++c) {
3751 const DrawCommand& cmd = list->command(c);
3752 if (cmd.material_id == 0) continue;
3753 if (materials.hasVertexHook(cmd.material_id)) { trusted = false; continue; }
3754 if (const MaterialRecord* m = materials.find(cmd.material_id)) {
3755 h = hash::combineWords(h, m->uboBytes.data(), m->uboBytes.size());
3756 for (const auto& binding : m->textures) h = hash::combine(h, binding.texture.id());
3757 }
3758 }
3759 }
3760 cover_key_ = h;
3761 cover_trusted_ = trusted;
3762 cover_lists_inputs_ = inputs;
3763 cover_lists_valid_ = vouched && !audit;
3764#else
3765 (void)registry;
3766#endif
3767}
3768
3769void RenderFrame::executeCoverPass() {
3770 if (coverCommandCount() == 0) return;
3771 ES_PROFILE_SCOPE("render.cover");
3772 if (cover_list_.commandCount() > 0 && !cover_held_uploaded_) {
3773 cover_pool_.upload();
3774 cover_held_uploaded_ = true;
3775 }
3776 if (cover_mover_list_.commandCount() > 0 && !cover_movers_uploaded_) {
3777 cover_mover_pool_.upload();
3778 cover_movers_uploaded_ = true;
3779 }
3780 if (cover_frame_ubo_ == BufferHandle::Invalid) {
3781 cover_frame_ubo_ = device_.createBuffer({GfxBufferUsage::Uniform, RenderContext::frameConstantsSize(), /*dynamic=*/true},
3782 GfxContent::transient(), nullptr);
3783 }
3784 if (cover_frame_ubo_ == BufferHandle::Invalid) return;
3785 device_.setViewport(0, 0, 1024, 1024);
3786 context_.useFrameConstants(cover_frame_ubo_, cover_view_projection_);
3787 context_.lights().uploadAndBind();
3788 if (cover_list_.commandCount() > 0) {
3789 cover_list_.execute(device_, cover_pool_, context_.materials(), context_.getWhiteTextureId(), nullptr,
3790 context_.perDrawBlocks());
3791 }
3792 if (cover_mover_list_.commandCount() > 0) {
3793 cover_mover_list_.execute(device_, cover_mover_pool_, context_.materials(), context_.getWhiteTextureId(), nullptr,
3794 context_.perDrawBlocks());
3795 }
3796 ++cover_draws_total_;
3797 ES_PROFILE_COUNTER("render.cover.draws", cover_list_.mergedDrawCallCount() + cover_mover_list_.mergedDrawCallCount());
3798#ifdef ES_ENABLE_POSTPROCESS
3799 cover_drawn_key_ = cover_key_;
3800 cover_drawn_valid_ = cover_trusted_ && cover_list_.skippedForProgram() == 0 && cover_mover_list_.skippedForProgram() == 0;
3801 cover_drawn_target_ = post_process_ ? post_process_->coverTargetId() : 0;
3802#endif
3803 context_.updateCameraConstants(view_projection_, scene_jitter_);
3804 device_.invalidatePipelineCache();
3805}
3806
3807void RenderFrame::executeMotionPass() {
3808 if (velocity_list_.commandCount() == 0) return;
3809 ES_PROFILE_SCOPE("render.motion");
3810 velocity_pool_.upload();
3811 // Through the camera the scene was drawn with, jitter included: a surface's depth here has to be the
3812 // scene's, since that is what the reader compares it with.
3813 context_.updateCameraConstants(view_projection_, velocity_jitter_);
3814 // The program is still a Lit shader and still declares the light block (see executeShadowPass).
3815 context_.lights().uploadAndBind();
3816 velocity_list_.execute(device_, velocity_pool_, context_.materials(), context_.getWhiteTextureId(),
3817 nullptr, context_.perDrawBlocks());
3818 ES_PROFILE_COUNTER("render.motion.draws", velocity_list_.mergedDrawCallCount());
3819 device_.invalidatePipelineCache();
3820}
3821
3822glm::vec3 srgbToLinearCpu(const glm::vec3& c) {
3823 auto conv = [](f32 v) {
3824 return v <= 0.04045f ? v / 12.92f : std::pow((v + 0.055f) / 1.055f, 2.4f);
3825 };
3826 return {conv(c.r), conv(c.g), conv(c.b)};
3827}
3828
3830 linear_color_ = linear;
3832#ifdef ES_ENABLE_POSTPROCESS
3833 if (post_process_) post_process_->setLinearOutput(linear);
3834#endif
3835}
3836
3837u32 RenderFrame::initBatchShader() {
3839}
3840
3841namespace {
3842
3843const std::vector<std::string>& batchVariantFeatures(BatchVariant variant) {
3844 static const std::vector<std::string> kPlain{};
3845 static const std::vector<std::string> kLit{"LIT"};
3846 static const std::vector<std::string> kAlphaClip{"ALPHA_CLIP"};
3847 static const std::vector<std::string> kPremultipliedColor{"PREMULTIPLIED_COLOR"};
3848 static const std::vector<std::string> kDisplayOutput{"DISPLAY_OUTPUT"};
3849 switch (variant) {
3850 case BatchVariant::Plain: return kPlain;
3851 case BatchVariant::Lit: return kLit;
3852 case BatchVariant::AlphaClip: return kAlphaClip;
3853 case BatchVariant::PremultipliedColor: return kPremultipliedColor;
3854 case BatchVariant::DisplayOutput: return kDisplayOutput;
3855 case BatchVariant::Count: break;
3856 }
3857 return kPlain;
3858}
3859
3860} // namespace
3861
3862const resource::ShaderHandle& RenderFrame::batchVariantHandle(const std::vector<std::string>& features) {
3863 const std::string key = resource::ShaderParser::variantKey(features);
3864 auto it = batch_variants_.find(key);
3865 if (it == batch_variants_.end()) {
3866 it = batch_variants_.emplace(key, compileBatchVariant(features)).first;
3867 }
3868 return it->second;
3869}
3870
3872 const resource::ShaderHandle*& handle = batch_variant_handles_[static_cast<usize>(variant)];
3873 if (!handle) handle = &batchVariantHandle(batchVariantFeatures(variant));
3874 Shader* shader = resource_manager_.getShader(*handle);
3875 return shader ? shader->getProgramId() : 0;
3876}
3877
3878u32 RenderFrame::batchProgram(const std::vector<std::string>& features) {
3879 Shader* shader = resource_manager_.getShader(batchVariantHandle(features));
3880 return shader ? shader->getProgramId() : 0;
3881}
3882
3884 static const std::string kDisplay = "DISPLAY_OUTPUT";
3885 std::vector<std::string> features;
3886 bool found = false;
3887 for (const auto& [key, handle] : batch_variants_) {
3888 Shader* shader = resource_manager_.getShader(handle);
3889 if (!shader || shader->getProgramId() != program) continue;
3890 size_t from = 0;
3891 while (from < key.size()) {
3892 const size_t bar = key.find('|', from);
3893 const size_t to = bar == std::string::npos ? key.size() : bar;
3894 features.push_back(key.substr(from, to - from));
3895 from = to + 1;
3896 }
3897 found = true;
3898 break;
3899 }
3900 if (!found || std::find(features.begin(), features.end(), kDisplay) != features.end()) return program;
3901 features.push_back(kDisplay);
3902 return batchProgram(features);
3903}
3904
3905resource::ShaderHandle RenderFrame::compileBatchVariant(const std::vector<std::string>& features) {
3906 // The batch shader is authored as a single .esshader with its WGSL twin,
3907 // embedded for the web build. Parse it and assemble the two stages for the
3908 // preferred target (single source of truth), injecting the requested
3909 // feature permutation — GLSL as #defines, WGSL through the assembly-time
3910 // preprocessor.
3911 const auto target = resource_manager_.preferredShaderTarget();
3913 // LIT is a Lit-domain variant: the domain drives the lighting injection,
3914 // same path as Lit material shaders.
3915 if (std::find(features.begin(), features.end(), "LIT") != features.end()) {
3916 parsed.domain = "Lit";
3917 }
3918 resource::ShaderHandle handle = resource_manager_.createShaderWithBindings(
3921 {{0, "a_position"}, {1, "a_color"}, {2, "a_texCoord"}},
3922 resource_manager_.preferredShaderLanguage(), resource_manager_.deferLinks());
3923
3924 Shader* shader = resource_manager_.getShader(handle);
3925 if (shader && shader->isValid()) {
3926 // After it links: at once, or (where shaders are not waited for) when a draw first needs it.
3927 // Sampler seeding is a GLSL concept; on WGSL the textures ride the bind group.
3928 if (shader->language() == GfxShaderLanguage::GLSL_ES300) shader->whenLinked([](Shader& s) {
3929 s.bind();
3930 // Bind the 8 multi-texture samplers to units 0..7 (per-program, set once).
3931 for (i32 i = 0; i < 8; ++i) {
3932 const std::string name = "u_textures[" + std::to_string(i) + "]";
3933 s.setUniform(name, i);
3934 }
3935 s.unbind();
3936 });
3937 return handle;
3938 }
3939
3940 const std::string vk = resource::ShaderParser::variantKey(features);
3941 ES_LOG_ERROR("Failed to create batch shader variant '{}'", vk.empty() ? "default" : vk.c_str());
3942 return {};
3943}
3944
3945} // namespace esengine
The single submission face: the ONLY place a DrawCommand is assembled.
Per-frame CPU scope timing (ES_PROFILE_SCOPE) read by the editor profiler.
#define ES_PROFILE_SCOPE(name)
#define ES_PROFILE_COUNTER(name, value)
Particles simulated by a compute kernel, drawn from the buffer the kernel wrote (WebGPU).
Hierarchy components for parent-child relationships.
Immediate mode 2D drawing API.
Engine-side 2D light registry — the per-frame LightConstants UBO and its CPU mirror.
2D light source component for the Lit material domain.
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
Shared mesh LOD eligibility and local bounds for drawing and shadow fitting.
Arbitrary-geometry 2D mesh renderable (deformed sprites, polygons, water surfaces,...
A box sight does not pass through, so what stands behind it is not drawn. ShadowCaster2D answers wher...
Conservative mesh reach and affine stretch for native placements.
What a shiny surface standing HERE reflects, when the sky is not it. LightProbeVolume answers the sam...
Frame resources and the shared scene rendering contract.
The point the frame is drawn relative to: a world far from zero loses precision in single floats,...
Parser for unified .esshader file format.
GPU shader program abstraction.
Marks an entity as a 2D shadow occluder for the Lit lighting path.
Makes a subtree sort as ONE unit against the rest of the scene.
Turns this entity's Sprite into a stencil the sprites drawn after it can be cut by.
2D sprite rendering component
Unified Transform component with local and world-space data.
void setUIStencilMask(u32 entity, i32 depth)
Definition ClipState.hpp:36
void setUIStencilTest(u32 entity, i32 depth)
Definition ClipState.hpp:42
void setScissor(u32 entity, i32 x, i32 y, i32 w, i32 h)
Definition ClipState.hpp:22
u32 mergedDrawCallCount() const
Definition DrawList.hpp:151
u32 depthMask() const
Definition DrawList.hpp:203
static u32 layerBit(i32 layer)
The mask bit of a sorting layer, or 0 when it has none (outside 0..31).
Definition DrawList.hpp:227
u32 mergedAwayCount() const
Definition DrawList.hpp:155
u32 breakCount(BatchBreak reason) const
Definition DrawList.hpp:153
u32 recordsInPass(i32 pass) const
void counter(const char *name, double value)
void gpuScope(const char *name, double ms)
static FrameProfiler & get()
static Unique< Framebuffer > create(GfxDevice &device, const FramebufferSpec &spec)
Creates a framebuffer from specification.
static constexpr GfxContent transient()
static constexpr GfxContent retained()
Abstract graphics device interface.
Definition GfxDevice.hpp:75
virtual void beginTimerQuery(u32 query)=0
Starts timing GPU work into a query; one query may be active at a time.
bool programReady(ShaderHandle program)
Whether program can be drawn with now, without waiting: linked, or finished linking in the background...
virtual GfxReadbackStatus pollReadback(ReadbackHandle handle)=0
The state of an in-flight readback; pumps backend completion events. A Failed readback is released by...
u32 createTimerQuery()
Creates a GPU elapsed-time query, or 0 when the backend cannot time GPU work.
virtual void endTimerQuery()=0
Stops the active timer query.
virtual bool takeReadback(ReadbackHandle handle, void *dest, usize destSize)=0
Copies a Ready readback's pixels (w*h*4 bytes) into dest and releases it.
bool isDeviceUsable() const
Whether work may be submitted — the one check the guards make.
virtual bool supportsFloatTargets()=0
Whether RGBA16F color attachments are renderable.
virtual bool timerDisjoint()=0
True when GPU timing was disturbed since the last check.
virtual bool getTimerQueryNs(u32 query, u64 *outNanoseconds)=0
Fetches a completed query's elapsed nanoseconds; false while still pending.
void end(GfxDevice &device)
void poll(GfxDevice &device)
void begin(GfxDevice &device)
void setShadowTiles(const glm::mat4 *matrices, const glm::vec4 *tiles, u32 count, const glm::vec4 &params)
resource::ShaderHandle shaderOf(u32 materialId) const
u32 count(QualityValue id) const
static u32 frameConstantsSize()
Bytes a buffer passed to useFrameConstants must hold.
LightStore & lights()
The engine-side per-frame 2D light registry (binding 2 LightConstants UBO).
MaterialStore & materials()
The engine-side material registry (handle -> resolved render state).
ProbeStore & probes()
The frame's probe volumes. Gathered beside the lights, because it answers the same question at the po...
u32 getWhiteTextureId() const
Gets the white texture handle's raw value (for untextured quads).
QualityValues & qualityValues()
void setEntityStencilMask(u32 entity, i32 refValue, bool hierarchical=false)
void renderToTarget(ecs::Registry &registry, const glm::mat4 &viewProjection, u32 w, u32 h)
u32 skeletalPreviewWidth(SkeletalPreviewId id) const
void endFrame()
Closes the FRAME, once, after every camera and every overlay.
void setColorSpace(bool linear)
Switch the frame to linear-light rendering (project colorSpace).
bool projectMaterialBake(u32 ticket, u32 material, u32 target, u32 instances)
void addPlugin(std::unique_ptr< RenderTypePlugin > plugin)
SkeletalPreviewId createSkeletalPreview(u32 w, u32 h)
void setEntityClipRect(u32 entity, i32 x, i32 y, i32 w, i32 h)
void setShadowBudget(u32 atlasSize, u32 cellSize, u32 cascades)
RenderPrewarmResult prewarmDocument(const MeshDocumentRecord *rows, u32 count)
The same readiness, from a prepared cell's own description — no entity of it need exist.
void begin(const glm::mat4 &view_projection, RenderTargetManager::Handle target=0)
void init(u32 width, u32 height)
u32 skeletalPreviewHeight(SkeletalPreviewId id) const
u32 displayProgram(u32 program)
void replayToDrawCall(i32 drawIndex)
const u8 * skeletalPreviewPixels(SkeletalPreviewId id) const
std::string takeTextureWants()
What each texture was asked for since the last take, as handle:side pairs joined by commas; the recor...
void submitRetainedText(ecs::Registry &registry, bool screen, const f32 *projection, u32 onlyRoot=0)
Every retained label laid out for one domain into the open list, culled against projection (world,...
void setLightingDirect(bool on)
u32 queueMaterialBake(u32 material, u32 shader, u32 target, u32 x, u32 y, u32 w, u32 h, const glm::vec4 &a, const glm::vec4 &b)
Draws material material through shader (a PostProcess-domain shader) into the rect (x,...
void cancelMaterialBakesFor(u32 target)
void beginFrame()
Opens the FRAME, once, before any of its cameras.
bool submitSkeletalPreviewBatch(SkeletalPreviewId id, const f32 *vertices, i32 vertexCount, const u16 *indices, i32 indexCount, u32 textureId, i32 blendMode, const f32 *transform16, i32 layer, f32 depth, u32 materialId, bool premultipliedColor=false)
void collectAll(ecs::Registry &registry, bool sceneGBuffer=true)
void submitSkeletalBatch(const f32 *vertices, i32 vertexCount, const u16 *indices, i32 indexCount, u32 textureId, i32 blendMode, const f32 *transform16, Entity entity, i32 layer, f32 depth, u32 materialId=0, bool premultipliedColor=false, f32 treeAlpha=1.0f, u32 cullBit=0)
Batch vertices posed by a skeletal runtime, drawn as one entity's geometry.
u32 batchProgram(BatchVariant variant)
i32 materialBakeState(u32 ticket)
A bake's state: 0 waiting, 1 drawn, -1 not drawable (no target, shader or material,...
void resize(u32 width, u32 height)
void setShadow2DSoftSamples(u32 samples)
How many samples across a light source a soft 2D shadow is drawn with: the quality level's say on the...
RenderFrame(GfxDevice &device, RenderContext &context, resource::ResourceManager &resource_manager)
bool renderSkeletalPreview(SkeletalPreviewId id, const glm::mat4 &viewProjection)
void destroySkeletalPreview(SkeletalPreviewId id)
bool setQualityValue(const std::string &name, f32 value)
RenderPrewarmResult prewarmPrograms(ecs::Registry &registry, const Entity *entities, u32 count)
Make ready the programs entities will need, drawing nothing.
u32 skeletalPreviewSize(SkeletalPreviewId id) const
void setEntityStencilTest(u32 entity, i32 refValue, bool hierarchical=false)
void setShadowDistance(f32 distance)
i32 pollSkeletalPreview(SkeletalPreviewId id)
bool visibleToCamera(i32 layer, const glm::vec3 &center, const glm::vec3 &halfExtents) const
Whether the camera being rendered right now would draw something of layer at these world bounds.
Handle create(u32 width, u32 height, bool depth=true, bool linearFilter=false, bool floatColor=false)
static constexpr Handle INVALID_HANDLE
RenderTarget * get(Handle handle)
TextureHandle getColorTexture() const
FramebufferHandle getFramebuffer() const
GPU shader program for rendering.
Definition Shader.hpp:86
u32 getProgramId() const
Gets the program handle's raw value, for command payloads and sort keys.
Definition Shader.hpp:257
GfxShaderLanguage language() const
The source language this program was compiled from.
Definition Shader.hpp:126
void whenLinked(std::function< void(Shader &)> fn)
Runs fn on this shader once it has linked: at once for one that has.
Definition Shader.cpp:164
ShaderHandle handle() const
Gets the device program handle.
Definition Shader.hpp:254
A square texture divided into a grid of cells, handed out as square blocks.
void reset()
Gives the whole atlas back. Called once per frame, before any claim.
void setTileBudget(u32 tiles)
static Unique< Texture > createVolume(GfxDevice &device, GfxContent content, u32 width, u32 height, u32 depth, const void *data, TextureFormat format)
A 3D texture, linearly filtered across all three axes and clamped at every edge.
Definition Texture.cpp:132
Central container for all entities and components.
Definition Registry.hpp:73
Central manager for GPU resources.
static void setLinearColorSpace(bool linear)
Process-global color-space mode. When linear, every assembled stage compiles with ES_LINEAR defined (...
static ParsedShader parse(const std::string &source)
Parses shader source into structured format (no include support).
static std::string variantKey(const std::vector< std::string > &features)
Stable cache key for a feature set (order-independent), e.g. "GRAYSCALE|TINT". Consumers key their co...
static std::string assembleStage(const ParsedShader &parsed, ShaderStage stage, const std::string &platform="", const std::vector< std::string > &features={}, ShaderTargetLanguage target=ShaderTargetLanguage::GLSL_ES300)
Assembles final GLSL source for a specific stage.
A frame's full-screen passes, compiled and run.
const std::vector< Entry > & last() const
u32 framesSkipped() const
Frames not timed because every slot was still waiting on the device.
void addPass(PassDesc pass)
ResourceId createTarget(const TargetDesc &desc)
void bounds(const Instance *instance, float *x, float *y, float *width, float *height)
constexpr const char * BATCH
@ VisibleOutside
Drawn only where the mask is NOT — a hole.
Definition Sprite.hpp:74
LightType
2D light kind. Point uses the Transform position + radius falloff; Directional uses the Transform's f...
Definition Light.hpp:36
constexpr u64 combine(u64 h, u64 v)
Definition Hash.hpp:33
constexpr u64 kFnv64Offset
Definition Hash.hpp:12
u64 combineWords(u64 h, const void *data, usize bytes)
Definition Hash.hpp:37
glm::mat4 perspective(float fov, float aspect, float nearPlane, float farPlane)
Creates a perspective projection matrix.
Definition Math.hpp:216
void transformedBox(const glm::mat3 &parent, const f32 *rows, const glm::vec3 &origin, const glm::vec3 &localCentre, const glm::vec3 &localHalf, glm::vec3 &centre, glm::vec3 &half)
f32 radius(const glm::vec3 &lo, const glm::vec3 &hi, f32 displacement)
Handle< esengine::Shader > ShaderHandle
Handle to a shader resource.
Definition Handle.hpp:214
Handle< esengine::Environment > EnvironmentHandle
Handle to a baked environment (irradiance + prefiltered reflection).
Definition Handle.hpp:229
constexpr ResourceId kNoResource
constexpr u32 MAX_LIGHTS
Max simultaneous 2D lights packed into the UBO. The injected fragment loop is a fixed bound; inactive...
static glm::vec3 environmentToWorld(const glm::vec3 &d, f32 yawDegrees)
static f32 splitFraction(u32 i, u32 count, f32 nearDist, f32 farDist, f32 lambda)
void meshLocalBounds(const Mesh &base, const Mesh *coarse, f32 displacement, glm::vec3 &lo, glm::vec3 &hi)
constexpr Unique< T > makeUnique(Args &&... args)
Creates a Unique pointer with the given arguments.
Definition Types.hpp:99
std::int32_t i32
Signed 32-bit integer.
Definition Types.hpp:54
void appendIndexedDraw(TransientBufferPool &pool, DrawList &drawList, const ClipState &clips, const void *verts, u32 vertexCount, const u32 *localIndices, u32 indexCount, const BatchDrawKey &key)
Copies raw vertices into the key's stream, then pushes one DrawCommand spanning them.
static glm::mat4 coneShadow(const glm::vec3 &pos, const glm::vec3 &dir, f32 fovDegrees, f32 reach)
constexpr u32 MAX_SHADOW_TILES
Max shadow tiles one frame's atlas hands out — the shader's array bound.
f32 packShadowBias(f32 texels, f32 slopeFloor)
constexpr u32 SHADOW_2D_TEXTURE_UNIT
constexpr u32 SHADOW_CUBE_FACES
Faces a point light's map is rendered as. Six cones at right angles cover every direction from a poin...
std::uint64_t u64
Unsigned 64-bit integer.
Definition Types.hpp:47
static glm::vec3 shadowUp(const glm::vec3 &dir)
An up that cannot be parallel to dir, whichever way it points.
std::size_t usize
Size type for indexing and sizes.
Definition Types.hpp:64
const ResolvedMask * nearestReachingMask(const ResolvedMask *masks, u32 count, const DrawList::SortIdentity &where)
The mask whose ref the stencil still holds at where, or null.
constexpr Entity INVALID_ENTITY
Invalid entity sentinel value.
Definition Types.hpp:174
constexpr u32 WATER_SUN_TEXTURE_UNIT
@ Capacity
More lights in view than the shader's arrays hold; the dimmest gave way.
Definition LightPlan.hpp:28
@ NoEnvironmentSun
Follows the environment's sun, and the frame's environment has none.
Definition LightPlan.hpp:30
static glm::vec3 lightForward(ecs::Transform *transform)
constexpr f32 qualityCap(QualityValue id)
static void frustumCorners(const glm::mat4 &invVP, glm::vec3 out[8])
@ RGBA16F
Half-float HDR (64 bpp); render use gated on supportsFloatTargets.
Definition Texture.hpp:50
glm::vec3 srgbToLinearCpu(const glm::vec3 &c)
constexpr f32 LIGHT_TILE_BITS
The sprite layers a light reaches ride in GpuLight::shadowMap.y above the atlas tile count: tiles + 8...
f32 packLightLayerRange(i32 layerMin, i32 layerMax)
The range of sprite layers a light reaches, as the number that rides in shadowMap....
static constexpr u32 LAYOUT_COUNT
Definition GfxEnums.hpp:102
ShadowGrant claimTiles(ShadowAtlas &atlas, Entity light, u32 want, u32 cells, i32 &outFirst, ShadowClaim policy=ShadowClaim::AllOrNothing)
Claim a complete shadow map, or explicitly allow fewer cascades.
glm::mat4 toClipDepthRange(const glm::mat4 &p, ClipDepthRange range)
The projection p as a device keeping range wants it.
static glm::mat4 spotProjection(f32 fovDegrees, f32 nearDist, f32 farDist)
std::uint32_t u32
Unsigned 32-bit integer.
Definition Types.hpp:45
const char * lightRefusalName(LightRefusal why)
The refusal as a word, for a log line and for a reader.
Definition LightPlan.hpp:34
constexpr u32 MAX_REFLECTION_PROBES
Columns of the reflection atlas one frame can address — column 0 the environment's,...
glm::vec3 rebased(const glm::vec3 &world)
A world position as the frame draws it: from the origin.
std::uint8_t u8
Unsigned 8-bit integer.
Definition Types.hpp:41
std::int64_t i64
Signed 64-bit integer.
Definition Types.hpp:56
constexpr u32 SHAPE_2D_TEXTURE_UNIT
ShadingMode
What a mesh is drawn WITH in a view, whatever its own material says.
std::uint16_t u16
Unsigned 16-bit integer.
Definition Types.hpp:43
glm::dvec3 & renderOrigin()
The origin, in world units. A double, as the world positions it is taken from are far from zero.
constexpr u32 MAX_TILED_LIGHTS
Lights a frame can carry through tiles, past the sixteen the loop reads directly. Three words of mask...
CameraView computeCameraView(const glm::mat4 &viewProjection)
LayoutId
Identifies a transient vertex stream / vertex format. Each layout has its own VBO+EBO+VAO in Transien...
Definition GfxEnums.hpp:88
const char * batchBreakCounter(BatchBreak r)
void orientedWorldAabb(const glm::vec3 &position, const glm::quat &rotation, const glm::vec3 &scale, const glm::vec3 &localMin, const glm::vec3 &localMax, glm::vec3 &outCentre, glm::vec3 &outHalf)
The world AABB of a turned box: its centre and half-extents, from a local box and the position,...
bool gatherLodLevels(resource::ResourceManager &resources, const ecs::LODGroup &group, const Mesh &base, LodLevels &out)
const char * refusalName(AtlasRefusal why)
The refusal as a word, for a log line and, later, for a reader.
const Mesh * placementCoarseMesh(resource::ResourceManager &resources, const Mesh &base, const ecs::MeshInstances &placements)
static EstellaContext & ctx()
constexpr u32 kShadowCascadeCells
static glm::vec3 cubeFace(u32 index)
constexpr u32 BATCH_QUAD_INDICES[6]
Canonical two-triangle quad winding shared by every batch path.
glm::vec4 cameraFromViewProjection(const glm::mat4 &viewProjection)
Where the frame is seen from, read out of the matrix that projects it.
ReadbackHandle
An in-flight framebuffer readback (GfxDevice::requestReadback).
Definition GfxEnums.hpp:43
float f32
32-bit floating point
Definition Types.hpp:59
static void neutralSkyIrradiance(std::array< glm::vec3, 9 > &sh)
constexpr u32 MAX_SHADOW_CASCADES
Slices one directional shadow map is split into, each covering a stretch of the view — so the near on...
The sorting identity a SortingGroup imposes on one of its members.
Definition DrawList.hpp:256
Entity identifier with packed index + generation.
Definition Types.hpp:135
void extractFromMatrix(const glm::mat4 &vp)
bool intersectsAABB(const glm::vec3 &center, const glm::vec3 &halfExtents) const
Plane planes[6]
Definition Frustum.hpp:28
bool intersectsSweptSphere(const glm::vec3 &a, const glm::vec3 &b, f32 radius) const
What a renderable's program key is made of, with no say in where the facts came from — a live entity'...
f32 signedDistance(const glm::vec3 &point) const
glm::vec3 normal
Definition Frustum.hpp:22
u32 culled
How many renderables this collect's frustum rejected.
WeightTarget weights
The one skinned draw this view colours by a joint's weights, if any.
u32 occluded
How many of those culled an OCCLUDER refused.
const OcclusionView * occlusion
What this view is already blocked by, or null for a collect that must not ask — a shadow face looks f...
ShadingMode shading
How the meshes of THIS collect are shaded. Shaded unless the view asked for another mode; a collect t...
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.
u32 lightsSpared
Light slots the lit quads of this collect were spared: per quad, the loop lights that cannot reach it...
const std::unordered_set< u32 > * selection
A motion collect that draws the editor's selection mask instead (RenderFrame::collectSelection): only...
const std::unordered_set< u32 > * screen_ui
The entities the SCREEN owns (UISystem::screenDomain), or null.
The frame's main-pass load-op: which attachments to clear, the color, and an optional region (w == 0 ...
Skeletal geometry a caller holds until it renders, owning its bytes.
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
What readying a set of renderables' programs found. Counts, not JSON: this crosses no boundary and pa...
Children list component.
Definition Hierarchy.hpp:66
std::vector< Entity > entities
List of child entity IDs.
Definition Hierarchy.hpp:69
A 2D light contributing to Lit-shaded materials.
Definition Light.hpp:54
Parent reference component.
Definition Hierarchy.hpp:46
One sorting identity for an entity and everything under it.
bool enabled
A disabled group is not a group: members sort on their own again.
Unified transform component.
Definition Transform.hpp:45
One full-screen pass.
std::function< void(const PassContext &)> execute
std::vector< ResourceId > reads
bool compute
A compute pass: no render pass is opened and no unit is bound — execute dispatches,...
std::vector< ResourceId > dependencies
Resources the pass uses but the graph must not bind.
bool keep
Wanted by a later frame rather than by this picture: not culled for nothing having read it yet.
u32 viewportX
The rect of its target this pass draws into. Zero width = all of it.
Shape of a target the graph allocates.
bool storage
Written by a compute shader (a pass with compute set), then sampled like any target.