Estella 0.113.0
A fast 2D and 3D game engine powered by WebAssembly and ECS
Loading...
Searching...
No Matches
MeshPlugin.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
7#include "MeshPlugin.hpp"
15#include "../rhi/Texture.hpp"
29#include "../../core/Log.hpp"
31#include "../../core/Hash.hpp"
32
33#include <glm/gtc/matrix_transform.hpp>
34#include <glm/gtc/matrix_inverse.hpp>
35#include <glm/gtc/matrix_access.hpp>
36
37#include <algorithm>
38#include <cmath>
39#include <limits>
40#include <string>
41#include <vector>
42
43#include <cmath>
44#include <cstring>
45
46namespace esengine {
47
48namespace {
49// Per-channel RGBA8 multiply, for tinting per-vertex colors.
50u32 mulColor(u32 a, u32 b) {
51 u32 r = (((a >> 0) & 0xFF) * ((b >> 0) & 0xFF)) / 255u;
52 u32 g = (((a >> 8) & 0xFF) * ((b >> 8) & 0xFF)) / 255u;
53 u32 bl = (((a >> 16) & 0xFF) * ((b >> 16) & 0xFF)) / 255u;
54 u32 al = (((a >> 24) & 0xFF) * ((b >> 24) & 0xFF)) / 255u;
55 return r | (g << 8) | (bl << 16) | (al << 24);
56}
59
76u32 skinnedBy(const Mesh& mesh, usize joints, bool& warnedBones) {
77 if (!mesh.isSkinned() || joints != mesh.inverseBind.size()) return 0;
78 // Posing the first MESH_MAX_BONES leaves the rest indexing a matrix this
79 // draw never uploads — the wrong-matrix read the count check above already
80 // rejects, so it takes the same answer. A chunked skin is drawn a chunk at a
81 // time, each with at most that many, so it may have any number.
82 if (joints > MESH_MAX_BONES && !mesh.isChunked()) {
83 if (!warnedBones) {
84 warnedBones = true;
85 ES_LOG_WARN("MeshSkin: {} joints exceeds the {} one draw can be posed by; drawing the"
86 " bind pose", joints, MESH_MAX_BONES);
87 }
88 return 0;
89 }
90 return static_cast<u32>(joints);
91}
92
93u32 skinJointCount(ecs::Registry& registry, Entity entity, const Mesh& mesh, bool& warnedBones) {
94 const auto* skin = registry.tryGet<ecs::MeshSkin>(entity);
95 return skin ? skinnedBy(mesh, skin->joints.size(), warnedBones) : 0;
96}
97
100MeshProgramFacts meshFactsFromDocument(RenderFrameContext& ctx, const MeshDocumentRecord& row,
101 bool& warnedBones) {
102 MeshProgramFacts facts;
103 const Mesh* resident = row.meshHandle != 0
104 ? ctx.resources.getMesh(resource::MeshHandle(row.meshHandle)) : nullptr;
105 facts.hasNormals = resident && resident->hasNormals;
106 facts.lit = row.lit != 0;
107 facts.materialId = row.materialId;
108 if (row.normalMapHandle != 0 && facts.lit && facts.hasNormals) {
109 if (Texture* tex = ctx.resources.getTexture(resource::TextureHandle(row.normalMapHandle))) {
110 facts.normalTextureId = tex->getId();
111 }
112 }
113 facts.skinned = resident && skinnedBy(*resident, row.jointCount, warnedBones) > 0;
114 facts.lightmapped = resident && resident->hasLightmapUV;
115 facts.tangents = resident && resident->hasTangents;
116 return facts;
117}
118
119u32 skinPose(ecs::Registry& registry, Entity entity, const Mesh& mesh,
120 std::vector<glm::mat4>& out, bool& warnedBones) {
121 const u32 count = skinJointCount(registry, entity, mesh, warnedBones);
122 if (count == 0) return 0;
123 const auto* skin = registry.tryGet<ecs::MeshSkin>(entity);
124
125 out.resize(count);
126 for (u32 i = 0; i < count; ++i) {
127 auto* joint = registry.tryGet<ecs::Transform>(skin->joints[i]);
128 // A joint that is not there leaves the bind pose, which is the mesh as
129 // authored rather than a vertex collapsed onto the origin.
130 if (!joint) { out[i] = glm::mat4(1.0f); continue; }
131 // Built from the decomposed world fields, the same three every other
132 // draw is placed by — the cached matrix is the transform system's own
133 // and is not guaranteed current for an entity nothing parents.
134 joint->ensureDecomposed();
135 const glm::mat4 world = glm::translate(glm::mat4(1.0f), rebased(joint->worldPosition))
136 * glm::mat4_cast(joint->worldRotation)
137 * glm::scale(glm::mat4(1.0f), joint->worldScale);
138 out[i] = world * mesh.inverseBind[i];
139 }
140 return count;
141}
142
152bool skinnedWorldBounds(ecs::Registry& registry, Entity entity, const Mesh& mesh, bool& warnedBones,
153 glm::vec3& centre, glm::vec3& half) {
154 const u32 count = skinJointCount(registry, entity, mesh, warnedBones);
155 if (count == 0) return false;
156 const auto* skin = registry.tryGet<ecs::MeshSkin>(entity);
157 const glm::vec3 bindCentre = (mesh.localMin + mesh.localMax) * 0.5f;
158 const f32 bindRadius = glm::length(mesh.localMax - mesh.localMin) * 0.5f;
159 glm::vec3 lo(std::numeric_limits<f32>::max()), hi(std::numeric_limits<f32>::lowest());
160 for (u32 i = 0; i < count; ++i) {
161 auto* joint = registry.tryGet<ecs::Transform>(skin->joints[i]);
162 if (!joint) continue;
163 joint->ensureDecomposed();
164 const glm::vec3 scale = glm::abs(joint->worldScale);
165 const f32 reach = (glm::length(glm::vec3(mesh.inverseBind[i] * glm::vec4(bindCentre, 1.0f))) + bindRadius)
166 * std::max({scale.x, scale.y, scale.z});
167 const glm::vec3 at = rebased(joint->worldPosition);
168 lo = glm::min(lo, at - reach);
169 hi = glm::max(hi, at + reach);
170 }
171 if (lo.x > hi.x) return false;
172 centre = (lo + hi) * 0.5f;
173 half = (hi - lo) * 0.5f;
174 return true;
175}
176
187bool morphShapes(ecs::Registry& registry, Entity entity, const Mesh& mesh,
188 MorphConstants& out) {
189 if (!mesh.isMorphable()) return false;
190 const auto* morph = registry.tryGet<ecs::MeshMorph>(entity);
191 if (!morph) return false;
192
193 // Weight i addresses target i, so a list longer than the mesh names shapes
194 // it does not have — those entries are not read rather than shifting the rest.
195 const u32 count = std::min(static_cast<u32>(morph->weights.size()), mesh.morphTargetCount);
196 u32 live = 0;
197 for (u32 t = 0; t < count; ++t) {
198 const f32 weight = morph->weights[t];
199 if (weight == 0.0f) continue;
200 if (live < MESH_MAX_ACTIVE_MORPHS) {
201 out.shape[live++] = glm::vec4(static_cast<f32>(t), weight, 0.0f, 0.0f);
202 continue;
203 }
204 // Full: the smallest of what is held loses its place, and only to
205 // something heavier — so what survives is the heaviest set, whatever
206 // order the weights arrived in.
207 u32 lightest = 0;
208 for (u32 i = 1; i < MESH_MAX_ACTIVE_MORPHS; ++i) {
209 if (std::abs(out.shape[i].y) < std::abs(out.shape[lightest].y)) lightest = i;
210 }
211 if (std::abs(weight) > std::abs(out.shape[lightest].y)) {
212 out.shape[lightest] = glm::vec4(static_cast<f32>(t), weight, 0.0f, 0.0f);
213 }
214 }
215 if (live == 0) return false;
216 out.info = glm::vec4(static_cast<f32>(live), static_cast<f32>(mesh.vertexCount),
217 mesh.morphHasNormals ? 2.0f : 1.0f,
218 static_cast<f32>(MORPH_TEXTURE_WIDTH));
219 return true;
220}
221
223void reportLodAuthoring(const LodLevels& levels, bool& warned) {
224 if (warned || !(levels.gap || levels.disordered || levels.skinMismatch)) return;
225 warned = true;
226 if (levels.gap) {
227 ES_LOG_WARN("LODGroup: a stand-in slot is empty, so every slot after it is unreachable —"
228 " fill lod1, then lod2, then lod3");
229 }
230 if (levels.disordered) {
231 ES_LOG_WARN("LODGroup: the screen sizes do not descend, so a level is handed over to"
232 " before the one before it");
233 }
234 if (levels.skinMismatch) {
235 ES_LOG_WARN("LODGroup: a stand-in has a different joint count from level 0; every level of"
236 " a skinned group must share the skeleton");
237 }
238}
239
240u32 meshVariant(bool normals, bool lit, bool normalMapped, bool skinned, bool depthOnly,
241 bool envMapped, bool lightmapped, bool weightHeat = false, bool gbuffer = false,
242 bool motion = false, bool tangents = false, bool direct = false) {
243 return (normals ? 1u : 0u) | (lit ? 2u : 0u) | (normalMapped ? 4u : 0u)
244 | (skinned ? 8u : 0u) | (depthOnly ? 16u : 0u) | (envMapped ? 32u : 0u)
245 | (lightmapped ? 64u : 0u) | (weightHeat ? 128u : 0u) | (gbuffer ? 256u : 0u)
246 | (motion ? 512u : 0u) | (tangents ? 1024u : 0u) | (direct ? 2048u : 0u);
247}
248
259constexpr glm::vec4 kWireFill{0.075f, 0.075f, 0.08f, 1.0f};
260constexpr glm::vec4 kWireInk{0.9f, 0.9f, 0.9f, 1.0f};
263constexpr i16 kWireFillBias = 4;
264
272void applyShading(ecs::MeshRenderer& mesh, ShadingMode mode) {
273 mesh.material = 0;
274 mesh.normalMap = {};
275 if (mode == ShadingMode::Wireframe) {
276 // The surface the edges stand on: dark, unlit, opaque so it hides what is behind it.
277 mesh.texture = {};
278 mesh.color = kWireFill;
279 mesh.lit = false;
280 mesh.opaque = true;
281 } else if (shadesAsClay(mode) || mode == ShadingMode::Clusters) {
282 mesh.texture = {};
283 mesh.color = glm::vec4(0.74f, 0.74f, 0.76f, 1.0f);
284 mesh.lit = true;
285 } else {
286 mesh.lit = false;
287 }
288}
289
294glm::vec4 clusterInk(u32 id) {
295 u32 h = id * 0x9E3779B1u;
296 h ^= h >> 15;
297 const f32 hue = static_cast<f32>(h & 0xFFFFu) / 65536.0f * 6.0f;
298 const f32 rise = hue - std::floor(hue);
299 const f32 low = 0.28f, high = 0.95f;
300 const f32 up = low + (high - low) * rise, down = high - (high - low) * rise;
301 switch (static_cast<u32>(hue) % 6u) {
302 case 0: return {high, up, low, 1.0f};
303 case 1: return {down, high, low, 1.0f};
304 case 2: return {low, high, up, 1.0f};
305 case 3: return {low, down, high, 1.0f};
306 case 4: return {up, low, high, 1.0f};
307 default: return {high, low, down, 1.0f};
308 }
309}
310
311struct MeshDrawKeys {
312 u32 variant = 0;
313 u32 normalTextureId = 0;
314};
315
316u32 meshVariantFrom(const MeshProgramFacts& facts, bool envMapped, bool shadowDepth, bool direct, bool weightHeat = false,
317 bool gbuffer = false) {
318 // `lightmapped` and `tangents` survive the shadow pass, unlike the three describing shading: each declares a vertex attribute.
319 // Weights are read off the surface of a skinned draw and nothing else's: the colour is
320 // the shade, so it asks for no light, no normal map and no depth pass of its own.
321 const bool heat = weightHeat && facts.skinned && !shadowDepth;
322 const bool lit = facts.lit && !shadowDepth && !heat;
323 // The surface record is for what takes light: an unlit surface has no normal worth recording.
324 return meshVariant(facts.hasNormals, lit,
325 facts.normalTextureId != 0 && !shadowDepth && !heat, facts.skinned, shadowDepth,
326 envMapped, facts.lightmapped, heat, gbuffer && lit, false, facts.tangents, direct && lit);
327}
328
330MeshProgramFacts meshFactsFromEntity(RenderFrameContext& ctx, ecs::Registry& registry,
331 Entity entity, const ecs::MeshRenderer& mesh,
332 const Mesh* resident, bool& warnedBones) {
333 MeshProgramFacts facts;
334 facts.hasNormals = resident && resident->hasNormals;
335 facts.lit = mesh.lit;
336 facts.opaque = mesh.opaque;
337 facts.materialId = mesh.material;
338 // Only meaningful with normals to perturb AND a draw that takes light.
339 if (mesh.normalMap.isValid() && mesh.lit && resident && resident->hasNormals) {
340 if (Texture* tex = ctx.resources.getTexture(mesh.normalMap)) {
341 facts.normalTextureId = tex->getId();
342 }
343 }
344 facts.skinned = resident && skinJointCount(registry, entity, *resident, warnedBones) > 0;
345 facts.lightmapped = resident && resident->hasLightmapUV;
346 facts.tangents = resident && resident->hasTangents;
347 return facts;
348}
349
351MeshDrawKeys meshDrawFrom(RenderFrameContext& ctx, Entity entity, const MeshProgramFacts& facts, bool shadowDepth,
352 bool weightHeat = false) {
353 return { meshVariantFrom(facts, ctx.environment_texture_id != 0
354 || (!shadowDepth && ctx.frame && ctx.frame->planarTextureFor(entity) != 0), shadowDepth, ctx.lighting_direct, weightHeat,
355 ctx.gbuffer && !shadowDepth),
356 facts.normalTextureId };
357}
358
359MeshDrawKeys meshDrawFor(RenderFrameContext& ctx, ecs::Registry& registry, Entity entity,
360 const ecs::MeshRenderer& mesh, const Mesh* resident, bool shadowDepth,
361 bool& warnedBones, bool weightHeat = false) {
362 return meshDrawFrom(ctx, entity, meshFactsFromEntity(ctx, registry, entity, mesh, resident, warnedBones), shadowDepth,
363 weightHeat);
364}
365
367u32 normalTextureOf(RenderFrameContext& ctx, const ecs::MeshRenderer& mesh, const MeshProgramFacts& facts) {
368 if (!mesh.normalMap.isValid() || !facts.lit || !facts.hasNormals) return 0;
369 Texture* tex = ctx.resources.getTexture(mesh.normalMap);
370 return tex ? tex->getId() : 0;
371}
372
377u8 ruledOut(ecs::Registry& registry, Entity entity) {
378 return (registry.has<ecs::Billboard>(entity) ? 1u : 0u)
379 | (registry.has<ecs::MeshInstances>(entity) ? 2u : 0u)
380 | (registry.has<ecs::LODGroup>(entity) ? 4u : 0u)
381 | (registry.has<ecs::Impostor>(entity) ? 8u : 0u)
382 | (registry.has<ecs::MeshSkin>(entity) ? 16u : 0u)
383 | (registry.has<ecs::MeshMorph>(entity) ? 32u : 0u);
384}
385
387u32 ruledOutChangedAt(const ecs::Registry& registry) {
388 u32 latest = 0;
389 for (const u32 t : {registry.lastChangedTick<ecs::Billboard>(), registry.lastChangedTick<ecs::MeshInstances>(),
390 registry.lastChangedTick<ecs::LODGroup>(), registry.lastChangedTick<ecs::Impostor>(),
391 registry.lastChangedTick<ecs::MeshSkin>(), registry.lastChangedTick<ecs::MeshMorph>()}) {
392 if (latest == 0 || (t != 0 && ecs::tickAfter(t, latest))) latest = t;
393 }
394 return latest;
395}
396} // namespace
397
398void MeshPlugin::scheduleSkins(RenderFrameContext& ctx, ecs::Registry& registry, SkinCache& cache) {
399 // Every skinned mesh the cache is asked for: a mesh not drawn this frame costs one dispatch, which is cheaper than finding
400 // which views will draw it.
401 for (const Entity entity : registry.view<ecs::MeshRenderer, ecs::MeshSkin>()) {
402 const auto& skin = registry.get<ecs::MeshSkin>(entity);
403 const auto usage = static_cast<SkinCacheUsage>(std::clamp(skin.skinCache, 0, 2));
404 if (!cache.wants(usage)) continue;
405 const auto& renderer = registry.get<ecs::MeshRenderer>(entity);
406 if (!renderer.enabled || !renderer.mesh.isValid()) continue;
407 const Mesh* resident = ctx.resources.getMesh(renderer.mesh);
408 if (!resident || !resident->isDrawable()) continue;
409 // A mesh being reshaped by its morph targets is posed in the vertex stage, where the shapes are applied first.
410 if (registry.has<ecs::MeshMorph>(entity) && resident->morphTexture != TextureHandle::Invalid) continue;
411 const u32 joints = skinPose(registry, entity, *resident, pose_scratch_, warned_bones_);
412 if (joints == 0) continue;
413 cache.schedule(entity, *resident, pose_scratch_.data(), joints);
414 }
415}
416
418 // A renderer initialized again runs this on a cache that compiled before. The
419 // RESOURCES are released, not just forgotten: a shader nobody holds still
420 // sits in the pool and keeps its program alive for good.
421 for (auto& shader : mesh_shaders_) {
422 if (shader.isValid()) ctx.resources.releaseShader(shader);
423 shader = {};
424 }
425 // Only when something WAS ready: a first boot has no readiness to invalidate,
426 // and an epoch that moves on it would age every stamp taken before the first
427 // frame. What this call means is "what was ready is not any more".
428 if (std::any_of(mesh_compiled_.begin(), mesh_compiled_.end(), [](bool c) { return c; })) {
429 ctx.render_context.advanceProgramEpoch();
430 }
431 mesh_compiled_.fill(false);
432 mesh_programs_.fill(0);
433 // A renderer rebuilt has resources rebuilt under it: nothing derived before is kept.
434 proxies_.clear();
435 proxy_slot_.clear();
436 ++proxy_epoch_;
437 ++cast_serial_;
438 // The base variant now, so a broken shader is a boot-time failure rather than
439 // one that waits for the first mesh; the rest compile when a draw asks.
440 meshProgram(ctx, 0);
441}
442
450u32 MeshPlugin::meshProgram(RenderFrameContext& ctx, u32 variant) {
451 const bool normals = (variant & 1u) != 0, lit = (variant & 2u) != 0;
452 const bool normalMapped = (variant & 4u) != 0, skinned = (variant & 8u) != 0;
453 const bool depthOnly = (variant & 16u) != 0, envMapped = (variant & 32u) != 0;
454 const bool lightmapped = (variant & 64u) != 0, weightHeat = (variant & 128u) != 0;
455 const bool gbuffer = (variant & 256u) != 0, motion = (variant & 512u) != 0;
456 const bool tangents = (variant & 1024u) != 0, direct = (variant & 2048u) != 0;
457 if (mesh_compiled_[variant]) return mesh_programs_[variant];
458 mesh_compiled_[variant] = true;
459 // Counted because the cost of this function is entirely the times it does
460 // NOT return above: every frame asks once per mesh, and only the first frame
461 // that needs a variant pays for it. WHICH one is the other half — a readiness
462 // that missed a requirement is named by the key that had to be built late.
463 ++compiled_this_frame_;
464 ++programs_built_;
465 last_compiled_variant_ = variant;
466
467 std::vector<std::string> features;
468 if (normals) features.emplace_back("MESH_NORMALS");
469 if (lit) features.emplace_back("LIT");
470 if (normalMapped) features.emplace_back("NORMAL_MAP");
471 if (skinned) features.emplace_back("SKINNED");
472 if (lightmapped) features.emplace_back("MESH_LIGHTMAP");
473 // Only where its vertex stage writes the tangent varying (lit, and not a depth pass): a fragment that declares one it lacks fails to link.
474 if (tangents && normals && lit && !depthOnly) features.emplace_back("MESH_TANGENTS");
475 if (weightHeat) features.emplace_back("WEIGHT_HEAT");
476 if (depthOnly) features.emplace_back("SHADOW_DEPTH");
477 if (motion) features.emplace_back("ES_VELOCITY");
478 // Resident geometry owns its texture slots, so it is the vertex source that can
479 // carry a shadow map and a reflection — the batch stream's are a per-vertex
480 // merge product, and a sampler pinned there would read someone's sprite.
481 else if (lit) {
482 features.emplace_back("ES_RECEIVE_SHADOW");
483 if (envMapped) features.emplace_back("ES_ENV_MAP");
484 // Resident geometry's world position is the real one whether or not it
485 // carries normals: two separate facts, and reading a light's distance in
486 // the plane on a surface that HAS depth is the 2D convention misapplied.
487 features.emplace_back("ES_SURFACE_3D");
488 }
489 // After the receiving features, not between them and the `else` they hang from: a lit draw that writes the
490 // surface record still receives shadows and reflections.
491 if (gbuffer) features.emplace_back("ES_GBUFFER");
492 if (direct) features.emplace_back("ES_LIGHT_DIRECT");
493
494 // Authored as mesh.esshader, WGSL twin included. Its vertex stage is the one
495 // that reads a model matrix, which is what lets the vertices stay local.
496 const auto target = ctx.resources.preferredShaderTarget();
498 auto compile = [&](std::vector<std::string> features) -> u32 {
499 const bool normalMapped = std::find(features.begin(), features.end(), "NORMAL_MAP")
500 != features.end();
501 resource::ShaderHandle& handle = mesh_shaders_[variant];
502 handle = ctx.resources.createShaderWithBindings(
505 {}, ctx.resources.preferredShaderLanguage(), ctx.resources.deferLinks() && !compile_in_place_);
506 Shader* shader = ctx.resources.getShader(handle);
507 if (!shader || !shader->isValid()) return 0;
508 if (shader->language() == GfxShaderLanguage::GLSL_ES300) {
509 // After it links: at once, or (where shaders are not waited for) when a draw first needs it.
510 shader->whenLinked([normalMapped](Shader& s) {
511 s.bind();
512 // A depth-only variant has no colour texture to seed.
513 if (s.hasUniform("u_texture")) s.setUniform("u_texture", 0);
514 // Slot 1 is where a draw's own second texture is bound (see pushBatchDraw).
515 if (normalMapped) s.setUniform("u_normalMap", 1);
516 s.unbind();
517 });
518 }
519 return shader->getProgramId();
520 };
521 mesh_programs_[variant] = compile(features);
522 // Said to the store the draw list asks, so the pipeline of a draw on this program declares the second output.
523 if (gbuffer && mesh_programs_[variant] != 0 && ctx.materials) ctx.materials->markGBufferProgram(mesh_programs_[variant], /*albedo=*/true);
524 return mesh_programs_[variant];
525}
526
527u32 MeshPlugin::previewProgram(RenderFrameContext& ctx, u32 variant) {
528 // What the vertex source and the pass's outputs need, and nothing that shades: normals (1), skinning (8), the bake (64)
529 // and the surface record (256) stay; lighting (2), normal maps (4), reflections (32), tangents (1024) and direct light
530 // (2048) go. A depth or motion variant is never previewed.
531 const u32 preview = variant & (1u | 8u | 64u | 256u);
532 if (mesh_compiled_[preview]) return mesh_programs_[preview];
533 compile_in_place_ = true;
534 const u32 program = meshProgram(ctx, preview);
535 compile_in_place_ = false;
536 return program;
537}
538
540 const MeshProgramFacts* facts, u32 count,
541 bool shadowPasses, bool residentGeometry) {
543 const u32 materialsBefore = ctx.materials ? ctx.materials->builtVariantCount() : 0;
544 const bool envMapped = ctx.environment_texture_id != 0;
545 for (u32 i = 0; i < count; ++i) {
546 // Both purposes when the scene draws depth too: the same renderable is
547 // asked for twice with different keys, and readying only the camera's
548 // leaves the first shadow map to pay for the other.
549 for (u32 pass = 0; pass < 2; ++pass) {
550 const bool shadowDepth = pass == 1;
551 if (shadowDepth && (!shadowPasses || !residentGeometry)) continue;
552 const u32 variant = meshVariantFrom(facts[i], envMapped, shadowDepth, ctx.lighting_direct);
553 ++out.asks;
554 if (out.addKey(variant)) ++out.uniqueKeys;
555 if (!mesh_compiled_[variant]) ++out.compiles;
556 meshProgram(ctx, variant);
557 }
558 // The second lazily-compiled path. A fixture without materials would let
559 // readiness look complete while a material-shaded world still hitched.
560 if (facts[i].materialId != 0 && ctx.materials) {
561 ++out.materialAsks;
563 facts[i].materialId, facts[i].hasNormals, facts[i].skinned, envMapped,
564 facts[i].lightmapped, facts[i].tangents));
565 ctx.materials->meshProgram(facts[i].materialId, ctx.resources, facts[i].hasNormals,
566 facts[i].skinned, envMapped, facts[i].lightmapped, false, facts[i].tangents,
567 false, facts[i].opaque);
568 }
569 }
570 if (ctx.materials) {
571 out.materialCompiles = ctx.materials->builtVariantCount() - materialsBefore;
572 }
573 compiled_this_frame_ = 0;
574 return out;
575}
576
578 const MeshDocumentRecord* rows, u32 count,
579 bool shadowPasses) {
580 std::vector<MeshProgramFacts> facts;
581 facts.reserve(count);
582 bool anyResident = false;
583 for (u32 i = 0; i < count; ++i) {
584 if (rows[i].meshHandle == 0) continue;
585 anyResident = anyResident
586 || ctx.resources.getMesh(resource::MeshHandle(rows[i].meshHandle)) != nullptr;
587 facts.push_back(meshFactsFromDocument(ctx, rows[i], warned_bones_));
588 }
589 return prewarmFacts(ctx, facts.data(), static_cast<u32>(facts.size()), shadowPasses,
590 anyResident);
591}
592
594 const Entity* entities, u32 count, bool shadowPasses) {
595 std::vector<MeshProgramFacts> facts;
596 facts.reserve(count);
597 bool anyResident = false;
598 for (u32 i = 0; i < count; ++i) {
599 const Entity entity = entities[i];
600 const auto* mesh = registry.tryGet<ecs::MeshRenderer>(entity);
601 if (!mesh || !mesh->enabled) continue;
602 if (mesh->indices.empty() && !mesh->mesh.isValid()) continue;
603 const Mesh* resident = mesh->mesh.isValid() ? ctx.resources.getMesh(mesh->mesh) : nullptr;
604 anyResident = anyResident || resident != nullptr;
605 facts.push_back(
606 meshFactsFromEntity(ctx, registry, entity, *mesh, resident, warned_bones_));
607 }
608 return prewarmFacts(ctx, facts.data(), static_cast<u32>(facts.size()), shadowPasses,
609 anyResident);
610}
611
612MeshPlugin::Pose* MeshPlugin::poseOf(const RenderFrameContext& ctx, Entity entity, MeshProxy* kept, bool make) {
613 const u64 key = poseKey(ctx, entity);
614 if (kept && kept->pose && kept->poseKey == key && kept->poseGeneration == pose_generation_) return kept->pose;
615 Pose* pose = nullptr;
616 if (make) {
617 pose = &poses_[key];
618 } else {
619 const auto found = poses_.find(key);
620 if (found != poses_.end()) pose = &found->second;
621 }
622 if (kept && pose) {
623 kept->pose = pose;
624 kept->poseKey = key;
625 kept->poseGeneration = pose_generation_;
626 }
627 return pose;
628}
629
630void MeshPlugin::trackPose(Pose& pose, const RenderFrameContext& ctx, const glm::mat4& model,
631 const std::vector<glm::mat4>* bones) {
632 // Last frame's, when the view drew this mesh last frame; otherwise it has no past worth following, and
633 // standing where it stands says "did not move".
634 const bool continued = pose.frame != 0 && pose.frame + 1 == ctx.motion_frame;
635 if (continued) {
636 // Where it was drawn from the origin of the frame before, as it is placed from the origin now.
637 pose.previous = modelFromOrigin(pose.current, pose.origin);
638 pose.bonesPrevious = pose.bonesCurrent;
639 for (glm::mat4& bone : pose.bonesPrevious) bone = modelFromOrigin(bone, pose.origin);
640 } else if (pose.frame != ctx.motion_frame) {
641 pose.previous = model;
642 if (bones) pose.bonesPrevious = *bones;
643 else pose.bonesPrevious.clear();
644 }
645 pose.current = model;
646 if (bones) pose.bonesCurrent = *bones;
647 else pose.bonesCurrent.clear();
648 pose.frame = ctx.motion_frame;
649 pose.origin = renderOrigin();
650}
651
652void MeshPlugin::addMover(Entity entity) {
653 const u32 index = entity.index();
654 if (index >= mover_at_.size()) mover_at_.resize(static_cast<usize>(index) + 1, 0);
655 movers_.push_back(entity);
656 mover_at_[index] = static_cast<u32>(movers_.size());
657}
658
659void MeshPlugin::clearMovers() {
660 for (const Entity e : movers_) mover_at_[e.index()] = 0;
661 movers_.clear();
662}
663
664bool MeshPlugin::dropStillMovers() {
665 constexpr u32 kStillLooks = 240;
666 bool dropped = false;
667 for (usize i = 0; i < movers_.size();) {
668 const Entity e = movers_[i];
669 const u32 index = e.index();
670 const u64 seen = index < cast_changed_at_.size() ? cast_changed_at_[index] : 0;
671 const bool same = static_cast<u32>(seen >> 32) == e.id();
672 if (same && cast_look_ - static_cast<u32>(seen) < kStillLooks) { ++i; continue; }
673 mover_at_[index] = 0;
674 movers_[i] = movers_.back();
675 movers_.pop_back();
676 if (i < movers_.size()) mover_at_[movers_[i].index()] = static_cast<u32>(i + 1);
677 dropped = true;
678 }
679 return dropped;
680}
681
683 key = cast_held_key_;
684 return cast_held_vouched_;
685}
686
688 const u32 now = registry.beginChangeRead();
689 if (++cast_look_ == 0) cast_look_ = 1;
690 u32 why = 0;
691 bool heldMoved = false;
692 if (registry.identity() != cast_registry_) {
693 why |= 1u;
694 clearMovers();
695 cast_changed_at_.clear();
696 }
697 if (registry.activityEpoch() != cast_activity_) why |= 2u;
698 if (why == 0) {
699 const u32 since = cast_tick_;
700 if (registry.anyChangedSince<ecs::MeshRenderer>(since)) why |= 4u;
701 if (registry.anyChangedSince<ecs::MeshSkin>(since) || registry.anyChangedSince<ecs::MeshMorph>(since)) why |= 8u;
702 if (registry.anyChangedSince<ecs::MeshInstances>(since) || registry.anyChangedSince<ecs::LODGroup>(since)
703 || registry.anyChangedSince<ecs::Billboard>(since) || registry.anyChangedSince<ecs::Impostor>(since)
704 || registry.anyChangedSince<ecs::MeshLightmap>(since)) {
705 why |= 16u;
706 }
707 if (why == 0 && registry.countOf<ecs::MeshSkin>() > 0) {
708 if (registry.anyChangedSince<ecs::Transform>(since)) why |= 32u;
709 } else if (why == 0) {
710 constexpr u32 kRecentLooks = 8;
711 registry.anyChangedSinceWhere<ecs::Transform>(since, [&](Entity e) {
712 if (!registry.has<ecs::MeshRenderer>(e)) return false;
713 why |= 64u;
714 const u32 index = e.index();
715 if (index >= cast_changed_at_.size()) cast_changed_at_.resize(static_cast<usize>(index) + 1, 0);
716 const u64 seen = cast_changed_at_[index];
717 const bool recent = static_cast<u32>(seen >> 32) == e.id() && cast_look_ - static_cast<u32>(seen) <= kRecentLooks;
718 cast_changed_at_[index] = (static_cast<u64>(e.id()) << 32) | cast_look_;
719 if (isMover(e)) return false;
720 heldMoved = true;
721 if (recent) addMover(e);
722 return false;
723 });
724 }
725 }
726 if ((why & 63u) || heldMoved) ++cast_held_serial_;
727 if (!movers_.empty() && cast_look_ % 60 == 0 && dropStillMovers()) ++cast_held_serial_;
728 if (registry.countOf<ecs::LODGroup>() > 0) why |= 128u;
729 ES_PROFILE_COUNTER("render.mesh.castChanged", why);
730 ES_PROFILE_COUNTER("render.mesh.castMovers", static_cast<u32>(movers_.size()));
731 if (why & 127u) ++cast_serial_;
732 cast_registry_ = registry.identity();
733 cast_activity_ = registry.activityEpoch();
734 cast_tick_ = now;
735 cast_held_vouched_ = false;
736 if (registry.countOf<ecs::LODGroup>() > 0) return false;
737
739 const auto mix = [&h](u64 v) { h = hash::combine(h, v); };
740 mix(registry.identity());
741 mix(ctx.materials ? ctx.materials->revision() : 0);
742 mix(ctx.materials ? ctx.materials->builtVariantCount() : 0);
743 mix(ctx.resources.meshesRevision());
744 mix(programs_built_);
745 mix(ctx.render_context.programEpoch());
746 mix(ctx.environment_texture_id != 0 ? 1u : 0u);
747 mix(ctx.batch_shader_id);
748 mix(ctx.white_texture_id);
749 const glm::dvec3 origin = renderOrigin();
750 u64 bits[3];
751 std::memcpy(bits, &origin, sizeof(bits));
752 mix(bits[0]); mix(bits[1]); mix(bits[2]);
753 u32 eye[3];
754 std::memcpy(eye, &ctx.view_eye, sizeof(eye));
755 mix(ctx.has_view_eye ? (static_cast<u64>(eye[0]) << 32 | eye[1]) ^ (static_cast<u64>(eye[2]) << 16) : 0u);
756 key = hash::combine(h, cast_serial_);
757 cast_held_key_ = hash::combine(hash::combine(h, 0x48454c44ull), cast_held_serial_);
758 cast_held_vouched_ = true;
759 return true;
760}
761
762void MeshPlugin::deriveProxy(RenderCollectContext& collect, MeshProxy& proxy, Entity entity, const ecs::MeshRenderer& mesh,
763 ecs::Transform& transform, u8 present, u32 now) {
764 auto& ctx = collect.frame_context;
765 proxy = MeshProxy{};
766 proxy.entity = entity;
767 proxy.builtAt = now;
768 proxy.presentAt = now;
769 proxy.epoch = proxy_epoch_;
770 proxy.present = present;
771 proxy.resident = mesh.mesh.isValid() ? ctx.resources.getMesh(mesh.mesh) : nullptr;
772 proxy.meshRevision = proxy.resident ? proxy.resident->revision : 0;
773 proxy.materialStore = ctx.materials ? ctx.materials->revision() : 0;
774 proxy.material = mesh.material != 0 && ctx.materials ? ctx.materials->find(mesh.material) : nullptr;
775 proxy.materialRevision = proxy.material ? proxy.material->revision : 0;
776 const ecs::MeshInstances* set = present == 2u ? collect.registry.tryGet<ecs::MeshInstances>(entity) : nullptr;
777 proxy.kept = (present == 0 || set != nullptr) && proxy.resident != nullptr && mesh.parallax == glm::vec2(1.0f);
778 if (!proxy.kept) return;
779 transform.ensureDecomposed();
780 proxy.position = rebased(transform.worldPosition);
781 proxy.rotation = transform.worldRotation;
782 proxy.scale = transform.worldScale;
783 proxy.bend = proxy.material ? ctx.materials->vertexBounds(mesh.material) : 0.0f;
784 proxy.depthTested = mesh.opaque || (proxy.material && proxy.material->depthTest);
785 proxy.model = glm::translate(glm::mat4(1.0f), proxy.position) * glm::mat4_cast(proxy.rotation)
786 * glm::scale(glm::mat4(1.0f), proxy.scale);
787 proxy.normalRows = glm::transpose(glm::inverse(glm::mat3(proxy.model)));
788 proxy.facts = meshFactsFromEntity(ctx, collect.registry, entity, mesh, proxy.resident, warned_bones_);
789 proxy.facts.normalTextureId = 0;
790 if (!set) {
791 const glm::vec3 padding(proxy.bend);
792 orientedWorldAabb(proxy.position, proxy.rotation, proxy.scale, proxy.resident->localMin - padding,
793 proxy.resident->localMax + padding, proxy.boxCentre, proxy.boxHalf);
794 return;
795 }
796 proxy.placed = true;
797 proxy.coarse = placementCoarseMesh(ctx.resources, *proxy.resident, *set);
798 proxy.coarseRevision = proxy.coarse ? proxy.coarse->revision : 0;
799 glm::vec3 lo, hi;
800 meshLocalBounds(*proxy.resident, proxy.coarse, proxy.bend, lo, hi);
801 const f32 placementRadius = placement_bounds::radius(lo, hi, 0.0f);
802 const glm::vec3 localCentre = (lo + hi) * 0.5f;
803 const glm::vec3 localHalf = (hi - lo) * 0.5f;
804 const glm::vec3 reach(placementRadius * set->maxScale);
805 orientedWorldAabb(proxy.position, proxy.rotation, proxy.scale, set->originMin - reach, set->originMax + reach,
806 proxy.boxCentre, proxy.boxHalf);
807 const glm::mat4& entityModel = proxy.model;
808 const glm::mat3 entityLinear(entityModel);
809 const u32 count = static_cast<u32>(set->transforms.size() / 16);
810 proxy.instances.resize(count);
811 proxy.records.assign(static_cast<usize>(count) * MESH_INSTANCE_STRIDE, 0);
812 for (u32 i = 0; i < count; ++i) {
813 const f32* r = set->transforms.data() + static_cast<usize>(i) * 16;
814 PlacedInstance& inst = proxy.instances[i];
815 inst.at = glm::vec3(entityModel * glm::vec4(r[3], r[7], r[11], 1.0f));
816 placement_bounds::transformedBox(entityLinear, r, inst.at, localCentre, localHalf, inst.centre, inst.half);
817 inst.radius = glm::length(inst.half);
818 inst.grow = std::sqrt(std::max({r[0] * r[0] + r[4] * r[4] + r[8] * r[8], r[1] * r[1] + r[5] * r[5] + r[9] * r[9],
819 r[2] * r[2] + r[6] * r[6] + r[10] * r[10]}));
820 u8* dst = proxy.records.data() + static_cast<usize>(i) * MESH_INSTANCE_STRIDE;
821 glm::mat4 placed(1.0f);
822 placed[0] = {r[0], r[4], r[8], 0.0f};
823 placed[1] = {r[1], r[5], r[9], 0.0f};
824 placed[2] = {r[2], r[6], r[10], 0.0f};
825 placed[3] = {r[3], r[7], r[11], 1.0f};
826 const glm::mat4 model = entityModel * placed;
827 for (u32 row = 0; row < 3; ++row) {
828 const glm::vec4 m{model[0][row], model[1][row], model[2][row], model[3][row]};
829 std::memcpy(dst + (MESH_INSTANCE_TEXEL_MODEL + row) * 16, &m, 16);
830 }
831 const glm::vec4 tint = mesh.color * glm::vec4(r[12], r[13], r[14], r[15]);
832 std::memcpy(dst + MESH_INSTANCE_TEXEL_TINT * 16, &tint, 16);
833 if (proxy.resident->hasNormals) {
834 const glm::mat3 nrm = glm::transpose(glm::inverse(glm::mat3(model)));
835 for (u32 row = 0; row < 3; ++row) std::memcpy(dst + (MESH_INSTANCE_TEXEL_NORMAL + row) * 16, &nrm[row][0], 12);
836 }
837 }
838}
839
840MeshPlugin::MeshProxy* MeshPlugin::retain(RenderCollectContext& collect, Entity entity, const ecs::MeshRenderer& mesh,
841 ecs::Transform& transform, u32 now, u32 rulesChangedAt) {
842 auto& registry = collect.registry;
843 auto& ctx = collect.frame_context;
844 const u32 index = entity.index();
845 if (index >= proxy_slot_.size()) proxy_slot_.resize(static_cast<usize>(index) + 1, ~0u);
846 u32& slot = proxy_slot_[index];
847 if (slot == ~0u) {
848 slot = static_cast<u32>(proxies_.size());
849 proxies_.emplace_back();
850 }
851 MeshProxy& proxy = proxies_[slot];
852
853 const Mesh* resident = mesh.mesh.isValid() ? ctx.resources.getMesh(mesh.mesh) : nullptr;
854 bool stale = proxy.entity != entity || proxy.epoch != proxy_epoch_
855 || resident != proxy.resident || (resident && resident->revision != proxy.meshRevision)
856 || registry.changedSince<ecs::Transform>(entity, proxy.builtAt)
857 || registry.changedSince<ecs::MeshRenderer>(entity, proxy.builtAt)
858 || (proxy.placed && registry.changedSince<ecs::MeshInstances>(entity, proxy.builtAt));
859 if (!stale && proxy.placed) {
860 const auto* set = registry.tryGet<ecs::MeshInstances>(entity);
861 const Mesh* coarse = set ? placementCoarseMesh(ctx.resources, *resident, *set) : nullptr;
862 stale = !set || coarse != proxy.coarse || (coarse && coarse->revision != proxy.coarseRevision);
863 }
864 const u64 store = ctx.materials ? ctx.materials->revision() : 0;
865 if (!stale && store != proxy.materialStore) {
866 const MaterialRecord* material = mesh.material != 0 && ctx.materials ? ctx.materials->find(mesh.material) : nullptr;
867 stale = material != proxy.material || (material && material->revision != proxy.materialRevision);
868 if (!stale) proxy.materialStore = store;
869 }
870 // A component that rules keeping out was added or removed somewhere since this one looked: is it this entity's?
871 u8 present = proxy.present;
872 bool looked = false;
873 if (!stale && rulesChangedAt != 0 && ecs::tickAfter(rulesChangedAt, proxy.presentAt)) {
874 present = ruledOut(registry, entity);
875 looked = true;
876 stale = present != proxy.present;
877 proxy.presentAt = now;
878 }
879 if (stale) {
880 deriveProxy(collect, proxy, entity, mesh, transform, looked ? present : ruledOut(registry, entity), now);
881 ++proxies_built_;
882 } else if (proxy.kept) {
883 ++proxies_kept_;
884 // With the change audit on, what is kept is checked against what the components derive now: a difference is a write
885 // that nothing stamped, and a draw that stands where the entity no longer does.
886 if (registry.changeAuditEnabled()) {
887 MeshProxy fresh;
888 deriveProxy(collect, fresh, entity, mesh, transform, ruledOut(registry, entity), now);
889 // By bits: a mesh scaled to nothing has a normal matrix of NaN, which equals nothing, itself included, though
890 // the same inputs give the same bits.
891 const auto bits = [](const auto& a, const auto& b) { return std::memcmp(&a, &b, sizeof(a)) == 0; };
892 const bool same = fresh.kept && fresh.resident == proxy.resident && fresh.material == proxy.material
893 && bits(fresh.position, proxy.position) && bits(fresh.rotation, proxy.rotation) && bits(fresh.scale, proxy.scale)
894 && bits(fresh.boxCentre, proxy.boxCentre) && bits(fresh.boxHalf, proxy.boxHalf) && bits(fresh.model, proxy.model)
895 && bits(fresh.normalRows, proxy.normalRows) && bits(fresh.bend, proxy.bend) && fresh.depthTested == proxy.depthTested
896 && fresh.facts.hasNormals == proxy.facts.hasNormals && fresh.facts.lit == proxy.facts.lit
897 && fresh.facts.skinned == proxy.facts.skinned && fresh.facts.lightmapped == proxy.facts.lightmapped
898 && fresh.facts.tangents == proxy.facts.tangents && fresh.facts.opaque == proxy.facts.opaque
899 && fresh.facts.materialId == proxy.facts.materialId
900 && fresh.placed == proxy.placed && fresh.coarse == proxy.coarse && fresh.records == proxy.records
901 && fresh.instances.size() == proxy.instances.size()
902 && (fresh.instances.empty()
903 || std::memcmp(fresh.instances.data(), proxy.instances.data(), fresh.instances.size() * sizeof(PlacedInstance)) == 0);
904 if (!same) {
905 ++proxies_stale_total_;
906 if (!warned_stale_) {
907 warned_stale_ = true;
908 ES_LOG_WARN("change audit: a kept mesh draw (entity {}) is not what its components derive now - something it"
909 " is derived from changed without a stamp or a revision", entity.index());
910 }
911 proxy = fresh;
912 }
913 }
914 }
915 return proxy.kept ? &proxy : nullptr;
916}
917
918namespace {
926void emitImpostorCard(RenderCollectContext& collect, const RenderFrame::ImpostorAtlas& atlas, const ecs::MeshRenderer& mesh,
927 Entity entity, const glm::vec3& centre, f32 radius, const glm::quat& rotation) {
928 const glm::vec4 eye = collect.camera.eye;
929 glm::vec3 toward = eye.w > 0.5f ? glm::vec3(eye) - centre : glm::vec3(eye);
930 if (glm::dot(toward, toward) < 1e-12f) return;
931 const glm::vec3 local = glm::inverse(rotation) * glm::normalize(toward);
932 const glm::uvec2 frame = impostor::nearestFrame(local, atlas.frames);
933 const glm::vec3 d = impostor::frameDirection(frame.x, frame.y, atlas.frames);
934 const glm::vec3 upLocal = impostor::pictureUp(d);
935 const glm::vec3 up = rotation * upLocal * radius;
936 const glm::vec3 right = rotation * glm::cross(upLocal, d) * radius;
937 const f32 n = static_cast<f32>(atlas.frames);
938 const f32 u0 = static_cast<f32>(frame.x) / n, u1 = static_cast<f32>(frame.x + 1u) / n;
939 const f32 v0 = static_cast<f32>(frame.y) / n, v1 = static_cast<f32>(frame.y + 1u) / n;
940 const BatchVertex quad[4] = {
941 {centre - right - up, 0xFFFFFFFFu, {u0, v0}},
942 {centre + right - up, 0xFFFFFFFFu, {u1, v0}},
943 {centre + right + up, 0xFFFFFFFFu, {u1, v1}},
944 {centre - right + up, 0xFFFFFFFFu, {u0, v1}},
945 };
946 // Blended over what is behind it, the picture's empty corners being transparent, and depth-tested so a nearer wall hides it.
947 BatchDrawKey key{
949 .layer = mesh.layer,
950 .shaderId = collect.frame_context.batch_shader_id,
951 .blend = BlendMode::Normal,
952 .textureId = atlas.texture,
953 .depth = collect.camera.viewDepth(centre),
954 .y = centre.y,
955 .entity = entity,
956 .type = RenderType::Mesh,
957 };
958 key.depthTest = true;
959 key.depthWrite = false;
960 appendQuad(collect.buffer_pool, collect.draw_list, collect.clip_state, quad, key);
961}
962
978struct PlacementReach {
979 f32 fine = 0.0f;
980 f32 coarse = 0.0f;
981};
982
984constexpr f32 kWholeTexture = 1.0e9f;
985
993f32 textureSideFor(const RenderFrameContext& ctx, f32 sizeOverDistance, f32 uvDensity) {
994 if (!(sizeOverDistance > 0.0f) || !ctx.frame) return 0.0f;
995 // Drawn, but with no density to say how much of a texture it holds: it asks for the whole file. Asking for nothing left a
996 // texture that started small at its start size for as long as it was on screen.
997 if (!(uvDensity > 0.0f)) return kWholeTexture;
998 const glm::mat4& vp = ctx.view_projection;
999 const f32 ndcPerUnit = glm::length(glm::vec3(vp[0][1], vp[1][1], vp[2][1]));
1000 return ndcPerUnit * 0.5f * ctx.frame->viewHeightPx() * sizeOverDistance / uvDensity;
1001}
1002
1004void wantTexturesOf(const RenderFrameContext& ctx, const ecs::MeshRenderer& mesh, const MaterialRecord* material, f32 side) {
1005 if (!(side > 0.0f) || !ctx.frame) return;
1006 if (mesh.texture.isValid()) ctx.frame->wantTextureSide(mesh.texture.id(), side);
1007 if (mesh.normalMap.isValid()) ctx.frame->wantTextureSide(mesh.normalMap.id(), side);
1008 if (material) for (const auto& b : material->textures) if (b.texture.isValid()) ctx.frame->wantTextureSide(b.texture.id(), side);
1009}
1010
1011template <typename Emit>
1012void emitPlacements(const RenderFrameContext& ctx, RenderCollectContext& collect, const ecs::MeshInstances& set,
1013 const ecs::MeshRenderer& mesh, const glm::vec3& position, const glm::quat& rotation,
1014 const glm::vec3& scale, const Mesh& fine, const Mesh* coarse,
1015 const glm::vec3& localCentre, const glm::vec3& localHalf, u32& records, PlacementReach& reach,
1016 Emit&& emit) {
1017 static thread_local std::vector<u32> nearList, farList;
1018 nearList.clear();
1019 farList.clear();
1020 const glm::mat4 entityModel = glm::translate(glm::mat4(1.0f), position) * glm::mat4_cast(rotation) * glm::scale(glm::mat4(1.0f), scale);
1021 const glm::mat3 entityLinear(entityModel);
1022 const bool eyeKnown = ctx.has_view_eye;
1023 const u32 count = static_cast<u32>(set.transforms.size() / 16);
1024 u32 tooFar = 0, outside = 0;
1025 // Only a scene view's pixels say how much texture is needed; a shadow map's texels are nobody's.
1026 const bool measuring = eyeKnown && ctx.purpose == RenderPurpose::Scene;
1027 const f32 entityGrow = std::max({std::abs(scale.x), std::abs(scale.y), std::abs(scale.z)});
1028 reach = {};
1029 for (u32 i = 0; i < count; ++i) {
1030 const f32* r = set.transforms.data() + static_cast<usize>(i) * 16;
1031 const glm::vec3 at = glm::vec3(entityModel * glm::vec4(r[3], r[7], r[11], 1.0f));
1032 glm::vec3 centre, half;
1033 placement_bounds::transformedBox(entityLinear, r, at, localCentre, localHalf, centre, half);
1034 const f32 radius = glm::length(half);
1035 f32 distance = 0.0f;
1036 if (eyeKnown) {
1037 distance = glm::distance(at, ctx.view_eye);
1038 const f32 centreDistance = glm::distance(centre, ctx.view_eye);
1039 if (set.drawDistance > 0.0f && centreDistance - radius > set.drawDistance) { ++tooFar; continue; }
1040 if (centreDistance + radius < set.minDistance) continue;
1041 if (ctx.purpose == RenderPurpose::ShadowDepth && set.shadowDistance > 0.0f && centreDistance - radius > set.shadowDistance) continue;
1042 }
1043 if (!collect.visible(centre, half, false)) { ++outside; continue; }
1044 if (ctx.purpose == RenderPurpose::ShadowDepth && !collect.castsIntoView(centre, radius)) { ++outside; continue; }
1045 const bool far = coarse && eyeKnown && set.lodDistance > 0.0f && distance > set.lodDistance;
1046 (far ? farList : nearList).push_back(i);
1047 if (measuring) {
1048 // The placement's own scale is the longest column of its 3x3, read as the record is written below.
1049 const f32 placedGrow = std::sqrt(std::max({r[0] * r[0] + r[4] * r[4] + r[8] * r[8],
1050 r[1] * r[1] + r[5] * r[5] + r[9] * r[9],
1051 r[2] * r[2] + r[6] * r[6] + r[10] * r[10]}));
1052 const f32 gap = std::max(glm::distance(centre, ctx.view_eye) - radius, 1e-3f);
1053 f32& best = far ? reach.coarse : reach.fine;
1054 best = std::max(best, entityGrow * placedGrow / gap);
1055 }
1056 }
1057 ES_PROFILE_COUNTER("render.placements.seen", count);
1058 ES_PROFILE_COUNTER("render.placements.tooFar", tooFar);
1059 ES_PROFILE_COUNTER("render.placements.outside", outside);
1060 ES_PROFILE_COUNTER("render.placements.coarse", farList.size());
1061 ES_PROFILE_COUNTER("render.placements.eye", eyeKnown ? 1 : 0);
1062 // The frame's record texture holds so many; past it the tail would draw unplaced, which is worse than not at all.
1063 const u32 room = records < MESH_INSTANCE_MAX_RECORDS ? MESH_INSTANCE_MAX_RECORDS - records : 0;
1064 if (nearList.size() > room) nearList.resize(room);
1065 if (farList.size() > room - nearList.size()) farList.resize(room - nearList.size());
1066 records += static_cast<u32>(nearList.size() + farList.size());
1067
1068 auto& buffers = collect.buffer_pool;
1069 const auto write = [&](const std::vector<u32>& list, const Mesh& geo) {
1070 if (list.empty()) return;
1071 const u32 offset = buffers.allocVertices(LayoutId::MeshInstance, MESH_INSTANCE_STRIDE * static_cast<u32>(list.size()));
1072 auto* dst = buffers.vertexData(LayoutId::MeshInstance) + offset;
1073 std::memset(dst, 0, static_cast<usize>(MESH_INSTANCE_STRIDE) * list.size());
1074 for (const u32 i : list) {
1075 const f32* r = set.transforms.data() + static_cast<usize>(i) * 16;
1076 glm::mat4 placed(1.0f);
1077 placed[0] = {r[0], r[4], r[8], 0.0f};
1078 placed[1] = {r[1], r[5], r[9], 0.0f};
1079 placed[2] = {r[2], r[6], r[10], 0.0f};
1080 placed[3] = {r[3], r[7], r[11], 1.0f};
1081 const glm::mat4 model = entityModel * placed;
1082 for (u32 row = 0; row < 3; ++row) {
1083 const glm::vec4 m{model[0][row], model[1][row], model[2][row], model[3][row]};
1084 std::memcpy(dst + (MESH_INSTANCE_TEXEL_MODEL + row) * 16, &m, 16);
1085 }
1086 const glm::vec4 tint = mesh.color * glm::vec4(r[12], r[13], r[14], r[15]);
1087 std::memcpy(dst + MESH_INSTANCE_TEXEL_TINT * 16, &tint, 16);
1088 if (geo.hasNormals) {
1089 const glm::mat3 nrm = glm::transpose(glm::inverse(glm::mat3(model)));
1090 for (u32 row = 0; row < 3; ++row) std::memcpy(dst + (MESH_INSTANCE_TEXEL_NORMAL + row) * 16, &nrm[row][0], 12);
1091 }
1092 dst += MESH_INSTANCE_STRIDE;
1093 }
1094 emit(geo, offset, static_cast<u32>(list.size()));
1095 };
1096 write(nearList, fine);
1097 if (coarse) write(farList, *coarse);
1098}
1099
1100template <typename Instance, typename Emit>
1101void emitKeptPlacements(const RenderFrameContext& ctx, RenderCollectContext& collect, const ecs::MeshInstances& set,
1102 const std::vector<Instance>& instances, const std::vector<u8>& cached, const glm::vec3& scale,
1103 const Mesh& fine, const Mesh* coarse, u32& records, PlacementReach& reach, Emit&& emit) {
1104 static thread_local std::vector<u32> nearList, farList;
1105 nearList.clear();
1106 farList.clear();
1107 const bool eyeKnown = ctx.has_view_eye;
1108 const u32 count = static_cast<u32>(instances.size());
1109 u32 tooFar = 0, outside = 0;
1110 const bool measuring = eyeKnown && ctx.purpose == RenderPurpose::Scene;
1111 const f32 entityGrow = std::max({std::abs(scale.x), std::abs(scale.y), std::abs(scale.z)});
1112 reach = {};
1113 for (u32 i = 0; i < count; ++i) {
1114 const Instance& inst = instances[i];
1115 f32 distance = 0.0f;
1116 if (eyeKnown) {
1117 distance = glm::distance(inst.at, ctx.view_eye);
1118 const f32 centreDistance = glm::distance(inst.centre, ctx.view_eye);
1119 if (set.drawDistance > 0.0f && centreDistance - inst.radius > set.drawDistance) { ++tooFar; continue; }
1120 if (centreDistance + inst.radius < set.minDistance) continue;
1121 if (ctx.purpose == RenderPurpose::ShadowDepth && set.shadowDistance > 0.0f && centreDistance - inst.radius > set.shadowDistance) continue;
1122 }
1123 if (!collect.visible(inst.centre, inst.half, false)) { ++outside; continue; }
1124 if (ctx.purpose == RenderPurpose::ShadowDepth && !collect.castsIntoView(inst.centre, inst.radius)) { ++outside; continue; }
1125 const bool far = coarse && eyeKnown && set.lodDistance > 0.0f && distance > set.lodDistance;
1126 (far ? farList : nearList).push_back(i);
1127 if (measuring) {
1128 const f32 gap = std::max(glm::distance(inst.centre, ctx.view_eye) - inst.radius, 1e-3f);
1129 f32& best = far ? reach.coarse : reach.fine;
1130 best = std::max(best, entityGrow * inst.grow / gap);
1131 }
1132 }
1133 ES_PROFILE_COUNTER("render.placements.seen", count);
1134 ES_PROFILE_COUNTER("render.placements.tooFar", tooFar);
1135 ES_PROFILE_COUNTER("render.placements.outside", outside);
1136 ES_PROFILE_COUNTER("render.placements.coarse", farList.size());
1137 ES_PROFILE_COUNTER("render.placements.eye", eyeKnown ? 1 : 0);
1138 const u32 room = records < MESH_INSTANCE_MAX_RECORDS ? MESH_INSTANCE_MAX_RECORDS - records : 0;
1139 if (nearList.size() > room) nearList.resize(room);
1140 if (farList.size() > room - nearList.size()) farList.resize(room - nearList.size());
1141 records += static_cast<u32>(nearList.size() + farList.size());
1142
1143 auto& buffers = collect.buffer_pool;
1144 const auto write = [&](const std::vector<u32>& list, const Mesh& geo) {
1145 if (list.empty()) return;
1146 const u32 offset = buffers.allocVertices(LayoutId::MeshInstance, MESH_INSTANCE_STRIDE * static_cast<u32>(list.size()));
1147 auto* dst = buffers.vertexData(LayoutId::MeshInstance) + offset;
1148 for (const u32 i : list) {
1149 std::memcpy(dst, cached.data() + static_cast<usize>(i) * MESH_INSTANCE_STRIDE, MESH_INSTANCE_STRIDE);
1150 dst += MESH_INSTANCE_STRIDE;
1151 }
1152 emit(geo, offset, static_cast<u32>(list.size()));
1153 };
1154 write(nearList, fine);
1155 if (coarse) write(farList, *coarse);
1156}
1157} // namespace
1158
1160constexpr f32 kClusterPixelError = 1.0f;
1166
1167bool MeshPlugin::clusterInspect(u32 entityId, u32& triangles, u32& clusters) const {
1168 const auto it = cluster_cuts_.find(entityId);
1169 if (it == cluster_cuts_.end() || !it->second.picked || it->second.usedAt + kClusterCutFreshCollects < cluster_serial_) {
1170 return false;
1171 }
1172 triangles = it->second.indexCount / 3;
1173 clusters = it->second.clusters;
1174 return true;
1175}
1176
1177const MeshPlugin::ClusterCut* MeshPlugin::clusterCut(RenderCollectContext& collect, Entity entity, const Mesh& mesh,
1178 const glm::vec3& position, const glm::quat& rotation, const glm::vec3& scale) {
1179 const RenderFrameContext& ctx = collect.frame_context;
1180 GfxDevice& device = collect.buffer_pool.device();
1181 const lod::ClusterHierarchy& hierarchy = *mesh.clusters;
1182 ClusterCut& cut = cluster_cuts_[entity.id()];
1183 cut.usedAt = cluster_serial_;
1184
1185 // The eye in the mesh's own space, where the bounds are stored. An error over a distance is the same ratio in either
1186 // space under one scale for every axis; under three, the largest is the one that shows the most.
1187 const glm::vec3 grow = glm::max(glm::abs(scale), glm::vec3(1e-12f));
1188 const f32 largest = std::max({grow.x, grow.y, grow.z});
1189 lod::ClusterEye eye;
1190 eye.flat = cluster_flat_;
1191 eye.scale = cluster_flat_ ? cluster_scale_ * largest : cluster_scale_;
1192 eye.threshold = kClusterPixelError / std::max(ctx.frame ? ctx.frame->lodDistanceScale() : 1.0f, 1e-3f);
1193 if (ctx.has_view_eye) {
1194 const glm::vec3 offset = glm::inverse(rotation) * (ctx.view_eye - position);
1195 eye.position = glm::vec3(scale.x < 0.0f ? -offset.x : offset.x, scale.y < 0.0f ? -offset.y : offset.y,
1196 scale.z < 0.0f ? -offset.z : offset.z) / grow;
1197 } else {
1198 // No eye to measure from: as if it stood on the surface, which asks for the mesh's own triangles.
1199 eye.flat = true;
1200 eye.scale = std::numeric_limits<f32>::max();
1201 }
1202
1203 const bool stored = cut.buffer != BufferHandle::Invalid && cut.mesh == &mesh && cut.meshRevision == mesh.revision
1204 && cut.deviceGeneration == device.deviceGeneration();
1205 if (stored && cut.picked && cut.eye.position == eye.position && cut.eye.scale == eye.scale
1206 && cut.eye.threshold == eye.threshold && cut.eye.flat == eye.flat) {
1207 return &cut;
1208 }
1209
1210 const u32 indexCount = lod::selectClusters(hierarchy, eye, cluster_picked_);
1211 const u64 signature = lod::cutSignature(cluster_picked_);
1212 if (!stored || signature != cut.signature || indexCount != cut.indexCount) {
1213 lod::assembleCut(hierarchy, cluster_picked_, mesh.arenaFirstVertex, cluster_indices_);
1214 const u32 bytes = indexCount * static_cast<u32>(sizeof(u32));
1215 if (cut.buffer != BufferHandle::Invalid && cut.deviceGeneration == device.deviceGeneration() && indexCount <= cut.capacity) {
1216 device.updateBuffer(cut.buffer, 0, cluster_indices_.data(), bytes);
1217 } else {
1218 // Room to spare: an eye that walks toward a mesh asks for a little more each time, and a buffer made to fit
1219 // would be made again at every step.
1220 const u32 capacity = std::min(indexCount + indexCount / 2 + 3 * 128, static_cast<u32>(hierarchy.indices.size()));
1221 cluster_indices_.resize(capacity, 0);
1222 BufferDesc desc;
1223 desc.usage = GfxBufferUsage::Index;
1224 desc.size = capacity * static_cast<u32>(sizeof(u32));
1225 desc.dynamic = true;
1226 if (cut.buffer != BufferHandle::Invalid) {
1227 device.resizeBuffer(cut.buffer, desc.size, cluster_indices_.data());
1228 } else {
1229 // Rewritten whenever the pick changes, and again from here after a device loss: nothing has to keep its bytes.
1230 cut.buffer = device.createBuffer(desc, GfxContent::transient(), cluster_indices_.data());
1231 }
1232 if (cut.buffer == BufferHandle::Invalid) {
1233 cut = ClusterCut{};
1234 return nullptr;
1235 }
1236 cut.capacity = capacity;
1237 }
1238 cut.signature = signature;
1239 cut.indexCount = indexCount;
1240 cut.clusters = static_cast<u32>(cluster_picked_.size());
1241 cut.ids = cluster_picked_;
1242 ++cluster_rebuilt_;
1243 }
1244 cut.mesh = &mesh;
1245 cut.meshRevision = mesh.revision;
1246 cut.deviceGeneration = device.deviceGeneration();
1247 cut.eye = eye;
1248 cut.picked = true;
1249 return &cut;
1250}
1251
1253 auto& registry = collect_ctx.registry;
1254 auto& clips = collect_ctx.clip_state;
1255 auto& buffers = collect_ctx.buffer_pool;
1256 auto& draw_list = collect_ctx.draw_list;
1257 auto& ctx = collect_ctx.frame_context;
1258 auto meshView = registry.activeView<ecs::Transform, ecs::MeshRenderer>();
1259 // Read once: the phase is the same for every mesh this collect walks.
1260 const bool shadowDepth = ctx.purpose == RenderPurpose::ShadowDepth;
1261 // The motion pass draws the same meshes a second time, only those that moved, with no material and no light
1262 // — what shadows and motion have in common is that neither is the surface's own look.
1263 const bool motion = ctx.purpose == RenderPurpose::Motion;
1264 const bool depthPass = shadowDepth || motion;
1265 ++cluster_serial_;
1266 if (ctx.purpose == RenderPurpose::Scene) {
1267 // What an error measures in this view: NDC y per world unit is the length of the view-projection's second row under
1268 // both projections, and half the view's pixels span one unit of NDC. An orthographic view's fourth row has no
1269 // direction in it: nothing there shrinks with distance.
1270 const glm::mat4& vp = ctx.view_projection;
1271 cluster_scale_ = glm::length(glm::vec3(vp[0][1], vp[1][1], vp[2][1])) * 0.5f * (ctx.frame ? ctx.frame->viewHeightPx() : 1080.0f);
1272 cluster_flat_ = glm::length(glm::vec3(vp[0][3], vp[1][3], vp[2][3])) < 1e-12f;
1273 cluster_meshes_ = cluster_triangles_ = cluster_source_triangles_ = cluster_rebuilt_ = cluster_drawn_ = 0;
1274 waiting_materials_ = 0;
1275 if (cluster_serial_ % 256 == 0 && !cluster_cuts_.empty()) {
1276 GfxDevice& device = buffers.device();
1277 for (auto it = cluster_cuts_.begin(); it != cluster_cuts_.end();) {
1278 if (it->second.usedAt + kClusterCutIdleCollects < cluster_serial_) {
1279 if (it->second.buffer != BufferHandle::Invalid) device.deleteBuffer(it->second.buffer);
1280 it = cluster_cuts_.erase(it);
1281 } else {
1282 ++it;
1283 }
1284 }
1285 }
1286 }
1287 if (!motion && ctx.track_motion && ctx.motion_frame % 256 == 0) {
1288 for (auto it = poses_.begin(); it != poses_.end();) {
1289 if (it->second.frame + 8 < ctx.motion_frame) {
1290 it = poses_.erase(it);
1291 ++pose_generation_;
1292 } else {
1293 ++it;
1294 }
1295 }
1296 }
1297
1298 u32 litProgram = 0;
1299 // The mesh as this view's mode describes it; one object reused across the walk.
1300 const ShadingMode shading = depthPass ? ShadingMode::Shaded : collect_ctx.shading;
1301 ecs::MeshRenderer shaded;
1302
1303 // What is kept between walks is the look as authored, which every view of it agrees on; a view that overrides it derives
1304 // afresh. The tick is this walk's look at the change stamps: a proxy derived now has seen every write stamped up to it.
1305 const bool keeping = shading == ShadingMode::Shaded;
1306 u32 now = 0, rulesChangedAt = 0;
1307 proxies_kept_ = proxies_built_ = 0;
1308 if (keeping) {
1309 if (renderOrigin() != proxy_origin_ || ctx.materials != proxy_materials_ || registry.identity() != proxy_registry_) {
1310 if (registry.identity() != proxy_registry_) {
1311 proxies_.clear();
1312 proxy_slot_.clear();
1313 }
1314 ++proxy_epoch_;
1315 proxy_origin_ = renderOrigin();
1316 proxy_materials_ = ctx.materials;
1317 proxy_registry_ = registry.identity();
1318 }
1319 now = registry.beginChangeRead();
1320 rulesChangedAt = ruledOutChangedAt(registry);
1321 }
1322
1323 // The walk is timed whole: two clock reads a walk. A clock read is a call out to the page (performance.now), and read at
1324 // every phase of every mesh it was four of every ten samples of a profiled frame and most of the time it reported - the
1325 // collect looked several times dearer than it was. The split by phase is a build option (ES_PROFILE_COLLECT_PHASES) for
1326 // whoever needs it and accepts that the clock is then in the number; a profile with function names says more.
1327 const bool timing = FrameProfiler::get().enabled();
1328#ifdef ES_PROFILE_COLLECT_PHASES
1329 constexpr bool phases = true;
1330#else
1331 constexpr bool phases = false;
1332#endif
1333 f64 phase[5] = {0, 0, 0, 0, 0};
1334 const f64 walkStart = timing ? es_profile_now_ms() : 0.0;
1335 f64 mark = timing && phases ? walkStart : 0.0;
1336 u32 walked = 0, coldDecompose = 0, lodGathers = 0, programAsks = 0, instanceRecords = 0;
1337 // Where the scene's opaque meshes went in the choice of a depth prepass: taken, left out for a cut-out or a bent vertex, or no program to be had.
1338 u32 prepassTaken = 0, prepassCutout = 0, prepassBent = 0, prepassNoProgram = 0;
1339 const auto tick = [&](int slot) {
1340 if (!phases || !timing) return;
1341 const f64 now = es_profile_now_ms();
1342 phase[slot] += now - mark;
1343 mark = now;
1344 };
1345
1346 const bool split = collect_ctx.casters != CasterSplit::All;
1347 const bool wantMovers = collect_ctx.casters == CasterSplit::Movers;
1348 // The editor's selection mask (a motion collect with a selection): the selected meshes, as they stand.
1349 const bool selecting = motion && collect_ctx.selection != nullptr;
1350 for (auto entity : meshView) {
1351 if (split && !ctx.causticReceivers && isMover(entity) != wantMovers) continue;
1352 if (selecting && !collect_ctx.selection->count(entity.id())) continue;
1353 ++walked;
1354 const auto& authored = meshView.get<ecs::MeshRenderer>(entity);
1355 const ecs::MeshRenderer* described = &authored;
1356 const bool heated = !depthPass && collect_ctx.weights.entity == entity;
1357 if (heated) {
1358 shaded = authored;
1359 applyShading(shaded, ShadingMode::Albedo);
1360 shaded.texture = {};
1361 shaded.color = glm::vec4(static_cast<f32>(collect_ctx.weights.joint), 0.0f, 0.0f, 1.0f);
1362 described = &shaded;
1363 } else if (shading != ShadingMode::Shaded) {
1364 shaded = authored;
1365 applyShading(shaded, shading);
1366 described = &shaded;
1367 }
1368 const auto& mesh = *described;
1369 // Empty indices no longer mean "nothing to draw": a resident mesh keeps
1370 // its geometry on the GPU and its inline payload deliberately empty.
1371 if (!mesh.enabled || (mesh.indices.empty() && !mesh.mesh.isValid())) continue;
1372
1373 auto& transform = meshView.get<ecs::Transform>(entity);
1374 // Kept from an earlier walk when nothing it was derived from has changed (MeshProxy); null derives it here.
1375 MeshProxy* kept = keeping && !heated ? retain(collect_ctx, entity, mesh, transform, now, rulesChangedAt) : nullptr;
1376 glm::vec3 position, scale;
1377 glm::quat rotation;
1378 if (kept) {
1379 // The motion pass draws what moved since the view's last frame, and only what is opaque. A kept draw that did not
1380 // is passed over here rather than after its cull, which is all the work the walk would have done to reach the same answer.
1381 if (selecting && kept->placed) continue;
1382 if (motion && !selecting) {
1383 if (kept->placed) continue;
1384 const Pose* pose = poseOf(ctx, entity, kept, false);
1385 if (!mesh.opaque || !pose || pose->frame != ctx.motion_frame || pose->previous == pose->current) continue;
1386 }
1387 position = kept->position;
1388 rotation = kept->rotation;
1389 scale = kept->scale;
1390 } else {
1391 if (!transform.decomposed_) ++coldDecompose;
1392 // Parallax is a CAMERA trick — a renderable shifted toward the view centre to
1393 // scroll slower. A shadow pass looks from a light, whose centre means nothing to
1394 // it, and its map is fitted to unshifted bounds: a caster stands where it is.
1395 transform.ensureDecomposed();
1396 position = shadowDepth
1397 ? rebased(transform.worldPosition)
1398 : parallaxedWorldPosition(transform, mesh.parallax, collect_ctx.camera);
1399 // A card turns to THIS view, whichever it is: the Transform keeps what was authored. Placements are each turned by their own
1400 // record, so a set of them is left as it stands.
1401 const ecs::Billboard* card = registry.tryGet<ecs::Billboard>(entity);
1402 rotation = card && card->enabled && !registry.tryGet<ecs::MeshInstances>(entity)
1403 ? billboard::facing(card->mode, ctx.view_projection, collect_ctx.camera.eye, position)
1404 : transform.worldRotation;
1405 scale = transform.worldScale;
1406 }
1407 tick(0);
1408
1409 // Bounds come from whichever geometry this is: a resident mesh keeps its
1410 // own, and the inline payload's are recomputed on upload. Reading the
1411 // component's for a resident mesh would cull it against an empty box.
1412 const Mesh* resident = kept ? kept->resident : mesh.mesh.isValid() ? ctx.resources.getMesh(mesh.mesh) : nullptr;
1413 // Only GPU-resident geometry casts: the inline payload takes the CPU path
1414 // below, which bakes world space into vertices for the BATCH shader — a
1415 // shader that writes colour, not the depth this pass is here to collect.
1416 if (depthPass && !resident) continue;
1417 // Many placements of one mesh, drawn as instances of it. What is placed does not move on its own, so the motion pass has nothing to say.
1418 const ecs::MeshInstances* placements = resident && (!kept || kept->placed) ? registry.tryGet<ecs::MeshInstances>(entity) : nullptr;
1419 if (placements && (placements->transforms.empty() || motion)) continue;
1420 // What light passes through (water) stands in no light's way. Rain's way is another matter: a see-through surface
1421 // set to cast no shadow (glass) still keeps rain off what is under it, so the rain's cover map takes it. What is
1422 // opaque and casts no shadow (a held gun, an effect's mesh) stays out of both.
1423 if (ctx.causticReceivers) {
1424 if (!mesh.opaque || (ctx.materials && ctx.materials->usesSceneColor(mesh.material))) continue;
1425 const bool deforming = registry.has<ecs::MeshSkin>(entity) || registry.has<ecs::MeshMorph>(entity)
1426 || (ctx.materials && ctx.materials->hasUntrackedDepthHook(mesh.material));
1427 if (split && (isMover(entity) || deforming) != wantMovers) continue;
1428 } else if (shadowDepth && !mesh.castShadows && !(ctx.rainCover && !mesh.opaque)) continue;
1429 // Only a surface that draws opaque and unblended has a motion worth writing: what is blended over
1430 // something has two, and the picture can follow one.
1431 if (motion && !selecting && !mesh.opaque) continue;
1432
1433 // A collect with no LOD memory must not select: a shadow map's own screen
1434 // size means nothing to a player, and borrowing a camera's answer would
1435 // make the answer the entity's rather than each view's.
1436 LodLevels levels;
1437 const ecs::LODGroup* group = nullptr;
1438 if (collect_ctx.lod.state && resident && !placements && !kept) {
1439 const auto* declared = registry.tryGet<ecs::LODGroup>(entity);
1440 if (declared && declared->enabled) {
1441 ++lodGathers;
1442 if (gatherLodLevels(ctx.resources, *declared, *resident, levels)) {
1443 group = declared;
1444 reportLodAuthoring(levels, warned_lod_);
1445 }
1446 }
1447 }
1448 tick(1);
1449 // Small enough, and an impostor with its pictures taken: a card facing this view stands in for the mesh. Only the scene's own
1450 // views draw one: a card casts no shadow, and a picture has no motion to write.
1451 if (ctx.purpose == RenderPurpose::Scene && resident && !placements && !kept && ctx.frame) {
1452 const auto* stand = registry.tryGet<ecs::Impostor>(entity);
1453 const RenderFrame::ImpostorAtlas* atlas = stand && stand->enabled ? ctx.frame->impostorAtlas(entity) : nullptr;
1454 if (atlas) {
1455 glm::vec3 centre;
1456 f32 radius = 0.0f;
1457 lod::boundingSphere(position, transform.worldRotation, scale, resident->localMin, resident->localMax, centre, radius);
1458 if (radius > 0.0f && lod::screenRelativeSize(ctx.view_projection, centre, radius) * ctx.frame->lodDistanceScale() < stand->screenSize) {
1459 if (collect_ctx.frustum.intersectsAABB(centre, glm::vec3(radius))) {
1460 emitImpostorCard(collect_ctx, *atlas, mesh, entity, centre, radius, transform.worldRotation);
1461 }
1462 continue;
1463 }
1464 }
1465 }
1466 // BEFORE the cull, because whether this draw depth-tests decides if an
1467 // occluder may refuse it, and the material is where that is finally said.
1468 // Reused by the draw key below: two lookups is how the two come to differ.
1469 const MaterialRecord* material = kept ? kept->material
1470 : (mesh.material != 0 && ctx.materials) ? ctx.materials->find(mesh.material) : nullptr;
1471 // A material that bends its vertices can put them outside the mesh's own box; culling the
1472 // box would drop a bent mesh that is still on screen, so it grows by what the material says.
1473 const f32 bend = kept ? kept->bend : material ? ctx.materials->vertexBounds(mesh.material) : 0.0f;
1474 const bool depthTested = kept ? kept->depthTested : mesh.opaque || (material && material->depthTest);
1475
1476 const Mesh* placementCoarse = !placements ? nullptr : kept ? kept->coarse : placementCoarseMesh(ctx.resources, *resident, *placements);
1477 f32 placementRadius = 0.0f;
1478 glm::vec3 placementCentre(0.0f), placementHalf(0.0f);
1479 if (placements && !kept) {
1480 glm::vec3 lo, hi;
1481 meshLocalBounds(*resident, placementCoarse, bend, lo, hi);
1482 placementRadius = placement_bounds::radius(lo, hi, 0.0f);
1483 placementCentre = (lo + hi) * 0.5f;
1484 placementHalf = (hi - lo) * 0.5f;
1485 }
1486 // Placements can rotate or shear independently. One origin-centred sphere includes both LODs and local deformation.
1487 const glm::vec3 reach(placements ? placementRadius * placements->maxScale : 0.0f);
1488 const glm::vec3 localMin = placements ? placements->originMin - reach
1489 : group ? levels.localMin
1490 : resident ? resident->localMin : glm::vec3(mesh.localMin, 0.0f);
1491 const glm::vec3 localMax = placements ? placements->originMax + reach
1492 : group ? levels.localMax
1493 : resident ? resident->localMax : glm::vec3(mesh.localMax, 0.0f);
1494 const glm::vec3 padding(placements ? 0.0f : bend);
1495
1496 glm::vec3 aabbCenter(0.0f), halfExtents(0.0f);
1497 if (kept) {
1498 aabbCenter = kept->boxCentre;
1499 halfExtents = kept->boxHalf;
1500 } else {
1501 orientedWorldAabb(position, rotation, scale, localMin - padding, localMax + padding,
1502 aabbCenter, halfExtents);
1503 }
1504 if (resident && !placements && !group && !kept) {
1505 skinnedWorldBounds(registry, entity, *resident, warned_bones_, aabbCenter, halfExtents);
1506 }
1507 // The collect's own predicate, not a frustum test of this plugin's: it
1508 // answers "outside the view" AND "behind something solid", and a mesh is
1509 // what both were built for.
1510 if (!collect_ctx.visible(aabbCenter, halfExtents, depthTested)) {
1511 ++collect_ctx.culled;
1512 tick(2);
1513 continue;
1514 }
1515 if (shadowDepth && !collect_ctx.castsIntoView(aabbCenter, glm::length(halfExtents))) {
1516 ++collect_ctx.culled;
1517 tick(2);
1518 continue;
1519 }
1520
1521 // Nothing visible is worth measuring precisely, so the cull runs first; what
1522 // survives it is measured on the sphere the whole group shares.
1523 if (group && collect_ctx.lod.follow) {
1524 // Cast by what the view draws: the level it settled on last frame (this frame's camera collect comes after the
1525 // shadows), nothing where it culled, the finest where it has not looked lately.
1526 u8 settled = 0;
1527 const auto& state = *collect_ctx.lod.state;
1528 if (!state.recent(collect_ctx.lod.view, entity, 2, settled)) settled = 0;
1529 const u8 shown = settled == lod::kCulled ? settled : state.drawn(collect_ctx.lod.view, entity, settled, levels.set.count);
1530 if (shown == lod::kCulled) { ++collect_ctx.culled; tick(2); continue; }
1531 resident = levels.mesh[shown];
1532 } else if (group) {
1533 glm::vec3 centre(0.0f);
1534 f32 radius = 0.0f;
1535 lod::boundingSphere(position, rotation, scale, localMin, localMax, centre, radius);
1536 const f32 screenSize = lod::screenRelativeSize(ctx.view_projection, centre, radius) * (ctx.frame ? ctx.frame->lodDistanceScale() : 1.0f);
1537 auto& state = *collect_ctx.lod.state;
1538 const u32 view = collect_ctx.lod.view;
1539 const u8 level = lod::selectLevel(levels.set, screenSize, state.lastLevel(view, entity));
1540 // The same size with no memory behind it. Recorded rather than derived
1541 // later: the two differing IS hysteresis holding a level, and an editor
1542 // that recomputed it would be a second selector free to disagree.
1543 const u8 unbiased = lod::selectLevel(levels.set, screenSize, 0);
1544 state.remember(view, entity, level, unbiased, levels.set.count, screenSize);
1545 // The POLICY's answer, not the one a creator is holding up to look at:
1546 // a preview is an editor's question about this view, and counting it
1547 // would put it in a shipped frame's profile.
1548 if (collect_ctx.lod.counts) collect_ctx.lod.counts->record(level);
1549 const u8 shown = state.drawn(view, entity, level, levels.set.count);
1550 if (shown == lod::kCulled) { ++collect_ctx.culled; tick(2); continue; }
1551 resident = levels.mesh[shown];
1552 }
1553 tick(2);
1554
1555 // How big a texture this mesh needs here: a texel about a pixel at the nearest point of its sphere. The scene's own views
1556 // only — a shadow map's texels are not anyone's pixels — and only where the mesh says how much texture its surface holds.
1557 // Placements are measured one by one where they are walked (emitPlacements), and asked for below.
1558 if (ctx.purpose == RenderPurpose::Scene && ctx.frame && resident && !placements) {
1559 glm::vec3 centre(0.0f);
1560 f32 radius = 0.0f;
1561 lod::boundingSphere(position, rotation, scale, resident->localMin, resident->localMax, centre, radius);
1562 const glm::vec4 eye = collect_ctx.camera.eye;
1563 const f32 distance = eye.w > 0.5f ? std::max(glm::length(glm::vec3(eye) - centre) - radius, 1e-3f) : 1.0f;
1564 const f32 grow = std::max({std::abs(scale.x), std::abs(scale.y), std::abs(scale.z)});
1565 wantTexturesOf(ctx, mesh, material, textureSideFor(ctx, grow / distance, resident->uvDensity));
1566 }
1567
1568 u32 textureId = ctx.white_texture_id;
1569 if (mesh.texture.isValid()) {
1570 if (Texture* tex = ctx.resources.getTexture(mesh.texture)) {
1571 textureId = tex->getId();
1572 }
1573 }
1574 MeshDrawKeys keys{};
1575 if (selecting) {
1576 // The mask's coverage, through the motion program with no movement in it. A skinned mesh is placed by bones
1577 // the motion records take from last frame's pose, which a still selection has none of: the editor outlines it itself.
1578 const MeshProgramFacts facts =
1579 kept ? kept->facts : meshFactsFromEntity(ctx, registry, entity, mesh, resident, warned_bones_);
1580 if (facts.skinned || !resident) continue;
1581 keys = { meshVariant(facts.hasNormals, false, false, false, false, false, false, false, false, true, facts.tangents), 0 };
1582 } else if (motion) {
1583 // What was drawn last frame and what is drawn now, for THIS view. Nothing known, or nothing changed,
1584 // means the camera's own motion says it all and the temporal pass already has that.
1585 const Pose* pose = poseOf(ctx, entity, kept, false);
1586 if (!pose || pose->frame != ctx.motion_frame
1587 || (pose->previous == pose->current && pose->bonesPrevious == pose->bonesCurrent)) {
1588 continue;
1589 }
1590 const MeshProgramFacts facts =
1591 kept ? kept->facts : meshFactsFromEntity(ctx, registry, entity, mesh, resident, warned_bones_);
1592 // A palette of a different size than last frame's has no joint-for-joint past to follow.
1593 if (facts.skinned && pose->bonesPrevious.size() != pose->bonesCurrent.size()) continue;
1594 keys = { meshVariant(facts.hasNormals, false, false, facts.skinned, false, false, false, false, false, true, facts.tangents), 0 };
1595 } else if (kept) {
1596 MeshProgramFacts facts = kept->facts;
1597 facts.normalTextureId = normalTextureOf(ctx, mesh, facts);
1598 keys = meshDrawFrom(ctx, entity, facts, shadowDepth);
1599 } else {
1600 keys = meshDrawFor(ctx, registry, entity, mesh, resident, shadowDepth, warned_bones_, heated);
1601 }
1602 const u32 normalTextureId = keys.normalTextureId;
1603
1604 BatchDrawKey key{
1605 .stage = ctx.current_stage,
1606 .layer = mesh.layer,
1607 .shaderId = ctx.batch_shader_id,
1608 .blend = BlendMode::Normal,
1609 .textureId = textureId,
1610 .normalTextureId = normalTextureId,
1611 .shadowTextureId = ctx.shadow_texture_id,
1612 .envTextureId = ctx.environment_texture_id,
1613 .depth = collect_ctx.camera.viewDepth(position),
1614 .y = position.y,
1615 .entity = entity,
1616 .type = RenderType::Mesh,
1617 };
1618
1619 if (!depthPass && ctx.frame) {
1620 const u32 reflection = ctx.frame->planarTextureFor(entity);
1621 if (reflection != 0) {
1622 key.envTextureId = reflection;
1623 key.planarIndex = draw_list.addPlanar(ctx.frame->planarConstants());
1624 }
1625 }
1626
1627 // An opaque surface says so itself rather than waiting for a depth layer:
1628 // no blending, depth written AND tested — the only way one mesh hides
1629 // another. Opaque sorts ahead of blended within a layer, so 2D stays on top.
1630 if (mesh.opaque) {
1632 key.blend = BlendMode::None;
1633 key.depthTest = true;
1634 key.depthWrite = true;
1635 }
1636 if (mesh.cullBackfaces) key.cull = static_cast<u8>(CullMode::Back);
1637
1638 // Material resolve mirrors SpritePlugin: an unregistered handle falls back to
1639 // the default batch shader; a material owns shading fully, so it takes
1640 // precedence over the lit toggle.
1641 if (mesh.material != 0) {
1642 if (const MaterialRecord* m = material) {
1643 key.shaderId = (m->shader != 0) ? m->shader : ctx.batch_shader_id;
1644 // An opaque mesh is drawn unblended whatever its material's blend says: the material's 0 is Normal, which
1645 // every material file names by default, and it left every opaque material surface blending — so it wrote
1646 // no surface record (screen-space reflections and rain read nothing) and a cut-out lost its alpha-to-coverage.
1647 key.blend = mesh.opaque ? BlendMode::None : m->blend;
1648 key.materialId = mesh.material;
1649 // Depth likewise, or a sphere's far side draws over its near side: a new material says depthTest false, and
1650 // the surface reads as the inside of a bowl, under light and shadow that look wrong for no reason a person can see.
1651 key.depthTest = mesh.opaque || m->depthTest;
1652 key.depthWrite = mesh.opaque || m->depthWrite;
1653 key.cull = static_cast<u8>(m->cull);
1654 key.depthBias = m->depthBias;
1655 }
1656 } else if (mesh.lit && ctx.frame) {
1657 if (litProgram == 0) litProgram = ctx.frame->batchProgram(BatchVariant::Lit);
1658 if (litProgram != 0) key.shaderId = litProgram;
1659 }
1660
1661 // Casting into a shadow map: opaque and depth-tested whatever the camera's
1662 // pass makes it, and none of the three ways to describe a surface — lit, a
1663 // normal map, a material. LAST, so the pass outranks all three.
1664 if (depthPass) {
1666 key.blend = BlendMode::None;
1667 key.depthTest = true;
1668 key.depthWrite = true;
1669 key.materialId = 0;
1670 key.shadowTextureId = 0;
1671 key.envTextureId = 0;
1672 }
1673
1674 // Resident geometry: only the transform is written for the frame. Its
1675 // vertices are local-space and untouched, so the CPU loop below — which
1676 // exists to bake world space into every vertex — is skipped entirely.
1677 if (resident && mesh_programs_[0] != 0) {
1678 // The pose, when this entity says what moves it. The bones are
1679 // world-space, so the entity's own transform is not read — which is
1680 // what glTF requires of a skinned mesh.
1681 const u32 poseSize = kept ? 0u : skinPose(registry, entity, *resident, pose_scratch_, warned_bones_);
1682 // Posed already this frame by the skin cache: the draw reads the posed copy as unskinned geometry in world space,
1683 // through the program a static mesh has. The motion pass poses in its vertex stage still, with last frame's pose beside it,
1684 // and so does the weight view, which colours by the joints the posed copy no longer carries to the program.
1686 if (poseSize > 0 && !motion && !heated && !placements && ctx.frame) {
1687 if (SkinCache* cache = ctx.frame->skinCache()) {
1688 cachedSkin = cache->bufferFor(entity);
1689 if (cachedSkin != BufferHandle::Invalid) cache->noteDraw();
1690 }
1691 }
1692 const bool cached = cachedSkin != BufferHandle::Invalid;
1693 const bool skinned = poseSize > 0 && !cached;
1694 const u32 drawVariant = cached ? (keys.variant & ~8u) : keys.variant;
1695
1696 // `lit` is the draw's own word and is honoured either way: geometry
1697 // with normals can be drawn unlit, and geometry without them takes
1698 // light off the constant normal a 2D surface has.
1699 tick(4);
1700 ++programAsks;
1701 const u32 residentShader = meshProgram(ctx, drawVariant);
1702 tick(3);
1703 if (resident->isDrawable() && residentShader != 0) {
1704 // The shape the mesh was REALIZED in, not a second derivation:
1705 // the record is read through that layout, so the fact that built
1706 // it must pack it. (It already excludes a skinned mesh.)
1707 const bool lightmapped = resident->hasLightmapUV && !motion;
1708 // A skinned motion draw carries last frame's palette in the records right behind its own: three
1709 // texels a bone from texel 8 on, which the shader reaches by index like any other texel.
1710 // A chunked skin writes each chunk's palette into a record of the chunk's own as it is drawn (below).
1711 const bool chunked = skinned && resident->isChunked();
1712 const u32 paletteRecords = motion && skinned && !chunked
1713 ? (3 * poseSize + MESH_INSTANCE_TEXELS - 1) / MESH_INSTANCE_TEXELS : 0;
1714 static thread_local std::vector<u8> unplaced;
1715 u32 instOffset = 0;
1716 u8* dst = nullptr;
1717 if (placements) {
1718 unplaced.resize(static_cast<usize>(MESH_INSTANCE_STRIDE) * (1 + paletteRecords));
1719 dst = unplaced.data();
1720 } else {
1721 instOffset = buffers.allocVertices(LayoutId::MeshInstance, MESH_INSTANCE_STRIDE * (1 + paletteRecords));
1722 dst = buffers.vertexData(LayoutId::MeshInstance) + instOffset;
1723 }
1724 // The record is one fixed shape, so every texel this variant
1725 // does not write still has to say something. Zero is the answer
1726 // each of them reads as absent.
1727 std::memset(dst, 0, MESH_INSTANCE_STRIDE * (1 + paletteRecords));
1728 // The shapes, whether or not bones move it: the two deform the
1729 // same vertices, and a morph target is what the mesh is BEFORE a
1730 // pose is applied to it.
1731 MorphConstants shapes{};
1732 if (!kept && morphShapes(registry, entity, *resident, shapes)) {
1733 key.morphIndex = draw_list.addMorphShapes(shapes);
1734 key.morphTextureId = static_cast<u32>(resident->morphTexture);
1735 }
1736 std::memcpy(dst + MESH_INSTANCE_TEXEL_TINT * 16, &mesh.color, 16);
1737 if (skinned) {
1738 // A chunked skin uploads each chunk's bones with the chunk's draw instead (below).
1739 if (!chunked) {
1740 key.skinOffset = draw_list.addSkinMatrices(pose_scratch_.data(), poseSize);
1741 key.skinCount = poseSize;
1742 }
1743 } else {
1744 const glm::mat4 model = cached ? glm::mat4(1.0f)
1745 : kept ? kept->model
1746 : glm::translate(glm::mat4(1.0f), position)
1747 * glm::mat4_cast(rotation)
1748 * glm::scale(glm::mat4(1.0f), scale);
1749 // Three rows, not four columns: the row the shader rebuilds is
1750 // the one an affine transform never varies.
1751 for (u32 row = 0; row < 3; ++row) {
1752 const glm::vec4 r{model[0][row], model[1][row], model[2][row], model[3][row]};
1753 std::memcpy(dst + (MESH_INSTANCE_TEXEL_MODEL + row) * 16, &r, 16);
1754 }
1755 if (resident->hasNormals) {
1756 // Written per object rather than derived per vertex: this is
1757 // the transform a normal takes under a non-uniform scale.
1758 const glm::mat3 nrm = cached ? glm::mat3(1.0f)
1759 : kept ? kept->normalRows : glm::transpose(glm::inverse(glm::mat3(model)));
1760 for (u32 row = 0; row < 3; ++row) {
1761 std::memcpy(dst + (MESH_INSTANCE_TEXEL_NORMAL + row) * 16, &nrm[row][0], 12);
1762 }
1763 }
1764 if (lightmapped) {
1765 // A zero scale where this object has no bake — the shader
1766 // reads it as "none" rather than as an atlas of black, which
1767 // an unlit surface would wear as darkness it never had.
1768 glm::vec4 rect{0.0f};
1769 if (const auto* baked = registry.tryGet<ecs::MeshLightmap>(entity)) {
1770 if (Texture* atlas = ctx.resources.getTexture(baked->lightmap)) {
1771 rect = baked->scaleOffset;
1772 key.lightmapTextureId = atlas->getId();
1773 }
1774 }
1775 std::memcpy(dst + MESH_INSTANCE_TEXEL_LIGHTMAP * 16, &rect, 16);
1776 }
1777 }
1778 if (selecting) {
1779 // No movement: "last frame" is this frame's camera times where the mesh stands now, so the program
1780 // writes zero motion, the depth, and full coverage.
1781 const glm::vec4 still{0.0f};
1782 std::memcpy(dst + MESH_INSTANCE_TEXEL_TINT * 16, &still, 16);
1783 const glm::mat4 model = kept ? kept->model
1784 : glm::translate(glm::mat4(1.0f), position) * glm::mat4_cast(rotation) * glm::scale(glm::mat4(1.0f), scale);
1785 const glm::mat4 now = ctx.motion_prev_view_projection * model;
1786 for (u32 row = 0; row < 4; ++row) {
1787 const glm::vec4 r{now[0][row], now[1][row], now[2][row], now[3][row]};
1788 std::memcpy(dst + (MESH_INSTANCE_TEXEL_NORMAL + row) * 16, &r, 16);
1789 }
1790 } else if (motion) {
1791 // This record is the motion pass's own, so the texels a lit draw keeps its tint, normal
1792 // matrix and bake in are free: last frame's shift in the tint's, and last frame's
1793 // view-projection times last frame's model — as rows, so the shader dots them with the local position.
1794 const Pose& pose = *poseOf(ctx, entity, kept, false);
1795 const glm::vec4 jitter{ctx.motion_prev_jitter, 0.0f, 0.0f};
1796 std::memcpy(dst + MESH_INSTANCE_TEXEL_TINT * 16, &jitter, 16);
1797 // A rigid mesh's last place is its last model, so the matrix is the two together; a skinned
1798 // one is placed by its bones, which the shader applies first, so only the camera goes here.
1799 const glm::mat4 before = skinned ? ctx.motion_prev_view_projection
1800 : ctx.motion_prev_view_projection * pose.previous;
1801 for (u32 row = 0; row < 4; ++row) {
1802 const glm::vec4 r{before[0][row], before[1][row], before[2][row], before[3][row]};
1803 std::memcpy(dst + (MESH_INSTANCE_TEXEL_NORMAL + row) * 16, &r, 16);
1804 }
1805 if (skinned && !chunked) {
1806 for (u32 bone = 0; bone < poseSize; ++bone) {
1807 const glm::mat4& m = pose.bonesPrevious[bone];
1808 for (u32 row = 0; row < 3; ++row) {
1809 const glm::vec4 r{m[0][row], m[1][row], m[2][row], m[3][row]};
1810 std::memcpy(dst + (MESH_INSTANCE_TEXELS + bone * 3 + row) * 16, &r, 16);
1811 }
1812 }
1813 }
1814 } else if (ctx.track_motion && !shadowDepth) {
1815 trackPose(*poseOf(ctx, entity, kept, true), ctx,
1816 poseSize > 0 ? glm::mat4(1.0f)
1817 : kept ? kept->model
1818 : glm::translate(glm::mat4(1.0f), position)
1819 * glm::mat4_cast(rotation)
1820 * glm::scale(glm::mat4(1.0f), scale),
1821 poseSize > 0 ? &pose_scratch_ : nullptr);
1822 }
1823
1824 // A draw reading its own atlas does not ask for IRRADIANCE, and asks
1825 // for its reflection either way — a lightmapped wall mirrors the room
1826 // like anything else. At the ENTITY's position: bones place a skin.
1827 if (!depthPass) {
1828 ProbeConstants probe;
1829 // Per pixel where the program can read the atlas: a mesh with lightmap UVs is compiled with
1830 // the bake's sampler on that unit, so it keeps the one value its position reads.
1831 const ProbeStore& store = ctx.render_context.probes();
1832 // By the mesh's world box, not its origin: an imported level's origins are wherever the file put them.
1833 const bool volume = key.lightmapTextureId == 0
1834 && store.sampleBox(aabbCenter, halfExtents, probe, !resident->hasLightmapUV);
1835 if (volume && probe.irradiance[0].w > 1.5f) key.probeGridTextureId = store.atlasTexture();
1836 if (volume) store.noteDraw(probe.irradiance[0].w > 1.5f);
1837 const u32 slot = ctx.render_context.reflections().slotForBox(aabbCenter, halfExtents);
1838 probe.reflection.x = static_cast<f32>(slot);
1839 if (volume || slot != 0) key.probeIndex = draw_list.addProbe(probe);
1840 }
1841
1842 // A material's default program is built for the BATCH vertex
1843 // source and would draw this at its local origin, so ask for the
1844 // one compiled for THIS source; a failed variant falls back.
1845 u32 materialProgram = 0;
1846 if (key.materialId != 0 && ctx.materials) {
1847 materialProgram = ctx.materials->meshProgram(key.materialId, ctx.resources,
1848 resident->hasNormals, skinned,
1849 key.envTextureId != 0,
1850 resident->hasLightmapUV,
1851 ctx.gbuffer && !shadowDepth,
1852 resident->hasTangents, false,
1853 key.blend == BlendMode::None);
1854 if (materialProgram == 0) {
1855 if (!warned_material_) {
1856 warned_material_ = true;
1857 ES_LOG_WARN("MeshRenderer: material {} has no mesh variant; using the mesh shader",
1858 key.materialId);
1859 }
1860 key.materialId = 0;
1861 }
1862 }
1863 key.shaderId = materialProgram != 0 ? materialProgram : residentShader;
1864 // A program still compiling in the background, the material's or the mesh's own: the draw takes the preview
1865 // program meanwhile (texture, colour and bake, compiled in place), rather than being left out until the compile
1866 // ends. A scene opens with every shape there, lit by its bake, and each surface takes its own shading the frame its
1867 // program is ready. It takes no prepass: a prepass left out while its colour draw tests depth for equality is no draw.
1868 bool previewing = false;
1869 if (!depthPass && !motion && key.shaderId != 0) {
1870 GfxDevice& device = buffers.device();
1871 if (device.skipPendingPrograms() && !device.programReady(ShaderHandle{key.shaderId})) {
1872 const u32 preview = previewProgram(ctx, drawVariant);
1873 if (preview != 0 && device.programReady(ShaderHandle{preview})) {
1874 key.shaderId = preview;
1875 key.materialId = 0;
1876 previewing = true;
1877 ES_PROFILE_COUNTER("render.mesh.previewing", ++waiting_materials_);
1878 }
1879 }
1880 }
1881 // A caster whose material bends it casts the bent shape, and one whose alpha is coverage casts
1882 // only where it is opaque: the depth program gets the material's hook and cutoff, and the draw
1883 // keeps the material so its params are bound.
1884 if (shadowDepth && material && ctx.materials
1885 && (ctx.materials->hasVertexHook(mesh.material) || ctx.materials->castsCutoutShadow(mesh.material))) {
1886 const u32 bentDepth = ctx.materials->shadowProgram(mesh.material, ctx.resources,
1887 resident->hasNormals, skinned, resident->hasTangents);
1888 if (bentDepth != 0) {
1889 key.shaderId = bentDepth;
1890 key.materialId = mesh.material;
1891 }
1892 }
1893 // The scene's depth prepass: an opaque, unblended, depth-writing surface has its depth drawn first by a program on its own vertex stage,
1894 // and is shaded only where that depth is the nearest. Not what reads the picture behind it, and not the views that change what a
1895 // surface is drawn as.
1896 if (!depthPass && !motion && !previewing && ctx.purpose == RenderPurpose::Scene && mesh.opaque && key.stage == RenderStage::Opaque
1897 && key.blend == BlendMode::None && key.depthTest && key.depthWrite && shading == ShadingMode::Shaded && !heated) {
1898 const bool refracts = key.materialId != 0 && ctx.materials && ctx.materials->usesSceneColor(key.materialId);
1899 const bool cutout = key.materialId != 0 && ctx.materials && ctx.materials->alphaIsCoverage(key.materialId);
1900 if (refracts) {
1901 } else if (cutout) {
1902 // Its alpha is coverage: a program that writes the same coverage, under the alpha-to-coverage the colour pass draws with.
1903 key.depthShaderId = ctx.materials->prepassCoverageProgram(key.materialId, ctx.resources, resident->hasNormals, skinned,
1904 resident->hasTangents);
1905 if (key.depthShaderId != 0) ++prepassTaken; else ++prepassCutout;
1906 } else {
1907 if (key.materialId != 0 && ctx.materials && ctx.materials->hasVertexHook(key.materialId)) {
1908 // A material that bends its vertices: the depth program carries the same bend.
1909 key.depthShaderId = ctx.materials->shadowProgram(key.materialId, ctx.resources, resident->hasNormals, skinned,
1910 resident->hasTangents);
1911 if (key.depthShaderId != 0) ++prepassTaken; else ++prepassBent;
1912 } else {
1913 u32 depthVariant = kept ? meshDrawFrom(ctx, entity, kept->facts, true).variant
1914 : meshDrawFor(ctx, registry, entity, mesh, resident, true, warned_bones_).variant;
1915 if (cached) depthVariant &= ~8u;
1916 key.depthShaderId = meshProgram(ctx, depthVariant);
1917 if (key.depthShaderId != 0) ++prepassTaken; else ++prepassNoProgram;
1918 }
1919 }
1920 }
1922 key.instanceCount = 1;
1924 const bool wire = shading == ShadingMode::Wireframe;
1925 if (wire) key.depthBias = kWireFillBias;
1926 // One draw of `count` records from `offset`, of the geometry `geo`. A cutout that asks for tips gets its soft outer band
1927 // as a second, blended draw of the same instances: no depth written, sorted with the other blended draws, and no
1928 // surface record.
1929 // The indices a draw of `geo` reads: its own, or the cut a clustered mesh is drawn through.
1931 u32 cutIndexCount = 0;
1932 // One draw of the run `firstIndex`, `indexCount` of what `emit` would draw: the whole of it, or a skin chunk.
1933 const auto emitRange = [&](const Mesh& geo, u32 offset, u32 count, u32 firstIndex, u32 indexCount) {
1934 BatchDrawKey drawn = key;
1935 drawn.instanceCount = count;
1936 drawn.vertexBuffer = cached && &geo == resident ? cachedSkin : geo.vertexBuffer;
1937 drawn.indexBuffer = cutBuffer != BufferHandle::Invalid ? cutBuffer : geo.indexBuffer;
1938 drawn.vertexLayout = geo.layout;
1939 pushBatchDraw(draw_list, clips, offset, 0, firstIndex, indexCount, drawn);
1940 if (!depthPass && !wire && key.materialId != 0 && ctx.materials && ctx.materials->hasTipPass(key.materialId)) {
1941 const u32 tipProgram = ctx.materials->meshProgram(key.materialId, ctx.resources, geo.hasNormals, skinned,
1942 key.envTextureId != 0, geo.hasLightmapUV, false,
1943 geo.hasTangents, true, false);
1944 if (tipProgram != 0) {
1945 BatchDrawKey tips = drawn;
1946 tips.shaderId = tipProgram;
1948 tips.blend = BlendMode::Normal;
1949 tips.depthWrite = false;
1950 pushBatchDraw(draw_list, clips, offset, 0, firstIndex, indexCount, tips);
1951 }
1952 }
1953 };
1954 const auto emit = [&](const Mesh& geo, u32 offset, u32 count) {
1955 emitRange(geo, offset, count, cutBuffer != BufferHandle::Invalid ? 0 : geo.firstIndex,
1956 cutBuffer != BufferHandle::Invalid ? cutIndexCount : geo.indexCount);
1957 };
1958 if (placements) {
1959 PlacementReach reach;
1960 if (kept) {
1961 emitKeptPlacements(ctx, collect_ctx, *placements, kept->instances, kept->records, scale, *resident,
1962 placementCoarse, instanceRecords, reach, emit);
1963 } else {
1964 emitPlacements(ctx, collect_ctx, *placements, mesh, position, rotation, scale, *resident, placementCoarse,
1965 placementCentre, placementHalf, instanceRecords, reach, emit);
1966 }
1967 const f32 fineSide = textureSideFor(ctx, reach.fine, resident->uvDensity);
1968 const f32 coarseSide = placementCoarse ? textureSideFor(ctx, reach.coarse, placementCoarse->uvDensity) : 0.0f;
1969 wantTexturesOf(ctx, mesh, material, std::max(fineSide, coarseSide));
1970 continue;
1971 }
1972 key.vertexBuffer = cached ? cachedSkin : resident->vertexBuffer;
1973 key.indexBuffer = resident->indexBuffer;
1974 key.vertexLayout = resident->layout;
1975 // A clustered mesh, one entity's own: through the clusters the scene's eye picks. The wireframe view draws
1976 // the mesh's own edges, which are level 0's, over level 0.
1977 bool inked = false;
1978 if (resident->clusters && !wire) {
1979 if (const ClusterCut* cut = clusterCut(collect_ctx, entity, *resident, position, rotation, scale)) {
1980 cutBuffer = cut->buffer;
1981 cutIndexCount = cut->indexCount;
1982 if (ctx.purpose == RenderPurpose::Scene) {
1983 ++cluster_meshes_;
1984 cluster_drawn_ += cut->clusters;
1985 cluster_triangles_ += cut->indexCount / 3;
1986 cluster_source_triangles_ += resident->indexCount / 3;
1987 }
1988 if (shading == ShadingMode::Clusters) {
1989 // One draw a cluster, each a copy of the entity's record with a colour of its own: a view for
1990 // looking at the cut, where a draw a cluster is what is being shown.
1991 const lod::ClusterHierarchy& hierarchy = *resident->clusters;
1992 u32 first = 0;
1993 for (const u32 id : cut->ids) {
1994 const u32 count = hierarchy.clusters[id].indexCount;
1995 const u32 offset = buffers.allocVertices(LayoutId::MeshInstance, MESH_INSTANCE_STRIDE);
1996 auto* records = buffers.vertexData(LayoutId::MeshInstance);
1997 std::memcpy(records + offset, records + instOffset, MESH_INSTANCE_STRIDE);
1998 const glm::vec4 ink = clusterInk(id);
1999 std::memcpy(records + offset + MESH_INSTANCE_TEXEL_TINT * 16, &ink, 16);
2000 BatchDrawKey drawn = key;
2001 drawn.indexBuffer = cut->buffer;
2002 pushBatchDraw(draw_list, clips, offset, 0, first, count, drawn);
2003 first += count;
2004 }
2005 inked = true;
2006 }
2007 }
2008 }
2009 if (!inked && chunked && cutBuffer == BufferHandle::Invalid) {
2010 // A skin past one draw's bones, a chunk at a time: each chunk's bones
2011 // posed and uploaded alone, its vertices' joints indexing them. A motion draw's record carries last
2012 // frame's palette, so each chunk gets a copy of the record with that chunk's bones behind it.
2013 static thread_local std::vector<glm::mat4> chunkPose;
2014 for (const MeshSkinChunk& chunk : resident->skinChunks) {
2015 chunkPose.resize(chunk.boneCount);
2016 for (u32 k = 0; k < chunk.boneCount; ++k) {
2017 chunkPose[k] = pose_scratch_[resident->skinChunkBones[chunk.boneOffset + k]];
2018 }
2019 u32 record = instOffset;
2020 if (motion) {
2021 const u32 palette = (3 * chunk.boneCount + MESH_INSTANCE_TEXELS - 1) / MESH_INSTANCE_TEXELS;
2022 record = buffers.allocVertices(LayoutId::MeshInstance, MESH_INSTANCE_STRIDE * (1 + palette));
2023 u8* records = buffers.vertexData(LayoutId::MeshInstance);
2024 std::memcpy(records + record, records + instOffset, MESH_INSTANCE_STRIDE);
2025 std::memset(records + record + MESH_INSTANCE_STRIDE, 0, MESH_INSTANCE_STRIDE * palette);
2026 const Pose& pose = *poseOf(ctx, entity, kept, false);
2027 for (u32 k = 0; k < chunk.boneCount; ++k) {
2028 const glm::mat4& m = pose.bonesPrevious[resident->skinChunkBones[chunk.boneOffset + k]];
2029 for (u32 row = 0; row < 3; ++row) {
2030 const glm::vec4 r{m[0][row], m[1][row], m[2][row], m[3][row]};
2031 std::memcpy(records + record + (MESH_INSTANCE_TEXELS + k * 3 + row) * 16, &r, 16);
2032 }
2033 }
2034 }
2035 key.skinOffset = draw_list.addSkinMatrices(chunkPose.data(), chunk.boneCount);
2036 key.skinCount = chunk.boneCount;
2037 emitRange(*resident, record, 1, resident->firstIndex + chunk.firstIndex, chunk.indexCount);
2038 }
2039 } else if (!inked) {
2040 emit(*resident, instOffset, 1);
2041 }
2042 // The edges, as a second draw of the same instance with its own ink: same
2043 // vertices, the mesh's line list, tested against the surface just drawn.
2044 if (wire && resident->hasEdges()) {
2045 const u32 edgeOffset = buffers.allocVertices(LayoutId::MeshInstance,
2047 auto* records = buffers.vertexData(LayoutId::MeshInstance);
2048 std::memcpy(records + edgeOffset, records + instOffset, MESH_INSTANCE_STRIDE);
2049 std::memcpy(records + edgeOffset + MESH_INSTANCE_TEXEL_TINT * 16, &kWireInk, 16);
2050 BatchDrawKey edges = key;
2051 edges.indexBuffer = resident->edgeIndexBuffer;
2053 edges.depthBias = 0;
2054 edges.depthTest = true;
2055 edges.depthWrite = false;
2056 // Blended at full alpha: what puts it in the stage AFTER the surface it
2057 // is drawn on (a depth layer derives the stage from the blend, and an
2058 // opaque line would sort among the surfaces and write depth).
2059 edges.blend = BlendMode::Normal;
2061 pushBatchDraw(draw_list, clips, edgeOffset, 0, 0, resident->edgeIndexCount, edges);
2062 }
2063 }
2064 continue;
2065 }
2066
2067 f32 angle = 2.0f * std::atan2(rotation.z, rotation.w);
2068 bool rotated = std::abs(angle) > 0.001f;
2069 f32 cosA = 1.0f, sinA = 0.0f;
2070 if (rotated) {
2071 cosA = std::cos(angle);
2072 sinA = std::sin(angle);
2073 }
2074
2075 u32 tint = packColor(mesh.color);
2076 bool tinted = tint != 0xFFFFFFFFu;
2077
2078 scratch_.resize(mesh.vertices.size());
2079 for (usize v = 0; v < mesh.vertices.size(); ++v) {
2080 const auto& in = mesh.vertices[v];
2081 glm::vec2 local(in.position.x * scale.x, in.position.y * scale.y);
2082 glm::vec3 world = rotated
2083 ? glm::vec3(position.x + local.x * cosA - local.y * sinA,
2084 position.y + local.x * sinA + local.y * cosA,
2085 position.z)
2086 : glm::vec3(position.x + local.x, position.y + local.y, position.z);
2087 scratch_[v] = { world, tinted ? mulColor(in.color, tint) : in.color, in.uv };
2088 }
2089
2090 appendIndexedBatch(buffers, draw_list, clips,
2091 scratch_.data(), static_cast<u32>(scratch_.size()),
2092 mesh.indices.data(), static_cast<u32>(mesh.indices.size()), key);
2093 }
2094 tick(4);
2095
2096 if (timing) {
2097 auto& profiler = FrameProfiler::get();
2098 if (phases) {
2099 profiler.add("render.collect.mesh.decompose", phase[0]);
2100 profiler.add("render.collect.mesh.lod", phase[1]);
2101 profiler.add("render.collect.mesh.bounds", phase[2]);
2102 profiler.add("render.collect.mesh.program", phase[3]);
2103 profiler.add("render.collect.mesh.emit", phase[4]);
2104 }
2105 // Which pass walked, how many times, and what the walk cost it: the same meshes are visited once per view of the frame, and the
2106 // total above cannot say which view the time belongs to.
2107 // The profiler keeps the name pointer, so these are literals, one set per purpose.
2108 const f64 spent = es_profile_now_ms() - walkStart;
2109 switch (ctx.purpose) {
2111 profiler.add("render.collect.mesh.scene.walks", 1.0);
2112 profiler.add("render.collect.mesh.scene.visits", static_cast<f64>(walked));
2113 profiler.add("render.collect.mesh.scene.ms", spent);
2114 break;
2116 profiler.add("render.collect.mesh.depth.walks", 1.0);
2117 profiler.add("render.collect.mesh.depth.visits", static_cast<f64>(walked));
2118 profiler.add("render.collect.mesh.depth.ms", spent);
2119 break;
2121 profiler.add("render.collect.mesh.motion.walks", 1.0);
2122 profiler.add("render.collect.mesh.motion.visits", static_cast<f64>(walked));
2123 profiler.add("render.collect.mesh.motion.ms", spent);
2124 break;
2125 default:
2126 profiler.add("render.collect.mesh.other.walks", 1.0);
2127 profiler.add("render.collect.mesh.other.visits", static_cast<f64>(walked));
2128 profiler.add("render.collect.mesh.other.ms", spent);
2129 break;
2130 }
2131 }
2132 // The counts beside the time, because a phase that grew and one whose UNIT
2133 // cost grew are different problems and the milliseconds cannot tell them
2134 // apart. `coldDecompose` is the one that only a first look can be high.
2135 ES_PROFILE_COUNTER("render.mesh.walked", walked);
2136 ES_PROFILE_COUNTER("render.mesh.placements", instanceRecords);
2137 ES_PROFILE_COUNTER("render.mesh.coldDecompose", coldDecompose);
2138 ES_PROFILE_COUNTER("render.mesh.lodGathers", lodGathers);
2139 ES_PROFILE_COUNTER("render.mesh.programAsks", programAsks);
2140 if (ctx.purpose == RenderPurpose::Scene) {
2141 // Clustered meshes the scene drew, the clusters and triangles they were drawn with, the triangles they have at
2142 // level 0, and how many of them had their index buffer rewritten because the pick changed.
2143 ES_PROFILE_COUNTER("render.cluster.meshes", cluster_meshes_);
2144 ES_PROFILE_COUNTER("render.cluster.clusters", cluster_drawn_);
2145 ES_PROFILE_COUNTER("render.cluster.triangles", cluster_triangles_);
2146 ES_PROFILE_COUNTER("render.cluster.sourceTriangles", cluster_source_triangles_);
2147 ES_PROFILE_COUNTER("render.cluster.rebuilt", cluster_rebuilt_);
2148 }
2149 // The scene's own collect says it; a shadow map's, which comes after, would overwrite it with zeroes.
2150 if (ctx.purpose == RenderPurpose::Scene) {
2151 // Draws whose view-independent half was kept from an earlier walk, and those derived again because something changed.
2152 ES_PROFILE_COUNTER("render.mesh.proxy.kept", proxies_kept_);
2153 ES_PROFILE_COUNTER("render.mesh.proxy.built", proxies_built_);
2154 // Kept draws the change audit found differing from a fresh derivation, since the plugin started: anything but 0 is a bug.
2155 ES_PROFILE_COUNTER("render.mesh.proxy.stale", proxies_stale_total_);
2156 ES_PROFILE_COUNTER("render.prepass.taken", prepassTaken);
2157 ES_PROFILE_COUNTER("render.prepass.cutout", prepassCutout);
2158 ES_PROFILE_COUNTER("render.prepass.bent", prepassBent);
2159 ES_PROFILE_COUNTER("render.prepass.noProgram", prepassNoProgram);
2160 }
2161 ES_PROFILE_COUNTER("render.mesh.programCompiles", compiled_this_frame_);
2162 // Material-owned programs built so far, CUMULATIVE. Read-only: an observer
2163 // that had to ask for readiness to see it would be the one paying, and the
2164 // frame it asked about would be clean because of the asking.
2165 if (ctx.materials != nullptr) {
2166 ES_PROFILE_COUNTER("render.mesh.materialPrograms", ctx.materials->builtVariantCount());
2167 }
2168 if (compiled_this_frame_ > 0) {
2169 ES_PROFILE_COUNTER("render.mesh.compiledKey", last_compiled_variant_);
2170 }
2171 compiled_this_frame_ = 0;
2172}
2173
2174} // namespace esengine
The single submission face: the ONLY place a DrawCommand is assembled.
The rotation that turns a card to a view.
A mesh that turns to whoever looks at it.
Per-frame CPU scope timing (ES_PROFILE_SCOPE) read by the editor profiler.
#define ES_PROFILE_COUNTER(name, value)
Which direction each picture of an impostor atlas is taken from, and which picture a view is shown.
A picture of a mesh, taken from many directions, drawn in its place once it is small.
The cheaper geometry that may stand in for a MeshRenderer once it is small.
Logging utilities for ESEngine.
#define ES_LOG_WARN(...)
Logs a warning message.
Definition Log.hpp:294
Engine-side material registry — the resolved "how to draw" for a material handle.
Shared mesh LOD eligibility and local bounds for drawing and shadow fitting.
Arbitrary-geometry 2D mesh renderable (deformed sprites, polygons, water surfaces,...
Geometry that lives on the GPU rather than in a frame.
The shapes one draw is blended towards: which targets, and how far.
Conservative mesh reach and affine stretch for native placements.
The indirect light where ONE draw stands, when a grid was baked for it.
Rendering context containing all renderer state.
Frame resources and the shared scene rendering contract.
Parser for unified .esshader file format.
Skinned meshes posed once a frame by a compute shader, into vertices every pass then draws as they ar...
GPU texture abstraction for 2D images.
Unified Transform component with local and world-space data.
static FrameProfiler & get()
static constexpr GfxContent transient()
Abstract graphics device interface.
Definition GfxDevice.hpp:75
BufferHandle createBuffer(const BufferDesc &desc, GfxContent content, const void *initialData)
Creates a buffer with fixed capacity and optional initial contents.
bool programReady(ShaderHandle program)
Whether program can be drawn with now, without waiting: linked, or finished linking in the background...
bool skipPendingPrograms() const
void deleteBuffer(BufferHandle buffer)
Deletes a buffer.
void updateBuffer(BufferHandle buffer, u32 offsetBytes, const void *data, u32 sizeBytes)
Updates a sub-range of a buffer; must fit within its capacity.
void resizeBuffer(BufferHandle buffer, u32 sizeBytes, const void *data)
Re-specifies a buffer's store with a new capacity, discarding prior contents.
u64 deviceGeneration() const
Which generation of the device the live GPU objects belong to.
void collect(RenderCollectContext &ctx) override
bool castInputs(RenderFrameContext &ctx, ecs::Registry &registry, u64 &key) override
For a plugin that casts: one number for everything its depth collect reads apart from the shadow view...
bool clusterInspect(u32 entityId, u32 &triangles, u32 &clusters) const override
What the last frames drew of the Cluster LOD mesh of the entity entityId.
RenderPrewarmResult prewarm(RenderFrameContext &ctx, ecs::Registry &registry, const Entity *entities, u32 count, bool shadowPasses) override
RenderPrewarmResult prewarmFacts(RenderFrameContext &ctx, const MeshProgramFacts *facts, u32 count, bool shadowPasses, bool residentGeometry)
Ready programs from facts already gathered — the door a PREPARED cell comes through,...
RenderPrewarmResult prewarmDocument(RenderFrameContext &ctx, const MeshDocumentRecord *rows, u32 count, bool shadowPasses) override
The same readiness, asked of a PREPARED cell's own description.
void init(RenderFrameContext &ctx) override
bool castHeldInputs(u64 &key) const override
Buffers, the layout that describes them, and the bounds culling reads.
Definition Mesh.hpp:85
glm::vec3 localMin
Definition Mesh.hpp:143
std::vector< MeshSkinChunk > skinChunks
Definition Mesh.hpp:178
VertexLayoutHandle layout
Definition Mesh.hpp:93
u32 arenaFirstVertex
Definition Mesh.hpp:105
BufferHandle vertexBuffer
Definition Mesh.hpp:91
bool hasTangents
Definition Mesh.hpp:136
resource::VertexBufferHandle vertices
Definition Mesh.hpp:87
bool isChunked() const
Definition Mesh.hpp:186
bool hasLightmapUV
Definition Mesh.hpp:132
glm::vec3 localMax
Definition Mesh.hpp:144
resource::IndexBufferHandle indices
Definition Mesh.hpp:88
std::shared_ptr< const lod::ClusterHierarchy > clusters
Definition Mesh.hpp:171
u32 indexCount
Definition Mesh.hpp:95
bool isDrawable() const
Definition Mesh.hpp:199
bool hasEdges() const
Definition Mesh.hpp:118
bool hasNormals
Definition Mesh.hpp:127
BufferHandle edgeIndexBuffer
Definition Mesh.hpp:114
u32 edgeIndexCount
Definition Mesh.hpp:115
std::vector< u16 > skinChunkBones
Definition Mesh.hpp:185
TextureHandle morphTexture
Definition Mesh.hpp:155
BufferHandle indexBuffer
Definition Mesh.hpp:92
The frame's probe volumes, and the trilinear read through them.
u32 atlasTexture() const
bool sampleBox(const glm::vec3 &centre, const glm::vec3 &half, ProbeConstants &out, bool perPixel=false) const
The volume a whole object stands in, by its world box rather than its origin.
void noteDraw(bool perPixel) const
Counts a draw that read a volume this frame, per pixel or per object: what the stats say a frame paid...
2D texture for GPU rendering
Definition Texture.hpp:116
Central container for all entities and components.
Definition Registry.hpp:73
bool anyChangedSince(u32 tick) const
Whether any T was written, added or removed after tick: the question a frame that may skip its walk a...
Definition Registry.hpp:220
u32 activityEpoch() const
Definition Registry.hpp:122
usize countOf() const
How many entities have a T.
Definition Registry.hpp:284
bool anyChangedSinceWhere(u32 tick, Visit &&visit) const
Calls visit(entity) for each T written or added after tick, until it returns true; returns whether on...
Definition Registry.hpp:232
bool has(Entity entity) const
Checks if an entity has a specific component.
Definition Registry.hpp:711
u32 beginChangeRead()
For a reader about to look: the tick it is looking at, after which the clock moves on.
Definition Registry.hpp:173
u64 identity() const
Which registry this is, never shared with another made in this process (a registry assigned over this...
Definition Registry.hpp:166
T * tryGet(Entity entity)
Tries to get a component from an entity.
Definition Registry.hpp:670
bool isValid() const
Checks if the handle references a valid resource.
Definition Handle.hpp:82
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.
glm::quat facing(i32 mode, const glm::mat4 &viewProjection, const glm::vec4 &eye, const glm::vec3 &position)
The rotation a card standing at position is drawn with in this view.
bool tickAfter(u32 a, u32 b)
Whether stamp a is later than tick b, across a wrap of the counter (stamps are kept within half its r...
constexpr u64 combine(u64 h, u64 v)
Definition Hash.hpp:33
constexpr u64 kFnv64Offset
Definition Hash.hpp:12
glm::uvec2 nearestFrame(const glm::vec3 &d, u32 frames)
The frame taken nearest d, a direction from the object toward the viewer in the object's own space.
glm::vec3 frameDirection(u32 i, u32 j, u32 frames)
The direction, from the object toward the camera, that frame (i, j) is taken from.
glm::vec3 pictureUp(const glm::vec3 &d)
The up a picture is taken with from d: world up laid flat across the view.
u8 selectLevel(const LevelSet &set, f32 size, u8 current)
The level size asks for, given the one shown last.
f32 screenRelativeSize(const glm::mat4 &viewProjection, const glm::vec3 &centre, f32 radius)
How much of the viewport's HEIGHT a sphere covers: 1 = one screen high.
u32 selectClusters(const ClusterHierarchy &hierarchy, const ClusterEye &eye, std::vector< u32 > &out)
The clusters eye draws, in the hierarchy's order, into out. Returns the indices they hold together.
u64 cutSignature(const std::vector< u32 > &picked)
A number that changes when the picked clusters do: two cuts with the same one are drawn from the same...
constexpr u8 kCulled
The level of an object small enough that nothing is drawn for it.
void boundingSphere(const glm::vec3 &position, const glm::quat &rotation, const glm::vec3 &scale, const glm::vec3 &localMin, const glm::vec3 &localMax, glm::vec3 &outCentre, f32 &outRadius)
The sphere a group is measured by: its centre in the world and its radius.
void assembleCut(const ClusterHierarchy &hierarchy, const std::vector< u32 > &picked, u32 vertexBase, std::vector< u32 > &out)
The picked clusters' indices, one run after another, into out.
void transformedBox(const glm::mat3 &parent, const f32 *rows, const glm::vec3 &origin, const glm::vec3 &localCentre, const glm::vec3 &localHalf, glm::vec3 &centre, glm::vec3 &half)
f32 radius(const glm::vec3 &lo, const glm::vec3 &hi, f32 displacement)
Handle< esengine::Shader > ShaderHandle
Handle to a shader resource.
Definition Handle.hpp:214
Handle< esengine::Texture > TextureHandle
Handle to a texture resource.
Definition Handle.hpp:217
Handle< esengine::Mesh > MeshHandle
Handle to GPU-resident geometry.
Definition Handle.hpp:226
static constexpr u32 MORPH_TEXTURE_WIDTH
Definition GfxEnums.hpp:145
void appendQuad(TransientBufferPool &pool, DrawList &drawList, const ClipState &clips, const BatchVertex quad[4], const BatchDrawKey &key)
void meshLocalBounds(const Mesh &base, const Mesh *coarse, f32 displacement, glm::vec3 &lo, glm::vec3 &hi)
static constexpr u32 MESH_INSTANCE_STRIDE
Definition GfxEnums.hpp:121
double es_profile_now_ms()
std::uint64_t u64
Unsigned 64-bit integer.
Definition Types.hpp:47
constexpr u64 kClusterCutIdleCollects
Collects a cut may go undrawn before its buffer is given back. A frame has several: the scene's,...
static constexpr u32 MESH_INSTANCE_TEXELS
Definition GfxEnums.hpp:108
void pushBatchDraw(DrawList &drawList, const ClipState &clips, u32 vertexByteOffset, u32 vertexCount, u32 indexOffset, u32 indexCount, const BatchDrawKey &key)
Atomic primitive: assemble + clip + push one DrawCommand for an index range ALREADY written into (or,...
std::size_t usize
Size type for indexing and sizes.
Definition Types.hpp:64
static constexpr u32 MESH_INSTANCE_TEXEL_LIGHTMAP
Definition GfxEnums.hpp:118
static constexpr u32 MESH_INSTANCE_TEXEL_TINT
Definition GfxEnums.hpp:112
static constexpr u32 MESH_INSTANCE_MAX_RECORDS
Definition GfxEnums.hpp:128
std::int16_t i16
Signed 16-bit integer.
Definition Types.hpp:52
glm::vec3 parallaxedWorldPosition(ecs::Transform &transform, const glm::vec2 &parallax, const CameraView &camera)
u32 packColor(f32 r, f32 g, f32 b, f32 a)
bool shadesAsClay(ShadingMode mode)
Whether a mode draws meshes as clay (the lit neutral surface).
constexpr f32 kClusterPixelError
The error a clustered mesh may show, in pixels of the scene view, before a finer cluster is drawn.
std::uint32_t u32
Unsigned 32-bit integer.
Definition Types.hpp:45
glm::mat4 modelFromOrigin(const glm::mat4 &model, const glm::dvec3 &origin)
A model placed from origin, as it is placed from the origin now.
glm::vec3 rebased(const glm::vec3 &world)
A world position as the frame draws it: from the origin.
std::uint8_t u8
Unsigned 8-bit integer.
Definition Types.hpp:41
ShadingMode
What a mesh is drawn WITH in a view, whatever its own material says.
@ Wireframe
A dark surface with every triangle edge drawn on it, hidden edges hidden.
@ Shaded
Each mesh as authored: its material, its textures, its light.
@ Albedo
Base colour and texture with no light and no material: what was painted.
static constexpr u32 MESH_MAX_ACTIVE_MORPHS
Definition GfxEnums.hpp:142
glm::dvec3 & renderOrigin()
The origin, in world units. A double, as the world positions it is taken from are far from zero.
SkinCacheUsage
A mesh's own word on the cache (MeshSkin::skinCache).
Definition SkinCache.hpp:43
void appendIndexedBatch(TransientBufferPool &pool, DrawList &drawList, const ClipState &clips, const BatchVertex *verts, u32 vertexCount, const u32 *localIndices, u32 indexCount, const BatchDrawKey &key)
Copies verts into the Batch stream, then pushes one DrawCommand spanning them.
double f64
64-bit floating point
Definition Types.hpp:61
static constexpr u32 MESH_INSTANCE_TEXEL_NORMAL
Definition GfxEnums.hpp:115
constexpr u64 kClusterCutFreshCollects
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)
static constexpr u32 MESH_INSTANCE_TEXEL_MODEL
Definition GfxEnums.hpp:111
const Mesh * placementCoarseMesh(resource::ResourceManager &resources, const Mesh &base, const ecs::MeshInstances &placements)
static EstellaContext & ctx()
@ Lines
Every two indices a line segment: a mesh's edges, for a diagnostic view.
float f32
32-bit floating point
Definition Types.hpp:59
static constexpr u32 MESH_MAX_BONES
Definition GfxEnums.hpp:138
Non-geometry attributes of a batch draw — everything needed to build the sort key + DrawCommand.
i16 depthBias
Depth-buffer units toward the eye.
GfxTopology topology
How the indices assemble.
u8 cull
CullMode: 0 = none, 1 = back, 2 = front.
VertexLayoutHandle vertexLayout
One vertex of the shared batch stream.
f32 viewDepth(const glm::vec3 &worldPos) const
How near worldPos is to the viewer, larger = nearer — the order the sort key wants,...
Entity identifier with packed index + generation.
Definition Types.hpp:135
constexpr u32 id() const
Returns the raw packed value for FFI serialization.
Definition Types.hpp:159
bool intersectsAABB(const glm::vec3 &center, const glm::vec3 &halfExtents) const
const Mesh * mesh[lod::kMaxStandIns+1]
A material's resolved render state (P0) plus its packed std140 constants (P1).
What a renderable's program key is made of, with no say in where the facts came from — a live entity'...
One piece a skinned mesh is drawn in, when its bones are more than one draw can carry.
Definition Mesh.hpp:68
One draw's shapes, laid out as the texels they are written as.
The indirect light one instance stands in — both halves of it.
bool follow
Read the level view settled on instead of choosing one: what a shadow cast for that view's picture is...
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.
ShadingMode shading
How the meshes of THIS collect are shaded. Shaded unless the view asked for another mode; a collect t...
bool castsIntoView(const glm::vec3 &centre, f32 radius)
Whether a caster bounded by a sphere can shade anything the camera sees. True where this collect asks...
bool visible(const glm::vec3 &centre, const glm::vec3 &halfExtents, bool depthTested)
Whether a renderable bounded by centre / halfExtents is drawn.
const std::unordered_set< u32 > * selection
A motion collect that draws the editor's selection mask instead (RenderFrame::collectSelection): only...
An impostor's pictures: the atlas texture and how many frames along its side.
What readying a set of renderables' programs found. Counts, not JSON: this crosses no boundary and pa...
bool addKey(u32 variant)
Whether this key is already in the set; adds it if not.
static u64 materialKey(u32 materialId, bool normals, bool skinned, bool envMapped, bool lightmapped, bool tangents=false)
What a material program is asked for, as one comparable value.
Turns the MeshRenderer beside it to face each view that draws it.
Definition Billboard.hpp:37
Stands a card in for the MeshRenderer beside it once the object covers less than screenSize of the vi...
Definition Impostor.hpp:32
Stand-in geometry chosen by how much of the screen the object covers.
Definition LODGroup.hpp:30
Many placements of the one mesh a MeshRenderer draws, as ONE renderable.
glm::vec3 originMin
The corners of the instances' ORIGINS and the greatest scale among them: with the mesh's own reach,...
std::vector< f32 > transforms
Sixteen floats an instance: the model's three rows (translation in .w) then its tint RGBA,...
Where a MeshRenderer's BAKED light comes from: the atlas, and the rectangle of it this object occupie...
What SHAPE a MeshRenderer is in: how far it is blended towards each of the shapes its mesh carries.
u32 material
Custom material ID (0 = use default batch shader).
glm::vec4 color
Color tint multiplied with per-vertex colors (white = unchanged).
resource::TextureHandle texture
Texture sampled by the mesh UVs (invalid = untextured, vertex colors only).
glm::vec2 parallax
Parallax scroll factor per axis. 1 = moves with the world (default, no parallax); <1 = scrolls slower...
bool opaque
Drawn as an opaque surface: no blending, and it takes part in depth — which is what lets one mesh hid...
resource::MeshHandle mesh
Geometry from an .esmesh, drawn INSTEAD of the inline vertices.
What deforms a MeshRenderer: the entities its Joints channel indexes.
Unified transform component.
Definition Transform.hpp:45
A mesh's clusters and the indices they name, every level together.