Estella 0.113.0
A fast 2D and 3D game engine powered by WebAssembly and ECS
Loading...
Searching...
No Matches
RenderFrameShadow2D.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
11#include "./RenderFrame.hpp"
12#include "../../core/Log.hpp"
21
22#include <algorithm>
23#include <cmath>
24
25namespace esengine {
26
27namespace {
28
31constexpr u32 kShadow2DFloats = 7;
32
35constexpr u32 kShape2DFloats = 8;
36
37
41constexpr f32 kShadow2DOvershoot = 1.25f;
42
43} // namespace
44
45void RenderFrame::collectShadow2D(ecs::Registry& registry) {
46 shadow_points_2d_.clear();
47 shadow_rings_2d_.clear();
48 shadow_2d_lights_.clear();
49 shadow_2d_unplaced_ = 0;
50 for (Shadow2DMask& mask : shadow_2d_masks_) {
51 mask.resource = rg::kNoResource;
52 mask.textureId = 0;
53 }
54 context_.lights().setMask2DRect(glm::vec4(0.0f));
55
56 auto casters = registry.activeView<ecs::Transform, ecs::ShadowCaster2D>();
57 for (auto entity : casters) {
58 const auto& caster = casters.get<ecs::ShadowCaster2D>(entity);
59 if (!caster.enabled) continue;
60 auto& transform = casters.get<ecs::Transform>(entity);
61 transform.ensureDecomposed();
62 const glm::vec3 p = rebased(transform.worldPosition);
63 // The shape turns with the entity, the way a collider on it does — a wall laid
64 // at an angle casts the shadow of a wall at that angle. Its SIZE is its own,
65 // also like a collider's: scaling the entity does not resize the occluder.
66 const glm::vec2 turn = flatTurnZ(transform.worldRotation);
67 const auto place = [&](f32 lx, f32 ly) {
68 return glm::vec2{p.x + lx * turn.x - ly * turn.y, p.y + lx * turn.y + ly * turn.x};
69 };
70 // An outline of its own, or the box. Two points enclose nothing, so a path
71 // short of a triangle is not a shape and the box stands.
72 if (caster.path.size() >= 3) {
73 shadow_rings_2d_.push_back({static_cast<u32>(shadow_points_2d_.size()),
74 static_cast<u32>(caster.path.size())});
75 for (const glm::vec2& local : caster.path) {
76 shadow_points_2d_.push_back(place(local.x, local.y));
77 }
78 continue;
79 }
80 const f32 hx = caster.size.x * 0.5f;
81 const f32 hy = caster.size.y * 0.5f;
82 if (hx <= 0.0f || hy <= 0.0f) continue;
83 shadow_rings_2d_.push_back({static_cast<u32>(shadow_points_2d_.size()), 4});
84 shadow_points_2d_.push_back(place(-hx, -hy));
85 shadow_points_2d_.push_back(place(hx, -hy));
86 shadow_points_2d_.push_back(place(hx, hy));
87 shadow_points_2d_.push_back(place(-hx, hy));
88 }
89 if (shadow_rings_2d_.empty()) return;
90
91 for (ShadowRing2D& ring : shadow_rings_2d_) {
92 const glm::vec2* pts = shadow_points_2d_.data() + ring.first;
93 glm::vec2 centre{0.0f};
94 for (u32 i = 0; i < ring.count; ++i) centre += pts[i];
95 centre /= static_cast<f32>(ring.count);
96 f32 radius = 0.0f;
97 for (u32 i = 0; i < ring.count; ++i) radius = std::max(radius, glm::distance(pts[i], centre));
98 ring.centre = centre;
99 ring.radius = radius;
100 }
101
102 // The lights that cast. The collect already ordered the light array by what the cap sorted on, so taking them in slot order takes the
103 // brightest first, the loop's sixteen and then the tiled list; the mask's channels are shared by lights that cannot meet (see
104 // ShadowChannels2D.hpp). A second mask doubles them, and takes the shape mask's texture unit: a frame with a cookie keeps the first four.
105 const LightConstants& lights = context_.lights().data();
106 std::vector<ShadowMaskLight> masks;
107 const auto consider = [&](const GpuLight& light, u32 slot, bool tiled) {
108 if (light.color.a <= 0.0f) return;
109 const f32 type = light.posDir.z;
110 Shadow2DLight entry;
111 entry.slot = slot;
112 entry.tiled = tiled;
113 entry.softness = light.shadow.x;
114 if (type < 0.5f || type > 1.5f) {
115 entry.pos = glm::vec2(light.posDir.x, light.posDir.y);
116 entry.reach = light.posDir.w;
117 } else {
118 // A sun: its rays are parallel, so what a shadow needs is the direction they
119 // travel and how far the author let one march. Zero distance is a sun that
120 // casts none, which is the default.
121 const glm::vec2 aim(light.posDir.x, light.posDir.y);
122 if (light.shadow.y <= 0.0f || glm::dot(aim, aim) < 1e-8f) return;
123 entry.directional = true;
124 entry.dir = glm::normalize(aim);
125 entry.reach = light.shadow.y;
126 }
127 if (entry.reach <= 0.0f) return;
128
129 ShadowMaskLight mask;
130 mask.pos = entry.pos;
131 if (entry.directional) {
132 mask.everywhere = true;
133 } else {
134 // Where its geometry can land: the furthest of the occluders it sees, plus how far a shadow is carried past them. A light
135 // that sees none draws nothing and has no shadow to read, so it takes no channel.
136 f32 furthest = -1.0f;
137 for (const ShadowRing2D& ring : shadow_rings_2d_) {
138 const f32 d = glm::distance(ring.centre, entry.pos);
139 if (d > entry.reach + entry.softness + ring.radius) continue;
140 furthest = std::max(furthest, d + ring.radius + entry.softness);
141 }
142 if (furthest < 0.0f) return;
143 mask.read = entry.reach;
144 mask.write = furthest + entry.reach * kShadow2DOvershoot;
145 }
146 shadow_2d_lights_.push_back(entry);
147 masks.push_back(mask);
148 };
149 for (u32 slot = 0; slot < context_.lights().count(); ++slot) consider(lights.lights[slot], slot, false);
150 for (u32 index = 0; index < context_.lights().tiledCount(); ++index) consider(lights.tiledLights[index], index, true);
151 if (shadow_2d_lights_.empty()) {
152 shadow_rings_2d_.clear();
153 shadow_points_2d_.clear();
154 return;
155 }
156
157 std::vector<i32> channels(masks.size(), -1);
158 const u32 channelCap = hasShape2DLight(registry) ? SHADOW_2D_MASK_CHANNELS : MAX_SHADOW_2D_LIGHTS;
159 const u32 dropped = assignShadowChannels(masks.data(), static_cast<u32>(masks.size()), channelCap, channels.data());
160 // A light that found no free channel still lights the scene; it only casts no 2D shadow. Kept in order, so what stays is the brightest.
161 usize kept = 0;
162 for (usize i = 0; i < shadow_2d_lights_.size(); ++i) {
163 if (channels[i] < 0) continue;
164 shadow_2d_lights_[kept] = shadow_2d_lights_[i];
165 shadow_2d_lights_[kept].channel = static_cast<u32>(channels[i]);
166 ++kept;
167 }
168 shadow_2d_lights_.resize(kept);
169 shadow_2d_unplaced_ = dropped;
170 if (shadow_2d_lights_.empty()) {
171 shadow_rings_2d_.clear();
172 shadow_points_2d_.clear();
173 return;
174 }
175
176 bool second = false;
177 for (const Shadow2DLight& light : shadow_2d_lights_) {
178 if (light.tiled) context_.lights().setTiledLightShadow2DChannel(light.slot, light.channel);
179 else context_.lights().setLightShadow2DChannel(light.slot, light.channel);
180 if (light.channel >= SHADOW_2D_MASK_CHANNELS) second = true;
181 }
182
183 rg::TargetDesc desc;
184 desc.scale = 1.0f;
185 desc.format = GfxPixelFormat::RGBA8;
186 // Nearest: a fragment reads the texel it was drawn into, and a filtered read would
187 // blend in the neighbouring light's shadow at a silhouette.
188 desc.linearFilter = false;
189 shadow_2d_masks_[0].resource = graph_.createTarget(desc);
190 if (second) shadow_2d_masks_[1].resource = graph_.createTarget(desc);
191}
192
193void RenderFrame::releaseShadow2DResources() {
194 for (Shadow2DMask& mask : shadow_2d_masks_) {
195 if (mask.vbo != BufferHandle::Invalid) device_.deleteBuffer(mask.vbo);
196 mask.vbo = BufferHandle::Invalid;
197 mask.vboBytes = 0;
198 }
199 if (shadow_2d_layout_ != VertexLayoutHandle::Invalid) device_.deleteVertexLayout(shadow_2d_layout_);
200 shadow_2d_layout_ = VertexLayoutHandle::Invalid;
201}
202
203bool RenderFrame::ensureShadow2DShader() {
204 if (shadow_2d_shader_.isValid()) return true;
205 if (shadow_2d_shader_tried_) return false;
206 shadow_2d_shader_tried_ = true;
207
208 auto& resources = resource_manager_;
209 const auto target = resources.preferredShaderTarget();
211 shadow_2d_shader_ = resources.createShader(
214 /*rewriteLoose=*/false, resources.preferredShaderLanguage());
215 if (!shadow_2d_shader_.isValid()) {
216 ES_LOG_ERROR("RenderFrame: no 2D shadow shader; 2D shadows are off this run");
217 return false;
218 }
219
220 VertexLayoutDesc layout;
221 layout.attributeCount = 3;
222 layout.strides[0] = kShadow2DFloats * sizeof(f32);
223 layout.attributes[0] = {0, 2, GfxDataType::Float, false, 0, 0};
224 layout.attributes[1] = {1, 1, GfxDataType::Float, false, 2 * sizeof(f32), 0};
225 layout.attributes[2] = {2, 4, GfxDataType::Float, false, 3 * sizeof(f32), 0};
226 shadow_2d_layout_ = device_.createVertexLayout(layout);
227 return shadow_2d_layout_ != VertexLayoutHandle::Invalid;
228}
229
230namespace {
231
233inline f32 cross2(const glm::vec2& a, const glm::vec2& b) {
234 return a.x * b.y - a.y * b.x;
235}
236
238inline glm::vec2 perpendicularTo(const glm::vec2& v) {
239 const f32 len = std::sqrt(v.x * v.x + v.y * v.y);
240 if (len < 1e-6f) return {1.0f, 0.0f};
241 return {-v.y / len, v.x / len};
242}
243
245inline glm::vec2 extrude(const glm::vec2& p, const glm::vec2& from, f32 reach) {
246 const glm::vec2 d = p - from;
247 const f32 len = std::sqrt(d.x * d.x + d.y * d.y);
248 if (len < 1e-6f) return p;
249 return p + d * (reach * kShadow2DOvershoot / len);
250}
251
252} // namespace
253
254void RenderFrame::buildShadow2DGeometry(u32 maskIndex) {
255 ES_PROFILE_SCOPE("render.shadow2d.geometry");
256 std::vector<f32>& vertices = shadow_2d_masks_[maskIndex].vertices;
257 vertices.clear();
258 // One silhouette is two triangles, and the worst case is every ring seen by every
259 // sample of every light. Reserved once so the frame's growth is not a re-alloc.
260 vertices.reserve(shadow_rings_2d_.size() * shadow_2d_lights_.size()
261 * shadow_2d_soft_samples_ * 6 * kShadow2DFloats);
262
263 auto vertex = [&vertices](const glm::vec2& p, f32 shadow, u32 channel) {
264 vertices.push_back(p.x);
265 vertices.push_back(p.y);
266 vertices.push_back(shadow);
267 for (u32 c = 0; c < 4; ++c) {
268 vertices.push_back(c == channel ? 1.0f : 0.0f);
269 }
270 };
271 auto triangle = [&vertex](const glm::vec2& a, f32 sa, const glm::vec2& b, f32 sb,
272 const glm::vec2& c, f32 sc, u32 channel) {
273 vertex(a, sa, channel);
274 vertex(b, sb, channel);
275 vertex(c, sc, channel);
276 };
277
278 for (const Shadow2DLight& light : shadow_2d_lights_) {
279 // Each mask draws the lights whose channel it carries, as that channel of its own four.
280 if (light.channel / SHADOW_2D_MASK_CHANNELS != maskIndex) continue;
281 const u32 channel = light.channel % SHADOW_2D_MASK_CHANNELS;
282 // A source with width is sampled across, each sample throwing its silhouette at its own share; the shares add, which is the
283 // soft edge. A penumbra made of samples IS banded: sixteen is where the bands stop reading as rays from the corner that threw them.
284 const u32 samples = light.softness > 1e-4f ? shadow_2d_soft_samples_ : 1u;
285 const f32 share = 1.0f / static_cast<f32>(samples);
286 // How far a sample sits from the middle of the source, in -1..1.
287 const auto offsetOf = [samples](u32 s) {
288 if (samples <= 1) return 0.0f;
289 return (static_cast<f32>(s) + 0.5f) / static_cast<f32>(samples) * 2.0f - 1.0f;
290 };
291
292 for (const ShadowRing2D& ring : shadow_rings_2d_) {
293 const glm::vec2* pts = shadow_points_2d_.data() + ring.first;
294 const glm::vec2 centre = ring.centre;
295
296 // Past a light's own reach it contributes nothing, so an occluder out there has no shadow
297 // to draw. The same test bounds where this light's channel is written (collectShadow2D).
298 if (!light.directional
299 && glm::distance(centre, light.pos) > light.reach + light.softness + ring.radius) {
300 continue;
301 }
302
303 for (u32 s = 0; s < samples; ++s) {
304 const f32 t = offsetOf(s);
305 if (light.directional) {
306 // Parallel rays, so a source with width is an ANGLE rather than a
307 // place: the softness is how wide it is where its shadows end, and
308 // what a sample changes is the direction they all travel.
309 const f32 spread = (light.reach > 1e-6f) ? light.softness / light.reach : 0.0f;
310 const f32 angle = t * spread;
311 const glm::vec2 dir{
312 light.dir.x * std::cos(angle) - light.dir.y * std::sin(angle),
313 light.dir.x * std::sin(angle) + light.dir.y * std::cos(angle),
314 };
315 // The silhouette of parallel rays: the two points furthest apart
316 // across the way they travel.
317 const glm::vec2 across = perpendicularTo(dir);
318 u32 lo = 0;
319 u32 hi = 0;
320 for (u32 i = 1; i < ring.count; ++i) {
321 if (glm::dot(pts[i] - pts[lo], across) < 0.0f) lo = i;
322 if (glm::dot(pts[i] - pts[hi], across) > 0.0f) hi = i;
323 }
324 const glm::vec2 reach = dir * (light.reach * kShadow2DOvershoot);
325 triangle(pts[lo], share, pts[hi], share, pts[hi] + reach, share, channel);
326 triangle(pts[lo], share, pts[hi] + reach, share, pts[lo] + reach, share, channel);
327 continue;
328 }
329
330 // The source is a disc, so it is sampled across the diameter square to
331 // what it is lighting — the direction its width actually widens.
332 const glm::vec2 from =
333 light.pos + perpendicularTo(centre - light.pos) * (t * light.softness);
334 // The silhouette from where this sample stands: the two points every
335 // other point of the ring sits between, seen from here. A sample inside
336 // the ring finds none and throws no shadow from it.
337 u32 lo = 0;
338 u32 hi = 0;
339 for (u32 i = 1; i < ring.count; ++i) {
340 if (cross2(pts[lo] - from, pts[i] - from) < 0.0f) lo = i;
341 if (cross2(pts[hi] - from, pts[i] - from) > 0.0f) hi = i;
342 }
343 if (lo == hi) continue;
344 const glm::vec2 farLo = extrude(pts[lo], from, light.reach);
345 const glm::vec2 farHi = extrude(pts[hi], from, light.reach);
346 triangle(pts[lo], share, pts[hi], share, farHi, share, channel);
347 triangle(pts[lo], share, farHi, share, farLo, share, channel);
348 }
349 }
350 }
351}
352
353void RenderFrame::declareShadow2DPass() {
354 for (u32 i = 0; i < 2; ++i) {
355 if (shadow_2d_masks_[i].resource == rg::kNoResource) continue;
356 rg::PassDesc mask;
357 mask.name = i == 0 ? "shadow-2d" : "shadow-2d-b";
358 mask.write = shadow_2d_masks_[i].resource;
359 mask.clear = true;
360 // Zero is "nothing hides this light here" in all four channels, which is what a
361 // frame whose geometry comes back empty has to read as.
362 mask.clearColor[0] = mask.clearColor[1] = mask.clearColor[2] = 0.0f;
363 mask.clearColor[3] = 0.0f;
364 mask.execute = [this, i](const rg::PassContext&) { executeShadow2DPass(i); };
365 graph_.addPass(std::move(mask));
366 }
367}
368
369void RenderFrame::executeShadow2DPass(u32 maskIndex) {
370 Shadow2DMask& mask = shadow_2d_masks_[maskIndex];
371 if (mask.resource == rg::kNoResource) return;
372 if (!ensureShadow2DShader()) return;
373
374 ES_PROFILE_SCOPE("render.shadow2d");
375 // Named before anything can return: a mask with no geometry is still cleared, and a light that holds one of its channels reads it.
376 mask.textureId = static_cast<u32>(graph_.textureOf(mask.resource));
377 buildShadow2DGeometry(maskIndex);
378 // What the mask cost, in the unit it is spent in: a shadow is triangles now, and
379 // neither the count nor the occluders behind it shows in a pixel.
380 ES_PROFILE_COUNTER("render.shadow2d.triangles",
381 static_cast<u32>(mask.vertices.size() / (kShadow2DFloats * 3)));
382 ES_PROFILE_COUNTER("render.shadow2d.occluders", static_cast<u32>(shadow_rings_2d_.size()));
383 ES_PROFILE_COUNTER("render.shadow2d.lights", static_cast<u32>(shadow_2d_lights_.size()));
384 // Casting lights that found every channel held by one they overlap, and so cast no 2D shadow this frame.
385 ES_PROFILE_COUNTER("render.shadow2d.unplaced", shadow_2d_unplaced_);
386 if (mask.vertices.empty()) return;
387
388 // One buffer per mask: the second mask's pass must not find the first's geometry overwritten before it runs.
389 const u32 bytes = static_cast<u32>(mask.vertices.size() * sizeof(f32));
390 if (mask.vbo == BufferHandle::Invalid || bytes > mask.vboBytes) {
391 if (mask.vbo != BufferHandle::Invalid) device_.deleteBuffer(mask.vbo);
392 // Grown in steps rather than to the exact size: the geometry follows how many
393 // lights are moving, and a re-create every frame is a re-create every frame.
394 mask.vboBytes = std::max(bytes * 2u, 4096u);
395 mask.vbo = device_.createBuffer(
396 {GfxBufferUsage::Vertex, mask.vboBytes, /*dynamic=*/true}, GfxContent::transient(), nullptr);
397 if (mask.vbo == BufferHandle::Invalid) return;
398 }
399 device_.updateBuffer(mask.vbo, 0, mask.vertices.data(), bytes);
400
401 Shader* shader = resource_manager_.getShader(shadow_2d_shader_);
402 if (!shader) return;
403
404 PipelineDesc desc{};
405 desc.program = shader->handle();
406 desc.vertexLayout = shadow_2d_layout_;
407 // Adding: one silhouette per sample across the source, each carrying its share, so
408 // what a fragment collects is how much of the source is hidden from it. Two walls
409 // over one pixel add past a whole shadow, and the read clamps.
410 desc.blend = BlendMode::PmaAdditive;
411 desc.blendEnabled = true;
412 desc.depthTest = false;
413 desc.depthWrite = false;
414 device_.setPipeline(device_.createPipeline(desc));
415 // The camera's own rect, as the scene pass will use it: the mask and the frame it
416 // shadows have to land on the same pixels, and opening a pass resets the viewport.
417 device_.setViewport(std::max(scene_viewport_.x, 0), std::max(scene_viewport_.y, 0),
418 static_cast<i32>(scene_viewport_.w), static_cast<i32>(scene_viewport_.h));
419 context_.updateCameraConstants(view_projection_);
420 device_.setVertexBuffer(0, mask.vbo, 0);
421 device_.setIndexBuffer(BufferHandle::Invalid);
422 device_.drawArrays(0, static_cast<u32>(mask.vertices.size() / kShadow2DFloats));
423}
424
425bool RenderFrame::hasShape2DLight(ecs::Registry& registry) {
426 auto view = registry.activeView<ecs::Transform, ecs::Light>();
427 for (auto entity : view) {
428 const auto& light = view.get<ecs::Light>(entity);
429 if (!light.enabled || !light.cookie.isValid()) continue;
430 Texture* tex = resource_manager_.getTexture(light.cookie);
431 if (tex && tex->getId() != 0) return true;
432 }
433 return false;
434}
435
436
437// The shape mask — the same target as the shadow mask above, carrying the other half
438// of "how much of this light is here": what its own cookie covers.
439
440void RenderFrame::collectShape2D(ecs::Registry& registry) {
441 shape_2d_lights_.clear();
442 shape_2d_resource_ = rg::kNoResource;
443 shape_2d_texture_id_ = 0;
444
445 const LightConstants& lights = context_.lights().data();
446 auto view = registry.activeView<ecs::Transform, ecs::Light>();
447 for (auto entity : view) {
448 if (shape_2d_lights_.size() >= MAX_SHAPE_2D_LIGHTS) break;
449 const auto& light = view.get<ecs::Light>(entity);
450 if (!light.enabled || !light.cookie.isValid()) continue;
451 Texture* tex = resource_manager_.getTexture(light.cookie);
452 if (!tex || tex->getId() == 0) continue;
453
454 // The light's own slot, found by where it stands: the collect wrote the array,
455 // and a light the cap dropped has no slot to give a channel to.
456 const glm::vec3 p = [&] {
457 auto& transform = view.get<ecs::Transform>(entity);
458 transform.ensureDecomposed();
459 return rebased(transform.worldPosition);
460 }();
461 u32 slot = MAX_LIGHTS;
462 for (u32 i = 0; i < context_.lights().count(); ++i) {
463 const GpuLight& gpu = lights.lights[i];
464 if (gpu.posDir.z > 1.5f || gpu.posDir.z < 0.5f) {
465 if (std::abs(gpu.posDir.x - p.x) < 1e-3f && std::abs(gpu.posDir.y - p.y) < 1e-3f) {
466 slot = i;
467 break;
468 }
469 }
470 }
471 if (slot >= MAX_LIGHTS) continue;
472
473 // The light's own reach where the author named no size: a shape smaller than the
474 // reach cuts the light off, and one larger is trimmed by the falloff anyway.
475 const f32 reach = std::max(light.radius, 0.0f) * 2.0f;
476 const f32 w = light.cookieSize.x > 0.0f ? light.cookieSize.x : reach;
477 const f32 h = light.cookieSize.y > 0.0f ? light.cookieSize.y : reach;
478 if (w <= 0.0f || h <= 0.0f) continue;
479
480 auto& transform = view.get<ecs::Transform>(entity);
481 const glm::vec2 turn = flatTurnZ(transform.worldRotation);
482 const auto corner = [&](f32 sx, f32 sy) {
483 const f32 lx = sx * w * 0.5f;
484 const f32 ly = sy * h * 0.5f;
485 return glm::vec2{p.x + lx * turn.x - ly * turn.y, p.y + lx * turn.y + ly * turn.x};
486 };
487 Shape2DLight entry;
488 entry.corners[0] = corner(-1.0f, -1.0f);
489 entry.corners[1] = corner(1.0f, -1.0f);
490 entry.corners[2] = corner(1.0f, 1.0f);
491 entry.corners[3] = corner(-1.0f, 1.0f);
492 entry.texture = tex->getId();
493 entry.slot = slot;
494 shape_2d_lights_.push_back(entry);
495 }
496 if (shape_2d_lights_.empty()) return;
497
498 for (u32 i = 0; i < shape_2d_lights_.size(); ++i) {
499 context_.lights().setLightShape2DChannel(shape_2d_lights_[i].slot, i);
500 }
501
502 rg::TargetDesc desc;
503 desc.scale = 1.0f;
504 desc.format = GfxPixelFormat::RGBA8;
505 // Linear: a cookie is artwork, and its edge is meant to be soft. The shadow mask
506 // reads nearest for the opposite reason — there, a filtered read would blend in the
507 // neighbouring light's silhouette.
508 desc.linearFilter = true;
509 shape_2d_resource_ = graph_.createTarget(desc);
510}
511
512void RenderFrame::releaseShape2DResources() {
513 if (shape_2d_vbo_ != BufferHandle::Invalid) device_.deleteBuffer(shape_2d_vbo_);
514 if (shape_2d_layout_ != VertexLayoutHandle::Invalid) device_.deleteVertexLayout(shape_2d_layout_);
515 shape_2d_vbo_ = BufferHandle::Invalid;
516 shape_2d_vbo_bytes_ = 0;
517 shape_2d_layout_ = VertexLayoutHandle::Invalid;
518}
519
520bool RenderFrame::ensureShape2DShader() {
521 if (shape_2d_shader_.isValid()) return true;
522 if (shape_2d_shader_tried_) return false;
523 shape_2d_shader_tried_ = true;
524
525 auto& resources = resource_manager_;
526 const auto target = resources.preferredShaderTarget();
528 shape_2d_shader_ = resources.createShader(
531 /*rewriteLoose=*/false, resources.preferredShaderLanguage());
532 if (!shape_2d_shader_.isValid()) {
533 ES_LOG_ERROR("RenderFrame: no 2D light-shape shader; shaped lights are off this run");
534 return false;
535 }
536
537 VertexLayoutDesc layout;
538 layout.attributeCount = 3;
539 layout.strides[0] = kShape2DFloats * sizeof(f32);
540 layout.attributes[0] = {0, 2, GfxDataType::Float, false, 0, 0};
541 layout.attributes[1] = {1, 2, GfxDataType::Float, false, 2 * sizeof(f32), 0};
542 layout.attributes[2] = {2, 4, GfxDataType::Float, false, 4 * sizeof(f32), 0};
543 shape_2d_layout_ = device_.createVertexLayout(layout);
544 return shape_2d_layout_ != VertexLayoutHandle::Invalid;
545}
546
547void RenderFrame::declareShape2DPass() {
548 if (shape_2d_resource_ == rg::kNoResource) return;
549
550 rg::PassDesc mask;
551 mask.name = "light-shape-2d";
552 mask.write = shape_2d_resource_;
553 mask.clear = true;
554 // Zero is "this light's shape does not reach here", which is what a frame whose
555 // quads come back empty has to read as.
556 mask.clearColor[0] = mask.clearColor[1] = mask.clearColor[2] = 0.0f;
557 mask.clearColor[3] = 0.0f;
558 mask.execute = [this](const rg::PassContext&) { executeShape2DPass(); };
559 graph_.addPass(std::move(mask));
560}
561
562void RenderFrame::executeShape2DPass() {
563 if (shape_2d_resource_ == rg::kNoResource) return;
564 if (!ensureShape2DShader()) return;
565
566 ES_PROFILE_SCOPE("render.lightshape2d");
567 ES_PROFILE_COUNTER("render.lightshape2d.lights", static_cast<u32>(shape_2d_lights_.size()));
568
569 shape_2d_vertices_.clear();
570 for (u32 i = 0; i < shape_2d_lights_.size(); ++i) {
571 const Shape2DLight& light = shape_2d_lights_[i];
572 const glm::vec2 uv[4] = {{0.0f, 0.0f}, {1.0f, 0.0f}, {1.0f, 1.0f}, {0.0f, 1.0f}};
573 const u32 order[6] = {0, 1, 2, 0, 2, 3};
574 for (u32 k = 0; k < 6; ++k) {
575 const u32 c = order[k];
576 shape_2d_vertices_.push_back(light.corners[c].x);
577 shape_2d_vertices_.push_back(light.corners[c].y);
578 shape_2d_vertices_.push_back(uv[c].x);
579 shape_2d_vertices_.push_back(uv[c].y);
580 for (u32 ch = 0; ch < 4; ++ch) {
581 shape_2d_vertices_.push_back(ch == i ? 1.0f : 0.0f);
582 }
583 }
584 }
585 if (shape_2d_vertices_.empty()) return;
586
587 const u32 bytes = static_cast<u32>(shape_2d_vertices_.size() * sizeof(f32));
588 if (shape_2d_vbo_ == BufferHandle::Invalid || bytes > shape_2d_vbo_bytes_) {
589 if (shape_2d_vbo_ != BufferHandle::Invalid) device_.deleteBuffer(shape_2d_vbo_);
590 shape_2d_vbo_bytes_ = std::max(bytes * 2u, 1024u);
591 shape_2d_vbo_ = device_.createBuffer(
592 {GfxBufferUsage::Vertex, shape_2d_vbo_bytes_, /*dynamic=*/true}, GfxContent::transient(), nullptr);
593 if (shape_2d_vbo_ == BufferHandle::Invalid) return;
594 }
595 device_.updateBuffer(shape_2d_vbo_, 0, shape_2d_vertices_.data(), bytes);
596
597 Shader* shader = resource_manager_.getShader(shape_2d_shader_);
598 if (!shader) return;
599
600 PipelineDesc desc{};
601 desc.program = shader->handle();
602 desc.vertexLayout = shape_2d_layout_;
603 // Adding: the channels are independent, so what a quad writes lands only in its
604 // own — and two quads of one light are not a thing this pass builds.
605 desc.blend = BlendMode::PmaAdditive;
606 desc.blendEnabled = true;
607 desc.depthTest = false;
608 desc.depthWrite = false;
609 device_.setPipeline(device_.createPipeline(desc));
610 device_.setViewport(std::max(scene_viewport_.x, 0), std::max(scene_viewport_.y, 0),
611 static_cast<i32>(scene_viewport_.w), static_cast<i32>(scene_viewport_.h));
612 context_.updateCameraConstants(view_projection_);
613 device_.setVertexBuffer(0, shape_2d_vbo_, 0);
614 device_.setIndexBuffer(BufferHandle::Invalid);
615 // One draw per light: the cookie is the draw's own texture, which is what an atlas
616 // would exist to avoid — and four quads do not need one.
617 for (u32 i = 0; i < shape_2d_lights_.size(); ++i) {
618 device_.bindTexture(0, TextureHandle{shape_2d_lights_[i].texture});
619 device_.drawArrays(i * 6, 6);
620 }
621
622 shape_2d_texture_id_ = static_cast<u32>(graph_.textureOf(shape_2d_resource_));
623}
624
625} // namespace esengine
Per-frame CPU scope timing (ES_PROFILE_SCOPE) read by the editor profiler.
#define ES_PROFILE_SCOPE(name)
#define ES_PROFILE_COUNTER(name, value)
2D light source component for the Lit material domain.
Logging utilities for ESEngine.
#define ES_LOG_ERROR(...)
Logs an error message.
Definition Log.hpp:296
Frame resources and the shared scene rendering contract.
Parser for unified .esshader file format.
Marks an entity as a 2D shadow occluder for the Lit lighting path.
Which channel of the 2D shadow mask each casting light draws into, so lights that never meet can shar...
Unified Transform component with local and world-space data.
static constexpr GfxContent transient()
Central container for all entities and components.
Definition Registry.hpp:73
static ParsedShader parse(const std::string &source)
Parses shader source into structured format (no include support).
static std::string assembleStage(const ParsedShader &parsed, ShaderStage stage, const std::string &platform="", const std::vector< std::string > &features={}, ShaderTargetLanguage target=ShaderTargetLanguage::GLSL_ES300)
Assembles final GLSL source for a specific stage.
constexpr const char * LIGHTSHAPE2D
constexpr const char * SHADOW2D
f32 radius(const glm::vec3 &lo, const glm::vec3 &hi, f32 displacement)
constexpr ResourceId kNoResource
constexpr u32 MAX_LIGHTS
Max simultaneous 2D lights packed into the UBO. The injected fragment loop is a fixed bound; inactive...
std::int32_t i32
Signed 32-bit integer.
Definition Types.hpp:54
constexpr u32 MAX_SHADOW_2D_LIGHTS
Channels of the 2D shadow mask: the lights that MEET one another and cast at once (see ShadowChannels...
std::size_t usize
Size type for indexing and sizes.
Definition Types.hpp:64
constexpr u32 MAX_SHAPE_2D_LIGHTS
Lights whose SHAPE one frame can carry — the shape mask's four channels.
u32 assignShadowChannels(const ShadowMaskLight *lights, u32 count, u32 channels, i32 *out)
Gives each light the first channel none of its collisions hold, in the order the lights are given.
std::uint32_t u32
Unsigned 32-bit integer.
Definition Types.hpp:45
glm::vec3 rebased(const glm::vec3 &world)
A world position as the frame draws it: from the origin.
constexpr u32 SHADOW_2D_MASK_CHANNELS
Channels one 2D shadow mask carries: an RGBA8 target has four.
glm::vec2 flatTurnZ(const glm::quat &rotation)
The cos/sin of the turn a plane renderable draws with: its entity's rotation about Z,...
float f32
32-bit floating point
Definition Types.hpp:59