载入中...
搜索中...
未找到
RenderSystem3D.cpp
浏览该文件的文档.
1// eve-hot-path
2// eve-hot-path
4#include "common/Assert.h"
5#include "common/Capability.h"
6#include "common/Exception.h"
7#include "common/Profile.h"
9#include "common/Status.h"
13#include "graphics/ClipSpace.h"
19#include "graphics/Graphics.h"
21#include "graphics/Light.h"
22#include "graphics/Material.h"
23#include "graphics/Mesh.h"
24#include "graphics/Outline.h"
32#include "graphics/Shader.h"
33#include "graphics/Shadow.h"
35#include "graphics/Texture.h"
37
38#include <algorithm>
39#include <cmath>
40#include <glm/geometric.hpp>
41#include <glm/gtc/matrix_inverse.hpp>
42#include <glm/gtc/matrix_transform.hpp>
43#include <glm/vec3.hpp>
44#include <unordered_map>
45#include <vector>
46
47namespace eve::graphics {
48
49namespace {
50
51std::vector<RenderSystem3D::GBufferExtraDrawer> g_gbufferDrawers;
52struct ShadowExtraDrawerEntry {
53 uint64_t token = 0;
55};
56std::vector<ShadowExtraDrawerEntry> g_shadowDrawers;
57uint64_t g_nextShadowDrawerToken = 1;
58std::vector<RenderSystem3D::DecalExtraDrawer> g_decalDrawers;
59struct CaptureExtraDrawerEntry {
60 uint64_t token = 0;
61 uint32_t mask = 0;
63};
64std::vector<CaptureExtraDrawerEntry> g_captureDrawers;
65uint64_t g_nextCaptureDrawerToken = 1;
66struct ForwardExtraDrawerEntry {
67 uint64_t token = 0;
69};
70std::vector<ForwardExtraDrawerEntry> g_forwardDrawers;
71uint64_t g_nextForwardExtraDrawerToken = 1;
72struct GpuOpaqueCollectorEntry {
73 uint64_t token = 0;
75};
76std::vector<GpuOpaqueCollectorEntry> g_gpuOpaqueCollectors;
77uint64_t g_nextGpuOpaqueCollectorToken = 1;
78
79glm::vec3 gLightDir = glm::normalize(glm::vec3(0.4f, 1.f, 0.3f));
80glm::vec3 gLightColor = glm::vec3(1.f);
81
83
84Camera3D* findDefaultCamera3D() {
85 if (ecs::current()->getManager<Camera3D>() == nullptr) return nullptr;
86 auto camView = ecs::View<Camera3D, Camera3D::Data>();
87 for (auto it = camView.begin(); it != camView.end(); ++it) {
88 auto [data] = *it;
89 if (!data->active || !data->entity) continue;
90 return data->entity;
91 }
92 return nullptr;
93}
94
95struct PackedLight3D {
96 Light3D::Data* data = nullptr;
97 bool isPoint = true;
98};
99
100void collectLights3D(std::vector<PackedLight3D>& out, size_t maxCount) {
101 out.clear();
102 if (ecs::current()->getManager<Light3D>() == nullptr) return;
103 auto view = ecs::View<Light3D, Light3D::Data>();
104 for (auto it = view.begin(); it != view.end(); ++it) {
105 auto [d] = *it;
106 d->shadowLocalSlot = -1; // cleared each frame; selectShadowCasters reassigns
107 if (!d->enabled) continue;
108 if (d->volumetricOnly) continue; // emissive proxies skip surface lighting
109 PackedLight3D pl;
110 pl.data = d;
111 pl.isPoint = (d->type != "dir");
112 out.push_back(pl);
113 }
114 std::stable_sort(out.begin(), out.end(), [](const PackedLight3D& a, const PackedLight3D& b) {
115 if (a.isPoint != b.isPoint) return a.isPoint && !b.isPoint;
116 return a.data->intensity > b.data->intensity;
117 });
118 if (out.size() > maxCount) out.resize(maxCount);
119}
120
123void promoteDirectional(std::vector<PackedLight3D>& packed) {
124 for (size_t i = 0; i < packed.size(); ++i) {
125 if (packed[i].isPoint) continue;
126 if (i != 0) std::swap(packed[0], packed[i]);
127 return;
128 }
129}
130
131void fillLight3DGpu(Light3DGpu& g, const Light3D::Data& d, bool isPoint) {
132 g.color = glm::vec4(d.r * d.intensity, d.g * d.intensity, d.b * d.intensity, 1.f);
133 g.spot = glm::vec4(0.f, 0.f, 0.f, -1.f);
134 if (!isPoint) {
135 glm::vec3 dir(d.dx, d.dy, d.dz);
136 if (glm::length(dir) < 1e-6f)
137 dir = glm::vec3(0.f, 1.f, 0.f);
138 else
139 dir = glm::normalize(dir);
140 g.posRadius = glm::vec4(dir, 0.f);
141 return;
142 }
143 g.posRadius = glm::vec4(d.x, d.y, d.z, d.radius);
144 if (d.type != "spot") return;
145 float cosOuter = 0.f, cosInner = 0.f;
146 lightSpotCosines(d.spotAngleDeg, d.spotSoftness, cosOuter, cosInner);
147 const float scale = 1.f / std::max(cosInner - cosOuter, 1e-4f);
148 const float bias = -cosOuter * scale;
149 glm::vec3 beam(d.dx, d.dy, d.dz);
150 if (glm::length(beam) < 1e-6f)
151 beam = glm::vec3(0.f, -1.f, 0.f);
152 else
153 beam = glm::normalize(beam);
154 // Encode local shadow slot in beam length: |beam| = 1 + (slot+1)/100.
155 // spotAttenuation3D normalizes; shaders decode the slot independently of
156 // packed vs clustered light indices (which diverge after CSM promotion).
157 if (d.shadowLocalSlot >= 0 && d.shadowLocalSlot < ShadowConfig::kLocalSlots)
158 beam *= 1.f + float(d.shadowLocalSlot + 1) * 0.01f;
159 g.spot = glm::vec4(beam, scale);
160 g.color.a = bias;
161}
162
163Lighting3DPack packLights3D(const std::vector<PackedLight3D>& lights, const Camera3D::Data* cam) {
164 Lighting3DPack pack{};
165 if (cam) {
166 pack.ambient = glm::vec4(cam->ambientR, cam->ambientG, cam->ambientB, 0.f);
167 }
168 if (lights.empty()) {
169 pack.count = 1;
170 pack.lights[0].posRadius = glm::vec4(gLightDir, 0.f);
171 pack.lights[0].color = glm::vec4(gLightColor, 1.f);
172 pack.lights[0].spot = glm::vec4(0.f, 0.f, 0.f, -1.f);
173 return pack;
174 }
175 const int n = std::min(int(lights.size()), Lighting3DPack::kMaxLights);
176 pack.count = n;
177 for (int i = 0; i < n; ++i) {
178 const auto* d = lights[size_t(i)].data;
179 fillLight3DGpu(pack.lights[i], *d, lights[size_t(i)].isPoint);
180 }
181 return pack;
182}
183
184void splitLights(const std::vector<PackedLight3D>& packed, std::vector<ClusteredLightGpu>& points,
185 std::vector<ClusteredLightGpu>& dirs) {
186 points.clear();
187 dirs.clear();
188 for (const auto& pl : packed) {
189 const auto* d = pl.data;
191 fillLight3DGpu(g, *d, pl.isPoint);
192 if (pl.isPoint)
193 points.push_back(g);
194 else
195 dirs.push_back(g);
196 }
197}
198
199} // namespace
200
201void Camera3D::setEye(float x, float y, float z) {
202 auto d = data();
203 d->eyeX = x;
204 d->eyeY = y;
205 d->eyeZ = z;
206}
207
208float Camera3D::getEyeX() { return data()->eyeX; }
209float Camera3D::getEyeY() { return data()->eyeY; }
210float Camera3D::getEyeZ() { return data()->eyeZ; }
211
212void Camera3D::setTarget(float x, float y, float z) {
213 auto d = data();
214 d->targetX = x;
215 d->targetY = y;
216 d->targetZ = z;
217}
218
219float Camera3D::getTargetX() { return data()->targetX; }
220float Camera3D::getTargetY() { return data()->targetY; }
221float Camera3D::getTargetZ() { return data()->targetZ; }
222
223void Camera3D::setUp(float x, float y, float z) {
224 auto d = data();
225 d->upX = x;
226 d->upY = y;
227 d->upZ = z;
228}
229
230void Camera3D::setFov(float fovYDeg) { data()->fovYDeg = fovYDeg; }
231
232float Camera3D::getFov() { return data()->fovYDeg; }
233
235 data()->orthographic = true;
236 data()->orthoHeight = std::max(0.001f, height);
237}
238
239void Camera3D::setPerspective() { data()->orthographic = false; }
240
241bool Camera3D::isOrthographic() { return data()->orthographic; }
242
243float Camera3D::getOrthoHeight() { return data()->orthoHeight; }
244
245Result<void> Camera3D::setPixelConfig(float pixelsPerUnit, int refWidth, int refHeight) {
246 if (!std::isfinite(pixelsPerUnit) || pixelsPerUnit <= 0.f)
248 DiagnosticCode::InvalidArgument, "pixelsPerUnit must be finite and > 0", "camera3d.pixelsPerUnit"));
249 if (refWidth < 0 || refHeight < 0)
251 "pixel reference size must be >= 0", "camera3d.pixelRef"));
252 if ((refWidth == 0) != (refHeight == 0))
254 "pixel reference width and height must both be set or both 0",
255 "camera3d.pixelRef"));
256 auto d = data();
257 d->pixelsPerUnit = pixelsPerUnit;
258 d->pixelRefWidth = refWidth;
259 d->pixelRefHeight = refHeight;
260 return Result<void>::success();
261}
262
264 auto d = data();
265 d->pixelsPerUnit = 0.f;
266 d->pixelRefWidth = 0;
267 d->pixelRefHeight = 0;
268 d->pixelScale = 1;
269}
270
271bool Camera3D::hasPixelConfig() { return data()->pixelsPerUnit > 0.f; }
272
273void Camera3D::setPixelSnap(bool enabled) { data()->pixelSnap = enabled; }
274
275bool Camera3D::getPixelSnap() { return data()->pixelSnap; }
276
277float Camera3D::getPixelsPerUnit() { return data()->pixelsPerUnit; }
278
279int Camera3D::getPixelRefWidth() { return data()->pixelRefWidth; }
280
281int Camera3D::getPixelRefHeight() { return data()->pixelRefHeight; }
282
283int Camera3D::getPixelScale() { return data()->pixelScale; }
284
285Result<void> Camera3D::applyPixelPerfect(int viewWidth, int viewHeight) {
286 if (viewWidth <= 0 || viewHeight <= 0)
288 Diagnostic::error(DiagnosticCode::InvalidArgument, "viewport size must be > 0", "camera3d.viewport"));
289 auto d = data();
290 if (!(d->pixelsPerUnit > 0.f))
292 DiagnosticCode::InvalidArgument, "pixel config requires pixelsPerUnit > 0", "camera3d.pixelsPerUnit"));
293 const auto sized =
294 computePixelPerfectScale(d->pixelsPerUnit, d->pixelRefWidth, d->pixelRefHeight, viewWidth, viewHeight);
295 d->pixelScale = sized.scale;
296 d->orthographic = true;
297 d->orthoHeight = sized.orthoHeight;
298 if (d->pixelSnap) snapToPixelGrid(viewWidth, viewHeight);
299 return Result<void>::success();
300}
301
302Result<void> Camera3D::setPixelOrthographic(float pixelsPerUnit, int viewWidth, int viewHeight, int refWidth,
303 int refHeight) {
304 auto configured = setPixelConfig(pixelsPerUnit, refWidth, refHeight);
305 if (!configured.ok()) return configured;
306 return applyPixelPerfect(viewWidth, viewHeight);
307}
308
309void Camera3D::snapToPixelGrid(int viewWidth, int viewHeight) {
310 auto d = data();
311 float worldPerPixel = 0.f;
312 if (d->pixelsPerUnit > 0.f) {
313 const auto sized =
314 computePixelPerfectScale(d->pixelsPerUnit, d->pixelRefWidth, d->pixelRefHeight, viewWidth, viewHeight);
315 worldPerPixel = sized.worldPerPixel;
316 } else if (d->orthographic && viewHeight > 0) {
317 worldPerPixel = d->orthoHeight / float(viewHeight);
318 }
319 if (!(worldPerPixel > 0.f) || !std::isfinite(worldPerPixel)) return;
320
321 const glm::vec3 eye(d->eyeX, d->eyeY, d->eyeZ);
322 const glm::vec3 target(d->targetX, d->targetY, d->targetZ);
323 glm::vec3 forward = target - eye;
324 const float flen = glm::length(forward);
325 if (flen < 1e-6f) return;
326 forward /= flen;
327 glm::vec3 up(d->upX, d->upY, d->upZ);
328 if (glm::length(up) < 1e-6f)
329 up = glm::vec3(0.f, 1.f, 0.f);
330 else
331 up = glm::normalize(up);
332 glm::vec3 right = glm::cross(forward, up);
333 if (glm::length(right) < 1e-6f)
334 right = glm::vec3(1.f, 0.f, 0.f);
335 else
336 right = glm::normalize(right);
337 up = glm::normalize(glm::cross(right, forward));
338
339 const float alongRight = glm::dot(eye, right);
340 const float alongUp = glm::dot(eye, up);
341 const float alongFwd = glm::dot(eye, forward);
342 const float snappedR = std::round(alongRight / worldPerPixel) * worldPerPixel;
343 const float snappedU = std::round(alongUp / worldPerPixel) * worldPerPixel;
344 const glm::vec3 snappedEye = right * snappedR + up * snappedU + forward * alongFwd;
345 const glm::vec3 delta = snappedEye - eye;
346 d->eyeX = snappedEye.x;
347 d->eyeY = snappedEye.y;
348 d->eyeZ = snappedEye.z;
349 d->targetX += delta.x;
350 d->targetY += delta.y;
351 d->targetZ += delta.z;
352}
353
354void Camera3D::setClipPlanes(float nearZ, float farZ) {
355 data()->nearZ = std::max(0.001f, nearZ);
356 data()->farZ = std::max(data()->nearZ + 0.001f, farZ);
357}
358
359float Camera3D::getNearClip(){return data()->nearZ;}
360float Camera3D::getFarClip(){return data()->farZ;}
361void Camera3D::setPhysicalLens(float aperture,float focalLength){
362 EV_PARAM_CHECK(std::isfinite(aperture),"aperture must be positive and finite");
363 EV_PARAM_CHECK(aperture>0.f,"aperture must be positive and finite");
364 EV_PARAM_CHECK(std::isfinite(focalLength),"focal length must be positive and finite");
365 EV_PARAM_CHECK(focalLength>0.f,"focal length must be positive and finite");
366 data()->aperture=aperture;data()->focalLength=focalLength;
367}
368float Camera3D::getAperture(){return data()->aperture;}
369float Camera3D::getFocalLength(){return data()->focalLength;}
371 EV_PARAM_CHECK(layer >= 0, "layer must be in [0,31]");
372 EV_PARAM_CHECK(layer < 32, "layer must be in [0,31]");
373 EV_PARAM_CHECK(std::isfinite(distance), "distance must be finite and non-negative");
374 EV_PARAM_CHECK(distance >= 0.f, "distance must be finite and non-negative");
375 data()->layerCullDistances[size_t(layer)] = distance;
376}
377
379 EV_PARAM_CHECK(layer >= 0, "layer must be in [0,31]");
380 EV_PARAM_CHECK(layer < 32, "layer must be in [0,31]");
381 return data()->layerCullDistances[size_t(layer)];
382}
383
385 EV_PARAM_CHECK(layer >= 0, "layer must be in [0,31]");
386 EV_PARAM_CHECK(layer < 32, "layer must be in [0,31]");
387 EV_PARAM_CHECK(std::isfinite(distance), "distance must be finite and non-negative");
388 EV_PARAM_CHECK(distance >= 0.f, "distance must be finite and non-negative");
389 data()->shadowLayerCullDistances[size_t(layer)] = distance;
390}
391
393 EV_PARAM_CHECK(layer >= 0, "layer must be in [0,31]");
394 EV_PARAM_CHECK(layer < 32, "layer must be in [0,31]");
395 return data()->shadowLayerCullDistances[size_t(layer)];
396}
397
398void Camera3D::setActive(bool active) { data()->active = active; }
399
400void Camera3D::setAmbient(float r, float g, float b) {
401 auto d = data();
402 d->ambientR = r;
403 d->ambientG = g;
404 d->ambientB = b;
405}
406
407void Camera3D::setEnvMap(Texture* cube) { data()->envMap = cube; }
408
409void Camera3D::setEnvIntensity(float intensity) { data()->envIntensity = intensity < 0.f ? 0.f : intensity; }
410
411void Camera3D::setExposure(float ev) { data()->exposureEV = std::clamp(ev, -16.f, 16.f); }
412
413float Camera3D::getExposure() { return data()->exposureEV; }
414
415void Camera3D::setAutoExposure(bool enabled, float minEV, float maxEV) {
416 auto d = data();
417 d->autoExposure = enabled;
418 d->autoExposureMinEV = std::clamp(std::min(minEV, maxEV), -16.f, 16.f);
419 d->autoExposureMaxEV = std::clamp(std::max(minEV, maxEV), -16.f, 16.f);
420}
421
422bool Camera3D::isAutoExposure() { return data()->autoExposure; }
423
424void Camera3D::setBloom(float intensity, float threshold) {
425 auto d = data();
426 d->bloomIntensity = std::clamp(intensity, 0.f, 8.f);
427 d->bloomThreshold = std::clamp(threshold, 0.f, 16.f);
428}
429
430float Camera3D::getBloomIntensity() { return data()->bloomIntensity; }
431float Camera3D::getBloomThreshold() { return data()->bloomThreshold; }
432
433void Camera3D::setDepthOfField(float focusDistance, float maxBlurPx, float focusRange) {
434 auto d = data();
435 d->dofFocusDistance = std::max(0.f, focusDistance);
436 d->dofMaxBlurPx = std::clamp(maxBlurPx, 0.f, 32.f);
437 d->dofFocusRange = std::max(1e-3f, focusRange);
438}
439
440void Camera3D::clearDepthOfField() { data()->dofMaxBlurPx = 0.f; }
441
442float Camera3D::getDofFocusDistance() { return data()->dofFocusDistance; }
443float Camera3D::getDofMaxBlur() { return data()->dofMaxBlurPx; }
444float Camera3D::getDofFocusRange() { return data()->dofFocusRange; }
445
446void Camera3D::setEnvProbe(float centerX, float centerY, float centerZ, float extentX,
447 float extentY, float extentZ) {
448 data()->envProbeCenter = glm::vec3(centerX, centerY, centerZ);
449 data()->envProbeExtent = glm::max(glm::vec3(extentX, extentY, extentZ), glm::vec3(0.f));
450}
451
452void Camera3D::clearEnvProbe() { data()->envProbeExtent = glm::vec3(0.f); }
453
455 const glm::vec3 e = data()->envProbeExtent;
456 return e.x > 0.f && e.y > 0.f && e.z > 0.f;
457}
458float Camera3D::getEnvProbeCenterX() { return data()->envProbeCenter.x; }
459float Camera3D::getEnvProbeCenterY() { return data()->envProbeCenter.y; }
460float Camera3D::getEnvProbeCenterZ() { return data()->envProbeCenter.z; }
461float Camera3D::getEnvProbeExtentX() { return data()->envProbeExtent.x; }
462float Camera3D::getEnvProbeExtentY() { return data()->envProbeExtent.y; }
463float Camera3D::getEnvProbeExtentZ() { return data()->envProbeExtent.z; }
464
465void Camera3D::setReflectionProbe(int slot, Texture* cubemap, float centerX, float centerY, float centerZ,
466 float extentX, float extentY, float extentZ, float intensity, float blendDistance,
467 int priority) {
468 if (slot < 0 || slot >= Data::kMaxReflectionProbes) return;
469 auto& probe = data()->reflectionProbes[static_cast<size_t>(slot)];
470 probe.cubemap = cubemap;
471 probe.center = glm::vec3(centerX, centerY, centerZ);
472 probe.extent = glm::max(glm::vec3(extentX, extentY, extentZ), glm::vec3(0.f));
473 probe.intensity = std::max(intensity, 0.f);
474 probe.blendDistance = std::max(blendDistance, 0.f);
475 probe.priority = priority;
476 probe.enabled = cubemap && glm::all(glm::greaterThan(probe.extent, glm::vec3(0.f))) && probe.intensity > 0.f;
477}
478
480 if (slot < 0 || slot >= Data::kMaxReflectionProbes) return;
481 data()->reflectionProbes[static_cast<size_t>(slot)] = {};
482}
483
485 int count = 0;
486 for (const auto& probe : data()->reflectionProbes)
487 if (probe.enabled) ++count;
488 return count;
489}
490
491static ReflectionProbeUpload selectReflectionProbes(const Camera3D::Data& camera, const glm::vec3& samplePosition) {
492 struct Candidate {
493 int slot = 0;
494 int priority = 0;
495 float distance2 = 0.f;
496 };
497 std::array<Candidate, Camera3D::Data::kMaxReflectionProbes> candidates{};
498 int candidateCount = 0;
500 const auto& probe = camera.reflectionProbes[static_cast<size_t>(slot)];
501 if (!probe.enabled || !probe.cubemap) continue;
502 const glm::vec3 outside = glm::max(glm::abs(samplePosition - probe.center) - probe.extent, glm::vec3(0.f));
503 candidates[static_cast<size_t>(candidateCount++)] = Candidate{slot, probe.priority, glm::dot(outside, outside)};
504 }
505 std::stable_sort(candidates.begin(), candidates.begin() + candidateCount,
506 [](const Candidate& a, const Candidate& b) {
507 if (a.priority != b.priority) return a.priority > b.priority;
508 if (a.distance2 != b.distance2) return a.distance2 < b.distance2;
509 return a.slot < b.slot;
510 });
511
512 ReflectionProbeUpload upload;
513 upload.count = std::min(candidateCount, ReflectionProbeUpload::kMaxProbes);
514 for (int i = 0; i < upload.count; ++i) {
515 const auto& source = camera.reflectionProbes[static_cast<size_t>(candidates[i].slot)];
516 auto& target = upload.probes[i];
517 target.cubemap = source.cubemap;
518 target.center = source.center;
519 target.extent = source.extent;
520 target.intensity = source.intensity;
521 target.blendDistance = source.blendDistance;
522 target.priority = source.priority;
523 }
524 return upload;
525}
526
527void Camera3D::screenToRay(float screenX, float screenY, float viewW, float viewH) {
528 auto d = data();
529 d->screenRayOx = d->eyeX;
530 d->screenRayOy = d->eyeY;
531 d->screenRayOz = d->eyeZ;
532 d->screenRayDx = 0.f;
533 d->screenRayDy = 0.f;
534 d->screenRayDz = -1.f;
535 if (viewW <= 0.f || viewH <= 0.f) return;
536
537 const glm::vec3 eye(d->eyeX, d->eyeY, d->eyeZ);
538 const glm::vec3 target(d->targetX, d->targetY, d->targetZ);
539 const glm::vec3 up(d->upX, d->upY, d->upZ);
540 const glm::mat4 viewM = glm::lookAtRH(eye, target, up);
541 const float aspect = viewW / viewH;
542 const float fovRad = d->fovYDeg * 0.017453292519943295f;
543 const glm::mat4 projM =
544 cameraProjectionVulkanRH_ZO(d->orthographic, fovRad, d->orthoHeight, aspect, d->nearZ, d->farZ);
545 const glm::mat4 invVP = glm::inverse(projM * viewM);
546
547 // Screen pixel → Vulkan NDC (Y-down; matches perspectiveVulkanRH_ZO).
548 const float ndcX = (screenX / viewW) * 2.f - 1.f;
549 const float ndcY = (screenY / viewH) * 2.f - 1.f;
550 auto unproject = [&](float ndcZ) -> glm::vec3 {
551 glm::vec4 w = invVP * glm::vec4(ndcX, ndcY, ndcZ, 1.f);
552 if (std::fabs(w.w) < 1e-8f) return eye;
553 w /= w.w;
554 return glm::vec3(w);
555 };
556 // ZO depth: near = 0, far = 1.
557 const glm::vec3 nearPt = unproject(0.f);
558 const glm::vec3 farPt = unproject(1.f);
559 glm::vec3 dir = farPt - nearPt;
560 const float len = glm::length(dir);
561 if (len > 1e-8f)
562 dir /= len;
563 else
564 dir = glm::normalize(target - eye);
565
566 d->screenRayOx = eye.x;
567 d->screenRayOy = eye.y;
568 d->screenRayOz = eye.z;
569 if (d->orthographic) {
570 d->screenRayOx = nearPt.x;
571 d->screenRayOy = nearPt.y;
572 d->screenRayOz = nearPt.z;
573 }
574 d->screenRayDx = dir.x;
575 d->screenRayDy = dir.y;
576 d->screenRayDz = dir.z;
577}
578
579float Camera3D::getScreenRayOriginX() { return data()->screenRayOx; }
580float Camera3D::getScreenRayOriginY() { return data()->screenRayOy; }
581float Camera3D::getScreenRayOriginZ() { return data()->screenRayOz; }
582float Camera3D::getScreenRayDirX() { return data()->screenRayDx; }
583float Camera3D::getScreenRayDirY() { return data()->screenRayDy; }
584float Camera3D::getScreenRayDirZ() { return data()->screenRayDz; }
585
586void RenderSystem3D::setDirectionalLight(float dx, float dy, float dz, float r, float g, float b) {
587 glm::vec3 d(dx, dy, dz);
588 if (glm::length(d) < 1e-6f) d = glm::vec3(0.f, 1.f, 0.f);
589 gLightDir = glm::normalize(d);
590 gLightColor = glm::vec3(r, g, b);
591}
592
594 if (!drawer) return;
595 g_gbufferDrawers.push_back(std::move(drawer));
596}
597
598uint64_t RenderSystem3D::addCaptureExtraDrawer(uint32_t reflectionCaptureMask, CaptureExtraDrawer drawer) {
599 if (!drawer || reflectionCaptureMask == 0u) return 0;
600 const uint64_t token = g_nextCaptureDrawerToken++;
601 g_captureDrawers.push_back(CaptureExtraDrawerEntry{token, reflectionCaptureMask, std::move(drawer)});
602 return token;
603}
604
606 if (token == 0) return;
607 g_captureDrawers.erase(
608 std::remove_if(g_captureDrawers.begin(), g_captureDrawers.end(),
609 [token](const CaptureExtraDrawerEntry& entry) { return entry.token == token; }),
610 g_captureDrawers.end());
611}
612
614 if (!drawer) return 0;
615 const uint64_t token = g_nextForwardExtraDrawerToken++;
616 g_forwardDrawers.push_back(ForwardExtraDrawerEntry{token, std::move(drawer)});
617 return token;
618}
619
621 if (token == 0) return;
622 g_forwardDrawers.erase(
623 std::remove_if(g_forwardDrawers.begin(), g_forwardDrawers.end(),
624 [token](const ForwardExtraDrawerEntry& entry) { return entry.token == token; }),
625 g_forwardDrawers.end());
626}
627
629 if (!collector) return 0;
630 const uint64_t token = g_nextGpuOpaqueCollectorToken++;
631 g_gpuOpaqueCollectors.push_back(GpuOpaqueCollectorEntry{token, std::move(collector)});
632 return token;
633}
634
636 if (token == 0) return;
637 g_gpuOpaqueCollectors.erase(
638 std::remove_if(g_gpuOpaqueCollectors.begin(), g_gpuOpaqueCollectors.end(),
639 [token](const GpuOpaqueCollectorEntry& entry) { return entry.token == token; }),
640 g_gpuOpaqueCollectors.end());
641}
642
644 if (!drawer) return 0;
645 const uint64_t token = g_nextShadowDrawerToken++;
646 g_shadowDrawers.push_back(ShadowExtraDrawerEntry{token, std::move(drawer)});
647 return token;
648}
649
651 if (token == 0) return;
652 g_shadowDrawers.erase(std::remove_if(g_shadowDrawers.begin(), g_shadowDrawers.end(),
653 [token](const ShadowExtraDrawerEntry& entry) { return entry.token == token; }),
654 g_shadowDrawers.end());
655}
656
658 if (!drawer) return;
659 g_decalDrawers.push_back(std::move(drawer));
660}
661
662namespace {
663
664ShadowPagingView makeShadowPagingView(Camera3D* cam, float aspect) {
666 if (!cam) return view;
667 auto cd = cam->data();
668 view.eye = glm::vec3(cd->eyeX, cd->eyeY, cd->eyeZ);
669 const glm::vec3 target(cd->targetX, cd->targetY, cd->targetZ);
670 const glm::vec3 up(cd->upX, cd->upY, cd->upZ);
671 const glm::mat4 v = glm::lookAtRH(view.eye, target, up);
672 const float fov = cd->fovYDeg * 0.017453292519943295f;
673 const glm::mat4 p = perspectiveVulkanRH_ZO(fov, std::max(aspect, 1e-3f), cd->nearZ, cd->farZ);
674 view.viewProj = p * v;
675 view.valid = true;
676 return view;
677}
678
679void selectFrameShadowCasters(const std::vector<PackedLight3D>& packed, const ShadowPagingView& view,
680 Light3D::Data*& directionalCaster, std::vector<LocalShadowSlot>& localSlots) {
681 std::vector<Light3D::Data*> lights;
682 std::vector<bool> isPoint;
683 lights.reserve(packed.size());
684 isPoint.reserve(packed.size());
685 for (const auto& pl : packed) {
686 lights.push_back(pl.data);
687 isPoint.push_back(pl.isPoint);
688 }
689 selectShadowCasters(lights, isPoint, ShadowSchemeSettings::current(), view, directionalCaster, localSlots);
690}
691
692void prioritizeShadowCaster(std::vector<PackedLight3D>& packed, Light3D::Data* caster) {
693 if (!caster || packed.empty()) return;
694 for (size_t i = 0; i < packed.size(); ++i) {
695 if (packed[i].data != caster) continue;
696 if (i != 0) std::swap(packed[0], packed[i]);
697 return;
698 }
699}
700
705struct FrustumPlanes {
706 glm::vec4 p[6]{};
707
708 bool sphereVisible(const glm::vec3& center, float radius) const {
709 for (const auto& pl : p) {
710 const float d = pl.x * center.x + pl.y * center.y + pl.z * center.z + pl.w;
711 if (d < -radius) return false;
712 }
713 return true;
714 }
715};
716
717FrustumPlanes extractFrustum(const glm::mat4& m) {
718 FrustumPlanes f;
719 const glm::vec4 r0(m[0][0], m[1][0], m[2][0], m[3][0]);
720 const glm::vec4 r1(m[0][1], m[1][1], m[2][1], m[3][1]);
721 const glm::vec4 r2(m[0][2], m[1][2], m[2][2], m[3][2]);
722 const glm::vec4 r3(m[0][3], m[1][3], m[2][3], m[3][3]);
723 auto norm = [](glm::vec4& v) {
724 const float l = glm::length(glm::vec3(v));
725 if (l > 1e-8f) v /= l;
726 };
727 f.p[0] = r3 + r0; // left
728 f.p[1] = r3 - r0; // right
729 f.p[2] = r3 + r1; // bottom
730 f.p[3] = r3 - r1; // top
731 // Vulkan clip space uses zero-to-one depth: near plane is z_clip = 0
732 // (plane r2), not the z = -w plane used by OpenGL-style [-1,1] depth.
733 f.p[4] = r2; // near
734 f.p[5] = r3 - r2; // far
735 for (auto& pl : f.p) norm(pl);
736 return f;
737}
738
744struct CameraView {
745 Camera3D::Data* data = nullptr;
746 glm::vec3 eye{0.f};
747 glm::mat4 view{1.f};
748 glm::mat4 proj{1.f};
749 glm::mat4 viewProj{1.f};
750 glm::mat4 cullViewProj{1.f};
751 FrustumPlanes frustum;
752 float fovRad = 1.f;
753 Lighting3DPack lighting{};
754 ClusteredLightingUpload clustered{};
755 bool clusteredValid = false;
757 bool clusteredUploaded = false;
758};
759
760CameraView buildCameraView(Camera3D::Data* cd, const std::vector<PackedLight3D>& packed, bool useClustered,
761 float aspect, const std::vector<ClusteredLightGpu>& clusteredPoints,
762 const std::vector<ClusteredLightGpu>& clusteredDirs, Graphics& gfx,
763 const glm::vec2& jitterNdc) {
764 CameraView cv;
765 cv.data = cd;
766 cv.eye = glm::vec3(cd->eyeX, cd->eyeY, cd->eyeZ);
767 const glm::vec3 look(cd->targetX, cd->targetY, cd->targetZ);
768 const glm::vec3 up(cd->upX, cd->upY, cd->upZ);
769 cv.view = glm::lookAtRH(cv.eye, look, up);
770 cv.fovRad = cd->fovYDeg * 0.017453292519943295f;
771 cv.proj = cameraProjectionVulkanRH_ZO(cd->orthographic, cv.fovRad, cd->orthoHeight, aspect, cd->nearZ, cd->farZ);
772 cv.cullViewProj = cv.proj * cv.view;
773 cv.frustum = extractFrustum(cv.cullViewProj);
774 cv.proj[2][0] += jitterNdc.x;
775 cv.proj[2][1] += jitterNdc.y;
776 cv.viewProj = cv.proj * cv.view;
777 cv.lighting = packLights3D(packed, cd);
778 if (useClustered && !cd->orthographic) {
779 cv.clustered = buildClusteredLighting(clusteredPoints, clusteredDirs, cv.view, cd->nearZ, cd->farZ,
780 gfx.getWidth(), gfx.getHeight(), cv.fovRad,
781 glm::vec4(cd->ambientR, cd->ambientG, cd->ambientB, 0.f));
782 cv.clusteredValid = true;
783 }
784 return cv;
785}
786
792struct CulledItem {
793 Renderable3D::MeshRenderer* mr = nullptr;
794 Mesh* mesh = nullptr;
795 Material* material = nullptr;
796 Shader* shader = nullptr; // effective mesh shader (material or legacy)
797 glm::mat4 model{1.f};
798 glm::vec3 worldC{0.f}; // world-space bounding-sphere center
799 glm::vec2 temporalMotion{0.f}; // object-only previous-UV correction
800 bool receiveShadow = true;
801 bool shadowsOnly = false;
802 bool shadowDoubleSided = true;
806 float lodWeight = 1.f;
807 bool lodFadeReverse = false;
808 bool speedTreeFade = false;
809 float worldR = 0.f; // world-space bounding-sphere radius (0 = unknown → unculled)
810 float distSq = 0.f;
811 float projectedDepth = 0.f;
814 int camIdx = 0;
815 uint32_t cascadeMask = 0; // bit c set when the caster may contribute to cascade c
816 bool inView = false; // inside the item camera's frustum
817 bool inDefaultView = false; // inside the default camera's frustum (G-buffer)
818 bool hair = false;
819 bool xray = false;
820};
821
823 if (count == 1) return SkinInfluenceLimit::One;
824 if (count == 2) return SkinInfluenceLimit::Two;
826}
827
828} // namespace
829
832 EV_PROFILE_MODULE("graphics", "Render3D");
833 eve::debug::RenderPassScope pass3d("RenderSystem3D");
834 Camera3D* defaultCam = findDefaultCamera3D();
835
837 rc->ensureCompiled();
838 rc->pathTracingState_ = PathTracingFrameState::Disabled;
839 rc->pathTracingDiagnostic_.clear();
840 if (rc->isPathTracingRequested()) {
841 auto* provider = rc->pathProvider_;
842 if (!provider || !provider->isAvailable()) {
843 rc->pathTracingState_ = PathTracingFrameState::Unavailable;
844 rc->pathTracingDiagnostic_ = "Hardware path tracing is unavailable; rendering raster frame";
845 } else {
846 rc->pathTracingState_ = PathTracingFrameState::SceneRejected;
847 const auto primitives = gfx.getPrimitiveScene();
848 if (!defaultCam || defaultCam->data()->orthographic || defaultCam->data()->envMap ||
849 defaultCam->data()->dofMaxBlurPx > 0.f || !g_forwardDrawers.empty() || !g_gpuOpaqueCollectors.empty() ||
850 !g_gbufferDrawers.empty() || !g_decalDrawers.empty() || (primitives && primitives->size())) {
851 rc->pathTracingDiagnostic_ = "Path scene requires a perspective camera and supported contributors";
852 } else {
853 auto scene = preparePathWorld(*ecs::current(), gfx, *provider);
854 if (!scene.ok()) {
855 rc->pathTracingDiagnostic_ = scene.status().describe();
856 } else {
857 const auto width = uint32_t(std::max(1, gfx.getPixelWidth()));
858 const auto height = uint32_t(std::max(1, gfx.getPixelHeight()));
859 auto output = provider->preparePathFrame(scene.value(), width, height);
860 if (!output.ok()) {
861 rc->pathTracingDiagnostic_ = output.status().describe();
862 } else {
863 const auto camera = defaultCam->data();
865 view.eye = {camera->eyeX, camera->eyeY, camera->eyeZ};
866 const auto projection = cameraProjectionVulkanRH_ZO(
867 false, camera->fovYDeg * 0.017453292519943295f, camera->orthoHeight,
868 float(width) / float(height), camera->nearZ, camera->farZ);
869 view.invViewProj = glm::inverse(
870 projection * glm::lookAtRH(view.eye,
871 glm::vec3(camera->targetX, camera->targetY, camera->targetZ),
872 glm::vec3(camera->upX, camera->upY, camera->upZ)));
873 view.environment = {camera->ambientR, camera->ambientG, camera->ambientB};
874 view.samples = rc->pathSamples_;
875 view.firstSample = rc->pathSampleIndex_;
876 view.resetTemporalHistory = view.firstSample == 0;
877 rc->pathSampleIndex_ = (rc->pathSampleIndex_ + view.samples) % (1u << 24);
878 view.denoise = rc->pathTemporalRequested_ ? PathDenoise::Temporal : PathDenoise::Spatial;
879 gfx.gpuDrivenSetEnabled(false);
880 gfx.setSceneExposure(std::exp2(camera->exposureEV));
881 gfx.setSceneAutoExposure(camera->autoExposure, camera->autoExposureMinEV,
882 camera->autoExposureMaxEV);
883 gfx.setSceneBloom(camera->bloomIntensity, camera->bloomThreshold);
884 gfx.setSceneDepthOfField(0.f, 0.f, 1.f, camera->nearZ, camera->farZ);
885 gfx.begin3DFrame();
886 auto recorded = provider->recordPathFrame(scene.value(), output.value(), view);
887 if (!recorded.ok()) throw eve::Exception("%s", recorded.status().describe().c_str());
888 rc->pathTracingState_ = PathTracingFrameState::Active;
889 return;
890 }
891 }
892 }
893 }
894 }
895 const bool doShadow = rc->hasPass("shadow");
896 const bool doGBuffer = rc->hasPass("gbuffer");
897 const bool doDecal = rc->hasPass("decal");
898 const bool doDeferredLighting = rc->hasPass("deferredLighting");
899 const bool doForward = rc->hasPass("forward");
900 const bool doHair = rc->hasPass("hair");
901 const bool allowClustered = rc->isEnabled("clustered");
902
903 std::vector<PackedLight3D> packed;
904 collectLights3D(packed, size_t(ClusteredLightConfig::kMaxLights));
905 promoteDirectional(packed);
906 Light3D::Data* shadowCaster = nullptr;
907 std::vector<LocalShadowSlot> localShadowSlots;
908 const float aspectEarly =
909 (gfx.getHeight() > 0) ? float(gfx.getWidth()) / float(gfx.getHeight()) : 1.f;
910 if (doShadow)
911 selectFrameShadowCasters(packed, makeShadowPagingView(defaultCam, aspectEarly), shadowCaster,
912 localShadowSlots);
913 prioritizeShadowCaster(packed, shadowCaster);
914 // CSM promotion may swap packed indices; refresh local slot → light mapping.
915 for (LocalShadowSlot& slot : localShadowSlots) {
916 slot.lightIndex = -1;
917 if (!slot.light) continue;
918 for (size_t i = 0; i < packed.size() && i < size_t(Lighting3DPack::kMaxLights); ++i) {
919 if (packed[i].data == slot.light) {
920 slot.lightIndex = int(i);
921 break;
922 }
923 }
924 }
925 const bool haveExtraShadowCasters = doShadow && !g_shadowDrawers.empty();
926
927 const float aspect = aspectEarly;
928
929 ShadowUpload shadowUpload{};
930 shadowUpload.active = false;
931 // Per-cascade light frustums for caster culling (sphere vs frustum).
932 FrustumPlanes cascadeFrustums[ShadowConfig::kCascades];
933 if ((shadowCaster || haveExtraShadowCasters) && defaultCam) {
934 auto cd = defaultCam->data();
935 glm::vec3 dir = shadowCaster ? glm::vec3(shadowCaster->dx, shadowCaster->dy, shadowCaster->dz) : gLightDir;
936 if (glm::length(dir) < 1e-6f)
937 dir = glm::vec3(0.f, 1.f, 0.f);
938 else
939 dir = glm::normalize(dir);
940 const float shadowBias = shadowCaster ? shadowCaster->shadowBias : 0.003f;
941 const float shadowStrength = shadowCaster ? shadowCaster->shadowStrength : 1.f;
942 const float fovRad = cd->fovYDeg * 0.017453292519943295f;
943 shadowUpload = buildDirectionalCSM(
944 dir, glm::vec3(cd->eyeX, cd->eyeY, cd->eyeZ), glm::vec3(cd->targetX, cd->targetY, cd->targetZ),
945 glm::vec3(cd->upX, cd->upY, cd->upZ), fovRad, aspect, cd->nearZ, cd->farZ, shadowBias, shadowStrength);
946 for (int c = 0; c < ShadowConfig::kCascades; ++c)
947 cascadeFrustums[c] = extractFrustum(shadowUpload.ubo.lightVP[c]);
948 } else if (!localShadowSlots.empty()) {
949 // Local-only frame: keep CSM inactive but still upload local VPs.
950 shadowUpload.active = true;
951 shadowUpload.ubo.bias = glm::vec4(0.002f, 0.f, 1.f, 0.02f);
952 shadowUpload.ubo.splits.w = 0.f;
953 }
954 if (!localShadowSlots.empty()) {
955 shadowUpload.active = true;
956 shadowUpload.ubo.localMeta =
957 glm::vec4(float(localShadowSlots.size()), 1.f, 0.f, 0.f);
958 shadowUpload.ubo.localSlot01 = glm::vec4(-1.f);
959 shadowUpload.ubo.localSlot23 = glm::vec4(-1.f);
960 for (size_t s = 0; s < localShadowSlots.size(); ++s) {
961 const LocalShadowSlot& slot = localShadowSlots[s];
962 shadowUpload.ubo.localVP[s] = slot.lightVP;
963 if (s < 4) shadowUpload.ubo.localBias[int(s)] = slot.bias;
964 if (slot.lightIndex >= 0 && slot.lightIndex < 8) {
965 glm::vec4& bank = slot.lightIndex < 4 ? shadowUpload.ubo.localSlot01 : shadowUpload.ubo.localSlot23;
966 bank[slot.lightIndex % 4] = float(s);
967 }
968 }
969 }
970 gfx.setMesh3DShadows(shadowUpload);
971
972 // Hybrid always builds the clustered light table so deferred lighting and
973 // transparent Forward+ share one upload. ForwardPlus still gates on light count.
974 const bool useClustered =
975 allowClustered && (doDeferredLighting || packed.size() > size_t(Lighting3DPack::kMaxLights));
976 // Light split / directional promotion is camera-independent: compute once,
977 // then each camera view bakes its own clustered table from these lists.
978 std::vector<ClusteredLightGpu> clusteredPoints;
979 std::vector<ClusteredLightGpu> clusteredDirs;
980 if (useClustered) {
981 splitLights(packed, clusteredPoints, clusteredDirs);
982 // Match packLights3D: the default sun belongs only to a lightless scene.
983 // Point-only scenes must not gain a directional light when using Hybrid.
984 if (packed.empty()) {
986 d.posRadius = glm::vec4(gLightDir, 0.f);
987 d.color = glm::vec4(gLightColor, 1.f);
988 clusteredDirs.push_back(d);
989 }
990 if (shadowCaster && !clusteredDirs.empty()) {
991 glm::vec3 dir(shadowCaster->dx, shadowCaster->dy, shadowCaster->dz);
992 if (glm::length(dir) < 1e-6f)
993 dir = glm::vec3(0.f, 1.f, 0.f);
994 else
995 dir = glm::normalize(dir);
996 for (size_t i = 0; i < clusteredDirs.size(); ++i) {
997 if (glm::length(glm::vec3(clusteredDirs[i].posRadius) - dir) < 1e-3f) {
998 if (i != 0) std::swap(clusteredDirs[0], clusteredDirs[i]);
999 break;
1000 }
1001 }
1002 }
1003 }
1004
1005 const bool haveManager = ecs::current()->getManager<Renderable3D>() != nullptr;
1006 const bool shadowActive = doShadow && shadowUpload.active;
1007
1008 // Per-camera constants (matrices, frustum, lighting, clustered table).
1009 // The default camera is slot 0 so the G-buffer pass reuses its view.
1010 std::vector<CameraView> cams;
1011 cams.reserve(2);
1012 glm::vec2 temporalJitter(0.f);
1013 AntiAliasing* temporalAA = nullptr;
1014 if (defaultCam && rc->isEnabled("taa")) {
1015 auto cd = defaultCam->data();
1016 temporalAA = gfx.pipelineAntiAliasing();
1017 temporalAA->setTemporalCamera(glm::vec3(cd->eyeX, cd->eyeY, cd->eyeZ),
1018 glm::vec3(cd->targetX, cd->targetY, cd->targetZ), cd->fovYDeg);
1019 temporalJitter = temporalAA->prepareTemporalJitter(gfx.getWidth(), gfx.getHeight());
1020 }
1021 if (defaultCam) {
1022 cams.push_back(buildCameraView(defaultCam->data().operator->(), packed, useClustered, aspect, clusteredPoints,
1023 clusteredDirs, gfx, temporalJitter));
1024 if (temporalAA) {
1025 auto cd = defaultCam->data();
1026 temporalAA->setTemporalViewProjection(cams.front().viewProj, cd->nearZ, cd->farZ);
1027 }
1028 }
1029 auto findOrAddCam = [&](Camera3D* camEnt) -> int {
1030 Camera3D::Data* d = camEnt->data().operator->();
1031 for (size_t i = 0; i < cams.size(); ++i) {
1032 if (cams[i].data == d) return int(i);
1033 }
1034 cams.push_back(
1035 buildCameraView(d, packed, useClustered, aspect, clusteredPoints, clusteredDirs, gfx, temporalJitter));
1036 return int(cams.size()) - 1;
1037 };
1038
1039 // Single ECS traversal: one model matrix, one LOD pick, one set of
1040 // sphere-vs-frustum tests per part. Passes below only replay the list.
1041 std::vector<CulledItem> items;
1042 items.reserve(1024);
1043 if (haveManager) {
1044 auto view = ecs::View<Renderable3D, Renderable3D::Transform3D, Renderable3D::MeshRenderer>();
1045 for (auto it = view.begin(); it != view.end(); ++it) {
1046 auto [xf, mr] = *it;
1047 if (!mr->visible) continue;
1048 if (mr->instances) {
1050 if (!valid) throw eve::Exception("%s", valid.status().describe().c_str());
1051 }
1052 Camera3D *camEnt = mr->camera ? mr->camera : defaultCam;
1053 if (!camEnt) continue;
1054 const int camIdx = camEnt == defaultCam ? 0 : findOrAddCam(camEnt);
1055 const CameraView& cv = cams[size_t(camIdx)];
1056 const float dx = xf->x - cv.eye.x;
1057 const float dy = xf->y - cv.eye.y;
1058 const float dz = xf->z - cv.eye.z;
1059 const float distSq = dx * dx + dy * dy + dz * dz;
1060 const float dist = std::sqrt(distSq);
1061 const float layerDistance = cv.data->layerCullDistances[size_t(mr->layer)];
1062 if (layerDistance > 0.f && dist > layerDistance) continue;
1063 const glm::mat4 model = modelFromTransform(*xf);
1064 const float maxScale = detail::sphereStretch(*xf);
1065 const bool shadowOk = mr->effectiveCastShadow();
1066
1067 auto pushPart = [&](Mesh* drawMesh, Material* mat, bool asHair, bool castsShadow,
1068 const ModelPart* modelPart, int lodLevel, float lodWeight,
1069 bool lodFadeReverse = false) {
1070 if (!drawMesh) return;
1071 CulledItem item;
1072 item.mr = mr;
1073 item.mesh = drawMesh;
1074 item.material = mat;
1075 item.shader = mat ? mat->effectiveShader() : mr->shader;
1076 item.model = model;
1077 const auto* lodState = lodLevel >= 0 && lodLevel < mr->lodCount &&
1078 mr->lodRendererStates[lodLevel].configured
1079 ? &mr->lodRendererStates[lodLevel]
1080 : nullptr;
1081 item.receiveShadow = lodState ? lodState->receiveShadows : mr->receiveShadow;
1082 item.shadowsOnly = lodState && lodState->shadowCastingMode == 3;
1083 item.shadowDoubleSided = lodState ? lodState->shadowCastingMode == 2
1084 : (!mat || mat->getDoubleSided());
1085 item.useReflectionProbes = !lodState || lodState->reflectionProbeUsage != 0;
1086 item.lightProbeUsage = lodState ? lodState->lightProbeUsage : 0;
1087 item.skinInfluenceLimit = lodState && lodState->skinQuality != 0 ? lodState->skinQuality : 4;
1088 item.lodWeight = std::clamp(lodWeight, 0.f, 1.f);
1089 item.lodFadeReverse = lodFadeReverse;
1090 item.speedTreeFade = mr->lodFadeMode == 1 && item.lodWeight < 0.9999f && !item.shader;
1091 if (temporalAA && (!lodState || lodState->motionVectorMode == 1))
1092 item.temporalMotion = temporalAA->prepareTemporalObjectMotion(mr, model);
1093 item.distSq = distSq;
1094 const glm::vec4 viewCenter = cv.view * glm::vec4(xf->x, xf->y, xf->z, 1.f);
1095 item.projectedDepth = -viewCenter.z;
1096 item.camIdx = camIdx;
1097 item.hair = asHair;
1098 item.surfaceMode = mat ? mat->surfaceMode()
1099 : (asHair ? SurfaceMode::Transparent
1101 item.sortPriority = modelPart && modelPart->hasSortPriority
1102 ? modelPart->sortPriority
1103 : (mat ? mat->getSortPriority() : 0);
1104 item.xray = mr->xrayHighlight;
1105 if (mr->instances) {
1106 const auto &range = *mr->instances;
1107 glm::vec3 center, half;
1108 for (int i = 0; i < 3; ++i) {
1109 center[i] = range.minimum[i] * .5f + range.maximum[i] * .5f;
1110 half[i] = range.maximum[i] * .5f - range.minimum[i] * .5f;
1111 }
1112 item.worldC = glm::vec3(model * glm::vec4(center, 1));
1113 item.worldR = glm::length(half) * maxScale;
1114 item.inView = meshInstanceRangeVisible(range, model, cv.cullViewProj, cv.eye);
1115 item.inDefaultView =
1116 !defaultCam || camIdx == 0
1117 ? item.inView
1118 : meshInstanceRangeVisible(range, model, cams[0].cullViewProj, cams[0].eye);
1119 } else if (drawMesh->hasBounds()) {
1120 const glm::vec4 c4 =
1121 model * glm::vec4(drawMesh->boundsCx, drawMesh->boundsCy, drawMesh->boundsCz, 1.f);
1122 item.worldC = glm::vec3(c4);
1123 item.worldR = drawMesh->boundsRadius * maxScale;
1124 item.inView = cv.frustum.sphereVisible(item.worldC, item.worldR);
1125 item.inDefaultView = !defaultCam || camIdx == 0
1126 ? item.inView
1127 : cams[0].frustum.sphereVisible(item.worldC, item.worldR);
1128 const Camera3D::Data* shadowCamera = defaultCam ? cams[0].data : cv.data;
1129 const float shadowDistance = shadowCamera->shadowLayerCullDistances[size_t(mr->layer)];
1130 if (shadowCaster && shadowActive && castsShadow &&
1131 (shadowDistance <= 0.f || dist <= shadowDistance)) {
1132 for (int c = 0; c < ShadowConfig::kCascades; ++c) {
1133 if (cascadeFrustums[c].sphereVisible(item.worldC, item.worldR))
1134 item.cascadeMask |= (1u << c);
1135 }
1136 }
1137 } else {
1138 // No bounds (e.g. legacy/imported mesh): never cull.
1139 item.inView = true;
1140 item.inDefaultView = true;
1141 const Camera3D::Data* shadowCamera = defaultCam ? cams[0].data : cv.data;
1142 const float shadowDistance = shadowCamera->shadowLayerCullDistances[size_t(mr->layer)];
1143 if (shadowCaster && shadowActive && castsShadow &&
1144 (shadowDistance <= 0.f || dist <= shadowDistance))
1145 item.cascadeMask = (1u << ShadowConfig::kCascades) - 1u;
1146 }
1147 items.push_back(item);
1148 };
1149
1150 if (mr->usesParts()) {
1151 for (int p = 0; p < mr->partCount; ++p) {
1152 Material* mat = mr->parts[p].material ? mr->parts[p].material : mr->material;
1153 const bool asHair = mat ? mat->isTransparentHair() : mr->isHair;
1154 const bool casts = shadowOk && !(mat && !mat->getCastShadow());
1155 pushPart(mr->parts[p].mesh, mat, asHair, casts, &mr->parts[p], -1, 1.f);
1156 }
1157 } else {
1158 const float lodDistance = dist / std::max(cv.data->lodBias, 0.001f);
1159 int primary=-1,secondary=-1;float secondaryWeight=0.f;
1160 mr->lodBlendForDistance(lodDistance,primary,secondary,secondaryWeight);
1161 auto meshAt=[&](int level)->Mesh*{
1162 if (mr->lodCount <= 0) return level >= 0 ? mr->mesh : nullptr;
1163 return level>=0&&level<mr->lodCount?mr->lodMeshes[level]:nullptr;
1164 };
1165 auto castsAt=[&](int level){return level<0||mr->lodRendererStates[level].shadowCastingMode!=0;};
1166 const float primaryWeight=1.f-secondaryWeight;
1167 const bool ditherShadows = mr->lodFadeMode == 1 && secondaryWeight > 0.f;
1168 pushPart(meshAt(primary),mr->material,mr->effectiveHair(),
1169 shadowOk&&castsAt(primary)&&(ditherShadows||primaryWeight>=.5f),
1170 nullptr,primary,primaryWeight);
1171 if(secondaryWeight>0.f)
1172 pushPart(meshAt(secondary),mr->material,mr->effectiveHair(),
1173 shadowOk&&castsAt(secondary)&&(ditherShadows||secondaryWeight>.5f),
1174 nullptr,secondary,secondaryWeight,true);
1175 }
1176 }
1177 }
1178
1179 // CSM shadow passes — replay the collected casters, culled per cascade.
1180 // Extra drawers may run without a Light3D caster (default gLightDir CSM).
1181 if (shadowActive && (shadowCaster || haveExtraShadowCasters) &&
1182 (haveManager || haveExtraShadowCasters)) {
1183 auto cd = defaultCam->data();
1184 for (int c = 0; c < ShadowConfig::kCascades; ++c) {
1185 eve::debug::rtPassBegin("ShadowPass");
1186 gfx.beginShadowPass(c);
1187 for (const auto& item : items) {
1188 if ((item.cascadeMask & (1u << c)) == 0) continue;
1189 eve::debug::rtBind("mesh", "shadowCaster");
1190 eve::debug::rtDraw("drawMeshShadow", "cascade");
1191 Texture* shadowAlbedo = item.material ? item.material->getAlbedoTexture() : item.mr->texture;
1192 const bool doubleSidedShadow = item.shadowDoubleSided ||
1193 (item.material && item.material->getDoubleSided());
1194 if (item.surfaceMode == SurfaceMode::Masked)
1195 gfx.setMesh3DSkinInfluenceLimit(skinInfluenceLimit(item.skinInfluenceLimit));
1196 if (item.surfaceMode == SurfaceMode::Masked)
1197 gfx.drawMeshShadowAlpha(item.mesh, shadowUpload.ubo.lightVP[c] * item.model, shadowAlbedo,
1198 doubleSidedShadow, item.lodWeight, item.lodFadeReverse,
1199 item.speedTreeFade);
1200 else if (item.surfaceMode != SurfaceMode::Transparent) {
1201 gfx.setMesh3DSkinInfluenceLimit(skinInfluenceLimit(item.skinInfluenceLimit));
1202 gfx.drawMeshShadow(item.mesh, shadowUpload.ubo.lightVP[c] * item.model, doubleSidedShadow);
1203 }
1204 }
1205 // Extra shadow casters (billboard/card geometry not in the ECS).
1206 for (const auto& entry : g_shadowDrawers) entry.drawer(gfx, shadowUpload.ubo.lightVP[c], *cd);
1207 gfx.endShadowPass();
1208 eve::debug::rtPassEnd("ShadowPass");
1209 }
1210 }
1211
1212 // Spot (perspective) local shadow slots — layers after the three CSM cascades.
1213 // Paging may keep a slot resident without redrawing when needsUpdate is false.
1214 if (doShadow && !localShadowSlots.empty() && (haveManager || haveExtraShadowCasters) && defaultCam) {
1215 auto cd = defaultCam->data();
1216 for (const LocalShadowSlot& slot : localShadowSlots) {
1217 if (!slot.needsUpdate) continue;
1218 eve::debug::rtPassBegin("LocalShadowPass");
1219 gfx.beginShadowPass(slot.layer);
1220 const FrustumPlanes localFrustum = extractFrustum(slot.lightVP);
1221 for (const auto& item : items) {
1222 if (item.surfaceMode == SurfaceMode::Transparent) continue;
1223 // Approximate: draw every opaque caster inside the spot frustum.
1224 const glm::vec3 center = glm::vec3(item.model[3]);
1225 if (!localFrustum.sphereVisible(center, 2.f)) continue;
1226 eve::debug::rtBind("mesh", "localShadowCaster");
1227 Texture* shadowAlbedo = item.material ? item.material->getAlbedoTexture() : item.mr->texture;
1228 const bool doubleSidedShadow =
1229 item.shadowDoubleSided || (item.material && item.material->getDoubleSided());
1230 gfx.setMesh3DSkinInfluenceLimit(skinInfluenceLimit(item.skinInfluenceLimit));
1231 if (item.surfaceMode == SurfaceMode::Masked)
1232 gfx.drawMeshShadowAlpha(item.mesh, slot.lightVP * item.model, shadowAlbedo, doubleSidedShadow,
1233 item.lodWeight, item.lodFadeReverse, item.speedTreeFade);
1234 else
1235 gfx.drawMeshShadow(item.mesh, slot.lightVP * item.model, doubleSidedShadow);
1236 }
1237 for (const auto& entry : g_shadowDrawers) entry.drawer(gfx, slot.lightVP, *cd);
1238 gfx.endShadowPass();
1239 eve::debug::rtPassEnd("LocalShadowPass");
1240 }
1241 }
1242
1243 // G-buffer fill (sampleable depth/normal) — before the forward swapchain pass.
1244 if (doGBuffer && defaultCam &&
1245 (haveManager || !g_gbufferDrawers.empty() || !g_gpuOpaqueCollectors.empty())) {
1246 eve::debug::rtPassBegin("GBufferPass");
1247 const CameraView& cv = cams[0]; // default camera is slot 0
1248 const int gw = std::max(1, gfx.getPixelWidth() > 0 ? gfx.getPixelWidth() : gfx.getWidth());
1249 const int gh = std::max(1, gfx.getPixelHeight() > 0 ? gfx.getPixelHeight() : gfx.getHeight());
1250 gfx.beginGBufferPass(gw, gh);
1251 gfx.setMesh3DView(cv.view);
1252 gfx.setMesh3DCameraPos(cv.eye);
1253 for (const auto& item : items) {
1254 // X-ray targets are skipped so their pixels record the occluder depth
1255 // behind them; the X-ray shader samples that to detect occlusion.
1256 if (item.xray || item.mr->instances) continue;
1257 if (item.surfaceMode == SurfaceMode::Transparent) continue;
1258 if (!item.inDefaultView) continue;
1259 Texture* alb = item.material ? item.material->getAlbedoTexture() : item.mr->texture;
1260 const float tr = item.material ? item.material->getTintR() : item.mr->r;
1261 const float tg = item.material ? item.material->getTintG() : item.mr->g;
1262 const float tb = item.material ? item.material->getTintB() : item.mr->b;
1263 const float roughness = item.material ? item.material->getRoughness() : item.mr->roughness;
1264 const float tintA = item.material ? item.material->getTintA() : item.mr->a;
1265 const float metallic = item.material ? item.material->getMetallic() : item.mr->metallic;
1266 if (item.material) {
1267 auto bound = item.material->bind(gfx);
1268 if (!bound) throw Exception("%s", bound.error()->message().c_str());
1269 } else {
1270 auto reset = gfx.setMesh3DPbrSurface(nullptr);
1271 if (!reset) throw Exception("%s", reset.error()->message().c_str());
1272 }
1273 gfx.setMesh3DSkinInfluenceLimit(skinInfluenceLimit(item.skinInfluenceLimit));
1274 eve::debug::rtDraw("drawMeshGBuffer", "gbuffer");
1275 if (item.surfaceMode == SurfaceMode::Masked)
1276 gfx.drawMeshGBufferAlpha(item.mesh, cv.viewProj * item.model, item.model, cv.data->nearZ, cv.data->farZ,
1277 alb, tr, tg, tb, item.temporalMotion.x, item.temporalMotion.y, roughness,
1278 metallic, tintA);
1279 else
1280 gfx.drawMeshGBuffer(item.mesh, cv.viewProj * item.model, item.model, cv.data->nearZ, cv.data->farZ, alb,
1281 tr, tg, tb, item.temporalMotion.x, item.temporalMotion.y, roughness, metallic,
1282 tintA);
1283 }
1284 auto resetGBufferMaterial = gfx.setMesh3DPbrSurface(nullptr);
1285 if (!resetGBufferMaterial) throw Exception("%s", resetGBufferMaterial.error()->message().c_str());
1286 // Extra G-buffer contributors (billboard/card geometry not in the ECS).
1287 for (const auto& drawer : g_gbufferDrawers) drawer(gfx, *cv.data, cv.viewProj, aspect);
1288 gfx.endGBufferPass();
1289 eve::debug::rtPassEnd("GBufferPass");
1290 } else if (!doGBuffer) {
1291 rc->getGBuffer()->clear();
1292 }
1293
1294 // Screen-space decal layer: box-projected decals read the G-buffer
1295 // depth/normal and write albedo/normal/params targets sampled by
1296 // mesh3d.frag before lighting. Skipped when no decals are registered or
1297 // the backend cannot run the pass (WebGPU).
1298 if (doDecal && defaultCam && !g_decalDrawers.empty() && gfx.supportsDecal()) {
1299 eve::debug::rtPassBegin("DecalPass");
1300 const CameraView& cv = cams[0];
1301 const int dw = std::max(1, gfx.getPixelWidth() > 0 ? gfx.getPixelWidth() : gfx.getWidth());
1302 const int dh = std::max(1, gfx.getPixelHeight() > 0 ? gfx.getPixelHeight() : gfx.getHeight());
1303 gfx.beginDecalPass(dw, dh);
1304 gfx.setDecalCamera(cv.viewProj, cv.data->nearZ, cv.data->farZ);
1305 for (const auto& drawer : g_decalDrawers) drawer(gfx, *cv.data, cv.viewProj, aspect);
1306 gfx.endDecalPass();
1307 eve::debug::rtPassEnd("DecalPass");
1308 }
1309
1310 if (!doForward && !doHair) return;
1311
1312 // GPU-driven opaque is a ForwardPlus path; Hybrid lights core opaque via
1313 // deferredLighting and must not also submit GPU-driven lit draws.
1314 // Repeated opaque mesh/material pairs are cheaper as one instanced indirect
1315 // draw. Keep the explicit feature for smaller scenes and other backends.
1316 bool autoInstance = false;
1317 if (rc->autoInstancingPath() == RenderControl::AutoInstancingPath::Auto && !rc->isEnabled("gpuDriven") &&
1318 !doDeferredLighting && !useClustered && defaultCam && gfx.getBackendName() == "vulkan" &&
1319 gfx.supportsGpuDriven3D()) {
1320 std::unordered_map<Material*, std::unordered_map<Mesh*, uint32_t>> counts;
1321 for (const CulledItem& item : items) {
1322 if (!item.inView || item.shadowsOnly || item.camIdx != 0 || !item.material ||
1323 item.surfaceMode != SurfaceMode::Opaque || item.shader || item.hair || item.xray ||
1324 item.speedTreeFade || item.lodWeight < 0.9999f || item.mr->instances || item.mr->camera ||
1325 item.mesh->hasGpuSkinning() || item.lightProbeUsage != 0 || !gfx.gpuDrivenMaterialUsable(item.material))
1326 continue;
1327 if (++counts[item.material][item.mesh] >= 128) {
1328 autoInstance = true;
1329 break;
1330 }
1331 }
1332 }
1333 const bool gpuDrivenWanted =
1334 !doDeferredLighting && (rc->isEnabled("gpuDriven") || autoInstance) && gfx.supportsGpuDriven3D();
1335 gfx.gpuDrivenSetEnabled(gpuDrivenWanted);
1336
1337 if (defaultCam) {
1338 auto cd = defaultCam->data();
1339 gfx.setSceneExposure(std::exp2(cd->exposureEV));
1340 gfx.setSceneAutoExposure(cd->autoExposure, cd->autoExposureMinEV, cd->autoExposureMaxEV);
1341 gfx.setSceneBloom(cd->bloomIntensity, cd->bloomThreshold);
1342 gfx.setSceneDepthOfField(cd->dofFocusDistance, cd->dofMaxBlurPx, cd->dofFocusRange,
1343 cd->nearZ, cd->farZ);
1344 }
1345 if (defaultCam) {
1346 const auto& cv = cams.front();
1347 auto prepared = detail::prepareViewResources(gfx, cv.viewProj, cv.eye);
1348 if (!prepared) throw eve::Exception("%s", prepared.status().describe().c_str());
1349 }
1350 gfx.begin3DFrame();
1351 if (!gfx.had3DThisFrame()) return;
1352
1353 // Phase C Hybrid: fullscreen clustered deferred lighting fills scene color
1354 // for core PBR opaque/masked pixels written to the GBuffer. Transparent and
1355 // extended-feature opaques still go through Forward+ below.
1356 if (doDeferredLighting && defaultCam && !cams.empty()) {
1357 eve::debug::rtPassBegin("DeferredLighting");
1358 const CameraView& cv = cams[0];
1359 gfx.setMesh3DViewProj(cv.viewProj);
1360 gfx.setMesh3DView(cv.view);
1361 gfx.setMesh3DClip(cv.data->nearZ, cv.data->farZ);
1362 gfx.setMesh3DCameraPos(cv.eye);
1363 gfx.setMesh3DEnv(cv.data->envMap, cv.data->envIntensity);
1364 gfx.setMesh3DEnvProbe(cv.data->envProbeCenter, cv.data->envProbeExtent);
1365 gfx.setMesh3DLighting(cv.lighting);
1366 if (cv.clusteredValid) {
1367 gfx.setMesh3DClusteredLighting(cv.clustered);
1368 } else {
1369 // Orthographic / empty: drawDeferredLighting synthesizes a valid
1370 // empty cluster table from the frame UBO primary light.
1372 off.active = false;
1374 }
1376 eve::debug::rtPassEnd("DeferredLighting");
1377 }
1378
1379 auto drawPersistentPrimitives = [&]() {
1380 if (cams.empty()) return;
1381 const CameraView& camera = cams.front();
1383 context.view = camera.view;
1384 context.projection = camera.proj;
1385 context.cameraPosition = camera.eye;
1386 context.viewportSize = glm::ivec2(gfx.getPixelWidth() > 0 ? gfx.getPixelWidth() : gfx.getWidth(),
1387 gfx.getPixelHeight() > 0 ? gfx.getPixelHeight() : gfx.getHeight());
1388 context.nearPlane = camera.data->nearZ;
1389 context.farPlane = camera.data->farZ;
1391 gfx.getPrimitiveScene()->render(canvas);
1392 if (!canvas.commands().empty() || !canvas.triangles().empty()) gfx.drawPrimitiveScene(canvas);
1393 };
1394
1395 if (!haveManager && g_forwardDrawers.empty() && g_gpuOpaqueCollectors.empty()) {
1396 drawPersistentPrimitives();
1397 return;
1398 }
1399
1400 // Replay the items collected above: opaque first, hair back-to-front.
1401 std::vector<const CulledItem*> opaque;
1402 std::vector<const CulledItem*> transparentItems;
1403 opaque.reserve(items.size());
1404 transparentItems.reserve(items.size() / 4);
1405 for (const auto& item : items) {
1406 if (!item.inView || item.shadowsOnly) continue;
1407 (item.surfaceMode == SurfaceMode::Transparent ? transparentItems : opaque).push_back(&item);
1408 }
1409 // Opaque: group by (camera, shader, material, mesh) so the backend sees
1410 // long runs of identical pipeline/descriptor state instead of thrashing
1411 // between materials. Hair stays sorted back-to-front by distance below.
1412 std::stable_sort(opaque.begin(), opaque.end(), [](const CulledItem* a, const CulledItem* b) {
1413 if (a->camIdx != b->camIdx) return a->camIdx < b->camIdx;
1414 if (a->shader != b->shader) return a->shader < b->shader;
1415 if (a->material != b->material) return a->material < b->material;
1416 return a->mesh < b->mesh;
1417 });
1418 std::stable_sort(transparentItems.begin(), transparentItems.end(), [](const CulledItem* a, const CulledItem* b) {
1419 if (a->camIdx != b->camIdx) return a->camIdx < b->camIdx;
1420 if (a->sortPriority != b->sortPriority) return a->sortPriority < b->sortPriority;
1421 return a->projectedDepth > b->projectedDepth;
1422 });
1423
1424 // Core metallic-roughness opaque/masked already lit by deferredLighting —
1425 // skip their Forward+ draws. Custom shaders, extended PBR, unlit, instances,
1426 // light probes, and x-ray stay on the forward path.
1427 auto isDeferredCoreOpaque = [&](const CulledItem& item) -> bool {
1428 if (!doDeferredLighting) return false;
1429 // The core deferred shader has no environment/decal samplers or
1430 // per-renderable shadow-receive policy. Keep those surfaces on the
1431 // existing opaque ForwardPlus overwrite path, alongside custom PBR.
1432 if (doDecal && !g_decalDrawers.empty()) return false;
1433 const auto* camera = cams[size_t(item.camIdx)].data;
1434 if (camera->envMap && camera->envIntensity > 0.f) return false;
1435 if (!item.receiveShadow) return false;
1436 if (item.surfaceMode == SurfaceMode::Transparent) return false;
1437 if (item.hair || item.xray || item.speedTreeFade) return false;
1438 if (item.mr->instances || item.lightProbeUsage != 0) return false;
1439 if (item.shader) return false;
1440 Material* mat = item.material;
1441 if (mat) {
1442 if (!mat->getReceiveShadow()) return false;
1443 if (mat->getTexCellBombStrength() > 0.f) return false;
1444 if (mat->getHeightTexture() && mat->getParallaxScale() > 0.f) return false;
1445 if (mat->effectiveShader()) return false;
1446 if (mat->isTransparentHair()) return false;
1447 const std::string model = mat->getShadingModel();
1448 if (model != "pbr") return false;
1449 if (!mat->getReceiveLight()) return false;
1450 // Dedicated PBR surfaces still use forward lighting for extensions
1451 // not represented by the five core G-buffer attachments.
1452 if (mat->hasPbrSurface()) return false;
1453 } else {
1454 if (item.mr->texBombStrength > 0.f) return false;
1455 if (item.mr->heightTexture && item.mr->parallaxScale > 0.f) return false;
1456 if (item.mr->shader) return false;
1457 if (!item.mr->receiveLight) return false;
1458 }
1459 return true;
1460 };
1461
1462 auto bindLegacyMaterial = [&](Renderable3D::MeshRenderer* mr) {
1464 mr->isHair, 0.5f);
1465 gfx.setMesh3DMaterial(mr->metallic, mr->roughness);
1466 gfx.setMesh3DTexCellBomb(mr->texBombScale, mr->texBombStrength, mr->texBombRot);
1467 gfx.setMesh3DNormalTexture(mr->normalTexture);
1468 gfx.setMesh3DPackedNormalMask(mr->packedNormalMask);
1469 gfx.setMesh3DHeightTexture(mr->heightTexture);
1470 gfx.setMesh3DParallax(mr->parallaxScale, mr->parallaxMinLayers, mr->parallaxMaxLayers);
1471 gfx.setMesh3DShadowReceive(mr->receiveShadow);
1472 };
1473
1474 // Per-camera / per-lighting state. The clustered SSBO table is uploaded at
1475 // most once per camera; afterwards only the cheap active flag toggles.
1476 int curCam = -1;
1477 bool curLit = false;
1478 bool curClustered = false;
1479 int curLightProbeUsage = 0;
1480
1481 auto drawMeshWithMaterial = [&](const CulledItem& item, CameraView& cv, std::span<const glm::mat4> models) {
1482 auto* mr = item.mr;
1483 Mesh* drawMesh = item.mesh;
1484 Material* mat = item.material;
1485 if (!drawMesh) return;
1486
1487 Texture* albedo = mr->texture;
1488 Color tint(mr->r, mr->g, mr->b, mr->a);
1489 Shader* shader = mr->shader;
1490 if (mat) {
1491 auto bound = mat->bind(gfx);
1492 if (!bound) throw Exception("%s", bound.error()->message().c_str());
1493 albedo = mat->getAlbedoTexture();
1494 tint = Color(mat->getTintR(), mat->getTintG(), mat->getTintB(), mat->getTintA());
1495 shader = mat->effectiveShader();
1496 } else {
1497 auto reset = gfx.setMesh3DPbrSurface(nullptr);
1498 if (!reset) throw Exception("%s", reset.error()->message().c_str());
1499 bindLegacyMaterial(mr);
1500 }
1501 if(item.lodWeight<0.9999f && !item.speedTreeFade)
1503 else if (item.speedTreeFade)
1505 mat && mat->getDoubleSided(), 0.5f, "cutoff");
1506 gfx.setMesh3DShadowReceive(item.receiveShadow && (!mat || mat->getReceiveShadow()));
1507
1508 const bool lit = mat ? mat->getReceiveLight() : mr->receiveLight;
1509 const bool clustered = lit && useClustered && !shader && item.lightProbeUsage == 0 && !item.speedTreeFade;
1510 if (item.camIdx != curCam || lit != curLit || clustered != curClustered ||
1511 (lit && (item.lightProbeUsage != 0 || curLightProbeUsage != 0))) {
1512 if (item.camIdx != curCam) {
1513 gfx.setMesh3DViewProj(cv.viewProj);
1514 gfx.setMesh3DView(cv.view);
1515 gfx.setMesh3DClip(cv.data->nearZ, cv.data->farZ);
1516 gfx.setMesh3DCameraPos(cv.eye);
1517 gfx.setMesh3DEnv(cv.data->envMap, cv.data->envIntensity);
1518 gfx.setMesh3DEnvProbe(cv.data->envProbeCenter, cv.data->envProbeExtent);
1519 curCam = item.camIdx;
1520 }
1521 if (clustered && cv.clusteredValid) {
1522 if (!cv.clusteredUploaded) {
1523 gfx.setMesh3DClusteredLighting(cv.clustered);
1524 cv.clusteredUploaded = true;
1525 } else {
1526 gfx.setMesh3DClusteredActive(true);
1527 }
1528 } else {
1529 gfx.setMesh3DClusteredActive(false);
1530 }
1531 if (lit) {
1532 Lighting3DPack lighting = cv.lighting;
1533 bool sampled = false;
1534 if (item.lightProbeUsage == 4 && mr->customLightProbe) {
1535 lighting.diffuseProbeSh = mr->customLightProbeSh;
1536 sampled = true;
1537 } else if (item.lightProbeUsage == 1) {
1539 item.worldC, 4);
1540 if (sample) {
1541 lighting.diffuseProbeSh = sample.value().coefficients;
1542 sampled = true;
1543 }
1544 } else if (item.lightProbeUsage == 2) {
1546 if (volume) {
1547 lighting.diffuseVolumePosition = volume.value().positions;
1548 lighting.diffuseVolumeExtent = volume.value().extents;
1549 lighting.diffuseVolumeSh = volume.value().coefficients;
1550 lighting.diffuseVolumeProbeCount = volume.value().count;
1551 lighting.diffuseVolumeTrilinearCell = volume.value().trilinearCell;
1552 }
1553 }
1554 lighting.diffuseProbeShEnabled = sampled;
1556 } else {
1557 Lighting3DPack none{};
1558 none.count = 0;
1559 none.ambient = glm::vec4(1.f, 1.f, 1.f, 0.f);
1560 gfx.setMesh3DLighting(none);
1561 }
1562 curLit = lit;
1563 curClustered = clustered;
1564 curLightProbeUsage = item.lightProbeUsage;
1565 }
1566
1567 // Local probes are spatial data. Select at the renderable bounds center
1568 // so adjacent volumes do not leak the camera's nearest probe into every
1569 // object in the frame.
1570 gfx.setMesh3DReflectionProbes(item.useReflectionProbes
1571 ? selectReflectionProbes(*cv.data, item.worldC) : ReflectionProbeUpload{});
1572
1573 const glm::mat4& model = item.model;
1574 if (albedo) eve::debug::rtBind("texture", "albedo");
1575 if (shader) eve::debug::rtBind("shader", item.hair ? "hair" : "mesh");
1576 eve::debug::rtBind("mesh", "renderable3d");
1577 eve::debug::rtDraw("drawMeshShader", shader ? "custom" : "default");
1578 if (!models.empty()) {
1579 eve::debug::rtDraw("drawMeshInstances", "ordinary material");
1580 auto drawn = gfx.drawMeshInstances(
1581 *drawMesh, models, albedo ? OptionalRef<Texture>{std::ref(*albedo)} : OptionalRef<Texture>{}, tint);
1582 if (!drawn) throw eve::Exception("%s", drawn.status().describe().c_str());
1583 } else if (mr->instances) {
1584 const auto &range = *mr->instances;
1585 auto drawn = gfx.drawMeshShaderInstances(*drawMesh, *shader, model, tint, range.first, range.count);
1586 if (!drawn) throw eve::Exception("%s", drawn.status().describe().c_str());
1587 } else
1588 gfx.drawMeshShader(drawMesh, model, albedo, tint, shader);
1589
1590 // X-ray second pass: paint only the occluded (behind-building) part over
1591 // the scene. The pipeline runs with depth test/write off + alpha blend and
1592 // the shader discards visible fragments by sampling the G-buffer depth.
1593 if (mr->xrayHighlight && mr->xrayShader) {
1594 float sw = gfx.getPixelWidth() > 0 ? float(gfx.getPixelWidth()) : float(gfx.getWidth());
1595 float shh = gfx.getPixelHeight() > 0 ? float(gfx.getPixelHeight()) : float(gfx.getHeight());
1596 if (mr->xrayShader->hasUniform("screenW")) mr->xrayShader->sendFloat("screenW", sw);
1597 if (mr->xrayShader->hasUniform("screenH")) mr->xrayShader->sendFloat("screenH", shh);
1598 eve::debug::rtBind("shader", "xray");
1599 eve::debug::rtDraw("drawMeshShader", "xray");
1600 gfx.drawMeshShader(drawMesh, model, albedo, tint, mr->xrayShader);
1601 }
1602 };
1603
1604 // Provide the G-buffer depth to X-ray shaders for the occlusion test.
1605 if (doGBuffer && rc->getGBuffer() && rc->getGBuffer()->isValid()) {
1607 }
1608
1609 if (doForward) {
1610 bool gpuDrivenUsed = false;
1611 if (gpuDrivenWanted && !useClustered && defaultCam &&
1612 (!opaque.empty() || !g_gpuOpaqueCollectors.empty())) {
1613 std::vector<const CulledItem*> gpuOpaque;
1614 std::vector<const CulledItem*> cpuOpaque;
1615 gpuOpaque.reserve(opaque.size());
1616 cpuOpaque.reserve(opaque.size());
1617 for (const CulledItem* it : opaque) {
1618 if ((autoInstance && (it->surfaceMode != SurfaceMode::Opaque || it->hair || it->xray ||
1619 it->speedTreeFade || it->lodWeight < 0.9999f || it->mr->instances)) ||
1620 it->mesh->hasGpuSkinning() || it->camIdx != 0 || !it->material || it->mr->camera != nullptr ||
1621 it->material->effectiveShader() != nullptr || it->lightProbeUsage != 0 ||
1622 !gfx.gpuDrivenMaterialUsable(it->material))
1623 cpuOpaque.push_back(it);
1624 else
1625 gpuOpaque.push_back(it);
1626 }
1627 if (!gpuOpaque.empty() || !g_gpuOpaqueCollectors.empty()) {
1628 const CameraView& cv = cams[0]; // default camera is slot 0
1629 const Camera3D::Data* cd = cv.data;
1630 const glm::vec3 eye = cv.eye;
1631 gfx.setMesh3DViewProj(cv.viewProj);
1632 gfx.setMesh3DView(cv.view);
1633 gfx.setMesh3DClip(cd->nearZ, cd->farZ);
1634 gfx.setMesh3DCameraPos(cv.eye);
1635 gfx.setMesh3DEnv(cd->envMap, cd->envIntensity);
1639 off.active = false;
1641 gfx.setMesh3DLighting(cv.lighting);
1642
1643 std::vector<eve::graphics::GpuInstance> instances;
1644 instances.reserve(gpuOpaque.size());
1645 std::unordered_map<Material*, uint32_t> materialIds;
1646 std::unordered_map<Mesh*, uint32_t> meshIds;
1647 auto materialId = [&](Material* material) {
1648 auto [entry, inserted] = materialIds.try_emplace(material);
1649 if (inserted) entry->second = gfx.gpuDrivenMaterialRecord(material);
1650 return entry->second;
1651 };
1652 auto meshId = [&](Mesh* mesh) {
1653 auto [entry, inserted] = meshIds.try_emplace(mesh);
1654 if (inserted) entry->second = gfx.gpuDrivenMeshRecord(mesh);
1655 return entry->second;
1656 };
1657 bool recordsOk = true;
1658 bool vgAny = false;
1659 const bool resolveWanted = gfx.gpuDrivenResolveWanted();
1660 for (const CulledItem* it : gpuOpaque) {
1661 const ReflectionProbeUpload probes = selectReflectionProbes(*cd, it->worldC);
1662 // Stage 3 VG: meshes with a virtual-geometry asset are culled /
1663 // drawn through the cluster path, not the instance chain.
1664 const uint32_t vgAsset =
1665 resolveWanted ? gfx.gpuDrivenVgAssetId(it->mesh) : eve::graphics::kInvalidGpuDrivenSlot;
1666 if (vgAsset != eve::graphics::kInvalidGpuDrivenSlot && probes.count == 0) {
1667 const uint32_t matId = materialId(it->material);
1669 recordsOk = false;
1670 break;
1671 }
1672 vgAny |= gfx.gpuDrivenVgSetInstance(vgAsset, it->model, matId);
1673 continue;
1674 }
1676 inst.model = it->model;
1677 inst.meshId = meshId(it->mesh);
1678 inst.materialId = materialId(it->material);
1679 inst.reflectionProbeSlots.z = uint32_t(probes.count);
1680 for (int probeIndex = 0; probeIndex < probes.count; ++probeIndex) {
1681 const auto& probe = probes.probes[probeIndex];
1682 const uint32_t slot = gfx.gpuDrivenReflectionProbeSlot(probe.cubemap);
1684 recordsOk = false;
1685 break;
1686 }
1687 inst.reflectionProbeSlots[probeIndex] = slot;
1688 inst.reflectionProbeCenter[probeIndex] = glm::vec4(probe.center, probe.intensity);
1689 inst.reflectionProbeExtent[probeIndex] = glm::vec4(probe.extent, probe.blendDistance);
1690 }
1691 if (!recordsOk) break;
1692 if (inst.meshId == eve::graphics::kInvalidGpuDrivenSlot ||
1693 inst.materialId == eve::graphics::kInvalidGpuDrivenSlot) {
1694 recordsOk = false;
1695 break;
1696 }
1697 instances.push_back(inst);
1698 }
1699 if (recordsOk && !g_gpuOpaqueCollectors.empty()) {
1700 const auto collectors = g_gpuOpaqueCollectors;
1701 for (const auto& entry : collectors)
1702 entry.collector(gfx, *cd, cv.viewProj, aspect, instances);
1703 }
1704 if (recordsOk) {
1705 // Stage 2: GPU frustum/HZB cull + GPU-written indirect commands.
1706 if (rc->isEnabled("gpuDriven") && gfx.gpuDrivenCullEnabled() && !instances.empty() &&
1707 gfx.gpuDrivenCullBegin(instances.data(), uint32_t(instances.size()))) {
1708 gfx.gpuDrivenCullEmit(cv.cullViewProj, eye, cd->fovYDeg, cd->nearZ, cd->farZ);
1709 if (gfx.gpuDrivenResolveWanted()) {
1710 // Stage 3: opaque goes to the GBuffer vis pass, the
1711 // scene color pass runs the fullscreen resolve.
1714 gfx.gpuDrivenResolve();
1715 } else {
1717 gfx.gpuDrivenDrawOpaque();
1718 }
1719 gpuDrivenUsed = true;
1720 } else if (rc->isEnabled("gpuDriven") && gfx.gpuDrivenCullEnabled() && instances.empty() && vgAny) {
1721 // VG-only frame: no instance chain; the vis pass runs the
1722 // VG cluster cull + draws + resolve.
1723 gfx.gpuDrivenVgComputeSection(cv.cullViewProj, eye, cd->fovYDeg, cd->nearZ, cd->farZ);
1726 gfx.gpuDrivenResolve();
1727 gpuDrivenUsed = true;
1728 } else {
1729 // Deferred scene pass must be open before stage-1 recording.
1731 if (gfx.gpuDrivenSubmitOpaque(instances.data(), uint32_t(instances.size())))
1732 gpuDrivenUsed = true;
1733 }
1734 }
1735 if (gpuDrivenUsed) {
1737 for (const CulledItem* item : cpuOpaque)
1738 drawMeshWithMaterial(*item, cams[size_t(item->camIdx)], {});
1739 }
1740 }
1741 }
1742 if (!gpuDrivenUsed) {
1744 // Frame-local projection of the existing Renderable3D View, not a second ECS owner.
1745 // Reads Transform3D/MeshRenderer only; no structural mutation or callbacks while grouping.
1746 // Opaque shared-state groups preserve each model matrix and original culling decision.
1747 const bool ordinaryInstances = !doDeferredLighting && !useClustered && gfx.supportsMeshInstancing();
1748 auto instanceEligible = [&](const CulledItem& item) {
1749 if (!ordinaryInstances || !item.material || item.shader || item.hair || item.xray ||
1750 item.speedTreeFade || item.lodWeight < .9999f || item.mr->instances || item.mr->camera ||
1751 item.mesh->hasGpuSkinning() || item.lightProbeUsage != 0 ||
1752 item.surfaceMode != SurfaceMode::Opaque || item.material->hasPbrSurface())
1753 return false;
1754 const auto& probes = cams[size_t(item.camIdx)].data->reflectionProbes;
1755 return std::none_of(probes.begin(), probes.end(),
1756 [](const auto& probe) { return probe.enabled && probe.cubemap; });
1757 };
1758 constexpr size_t minInstances = 128;
1759 constexpr size_t maxBatchInstances = 16384;
1760 std::vector<glm::mat4> models;
1761 for (size_t first = 0; first < opaque.size();) {
1762 const CulledItem& item = *opaque[first];
1763 if (isDeferredCoreOpaque(item)) {
1764 ++first;
1765 continue;
1766 }
1767 size_t end = first + 1;
1768 if (instanceEligible(item)) {
1769 while (end < opaque.size()) {
1770 const auto& next = *opaque[end];
1771 if (next.camIdx != item.camIdx || next.mesh != item.mesh || next.material != item.material ||
1772 next.receiveShadow != item.receiveShadow ||
1773 next.useReflectionProbes != item.useReflectionProbes || !instanceEligible(next))
1774 break;
1775 ++end;
1776 }
1777 }
1778 if (end - first >= minInstances) {
1779 models.reserve(std::min(end - first, maxBatchInstances));
1780 for (size_t batch = first; batch < end; batch += maxBatchInstances) {
1781 const size_t stop = std::min(end, batch + maxBatchInstances);
1782 models.clear();
1783 for (size_t i = batch; i < stop; ++i) models.push_back(opaque[i]->model);
1784 drawMeshWithMaterial(item, cams[size_t(item.camIdx)], models);
1785 }
1786 } else {
1787 for (size_t i = first; i < end; ++i)
1788 drawMeshWithMaterial(*opaque[i], cams[size_t(opaque[i]->camIdx)], {});
1789 }
1790 first = end;
1791 }
1792 }
1793 if (defaultCam && !g_forwardDrawers.empty()) {
1795 const CameraView& cv = cams.front();
1796 const Camera3D::Data* cd = cv.data;
1797 gfx.setMesh3DViewProj(cv.viewProj);
1798 gfx.setMesh3DView(cv.view);
1799 gfx.setMesh3DClip(cd->nearZ, cd->farZ);
1800 gfx.setMesh3DCameraPos(cv.eye);
1801 gfx.setMesh3DEnv(cd->envMap, cd->envIntensity);
1804 gfx.setMesh3DLighting(cv.lighting);
1805 if (useClustered)
1806 gfx.setMesh3DClusteredLighting(cv.clustered);
1807 else {
1809 off.active = false;
1811 }
1812 const auto drawers = g_forwardDrawers;
1813 for (const auto& entry : drawers) entry.drawer(gfx, *cd, cv.viewProj, aspect);
1814 }
1815 }
1816 if (doForward || doHair) {
1817 // Generic transparent surfaces belong to the forward pass; the legacy
1818 // hair pass remains independently switchable for hair materials.
1820 for (const CulledItem* item : transparentItems) {
1821 if ((item->hair && doHair) || (!item->hair && doForward))
1822 drawMeshWithMaterial(*item, cams[size_t(item->camIdx)], {});
1823 }
1824 }
1825
1826 drawPersistentPrimitives();
1827
1828 const bool doAO = rc->isEnabled("ao");
1829 const bool doContactShadow = rc->isEnabled("contactShadow");
1830 const bool doRTGI = rc->isEnabled("rtgi") || rc->isEnabled("reflectionChain");
1831 const bool doSSR = rc->isEnabled("ssr") || rc->isEnabled("reflectionChain");
1832 const bool doRTX = rc->isEnabled("rtx");
1833 bool aoApplied = false;
1834 auto applyAO = [&]() {
1835 if ((!doAO && !doContactShadow) || !gfx.supportsGBufferPost() || !defaultCam || !gfx.had3DThisFrame()) return;
1836 GBuffer* gb = rc->getGBuffer();
1837 if (gb && gb->isValid()) {
1838 auto cd = defaultCam->data();
1839 const float aspectSafe = aspect > 1e-4f ? aspect : 1.f;
1840 auto bindCam = [&](auto* fx) {
1841 fx->setCamera(cd->eyeX, cd->eyeY, cd->eyeZ, cd->targetX, cd->targetY, cd->targetZ, cd->upX, cd->upY,
1842 cd->upZ, cd->fovYDeg, aspectSafe, cd->nearZ, cd->farZ);
1843 };
1844 // WebGPU cannot bind a depth-aspect texture to the generic 2D
1845 // post-process layout. Its G-buffer already carries equivalent
1846 // linear depth in a filterable RGBA target.
1847 Texture* depth = gfx.getBackendName() == "webgpu" ? gb->getDepthTexture() : gb->getHwDepthTexture();
1848 if (doAO) {
1850 ao->setQuality("medium");
1851 ao->setIntensity(0.16f);
1852 ao->setPower(1.1f);
1853 ao->setRadius(std::clamp(cd->farZ * 0.006f, 0.18f, 0.35f));
1854 bindCam(ao);
1855 if (depth) ao->applyFromGBuffer(&gfx, depth, gb->getNormalTexture());
1856 }
1857 if (doContactShadow && depth) {
1859 // High: dual-ray soft (center + tangent) + binary refine;
1860 // kills zebra banding under spheres / box feet without a blur pass.
1861 cs->setQuality(rc->getPostProcessQuality() == "low" ? "medium" : "high");
1862 glm::vec3 lightDir = gLightDir;
1863 if (shadowCaster) {
1864 lightDir = glm::vec3(shadowCaster->dx, shadowCaster->dy, shadowCaster->dz);
1865 } else if (!packed.empty() && packed[0].data && !packed[0].isPoint) {
1866 lightDir = glm::vec3(packed[0].data->dx, packed[0].data->dy, packed[0].data->dz);
1867 }
1868 if (glm::length(lightDir) < 1e-6f)
1869 lightDir = glm::vec3(0.f, 1.f, 0.f);
1870 else
1871 lightDir = glm::normalize(lightDir);
1873 bindCam(cs);
1874 if (!cams.empty()) cs->setInvViewProj(glm::inverse(cams.front().viewProj));
1875 cs->applyFromGBuffer(&gfx, depth, gb->getNormalTexture());
1876 }
1877 // Fullscreen SSGI from lit scene color reprints nearby props
1878 // (curtains, planters) onto the floor as multiple swimming ghosts.
1879 // Mesh shaders still add hemispheric sky/ground + wrap fill.
1880 }
1881 aoApplied = true;
1882 };
1883
1884 const bool doReflectionLighting = doRTGI || doSSR || doRTX;
1885 if (doReflectionLighting && defaultCam && gfx.had3DThisFrame()) {
1886 GBuffer* gb = rc->getGBuffer();
1887 if (gb && gb->isValid()) {
1888 Texture* sceneColor = gfx.getSceneColorTexture();
1889 Texture* depth = gfx.getBackendName() == "webgpu" ? gb->getDepthTexture() : gb->getHwDepthTexture();
1890 if (sceneColor && depth) {
1891 DepthPyramid* depthPyramid = gfx.pipelineDepthPyramid();
1892 const std::string reflectionQuality = rc->getReflectionQuality();
1893 const int depthBudget = reflectionQuality == "low" ? 4 : reflectionQuality == "medium" ? 6 : 8;
1894 Texture* depthAtlas = depthPyramid->build(depth, depthBudget);
1895 const int depthLevels = depthPyramid->getLevelCount();
1896 auto cd = defaultCam->data();
1897 const float aspectSafe = aspect > 1e-4f ? aspect : 1.f;
1898 const float dw = gfx.getCanvas() ? float(gfx.getCanvas()->getWidth()) : float(gfx.getWidth());
1899 const float dh = gfx.getCanvas() ? float(gfx.getCanvas()->getHeight()) : float(gfx.getHeight());
1900 auto bindCam = [&](auto* fx) {
1901 fx->setCamera(cd->eyeX, cd->eyeY, cd->eyeZ, cd->targetX, cd->targetY, cd->targetZ, cd->upX, cd->upY,
1902 cd->upZ, cd->fovYDeg, aspectSafe, cd->nearZ, cd->farZ);
1903 if (!cams.empty()) fx->setInvViewProj(glm::inverse(cams.front().viewProj));
1904 };
1905
1906 Texture* rtgiTexture = nullptr;
1907 Texture* ssrTexture = nullptr;
1908
1909 if (doRTGI) {
1911 if (gi->getQuality() != rc->getReflectionQuality()) gi->setQuality(rc->getReflectionQuality());
1915 gi->setDepthPyramid(depthAtlas, depthLevels);
1916 bindCam(gi);
1917 Canvas* rtgiCanvas = gi->getWorkingCanvas();
1918 if (rtgiCanvas) {
1919 gi->applyFromSceneTo(&gfx, sceneColor, depth, rtgiCanvas);
1920 rtgiTexture = gi->getWorkingTexture();
1921 }
1922 }
1923
1924 // Hardware RT reflections (optional module). Prefer RTX when
1925 // available; fall through to SSR on NoOp / failure / absent provider.
1926 if (doRTX) {
1927 if (auto rayTracing = gfx.rayTracingService()) {
1928 auto* rt = &rayTracing->get();
1929 if (rt->isAvailable()) {
1931 Canvas* reflCanvas = ssr->getReflectionCanvas();
1932 if (reflCanvas) {
1933 // Switching canvas ends the open scene-color pass so RT
1934 // can sample the finished frame on the present CB.
1935 Canvas* prevCanvas = gfx.getCanvas();
1936 gfx.setCanvas(reflCanvas);
1937
1938 rt->clearScene();
1939 constexpr size_t kMaxRtMeshes = 64;
1940 size_t registered = 0;
1941 for (const CulledItem* item : opaque) {
1942 if (!item || !item->mesh || registered >= kMaxRtMeshes) continue;
1943 auto added = rt->addMesh(item->mesh, item->model);
1944 if (added.ok()) {
1945 ++registered;
1946 (void)added.value();
1947 } else {
1948 added.ignore();
1949 }
1950 }
1951 bool produced = false;
1952 if (registered > 0) {
1953 auto rebuilt = rt->rebuildScene();
1954 if (rebuilt.ok()) {
1955 glm::mat4 viewProj = !cams.empty() ? cams.front().viewProj : glm::mat4(1.f);
1956 glm::mat4 invVP = glm::inverse(viewProj);
1957 glm::vec3 eye(cd->eyeX, cd->eyeY, cd->eyeZ);
1958 auto applied =
1959 rt->applyReflections(&gfx, sceneColor, depth, gb->getNormalTexture(),
1960 reflCanvas, invVP, viewProj, eye);
1961 if (applied.ok() && applied.code() != eve::StatusCode::NoOp) {
1962 ssrTexture = reflCanvas->getTexture();
1963 produced = true;
1964 } else {
1965 applied.ignore();
1966 }
1967 } else {
1968 rebuilt.ignore();
1969 }
1970 }
1971 (void)produced;
1972 gfx.setCanvas(prevCanvas);
1973 }
1974 }
1975 }
1976 }
1977
1978 // Portable SSR path: explicit ssr/reflectionChain, or RTX requested
1979 // but hardware did not produce a usable reflection texture.
1980 if ((doSSR || doRTX) && !ssrTexture) {
1982 if (ssr->getQuality() != rc->getReflectionQuality()) ssr->setQuality(rc->getReflectionQuality());
1983 ssr->setEnabled(true);
1985 ssr->setDepthPyramid(depthAtlas, depthLevels);
1986 bindCam(ssr);
1987 Canvas* reflCanvas = ssr->getReflectionCanvas();
1988 if (reflCanvas) {
1989 ssr->applyFromSceneTo(&gfx, sceneColor, depth, gb->getNormalTexture(), gb->getAlbedoTexture(),
1990 reflCanvas);
1991 ssrTexture = ssr->getReflectionTexture();
1992 }
1993 }
1994
1995 // Queue AO only after selecting the final composition target;
1996 // switching targets with a pending AO draw presents too early.
1997 if (rtgiTexture || ssrTexture) {
1998 if (Canvas* composite = gfx.pipelineReflectionComposite(int(dw), int(dh))) {
1999 // Register before setCanvas(): switching away from the scene target
2000 // closes its pass and queues the final resolve immediately.
2001 gfx.setFinalSceneTexture(composite->getTexture());
2002 Canvas* previous = gfx.getCanvas();
2003 gfx.setCanvas(composite);
2004 gfx.drawTexturedRectShaderUV(sceneColor, nullptr, 0.f, 0.f, dw, dh, 0.f, 0.f, 1.f, 1.f,
2005 Color(1.f, 1.f, 1.f, 1.f), false, BlendMode::Opaque);
2006 applyAO();
2007 if (rtgiTexture)
2008 gfx.drawTexturedRectShaderUV(rtgiTexture, nullptr, 0.f, 0.f, dw, dh, 0.f, 0.f, 1.f, 1.f,
2009 Color(1.f, 1.f, 1.f, 1.f), false, BlendMode::Additive);
2010 if (ssrTexture)
2011 gfx.drawTexturedRectShaderUV(ssrTexture, nullptr, 0.f, 0.f, dw, dh, 0.f, 0.f, 1.f, 1.f,
2012 Color(1.f, 1.f, 1.f, 1.f), false, BlendMode::Premultiplied);
2013 gfx.setCanvas(previous);
2014 }
2015 }
2016 }
2017 }
2018 }
2019 if (!aoApplied) applyAO();
2020
2021 const bool doOutline = rc->isEnabled("outline");
2022 if (doOutline && defaultCam && gfx.had3DThisFrame()) {
2023 GBuffer* gb = rc->getGBuffer();
2024 if (gb && gb->isValid()) {
2025 Outline* outline = gfx.pipelineOutline();
2026 auto cd = defaultCam->data();
2027 outline->setClip(cd->nearZ, cd->farZ);
2028 Texture* depth = gfx.getBackendName() == "webgpu" ? gb->getDepthTexture() : gb->getHwDepthTexture();
2029 if (depth) outline->apply(&gfx, depth, gb->getNormalTexture());
2030 }
2031 }
2032}
2033
2034void RenderSystem3D::renderToCanvas(Graphics& gfx, Canvas* target, Camera3D* camera, uint32_t reflectionCaptureMask,
2035 float lodDistanceScale, bool includeTransparent, bool useClusteredLighting,
2036 Texture* skyFaceTexture, Mesh* skyQuad, float skyFaceTextureScale,
2037 bool includePrimitives) {
2038 renderToCanvasImpl(gfx, target, camera, reflectionCaptureMask, lodDistanceScale, includeTransparent,
2039 useClusteredLighting, skyFaceTexture, skyQuad, skyFaceTextureScale, CanvasShadows::Disabled,
2040 includePrimitives);
2041}
2042
2044 renderToCanvasImpl(gfx, &target, &camera, 0xffffffffu, 1.f, true, true, nullptr, nullptr, 1.f,
2045 CanvasShadows::Directional, false);
2046}
2047
2048void RenderSystem3D::renderToCanvasImpl(Graphics& gfx, Canvas* target, Camera3D* camera, uint32_t reflectionCaptureMask,
2049 float lodDistanceScale, bool includeTransparent, bool useClusteredLighting,
2050 Texture* skyFaceTexture, Mesh* skyQuad, float skyFaceTextureScale,
2051 CanvasShadows shadows, bool includePrimitives) {
2052 if (!target || !camera) return;
2053 auto cd = camera->data();
2054 const float aspect = target->getWidth() > 0 ? float(target->getWidth()) / float(target->getHeight()) : 1.f;
2055
2056 const glm::vec3 eye(cd->eyeX, cd->eyeY, cd->eyeZ);
2057 const glm::vec3 look(cd->targetX, cd->targetY, cd->targetZ);
2058 const glm::vec3 up(cd->upX, cd->upY, cd->upZ);
2059 const glm::mat4 viewM = glm::lookAtRH(eye, look, up);
2060 const float fovRad = cd->fovYDeg * 0.017453292519943295f;
2061 const glm::mat4 projM =
2062 cameraProjectionVulkanRH_ZO(cd->orthographic, fovRad, cd->orthoHeight, aspect, cd->nearZ, cd->farZ);
2063 auto prepared = detail::prepareViewResources(gfx, projM * viewM, eye);
2064 if (!prepared) throw eve::Exception("%s", prepared.status().describe().c_str());
2065 // Collect lights before staging optional directional preview shadows.
2066 std::vector<PackedLight3D> packed;
2067 collectLights3D(packed, size_t(ClusteredLightConfig::kMaxLights));
2068 promoteDirectional(packed);
2069 const glm::mat4 captureViewProj = projM * viewM;
2070 {
2071 const FrustumPlanes captureFrustum = extractFrustum(captureViewProj);
2072 struct CanvasItem {
2073 Renderable3D::MeshRenderer* mr = nullptr;
2074 Mesh* mesh = nullptr;
2075 Material* material = nullptr;
2076 glm::mat4 model{1.f};
2077 float distance2 = 0.f;
2078 SurfaceMode surface = SurfaceMode::Opaque;
2079 int sortPriority = 0;
2080 float lodWeight = 1.f;
2081 bool lodFadeReverse = false;
2082 bool speedTreeFade = false;
2083 int skinInfluenceLimit = 4;
2084 int lightProbeUsage = 0;
2085 glm::vec3 worldCenter{0.f};
2086 bool inView = true;
2087 };
2088 std::vector<CanvasItem> canvasItems;
2089 if (ecs::current()->getManager<Renderable3D>() != nullptr) {
2090 auto view = ecs::View<Renderable3D, Renderable3D::Transform3D, Renderable3D::MeshRenderer>();
2091 for (auto it = view.begin(); it != view.end(); ++it) {
2092 auto [xf, mr] = *it;
2093 if (!mr->visible || (mr->reflectionCaptureMask & reflectionCaptureMask) == 0u) continue;
2094 if (mr->instances) {
2096 if (!valid) throw eve::Exception("%s", valid.status().describe().c_str());
2097 }
2098 const glm::mat4 model = modelFromTransform(*xf);
2099 const float maxScale = detail::sphereStretch(*xf);
2100 const float dx = xf->x - eye.x;
2101 const float dy = xf->y - eye.y;
2102 const float dz = xf->z - eye.z;
2103 const float distance2 = dx * dx + dy * dy + dz * dz;
2104 auto append = [&](Mesh* mesh, Material* material, bool hair, float lodWeight,
2105 int skinInfluenceLimit = 4, int lightProbeUsage = 0, bool lodFadeReverse = false) {
2106 if (!mesh) return;
2107 glm::vec3 worldCenter(xf->x, xf->y, xf->z);
2108 bool inView = true;
2109 if (mr->instances) {
2110 inView = meshInstanceRangeVisible(*mr->instances, model, captureViewProj, eye);
2111 } else if (mesh->hasBounds()) {
2112 const glm::vec4 transformedCenter =
2113 model * glm::vec4(mesh->boundsCx, mesh->boundsCy, mesh->boundsCz, 1.f);
2114 worldCenter = glm::vec3(transformedCenter);
2115 inView = captureFrustum.sphereVisible(worldCenter, mesh->boundsRadius * maxScale);
2116 }
2117 if (!inView && shadows == CanvasShadows::Disabled) return;
2118 SurfaceMode surface =
2120 lodWeight = std::clamp(lodWeight, 0.f, 1.f);
2121 const bool speedTreeFade =
2122 mr->lodFadeMode == 1 && lodWeight < 0.9999f && !(material && material->effectiveShader());
2123 if (lodWeight < 0.9999f && !speedTreeFade) surface = SurfaceMode::Transparent;
2124 if (surface == SurfaceMode::Transparent && !includeTransparent) return;
2125 const int sortPriority = material ? material->getSortPriority() : 0;
2126 canvasItems.push_back(CanvasItem{mr, mesh, material, model, distance2, surface, sortPriority,
2128 lightProbeUsage, worldCenter, inView});
2129 };
2130 if (mr->usesParts()) {
2131 for (int part = 0; part < mr->partCount; ++part) {
2132 Material* material = mr->parts[part].material ? mr->parts[part].material : mr->material;
2133 append(mr->parts[part].mesh, material, material ? material->isTransparentHair() : mr->isHair,
2134 1.f);
2135 }
2136 } else {
2137 const float distance = std::sqrt(distance2) * std::max(lodDistanceScale, 0.01f);
2138 int primary = -1, secondary = -1;
2139 float secondaryWeight = 0.f;
2140 mr->lodBlendForDistance(distance, primary, secondary, secondaryWeight);
2141 auto meshAt = [&](int level) -> Mesh* {
2142 if (mr->lodCount <= 0) return level >= 0 ? mr->mesh : nullptr;
2143 return level >= 0 && level < mr->lodCount ? mr->lodMeshes[level] : nullptr;
2144 };
2145 const bool hair = mr->material ? mr->material->isTransparentHair() : mr->isHair;
2146 auto qualityAt = [&](int level) {
2147 if (level < 0 || level >= mr->lodCount || !mr->lodRendererStates[level].configured ||
2148 mr->lodRendererStates[level].skinQuality == 0)
2149 return 4;
2150 return mr->lodRendererStates[level].skinQuality;
2151 };
2152 auto lightProbeAt = [&](int level) {
2153 if (level < 0 || level >= mr->lodCount || !mr->lodRendererStates[level].configured) return 0;
2154 return mr->lodRendererStates[level].lightProbeUsage;
2155 };
2156 append(meshAt(primary), mr->material, hair, 1.f - secondaryWeight, qualityAt(primary),
2157 lightProbeAt(primary));
2158 if (secondaryWeight > 0.f)
2159 append(meshAt(secondary), mr->material, hair, secondaryWeight, qualityAt(secondary),
2160 lightProbeAt(secondary), true);
2161 }
2162 }
2163 }
2164 std::stable_sort(canvasItems.begin(), canvasItems.end(), [](const CanvasItem& a, const CanvasItem& b) {
2165 const bool transparentA = a.surface == SurfaceMode::Transparent;
2166 const bool transparentB = b.surface == SurfaceMode::Transparent;
2167 if (transparentA != transparentB) return !transparentA;
2168 if (transparentA) {
2169 if (a.sortPriority != b.sortPriority) return a.sortPriority < b.sortPriority;
2170 if (a.distance2 != b.distance2) return a.distance2 > b.distance2;
2171 }
2172 if (a.material != b.material) return a.material < b.material;
2173 return a.mesh < b.mesh;
2174 });
2175
2176 ShadowUpload shadowUpload{};
2177 Light3D::Data* caster = nullptr;
2178 if (shadows == CanvasShadows::Directional && ShadowSchemeSettings::current().enableDirectionalCsm) {
2179 for (const auto& light : packed) {
2180 if (!light.isPoint && light.data->castShadow && light.data->shadowMethod != 1) {
2181 caster = light.data;
2182 break;
2183 }
2184 }
2185 }
2186 if (caster) {
2187 prioritizeShadowCaster(packed, caster);
2188 glm::vec3 direction(caster->dx, caster->dy, caster->dz);
2189 direction = glm::length(direction) < 1e-6f ? glm::vec3(0.f, 1.f, 0.f) : glm::normalize(direction);
2190 shadowUpload = buildDirectionalCSM(direction, eye, look, up, fovRad, aspect, cd->nearZ, cd->farZ,
2191 caster->shadowBias, caster->shadowStrength);
2192 gfx.setMesh3DShadows(shadowUpload);
2193 for (int cascade = 0; cascade < ShadowConfig::kCascades; ++cascade) {
2194 gfx.beginShadowPass(cascade);
2195 for (const CanvasItem& item : canvasItems) {
2196 if (!item.mr->effectiveCastShadow() || (item.material && !item.material->getCastShadow())) continue;
2197 if (item.surface == SurfaceMode::Transparent) continue;
2198 const float limit = cd->shadowLayerCullDistances[size_t(item.mr->layer)];
2199 if (limit > 0.f && item.distance2 > limit * limit) continue;
2200 const bool doubleSided = item.material && item.material->getDoubleSided();
2201 gfx.setMesh3DSkinInfluenceLimit(skinInfluenceLimit(item.skinInfluenceLimit));
2202 if (item.surface == SurfaceMode::Masked)
2203 gfx.drawMeshShadowAlpha(item.mesh, shadowUpload.ubo.lightVP[cascade] * item.model,
2204 item.material ? item.material->getAlbedoTexture() : item.mr->texture,
2206 else
2207 gfx.drawMeshShadow(item.mesh, shadowUpload.ubo.lightVP[cascade] * item.model, doubleSided);
2208 }
2209 gfx.endShadowPass();
2210 }
2211 }
2212 // Offscreen backends consume staged shadows before opening color.
2213 gfx.setMesh3DShadows(shadowUpload);
2215 gfx.setMesh3DViewProj(projM * viewM);
2216 gfx.setMesh3DView(viewM);
2217 gfx.setMesh3DClip(cd->nearZ, cd->farZ);
2219 gfx.setMesh3DEnv(cd->envMap, cd->envIntensity);
2220 gfx.setMesh3DEnvProbe(cd->envProbeCenter, cd->envProbeExtent);
2221 gfx.setMesh3DReflectionProbes(selectReflectionProbes(*cd, eye));
2222 gfx.setSceneExposure(std::exp2(cd->exposureEV));
2223 gfx.setSceneAutoExposure(cd->autoExposure, cd->autoExposureMinEV, cd->autoExposureMaxEV);
2224 gfx.setSceneBloom(cd->bloomIntensity, cd->bloomThreshold);
2225 gfx.setSceneDepthOfField(cd->dofFocusDistance, cd->dofMaxBlurPx, cd->dofFocusRange, cd->nearZ, cd->farZ);
2226
2227 bool clusteredCapture = false;
2228 if (useClusteredLighting && packed.size() > size_t(Lighting3DPack::kMaxLights)) {
2229 std::vector<ClusteredLightGpu> clusteredPoints;
2230 std::vector<ClusteredLightGpu> clusteredDirections;
2231 splitLights(packed, clusteredPoints, clusteredDirections);
2232 ClusteredLightingUpload clustered =
2233 buildClusteredLighting(clusteredPoints, clusteredDirections, viewM, cd->nearZ, cd->farZ,
2234 target->getWidth(), target->getHeight(), cd->fovYDeg * 0.017453292519943295f,
2235 glm::vec4(cd->ambientR, cd->ambientG, cd->ambientB, 0.f));
2236 clusteredCapture = clustered.active;
2238 } else {
2239 ClusteredLightingUpload noClustered{};
2240 noClustered.active = false;
2241 gfx.setMesh3DClusteredLighting(noClustered);
2242 }
2243 gfx.setMesh3DLighting(packLights3D(packed, cd.operator->()));
2244 gfx.setMesh3DShadows(shadowUpload);
2245
2246 if (skyFaceTexture && skyQuad) {
2247 const float distance = std::max(cd->farZ * 0.999f, cd->nearZ * 2.f);
2248 glm::mat4 skyModel = glm::inverse(viewM);
2249 skyModel = glm::translate(skyModel, glm::vec3(0.f, 0.f, -distance));
2250 skyModel = glm::scale(skyModel, glm::vec3(distance * aspect * 1.01f, distance * 1.01f, 1.f));
2251 Lighting3DPack unlit{};
2252 unlit.ambient = glm::vec4(1.f, 1.f, 1.f, 0.f);
2253 gfx.setMesh3DClusteredActive(false);
2254 gfx.setMesh3DLighting(unlit);
2255 gfx.setMesh3DEnv(nullptr, 0.f);
2257 gfx.setMesh3DMaterial(0.f, 1.f);
2258 gfx.setMesh3DShadowReceive(false);
2259 const float skyScale = std::max(skyFaceTextureScale, 0.f);
2260 gfx.drawMeshShader(skyQuad, skyModel, skyFaceTexture, Color(skyScale, skyScale, skyScale, 1.f), nullptr);
2261 gfx.setMesh3DEnv(cd->envMap, cd->envIntensity);
2262 gfx.setMesh3DClusteredActive(clusteredCapture);
2263 gfx.setMesh3DLighting(packLights3D(packed, cd.operator->()));
2264 }
2265
2266 bool lightingEnabled = true;
2267 for (const CanvasItem& item : canvasItems) {
2268 if (!item.inView) continue;
2269 Renderable3D::MeshRenderer* mr = item.mr;
2270 Texture* albedo = mr->texture;
2271 Color tint(mr->r, mr->g, mr->b, mr->a);
2272 Shader* shader = mr->shader;
2273 const bool lit = item.material ? item.material->getReceiveLight() : mr->receiveLight;
2274 if (lit) {
2275 Lighting3DPack lighting = packLights3D(packed, cd.operator->());
2276 bool sampled = false;
2277 if (item.lightProbeUsage == 4 && mr->customLightProbe) {
2278 lighting.diffuseProbeSh = mr->customLightProbeSh;
2279 sampled = true;
2280 } else if (item.lightProbeUsage == 1) {
2282 item.worldCenter, 4);
2283 if (sample) {
2284 lighting.diffuseProbeSh = sample.value().coefficients;
2285 sampled = true;
2286 }
2287 } else if (item.lightProbeUsage == 2) {
2288 auto volume = DiffuseLightProbeRegistry::instance().selectVolume(item.worldCenter);
2289 if (volume) {
2290 lighting.diffuseVolumePosition = volume.value().positions;
2291 lighting.diffuseVolumeExtent = volume.value().extents;
2292 lighting.diffuseVolumeSh = volume.value().coefficients;
2293 lighting.diffuseVolumeProbeCount = volume.value().count;
2294 lighting.diffuseVolumeTrilinearCell = volume.value().trilinearCell;
2295 }
2296 }
2297 lighting.diffuseProbeShEnabled = sampled;
2298 gfx.setMesh3DClusteredActive(clusteredCapture && item.lightProbeUsage == 0);
2300 } else if (lightingEnabled) {
2301 gfx.setMesh3DClusteredActive(false);
2302 Lighting3DPack unlit{};
2303 unlit.ambient = glm::vec4(1.f, 1.f, 1.f, 0.f);
2304 gfx.setMesh3DLighting(unlit);
2305 }
2306 lightingEnabled = lit;
2307 if (item.material) {
2308 auto bound = item.material->bind(gfx);
2309 if (!bound) throw Exception("%s", bound.error()->message().c_str());
2310 albedo = item.material->getAlbedoTexture();
2311 tint = Color(item.material->getTintR(), item.material->getTintG(), item.material->getTintB(),
2312 item.material->getTintA());
2313 shader = item.material->effectiveShader();
2314 } else {
2315 gfx.setMesh3DSurface(item.surface, BlendMode::Alpha, false, mr->isHair, 0.5f);
2316 gfx.setMesh3DMaterial(mr->metallic, mr->roughness);
2317 gfx.setMesh3DTexCellBomb(mr->texBombScale, mr->texBombStrength, mr->texBombRot);
2318 gfx.setMesh3DNormalTexture(mr->normalTexture);
2319 gfx.setMesh3DHeightTexture(mr->heightTexture);
2320 gfx.setMesh3DParallax(mr->parallaxScale, mr->parallaxMinLayers, mr->parallaxMaxLayers);
2321 }
2322 if (item.lodWeight < 0.9999f && !item.speedTreeFade)
2324 item.material && item.material->getDoubleSided(), false, 0.5f);
2325 else if (item.speedTreeFade)
2327 item.material && item.material->getDoubleSided(), 0.5f, "cutoff");
2328 gfx.setMesh3DShadowReceive(shadowUpload.active && mr->receiveShadow &&
2329 (!item.material || item.material->getReceiveShadow()));
2330 eve::debug::rtDraw("drawMeshShader", shader ? "custom" : "default");
2331 if (mr->instances) {
2332 const auto &range = *mr->instances;
2333 auto drawn =
2334 gfx.drawMeshShaderInstances(*item.mesh, *shader, item.model, tint, range.first, range.count);
2335 if (!drawn) throw eve::Exception("%s", drawn.status().describe().c_str());
2336 } else
2337 gfx.drawMeshShader(item.mesh, item.model, albedo, tint, shader);
2338 }
2339 }
2340
2341 // Copy the list so a contributor may safely unregister itself while drawing.
2342 const auto captureDrawers = g_captureDrawers;
2343 for (const CaptureExtraDrawerEntry& entry : captureDrawers) {
2344 if ((entry.mask & reflectionCaptureMask) == 0u || !entry.drawer) continue;
2345 entry.drawer(gfx, *cd, captureViewProj, aspect, reflectionCaptureMask);
2346 }
2347
2348 if (includePrimitives) {
2349 SceneDrawContext context;
2350 context.view = viewM;
2351 context.projection = projM;
2352 context.cameraPosition = eye;
2353 context.viewportSize = glm::ivec2(target->getWidth(), target->getHeight());
2354 context.nearPlane = cd->nearZ;
2355 context.farPlane = cd->farZ;
2356 PrimitiveSceneCanvas3D primitives(context);
2357 gfx.getPrimitiveScene()->render(primitives);
2358 if (!primitives.commands().empty() || !primitives.triangles().empty()) gfx.drawPrimitiveScene(primitives);
2359 }
2360
2361 gfx.end3DFrameToCanvas();
2362}
2363
2364} // namespace eve::graphics
double z
double y
double m[16]
double x
LogicalId target
bool & active
float w
Definition AnimClip.cpp:738
EVEngine assertion entry point, backed by zeroerr.
#define EV_PARAM_CHECK(cond,...)
Validate a function parameter / public API precondition.
Definition Assert.h:30
std::string output
double volume
const std::string & s
int mask
float ao
int priority
bool applied
graphics::Texture * albedo
glm::vec4 p[6]
tensor::Graph g
Definition GpuGraph.cpp:7
std::vector< eve::ProcgenProbeDesc > lights
float camera[2]
glm::vec4 tint
float u
Definition Grass.cpp:233
glm::vec3 n
Definition Grass.cpp:63
double r
float v
HexVec3 up
HexVec3 right
std::int32_t c
std::int32_t first
int secondary
std::uint32_t height
std::uint32_t width
Range range
std::array< float, 3 > scale
ActionGuidePack pack
bool valid
MeleePoint3 b
Definition MeleeHit.cpp:41
double radius
Definition MeleeHit.cpp:42
MeleePoint3 a
Definition MeleeHit.cpp:40
float distance
float roughness
float tb
float tr
bool doubleSided
float tg
float metallic
int level
OceanGpuFrameToken token
OceanMeshSettings mesh
glm::dvec2 center
glm::dvec3 dx
glm::dvec3 dz
OceanSprayView view
std::shared_ptr< const OceanSprayFrame > previous
std::array< uint32_t, 16 > material
Texture * texture
TileLayer * layer
float f
std::shared_ptr< const std::vector< glm::vec2 > > points
std::weak_ptr< PrimitiveScene > scene
#define EV_PROFILE_MODULE(module, name)
Profile the enclosing scope, tagged with a module for grouping.
Definition Profile.h:158
float d
std::string slot
Local-probe upload record kept off the high-fanout IGraphics3D header.
uint32_t cascadeMask
bool lodFadeReverse
bool inView
glm::vec2 temporalMotion
glm::mat4 cullViewProj
RenderSystem3D::ShadowExtraDrawer drawer
float projectedDepth
bool clusteredUploaded
Whether the clustered SSBOs were uploaded for this camera this frame.
bool inDefaultView
Renderable3D::MeshRenderer * mr
glm::vec3 eye
RenderSystem3D::GpuOpaqueCollector collector
float fovRad
FrustumPlanes frustum
bool useReflectionProbes
float lodWeight
ClusteredLightingUpload clustered
int lightProbeUsage
int camIdx
bool receiveShadow
int sortPriority
glm::vec3 worldC
bool clusteredValid
bool speedTreeFade
bool xray
glm::mat4 viewProj
float worldR
Shader * shader
bool hair
Lighting3DPack lighting
bool shadowDoubleSided
SurfaceMode surfaceMode
float distSq
glm::mat4 model
bool shadowsOnly
glm::mat4 proj
int skinInfluenceLimit
bool isPoint
RoadLaneDirection direction
ScriptStructure out
std::string_view source
size_t end
std::size_t candidateCount
Definition Sensing.cpp:33
std::map< std::array< int, 4 >, std::vector< const Subject * > > candidates
Definition Sensing.cpp:32
float shadowStrength
Definition Shadow.cpp:154
Light3D::Data * light
Definition Shadow.cpp:147
float dy
Definition Shadow.cpp:151
float bias
Definition Shadow.cpp:149
int count
Structured operation status used by the common Result foundation.
int limit
Definition TreeMesh.cpp:166
V3 dir
Definition TreeMesh.cpp:151
std::uint32_t depth
const VegetationPresetContext & context
V forward
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
EVENGINE_API_FOUNDATION public API.
Definition Exception.h:13
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
RAII pass scope for C++ call sites.
Definition RenderTrace.h:90
Screen-space ambient occlusion.
void setQuality(const std::string &quality)
"low" | "medium" | "high" (unknown → medium).
Classic image-space anti-aliasing.
void setTemporalCamera(const glm::vec3 &eye, const glm::vec3 &target, float fovYDeg)
Detect camera cuts and invalidate incompatible temporal history.
glm::vec2 prepareTemporalJitter(int width, int height)
Return this frame's Halton projection jitter in NDC units.
glm::vec2 prepareTemporalObjectMotion(const void *objectKey, const glm::mat4 &model)
Per-object UV correction relative to static-world camera reprojection.
void setTemporalViewProjection(const glm::mat4 &viewProjection, float nearZ, float farZ)
Set the jittered camera matrix used for depth-based history reprojection.
EVENGINE_API_BACKENDS public API.
void setBloom(float intensity, float threshold=1.f)
Configure HDR bloom. Zero intensity disables it.
float getPixelsPerUnit()
Return configured pixels per world unit, or 0 when unset.
float getEyeX()
Camera eye position (world space).
void snapToPixelGrid(int viewWidth, int viewHeight)
Snap the eye onto the view-plane pixel grid for the current ortho / pixel sizing.
Result< void > setPixelOrthographic(float pixelsPerUnit, int viewWidth, int viewHeight, int refWidth=0, int refHeight=0)
One-shot perfect-pixel orthographic setup: store config then apply for this viewport.
float getDofFocusDistance()
Return DOF focus distance.
float getNearClip()
Return the positive near clipping distance.
float getDofFocusRange()
Return DOF focus range.
bool hasPixelConfig()
Return whether a pixels-per-unit config is stored.
void setShadowLayerCullDistance(int layer, float distance)
Set the shadow-caster cull distance for one render layer; zero disables it.
int getPixelScale()
Return the last integer upscale from applyPixelPerfect.
float getAperture()
Return physical-camera aperture.
void setDepthOfField(float focusDistance, float maxBlurPx, float focusRange=8.f)
Configure Gaussian depth-of-field on the final HDR resolve.
float getFocalLength()
Return physical-camera focal length in millimetres.
float getFov()
Vertical field of view in degrees.
void setLayerCullDistance(int layer, float distance)
Set the camera cull distance for one render layer; zero disables the override.
float getDofMaxBlur()
Return DOF max blur in texels (0 when disabled).
void setReflectionProbe(int slot, Texture *cubemap, float centerX, float centerY, float centerZ, float extentX, float extentY, float extentZ, float intensity=1.f, float blendDistance=1.f, int priority=0)
Configure one local reflection probe slot.
bool isAutoExposure()
Return whether automatic exposure is enabled.
float getBloomThreshold()
Return bloom threshold in linear HDR units.
void setPerspective()
Return to perspective projection, retaining the configured field of view.
bool isOrthographic()
Return whether the camera currently uses orthographic projection.
float getExposure()
Return exposure compensation in photographic stops.
void setUp(float x, float y, float z)
void setOrthographic(float height)
Enable a pure orthographic projection with the given vertical world-space span.
int getPixelRefWidth()
Return reference width, or 0 when unset.
void clearEnvProbe()
Disable box projection and return to an infinite-distance environment.
Result< void > applyPixelPerfect(int viewWidth, int viewHeight)
Enable pure orthographic projection sized for crisp pixels from the stored config.
Result< void > setPixelConfig(float pixelsPerUnit, int refWidth=0, int refHeight=0)
Store perfect-pixel sizing for pure orthographic projection.
float getOrthoHeight()
Return the vertical world-space span used by orthographic projection.
void clearReflectionProbe(int slot)
Disable one local reflection probe slot.
void setFov(float fovYDeg)
float getBloomIntensity()
Return bloom intensity.
void setPhysicalLens(float aperture, float focalLength)
Set positive physical-camera aperture and focal length metadata.
bool getPixelSnap()
Return whether pixel-grid snapping is enabled.
void screenToRay(float screenX, float screenY, float viewW, float viewH)
Build a world-space picking ray from a screen pixel. Stores origin (camera eye) and normalized direct...
void setExposure(float ev)
Set exposure compensation in photographic stops. Positive values brighten.
float getLayerCullDistance(int layer)
Return the camera cull-distance override for one render layer.
void setEnvIntensity(float intensity)
void setEnvProbe(float centerX, float centerY, float centerZ, float extentX, float extentY, float extentZ)
Enable box-projected IBL for the camera environment cubemap.
float getFarClip()
Return the far clipping distance.
void clearPixelConfig()
Clear pixel sizing so applyPixelPerfect / setPixelOrthographic require a fresh config.
void setAutoExposure(bool enabled, float minEV=-8.f, float maxEV=8.f)
Enable log-average automatic exposure and set its EV clamp range.
void setTarget(float x, float y, float z)
float getShadowLayerCullDistance(int layer)
Return the shadow-caster cull-distance override for one render layer.
void clearDepthOfField()
Disable depth-of-field while retaining the current focus settings.
void setPixelSnap(bool enabled)
Enable or disable snapping the eye onto the view-plane pixel grid.
void setAmbient(float r, float g, float b)
void setActive(bool active)
int getReflectionProbeCount()
Return the number of enabled local reflection probes.
void setEye(float x, float y, float z)
float getTargetX()
Look-at target (world space).
bool hasEnvProbe()
True when all three box-probe extents are positive.
void setEnvMap(Texture *cube)
Specular IBL cubemap (Graphics::newCubemap). nullptr disables IBL.
void setClipPlanes(float nearZ, float farZ)
Set positive near/far clipping distances; far is kept beyond near.
int getPixelRefHeight()
Return reference height, or 0 when unset.
Canvas public API.
Definition Canvas.h:17
virtual int getWidth() const =0
Returns the width.
virtual Texture * getTexture()=0
Sampleable color buffer; screen Canvas returns nullptr.
virtual int getHeight() const =0
Returns the height.
Screen-space contact shadows for the primary directional light.
void setInvViewProj(const glm::mat4 &invViewProj)
Sets the inv view proj.
void setQuality(const std::string &quality)
"low" | "medium" | "high" (unknown → medium).
void applyFromGBuffer(Graphics *gfx, Texture *hwDepth, Texture *worldNormal)
Darken the current target using contact shadows from GBuffer depth.
void setLightDirection(float x, float y, float z)
World-space direction toward the light (normalized on write). Matches Light3D directional convention ...
Cross-backend min/max hardware-depth pyramid packed into one texture atlas.
int getLevelCount() const
Number of valid levels in the last build.
Texture * build(Texture *depth, int maxLevels=8)
Build the min/max hierarchy from a hardware depth texture.
static DiffuseLightProbeRegistry & instance()
Return the process-wide graphics-owned registry.
Result< DiffuseLightProbeVolumeSample > selectVolume(const glm::vec3 &position) const
Select an object-local proxy volume; fragment shading performs the spatial interpolation.
Result< DiffuseLightProbeSample > sample(const glm::vec3 &position, int maxSamples) const
Blend up to maxSamples probes whose influence volumes contain position.
Screen-space buffers for mid/post effects and Hybrid deferred lighting.
Definition GBuffer.h:28
Texture * getAlbedoTexture() const
Returns the albedo texture.
Definition GBuffer.h:57
Texture * getNormalTexture() const
Returns the normal texture.
Definition GBuffer.h:55
Texture * getDepthTexture() const
Returns the depth texture.
Definition GBuffer.h:51
void clear()
Clears .
Definition GBuffer.cpp:43
Texture * getHwDepthTexture() const
Returns the hw depth texture.
Definition GBuffer.h:53
bool isValid() const
True when valid.
Definition GBuffer.cpp:5
Screen-space single-bounce GI (SSGI). @lifetime All texture arguments are borrowed for the duration o...
Canvas * getWorkingCanvas()
Returns the working canvas.
void setTemporalMotionTexture(Texture *motionDepth)
Set packed linear-depth and motion texture used by temporal GI resolve.
void applyFromSceneTo(Graphics *gfx, Texture *color, Texture *hwDepth, Canvas *dest)
Applies from scene to.
Texture * getWorkingTexture()
Temporally resolved GI texture, or the raw working texture before history exists. @lifetime Returned ...
void setQuality(const std::string &quality)
"low" | "medium" | "high" | "ultra" (unknown becomes medium).
std::string getQuality() const
Returns the quality.
void setDepthPyramid(Texture *atlas, int levels)
Set the shared horizontally packed RG min/max depth hierarchy.
void setWorldNormalTexture(Texture *worldNormal)
Set the GBuffer world-normal texture used for guided GI sampling.
void setAlbedoTexture(Texture *albedo)
Set receiver albedo used for energy-conserving diffuse GI response.
ScreenSpaceReflection * pipelineScreenSpaceReflection()
Pipeline screen space reflection.
virtual void beginShadowPass(int cascadeIndex)=0
Depth-only shadow pass for one cascade layer (0..2). Draws are recorded into the next begin3DFrame co...
virtual void setMesh3DEnvProbe(const glm::vec3 &center, const glm::vec3 &extent)=0
Box projection bounds for the active environment; zero extent disables it.
virtual void setMesh3DReflectionProbes(const ReflectionProbeUpload &upload)=0
Upload the two dominant local reflection probes for subsequent mesh draws.
virtual bool gpuDrivenSubmitOpaque(const GpuInstance *instances, uint32_t instanceCount)
Upload + record GPU-driven opaque draws (call inside the open 3D frame). The backend sorts instances ...
Definition Graphics.h:352
virtual std::string getBackendName() const =0
Renderer backend id used by sibling modules (e.g. Gpgpu).
int getPixelHeight() const
Returns the pixel height.
Definition Graphics.h:495
virtual bool gpuDrivenCullEnabled() const
True when the stage-2 GPU cull chain will run this frame.
Definition Graphics.h:375
virtual void setMesh3DShadows(const ShadowUpload &upload)=0
Upload CSM constants for subsequent default mesh draws (active=false disables).
virtual void endGBufferPass()=0
Ends g buffer pass.
virtual void setMesh3DClip(float nearZ, float farZ)=0
Near/far used to pack linear depth into scene color A (SSGI).
virtual void gpuDrivenOpenScenePass()
Open the scene color pass that begin3DFrame deferred (cull path).
Definition Graphics.h:398
virtual void setMesh3DMaterial(float metallic, float roughness)=0
Metallic (0..1) and roughness (0..1) for the next default mesh draw.
virtual bool gpuDrivenVgSetInstance(std::uint32_t vgAssetId, const glm::mat4 &model, std::uint32_t materialId)
Register one instance of a VG asset this frame (model + material). The first instance per asset wins;...
Definition Graphics.h:445
int getWidth() const
Returns the width.
Definition Graphics.h:489
virtual std::uint32_t gpuDrivenVgAssetId(Mesh *mesh) const
VG asset id attached to a mesh (kInvalidGpuDrivenSlot when none).
Definition Graphics.h:427
virtual void drawTexturedRectShaderUV(Texture *texture, Shader *shader, float x, float y, float w, float h, float u0, float v0, float u1, float v1, const Color &color, bool rotatedUV=false, BlendMode blend=BlendMode::Alpha)=0
UV draw with an explicit Shader (nullptr = default textured pipeline).
virtual void setMesh3DViewProj(const glm::mat4 &viewProj)=0
Sets the mesh 3 d view proj.
virtual void drawMeshShadow(Mesh *mesh, const glm::mat4 &lightMVP, bool doubleSided=true)=0
Queue an opaque shadow caster.
virtual void drawMeshShadowAlpha(Mesh *mesh, const glm::mat4 &lightMVP, Texture *albedo=nullptr, bool doubleSided=true, float lodWeight=1.f, bool lodFadeReverse=false, bool lodDither=false)=0
Shadow pass draw with alpha-cutout discard (card/billboard geometry such as sprite-stack slices): tra...
virtual Result< void > setMesh3DPbrSurface(const PbrSurface *surface)
Copy a validated extended surface for subsequent draws; null resets to legacy shading.
Definition Graphics.h:1253
virtual void setMesh3DCameraPos(const glm::vec3 &eye)=0
Camera eye used by mesh shaders that need view/rim (stored in Mesh3DUBO).
virtual uint32_t gpuDrivenMeshRecord(Mesh *mesh)
GPU mesh-table slot for a mesh (kInvalidGpuDrivenSlot when not uploaded).
Definition Graphics.h:296
eve::OptionalRef< IRayTracing > rayTracingService() const noexcept
Borrow the optional ray-tracing service resolved at graphics construction. @ownership Provider-owned;...
Definition Graphics.cpp:186
virtual void endShadowPass()=0
Ends shadow pass.
virtual void setMesh3DPackedNormalMask(bool enabled)=0
Interpret normal texture RG as tangent XY, B as AO and A as smoothness for terrain surfaces.
GlobalIllumination * pipelineGlobalIllumination()
Pipeline global illumination.
virtual void setMesh3DClusteredActive(bool active)=0
Cheap per-draw toggle for the already-uploaded clustered light table. Unlike setMesh3DClusteredLighti...
virtual void begin3DFrameToCanvas(Canvas *canvas)=0
Open a 3D render pass targeting an offscreen Canvas (color + depth) at the canvas size....
virtual void setMesh3DEnv(Texture *cube, float intensity)=0
Specular IBL environment for subsequent default mesh draws. cube must be from newCubemap (or nullptr ...
virtual bool gpuDrivenMaterialUsable(Material *material)
Whether a material can be shaded by the GPU-driven opaque path. Backends/drivers with descriptor-inde...
Definition Graphics.h:326
virtual void setMesh3DTexCellBomb(float cellScale, float strength, float rotAmount=1.f)=0
Texture cell bombing for the next default mesh draw (breaks tiling). cellScale: cells per UV unit (ty...
virtual void beginDecalPass(int width, int height)=0
Open the decal pass (reads G-buffer hwDepth + normal, writes the screen-space DecalLayer targets)....
virtual Canvas * getCanvas() const =0
Returns the canvas.
virtual void setSceneExposure(float exposure)=0
Set linear exposure multiplier used by the final scene tone-map resolve.
virtual void beginGBufferPass(int width, int height)=0
Depth/normal(/albedo) fill pass for mid/post effects. One-shot submit (like shadow); call before begi...
virtual void setMesh3DClusteredLighting(const ClusteredLightingUpload &upload)=0
Enable clustered forward path for subsequent default mesh draws (SSBO light lists)....
virtual void setMesh3DParallax(float scale, float minLayers=8.f, float maxLayers=32.f)=0
Parallax occlusion mapping for the next default mesh draw. scale: UV displacement strength (0=off)....
virtual void setSceneBloom(float intensity, float threshold)=0
Configure final HDR bloom intensity and linear threshold.
Outline * pipelineOutline()
Pipeline-owned Outline used by RenderSystem3D when the "outline" feature is on.
std::shared_ptr< PrimitiveScene > getPrimitiveScene() const noexcept
Returns the authoritative persistent spatial-primitive scene.
Definition Graphics.h:508
virtual void setMesh3DView(const glm::mat4 &view)=0
Camera view matrix for subsequent drawMesh (view-space depth / CSM select).
virtual Result< void > drawMeshInstances(Mesh &mesh, std::span< const glm::mat4 > models, OptionalRef< Texture > texture, const Color &tint)
Draw a batch of static meshes using the current ordinary material and lighting bindings.
Definition Graphics.h:1151
virtual bool gpuDrivenScenePassPending() const
Scene pass opening deferred until after the compute cull section.
Definition Graphics.h:378
virtual void gpuDrivenResolve()
Record the fullscreen vis resolve inside the open scene color pass.
Definition Graphics.h:414
virtual void setCanvas(Canvas *canvas)=0
nullptr or this → screen. Switching flushes pending draws to the previous target.
bool had3DThisFrame() const
Had 3 d this frame.
Definition Graphics.h:1552
virtual Result< void > drawMeshShaderInstances(Mesh &mesh, Shader &shader, const glm::mat4 &model, const Color &tint, std::uint32_t first, std::uint32_t count)
Draw a checked range from a resource shader's immutable instance matrix buffer. @ownership Mesh and S...
Definition Graphics.h:1175
virtual void setDecalCamera(const glm::mat4 &viewProj, float nearZ, float farZ)=0
Per-frame camera constants for the decal pass (world-space reconstruction from the G-buffer depth)....
virtual void setMesh3DSurface(SurfaceMode mode, BlendMode blend, bool depthWrite, bool doubleSided, float alphaCutoff, const std::string &alphaTechnique="cutoff")=0
Select pipeline state for subsequent mesh draws.
virtual void setSceneAutoExposure(bool enabled, float minEV, float maxEV)=0
Configure log-average scene auto exposure and its EV clamp range.
ContactShadow * pipelineContactShadow()
Pipeline contact shadow.
AntiAliasing * pipelineAntiAliasing()
Pipeline anti aliasing.
virtual void setMesh3DSceneDepth(Texture *depth)=0
Optional scene hardware depth (G-buffer hwDepth, Vulkan NDC z) bound to mesh3d shader binding 7....
AmbientOcclusion * pipelineAmbientOcclusion()
Pipeline-owned AO / GI / AA used by RenderSystem3D when features "ao" / "gi" / "aa" are enabled....
virtual void gpuDrivenSetEnabled(bool enabled)
Enable/disable the GPU-driven opaque path (no-op when unsupported).
Definition Graphics.h:293
virtual void drawMeshGBufferAlpha(Mesh *mesh, const glm::mat4 &mvp, const glm::mat4 &model, float nearZ, float farZ, Texture *albedo=nullptr, float tintR=1.f, float tintG=1.f, float tintB=1.f, float motionX=0.f, float motionY=0.f, float roughness=0.45f, float metallic=0.f, float tintA=1.f)=0
GBuffer fill with alpha-cutout discard (card/billboard geometry such as sprite-stack slices): same ou...
virtual uint32_t gpuDrivenMaterialRecord(Material *material)
GPU material-table slot for a material (lazily created).
Definition Graphics.h:302
virtual void setMesh3DSkinInfluenceLimit(SkinInfluenceLimit count)=0
Limit GPU skinning to the strongest one, two or four vertex influences.
virtual bool gpuDrivenResolveWanted() const
True when the stage-3 vis+resolve path should run this frame.
Definition Graphics.h:408
virtual void gpuDrivenRecordVisPass()
Record the GBuffer vis pass (opaque indirect draws write visID/visBary).
Definition Graphics.h:411
virtual void setMesh3DShadowReceive(bool receive)=0
Per-draw: when false, shadow sampling is forced off for the next mesh draw.
virtual bool supportsGBufferPost() const
Whether gbuffer-based post-process shaders (AO, GI) can be created on this backend....
Definition Graphics.h:260
virtual void begin3DFrame()=0
Begin a 3D frame: shadow/gbuffer (if pending) then a sampleable scene color pass (color+depth)....
void setFinalSceneTexture(Texture *texture)
Override the HDR source consumed by the next backend scene resolve.
Definition Graphics.h:2147
virtual bool supportsGpuDriven3D() const
True when the backend can run GPU-driven opaque draws.
Definition Graphics.h:277
virtual uint32_t gpuDrivenReflectionProbeSlot(Texture *cubemap)
Return/register a bindless cubemap slot for a GPU-driven local probe.
Definition Graphics.h:332
virtual void drawMeshGBuffer(Mesh *mesh, const glm::mat4 &mvp, const glm::mat4 &model, float nearZ, float farZ, Texture *albedo=nullptr, float tintR=1.f, float tintG=1.f, float tintB=1.f, float motionX=0.f, float motionY=0.f, float roughness=0.45f, float metallic=0.f, float tintA=1.f)=0
Queue a GBuffer surface using the currently bound PBR material when present.
DepthPyramid * pipelineDepthPyramid()
Pipeline-owned shared min/max depth hierarchy for screen-space effects. @lifetime Returned effect rem...
virtual void gpuDrivenCullEmit(const glm::mat4 &viewProj, const glm::vec3 &eye, float fovYDeg, float nearZ, float farZ)
Record the cull + emit compute dispatches for the current frame.
Definition Graphics.h:388
virtual void gpuDrivenDrawOpaque()
Draw the opaque geometry with GPU-written indirect commands.
Definition Graphics.h:401
virtual Texture * getSceneColorTexture()
Sampleable 3D color target for the current frame (RGB = lit, A = linear depth). Valid after begin3DFr...
Definition Graphics.h:1075
virtual void drawMeshShader(Mesh *mesh, const glm::mat4 &model, Texture *texture, const Color &tint, Shader *shader)=0
Draw mesh with an explicit Mesh3D Shader (nullptr = default PBR pipeline).
RenderControl * getRenderControl()
Shared compilable 3D render control (features → pass list + GBuffer). Owned by Graphics; valid for th...
Definition Graphics.cpp:279
virtual void setSceneDepthOfField(float focusDistance, float maxBlurPx, float focusRange, float nearZ, float farZ)=0
Configure final-scene Gaussian depth-of-field.
virtual void gpuDrivenVgComputeSection(const glm::mat4 &viewProj, const glm::vec3 &eye, float fovYDeg, float nearZ, float farZ)
Record the HZB build + cull-params section (VG-only frames).
Definition Graphics.h:454
virtual void endDecalPass()=0
Ends decal pass.
virtual void end3DFrameToCanvas()=0
Ends 3 d frame to canvas.
virtual void drawDeferredLighting()
Fullscreen deferred lighting into the open scene-color pass. Samples GBuffer + clustered lights + CSM...
Definition Graphics.h:274
virtual bool supportsMeshInstancing() const
Whether the initialized backend can instance ordinary opaque meshes without bindless textures....
Definition Graphics.h:1136
int getPixelWidth() const
Returns the pixel width.
Definition Graphics.h:493
virtual bool supportsDecal() const
True when the backend can render the screen-space decal layer (box-projected decals writing albedo/no...
Definition Graphics.h:1335
int getHeight() const
Returns the height.
Definition Graphics.h:491
Canvas * pipelineReflectionComposite(int width, int height)
Return a reusable HDR target for composing screen-space lighting. @lifetime Returned canvas is Graphi...
virtual void setMesh3DNormalTexture(Texture *normal)=0
Optional normal map for the next drawMesh / drawMeshShader (nullptr = flat).
virtual bool gpuDrivenCullBegin(const GpuInstance *instances, uint32_t instanceCount)
Upload sorted instances + bucket metadata for the cull chain.
Definition Graphics.h:381
virtual void setMesh3DHeightTexture(Texture *height)=0
Optional height map for parallax (R channel; nullptr = flat / off).
virtual void setMesh3DLighting(const Lighting3DPack &pack)=0
Per-frame ambient + up to 8 lights packed into Mesh3DUBO.
virtual void drawPrimitiveScene(const PrimitiveSceneCanvas3D &canvas)=0
Submits an owning frame-local primitive canvas into the active 3D pass.
Packages shading method + surface parameters into one attachable asset.
Definition Material.h:38
float getParallaxScale() const
Returns the parallax scale.
Definition Material.h:265
bool hasPbrSurface() const
Whether full PBR texture/extension rendering is requested.
Definition Material.h:67
Texture * getAlbedoTexture() const
Get the borrowed material texture. @ownership Graphics factory owns the resource. @lifetime Keep aliv...
Definition Material.h:128
float getTexCellBombStrength() const
Returns the tex cell bomb strength.
Definition Material.h:258
float getTintR() const
Returns the tint r.
Definition Material.h:235
bool getReceiveShadow() const
Returns the receive shadow.
Definition Material.h:284
bool isTransparentHair() const
True when this material should go through the hair transparent pass.
Definition Material.cpp:219
float getTintA() const
Returns the tint a.
Definition Material.h:241
bool getDoubleSided() const
Returns the double sided.
Definition Material.h:344
std::string getShadingModel() const
Returns the shading model.
Definition Material.h:53
float getTintB() const
Returns the tint b.
Definition Material.h:239
Result< void > bind(Graphics &gfx) const
Push this material onto Graphics mesh3d state for the next draw. Does not issue the draw itself....
Definition Material.cpp:328
bool getCastShadow() const
Returns the cast shadow.
Definition Material.h:279
float getTintG() const
Returns the tint g.
Definition Material.h:237
bool getReceiveLight() const
Returns the receive light.
Definition Material.h:274
Shader * effectiveShader() const
Return the borrowed effective shader, or nullptr for the default PBR pipeline. @lifetime The pointer ...
Definition Material.cpp:214
Texture * getHeightTexture() const
Returns the height texture.
Definition Material.h:182
GPU mesh handle (+ optional CPU morph targets).
Definition Mesh.h:26
float boundsCx
Model-space bounding sphere used for view/cascade frustum culling. Computed from vertex positions at ...
Definition Mesh.h:60
bool hasBounds() const
True when a valid bounding sphere is available for culling.
Definition Mesh.h:66
float boundsRadius
Definition Mesh.h:63
Screen-space model outline (t3ssel8r-style), computed from the GBuffer hardware depth + world-normal ...
Definition Outline.h:33
void setClip(float nearZ, float farZ)
Near/far used to linearize the hardware depth.
Definition Outline.cpp:110
bool apply(Graphics *gfx, Texture *hwDepth, Texture *worldNormal)
Draw the outline over the currently bound canvas / screen. hwDepth is the D32 GBuffer (Vulkan NDC z),...
Definition Outline.cpp:147
Frame-local scene recorder for 3D line primitives.
const std::vector< TriangleCommand3D > & triangles() const noexcept
Triangles.
const std::vector< PolylineCommand3D > & commands() const noexcept
Commands.
Declarative, compilable 3D render control.
void ensureCompiled()
Ensure compiled; no-op when already clean.
AutoInstancingPath autoInstancingPath() const
Return the automatic instancing selection; render-thread affine, no callbacks.
std::string getReflectionQuality() const
Return the shared TAA/RTGI/SSR quality preset.
std::string getPostProcessQuality() const
Return the unified post-process quality for TAA, RTGI and SSR.
bool isEnabled(const std::string &feature) const
True when enabled.
GBuffer * getGBuffer()
Returns the g buffer.
bool hasPass(const std::string &name) const
True when pass.
bool isPathTracingRequested() const
True when the pathTracing feature is requested; render-thread query.
static void setDirectionalLight(float dx, float dy, float dz, float r, float g, float b)
Legacy single directional light used when no enabled Light3D exists.
static void renderWithShadowsToCanvas(Graphics &gfx, Canvas &target, Camera3D &camera)
Render an editor preview with directional cascaded shadows before forward shading....
static void removeShadowExtraDrawer(uint64_t token)
Remove one shadow callback before destroying its captured state.
static void removeForwardExtraDrawer(uint64_t token)
Unregister a main forward-pass contributor.
static void addDecalExtraDrawer(DecalExtraDrawer drawer)
Adds decal extra drawer.
std::function< void(Graphics &gfx, const Camera3D::Data &cam, const glm::mat4 &viewProj, float aspect, std::vector< GpuInstance > &instances)> GpuOpaqueCollector
Collect non-ECS geometry for the normal GPU-driven opaque submission.
static uint64_t addShadowExtraDrawer(ShadowExtraDrawer drawer)
Adds shadow extra drawer.
static void removeCaptureExtraDrawer(uint64_t token)
Unregister an offscreen capture contributor.
static void addGBufferExtraDrawer(GBufferExtraDrawer drawer)
Adds g buffer extra drawer.
static uint64_t addCaptureExtraDrawer(uint32_t reflectionCaptureMask, CaptureExtraDrawer drawer)
Register custom forward geometry for offscreen captures.
static void renderToCanvas(Graphics &gfx, Canvas *target, Camera3D *camera, uint32_t reflectionCaptureMask=0xffffffffu, float lodDistanceScale=1.f, bool includeTransparent=true, bool useClusteredLighting=true, Texture *skyFaceTexture=nullptr, Mesh *skyQuad=nullptr, float skyFaceTextureScale=1.f, bool includePrimitives=false)
Forward 3D pass into an offscreen canvas using multipart materials, LOD, masked surfaces and sorted t...
static void render(Graphics &gfx)
Renders .
static uint64_t addForwardExtraDrawer(ForwardExtraDrawer drawer)
Register a main forward-pass contributor.
std::function< void(Graphics &gfx, const Camera3D::Data &cam, const glm::mat4 &viewProj, float aspect, uint32_t reflectionCaptureMask)> CaptureExtraDrawer
Draw custom forward geometry into reflection-probe and preview captures.
std::function< void(Graphics &gfx, const glm::mat4 &lightVP, const Camera3D::Data &cam)> ShadowExtraDrawer
Register a callback that casts shadows for geometry outside the Renderable3D ECS (e....
std::function< void(Graphics &gfx, const Camera3D::Data &cam, const glm::mat4 &viewProj, float aspect)> ForwardExtraDrawer
Draw custom opaque geometry after the main scene pass is open. @thread Register, unregister and invok...
static void removeGpuOpaqueCollector(uint64_t token)
Unregister a GPU-driven opaque contributor.
static uint64_t addGpuOpaqueCollector(GpuOpaqueCollector collector)
Register a GPU-driven opaque contributor.
std::function< void(Graphics &gfx, const Camera3D::Data &cam, const glm::mat4 &viewProj, float aspect)> DecalExtraDrawer
Register a callback that draws screen-space decals (box-projected volumes writing the DecalLayer) aft...
std::function< void(Graphics &gfx, const Camera3D::Data &cam, const glm::mat4 &viewProj, float aspect)> GBufferExtraDrawer
Register a callback that fills the G-buffer (depth/normal/albedo) for geometry outside the Renderable...
EVENGINE_API_BACKENDS public API.
Screen-space reflections (SSR) as a fullscreen post pass. @lifetime All Graphics and texture argument...
std::string getQuality() const
Return the active SSR quality preset.
void applyFromSceneTo(Graphics *gfx, Texture *sceneColor, Texture *hwDepth, Texture *worldNormal, Canvas *dest)
Write the SSR result into the currently bound canvas / dest.
void setQuality(const std::string &quality)
Set "low", "medium", "high" or "ultra" SSR quality preset.
Texture * getReflectionTexture()
The reflection texture from the owned canvas, or nullptr before first apply.
void setEnabled(bool enabled)
Enable/disable the pass. When disabled it emits transparent (0 hit).
Canvas * getReflectionCanvas()
Owned reflection canvas (created on first use at the current target size).
void setDepthPyramid(Texture *atlas, int levels)
Set the shared horizontally packed RG min/max depth hierarchy.
void setTemporalMotionTexture(Texture *motionDepth)
Set packed linear-depth and motion texture used by temporal SSR resolve.
Custom GPU program.
Definition Shader.h:41
GPU texture created via Graphics::newTexture. Owns GPU resources through an opaque backend handle.
Definition Texture.h:15
void rtBind(const char *kind, const char *name)
Rt bind.
Definition RenderTrace.h:69
void rtPassBegin(const char *name)
Rt pass begin.
Definition RenderTrace.h:57
void rtFrameBegin()
Rt frame begin.
Definition RenderTrace.h:49
void rtDraw(const char *api, const char *detail=nullptr)
Rt draw.
Definition RenderTrace.h:73
void rtPassEnd(const char *name)
Rt pass end.
Definition RenderTrace.h:61
EVENGINE_API_BACKENDS Result< void > prepareViewResources(Graphics &graphics, const glm::mat4 &viewProjection, const glm::vec3 &eye)
Dispatch preparers before opening the destination; no callbacks means success. @thread Graphics threa...
Result< void > validateInstancedRenderable(const Renderable3D::MeshRenderer &mr)
Validate instanced renderable.
glm::mat4 modelFromTransform(const Renderable3D::Transform3D &t)
Resolve the value-owned scene world matrix or the local TRS on the render thread.
float sphereStretch(const Renderable3D::Transform3D &t)
Conservative sphere stretch; preserves culling under scene-parent shear.
卡牌游戏 UI 工具模块:工厂 + 脚本绑定入口。 功能参考 ycarowr/UiCard:扇形手牌布局、抽牌/洗牌、悬浮放大、拖拽到落牌区、 敌方手牌(背面/偷看)、费用不足置灰,以及可实时调节的布局...
Definition Animation.h:25
bool meshInstanceRangeVisible(const MeshInstanceRange &range, const glm::mat4 &model, const glm::mat4 &vp, const glm::vec3 &eye)
Test transformed bounds against Vulkan clip planes and horizontal distance.
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
ClusteredLightingUpload buildClusteredLighting(const std::vector< ClusteredLightGpu > &points, const std::vector< ClusteredLightGpu > &dirs, const glm::mat4 &view, float nearZ, float farZ, int screenW, int screenH, float fovYRad, const glm::vec4 &ambient)
Build clustered tables for point lights in view space.
SurfaceMode
How a 3D surface contributes to depth and color passes.
Definition SurfaceMode.h:6
glm::mat4 cameraProjectionVulkanRH_ZO(bool orthographic, float fovyRad, float orthoHeight, float aspect, float zNear, float zFar)
Camera projection shared by rendering, picking, and diagnostic passes.
Definition ClipSpace.h:38
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
eve::Color Color
RGBA color used by every graphics draw call. Lives inside eve::graphics so including a graphics heade...
Definition Color.h:13
Light3DGpu ClusteredLightGpu
void lightSpotCosines(float angleDeg, float softness, float &cosOuter, float &cosInner)
Convert spot angle/softness into GPU cosines (outer < inner). Shared by Light2D and Light3D flashligh...
Definition Light.h:27
constexpr uint32_t kInvalidGpuDrivenSlot
GPU-driven API surface without GLM layout records.
SkinInfluenceLimit
Number of strongest vertex influences retained by GPU skinning.
Definition IGraphics3D.h:20
PixelPerfectScale computePixelPerfectScale(float pixelsPerUnit, int refWidth, int refHeight, int viewWidth, int viewHeight)
Compute integer scale and projection spans for a perfect-pixel camera.
Definition CameraPixel.h:31
Result< PathSceneToken > preparePathWorld(ecs::Table &world, Graphics &graphics, IRayTracing &provider)
Prepare an unculled path scene from the supplied ECS world.
double sample(const Heightmap &map, double u, double v)
Sample.
V3 normalize(V3 a)
Module-private road bake implementation helper.
Definition RoadBake.cpp:31
std::optional< std::reference_wrapper< T > > OptionalRef
Optional borrowed reference; it does not extend T's lifetime.
Definition BorrowedRef.h:24
bool enabled
std::array< float, 32 > shadowLayerCullDistances
static constexpr int kMaxReflectionProbes
CPU-built clustered lighting upload for one frame/camera. Point lights are clustered; directional lig...
Per-instance GPU record (std430). Mirrors GLSL GpuInstance.
GPU light packing for mesh3d / PBR (std140-friendly).
Definition Light.h:160
Data public API.
Definition Light.h:199
Lighting3DPack public API.
Definition Light.h:171
static constexpr int kMaxLights
Definition Light.h:172
std::array< glm::vec4, 9 > diffuseProbeSh
Definition Light.h:176
One allocated local (spot/point-face) shadow slot for the frame. @ownership Ephemeral CPU descriptor;...
One mesh + material slot on a multi-part model (Assimp mesh / body region). When Material* is null,...
Definition Material.h:404
Deterministic path sample batch. Zero history starts a new accumulation.
ReflectionProbeUpload public API.
Immutable camera and viewport facts used to resolve one 3D draw list. Projection uses the engine's RH...
static constexpr int kLocalSlots
Extra depth-array layers for spot (perspective) local shadows.
Definition Shadow.h:26
static constexpr int kCascades
Definition Shadow.h:24
Camera context used to score local shadow candidates for atlas paging. @ownership Ephemeral; valid on...
static ShadowSchemeSettings & current()
Borrow the process-wide settings object.
Definition Shadow.cpp:216
ShadowUpload public API.
Definition Shadow.h:62
glm::vec4 lightDir
glm::uvec4 counts