Estella 0.113.0
A fast 2D and 3D game engine powered by WebAssembly and ECS
Loading...
Searching...
No Matches
PostProcessPipeline.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
13
15#include "../RenderOrigin.hpp"
16#include "./RenderContext.hpp"
17#include "./VoxelGI.hpp"
18#include "./DynamicGI.hpp"
19#include "../rhi/GfxDevice.hpp"
23#include "../rhi/Shader.hpp"
27#include "../../core/Log.hpp"
28#include <algorithm>
29#include <cmath>
30#include <cstring>
31
32#include "../rhi/GfxEnums.hpp"
33
34namespace esengine {
35
37 RenderContext& context,
38 resource::ResourceManager& resourceManager,
39 rg::RenderGraph& graph)
40 : device_(device)
41 , context_(context)
42 , resourceManager_(resourceManager)
43 , graph_(&graph)
44 , frameGraph_(&graph) {
45}
46
48 RenderContext& context,
49 resource::ResourceManager& resourceManager)
50 : device_(device)
51 , context_(context)
52 , resourceManager_(resourceManager) {
53}
54
56 if (initialized_) {
57 shutdown();
58 }
59}
60
61void PostProcessPipeline::init(u32 width, u32 height) {
62 if (initialized_) return;
63
64 width_ = width;
65 height_ = height;
66
67 blitShader_ = compileBlit({});
68 if (!blitShader_.isValid()) {
69 ES_LOG_ERROR("PostProcessPipeline: Failed to create blit shader");
70 return;
71 }
72
73 applySampleRequest();
74
75 initialized_ = true;
76}
77
85resource::ShaderHandle PostProcessPipeline::compileBlit(const std::vector<std::string>& features) {
86 const auto target = resourceManager_.preferredShaderTarget();
88 const auto handle = resourceManager_.createShader(
91 /*rewriteLoose=*/false,
92 resourceManager_.preferredShaderLanguage());
93 // Its parameters are read as a material's are, off the reflected layout: the block and the texture slot every variant declares.
94 if (handle.isValid()) {
95 context_.materials().registerLayout(handle, MaterialStore::layoutOf(parsed));
96 // The table's sampler is in the program only where the look is (the others do not read it, and the compiler drops it).
97 if (Shader* compiled = resourceManager_.getShader(handle);
98 compiled && compiled->language() == GfxShaderLanguage::GLSL_ES300 && compiled->hasUniform("u_displayLut")) {
99 compiled->bind();
100 for (const auto& p : parsed.properties) {
101 if (p.fromParam && p.name == "u_displayLut" && p.textureUnit >= 0) compiled->setUniform(p.name, static_cast<i32>(p.textureUnit));
102 }
103 compiled->unbind();
104 }
105 }
106 return handle;
107}
108
110 view_exposure_ = std::isfinite(ev) ? std::clamp(ev, -10.0f, 10.0f) : 0.0f;
111 context_.setViewExposure(view_exposure_);
112}
113
118resource::ShaderHandle PostProcessPipeline::blitVariant(bool upscale, OutputTransform transform, bool lut) {
119 const u32 key = (upscale ? 1u : 0u) | (static_cast<u32>(transform) << 1) | (lut ? 8u : 0u);
120 if (key == 0) return blitShader_;
121 if (const auto it = blitVariants_.find(key); it != blitVariants_.end()) return it->second;
122 std::vector<std::string> features;
123 if (upscale) features.push_back("ES_UPSCALE");
124 if (transform == OutputTransform::Neutral) features.push_back("ES_TONEMAP_NEUTRAL");
125 if (transform == OutputTransform::ACES) features.push_back("ES_TONEMAP");
126 if (lut) features.push_back("ES_DISPLAY_LUT");
127 const resource::ShaderHandle handle = compileBlit(features);
128 if (!handle.isValid()) ES_LOG_ERROR("PostProcessPipeline: the last pass would not compile with upscale={} curve={} lut={}", upscale, static_cast<u32>(transform), lut);
129 blitVariants_[key] = handle;
130 return handle;
131}
132
133resource::ShaderHandle PostProcessPipeline::outputShader() {
134 // What the last pass is asked for, and then, where a variant would not compile, less of it: the look first (it is the part a flat frame
135 // can do without), then the resampling, then the curve. Never a black frame.
136 const bool upscale = presentUpscales();
137 const bool lut = displayLutActive();
138 const struct { bool upscale; OutputTransform transform; bool lut; } wants[] = {
139 {upscale, output_transform_, lut},
140 {upscale, output_transform_, false},
141 {false, output_transform_, false},
142 {false, OutputTransform::None, false},
143 };
144 for (const auto& w : wants) {
145 const resource::ShaderHandle handle = blitVariant(w.upscale, w.transform, w.lut);
146 if (handle.isValid()) return handle;
147 }
148 return blitShader_;
149}
150
156GfxPixelFormat PostProcessPipeline::interFormat() const {
157 return frame_format_.effective;
158}
159
161void PostProcessPipeline::commitFormat() {
162 frame_format_ = decideHdrFormat(linear_output_, device_.supportsFloatTargets());
163}
164
165void PostProcessPipeline::ensureGraph() {
166 if (graph_) return;
167 // Only the frame-less fallback reaches here; with a frame, graph_ is the
168 // frame's from construction and this is a no-op.
169 ownedGraph_ = makeUnique<rg::RenderGraph>(device_);
170 graph_ = ownedGraph_.get();
171 commitFormat();
172 if (linear_output_) {
173 ES_LOG_INFO("PostProcess intermediates: {}",
174 interFormat() == GfxPixelFormat::RGBA16F ? "RGBA16F (HDR)"
175 : "SRGB8_ALPHA8 (LDR linear)");
176 }
177}
178
186rg::TargetDesc PostProcessPipeline::chainTarget(bool withDepth) const {
187 rg::TargetDesc desc;
188 desc.format = interFormat();
189 desc.linearFilter = true;
190 desc.depthStencil = withDepth;
191 return desc;
192}
193
200rg::TargetDesc PostProcessPipeline::blitSourceTarget(bool withDepth) const {
201 rg::TargetDesc desc = chainTarget(withDepth);
202 if (presentIsWholeMultiple()) desc.linearFilter = false;
203 return desc;
204}
205
207 if (!initialized_) return;
208
209 for (auto& pass : passes_) releasePassResources(pass);
210 for (auto& pass : screenPasses_) releasePassResources(pass);
211 releasePassResources(sky_capture_.copy);
212 releasePassResources(cloud_shadow_copy_);
213 dropSpareParamUbos();
214 sky_capture_.target.reset();
215 sky_capture_.state = SkyCapture::State::Idle;
216 for (auto& [source, program] : compute_cache_) device_.deleteCompute(program);
217 compute_cache_.clear();
218 voxel_gis_.clear();
219 dynamic_gis_.clear();
220 if (compute_view_ubo_ != BufferHandle::Invalid) {
221 device_.deleteBuffer(compute_view_ubo_);
222 compute_view_ubo_ = BufferHandle::Invalid;
223 }
224 passes_.clear();
225 screenPasses_.clear();
226 temporal_.clear();
227 feedback_.clear();
228
229 auto* device = &device_;
230 if (projected_triangle_indices_ != BufferHandle::Invalid && device) {
231 device->deleteBuffer(projected_triangle_indices_);
232 projected_triangle_indices_ = BufferHandle::Invalid;
233 }
234 if (screen_quad_vbo_ != BufferHandle::Invalid && device) {
235 device->deleteBuffer(screen_quad_vbo_);
236 screen_quad_vbo_ = BufferHandle::Invalid;
237 }
238 if (screen_quad_layout_ != VertexLayoutHandle::Invalid && device) {
239 device->deleteVertexLayout(screen_quad_layout_);
240 screen_quad_layout_ = VertexLayoutHandle::Invalid;
241 }
242
243 ownedGraph_.reset();
244 // Back to the frame's, not to none: the frame outlives a shutdown and goes on running its graph,
245 // so a pipeline restarted on a graph of its own declares passes nothing executes, and presents black.
246 graph_ = frameGraph_;
247 screenFBO_.reset();
248 sceneResource_ = rg::kNoResource;
249 screenCaptureActive_ = false;
250 screenFBOCreated_ = false;
251 sceneTexture_ = TextureHandle::Invalid;
252
253 if (blitShader_.isValid()) {
254 resourceManager_.releaseShader(blitShader_);
255 }
256 if (copyShader_.isValid()) {
257 resourceManager_.releaseShader(copyShader_);
258 copyShader_ = resource::ShaderHandle{};
259 }
260 if (exactCopyShader_.isValid()) {
261 resourceManager_.releaseShader(exactCopyShader_);
262 exactCopyShader_ = resource::ShaderHandle{};
263 }
264 if (rgbmShader_.isValid()) {
265 resourceManager_.releaseShader(rgbmShader_);
266 rgbmShader_ = resource::ShaderHandle{};
267 }
268 if (copyDepthShader_.isValid()) {
269 resourceManager_.releaseShader(copyDepthShader_);
270 copyDepthShader_ = resource::ShaderHandle{};
271 }
272 for (auto* outline : {&outlineShader_, &outlineGroundShader_}) {
273 if (outline->isValid()) resourceManager_.releaseShader(*outline);
274 *outline = resource::ShaderHandle{};
275 }
276 for (auto& [key, shader] : blitVariants_) {
277 if (shader.isValid()) resourceManager_.releaseShader(shader);
278 }
279 blitVariants_.clear();
280 if (blitParamUbo_ != BufferHandle::Invalid) {
281 device_.deleteBuffer(blitParamUbo_);
282 blitParamUbo_ = BufferHandle::Invalid;
283 blitParamAmount_ = -1.0f;
284 }
285
286 initialized_ = false;
287 ES_LOG_INFO("PostProcessPipeline shutdown");
288}
289
291 if (!initialized_) return;
292 if (width == width_ && height == height_) return;
293
294 width_ = width;
295 height_ = height;
296
297 // The pool is keyed by shape, so targets at the old size would never be
298 // handed out again — they would just sit there holding memory.
299 if (graph_) graph_->releasePool();
300 sceneResource_ = rg::kNoResource;
301 // History at the old size names texels this picture no longer has.
302 temporal_.clear();
303 feedback_.clear();
304
305 ensureGraph();
306
307 if (screenFBOCreated_) {
308 screenFBO_.reset();
309 screenFBOCreated_ = false;
310 ensureScreenFBO();
311 }
312}
313
315 PostProcessPass pass;
316 pass.name = name;
317 pass.shader = shader;
318 pass.enabled = true;
319
320 passes_.push_back(pass);
321 return static_cast<u32>(passes_.size() - 1);
322}
323
324bool PostProcessPipeline::supportsCompute() const { return device_.supportsCompute(); }
325
326bool PostProcessPipeline::runnable(const PostProcessPass& pass) const {
327 if (!pass.nativeKind.empty()) return pass.enabled && device_.supportsCompute();
328 return pass.enabled && (!pass.isCompute || (device_.supportsCompute() && pass.compute != ComputeHandle::Invalid));
329}
330
331bool PostProcessPipeline::programPending(const PostProcessPass& pass) const {
332 if (!device_.skipPendingPrograms() || !pass.nativeKind.empty() || pass.isCompute) return false;
333 const Shader* shader = resourceManager_.getShader(pass.shader);
334 return shader && !device_.programReady(shader->handle());
335}
336
337u32 PostProcessPipeline::addNativePass(const std::string& name, const std::string& kind) {
338 PostProcessPass pass;
339 pass.name = name;
340 pass.enabled = true;
341 pass.nativeKind = kind;
342 passes_.push_back(pass);
343 return static_cast<u32>(passes_.size() - 1);
344}
345
346u32 PostProcessPipeline::addComputePass(const std::string& name, const std::string& wgsl,
347 const std::vector<std::string>& params, u32 workgroupX, u32 workgroupY) {
348 PostProcessPass pass;
349 pass.name = name;
350 pass.enabled = true;
351 pass.isCompute = true;
352 pass.usesComputeDepth = wgsl.find("texture_depth") != std::string::npos;
353 pass.computeParams = params;
354 pass.workgroupX = std::max(workgroupX, 1u);
355 pass.workgroupY = std::max(workgroupY, 1u);
356 if (device_.supportsCompute()) {
357 auto cached = compute_cache_.find(wgsl);
358 if (cached == compute_cache_.end()) {
359 std::string log;
360 const ComputeHandle program = device_.createCompute(GfxComputeSource{GfxShaderLanguage::WGSL, wgsl.c_str(), "main"}, &log);
361 if (program == ComputeHandle::Invalid) {
362 ES_LOG_ERROR("PostProcessPipeline: compute pass '{}' did not compile: {}", name, log);
363 }
364 // A program that failed is remembered as failed, or every camera of every frame would try it again.
365 cached = compute_cache_.emplace(wgsl, program).first;
366 }
367 pass.compute = cached->second;
368 }
369 passes_.push_back(pass);
370 return static_cast<u32>(passes_.size() - 1);
371}
372
379void PostProcessPipeline::applySampleRequest() {
380 scene_samples_ = std::clamp(requested_samples_, 1u, device_.maxSamples());
381 // A frame with no chain draws straight to the backbuffer, which on a surface
382 // the host does not antialias needs the same answer — one setting, both paths.
383 device_.setSurfaceSamples(scene_samples_);
384}
385
387 requested_samples_ = samples < 1u ? 1u : samples;
388 if (initialized_) applySampleRequest();
389}
390
391void PostProcessPipeline::setPassScale(const std::string& passName, f32 scale) {
392 if (auto* pass = findPass(passName)) {
393 // A pass that draws at zero has no pixels and one that draws above the
394 // chain size would resample upward for nothing: neither is a fraction.
395 pass->scale = std::clamp(scale, 0.01f, 1.0f);
396 }
397}
398
399void PostProcessPipeline::setPassContinuesEffect(const std::string& passName) {
400 if (auto* pass = findPass(passName)) pass->continuesEffect = true;
401}
402
403bool PostProcessPipeline::passHasTexture(const PostProcessPass& pass, const char* name) {
404 const MaterialUniformLayout* layout = context_.materials().layoutFor(pass.shader);
405 if (!layout) return false;
406 for (const auto& slot : layout->textures) {
407 if (slot.name == name) return true;
408 }
409 return false;
410}
411
412bool PostProcessPipeline::passUsesLights(const PostProcessPass& pass) {
413 const MaterialUniformLayout* layout = context_.materials().layoutFor(pass.shader);
414 return layout && layout->usesLights;
415}
416
417bool PostProcessPipeline::passIsTemporal(const PostProcessPass& pass) {
418 return passHasTexture(pass, "u_history");
419}
420
421u64 PostProcessPipeline::feedbackKey(const std::string& passName) const {
422 return temporalKey_ * 1000003ull + std::hash<std::string>{}(passName);
423}
424
425bool PostProcessPipeline::passesWantGBuffer() {
426 if (bypass_) return false;
427 for (const auto& pass : passes_) {
428 if (!pass.enabled) continue;
429 // The voxel GI reads the surface's normal, whatever the effect's shader (it has none).
430 if (!pass.nativeKind.empty()) {
431 // Measuring (DynamicGI u_skip bit 32): this pass does not ask for the G-buffer, to read what the G-buffer scene costs by itself.
432 if (const auto skip = pass.floatUniforms.find("u_skip"); skip != pass.floatUniforms.end() && (static_cast<u32>(skip->second) & 32u)) continue;
433 if (device_.supportsCompute()) return true;
434 continue;
435 }
436 const MaterialUniformLayout* layout = context_.materials().layoutFor(pass.shader);
437 if (layout && layout->usesGBuffer) return true;
438 }
439 return false;
440}
441
443 if (!initialized_ || bypass_) return false;
444 for (const auto& pass : passes_) {
445 if (pass.enabled && passIsTemporal(pass)) return true;
446 }
447 return false;
448}
449
451 if (!initialized_ || bypass_) return false;
452 for (const auto& pass : passes_) {
453 if (!pass.enabled || !pass.nativeKind.empty() || passIsTemporal(pass)) continue;
454 const MaterialUniformLayout* layout = context_.materials().layoutFor(pass.shader);
455 if (layout && layout->find("u_prevViewProjection0")) return true;
456 }
457 return false;
458}
459
460void PostProcessPipeline::trackView(const glm::mat4& viewProjection, u64 key) {
461 TemporalState& state = temporal_[key];
462 temporalKey_ = key;
463 state.previous = state.frame > 0 ? viewProjectionFromOrigin(state.current, state.origin) : viewProjection;
464 state.current = viewProjection;
465 state.origin = renderOrigin();
466 ++state.frame;
467}
468
470 if (!initialized_ || bypass_) return false;
471 for (const auto& pass : passes_) {
472 if (!pass.enabled || !pass.nativeKind.empty()) continue;
473 const MaterialUniformLayout* layout = context_.materials().layoutFor(pass.shader);
474 if (!layout || !layout->find("u_sceneCoverage")) continue;
475 if (const auto it = pass.floatUniforms.find("u_panorama"); it != pass.floatUniforms.end() && it->second > 0.001f) continue;
476 return true;
477 }
478 return false;
479}
480
482 if (!initialized_ || bypass_ || !device_.supportsFloatTargets()) return false;
483 for (const auto& pass : passes_) {
484 if (pass.enabled && passHasTexture(pass, "u_velocity")) return true;
485 }
486 return false;
487}
488
489namespace {
491f32 halton(u32 index, u32 base) {
492 f32 f = 1.0f, r = 0.0f;
493 while (index > 0) {
494 f /= static_cast<f32>(base);
495 r += f * static_cast<f32>(index % base);
496 index /= base;
497 }
498 return r;
499}
502constexpr u32 kJitterPhases = 8;
503} // namespace
504
505glm::vec2 PostProcessPipeline::beginTemporalView(const glm::mat4& viewProjection, u64 key) {
506 TemporalState& state = temporal_[key];
507 temporalKey_ = key;
508 if (state.frame > 0) state.previous = viewProjectionFromOrigin(state.current, state.origin);
509 else state.previous = viewProjection;
510 state.current = viewProjection;
511 state.origin = renderOrigin();
512 ++state.frame;
513 // A chain that did not write last frame leaves history of a picture this one no
514 // longer follows (a camera that was off, a frame the host skipped).
515 if (state.writtenFrame + 1 != state.frame) state.valid = false;
516 const u32 phase = (state.frame % kJitterPhases) + 1;
517 const f32 jx = halton(phase, 2) - 0.5f;
518 const f32 jy = halton(phase, 3) - 0.5f;
519 const f32 w = static_cast<f32>(std::max(width_, 1u));
520 const f32 h = static_cast<f32>(std::max(height_, 1u));
521 state.jitter = {jx * 2.0f / w, jy * 2.0f / h};
522 return state.jitter;
523}
524
526 u64 key) const {
527 const auto it = temporal_.find(key);
528 const u32 frame = it == temporal_.end() ? 0u : it->second.frame;
529 TemporalView view;
530 view.previous = frame > 0 ? viewProjectionFromOrigin(it->second.current, it->second.origin) : viewProjection;
531 // The step beginTemporalView will take next: one frame on, the same phase of the same sequence.
532 const u32 phase = ((frame + 1) % kJitterPhases) + 1;
533 const f32 w = static_cast<f32>(std::max(width_, 1u));
534 const f32 h = static_cast<f32>(std::max(height_, 1u));
535 view.jitter = {(halton(phase, 2) - 0.5f) * 2.0f / w, (halton(phase, 3) - 0.5f) * 2.0f / h};
536 if (frame > 0) {
537 const u32 before = (frame % kJitterPhases) + 1;
538 view.previousJitter = {(halton(before, 2) - 0.5f) * 2.0f / w, (halton(before, 3) - 0.5f) * 2.0f / h};
539 }
540 return view;
541}
542
543// The map is drawn for an effect that says how far it reaches (rain, snow): one that only reads it (reflections, keeping the
544// ground under a roof dry) borrows it where it is drawn, and does not cost a second picture of the scene by being on alone.
545bool PostProcessPipeline::passDrawsCover(const PostProcessPass& pass) {
546 if (!passHasTexture(pass, "u_rainCover")) return false;
547 const MaterialUniformLayout* layout = context_.materials().layoutFor(pass.shader);
548 return layout && layout->find("u_shelterRange");
549}
550
552 if (!initialized_ || bypass_) return false;
553 for (const auto& pass : passes_) {
554 if (pass.enabled && passDrawsCover(pass)) return true;
555 }
556 return false;
557}
558
560 for (const auto& pass : passes_) {
561 if (!pass.enabled || !passDrawsCover(pass)) continue;
562 if (auto it = pass.floatUniforms.find("u_shelterRange"); it != pass.floatUniforms.end()) {
563 return std::max(it->second, 10.0f);
564 }
565 }
566 return 3000.0f;
567}
568
570 for (const auto& pass : passes_) {
571 if (!pass.enabled || !passDrawsCover(pass)) continue;
572 if (auto it = pass.floatUniforms.find("u_shelterBias"); it != pass.floatUniforms.end()) return it->second;
573 return 40.0f;
574 }
575 return 40.0f;
576}
577
579 cover_active_ = false;
580 if (!graph_) return rg::kNoResource;
581 if (!cover_fbo_ || cover_fbo_->getWidth() != size) {
582 FramebufferSpec spec;
583 spec.width = size;
584 spec.height = size;
586 spec.depthStencil = true;
587 spec.linearFilter = false;
588 cover_fbo_ = Framebuffer::create(device_, spec);
589 if (!cover_fbo_) {
590 ES_LOG_ERROR("PostProcessPipeline: Failed to create the rain cover target");
591 return rg::kNoResource;
592 }
593 static u32 nextCoverSerial = 0;
594 cover_serial_ = ++nextCoverSerial;
595 }
596 cover_resource_ = graph_->importTarget(cover_fbo_->handle(), size, size, /*output=*/false,
597 cover_fbo_->getColorAttachment());
598 cover_active_ = true;
599 return cover_resource_;
600}
601
603 velocity_active_ = false;
604 if (!graph_ || !device_.supportsFloatTargets()) return rg::kNoResource;
605 const u32 w = std::max(width_, 1u);
606 const u32 h = std::max(height_, 1u);
607 if (!velocity_fbo_ || velocity_fbo_->getWidth() != w || velocity_fbo_->getHeight() != h) {
608 FramebufferSpec spec;
609 spec.width = w;
610 spec.height = h;
612 spec.depthStencil = true;
613 spec.linearFilter = false;
614 velocity_fbo_ = Framebuffer::create(device_, spec);
615 if (!velocity_fbo_) {
616 ES_LOG_ERROR("PostProcessPipeline: Failed to create the motion target");
617 return rg::kNoResource;
618 }
619 }
620 velocity_resource_ = graph_->importTarget(velocity_fbo_->handle(), w, h, /*output=*/false,
621 velocity_fbo_->getColorAttachment());
622 velocity_active_ = true;
623 return velocity_resource_;
624}
625
626bool PostProcessPipeline::passIsHighPrecision(const PostProcessPass& pass) {
627 const MaterialUniformLayout* layout = context_.materials().layoutFor(pass.shader);
628 return layout && layout->highPrecision && device_.supportsFloatTargets();
629}
630
631PostProcessPipeline::TemporalState* PostProcessPipeline::prepareHistory(TemporalState& state,
632 u32 w, u32 h,
633 GfxPixelFormat format) {
634 w = std::max(w, 1u);
635 h = std::max(h, 1u);
636 if (state.history[0] && state.width == w && state.height == h
637 && state.format == format) {
638 return &state;
639 }
640 for (auto& fbo : state.history) {
641 FramebufferSpec spec;
642 spec.colorFormat = format;
643 spec.width = w;
644 spec.height = h;
645 spec.depthStencil = false;
646 // The reprojected read lands between texels, so it wants the filter.
647 spec.linearFilter = true;
648 fbo = Framebuffer::create(device_, spec);
649 if (!fbo) {
650 ES_LOG_ERROR("PostProcessPipeline: Failed to create a temporal history target");
651 state.history[0].reset();
652 state.history[1].reset();
653 return nullptr;
654 }
655 }
656 state.width = w;
657 state.height = h;
658 state.format = format;
659 state.valid = false;
660 return &state;
661}
662
664 if (!rgbmShader_.isValid()) {
665 rgbmShader_ = compileBlit({"ES_RGBM"});
666 if (!rgbmShader_.isValid()) { ES_LOG_ERROR("PostProcessPipeline: the RGBM pack would not compile"); return; }
667 }
668 Shader* shader = resourceManager_.getShader(rgbmShader_);
669 if (!shader) return;
670 applyPassPipeline(*shader);
671 if (shader->hasUniform("u_texture")) shader->setUniform("u_texture", 0);
672 shader->commitParams();
673 bindBlitInputs(rgbmShader_);
674 drawScreenQuad();
675}
676
677void PostProcessPipeline::requestSkyCapture(const std::string& passName, u32 width, u32 height) {
678 sky_capture_.pass = passName;
679 sky_capture_.width = std::clamp(width, 4u, 512u);
680 sky_capture_.height = std::clamp(height, 2u, 256u);
681 sky_capture_.state = SkyCapture::State::Requested;
682 sky_capture_.readback = ReadbackHandle::Invalid;
683}
684
686 SkyCapture& c = sky_capture_;
687 switch (c.state) {
688 case SkyCapture::State::Idle: return 2;
689 case SkyCapture::State::Requested: return 0;
690 case SkyCapture::State::Drawn:
691 c.readback = c.target ? device_.requestReadback(c.target->handle(), c.width, c.height) : ReadbackHandle::Invalid;
692 if (c.readback == ReadbackHandle::Invalid) { c.state = SkyCapture::State::Idle; return 2; }
693 c.state = SkyCapture::State::Reading;
694 [[fallthrough]];
695 case SkyCapture::State::Reading: {
696 const GfxReadbackStatus status = device_.pollReadback(c.readback);
697 if (status == GfxReadbackStatus::Pending) return 0;
698 c.state = SkyCapture::State::Idle;
699 if (status != GfxReadbackStatus::Ready) return 2;
700 c.pixels.resize(static_cast<usize>(c.width) * c.height * 4);
701 return device_.takeReadback(c.readback, c.pixels.data(), c.pixels.size()) ? 1 : 2;
702 }
703 }
704 return 2;
705}
706
707void PostProcessPipeline::declareSkyCapture(const PostProcessPass& pass, rg::ResourceId input, rg::ResourceId effectInput) {
708 SkyCapture& c = sky_capture_;
709 if (!c.target || c.target->getSpecification().width != c.width || c.target->getSpecification().height != c.height) {
710 FramebufferSpec spec;
712 spec.width = c.width;
713 spec.height = c.height;
714 spec.depthStencil = false;
715 spec.linearFilter = true;
716 c.target = Framebuffer::create(device_, spec);
717 if (!c.target) {
718 ES_LOG_ERROR("PostProcessPipeline: could not make the sky capture target");
719 c.state = SkyCapture::State::Idle;
720 return;
721 }
722 }
723 // The pass's shader and settings, its own parameter buffer kept.
724 const BufferHandle ubo = c.copy.paramUbo;
725 c.copy = pass;
726 c.copy.paramUbo = ubo;
727 c.copy.name = pass.name + "_skyCapture";
728 c.copy.temporal = false;
729 c.copy.feedback = false;
730 c.copy.earlierInputs.clear();
731 c.copy.floatUniforms["u_skyCapture"] = 1.0f;
732 c.copy.paramDirty = true;
733
734 rg::PassDesc node;
735 node.name = c.copy.name;
736 node.reads = {input, effectInput};
737 node.keep = true;
738 node.write = graph_->importTarget(c.target->handle(), c.width, c.height, /*output=*/false, c.target->getColorAttachment());
739 node.execute = [this](const rg::PassContext& ctx) {
740 renderPass(sky_capture_.copy, ctx);
741 sky_capture_.state = SkyCapture::State::Drawn;
742 };
743 graph_->addPass(std::move(node));
744}
745
746const PostProcessPass* PostProcessPipeline::cloudShadowCaster(f32& extentKm, f32& unitsPerKm) const {
747 for (const PostProcessPass& pass : passes_) {
748 // A caster whose program is still compiling casts nothing yet, as its effect draws nothing yet.
749 if (!pass.enabled || programPending(pass)) continue;
750 const MaterialUniformLayout* layout = context_.materials().layoutFor(pass.shader);
751 if (!layout || !layout->find("u_cloudShadowPass")) continue;
752 // What the pass was set to, else what its shader declares.
753 const auto value = [&](const char* name, f32 fallback) {
754 if (auto it = pass.floatUniforms.find(name); it != pass.floatUniforms.end()) return it->second;
755 if (const MaterialParamSlot* slot = layout->find(name)) return slot->defaults[0];
756 return fallback;
757 };
758 if (value("u_castCloudShadows", 0.0f) < 0.5f) continue;
759 if (layout->find("u_cloudShadow") && value("u_cloudShadow", 0.0f) <= 0.001f) continue;
760 extentKm = std::max(value("u_cloudShadowExtentKm", 16.0f), 0.1f);
761 unitsPerKm = layout->find("u_unitsPerKm") ? std::max(value("u_unitsPerKm", 0.0f), 0.0f) : 0.0f;
762 return &pass;
763 }
764 return nullptr;
765}
766
767void PostProcessPipeline::drawCloudShadow(const glm::mat4& inverse, const glm::vec4& rect, const rg::PassContext& ctx) {
768 f32 extentKm = 0.0f, unitsPerKm = 0.0f;
769 const PostProcessPass* caster = cloudShadowCaster(extentKm, unitsPerKm);
770 if (!caster) return;
771 // The pass's shader and settings, its own parameter buffer kept, as the sky capture's copy is.
772 const BufferHandle ubo = cloud_shadow_copy_.paramUbo;
773 cloud_shadow_copy_ = *caster;
774 cloud_shadow_copy_.paramUbo = ubo;
775 cloud_shadow_copy_.name = caster->name + "_cloudShadow";
776 cloud_shadow_copy_.temporal = false;
777 cloud_shadow_copy_.feedback = false;
778 cloud_shadow_copy_.earlierInputs.clear();
779 cloud_shadow_copy_.floatUniforms["u_cloudShadowPass"] = 1.0f;
780 for (int c = 0; c < 4; ++c) {
781 cloud_shadow_copy_.vec4Uniforms["u_cloudShadowInv" + std::to_string(c)] = glm::vec4(inverse[c]);
782 }
783 cloud_shadow_copy_.vec4Uniforms["u_cloudShadowRect"] = rect;
784 cloud_shadow_copy_.paramDirty = true;
785 drawing_cloud_shadow_ = true;
786 // Nothing of a scene on the input units either: the pass reads none, and the last bound may be a target of this frame's.
787 device_.bindTexture(0, TextureHandle::Invalid);
788 device_.bindTexture(1, TextureHandle::Invalid);
789 renderPass(cloud_shadow_copy_, ctx);
790 drawing_cloud_shadow_ = false;
791}
792
794 const std::vector<std::pair<std::string, glm::vec4>>& overrides, u32 scratch) {
795 const resource::ShaderHandle handle(shader);
796 Shader* program = resourceManager_.getShader(handle);
797 if (!program) return false;
798 applyPassPipeline(*program);
799 // Nothing of a scene on the units a fullscreen program declares: a bake reads none, and the last bound may be this frame's target.
800 device_.bindTexture(0, TextureHandle::Invalid);
801 device_.bindTexture(1, TextureHandle::Invalid);
802 device_.bindTexture(kSceneDepthUnit, TextureHandle::Invalid);
803 device_.bindTexture(kGBufferUnit, TextureHandle::Invalid);
804 if (!context_.materials().bindThrough(material, handle, overrides, scratch)) return false;
805 drawScreenQuad();
806 return true;
807}
808
810 const resource::ShaderHandle handle = context_.materials().shaderOf(material);
811 Shader* program = handle.isValid() ? resourceManager_.getShader(handle) : nullptr;
812 return program && context_.materials().layoutFor(handle) && device_.programReady(program->handle());
813}
814
816 const resource::ShaderHandle handle = context_.materials().shaderOf(material);
817 Shader* program = handle.isValid() ? resourceManager_.getShader(handle) : nullptr;
818 if (!program) return false;
819 applyPassPipeline(*program, /*over=*/true);
820 if (program->language() == GfxShaderLanguage::GLSL_ES300 && program->hasUniform("u_texture")) {
821 program->setUniform("u_texture", 0);
822 }
823 device_.bindTexture(1, TextureHandle::Invalid);
824 device_.bindTexture(kSceneDepthUnit, TextureHandle::Invalid);
825 device_.bindTexture(kGBufferUnit, TextureHandle::Invalid);
826 context_.materials().bindForDraw(material);
827 drawScreenQuad();
828 return true;
829}
830
831void PostProcessPipeline::releasePassResources(PostProcessPass& pass) {
832 if (pass.paramUbo != BufferHandle::Invalid) {
833 device_.deleteBuffer(pass.paramUbo);
835 pass.paramUboBytes = 0;
836 }
837}
838
839BufferHandle PostProcessPipeline::takeParamUbo(u32 bytes, const void* data) {
840 for (usize i = 0; i < spare_param_ubos_.size(); ++i) {
841 if (spare_param_ubos_[i].bytes != bytes) continue;
842 const BufferHandle handle = spare_param_ubos_[i].handle;
843 spare_param_ubos_[i] = spare_param_ubos_.back();
844 spare_param_ubos_.pop_back();
845 device_.updateBuffer(handle, 0, data, bytes);
846 return handle;
847 }
848 return device_.createBuffer({GfxBufferUsage::Uniform, bytes, /*dynamic=*/true}, GfxContent::retained(), data);
849}
850
851void PostProcessPipeline::dropSpareParamUbos() {
852 for (const SpareParamUbo& spare : spare_param_ubos_) device_.deleteBuffer(spare.handle);
853 spare_param_ubos_.clear();
854}
855
856void PostProcessPipeline::setPassUniformFloat(const std::string& passName,
857 const std::string& uniform, f32 value) {
858 if (auto* pass = findPass(passName)) {
859 pass->floatUniforms[uniform] = value;
860 pass->paramDirty = true;
861 }
862}
863
864void PostProcessPipeline::setPassTexture(const std::string& passName,
865 const std::string& uniform, u32 glTextureId) {
866 auto* pass = findPass(passName);
867 if (!pass) return;
868 for (auto& [name, id] : pass->textureUniforms) {
869 if (name == uniform) { id = glTextureId; return; }
870 }
871 pass->textureUniforms.emplace_back(uniform, glTextureId);
872}
873
874void PostProcessPipeline::setPassUniformVec4(const std::string& passName,
875 const std::string& uniform,
876 const glm::vec4& value) {
877 if (auto* pass = findPass(passName)) {
878 pass->vec4Uniforms[uniform] = value;
879 pass->paramDirty = true;
880 }
881}
882
884 if (index >= passes_.size()) return nullptr;
885 return &passes_[index];
886}
887
888const PostProcessPass* PostProcessPipeline::getPass(const std::string& name) const {
889 for (const auto& pass : passes_) {
890 if (pass.name == name) {
891 return &pass;
892 }
893 }
894 return nullptr;
895}
896
897PostProcessPass* PostProcessPipeline::findPass(const std::string& name) {
898 for (auto& pass : passes_) {
899 if (pass.name == name) {
900 return &pass;
901 }
902 }
903 return nullptr;
904}
905
906void PostProcessPipeline::ensureScreenQuad() {
907 if (screen_quad_layout_ != VertexLayoutHandle::Invalid) return;
908
909 // One fullscreen triangle (position + uv), drawn non-indexed.
910 f32 vertices[] = {
911 -1.0f, -1.0f, 0.0f, 0.0f,
912 3.0f, -1.0f, 2.0f, 0.0f,
913 -1.0f, 3.0f, 0.0f, 2.0f,
914 };
915 screen_quad_vbo_ = device_.createBuffer(
916 {GfxBufferUsage::Vertex, static_cast<u32>(sizeof(vertices)), /*dynamic=*/false},
917 GfxContent::retained(), vertices);
918
919 VertexLayoutDesc desc;
920 desc.attributeCount = 2;
921 desc.strides[0] = 4 * sizeof(f32);
922 desc.attributes[0] = {0, 2, GfxDataType::Float, false, 0, 0};
923 desc.attributes[1] = {1, 2, GfxDataType::Float, false, 2 * sizeof(f32), 0};
924 screen_quad_layout_ = device_.createVertexLayout(desc);
925}
926
927void PostProcessPipeline::drawScreenQuad() {
928 device_.setVertexBuffer(0, screen_quad_vbo_, 0);
929 device_.setIndexBuffer(BufferHandle::Invalid);
930 device_.drawArrays(0, 3);
931}
932
934 // The collected light list includes environment-following suns, visibility and the view's light selection.
935 glm::vec4 sun(0.0f);
936 for (const auto& light : context_.lights().data().lights) {
937 if (light.posDir.z > 0.5f && light.posDir.z < 1.5f && light.color.a > 0.0f) {
938 sun = glm::vec4(-glm::normalize(glm::vec3(light.posDir.x, light.posDir.y, light.posDir.w)), 1.0f);
939 break;
940 }
941 }
942 return sun;
943}
944
945bool PostProcessPipeline::drawProjectedMaterial(u32 material, u32 instances, u32 scratch, const glm::vec4& sun,
946 const glm::vec4& receiverWindow, TextureHandle receiverDepth, TextureHandle movingDepth) {
947 const auto ref = context_.materials().shaderOf(material);
948 Shader* shader = resourceManager_.getShader(ref);
949 const auto* layout = context_.materials().layoutFor(ref);
950 if (!shader || !layout) return false;
951 if (layout->findTexture("u_bakeReceiverDepth") && sun.y <= 0.0f) return true;
952 if (projected_triangle_indices_ == BufferHandle::Invalid) {
953 const u16 triangle[] = {0, 1, 2};
954 projected_triangle_indices_ = device_.createBuffer({GfxBufferUsage::Index, sizeof(triangle), false},
955 GfxContent::retained(), triangle);
956 if (projected_triangle_indices_ == BufferHandle::Invalid) return false;
957 }
958 applyPassPipeline(*shader, false, true);
959 if (!context_.materials().bindThrough(material, ref, {{"u_bakeSun", sun}, {"u_bakeReceiverWindow", receiverWindow}}, scratch)) return false;
960 device_.setVertexBuffer(0, screen_quad_vbo_, 0);
961 if (receiverDepth != TextureHandle::Invalid) {
962 if (const auto* slot = layout->findTexture("u_bakeReceiverDepth")) device_.bindTexture(slot->unit, receiverDepth);
963 }
964 if (movingDepth != TextureHandle::Invalid) {
965 if (const auto* slot = layout->findTexture("u_bakeMovingDepth")) device_.bindTexture(slot->unit, movingDepth);
966 }
967 device_.setIndexBuffer(projected_triangle_indices_);
968 device_.drawElementsInstanced(3, GfxDataType::UnsignedShort, 0, instances);
969 return true;
970}
971
972void PostProcessPipeline::applyPassPipeline(const Shader& shader, bool over, bool additive) {
973 ensureScreenQuad();
974 // Fullscreen passes overwrite every pixel: no blend, no depth, no stencil. The one exception is the present of a
975 // camera that keeps the colour under it, which lays its picture over by coverage. The capture was cleared to
976 // transparent, so its colour is already weighted by its alpha (a resolve averages both): premultiplied.
977 PipelineDesc desc{};
978 desc.program = shader.handle();
979 desc.vertexLayout = screen_quad_layout_;
980 desc.blendEnabled = over || additive;
981 if (additive) desc.blend = BlendMode::PmaAdditive;
982 else if (over) desc.blend = BlendMode::PremultipliedAlpha;
983 desc.depthTest = false;
984 desc.depthWrite = false;
985 device_.setPipeline(device_.createPipeline(desc));
986}
987
989 if (screenCaptureActive_ && screenFBOCreated_) return screenFBO_->handle();
990 if (inFrame_ && graph_) return graph_->framebufferOf(sceneResource_);
992}
993
994void PostProcessPipeline::begin(const f32* clearColor) {
995 if (!isEngaged() || inFrame_) return;
996
997 ensureGraph();
998 if (!graph_) return;
999
1000 // The frame's format is taken HERE, before its first resource exists, and
1001 // every target built between here and end() reads it. A policy flip lands on
1002 // the next frame rather than halfway through this one.
1003 commitFormat();
1004
1005 // The graph opens HERE and not at end(), because the scene target is its
1006 // first resource and the scene is drawn before any pass can be declared.
1007 graph_->begin(width_, height_);
1008 // With no pass to run, the blit samples the scene target itself, so the
1009 // present's filter is the one that applies to it.
1010 const bool sceneIsBlitSource = bypass_ || passes_.empty();
1011 rg::TargetDesc sceneDesc =
1012 sceneIsBlitSource ? blitSourceTarget(scene_needs_depth_) : chainTarget(scene_needs_depth_);
1013 // The only target geometry is rasterised into, so the only one with edges.
1014 // Every other target in the chain is a fullscreen pass and stays at one
1015 // sample. Gate: check-postfx-aa.
1016 sceneDesc.samples = scene_samples_;
1017 // The surface record needs the scene's depth to test against and to be read beside, so a frame
1018 // with no depth has no use for one.
1019 scene_gbuffer_ = scene_needs_depth_ && passesWantGBuffer();
1020 sceneDesc.gbuffer = scene_gbuffer_;
1021 sceneResource_ = graph_->createExternalTarget(sceneDesc);
1022 if (sceneResource_ == rg::kNoResource) {
1023 ES_LOG_ERROR("PostProcessPipeline: no scene target this frame");
1024 return;
1025 }
1026
1027 RenderPassDesc pass{graph_->framebufferOf(sceneResource_),
1028 /*clearColor=*/true, /*clearDepth=*/true};
1029 if (clearColor) {
1030 for (int i = 0; i < 4; ++i) pass.clearColorValue[i] = clearColor[i];
1031 if (linear_output_) {
1032 // Authored sRGB -> linear; the sRGB attachment re-encodes on store.
1033 for (int i = 0; i < 3; ++i) {
1034 const f32 v = pass.clearColorValue[i];
1035 pass.clearColorValue[i] =
1036 v <= 0.04045f ? v / 12.92f : std::pow((v + 0.055f) / 1.055f, 2.4f);
1037 }
1038 }
1039 }
1040 device_.beginRenderPass(pass);
1041 device_.setViewport(0, 0, width_, height_);
1042
1043 inFrame_ = true;
1044}
1045
1047 // Gated on inFrame_ alone, not on isEngaged(): whatever begin() opened has
1048 // to be resolved even if the answer changed underneath in between.
1049 if (!initialized_ || !inFrame_) return;
1050
1051 // Read while the resource still holds its target — the graph hands it back
1052 // at the last pass that reads it.
1053 sceneTexture_ = graph_->textureOf(sceneResource_);
1054 // What Framebuffer::unbind did for the FBO this replaced: a WebGPU pass
1055 // encoder has to be closed before the graph opens the first one of its own.
1056 device_.endRenderPass();
1057
1058 runChain(passes_, sceneResource_);
1059}
1060
1062 velocity_active_ = false;
1063 cover_active_ = false;
1064 background_sky_ = false;
1065 if (!initialized_ || !inFrame_) return;
1066 device_.invalidatePipelineCache();
1067 inFrame_ = false;
1068 output_target_fbo_ = FramebufferHandle::Default;
1069 present_over_ = false;
1070 // Per-frame, like the target above: a camera that asked for a present must not
1071 // leave the next one engaged for a frame it never asked about.
1072 present_required_ = false;
1073}
1074
1075void PostProcessPipeline::renderPass(PostProcessPass& pass, const rg::PassContext& ctx) {
1076 Shader* shader = resourceManager_.getShader(pass.shader);
1077 if (!shader) return;
1078
1079 auto* device = &device_;
1080 applyPassPipeline(*shader);
1081 const bool glsl = shader->language() == GfxShaderLanguage::GLSL_ES300;
1082 if (glsl) {
1083 // Engine sampler seeding is a GLSL concept; the WGSL twins read the
1084 // input/scene as the t0/s0 and t1/s1 bind-group pairs.
1085 // An effect that makes its picture rather than reading one (the sky) has no input to seat.
1086 if (shader->hasUniform("u_texture")) shader->setUniform("u_texture", 0);
1087 if (shader->hasUniform("u_sceneTexture")) shader->setUniform("u_sceneTexture", 1);
1088 if (shader->hasUniform("u_sceneDepth")) {
1089 shader->setUniform("u_sceneDepth", static_cast<i32>(kSceneDepthUnit));
1090 }
1091 if (shader->hasUniform("u_gbuffer")) {
1092 shader->setUniform("u_gbuffer", static_cast<i32>(kGBufferUnit));
1093 }
1094 if (shader->hasUniform("u_shadowMap")) {
1095 shader->setUniform("u_shadowMap", static_cast<i32>(SHADOW_MAP_TEXTURE_UNIT));
1096 }
1097 }
1098
1099 // #pragma-param effects: params ride the reflected MaterialConstants block
1100 // (binding 1) exactly like a material's — compileEsshader registered the
1101 // layout when the effect compiled. Resolution-style inputs come from the
1102 // injected u_viewport, so nothing per-pass remains loose.
1103 const MaterialUniformLayout* layout = context_.materials().layoutFor(pass.shader);
1104 TemporalState* temporal = nullptr;
1105 if (pass.temporal) {
1106 if (auto it = temporal_.find(temporalKey_); it != temporal_.end()) temporal = &it->second;
1107 } else if (pass.feedback) {
1108 if (auto it = feedback_.find(pass.historyKey); it != feedback_.end()) temporal = &it->second;
1109 }
1110 if (layout && layout->find("u_backgroundSky")) {
1111 const f32 behind = background_sky_ ? 1.0f : 0.0f;
1112 const auto [held, added] = pass.floatUniforms.try_emplace("u_backgroundSky", behind);
1113 if (added || held->second != behind) {
1114 held->second = behind;
1115 pass.paramDirty = true;
1116 }
1117 }
1118 // An effect that reflects the environment declares its parameters, and takes them from the
1119 // light block the scene was drawn with: how the atlas is laid out, how bright it is, how far the sky has turned.
1120 // An effect that asks what stands over a place is handed the matrix the answer was drawn through, and whether there is one.
1121 if (layout && layout->find("u_coverMatrix0")) {
1122 for (int c = 0; c < 4; ++c) {
1123 pass.vec4Uniforms["u_coverMatrix" + std::to_string(c)] = glm::vec4(cover_matrix_[c]);
1124 }
1125 pass.floatUniforms["u_coverActive"] = cover_active_ ? 1.0f : 0.0f;
1126 // The reach the map was drawn with and the bias it is read with, for a pass that reads it without stating either (reflections
1127 // read the rain's): both are the drawing effect's, in its world's units.
1128 if (layout->find("u_coverRange")) pass.floatUniforms["u_coverRange"] = coverRange();
1129 if (layout->find("u_coverBias")) pass.floatUniforms["u_coverBias"] = coverBias();
1130 pass.paramDirty = true;
1131 }
1132 if (layout && layout->usesLights) {
1133 // The block the scene was lit with, bound again: the passes between have no claim on its slot, but a
1134 // chain is not the place to find out. And the atlas on the unit the Lit shaders read it from.
1135 context_.lights().uploadAndBind();
1136 // Not while the atlas is the target being drawn: a texture read and written in one pass is no answer on GL and an error on WebGPU.
1137 if (drawing_cloud_shadow_) {
1138 device->bindTexture(SHADOW_MAP_TEXTURE_UNIT, context_.materials().builtinDefault(MaterialDefaultTexture::White));
1139 } else if (shadow_texture_ != 0) {
1140 device->bindTexture(SHADOW_MAP_TEXTURE_UNIT, TextureHandle{shadow_texture_});
1141 }
1142 }
1143 if (layout && layout->find("u_envParams")) {
1144 const LightConstants& lights = context_.lights().data();
1145 pass.vec4Uniforms["u_envParams"] = lights.envParams;
1146 pass.vec4Uniforms["u_envTint"] = lights.envTint;
1147 pass.vec4Uniforms["u_reflParams"] = lights.reflParams;
1148 pass.paramDirty = true;
1149 }
1150 if (temporal && pass.temporal) {
1151 // The previous picture's camera, as columns: a world point times it is where
1152 // that point was one frame ago. Re-sent each frame because it is each frame's.
1153 for (int c = 0; c < 4; ++c) {
1154 pass.vec4Uniforms["u_prevViewProjection" + std::to_string(c)] =
1155 glm::vec4(temporal->previous[c]);
1156 }
1157 pass.floatUniforms["u_historyValid"] = temporal->valid ? 1.0f : 0.0f;
1158 pass.vec4Uniforms["u_jitter"] = glm::vec4(temporal->jitter, 0.0f, 0.0f);
1159 pass.paramDirty = true;
1160 } else if (temporal) {
1161 pass.floatUniforms["u_historyValid"] = temporal->valid ? 1.0f : 0.0f;
1162 pass.paramDirty = true;
1163 }
1164 // An effect that wants only where the camera WAS (motion blur): no history, so no `temporal` above, but the
1165 // same matrix. Nothing to send before the view has been followed once.
1166 if (!pass.temporal && layout && layout->find("u_prevViewProjection0")) {
1167 if (auto it = temporal_.find(temporalKey_); it != temporal_.end()) {
1168 for (int c = 0; c < 4; ++c) {
1169 pass.vec4Uniforms["u_prevViewProjection" + std::to_string(c)] = glm::vec4(it->second.previous[c]);
1170 }
1171 pass.paramDirty = true;
1172 }
1173 }
1174 if (layout) {
1175 if (layout->blockSize > 0) {
1176 if (pass.paramDirty || pass.paramBytes.size() < layout->blockSize) {
1177 // Defaults first, then the pass's set values by reflected offset.
1178 // A multi-pass effect (bloom) carries its full uniform set; each
1179 // sub-pass layout picks only the params it declares.
1180 pass.paramBytes.assign(layout->blockSize, 0);
1181 for (const auto& p : layout->params) {
1182 std::memcpy(pass.paramBytes.data() + p.offset, p.defaults,
1183 p.arity * sizeof(f32));
1184 if (auto fit = pass.floatUniforms.find(p.name); fit != pass.floatUniforms.end()) {
1185 std::memcpy(pass.paramBytes.data() + p.offset, &fit->second, sizeof(f32));
1186 }
1187 if (auto vit = pass.vec4Uniforms.find(p.name); vit != pass.vec4Uniforms.end()) {
1188 std::memcpy(pass.paramBytes.data() + p.offset, &vit->second.x,
1189 std::min(p.arity, 4u) * sizeof(f32));
1190 }
1191 }
1192 pass.paramDirty = false;
1193 if (pass.paramUbo == BufferHandle::Invalid) {
1194 pass.paramUbo = takeParamUbo(layout->blockSize, pass.paramBytes.data());
1195 pass.paramUboBytes = layout->blockSize;
1196 } else {
1197 device->updateBuffer(pass.paramUbo, 0, pass.paramBytes.data(),
1198 static_cast<u32>(pass.paramBytes.size()));
1199 }
1200 }
1201 if (pass.paramUbo != BufferHandle::Invalid) {
1202 device->setUniformBuffer(MATERIAL_CONSTANTS_BINDING, pass.paramUbo);
1203 }
1204 }
1205 // Scene depth, bound whether or not this pass reads it: the WGSL twin
1206 // declares the unit either way. runChain keeps the scene alive through
1207 // every pass for it.
1208
1209 // A target with no depth binds nothing, and an effect over a scene that
1210 // wrote none then finds no edge — the right answer for a flat one.
1211 // Not while a cloud shadow is drawn before the scene: the id kept from the frame before can name the atlas being drawn into.
1212 const bool scene = graph_ && !drawing_cloud_shadow_;
1213 device->bindTexture(kSceneDepthUnit, scene ? graph_->depthTextureOf(sceneResource_) : TextureHandle::Invalid);
1214 // And the surface record, on the unit below it, on the same terms: nothing where the frame drew none.
1215 device->bindTexture(kGBufferUnit, scene && scene_gbuffer_ ? graph_->gbufferTextureOf(sceneResource_)
1216 : TextureHandle::Invalid);
1217
1218 // Texture params (LUTs, masks) bind at their reflected material units;
1219 // an unset param gets its declared default (white/black/flatnormal).
1220 for (const auto& slot : layout->textures) {
1221 TextureHandle gpu = context_.materials().builtinDefault(slot);
1222 if (temporal && (slot.name == "u_history" || slot.name == "u_feedback")
1223 && temporal->history[temporal->readIndex]) {
1224 gpu = temporal->history[temporal->readIndex]->getColorAttachment();
1225 }
1226 if (slot.name == "u_environment" && environment_texture_ != 0) {
1227 gpu = TextureHandle{environment_texture_};
1228 }
1229 if (slot.name == "u_velocity" && velocity_active_ && velocity_fbo_) {
1230 gpu = velocity_fbo_->getColorAttachment();
1231 }
1232 // The scene's albedo, beside its surface record: what bounce light an effect adds is coloured by.
1233 if (slot.name == "u_sceneAlbedo" && graph_ && scene_gbuffer_ && !drawing_cloud_shadow_) {
1234 const TextureHandle albedo = graph_->albedoTextureOf(sceneResource_);
1235 if (albedo != TextureHandle::Invalid) gpu = albedo;
1236 }
1237 if (slot.name == "u_rainCover" && cover_active_ && cover_fbo_) {
1238 gpu = cover_fbo_->getColorAttachment();
1239 }
1240 for (const auto& [name, glId] : pass.textureUniforms) {
1241 if (name == slot.name && glId != 0) { gpu = TextureHandle{glId}; break; }
1242 }
1243 for (const auto& [name, id] : pass.earlierInputs) {
1244 if (name != slot.name || !graph_) continue;
1245 const TextureHandle earlier = graph_->textureOf(id);
1246 if (earlier != TextureHandle::Invalid) gpu = earlier;
1247 break;
1248 }
1249 if (gpu != TextureHandle::Invalid) device->bindTexture(slot.unit, gpu);
1250 }
1251 } else if (glsl) {
1252 // Legacy loose-uniform path for raw-GLSL passes (addPass with a
1253 // hand-created shader): resolution, in-order extra textures, and the
1254 // DrawParams block lifted at creation.
1255 // The pass's own size, not the screen's: a chain link that runs at a
1256 // fraction of the reference size must sample by ITS texel grid.
1257 if (shader->hasUniform("u_resolution")) {
1258 shader->setUniform("u_resolution", glm::vec2(static_cast<f32>(ctx.width), static_cast<f32>(ctx.height)));
1259 }
1260 u32 extraUnit = 2;
1261 for (const auto& [name, glId] : pass.textureUniforms) {
1262 // Stops below the scene-depth unit rather than walking into it: a
1263 // sixth loose texture would otherwise take the binding depth is on.
1264 if (extraUnit >= kGBufferUnit) break;
1265 if (glId != 0 && shader->hasUniform(name)) {
1266 device->bindTexture(extraUnit, TextureHandle{glId});
1267 shader->setUniform(name, static_cast<i32>(extraUnit));
1268 }
1269 ++extraUnit;
1270 }
1271 for (const auto& [name, value] : pass.floatUniforms) {
1272 if (shader->hasUniform(name)) shader->setUniform(name, value);
1273 }
1274 for (const auto& [name, value] : pass.vec4Uniforms) {
1275 if (shader->hasUniform(name)) shader->setUniform(name, value);
1276 }
1277 shader->commitParams();
1278 }
1279
1280 drawScreenQuad();
1281}
1282
1283void PostProcessPipeline::computePass(PostProcessPass& pass, const rg::PassContext& ctx) {
1284 if (pass.compute == ComputeHandle::Invalid || ctx.output == TextureHandle::Invalid) return;
1285 const TextureHandle input = ctx.input(0);
1286 if (input == TextureHandle::Invalid) return;
1287
1288 // The params block: the pass's floats in the order the effect declared them, at least one vec4 (a uniform
1289 // binding is never smaller than that).
1290 const usize floats = std::max<usize>(4, (pass.computeParams.size() + 3) / 4 * 4);
1291 std::vector<f32> values(floats, 0.0f);
1292 for (usize i = 0; i < pass.computeParams.size(); ++i) {
1293 if (auto it = pass.floatUniforms.find(pass.computeParams[i]); it != pass.floatUniforms.end()) values[i] = it->second;
1294 }
1295 const u32 paramBytes = static_cast<u32>(values.size() * sizeof(f32));
1296 if (pass.paramUbo == BufferHandle::Invalid) {
1297 pass.paramUbo = takeParamUbo(paramBytes, values.data());
1298 pass.paramUboBytes = paramBytes;
1299 } else {
1300 device_.updateBuffer(pass.paramUbo, 0, values.data(), paramBytes);
1301 }
1302
1303 const f32 w = static_cast<f32>(std::max(ctx.width, 1u));
1304 const f32 h = static_cast<f32>(std::max(ctx.height, 1u));
1305 const f32 view[4] = {w, h, 1.0f / w, 1.0f / h};
1306 if (compute_view_ubo_ == BufferHandle::Invalid) {
1307 compute_view_ubo_ = device_.createBuffer({GfxBufferUsage::Uniform, sizeof(view), /*dynamic=*/true},
1308 GfxContent::retained(), view);
1309 } else {
1310 device_.updateBuffer(compute_view_ubo_, 0, view, sizeof(view));
1311 }
1312
1313 // The scene's depth where the frame wrote one; the device stands a blank in where it did not.
1314 const TextureHandle depth = (pass.usesComputeDepth && graph_ && sceneResource_ != rg::kNoResource) ? graph_->depthTextureOf(sceneResource_)
1315 : TextureHandle::Invalid;
1316 const GfxComputeBinding bindings[6] = {
1317 GfxComputeBinding::sampled(0, input),
1318 GfxComputeBinding::storageTexture(1, ctx.output),
1319 GfxComputeBinding::uniform(2, pass.paramUbo),
1320 GfxComputeBinding::uniform(3, compute_view_ubo_),
1321 GfxComputeBinding::depth(4, depth),
1322 GfxComputeBinding::sampler(5, TextureFilter::Linear),
1323 };
1324 const u32 groupsX = (ctx.width + pass.workgroupX - 1) / pass.workgroupX;
1325 const u32 groupsY = (ctx.height + pass.workgroupY - 1) / pass.workgroupY;
1326 device_.dispatchCompute(pass.compute, bindings, 6, groupsX, groupsY, 1);
1327}
1328
1330 // What no chain took over in the last few clears is nobody's; what this chain holds is a later one's to take.
1331 constexpr u32 kSpareClears = 8;
1332 for (usize i = 0; i < spare_param_ubos_.size();) {
1333 if (++spare_param_ubos_[i].clears <= kSpareClears) { ++i; continue; }
1334 device_.deleteBuffer(spare_param_ubos_[i].handle);
1335 spare_param_ubos_[i] = spare_param_ubos_.back();
1336 spare_param_ubos_.pop_back();
1337 }
1338 for (auto& pass : passes_) {
1339 if (pass.paramUbo == BufferHandle::Invalid) continue;
1340 if (pass.paramUboBytes > 0) spare_param_ubos_.push_back({pass.paramUbo, pass.paramUboBytes, 0});
1341 else device_.deleteBuffer(pass.paramUbo);
1342 pass.paramUbo = BufferHandle::Invalid;
1343 pass.paramUboBytes = 0;
1344 }
1345 passes_.clear();
1346 // The display look is the chain's, like its passes: the next camera says its own.
1347 display_lut_texture_ = 0;
1348 display_lut_amount_ = 0.0f;
1349}
1350
1352 output_target_fbo_ = target;
1353}
1354
1356 output_vp_x_ = x;
1357 output_vp_y_ = y;
1358 output_vp_w_ = w;
1359 output_vp_h_ = h;
1360}
1361
1363 resource::ShaderHandle& handle = marked ? copyShader_ : exactCopyShader_;
1364 if (!handle.isValid()) {
1365 handle = compileBlit({marked ? "ES_COPY" : "ES_COPY_EXACT"});
1366 if (!handle.isValid()) {
1367 ES_LOG_ERROR("PostProcessPipeline: no copy shader; a refractive surface sees nothing behind it");
1368 return;
1369 }
1370 }
1371 Shader* shader = resourceManager_.getShader(handle);
1372 if (!shader) return;
1373 applyPassPipeline(*shader);
1374 if (shader->hasUniform("u_texture")) shader->setUniform("u_texture", 0);
1375 shader->commitParams();
1376 bindBlitInputs(handle);
1377 drawScreenQuad();
1378}
1379
1381 return device_.supportsFloatTargets();
1382}
1383
1384namespace {
1385// The top unit: the post header gives units 0-6 a sampler and the material's textures start at 8. A unit read by texel
1386// alone is unfilterable, as the RGBA32F mask needs.
1387constexpr u32 kSelectionMaskUnit = 15;
1388} // namespace
1389
1391 if (mask == TextureHandle::Invalid) return;
1392 if (!outlineShader_.isValid()) {
1393 outlineShader_ = compileBlit({"ES_SELECTION_OUTLINE"});
1394 if (!outlineShader_.isValid()) return;
1395 }
1396 Shader* shader = resourceManager_.getShader(outlineShader_);
1397 if (!shader) return;
1398 applyPassPipeline(*shader, /*over=*/true);
1399 if (shader->hasUniform("u_selectionMask")) shader->setUniform("u_selectionMask", static_cast<i32>(kSelectionMaskUnit));
1400 shader->commitParams();
1401 // After the blit's own inputs, which bind a default to every sampler the variant declares.
1402 bindBlitInputs(outlineShader_);
1403 device_.bindTexture(kSelectionMaskUnit, mask);
1404 drawScreenQuad();
1405 device_.bindTexture(kSelectionMaskUnit, TextureHandle::Invalid);
1406}
1407
1409 if (depth == TextureHandle::Invalid) return;
1410 if (!outlineGroundShader_.isValid()) {
1411 outlineGroundShader_ = compileBlit({"ES_SELECTION_SCENE_DEPTH"});
1412 if (!outlineGroundShader_.isValid()) return;
1413 }
1414 Shader* shader = resourceManager_.getShader(outlineGroundShader_);
1415 if (!shader) return;
1416 applyPassPipeline(*shader);
1417 if (shader->hasUniform("u_sceneDepth")) shader->setUniform("u_sceneDepth", static_cast<i32>(kSceneDepthUnit));
1418 shader->commitParams();
1419 bindBlitInputs(outlineGroundShader_);
1420 device_.bindTexture(kSceneDepthUnit, depth);
1421 drawScreenQuad();
1422 device_.bindTexture(kSceneDepthUnit, TextureHandle::Invalid);
1423}
1424
1426 if (!copyDepthShader_.isValid()) {
1427 copyDepthShader_ = compileBlit({"ES_COPY_DEPTH"});
1428 if (!copyDepthShader_.isValid()) {
1429 ES_LOG_ERROR("PostProcessPipeline: no depth copy shader; water sees no depth behind it");
1430 return;
1431 }
1432 }
1433 Shader* shader = resourceManager_.getShader(copyDepthShader_);
1434 if (!shader) return;
1435 applyPassPipeline(*shader);
1436 if (shader->hasUniform("u_texture")) shader->setUniform("u_texture", 0);
1437 if (shader->hasUniform("u_sceneDepth")) shader->setUniform("u_sceneDepth", static_cast<i32>(kSceneDepthUnit));
1438 shader->commitParams();
1439 device_.bindTexture(kSceneDepthUnit, graph_ ? graph_->depthTextureOf(sceneResource_) : TextureHandle::Invalid);
1440 bindBlitInputs(copyDepthShader_);
1441 drawScreenQuad();
1442}
1443
1444void PostProcessPipeline::blitPass() {
1445 const resource::ShaderHandle outputHandle = outputShader();
1446 Shader* shader = resourceManager_.getShader(outputHandle);
1447 if (!shader) return;
1448
1449 // The output rect is the one thing a pass does not get from its target: the
1450 // graph sized the viewport to the whole target, and a camera writing into a
1451 // shared surface owns only part of it.
1452 if (output_vp_w_ > 0 && output_vp_h_ > 0) {
1453 device_.setViewport(output_vp_x_, output_vp_y_, output_vp_w_, output_vp_h_);
1454 }
1455
1456 applyPassPipeline(*shader, present_over_);
1457 if (shader->hasUniform("u_texture")) shader->setUniform("u_texture", 0);
1458 shader->commitParams();
1459 bindBlitInputs(outputHandle);
1460
1461 drawScreenQuad();
1462}
1463
1464void PostProcessPipeline::bindBlitInputs(const resource::ShaderHandle& handle) {
1465 const MaterialUniformLayout* layout = context_.materials().layoutFor(handle);
1466 if (!layout) return;
1467 // Only the last pass applies the look: the copies share the file, and read the amount as none.
1468 const bool lastPass = handle.id() != copyShader_.id() && handle.id() != exactCopyShader_.id() && handle.id() != copyDepthShader_.id();
1469 const f32 amount = lastPass && displayLutActive() ? display_lut_amount_ : 0.0f;
1470 if (layout->blockSize > 0) {
1471 if (blitParamUbo_ == BufferHandle::Invalid || blitParamAmount_ != amount) {
1472 std::vector<u8> bytes(layout->blockSize, 0);
1473 for (const auto& p : layout->params) {
1474 if (p.name == "u_displayLutAmount") std::memcpy(bytes.data() + p.offset, &amount, sizeof(f32));
1475 }
1476 if (blitParamUbo_ == BufferHandle::Invalid) {
1477 blitParamUbo_ = device_.createBuffer({GfxBufferUsage::Uniform, layout->blockSize, /*dynamic=*/true},
1478 GfxContent::retained(), bytes.data());
1479 } else {
1480 device_.updateBuffer(blitParamUbo_, 0, bytes.data(), static_cast<u32>(bytes.size()));
1481 }
1482 blitParamAmount_ = amount;
1483 }
1484 device_.setUniformBuffer(MATERIAL_CONSTANTS_BINDING, blitParamUbo_);
1485 }
1486 for (const auto& slot : layout->textures) {
1487 TextureHandle gpu = context_.materials().builtinDefault(slot);
1488 if (slot.name == "u_displayLut" && lastPass && display_lut_texture_ != 0) gpu = TextureHandle{display_lut_texture_};
1489 if (gpu != TextureHandle::Invalid) device_.bindTexture(slot.unit, gpu);
1490 }
1491}
1492
1493void PostProcessPipeline::runChain(std::vector<PostProcessPass>& passes, rg::ResourceId scene) {
1494 if (!graph_ || scene == rg::kNoResource) return;
1495
1496 // The surface has to be declared big enough to hold the rect the blit writes,
1497 // which is NOT the chain's size once the present scales. Only the extent
1498 // matters: blitPass sets its own viewport, so the graph's default never runs.
1499 const u32 outW = std::max(width_, output_vp_x_ + output_vp_w_);
1500 const u32 outH = std::max(height_, output_vp_y_ + output_vp_h_);
1501 const rg::ResourceId out = graph_->importTarget(output_target_fbo_, outW, outH);
1502 const rg::TargetDesc desc = chainTarget(/*withDepth=*/false);
1503 const rg::TargetDesc blitDesc = blitSourceTarget(/*withDepth=*/false);
1504
1505 // What runs this frame. With background compiles on, an effect whose program the browser is still compiling sits the frame out, the
1506 // way a draw does - every pass of the effect together, since a later one reads the earlier ones' pictures by name.
1507 std::vector<char> live(passes.size());
1508 for (usize i = 0; i < passes.size(); ++i) live[i] = runnable(passes[i]) ? 1 : 0;
1509 if (device_.skipPendingPrograms()) {
1510 for (usize begin = 0; begin < passes.size();) {
1511 usize end = begin + 1;
1512 while (end < passes.size() && passes[end].continuesEffect) ++end;
1513 bool ready = true;
1514 for (usize k = begin; k < end && ready; ++k) ready = !live[k] || !programPending(passes[k]);
1515 if (!ready) std::fill(live.begin() + static_cast<std::ptrdiff_t>(begin), live.begin() + static_cast<std::ptrdiff_t>(end), 0);
1516 begin = end;
1517 }
1518 }
1519
1520 // Which enabled pass is last decides which target the blit will sample.
1521 usize lastEnabled = passes.size();
1522 for (usize i = passes.size(); i-- > 0;) {
1523 if (live[i]) { lastEnabled = i; break; }
1524 }
1525
1526 rg::ResourceId input = scene;
1527 rg::ResourceId effectInput = scene;
1528 // The outputs of the current effect's passes so far, by pass name: what a `u_pass_<name>` texture reads.
1529 std::vector<std::pair<std::string, rg::ResourceId>> effectOutputs;
1530 for (usize i = 0; i < passes.size(); ++i) {
1531 auto& pass = passes[i];
1532 if (!live[i]) continue;
1533 if (!pass.continuesEffect) {
1534 effectInput = input;
1535 effectOutputs.clear();
1536 }
1537 rg::PassDesc node;
1538 node.name = pass.name;
1539 pass.earlierInputs.clear();
1540 if (const MaterialUniformLayout* layout = context_.materials().layoutFor(pass.shader)) {
1541 for (const auto& slot : layout->textures) {
1542 if (slot.name == "u_sceneColor") {
1543 pass.earlierInputs.emplace_back(slot.name, scene);
1544 node.dependencies.push_back(scene);
1545 continue;
1546 }
1547 if (slot.name.rfind("u_pass_", 0) != 0) continue;
1548 const std::string wanted = slot.name.substr(7);
1549 for (const auto& [name, id] : effectOutputs) {
1550 if (name != wanted) continue;
1551 pass.earlierInputs.emplace_back(slot.name, id);
1552 node.dependencies.push_back(id);
1553 break;
1554 }
1555 }
1556 }
1557 // Unit 1 is the image the pass's effect started from, which a composite
1558 // (bloom's and SSAO's last link) lays its result over — not the untouched
1559 // scene, which would discard every effect earlier in the chain.
1560 node.reads = {input, effectInput};
1561 // Every pass samples the scene's depth, so the scene target has to outlive
1562 // the last pass that reads its colour: returned to the pool any earlier,
1563 // an SSAO behind a colour grade found no depth and occluded nothing.
1564 // Added to, not assigned: the `u_pass_` targets above are dependencies too, and must outlive this pass.
1565 if (scene_needs_depth_ || scene_gbuffer_) node.dependencies.push_back(scene);
1566 // The motion pass wrote a target this one reads by name, not by unit: the graph owes it ordering
1567 // (and the pass its place in the culled set), and the pipeline binds it.
1568 if (velocity_active_ && velocity_resource_ != rg::kNoResource && passHasTexture(pass, "u_velocity")) {
1569 node.dependencies.push_back(velocity_resource_);
1570 }
1571 if (cover_active_ && cover_resource_ != rg::kNoResource && passHasTexture(pass, "u_rainCover")) {
1572 node.dependencies.push_back(cover_resource_);
1573 }
1574 if (shadow_resource_ != rg::kNoResource && passUsesLights(pass)) {
1575 node.dependencies.push_back(shadow_resource_);
1576 }
1577 // The last pass feeds the blit, which copies into the output rect at the
1578 // chain's size — so it draws full-size whatever fraction it asked for.
1579 rg::TargetDesc writeDesc = (i == lastEnabled) ? blitDesc : desc;
1580 if (i != lastEnabled) writeDesc.scale = pass.scale;
1581 if (passIsHighPrecision(pass)) writeDesc.format = GfxPixelFormat::RGBA16F;
1582 if (!pass.nativeKind.empty()) {
1583 // A pass the engine implements itself, in compute passes of its own that it declares onto the graph.
1584 if (pass.nativeKind == "dynamicGI" && &passes == &passes_ && (scene_needs_depth_ || scene_gbuffer_) && scene_gbuffer_) {
1585 const auto get = [&pass](const char* name, f32 fallback) {
1586 const auto it = pass.floatUniforms.find(name);
1587 return it != pass.floatUniforms.end() ? it->second : fallback;
1588 };
1589 DynamicGIParams gi;
1590 gi.intensity = get("u_intensity", gi.intensity);
1591 gi.blend = get("u_blend", gi.blend);
1592 gi.cardSlices = static_cast<u32>(std::max(get("u_cardSlices", static_cast<f32>(gi.cardSlices)), 1.0f));
1593 gi.probeStride = static_cast<u32>(std::max(get("u_probeStride", static_cast<f32>(gi.probeStride)), 1.0f));
1594 gi.skip = static_cast<u32>(std::max(get("u_skip", 0.0f), 0.0f));
1595 gi.probeSpacing = static_cast<u32>(std::max(get("u_probeSpacing", 0.0f), 0.0f));
1596 gi.halfRes = get("u_halfRes", 0.0f) > 0.5f;
1597 gi.probeDensity = get("u_probeDensity", 1.0f);
1598 gi.probeRows = static_cast<u32>(std::max(get("u_probeRows", static_cast<f32>(gi.probeRows)), 1.0f) + 0.5f);
1599 auto& cache = dynamic_gis_[temporalKey_];
1600 if (!cache) {
1601 if (dynamic_gis_.size() > 4) {
1602 for (auto it = dynamic_gis_.begin(); it != dynamic_gis_.end(); ++it) {
1603 if (it->first != temporalKey_) { dynamic_gis_.erase(it); break; }
1604 }
1605 }
1606 dynamic_gis_[temporalKey_] = makeUnique<DynamicGI>(device_, context_);
1607 }
1608 input = dynamic_gis_[temporalKey_]->declare(*graph_, input, scene, gi, width_, height_);
1609 }
1610 if (pass.nativeKind == "voxelGI" && &passes == &passes_ && (scene_needs_depth_ || scene_gbuffer_) && scene_gbuffer_) {
1611 const auto get = [&pass](const char* name, f32 fallback) {
1612 const auto it = pass.floatUniforms.find(name);
1613 return it != pass.floatUniforms.end() ? it->second : fallback;
1614 };
1615 VoxelGIParams gi;
1616 gi.intensity = get("u_intensity", gi.intensity);
1617 gi.rays = static_cast<u32>(std::max(get("u_rays", static_cast<f32>(gi.rays)), 1.0f));
1618 gi.voxelSize = get("u_voxelSize", gi.voxelSize);
1619 gi.range = get("u_range", gi.range);
1620 gi.maxBounce = get("u_maxBounce", gi.maxBounce);
1621 gi.decay = get("u_decay", gi.decay);
1622 gi.bias = get("u_bias", gi.bias);
1623 gi.divisor = static_cast<u32>(std::max(get("u_divisor", static_cast<f32>(gi.divisor)), 1.0f));
1624 gi.debug = get("u_debug", gi.debug);
1625 gi.blend = get("u_blend", gi.blend);
1626 gi.sunAlbedo = get("u_sunAlbedo", gi.sunAlbedo);
1627 gi.bounceFeedback = get("u_bounceFeedback", gi.bounceFeedback);
1628 gi.gridSize = static_cast<u32>(std::max(get("u_gridSize", static_cast<f32>(gi.gridSize)), 1.0f) + 0.5f);
1629 gi.sunSamples = static_cast<u32>(std::max(get("u_sunSamples", static_cast<f32>(gi.sunSamples)), 1.0f) + 0.5f);
1630 auto& cache = voxel_gis_[temporalKey_];
1631 if (!cache) {
1632 // A handful of cameras at most have a cache each; one past that evicts another's, which rebuilds when its camera returns.
1633 if (voxel_gis_.size() > 4) {
1634 for (auto it = voxel_gis_.begin(); it != voxel_gis_.end(); ++it) {
1635 if (it->first != temporalKey_) { voxel_gis_.erase(it); break; }
1636 }
1637 }
1638 voxel_gis_[temporalKey_] = makeUnique<VoxelGI>(device_, context_);
1639 }
1640 input = voxel_gis_[temporalKey_]->declare(*graph_, input, scene, gi, width_, height_,
1641 TextureHandle{shadow_texture_}, shadow_resource_);
1642 }
1643 continue;
1644 }
1645 if (pass.isCompute) {
1646 // A compute pass writes a storage texture, which is a half float whatever the chain keeps between passes (the
1647 // shader says its format), and it reads the scene's depth, so the scene has to outlive it.
1648 writeDesc.format = GfxPixelFormat::RGBA16F;
1649 writeDesc.storage = true;
1650 writeDesc.linearFilter = true;
1651 pass.temporal = false;
1652 pass.feedback = false;
1653 node.compute = true;
1654 node.asyncCompute = true;
1655 node.reads = {input};
1656 if (pass.usesComputeDepth) node.dependencies = {scene};
1657 node.write = graph_->createTarget(writeDesc);
1658 node.execute = [this, &pass](const rg::PassContext& ctx) { computePass(pass, ctx); };
1659 input = node.write;
1660 effectOutputs.emplace_back(pass.name, input);
1661 graph_->addPass(std::move(node));
1662 continue;
1663 }
1664 if (sky_capture_.state == SkyCapture::State::Requested && pass.name == sky_capture_.pass && &passes == &passes_) {
1665 declareSkyCapture(pass, input, effectInput);
1666 }
1667 // A temporal pass writes the history target itself, so that what it wrote is
1668 // still there next frame, and the passes after it read it from there.
1669 TemporalState* temporal = nullptr;
1670 pass.temporal = false;
1671 pass.feedback = false;
1672 if (&passes == &passes_) {
1673 if (passIsTemporal(pass)) {
1674 // Never begun: nothing shifted this frame's picture, and nothing is remembered.
1675 if (auto it = temporal_.find(temporalKey_); it != temporal_.end() && it->second.frame > 0) {
1676 temporal = prepareHistory(it->second, width_, height_, interFormat());
1677 pass.temporal = temporal != nullptr;
1678 }
1679 } else if (passHasTexture(pass, "u_feedback")) {
1680 // At the pass's own size: a measurement is a few texels, not a picture.
1681 pass.historyKey = feedbackKey(pass.name);
1682 u32 fw = static_cast<u32>(static_cast<f32>(width_) * pass.scale);
1683 u32 fh = static_cast<u32>(static_cast<f32>(height_) * pass.scale);
1684 // A memory that is not a picture (the voxel cache laid out as an atlas) names its own size, in texels.
1685 const auto sized = [&pass](const char* name, u32 fallback) {
1686 const auto it = pass.floatUniforms.find(name);
1687 return it != pass.floatUniforms.end() && it->second >= 1.0f ? std::min(static_cast<u32>(it->second), 4096u) : fallback;
1688 };
1689 fw = sized("u_feedbackWidth", fw);
1690 fh = sized("u_feedbackHeight", fh);
1691 // What it remembers is a measurement: kept in a float even where the picture is 8 bits a channel.
1692 temporal = prepareHistory(feedback_[pass.historyKey], fw, fh,
1693 passIsHighPrecision(pass) ? GfxPixelFormat::RGBA16F : interFormat());
1694 pass.feedback = temporal != nullptr;
1695 }
1696 }
1697 if (temporal) {
1698 const u32 write = temporal->readIndex ^ 1u;
1699 Framebuffer& target = *temporal->history[write];
1700 node.write = graph_->importTarget(target.handle(), temporal->width, temporal->height,
1701 /*output=*/false, target.getColorAttachment());
1702 node.execute = [this, &pass, temporal, write](const rg::PassContext& ctx) {
1703 renderPass(pass, ctx);
1704 temporal->readIndex = write;
1705 temporal->valid = true;
1706 temporal->writtenFrame = temporal->frame;
1707 };
1708 } else {
1709 node.write = graph_->createTarget(writeDesc);
1710 node.execute = [this, &pass](const rg::PassContext& ctx) { renderPass(pass, ctx); };
1711 }
1712 input = node.write;
1713 effectOutputs.emplace_back(pass.name, input);
1714 graph_->addPass(std::move(node));
1715 }
1716
1717 rg::PassDesc blit;
1718 blit.name = "blit";
1719 blit.reads = {input};
1720 blit.write = out;
1721 blit.execute = [this](const rg::PassContext&) { blitPass(); };
1722 graph_->addPass(std::move(blit));
1723
1724 // The editor's selection, ringed over the finished picture: after the look, so the outline keeps its colour.
1725 if (selectionMask_ != rg::kNoResource) {
1726 const rg::ResourceId mask = selectionMask_;
1727 rg::PassDesc outline;
1728 outline.name = "selection-outline";
1729 outline.reads = {mask};
1730 outline.write = out;
1731 outline.execute = [this, mask](const rg::PassContext&) {
1732 if (output_vp_w_ > 0 && output_vp_h_ > 0) device_.setViewport(output_vp_x_, output_vp_y_, output_vp_w_, output_vp_h_);
1733 drawSelectionOutline(graph_->textureOf(mask));
1734 };
1735 graph_->addPass(std::move(outline));
1736 }
1737 selectionMask_ = rg::kNoResource;
1738}
1739
1740void PostProcessPipeline::ensureScreenFBO() {
1741 // This one PERSISTS across frames, so a colour-space change leaves it holding
1742 // the format it was made under while the chain has moved on. Remade when it
1743 // no longer matches.
1744 if (screenFBOCreated_ && screenFBOFormat_ == interFormat()) return;
1745 screenFBO_.reset();
1746 screenFBOCreated_ = false;
1747
1748 FramebufferSpec spec;
1749 // The multi-camera composition surface carries scene values too — same
1750 // format + filter story as the capture/ping-pong chain (HDR in
1751 // linear+float mode; bilinear for the blur taps).
1752 spec.colorFormat = interFormat();
1753 spec.width = width_;
1754 spec.height = height_;
1755 spec.depthStencil = false;
1756 spec.linearFilter = true;
1757
1758 screenFBO_ = Framebuffer::create(device_, spec);
1759 if (!screenFBO_) {
1760 ES_LOG_ERROR("PostProcessPipeline: Failed to create screen FBO");
1761 return;
1762 }
1763
1764 screenFBOFormat_ = spec.colorFormat;
1765 screenFBOCreated_ = true;
1766}
1767
1769 if (!initialized_ || screenCaptureActive_) return;
1770
1771 ensureScreenFBO();
1772 if (!screenFBOCreated_) return;
1773
1774 device_.beginRenderPass({screenFBO_->handle(), /*clearColor=*/true, /*clearDepth=*/true});
1775 device_.setViewport(0, 0, width_, height_);
1776
1777 screenCaptureActive_ = true;
1778}
1779
1781 if (!initialized_ || !screenCaptureActive_) return;
1782
1783 screenFBO_->unbind();
1784 screenCaptureActive_ = false;
1785}
1786
1788 if (!initialized_ || !screenFBOCreated_) return;
1789
1790 auto* device = &device_;
1791 device->invalidatePipelineCache();
1792 device->setScissorTest(false);
1793
1794 ensureGraph();
1795 if (!graph_) return;
1796
1797 sceneTexture_ = screenFBO_->getColorAttachment();
1798 screenFBO_->unbind();
1799
1800 // The composition surface every camera drew into is NOT a transient (it
1801 // outlives each camera graph), so this chain imports it and opens a graph
1802 // of its own.
1803 graph_->begin(width_, height_);
1804 runChain(screenPasses_, graph_->importTexture(sceneTexture_, width_, height_));
1805 // Its own graph and its own run: this chain composes what every camera drew
1806 // and happens after the last of them ended, so no frame is declaring here.
1807 graph_->execute();
1808
1809 device->invalidatePipelineCache();
1810}
1811
1813 PostProcessPass pass;
1814 pass.name = name;
1815 pass.shader = shader;
1816 pass.enabled = true;
1817
1818 screenPasses_.push_back(pass);
1819 return static_cast<u32>(screenPasses_.size() - 1);
1820}
1821
1823 for (auto& pass : screenPasses_) releasePassResources(pass);
1824 screenPasses_.clear();
1825}
1826
1827PostProcessPass* PostProcessPipeline::findScreenPass(const std::string& name) {
1828 for (auto& pass : screenPasses_) {
1829 if (pass.name == name) {
1830 return &pass;
1831 }
1832 }
1833 return nullptr;
1834}
1835
1836void PostProcessPipeline::setScreenPassUniformFloat(const std::string& passName,
1837 const std::string& uniform, f32 value) {
1838 if (auto* pass = findScreenPass(passName)) {
1839 pass->floatUniforms[uniform] = value;
1840 pass->paramDirty = true;
1841 }
1842}
1843
1844void PostProcessPipeline::setScreenPassUniformVec4(const std::string& passName,
1845 const std::string& uniform,
1846 const glm::vec4& value) {
1847 if (auto* pass = findScreenPass(passName)) {
1848 pass->vec4Uniforms[uniform] = value;
1849 pass->paramDirty = true;
1850 }
1851}
1852
1853} // namespace esengine
Diffuse global illumination from the scene's distance field and surface cache, run as compute passes ...
Abstract graphics device interface.
Backend-agnostic graphics enumerations.
Per-frame 2D lighting constants — the third tier of the engine's constant-buffer layering (after per-...
Logging utilities for ESEngine.
#define ES_LOG_ERROR(...)
Logs an error message.
Definition Log.hpp:296
#define ES_LOG_INFO(...)
Logs an info message.
Definition Log.hpp:292
Binding points for per-material shader constants — the second tier of the engine's constant-buffer la...
Engine-side material registry — the resolved "how to draw" for a material handle.
Post-processing effects pipeline.
Rendering context containing all renderer state.
The point the frame is drawn relative to: a world far from zero loses precision in single floats,...
Central resource management system.
Parser for unified .esshader file format.
GPU shader program abstraction.
Diffuse global illumination from a world-space voxel cache, run as compute passes (WebGPU).
static Unique< Framebuffer > create(GfxDevice &device, const FramebufferSpec &spec)
Creates a framebuffer from specification.
static constexpr GfxContent retained()
Abstract graphics device interface.
Definition GfxDevice.hpp:75
bool programReady(ShaderHandle program)
Whether program can be drawn with now, without waiting: linked, or finished linking in the background...
virtual void setSurfaceSamples(u32 samples)
Asks for the backbuffer to be drawn with this many samples.
bool skipPendingPrograms() const
virtual u32 maxSamples()=0
Most samples an offscreen colour attachment may carry; 1 = none.
virtual bool supportsFloatTargets()=0
Whether RGBA16F color attachments are renderable.
void deleteBuffer(BufferHandle buffer)
Deletes a buffer.
virtual bool supportsCompute() const
Whether this device runs compute shaders.
void registerLayout(resource::ShaderHandle shader, MaterialUniformLayout layout)
const MaterialUniformLayout * layoutFor(resource::ShaderHandle shader) const
static MaterialUniformLayout layoutOf(const resource::ParsedShader &parsed)
void setPassContinuesEffect(const std::string &passName)
Mark passName as a later pass of the effect the pass before it began.
void setPassUniformVec4(const std::string &passName, const std::string &uniform, const glm::vec4 &value)
Sets a vec4 uniform for a pass.
void executeScreenPasses()
Executes screen-level post-process passes on captured output.
bool velocityWanted()
Whether an enabled pass reads how far each moving surface travelled (u_velocity).
void resize(u32 width, u32 height)
Resizes the framebuffers.
void clearScreenPasses()
Clears all screen-level passes.
f32 coverRange()
How far from the camera, in world units, that map reaches each way (the effect's u_shelterRange).
PostProcessPipeline(GfxDevice &device, RenderContext &context, resource::ResourceManager &resourceManager, rg::RenderGraph &graph)
Builds a pipeline that declares its chains onto the FRAME's graph.
u32 addComputePass(const std::string &name, const std::string &wgsl, const std::vector< std::string > &params, u32 workgroupX, u32 workgroupY)
Adds a pass that is a compute shader over the picture instead of a draw.
void begin(const f32 *clearColor=nullptr)
Begins rendering to the pipeline.
u32 addNativePass(const std::string &name, const std::string &kind)
Adds a pass the engine implements itself: "voxelGI" (see VoxelGI). Its parameters are set like any pa...
const PostProcessPass * getPass(u32 index) const
Gets a pass by index.
bool isEngaged() const
Whether the scene goes through the graph or straight to the surface.
void drawCloudShadow(const glm::mat4 &inverse, const glm::vec4 &rect, const rg::PassContext &ctx)
Draws the caster's cloud shadow into the tile at rect of the bound target: what of the sun is left in...
const PostProcessPass * cloudShadowCaster(f32 &extentKm, f32 &unitsPerKm) const
The sky that casts the sun's cloud shadow this frame, how far its map reaches each way in kilometres,...
bool temporalActive()
Whether this frame's chain holds a temporal effect.
glm::vec2 beginTemporalView(const glm::mat4 &viewProjection, u64 key)
Starts a frame of the temporal view key, and answers how far to shift it.
void setScreenPassUniformFloat(const std::string &passName, const std::string &uniform, f32 value)
Sets a float uniform for a screen-level pass.
bool coverWanted()
Whether an enabled pass reads what stands over each place (u_rainCover).
rg::ResourceId declareCover(u32 size)
The map's target for this frame, declared in the graph (kNoResource when it cannot be made).
void setScreenPassUniformVec4(const std::string &passName, const std::string &uniform, const glm::vec4 &value)
Sets a vec4 uniform for a screen-level pass.
bool drawProjectedMaterial(u32 material, u32 instances, u32 scratch, const glm::vec4 &sun, const glm::vec4 &receiverWindow, TextureHandle receiverDepth, TextureHandle movingDepth)
FramebufferHandle currentSceneFBO() const
The surface the scene is currently rendering into: the screen-capture FBO when the screen stack is li...
void setOutputTarget(FramebufferHandle target)
Sets the output target for the final blit (Default = screen).
void clearPasses()
Checks if bypass mode is enabled.
TemporalView peekTemporalView(const glm::mat4 &viewProjection, u64 key) const
void setPassUniformFloat(const std::string &passName, const std::string &uniform, f32 value)
Sets a float uniform for a pass.
bool presentUpscales() const
Whether the present is a whole-multiple upscale of the chain.
void beginScreenCapture()
Begins screen-level capture (all camera output goes into screen FBO).
void drawSelectionOutline(TextureHandle mask)
The selection's outline over what the bound target holds, from its mask. Blended over; the caller set...
rg::ResourceId declareVelocity()
The motion pass's target for this frame, declared in the graph (kNoResource when it cannot be made).
void requestSkyCapture(const std::string &passName, u32 width, u32 height)
Draws pass passName once more, next frame, into a width x height RGBA8 target with its float param u_...
void trackView(const glm::mat4 &viewProjection, u64 key)
Records this frame's camera as the view key's current one, and last frame's as its previous....
void setPassScale(const std::string &passName, f32 scale)
Draw passName at scale of the chain size (clamped to (0, 1]).
void shutdown()
Shuts down and releases resources.
bool drawMaterialThrough(u32 material, u32 shader, const std::vector< std::pair< std::string, glm::vec4 > > &overrides, u32 scratch)
u32 addPass(const std::string &name, resource::ShaderHandle shader)
Adds a post-processing pass.
bool sceneCoverageWanted()
Whether the scene is to be cleared to nothing (all four channels zero) so that its alpha says how muc...
u32 addScreenPass(const std::string &name, resource::ShaderHandle shader)
Adds a screen-level post-process pass.
void encodeRgbm()
Draws the texture on unit 0 into the bound target as RGBM over 8 (alpha 0 kept for nothing drawn): a ...
bool cameraMotionWanted()
Whether an enabled pass that keeps no history reads the previous camera (u_prevViewProjection0).
i32 pollSkyCapture()
0 = not yet, 1 = the pixels are ready (skyCapturePixels), 2 = none was asked for or it failed....
void setRequestedSamples(u32 samples)
The project's multisampling request; 1 = off. Clamped by the device.
bool supportsCompute() const
Whether passes added with addComputePass run on this device.
void setPassTexture(const std::string &passName, const std::string &uniform, u32 glTextureId)
Binds a texture to a pass's sampler uniform (unit 2 upward, in registration order)....
f32 coverBias()
The bias the drawing effect reads the map with (its u_shelterBias), for a pass that only borrows the ...
void init(u32 width, u32 height)
Initializes the pipeline with given dimensions.
void setOutputViewport(u32 x, u32 y, u32 w, u32 h)
Sets the output viewport for the final blit.
void drawSelectionGround(TextureHandle depth)
The selection mask's ground, into the bound mask target: the scene's depth in g, nothing covered.
void endScreenCapture()
Ends screen-level capture.
void grabDepth()
Draws, into the target being drawn, the distance to the opaque scene at every pixel (the scene's dept...
MaterialStore & materials()
The engine-side material registry (handle -> resolved render state).
GPU shader program for rendering.
Definition Shader.hpp:86
void commitParams()
Uploads the shadow (when dirty) and binds this shader's params UBO at DRAW_PARAMS_BINDING.
Definition Shader.cpp:382
GfxShaderLanguage language() const
The source language this program was compiled from.
Definition Shader.hpp:126
void setUniform(const std::string &name, i32 value) const
Sets an integer uniform.
Definition Shader.cpp:422
bool hasUniform(const std::string &name) const
True if the linked program declares this uniform.
Definition Shader.cpp:364
ShaderHandle handle() const
Gets the device program handle.
Definition Shader.hpp:254
bool isValid() const
Checks if the handle references a valid resource.
Definition Handle.hpp:82
Central manager for GPU resources.
ShaderTargetLanguage preferredShaderTarget() const
preferredShaderLanguage() as a ShaderParser assembly target.
GfxShaderLanguage preferredShaderLanguage() const
The language embedded pipelines must author their sources in.
Shader * getShader(ShaderHandle handle)
Gets a shader by handle.
ShaderHandle createShader(const std::string &vertSrc, const std::string &fragSrc, bool rewriteLoose=true, GfxShaderLanguage language=GfxShaderLanguage::GLSL_ES300, bool deferLink=false)
static ParsedShader parse(const std::string &source)
Parses shader source into structured format (no include support).
static std::string assembleStage(const ParsedShader &parsed, ShaderStage stage, const std::string &platform="", const std::vector< std::string > &features={}, ShaderTargetLanguage target=ShaderTargetLanguage::GLSL_ES300)
Assembles final GLSL source for a specific stage.
Handle< esengine::Shader > ShaderHandle
Handle to a shader resource.
Definition Handle.hpp:214
constexpr ResourceId kNoResource
FramebufferHandle
Handle 0 is the default framebuffer (backbuffer); it cannot be created or deleted.
Definition GfxEnums.hpp:41
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
std::uint64_t u64
Unsigned 64-bit integer.
Definition Types.hpp:47
std::size_t usize
Size type for indexing and sizes.
Definition Types.hpp:64
OutputTransform
What the last pass of a chain does to scene values on the way out.
@ ACES
Narkowicz ACES filmic curve, for a scene that carries HDR radiance.
@ None
Encode only. Values above 1 clip, which is what LDR content means.
@ Neutral
Khronos PBR Neutral: hue and saturation survive, highlights roll off.
glm::mat4 viewProjectionFromOrigin(const glm::mat4 &viewProjection, const glm::dvec3 &origin)
A view-projection made for origin, for a point given from the origin now: the point from the old orig...
ComputeHandle
A compute program (GfxDevice::createCompute); only a device that supportsCompute() issues one.
Definition GfxEnums.hpp:39
constexpr u32 kGBufferUnit
The unit a PostProcess pass reads the scene's surface record at: what a surface IS — octahedral norma...
HdrFormatDecision decideHdrFormat(bool linearOutput, bool supportsFloatTargets)
What a linear project asks for, and what supportsFloatTargets grants.
Definition HdrFormat.hpp:82
constexpr u32 kSceneDepthUnit
The unit a PostProcess pass reads the scene's DEPTH at.
GfxReadbackStatus
State of an in-flight readback. GL completes at request time (first poll reports Ready); WebGPU resol...
Definition GfxEnums.hpp:47
std::uint32_t u32
Unsigned 32-bit integer.
Definition Types.hpp:45
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.
static EstellaContext & ctx()
float f32
32-bit floating point
Definition Types.hpp:59
Framebuffer creation parameters.
GfxPixelFormat colorFormat
Color attachment format. RGBA16F needs GfxDevice::supportsFloatTargets.
bool depthStencil
Whether to create depth/stencil attachment.
bool linearFilter
Texture filter mode: false=GL_NEAREST, true=GL_LINEAR.
u32 height
Framebuffer height in pixels.
u32 width
Framebuffer width in pixels.
A compute program's source. Compute is WGSL only: GLSL ES 3.00 has no compute stage.
Definition GfxEnums.hpp:673
One scalar/vector param's slot in a shader's std140 MaterialConstants block.
A shader's layout: std140 block (scalar/vector params) + texture sampler slots.
const MaterialParamSlot * find(const std::string &name) const
bool highPrecision
The shader writes a measurement and wants a float target (ParsedShader::highPrecision).
std::vector< MaterialTextureSlot > textures
const MaterialTextureSlot * findTexture(const std::string &name) const
bool usesLights
The shader reads the frame's light block and shadow atlas (ParsedShader::usesLights).
Post-processing pass configuration.
resource::ShaderHandle shader
std::unordered_map< std::string, f32 > floatUniforms
u32 paramUboBytes
The size paramUbo was made with: what lets the next chain's pass of the same size take it over.
std::string nativeKind
A pass the engine implements itself, in compute passes of its own (see VoxelGI): its name,...
std::vector< std::pair< std::string, u32 > > textureUniforms
u64 historyKey
Which remembered state the pass uses, resolved when the chain is declared.
std::vector< std::pair< std::string, rg::ResourceId > > earlierInputs
std::vector< std::string > computeParams
std::unordered_map< std::string, glm::vec4 > vec4Uniforms
What a temporal view would be given by its NEXT begin: the sub-pixel shift and last frame's camera.
glm::vec2 previousJitter
The shift the previous frame was drawn with.
One render pass: a target, which attachments to clear on entry, and the clear values — full load-op s...
Definition GfxEnums.hpp:485
Shape of a target the graph allocates.
bool gbuffer
A second colour attachment for the surface's material, drawn beside the first.