8#ifdef ES_ENABLE_GPU_PARTICLES
33#include <glm/gtc/matrix_transform.hpp>
34#include <glm/gtc/type_ptr.hpp>
39#include <emscripten.h>
55 if (queries_[0] != 0) {
62 if (state_ != 1 || inflight_[write_])
return;
70 inflight_[write_] =
true;
71 write_ = (write_ + 1) % kRing;
76 if (state_ != 1)
return;
78 for (
int i = 0; i < kRing; ++i) inflight_[i] =
false;
82 while (inflight_[read_]) {
85 last_ms_ =
static_cast<f32>(ns) / 1.0e6f;
86 inflight_[read_] =
false;
87 read_ = (read_ + 1) % kRing;
96 const f32* m = glm::value_ptr(vp);
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];
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];
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];
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];
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];
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];
116 for (
u32 i = 0; i < 6; ++i) {
120 planes[i].distance /= len;
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);
131 f32 dist =
planes[i].signedDistance(center);
141 for (
u32 i = 0; i < 6; ++i) {
142 if (
planes[i].signedDistance(a) < -radius &&
planes[i].signedDistance(b) < -radius)
return false;
151 , resource_manager_(resource_manager)
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);
177#ifdef ES_ENABLE_POSTPROCESS
180 post_process_->setLinearOutput(linear_color_);
184 applySceneDepthNeed();
185 post_process_->init(width, height);
188#ifdef ES_ENABLE_GPU_PARTICLES
194 velocity_pool_.init();
195 selection_pool_.init();
197 shadow_mover_pool_.init();
198 cover_mover_pool_.init();
201 batch_shader_id_ = initBatchShader();
206 context_.getWhiteTextureId(),
213 for (
auto& plugin : plugins_) {
214 plugin->init(initCtx);
219 for (
auto& plugin : plugins_) {
223#ifdef ES_ENABLE_GPU_PARTICLES
224 if (gpu_particles_) {
225 gpu_particles_->release();
226 gpu_particles_.reset();
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();
238 shadow_mover_pool_.shutdown();
239 cover_mover_pool_.shutdown();
241 device_.deleteBuffer(cover_frame_ubo_);
244 planar_pool_.shutdown();
246 if (overlay_hold_) overlay_hold_->pool.shutdown();
247 overlay_hold_.reset();
248 for (
auto& segment : segments_)
if (segment.hold) segment.hold->pool.shutdown();
250 segments_trusted_ =
false;
251 overlay_valid_ =
false;
252 probe_pool_.shutdown();
254 device_.deleteBuffer(probe_capture_.frameUbo);
257 releasePlanarCaptures();
258 releaseShadowFrameUbos();
259 releaseShadow2DResources();
260 releaseShape2DResources();
261 releaseOverlayBackdrop();
262 releaseFrameTargets();
263 target_pool_.clear();
265#ifdef ES_ENABLE_POSTPROCESS
267 post_process_->shutdown();
268 post_process_.reset();
279#ifdef ES_ENABLE_POSTPROCESS
281 post_process_->resize(width, height);
288bool RenderFrame::gpuDetailWanted()
const {
291 return EM_ASM_INT({
return Module.esGpuDetail ? 1 : 0; }) != 0;
300 const u32 prepassDraws = depth_prepass_ && opaque ? list.depthPrepassDraws() : 0u;
301 const bool prepass = prepassDraws > 0;
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"));
312 if (detail) sinkFor(
"prepass:");
313 list.execute(device_, buffers, context_.materials(), context_.getWhiteTextureId(),
315 if (detail) list.setShaderRunSink(
nullptr);
317 if (detail) sinkFor(
"");
318 list.execute(device_, buffers, context_.materials(), context_.getWhiteTextureId(),
319 capture, context_.perDrawBlocks(), phase,
322 running_pass_timer_->segment(
"tail");
323 list.setShaderRunSink(
nullptr);
331 glm::vec2 jitter{0.0f};
332#ifdef ES_ENABLE_POSTPROCESS
334 if (post_process_) post_process_->setEnvironmentTexture(environment_texture_id_);
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_);
345 scene_jitter_ = jitter;
346 context_.updateCameraConstants(view_projection_, jitter);
350 if ((shadow2DActive() || shape2DActive()) && width_ > 0 && height_ > 0) {
351 const f32 w =
static_cast<f32>(width_);
352 const f32 h =
static_cast<f32>(height_);
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));
360 context_.lights().setMask2DRect(glm::vec4(0.0f));
364 draw_list_.setMask2DTexture(
SHAPE_2D_TEXTURE_UNIT, shape_2d_texture_id_ != 0 ? shape_2d_texture_id_ : shadow_2d_masks_[1].textureId);
369 WaterSunField field = water_sun_;
370 if (cloud_sun_slot_ < 0 || glm::dot(-cloud_sun_aim_, field.sunDirection) < 0.99999f) field = {};
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);
378 ?
TextureHandle{context_.getWhiteTextureId()} : field.texture);
379 context_.lights().uploadAndBind();
383#ifdef ES_ENABLE_POSTPROCESS
384 draw_list_.setGBufferPass(post_process_ && post_process_->sceneHasGBuffer());
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()) {
392 stats_.waiting_for_program = draw_list_.skippedForProgram();
398 const ProbeStore& probes = context_.probes();
401 ES_PROFILE_COUNTER(
"render.probes.atlasBytes", probes.atlasTexture() != 0 ? probes.atlasBytes() : 0);
408 device_.invalidatePipelineCache();
409 device_.setScissorTest(
false);
415void RenderFrame::releaseFrameTargets() {
416 shadow_texture_id_ = 0;
421 if (skin_cache_) skin_cache_->beginFrame(planar_frame_);
424 overlay_active_ =
false;
425 overlay_segmented_ =
false;
427#ifdef ES_ENABLE_GPU_PARTICLES
428 if (gpu_particles_) gpu_particles_->beginFrame();
430 for (
auto it = planar_captures_.begin(); it != planar_captures_.end();) {
431 if (frame_collected_ && it->second.lastSeen + 1 < planar_frame_) {
433 it = planar_captures_.erase(it);
439 releaseFrameTargets();
445 if (frame_collected_) {
446 depth_answered_ =
true;
447 if (frame_depth_seen_) depth_seen_ =
true;
448 scene_picture_seen_ = frame_scene_picture_seen_;
450 frame_scene_picture_seen_ =
false;
451 frame_collected_ =
false;
452 frame_depth_seen_ =
false;
453 applySceneDepthNeed();
459 lod_view_state_.beginFrame();
464 context_.beginPerDrawBlocks();
465 frame_capture_.beginFrame();
470 std::fill(std::begin(frame_breaks_), std::end(frame_breaks_), 0u);
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();
480 post_process_->setComputeNeedsDepth(computeNeedsDepth || scene_picture_seen_);
483 post_process_->setSelectionWanted(outlining);
484 post_process_->setSceneNeedsDepth(!depth_answered_ || depth_seen_ || computeNeedsDepth || scene_picture_seen_
485 || draw_list_.
depthMask() != 0 || outlining);
500#ifdef ES_ENABLE_POSTPROCESS
501 if (post_process_) post_process_->setBackgroundSky(
false);
502 if (post_process_ && post_process_->isEngaged()) {
511 projected_bake_resources_.clear();
518 if (!device_.beginDeviceFrame()) {
523 view_projection_ = view_projection;
524 frustum_.extractFromMatrix(view_projection);
528 current_target_ = target;
533 openPass(clear, target);
538 scene_viewport_ = {clear.
x, clear.
y, clear.
w, clear.
h};
544#ifdef ES_ENABLE_POSTPROCESS
545 if (post_process_ && post_process_->isEngaged()) {
546 scene_resource_ = post_process_->sceneResource();
550 graph_.begin(width_, height_);
551 scene_resource_ = graph_.importTarget(scene_fbo_, width_, height_);
559#ifdef ES_ENABLE_POSTPROCESS
560 const bool usePostProcess = post_process_ && post_process_->isEngaged();
562 const bool usePostProcess =
false;
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};
584#ifdef ES_ENABLE_POSTPROCESS
586 if (usePostProcess && post_process_->sceneCoverageWanted()) {
592 if (usePostProcess && !clear.color) {
594 post_process_->setPresentOver(
true);
602 if (usePostProcess) {
603#ifdef ES_ENABLE_POSTPROCESS
605 auto* rt = target_manager_.get(target);
607 post_process_->setOutputTarget(rt->getFramebuffer());
616 pass.
target = post_process_->currentSceneFBO();
617 device_.beginRenderPass(pass);
620 auto* rt = target_manager_.get(target);
622 pass.
target = rt->getFramebuffer();
623 device_.beginRenderPass(pass);
629#ifdef ES_ENABLE_POSTPROCESS
630 if (post_process_) pass.
target = post_process_->currentSceneFBO();
632 device_.beginRenderPass(pass);
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);
651 stats_.triangles += (cmd.index_count / 3) * (cmd.instance_count ? cmd.instance_count : 1);
657#ifdef ES_ENABLE_PARTICLES
658 stats_.particles += list.sourceEntityCount(RenderType::Particle);
665 if (!in_frame_ || flushed_)
return;
672 if (!device_.isDeviceUsable())
return;
675 device_.invalidatePipelineCache();
690 draw_list_.reserveMask2DSlots(
693 draw_list_.finalize(pool_);
701 accumulateStats(draw_list_);
706 tallyPass(draw_list_);
711 if (gpu_frame_open_) {
712 gpu_frame_open_ =
false;
713 if (gpu_frame_passes_ && pass_timer_) {
724 for (
const auto& e : passTimer.
last()) {
725 pass_scope_names_.try_emplace(e.name, std::string(
"pass/") + e.name);
732 }
else if (!gpu_frame_passes_) {
733 gpu_timer_.end(device_);
734 pass_graph_ms_ = -1.0f;
738 frame_capture_.endFrame();
740 stats_.gpu_draws = device_.takeDraws();
741 publishFrameCounters();
749void RenderFrame::tallyPass(
const DrawList& list) {
756void RenderFrame::publishFrameCounters() {
767 if (frame_breaks_[r] == 0)
continue;
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);
807#ifdef ES_ENABLE_PARTICLES
810#ifdef ES_ENABLE_GPU_PARTICLES
811 ES_PROFILE_COUNTER(
"render.particles.gpuSlots", gpu_particles_ ? gpu_particles_->drawnSlots() : 0u);
817 if (!in_frame_)
return;
823#ifdef ES_ENABLE_POSTPROCESS
824 const bool usePostProcess = post_process_ && post_process_->isEngaged();
826 const bool usePostProcess =
false;
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));
851 for (
const Shadow2DMask& mask : shadow_2d_masks_) {
855 scene.
dependencies.insert(scene.
dependencies.end(), projected_bake_resources_.begin(), projected_bake_resources_.end());
856#ifdef ES_ENABLE_GPU_PARTICLES
858 if (gpu_particles_) {
867#ifdef ES_ENABLE_POSTPROCESS
868 glass = usePostProcess && draw_list_.anyUsesSceneColor(context_.materials());
875 bool layered =
false;
876#ifdef ES_ENABLE_POSTPROCESS
877 layered = glass && draw_list_.anyBlendedWithoutSceneColor(context_.materials());
880#ifdef ES_ENABLE_POSTPROCESS
881 screen = usePostProcess && draw_list_.anyUsesScreenColor(context_.materials());
883 draw_list_.setDeferScreenColor(screen);
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();
896#ifdef ES_ENABLE_POSTPROCESS
897 grabDepth = graph_.createTarget(post_process_->grabDepthTarget());
899 blendedPass.
name =
"scene-blended";
902 context_.materials().setSceneDepth(graph_.textureOf(grabDepth));
905 if (!screen && presented_overlay_draw_) presented_overlay_draw_->flushDeferred();
910#ifdef ES_ENABLE_POSTPROCESS
911 grab = graph_.createTarget(post_process_->grabTarget());
912 if (layered) grabOpaque = graph_.createTarget(post_process_->grabTarget());
915 if (draw_list_.anyUsesSceneDepth(context_.materials()) && post_process_->canGrabDepth()) {
916 grabDepth = graph_.createTarget(post_process_->grabDepthTarget());
919 glassPass.
name =
"scene-glass";
924 blendedPass.
name =
"scene-blended";
928 if (grabDepth !=
rg::kNoResource) context_.materials().setSceneDepth(graph_.textureOf(grabDepth));
933 overPass.
name =
"scene-blended-over";
937 if (grabDepth !=
rg::kNoResource) context_.materials().setSceneDepth(graph_.textureOf(grabDepth));
940 if (!screen && presented_overlay_draw_) presented_overlay_draw_->flushDeferred();
944 context_.materials().setSceneColor(graph_.textureOf(grab));
945 if (grabDepth !=
rg::kNoResource) context_.materials().setSceneDepth(graph_.textureOf(grabDepth));
949 if (!layered && !screen && presented_overlay_draw_) presented_overlay_draw_->flushDeferred();
957 const bool ordered = !glass && draw_list_.anyUsesSceneColor(context_.materials())
958 && draw_list_.anyBlendedWithoutSceneColor(context_.materials());
967 if (!glass && !depthFade && !screen && presented_overlay_draw_) presented_overlay_draw_->flushDeferred();
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()));
976#ifdef ES_ENABLE_POSTPROCESS
978 copy.
name =
"scene-grab";
979 copy.
reads = {scene_resource_};
980 copy.
write = layered ? grabOpaque : grab;
983 graph_.addPass(std::move(copy));
986 copyDepth.
name =
"scene-grab-depth";
987 copyDepth.
reads = {scene_resource_};
988 copyDepth.
write = grabDepth;
990 graph_.addPass(std::move(copyDepth));
993 graph_.addPass(std::move(blendedPass));
995 copyBlended.
name =
"scene-grab-blended";
996 copyBlended.
reads = {scene_resource_};
997 copyBlended.
write = grab;
999 graph_.addPass(std::move(copyBlended));
1002 restore.
name =
"scene-restore";
1003 restore.
reads = {grabOpaque};
1004 restore.
write = scene_resource_;
1008 graph_.addPass(std::move(restore));
1011 graph_.addPass(std::move(glassPass));
1012 if (layered) graph_.addPass(std::move(overPass));
1015#ifdef ES_ENABLE_POSTPROCESS
1017 copyDepth.
name =
"scene-grab-depth";
1018 copyDepth.
reads = {scene_resource_};
1019 copyDepth.
write = grabDepth;
1021 graph_.addPass(std::move(copyDepth));
1022 graph_.addPass(std::move(blendedPass));
1026#ifdef ES_ENABLE_POSTPROCESS
1027 const rg::ResourceId grabScreen = graph_.createTarget(post_process_->grabTarget());
1029 copyScreen.
name =
"screen-grab";
1030 copyScreen.
reads = {scene_resource_};
1031 copyScreen.
write = grabScreen;
1033 graph_.addPass(std::move(copyScreen));
1034 screenPass.
name =
"scene-screen";
1037 context_.materials().setScreenColor(graph_.textureOf(grabScreen));
1040 if (presented_overlay_draw_) presented_overlay_draw_->flushDeferred();
1042 graph_.addPass(std::move(screenPass));
1047#ifdef ES_ENABLE_POSTPROCESS
1050 if (usePostProcess && scene_resource_ !=
rg::kNoResource && velocity_list_.commandCount() > 0) {
1051 const rg::ResourceId velocity = post_process_->declareVelocity();
1054 motion.
name =
"motion";
1055 motion.
write = velocity;
1056 motion.
clear =
true;
1061 graph_.addPass(std::move(motion));
1066#ifdef ES_ENABLE_POSTPROCESS
1068 if (usePostProcess && scene_resource_ !=
rg::kNoResource && cover_wanted_ && coverCommandCount() > 0) {
1070 const bool standing = cover_drawn_valid_ && cover_trusted_ && cover_drawn_key_ == cover_key_
1071 && cover_drawn_target_ == post_process_->coverTargetId();
1073 if (standing) ++cover_kept_total_;
1074 if (cover !=
rg::kNoResource) post_process_->setCoverMatrix(cover_view_projection_);
1077 pass.
name =
"rain-cover";
1084 graph_.addPass(std::move(pass));
1089#ifdef ES_ENABLE_POSTPROCESS
1094 if (selectionMask !=
rg::kNoResource) post_process_->setSelectionMask(selectionMask);
1097 if (usePostProcess) {
1098#ifdef ES_ENABLE_POSTPROCESS
1099 post_process_->setShadowAtlas(shadow_texture_id_, shadow_resource_);
1100 post_process_->declareChain();
1110 if (pass_timer_->available()) passTimer = pass_timer_.get();
1115 if (!gpu_frame_open_) {
1116 gpu_frame_open_ =
true;
1117 gpu_frame_passes_ = passTimer !=
nullptr;
1121 gpu_timer_.poll(device_);
1122 gpu_timer_.begin(device_);
1125 if (gpu_frame_passes_ && passTimer) {
1126 graph_.setPassTimer(passTimer);
1127 running_pass_timer_ = passTimer;
1129 running_pass_timer_ =
nullptr;
1130 graph_.setPassTimer(
nullptr);
1135#ifdef ES_ENABLE_GPU_PARTICLES
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);
1143 shadow_views_.clear();
1145 if (usePostProcess) {
1146#ifdef ES_ENABLE_POSTPROCESS
1147 post_process_->chainDone();
1150 auto* rt = target_manager_.get(current_target_);
1157 stats_.gpu_time_ms = pass_graph_ms_ >= 0.0f ? pass_graph_ms_ : gpu_timer_.lastMs();
1163 device_.endRenderPass();
1164 runPendingReplay(view_projection_, scene_viewport_.w, scene_viewport_.h);
1172 if (drawIndex < 0 ||
static_cast<u32>(drawIndex) >= frame_capture_.getRecordCount())
return;
1174 const u32 pass = records[drawIndex].
pass;
1176 for (
i32 i = 0; i < drawIndex; ++i) {
1177 if (records[i].pass == pass) ++local;
1179 replay_pass_ =
static_cast<i32>(pass);
1180 replay_draw_ = local;
1183 snapshot_pixels_.clear();
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_;
1191 if (w == 0 || h == 0) {
1200 if (replay_rt_ == 0) {
1201 replay_rt_ = target_manager_.
create(w, h,
true,
false);
1202 }
else if (
auto* existing = target_manager_.get(replay_rt_);
1203 existing && (existing->getWidth() != w || existing->getHeight() != h)) {
1204 existing->resize(w, h);
1206 auto* rt = target_manager_.get(replay_rt_);
1209 RenderPassDesc replayPass{rt->getFramebuffer(),
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);
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();
1223 device_.setScissorTest(
false);
1224 device_.invalidatePipelineCache();
1225 device_.endRenderPass();
1229 snapshot_pixels_.clear();
1230 snapshot_readback_ = device_.requestReadback(rt->getFramebuffer(), w, h);
1234 renderSurface(registry, viewProjection, preview_, w, h, {});
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;
1243 if (surface.target == 0) {
1244 surface.target = target_manager_.
create(w, h,
true,
false);
1245 }
else if (
auto* existing = target_manager_.
get(surface.target);
1246 existing && (existing->getWidth() != w || existing->getHeight() != h)) {
1247 existing->resize(w, h);
1249 auto* rt = target_manager_.get(surface.target);
1252 RenderPassDesc previewPass{rt->getFramebuffer(),
true};
1253 previewPass.clearDepth =
true;
1254 previewPass.clearStencil =
true;
1255 previewPass.clearColorValue[3] = 0.0f;
1256 device_.beginRenderPass(previewPass);
1257 device_.setViewport(0, 0, w, h);
1262 view_projection_ = viewProjection;
1263 frustum_.extractFromMatrix(viewProjection);
1264 view_id_ = kPreviewViewId;
1268 clip_state_.clear();
1276 for (
const auto& batch : extraSkeletalBatches) {
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);
1283 draw_list_.finalize(pool_);
1285 context_.updateCameraConstants(viewProjection);
1286 context_.lights().uploadAndBind();
1287 draw_list_.execute(device_, pool_, context_.materials(), context_.getWhiteTextureId(),
1288 nullptr, context_.perDrawBlocks());
1291 device_.invalidatePipelineCache();
1297 surface.pixels.clear();
1298 surface.readback = device_.requestReadback(rt->getFramebuffer(), w, h);
1302 if (replay_draw_ >= 0)
return 0;
1303 return pollReadback(snapshot_readback_, snapshot_pixels_, snapshot_w_, snapshot_h_);
1306RenderFrame::SkeletalPreview* RenderFrame::skeletalPreview(SkeletalPreviewId
id) {
1307 auto it = skeletal_previews_.find(
id);
1308 return it == skeletal_previews_.end() ?
nullptr : it->second.get();
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();
1317 if (w == 0 || h == 0)
return 0;
1318 auto preview = std::make_unique<SkeletalPreview>();
1322 preview->entity = preview->registry.create();
1324 preview->surface.width = w;
1325 preview->surface.height = h;
1327 skeletal_previews_.emplace(
id, std::move(preview));
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
1338 auto* preview = skeletalPreview(
id);
1339 if (!preview || !vertices || !indices || vertexCount < 0 || indexCount < 0)
return false;
1343 batch.
vertices.assign(vertices, vertices +
static_cast<usize>(vertexCount) * 8);
1344 batch.
indices.assign(indices, indices +
static_cast<usize>(indexCount));
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;
1353 preview->pending.push_back(std::move(batch));
1358 auto* preview = skeletalPreview(
id);
1359 if (!preview)
return false;
1365 const auto batches = std::exchange(preview->pending, {});
1366 renderSurface(preview->registry, viewProjection, preview->surface,
1367 preview->surface.width, preview->surface.height, batches);
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);
1379 const auto* preview = skeletalPreview(
id);
1380 return preview ? preview->surface.pixels.data() :
nullptr;
1384 const auto* preview = skeletalPreview(
id);
1385 return preview ?
static_cast<u32>(preview->surface.pixels.size()) : 0;
1389 const auto* preview = skeletalPreview(
id);
1390 return preview ? preview->surface.width : 0;
1394 const auto* preview = skeletalPreview(
id);
1395 return preview ? preview->surface.height : 0;
1399 auto it = skeletal_previews_.find(
id);
1400 if (it == skeletal_previews_.end())
return;
1403 auto& surface = it->second->surface;
1405 device_.discardReadback(surface.readback);
1408 if (surface.target != 0) target_manager_.release(surface.target);
1409 skeletal_previews_.erase(it);
1413 return pollReadback(preview_.readback, preview_.pixels, preview_.width, preview_.height);
1419 return pixels.empty() ? 2 : 1;
1425 pixels.resize(
static_cast<usize>(w) * h * 4);
1426 const bool ok = device_.
takeReadback(handle, pixels.data(), pixels.size());
1428 if (!ok) pixels.clear();
1444 clip_rects_.clear();
1448 stencil_masks_[entity] = {refValue,
true, hierarchical};
1452 stencil_masks_[entity] = {refValue,
false, hierarchical};
1456 stencil_masks_.clear();
1468 plugins_.push_back(std::move(plugin));
1471void RenderFrame::buildClipState() {
1472 clip_state_.
clear();
1474 for (
const auto& [entity, rect] : clip_rects_) {
1475 clip_state_.
setScissor(entity, rect.x, rect.y, rect.w, rect.h);
1478 for (
const auto& [entity, info] : stencil_masks_) {
1479 if (info.hierarchical) {
1485 clip_state_.setStencilMask(entity, info.ref_value);
1487 clip_state_.setStencilTest(entity, info.ref_value);
1503 list.setSortingGroup(entity.id(), identity);
1511 if (inner.enabled) {
1512 childIdentity.blockOrder =
true;
1513 childIdentity.block = inner.order;
1516 assignSortingSubtree(registry, list, child, childIdentity);
1538void RenderFrame::buildSortingGroups(
ecs::Registry& registry) {
1539 draw_list_.clearSortingGroups();
1541 auto groups = registry.activeView<ecs::SortingGroup>();
1542 for (
auto entity : groups) {
1543 const auto& group = groups.get(entity);
1544 if (!group.enabled)
continue;
1548 if (hasEnclosingGroup(registry, entity))
continue;
1549 assignSortingSubtree(registry, draw_list_, entity,
1550 {group.layer, group.order,
false, 0});
1554void RenderFrame::buildTreeSequence(
ecs::Registry& registry) {
1555 std::vector<u32>& sequence = draw_list_.treeSequence();
1557 if (draw_list_.treeMask() == 0)
return;
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);
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;
1581void RenderFrame::buildSpriteMasks(
ecs::Registry& registry) {
1584 static constexpr i32 MAX_MASK_REF = 255;
1586 std::vector<ResolvedMask>& masks = sprite_mask_scratch_;
1589 auto maskView = registry.activeView<ecs::SpriteMask>();
1590 for (
auto entity : maskView) {
1591 const auto& mask = maskView.get(entity);
1592 if (!mask.enabled)
continue;
1595 if (!registry.has<ecs::Sprite>(entity))
continue;
1596 const auto& sprite = registry.get<ecs::Sprite>(entity);
1597 if (!sprite.enabled)
continue;
1600 draw_list_.sortIdentity(entity.id(), sprite.layer, sprite.order),
1601 {mask.rangeEndLayer, mask.rangeEndOrder},
1605 mask_entities_scratch_.push_back(entity);
1607 if (masks.empty()) { mask_entities_scratch_.clear();
return; }
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; });
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");
1623 masks[slot].ref = nextRef++;
1624 clip_state_.setStencilMask(mask_entities_scratch_[slot].
id(), masks[slot].ref);
1626 if (clip_state_.reserveSpriteStencilReferences(nextRef - 1)) {
1627 ES_LOG_WARN(
"UI masks exceed remaining stencil references after SpriteMask allocation; overflowing subtrees are clipped");
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;
1636 const auto where = draw_list_.sortIdentity(entity.id(), sprite.layer, sprite.order);
1637 const ResolvedMask* nearest =
1639 if (!nearest)
continue;
1642 clip_state_.setStencilTestOutside(entity.id(), nearest->ref);
1644 clip_state_.setStencilTest(entity.id(), nearest->ref);
1647 mask_entities_scratch_.clear();
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);
1657 out += std::to_string(
static_cast<u32>(std::ceil(side)));
1659 texture_wants_.clear();
1675 environment_texture_id_
1677 ctx.lighting_direct = lighting_direct_;
1679 ctx.has_view_eye = eye.w > 0.5f;
1680 if (
ctx.has_view_eye)
ctx.view_eye = glm::vec3(eye);
1688 if (!transform)
return glm::vec3(0.0f, 0.0f, -1.0f);
1690 return transform->
worldRotation * glm::vec3(0.0f, 0.0f, -1.0f);
1700void RenderFrame::collectProbes(ecs::Registry& registry) {
1701 ProbeStore& probes = context_.
probes();
1704 auto view = registry.activeView<ecs::LightProbeVolume>();
1705 for (
auto entity : view) {
1706 const auto& volume = view.get(entity);
1707 if (!volume.enabled)
continue;
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;
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);
1723 if (!probes_per_pixel_) {
1724 if (probe_atlas_) probe_atlas_.reset();
1725 probes.forgetAtlas();
1729 if (probes.layoutAtlas(256) && probes.atlasWidth() > 0) {
1730 probes.fillAtlas(probe_atlas_texels_);
1734 probes.setAtlasTexture(probes.atlasWidth() > 0 && probe_atlas_ ? probe_atlas_->getId() : 0);
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();
1757 occlusion_.addBox(
rebased(transform->worldPosition), transform->worldRotation,
1758 glm::abs(occluder.halfExtents));
1760 occlusion_.finish();
1771void RenderFrame::collectReflections(
ecs::Registry& registry) {
1772 ReflectionStore& store = context_.reflections();
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());
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);
1799 if (store.empty())
return;
1801 const Environment* baked =
1803 if (!baked || !baked->hasSpecular())
return;
1804 Texture* atlas = resource_manager_.getTexture(baked->specular);
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);
1818 environment_texture_id_ = atlas->getId();
1819 context_.lights().setReflections(
1820 glm::vec4(1.0f, baked->maxRange,
static_cast<f32>(baked->mipCount) - 1.0f,
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};
1833void RenderFrame::collectLights(ecs::Registry& registry) {
1834 LightStore& lights = context_.
lights();
1836 shadow_casters_.clear();
1837 cloud_sun_slot_ = -1;
1839 environment_texture_id_ = 0;
1840 sky_texture_id_ = 0;
1842 scene_sky_available_ =
false;
1844 if (view_lighting_.
studio) {
1845 collectStudioLights(registry);
1852 auto view = registry.activeView<ecs::Light>();
1854 const Environment* sky =
nullptr;
1855 glm::vec3 skyScale(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;
1864 if (
const Environment* environment = resource_manager_.getEnvironment(environmentOf(light))) {
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;
1875 const ecs::Light* tone =
nullptr;
1876 for (
auto entity : view) {
1877 const auto& light = view.get(entity);
1879 if (entity == skyLight) { tone = &light;
break; }
1880 if (!tone) tone = &light;
1882 if (tone) context_.lights().setReflectionTone(tone->reflectionScale, tone->reflectionSaturation);
1883 context_.lights().setBakedTint(tone ? glm::vec3(tone->bakedTint) : glm::vec3(1.0f));
1885 const bool sunCast = sunFollowed && sky && sky->hasSun;
1887 light_cap_.environmentSun =
true;
1894 std::vector<CollectedLight>& collected = light_scratch_;
1896 bool haveSun =
false;
1901 for (
auto entity : view) {
1902 const auto& light = view.get(entity);
1903 if (!light.enabled || light.intensity <= 0.0f)
continue;
1908 const glm::vec3 rgb = linear_color_ ?
srgbToLinearCpu(glm::vec3{light.color})
1909 : glm::vec3{light.color};
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);
1926 if (followsSun && !sunCast) {
1927 light_cap_.refused.push_back({entity,
static_cast<u8>(type), light.intensity,
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;
1941 gpu.color = glm::vec4(followsSun ? sky->sunColor * skyScale * rgb : rgb, light.intensity);
1944 gpu.shadow = glm::vec4(std::max(light.shadowSoftness, 0.0f),
1945 std::max(light.shadowDistance, 0.0f), 0.0f, 0.0f);
1951 gpu.falloff = glm::vec4(std::max(light.innerRadius, 0.0f),
1952 light.inverseSquare ? -world_units_per_meter_ : std::max(light.falloff, 0.0f),
1954 std::clamp(light.shadowStrength, 0.0f, 1.0f), -1.0f);
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);
1967 gpu.shadowMap.z = std::tan(glm::radians(
1968 std::clamp(light.sourceAngle, 0.0f, 179.0f) * 0.5f));
1971 if (light.meshShadows && !haveSun) {
1973 castsMeshShadow =
true;
1976 caster.extent = std::max(light.shadowExtent, 0.0f);
1979 auto* transform = registry.tryGet<ecs::Transform>(entity);
1980 if (!transform)
continue;
1981 transform->ensureDecomposed();
1982 const glm::vec3 p =
rebased(transform->worldPosition);
1984 gpu.posDir = glm::vec4(p.x, p.y, typeId, light.radius);
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;
2005 if (light.meshShadows) {
2006 castsMeshShadow =
true;
2010 caster.range = std::max(light.radius, 0.0f);
2011 caster.outerAngle = light.outerAngle;
2014 collected.push_back({gpu, castsMeshShadow, caster});
2017 const QualityValues& quality = context_.qualityValues();
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);
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;
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);
2040 light_cap_.refused.push_back({rest.caster.light,
static_cast<u8>(rest.gpu.posDir.z),
2043 ES_LOG_WARN(
"collectLights: light {} is not in this frame ({}); {} kept of {}, brightest first",
2045 loopLimit + tiled.size(), collected.size());
2048 collected.resize(loopLimit);
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;
2055 shadow_casters_.push_back(caster);
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);
2066 lights.addLight(collected[slot].gpu);
2068 for (
const CollectedLight& light : tiled) {
2069 lights.addTiledLight(light.gpu, view_projection_);
2072 lights.markLoopLights(view_projection_);
2076 collectShadow2D(registry);
2077 collectShape2D(registry);
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);
2092void RenderFrame::collectStudioLights(ecs::Registry& registry) {
2093 LightStore& lights = context_.
lights();
2094 const ViewLighting& view = view_lighting_;
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;
2103 if (!light.environment.isValid())
continue;
2104 const Environment* environment = resource_manager_.getEnvironment(light.environment);
2105 if (!environment)
continue;
2107 if (environment->hasSpecular()) {
2108 if (Texture* atlas = resource_manager_.getTexture(environment->specular)) {
2109 textureId = atlas->getId();
2113 if (environment->sky.isValid()) {
2114 if (Texture* sky = resource_manager_.getTexture(environment->sky)) panorama = sky->getId();
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;
2125 std::array<glm::vec3, 9> sh;
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);
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);
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;
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;
2146 rig(-35.0f, 40.0f, view.keyIntensity);
2147 rig(145.0f, 15.0f, view.fillIntensity);
2148 light_cap_.requested = light_cap_.accepted;
2152 collectShadow2D(registry);
2153 collectShape2D(registry);
2157 return light.environment.isValid() ? light.environment : sky_environment_;
2160bool RenderFrame::collectEnvironment(
const ecs::Light& light,
const glm::vec3& scale,
2163 if (!handle.isValid())
return false;
2164 const Environment* environment = resource_manager_.getEnvironment(handle);
2165 if (!environment)
return false;
2168 if (environment->hasSpecular()) {
2169 if (Texture* atlas = resource_manager_.getTexture(environment->specular)) {
2170 textureId = atlas->getId();
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;
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;
2185 if (!context_.lights().setEnvironment(irradiance.data(), params, scale,
2186 glm::radians(light.environmentRotation))) {
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();
2196 draw_sky_ = light.drawEnvironment && (textureId != 0 || sky_texture_id_ != 0);
2200RenderFrame::ShadowBounds RenderFrame::gatherShadowBounds(
ecs::Registry& registry,
bool includeHair) {
2201 auto meshes = registry.activeView<ecs::Transform, ecs::MeshRenderer>();
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;
2216 const auto* group = registry.tryGet<ecs::LODGroup>(entity);
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);
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);
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;
2239 include(centre, half);
2242 glm::vec3 centre, half;
2243 orientedWorldAabb(position, transform.worldRotation, transform.worldScale, lo, hi, centre, half);
2244 include(centre, half);
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;
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);
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);
2285 proj[2][2] = farDist / (nearDist - farDist);
2287 proj[3][2] = (nearDist * farDist) / (nearDist - farDist);
2293 return std::abs(dir.z) > 0.99f ? glm::vec3(0.0f, 1.0f, 0.0f) : glm::vec3(0.0f, 0.0f, 1.0f);
2303static glm::mat4
coneShadow(
const glm::vec3& pos,
const glm::vec3& dir,
f32 fovDegrees,
2308 const f32 farPlane = std::max(reach, 1e-3f);
2309 const f32 nearPlane = std::max(farPlane * 0.005f, 1e-3f);
2311 * glm::lookAt(pos, pos + dir,
shadowUp(dir));
2318 glm::vec3 dir(0.0f);
2319 dir[
static_cast<i32>(index / 2)] = (index % 2 == 0) ? 1.0f : -1.0f;
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);
2331 if (shadow_atlas_size_ == atlasSize && shadow_cell_size_ == cellSize)
return;
2332 shadow_atlas_size_ = atlasSize;
2333 shadow_cell_size_ = cellSize;
2338 shadow_distance_ = std::isfinite(distance) ? std::max(distance, 0.0f) : 0.0f;
2342 lighting_direct_ = on;
2343 context_.materials().setLightingDirect(on);
2351 return context_.qualityValues().set(name, value);
2355 shadow_2d_soft_samples_ = std::clamp(samples, 1u, 32u);
2359 shadow_texture_id_ = 0;
2361 shadow_views_.clear();
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_;
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_);
2385 if (shadow_casters_.empty() && cloudExtent <= 0.0f)
return;
2387 const glm::mat4 invVP = glm::inverse(view_projection_);
2391 const glm::vec4 eye = invVP * glm::vec4(0.0f, 0.0f, 1.0f, 0.0f);
2394 glm::vec3 corners[8];
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;
2402 const auto& castersMin = sceneBounds.casters.min;
2403 const auto& castersMax = sceneBounds.casters.max;
2404 const bool haveCasters = sceneBounds.casters.valid;
2408 const auto& hairMin = sceneBounds.hair.min;
2409 const auto& hairMax = sceneBounds.hair.max;
2410 const bool haveHair = sceneBounds.hair.valid;
2412 f32 nearDist = 0.0f, farDist = 1.0f;
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);
2419 nearDist = std::max(nearDist, 1e-3f);
2420 farDist = std::max(farDist, nearDist * 1.001f);
2425 f32 reach = shadow_distance_ > 0.0f ? shadow_distance_ : farDist;
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));
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);
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;
2442 farDist = limitedFar;
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];
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);
2465 if (cloudExtent > 0.0f) {
2468 for (
usize i = 0; i < shadow_casters_.size(); ++i) {
2469 const ShadowCaster& caster = shadow_casters_[i];
2473 const bool focus = haveHair && caster.extent <= 0.0f;
2474 const u32 want = (
perspective && caster.extent <= 0.0f) ? shadow_cascades_ + (focus ? 1u : 0u) : 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);
2481 for (
const ShadowGrant& g : shadow_plan_.grants) {
2482 shadow_plan_.requestedTiles += g.requested;
2483 shadow_plan_.grantedTiles += g.granted;
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));
2495 const u32 atlasSize = shadow_atlas_.occupiedSize();
2498 bool anyTile =
false;
2499 if (cloud_tile_ >= 0) {
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_));
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;
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);
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);
2546 cube ? 90.0f : caster.outerAngle, caster.range);
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);
2556 if (!perspective || caster.extent > 0.0f) {
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) {
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));
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);
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;
2591 for (
const glm::vec3& p : slice) centre += p;
2593 for (
const glm::vec3& p : slice) {
2594 radius = std::max(radius, glm::length(p - centre));
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));
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));
2618 const glm::mat4 lightView = glm::lookAt(centre + toLight * castDistance,
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;
2632 matrices[tileIndex] = projection;
2636 tiles[tileIndex] = shadow_atlas_.unitRect(tileIndex, atlasSize);
2637 tiles[tileIndex].w =
packShadowBias(caster.bias, caster.slopeFloor);
2642 Frustum tileFrustum;
2643 tileFrustum.extractFromMatrix(projection);
2644 if (haveBounds && !tileFrustum.intersectsAABB((boundsMin + boundsMax) * 0.5f,
2645 (boundsMax - boundsMin) * 0.5f)) {
2649 ShadowView view{projection, tile.x, tile.y, tile.size};
2653 if (caster.shape ==
ShadowShape::Box && haveBounds && planar_captures_.empty() && glm::length(caster.dir) > 1e-6f) {
2655 view.ray = glm::normalize(caster.dir);
2656 view.floorY = boundsMin.y;
2657 view.reachCap = glm::length(boundsMax - boundsMin);
2659 shadow_views_.push_back(view);
2666 if (plannedTiles == 0) {
2679 if (!anyTile)
return;
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;
2691 shadow_drawn_valid_ =
false;
2692 shadow_tiles_known_ =
false;
2694 if (!shadow_target_) {
2695 shadow_views_.clear();
2698 shadow_resource_ = graph_.importTarget(shadow_target_->handle(), atlasSize, atlasSize,
false,
2699 shadow_target_->getColorAttachment());
2701 shadow_views_.clear();
2705 shadow_texture_id_ =
static_cast<u32>(graph_.textureOf(shadow_resource_));
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));
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);
2719void RenderFrame::declareShadowPass(
ecs::Registry& registry) {
2722 shadow_target_.reset();
2723 shadow_drawn_valid_ =
false;
2724 shadow_held_valid_ =
false;
2725 shadow_lists_valid_ =
false;
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();
2735 shadow_reused_ =
true;
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");
2748 if (shadow_reused_) {
2750 shadow_drawn_inputs_ = inputs;
2751 shadow_drawn_inputs_valid_ = vouched;
2753 shadow_pending_key_ = key;
2754 shadow_pending_trusted_ = trusted;
2755 shadow_pending_inputs_ = inputs;
2756 shadow_pending_inputs_valid_ = vouched;
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));
2766 if (shadow_reused_) {
2776 shadow_drawn_valid_ =
false;
2779 shadow_frame_tiles_ = shadow_frame_draws_ = 0;
2780 shadow_tile_passes_left_ = 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;
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;
2801 const auto square = [](rg::PassDesc& pass) {
2810 rg::PassDesc shadow;
2811 shadow.name =
"shadow-atlas";
2812 shadow.write = shadow_resource_;
2814 shadow.execute = [
this](
const rg::PassContext&) { executeShadowPass(); };
2815 graph_.addPass(std::move(shadow));
2816 }
else if (kept == viewCount) {
2818 recordShadowTiles(
false);
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];
2825 tile.name =
"shadow-square";
2826 tile.write = shadow_resource_;
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));
2841 if (shadow_tile_passes_left_ > 0) {
2842 shadow_squares_kept_total_ += kept;
2843 shadow_squares_drawn_total_ += shadow_tile_passes_left_;
2847#ifdef ES_ENABLE_POSTPROCESS
2848 if (cloud_tile_ < 0 || !post_process_)
return;
2851 cloud.name =
"cloud-shadow";
2852 cloud.write = shadow_resource_;
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));
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;
2870 material_bake_states_[ticket] = -1;
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();
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);
2887 }), material_bakes_.end());
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;
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);
2908void RenderFrame::declareMaterialBakes(
ecs::Registry& registry) {
2909#ifdef ES_ENABLE_POSTPROCESS
2911 if (material_bakes_.empty() || material_bakes_frame_ == planar_frame_ || !post_process_)
return;
2912 material_bakes_frame_ = planar_frame_;
2913 std::vector<MaterialBake> waiting;
2915 usize captureIndex = 0;
2916 for (
const MaterialBake& bake : material_bakes_) {
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;
2927 waiting.push_back(bake);
2932 WaterSunField field;
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;
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};
2949 pass.name =
"material-bake";
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_;
2964 const auto source = pass.write;
2965 graph_.addPass(std::move(pass));
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);
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{};
2986 graph_.addPass(std::move(projection));
2989 material_bakes_ = std::move(waiting);
2995void RenderFrame::ensureShadowFrameUbos(
u32 count) {
2997 while (shadow_frame_ubos_.size() < count) {
3001 shadow_frame_ubos_.push_back(ubo);
3005void RenderFrame::releaseShadowFrameUbos() {
3009 shadow_frame_ubos_.clear();
3012bool RenderFrame::shadowInputs(
ecs::Registry& registry,
u64& key,
u64& heldKey,
bool& heldVouched) {
3016 const auto words = [&h, &held](
const void* data,
usize bytes) {
3020 bool vouched =
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;
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);
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));
3045 words(&view_projection_,
sizeof(glm::mat4));
3046 mix(shadow_receiver_cull_ ? 1u : 0u);
3050 heldVouched = heldVouched && vouched;
3055 std::vector<DrawList>& lists,
u32& culled) {
3056 const usize viewCount = shadow_views_.size();
3058 if (lists.size() < viewCount) lists.resize(viewCount);
3060 for (
usize vi = 0; vi < viewCount; ++vi) {
3061 const ShadowView& view = shadow_views_[vi];
3062 DrawList& list = lists[vi];
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,
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;
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);
3085 culled += collectCtx.shadowCulled;
3086 list.finalize(pool);
3090u32 RenderFrame::shadowViewDraws(
usize vi)
const {
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();
3097bool RenderFrame::collectShadowViews(
ecs::Registry& registry,
u64 inputs,
bool vouched,
u64 heldInputs,
bool heldVouched,
3099 const usize viewCount = shadow_views_.size();
3100 ensureShadowFrameUbos(
static_cast<u32>(viewCount));
3103 mix(device_.deviceGeneration());
3104 mix(device_.geometryWrites());
3105 mix(
static_cast<u64>(shadow_target_ ?
static_cast<u32>(shadow_target_->handle()) : 0u));
3108 for (
const ShadowView& view : shadow_views_) {
3109 mix((
static_cast<u64>(view.x) << 32) | view.y);
3112 mix(
static_cast<u64>(
static_cast<i64>(cloud_tile_)));
3113 mix(shadow_target_ ? shadow_target_->getWidth() : 0u);
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_;
3121 key = shadow_lists_key_;
3122 return shadow_lists_trusted_;
3124 const bool heldStands = heldVouched && sized && shadow_held_valid_ && heldInputs == shadow_held_inputs_;
3125 u32 moverCulled = 0;
3126 if (heldStands && !audit) {
3129 const std::vector<u64> wasHashes = heldStands ? shadow_held_hash_ : std::vector<u64>{};
3131 shadow_held_culled_);
3132 shadow_held_uploaded_ =
false;
3133 ++shadow_held_builds_;
3135 bool poolTrusted =
true;
3137 if (shadow_pool_.indicesUsed(
static_cast<LayoutId>(layout)) > 0) poolTrusted =
false;
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;
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");
3154 shadow_held_inputs_ = heldInputs;
3155 shadow_held_valid_ = heldVouched;
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_;
3162 shadow_mover_pool_.beginFrame();
3163 for (
usize vi = 0; vi < viewCount; ++vi) shadow_mover_lists_[vi].clear();
3165 shadow_pool_uploaded_ =
false;
3166 shadow_casters_culled_ = shadow_held_culled_ + moverCulled;
3170 bool moverPoolTrusted =
true;
3172 if (shadow_mover_pool_.indicesUsed(
static_cast<LayoutId>(layout)) > 0) moverPoolTrusted =
false;
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) {
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);
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());
3201 shadow_view_keys_[vi] = v;
3202 shadow_view_trusted_[vi] = viewTrusted ? 1 : 0;
3203 trusted = trusted && viewTrusted;
3207 shadow_lists_inputs_ = inputs;
3208 shadow_lists_valid_ = vouched && !audit;
3209 shadow_lists_key_ = key;
3210 shadow_lists_trusted_ = trusted;
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;
3225 if (anyMovers && !shadow_pool_uploaded_) {
3226 shadow_mover_pool_.upload();
3227 shadow_pool_uploaded_ =
true;
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();
3233 held.execute(device_, shadow_pool_, context_.materials(), context_.getWhiteTextureId(),
nullptr, context_.perDrawBlocks());
3236 movers->execute(device_, shadow_mover_pool_, context_.materials(), context_.getWhiteTextureId(),
nullptr,
3237 context_.perDrawBlocks());
3239 ++shadow_frame_tiles_;
3240 shadow_frame_draws_ += shadowViewDraws(vi);
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);
3250 bool allDrawn =
true;
3251 for (
usize vi = 0; vi < viewCount; ++vi) {
3252 if (!all && !shadow_view_redraw_[vi])
continue;
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);
3260 shadow_tile_layout_ = shadow_layout_;
3261 shadow_tiles_known_ =
true;
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];
3272 shadow_held_tiles_ = heldTiles;
3273 shadow_held_draws_ = heldDraws;
3279 ES_PROFILE_COUNTER(
"render.shadow.cullViews", [&] {
u32 n = 0;
for (
const ShadowView& v : shadow_views_) n += v.sun ? 1u : 0u;
return n; }());
3282void RenderFrame::executeShadowTile(
usize vi) {
3285 if (shadow_tile_passes_left_ > 0 && --shadow_tile_passes_left_ == 0) recordShadowTiles(
false);
3286 device_.invalidatePipelineCache();
3289void RenderFrame::executeShadowPass() {
3292 for (
usize vi = 0; vi < shadow_views_.size(); ++vi) drawShadowView(vi);
3293 recordShadowTiles(
true);
3295 device_.invalidatePipelineCache();
3305 if (!draw_sky_)
return;
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];
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");
3323 {}, resource_manager_.preferredShaderLanguage(), resource_manager_.deferLinks());
3324 if (
auto* shader = resource_manager_.getShader(handle)) {
3329 s.setUniform(
"u_texture", 0);
3334 if (program == 0)
return;
3336 if (device_.skipPendingPrograms() && !device_.programReady(
ShaderHandle{program}))
return;
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;
3351 key.layer = std::numeric_limits<i32>::min();
3352 key.shaderId = program;
3357 key.textureId = panorama ? sky_texture_id_ :
ctx.frame_context.white_texture_id;
3358 key.envTextureId = environment_texture_id_;
3362 key.depthTest =
false;
3363 key.depthWrite =
false;
3366#ifdef ES_ENABLE_POSTPROCESS
3367 if (post_process_) post_process_->setBackgroundSky(
true);
3372 const glm::vec3& halfExtents)
const {
3374 return frustum_.intersectsAABB(center, halfExtents);
3379 auto ctx = makeContext();
3383 const bool shadowPasses = !shadow_casters_.empty();
3385 for (
auto& plugin : plugins_) {
3386 out += plugin->prewarm(
ctx, registry, entities, count, shadowPasses);
3392 auto ctx = makeContext();
3393 const bool shadowPasses = !shadow_casters_.empty();
3395 for (
auto& plugin : plugins_) out += plugin->prewarmDocument(
ctx, rows, count, shadowPasses);
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_);
3406 if (!skin_cache_->hasWork())
return;
3416 pass.
name =
"skin-cache";
3421 graph_.
addPass(std::move(pass));
3430 {
ES_PROFILE_SCOPE(
"render.collect.sorting"); buildSortingGroups(registry); buildTreeSequence(registry); }
3432 {
ES_PROFILE_SCOPE(
"render.collect.spriteMasks"); buildSpriteMasks(registry); }
3439 {
ES_PROFILE_SCOPE(
"render.collect.reflections"); collectReflections(registry); }
3442 const ShadingMode viewMode = view_shading_.get(view_id_);
3448 {
ES_PROFILE_SCOPE(
"render.collect.occluders"); collectOccluders(registry); }
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); }
3462 auto ctx = makeContext();
3463#ifdef ES_ENABLE_POSTPROCESS
3466 ctx.gbuffer = sceneGBuffer && post_process_ && post_process_->sceneHasGBuffer();
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_;
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_);
3493 for (
auto& plugin : plugins_) {
3495 plugin->collect(collectCtx);
3498 if (retained_text_collected_) {
3500 const glm::mat4 world = view_projection_ * glm::translate(glm::mat4(1.0f), -glm::vec3(
renderOrigin()));
3507 stats_.culled += collectCtx.
culled;
3508 stats_.occluded += collectCtx.
occluded;
3511 velocity_list_.clear();
3512 selection_list_.clear();
3513 cover_wanted_ =
false;
3514#ifdef ES_ENABLE_POSTPROCESS
3515 if (followMotion) collectMotion(registry);
3517 if (view_selection_.count(view_id_) && device_.supportsFloatTargets()) collectSelection(registry);
3518 if (sceneGBuffer && post_process_ && post_process_->isEngaged() && post_process_->coverWanted()) collectCover(registry);
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());
3529void RenderFrame::collectSelection(
ecs::Registry& registry) {
3531#ifdef ES_ENABLE_POSTPROCESS
3533 auto ctx = makeContext();
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);
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);
3549 selection_list_.finalize(selection_pool_);
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;
3564 spec.depthStencil =
true;
3565 spec.linearFilter =
false;
3569 const rg::ResourceId mask = graph_.importTarget(selection_fbo_->handle(), w, h,
false,
3570 selection_fbo_->getColorAttachment());
3572 pass.
name =
"selection-mask";
3575 pass.dependencies = {scene_resource_};
3578 pass.clearDepth =
true;
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));
3587void RenderFrame::executeSelectionPass() {
3588 if (selection_list_.commandCount() == 0)
return;
3590#ifdef ES_ENABLE_POSTPROCESS
3594 if (post_process_) post_process_->drawSelectionGround(graph_.depthTextureOf(scene_resource_));
3596 selection_pool_.upload();
3597 context_.updateCameraConstants(view_projection_, glm::vec2(0.0f));
3599 context_.lights().uploadAndBind();
3600 selection_list_.execute(device_, selection_pool_, context_.materials(), context_.getWhiteTextureId(),
3601 nullptr, context_.perDrawBlocks());
3602 device_.invalidatePipelineCache();
3607#ifdef ES_ENABLE_POSTPROCESS
3608 const auto view = post_process_->peekTemporalView(view_projection_,
static_cast<u64>(current_target_));
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();
3615 auto ctx = makeContext();
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,
3625 collectCtx.ui_tree_layers = ui_tree_layers_;
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);
3632 velocity_list_.finalize(velocity_pool_);
3638bool RenderFrame::coverInputs(
ecs::Registry& registry,
u64& key,
u64& heldKey,
bool& heldVouched) {
3642 bool vouched =
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;
3655 mix(device_.deviceGeneration());
3656 mix(device_.geometryWrites());
3662 heldVouched = heldVouched && vouched;
3668#ifdef ES_ENABLE_POSTPROCESS
3669 cover_wanted_ =
true;
3670 const f32 range = post_process_->coverRange();
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;
3682 cover_view_projection_ = proj * view;
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_) {
3694 frustum.extractFromMatrix(cover_view_projection_);
3695 const auto collectInto = [&](
CasterSplit split, TransientBufferPool& pool, DrawList& list) {
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,
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);
3710 list.finalize(pool);
3713 const bool heldStands = heldVouched && cover_held_valid_ && heldInputs == cover_held_inputs_;
3714 if (heldStands && !audit) {
3718 cover_held_uploaded_ =
false;
3721 bool trusted =
true;
3723 if (cover_pool_.indicesUsed(
static_cast<LayoutId>(layout)) > 0) trusted =
false;
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;
3730 if (cover_held_valid_) {
3732 ++cover_mover_collects_;
3734 cover_mover_pool_.beginFrame();
3735 cover_mover_list_.clear();
3737 cover_movers_uploaded_ =
false;
3743 bool trusted = cover_held_trusted_;
3745 if (cover_mover_pool_.indicesUsed(
static_cast<LayoutId>(layout)) > 0) trusted =
false;
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)) {
3756 for (
const auto& binding : m->textures) h =
hash::combine(h, binding.texture.id());
3761 cover_trusted_ = trusted;
3762 cover_lists_inputs_ = inputs;
3763 cover_lists_valid_ = vouched && !audit;
3769void RenderFrame::executeCoverPass() {
3770 if (coverCommandCount() == 0)
return;
3772 if (cover_list_.commandCount() > 0 && !cover_held_uploaded_) {
3773 cover_pool_.upload();
3774 cover_held_uploaded_ =
true;
3776 if (cover_mover_list_.commandCount() > 0 && !cover_movers_uploaded_) {
3777 cover_mover_pool_.upload();
3778 cover_movers_uploaded_ =
true;
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());
3792 if (cover_mover_list_.commandCount() > 0) {
3793 cover_mover_list_.execute(device_, cover_mover_pool_, context_.materials(), context_.getWhiteTextureId(),
nullptr,
3794 context_.perDrawBlocks());
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;
3803 context_.updateCameraConstants(view_projection_, scene_jitter_);
3804 device_.invalidatePipelineCache();
3807void RenderFrame::executeMotionPass() {
3808 if (velocity_list_.commandCount() == 0)
return;
3810 velocity_pool_.upload();
3813 context_.updateCameraConstants(view_projection_, velocity_jitter_);
3815 context_.lights().uploadAndBind();
3816 velocity_list_.execute(device_, velocity_pool_, context_.materials(), context_.getWhiteTextureId(),
3817 nullptr, context_.perDrawBlocks());
3819 device_.invalidatePipelineCache();
3823 auto conv = [](
f32 v) {
3824 return v <= 0.04045f ? v / 12.92f : std::pow((v + 0.055f) / 1.055f, 2.4f);
3826 return {conv(c.r), conv(c.g), conv(c.b)};
3830 linear_color_ = linear;
3832#ifdef ES_ENABLE_POSTPROCESS
3833 if (post_process_) post_process_->setLinearOutput(linear);
3837u32 RenderFrame::initBatchShader() {
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"};
3864 auto it = batch_variants_.find(key);
3865 if (it == batch_variants_.end()) {
3866 it = batch_variants_.emplace(key, compileBatchVariant(features)).first;
3873 if (!handle) handle = &batchVariantHandle(batchVariantFeatures(variant));
3874 Shader* shader = resource_manager_.getShader(*handle);
3879 Shader* shader = resource_manager_.getShader(batchVariantHandle(features));
3884 static const std::string kDisplay =
"DISPLAY_OUTPUT";
3885 std::vector<std::string> features;
3887 for (
const auto& [key, handle] : batch_variants_) {
3888 Shader* shader = resource_manager_.getShader(handle);
3889 if (!shader || shader->
getProgramId() != program)
continue;
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));
3900 if (!found || std::find(features.begin(), features.end(), kDisplay) != features.end())
return program;
3901 features.push_back(kDisplay);
3911 const auto target = resource_manager_.preferredShaderTarget();
3915 if (std::find(features.begin(), features.end(),
"LIT") != features.end()) {
3916 parsed.domain =
"Lit";
3921 {{0,
"a_position"}, {1,
"a_color"}, {2,
"a_texCoord"}},
3922 resource_manager_.preferredShaderLanguage(), resource_manager_.deferLinks());
3924 Shader* shader = resource_manager_.getShader(handle);
3925 if (shader && shader->isValid()) {
3931 for (
i32 i = 0; i < 8; ++i) {
3932 const std::string name =
"u_textures[" + std::to_string(i) +
"]";
3933 s.setUniform(name, i);
3941 ES_LOG_ERROR(
"Failed to create batch shader variant '{}'", vk.empty() ?
"default" : vk.c_str());
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.
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.
#define ES_LOG_ERROR(...)
Logs an error message.
#define ES_LOG_INFO(...)
Logs an info message.
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
void setUIStencilMask(u32 entity, i32 depth)
void setUIStencilTest(u32 entity, i32 depth)
void setScissor(u32 entity, i32 x, i32 y, i32 w, i32 h)
u32 mergedDrawCallCount() const
static u32 layerBit(i32 layer)
The mask bit of a sorting layer, or 0 when it has none (outside 0..31).
u32 mergedAwayCount() const
u32 breakCount(BatchBreak reason) const
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.
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 ¶ms)
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 ®istry, 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)
void clearAllStencilMasks()
u32 skeletalPreviewHeight(SkeletalPreviewId id) const
i32 pollSnapshotReadback()
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 ®istry, bool screen, const f32 *projection, u32 onlyRoot=0)
Every retained label laid out for one domain into the open list, culled against projection (world,...
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 ®istry, 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)
i32 pollPreviewReadback()
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 ®istry, 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 ¢er, 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.
u32 getProgramId() const
Gets the program handle's raw value, for command payloads and sort keys.
GfxShaderLanguage language() const
The source language this program was compiled from.
void whenLinked(std::function< void(Shader &)> fn)
Runs fn on this shader once it has linked: at once for one that has.
ShaderHandle handle() const
Gets the device program handle.
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.
Central container for all entities and components.
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 bool linearColorSpace()
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.
u32 framesDisjoint() const
u32 framesDropped() const
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 * SKY
constexpr const char * BATCH
@ VisibleOutside
Drawn only where the mask is NOT — a hole.
LightType
2D light kind. Point uses the Transform position + radius falloff; Directional uses the Transform's f...
constexpr u64 combine(u64 h, u64 v)
constexpr u64 kFnv64Offset
u64 combineWords(u64 h, const void *data, usize bytes)
glm::mat4 perspective(float fov, float aspect, float nearPlane, float farPlane)
Creates a perspective projection matrix.
void transformedBox(const glm::mat3 &parent, const f32 *rows, const glm::vec3 &origin, const glm::vec3 &localCentre, const glm::vec3 &localHalf, glm::vec3 ¢re, glm::vec3 &half)
f32 radius(const glm::vec3 &lo, const glm::vec3 &hi, f32 displacement)
Handle< esengine::Shader > ShaderHandle
Handle to a shader resource.
Handle< esengine::Environment > EnvironmentHandle
Handle to a baked environment (irradiance + prefiltered reflection).
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.
std::int32_t i32
Signed 32-bit integer.
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.
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.
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.
constexpr u32 WATER_SUN_TEXTURE_UNIT
@ Capacity
More lights in view than the shader's arrays hold; the dimmest gave way.
@ NoEnvironmentSun
Follows the environment's sun, and the frame's environment has none.
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.
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
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.
const char * lightRefusalName(LightRefusal why)
The refusal as a word, for a log line and for a reader.
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.
std::int64_t i64
Signed 64-bit integer.
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.
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...
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).
float f32
32-bit floating point
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.
Entity identifier with packed index + generation.
void extractFromMatrix(const glm::mat4 &vp)
bool intersectsAABB(const glm::vec3 ¢er, const glm::vec3 &halfExtents) const
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
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.
std::vector< u16 > indices
std::vector< f32 > vertices
One render pass: a target, which attachments to clear on entry, and the clear values — full load-op s...
u32 clearH
Clear region size; 0 = the whole target.
i32 clearY
Clear region origin (pixels).
What readying a set of renderables' programs found. Counts, not JSON: this crosses no boundary and pa...
std::vector< Entity > entities
List of child entity IDs.
A 2D light contributing to Lit-shaded materials.
Parent reference component.
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.
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.