Lagrange
project_attributes_directional.h
1/*
2 * Copyright 2020 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 <lagrange/MeshTrait.h>
15#include <lagrange/bvh/project_attributes_closest_vertex.h>
16#include <lagrange/create_mesh.h>
17#include <lagrange/raycasting/create_ray_caster.h>
18#include <lagrange/raycasting/project_attributes_closest_point.h>
19#include <lagrange/raycasting/project_options.h>
20#include <lagrange/utils/safe_cast.h>
21
22// clang-format off
23#include <lagrange/utils/warnoff.h>
24#include <igl/bounding_box_diagonal.h>
25#include <lagrange/utils/warnon.h>
26// clang-format on
27
28#include <tbb/parallel_for.h>
29
30#include <algorithm>
31#include <string>
32#include <type_traits>
33#include <vector>
34
35namespace lagrange {
36namespace raycasting {
37
69template <
70 typename SourceMeshType,
71 typename TargetMeshType,
72 typename DerivedVector,
73 typename DefaultScalar = typename SourceMeshType::Scalar>
75 const SourceMeshType& source,
76 TargetMeshType& target,
77 const std::vector<std::string>& names,
78 const Eigen::MatrixBase<DerivedVector>& direction,
79 CastMode cast_mode = CastMode::BOTH_WAYS,
80 WrapMode wrap_mode = WrapMode::CONSTANT,
81 DefaultScalar default_value = DefaultScalar(0),
82 std::function<void(typename TargetMeshType::Index, bool)> user_callback = nullptr,
83 EmbreeRayCaster<ScalarOf<SourceMeshType>>* ray_caster = nullptr,
84 std::function<bool(IndexOf<TargetMeshType>)> skip_vertex = nullptr)
85{
86 static_assert(MeshTrait<SourceMeshType>::is_mesh(), "Input type is not Mesh");
87 static_assert(MeshTrait<TargetMeshType>::is_mesh(), "Output type is not Mesh");
88 la_runtime_assert(source.get_vertex_per_facet() == 3);
89
90 // Typedef festival because templates...
91 using Scalar = typename SourceMeshType::Scalar;
92 using Index = typename TargetMeshType::Index;
93 using SourceArray = typename SourceMeshType::AttributeArray;
94 using TargetArray = typename SourceMeshType::AttributeArray;
95 using Point = typename EmbreeRayCaster<Scalar>::Point;
96 using Direction = typename EmbreeRayCaster<Scalar>::Direction;
97 using RayCasterIndex = typename EmbreeRayCaster<Scalar>::Index;
98 using Scalar4 = typename EmbreeRayCaster<Scalar>::Scalar4;
99 using Index4 = typename EmbreeRayCaster<Scalar>::Index4;
100 using Point4 = typename EmbreeRayCaster<Scalar>::Point4;
101 using Direction4 = typename EmbreeRayCaster<Scalar>::Direction4;
102 using Mask4 = typename EmbreeRayCaster<Scalar>::Mask4;
103
104 // We need to convert to a shared_ptr AND the ray caster will make another copy of the data..
105 std::unique_ptr<EmbreeRayCaster<Scalar>> engine;
106 if (!ray_caster) {
107 auto mesh = lagrange::to_shared_ptr(
108 lagrange::create_mesh(source.get_vertices(), source.get_facets()));
109 // Robust mode gives slightly more accurate results...
110 engine = create_ray_caster<Scalar>(EMBREE_ROBUST, BUILD_QUALITY_HIGH);
111
112 // Gosh why do I need to specify a transform here?
113 engine->add_mesh(mesh, Eigen::Matrix<Scalar, 4, 4>::Identity());
114
115 // Do a dummy raycast to trigger scene update, otherwise `cast()` will not work in
116 // multithread mode... (this is why we need const-safety...)
117 engine->cast(Point(0, 0, 0), Direction(0, 0, 1));
118 ray_caster = engine.get();
119 } else {
120 logger().debug("Using provided ray-caster");
121 }
122
123 // Store pointer to source/target arrays
124 std::vector<const SourceArray*> source_attrs;
125 source_attrs.reserve(names.size());
126 std::vector<TargetArray> target_attrs(names.size());
127 for (size_t k = 0; k < names.size(); ++k) {
128 const auto& name = names[k];
129 la_runtime_assert(source.has_vertex_attribute(name));
130 source_attrs.push_back(&source.get_vertex_attribute(name));
131 if (target.has_vertex_attribute(name)) {
132 target.export_vertex_attribute(name, target_attrs[k]);
133 } else {
134 target_attrs[k].resize(target.get_num_vertices(), source_attrs[k]->cols());
135 }
136 }
137
138 auto diag = igl::bounding_box_diagonal(source.get_vertices());
139
140 // Using `char` instead of `bool` because we write concurrently to this
141 std::vector<char> is_hit;
142 if (wrap_mode != WrapMode::CONSTANT) {
143 is_hit.assign(target.get_num_vertices(), false);
144 }
145
146 Index num_vertices = target.get_num_vertices();
147 Index num_packets = (num_vertices + 3) / 4;
148
149 Direction4 dirs;
150 dirs.row(0) = direction.normalized().transpose();
151 for (int i = 1; i < 4; ++i) {
152 dirs.row(i) = dirs.row(0);
153 }
154 Direction4 dirs2 = -dirs;
155
156 tbb::parallel_for(Index(0), num_packets, [&](Index packet_index) {
157 Index batchsize = std::min(num_vertices - (packet_index << 2), 4);
158 Mask4 mask = Mask4::Constant(-1);
159 Point4 origins;
160
161 int num_skipped_in_packet = 0;
162 for (Index b = 0; b < batchsize; ++b) {
163 Index i = (packet_index << 2) + b;
164 if (skip_vertex && skip_vertex(i)) {
165 logger().trace("skipping vertex: {}", i);
166 if (!is_hit.empty()) {
167 is_hit[i] = true;
168 }
169 mask(b) = 0;
170 ++num_skipped_in_packet;
171 continue;
172 }
173
174 origins.row(b) = target.get_vertices().row(i);
175 }
176
177 if (num_skipped_in_packet == batchsize) return;
178
179 for (Index b = batchsize; b < 4; ++b) {
180 mask(b) = 0;
181 }
182
183 Index4 mesh_indices;
184 Index4 instance_indices;
185 Index4 facet_indices;
186 Scalar4 ray_depths;
187 Point4 barys;
188 Point4 normals;
189 uint8_t hits = ray_caster->cast4(
190 batchsize,
191 origins,
192 dirs,
193 mask,
194 mesh_indices,
195 instance_indices,
196 facet_indices,
197 ray_depths,
198 barys,
199 normals);
200
201 if (cast_mode == CastMode::BOTH_WAYS) {
202 // Try again in the other direction. Slightly offset ray origin, and keep closest point.
203 Point4 origins2 = origins + Scalar(1e-6) * diag * dirs;
204 Index4 mesh_indices2;
205 Index4 instance_indices2;
206 Index4 facet_indices2;
207 Scalar4 ray_depths2;
208 Point4 barys2;
209 Point4 norms2;
210 uint8_t hits2 = ray_caster->cast4(
211 batchsize,
212 origins2,
213 dirs2,
214 mask,
215 mesh_indices2,
216 instance_indices2,
217 facet_indices2,
218 ray_depths2,
219 barys2,
220 norms2);
221
222 for (Index b = 0; b < batchsize; ++b) {
223 if (!mask(b)) continue;
224 auto len2 = std::abs(Scalar(1e-6) * diag - ray_depths2(b));
225 bool hit = hits & (1 << b);
226 bool hit2 = hits2 & (1 << b);
227 if (hit2 && (!hit || len2 < ray_depths(b))) {
228 hits |= 1 << b;
229 mesh_indices(b) = mesh_indices2(b);
230 facet_indices(b) = facet_indices2(b);
231 barys.row(b) = barys2.row(b);
232 }
233 }
234 }
235 for (Index b = 0; b < batchsize; ++b) {
236 if (!mask(b)) continue;
237 bool hit = hits & (1 << b);
238 Index i = (packet_index << 2) + b;
239 if (hit) {
240 // Hit occurred, interpolate data
242 facet_indices(b) >= 0 &&
243 facet_indices(b) < static_cast<RayCasterIndex>(source.get_num_facets()));
244 auto face = source.get_facets().row(facet_indices(b));
245 for (size_t k = 0; k < source_attrs.size(); ++k) {
246 target_attrs[k].row(i).setZero();
247 for (int lv = 0; lv < 3; ++lv) {
248 target_attrs[k].row(i) += source_attrs[k]->row(face[lv]) * barys(b, lv);
249 }
250 }
251 } else {
252 // Not hit. Set values according to wrap_mode + call user-callback at the end if
253 // needed
254 for (size_t k = 0; k < source_attrs.size(); ++k) {
255 switch (wrap_mode) {
257 target_attrs[k].row(i).setConstant(safe_cast<Scalar>(default_value));
258 break;
259 default: break;
260 }
261 }
262 }
263 if (!is_hit.empty()) {
264 is_hit[i] = hit;
265 }
266 if (user_callback) {
267 user_callback(i, hit);
268 }
269 }
270 });
271
272 // Not super pretty way, we still need to separately add/create the attribute,
273 // THEN import it without copy. Would be better if we could get a ref to it.
274 for (size_t k = 0; k < names.size(); ++k) {
275 const auto& name = names[k];
276 target.add_vertex_attribute(name);
277 target.import_vertex_attribute(name, target_attrs[k]);
278 }
279
280 // If there is any vertex without a hit, we defer to the relevant functions with filtering
281 if (wrap_mode != WrapMode::CONSTANT) {
282 bool all_hit = std::all_of(is_hit.begin(), is_hit.end(), [](char x) { return bool(x); });
283 if (!all_hit) {
284 if (wrap_mode == WrapMode::CLOSEST_POINT) {
285 project_attributes_closest_point(source, target, names, ray_caster, [&](Index i) {
286 return bool(is_hit[i]);
287 });
288 } else if (wrap_mode == WrapMode::CLOSEST_VERTEX) {
289 ::lagrange::bvh::project_attributes_closest_vertex(
290 source,
291 target,
292 names,
293 [&](Index i) { return bool(is_hit[i]); });
294 } else {
295 throw std::runtime_error("not implemented");
296 }
297 }
298 }
299}
300
301} // namespace raycasting
302} // namespace lagrange
A wrapper for Embree's raycasting API to compute ray intersections with (instances of) meshes.
Definition: EmbreeRayCaster.h:47
LA_CORE_API spdlog::logger & logger()
Retrieves the current logger.
Definition: Logger.cpp:40
#define la_runtime_assert(...)
Runtime assertion check.
Definition: assert.h:169
@ EMBREE_ROBUST
Corresponds to RTC_SCENE_FLAG_ROBUST.
Definition: create_ray_caster.h:25
CastMode
Ray-casting mode.
Definition: project_options.h:28
@ BOTH_WAYS
Cast a ray both forward and backward in the prescribed direction.
WrapMode
Wraping mode for vertices without a hit.
Definition: project_options.h:34
@ CLOSEST_POINT
Interpolate attribute from the closest point on the source mesh.
@ CONSTANT
Fill with a constant value (defaults to 0).
@ CLOSEST_VERTEX
Copy attribute from the closest vertex on the source mesh.
void project_attributes_directional(const SourceMeshType &source, TargetMeshType &target, const std::vector< std::string > &names, const Eigen::MatrixBase< DerivedVector > &direction, CastMode cast_mode=CastMode::BOTH_WAYS, WrapMode wrap_mode=WrapMode::CONSTANT, DefaultScalar default_value=DefaultScalar(0), std::function< void(typename TargetMeshType::Index, bool)> user_callback=nullptr, EmbreeRayCaster< ScalarOf< SourceMeshType > > *ray_caster=nullptr, std::function< bool(IndexOf< TargetMeshType >)> skip_vertex=nullptr)
Project vertex attributes from one mesh to another, by projecting target vertices along a prescribed ...
Definition: project_attributes_directional.h:74
void project_attributes_closest_point(const SourceMeshType &source, TargetMeshType &target, const std::vector< std::string > &names, EmbreeRayCaster< ScalarOf< SourceMeshType > > *ray_caster=nullptr, std::function< bool(IndexOf< TargetMeshType >)> skip_vertex=nullptr)
Project vertex attributes from one mesh to another, by copying attributes from the closest point on t...
Definition: project_attributes_closest_point.h:49
@ BUILD_QUALITY_HIGH
Corresponds to RTC_BUILD_QUALITY_HIGH.
Definition: create_ray_caster.h:32
Main namespace for Lagrange.
Definition: AABBIGL.h:30
auto create_mesh(const Eigen::MatrixBase< DerivedV > &vertices, const Eigen::MatrixBase< DerivedF > &facets)
This function create a new mesh given the vertex and facet arrays by copying data into the Mesh objec...
Definition: create_mesh.h:39
std::shared_ptr< T > to_shared_ptr(std::unique_ptr< T > &&ptr)
Helper for automatic type deduction for unique_ptr to shared_ptr conversion.
Definition: common.h:84
MeshTrait class provide compiler check for different mesh types.
Definition: MeshTrait.h:108