Lagrange
Loading...
Searching...
No Matches
mesh_utils.h
1/*
2 * Copyright 2025 Adobe. All rights reserved.
3 * This file is licensed to you under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License. You may obtain a copy
5 * of the License at http://www.apache.org/licenses/LICENSE-2.0
6 *
7 * Unless required by applicable law or agreed to in writing, software distributed under
8 * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
9 * OF ANY KIND, either express or implied. See the License for the specific language
10 * governing permissions and limitations under the License.
11 */
12#pragma once
13
14#include "Padding.h"
15
16#include <lagrange/Attribute.h>
17#include <lagrange/AttributeTypes.h>
18#include <lagrange/ExactPredicatesShewchuk.h>
19#include <lagrange/IndexedAttribute.h>
20#include <lagrange/Logger.h>
21#include <lagrange/SurfaceMeshTypes.h>
22#include <lagrange/cast_attribute.h>
23#include <lagrange/find_matching_attributes.h>
24#include <lagrange/internal/get_uv_attribute.h>
25#include <lagrange/map_attribute.h>
26#include <lagrange/solver/DirectSolver.h>
27#include <lagrange/triangulate_polygonal_facets.h>
28#include <lagrange/utils/Error.h>
29#include <lagrange/utils/fmt_eigen.h>
30#include <lagrange/views.h>
31#include <lagrange/weld_indexed_attribute.h>
32
33// Include before any TextureSignalProcessing header to override their threadpool implementation.
34#include "ThreadPool.h"
35#define MULTI_THREADING_INCLUDED
36using namespace lagrange::texproc::threadpool;
37
38// clang-format off
39#include <lagrange/utils/warnoff.h>
40#include <Misha/RegularGrid.h>
41#include <lagrange/utils/warnon.h>
42// clang-format on
43
44#include <Eigen/Sparse>
45
46#include <random>
47
48namespace lagrange::texproc {
49
50namespace {
51
52using namespace MishaK;
53
54// Using `Point` directly leads to ambiguity with Apple Accelerate types.
55template <typename T, unsigned N>
56using Vector = MishaK::Point<T, N>;
57
58// The dimension of the embedding space
59static const unsigned int Dim = 3;
60
61// The dimension of the manifold
62static const unsigned int K = 2;
63
64// The linear solver
65using Solver = lagrange::solver::SolverLDLT<Eigen::SparseMatrix<double>>;
66
67} // namespace
68
69enum class RequiresIndexedTexcoords { Yes, No };
70enum class CheckFlippedUV { Yes, No };
71
72namespace mesh_utils {
73
74template <unsigned int NumChannels, typename ValueType>
75void set_grid(
76 image::experimental::View3D<ValueType> texture,
77 RegularGrid<K, Vector<double, NumChannels>>& grid)
78{
79 unsigned int num_channels = static_cast<unsigned int>(texture.extent(2));
80 if (num_channels != NumChannels) la_debug_assert("Number of channels don't match");
81
82 // Copy the texture data into the texture grid
83 grid.resize(texture.extent(0), texture.extent(1));
84 for (unsigned int j = 0; j < grid.res(1); j++) {
85 for (unsigned int i = 0; i < grid.res(0); i++) {
86 for (unsigned int c = 0; c < NumChannels; c++) {
87 grid(i, j)[c] = texture(i, j, c);
88 }
89 }
90 }
91}
92
93template <unsigned int NumChannels, typename ValueType>
94void set_raw_view(
95 const RegularGrid<K, Vector<double, NumChannels>>& grid,
96 image::experimental::View3D<ValueType> texture)
97{
98 // Copy the texture grid data back into the texture
99 for (unsigned int j = 0; j < grid.res(1); j++) {
100 for (unsigned int i = 0; i < grid.res(0); i++) {
101 for (unsigned int c = 0; c < NumChannels; c++) {
102 texture(i, j, c) = grid(i, j)[c];
103 }
104 }
105 }
106}
107
108template <typename ValueType>
109void set_raw_view(
110 const RegularGrid<K, double>& grid,
111 image::experimental::View3D<ValueType> texture)
112{
113 // Copy the texture grid data back into the texture
114 for (unsigned int j = 0; j < grid.res(1); j++) {
115 for (unsigned int i = 0; i < grid.res(0); i++) {
116 texture(i, j, 0) = grid(i, j);
117 }
118 }
119}
120
121template <typename Scalar, typename Index>
122void check_for_flipped_uv(const SurfaceMesh<Scalar, Index>& mesh, AttributeId id)
123{
124 auto uv_mesh =
125 [&]() -> std::pair<ConstRowMatrixView<Scalar>, std::optional<ConstRowMatrixView<Index>>> {
126 if (mesh.is_attribute_indexed(id)) {
127 const auto& uv_attr = mesh.template get_indexed_attribute<Scalar>(id);
128 auto uv_values = matrix_view(uv_attr.values());
129 auto uv_indices = reshaped_view(uv_attr.indices(), 3);
130 return {uv_values, uv_indices};
131 } else {
132 const auto& uv_attr = mesh.template get_attribute<Scalar>(id);
134 uv_attr.get_element_type() == AttributeElement::Vertex ||
135 uv_attr.get_element_type() == AttributeElement::Corner,
136 "UV attribute must be per-vertex or per-corner.");
137 auto uv_values = matrix_view(uv_attr);
138 return {
139 uv_values,
140 uv_attr.get_element_type() == AttributeElement::Vertex
141 ? std::nullopt
142 : std::optional<ConstRowMatrixView<Index>>(facet_view(mesh))};
143 }
144 }();
145
146 auto uv_index = [&](Index f, unsigned int k) {
147 if (uv_mesh.second.has_value()) {
148 return (*uv_mesh.second)(f, k);
149 } else {
150 return f * 3 + k;
151 }
152 };
153
154 ExactPredicatesShewchuk predicates;
155 for (Index f = 0; f < mesh.get_num_facets(); ++f) {
156 Eigen::RowVector2d p0 = uv_mesh.first.row(uv_index(f, 0)).template cast<double>();
157 Eigen::RowVector2d p1 = uv_mesh.first.row(uv_index(f, 1)).template cast<double>();
158 Eigen::RowVector2d p2 = uv_mesh.first.row(uv_index(f, 2)).template cast<double>();
159 auto r = predicates.orient2D(p0.data(), p1.data(), p2.data());
160 if (r <= 0) {
161 throw Error(
162 fmt::format(
163 "The input mesh has flipped UVs:\n p0=({:.3g})\n p1=({:.3g})\n p2=("
164 "{:.3g})\n"
165 "Please fix the input mesh before proceeding.",
166 fmt::join(p0, ", "),
167 fmt::join(p1, ", "),
168 fmt::join(p2, ", ")));
169 }
170 }
171}
172
173//
174// Jitters texel coordinates to avoid creating rank-deficient systems when a texture vertex falls
175// exactly on a texel center.
176//
177// Consider the case when a (boundary) texture vertex falls at integer location (i,j). The code
178// "activates" all texels supported on that vertex . Depending on how you handle open/closed
179// intervals (and taking into account issues of rounding), in principle you could activate any of
180// the 9 texels in [i-1,i+1]x[j-1,j+1]. But of these 9 only the center one is actually supported on
181// the vertex. If it is also the case that all the adjacent texture vertices are on one side, this
182// could lead to problems.
183//
184// For example, if the vertices are all to the right of i, then the texels {i-1}x[j-1,j+1] will not
185// be supported anywhere on the chart and the associated entries in its mass-matrix row will all be
186// zero. And, unless that DoF is removed, this causes the linear system to be rank deficient,
187// resulting in issues for the numerical factorization.
188//
189// This problem is removed by slightly jittering texture coordinates to move them off the texture
190// lattice edges, so that a given texture vertex can be assumed to always have four well-defined
191// texels supporting it.
192//
193// @note Another alternative is to use a small cutoff distance to avoid activating texels that
194// have almost no support when visiting a seam texture vertex.
195//
196template <typename Scalar>
197void jitter_texture(
198 span<Scalar> texcoords_buffer,
199 unsigned int width,
200 unsigned int height,
201 double epsilon = 1e-4)
202{
203 if (std::abs(epsilon) < std::numeric_limits<double>().denorm_min()) {
204 return;
205 }
206
207 Scalar jitter_scale = static_cast<Scalar>(epsilon / std::max<unsigned int>(width, height));
208 std::mt19937 gen;
209 std::uniform_real_distribution<Scalar> dist(-jitter_scale, jitter_scale);
210 for (auto& x : texcoords_buffer) {
211 x += dist(gen);
212 }
213}
214
215template <typename Scalar, typename Index>
216struct MeshWrapper
217{
218 MeshWrapper(const SurfaceMesh<Scalar, Index>& mesh_)
219 : mesh(mesh_)
220 {}
221
222 size_t num_simplices() const { return static_cast<size_t>(mesh.get_num_facets()); }
223 size_t num_vertices() const { return static_cast<size_t>(mesh.get_num_vertices()); }
224 size_t num_texcoords() const { return texcoords.size() / K; }
225
226 Vector<double, Dim> vertex(size_t i) const
227 {
229 for (unsigned int d = 0; d < Dim; d++) {
230 p[d] = static_cast<double>(vertices[i * Dim + d]);
231 }
232 return p;
233 }
234
235 Vector<double, K> texcoord(size_t i) const
236 {
238 for (unsigned int k = 0; k < K; k++) {
239 q[k] = static_cast<double>(texcoords[i * K + k]);
240 }
241 return q;
242 }
243
244 Vector<double, K> vflipped_texcoord(size_t i) const
245 {
247 for (unsigned int k = 0; k < K; k++) {
248 q[k] = static_cast<double>(texcoords[i * K + k]);
249 }
250 q[1] = 1.0 - q[1];
251 return q;
252 }
253
254 int vertex_index(size_t f, unsigned int k) const
255 {
256 return static_cast<int>(vertex_indices[f * (K + 1) + k]);
257 }
258
259 int texture_index(size_t f, unsigned int k) const
260 {
261 switch (texture_element) {
262 case AttributeElement::Indexed: return static_cast<int>(texture_indices[f * (K + 1) + k]);
263 case AttributeElement::Vertex: return static_cast<int>(vertex_indices[f * (K + 1) + k]);
264 case AttributeElement::Corner: return static_cast<int>(f * (K + 1) + k);
265 default: la_debug_assert("Unsupported texture element type"); return 0;
266 }
267 }
268
269 Simplex<double, K, K> simplex_texcoords(size_t f) const
270 {
271 Simplex<double, K, K> s;
272 for (unsigned int k = 0; k <= K; k++) {
273 s[k] = texcoord(texture_index(f, k));
274 }
275 return s;
276 }
277
278 Simplex<double, K, K> vflipped_simplex_texcoords(size_t f) const
279 {
280 Simplex<double, K, K> s;
281 for (unsigned int k = 0; k <= K; k++) {
282 s[k] = vflipped_texcoord(texture_index(f, k));
283 }
284 return s;
285 }
286
287 Simplex<double, Dim, K> simplex_vertices(size_t f) const
288 {
289 Simplex<double, Dim, K> s;
290 for (unsigned int k = 0; k <= K; k++) {
291 s[k] = vertex(vertex_index(f, k));
292 }
293 return s;
294 }
295
296 SimplexIndex<K> facet_indices(size_t f) const
297 {
298 SimplexIndex<K> simplex;
299 for (unsigned int k = 0; k <= K; ++k) {
300 simplex[k] = static_cast<int>(vertex_indices[f * (K + 1) + k]);
301 }
302 return simplex;
303 }
304
306 span<const Scalar> vertices;
307 span<Scalar> texcoords;
308 span<const Index> vertex_indices;
309 span<const Index> texture_indices;
311};
312
313template <typename Scalar, typename Index>
314MeshWrapper<Scalar, Index> create_mesh_wrapper(
315 const SurfaceMesh<Scalar, Index>& mesh_in,
316 RequiresIndexedTexcoords requires_indexed_texcoords,
317 CheckFlippedUV check_flipped_uv)
318{
319 MeshWrapper wrapper(mesh_in);
320 SurfaceMesh<Scalar, Index>& _mesh = wrapper.mesh;
321
323
324 // Get the texcoord id (and set the texcoords if they weren't already)
325 AttributeId texcoord_id;
326
327 // If the mesh comes with UVs
328 if (auto res = find_matching_attribute(_mesh, AttributeUsage::UV)) {
329 texcoord_id = res.value();
330 } else {
331 la_runtime_assert(false, "Requires uv coordinates.");
332 }
333 // Make sure the UV coordinate type is the same as that of the vertices
334 if (!_mesh.template is_attribute_type<Scalar>(texcoord_id)) {
335 logger().warn(
336 "Input uv coordinates do not have the same scalar type as the input points. Casting "
337 "attribute.");
338 texcoord_id = cast_attribute_in_place<Scalar>(_mesh, texcoord_id);
339 }
340
341 // Make sure the UV coordinates are indexed
342 if (requires_indexed_texcoords == RequiresIndexedTexcoords::Yes &&
344 logger().warn("UV coordinates are not indexed. Welding.");
345 texcoord_id = map_attribute_in_place(_mesh, texcoord_id, AttributeElement::Indexed);
346 weld_indexed_attribute(_mesh, texcoord_id);
347 }
348
349 // Make sure that the number of corners is equal to (K+1) time sthe number of simplices
351 _mesh.get_num_corners() == _mesh.get_num_facets() * (K + 1),
352 "Numer of corners doesn't match the number of simplices");
353
354 if (check_flipped_uv == CheckFlippedUV::Yes) {
355 check_for_flipped_uv(_mesh, texcoord_id);
356 }
357
358 wrapper.vertices = _mesh.get_vertex_to_position().get_all();
359 wrapper.vertex_indices = _mesh.get_corner_to_vertex().get_all();
360 if (_mesh.is_attribute_indexed(texcoord_id)) {
361 auto& uv_attr = _mesh.template ref_indexed_attribute<Scalar>(texcoord_id);
362 wrapper.texcoords = uv_attr.values().ref_all();
363 wrapper.texture_indices = uv_attr.indices().get_all();
364 wrapper.texture_element = AttributeElement::Indexed;
365 } else {
366 auto& uv_attr = _mesh.template ref_attribute<Scalar>(texcoord_id);
367 wrapper.texcoords = uv_attr.ref_all();
368 wrapper.texture_indices = {};
369 wrapper.texture_element = uv_attr.get_element_type();
370 }
371
372 return wrapper;
373}
374
375// Pad input texture to ensure that texture coordinates fall within the rectangle defined by the
376// _centers_ of the corner texels.
377template <typename Scalar, typename Index>
378Padding create_padding(MeshWrapper<Scalar, Index>& wrapper, unsigned int width, unsigned int height)
379{
380 static_assert(sizeof(std::array<Scalar, 2>) == 2 * sizeof(Scalar));
382 reinterpret_cast<std::array<Scalar, 2>*>(wrapper.texcoords.data()),
383 wrapper.num_texcoords());
384 Padding padding;
385 padding = Padding::init<Scalar>(width, height, texcoords);
386 padding.pad(width, height, texcoords);
387 return padding;
388}
389
390} // namespace mesh_utils
391
392} // namespace lagrange::texproc
AttributeElement get_element_type() const
Gets the attribute element type.
Definition Attribute.h:101
lagrange::span< const ValueType > get_all() const
Returns a read-only view of the buffer spanning num elements x num channels.
Definition Attribute.cpp:512
virtual short orient2D(double p1[2], double p2[2], double p3[2]) const
Exact 2D orientation test.
Definition ExactPredicatesShewchuk.cpp:37
A general purpose polygonal mesh class.
Definition SurfaceMesh.h:66
const AttributeBase & get_attribute_base(std::string_view name) const
Gets a read-only reference to the base class of attribute given its name.
Definition SurfaceMesh.cpp:1276
bool is_attribute_indexed(std::string_view name) const
Determines whether the specified attribute is indexed.
Definition SurfaceMesh.cpp:1235
const Attribute< Index > & get_corner_to_vertex() const
Gets a read-only reference to the corner -> vertex id attribute.
Definition SurfaceMesh.cpp:1399
Index get_num_facets() const
Retrieves the number of facets.
Definition SurfaceMesh.h:678
const Attribute< Scalar > & get_vertex_to_position() const
Gets a read-only reference to the vertex -> positions attribute.
Definition SurfaceMesh.cpp:1387
Index get_num_corners() const
Retrieves the number of corners.
Definition SurfaceMesh.h:685
LA_CORE_API spdlog::logger & logger()
Retrieves the current logger.
Definition Logger.cpp:40
AttributeId map_attribute_in_place(SurfaceMesh< Scalar, Index > &mesh, AttributeId id, AttributeElement new_element)
Map attribute values to a different element type.
Definition map_attribute.cpp:270
uint32_t AttributeId
Identified to be used to access an attribute.
Definition AttributeFwd.h:73
AttributeElement
Type of element to which the attribute is attached.
Definition AttributeFwd.h:26
@ UV
Mesh attribute must have exactly 2 channels.
Definition AttributeFwd.h:62
@ Scalar
Mesh attribute must have exactly 1 channel.
Definition AttributeFwd.h:56
@ Value
Values that are not attached to a specific element.
Definition AttributeFwd.h:42
@ Indexed
Indexed mesh attributes.
Definition AttributeFwd.h:45
@ Corner
Per-corner mesh attributes.
Definition AttributeFwd.h:37
@ Vertex
Per-vertex mesh attributes.
Definition AttributeFwd.h:28
AttributeId cast_attribute_in_place(SurfaceMesh< Scalar, Index > &mesh, AttributeId attribute_id)
Cast an attribute in place to a different value type.
Definition cast_attribute.cpp:68
std::optional< AttributeId > find_matching_attribute(const SurfaceMesh< Scalar, Index > &mesh, const AttributeMatcher &options)
Finds the first attribute with the specified usage/element type/number of channels.
Definition find_matching_attributes.cpp:37
void triangulate_polygonal_facets(SurfaceMesh< Scalar, Index > &mesh, const TriangulationOptions &options={})
Triangulate polygonal facets of a mesh using a prescribed set of rules.
Definition triangulate_polygonal_facets.cpp:520
SurfaceMesh< ToScalar, ToIndex > cast(const SurfaceMesh< FromScalar, FromIndex > &source_mesh, const AttributeFilter &convertible_attributes={}, std::vector< std::string > *converted_attributes_names=nullptr)
Cast a mesh to a mesh of different scalar and/or index type.
ConstRowMatrixView< ValueType > matrix_view(const Attribute< ValueType > &attribute)
Returns a read-only view of a given attribute in the form of an Eigen matrix.
Definition views.cpp:35
Eigen::Matrix< Scalar, Eigen::Dynamic, 1 > Vector
Type alias for one-dimensional column Eigen vectors.
Definition views.h:79
ConstRowMatrixView< ValueType > reshaped_view(const Attribute< ValueType > &attribute, size_t num_cols)
Returns a read-only view of a given single-channel attribute in the form of an Eigen matrix with a pr...
Definition views.cpp:71
ConstRowMatrixView< Index > facet_view(const SurfaceMesh< Scalar, Index > &mesh)
Returns a read-only view of a mesh facets in the form of an Eigen matrix.
Definition views.cpp:170
const Eigen::Map< const RowMatrix< Scalar >, Eigen::Unaligned > ConstRowMatrixView
Type alias for row-major const matrix view.
Definition views.h:75
#define la_runtime_assert(...)
Runtime assertion check.
Definition assert.h:174
#define la_debug_assert(...)
Debug assertion check.
Definition assert.h:194
::nonstd::span< T, Extent > span
A bounds-safe view for sequences of objects.
Definition span.h:27
@ Error
Throw an error if collision is detected.
Definition MappingPolicy.h:24