14#include <lagrange/Logger.h>
15#include <lagrange/internal/constants.h>
16#include <lagrange/raycasting/RayCaster.h>
17#include <lagrange/scene/SimpleScene.h>
18#include <lagrange/scene/simple_scene_bbox.h>
19#include <lagrange/utils/AdjacencyList.h>
20#include <lagrange/utils/assert.h>
21#include <lagrange/utils/geometry3d.h>
22#include <lagrange/utils/range.h>
23#include <lagrange/views.h>
26#include <Eigen/Geometry>
40namespace lagrange::raycasting::detail {
51inline double binomial_upper_tail(uint64_t n, uint64_t num_trials,
double p)
53 if (n == 0)
return 1.0;
54 if (n > num_trials)
return 0.0;
55 const double q = 1.0 - p;
56 double pmf = std::pow(q,
static_cast<double>(num_trials));
58 for (uint64_t k = 1; k < n; ++k) {
59 pmf *=
static_cast<double>(num_trials - k + 1) /
static_cast<double>(k) * (p / q);
69inline bool is_confidently_visible(uint64_t n, uint64_t num_trials,
double threshold,
double alpha)
71 if (n == 0 || num_trials == 0)
return false;
72 if (threshold <= 0.0)
return true;
73 if (threshold >= 1.0)
return false;
74 if (
static_cast<double>(n) <=
static_cast<double>(num_trials) * threshold)
return false;
76 constexpr uint64_t exact_cap = 1000;
77 if (num_trials <= exact_cap)
return binomial_upper_tail(n, num_trials, threshold) <= alpha;
79 const double variance =
static_cast<double>(num_trials) * threshold * (1.0 - threshold);
80 const double z = (
static_cast<double>(n) - 0.5 -
static_cast<double>(num_trials) * threshold) /
82 return 0.5 * std::erfc(z / std::sqrt(2.0)) <= alpha;
90[[nodiscard]]
constexpr double compute_lambda(
double running_mean,
double running_var,
double y0)
92 const double lambda = (running_mean - y0) / std::max(running_var, 1e-9);
93 return std::clamp(lambda, 0.0, 0.5 / std::max(y0, 1e-9));
97[[nodiscard]]
inline double logwealth_step(
double lambda,
double y,
double y0)
99 return std::log1p(lambda * (y - y0));
104template <
typename Scalar,
typename Index>
107 const auto bbox = scene::simple_scene_bbox(scene);
108 if (bbox.isEmpty())
return 0.0;
109 const Eigen::Vector3<Scalar> d = bbox.sizes().cwiseMax(
Scalar(0));
110 return 2.0 * (
static_cast<double>(d.x()) * d.y() +
static_cast<double>(d.y()) * d.z() +
111 static_cast<double>(d.x()) * d.z());
115template <
typename Scalar>
116Eigen::Array4<Scalar> generate_vec4(
const size_t i)
118 constexpr double phi_1 = 1.1673039782614186842560459;
119 constexpr double phi_2 = phi_1 * phi_1;
120 constexpr double phi_3 = phi_2 * phi_1;
121 constexpr double phi_4 = phi_2 * phi_2;
122 const Eigen::Array4d phi(phi_1, phi_2, phi_3, phi_4);
124 const Eigen::Array4d shifted =
static_cast<double>(i) / phi + 0.5;
125 return (shifted - shifted.floor()).template
cast<Scalar>();
128template <
typename Scalar>
133 Eigen::RowVector2<Scalar> bary;
134 Eigen::RowVector3<Scalar> direction;
137 explicit RaySampler(
const Eigen::RowVector3<Scalar>& normal)
140 Eigen::Vector3<Scalar> x_col, y_col;
142 m_x_axis = x_col.transpose();
143 m_y_axis = y_col.transpose();
149 : m_normal(other.m_normal)
150 , m_x_axis(other.m_x_axis)
151 , m_y_axis(other.m_y_axis)
152 , m_sample_index(other.m_sample_index.load(std::memory_order_relaxed))
158 const Eigen::RowVector3<Scalar>& get_normal()
const {
return m_normal; }
165 generate_vec4<Scalar>(m_sample_index.fetch_add(1, std::memory_order_relaxed));
166 const Scalar phi = 2 *
static_cast<Scalar>(lagrange::internal::pi) * vec4[0];
167 const Scalar r2 = vec4[1];
168 const Scalar r = std::sqrt(r2);
169 const Scalar x = r * std::cos(phi);
170 const Scalar y = r * std::sin(phi);
173 result.direction = x * m_x_axis + y * m_y_axis + z * m_normal;
174 result.bary = vec4.template tail<2>();
175 if (result.bary[0] + result.bary[1] > 1) {
177 result.direction = -result.direction;
178 result.bary = Eigen::RowVector2<Scalar>::Ones() - result.bary;
188 generate_vec4<Scalar>(m_sample_index.fetch_add(1, std::memory_order_relaxed));
189 const double kappa_d =
static_cast<double>(kappa);
190 const double u =
static_cast<double>(vec4[0]);
191 const double arg = u + (1.0 - u) * std::exp(-2.0 * kappa_d);
192 const Scalar w =
static_cast<Scalar>(1.0 + std::log(arg) / kappa_d);
194 const Scalar phi = 2 *
static_cast<Scalar>(lagrange::internal::pi) * vec4[1];
195 Eigen::Vector3<Scalar> e1, e2;
199 w * axis + s * (std::cos(phi) * e1.transpose() + std::sin(phi) * e2.transpose());
200 result.bary = vec4.template tail<2>();
201 if (result.bary[0] + result.bary[1] > 1) {
202 result.bary = Eigen::RowVector2<Scalar>::Ones() - result.bary;
204 la_debug_assert(result.direction.allFinite(),
"sample_vmf: non-finite direction");
209 const Eigen::RowVector3<Scalar> m_normal;
210 Eigen::RowVector3<Scalar> m_x_axis;
211 Eigen::RowVector3<Scalar> m_y_axis;
212 std::atomic<size_t> m_sample_index{0};
217template <
typename Scalar>
220 Eigen::Vector3<Scalar> base;
221 Eigen::Vector3<Scalar> edge0;
222 Eigen::Vector3<Scalar> edge1;
226template <
typename Scalar>
227Eigen::RowVector3<Scalar> triangle_position(
229 const Eigen::RowVector2<Scalar>& bary)
231 return (t.base + bary(0) * t.edge0 + bary(1) * t.edge1).transpose();
237 static constexpr size_t capacity = 16;
239 RayCaster::Point16f origins;
240 RayCaster::Direction16f directions;
241 RayCaster::Float16 tmins;
244 template <
typename Origin,
typename Direction>
245 void push(
const Origin& origin,
const Direction& direction,
float tmin = 1e-6f)
247 origins.row(count) = origin.template cast<float>();
248 directions.row(count) = direction.template cast<float>();
253 bool full()
const {
return count == capacity; }
254 bool empty()
const {
return count == 0; }
255 void clear() { count = 0; }
257 uint32_t cast(
const RayCaster& caster)
const
259 return caster.
occluded16(origins, directions, count, tmins);
267template <
typename Scalar>
270 std::vector<Scalar> facet_areas;
271 std::vector<RaySampler<Scalar>> ray_samplers;
272 std::vector<FacetTriangle<Scalar>> facet_triangles;
277template <
typename Scalar,
typename Index>
278double initialize_instance_geometry(
280 const Eigen::Transform<Scalar, 3, Eigen::Affine>& transform,
282 std::vector<Eigen::Vector3<Scalar>>& world_vertices)
284 const Index num_facets = mesh.get_num_facets();
285 instance.facet_areas.resize(num_facets);
286 instance.facet_triangles.resize(num_facets);
287 instance.ray_samplers.clear();
288 instance.ray_samplers.reserve(num_facets);
292 world_vertices.resize(mesh.get_num_vertices());
294 world_vertices[v] = transform * Eigen::Vector3<Scalar>(vertices.row(v).transpose());
297 double total_area = 0.0;
299 const auto& v0 = world_vertices[facets(f, 0)];
300 const auto& v1 = world_vertices[facets(f, 1)];
301 const auto& v2 = world_vertices[facets(f, 2)];
302 const Eigen::Vector3<Scalar> edge0 = v0 - v2;
303 const Eigen::Vector3<Scalar> edge1 = v1 - v2;
304 instance.facet_triangles[f] = {v2, edge0, edge1};
306 const Eigen::Vector3<Scalar> area_vector =
Scalar(0.5) * edge0.cross(edge1);
307 const Scalar area = area_vector.norm();
308 instance.facet_areas[f] = area;
309 total_area +=
static_cast<double>(area);
311 instance.ray_samplers.emplace_back(
312 area > 0 ? Eigen::RowVector3<Scalar>(area_vector.transpose() / area)
313 : Eigen::RowVector3<Scalar>::UnitZ());
322template <
typename Scalar>
325 static constexpr int capacity = 4;
326 std::array<Eigen::Vector3<Scalar>, capacity> dir{};
327 std::array<Scalar, capacity> weight{};
330 void add(
const Eigen::Vector3<Scalar>& d,
Scalar merge_cos)
333 Scalar best_cos = merge_cos;
334 for (
int i = 0; i < size; ++i) {
335 const Scalar c = dir[i].dot(d);
343 dir[best] = (dir[best] + (d - dir[best]) / weight[best]).normalized();
344 }
else if (size < capacity) {
350 for (
int i = 1; i < capacity; ++i)
351 if (weight[i] < weight[lo]) lo = i;
359template <
typename Scalar,
typename Index>
365 std::vector<Index> active_local_facets;
367 std::optional<AdjacencyList<Index>> facet_neighbors;
371 std::vector<SeedReservoir<Scalar>> facet_seeds_snapshot;
374template <
typename Derived,
typename Scalar>
379 Derived& derived() {
return static_cast<Derived&
>(*this); }
380 const Derived& derived()
const {
return static_cast<const Derived&
>(*this); }
382 size_t num_instances()
const {
return derived().m_instances.size(); }
383 Scalar compute_total_active_weight()
const
386 return std::accumulate(r.begin(), r.end(),
Scalar(0), [&](
Scalar s,
size_t i) {
387 return s + derived().instance_active_weight(i);
391 void run_batch(uint64_t num_rays)
393 const Scalar total = compute_total_active_weight();
394 if (total <= 0)
return;
396 const auto t_start = std::chrono::steady_clock::now();
399 const Scalar inst_weight = derived().instance_active_weight(i);
400 if (inst_weight <= 0)
continue;
402 const uint64_t inst_rays =
static_cast<uint64_t
>(
403 std::round(
static_cast<double>(num_rays) * inst_weight / total));
404 if (inst_rays == 0)
continue;
406 derived().process_instance(i, inst_rays, inst_weight);
409 derived().end_batch();
411 const auto t_end = std::chrono::steady_clock::now();
412 const auto batch_ms =
413 std::chrono::duration_cast<std::chrono::milliseconds>(t_end - t_start).count();
419template <
typename Sampler,
typename Index>
420std::pair<uint64_t, uint64_t> sum_progress(
const Sampler& sampler, Index count)
422 uint64_t num_visible = 0;
423 uint64_t total_rays = 0;
424 for (Index i = 0; i < count; ++i) {
425 if (sampler.is_visible(i)) ++num_visible;
426 total_rays += sampler.num_rays_cast(i);
428 return {num_visible, total_rays};
A general purpose polygonal mesh class.
Definition SurfaceMesh.h:73
A ray caster built on top of Embree that operates directly on SurfaceMesh and SimpleScene objects.
Definition RayCaster.h:196
uint32_t occluded16(const Point16f &origins, const Direction16f &directions, const std::variant< Mask16, size_t > &active=size_t(16), const Float16 &tmin=Float16::Zero(), const Float16 &tmax=Float16::Constant(std::numeric_limits< float >::infinity())) const
Test a packet of up to 16 rays for occlusion.
Definition RayCaster.cpp:1640
Simple scene container for instanced meshes.
Definition SimpleScene.h:62
spdlog::logger & logger()
Retrieves the current logger.
Definition Logger.cpp:40
@ Scalar
Mesh attribute must have exactly 1 channel.
Definition AttributeFwd.h:56
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< Scalar > vertex_view(const SurfaceMesh< Scalar, Index > &mesh)
Returns a read-only view of the mesh vertices in the form of an Eigen matrix.
Definition views.cpp:156
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
#define la_debug_assert(...)
Debug assertion check.
Definition assert.h:197
Anytime-valid betting test helpers for a bounded mean, following Waudby-Smith & Ramdas (2024),...
Definition occluded_sampler_common.h:87
void orthogonal_frame(const Eigen::Matrix< Scalar, 3, 1 > &x, Eigen::Matrix< Scalar, 3, 1 > &y, Eigen::Matrix< Scalar, 3, 1 > &z)
Build an orthogonal frame given a single vector.
Definition geometry3d.h:125
internal::Range< Index > range(Index end)
Returns an iterable object representing the range [0, end).
Definition range.h:176
Per-instance data for OccludedFacetSampler; gates each facet individually.
Definition occluded_sampler_common.h:361
std::vector< SeedReservoir< Scalar > > facet_seeds
Per-facet escape-direction seeds, only updated in flush() from snapshot (to avoid race condition).
Definition occluded_sampler_common.h:370
std::vector< Scalar > facet_weights
Per-facet ray-allocation weight ∝ 1/tau_f = (area / mean_face_area)^size_influence.
Definition occluded_sampler_common.h:364
Precomputed world-space facet triangle for O(1) ray origins: base = V2, edge0 = V0 - V2,...
Definition occluded_sampler_common.h:219
Definition occluded_sampler_common.h:376
Per-instance precomputation shared by both samplers.
Definition occluded_sampler_common.h:269
16-ray SIMD packet for RayCaster::occluded16. push widens to float on entry.
Definition occluded_sampler_common.h:236
uint32_t occupied_mask() const
Low count bits set — masks off undefined slots in a partial packet's cast mask.
Definition occluded_sampler_common.h:263
Definition occluded_sampler_common.h:132
Definition occluded_sampler_common.h:130
Sample sample_vmf(const Eigen::RowVector3< Scalar > &axis, Scalar kappa)
Sample a direction from a von Mises-Fisher lobe (mean axis, concentration kappa) on the full sphere,...
Definition occluded_sampler_common.h:185
Sample sample_cosine()
Bi-hemisphere sample via Malley's method: when bary reflection fires (u+v > 1), the direction is also...
Definition occluded_sampler_common.h:162
Bounded set of escape-direction "seeds" for a facet, feeding the adaptive vMF-mixture proposal.
Definition occluded_sampler_common.h:324