载入中...
搜索中...
未找到
Mesh.cpp
浏览该文件的文档.
1#include "graphics/Mesh.h"
2
3#include <assimp/mesh.h>
4
5#include "graphics/Graphics.h"
6
7#include <algorithm>
8#include <atomic>
9#include <cmath>
10#include <cstring>
11#include <limits>
12
13#include <glm/mat4x4.hpp>
14#include <glm/vec3.hpp>
15
16namespace eve::graphics {
17Result<void> Mesh::setTexcoordSet(uint32_t set, std::span<const float> values) {
18 if (gpuVertexCount <= 0 || values.size() != size_t(gpuVertexCount) * 2 ||
19 std::any_of(values.begin(), values.end(), [](float x) { return !std::isfinite(x); }))
21 Diagnostic::error(DiagnosticCode::InvalidArgument, "UV channel must match mesh vertices"));
22 std::vector<float> owned(values.begin(), values.end());
23 texcoords_.insert_or_assign(set, std::move(owned));
24 ++texcoordRevision_;
25 return Result<void>::success();
26}
27std::span<const float> Mesh::texcoordSet(uint32_t set) const {
28 auto found = texcoords_.find(set);
29 return found == texcoords_.end() ? std::span<const float>{} : std::span<const float>(found->second);
30}
31
32
33namespace {
34const std::vector<float> kEmptyAttribute;
35}
36
38 markTangentFrameChanged();
39 importedUvs_.clear();
40 for (unsigned channel = 0; channel < mesh.GetNumUVChannels(); ++channel) {
41 if (!mesh.HasTextureCoords(channel)) continue;
42 std::vector<float> values;
43 values.reserve(size_t(mesh.mNumVertices) * 2u);
44 for (unsigned i = 0; i < mesh.mNumVertices; ++i) {
45 values.push_back(mesh.mTextureCoords[channel][i].x);
46 values.push_back(mesh.mTextureCoords[channel][i].y);
47 }
48 importedUvs_.push_back(std::move(values));
49 }
50 importedColors_.clear();
51 for (unsigned channel = 0; channel < mesh.GetNumColorChannels(); ++channel) {
52 if (!mesh.HasVertexColors(channel)) continue;
53 std::vector<float> values;
54 values.reserve(size_t(mesh.mNumVertices) * 4u);
55 for (unsigned i = 0; i < mesh.mNumVertices; ++i) {
56 const aiColor4D &c = mesh.mColors[channel][i];
57 values.insert(values.end(), {c.r, c.g, c.b, c.a});
58 }
59 importedColors_.push_back(std::move(values));
60 }
61 importedTangents_.clear();
62 importedBitangents_.clear();
63 if (mesh.HasTangentsAndBitangents()) {
64 importedTangents_.reserve(size_t(mesh.mNumVertices) * 3u);
65 importedBitangents_.reserve(size_t(mesh.mNumVertices) * 3u);
66 for (unsigned i = 0; i < mesh.mNumVertices; ++i) {
67 const aiVector3D &t = mesh.mTangents[i];
68 const aiVector3D &b = mesh.mBitangents[i];
69 importedTangents_.insert(importedTangents_.end(), {t.x, t.y, t.z});
70 importedBitangents_.insert(importedBitangents_.end(), {b.x, b.y, b.z});
71 }
72 }
73}
74
75const std::vector<float> &Mesh::importedUv(int channel) const {
76 return channel >= 0 && static_cast<size_t>(channel) < importedUvs_.size()
77 ? importedUvs_[static_cast<size_t>(channel)]
78 : kEmptyAttribute;
79}
80
81const std::vector<float> &Mesh::importedColor(int channel) const {
82 return channel >= 0 && static_cast<size_t>(channel) < importedColors_.size()
83 ? importedColors_[static_cast<size_t>(channel)]
84 : kEmptyAttribute;
85}
86
87Result<void> Mesh::setSkinPalette(const float* matrices, int matrixCount) {
88 if (!matrices || matrixCount <= 0 || static_cast<size_t>(matrixCount) > skinPalette_.max_size() / 16u)
90 const size_t count = static_cast<size_t>(matrixCount) * 16u;
91 for (size_t i = 0; i < count; ++i)
92 if (!std::isfinite(matrices[i]))
94 Diagnostic::error(DiagnosticCode::InvalidArgument, "Non-finite skin palette matrix"));
95 // Validate before mutation. A valid aliased input can only fit within the
96 // current size; copy it before shrinking so overlapping subranges work.
97 if (count <= skinPalette_.size()) {
98 std::memmove(skinPalette_.data(), matrices, count * sizeof(float));
99 skinPalette_.resize(count);
100 } else {
101 // float resize preserves the previous palette if allocation fails.
102 skinPalette_.resize(count);
103 std::memcpy(skinPalette_.data(), matrices, count * sizeof(float));
104 }
105 return Result<void>::success();
106}
107
108void Mesh::computeBounds(const float *posXYZ, int vertexCount) {
109 static std::atomic<uint64_t> generation{0};
110 geometryGeneration_ = ++generation;
111 hasLocalBounds_ = false;
112 boundsCx = 0.f;
113 boundsCy = 0.f;
114 boundsCz = 0.f;
115 boundsRadius = 0.f;
116 if (!posXYZ || vertexCount <= 0) return;
117
118 const size_t n = size_t(vertexCount);
119 for (int axis = 0; axis < 3; ++axis) {
120 localBounds_[axis] = std::numeric_limits<float>::max();
121 localBounds_[axis + 3] = std::numeric_limits<float>::lowest();
122 }
123 glm::vec3 c(0.f);
124 for (size_t i = 0; i < n; ++i) {
125 for (int axis = 0; axis < 3; ++axis) {
126 const float value = posXYZ[i * 3u + static_cast<std::size_t>(axis)];
127 if (!std::isfinite(value)) return;
128 localBounds_[axis] = std::min(localBounds_[axis], value);
129 localBounds_[axis + 3] = std::max(localBounds_[axis + 3], value);
130 }
131 c.x += posXYZ[i * 3u + 0u];
132 c.y += posXYZ[i * 3u + 1u];
133 c.z += posXYZ[i * 3u + 2u];
134 }
135 c /= float(n);
136 if (!std::isfinite(c.x) || !std::isfinite(c.y) || !std::isfinite(c.z)) return;
137 boundsCx = c.x;
138 boundsCy = c.y;
139 boundsCz = c.z;
140
141 float r = 0.f;
142 for (size_t i = 0; i < n; ++i) {
143 const float dx = posXYZ[i * 3u + 0u] - c.x;
144 const float dy = posXYZ[i * 3u + 1u] - c.y;
145 const float dz = posXYZ[i * 3u + 2u] - c.z;
146 const float d = std::sqrt(dx * dx + dy * dy + dz * dz);
147 if (d > r) r = d;
148 }
149 // Degenerate (single-point) meshes still get a tiny non-zero sphere so
150 // hasBounds() stays meaningful and the culler never drops point geometry.
151 if (std::isfinite(r)) {
152 boundsRadius = r > 0.f ? r : 1e-4f;
153 hasLocalBounds_ = true;
154 }
155}
156
158 if (!hasLocalBounds_)
160 DiagnosticCode::NotFound, "Mesh has no finite vertex bounds", "graphics.mesh.localBounds"));
161 return Result<std::array<float, 6>>::success(localBounds_);
162}
163
164void Mesh::drawOcclusion(Graphics* gfx, const glm::mat4& matrix) const {
165 if (!gfx || !getCastOcclusion()) return;
166 const float x = matrix[3][0];
167 const float y = matrix[3][1];
168 const float w = std::sqrt(matrix[0][0] * matrix[0][0] + matrix[0][1] * matrix[0][1]);
169 const float h = std::sqrt(matrix[1][0] * matrix[1][0] + matrix[1][1] * matrix[1][1]);
170 if (w <= 0.f || h <= 0.f) return;
171 gfx->drawOcclusionSolid(x, y, w, h);
172}
173
175 basePos_.clear();
176 baseNrm_.clear();
177 baseUv_.clear();
178 morphs_.clear();
179 morphWeights_.clear();
180 morphDirty_ = false;
181}
182
183void Mesh::initMorphBase(int vertexCount, const float *posXYZ, const float *nrmXYZ,
184 const float *uvST) {
186 if (vertexCount <= 0 || !posXYZ) return;
187 const size_t n = size_t(vertexCount);
188 basePos_.assign(posXYZ, posXYZ + n * 3);
189 if (nrmXYZ)
190 baseNrm_.assign(nrmXYZ, nrmXYZ + n * 3);
191 else
192 baseNrm_.assign(n * 3, 0.f);
193 if (uvST)
194 baseUv_.assign(uvST, uvST + n * 2);
195 else
196 baseUv_.assign(n * 2, 0.f);
197}
198
199bool Mesh::addMorphTarget(const std::string &name, const float *deltaPosXYZ) {
200 if (name.empty() || !deltaPosXYZ || basePos_.empty()) return false;
201 if (hasMorph(name)) return false;
202 MorphTarget t;
203 t.name = name;
204 t.deltaPos.assign(deltaPosXYZ, deltaPosXYZ + basePos_.size());
205 morphs_.push_back(std::move(t));
206 morphWeights_[name] = 0.f;
207 morphDirty_ = true;
208 return true;
209}
210
211bool Mesh::addMorphTargetAbsolute(const std::string &name, const float *absPosXYZ) {
212 if (name.empty() || !absPosXYZ || basePos_.empty()) return false;
213 if (hasMorph(name)) return false;
214 MorphTarget t;
215 t.name = name;
216 t.deltaPos.resize(basePos_.size());
217 for (size_t i = 0; i < basePos_.size(); ++i)
218 t.deltaPos[i] = absPosXYZ[i] - basePos_[i];
219 morphs_.push_back(std::move(t));
220 morphWeights_[name] = 0.f;
221 morphDirty_ = true;
222 return true;
223}
224
226 if (!basePos_.empty()) return int(basePos_.size() / 3);
227 return gpuVertexCount;
228}
229
230Result<void> Mesh::setMorphNormalDeltas(std::string_view name, std::span<const float> deltas) {
231 const auto target =
232 std::find_if(morphs_.begin(), morphs_.end(), [&](const auto &morph) { return morph.name == name; });
233 if (target == morphs_.end())
235 Diagnostic::error(DiagnosticCode::NotFound, "Morph target was not found", std::string(name)));
236 if ((!deltas.empty() && deltas.size() != baseNrm_.size()) ||
237 std::any_of(deltas.begin(), deltas.end(), [](float x) { return !std::isfinite(x); }))
239 "Expected finite normal deltas matching the morph base"));
240 std::vector<float> owned(deltas.begin(), deltas.end());
241 target->deltaNrm.swap(owned);
242 morphDirty_ = true;
243 return Result<void>::success();
244}
245
246int Mesh::getMorphCount() const { return int(morphs_.size()); }
247
248std::string Mesh::getMorphName(int index) const {
249 if (index < 0 || size_t(index) >= morphs_.size()) return {};
250 return morphs_[size_t(index)].name;
251}
252
253bool Mesh::hasMorph(const std::string &name) const {
254 return morphWeights_.find(name) != morphWeights_.end();
255}
256
257bool Mesh::setMorphWeight(const std::string &name, float weight) {
258 auto it = morphWeights_.find(name);
259 if (it == morphWeights_.end()) return false;
260 if (weight < 0.f) weight = 0.f;
261 if (weight > 1.f) weight = 1.f;
262 if (std::fabs(it->second - weight) > 1e-6f) {
263 it->second = weight;
264 morphDirty_ = true;
265 }
266 return true;
267}
268
269float Mesh::getMorphWeight(const std::string &name) const {
270 auto it = morphWeights_.find(name);
271 return it == morphWeights_.end() ? 0.f : it->second;
272}
273
275 for (auto &kv : morphWeights_) {
276 if (kv.second != 0.f) {
277 kv.second = 0.f;
278 morphDirty_ = true;
279 }
280 }
281}
282
283void Mesh::computeMorphedPositions(std::vector<float> &outPos, std::vector<float> &outNrm) const {
284 outPos = basePos_;
285 outNrm = baseNrm_;
286 if (outPos.empty()) return;
287 bool normalsChanged = false;
288 for (const MorphTarget &t : morphs_) {
289 auto it = morphWeights_.find(t.name);
290 const float w = (it == morphWeights_.end()) ? 0.f : it->second;
291 if (std::fabs(w) < 1e-8f) continue;
292 for (size_t i = 0; i < outPos.size() && i < t.deltaPos.size(); ++i)
293 outPos[i] += t.deltaPos[i] * w;
294 if (!t.deltaNrm.empty()) {
295 normalsChanged = true;
296 for (size_t i = 0; i < outNrm.size(); ++i) outNrm[i] += t.deltaNrm[i] * w;
297 }
298 }
299 if (normalsChanged)
300 for (size_t i = 0; i + 2 < outNrm.size(); i += 3) {
301 const float length = std::hypot(outNrm[i], outNrm[i + 1], outNrm[i + 2]);
302 if (length > 1e-8f) {
303 outNrm[i] /= length;
304 outNrm[i + 1] /= length;
305 outNrm[i + 2] /= length;
306 } else {
307 outNrm[i] = baseNrm_[i];
308 outNrm[i + 1] = baseNrm_[i + 1];
309 outNrm[i + 2] = baseNrm_[i + 2];
310 }
311 }
312}
313
314} // namespace eve::graphics
double y
double x
LogicalId target
float w
Definition AnimClip.cpp:738
ActiveSource owned
Generation generation
Definition ECS.cpp:40
std::string name
Definition ECS.cpp:154
std::uint32_t vertexCount
float u
Definition Grass.cpp:233
glm::vec3 n
Definition Grass.cpp:63
double r
std::int32_t c
int h
float length
JointPoint2D axis
MeleePoint3 b
Definition MeleeHit.cpp:41
OceanMeshSettings mesh
glm::dvec3 dx
glm::dvec3 dz
std::set< std::string > values
Object::Ptr value
float d
float t
bool found
glm::dmat4 matrix
float dy
Definition Shadow.cpp:151
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
bool getCastOcclusion() const
When false, skipped by Graphics::drawOcclusion / volumetric occluder passes.
Definition Drawable.h:31
virtual void drawOcclusionSolid(float x, float y, float w, float h)
Draws occlusion solid.
void initMorphBase(int vertexCount, const float *posXYZ, const float *nrmXYZ=nullptr, const float *uvST=nullptr)
Capture base pose (xyz packed). Optional normals/uvs (same vertex count).
Definition Mesh.cpp:183
const std::vector< float > & importedUv(int channel) const
Imported uv.
Definition Mesh.cpp:75
void clearMorphData()
Clears morph data.
Definition Mesh.cpp:174
void computeBounds(const float *posXYZ, int vertexCount)
Compute the bounding sphere (centroid + max radius) from positions.
Definition Mesh.cpp:108
int gpuVertexCount
Vertex count of the GPU buffer (morph CPU base may be empty).
Definition Mesh.h:31
bool setMorphWeight(const std::string &name, float weight)
Sets the morph weight.
Definition Mesh.cpp:257
void captureImportedAttributes(const ::aiMesh &mesh)
Retain imported UV/color/tangent streams for custom pipelines and baking.
Definition Mesh.cpp:37
bool addMorphTarget(const std::string &name, const float *deltaPosXYZ)
Adds morph target.
Definition Mesh.cpp:199
bool hasMorph(const std::string &name) const
True when morph.
Definition Mesh.cpp:253
float boundsCx
Model-space bounding sphere used for view/cascade frustum culling. Computed from vertex positions at ...
Definition Mesh.h:60
Result< std::array< float, 6 > > localBounds() const
Copy CPU-uploaded mesh-local minimum XYZ and maximum XYZ.
Definition Mesh.cpp:157
void drawOcclusion(Graphics *gfx, const glm::mat4 &matrix) const override
Screen-space black proxy for volumetric occlusion. Interprets matrix as 2D affine (translation + scal...
Definition Mesh.cpp:164
Result< void > setMorphNormalDeltas(std::string_view name, std::span< const float > deltas)
Copy normal deltas for an existing morph, or clear them with an empty span. Input is borrowed only du...
Definition Mesh.cpp:230
float getMorphWeight(const std::string &name) const
Returns the morph weight.
Definition Mesh.cpp:269
bool addMorphTargetAbsolute(const std::string &name, const float *absPosXYZ)
Absolute morph (Assimp aiAnimMesh style): stored as delta from base.
Definition Mesh.cpp:211
void clearMorphWeights()
Clears morph weights.
Definition Mesh.cpp:274
int getMorphCount() const
Returns the morph count.
Definition Mesh.cpp:246
Result< void > setTexcoordSet(uint32_t set, std::span< const float > values)
Copy one packed ST channel; finite values/count are checked atomically. Render-thread only,...
Definition Mesh.cpp:17
std::string getMorphName(int index) const
Returns the morph name.
Definition Mesh.cpp:248
std::span< const float > texcoordSet(uint32_t set) const
Borrow a channel until mutation/destruction; empty means absent. Render-thread only.
Definition Mesh.cpp:27
float boundsRadius
Definition Mesh.h:63
int getVertexCount() const
Returns the vertex count.
Definition Mesh.cpp:225
const std::vector< float > & importedColor(int channel) const
Imported color.
Definition Mesh.cpp:81
Result< void > setSkinPalette(const float *matrices, int matrixCount)
Copy a dynamically sized column-major palette on the render thread. Invalid/non-finite input leaves t...
Definition Mesh.cpp:87
void computeMorphedPositions(std::vector< float > &outPos, std::vector< float > &outNrm) const
Bake current weights into outPos / outNrm (xyz packed).
Definition Mesh.cpp:283
卡牌游戏 UI 工具模块:工厂 + 脚本绑定入口。 功能参考 ycarowr/UiCard:扇形手牌布局、抽牌/洗牌、悬浮放大、拖拽到落牌区、 敌方手牌(背面/偷看)、费用不足置灰,以及可实时调节的布局...
Definition Animation.h:25