载入中...
搜索中...
未找到
Guides.cpp
浏览该文件的文档.
2#include <algorithm>
3#include <cmath>
4#include <cstddef>
5#include <glm/geometric.hpp>
6#include <limits>
7#include <utility>
8#include "common/Diagnostic.h"
10
11// Guides.cpp
12namespace eve::graphics::hair {
13namespace {
14
15glm::vec3 rootOf(const StrandsDatas &datas, size_t curveIndex) {
16 const auto pts = datas.curvePoints(curveIndex);
17 return pts.empty() ? glm::vec3(0.f) : pts[0].position;
18}
19
20glm::vec3 sampleCurveAtU(const StrandsDatas &datas, size_t curveIndex, float u) {
21 const auto pts = datas.curvePoints(curveIndex);
22 if (pts.empty()) return {};
23 if (pts.size() == 1) return pts[0].position;
24 const float t = std::clamp(u, 0.f, 1.f);
25 // Prefer explicit per-point u; fall back to index parameterization.
26 size_t i1 = 1;
27 while (i1 + 1 < pts.size() && pts[i1].u < t) ++i1;
28 const size_t i0 = i1 - 1;
29 const float u0 = pts[i0].u;
30 const float u1 = pts[i1].u;
31 float alpha = 0.f;
32 if (std::fabs(u1 - u0) > 1e-8f) {
33 alpha = (t - u0) / (u1 - u0);
34 } else {
35 alpha = float(i1 - i0) > 0.f ? 1.f : 0.f;
36 }
37 alpha = std::clamp(alpha, 0.f, 1.f);
38 return pts[i0].position * (1.f - alpha) + pts[i1].position * alpha;
39}
40
41float weightExponent(InterpolationMode mode) {
42 switch (mode) {
43 case InterpolationMode::Rigid: return 4.f; // strongly prefer nearest guide
44 case InterpolationMode::Smooth: return 1.f;
46 default: return 2.f;
47 }
48}
49
50} // namespace
51
53 auto ok = strands.validate();
54 if (!ok.ok()) return Result<StrandsDatas>::failure(ok.status());
55 if (strands.curveCount() == 0) {
57 Diagnostic::error(DiagnosticCode::InvalidArgument, "extractGuides: empty strands", "hair.guides"));
58 }
59
60 const float frac = std::clamp(guideFraction, 0.01f, 1.f);
61 const size_t keep = std::max<size_t>(1, size_t(std::ceil(double(strands.curveCount()) * double(frac))));
62 const size_t step = std::max<size_t>(1, strands.curveCount() / keep);
63
64 std::vector<StrandPoint> points;
65 std::vector<StrandCurve> curves;
66 points.reserve(strands.pointCount());
67 curves.reserve(keep);
68
69 for (size_t ci = 0; ci < strands.curveCount() && curves.size() < keep; ci += step) {
70 const auto pts = strands.curvePoints(ci);
71 if (pts.size() < 2) continue;
73 curve.pointOffset = uint32_t(points.size());
74 curve.pointCount = uint32_t(pts.size());
75 float len = 0.f;
76 for (size_t pi = 0; pi < pts.size(); ++pi) {
77 points.push_back(pts[pi]);
78 if (pi > 0) len += glm::length(pts[pi].position - pts[pi - 1].position);
79 }
80 curve.length = len;
81 curves.push_back(curve);
82 }
83
84 if (curves.empty()) {
86 Diagnostic::error(DiagnosticCode::Failed, "extractGuides: no usable curves", "hair.guides"));
87 }
88
90 out.setPoints(std::move(points));
91 out.setCurves(std::move(curves));
92 auto valid = out.validate();
93 if (!valid.ok()) return Result<StrandsDatas>::failure(valid.status());
94 return Result<StrandsDatas>::success(std::move(out));
95}
96
98 int maxInfluences, InterpolationMode mode) {
99 auto sOk = strands.validate();
100 if (!sOk.ok()) return Result<std::vector<StrandGuideWeights>>::failure(sOk.status());
101 auto gOk = guides.validate();
102 if (!gOk.ok()) return Result<std::vector<StrandGuideWeights>>::failure(gOk.status());
103 if (guides.curveCount() == 0) {
105 Diagnostic::error(DiagnosticCode::InvalidArgument, "buildGuideWeights: no guides", "hair.guides"));
106 }
107
108 const int k = std::clamp(maxInfluences, 1, StrandGuideWeights::kMaxInfluences);
109 const float exp = weightExponent(mode);
110 std::vector<StrandGuideWeights> out(strands.curveCount());
111
112 for (size_t si = 0; si < strands.curveCount(); ++si) {
113 const glm::vec3 root = rootOf(strands, si);
114 struct Cand {
115 uint32_t index;
116 float dist2;
117 };
118 std::vector<Cand> cands;
119 cands.reserve(guides.curveCount());
120 for (size_t gi = 0; gi < guides.curveCount(); ++gi) {
121 const glm::vec3 d = rootOf(guides, gi) - root;
122 cands.push_back({uint32_t(gi), glm::dot(d, d)});
123 }
124 const size_t take = std::min(size_t(k), cands.size());
125 std::partial_sort(cands.begin(), cands.begin() + std::ptrdiff_t(take), cands.end(),
126 [](const Cand &a, const Cand &b) { return a.dist2 < b.dist2; });
127
129 float wSum = 0.f;
130 for (size_t i = 0; i < take; ++i) {
131 const float dist = std::sqrt(std::max(cands[i].dist2, 0.f));
132 const float w = 1.f / std::pow(std::max(dist, 1e-4f), exp);
133 row.influencers[row.count] = {cands[i].index, w};
134 wSum += w;
135 ++row.count;
136 }
137 if (wSum > 0.f) {
138 for (int i = 0; i < row.count; ++i) row.influencers[i].weight /= wSum;
139 } else if (row.count > 0) {
140 row.influencers[0].weight = 1.f;
141 for (int i = 1; i < row.count; ++i) row.influencers[i].weight = 0.f;
142 }
143 out[si] = row;
144 }
145 return Result<std::vector<StrandGuideWeights>>::success(std::move(out));
146}
147
149 const StrandsDatas &guidesDeformed,
150 const std::vector<StrandGuideWeights> &weights, InterpolationMode mode) {
151 auto sOk = strandsRest.validate();
152 if (!sOk.ok()) return Result<StrandsDatas>::failure(sOk.status());
153 auto g0 = guidesRest.validate();
154 if (!g0.ok()) return Result<StrandsDatas>::failure(g0.status());
155 auto g1 = guidesDeformed.validate();
156 if (!g1.ok()) return Result<StrandsDatas>::failure(g1.status());
157 if (guidesRest.curveCount() != guidesDeformed.curveCount()) {
160 "interpolateStrands: guide rest/deformed curve count mismatch", "hair.guides"));
161 }
162 if (weights.size() != strandsRest.curveCount()) {
164 DiagnosticCode::InvariantViolation, "interpolateStrands: weights size mismatch", "hair.guides.weights"));
165 }
166
167 std::vector<StrandPoint> points(strandsRest.points().begin(), strandsRest.points().end());
168 std::vector<StrandCurve> curves(strandsRest.curves().begin(), strandsRest.curves().end());
169
170 for (size_t si = 0; si < strandsRest.curveCount(); ++si) {
171 const StrandCurve &curve = curves[si];
172 const StrandGuideWeights &row = weights[si];
173 if (curve.pointCount == 0 || row.count <= 0) continue;
174
175 if (mode == InterpolationMode::Rigid) {
176 glm::vec3 delta(0.f);
177 for (int i = 0; i < row.count; ++i) {
178 const auto &inf = row.influencers[i];
179 const glm::vec3 rest = rootOf(guidesRest, inf.guideIndex);
180 const glm::vec3 def = rootOf(guidesDeformed, inf.guideIndex);
181 delta += (def - rest) * inf.weight;
182 }
183 for (uint32_t pi = 0; pi < curve.pointCount; ++pi) {
184 points[curve.pointOffset + pi].position += delta;
185 }
186 continue;
187 }
188
189 // Offset / Smooth: per-point guide deltas at matching u.
190 for (uint32_t pi = 0; pi < curve.pointCount; ++pi) {
191 StrandPoint &pt = points[curve.pointOffset + pi];
192 glm::vec3 delta(0.f);
193 for (int i = 0; i < row.count; ++i) {
194 const auto &inf = row.influencers[i];
195 const glm::vec3 restP = sampleCurveAtU(guidesRest, inf.guideIndex, pt.u);
196 const glm::vec3 defP = sampleCurveAtU(guidesDeformed, inf.guideIndex, pt.u);
197 delta += (defP - restP) * inf.weight;
198 }
199 pt.position += delta;
200 }
201 }
202
204 out.setPoints(std::move(points));
205 out.setCurves(std::move(curves));
206 auto valid = out.validate();
207 if (!valid.ok()) return Result<StrandsDatas>::failure(valid.status());
208 return Result<StrandsDatas>::success(std::move(out));
209}
210
211} // namespace eve::graphics::hair
212
213// Simulation.cpp
214namespace eve::graphics::hair {
215namespace {
216
217constexpr float kEpsilon = 1e-8f;
218
219} // namespace
220
222 auto ok = guides.validate();
223 if (!ok.ok()) return Result<void>::failure(ok.status());
224 if (guides.curveCount() == 0) {
226 "GuideSimulator::reset: empty guides", "hair.sim.guides"));
227 }
228
229 params_ = params;
230 params_.damping = std::clamp(params_.damping, 0.f, 1.f);
231 params_.iterations = std::clamp(params_.iterations, 1, 16);
232 params_.compliance = std::max(0.f, params_.compliance);
233 params_.maxDt = std::max(1e-4f, params_.maxDt);
234
235 restPoints_.assign(guides.points().begin(), guides.points().end());
236 curves_.clear();
237 curves_.reserve(guides.curveCount());
238 segments_.clear();
239 pos_.clear();
240 prev_.clear();
241 pinned_.clear();
242
243 pos_.reserve(guides.pointCount());
244 prev_.reserve(guides.pointCount());
245 pinned_.reserve(guides.pointCount());
246
247 for (size_t ci = 0; ci < guides.curveCount(); ++ci) {
248 const auto pts = guides.curvePoints(ci);
249 if (pts.size() < 2) {
251 "GuideSimulator::reset: guide curve needs >= 2 points",
252 "hair.sim.curve"));
253 }
254 CurveSpan span;
255 span.pointOffset = uint32_t(pos_.size());
256 span.pointCount = uint32_t(pts.size());
257 float len = 0.f;
258 for (size_t pi = 0; pi < pts.size(); ++pi) {
259 const glm::vec3 p = pts[pi].position;
260 pos_.push_back(p);
261 prev_.push_back(p);
262 pinned_.push_back(pi == 0 ? uint8_t(1) : uint8_t(0));
263 if (pi > 0) {
264 const float seg = glm::length(pts[pi].position - pts[pi - 1].position);
265 len += seg;
266 Segment s;
267 s.i0 = span.pointOffset + uint32_t(pi - 1);
268 s.i1 = span.pointOffset + uint32_t(pi);
269 s.restLength = std::max(seg, kEpsilon);
270 segments_.push_back(s);
271 }
272 }
273 span.length = len;
274 curves_.push_back(span);
275 }
276
277 return Result<void>::success();
278}
279
281 restPoints_.clear();
282 curves_.clear();
283 segments_.clear();
284 pos_.clear();
285 prev_.clear();
286 pinned_.clear();
287}
288
290 params_ = params;
291 params_.damping = std::clamp(params_.damping, 0.f, 1.f);
292 params_.iterations = std::clamp(params_.iterations, 1, 16);
293 params_.compliance = std::max(0.f, params_.compliance);
294 params_.maxDt = std::max(1e-4f, params_.maxDt);
295}
296
297Result<void> GuideSimulator::setPinnedRoots(const float *rootPositionsXYZ, int rootCount) {
298 if (!isReady()) {
300 "GuideSimulator::setPinnedRoots: not ready", "hair.sim"));
301 }
302 if (!rootPositionsXYZ || rootCount != int(curves_.size())) {
305 "GuideSimulator::setPinnedRoots: rootCount must equal curveCount", "hair.sim.roots"));
306 }
307 for (size_t ci = 0; ci < curves_.size(); ++ci) {
308 const uint32_t idx = curves_[ci].pointOffset;
309 const glm::vec3 p{rootPositionsXYZ[ci * 3 + 0], rootPositionsXYZ[ci * 3 + 1], rootPositionsXYZ[ci * 3 + 2]};
310 if (!std::isfinite(p.x) || !std::isfinite(p.y) || !std::isfinite(p.z)) {
312 DiagnosticCode::InvalidArgument, "GuideSimulator::setPinnedRoots: non-finite", "hair.sim.roots"));
313 }
314 const glm::vec3 delta = p - pos_[idx];
315 pos_[idx] = p;
316 prev_[idx] = p;
317 for (uint32_t pi = 1; pi < curves_[ci].pointCount; ++pi) {
318 pos_[idx + pi] += delta;
319 prev_[idx + pi] += delta;
320 }
321 }
322 return Result<void>::success();
323}
324
325void GuideSimulator::solveDistances(float dt) {
326 const float dt2 = dt * dt;
327 const float alpha = params_.compliance / std::max(dt2, kEpsilon);
328
329 for (int it = 0; it < params_.iterations; ++it) {
330 for (const Segment &seg : segments_) {
331 glm::vec3 &p0 = pos_[seg.i0];
332 glm::vec3 &p1 = pos_[seg.i1];
333 const float w0 = pinned_[seg.i0] ? 0.f : 1.f;
334 const float w1 = pinned_[seg.i1] ? 0.f : 1.f;
335 const float wSum = w0 + w1;
336 if (wSum < kEpsilon) continue;
337
338 glm::vec3 delta = p1 - p0;
339 float len = glm::length(delta);
340 if (len < kEpsilon) {
341 delta = glm::vec3(0.f, kEpsilon, 0.f);
342 len = kEpsilon;
343 }
344 const glm::vec3 n = delta / len;
345 const float C = len - seg.restLength;
346 const float corr = C / (wSum + alpha);
347 p0 += n * (corr * w0);
348 p1 -= n * (corr * w1);
349 }
350 }
351}
352
353void GuideSimulator::resolveCollisions() {
354 const float yPlane = params_.collisionY;
355 if (yPlane < -1.0e5f) return;
356 for (size_t i = 0; i < pos_.size(); ++i) {
357 if (pinned_[i]) continue;
358 if (pos_[i].y < yPlane) {
359 pos_[i].y = yPlane;
360 if (prev_[i].y < yPlane) prev_[i].y = yPlane;
361 }
362 }
363}
364
366 if (!isReady()) {
368 Diagnostic::error(DiagnosticCode::InvalidArgument, "GuideSimulator::step: not ready", "hair.sim"));
369 }
370 if (!std::isfinite(dt) || dt <= 0.f) {
372 DiagnosticCode::InvalidArgument, "GuideSimulator::step: dt must be positive finite", "hair.sim.dt"));
373 }
374
375 const float stepDt = std::min(dt, params_.maxDt);
376 const float damp = std::pow(std::clamp(params_.damping, 0.f, 1.f), stepDt);
377 const glm::vec3 accel = params_.gravity + params_.wind;
378
379 for (size_t i = 0; i < pos_.size(); ++i) {
380 if (pinned_[i]) {
381 prev_[i] = pos_[i];
382 continue;
383 }
384 const glm::vec3 cur = pos_[i];
385 const glm::vec3 vel = (cur - prev_[i]) * damp;
386 pos_[i] = cur + vel + accel * (stepDt * stepDt);
387 prev_[i] = cur;
388 }
389
390 solveDistances(stepDt);
391 resolveCollisions();
392
393 for (size_t i = 0; i < pos_.size(); ++i) {
394 if (pinned_[i]) pos_[i] = prev_[i];
395 }
396 return Result<void>::success();
397}
398
400 if (!isReady()) {
402 Diagnostic::error(DiagnosticCode::InvalidArgument, "GuideSimulator::snapshot: not ready", "hair.sim"));
403 }
404 if (restPoints_.size() != pos_.size()) {
406 "GuideSimulator::snapshot: size mismatch", "hair.sim"));
407 }
408
409 std::vector<StrandPoint> points = restPoints_;
410 for (size_t i = 0; i < pos_.size(); ++i) {
411 points[i].position = pos_[i];
412 }
413 std::vector<StrandCurve> curves;
414 curves.reserve(curves_.size());
415 for (const CurveSpan &span : curves_) {
417 curve.pointOffset = span.pointOffset;
418 curve.pointCount = span.pointCount;
419 float len = 0.f;
420 for (uint32_t pi = 1; pi < span.pointCount; ++pi) {
421 len += glm::length(pos_[span.pointOffset + pi] - pos_[span.pointOffset + pi - 1]);
422 }
423 curve.length = len;
424 curves.push_back(curve);
425 }
426
428 out.setPoints(std::move(points));
429 out.setCurves(std::move(curves));
430 auto valid = out.validate();
431 if (!valid.ok()) return Result<StrandsDatas>::failure(valid.status());
432 return Result<StrandsDatas>::success(std::move(out));
433}
434
435} // namespace eve::graphics::hair
double y
float w
Definition AnimClip.cpp:738
int root
Definition AnimSmr.cpp:119
const std::string & s
int strands
glm::vec4 p[6]
Stable, structured diagnostics shared by engine modules.
uint32_t i1
Definition Grass.cpp:61
uint32_t i0
Definition Grass.cpp:61
float u
Definition Grass.cpp:233
glm::vec3 n
Definition Grass.cpp:63
std::array< float, 3 > position
std::vector< RecipeParam > params
bool valid
MeleePoint3 b
Definition MeleeHit.cpp:41
MeleePoint3 a
Definition MeleeHit.cpp:40
double dt
int idx
std::shared_ptr< const std::vector< glm::vec2 > > points
float d
float t
ScriptStructure out
Heightmap curve
float weights[3]
float step
Definition TreeMesh.cpp:451
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
void setParams(const GuideSimParams &params)
Sets the params.
Definition Guides.cpp:289
Result< void > step(float dt)
Advance simulation by dt seconds (clamped by params.maxDt).
Definition Guides.cpp:365
Result< StrandsDatas > snapshot() const
Export current particle positions as StrandsDatas (same topology). @ownership Returned buffer uniquel...
Definition Guides.cpp:399
const GuideSimParams & params() const
Params.
Definition Simulation.h:70
Result< void > reset(const StrandsDatas &guides, const GuideSimParams &params={})
Capture rest topology and pin every curve root. @ownership Copies guides; caller retains the source.
Definition Guides.cpp:221
Result< void > setPinnedRoots(const float *rootPositionsXYZ, int rootCount)
Teleport pinned roots (e.g. after skin binding deform).
Definition Guides.cpp:297
bool isReady() const
True when ready.
Definition Simulation.h:73
CPU-authoritative strand buffer (UE FHairStrandsDatas analogue).
std::span< const StrandCurve > curves() const
Borrowed curves; invalidated by mutation.
Result< void > validate() const
Verify offsets, counts, and finite values.
void setPoints(std::vector< StrandPoint > points)
Sets the points.
std::span< const StrandPoint > points() const
Borrowed points; invalidated by mutation.
std::span< const StrandPoint > curvePoints(size_t curveIndex) const
Borrowed points of one curve.
Procedural hair/fur card meshes + material/LOD helpers (no strand simulation).
Definition Graphics.h:64
InterpolationMode
How render strands follow deformed guides (UE interpolation analogue).
Definition Guides.h:19
Result< StrandsDatas > extractGuides(const StrandsDatas &strands, float guideFraction)
Pick a deterministic subset of curves as guides (density thinning).
Definition Guides.cpp:52
Result< StrandsDatas > interpolateStrands(const StrandsDatas &strandsRest, const StrandsDatas &guidesRest, const StrandsDatas &guidesDeformed, const std::vector< StrandGuideWeights > &weights, InterpolationMode mode)
Drive rest render strands with deformed guides using precomputed weights. @ownership Returned datas u...
Definition Guides.cpp:148
Result< std::vector< StrandGuideWeights > > buildGuideWeights(const StrandsDatas &strands, const StrandsDatas &guides, int maxInfluences, InterpolationMode mode)
Build k-nearest guide weights for every render strand (by root distance).
Definition Guides.cpp:97
Parameters for CPU guide-strand dynamics (UE groom sim lite analogue).
Definition Simulation.h:21
int iterations
XPBD solver iterations per substep (clamped to [1, 16]).
Definition Simulation.h:26
float collisionY
Infinite ground plane y = collisionY; particles below are pushed up. Set very low (default) to disabl...
Definition Simulation.h:39
float compliance
XPBD distance compliance (m/N); 0 ≈ hard constraint. Larger values allow more stretch.
Definition Simulation.h:31
float damping
Velocity retention per second (0 = freeze, 1 = no damping).
Definition Simulation.h:24
float maxDt
Clamp for a single step (seconds).
Definition Simulation.h:33
One strand as a contiguous point range. @ownership Value type owned by StrandsDatas.
Up to kMaxInfluences guides influencing one render strand. @ownership Owned by the weights table retu...
Definition Guides.h:31
static constexpr int kMaxInfluences
Definition Guides.h:32
One control point on a hair curve (UE FHairStrandsDatas point analogue). @ownership Value type owned ...
float u
Root-to-tip parameter in [0, 1].