载入中...
搜索中...
未找到
ReflectionProbeCapture.cpp
浏览该文件的文档.
2#include <algorithm>
3#include <array>
4#include <cmath>
5#include <limits>
6#include "graphics/Canvas.h"
7#include "graphics/Graphics.h"
8#include "graphics/Mesh.h"
11
12// ReflectionProbeCapture.cpp
13namespace eve::graphics {
14
16
18 const auto registries = registries_;
20 if (registry) registry->remove(this);
21}
22
23void ReflectionProbeCapture::attachRegistry(ReflectionProbeRegistry *registry) {
24 if (!registry || std::find(registries_.begin(), registries_.end(), registry) != registries_.end()) return;
25 registries_.push_back(registry);
26}
27
28void ReflectionProbeCapture::detachRegistry(ReflectionProbeRegistry *registry) {
29 registries_.erase(std::remove(registries_.begin(), registries_.end(), registry), registries_.end());
30}
31
32void ReflectionProbeCapture::configure(float x, float y, float z, int resolution, float nearZ, float farZ) {
33 const int clampedResolution = std::clamp(resolution, 16, 2048);
34 const float clampedNear = std::max(nearZ, 0.001f);
35 const float clampedFar = std::max(farZ, clampedNear + 0.01f);
36 const bool changed = x != centerX_ || y != centerY_ || z != centerZ_ || clampedResolution != resolution_ ||
37 clampedNear != nearZ_ || clampedFar != farZ_;
38 centerX_ = x;
39 centerY_ = y;
40 centerZ_ = z;
41 resolution_ = clampedResolution;
42 nearZ_ = clampedNear;
43 farZ_ = clampedFar;
45}
46
48 nextFace_ = 0;
49 pending_ = true;
50 recaptureAfterPublish_ = false;
51 captureSkyR_ = skyR_;
52 captureSkyG_ = skyG_;
53 captureSkyB_ = skyB_;
54 captureSkyFaceTextures_ = skyFaceTextures_;
55 captureSkyFaceTextureScales_ = skyFaceTextureScales_;
56 captureSkyIntensity_ = skyIntensity_;
57 captureEnvironmentLighting_ = environmentLighting_;
58 captureEnvironmentLightingIntensity_ = environmentLightingIntensity_;
59 captureLodDistanceScale_ = lodDistanceScale_;
60 snapshotCaptureTransparent_ = captureTransparent_;
61 snapshotCaptureClusteredLighting_ = captureClusteredLighting_;
62 if (camera_) {
63 camera_->setEnvMap(captureEnvironmentLighting_);
64 camera_->setEnvIntensity(captureEnvironmentLightingIntensity_);
65 }
66}
67
68void ReflectionProbeCapture::requestCaptureAfterPublish() {
69 if (pending_ && nextFace_ == 0) {
71 return;
72 }
73 if (pending_ || publishedRevision_ != revision_) {
74 recaptureAfterPublish_ = true;
75 return;
76 }
78}
79
80void ReflectionProbeCapture::queueCapture() { requestCaptureAfterPublish(); }
81
82void ReflectionProbeCapture::ensureResources() {
83 if (!gfx_) return;
84 if (!camera_) {
85 camera_ = Camera3D::createCamera();
86 camera_->setActive(false);
87 camera_->setFov(90.f);
88 camera_->setAmbient(0.f, 0.f, 0.f);
89 camera_->setEnvMap(captureEnvironmentLighting_);
90 camera_->setEnvIntensity(captureEnvironmentLightingIntensity_);
91 camera_->setAutoExposure(false);
92 camera_->setExposure(0.f);
93 camera_->setBloom(0.f, 1.f);
94 camera_->clearEnvProbe();
95 for (int i = 0; i < Camera3D::Data::kMaxReflectionProbes; ++i) camera_->clearReflectionProbe(i);
96 }
97 if (!skyQuad_) {
98 static constexpr float positions[] = {
99 -1.f, -1.f, 0.f, 1.f, -1.f, 0.f, 1.f, 1.f, 0.f, -1.f, 1.f, 0.f,
100 };
101 static constexpr float normals[] = {
102 0.f, 0.f, 1.f, 0.f, 0.f, 1.f, 0.f, 0.f, 1.f, 0.f, 0.f, 1.f,
103 };
104 static constexpr float uvs[] = {0.f, 1.f, 1.f, 1.f, 1.f, 0.f, 0.f, 0.f};
105 static constexpr uint32_t indices[] = {0, 1, 2, 0, 2, 3};
106 skyQuad_ = gfx_->newMeshFromArrays(positions, normals, uvs, 4, indices, 6);
107 }
108 if (allocatedResolution_ == resolution_ && faces_[0]) return;
109 for (Canvas *&face : faces_) face = gfx_->newHDRCanvas(resolution_, resolution_);
110 allocatedResolution_ = resolution_;
111}
112
113void ReflectionProbeCapture::captureFace(int face) {
114 static constexpr std::array<std::array<float, 3>, 6> directions{{
115 {{1.f, 0.f, 0.f}},
116 {{-1.f, 0.f, 0.f}},
117 {{0.f, 1.f, 0.f}},
118 {{0.f, -1.f, 0.f}},
119 {{0.f, 0.f, 1.f}},
120 {{0.f, 0.f, -1.f}},
121 }};
122 static constexpr std::array<std::array<float, 3>, 6> ups{{
123 {{0.f, -1.f, 0.f}},
124 {{0.f, -1.f, 0.f}},
125 {{0.f, 0.f, 1.f}},
126 {{0.f, 0.f, -1.f}},
127 {{0.f, -1.f, 0.f}},
128 {{0.f, -1.f, 0.f}},
129 }};
130 const auto &direction = directions[static_cast<size_t>(face)];
131 const auto &up = ups[static_cast<size_t>(face)];
132 camera_->setEye(centerX_, centerY_, centerZ_);
133 camera_->setTarget(centerX_ + direction[0], centerY_ + direction[1], centerZ_ + direction[2]);
134 camera_->setUp(up[0], up[1], up[2]);
135 auto data = camera_->data();
136 data->nearZ = nearZ_;
137 data->farZ = farZ_;
138 faces_[static_cast<size_t>(face)]->clear(Color(captureSkyR_[static_cast<size_t>(face)] * captureSkyIntensity_,
139 captureSkyG_[static_cast<size_t>(face)] * captureSkyIntensity_,
140 captureSkyB_[static_cast<size_t>(face)] * captureSkyIntensity_, 1.f),
141 std::nullopt, 1.0);
142 RenderSystem3D::renderToCanvas(*gfx_, faces_[static_cast<size_t>(face)], camera_, captureMask_,
143 captureLodDistanceScale_, snapshotCaptureTransparent_,
144 snapshotCaptureClusteredLighting_,
145 captureSkyFaceTextures_[static_cast<size_t>(face)], skyQuad_,
146 captureSkyFaceTextureScales_[static_cast<size_t>(face)]);
147}
148
149bool ReflectionProbeCapture::update(int faceBudget) {
150 lastCapturedFaceCount_ = 0;
151 if (!pending_ || !gfx_) return isCaptureComplete();
152 ensureResources();
153 const int budget = std::clamp(faceBudget, 1, 6);
154 float capturedGpuDurationMs = 0.f;
155 for (int captured = 0; captured < budget && nextFace_ < 6; ++captured) {
156 captureFace(nextFace_++);
157 capturedGpuDurationMs += gfx_->getLastOffscreen3DGpuDurationMs();
158 ++lastCapturedFaceCount_;
159 ++totalCapturedFaceCount_;
160 }
161 reportGpuDurationMs(capturedGpuDurationMs);
162 if (nextFace_ >= 6) {
163 pending_ = false;
164 ++revision_;
165 }
166 return isCaptureComplete();
167}
168
170 if (face < 0 || face >= 6) return nullptr;
171 return faces_[static_cast<size_t>(face)];
172}
173
175 if (!gfx_ || !isCaptureComplete()) return false;
176 if (stagedRevision_ == revision_ && stagingCubemap_) return true;
177 if (!stagingCubemap_ || stagingResolution_ != resolution_) {
178 stagingCubemap_ = gfx_->newHDRCubemap(resolution_);
179 stagingResolution_ = stagingCubemap_ ? resolution_ : 0;
180 }
181 if (!stagingCubemap_) return false;
182 if (!gfx_->copyHDRCanvasesToCubemap(faces_.data(), static_cast<int>(faces_.size()), stagingCubemap_)) return false;
184 stagedRevision_ = revision_;
185 return true;
186}
187
189 if (!gfx_ || !stagingCubemap_ || stagedRevision_ != revision_) return false;
190 if (!gfx_->filterHDRReflectionCubemap(stagingCubemap_, sampleCount)) return false;
192 lastFilterSampleCount_ = std::clamp(sampleCount, 8, 512);
193 Texture *previousActive = activeCubemap_;
194 const int previousResolution = activeResolution_;
195 activeCubemap_ = stagingCubemap_;
196 activeResolution_ = resolution_;
197 publishedRevision_ = stagedRevision_;
198 stagingCubemap_ = previousResolution == resolution_ ? previousActive : nullptr;
199 stagingResolution_ = stagingCubemap_ ? resolution_ : 0;
200 framesSincePublish_ = 0;
201 return true;
202}
203
204void ReflectionProbeCapture::setUpdateMode(const std::string &mode) {
205 if (mode == "static")
206 updateMode_ = UpdateMode::Static;
207 else if (mode == "realtime")
208 updateMode_ = UpdateMode::Realtime;
209 else if (mode == "time_sliced" || mode == "timesliced")
210 updateMode_ = UpdateMode::TimeSliced;
211 else
212 updateMode_ = UpdateMode::OnDemand;
213}
214
216 switch (updateMode_) {
217 case UpdateMode::Static: return "static";
218 case UpdateMode::Realtime: return "realtime";
219 case UpdateMode::TimeSliced: return "time_sliced";
220 case UpdateMode::OnDemand: return "on_demand";
221 }
222 return "on_demand";
223}
224
225void ReflectionProbeCapture::setRefreshInterval(int frames) { refreshInterval_ = std::clamp(frames, 1, 36000); }
226
228 const uint32_t nextMask = static_cast<uint32_t>(mask);
229 if (nextMask == captureMask_) return;
230 captureMask_ = nextMask;
232}
233
234void ReflectionProbeCapture::setEnvironmentLighting(Texture *environment, float intensity) {
235 const float nextIntensity = std::max(intensity, 0.f);
236 if (environment == environmentLighting_ && nextIntensity == environmentLightingIntensity_) return;
237 environmentLighting_ = environment;
238 environmentLightingIntensity_ = nextIntensity;
239 requestCaptureAfterPublish();
240}
241
242void ReflectionProbeCapture::setSkyColor(float r, float g, float b, float intensity) {
243 const float nextR = std::max(r, 0.f);
244 const float nextG = std::max(g, 0.f);
245 const float nextB = std::max(b, 0.f);
246 const float nextIntensity = std::max(intensity, 0.f);
247 bool changed = nextIntensity != skyIntensity_;
248 for (size_t face = 0; face < 6; ++face) {
249 changed = changed || skyR_[face] != nextR || skyG_[face] != nextG || skyB_[face] != nextB;
250 skyR_[face] = nextR;
251 skyG_[face] = nextG;
252 skyB_[face] = nextB;
253 }
254 skyIntensity_ = nextIntensity;
255 if (changed) requestCaptureAfterPublish();
256}
257
258void ReflectionProbeCapture::setSkyFaceColor(int face, float r, float g, float b) {
259 if (face < 0 || face >= 6) return;
260 const size_t index = static_cast<size_t>(face);
261 const float nextR = std::max(r, 0.f);
262 const float nextG = std::max(g, 0.f);
263 const float nextB = std::max(b, 0.f);
264 if (skyR_[index] == nextR && skyG_[index] == nextG && skyB_[index] == nextB) return;
265 skyR_[index] = nextR;
266 skyG_[index] = nextG;
267 skyB_[index] = nextB;
268 requestCaptureAfterPublish();
269}
270
272 if (face < 0 || face >= 6) return;
273 const size_t index = static_cast<size_t>(face);
274 if (skyFaceTextures_[index] == texture) return;
275 skyFaceTextures_[index] = texture;
276 requestCaptureAfterPublish();
277}
278
280 if (face < 0 || face >= 6) return nullptr;
281 return skyFaceTextures_[static_cast<size_t>(face)];
282}
283
285 if (face < 0 || face >= 6) return;
286 const size_t index = static_cast<size_t>(face);
287 const float nextScale = std::clamp(scale, 0.f, 64.f);
288 if (skyFaceTextureScales_[index] == nextScale) return;
289 skyFaceTextureScales_[index] = nextScale;
290 requestCaptureAfterPublish();
291}
292
294 if (face < 0 || face >= 6) return 1.f;
295 return skyFaceTextureScales_[static_cast<size_t>(face)];
296}
297
298float ReflectionProbeCapture::getSkyFaceColor(int face, int component) const {
299 if (face < 0 || face >= 6 || component < 0 || component >= 3) return 0.f;
300 const size_t index = static_cast<size_t>(face);
301 if (component == 0) return skyR_[index];
302 if (component == 1) return skyG_[index];
303 return skyB_[index];
304}
305
307 const float nextScale = std::clamp(scale, 0.25f, 4.f);
308 if (nextScale == lodDistanceScale_) return;
309 lodDistanceScale_ = nextScale;
310 requestCaptureAfterPublish();
311}
312
314 if (enabled == captureTransparent_) return;
315 captureTransparent_ = enabled;
316 requestCaptureAfterPublish();
317}
318
320 if (enabled == captureClusteredLighting_) return;
321 captureClusteredLighting_ = enabled;
322 requestCaptureAfterPublish();
323}
324
326 gpuBudgetMs_ = std::clamp(milliseconds, 0.1f, 16.f);
327 underBudgetReports_ = 0;
328}
329
331 if (milliseconds <= 0.f || !std::isfinite(milliseconds)) return;
332 smoothedGpuDurationMs_ =
333 smoothedGpuDurationMs_ > 0.f ? smoothedGpuDurationMs_ * 0.8f + milliseconds * 0.2f : milliseconds;
334
335 if (smoothedGpuDurationMs_ > gpuBudgetMs_ * 1.1f) {
336 underBudgetReports_ = 0;
337 if (adaptiveFaceBudget_ > 1)
338 --adaptiveFaceBudget_;
339 else
340 adaptiveFilterSamples_ = std::max(adaptiveFilterSamples_ / 2, 8);
341 return;
342 }
343
344 if (smoothedGpuDurationMs_ < gpuBudgetMs_ * 0.7f) {
345 if (++underBudgetReports_ < 4) return;
346 underBudgetReports_ = 0;
347 if (adaptiveFilterSamples_ < 64)
348 adaptiveFilterSamples_ = std::min(adaptiveFilterSamples_ * 2, 64);
349 else
350 adaptiveFaceBudget_ = std::min(adaptiveFaceBudget_ + 1, 6);
351 } else {
352 underBudgetReports_ = 0;
353 }
354}
355
356bool ReflectionProbeCapture::tickAdaptive() { return tick(adaptiveFaceBudget_, adaptiveFilterSamples_); }
357
358void ReflectionProbeCapture::advanceRefreshPolicy() {
359 ++framesSincePublish_;
360 if (!pending_) {
361 if (recaptureAfterPublish_ && publishedRevision_ == revision_)
363 else if (updateMode_ == UpdateMode::Realtime ||
364 (updateMode_ == UpdateMode::TimeSliced && framesSincePublish_ >= refreshInterval_))
366 else if (updateMode_ == UpdateMode::Static && revision_ == 0)
368 }
369}
370
371bool ReflectionProbeCapture::tick(int faceBudget, int filterSamples) {
373 advanceRefreshPolicy();
374 if (pending_ && !update(faceBudget)) return false;
375 if (publishedRevision_ == revision_) return false;
376 if (!stageCapturedFaces()) return false;
377 return filterAndPublish(filterSamples);
378}
379
380void ReflectionProbeCapture::configureInfluence(float extentX, float extentY, float extentZ, float intensity,
381 float blendDistance, int priority) {
382 influenceExtentX_ = std::max(extentX, 0.001f);
383 influenceExtentY_ = std::max(extentY, 0.001f);
384 influenceExtentZ_ = std::max(extentZ, 0.001f);
385 influenceIntensity_ = std::max(intensity, 0.f);
386 influenceBlendDistance_ = std::max(blendDistance, 0.f);
387 influencePriority_ = priority;
388}
389
391 if (!camera || !activeCubemap_ || publishedRevision_ == 0) return false;
392 camera->setReflectionProbe(slot, activeCubemap_, centerX_, centerY_, centerZ_, influenceExtentX_, influenceExtentY_,
393 influenceExtentZ_, influenceIntensity_, influenceBlendDistance_, influencePriority_);
394 return true;
395}
396
397bool ReflectionProbeCapture::applyToCamera(Camera3D *camera, int slot, float extentX, float extentY, float extentZ,
398 float intensity, float blendDistance, int priority) {
399 configureInfluence(extentX, extentY, extentZ, intensity, blendDistance, priority);
401}
402
403} // namespace eve::graphics
404
405// ReflectionProbeRegistry.cpp
406namespace eve::graphics {
407
409
411 if (!probe) return;
412 const auto found =
413 std::find_if(entries_.begin(), entries_.end(), [probe](const Entry &entry) { return entry.probe == probe; });
414 if (found == entries_.end()) {
415 entries_.push_back(Entry{probe, nextOrder_++});
416 probe->attachRegistry(this);
417 }
418}
419
421 if (probe) probe->detachRegistry(this);
422 entries_.erase(
423 std::remove_if(entries_.begin(), entries_.end(), [probe](const Entry &entry) { return entry.probe == probe; }),
424 entries_.end());
425 lastSelected_.erase(std::remove(lastSelected_.begin(), lastSelected_.end(), probe), lastSelected_.end());
426}
427
429 for (const Entry &entry : entries_)
430 if (entry.probe) entry.probe->detachRegistry(this);
431 entries_.clear();
432 lastSelected_.clear();
433 lastSelectedCount_ = 0;
434 lastCapturedFaceCount_ = 0;
435 lastPublishedCount_ = 0;
436 lastCandidateCount_ = 0;
437 lastDistanceCulledCount_ = 0;
438}
439
441 if (!std::isfinite(distance) || distance <= 0.f)
443 "Reflection probe render distance must be positive and finite",
444 "graphics.reflectionProbe.maxRenderDistance"));
445 maxRenderDistance_ = distance;
446 return Result<void>::success();
447}
448
450 selectionHysteresis_ = std::clamp(distance, 0.f, 100.f);
451}
452
454 const uint32_t mask = static_cast<uint32_t>(changedMask);
455 int queued = 0;
456 for (Entry &entry : entries_) {
457 if (!entry.probe || (static_cast<uint32_t>(entry.probe->getCaptureMask()) & mask) == 0u) continue;
458 entry.probe->queueCapture();
459 ++queued;
460 }
461 return queued;
462}
463
464int ReflectionProbeRegistry::queueCaptureAABB(float minX, float minY, float minZ, float maxX, float maxY, float maxZ,
465 int changedMask) {
466 const float changedMin[3] = {std::min(minX, maxX), std::min(minY, maxY), std::min(minZ, maxZ)};
467 const float changedMax[3] = {std::max(minX, maxX), std::max(minY, maxY), std::max(minZ, maxZ)};
468 const uint32_t mask = static_cast<uint32_t>(changedMask);
469 int queued = 0;
470 for (Entry &entry : entries_) {
471 ReflectionProbeCapture *probe = entry.probe;
472 if (!probe || (static_cast<uint32_t>(probe->getCaptureMask()) & mask) == 0u) continue;
473 const float center[3] = {probe->getCenterX(), probe->getCenterY(), probe->getCenterZ()};
474 float distance2 = 0.f;
475 for (int axis = 0; axis < 3; ++axis) {
476 const float nearest = std::clamp(center[axis], changedMin[axis], changedMax[axis]);
477 const float delta = center[axis] - nearest;
478 distance2 += delta * delta;
479 }
480 const float captureRadius = probe->getCaptureFarDistance();
481 if (distance2 > captureRadius * captureRadius) continue;
482 probe->queueCapture();
483 ++queued;
484 }
485 return queued;
486}
487
488int ReflectionProbeRegistry::tick(int faceBudget, int filterBudget, int filterSamples) {
489 lastCapturedFaceCount_ = 0;
490 lastPublishedCount_ = 0;
491 faceBudget = std::max(faceBudget, 0);
492 filterBudget = std::max(filterBudget, 0);
493 filterSamples = std::clamp(filterSamples, 8, 512);
494
495 for (Entry &entry : entries_) {
496 if (!entry.probe || (distanceCullingEnabled_ && entry.distanceCulled)) continue;
497 entry.probe->advanceRefreshPolicy();
498 const bool waiting =
499 entry.probe->isCapturePending() || entry.probe->getPublishedRevision() != entry.probe->getRevision();
500 if (waiting && entry.waitAge < std::numeric_limits<uint32_t>::max()) ++entry.waitAge;
501 }
502
503 auto better = [](const Entry *a, const Entry *b) {
504 const int priorityA = a->probe->getInfluencePriority();
505 const int priorityB = b->probe->getInfluencePriority();
506 if (priorityA != priorityB) return priorityA > priorityB;
507 if (a->waitAge != b->waitAge) return a->waitAge > b->waitAge;
508 return a->order < b->order;
509 };
510
511 while (faceBudget-- > 0) {
512 Entry *selected = nullptr;
513 for (Entry &entry : entries_) {
514 if (!entry.probe || !entry.probe->isCapturePending()) continue;
515 if (!selected || better(&entry, selected)) selected = &entry;
516 }
517 if (!selected) break;
518 selected->probe->update(1);
519 selected->waitAge = 0;
520 lastCapturedFaceCount_ += selected->probe->getLastCapturedFaceCount();
521 }
522
523 while (filterBudget-- > 0) {
524 Entry *selected = nullptr;
525 for (Entry &entry : entries_) {
526 if (!entry.probe || entry.probe->isCapturePending() ||
527 entry.probe->getRevision() == entry.probe->getPublishedRevision())
528 continue;
529 if (!selected || better(&entry, selected)) selected = &entry;
530 }
531 if (!selected) break;
532 if (selected->probe->stageCapturedFaces() && selected->probe->filterAndPublish(filterSamples)) {
533 selected->waitAge = 0;
534 ++lastPublishedCount_;
535 } else {
536 break;
537 }
538 }
539 return lastPublishedCount_;
540}
541
543 lastSelectedCount_ = 0;
544 lastCandidateCount_ = 0;
545 lastDistanceCulledCount_ = 0;
546 if (!camera) {
547 lastSelected_.clear();
548 return 0;
549 }
550 for (int slot = 0; slot < Camera3D::Data::kMaxReflectionProbes; ++slot) camera->clearReflectionProbe(slot);
551
552 struct Candidate {
553 ReflectionProbeCapture *probe = nullptr;
554 int priority = 0;
555 float distance2 = 0.f;
556 bool retained = false;
557 uint64_t order = 0;
558 };
559 std::vector<Candidate> candidates;
560 candidates.reserve(entries_.size());
561 const auto cameraData = camera->data();
562 const float eye[3] = {cameraData->eyeX, cameraData->eyeY, cameraData->eyeZ};
563 const float target[3] = {cameraData->targetX, cameraData->targetY, cameraData->targetZ};
564 const float viewSegment[3] = {target[0] - eye[0], target[1] - eye[1], target[2] - eye[2]};
565 const float viewSegmentLength2 =
566 viewSegment[0] * viewSegment[0] + viewSegment[1] * viewSegment[1] + viewSegment[2] * viewSegment[2];
567 for (Entry &entry : entries_) {
568 ReflectionProbeCapture *probe = entry.probe;
569 if (!probe) continue;
570 const float center[3] = {probe->getCenterX(), probe->getCenterY(), probe->getCenterZ()};
571 const float eyeDx = center[0] - eye[0], eyeDy = center[1] - eye[1], eyeDz = center[2] - eye[2];
572 const bool distanceCulled = distanceCullingEnabled_ && eyeDx * eyeDx + eyeDy * eyeDy + eyeDz * eyeDz >=
573 maxRenderDistance_ * maxRenderDistance_;
574 if (entry.distanceCulled && !distanceCulled) probe->queueCapture();
575 entry.distanceCulled = distanceCulled;
576 if (distanceCulled) {
577 ++lastDistanceCulledCount_;
578 continue;
579 }
580 if (!probe->getActiveCubemap() || probe->getPublishedRevision() == 0 || probe->getInfluenceIntensity() <= 0.f)
581 continue;
582 const float extent[3] = {probe->getInfluenceExtentX(), probe->getInfluenceExtentY(),
583 probe->getInfluenceExtentZ()};
584 float closestT = 0.f;
585 if (viewSegmentLength2 > 1e-8f) {
586 const float toCenter[3] = {center[0] - eye[0], center[1] - eye[1], center[2] - eye[2]};
587 closestT = std::clamp(
588 (toCenter[0] * viewSegment[0] + toCenter[1] * viewSegment[1] + toCenter[2] * viewSegment[2]) /
589 viewSegmentLength2,
590 0.f, 1.f);
591 }
592 const float closestViewPoint[3] = {
593 eye[0] + viewSegment[0] * closestT,
594 eye[1] + viewSegment[1] * closestT,
595 eye[2] + viewSegment[2] * closestT,
596 };
597 float distance2 = 0.f;
598 for (int axis = 0; axis < 3; ++axis) {
599 const float outside = std::max(std::abs(closestViewPoint[axis] - center[axis]) - extent[axis], 0.f);
600 distance2 += outside * outside;
601 }
602 const bool retained = std::find(lastSelected_.begin(), lastSelected_.end(), probe) != lastSelected_.end();
603 const float distance = std::sqrt(distance2);
604 const float biasedDistance = retained ? std::max(distance - selectionHysteresis_, 0.f) : distance;
605 candidates.push_back(
606 Candidate{probe, probe->getInfluencePriority(), biasedDistance * biasedDistance, retained, entry.order});
607 }
608 lastCandidateCount_ = static_cast<int>(candidates.size());
609 std::stable_sort(candidates.begin(), candidates.end(), [](const Candidate &a, const Candidate &b) {
610 if (a.priority != b.priority) return a.priority > b.priority;
611 if (a.distance2 != b.distance2) return a.distance2 < b.distance2;
612 if (a.retained != b.retained) return a.retained;
613 return a.order < b.order;
614 });
615
616 const int selected = std::min(static_cast<int>(candidates.size()), Camera3D::Data::kMaxReflectionProbes);
617 lastSelected_.clear();
618 lastSelected_.reserve(static_cast<size_t>(selected));
619 for (int slot = 0; slot < selected; ++slot) {
620 ReflectionProbeCapture *probe = candidates[static_cast<size_t>(slot)].probe;
621 if (probe->applyConfiguredToCamera(camera, slot)) {
622 lastSelected_.push_back(probe);
623 ++lastSelectedCount_;
624 }
625 }
626 return lastSelectedCount_;
627}
628
629} // namespace eve::graphics
double z
double y
double x
LogicalId target
std::string selected
int mask
std::unordered_map< std::string, std::unique_ptr< ProviderRegistry< void > > > registries
int priority
bool changed
tensor::Graph g
Definition GpuGraph.cpp:7
float camera[2]
float u
Definition Grass.cpp:233
double r
std::vector< std::uint32_t > indices
std::vector< float > normals
std::vector< float > positions
HexVec3 up
JointPoint2D axis
std::array< float, 3 > scale
MeleePoint3 b
Definition MeleeHit.cpp:41
MeleePoint3 a
Definition MeleeHit.cpp:40
float distance
std::vector< std::int32_t > order
glm::dvec2 center
size_t directions
size_t queued
Definition OnnxGpgpu.cpp:60
double & milliseconds
Definition OnnxGpgpu.cpp:19
Texture * texture
const eve::script::BindingContractRegistry & registry
std::string slot
glm::vec3 eye
RoadLaneDirection direction
bool found
std::map< std::array< int, 4 >, std::vector< const Subject * > > candidates
Definition Sensing.cpp:32
SimulationTick tick
uint32_t index
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
Move-only operation result carrying either a value or Status.
Definition Result.h:176
static Result success(T value)
Construct a successful result owning value.
Definition Result.h:185
static Result failure(Status status)
Construct a failed result from a structured status.
Definition Result.h:196
EVENGINE_API_BACKENDS public API.
void setBloom(float intensity, float threshold=1.f)
Configure HDR bloom. Zero intensity disables it.
static Camera3D * createCamera(ecs::Table &table= *ecs::current())
Create an active camera in the current ECS table.
void setUp(float x, float y, float z)
void clearEnvProbe()
Disable box projection and return to an infinite-distance environment.
void clearReflectionProbe(int slot)
Disable one local reflection probe slot.
void setFov(float fovYDeg)
void setExposure(float ev)
Set exposure compensation in photographic stops. Positive values brighten.
void setEnvIntensity(float intensity)
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)
void setAmbient(float r, float g, float b)
void setActive(bool active)
void setEye(float x, float y, float z)
void setEnvMap(Texture *cube)
Specular IBL cubemap (Graphics::newCubemap). nullptr disables IBL.
Canvas public API.
Definition Canvas.h:17
virtual bool copyHDRCanvasesToCubemap(Canvas *const *sources, int faceCount, Texture *cubemap)
Copy consecutive RGBA16F canvases into cubemap base-level faces.
Definition Graphics.h:577
virtual bool filterHDRReflectionCubemap(Texture *cubemap, int sampleCount=64)
Generate GGX specular mips and final diffuse irradiance for an HDR cubemap. @compatibility Preserves ...
Definition Graphics.h:588
virtual float getLastOffscreen3DGpuDurationMs() const
Return the GPU timestamp duration of the most recently completed offscreen 3D pass,...
Definition Graphics.h:1058
virtual Mesh * newMeshFromArrays(const float *posXYZ, const float *nrmXYZ, const float *uvST, int vertexCount, const uint32_t *indices, int indexCount)=0
Upload a triangle mesh from packed CPU arrays. Owned by Graphics. posXYZ required (vertexCount*3)....
virtual Texture * newHDRCubemap(int faceSize)
Allocate a linear RGBA16F six-layer staging cubemap for runtime capture.
Definition Graphics.h:549
Incremental six-face HDR scene capture for a runtime reflection probe.
float getInfluenceExtentY() const
Return persistent influence half extent Y.
float getCaptureFarDistance() const
Return the capture far distance used for spatial dirty culling.
void requestCapture()
Mark all six faces dirty and restart capture at +X.
void setGpuBudgetMs(float milliseconds)
Set the GPU-time budget used by adaptive capture scheduling, in milliseconds.
~ReflectionProbeCapture()
Detach this probe from every registry before script-owned destruction.
bool applyConfiguredToCamera(Camera3D *camera, int slot)
Submit the persistent influence and active cubemap to a Camera3D slot. @compatibility Preserves the s...
float getInfluenceExtentX() const
Return persistent influence half extent X.
std::string getUpdateMode() const
Return the current refresh mode.
bool tickAdaptive()
Advance capture and filtering using the GPU-budget controller's workload.
void setEnvironmentLighting(Texture *environment, float intensity=1.f)
Set non-recursive global environment lighting for captured geometry.
bool tick(int faceBudget=1, int filterSamples=64)
Advance capture, staging, filtering and publishing under the selected policy.
float getCenterY() const
Return probe world-space center Y.
Canvas * getFaceCanvas(int face) const
Return one captured HDR face Canvas in +X,-X,+Y,-Y,+Z,-Z order. @lifetime Returned canvas is borrowed...
uint32_t getPublishedRevision() const
Last capture revision atomically published for lighting.
void setRefreshInterval(int frames)
Set automatic refresh interval in frames for time_sliced mode.
void setCaptureClusteredLighting(bool enabled)
Enable clustered lighting for captures that exceed the legacy light pack.
int getInfluencePriority() const
Return persistent overlap-selection priority.
float getInfluenceExtentZ() const
Return persistent influence half extent Z.
bool isCaptureComplete() const
True after at least one complete six-face capture.
void setSkyFaceTextureScale(int face, float scale)
Set the linear HDR radiance multiplier for one sky face texture.
float getInfluenceIntensity() const
Return persistent reflection intensity.
ReflectionProbeCapture(Graphics *gfx)
Reflection probe capture.
void setSkyFaceTexture(int face, Texture *texture)
Set a directional per-pixel sky texture for one capture face.
void configureInfluence(float extentX, float extentY, float extentZ, float intensity=1.f, float blendDistance=1.f, int priority=0)
Configure the persistent box influence used for lighting and editor display.
void reportGpuDurationMs(float milliseconds)
Report a backend timestamp duration for the most recent probe workload.
bool update(int faceBudget=1)
Capture up to faceBudget dirty faces.
void queueCapture()
Queue a coherent recapture without restarting a revision already in progress.
float getSkyFaceTextureScale(int face) const
Return one sky face texture's linear HDR radiance multiplier.
void setSkyFaceColor(int face, float r, float g, float b)
Override one directional backup sky face in +X,-X,+Y,-Y,+Z,-Z order.
float getCenterZ() const
Return probe world-space center Z.
void setUpdateMode(const std::string &mode)
Set refresh mode: static, on_demand, time_sliced, or realtime.
bool applyToCamera(Camera3D *camera, int slot, float extentX, float extentY, float extentZ, float intensity=1.f, float blendDistance=1.f, int priority=0)
Assign the active cubemap to a Camera3D local reflection-probe slot.
void setCaptureMask(int mask)
Set the object-layer mask visible to this reflection capture.
Texture * getSkyFaceTexture(int face) const
Return one directional per-pixel sky texture, or nullptr. @lifetime Returned texture is borrowed; its...
int getCaptureMask() const
Return the object-layer mask visible to this reflection capture.
float getCenterX() const
Return probe world-space center X.
void setCaptureLodDistanceScale(float scale)
Set capture LOD distance scale; below one retains higher-detail LODs farther away.
void configure(float x, float y, float z, int resolution=128, float nearZ=0.1f, float farZ=100.f)
Configure the probe origin, face resolution and clipping planes.
bool stageCapturedFaces()
Copy a complete capture revision into a backend HDR staging cubemap. @compatibility Preserves the scr...
void setSkyColor(float r, float g, float b, float intensity=1.f)
Set a linear HDR backup sky color for empty capture pixels.
Texture * getActiveCubemap() const
Last fully filtered cubemap, safe to assign to Camera3D reflection probes. @lifetime Returned texture...
bool filterAndPublish(int sampleCount=64)
Filter with 8-512 samples and atomically publish the active cubemap. @compatibility Preserves the scr...
float getSkyFaceColor(int face, int component) const
Return one directional sky-face color component, or zero for invalid indices.
void setCaptureTransparent(bool enabled)
Enable or disable transparent/hair surfaces in probe captures.
Scene-level stable selection of published reflection probes for a camera.
int tick(int faceBudget=1, int filterBudget=1, int filterSamples=64)
Advance every refresh policy while enforcing scene-wide GPU work budgets.
~ReflectionProbeRegistry()
Detach all probes before script-owned destruction.
void remove(ReflectionProbeCapture *probe)
Remove a registered probe.
Result< void > setMaxRenderDistance(float distance)
Set the positive Pcg probe render distance; failure preserves the previous value.
void setSelectionHysteresis(float distance)
Set world-space distance hysteresis used to retain previous camera selections.
int queueCaptureAABB(float minX, float minY, float minZ, float maxX, float maxY, float maxZ, int changedMask=-1)
Queue probes whose mask and capture-radius sphere overlap a changed world AABB.
void clear()
Remove every registered probe.
int queueCapture(int changedMask=-1)
Queue coherent recapture for probes whose capture mask intersects changedMask.
int updateCamera(Camera3D *camera)
Select eight probes nearest the camera view segment and replace Camera3D slots.
void add(ReflectionProbeCapture *probe)
Register a probe once; duplicate registrations are ignored.
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...
GPU texture created via Graphics::newTexture. Owns GPU resources through an opaque backend handle.
Definition Texture.h:15
卡牌游戏 UI 工具模块:工厂 + 脚本绑定入口。 功能参考 ycarowr/UiCard:扇形手牌布局、抽牌/洗牌、悬浮放大、拖拽到落牌区、 敌方手牌(背面/偷看)、费用不足置灰,以及可实时调节的布局...
Definition Animation.h:25
eve::Color Color
RGBA color used by every graphics draw call. Lives inside eve::graphics so including a graphics heade...
Definition Color.h:13
bool enabled
static constexpr int kMaxReflectionProbes