载入中...
搜索中...
未找到
LayeredClothGPU.cpp
浏览该文件的文档.
2#include <algorithm>
3#include <cmath>
4#include <cstdint>
5#include <utility>
6#include "common/Exception.h"
8#include "gpgpu/Gpgpu.h"
9#include "gpgpu/GpuBuffer.h"
10#include "gpgpu/Sequence.h"
11#include "graphics/Graphics.h"
12#include "graphics/Mesh.h"
13#include "physics/cloth/LayeredClothGpuKernel.inc"
14namespace eve::physics {
15namespace {
16void finite3(float x, float y, float z) {
17 if (!std::isfinite(x) || !std::isfinite(y) || !std::isfinite(z))
18 throw Exception("LayeredClothGPU: nonfinite vector");
19}
20} // namespace
24 std::array<std::unique_ptr<gpgpu::GpuBuffer>, 8> buffers;
25 std::unique_ptr<gpgpu::ComputeShader> kernel;
26 std::unique_ptr<gpgpu::Sequence> sequence;
27 graphics::Mesh* mesh = nullptr; // Borrowed Graphics-owned; released during teardown.
28 std::vector<float> initial, adjacency;
29 std::array<float, 32> params{};
30 int count = 0, triangles = 0, buckets = 1, capacity = 0, substeps = 2, iterations = 8;
31 bool contacts = true, self = false, failed = false;
33 void bind() {
34 for (int i = 0; i < 8; ++i) kernel->bindBuffer(i, buffers[static_cast<size_t>(i)].get());
35 for (int i = 0; i < 32; ++i) kernel->setFloat(i, params[static_cast<size_t>(i)]);
36 }
37 void dispatch(int mode, int work, bool swap = false) {
38 kernel->setFloat(7, float(mode));
39 sequence->recordDispatch(kernel.get(), (work + 63) / 64);
40 if (swap) {
41 std::swap(buffers[0], buffers[1]);
42 kernel->bindBuffer(0, buffers[0].get());
43 kernel->bindBuffer(1, buffers[1].get());
44 }
45 }
46 // Packing is also a graphics-queue retirement point. No readback is recorded.
47 void packSubmit() {
48 bind();
49 sequence->begin();
50 dispatch(5, count);
51 sequence->submit();
52 }
54 // Teardown synchronization is resource retirement, not a simulation step.
55 // Providers/device must still be alive (public lifetime contract).
56 try {
57 if (kernel && sequence && buffers[7]) packSubmit();
58 } catch (...) {
59 }
60 if (mesh) {
61 try {
62 if (graphics.releaseMesh(mesh)) delete mesh;
63 } catch (...) {
64 }
65 mesh = nullptr;
66 }
67 sequence.reset();
68 kernel.reset();
69 }
70};
72 float spacing, float gap, float x, float y, float z) {
73 finite3(x, y, z);
74 if (layers < 1 || layers > 8 || cols < 2 || rows < 2 || cols > 128 || rows > 128 || !std::isfinite(spacing) ||
75 spacing <= 0 || !std::isfinite(gap) || gap <= 0 || !std::isfinite(x + float(cols) * spacing) ||
76 !std::isfinite(y + float(layers) * gap) || !std::isfinite(z + float(rows) * spacing))
77 throw Exception("LayeredClothGPU: invalid grid or coordinates");
78 if (!compute.isAvailable()) throw Exception("LayeredClothGPU: Vulkan compute is unavailable");
79 auto p = std::make_unique<Impl>(compute, graphics);
80 p->count = layers * cols * rows;
81 p->triangles = layers * (cols - 1) * (rows - 1) * 2;
82 while (p->buckets < p->count * 2) p->buckets *= 2;
83 p->capacity = (p->count + p->triangles) * 32;
84 const std::array<int, 8> bytes = {
85 p->count * 16, p->count * 16, p->count * 16, p->count * 12 * 16, p->buckets * 4, p->capacity * 32, 32,
86 p->count * 2 * 88};
87 // Refuse huge per-buffer allocations before touching the device.
88 for (int size : bytes)
89 if (size > 128 * 1024 * 1024) throw Exception("LayeredClothGPU: grid exceeds resident budget");
90 for (int i = 0; i < 8; ++i)
91 p->buffers[size_t(i)].reset(compute.newBuffer(bytes[size_t(i)], i == 7 ? "storage_vertex" : "storage"));
92 if (p->buffers[7]->residentView().backend != GpuResidentBackend::Vulkan)
93 throw Exception("LayeredClothGPU: resident drawing requires Vulkan");
94 p->kernel.reset(compute.newShader(detail::layeredClothKernel));
95 p->sequence.reset(compute.newSequence());
96 p->initial.resize(size_t(p->count) * 4);
97 p->adjacency.assign(size_t(p->count) * 12 * 4, 0.f);
98 std::vector<float> positions(size_t(p->count) * 2 * 3, 0.f);
99 std::vector<uint32_t> indices;
100 const int dr[12] = {0, 0, 1, -1, 1, 1, -1, -1, 0, 0, 2, -2};
101 const int dc[12] = {1, -1, 0, 0, 1, -1, 1, -1, 2, -2, 0, 0};
102 for (int l = 0; l < layers; ++l)
103 for (int r = 0; r < rows; ++r)
104 for (int c = 0; c < cols; ++c) {
105 int i = (l * rows + r) * cols + c;
106 size_t base = size_t(i) * 4;
107 p->initial[base] = x + float(c) * spacing;
108 p->initial[base + 1] = y + float(l) * gap;
109 p->initial[base + 2] = z + float(r) * spacing;
110 p->initial[base + 3] = r == 0 ? 0.f : 1.f;
111 for (int side = 0; side < 2; ++side)
112 for (int k = 0; k < 3; ++k)
113 positions[size_t(i + side * p->count) * 3 + size_t(k)] = p->initial[base + size_t(k)];
114 for (int k = 0; k < 12; ++k) {
115 int rr = r + dr[k], cc = c + dc[k];
116 size_t edge = (size_t(i) * 12 + size_t(k)) * 4;
117 p->adjacency[edge] = -1;
118 if (rr < 0 || cc < 0 || rr >= rows || cc >= cols) continue;
119 p->adjacency[edge] = float((l * rows + rr) * cols + cc);
120 p->adjacency[edge + 1] = spacing * std::sqrt(float(dr[k] * dr[k] + dc[k] * dc[k]));
121 p->adjacency[edge + 2] = k < 8 ? 1e-7f : 1e-4f;
122 }
123 if (r + 1 < rows && c + 1 < cols)
124 for (const auto& tri :
125 {std::array<int, 3>{i, i + cols, i + 1}, std::array<int, 3>{i + cols, i + cols + 1, i + 1}}) {
126 for (int v : tri) indices.push_back(uint32_t(v));
127 for (auto it = tri.rbegin(); it != tri.rend(); ++it)
128 indices.push_back(uint32_t(*it + p->count));
129 }
130 }
131 p->mesh = graphics.newMeshFromArrays(positions.data(), nullptr, nullptr, p->count * 2, indices.data(),
132 int(indices.size()));
133 p->params[1] = float(p->count);
134 p->params[2] = float(cols);
135 p->params[3] = float(rows);
136 p->params[4] = float(layers);
137 p->params[5] = spacing;
138 p->params[6] = std::min(gap * 0.8f, spacing * 0.3f);
139 p->params[10] = -9.8f;
140 p->params[15] = 0.005f;
141 p->params[17] = 0.2f;
142 p->params[19] = float(p->buckets);
143 p->params[20] = float(p->capacity);
144 p->params[21] = float(p->triangles);
145 p->params[22] = 1;
146 p->params[23] = 0.2f;
147 p->params[24] = spacing * 2;
148 p->params[27] = -3;
149 impl_ = std::move(p);
150 reset();
151}
154 auto& p = *impl_;
155 p.bind();
156 p.sequence->begin();
157 for (int i = 0; i < 3; ++i)
158 p.sequence->recordUpload(p.buffers[size_t(i)].get(), p.initial.data(), p.initial.size() * 4);
159 p.sequence->recordUpload(p.buffers[3].get(), p.adjacency.data(), p.adjacency.size() * 4);
160 const std::array<unsigned, 8> zeros{};
161 p.sequence->recordUpload(p.buffers[6].get(), zeros.data(), 32);
162 p.dispatch(5, p.count);
163 p.sequence->submit();
164 p.failed = false;
165}
167 auto& p = *impl_;
168 if (!std::isfinite(dt) || dt < 0 || dt > 0.05f || (dt > 0 && dt < 1e-6f))
170 DiagnosticCode::InvalidArgument, "dt must be zero or finite in [1e-6,0.05]", "physics.layeredGpu.update"));
171 if (p.failed)
173 "GPU solver requires reset after failure",
174 "physics.layeredGpu.update"));
175 if (dt == 0) return Result<void>::success();
176 try {
177 p.params[0] = dt / float(p.substeps);
178 p.params[18] = p.self ? 1.f : 0.f;
179 p.bind();
180 p.sequence->begin();
181 p.kernel->setFloat(26, 1.f);
182 p.dispatch(2, p.buckets);
183 p.kernel->setFloat(26, 0.f);
184 for (int s = 0; s < p.substeps; ++s) {
185 p.dispatch(0, p.count, true);
186 for (int it = 0; it < p.iterations; ++it) {
187 p.dispatch(1, p.count, true);
188 if (p.contacts || p.self) {
189 // contact() distinguishes self/inter through this parameter.
190 p.kernel->setFloat(16, p.contacts ? 1.f : 0.f);
191 p.kernel->setFloat(26, 0.f);
192 p.dispatch(2, p.buckets);
193 p.dispatch(3, std::max(p.count, p.triangles));
194 p.dispatch(6, p.count);
195 p.dispatch(4, p.count, true);
196 }
197 }
198 }
199 p.dispatch(5, p.count);
200 p.sequence->submit();
201 return Result<void>::success();
202 } catch (const std::exception& e) {
203 p.failed = true;
204 return Result<void>::failure(Diagnostic::error(DiagnosticCode::Failed, e.what(), "physics.layeredGpu.update"));
205 }
206}
208 auto& p = *impl_;
209 if (p.failed)
211 "GPU solver requires reset after failure",
212 "physics.layeredGpu.draw"));
213 auto view = p.buffers[7]->residentView();
214 view.strideBytes = 88;
215 return p.graphics.drawMeshResidentVertices(*p.mesh, view);
216}
217void LayeredClothGPU::setSolver(int substeps, int iterations) {
218 if (substeps < 1 || substeps > 16 || iterations < 1 || iterations > 64)
219 throw Exception("LayeredClothGPU: invalid solver budget");
220 impl_->substeps = substeps;
221 impl_->iterations = iterations;
222}
223void LayeredClothGPU::setGravity(float x, float y, float z) {
224 finite3(x, y, z);
225 impl_->params[9] = x;
226 impl_->params[10] = y;
227 impl_->params[11] = z;
228}
229void LayeredClothGPU::setWind(float x, float y, float z) {
230 finite3(x, y, z);
231 impl_->params[12] = x;
232 impl_->params[13] = y;
233 impl_->params[14] = z;
234}
235void LayeredClothGPU::setInterCollision(bool on) { impl_->contacts = on; }
236void LayeredClothGPU::setSelfCollision(bool on) { impl_->self = on; }
238 if (!std::isfinite(thickness) || thickness <= 0 || !std::isfinite(friction) || friction < 0 || friction > 1)
239 throw Exception("LayeredClothGPU: invalid contact material");
240 impl_->params[6] = thickness;
241 impl_->params[17] = friction;
242}
244 if (!std::isfinite(y)) throw Exception("LayeredClothGPU: invalid floor");
245 impl_->params[27] = y;
246}
248 auto& p = *impl_;
249 if (index < 0 || index >= p.count || !std::isfinite(mass) || mass < 0)
250 throw Exception("LayeredClothGPU: invalid particle mass");
251 p.bind();
252 p.sequence->begin();
253 p.sequence->recordUpload(p.buffers[2].get(), &mass, 4, uint64_t(index) * 16 + 12);
254 p.dispatch(5, p.count);
255 p.sequence->submit();
256}
257int LayeredClothGPU::getParticleCount() const { return impl_->count; }
258std::vector<float> LayeredClothGPU::readPositions() {
259 auto& p = *impl_;
260 auto staging = std::unique_ptr<gpgpu::GpuBuffer>(p.compute.newBuffer(p.count * 16, "staging"));
261 p.bind();
262 p.sequence->begin();
263 p.dispatch(5, p.count);
264 p.sequence->recordDownload(p.buffers[0].get(), staging.get(), uint64_t(p.count) * 16);
265 p.sequence->submit();
266 std::vector<float> result(size_t(p.count) * 4);
267 staging->downloadBytes(result.data(), result.size() * 4);
268 return result;
269}
270std::array<unsigned, 4> LayeredClothGPU::readDiagnostics() {
271 auto& p = *impl_;
272 auto staging = std::unique_ptr<gpgpu::GpuBuffer>(p.compute.newBuffer(16, "staging"));
273 p.bind();
274 p.sequence->begin();
275 p.dispatch(5, p.count);
276 p.sequence->recordDownload(p.buffers[6].get(), staging.get(), 16);
277 p.sequence->submit();
278 std::array<unsigned, 4> result{};
279 staging->downloadBytes(result.data(), 16);
280 return result;
281}
282} // namespace eve::physics
double z
double y
double x
const std::string & s
float gap
glm::vec4 p[6]
int rows
int cols
float friction
tensor::Graph g
Definition GpuGraph.cpp:7
double r
std::vector< std::uint32_t > indices
std::vector< float > positions
float v
std::int32_t c
float thickness
Poco::JSON::Object::Ptr result
std::uint64_t bytes
double dt
OceanSprayView view
std::vector< int64_t > zeros
OnnxCompute * compute
Graphics * graphics
int spacing
int iterations
Definition TreeMesh.cpp:448
float size
Definition TreeMesh.cpp:158
uint32_t index
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
GPGPU module — compute shaders + storage buffers via the active Graphics backend. Uses the graphics q...
Definition Gpgpu.h:23
virtual bool releaseMesh(Mesh *mesh)
Eagerly releases a mesh created by this Graphics.
Definition Graphics.h:935
GPU mesh handle (+ optional CPU morph targets).
Definition Mesh.h:26
void setGravity(float x, float y, float z)
Set finite world gravity; throws on invalid input.
std::array< unsigned, 4 > readDiagnostics()
Explicit readback: hash references attempted, last overflow flag, contact projections,...
void setWind(float x, float y, float z)
Set finite uniform wind acceleration; not triangle aerodynamics.
LayeredClothGPU(gpgpu::Gpgpu &compute, graphics::Graphics &graphics, int layers, int cols, int rows, float spacing, float gap, float x, float y, float z)
Allocate grids, bake adjacency and compile compute; throws on invalid input or unavailable backend.
void setSolver(int substeps, int iterations)
Set substeps [1,16], iterations [1,64]; throws before mutation on invalid budget.
Result< void > draw()
Record direct resident-buffer drawing inside an open 3D pass; no host vertex transfer.
void setParticleInverseMass(int index, float inverseMass)
Change one particle's inverse mass, effective on the next update; zero pins. @cost One tiny upload pl...
void setContact(float thickness, float friction)
Set separation >0, friction [0,1]; throws on nonfinite/out-of-range input.
void reset()
Restore initial pinned pose and material/particle overrides; synchronously uploads once....
Result< void > update(float dt)
Execute finite dt in [1e-6,0.05] on GPU; zero is a no-op. Input failure leaves state unchanged.
int getParticleCount() const
Return total simulation particles (render stream duplicates each for two sides).
~LayeredClothGPU()
Wait for resident draw retirement and release compute resources; never throws.
void setSelfCollision(bool enabled)
Enable nonlocal point-face and edge-edge contact within each sheet.
std::vector< float > readPositions()
Explicit diagnostic readback, XYZW per particle; W is inverse mass. @cost Full state download plus GP...
void setInterCollision(bool enabled)
Enable inter-layer point-face and edge-edge contact, independently of self contact.
void setFloor(float y)
Set finite floor height, default -3 metres.
Optional physics backend for vehicle mobility and body attach.
Definition Climbing.h:36
std::array< std::unique_ptr< gpgpu::GpuBuffer >, 8 > buffers
void dispatch(int mode, int work, bool swap=false)
std::unique_ptr< gpgpu::ComputeShader > kernel
Impl(gpgpu::Gpgpu &c, graphics::Graphics &g)
std::unique_ptr< gpgpu::Sequence > sequence