Momentum
A library for solving nonlinear optimization problems related to human body kinematics
Loading...
Searching...
No Matches
urdf_mesh_io.cpp
Go to the documentation of this file.
1/*
2 * Copyright (c) Meta Platforms, Inc. and affiliates.
3 *
4 * This source code is licensed under the MIT license found in the
5 * LICENSE file in the root directory of this source tree.
6 */
7
9
10#include <cmath>
11#include "momentum/common/log.h"
13
14#include <array>
15#include <fstream>
16#include <sstream>
17#include <unordered_map>
18
19namespace momentum {
20
21namespace {
22
23// Hash for Eigen::Vector3f to support vertex deduplication in STL loading.
24struct Vector3fHash {
25 size_t operator()(const Eigen::Vector3f& v) const {
26 size_t h = 0;
27 for (int i = 0; i < 3; ++i) {
28 // Combine bits of each float component
29 uint32_t bits = 0;
30 std::memcpy(&bits, &v[i], sizeof(float));
31 h ^= std::hash<uint32_t>{}(bits) + 0x9e3779b9 + (h << 6) + (h >> 2);
32 }
33 return h;
34 }
35};
36
37// Approximate equality for vertex deduplication.
38struct Vector3fEqual {
39 bool operator()(const Eigen::Vector3f& a, const Eigen::Vector3f& b) const {
40 return a.isApprox(b, 1e-7f);
41 }
42};
43
44// Returns the deduplicated vertex index, inserting a new vertex if needed.
45int32_t deduplicateVertex(
46 const Eigen::Vector3f& v,
47 std::unordered_map<Eigen::Vector3f, int32_t, Vector3fHash, Vector3fEqual>& vertexMap,
48 std::vector<Eigen::Vector3f>& vertices) {
49 auto it = vertexMap.find(v);
50 if (it != vertexMap.end()) {
51 return it->second;
52 }
53 const auto idx = static_cast<int32_t>(vertices.size());
54 vertexMap[v] = idx;
55 vertices.push_back(v);
56 return idx;
57}
58
59// Try to detect if an STL file is binary (as opposed to ASCII).
60// A binary STL has an 80-byte header + 4-byte triangle count, then
61// 50 bytes per triangle. If the file size matches, it's binary.
62bool isBinaryStl(const filesystem::path& filepath) {
63 std::ifstream file(filepath, std::ios::binary | std::ios::ate);
64 if (!file.is_open()) {
65 return false;
66 }
67
68 const auto fileSize = file.tellg();
69 if (fileSize < 84) {
70 return false; // Too small for binary STL
71 }
72
73 // Read triangle count from bytes 80-83
74 file.seekg(80);
75 uint32_t numTriangles = 0;
76 file.read(reinterpret_cast<char*>(&numTriangles), sizeof(uint32_t));
77
78 // Binary STL: 80 (header) + 4 (count) + numTriangles * 50
79 const auto expectedSize =
80 static_cast<std::streamoff>(84) + static_cast<std::streamoff>(numTriangles) * 50;
81 return fileSize == expectedSize;
82}
83
84std::optional<Mesh> loadBinaryStl(const filesystem::path& filepath) {
85 std::ifstream file(filepath, std::ios::binary);
86 if (!file.is_open()) {
87 return std::nullopt;
88 }
89
90 // Skip 80-byte header
91 file.seekg(80);
92
93 uint32_t numTriangles = 0;
94 file.read(reinterpret_cast<char*>(&numTriangles), sizeof(uint32_t));
95 if (!file.good() || numTriangles == 0) {
96 return std::nullopt;
97 }
98
99 Mesh mesh;
100 std::unordered_map<Eigen::Vector3f, int32_t, Vector3fHash, Vector3fEqual> vertexMap;
101
102 for (uint32_t i = 0; i < numTriangles; ++i) {
103 // Read normal (3 floats) — we'll recompute normals later
104 std::array<float, 3> normal{};
105 file.read(reinterpret_cast<char*>(normal.data()), sizeof(float) * 3);
106
107 // Read 3 vertices (9 floats)
108 std::array<Eigen::Vector3f, 3> v;
109 for (auto& j : v) {
110 std::array<float, 3> coords{};
111 file.read(reinterpret_cast<char*>(coords.data()), sizeof(float) * 3);
112 j = Eigen::Vector3f(coords[0], coords[1], coords[2]);
113 }
114
115 // Skip attribute byte count (2 bytes)
116 uint16_t attrByteCount = 0;
117 file.read(reinterpret_cast<char*>(&attrByteCount), sizeof(uint16_t));
118
119 if (!file.good()) {
120 return std::nullopt;
121 }
122
123 // Deduplicate vertices and add face
124 Eigen::Vector3i face;
125 for (int j = 0; j < 3; ++j) {
126 face[j] = deduplicateVertex(v[j], vertexMap, mesh.vertices);
127 }
128 mesh.faces.push_back(face);
129 }
130
131 mesh.updateNormals();
132 return mesh;
133}
134
135std::optional<Mesh> loadAsciiStl(const filesystem::path& filepath) {
136 std::ifstream file(filepath);
137 if (!file.is_open()) {
138 return std::nullopt;
139 }
140
141 Mesh mesh;
142 std::unordered_map<Eigen::Vector3f, int32_t, Vector3fHash, Vector3fEqual> vertexMap;
143 std::string line;
144 std::string token;
145
146 while (std::getline(file, line)) {
147 std::istringstream iss(line);
148 iss >> token;
149
150 if (token == "vertex") {
151 // Read three vertex lines for one facet
152 std::array<Eigen::Vector3f, 3> v;
153 float x = NAN, y = NAN, z = NAN;
154 iss >> x >> y >> z;
155 v[0] = Eigen::Vector3f(x, y, z);
156
157 for (int j = 1; j < 3; ++j) {
158 if (!std::getline(file, line)) {
159 return std::nullopt;
160 }
161 std::istringstream viss(line);
162 viss >> token; // "vertex"
163 viss >> x >> y >> z;
164 v[j] = Eigen::Vector3f(x, y, z);
165 }
166
167 Eigen::Vector3i face;
168 for (int j = 0; j < 3; ++j) {
169 face[j] = deduplicateVertex(v[j], vertexMap, mesh.vertices);
170 }
171 mesh.faces.push_back(face);
172 }
173 }
174
175 if (mesh.faces.empty()) {
176 return std::nullopt;
177 }
178
179 mesh.updateNormals();
180 return mesh;
181}
182
183} // namespace
184
185Mesh generateBoxMesh(float dimX, float dimY, float dimZ) {
186 const float hx = dimX * 0.5f;
187 const float hy = dimY * 0.5f;
188 const float hz = dimZ * 0.5f;
189
190 Mesh mesh;
191 mesh.vertices = {
192 {-hx, -hy, -hz},
193 {hx, -hy, -hz},
194 {hx, hy, -hz},
195 {-hx, hy, -hz},
196 {-hx, -hy, hz},
197 {hx, -hy, hz},
198 {hx, hy, hz},
199 {-hx, hy, hz},
200 };
201
202 // Two triangles per face, 6 faces = 12 triangles.
203 // Winding order: counter-clockwise when viewed from outside.
204 mesh.faces = {
205 // -Z face
206 {0, 2, 1},
207 {0, 3, 2},
208 // +Z face
209 {4, 5, 6},
210 {4, 6, 7},
211 // -Y face
212 {0, 1, 5},
213 {0, 5, 4},
214 // +Y face
215 {2, 3, 7},
216 {2, 7, 6},
217 // -X face
218 {0, 4, 7},
219 {0, 7, 3},
220 // +X face
221 {1, 2, 6},
222 {1, 6, 5},
223 };
224
225 mesh.updateNormals();
226 return mesh;
227}
228
229Mesh generateCylinderMesh(float radius, float length, int segments) {
230 Mesh mesh;
231
232 const float halfLen = length * 0.5f;
233
234 // Bottom center vertex (index 0)
235 mesh.vertices.emplace_back(0.0f, 0.0f, -halfLen);
236 // Top center vertex (index 1)
237 mesh.vertices.emplace_back(0.0f, 0.0f, halfLen);
238
239 // Ring vertices: bottom ring starts at index 2, top ring at index 2 + segments
240 for (int i = 0; i < segments; ++i) {
241 const float angle = twopi<float>() * static_cast<float>(i) / static_cast<float>(segments);
242 const float x = radius * std::cos(angle);
243 const float y = radius * std::sin(angle);
244 mesh.vertices.emplace_back(x, y, -halfLen); // bottom ring
245 }
246 for (int i = 0; i < segments; ++i) {
247 const float angle = twopi<float>() * static_cast<float>(i) / static_cast<float>(segments);
248 const float x = radius * std::cos(angle);
249 const float y = radius * std::sin(angle);
250 mesh.vertices.emplace_back(x, y, halfLen); // top ring
251 }
252
253 const int bottomRingStart = 2;
254 const int topRingStart = 2 + segments;
255
256 for (int i = 0; i < segments; ++i) {
257 const int next = (i + 1) % segments;
258
259 // Bottom cap (winding: center, next, current — looking from -Z)
260 mesh.faces.emplace_back(0, bottomRingStart + next, bottomRingStart + i);
261
262 // Top cap (winding: center, current, next — looking from +Z)
263 mesh.faces.emplace_back(1, topRingStart + i, topRingStart + next);
264
265 // Side quads (two triangles each)
266 const int b0 = bottomRingStart + i;
267 const int b1 = bottomRingStart + next;
268 const int t0 = topRingStart + i;
269 const int t1 = topRingStart + next;
270 mesh.faces.emplace_back(b0, b1, t1);
271 mesh.faces.emplace_back(b0, t1, t0);
272 }
273
274 mesh.updateNormals();
275 return mesh;
276}
277
278Mesh generateSphereMesh(float radius, int latSegments, int lonSegments) {
279 Mesh mesh;
280
281 // Top pole (index 0)
282 mesh.vertices.emplace_back(0.0f, 0.0f, radius);
283
284 // Latitude rings (from top to bottom, excluding poles)
285 for (int lat = 1; lat < latSegments; ++lat) {
286 const float phi = pi<float>() * static_cast<float>(lat) / static_cast<float>(latSegments);
287 const float sinPhi = std::sin(phi);
288 const float cosPhi = std::cos(phi);
289
290 for (int lon = 0; lon < lonSegments; ++lon) {
291 const float theta =
292 twopi<float>() * static_cast<float>(lon) / static_cast<float>(lonSegments);
293 const float x = radius * sinPhi * std::cos(theta);
294 const float y = radius * sinPhi * std::sin(theta);
295 const float z = radius * cosPhi;
296 mesh.vertices.emplace_back(x, y, z);
297 }
298 }
299
300 // Bottom pole (last vertex)
301 const auto bottomPole = static_cast<int32_t>(mesh.vertices.size());
302 mesh.vertices.emplace_back(0.0f, 0.0f, -radius);
303
304 // Top cap triangles (pole to first ring)
305 for (int lon = 0; lon < lonSegments; ++lon) {
306 const int next = (lon + 1) % lonSegments;
307 mesh.faces.emplace_back(0, 1 + lon, 1 + next);
308 }
309
310 // Middle quad strips between rings
311 for (int lat = 0; lat < latSegments - 2; ++lat) {
312 const int ringStart = 1 + lat * lonSegments;
313 const int nextRingStart = 1 + (lat + 1) * lonSegments;
314 for (int lon = 0; lon < lonSegments; ++lon) {
315 const int next = (lon + 1) % lonSegments;
316 const int a = ringStart + lon;
317 const int b = ringStart + next;
318 const int c = nextRingStart + next;
319 const int d = nextRingStart + lon;
320 mesh.faces.emplace_back(a, d, c);
321 mesh.faces.emplace_back(a, c, b);
322 }
323 }
324
325 // Bottom cap triangles (last ring to pole)
326 const int lastRingStart = 1 + (latSegments - 2) * lonSegments;
327 for (int lon = 0; lon < lonSegments; ++lon) {
328 const int next = (lon + 1) % lonSegments;
329 mesh.faces.emplace_back(lastRingStart + lon, bottomPole, lastRingStart + next);
330 }
331
332 mesh.updateNormals();
333 return mesh;
334}
335
336std::optional<Mesh> loadStlMesh(const filesystem::path& filepath) {
337 if (!filesystem::exists(filepath)) {
338 MT_LOGW("STL file not found: {}", filepath.string());
339 return std::nullopt;
340 }
341
342 if (isBinaryStl(filepath)) {
343 return loadBinaryStl(filepath);
344 }
345 return loadAsciiStl(filepath);
346}
347
348std::optional<Mesh> loadObjMesh(const filesystem::path& filepath) {
349 if (!filesystem::exists(filepath)) {
350 MT_LOGW("OBJ file not found: {}", filepath.string());
351 return std::nullopt;
352 }
353
354 std::ifstream file(filepath);
355 if (!file.is_open()) {
356 MT_LOGW("Failed to open OBJ file: {}", filepath.string());
357 return std::nullopt;
358 }
359
360 Mesh mesh;
361 std::string line;
362
363 while (std::getline(file, line)) {
364 if (line.empty() || line[0] == '#') {
365 continue;
366 }
367
368 std::istringstream iss(line);
369 std::string token;
370 iss >> token;
371
372 if (token == "v") {
373 float x = NAN, y = NAN, z = NAN;
374 iss >> x >> y >> z;
375 mesh.vertices.emplace_back(x, y, z);
376 } else if (token == "f") {
377 // Parse face indices. Supports formats:
378 // f v1 v2 v3 ...
379 // f v1/vt1 v2/vt2 v3/vt3 ...
380 // f v1/vt1/vn1 v2/vt2/vn2 v3/vt3/vn3 ...
381 // f v1//vn1 v2//vn2 v3//vn3 ...
382 std::vector<int32_t> faceIndices;
383 std::string vertexToken;
384 while (iss >> vertexToken) {
385 // Extract vertex index (everything before the first '/')
386 const auto slashPos = vertexToken.find('/');
387 const std::string indexStr =
388 (slashPos != std::string::npos) ? vertexToken.substr(0, slashPos) : vertexToken;
389 const int idx = std::stoi(indexStr);
390 // OBJ indices are 1-based; negative indices are relative to current vertex count
391 const int32_t resolvedIdx =
392 (idx > 0) ? (idx - 1) : static_cast<int32_t>(mesh.vertices.size()) + idx;
393 faceIndices.push_back(resolvedIdx);
394 }
395
396 // Triangulate polygon faces using fan triangulation
397 if (faceIndices.size() >= 3) {
398 for (size_t i = 2; i < faceIndices.size(); ++i) {
399 mesh.faces.emplace_back(
400 faceIndices[0], faceIndices[static_cast<int32_t>(i) - 1], faceIndices[i]);
401 }
402 }
403 }
404 }
405
406 if (mesh.vertices.empty() || mesh.faces.empty()) {
407 MT_LOGW("OBJ file contains no geometry: {}", filepath.string());
408 return std::nullopt;
409 }
410
411 mesh.updateNormals();
412 return mesh;
413}
414
415std::optional<filesystem::path> resolveMeshPath(
416 const std::string& filename,
417 const filesystem::path& urdfDir) {
418 // Handle file:// URI
419 const std::string fileScheme = "file://";
420 if (filename.substr(0, fileScheme.size()) == fileScheme) {
421 const filesystem::path resolved(filename.substr(fileScheme.size()));
422 if (filesystem::exists(resolved)) {
423 return resolved;
424 }
425 MT_LOGW("Mesh file not found: {}", resolved.string());
426 return std::nullopt;
427 }
428
429 // Handle package:// URI — strip scheme and package name, resolve relative to URDF dir
430 const std::string packageScheme = "package://";
431 if (filename.substr(0, packageScheme.size()) == packageScheme) {
432 // Find the end of the package name (next '/' after "package://")
433 const auto pathStart = filename.find('/', packageScheme.size());
434 if (pathStart == std::string::npos) {
435 MT_LOGW("Invalid package:// URI: {}", filename);
436 return std::nullopt;
437 }
438 const std::string relativePath = filename.substr(pathStart + 1);
439
440 // Try resolving relative to URDF directory
441 filesystem::path resolved = urdfDir / relativePath;
442 if (filesystem::exists(resolved)) {
443 return resolved;
444 }
445
446 // Try resolving relative to parent of URDF directory
447 // (common layout: pkg/urdf/robot.urdf and pkg/meshes/part.stl)
448 resolved = urdfDir.parent_path() / relativePath;
449 if (filesystem::exists(resolved)) {
450 return resolved;
451 }
452
453 MT_LOGW("Could not resolve package:// mesh path: {}", filename);
454 return std::nullopt;
455 }
456
457 // Handle absolute paths
458 const filesystem::path path(filename);
459 if (path.is_absolute()) {
460 if (filesystem::exists(path)) {
461 return path;
462 }
463 MT_LOGW("Mesh file not found: {}", path.string());
464 return std::nullopt;
465 }
466
467 // Handle relative paths — resolve relative to URDF directory
468 const filesystem::path resolved = urdfDir / path;
469 if (filesystem::exists(resolved)) {
470 return resolved;
471 }
472
473 MT_LOGW("Mesh file not found: {}", resolved.string());
474 return std::nullopt;
475}
476
477} // namespace momentum
#define MT_LOGW(...)
Definition log.h:180
T normal(const T &mean, const T &sigma)
Normally distributed value via the global Random singleton.
Definition random-inl.h:382
Mesh generateCylinderMesh(float radius, float length, int segments)
Generates a cylinder mesh centered at the origin with the Z axis as its axis.
MeshT< float > Mesh
Definition fwd.h:20
Mesh generateSphereMesh(float radius, int latSegments, int lonSegments)
Generates a UV sphere mesh centered at the origin.
Mesh generateBoxMesh(float dimX, float dimY, float dimZ)
Generates a box mesh with the given dimensions centered at the origin.
std::optional< filesystem::path > resolveMeshPath(const std::string &filename, const filesystem::path &urdfDir)
Resolves a mesh filename from a URDF visual element to a filesystem path.
std::optional< Mesh > loadStlMesh(const filesystem::path &filepath)
Loads a mesh from an STL file (binary or ASCII).
constexpr T twopi() noexcept
Returns 2 * pi.
Definition constants.h:60
constexpr T pi() noexcept
Returns the mathematical constant pi.
Definition constants.h:50
std::optional< Mesh > loadObjMesh(const filesystem::path &filepath)
Loads a mesh from a Wavefront OBJ file (vertices and triangular/polygon faces).
void updateNormals()
Compute vertex normals by averaging connected face normals.
Definition mesh.cpp:17
std::vector< Eigen::Vector3< T > > vertices
List of mesh vertices in 3D space.
Definition mesh.h:22
std::vector< Eigen::Vector3i > faces
List of triangular faces defined by vertex indices.
Definition mesh.h:28