载入中...
搜索中...
未找到
OceanWake.cpp
浏览该文件的文档.
1#include "fluids/OceanWake.h"
5
6#include <algorithm>
7#include <atomic>
8#include <cmath>
9#include <cstdint>
10#include <limits>
11
12namespace eve::fluids {
15 double time = 0.0;
16 std::uint64_t identity = 0, revision = 0;
17 std::vector<double> height, velocity, foam;
18};
19namespace {
20std::atomic<std::uint64_t> nextWakeIdentity{1};
21bool finite(glm::dvec2 p) { return std::isfinite(p.x) && std::isfinite(p.y) && glm::length(p) <= 1e9; }
22template <class T>
24 return Result<T>::failure(
25 Diagnostic::error(DiagnosticCode::InvalidArgument, "Invalid ocean wake input", "fluids.ocean.wake"));
26}
27} // namespace
28OceanWake::OceanWake(std::unique_ptr<Impl> impl) : impl_(std::move(impl)) {}
29OceanWake::~OceanWake() = default;
31 if (s.resolution < 8 || s.resolution > 512 || (s.resolution & (s.resolution - 1)) != 0 ||
32 !std::isfinite(s.length) || s.length < 8.0 || s.length > 4096.0 || !std::isfinite(s.depth) || s.depth < 0.1 ||
33 s.depth > 10000.0 || !std::isfinite(s.gravity) || s.gravity <= 0.0 || s.gravity > 100.0 ||
34 !std::isfinite(s.damping) || s.damping < 0.0 || s.damping > 10.0 || !std::isfinite(s.absorptionWidth) ||
35 s.absorptionWidth < 2.0 * s.length / s.resolution || s.absorptionWidth > s.length * 0.4 ||
36 !std::isfinite(s.foamDecay) || s.foamDecay < 0.0 || s.foamDecay > 10.0 || !finite(s.center))
38 auto impl = std::make_unique<Impl>();
39 impl->settings = s;
40 impl->identity = nextWakeIdentity.fetch_add(1, std::memory_order_relaxed);
41 impl->height.resize(s.resolution * s.resolution);
42 impl->velocity.resize(impl->height.size());
43 impl->foam.resize(impl->height.size());
44 return Result<std::unique_ptr<OceanWake>>::success(std::unique_ptr<OceanWake>(new OceanWake(std::move(impl))));
45}
46Result<void> OceanWake::inject(std::span<const OceanWakeImpulse> impulses) {
47 const auto& s = impl_->settings;
48 if (impl_->revision == std::numeric_limits<std::uint64_t>::max() || impulses.size() > 256) return invalid<void>();
49 for (const auto& p : impulses)
50 if (!finite(p.position) || !finite(p.direction) || !std::isfinite(p.radius) ||
51 p.radius < s.length / s.resolution || p.radius > s.length * 0.25 || !std::isfinite(p.velocity) ||
52 std::abs(p.velocity) > 5.0 || !std::isfinite(p.foam) || p.foam < 0.0 || p.foam > 1.0)
53 return invalid<void>();
54 for (unsigned z = 0; z < s.resolution; ++z) {
55 for (unsigned x = 0; x < s.resolution; ++x) {
56 const auto index = z * s.resolution + x;
57 const auto point = s.center + (glm::dvec2(x, z) / double(s.resolution) - 0.5) * s.length;
58 double rate = 0.0, foam = 0.0;
59 for (const auto& p : impulses) {
60 const auto delta = (point - p.position) / p.radius;
61 const double distance2 = glm::dot(delta, delta);
62 if (distance2 > 16.0) continue;
63 const double envelope = std::exp(-0.5 * distance2);
64 const double directionLength = glm::length(p.direction);
65 const double shape = directionLength > 1e-8 ? glm::dot(delta, p.direction / directionLength) : 1.0;
66 rate += p.velocity * envelope * shape;
67 foam += p.foam * envelope;
68 }
69 impl_->velocity[index] = std::clamp(impl_->velocity[index] + rate, -10.0, 10.0);
70 impl_->foam[index] = std::clamp(impl_->foam[index] + foam, 0.0, 1.0);
71 }
72 }
73 ++impl_->revision;
74 return Result<void>::success();
75}
76OceanWakeStep::OceanWakeStep(std::unique_ptr<OceanWake> candidate) : candidate_(std::move(candidate)) {}
79 const OceanSpectrumFrame& water) const {
80 if (impl_->revision == std::numeric_limits<std::uint64_t>::max()) return invalid<std::unique_ptr<OceanWakeStep>>();
81 auto candidate = std::unique_ptr<OceanWake>(new OceanWake(std::make_unique<Impl>(*impl_)));
82 auto prepared = candidate->advance(dt, endTime, water);
83 if (!prepared) return Result<std::unique_ptr<OceanWakeStep>>::failure(prepared.status());
85 std::unique_ptr<OceanWakeStep>(new OceanWakeStep(std::move(candidate))));
86}
88 if (step.consumed_ || step.candidate_->impl_->identity != impl_->identity ||
89 step.candidate_->impl_->revision != impl_->revision)
91 DiagnosticCode::Conflict, "Ocean wake candidate is foreign, consumed or stale", "fluids.ocean.wake"));
92 impl_.swap(step.candidate_->impl_);
93 ++impl_->revision;
94 step.consumed_ = true;
95 return Result<void>::success();
96}
97Result<void> OceanWake::advance(double dt, double endTime, const OceanSpectrumFrame& water) {
98 if (!std::isfinite(dt) || dt <= 0.0 || dt > 1.0 / 30.0 || !std::isfinite(endTime) ||
99 std::abs(endTime - impl_->time - dt) > 1e-8 || endTime > 1e9 || std::abs(water.time() - impl_->time) > 1e-8)
100 return invalid<void>();
101 const auto& s = impl_->settings;
102 const auto n = s.resolution;
103 // Stage transport before mutating any wave state: an inverse-query failure is atomic.
104 std::vector<double> foam(impl_->foam.size(), 0.0);
105 if (std::any_of(impl_->foam.begin(), impl_->foam.end(), [](double f) { return f > 0.0; })) {
106 const double cell = s.length / n;
107 auto coverage = [&](glm::dvec2 point) {
108 const auto uv = (point - s.center) / cell + double(n) * 0.5;
109 if (uv.x <= -1.0 || uv.y <= -1.0 || uv.x >= n || uv.y >= n) return 0.0;
110 const auto base = glm::floor(uv), fraction = uv - base;
111 double result = 0.0;
112 for (int dz = 0; dz < 2; ++dz)
113 for (int dx = 0; dx < 2; ++dx) {
114 const int x = int(base.x) + dx, z = int(base.y) + dz;
115 if (x < 0 || z < 0 || x >= int(n) || z >= int(n)) continue;
116 result += impl_->foam[z * n + x] * (dx ? fraction.x : 1.0 - fraction.x) *
117 (dz ? fraction.y : 1.0 - fraction.y);
118 }
119 return std::clamp(result, 0.0, 1.0);
120 };
121 for (unsigned z = 0; z < n; ++z)
122 for (unsigned x = 0; x < n; ++x) {
123 const auto point = s.center + (glm::dvec2(x, z) - double(n) * 0.5) * cell;
124 auto start = water.sample(point);
125 if (!start) return Result<void>::failure(start.status());
126 const auto v = start.value().velocity;
127 auto midpoint = water.sample(point - glm::dvec2(v.x, v.z) * (dt * 0.5));
128 if (!midpoint) return Result<void>::failure(midpoint.status());
129 const auto m = midpoint.value().velocity;
130 foam[z * n + x] = coverage(point - glm::dvec2(m.x, m.z) * dt);
131 }
132 }
133 std::vector<ocean_detail::Complex> height(impl_->height.begin(), impl_->height.end());
134 std::vector<ocean_detail::Complex> velocity(impl_->velocity.begin(), impl_->velocity.end());
137 for (unsigned z = 0; z < n; ++z) {
138 for (unsigned x = 0; x < n; ++x) {
139 const int ix = x < n / 2 ? int(x) : int(x) - int(n);
140 const int iz = z < n / 2 ? int(z) : int(z) - int(n);
141 const auto i = z * n + x;
142 const double k = std::hypot(double(ix), double(iz)) * ocean_detail::tau / s.length;
143 if (k == 0.0) {
144 height[i] = 0.0;
145 velocity[i] = 0.0;
146 continue;
147 }
148 const double omega = std::sqrt(s.gravity * k * std::tanh(k * s.depth));
149 const double sn = std::sin(omega * dt), cs = std::cos(omega * dt);
150 const auto oldHeight = height[i];
151 height[i] = oldHeight * cs + velocity[i] * (sn / omega);
152 velocity[i] = velocity[i] * cs - oldHeight * (omega * sn);
153 }
154 }
157 for (unsigned z = 0; z < n; ++z) {
158 for (unsigned x = 0; x < n; ++x) {
159 const auto i = z * n + x;
160 const double edge = double(std::min({x, z, n - 1 - x, n - 1 - z})) * s.length / n;
161 const double sponge = std::clamp(1.0 - edge / s.absorptionWidth, 0.0, 1.0);
162 const double decay = std::exp(-(s.damping + 8.0 * sponge * sponge) * dt);
163 impl_->height[i] = std::clamp(height[i].real() * decay, -5.0, 5.0);
164 impl_->velocity[i] = std::clamp(velocity[i].real() * decay, -10.0, 10.0);
165 impl_->foam[i] = foam[i] * std::exp(-(s.foamDecay + 8.0 * sponge * sponge) * dt);
166 }
167 }
168 // White water is produced on steep, elevated faces, then transported and
169 // decayed by the existing foam field. Evaluate after every height is updated
170 // so the result does not depend on grid traversal order. This is a visual
171 // breaking-wave closure for the linear solver, not an overturning-fluid model.
172 const double cell = s.length / n;
173 for (unsigned z = 1; z + 1 < n; ++z) {
174 for (unsigned x = 1; x + 1 < n; ++x) {
175 const auto i = z * n + x;
176 const double slope =
177 std::hypot(impl_->height[i + 1] - impl_->height[i - 1], impl_->height[i + n] - impl_->height[i - n]) /
178 (2.0 * cell);
179 const double steep = std::clamp((slope - 0.035) / 0.10, 0.0, 1.0);
180 const double curvature = (4.0 * impl_->height[i] - impl_->height[i + 1] - impl_->height[i - 1] -
181 impl_->height[i + n] - impl_->height[i - n]) /
182 cell;
183 const double crest = std::clamp(impl_->height[i] / 0.6, 0.0, 1.0) * std::clamp(curvature / 0.10, 0.0, 1.0);
184 const double generated = -std::expm1(-4.0 * steep * steep * crest * dt);
185 impl_->foam[i] += (1.0 - impl_->foam[i]) * generated;
186 }
187 }
188 impl_->time = endTime;
189 return Result<void>::success();
190}
192 if (impl_->revision == std::numeric_limits<std::uint64_t>::max() || !finite(center)) return invalid<void>();
193 auto& s = impl_->settings;
194 const double cell = s.length / s.resolution;
195 const auto shift = glm::round((center - s.center) / cell);
196 const auto oldHeight = impl_->height, oldVelocity = impl_->velocity, oldFoam = impl_->foam;
197 for (unsigned z = 0; z < s.resolution; ++z) {
198 for (unsigned x = 0; x < s.resolution; ++x) {
199 const auto i = z * s.resolution + x;
200 const double ox = x + shift.x, oz = z + shift.y;
201 if (ox >= 0.0 && ox < s.resolution && oz >= 0.0 && oz < s.resolution) {
202 const auto j = unsigned(oz) * s.resolution + unsigned(ox);
203 impl_->height[i] = oldHeight[j];
204 impl_->velocity[i] = oldVelocity[j];
205 impl_->foam[i] = oldFoam[j];
206 } else {
207 impl_->height[i] = 0.0;
208 impl_->velocity[i] = 0.0;
209 impl_->foam[i] = 0.0;
210 }
211 }
212 }
213 s.center += shift * cell;
214 ++impl_->revision;
215 return Result<void>::success();
216}
219 const auto& s = impl_->settings;
220 const auto uv = ((worldXZ - s.center) / s.length + 0.5) * double(s.resolution);
222 if (uv.x < 0.0 || uv.y < 0.0 || uv.x >= s.resolution - 1 || uv.y >= s.resolution - 1)
224 const auto x = int(uv.x), z = int(uv.y);
225 const double fx = uv.x - x, fz = uv.y - z;
228 for (int j = 0; j < 4; ++j) {
229 for (int i = 0; i < 4; ++i) {
230 const int ix = x + i - 1, iz = z + j - 1;
231 if (ix < 0 || iz < 0 || ix >= int(s.resolution) || iz >= int(s.resolution)) continue;
232 const auto index = unsigned(iz) * s.resolution + unsigned(ix);
233 out.height += impl_->height[index] * wx[i] * wz[j];
234 out.velocity += impl_->velocity[index] * wx[i] * wz[j];
235 out.foam += impl_->foam[index] * wx[i] * wz[j];
236 out.gradient += impl_->height[index] * glm::dvec2(dx[i] * wz[j], wx[i] * dz[j]) * (s.resolution / s.length);
237 }
238 }
239 const double cell = s.length / s.resolution;
240 const auto edgeBlend = [&](double coordinate) {
241 const double far = double(s.resolution - 1) - coordinate;
242 const double distance = std::min(coordinate, far) * cell;
243 const double t = std::clamp(distance / s.absorptionWidth, 0.0, 1.0);
244 return glm::dvec2(t * t * (3.0 - 2.0 * t),
245 (coordinate < far ? 1.0 : -1.0) * 6.0 * t * (1.0 - t) / s.absorptionWidth);
246 };
247 const auto bx = edgeBlend(uv.x), bz = edgeBlend(uv.y);
248 const double blend = bx.x * bz.x;
249 out.gradient = out.gradient * blend + out.height * glm::dvec2(bx.y * bz.x, bx.x * bz.y);
250 out.height *= blend;
251 out.velocity *= blend;
252 out.foam = std::clamp(out.foam * blend, 0.0, 1.0);
254}
255double OceanWake::time() const { return impl_->time; }
256OceanWakeSettings OceanWake::settings() const { return impl_->settings; }
257OceanWakeGridView OceanWake::gridView() const { return {impl_->settings, impl_->time, impl_->height, impl_->foam}; }
258} // namespace eve::fluids
double z
double y
double m[16]
double x
Duration start
eve::Duration endTime
const std::string & s
void * impl
float uv
glm::vec4 p[6]
ShaderImageInput shape
glm::vec3 n
Definition Grass.cpp:63
float v
float blend
std::uint32_t height
std::string coverage
Poco::JSON::Object::Ptr result
float distance
glm::dvec2 center
glm::dvec3 dx
glm::dvec3 velocity
glm::dvec3 dz
double dt
ssq::Object water
bool finite
float f
float t
ScriptStructure out
Cell cell
float step
Definition TreeMesh.cpp:451
uint32_t index
double ox
float fraction
glm::vec3 point
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
Immutable spatial projection at one simulation timestamp, independent of its spectrum owner....
Owning, single-use candidate; no source frame, owner pointer or GPU resource is retained....
Definition OceanWake.h:119
OceanWakeStep(const OceanWakeStep &)=delete
EVENGINE_API_DOMAINS ~OceanWakeStep()
Caller-owned wave field with finite-depth gravity dispersion and absorbing boundaries....
Definition OceanWake.h:53
EVENGINE_API_DOMAINS Result< void > recenter(glm::dvec2 center)
Move the window by whole cells, retaining overlapping world-space history.
EVENGINE_API_DOMAINS OceanWakeSettings settings() const
Owning configuration including current window center.
EVENGINE_API_DOMAINS Result< void > commitStep(OceanWakeStep &step)
Publish a prepared candidate by constant-time state swap without allocation.
Definition OceanWake.cpp:87
static EVENGINE_API_DOMAINS Result< std::unique_ptr< OceanWake > > create(const OceanWakeSettings &settings)
Construct a checked field via explicit settings; copies settings and retains no input.
Definition OceanWake.cpp:30
EVENGINE_API_DOMAINS Result< void > inject(std::span< const OceanWakeImpulse > impulses)
Inject a bounded batch of localized disturbances atomically into vertical velocity/foam.
Definition OceanWake.cpp:46
OceanWake(const OceanWake &)=delete
EVENGINE_API_DOMAINS Result< std::unique_ptr< OceanWakeStep > > prepareStep(double dt, double endTime, const OceanSpectrumFrame &water) const
Prepare an owning candidate for one fixed step with exact per-mode dispersion omega² = g*k*tanh(k*dep...
Definition OceanWake.cpp:78
EVENGINE_API_DOMAINS double time() const
Current externally advanced simulation time, initially zero.
EVENGINE_API_DOMAINS OceanWakeGridView gridView() const
Borrow raw height/foam for immediate GPU upload; never retain across mutation or destruction.
EVENGINE_API_DOMAINS Result< OceanWakeSample > sample(glm::dvec2 worldXZ) const
Query a world point; returns zero outside the tile, InvalidArgument for nonfinite inputs.
friend class OceanWakeStep
Definition OceanWake.h:108
EVENGINE_API_DOMAINS ~OceanWake()
std::array< double, 4 > derivatives(double t)
std::array< double, 4 > weights(double t)
void forward2D(std::vector< Complex > &a, unsigned n)
Produce normalized Fourier amplitudes from a validated N by N spatial grid. @cost O(N squared log N) ...
void inverse2D(std::vector< Complex > &a, unsigned n)
Transform a validated N by N grid in place using row/column scratch. @cost O(N squared log N) arithme...
Status invalid(const char *message)
GLSL compute kernels for the GPU surface-flow solver.
Definition FluidTarget.h:12
Call-only borrowed raw grids; owner must remain alive and unmodified during consumption.
Definition OceanWake.h:42
Local world-space height perturbation, world slope and vertical particle speed.
Definition OceanWake.h:35
Local dispersive wave tile, SI units; kept independent of the observing camera.
Definition OceanWake.h:16
std::vector< double > foam
Definition OceanWake.cpp:17
OceanWakeSettings settings
Definition OceanWake.cpp:14
std::vector< double > velocity
Definition OceanWake.cpp:17
std::vector< double > height
Definition OceanWake.cpp:17