载入中...
搜索中...
未找到
MeshMerge.cpp
浏览该文件的文档.
2
4
5#include <algorithm>
6#include <cmath>
7#include <cstdint>
8#include <unordered_map>
9#include <utility>
10
11namespace eve::procgen {
12namespace {
13
14Result<MeshBuild> weldMeshLocal(const MeshBuild& input, float tolerance,
15 std::vector<std::int32_t>& vertexSourceIds) {
16 if (!std::isfinite(tolerance) || tolerance <= 0.f)
18 "merge weld tolerance must be finite and positive",
19 "weldTolerance", {}, "procgen.mesh.merge"));
20 struct Key {
21 std::int64_t x, y, z;
22 bool operator==(const Key&) const = default;
23 };
24 struct Hash {
25 std::size_t operator()(const Key& key) const noexcept {
26 std::size_t value = std::hash<std::int64_t>{}(key.x);
27 value ^= std::hash<std::int64_t>{}(key.y) + 0x9e3779b9u + (value << 6u) + (value >> 2u);
28 value ^= std::hash<std::int64_t>{}(key.z) + 0x9e3779b9u + (value << 6u) + (value >> 2u);
29 return value;
30 }
31 };
32 MeshBuild output;
33 output.reserve(input.getVertexCount(), input.getIndexCount());
34 std::unordered_map<Key, std::uint32_t, Hash> vertices;
35 std::vector<std::uint32_t> remap(static_cast<std::size_t>(input.getVertexCount()));
36 std::vector<std::int32_t> outSources;
37 outSources.reserve(static_cast<std::size_t>(input.getVertexCount()));
38 for (int i = 0; i < input.getVertexCount(); ++i) {
39 const Key key{std::llround(input.getPositionX(i) / tolerance),
40 std::llround(input.getPositionY(i) / tolerance),
41 std::llround(input.getPositionZ(i) / tolerance)};
42 const auto found = vertices.find(key);
43 if (found != vertices.end()) {
44 remap[static_cast<std::size_t>(i)] = found->second;
45 continue;
46 }
47 const auto next = static_cast<std::uint32_t>(output.getVertexCount());
48 vertices.emplace(key, next);
49 remap[static_cast<std::size_t>(i)] = next;
50 output.addVertex(input.getPositionX(i), input.getPositionY(i), input.getPositionZ(i), input.getNormalX(i),
51 input.getNormalY(i), input.getNormalZ(i), input.getUvU(i), input.getUvV(i));
52 outSources.push_back(vertexSourceIds[static_cast<std::size_t>(i)]);
53 }
54 std::vector<int> assignments;
55 for (int i = 0; i + 2 < input.getIndexCount(); i += 3) {
56 const auto a = remap[static_cast<std::size_t>(input.getIndex(i))];
57 const auto b = remap[static_cast<std::size_t>(input.getIndex(i + 1))];
58 const auto c = remap[static_cast<std::size_t>(input.getIndex(i + 2))];
59 if (a == b || b == c || a == c) continue;
60 output.addTriangle(a, b, c);
61 assignments.push_back(input.getTriangleGroup(i / 3));
62 }
63 std::vector<std::string> names;
64 names.reserve(static_cast<std::size_t>(input.getGroupCount()));
65 for (int i = 0; i < input.getGroupCount(); ++i) names.push_back(input.getGroupName(i));
66 auto restored = output.restoreGroupData(std::move(names), std::move(assignments), -1);
67 if (!restored.ok()) return Result<MeshBuild>::failure(restored.status());
68 if (input.hasVertexColors()) {
69 std::vector<float> colors(static_cast<std::size_t>(output.getVertexCount()) * 4u, 1.f);
70 for (int i = 0; i < input.getVertexCount(); ++i) {
71 const auto dst = remap[static_cast<std::size_t>(i)];
72 for (int c = 0; c < 4; ++c)
73 colors[static_cast<std::size_t>(dst) * 4u + static_cast<std::size_t>(c)] = input.getColor(i, c);
74 }
75 auto set = output.setVertexColors(std::move(colors));
76 if (!set.ok()) return Result<MeshBuild>::failure(set.status());
77 }
78 // Shared verts need geometry normals; keep the first copy's normal would crease the weld.
79 {
80 auto& normals = output.normals();
81 const auto& positions = output.positions();
82 const auto& indices = output.indices();
83 std::fill(normals.begin(), normals.end(), 0.f);
84 for (std::size_t i = 0; i + 2 < indices.size(); i += 3) {
85 const std::size_t a = static_cast<std::size_t>(indices[i]) * 3u;
86 const std::size_t b = static_cast<std::size_t>(indices[i + 1u]) * 3u;
87 const std::size_t c = static_cast<std::size_t>(indices[i + 2u]) * 3u;
88 const float abx = positions[b] - positions[a];
89 const float aby = positions[b + 1u] - positions[a + 1u];
90 const float abz = positions[b + 2u] - positions[a + 2u];
91 const float acx = positions[c] - positions[a];
92 const float acy = positions[c + 1u] - positions[a + 1u];
93 const float acz = positions[c + 2u] - positions[a + 2u];
94 const float fx = aby * acz - abz * acy;
95 const float fy = abz * acx - abx * acz;
96 const float fz = abx * acy - aby * acx;
97 for (const auto vertex : {a, b, c}) {
98 normals[vertex] += fx;
99 normals[vertex + 1u] += fy;
100 normals[vertex + 2u] += fz;
101 }
102 }
103 for (std::size_t i = 0; i + 2 < normals.size(); i += 3) {
104 const float length =
105 std::sqrt(normals[i] * normals[i] + normals[i + 1u] * normals[i + 1u] + normals[i + 2u] * normals[i + 2u]);
106 if (length > 1e-7f) {
107 normals[i] /= length;
108 normals[i + 1u] /= length;
109 normals[i + 2u] /= length;
110 }
111 }
112 }
113 for (const auto& [key, value] : input.metadata()) output.setMeta(key, value);
114 vertexSourceIds = std::move(outSources);
115 return Result<MeshBuild>::success(std::move(output));
116}
117
118void translateMesh(MeshBuild& mesh, float dx, float dy, float dz) {
119 auto& positions = mesh.positions();
120 for (std::size_t i = 0; i + 2 < positions.size(); i += 3u) {
121 positions[i] += dx;
122 positions[i + 1u] += dy;
123 positions[i + 2u] += dz;
124 }
125}
126
127} // namespace
128
129Result<void> MeshMergePlan::appendSource(const MeshBuild& mesh, float tx, float ty, float tz, float yawDegrees,
130 float sx, float sy, float sz, std::string defaultMaterialId) {
131 if (mesh.empty())
133 "source", {}, "procgen.mesh.merge"));
134 if (!std::isfinite(tx) || !std::isfinite(ty) || !std::isfinite(tz) || !std::isfinite(yawDegrees) ||
135 !std::isfinite(sx) || !std::isfinite(sy) || !std::isfinite(sz) || sx == 0.f || sy == 0.f || sz == 0.f)
137 "merge source transform is invalid", "transform", {},
138 "procgen.mesh.merge"));
139 if (defaultMaterialId.empty())
141 "merge default material id is empty", "defaultMaterialId", {},
142 "procgen.mesh.merge"));
143 MeshBuild transformed;
144 if (!transformed.appendTransformed(&mesh, tx, ty, tz, yawDegrees, sx, sy, sz))
146 "merge failed to transform source mesh", "source", {},
147 "procgen.mesh.merge"));
148 if (transformed.getGroupCount() == 0) {
149 // Stamp default material onto every triangle.
150 MeshBuild stamped;
151 stamped.reserve(transformed.getVertexCount(), transformed.getIndexCount());
152 stamped.setActiveGroup(defaultMaterialId);
153 for (int v = 0; v < transformed.getVertexCount(); ++v)
154 stamped.addVertex(transformed.getPositionX(v), transformed.getPositionY(v), transformed.getPositionZ(v),
155 transformed.getNormalX(v), transformed.getNormalY(v), transformed.getNormalZ(v),
156 transformed.getUvU(v), transformed.getUvV(v));
157 for (int i = 0; i + 2 < transformed.getIndexCount(); i += 3)
158 stamped.addTriangle(static_cast<std::uint32_t>(transformed.getIndex(i)),
159 static_cast<std::uint32_t>(transformed.getIndex(i + 1)),
160 static_cast<std::uint32_t>(transformed.getIndex(i + 2)));
161 if (transformed.hasVertexColors()) {
162 auto set = stamped.setVertexColors(transformed.colors());
163 if (!set.ok()) return Result<void>::failure(set.status());
164 }
165 transformed = std::move(stamped);
166 }
167 Source source;
168 source.mesh = std::move(transformed);
169 source.defaultMaterialId = std::move(defaultMaterialId);
170 sources_.push_back(std::move(source));
171 return Result<void>::success();
172}
173
174void MeshMergePlan::clear() noexcept { sources_.clear(); }
175int MeshMergePlan::getSourceCount() const noexcept { return static_cast<int>(sources_.size()); }
176
178 enableContactBlend_ = enabled;
179 return Result<void>::success();
180}
181
183 if (params.falloff != "smooth" && params.falloff != "linear" && params.falloff != "sharp" &&
184 params.falloff != "sphere")
186 "merge contact blend falloff is invalid", "falloff", {},
187 "procgen.mesh.merge"));
188 falloffStorage_ = std::string(params.falloff);
189 blendParams_ = params;
190 blendParams_.falloff = falloffStorage_;
191 return Result<void>::success();
192}
193
195 if (!std::isfinite(tolerance))
197 "merge weld tolerance must be finite", "weldTolerance", {},
198 "procgen.mesh.merge"));
199 weldTolerance_ = tolerance;
200 return Result<void>::success();
201}
202
204 if (!std::isfinite(quality) || quality > 1.f)
206 "merge simplify quality must be finite and <= 1",
207 "simplifyQuality", {}, "procgen.mesh.merge"));
208 simplifyQuality_ = quality;
209 return Result<void>::success();
210}
211
213 pivotMode_ = mode;
214 return Result<void>::success();
215}
216
218 mergeVertexColors_ = enabled;
219 return Result<void>::success();
220}
221
223 if (plan.sources_.empty())
225 DiagnosticCode::InvalidArgument, "merge plan has no sources", "plan", {}, "procgen.mesh.merge"));
226
227 MeshBuild combined;
228 std::vector<std::int32_t> vertexSourceIds;
229 float firstX = 0.f, firstY = 0.f, firstZ = 0.f;
230 bool haveFirst = false;
231
232 for (std::size_t sourceIndex = 0; sourceIndex < plan.sources_.size(); ++sourceIndex) {
233 const auto& source = plan.sources_[sourceIndex];
234 if (!haveFirst && source.mesh.getVertexCount() > 0) {
235 firstX = source.mesh.getPositionX(0);
236 firstY = source.mesh.getPositionY(0);
237 firstZ = source.mesh.getPositionZ(0);
238 haveFirst = true;
239 }
240 if (!combined.appendTransformed(&source.mesh, 0.f, 0.f, 0.f, 0.f, 1.f, 1.f, 1.f))
242 DiagnosticCode::InvalidArgument, "merge append failed", "source", {}, "procgen.mesh.merge"));
243 for (int v = 0; v < source.mesh.getVertexCount(); ++v)
244 vertexSourceIds.push_back(static_cast<std::int32_t>(sourceIndex));
245 }
246
247 if (!plan.mergeVertexColors_ && combined.hasVertexColors()) {
248 auto cleared = combined.setVertexColors({});
249 if (!cleared.ok()) return Result<MeshBuild>::failure(cleared.status());
250 }
251
252 // Contact blend first so soft-snap can close gaps; weld afterward so snapped
253 // contact verts can become a continuous shell with shared normals.
254 if (plan.enableContactBlend_) {
255 auto blended = meshContactBlendResult(combined, vertexSourceIds, plan.blendParams_);
256 if (!blended.ok()) return blended;
257 combined = std::move(blended).takeValue();
258 }
259
260 if (plan.weldTolerance_ > 0.f) {
261 auto welded = weldMeshLocal(combined, plan.weldTolerance_, vertexSourceIds);
262 if (!welded.ok()) return welded;
263 combined = std::move(welded).takeValue();
264 // Weld rebuilds geometry normals; re-apply soft-snap neighborhood smooth for continuous lighting.
265 if (plan.enableContactBlend_ && plan.blendParams_.softSnapPositions)
267 }
268
269 if (plan.simplifyQuality_ > 0.f && plan.simplifyQuality_ < 1.f) {
270 MeshBuild simplified;
271 auto simp = simplifyGtsMesh(simplified, combined, plan.simplifyQuality_, {});
272 if (!simp.ok()) return Result<MeshBuild>::failure(simp.status());
273 combined = std::move(simplified);
274 }
275
276 if (plan.pivotMode_ == MeshMergePlan::PivotMode::FirstSource && haveFirst)
277 translateMesh(combined, -firstX, -firstY, -firstZ);
278
279 combined.setMeta("kind", "procgen.mesh.merged");
280 combined.setMeta("contactBlend.enabled", plan.enableContactBlend_ ? "1" : "0");
281 return Result<MeshBuild>::success(std::move(combined));
282}
283
284} // namespace eve::procgen
double z
double y
double x
std::string output
SQObjectPtr key
Definition ECS.cpp:155
EvpackChunkInput input
Definition Evpack.cpp:170
std::vector< std::uint32_t > indices
std::vector< float > normals
std::vector< float > positions
float v
std::int32_t c
float length
std::vector< RecipeParam > params
MeleePoint3 b
Definition MeleeHit.cpp:41
MeleePoint3 a
Definition MeleeHit.cpp:40
ScriptMotionSinkStore< ScriptMotionSink< MotionColorTraits > > colors
OceanMeshSettings mesh
glm::dvec3 dx
glm::dvec3 dz
Object::Ptr value
std::unordered_map< std::uint32_t, std::uint32_t > remap
bool found
std::string_view source
float dy
Definition Shadow.cpp:151
std::array< double, 2 > vertices[3]
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
CPU triangle mesh from procedural mesh recipes (e.g. marching cubes). Positions/normals are xyz-packe...
Definition MeshBuild.h:20
float getPositionZ(int i) const
Returns the position z.
float getPositionY(int i) const
Returns the position y.
void addVertex(float px, float py, float pz, float nx, float ny, float nz, float u, float v)
Adds vertex.
Definition MeshBuild.cpp:35
void addTriangle(uint32_t i0, uint32_t i1, uint32_t i2)
Adds triangle.
Definition MeshBuild.cpp:48
float getNormalZ(int i) const
Returns the normal z.
int getGroupCount() const
Number of named triangle groups.
Definition MeshBuild.cpp:65
void reserve(int vertexCount, int indexCount)
Reserve.
Definition MeshBuild.cpp:22
void setMeta(const std::string &key, const std::string &value)
Sets the meta.
int setActiveGroup(const std::string &name)
Select/create the named group assigned to subsequently added triangles.
Definition MeshBuild.cpp:55
const std::vector< float > & colors() const
Colors.
Definition MeshBuild.h:132
float getNormalY(int i) const
Returns the normal y.
int getIndexCount() const
Returns the index count.
eve::Result< void > setVertexColors(std::vector< float > colors)
Atomically replace the optional packed RGBA stream; empty removes it.
float getUvU(int i) const
Returns the uv u.
bool appendTransformed(const MeshBuild *other, float tx, float ty, float tz, float yawDegrees, float sx, float sy, float sz)
Append another procedural mesh after an affine transform.
float getUvV(int i) const
Returns the uv v.
float getNormalX(int i) const
Returns the normal x.
int getIndex(int i) const
bool hasVertexColors() const noexcept
Return whether this mesh owns one packed RGBA color per vertex.
float getPositionX(int i) const
Returns the position x.
Authoring plan for commit-style static mesh merge.
Definition MeshMerge.h:21
int getSourceCount() const noexcept
PivotMode
Pivot placement for the merged mesh.
Definition MeshMerge.h:24
Result< void > setContactBlendParams(const MeshContactBlendParams &params)
Result< void > setMergeVertexColors(bool enabled) noexcept
Result< void > setEnableContactBlend(bool enabled) noexcept
Result< void > setPivotMode(PivotMode mode) noexcept
Result< void > appendSource(const MeshBuild &mesh, float tx, float ty, float tz, float yawDegrees, float sx, float sy, float sz, std::string defaultMaterialId="default")
Copy one mesh after yaw/scale/translation into the plan.
Result< void > setWeldTolerance(float tolerance) noexcept
Positive weld tolerance enables hard weld after contact blend; non-positive disables (default)....
Result< void > setSimplifyQuality(float quality) noexcept
Optional GTS quality in (0,1); non-positive disables simplify (default). When set,...
constexpr HexDirection next(HexDirection d) noexcept
The next direction clockwise (NW wraps to NE).
Definition HexMetrics.h:76
Result< int > simplifyGtsMesh(MeshBuild &output, const MeshBuild &source, float quality, const GtsMeshSimplificationOptions &o)
Simplify a mesh with deterministic quadric edge collapse.
Result< MeshBuild > meshContactBlendResult(const MeshBuild &mesh, const std::vector< std::int32_t > &vertexSourceIds, const MeshContactBlendParams &params)
Fuse edge normals / optional positions and material blend weights across source slices.
void rebuildSoftSnapContactNormals(MeshBuild &mesh)
Rebuild triangle normals then 1-ring-average them (soft-snap / post-weld lighting).
Result< MeshBuild > mergeStaticMeshes(const MeshMergePlan &plan)
Merge planned static meshes into one owning MeshBuild.
bool enabled
Parameters for contact-band edge and material fusion.
std::string_view falloff
smooth|linear|sharp|sphere