31constexpr u32 kShadow2DFloats = 7;
35constexpr u32 kShape2DFloats = 8;
41constexpr f32 kShadow2DOvershoot = 1.25f;
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_) {
54 context_.lights().setMask2DRect(glm::vec4(0.0f));
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);
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};
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));
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));
89 if (shadow_rings_2d_.empty())
return;
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);
97 for (
u32 i = 0; i < ring.count; ++i) radius = std::max(radius, glm::distance(pts[i], centre));
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;
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;
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;
127 if (entry.reach <= 0.0f)
return;
129 ShadowMaskLight mask;
130 mask.pos = entry.pos;
131 if (entry.directional) {
132 mask.everywhere =
true;
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);
142 if (furthest < 0.0f)
return;
143 mask.read = entry.reach;
144 mask.write = furthest + entry.reach * kShadow2DOvershoot;
146 shadow_2d_lights_.push_back(entry);
147 masks.push_back(mask);
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();
157 std::vector<i32> channels(masks.size(), -1);
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]);
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();
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);
188 desc.linearFilter =
false;
189 shadow_2d_masks_[0].resource = graph_.createTarget(desc);
190 if (second) shadow_2d_masks_[1].resource = graph_.createTarget(desc);
193void RenderFrame::releaseShadow2DResources() {
194 for (Shadow2DMask& mask : shadow_2d_masks_) {
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;
208 auto& resources = resource_manager_;
209 const auto target = resources.preferredShaderTarget();
211 shadow_2d_shader_ = resources.createShader(
214 false, resources.preferredShaderLanguage());
215 if (!shadow_2d_shader_.isValid()) {
216 ES_LOG_ERROR(
"RenderFrame: no 2D shadow shader; 2D shadows are off this run");
220 VertexLayoutDesc layout;
221 layout.attributeCount = 3;
222 layout.strides[0] = kShadow2DFloats *
sizeof(
f32);
226 shadow_2d_layout_ = device_.createVertexLayout(layout);
233inline f32 cross2(
const glm::vec2& a,
const glm::vec2& b) {
234 return a.x * b.y - a.y * b.x;
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};
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);
254void RenderFrame::buildShadow2DGeometry(
u32 maskIndex) {
256 std::vector<f32>& vertices = shadow_2d_masks_[maskIndex].vertices;
260 vertices.reserve(shadow_rings_2d_.size() * shadow_2d_lights_.size()
261 * shadow_2d_soft_samples_ * 6 * kShadow2DFloats);
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);
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);
278 for (
const Shadow2DLight& light : shadow_2d_lights_) {
284 const u32 samples = light.softness > 1e-4f ? shadow_2d_soft_samples_ : 1u;
285 const f32 share = 1.0f /
static_cast<f32>(samples);
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;
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;
298 if (!light.directional
299 && glm::distance(centre, light.pos) > light.reach + light.softness + ring.radius) {
303 for (
u32 s = 0; s < samples; ++s) {
304 const f32 t = offsetOf(s);
305 if (light.directional) {
309 const f32 spread = (light.reach > 1e-6f) ? light.softness / light.reach : 0.0f;
310 const f32 angle = t * spread;
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),
317 const glm::vec2 across = perpendicularTo(dir);
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;
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);
332 const glm::vec2 from =
333 light.pos + perpendicularTo(centre - light.pos) * (t * light.softness);
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;
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);
353void RenderFrame::declareShadow2DPass() {
354 for (
u32 i = 0; i < 2; ++i) {
357 mask.name = i == 0 ?
"shadow-2d" :
"shadow-2d-b";
358 mask.write = shadow_2d_masks_[i].resource;
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));
369void RenderFrame::executeShadow2DPass(
u32 maskIndex) {
370 Shadow2DMask& mask = shadow_2d_masks_[maskIndex];
372 if (!ensureShadow2DShader())
return;
376 mask.textureId =
static_cast<u32>(graph_.textureOf(mask.resource));
377 buildShadow2DGeometry(maskIndex);
381 static_cast<u32>(mask.vertices.size() / (kShadow2DFloats * 3)));
386 if (mask.vertices.empty())
return;
389 const u32 bytes =
static_cast<u32>(mask.vertices.size() *
sizeof(
f32));
394 mask.vboBytes = std::max(bytes * 2u, 4096u);
395 mask.vbo = device_.createBuffer(
399 device_.updateBuffer(mask.vbo, 0, mask.vertices.data(), bytes);
401 Shader* shader = resource_manager_.getShader(shadow_2d_shader_);
405 desc.program = shader->handle();
406 desc.vertexLayout = shadow_2d_layout_;
411 desc.blendEnabled =
true;
412 desc.depthTest =
false;
413 desc.depthWrite =
false;
414 device_.setPipeline(device_.createPipeline(desc));
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);
422 device_.drawArrays(0,
static_cast<u32>(mask.vertices.size() / kShadow2DFloats));
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;
441 shape_2d_lights_.clear();
443 shape_2d_texture_id_ = 0;
445 const LightConstants& lights = context_.lights().data();
446 auto view = registry.activeView<ecs::Transform, ecs::Light>();
447 for (
auto entity : view) {
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;
456 const glm::vec3 p = [&] {
457 auto& transform = view.get<ecs::Transform>(entity);
458 transform.ensureDecomposed();
459 return rebased(transform.worldPosition);
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) {
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;
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};
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();
494 shape_2d_lights_.push_back(entry);
496 if (shape_2d_lights_.empty())
return;
498 for (
u32 i = 0; i < shape_2d_lights_.size(); ++i) {
499 context_.lights().setLightShape2DChannel(shape_2d_lights_[i].slot, i);
508 desc.linearFilter =
true;
509 shape_2d_resource_ = graph_.createTarget(desc);
512void RenderFrame::releaseShape2DResources() {
516 shape_2d_vbo_bytes_ = 0;
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;
525 auto& resources = resource_manager_;
526 const auto target = resources.preferredShaderTarget();
528 shape_2d_shader_ = resources.createShader(
531 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");
537 VertexLayoutDesc layout;
538 layout.attributeCount = 3;
539 layout.strides[0] = kShape2DFloats *
sizeof(
f32);
543 shape_2d_layout_ = device_.createVertexLayout(layout);
547void RenderFrame::declareShape2DPass() {
551 mask.name =
"light-shape-2d";
552 mask.write = shape_2d_resource_;
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));
562void RenderFrame::executeShape2DPass() {
564 if (!ensureShape2DShader())
return;
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);
585 if (shape_2d_vertices_.empty())
return;
587 const u32 bytes =
static_cast<u32>(shape_2d_vertices_.size() *
sizeof(
f32));
590 shape_2d_vbo_bytes_ = std::max(bytes * 2u, 1024u);
591 shape_2d_vbo_ = device_.createBuffer(
595 device_.updateBuffer(shape_2d_vbo_, 0, shape_2d_vertices_.data(), bytes);
597 Shader* shader = resource_manager_.getShader(shape_2d_shader_);
601 desc.program = shader->handle();
602 desc.vertexLayout = shape_2d_layout_;
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);
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);
622 shape_2d_texture_id_ =
static_cast<u32>(graph_.textureOf(shape_2d_resource_));
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.
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...
static constexpr GfxContent transient()
Central container for all entities and components.
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.
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.
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.
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