载入中...
搜索中...
未找到
Shadow.cpp
浏览该文件的文档.
1#include "graphics/Shadow.h"
2#include <algorithm>
3#include <cmath>
4#include <cstdlib>
5#include <glm/gtc/matrix_transform.hpp>
6#include "common/Diagnostic.h"
9
10// Shadow.cpp
11namespace eve::graphics {
12
13namespace {
14
15glm::mat4 cascadeVP(const glm::vec3& lightDir, const glm::vec3& eye, const glm::vec3& target, const glm::vec3& up,
16 float fovYRad, float aspect, float nearZ, float farZ, float mapSize, float* texelWorldOut,
17 float* zRangeOut) {
18 const glm::mat4 view = glm::lookAtRH(eye, target, up);
19 // Match the camera projection used by RenderSystem3D so frustum corners align.
20 const glm::mat4 proj = perspectiveVulkanRH_ZO(fovYRad, aspect, nearZ, farZ);
21 const glm::mat4 inv = glm::inverse(proj * view);
22
23 // NDC cube corners → world
24 glm::vec3 corners[8];
25 int idx = 0;
26 for (int z = 0; z < 2; ++z)
27 for (int y = 0; y < 2; ++y)
28 for (int x = 0; x < 2; ++x) {
29 const glm::vec4 ndc(x ? 1.f : -1.f, y ? 1.f : -1.f, z ? 1.f : 0.f, 1.f);
30 glm::vec4 w = inv * ndc;
31 w /= w.w;
32 corners[idx++] = glm::vec3(w);
33 }
34
35 glm::vec3 worldCenter(0.f);
36 for (int i = 0; i < 8; ++i) worldCenter += corners[i];
37 worldCenter *= 0.125f;
38 float radius = 0.5f;
39 for (int i = 0; i < 8; ++i) radius = std::max(radius, glm::length(corners[i] - worldCenter));
40
41 glm::vec3 L = glm::normalize(lightDir);
42 if (glm::length(L) < 1e-6f) L = glm::vec3(0.f, 1.f, 0.f);
43 glm::vec3 lightUp(0.f, 1.f, 0.f);
44 if (std::abs(glm::dot(L, lightUp)) > 0.95f) lightUp = glm::vec3(0.f, 0.f, 1.f);
45 // Camera-independent view: rotation from L only. If lookAt follows the
46 // frustum center, static receivers crawl in shadow UV as the camera moves
47 // (Cornell floor: large jagged umbrae swimming/flickering).
48 const glm::mat4 lightView = glm::lookAtRH(L * 50.f, glm::vec3(0.f), lightUp);
49
50 glm::vec3 minB(1e9f), maxB(-1e9f);
51 for (int i = 0; i < 8; ++i) {
52 const glm::vec3 lp = glm::vec3(lightView * glm::vec4(corners[i], 1.f));
53 minB = glm::min(minB, lp);
54 maxB = glm::max(maxB, lp);
55 }
56 glm::vec3 centerLS = glm::vec3(lightView * glm::vec4(worldCenter, 1.f));
57
58 const float zPad = (maxB.z - minB.z) * 0.1f + 0.5f;
59 minB.z -= zPad;
60 // Pad toward the light so casters just outside the view frustum still
61 // write depth. Cornell: camera looks slightly down, the ceiling sits
62 // above the cascade near plane and never occludes the left/top creases.
63 maxB.z += zPad + 2.f;
64 if (zRangeOut) *zRangeOut = std::max(-minB.z - (-maxB.z), 1e-3f);
65
66 const float atlasSize = std::max(mapSize, 1.f);
67 // World-space frustum sphere radius is pose-invariant for a given split, so
68 // the texel grid does not rescale as the camera rotates.
69 const float texelWorld = (2.f * radius) / atlasSize;
70 if (texelWorldOut) *texelWorldOut = texelWorld;
71
72 auto snap = [&](float v) { return std::floor(v / texelWorld) * texelWorld; };
73 centerLS.x = snap(centerLS.x);
74 centerLS.y = snap(centerLS.y);
75
76 const glm::mat4 lightProj = orthoVulkanRH_ZO(centerLS.x - radius, centerLS.x + radius, centerLS.y - radius,
77 centerLS.y + radius, -maxB.z, -minB.z);
78 return lightProj * lightView;
79}
80
81} // namespace
82
83ShadowUpload buildDirectionalCSM(const glm::vec3& lightDirTowardSurface, const glm::vec3& eye, const glm::vec3& target,
84 const glm::vec3& up, float fovYRad, float aspect, float nearZ, float farZ, float bias,
85 float strength) {
87 out.active = true;
88 const auto& scheme = ShadowSchemeSettings::current();
89 const int atlasSize = scheme.resolvedAtlasMapSize();
90 const float maxDistance = scheme.resolvedDirectionalMaxDistance();
91 const float n = std::max(nearZ, 1e-3f);
92 const float fCam = std::max(farZ, n + 1e-2f);
93 const float f = std::min(fCam, std::max(n + 1e-2f, maxDistance));
94 const float ratio = f / n;
95 float splits[ShadowConfig::kCascades + 1];
96 splits[0] = n;
97 for (int i = 1; i <= ShadowConfig::kCascades; ++i) {
98 const float p = float(i) / float(ShadowConfig::kCascades);
99 const float logS = n * std::pow(ratio, p);
100 const float uniS = n + (f - n) * p;
101 splits[i] = ShadowConfig::kSplitLambda * logS + (1.f - ShadowConfig::kSplitLambda) * uniS;
102 }
103
104 float screenCoverage[ShadowConfig::kCascades]{};
105 for (int i = 0; i < ShadowConfig::kCascades; ++i) {
106 screenCoverage[i] = estimateCascadeScreenCoverage(eye, target, up, fovYRad, aspect, splits[i], splits[i + 1]);
107 }
108 const AdaptiveCascadeAllocation alloc =
109 allocateAdaptiveCascadeResolutions(atlasSize, splits, screenCoverage, scheme);
110 out.atlasMapSize = alloc.atlasSize;
111
112 float cascadeNdc[ShadowConfig::kCascades]{};
113 float cascadeTexel[ShadowConfig::kCascades]{};
114 float uvScale[ShadowConfig::kCascades]{};
115 for (int i = 0; i < ShadowConfig::kCascades; ++i) {
116 float texelWorld = 0.f;
117 float zRange = 1.f;
118 out.cascadeMapSizes[i] = alloc.sizes[i];
119 out.ubo.lightVP[i] = cascadeVP(lightDirTowardSurface, eye, target, up, fovYRad, aspect, splits[i],
120 splits[i + 1], float(alloc.sizes[i]), &texelWorld, &zRange);
121 // ~0.6 texels of world bias. More than that, projected onto a grazing
122 // Cornell wall, becomes a multi-pixel bright rim on the left/top of
123 // the umbra (peter-panning at the box/wall crease).
124 const float autoNdc = std::clamp((0.6f * texelWorld) / zRange, 1e-5f, 0.01f);
125 cascadeNdc[i] = std::max(std::max(0.f, bias), autoNdc);
126 cascadeTexel[i] = texelWorld;
127 uvScale[i] = float(alloc.sizes[i]) / float(std::max(alloc.atlasSize, 1));
128 }
129 const float perceptualStrength = std::sqrt(std::clamp(strength, 0.f, 1.f));
130 out.ubo.splits = glm::vec4(splits[1], splits[2], splits[3], perceptualStrength);
131 out.ubo.cascadeBias = glm::vec4(cascadeNdc[0], cascadeNdc[1], cascadeNdc[2], 0.f);
132 out.ubo.cascadeTexel = glm::vec4(cascadeTexel[0], cascadeTexel[1], cascadeTexel[2], 0.f);
133 out.ubo.bias = glm::vec4(cascadeNdc[0], 1.f, 1.f, 0.02f);
134 out.ubo.cascadeUvScale = glm::vec4(uvScale[0], uvScale[1], uvScale[2], float(alloc.atlasSize));
135 return out;
136}
137
138} // namespace eve::graphics
139
140// ShadowScheme.cpp
141namespace eve::graphics {
142namespace {
143
144ShadowSchemeSettings g_shadowSchemeSettings{};
145
146struct LocalPageCacheEntry {
147 Light3D::Data* light = nullptr;
148 glm::mat4 lightVP{1.f};
149 float bias = 0.002f;
150 float x = 0.f, y = 0.f, z = 0.f;
151 float dx = 0.f, dy = 0.f, dz = 0.f;
152 float radius = 0.f;
153 float spotAngleDeg = 0.f;
154 float shadowStrength = 1.f;
155 bool occupied = false;
156};
157
158struct LocalPageCache {
159 LocalPageCacheEntry slots[ShadowConfig::kLocalSlots]{};
160};
161
162LocalPageCache g_localPageCache{};
163
164bool equalsIgnoreCase(std::string_view a, std::string_view b) {
165 if (a.size() != b.size()) return false;
166 for (size_t i = 0; i < a.size(); ++i) {
167 const char ca = (a[i] >= 'A' && a[i] <= 'Z') ? char(a[i] - 'A' + 'a') : a[i];
168 const char cb = (b[i] >= 'A' && b[i] <= 'Z') ? char(b[i] - 'A' + 'a') : b[i];
169 if (ca != cb) return false;
170 }
171 return true;
172}
173
174glm::vec3 safeNormalize(const glm::vec3& v, const glm::vec3& fallback) {
175 const float len = glm::length(v);
176 return len > 1e-6f ? v / len : fallback;
177}
178
179bool lightParamsMatchCache(const Light3D::Data& d, const LocalPageCacheEntry& e, float resolvedBias) {
180 constexpr float kEps = 1e-4f;
181 return e.occupied && e.light == &d && std::abs(e.x - d.x) < kEps && std::abs(e.y - d.y) < kEps &&
182 std::abs(e.z - d.z) < kEps && std::abs(e.dx - d.dx) < kEps && std::abs(e.dy - d.dy) < kEps &&
183 std::abs(e.dz - d.dz) < kEps && std::abs(e.radius - d.radius) < kEps &&
184 std::abs(e.spotAngleDeg - d.spotAngleDeg) < kEps && std::abs(e.shadowStrength - d.shadowStrength) < kEps &&
185 std::abs(e.bias - resolvedBias) < kEps;
186}
187
188void storeCacheEntry(LocalPageCacheEntry& e, Light3D::Data* d, const glm::mat4& vp, float bias) {
189 e = LocalPageCacheEntry{};
190 e.occupied = d != nullptr;
191 e.light = d;
192 e.lightVP = vp;
193 e.bias = bias;
194 if (!d) return;
195 e.x = d->x;
196 e.y = d->y;
197 e.z = d->z;
198 e.dx = d->dx;
199 e.dy = d->dy;
200 e.dz = d->dz;
201 e.radius = d->radius;
202 e.spotAngleDeg = d->spotAngleDeg;
203 e.shadowStrength = d->shadowStrength;
204}
205
206int findCachedSlot(Light3D::Data* light) {
207 if (!light) return -1;
208 for (int s = 0; s < ShadowConfig::kLocalSlots; ++s) {
209 if (g_localPageCache.slots[s].occupied && g_localPageCache.slots[s].light == light) return s;
210 }
211 return -1;
212}
213
214} // namespace
215
216ShadowSchemeSettings& ShadowSchemeSettings::current() { return g_shadowSchemeSettings; }
217
219 static constexpr int kAllowed[] = {256, 512, 1024, 2048, 4096};
220 if (size <= kAllowed[0]) return kAllowed[0];
221 int best = kAllowed[0];
222 int bestDist = std::abs(size - best);
223 for (int candidate : kAllowed) {
224 const int dist = std::abs(size - candidate);
225 if (dist < bestDist) {
226 best = candidate;
227 bestDist = dist;
228 }
229 }
230 return best;
231}
232
233int shadowMapSizeForResolutionTier(int resolutionTier) {
234 switch (resolutionTier) {
235 case 0: return 512;
236 case 1: return 1024;
237 case 2: return 2048;
238 default: return 4096;
239 }
240}
241
243 const int directional = clampShadowMapSize(directionalMapSize);
245 return std::max(directional, local);
246}
247
252
253Result<void> setShadowSchemeMapSizes(int directionalMapSize, int localMapSize) {
254 if (directionalMapSize <= 0) {
256 DiagnosticCode::InvalidArgument, "directional shadow map size must be positive", "graphics.shadow"));
257 }
259 settings.directionalMapSize = clampShadowMapSize(directionalMapSize);
260 if (localMapSize > 0) {
261 settings.localMapSize = clampShadowMapSize(localMapSize);
262 } else if (localMapSize == 0) {
264 DiagnosticCode::InvalidArgument, "local shadow map size must be positive when set", "graphics.shadow"));
265 }
266 return Result<void>::success();
267}
268
270 if (!std::isfinite(meters) || meters <= 0.f) {
272 "directional shadow max distance must be finite and > 0",
273 "graphics.shadow"));
274 }
276 return Result<void>::success();
277}
278
279namespace {
280
281int g_adaptiveCascadeSizes[ShadowConfig::kCascades] = {0, 0, 0};
282int g_adaptiveCascadeAtlas = 0;
283
284} // namespace
285
286float estimateCascadeScreenCoverage(const glm::vec3& eye, const glm::vec3& target, const glm::vec3& up, float fovYRad,
287 float aspect, float nearZ, float farZ) {
288 const float n = std::max(nearZ, 1e-3f);
289 const float f = std::max(farZ, n + 1e-3f);
290 const glm::mat4 view = glm::lookAtRH(eye, target, up);
291 const glm::mat4 proj = perspectiveVulkanRH_ZO(fovYRad, aspect, n, f);
292 const glm::mat4 inv = glm::inverse(proj * view);
293 glm::vec2 minNdc(1.f), maxNdc(-1.f);
294 int valid = 0;
295 for (int z = 0; z < 2; ++z)
296 for (int y = 0; y < 2; ++y)
297 for (int x = 0; x < 2; ++x) {
298 const glm::vec4 ndcCorner(x ? 1.f : -1.f, y ? 1.f : -1.f, z ? 1.f : 0.f, 1.f);
299 glm::vec4 world = inv * ndcCorner;
300 if (std::abs(world.w) < 1e-8f) continue;
301 world /= world.w;
302 // Reproject with a long camera frustum so coverage reflects how
303 // much of the *current view* this slice occupies (silhouette /
304 // shadow-edge importance across the frame).
305 const glm::mat4 viewLong = view;
306 const glm::mat4 projLong = perspectiveVulkanRH_ZO(fovYRad, aspect, n, std::max(f, n + 1.f) * 4.f);
307 const glm::vec4 clip = projLong * viewLong * glm::vec4(glm::vec3(world), 1.f);
308 if (std::abs(clip.w) < 1e-8f) continue;
309 const glm::vec2 ndc(clip.x / clip.w, clip.y / clip.w);
310 minNdc = glm::min(minNdc, ndc);
311 maxNdc = glm::max(maxNdc, ndc);
312 ++valid;
313 }
314 if (valid < 4) return 0.f;
315 minNdc = glm::clamp(minNdc, glm::vec2(-1.f), glm::vec2(1.f));
316 maxNdc = glm::clamp(maxNdc, glm::vec2(-1.f), glm::vec2(1.f));
317 const float area = std::max(0.f, maxNdc.x - minNdc.x) * std::max(0.f, maxNdc.y - minNdc.y);
318 return std::clamp(area * 0.25f, 0.f, 1.f);
319}
320
322 const float (&splitEnds)[ShadowConfig::kCascades + 1],
323 const float (&screenCoverage)[ShadowConfig::kCascades],
326 const int atlas = clampShadowMapSize(atlasSize);
327 out.atlasSize = atlas;
328 if (!settings.enableAdaptiveCascadeResolution) {
329 for (int i = 0; i < ShadowConfig::kCascades; ++i) out.sizes[i] = atlas;
330 return out;
331 }
332
334 float scoreSum = 0.f;
335 for (int i = 0; i < ShadowConfig::kCascades; ++i) {
336 const float nearS = splitEnds[i];
337 const float farS = splitEnds[i + 1];
338 const float mid = std::max(0.5f * (nearS + farS), 0.25f);
339 // Near camera → higher score. Screen coverage boosts cascades that
340 // paint large / edge-heavy regions of the frame.
341 const float distanceTerm = settings.adaptiveDistanceWeight / mid;
342 const float screenTerm = settings.adaptiveScreenWeight * std::clamp(screenCoverage[i], 0.f, 1.f);
343 score[i] = std::max(1e-4f, distanceTerm + screenTerm);
344 // Prefer monotonic near > far even when a distant cascade fills the screen.
345 score[i] *= (1.f + 0.35f * float(ShadowConfig::kCascades - 1 - i));
346 scoreSum += score[i];
347 }
348
349 // Convert scores to power-of-two edge lengths under the atlas budget.
350 // Area share ≈ score/sum, so edge ≈ atlas * sqrt(share). Near cascade is
351 // floored to at least atlas/2 so contact shadows stay sharp.
352 int sizes[ShadowConfig::kCascades]{};
353 for (int i = 0; i < ShadowConfig::kCascades; ++i) {
354 const float share = score[i] / std::max(scoreSum, 1e-4f);
355 const float edge = float(atlas) * std::sqrt(std::clamp(share * float(ShadowConfig::kCascades), 0.05f, 1.f));
356 sizes[i] = clampShadowMapSize(int(std::lround(edge)));
357 }
358 sizes[0] = std::max(sizes[0], clampShadowMapSize(atlas / 2));
359 sizes[0] = std::min(sizes[0], atlas);
360 for (int i = 1; i < ShadowConfig::kCascades; ++i) sizes[i] = std::min(sizes[i], sizes[i - 1]);
361
362 // Hysteresis against last frame to avoid size ping-pong when coverage wobbles.
363 if (g_adaptiveCascadeAtlas == atlas) {
364 const float hyst = std::clamp(settings.adaptiveSizeHysteresis, 0.f, 0.9f);
365 for (int i = 0; i < ShadowConfig::kCascades; ++i) {
366 const int prev = g_adaptiveCascadeSizes[i];
367 if (prev <= 0) continue;
368 const float ratio = float(sizes[i]) / float(prev);
369 if (ratio > 1.f - hyst && ratio < 1.f + hyst) sizes[i] = prev;
370 }
371 for (int i = 1; i < ShadowConfig::kCascades; ++i) sizes[i] = std::min(sizes[i], sizes[i - 1]);
372 }
373 for (int i = 0; i < ShadowConfig::kCascades; ++i) {
374 out.sizes[i] = sizes[i];
375 g_adaptiveCascadeSizes[i] = sizes[i];
376 }
377 g_adaptiveCascadeAtlas = atlas;
378 return out;
379}
380
382 for (auto& slot : g_localPageCache.slots) slot = LocalPageCacheEntry{};
383 for (int& s : g_adaptiveCascadeSizes) s = 0;
384 g_adaptiveCascadeAtlas = 0;
385}
386
388 if (equalsIgnoreCase(name, "auto")) return Result<ShadowMethod>::success(ShadowMethod::Auto);
389 if (equalsIgnoreCase(name, "none") || equalsIgnoreCase(name, "off"))
391 if (equalsIgnoreCase(name, "csm") || equalsIgnoreCase(name, "cascaded") || equalsIgnoreCase(name, "directional"))
393 if (equalsIgnoreCase(name, "perspective") || equalsIgnoreCase(name, "spot"))
395 if (equalsIgnoreCase(name, "cube") || equalsIgnoreCase(name, "cubemap") || equalsIgnoreCase(name, "point"))
398 Diagnostic::error(DiagnosticCode::InvalidArgument, "Unknown shadow method", "graphics.shadow"));
399}
400
402 switch (method) {
403 case ShadowMethod::Auto: return "auto";
404 case ShadowMethod::None: return "none";
405 case ShadowMethod::CascadedDirectional: return "csm";
406 case ShadowMethod::PerspectiveSpot: return "perspective";
407 case ShadowMethod::CubePoint: return "cube";
408 }
409 return "none";
410}
411
412Result<ShadowMethod> resolveShadowMethod(std::string_view lightType, ShadowMethod requested) {
413 ShadowMethod method = requested;
414 if (method == ShadowMethod::Auto) {
415 if (lightType == "dir")
417 else if (lightType == "spot")
419 else if (lightType == "point")
421 else
423 }
425 if (lightType == "dir" && method != ShadowMethod::CascadedDirectional) {
427 DiagnosticCode::Unsupported, "Directional lights only support csm shadows", "graphics.shadow"));
428 }
429 if (lightType == "spot" && method != ShadowMethod::PerspectiveSpot) {
431 DiagnosticCode::Unsupported, "Spot lights only support perspective shadows", "graphics.shadow"));
432 }
433 if (lightType == "point" && method != ShadowMethod::CubePoint) {
435 DiagnosticCode::Unsupported, "Point lights only support cube shadows", "graphics.shadow"));
436 }
438}
439
440glm::mat4 buildSpotShadowVP(const glm::vec3& position, const glm::vec3& direction, float range, float outerAngleDeg) {
441 const glm::vec3 forward = safeNormalize(direction, glm::vec3(0.f, -1.f, 0.f));
442 glm::vec3 up(0.f, 1.f, 0.f);
443 if (std::abs(glm::dot(forward, up)) > 0.95f) up = glm::vec3(0.f, 0.f, 1.f);
444 const float farZ = std::max(range, 1e-2f);
445 const float nearZ = std::max(farZ * 0.01f, 0.05f);
446 const float fovY = std::clamp(outerAngleDeg, 0.1f, 89.f) * 2.f * 0.017453292519943295f;
447 const glm::mat4 view = glm::lookAtRH(position, position + forward, up);
448 const glm::mat4 proj = perspectiveVulkanRH_ZO(fovY, 1.f, nearZ, farZ);
449 return proj * view;
450}
451
452Result<glm::mat4> buildPointShadowFaceVP(const glm::vec3& position, int faceIndex, float range) {
453 if (faceIndex < 0 || faceIndex > 5) {
455 Diagnostic::error(DiagnosticCode::InvalidArgument, "Point shadow face must be 0..5", "graphics.shadow"));
456 }
457 static const glm::vec3 kForward[6] = {
458 {1.f, 0.f, 0.f}, {-1.f, 0.f, 0.f}, {0.f, 1.f, 0.f}, {0.f, -1.f, 0.f}, {0.f, 0.f, 1.f}, {0.f, 0.f, -1.f},
459 };
460 static const glm::vec3 kUp[6] = {
461 {0.f, -1.f, 0.f}, {0.f, -1.f, 0.f}, {0.f, 0.f, 1.f}, {0.f, 0.f, -1.f}, {0.f, -1.f, 0.f}, {0.f, -1.f, 0.f},
462 };
463 const float farZ = std::max(range, 1e-2f);
464 const float nearZ = std::max(farZ * 0.01f, 0.05f);
465 const glm::mat4 view = glm::lookAtRH(position, position + kForward[faceIndex], kUp[faceIndex]);
466 const glm::mat4 proj = perspectiveVulkanRH_ZO(1.5707963267948966f, 1.f, nearZ, farZ);
468}
469
471 const ShadowSchemeSettings& settings, bool hadSlot) {
472 float score = std::max(light.intensity, 0.f);
473 if (settings.enableLocalPaging && view.valid) {
474 const glm::vec3 pos(light.x, light.y, light.z);
475 const float dist = std::max(glm::length(pos - view.eye), 0.1f);
476 const float range = std::max(light.radius, 0.1f);
477 const float atten = std::clamp(1.f - dist / (range * 2.f + dist), 0.f, 1.f);
478 const float coverage = std::clamp(range / dist, 0.f, 4.f);
479 const glm::vec4 clip = view.viewProj * glm::vec4(pos, 1.f);
480 float frustum = 0.02f;
481 if (clip.w > 1e-5f) {
482 const float invW = 1.f / clip.w;
483 const float ndcX = clip.x * invW;
484 const float ndcY = clip.y * invW;
485 const float ndcZ = clip.z * invW;
486 const float pad = coverage * 0.5f;
487 if (std::abs(ndcX) < 1.f + pad && std::abs(ndcY) < 1.f + pad && ndcZ > -pad && ndcZ < 1.f + pad) {
488 const float edge = std::max(std::abs(ndcX), std::abs(ndcY));
489 frustum = std::clamp(1.f - 0.5f * edge, 0.15f, 1.f);
490 } else {
491 frustum = 0.05f;
492 }
493 }
494 score = light.intensity * atten * (0.35f + 0.65f * std::min(coverage, 1.5f) / 1.5f) * (0.25f + 0.75f * frustum);
495 }
496 if (hadSlot) score *= (1.f + std::max(settings.hysteresisBonus, 0.f));
497 return score;
498}
499
500void selectShadowCasters(const std::vector<Light3D::Data*>& lights, const std::vector<bool>& isPointFlags,
502 Light3D::Data*& directionalCaster, std::vector<LocalShadowSlot>& localSlots) {
503 directionalCaster = nullptr;
504 localSlots.clear();
505 float bestDirI = -1.f;
506
507 struct SpotCandidate {
508 Light3D::Data* light = nullptr;
509 size_t index = 0;
510 float score = 0.f;
511 int prevSlot = -1;
512 };
513 std::vector<SpotCandidate> spots;
514 spots.reserve(lights.size());
515
516 for (size_t i = 0; i < lights.size(); ++i) {
517 Light3D::Data* d = lights[i];
518 if (!d) continue;
519 d->shadowLocalSlot = -1;
520 if (!d->enabled || !d->castShadow || d->volumetricOnly) continue;
521 const bool isPoint = i < isPointFlags.size() ? isPointFlags[i] : (d->type != "dir");
522 auto resolved = resolveShadowMethod(d->type, static_cast<ShadowMethod>(d->shadowMethod));
523 if (!resolved.ok()) continue;
524 const ShadowMethod method = resolved.value();
525 if (method == ShadowMethod::None) continue;
526
528 if (!settings.enableDirectionalCsm) continue;
529 if (d->intensity > bestDirI) {
530 bestDirI = d->intensity;
531 directionalCaster = d;
532 }
533 continue;
534 }
535 if (d->type == "spot" && method == ShadowMethod::PerspectiveSpot) {
536 if (!settings.enableSpotPerspective) continue;
537 const int prev = findCachedSlot(d);
538 const float score = scoreSpotShadowCandidate(*d, view, settings, prev >= 0);
539 if (settings.enableLocalPaging && view.valid && score < settings.minPageScore) continue;
540 spots.push_back({d, i, score, prev});
541 }
542 if (d->type == "point" && method == ShadowMethod::CubePoint && settings.enablePointCube &&
543 settings.maxPointShadowCasters > 0) {
544 // Reserved for the cube-atlas pass.
545 }
546 }
547
548 std::stable_sort(spots.begin(), spots.end(),
549 [](const SpotCandidate& a, const SpotCandidate& b) { return a.score > b.score; });
550 const int maxSpots = std::max(0, std::min(settings.maxSpotShadowCasters, ShadowConfig::kLocalSlots));
551 if (maxSpots == 0 || spots.empty()) {
553 return;
554 }
555
556 const size_t winnerCount = std::min(size_t(maxSpots), spots.size());
557 std::vector<bool> winnerTaken(winnerCount, false);
558
560 float assignedScore[ShadowConfig::kLocalSlots]{};
561 size_t assignedIndex[ShadowConfig::kLocalSlots]{};
562
563 // Sticky: keep previous physical slot when that light is still a winner.
564 for (size_t w = 0; w < winnerCount; ++w) {
565 const int prev = spots[w].prevSlot;
566 if (prev < 0 || prev >= maxSpots) continue;
567 if (assigned[prev]) continue;
568 assigned[prev] = spots[w].light;
569 assignedScore[prev] = spots[w].score;
570 assignedIndex[prev] = spots[w].index;
571 winnerTaken[w] = true;
572 }
573
574 for (size_t w = 0; w < winnerCount; ++w) {
575 if (winnerTaken[w]) continue;
576 int slot = -1;
577 for (int s = 0; s < maxSpots; ++s) {
578 if (!assigned[s]) {
579 slot = s;
580 break;
581 }
582 }
583 if (slot < 0) {
584 int victim = -1;
585 float worst = 1e30f;
586 for (int s = 0; s < maxSpots; ++s) {
587 if (assignedScore[s] < worst) {
588 worst = assignedScore[s];
589 victim = s;
590 }
591 }
592 if (victim < 0 || assignedScore[victim] >= spots[w].score) continue;
593 slot = victim;
594 }
595 assigned[slot] = spots[w].light;
596 assignedScore[slot] = spots[w].score;
597 assignedIndex[slot] = spots[w].index;
598 winnerTaken[w] = true;
599 }
600
601 struct UpdateCandidate {
602 int slot = -1;
603 int priority = 0;
604 float score = 0.f;
605 };
606 std::vector<UpdateCandidate> updates;
607 updates.reserve(size_t(maxSpots));
608 LocalPageCacheEntry nextCache[ShadowConfig::kLocalSlots]{};
609 // Map physical slot → localSlots index for later update-budget edits.
610 int slotToLocalIndex[ShadowConfig::kLocalSlots];
611 for (int& v : slotToLocalIndex) v = -1;
612
613 for (int s = 0; s < maxSpots; ++s) {
614 Light3D::Data* d = assigned[s];
615 if (!d) continue;
616
617 const float bias = d->shadowBias > 0.f ? d->shadowBias : settings.defaultSpotBias;
618 const glm::vec3 dir = safeNormalize(glm::vec3(d->dx, d->dy, d->dz), glm::vec3(0.f, -1.f, 0.f));
619 const glm::mat4 vp =
620 buildSpotShadowVP(glm::vec3(d->x, d->y, d->z), dir, std::max(d->radius, 0.1f), d->spotAngleDeg);
621
623 slot.light = d;
626 slot.lightIndex = int(assignedIndex[s]);
627 slot.lightVP = vp;
628 slot.bias = bias;
629 slot.strength = d->shadowStrength;
630 slot.score = assignedScore[s];
631 slot.needsUpdate = true;
632
633 const LocalPageCacheEntry& prev = g_localPageCache.slots[s];
634 const bool sameLight = prev.occupied && prev.light == d;
635 const bool paramsSame = sameLight && lightParamsMatchCache(*d, prev, bias);
636 if (paramsSame) {
637 slot.needsUpdate = false;
638 slot.lightVP = prev.lightVP;
639 slot.bias = prev.bias;
640 } else {
641 int priority = sameLight ? 2 : 3;
642 updates.push_back({s, priority, slot.score});
643 }
644
645 d->shadowLocalSlot = s;
646 storeCacheEntry(nextCache[s], d, slot.lightVP, slot.bias);
647 slotToLocalIndex[s] = int(localSlots.size());
648 localSlots.push_back(slot);
649 }
650
651 const int updateBudget = std::max(0, std::min(settings.maxLocalUpdatesPerFrame, ShadowConfig::kLocalSlots));
652 std::stable_sort(updates.begin(), updates.end(), [](const UpdateCandidate& a, const UpdateCandidate& b) {
653 if (a.priority != b.priority) return a.priority > b.priority;
654 return a.score > b.score;
655 });
656 for (size_t i = size_t(updateBudget); i < updates.size(); ++i) {
657 const int phys = updates[i].slot;
658 const int li = slotToLocalIndex[phys];
659 if (li < 0) continue;
660 LocalShadowSlot& slot = localSlots[size_t(li)];
661 slot.needsUpdate = false;
662 const LocalPageCacheEntry& prev = g_localPageCache.slots[phys];
663 if (prev.occupied && prev.light == slot.light) {
664 slot.lightVP = prev.lightVP;
665 slot.bias = prev.bias;
666 nextCache[phys].lightVP = prev.lightVP;
667 nextCache[phys].bias = prev.bias;
668 }
669 }
670
671 for (int s = 0; s < ShadowConfig::kLocalSlots; ++s) g_localPageCache.slots[s] = nextCache[s];
672}
673
674} // namespace eve::graphics
double z
double y
double x
LogicalId target
double score
Definition Agent.cpp:51
float w
Definition AnimClip.cpp:738
int mid
Definition AnimSmr.cpp:120
const std::string & s
int priority
glm::vec4 p[6]
Stable, structured diagnostics shared by engine modules.
std::string name
Definition ECS.cpp:154
std::uint16_t method
float strength
std::vector< eve::ProcgenProbeDesc > lights
glm::vec4 clip
float area
Definition Grass.cpp:62
glm::vec3 n
Definition Grass.cpp:63
float v
HexVec3 up
float ratio
std::string local
Range range
std::array< float, 3 > position
std::string coverage
bool valid
MeleePoint3 b
Definition MeleeHit.cpp:41
double radius
Definition MeleeHit.cpp:42
MeleePoint3 a
Definition MeleeHit.cpp:40
OceanWakeSettings settings
glm::dvec3 dx
glm::dvec3 dz
OceanSprayView view
int idx
float f
float d
std::string slot
glm::vec3 eye
FrustumPlanes frustum
glm::mat4 proj
bool isPoint
RoadNetwork resolved
RoadLaneDirection direction
Value::Array corners
ScriptStructure out
float shadowStrength
Definition Shadow.cpp:154
glm::mat4 lightVP
Definition Shadow.cpp:148
float spotAngleDeg
Definition Shadow.cpp:153
Light3D::Data * light
Definition Shadow.cpp:147
float dy
Definition Shadow.cpp:151
float bias
Definition Shadow.cpp:149
bool occupied
Definition Shadow.cpp:155
LocalPageCacheEntry slots[ShadowConfig::kLocalSlots]
Definition Shadow.cpp:159
std::map< Cell, int > best
float size
Definition TreeMesh.cpp:158
V3 dir
Definition TreeMesh.cpp:151
uint32_t index
V forward
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
Move-only operation result carrying either a value or Status.
Definition Result.h:176
static Result success(T value)
Construct a successful result owning value.
Definition Result.h:185
static Result failure(Status status)
Construct a failed result from a structured status.
Definition Result.h:196
卡牌游戏 UI 工具模块:工厂 + 脚本绑定入口。 功能参考 ycarowr/UiCard:扇形手牌布局、抽牌/洗牌、悬浮放大、拖拽到落牌区、 敌方手牌(背面/偷看)、费用不足置灰,以及可实时调节的布局...
Definition Animation.h:25
void selectShadowCasters(const std::vector< Light3D::Data * > &lights, const std::vector< bool > &isPointFlags, const ShadowSchemeSettings &settings, const ShadowPagingView &view, Light3D::Data *&directionalCaster, std::vector< LocalShadowSlot > &localSlots)
Select directional CSM caster + paged local spot slots for one frame.
Definition Shadow.cpp:500
glm::mat4 perspectiveVulkanRH_ZO(float fovyRad, float aspect, float zNear, float zFar)
Right-handed, zero-to-one depth perspective for Vulkan swapchains.
Definition ClipSpace.h:22
ShadowUpload buildDirectionalCSM(const glm::vec3 &lightDirTowardSurface, const glm::vec3 &eye, const glm::vec3 &target, const glm::vec3 &up, float fovYRad, float aspect, float nearZ, float farZ, float bias, float strength)
Build 3 cascade light view-proj matrices for a directional light.
Definition Shadow.cpp:83
glm::mat4 buildSpotShadowVP(const glm::vec3 &position, const glm::vec3 &direction, float range, float outerAngleDeg)
Build a perspective light VP for a spot caster (Vulkan RH, ZO depth).
Definition Shadow.cpp:440
AdaptiveCascadeAllocation allocateAdaptiveCascadeResolutions(int atlasSize, const float(&splitEnds)[ShadowConfig::kCascades+1], const float(&screenCoverage)[ShadowConfig::kCascades], const ShadowSchemeSettings &settings)
Distribute atlas resolution across cascades by distance + screen coverage.
Definition Shadow.cpp:321
float scoreSpotShadowCandidate(const Light3D::Data &light, const ShadowPagingView &view, const ShadowSchemeSettings &settings, bool hadSlot)
Score a spot caster for local-shadow paging (higher = more important).
Definition Shadow.cpp:470
int shadowMapSizeForResolutionTier(int resolutionTier)
Map PhotoMode m_shadowResolution (0..3) to an atlas edge length.
Definition Shadow.cpp:233
void resetShadowLocalPageCache()
Clear sticky local-page cache (tests / scheme resets).
Definition Shadow.cpp:381
Result< ShadowMethod > resolveShadowMethod(std::string_view lightType, ShadowMethod requested)
Resolve Auto / validate an explicit method for a concrete light type.
Definition Shadow.cpp:412
float estimateCascadeScreenCoverage(const glm::vec3 &eye, const glm::vec3 &target, const glm::vec3 &up, float fovYRad, float aspect, float nearZ, float farZ)
Estimate how much of the screen a cascade frustum slice covers.
Definition Shadow.cpp:286
const char * shadowMethodName(ShadowMethod method)
Canonical lowercase name for a ShadowMethod (auto, none, csm, …).
Definition Shadow.cpp:401
Result< glm::mat4 > buildPointShadowFaceVP(const glm::vec3 &position, int faceIndex, float range)
Build one cube-face light VP for a point caster.
Definition Shadow.cpp:452
int clampShadowMapSize(int size)
Clamp/round a requested map size to an allowed power-of-two.
Definition Shadow.cpp:218
Result< void > setShadowSchemeMapSizes(int directionalMapSize, int localMapSize)
Apply directional (and optional local) map sizes with validation. @cost Cheap CPU clamp; GPU recreate...
Definition Shadow.cpp:253
Result< void > setShadowSchemeDirectionalMaxDistance(float meters)
Apply CSM max distance with validation.
Definition Shadow.cpp:269
glm::mat4 orthoVulkanRH_ZO(float left, float right, float bottom, float top, float zNear, float zFar)
Ortho vulkan rh zo.
Definition ClipSpace.h:30
ShadowMethod
How a Light3D produces real-time shadows. Auto resolves per light type (dir→CSM, spot→perspective,...
Definition Shadow.h:14
Result< ShadowMethod > parseShadowMethod(std::string_view name)
Parse a script/editor method name into ShadowMethod.
Definition Shadow.cpp:387
Per-cascade effective map sizes chosen for one CSM build. @ownership Value type; copied into ShadowUp...
int sizes[ShadowConfig::kCascades]
Data public API.
Definition Light.h:199
int shadowLocalSlot
Frame-transient local shadow atlas slot (0..kLocalSlots-1), or -1. Written by selectShadowCasters; pa...
Definition Light.h:223
One allocated local (spot/point-face) shadow slot for the frame. @ownership Ephemeral CPU descriptor;...
bool needsUpdate
When false, skip the shadow pass and keep the cached depth layer.
static constexpr float kSplitLambda
Definition Shadow.h:29
static constexpr int kLocalSlots
Extra depth-array layers for spot (perspective) local shadows.
Definition Shadow.h:26
static constexpr float kMaxDistance
Definition Shadow.h:32
static constexpr int kCascades
Definition Shadow.h:24
Camera context used to score local shadow candidates for atlas paging. @ownership Ephemeral; valid on...
Process-wide defaults for creating shadows per light family.
int localMapSize
Preferred local-spot atlas edge length; shares the directional array today.
int resolvedAtlasMapSize() const
Atlas edge length actually allocated for GPU shadow maps.
Definition Shadow.cpp:242
float resolvedDirectionalMaxDistance() const
CSM far clamp used by buildDirectionalCSM.
Definition Shadow.cpp:248
float directionalMaxDistance
Practical CSM far distance (camera-forward meters). Camera far is clamped to this so large scenes kee...
int directionalMapSize
Preferred directional CSM atlas edge length (texels); clamped to {256..4096}².
static ShadowSchemeSettings & current()
Borrow the process-wide settings object.
Definition Shadow.cpp:216
ShadowUpload public API.
Definition Shadow.h:62
glm::vec4 lightDir
uint32_t pad[2]