载入中...
搜索中...
未找到
OceanGpuSpectrum.cpp
浏览该文件的文档.
2
6#include "fluids/shaders/ocean_evolve_spv.inc"
7#include "fluids/shaders/ocean_fft_spv.inc"
8#include "fluids/shaders/ocean_pack_spv.inc"
10#include "gpgpu/ComputeShader.h"
11#include "gpgpu/Gpgpu.h"
12#include "gpgpu/GpuBuffer.h"
13#include "gpgpu/Sequence.h"
14#include "graphics/Graphics.h"
15
16#include <algorithm>
17#include <array>
18#include <atomic>
19#include <cmath>
20#include <exception>
21#include <limits>
22#include <numbers>
23
24namespace eve::fluids {
25namespace {
26constexpr double tau = 2.0 * std::numbers::pi;
27std::atomic<std::uint64_t> nextOwner{1};
28Diagnostic diagnostic(DiagnosticCode code, const char* message) {
29 return Diagnostic::error(code, message, "fluids.ocean.gpu");
30}
31} // namespace
33 enum class State { Empty, Ready, Failed };
34 struct Band {
35 std::unique_ptr<gpgpu::GpuBuffer> coefficients, ping, pong, packed;
36 };
37 std::shared_ptr<const OceanSpectrumData> data, target;
38 double start = 0.0, duration = 1.0;
39 std::weak_ptr<const void> lifetime;
40 std::unique_ptr<gpgpu::ComputeShader> evolve, fft, pack;
41 std::unique_ptr<gpgpu::Sequence> sequence;
42 std::vector<Band> bands;
43 std::unique_ptr<gpgpu::GpuBuffer> atlas;
45 std::uint64_t owner = nextOwner.fetch_add(1), revision = 0;
46 double anchor = std::numeric_limits<double>::quiet_NaN();
49 void release() {
51 ++revision;
52 sequence.reset();
53 evolve.reset();
54 fft.reset();
55 pack.reset();
56 bands.clear();
57 atlas.reset();
58 }
61 release();
62 }
63};
64OceanGpuSpectrum::OceanGpuSpectrum() : impl_(std::make_unique<Impl>()) {}
69
72 : data_(transition.from_.data_),
73 target_(transition.to_.data_),
74 start_(transition.start_),
75 duration_(transition.duration_),
76 graphics_(graphics),
77 compute_(compute) {}
78
81 if (graphics_.resourceLifetime().expired())
82 return Output::failure(diagnostic(DiagnosticCode::StaleHandle, "Graphics provider retired"));
83 if (graphics_.getBackendName() != "vulkan" || !compute_.isAvailable())
84 return Output::failure(
85 diagnostic(DiagnosticCode::Unsupported, "Ocean FFT requires an available Vulkan compute provider"));
86 std::unique_ptr<OceanGpuSpectrum> result(new OceanGpuSpectrum);
87 auto& state = *result->impl_;
88 state.data = data_;
89 state.target = target_;
90 state.start = start_;
91 state.duration = duration_;
92 state.lifetime = graphics_.resourceLifetime();
93 auto retiring = graphics_.onResourcesRetiring([target = &state]() { target->release(); });
94 if (!retiring) return Output::failure(retiring.status());
95 state.retirement = std::move(retiring.value());
96 try {
97 auto evolve = gpgpu::createComputeShader(
99 if (!evolve) return Output::failure(evolve.status());
100 state.evolve = std::move(evolve.value());
101 auto fft =
103 if (!fft) return Output::failure(fft.status());
104 state.fft = std::move(fft.value());
105 auto pack =
107 if (!pack) return Output::failure(pack.status());
108 state.pack = std::move(pack.value());
109 state.sequence.reset(compute_.newSequence());
110 if (!state.sequence || !state.sequence->isAvailable())
111 return Output::failure(diagnostic(DiagnosticCode::Unsupported, "Ocean GPU command sequence unavailable"));
112 for (const auto& source : data_->bands) {
114 const auto count = source.settings.resolution * source.settings.resolution;
115 band.coefficients.reset(
116 compute_.newBuffer(static_cast<int>(count * 8 * (target_ ? 2 : 1) * sizeof(float))));
117 band.ping.reset(compute_.newBuffer(static_cast<int>(count * 12 * sizeof(float))));
118 band.pong.reset(compute_.newBuffer(static_cast<int>(count * 12 * sizeof(float))));
119 band.packed.reset(compute_.newBuffer(static_cast<int>(count * 6 * sizeof(float))));
120 if (!band.coefficients || !band.ping || !band.pong || !band.packed)
121 return Output::failure(diagnostic(DiagnosticCode::Unsupported, "Ocean GPU allocation unavailable"));
122 state.bands.push_back(std::move(band));
123 auto& layout = state.atlasLayout;
124 layout.width = std::max(layout.width, source.settings.resolution);
125 layout.bands[layout.bandCount++] = {source.settings.resolution, layout.height, source.settings.length};
126 layout.height += source.settings.resolution * 3;
127 }
128 state.atlasLayout.seaLevel = data_->settings.seaLevel;
129 state.atlas.reset(
130 compute_.newBuffer(static_cast<int>(state.atlasLayout.width * state.atlasLayout.height * sizeof(float))));
131 if (!state.atlas)
132 return Output::failure(diagnostic(DiagnosticCode::Unsupported, "Ocean GPU atlas unavailable"));
133 } catch (const std::exception& error) {
134 return Output::failure(diagnostic(DiagnosticCode::Failed, error.what()));
135 }
136 return Output::success(std::move(result));
137}
142
144 using Output = Result<OceanGpuFrameToken>;
145 auto& state = *owner_.impl_;
146 if (state.lifetime.expired() || !state.sequence)
147 return Output::failure(diagnostic(DiagnosticCode::StaleHandle, "Ocean GPU provider retired"));
149 return Output::failure(
150 diagnostic(DiagnosticCode::Failed, "Rebuild the ocean GPU projection after a backend failure"));
151 if (!std::isfinite(time_) || std::abs(time_) > 1e9)
152 return Output::failure(diagnostic(DiagnosticCode::InvalidArgument, "Invalid ocean GPU time"));
153 ++state.revision;
155 // Rebase phase in double once per 16 simulation seconds, around the nearest
156 // anchor. A signed relative time in [-8, 8) halves the worst float phase
157 // error while retaining the same coefficient upload frequency.
158 const double anchor = std::floor((time_ + 8.0) / 16.0) * 16.0;
159 const double u = state.target ? std::clamp((time_ - state.start) / state.duration, 0.0, 1.0) : 0.0;
160 const double weight = u * u * u * (10.0 + u * (-15.0 + 6.0 * u));
161 const double rate = state.target ? 30.0 * u * u * (1.0 - u) * (1.0 - u) / state.duration : 0.0;
162 const double levelDelta = state.target ? state.target->settings.seaLevel - state.data->settings.seaLevel : 0.0;
163 try {
164 auto& sequence = *state.sequence;
165 sequence.begin();
166 for (std::size_t bandIndex = 0; bandIndex < state.bands.size(); ++bandIndex) {
167 const auto& source = state.data->bands[bandIndex];
168 auto& band = state.bands[bandIndex];
169 const unsigned n = source.settings.resolution, count = n * n;
170 const int groups = static_cast<int>((count * 6 + 63) / 64);
171 if (anchor != state.anchor) {
172 std::vector<float> coefficients(count * 8 * (state.target ? 2 : 1));
173 for (unsigned z = 0; z < n; ++z)
174 for (unsigned x = 0; x < n; ++x) {
175 const int ix = x < n / 2 ? int(x) : int(x) - int(n);
176 const int iz = z < n / 2 ? int(z) : int(z) - int(n);
177 const glm::dvec2 k = glm::dvec2(ix, iz) * (tau / source.settings.length);
178 const double omega = std::sqrt(state.data->settings.gravity * glm::length(k));
179 const double advection = glm::dot(k, state.data->settings.current);
180 const unsigned i = z * n + x, opposite = ((n - z) % n) * n + (n - x) % n;
181 // Match CPU phase reduction before multiplication, including very large times.
182 const auto wind = std::polar(1.0, std::remainder(-omega * anchor, tau));
183 const auto flow = std::polar(1.0, std::remainder(-advection * anchor, tau));
184 const auto a = source.coefficients[i] * wind * flow;
185 const auto b = std::conj(source.coefficients[opposite]) * std::conj(wind) * flow;
186 const std::array<double, 8> values{a.real(), a.imag(), b.real(), b.imag(),
187 k.x, k.y, omega, advection};
188 for (unsigned component = 0; component < 8; ++component)
189 coefficients[i * 8 + component] = static_cast<float>(values[component]);
190 if (state.target) {
191 const auto& target = state.target->bands[bandIndex];
192 const auto ta = target.coefficients[i] * wind * flow;
193 const auto tb = std::conj(target.coefficients[opposite]) * std::conj(wind) * flow;
194 const std::array<double, 8> next{ta.real(), ta.imag(), tb.real(), tb.imag(),
195 k.x, k.y, omega, advection};
196 for (unsigned component = 0; component < 8; ++component)
197 coefficients[(count + i) * 8 + component] = static_cast<float>(next[component]);
198 }
199 }
200 sequence.recordUpload(band.coefficients.get(), coefficients.data(),
201 coefficients.size() * sizeof(float));
202 }
203 state.evolve->bindBuffer(0, band.coefficients.get());
204 state.evolve->bindBuffer(1, band.ping.get());
205 state.evolve->setFloat(0, static_cast<float>(n));
206 state.evolve->setFloat(1, static_cast<float>(time_ - anchor));
207 state.evolve->setFloat(2, static_cast<float>(state.data->settings.choppiness));
208 state.evolve->setFloat(3, state.target ? 1.0F : 0.0F);
209 state.evolve->setFloat(4, static_cast<float>(weight));
210 state.evolve->setFloat(5, static_cast<float>(rate));
211 state.evolve->setFloat(6, state.target ? static_cast<float>(state.target->settings.choppiness) : 0.0F);
212 state.evolve->setFloat(7, bandIndex == 0 ? static_cast<float>(levelDelta * rate) : 0.0F);
213 sequence.recordDispatch(state.evolve.get(), groups);
214 auto* sourceBuffer = band.ping.get();
215 auto* destination = band.pong.get();
216 for (unsigned axis = 0; axis < 2; ++axis)
217 for (unsigned width = 2; width <= n; width *= 2) {
218 state.fft->bindBuffer(0, sourceBuffer);
219 state.fft->bindBuffer(1, destination);
220 state.fft->setFloat(0, static_cast<float>(n));
221 state.fft->setFloat(1, static_cast<float>(width));
222 state.fft->setFloat(2, static_cast<float>(axis));
223 sequence.recordDispatch(state.fft.get(), groups);
224 std::swap(sourceBuffer, destination);
225 }
226 state.pack->bindBuffer(0, sourceBuffer);
227 state.pack->bindBuffer(1, band.packed.get());
228 state.pack->bindBuffer(2, state.atlas.get());
229 state.pack->setFloat(0, static_cast<float>(count * 6));
230 state.pack->setFloat(1, static_cast<float>(n));
231 state.pack->setFloat(2, static_cast<float>(state.atlasLayout.width));
232 state.pack->setFloat(3, static_cast<float>(state.atlasLayout.bands[bandIndex].firstRow));
233 sequence.recordDispatch(state.pack.get(), groups);
234 }
235 sequence.submit();
236 if (sequence.getStatus() != gpgpu::SequenceStatus::Complete)
237 return Output::failure(diagnostic(DiagnosticCode::Failed, "Ocean GPU submission did not complete"));
238 } catch (const std::exception& error) {
239 state.anchor = std::numeric_limits<double>::quiet_NaN();
240 return Output::failure(diagnostic(DiagnosticCode::Failed, error.what()));
241 }
242 state.atlasLayout.seaLevel = state.data->settings.seaLevel + weight * levelDelta;
243 state.anchor = anchor;
246 token.owner_ = state.owner;
247 token.revision_ = state.revision;
248 token.time_ = time_;
249 return Output::success(token);
250}
252 const auto& state = *impl_;
253 if (state.lifetime.expired() || state.status != Impl::State::Ready || token.owner_ != state.owner ||
254 token.revision_ != state.revision)
255 return Result<OceanGpuBandView>::failure(diagnostic(DiagnosticCode::StaleHandle, "Ocean GPU frame is stale"));
256 if (index >= state.bands.size())
258 diagnostic(DiagnosticCode::InvalidArgument, "Ocean band index out of range"));
259 const auto& settings = state.data->bands[index].settings;
261 {state.bands[index].packed->residentView(), settings.resolution, settings.length});
262}
264 auto valid = band(token, 0);
265 if (!valid) return Result<OceanGpuAtlasView>::failure(valid.status());
266 auto view = impl_->atlasLayout;
267 view.buffer = impl_->atlas->residentView();
269}
271 const auto& state = *owner_.impl_;
272 auto valid = owner_.band(token_, 0);
273 if (!valid) return Result<OceanSpectrumFrame>::failure(valid.status());
275 result.time_ = token_.time_;
276 result.seaLevel_ = state.atlasLayout.seaLevel;
277 result.current_ = state.data->settings.current;
278 try {
279 for (std::size_t b = 0; b < state.bands.size(); ++b) {
280 const auto& settings = state.data->bands[b].settings;
281 const auto count = settings.resolution * settings.resolution;
282 std::vector<float> values(count * 6);
283 state.bands[b].packed->readFloat32s(values.data(), static_cast<int>(values.size()));
284 if (!std::all_of(values.begin(), values.end(), [](float value) { return std::isfinite(value); }))
286 diagnostic(DiagnosticCode::Failed, "Ocean GPU output contains nonfinite values"));
288 grid.resolution = settings.resolution;
289 grid.length = settings.length;
290 grid.displacement.resize(count);
291 grid.velocity.resize(count);
292 for (unsigned i = 0; i < count; ++i) {
293 grid.displacement[i] = {values[i], values[count + i], values[2 * count + i]};
294 grid.velocity[i] = {values[3 * count + i], values[4 * count + i], values[5 * count + i]};
295 }
296 result.grids_.push_back(std::move(grid));
297 }
298 } catch (const std::exception& error) {
300 }
302}
303} // namespace eve::fluids
double z
double x
LogicalId target
std::string layout
std::string message
DiagnosticCode code
eve::Observer retiring
float u
Definition Grass.cpp:233
glm::vec3 n
Definition Grass.cpp:63
std::uint32_t width
JointPoint2D axis
ActionGuidePack pack
Poco::JSON::Object::Ptr result
bool valid
MeleePoint3 b
Definition MeleeHit.cpp:41
MeleePoint3 a
Definition MeleeHit.cpp:40
float tb
float ta
OceanWakeSettings settings
OceanGpuFrameToken token
OceanSprayView view
uint32_t groups
Definition OnnxGpgpu.cpp:39
std::unique_ptr< gpgpu::Sequence > sequence
Definition OnnxGpgpu.cpp:43
OnnxCompute * compute
std::string error
Definition Package.cpp:174
std::set< std::string > values
Object::Ptr value
Graphics * graphics
std::string_view source
int count
double weight
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
Move-only RAII token that owns one observer registration.
void dispose() noexcept
Cancels this registration; safe to call repeatedly.
Synchronous borrowed submission builder; do not retain across owner destruction.
EVENGINE_API_DOMAINS Result< OceanGpuFrameToken > submit() const
Evolve all six spectral fields and inverse FFT in one command sequence; no CPU readback....
Opaque revision of a completed GPU ocean; copying does not extend resource lifetime.
Borrowed diagnostic readback builder; revision checked again at build, never silently reads a newer f...
EVENGINE_API_DOMAINS Result< OceanSpectrumFrame > build() const
Download a completed projection into an owning CPU frame for parity tests and diagnostics....
EVENGINE_API_DOMAINS Result< std::unique_ptr< OceanGpuSpectrum > > build() const
Allocate compiled pipelines and band buffers; Unsupported explicitly selects a caller-chosen CPU path...
EVENGINE_API_DOMAINS OceanGpuSpectrumBuilder(const OceanSpectrum &spectrum, graphics::Graphics &graphics, gpgpu::Gpgpu &compute)
Graphics must be the active same-device provider used by the injected Gpgpu service.
Render-thread-owned GPU projection of immutable spectral coefficients, with no independent clock....
EVENGINE_API_DOMAINS Result< OceanGpuBandView > band(const OceanGpuFrameToken &token, unsigned index) const
Validate revision and borrow one band for immediate same-device consumption; no allocation.
EVENGINE_API_DOMAINS OceanGpuFrameBuilder frameBuilder(double time)
Prepare a cheap call-only builder; owner must outlive submit().
EVENGINE_API_DOMAINS OceanGpuReadbackBuilder readbackBuilder(const OceanGpuFrameToken &token) const
Prepare explicit diagnostic readback; no readback occurs in normal GPU rendering.
EVENGINE_API_DOMAINS ~OceanGpuSpectrum()
EVENGINE_API_DOMAINS Result< OceanGpuAtlasView > atlas(const OceanGpuFrameToken &token) const
Validate revision and borrow the complete rendering atlas for immediate same-device copying.
Immutable finite sea-state transition; the caller supplies the only simulation clock....
Immutable spatial projection at one simulation timestamp, independent of its spectrum owner....
Immutable initial spectrum; data is shared only with owning frame builders.
GPGPU module — compute shaders + storage buffers via the active Graphics backend. Uses the graphics q...
Definition Gpgpu.h:23
bool isAvailable() const
True when the active Graphics backend can run compute (device initialized).
Definition Gpgpu.cpp:284
GpuBuffer * newBuffer(int byteSize, const std::string &usage="storage")
Allocate a GPU buffer. usage: "storage" (SSBO) | "staging" (host transfer) | "storage_vertex" (Vulkan...
Definition Gpgpu.cpp:372
Sequence * newSequence()
Create a Kompute-style command Sequence: record buffer transfers and compute dispatches into one comm...
Definition Gpgpu.cpp:384
virtual std::string getBackendName() const =0
Renderer backend id used by sibling modules (e.g. Gpgpu).
std::weak_ptr< const void > resourceLifetime() const
Observe this provider's resource lifetime without extending it.
Result< eve::Subscription > onResourcesRetiring(std::function< void()> callback) const
Register cleanup before this provider destroys its GPU device/resources.
eve::Diagnostic Diagnostic
GLSL compute kernels for the GPU surface-flow solver.
Definition FluidTarget.h:12
EVENGINE_API_WORLD Result< std::unique_ptr< ComputeShader > > createComputeShader(const std::vector< uint32_t > &words)
Create an owning compute pipeline from valid SPIR-V produced by compileComputeSpirv.
Definition Gpgpu.cpp:307
DiagnosticCode
Stable machine-readable diagnostic codes.
Definition Diagnostic.h:47
Call-only borrowed packed float atlas; each four RGBA8 bytes preserve one float's bits....
std::unique_ptr< gpgpu::GpuBuffer > ping
std::unique_ptr< gpgpu::GpuBuffer > packed
std::unique_ptr< gpgpu::GpuBuffer > pong
std::unique_ptr< gpgpu::GpuBuffer > coefficients
std::unique_ptr< gpgpu::ComputeShader > fft
std::weak_ptr< const void > lifetime
std::unique_ptr< gpgpu::GpuBuffer > atlas
std::shared_ptr< const OceanSpectrumData > target
std::unique_ptr< gpgpu::ComputeShader > pack
std::unique_ptr< gpgpu::Sequence > sequence
std::unique_ptr< gpgpu::ComputeShader > evolve
std::shared_ptr< const OceanSpectrumData > data
Owning periodic displacement and particle velocity arrays; index = z * resolution + x.