载入中...
搜索中...
未找到
GroomAsset.cpp
浏览该文件的文档.
1// eve-hot-path
3#include <algorithm>
4#include <cmath>
5#include <string>
6#include <vector>
7#include "common/Diagnostic.h"
8#include "common/Exception.h"
9#include "graphics/Color.h"
10#include "graphics/Graphics.h"
11#include "graphics/HairCards.h"
12#include "graphics/HairShader.h"
13#include "graphics/Mesh.h"
14#include "graphics/Shader.h"
15#include "graphics/Texture.h"
18
19// GroomAsset.cpp
20namespace eve::graphics::hair {
21
23 if (group.name.empty()) {
25 "GroomAsset::addGroup: empty name", "hair.groom.group.name"));
26 }
27 for (const GroomGroup &existing : groups_) {
28 if (existing.groupId == group.groupId) {
30 DiagnosticCode::AlreadyExists, "GroomAsset::addGroup: duplicate groupId", "hair.groom.group.id"));
31 }
32 }
33 if (group.lods.empty()) {
35 lod.screenSize = 1.f;
36 lod.representation = Representation::Strands;
37 lod.curveFraction = 1.f;
38 lod.thicknessScale = 1.f;
39 group.lods.push_back(lod);
40 }
41 auto strandsOk = group.strands.validate();
42 if (!strandsOk.ok()) return Result<void>::failure(strandsOk.status());
43 if (group.guides.curveCount() > 0) {
44 auto guidesOk = group.guides.validate();
45 if (!guidesOk.ok()) return Result<void>::failure(guidesOk.status());
46 }
47 groups_.push_back(std::move(group));
48 return Result<void>::success();
49}
50
51const GroomGroup *GroomAsset::groupAt(size_t index) const {
52 if (index >= groups_.size()) return nullptr;
53 return &groups_[index];
54}
55
56const GroomGroup *GroomAsset::findGroupById(uint32_t groupId) const {
57 for (const GroomGroup &g : groups_) {
58 if (g.groupId == groupId) return &g;
59 }
60 return nullptr;
61}
62
63void GroomAsset::clear() { groups_.clear(); }
64
66 if (groups_.empty()) {
68 Diagnostic::error(DiagnosticCode::InvalidArgument, "GroomAsset: no groups", "hair.groom.groups"));
69 }
70 for (size_t i = 0; i < groups_.size(); ++i) {
71 auto ok = groups_[i].strands.validate();
72 if (!ok.ok()) return Result<void>::failure(ok.status());
73 if (groups_[i].guides.curveCount() > 0) {
74 auto guidesOk = groups_[i].guides.validate();
75 if (!guidesOk.ok()) return Result<void>::failure(guidesOk.status());
76 }
77 if (groups_[i].lods.empty()) {
79 "GroomAsset: group has empty LOD table",
80 "hair.groom.groups[" + std::to_string(i) + "].lods"));
81 }
82 }
83 return Result<void>::success();
84}
85
86size_t selectLodIndex(const std::vector<GroomLod> &lods, float screenSize) {
87 if (lods.empty()) return 0;
88 // Ordered finest → coarsest. Pick the last entry whose threshold is still
89 // >= the current screen size (i.e. the coarsest LOD that still applies).
90 size_t best = 0;
91 for (size_t i = 0; i < lods.size(); ++i) {
92 if (screenSize <= lods[i].screenSize) best = i;
93 }
94 return best;
95}
96
97} // namespace eve::graphics::hair
98
99// GroomInstance.cpp
101
102#include "common/Diagnostic.h"
103#include "common/Exception.h"
104#include "graphics/Color.h"
105#include "graphics/Graphics.h"
106#include "graphics/HairCards.h"
107#include "graphics/HairShader.h"
108#include "graphics/Mesh.h"
109#include "graphics/Shader.h"
110#include "graphics/Texture.h"
113
114#include <algorithm>
115#include <cmath>
116#include <vector>
117
118namespace eve::graphics::hair {
119namespace {
120
122CardMeshData buildCardsFromStrands(const StrandsDatas &strands, float widthScale) {
123 CardMeshData combined;
124 const float width = std::max(1e-4f, 0.004f * widthScale);
125 std::vector<float> pointsXYZ;
126 for (size_t ci = 0; ci < strands.curveCount(); ++ci) {
127 const auto pts = strands.curvePoints(ci);
128 if (pts.size() < 2) continue;
129 pointsXYZ.clear();
130 pointsXYZ.reserve(pts.size() * 3);
131 float avgRadius = 0.f;
132 for (const StrandPoint &p : pts) {
133 pointsXYZ.push_back(p.position.x);
134 pointsXYZ.push_back(p.position.y);
135 pointsXYZ.push_back(p.position.z);
136 avgRadius += p.radius;
137 }
138 avgRadius /= float(pts.size());
139 const float cardWidth = std::max(width, avgRadius * 4.f * widthScale);
140 appendCardMesh(combined, buildCardsAlongPolyline(pointsXYZ.data(), int(pts.size()), cardWidth));
141 }
142 return combined;
143}
144
145} // namespace
146
148 if (!gfx_) throw eve::Exception("GroomInstance: null graphics");
149 auto registered = addViewPreparation([this](Graphics &graphics, const glm::mat4 &, const glm::vec3 &) {
150 if (&graphics != gfx_ || !geometryDirty_ || asset_.groupCount() == 0) return Result<void>::success();
151 return rebuild();
152 });
153 preparationToken_ = std::move(registered).expect("GroomInstance: view preparation registration failed");
154}
155
157
158const GroomGroup *GroomInstance::primaryGroup() const { return asset_.groupAt(0); }
159
160size_t GroomInstance::resolveLodIndex(const GroomGroup &group) const {
161 if (group.lods.empty()) return 0;
162 if (forcedLod_ >= 0) {
163 size_t lodIndex = size_t(forcedLod_);
164 if (lodIndex >= group.lods.size()) lodIndex = group.lods.size() - 1;
165 return lodIndex;
166 }
167 return selectLodIndex(group.lods, screenSize_);
168}
169
170StrandsDatas GroomInstance::decimatedStrands(const StrandsDatas &src, float curveFraction) const {
171 StrandsDatas out;
172 if (src.curveCount() == 0) return out;
173 const float frac = std::clamp(curveFraction, 0.05f, 1.f);
174 const size_t keep = std::max<size_t>(1, size_t(std::ceil(double(src.curveCount()) * double(frac))));
175 const size_t step = std::max<size_t>(1, src.curveCount() / keep);
176
177 std::vector<StrandPoint> points;
178 std::vector<StrandCurve> curves;
179 points.reserve(src.pointCount());
180 curves.reserve(keep);
181
182 for (size_t ci = 0; ci < src.curveCount(); ci += step) {
183 if (curves.size() >= keep) break;
184 const auto pts = src.curvePoints(ci);
185 if (pts.size() < 2) continue;
186 StrandCurve curve;
187 curve.pointOffset = uint32_t(points.size());
188 curve.pointCount = uint32_t(pts.size());
189 float len = 0.f;
190 for (size_t pi = 0; pi < pts.size(); ++pi) {
191 points.push_back(pts[pi]);
192 if (pi > 0) len += glm::length(pts[pi].position - pts[pi - 1].position);
193 }
194 curve.length = len;
195 curves.push_back(curve);
196 }
197 out.setPoints(std::move(points));
198 out.setCurves(std::move(curves));
199 return out;
200}
201
202Result<void> GroomInstance::rebuildClusterGrids() {
203 groupCull_.assign(asset_.groupCount(), GroupCullState{});
204 for (size_t gi = 0; gi < asset_.groupCount(); ++gi) {
205 const GroomGroup *group = asset_.groupAt(gi);
206 if (!group) continue;
207 auto built = groupCull_[gi].clusters.build(group->strands, clusterCellSize_);
208 if (!built.ok()) return Result<void>::failure(built.status());
209 }
210 return Result<void>::success();
211}
212
213Result<void> GroomInstance::bakeFromStrands(StrandsDatas strands, const char *debugName) {
214 auto ok = strands.validate();
215 if (!ok.ok()) return Result<void>::failure(ok.status());
216
217 GroomGroup group;
218 group.name = debugName ? debugName : "default";
219 group.groupId = 0;
220 group.strands = std::move(strands);
221
222 // Mid LOD uses HairCards geometry (PR #400); far culls to None.
223 GroomLod nearLod;
224 nearLod.screenSize = 1.f;
225 nearLod.representation = Representation::Strands;
226 nearLod.curveFraction = 1.f;
227 GroomLod midLod;
228 midLod.screenSize = 0.35f;
229 midLod.representation = Representation::Cards;
230 midLod.curveFraction = 0.3f;
231 midLod.thicknessScale = 2.f;
232 GroomLod farLod;
233 farLod.screenSize = 0.12f;
234 farLod.representation = Representation::None;
235 farLod.curveFraction = 0.05f;
236 group.lods = {nearLod, midLod, farLod};
237
238 GroomAsset asset;
239 auto add = asset.addGroup(std::move(group));
240 if (!add.ok()) return Result<void>::failure(add.status());
241 return setAsset(asset);
242}
243
245 auto ok = asset.validate();
246 if (!ok.ok()) return Result<void>::failure(ok.status());
247 GroomAsset candidate = asset;
248 auto previousAsset = std::move(asset_);
249 auto previousCull = std::move(groupCull_);
250 auto previousSim = std::move(groupSim_);
251 const bool keepSim = guideSimEnabled_;
252 const bool previousDirty = geometryDirty_;
253 auto restore = [&] {
254 asset_ = std::move(previousAsset);
255 groupCull_ = std::move(previousCull);
256 groupSim_ = std::move(previousSim);
257 guideSimEnabled_ = keepSim;
258 geometryDirty_ = previousDirty;
259 };
260 asset_ = std::move(candidate);
261 markGeometryDirty();
262 clearGuideSimulation();
263 try {
264 auto grid = rebuildClusterGrids();
265 if (!grid.ok()) {
266 auto error = grid.status();
267 restore();
269 }
270 if (keepSim) {
271 auto simulation = setupGuideSimulation(guideFraction_, guideInterpMode_);
272 if (!simulation.ok()) {
273 auto error = simulation.status();
274 restore();
276 }
277 }
278 auto rebuilt = rebuild();
279 if (!rebuilt.ok()) {
280 auto error = rebuilt.status();
281 restore();
283 }
284 return Result<void>::success();
285 } catch (const std::exception &error) {
286 restore();
287 return Result<void>::failure(Diagnostic::error(DiagnosticCode::Failed, error.what(), "hair.groom.asset"));
288 }
289}
290
292 auto strands = generateOnPlane(sizeX, sizeZ, params);
293 if (!strands.ok()) return Result<void>::failure(strands.status());
294 return bakeFromStrands(std::move(strands).value(), "procedural_plane");
295}
296
297Result<void> GroomInstance::bakeProceduralMesh(const float *posXYZ, const float *nrmXYZ, int vertexCount,
298 const uint32_t *indices, int indexCount,
299 const ProceduralParams &params) {
300 auto strands = generateOnMesh(posXYZ, nrmXYZ, vertexCount, indices, indexCount, params);
301 if (!strands.ok()) return Result<void>::failure(strands.status());
302 return bakeFromStrands(std::move(strands).value(), "procedural_mesh");
303}
304
306 if (forcedLod_ == lod) return;
307 forcedLod_ = lod;
308 markGeometryDirty();
309}
310
311int GroomInstance::getForcedLod() const { return forcedLod_; }
312
313void GroomInstance::setScreenSize(float screenSize) {
314 const float next = std::clamp(screenSize, 0.f, 1.f);
315 if (next == screenSize_) return;
316 const float previous = screenSize_;
317 screenSize_ = next;
318 if (forcedLod_ >= 0) return;
319 for (size_t i = 0; i < asset_.groupCount(); ++i) {
320 const auto &group = *asset_.groupAt(i);
321 if (selectLodIndex(group.lods, previous) != selectLodIndex(group.lods, next)) markGeometryDirty();
322 }
323}
324
325float GroomInstance::getScreenSize() const { return screenSize_; }
326
328 const float next = scale > 1e-6f ? scale : 1e-6f;
329 if (next == widthScale_) return;
330 widthScale_ = next;
331 markGeometryDirty();
332}
333
334float GroomInstance::getWidthScale() const { return widthScale_; }
335
336void GroomInstance::setSideHint(float x, float y, float z) {
337 const glm::vec3 next(x, y, z);
338 if (next == sideHint_) return;
339 sideHint_ = next;
340 markGeometryDirty();
341}
342
344 if (enabled == clusterCulling_) return;
345 clusterCulling_ = enabled;
346 markGeometryDirty();
347}
348
349bool GroomInstance::isClusterCullingEnabled() const { return clusterCulling_; }
350
351void GroomInstance::setMarschnerLobes(float r, float tt, float trt) {
352 marschnerR_ = r >= 0.f ? r : 0.f;
353 marschnerTT_ = tt >= 0.f ? tt : 0.f;
354 marschnerTRT_ = trt >= 0.f ? trt : 0.f;
355 applyShadingParams();
356}
357
358float GroomInstance::getMarschnerR() const { return marschnerR_; }
359
360float GroomInstance::getMarschnerTT() const { return marschnerTT_; }
361
362float GroomInstance::getMarschnerTRT() const { return marschnerTRT_; }
363
364void GroomInstance::setSelfShadow(float strength, float bias, float rootAo) {
365 selfShadowStrength_ = std::clamp(strength, 0.f, 1.f);
366 selfShadowBias_ = std::clamp(bias, 0.f, 1.f);
367 rootAoStrength_ = std::clamp(rootAo, 0.f, 1.f);
368 applyShadingParams();
369}
370
371float GroomInstance::getSelfShadowStrength() const { return selfShadowStrength_; }
372
373float GroomInstance::getSelfShadowBias() const { return selfShadowBias_; }
374
375float GroomInstance::getRootAoStrength() const { return rootAoStrength_; }
376
377void GroomInstance::clearGuideSimulation() {
378 groupSim_.clear();
379 guideSimEnabled_ = false;
380}
381
382Result<void> GroomInstance::setupGuideSimulation(float guideFraction, InterpolationMode mode) {
383 groupSim_.assign(asset_.groupCount(), GroupSimState{});
384 for (size_t gi = 0; gi < asset_.groupCount(); ++gi) {
385 const GroomGroup *group = asset_.groupAt(gi);
386 if (!group) continue;
387 GroupSimState &state = groupSim_[gi];
388 state.restStrands = group->strands;
389
390 if (group->guides.curveCount() > 0) {
391 state.restGuides = group->guides;
392 } else {
393 auto guides = extractGuides(group->strands, guideFraction);
394 if (!guides.ok()) return Result<void>::failure(guides.status());
395 state.restGuides = std::move(guides).value();
396 }
397
398 auto weights = buildGuideWeights(state.restStrands, state.restGuides, 3, mode);
399 if (!weights.ok()) return Result<void>::failure(weights.status());
400 state.weights = std::move(weights).value();
401
402 auto reset = state.simulator.reset(state.restGuides, guideSimParams_);
403 if (!reset.ok()) return Result<void>::failure(reset.status());
404
405 state.deformedStrands = state.restStrands;
406 state.active = true;
407 }
408 guideFraction_ = std::clamp(guideFraction, 0.01f, 1.f);
409 guideInterpMode_ = mode;
410 guideSimEnabled_ = true;
411 return Result<void>::success();
412}
413
415 InterpolationMode mode) {
416 if (asset_.groupCount() == 0) {
418 DiagnosticCode::InvalidArgument, "GroomInstance::enableGuideSimulation: no groups", "hair.groom.sim"));
419 }
420 guideSimParams_ = params;
421 auto setup = setupGuideSimulation(guideFraction, mode);
422 if (!setup.ok()) {
423 clearGuideSimulation();
424 return Result<void>::failure(setup.status());
425 }
426 markGeometryDirty();
427 return Result<void>::success();
428}
429
431 clearGuideSimulation();
432 if (asset_.groupCount() == 0) return Result<void>::success();
433 markGeometryDirty();
434 return Result<void>::success();
435}
436
437bool GroomInstance::isGuideSimulationEnabled() const { return guideSimEnabled_; }
438
440 guideSimParams_ = params;
441 for (GroupSimState &state : groupSim_) {
442 if (state.active) state.simulator.setParams(guideSimParams_);
443 }
444}
445
446const GuideSimParams &GroomInstance::getGuideSimParams() const { return guideSimParams_; }
447
449 if (!guideSimEnabled_) return Result<void>::success();
450 if (groupSim_.size() != asset_.groupCount()) {
451 auto setup = setupGuideSimulation(guideFraction_, guideInterpMode_);
452 if (!setup.ok()) return Result<void>::failure(setup.status());
453 }
454
455 for (size_t gi = 0; gi < groupSim_.size(); ++gi) {
456 GroupSimState &state = groupSim_[gi];
457 if (!state.active) continue;
458 auto stepped = state.simulator.step(dt);
459 if (!stepped.ok()) return Result<void>::failure(stepped.status());
460 auto deformedGuides = state.simulator.snapshot();
461 if (!deformedGuides.ok()) return Result<void>::failure(deformedGuides.status());
462 auto strands = interpolateStrands(state.restStrands, state.restGuides, deformedGuides.value(), state.weights,
463 guideInterpMode_);
464 if (!strands.ok()) return Result<void>::failure(strands.status());
465 state.deformedStrands = std::move(strands).value();
466 }
467 markGeometryDirty();
468 return Result<void>::success();
469}
470
471Mesh *GroomInstance::getMesh() const { return meshVisible_ ? mesh_ : nullptr; }
472
473Shader *GroomInstance::getShader() const { return shader_; }
474
475Texture *GroomInstance::getTexture() const { return texture_; }
476
477size_t GroomInstance::getGroupCount() const { return asset_.groupCount(); }
478
479int GroomInstance::getActiveLodIndex() const { return activeLodIndex_; }
480
481int GroomInstance::getActiveRepresentation() const { return int(activeRepresentation_); }
482
484 size_t total = 0;
485 for (const GroupCullState &state : groupCull_) total += state.clusters.clusterCount();
486 return total;
487}
488
490 if (clusterCulling_) {
491 int total = 0;
492 bool anyMask = false;
493 for (const GroupCullState &state : groupCull_) {
494 if (!state.hasVisibility) continue;
495 anyMask = true;
496 total += int(state.visibleCurves.size());
497 }
498 if (anyMask) return total;
499 }
500 int total = 0;
501 for (size_t gi = 0; gi < asset_.groupCount(); ++gi) {
502 const GroomGroup *g = asset_.groupAt(gi);
503 if (g) total += int(g->strands.curveCount());
504 }
505 return total;
506}
507
508void GroomInstance::applyShadingParams() {
509 if (!shader_) return;
510 shader_->sendFloat("marschnerR", marschnerR_);
511 shader_->sendFloat("marschnerTT", marschnerTT_);
512 shader_->sendFloat("marschnerTRT", marschnerTRT_);
513 shader_->sendFloat("selfShadowStrength", selfShadowStrength_);
514 shader_->sendFloat("selfShadowBias", selfShadowBias_);
515 shader_->sendFloat("rootAoStrength", rootAoStrength_);
516}
517
518Result<void> GroomInstance::ensureDrawResources() {
519 if (!shader_) {
520 shader_ = createShader(gfx_);
521 if (!shader_) {
523 Diagnostic::error(DiagnosticCode::Failed, "GroomInstance: hair shader failed", "hair.groom.shader"));
524 }
525 }
526 applyShadingParams();
527 if (!texture_) {
528 const uint8_t white[4] = {210, 170, 120, 255};
529 texture_ = gfx_->newTexture(1, 1, white);
530 if (!texture_) {
532 Diagnostic::error(DiagnosticCode::Failed, "GroomInstance: texture failed", "hair.groom.texture"));
533 }
534 }
535 return Result<void>::success();
536}
537
539 if (!viewProj16) {
541 DiagnosticCode::InvalidArgument, "GroomInstance::updateVisibility: null viewProj", "hair.groom.viewProj"));
542 }
543 if (groupCull_.size() != asset_.groupCount()) {
544 auto grid = rebuildClusterGrids();
545 if (!grid.ok()) return Result<void>::failure(grid.status());
546 }
547 for (GroupCullState &state : groupCull_) {
548 auto visibleClusters = state.clusters.cullClusters(viewProj16);
549 if (!visibleClusters.ok()) return Result<void>::failure(visibleClusters.status());
550 auto curves = state.clusters.collectCurveIndices(visibleClusters.value());
551 if (!curves.ok()) return Result<void>::failure(curves.status());
552 if (!state.hasVisibility || state.visibleCurves != curves.value()) markGeometryDirty();
553 state.visibleCurves = std::move(curves).value();
554 state.hasVisibility = true;
555 }
556 return Result<void>::success();
557}
558
560 if (!geometryDirty_) return Result<void>::success();
561 struct PublicationGuard {
562 GroomInstance &groom;
563 int lod;
564 Representation representation;
565 ~PublicationGuard() {
566 if (groom.geometryDirty_) {
567 groom.activeLodIndex_ = lod;
568 groom.activeRepresentation_ = representation;
569 }
570 }
571 } publication{*this, activeLodIndex_, activeRepresentation_};
572 if (asset_.groupCount() == 0) {
574 Diagnostic::error(DiagnosticCode::InvalidArgument, "GroomInstance::rebuild: no groups", "hair.groom"));
575 }
576 if (groupCull_.size() != asset_.groupCount()) {
577 auto grid = rebuildClusterGrids();
578 if (!grid.ok()) return Result<void>::failure(grid.status());
579 }
580
581 // Report LOD from the primary group (representative for script getters).
582 const GroomGroup *primary = primaryGroup();
583 if (primary && !primary->lods.empty()) {
584 activeLodIndex_ = int(resolveLodIndex(*primary));
585 activeRepresentation_ = primary->lods[size_t(activeLodIndex_)].representation;
586 } else {
587 activeLodIndex_ = 0;
588 activeRepresentation_ = Representation::None;
589 }
590
591 RibbonMesh ribbonCombined;
592 CardMeshData cardCombined;
593 bool anyRibbon = false;
594 bool anyCards = false;
595
596 for (size_t gi = 0; gi < asset_.groupCount(); ++gi) {
597 const GroomGroup *group = asset_.groupAt(gi);
598 if (!group || group->lods.empty()) continue;
599
600 const size_t lodIndex = resolveLodIndex(*group);
601 const GroomLod &lod = group->lods[lodIndex];
602 if (lod.representation == Representation::None) continue;
603 if (lod.representation == Representation::Meshes) {
605 "GroomInstance::rebuild: Meshes LOD not implemented yet",
606 "hair.groom.representation"));
607 }
608
609 StrandsDatas source = group->strands;
610 if (guideSimEnabled_ && gi < groupSim_.size() && groupSim_[gi].active) {
611 source = groupSim_[gi].deformedStrands;
612 }
613 if (clusterCulling_ && gi < groupCull_.size() && groupCull_[gi].hasVisibility) {
614 if (groupCull_[gi].visibleCurves.empty()) continue;
615 auto filtered = filterStrandsByCurves(source, groupCull_[gi].visibleCurves);
616 if (!filtered.ok()) return Result<void>::failure(filtered.status());
617 source = std::move(filtered).value();
618 }
619
620 StrandsDatas strands = decimatedStrands(source, lod.curveFraction);
621 auto ok = strands.validate();
622 if (!ok.ok()) return Result<void>::failure(ok.status());
623
624 if (lod.representation == Representation::Cards) {
625 appendCardMesh(cardCombined, buildCardsFromStrands(strands, widthScale_ * lod.thicknessScale));
626 anyCards = true;
627 continue;
628 }
629
630 RibbonParams ribbon;
631 ribbon.sideHint = sideHint_;
632 ribbon.widthScale = widthScale_ * lod.thicknessScale;
633 auto meshData = buildRibbons(strands, ribbon);
634 if (!meshData.ok()) return Result<void>::failure(meshData.status());
635 appendRibbonMesh(ribbonCombined, meshData.value());
636 anyRibbon = true;
637 }
638
639 // Prefer the primary group's representation when both ribbon and cards exist.
640 const bool useCards = anyCards && (!anyRibbon || activeRepresentation_ == Representation::Cards);
641
642 if (useCards) {
643 if (cardCombined.indices.empty()) {
644 meshVisible_ = false;
645 geometryDirty_ = false;
646 return Result<void>::success();
647 }
648 return publishMesh(cardCombined.positions, cardCombined.normals, cardCombined.uvs, cardCombined.indices);
649 }
650
651 if (!anyRibbon || ribbonCombined.indices.empty()) {
652 meshVisible_ = false;
653 geometryDirty_ = false;
654 return Result<void>::success();
655 }
656
657 return publishMesh(ribbonCombined.posXYZ, ribbonCombined.nrmXYZ, ribbonCombined.uvST, ribbonCombined.indices);
658}
659
660Result<void> GroomInstance::publishMesh(const std::vector<float> &positions, const std::vector<float> &normals,
661 const std::vector<float> &uvs, const std::vector<uint32_t> &indices) {
662 auto resources = ensureDrawResources();
663 if (!resources.ok()) return Result<void>::failure(resources.status());
664 if (mesh_) {
665 if (!gfx_->updateMeshVertices(mesh_, positions.data(), normals.data(), uvs.data(), int(positions.size() / 3),
666 indices.data(), int(indices.size())))
668 Diagnostic::error(DiagnosticCode::Failed, "GroomInstance: mesh update failed", "hair.groom.mesh"));
669 } else {
670 mesh_ = gfx_->newMeshFromArrays(positions.data(), normals.data(), uvs.data(), int(positions.size() / 3),
671 indices.data(), int(indices.size()));
672 if (!mesh_)
674 Diagnostic::error(DiagnosticCode::Failed, "GroomInstance: mesh creation failed", "hair.groom.mesh"));
675 }
676 meshVisible_ = true;
677 geometryDirty_ = false;
678 return Result<void>::success();
679}
680
681void GroomInstance::draw() { draw(lastModel_); }
682
683void GroomInstance::draw(const glm::mat4 &model) {
684 lastModel_ = model;
685 if (geometryDirty_ && asset_.groupCount() > 0) rebuild().expect("GroomInstance: draw preparation failed");
686 if (!gfx_ || !meshVisible_ || !mesh_ || !shader_ || !texture_) return;
687 applyShadingParams();
688 const Color tint(1.f, 1.f, 1.f, 1.f);
689 gfx_->drawMeshShader(mesh_, model, texture_, tint, shader_);
690}
691
693 int total = 0;
694 for (size_t gi = 0; gi < asset_.groupCount(); ++gi) {
695 const GroomGroup *g = asset_.groupAt(gi);
696 if (g) total += int(g->strands.curveCount());
697 }
698 return total;
699}
700
702 int total = 0;
703 for (size_t gi = 0; gi < asset_.groupCount(); ++gi) {
704 const GroomGroup *g = asset_.groupAt(gi);
705 if (g) total += int(g->strands.pointCount());
706 }
707 return total;
708}
709
710} // namespace eve::graphics::hair
double z
double y
double x
int strands
glm::vec4 p[6]
Stable, structured diagnostics shared by engine modules.
float strength
std::uint32_t vertexCount
std::uint32_t indexCount
tensor::Graph g
Definition GpuGraph.cpp:7
glm::vec4 tint
double r
std::vector< std::uint32_t > indices
std::vector< float > normals
std::vector< float > positions
std::uint32_t width
std::array< float, 3 > position
std::array< float, 3 > scale
std::vector< RecipeParam > params
double dt
std::shared_ptr< const OceanSprayFrame > previous
std::vector< std::weak_ptr< DeviceBytes > > resources
Definition OnnxGpgpu.cpp:55
std::string error
Definition Package.cpp:174
std::shared_ptr< const std::vector< glm::vec2 > > points
Object::Ptr value
glm::mat4 model
int lod
Graphics * graphics
ScriptStructure out
std::string_view source
float bias
Definition Shadow.cpp:149
AbilityActivationGroup group
std::map< Cell, int > best
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.
EVENGINE_API_FOUNDATION public API.
Definition Exception.h:13
void expect(std::string_view message) const
Require success for a void operation.
Definition Result.h:582
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
virtual Texture * newTexture(int width, int height, const uint8_t *rgba, bool repeatU=false, bool repeatV=false)=0
Creates a texture. @ownership Caller deletes unless documented otherwise.
virtual bool updateMeshVertices(Mesh *mesh, const float *posXYZ, const float *nrmXYZ, const float *uvST, int vertexCount, const uint32_t *indices, int indexCount)=0
In-place update of a mesh's vertex/index data (CPU -> host-visible VBO). Only call when content chang...
virtual void drawMeshShader(Mesh *mesh, const glm::mat4 &model, Texture *texture, const Color &tint, Shader *shader)=0
Draw mesh with an explicit Mesh3D Shader (nullptr = default PBR pipeline).
virtual Mesh * newMeshFromArrays(const float *posXYZ, const float *nrmXYZ, const float *uvST, int vertexCount, const uint32_t *indices, int indexCount)=0
Upload a triangle mesh from packed CPU arrays. Owned by Graphics. posXYZ required (vertexCount*3)....
GPU mesh handle (+ optional CPU morph targets).
Definition Mesh.h:26
Custom GPU program.
Definition Shader.h:41
void sendFloat(const std::string &name, float x)
Definition Shader.cpp:107
GPU texture created via Graphics::newTexture. Owns GPU resources through an opaque backend handle.
Definition Texture.h:15
Shared CPU groom container (UE UGroomAsset analogue).
Definition GroomAsset.h:52
const GroomGroup * groupAt(size_t index) const
const GroomGroup * findGroupById(uint32_t groupId) const
Result< void > validate() const
Validate every group strands buffer and LOD table.
Result< void > addGroup(GroomGroup group)
Append a group; fails when name is empty or groupId collides. @ownership group is moved into the asse...
Runtime groom drawable (UE UGroomComponent analogue).
Shader * getShader() const
Returns the shader.
void setClusterCullingEnabled(bool enabled)
Enable/disable CPU cluster frustum filtering before mesh bake. When enabled, call updateVisibility wi...
GroomInstance(Graphics *gfx)
Groom instance.
float getSelfShadowBias() const
Returns the self shadow bias.
int getPointCount() const
Returns the point count.
Result< void > update(float dt)
Advance guide simulation by dt; queue geometry for the next view preparation or draw....
Result< void > bakeProceduralPlane(float sizeX, float sizeZ, const ProceduralParams &params={})
Bake a procedural plane groom into a single default group.
void setSideHint(float x, float y, float z)
Sets the side hint.
Result< void > bakeProceduralMesh(const float *posXYZ, const float *nrmXYZ, int vertexCount, const uint32_t *indices, int indexCount, const ProceduralParams &params={})
Bake procedural strands on an indexed triangle mesh.
float getMarschnerR() const
Returns the marschner r.
void setSelfShadow(float strength, float bias, float rootAo)
Cheap analytical self-shadow (fiber wrap + along-strand root AO).
void setWidthScale(float scale)
Sets the width scale.
Result< void > updateVisibility(const float *viewProj16)
Update the explicitly supplied visibility mask; equal masks do not dirty geometry....
Result< void > disableGuideSimulation()
Disable guide simulation and restore rest strands on next rebuild.
int getCurveCount() const
Returns the curve count.
float getWidthScale() const
Returns the width scale.
Result< void > setAsset(const GroomAsset &asset)
Replace runtime strands from a shared asset (deep copy of groups). @ownership Asset remains owned by ...
float getMarschnerTRT() const
Returns the marschner trt.
bool isClusterCullingEnabled() const
True when cluster culling enabled.
int getForcedLod() const
Returns the forced lod.
size_t getClusterCount() const
Returns the cluster count.
Result< void > rebuild()
Explicit synchronous refresh of pending geometry; clean instances are no-ops.
float getMarschnerTT() const
Returns the marschner tt.
const GuideSimParams & getGuideSimParams() const
Returns the guide sim params.
int getVisibleCurveCount() const
Returns the visible curve count.
float getScreenSize() const
Returns the screen size.
size_t getGroupCount() const
Returns the group count.
Mesh * getMesh() const
Return the last published visible mesh, or null for a culled/empty groom. @ownership Borrowed from Gr...
void setGuideSimParams(const GuideSimParams &params)
void setMarschnerLobes(float r, float tt, float trt)
Marschner-approximate lobe weights (R / TT / TRT) applied to the hair shader. Defaults: 1 / 0....
int getActiveRepresentation() const
Returns the active representation.
float getRootAoStrength() const
Returns the root ao strength.
float getSelfShadowStrength() const
Returns the self shadow strength.
int getActiveLodIndex() const
Returns the active lod index.
void setScreenSize(float screenSize)
Screen-size hint in [0,1] used when forced LOD is disabled.
void setForcedLod(int lod)
Force LOD index; -1 restores automatic selection.
Result< void > enableGuideSimulation(const GuideSimParams &params={}, float guideFraction=0.15f, InterpolationMode mode=InterpolationMode::Offset)
Enable lightweight guide XPBD/Verlet for every group.
Texture * getTexture() const
Returns the texture.
CPU-authoritative strand buffer (UE FHairStrandsDatas analogue).
Procedural hair/fur card meshes + material/LOD helpers (no strand simulation).
Definition Graphics.h:64
CardMeshData buildCardsAlongPolyline(const float *pointsXYZ, int pointCount, float width)
Build one card per polyline segment, facing a camera-facing side approximated by world up.
Definition HairCards.cpp:76
Representation
Geometry representation selected by a groom LOD (UE GeometryType analogue).
Definition GroomAsset.h:14
InterpolationMode
How render strands follow deformed guides (UE interpolation analogue).
Definition Guides.h:19
Result< RibbonMesh > buildRibbons(const StrandsDatas &strands, const RibbonParams &params)
Expand validated strands into stable (non-view-facing) ribbons.
Result< StrandsDatas > generateOnPlane(float sizeX, float sizeZ, const ProceduralParams &params)
Grow strands on a Y-up XZ plane centered at the origin.
Result< StrandsDatas > extractGuides(const StrandsDatas &strands, float guideFraction)
Pick a deterministic subset of curves as guides (density thinning).
Definition Guides.cpp:52
Result< StrandsDatas > filterStrandsByCurves(const StrandsDatas &src, const std::vector< uint32_t > &curveIndices)
Copy a subset of curves into a new StrandsDatas (preserves point order).
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< StrandsDatas > generateOnMesh(const float *posXYZ, const float *nrmXYZ, int vertexCount, const uint32_t *indices, int indexCount, const ProceduralParams &params)
Grow strands from area-weighted samples on an indexed triangle mesh.
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
void appendRibbonMesh(RibbonMesh &dst, const RibbonMesh &src)
Append src into dst, rebasing triangle indices by dst vertex count. @ownership Both meshes remain cal...
void appendCardMesh(CardMeshData &dst, const CardMeshData &src)
Append src into dst (vertex/index rebase).
size_t selectLodIndex(const std::vector< GroomLod > &lods, float screenSize)
Pick the LOD index for a given screen size (largest screenSize ≤ query).
Shader * createShader(Graphics *gfx)
Create the default hair shader (alpha-blended, anisotropic specular). Owned by Graphics.
eve::Color Color
RGBA color used by every graphics draw call. Lives inside eve::graphics so including a graphics heade...
Definition Color.h:13
void removeViewPreparation(uint64_t token) noexcept
Remove a registration; missing/zero tokens are harmless. @thread Graphics thread outside dispatch....
Result< uint64_t > addViewPreparation(ViewPreparation callback)
Register a preparer for main and offscreen views; empty callbacks fail. @ownership Registry owns the ...
ForceVector add(ForceVector a, ForceVector b)
Definition ForceMath.h:13
bool enabled
CPU-side interleaved mesh arrays for upload via Graphics::newMeshFromArrays.
Definition HairCards.h:27
std::vector< uint32_t > indices
Definition HairCards.h:31
std::vector< float > normals
xyz per vertex
Definition HairCards.h:29
std::vector< float > positions
xyz per vertex
Definition HairCards.h:28
std::vector< float > uvs
uv per vertex
Definition HairCards.h:30
One groom group (UE hair group analogue: bangs / scalp / beard …). @ownership Owned by GroomAsset.
Definition GroomAsset.h:31
std::vector< GroomLod > lods
Definition GroomAsset.h:40
One LOD entry for a groom group.
Definition GroomAsset.h:17
float screenSize
Switch to this LOD when screen size falls below this value (0..1).
Definition GroomAsset.h:19
Parameters for CPU guide-strand dynamics (UE groom sim lite analogue).
Definition Simulation.h:21
Parameters for growing strands on a triangle mesh (scalp / body).
Definition Procedural.h:16
Triangle-list ribbon mesh expanded from strand curves.
std::vector< float > posXYZ
std::vector< float > nrmXYZ
std::vector< uint32_t > indices
RibbonParams public API.
glm::vec3 sideHint
World-space side hint used to extrude the ribbon (normalized internally).
float widthScale
Multiplier applied to each point radius.