载入中...
搜索中...
未找到
FogRayMarch.cpp
浏览该文件的文档.
2#include <algorithm>
3#include <cmath>
4#include <glm/common.hpp>
5#include <glm/geometric.hpp>
6#include "common/Diagnostic.h"
7#include "common/Status.h"
11
12// FogRayMarch.cpp
13namespace eve::graphics::fog {
14namespace {
15
16[[nodiscard]] std::optional<FogRayInterval> intersectSlab(float origin, float dir, float minV, float maxV) {
17 if (std::fabs(dir) < 1e-8f) {
18 if (origin < minV || origin > maxV) return std::nullopt;
19 return FogRayInterval{0.f, 1e6f};
20 }
21 float t0 = (minV - origin) / dir;
22 float t1 = (maxV - origin) / dir;
23 if (t0 > t1) std::swap(t0, t1);
24 return FogRayInterval{t0, t1};
25}
26
27[[nodiscard]] std::optional<FogRayInterval> intersectRayAabb(const glm::vec3& o, const glm::vec3& d,
28 const glm::vec3& mn, const glm::vec3& mx) {
29 auto sx = intersectSlab(o.x, d.x, mn.x, mx.x);
30 auto sy = intersectSlab(o.y, d.y, mn.y, mx.y);
31 auto sz = intersectSlab(o.z, d.z, mn.z, mx.z);
32 if (!sx || !sy || !sz) return std::nullopt;
33 const float tEnter = std::max({sx->tEnter, sy->tEnter, sz->tEnter, 0.f});
34 const float tExit = std::min({sx->tExit, sy->tExit, sz->tExit});
35 if (tExit <= tEnter) return std::nullopt;
36 return FogRayInterval{tEnter, tExit};
37}
38
39} // namespace
40
41std::optional<FogRayInterval> FogRayMarch::intersectBound(const glm::vec3& origin, const glm::vec3& direction,
42 const FogVolumeBound& bound) {
43 const float len = glm::length(direction);
44 if (!(len > 1e-8f)) return std::nullopt;
45 const glm::vec3 d = direction / len;
46
47 switch (bound.kind) {
49 // Ray vs sphere centered at origin xz / y=0 shell approximation.
50 const glm::vec3 center(origin.x, 0.f, origin.z);
51 const glm::vec3 oc = origin - center;
52 const float b = glm::dot(oc, d);
53 const float c = glm::dot(oc, oc) - bound.skyRadius * bound.skyRadius;
54 const float disc = b * b - c;
55 if (disc < 0.f) return std::nullopt;
56 const float s = std::sqrt(disc);
57 const float t0 = -b - s;
58 const float t1 = -b + s;
59 const float tEnter = std::max(t0, 0.f);
60 if (t1 <= tEnter) return std::nullopt;
61 return FogRayInterval{tEnter, t1};
62 }
64 auto slab = intersectSlab(origin.y, d.y, bound.heightMin, bound.heightMax);
65 if (!slab) return std::nullopt;
66 const float tEnter = std::max(slab->tEnter, 0.f);
67 if (slab->tExit <= tEnter) return std::nullopt;
68 // Cap far distance so infinite rays remain bounded.
69 return FogRayInterval{tEnter, std::min(slab->tExit, tEnter + 200.f)};
70 }
72 // Transform ray into OBB local space, then AABB test.
73 const glm::vec3 o = origin - bound.obbCenter;
74 const glm::vec3 localO(glm::dot(o, bound.obbAxisX), glm::dot(o, bound.obbAxisY),
75 glm::dot(o, bound.obbAxisZ));
76 const glm::vec3 localD(glm::dot(d, bound.obbAxisX), glm::dot(d, bound.obbAxisY),
77 glm::dot(d, bound.obbAxisZ));
78 return intersectRayAabb(localO, localD, -bound.obbHalfExtents, bound.obbHalfExtents);
79 }
80 }
81 return std::nullopt;
82}
83
85 const glm::vec3& origin, const glm::vec3& direction,
86 const FogVolumeBound& bound, const glm::vec3& lightDir,
87 const glm::vec3& lightColor, float lightIntensity,
88 const glm::vec3& skyAmbient, const glm::vec3& groundAmbient,
89 int sampleCount, float sceneDepth, const BeerLightCache* beerCache,
90 bool useAnalyticSegments) const {
91 if (sampleCount < 1 || sampleCount > 256) {
93 DiagnosticCode::InvalidArgument, "sampleCount must be in [1,256]", "sampleCount", {}, "graphics.fog"));
94 }
95 const float dirLen = glm::length(direction);
96 if (!(dirLen > 1e-8f)) {
98 DiagnosticCode::InvalidArgument, "direction must be non-zero", "direction", {}, "graphics.fog"));
99 }
100 const glm::vec3 dir = direction / dirLen;
101 auto interval = intersectBound(origin, dir, bound);
102 if (!interval) {
103 FogRayResult empty;
104 return Result<FogRayResult>::success(empty);
105 }
106 if (sceneDepth > 0.f) interval->tExit = std::min(interval->tExit, sceneDepth);
107 if (!interval->valid()) {
108 FogRayResult empty;
109 return Result<FogRayResult>::success(empty);
110 }
111
112 const glm::vec3 L = glm::length(lightDir) > 1e-6f ? glm::normalize(lightDir) : glm::vec3(0.f, 1.f, 0.f);
113 const float cosTheta = glm::dot(-dir, L);
114 const float phase = profile.phase(cosTheta);
115
117 float T = 1.f;
118 const float segLen = interval->length() / static_cast<float>(sampleCount);
119 float prevDensity = -1.f;
120
121 for (int i = 0; i < sampleCount && T > 1e-4f; ++i) {
122 const float t = interval->tEnter + (static_cast<float>(i) + 0.5f) * segLen;
123 const glm::vec3 p = origin + dir * t;
124 const float density = field.sampleDensity(p);
125 const float sigmaT = profile.extinctionAt(density);
126 const glm::vec3 sigmaS = profile.scatteringAt(density);
127
128 float stepOptical = sigmaT * segLen;
129 float stepT;
130 if (useAnalyticSegments && prevDensity >= 0.f &&
131 std::fabs(density - prevDensity) < 0.02f * std::max(1.f, prevDensity)) {
132 // Closed-form Beer segment for locally stable media.
133 stepT = std::exp(-stepOptical);
134 } else {
135 stepT = std::exp(-stepOptical);
136 }
137 prevDensity = density;
138
139 float visibility = 1.f;
140 if (beerCache && beerCache->valid()) {
141 visibility = beerCache->sampleTransmittance(field, p);
142 }
143 const glm::vec3 ambient = profile.ambientRadiance(skyAmbient, groundAmbient, density);
144 const glm::vec3 assist = field.sampleLightAssist(p);
145 const glm::vec3 Li = lightColor * lightIntensity * visibility * phase + ambient + assist;
146 // Front-to-back: in-scatter attenuated by current transmittance.
147 const glm::vec3 scatter = sigmaS * Li * ((1.f - stepT) / std::max(sigmaT, 1e-6f));
148 result.inScatter += T * scatter;
149 T *= stepT;
150 result.opticalDepth += stepOptical;
151 ++result.samplesUsed;
152 }
153
154 result.transmittance = T;
156}
157
158} // namespace eve::graphics::fog
159
160// FogSystem.cpp
161namespace eve::graphics::fog {
162
164 quality_ = quality;
165 beerCache_.invalidate();
166 return Result<void>::success();
167}
168
169Result<void> FogSystem::configureDomain(int simWidth, int simHeight, int simDepth, const FogWorldBounds& bounds,
170 float fixedDt) {
171 auto resized = density_.resize(simWidth, simHeight, simDepth, bounds);
172 if (!resized.ok()) return resized;
173 auto configured = fluid_.configure(density_, fixedDt);
174 if (!configured.ok()) return configured;
175 beerCache_.invalidate();
176 return Result<void>::success();
177}
178
179Result<void> FogSystem::seedHeightFog(float baseDensity, float baseHeight, float falloff, float curlScale,
180 std::uint32_t seed) {
181 auto seeded = density_.seedHeightBand(baseDensity, baseHeight, falloff, curlScale, seed);
182 if (!seeded.ok()) return seeded;
183 auto pulled = fluid_.pullDensity(density_);
184 if (!pulled.ok()) return pulled;
185 beerCache_.invalidate();
186 return Result<void>::success();
187}
188
190 auto stepped = fluid_.step(dt, wind_, &interactor_, simTime_);
191 if (!stepped.ok()) return stepped;
192 auto pushed = fluid_.pushDensity(density_);
193 if (!pushed.ok()) return Result<FogCflReport>::failure(pushed.status());
194 simTime_ += dt;
195 ++frameIndex_;
196 beerCache_.invalidate();
197 return stepped;
198}
199
200Result<void> FogSystem::ensureBeerCache(const glm::vec3& lightDir, const glm::vec3& lightColor, float intensity) {
201 const auto budget = budgetFor(quality_);
202 if (!budget.beerLightCache) {
203 beerCache_.invalidate();
205 }
206 if (beerCache_.matches(density_.revision(),
207 glm::length(lightDir) > 1e-6f ? glm::normalize(lightDir) : glm::vec3(0, 1, 0), intensity)) {
209 }
210 return beerCache_.rebuild(density_, profile_, lightDir, lightColor, intensity, 6);
211}
212
213Result<FogRayResult> FogSystem::marchRay(const glm::vec3& origin, const glm::vec3& direction,
214 const FogVolumeBound& bound, const glm::vec3& lightDir,
215 const glm::vec3& lightColor, float lightIntensity, const glm::vec3& skyAmbient,
216 const glm::vec3& groundAmbient, float sceneDepth) const {
217 const auto budget = budgetFor(quality_);
218 const BeerLightCache* cache = (budget.beerLightCache && beerCache_.valid()) ? &beerCache_ : nullptr;
219 return rayMarch_.integrate(density_, profile_, origin, direction, bound, lightDir, lightColor, lightIntensity,
220 skyAmbient, groundAmbient, budget.raySamples, sceneDepth, cache,
222}
223
225 const glm::vec3& lightColor, float intensity) {
226 const auto budget = budgetFor(quality_);
227 if (volume.getWidth() != budget.froxelWidth || volume.getHeight() != budget.froxelHeight ||
228 volume.getDepth() != budget.froxelDepth) {
230 volume.setDepthRange(0.1f, std::max(density_.bounds().size().z, 40.f));
231 } else {
232 volume.clear();
233 }
234
235 auto cacheReady = ensureBeerCache(lightDir, lightColor, intensity);
236 if (!cacheReady.ok()) return Result<int>::failure(cacheReady.status());
237
238 auto injected = froxelBridge_.inject(volume, density_, profile_, invViewProj, budget.occupancySkip);
239 if (!injected.ok()) return injected;
240
241 const BeerLightCache* cache = (budget.beerLightCache && beerCache_.valid()) ? &beerCache_ : nullptr;
242 auto integrated =
243 froxelBridge_.integrate(volume, density_, profile_, invViewProj, lightDir, lightColor, intensity, cache);
244 if (!integrated.ok()) return Result<int>::failure(integrated.status());
245
246 if (budget.temporalHistory && frameIndex_ > 1) {
247 // Lightweight self-history: blend with a cleared-then-reintegrated snapshot is
248 // intentionally skipped here; callers may keep an external history volume.
249 (void)budget.historyWeight;
250 }
251 return injected;
252}
253
255 if (volume.getWidth() <= 0 || density_.width() <= 0) {
256 return Result<int>::failure(Diagnostic::error(DiagnosticCode::Failed, "froxel/density volumes are empty",
257 "injectToFroxel", {}, "graphics.fog"));
258 }
259 const auto budget = budgetFor(quality_);
260 return froxelBridge_.inject(volume, density_, profile_, invViewProj, budget.occupancySkip);
261}
262
264 if (!volumetric) {
266 Diagnostic::error(DiagnosticCode::InvalidArgument, "volumetric is null", "volumetric", {}, "graphics.fog"));
267 }
269 if (!volume) {
271 DiagnosticCode::Failed, "volumetric has no AtmosphereVolume; call configureFroxelGrid first",
272 "atmosphereVolume", {}, "graphics.fog"));
273 }
274 return injectToFroxel(*volume, volumetric->getInvViewProj());
275}
276
277Result<int> FogSystem::syncToVolumetric(Volumetric* volumetric, const glm::vec3& lightDir, const glm::vec3& lightColor,
278 float intensity) {
279 if (!volumetric) {
281 Diagnostic::error(DiagnosticCode::InvalidArgument, "volumetric is null", "volumetric", {}, "graphics.fog"));
282 }
284 if (!volume) {
286 DiagnosticCode::Failed, "volumetric has no AtmosphereVolume; call configureFroxelGrid first",
287 "atmosphereVolume", {}, "graphics.fog"));
288 }
289
290 // Keep Volumetric atlas metadata in sync with the quality grid. Resizing the
291 // AtmosphereVolume alone leaves froxelAtlasCols_/Rows_ stale and corrupts upload.
292 const auto budget = budgetFor(quality_);
293 float nearDistance = volume->getNearDistance();
294 float farDistance = volume->getFarDistance();
295 if (!(farDistance > nearDistance)) {
296 nearDistance = 0.1f;
297 farDistance = std::max(density_.bounds().size().z, 40.f);
298 }
300 farDistance);
301 volume = volumetric->getAtmosphereVolume();
302 if (!volume) {
304 "configureFroxelGrid left AtmosphereVolume empty",
305 "atmosphereVolume", {}, "graphics.fog"));
306 }
307
308 auto cacheReady = ensureBeerCache(lightDir, lightColor, intensity);
309 if (!cacheReady.ok()) return Result<int>::failure(cacheReady.status());
310
311 const glm::mat4& invViewProj = volumetric->getInvViewProj();
312 auto injected = froxelBridge_.inject(*volume, density_, profile_, invViewProj, budget.occupancySkip);
313 if (!injected.ok()) return injected;
314
315 const BeerLightCache* cache = (budget.beerLightCache && beerCache_.valid()) ? &beerCache_ : nullptr;
316 auto integrated =
317 froxelBridge_.integrate(*volume, density_, profile_, invViewProj, lightDir, lightColor, intensity, cache);
318 if (!integrated.ok()) return Result<int>::failure(integrated.status());
319 return injected;
320}
321
323 const glm::vec3& direction, float sceneDepth, float mediumDensity) const {
324 const auto budget = budgetFor(quality_);
325 return volLight_.integrate(beam, profile_, origin, direction, sceneDepth, budget.volLightSegments, mediumDensity);
326}
327
328Result<std::vector<DustParticle>> FogSystem::generateDust(int count, float turbulenceMeters, std::uint32_t seed) const {
329 return dust_.generate(density_.bounds(), count, simTime_, turbulenceMeters, seed);
330}
331
333 float neighborOpacity) const noexcept {
334 return art_.stylize(physical, viewZ, neighborOpacity);
335}
336
337} // namespace eve::graphics::fog
double volume
const std::string & s
glm::vec4 p[6]
Stable, structured diagnostics shared by engine modules.
float density
std::int32_t c
Poco::JSON::Object::Ptr result
MeleePoint3 b
Definition MeleeHit.cpp:41
glm::dvec3 origin
glm::dvec2 center
double dt
float d
float t
RoadLaneDirection direction
int count
Structured operation status used by the common Result foundation.
float phase
uint32_t seed
Definition TreeMesh.cpp:276
V3 dir
Definition TreeMesh.cpp:151
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
static Status success(StatusCode code=StatusCode::Ok)
Construct a successful status with an explicit non-error outcome.
Definition Status.cpp:19
Camera-frustum volume used by the volumetric fog passes and CPU references.
Volumetric light + fog.
Definition Volumetric.h:38
const glm::mat4 & getInvViewProj() const
Inverse view-projection last written by setCamera / setInvViewProj.
Definition Volumetric.h:215
AtmosphereVolume * getAtmosphereVolume() const
Access the froxel media grid for native density/light injection.
Definition Volumetric.h:213
void configureFroxelGrid(int width, int height, int depth, float nearDistance, float farDistance)
Configure the CPU reference/fallback froxel grid used by the atlas renderer. Quality presets choose s...
Result< FogRayResult > integrate(const AnalyticBeam &beam, const FogProfile &profile, const glm::vec3 &origin, const glm::vec3 &direction, float sceneDepth, int segments, float mediumDensity) const
Integrate the beam contribution along a view ray.
Cached light-path transmittance used by Fast / Enhanced quality tiers.
Result< void > rebuild(const FogDensityField &field, const FogProfile &profile, const glm::vec3 &lightDir, const glm::vec3 &lightColor, float intensity, int samplesPerCell=6)
Rebuild transmittance along the primary light for each density cell.
bool matches(std::uint64_t densityRevision, const glm::vec3 &lightDir, float intensity) const noexcept
True when the cache matches the supplied state.
void invalidate()
Mark cache stale (quality change, light cut, etc.).
float sampleTransmittance(const FogDensityField &field, const glm::vec3 &world) const noexcept
Sample cached transmittance at a world position (1 = fully lit).
World-space density bands, curl assist velocity, and lighting helpers.
const FogWorldBounds & bounds() const noexcept
Result< void > seedHeightBand(float baseDensity, float baseHeight, float falloff, float curlScale, std::uint32_t seed)
Seed a height-banded density layer with optional curl noise.
Result< void > resize(int width, int height, int depth, const FogWorldBounds &bounds)
Allocate a regular lattice over world bounds.
std::uint64_t revision() const noexcept
Result< void > integrate(AtmosphereVolume &volume, const FogDensityField &field, const FogProfile &profile, const glm::mat4 &invViewProj, const glm::vec3 &lightDir, const glm::vec3 &lightColor, float intensity, const BeerLightCache *beerCache)
Integrate froxels with optional Beer-cache visibility.
Result< int > inject(AtmosphereVolume &volume, const FogDensityField &field, const FogProfile &profile, const glm::mat4 &invViewProj, bool occupancySkip)
Inject density-field media into an AtmosphereVolume froxel grid.
Unit-density optical profile for participating media.
Definition FogProfile.h:16
float extinctionAt(float density) const noexcept
Extinction for a sampled density value.
glm::vec3 ambientRadiance(const glm::vec3 &skyUp, const glm::vec3 &groundDown, float density) const noexcept
Ambient term using up/down visibility and AO.
float phase(float cosTheta) const noexcept
Dual-lobe Henyey–Greenstein phase evaluated for cosθ.
glm::vec3 scatteringAt(float density) const noexcept
Scattering coefficient σ_s = albedo * σ_t.
static std::optional< FogRayInterval > intersectBound(const glm::vec3 &origin, const glm::vec3 &direction, const FogVolumeBound &bound)
Intersect a ray with a volume bound; returns empty when misses.
Result< FogRayResult > integrate(const FogDensityField &field, const FogProfile &profile, const glm::vec3 &origin, const glm::vec3 &direction, const FogVolumeBound &bound, const glm::vec3 &lightDir, const glm::vec3 &lightColor, float lightIntensity, const glm::vec3 &skyAmbient, const glm::vec3 &groundAmbient, int sampleCount, float sceneDepth, const BeerLightCache *beerCache, bool useAnalyticSegments) const
Integrate one view ray through the density field.
Result< int > injectToFroxel(AtmosphereVolume &volume, const glm::mat4 &invViewProj)
Add MAC density into an existing froxel grid without clearing or integrating.
Result< std::vector< DustParticle > > generateDust(int count, float turbulenceMeters, std::uint32_t seed=7u) const
Generate procedural dust for the simulation bounds.
Result< void > setQuality(FogQuality quality)
Select Fast / Enhanced / PhysicalReference and invalidate caches.
Result< FogRayResult > integrateBeam(const AnalyticBeam &beam, const glm::vec3 &origin, const glm::vec3 &direction, float sceneDepth, float mediumDensity) const
Analytic beam integration using the active quality segment count.
FogQuality quality() const noexcept
Quality.
Definition FogSystem.h:49
Result< FogRayResult > marchRay(const glm::vec3 &origin, const glm::vec3 &direction, const FogVolumeBound &bound, const glm::vec3 &lightDir, const glm::vec3 &lightColor, float lightIntensity, const glm::vec3 &skyAmbient, const glm::vec3 &groundAmbient, float sceneDepth) const
World-space ray march through the live density field.
Result< int > renderToFroxel(AtmosphereVolume &volume, const glm::mat4 &invViewProj, const glm::vec3 &lightDir, const glm::vec3 &lightColor, float intensity)
Inject + integrate the density field into a froxel AtmosphereVolume.
Result< int > syncToVolumetric(Volumetric *volumetric, const glm::vec3 &lightDir, const glm::vec3 &lightColor, float intensity)
Map the live density field into a Volumetric froxel grid and integrate lighting. Resizes the atlas to...
FogQualityBudget budget() const noexcept
Budget.
Definition FogSystem.h:51
ContinuousArtOutput stylize(const FogRayResult &physical, float viewZ, float neighborOpacity=0.f) const noexcept
Apply ContinuousArt to a physical ray result.
Result< int > injectToVolumetric(Volumetric *volumetric)
Additive MAC inject into a Volumetric that already holds height fog / volumes. Does not resize,...
Result< void > configureDomain(int simWidth, int simHeight, int simDepth, const FogWorldBounds &bounds, float fixedDt=1.f/60.f)
Allocate density + MAC over world bounds at the quality froxel-ish resolution. Simulation resolution ...
Result< void > seedHeightFog(float baseDensity, float baseHeight, float falloff, float curlScale, std::uint32_t seed=1u)
Seed a height-banded fog volume.
Result< FogCflReport > stepSimulation(float dt)
Advance wind + MAC fluid by wall-clock dt (fixed substeps inside).
Result< void > ensureBeerCache(const glm::vec3 &lightDir, const glm::vec3 &lightColor, float intensity)
Refresh BeerLightCache when quality/light/density require it.
Result< void > configure(const FogDensityField &field, float fixedDt=kDefaultFixedDt)
Allocate MAC arrays matching a density field lattice.
Result< void > pullDensity(const FogDensityField &field)
Copy concentration from a density field (same resolution).
Result< void > pushDensity(FogDensityField &field) const
Write concentration back into a density field.
Result< FogCflReport > step(float dt, SceneWind &wind, FogInteractor *interactor, float simTime)
Advance simulation by wall-clock dt using fixed substeps.
Result< std::vector< DustParticle > > generate(const FogWorldBounds &volume, int count, float timeSeconds, float turbulenceMeters, std::uint32_t seed) const
Generate dust inside an AABB for the current view time.
FogQualityBudget budgetFor(FogQuality quality) noexcept
Resolve the budget for a quality preset.
Definition FogTypes.h:52
FogQuality
Tracking / cache / skip budget for the realtime fog pipeline.
Definition FogTypes.h:13
@ PhysicalReference
Dense tracking, no skip shortcuts.
Analytic beam volume: capped cone frustum or pyramidal spot.
Stylized fog presentation derived from a physical FogRayResult.
Definition FogTypes.h:169
Interval along a ray where media is present (t in world units).
Definition FogTypes.h:112
Optical result of integrating one view ray through fog.
Definition FogTypes.h:122
Analytic volume used to bound a camera ray before sampling.
Definition FogRayMarch.h:17
Axis-aligned world bounds for a fog simulation domain.
Definition FogTypes.h:96
glm::vec3 size() const noexcept
Returns the size of .
Definition FogTypes.h:101
glm::vec4 lightColor
glm::vec4 ambient
glm::vec4 lightDir
glm::mat4 invViewProj
glm::vec4 bounds