Skip to content

Commit 685d72f

Browse files
sawenzelclaude
andcommitted
Add the CADSupport module with the exact BVH surface solid
This adds the module Detectors/CADSupport with O2BVHSurfaceSolid, an exact representation of a CAD solid. - O2BVHSurfaceSolid holds a CAD solid as trimmed surfaces in a BVH and loads it from a surfaces_*.bin sidecar. - O2BVHAssembly answers navigation queries over a set of these solids. - CADGeometryUtils lives in the module under namespace o2::cad, and ExternalModule and ExternalDetector link O2::CADSupport. - O2Tessellated's ray queries prune on hit, which speeds up every tessellated geometry in o2-sim. - O2Tessellated gains GetPointsOnSegments, covered by the new test testO2Tessellated. - O2OverlapCheck sorts pairs of placed solids into disjoint, touching and interpenetrating by overlap depth. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
1 parent b7d563b commit 685d72f

36 files changed

Lines changed: 21961 additions & 37 deletions

Detectors/Base/CMakeLists.txt

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,6 @@ o2_add_library(DetectorsBase
3737
src/GlobalParams.cxx
3838
src/O2Tessellated.cxx
3939
src/TGeoGeometryUtils.cxx
40-
src/CADGeometryUtils.cxx
4140
PUBLIC_LINK_LIBRARIES FairRoot::Base
4241
O2::CommonUtils
4342
O2::DetectorsCommonDataFormats
@@ -90,6 +89,13 @@ o2_add_test(
9089
PUBLIC_LINK_LIBRARIES O2::DetectorsBase
9190
LABELS detectorsbase)
9291

92+
o2_add_test(
93+
O2Tessellated
94+
SOURCES test/testO2Tessellated.cxx
95+
COMPONENT_NAME DetectorsBase
96+
PUBLIC_LINK_LIBRARIES O2::DetectorsBase
97+
LABELS detectorsbase)
98+
9399
if(BUILD_SIMULATION)
94100
if (NOT APPLE)
95101
o2_add_test(

Detectors/Base/include/DetectorsBase/O2Tessellated.h

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,10 @@ class O2Tessellated : public TGeoBBox
8888
const TBuffer3D& GetBuffer3D(int reqSections, Bool_t localFrame) const override;
8989
void GetMeshNumbers(int& nvert, int& nsegs, int& npols) const override;
9090
int GetNmeshVertices() const override { return fNvert; }
91+
92+
/// Fill \a array with \a npoints points on this solid's boundary: every vertex, then deterministic R2 samples on facet interiors.
93+
Bool_t GetPointsOnSegments(Int_t npoints, Double_t* array) const override;
94+
9195
void InspectShape() const override {}
9296
TBuffer3D* MakeBuffer3D() const override;
9397
void Print(Option_t* option = "") const override;

Detectors/Base/src/O2Tessellated.cxx

Lines changed: 102 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -484,6 +484,67 @@ void O2Tessellated::GetMeshNumbers(int& nvert, int& nsegs, int& npols) const
484484
npols = GetNfacets();
485485
}
486486

487+
////////////////////////////////////////////////////////////////////////////////
488+
/// Fill array with npoints points on the solid's boundary. See the header.
489+
490+
Bool_t O2Tessellated::GetPointsOnSegments(Int_t npoints, Double_t* array) const
491+
{
492+
if (array == nullptr || npoints <= 0 || fVertices.empty()) {
493+
return kFALSE;
494+
}
495+
const int vertexCount = static_cast<int>(fVertices.size());
496+
if (npoints < vertexCount) {
497+
// Hand the caller back to SetPoints(), which gives it every vertex -- more points than asked
498+
// for, all of them exactly on the shape.
499+
return kFALSE;
500+
}
501+
for (int vertexIndex = 0; vertexIndex < vertexCount; ++vertexIndex) {
502+
fVertices[vertexIndex].CopyTo(&array[3 * vertexIndex]);
503+
}
504+
505+
const int extraCount = npoints - vertexCount;
506+
const int facetCount = static_cast<int>(fFacets.size());
507+
if (extraCount == 0) {
508+
return kTRUE;
509+
}
510+
if (facetCount == 0) {
511+
for (int extraIndex = 0; extraIndex < extraCount; ++extraIndex) {
512+
fVertices[extraIndex % vertexCount].CopyTo(&array[3 * (vertexCount + extraIndex)]);
513+
}
514+
return kTRUE;
515+
}
516+
517+
// The same deterministic R2 low-discrepancy pair O2BVHSurfaceSolid::GetPointsOnSegments uses:
518+
// what a shape hands out must depend on the shape and on nothing else.
519+
constexpr double kAlpha1 = 0.7548776662466927;
520+
constexpr double kAlpha2 = 0.5698402909980532;
521+
for (int extraIndex = 0; extraIndex < extraCount; ++extraIndex) {
522+
const int facetIndex =
523+
static_cast<int>((static_cast<long long>(extraIndex) * facetCount) / extraCount) % facetCount;
524+
const TGeoFacet& facet = fFacets[facetIndex];
525+
const int facetVertices = facet.GetNvert();
526+
double first = std::fmod(0.5 + kAlpha1 * (extraIndex + 1), 1.);
527+
double second = std::fmod(0.5 + kAlpha2 * (extraIndex + 1), 1.);
528+
if (first + second > 1.) {
529+
first = 1. - first;
530+
second = 1. - second;
531+
}
532+
// A quad facet is two triangles sharing vertex 0; pick one by the parity of the sample index
533+
// so both halves are covered.
534+
const int cornerB = (facetVertices > 3 && (extraIndex & 1)) ? 2 : 1;
535+
const int cornerC = (facetVertices > 3 && (extraIndex & 1)) ? 3 : ((facetVertices > 2) ? 2 : 1);
536+
const Vertex_t& vertexA = fVertices[facet[0]];
537+
const Vertex_t& vertexB = fVertices[facet[cornerB]];
538+
const Vertex_t& vertexC = fVertices[facet[cornerC]];
539+
const double weightA = 1. - first - second;
540+
double* slot = &array[3 * (vertexCount + extraIndex)];
541+
slot[0] = weightA * vertexA.x() + first * vertexB.x() + second * vertexC.x();
542+
slot[1] = weightA * vertexA.y() + first * vertexB.y() + second * vertexC.y();
543+
slot[2] = weightA * vertexA.z() + first * vertexB.z() + second * vertexC.z();
544+
}
545+
return kTRUE;
546+
}
547+
487548
////////////////////////////////////////////////////////////////////////////////
488549
/// Creates a TBuffer3D describing *this* shape.
489550
/// Coordinates are in local reference frame.
@@ -901,6 +962,27 @@ inline Vec3f<T> triangleNormal(const Vec3f<T>& a, const Vec3f<T>& b, const Vec3f
901962
return normalize(cross(e1, e2));
902963
}
903964

965+
/// Outward pad of every BVH leaf box, so a facet lies strictly inside the box that stands for it.
966+
constexpr float kFacetBoxPad = 0.001f;
967+
968+
/// Lowering the ray bound cannot drop a nearer facet while |origin| + |box| + distance stays below
969+
/// this: the float rounding of ray, box and traversal then stays well inside kFacetBoxPad.
970+
constexpr double kMaxPruneScale = kFacetBoxPad * (1 << 24) / 8.;
971+
972+
/// The largest hit distance that may be used as a ray bound for this origin and root box.
973+
template <typename BBox>
974+
double pruneLimit(const BBox& bbox, const double* point)
975+
{
976+
double origin = 0.;
977+
double box = 0.;
978+
for (int index = 0; index < 3; ++index) {
979+
origin = std::max(origin, std::abs(point[index]));
980+
box = std::max({box, std::abs(static_cast<double>(bbox.min[index])),
981+
std::abs(static_cast<double>(bbox.max[index]))});
982+
}
983+
return kMaxPruneScale - origin - box;
984+
}
985+
904986
} // end anonymous namespace
905987

906988
////////////////////////////////////////////////////////////////////////////////
@@ -960,6 +1042,10 @@ Double_t O2Tessellated::DistFromOutside(const Double_t* point, const Double_t* d
9601042

9611043
static constexpr bool use_robust_traversal = true;
9621044

1045+
// the ray object is ours and mutable: bvh2 re-reads tmax at every box test, so lowering it on a
1046+
// hit prunes the rest of the traversal
1047+
const double prune_limit = pruneLimit(topnode_bbox, point);
1048+
9631049
Vertex_t dir_v{dir[0], dir[1], dir[2]};
9641050
// Traverse the BVH and apply concrete object intersection in BVH leafs
9651051
bvh::v2::GrowingStack<Bvh::Index> stack;
@@ -979,6 +1065,9 @@ Double_t O2Tessellated::DistFromOutside(const Double_t* point, const Double_t* d
9791065

9801066
if (thisdist < local_step) {
9811067
local_step = thisdist;
1068+
if (local_step <= prune_limit) {
1069+
ray.tmax = truncate_roundup(local_step);
1070+
}
9821071
}
9831072
}
9841073
return false; // go on after this
@@ -1023,6 +1112,10 @@ Double_t O2Tessellated::DistFromInside(const Double_t* point, const Double_t* di
10231112

10241113
static constexpr bool use_robust_traversal = true;
10251114

1115+
// as in DistFromOutside: lowering the ray's own tmax on a hit prunes the rest of the traversal
1116+
const auto rootbox = mybvh->get_root().get_bbox();
1117+
const double prune_limit = pruneLimit(rootbox, point);
1118+
10261119
Vertex_t dir_v{dir[0], dir[1], dir[2]};
10271120
// Traverse the BVH and apply concrete object intersection in BVH leafs
10281121
bvh::v2::GrowingStack<Bvh::Index> stack;
@@ -1045,6 +1138,9 @@ Double_t O2Tessellated::DistFromInside(const Double_t* point, const Double_t* di
10451138
rayTriangle(Vertex_t{point[0], point[1], point[2]}, dir_v, v0, v1, v2, 0.);
10461139
if (t < local_step) {
10471140
local_step = t;
1141+
if (local_step <= prune_limit) {
1142+
ray.tmax = truncate_roundup(local_step);
1143+
}
10481144
}
10491145
}
10501146
return false; // go on after this
@@ -1095,12 +1191,12 @@ void O2Tessellated::BuildBVH()
10951191
const auto& v2 = fVertices[facet[1]];
10961192
const auto& v3 = fVertices[facet[2]];
10971193
BBox bbox;
1098-
bbox.min[0] = std::min(std::min(v1[0], v2[0]), v3[0]) - 0.001f;
1099-
bbox.min[1] = std::min(std::min(v1[1], v2[1]), v3[1]) - 0.001f;
1100-
bbox.min[2] = std::min(std::min(v1[2], v2[2]), v3[2]) - 0.001f;
1101-
bbox.max[0] = std::max(std::max(v1[0], v2[0]), v3[0]) + 0.001f;
1102-
bbox.max[1] = std::max(std::max(v1[1], v2[1]), v3[1]) + 0.001f;
1103-
bbox.max[2] = std::max(std::max(v1[2], v2[2]), v3[2]) + 0.001f;
1194+
bbox.min[0] = std::min(std::min(v1[0], v2[0]), v3[0]) - kFacetBoxPad;
1195+
bbox.min[1] = std::min(std::min(v1[1], v2[1]), v3[1]) - kFacetBoxPad;
1196+
bbox.min[2] = std::min(std::min(v1[2], v2[2]), v3[2]) - kFacetBoxPad;
1197+
bbox.max[0] = std::max(std::max(v1[0], v2[0]), v3[0]) + kFacetBoxPad;
1198+
bbox.max[1] = std::max(std::max(v1[1], v2[1]), v3[1]) + kFacetBoxPad;
1199+
bbox.max[2] = std::max(std::max(v1[2], v2[2]), v3[2]) + kFacetBoxPad;
11041200
return bbox;
11051201
};
11061202

Detectors/Base/src/TGeoGeometryUtils.cxx

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -136,7 +136,8 @@ TGeoTessellated* MakeTessellated(const TBuffer3D& buf)
136136
}
137137
} // end anonymous namespace
138138

139-
///< Transform any (primitive) TGeoShape to a TGeoTessellated
139+
///< Transform any (primitive) TGeoShape to a TGeoTessellated.
140+
/// Display and export only: TGeoTessellated does not navigate (it is tracked as its bounding box); use O2Tessellated for transport.
140141
TGeoTessellated* TGeoGeometryUtils::TGeoShapeToTGeoTessellated(TGeoShape const* shape)
141142
{
142143
auto& buf = shape->GetBuffer3D(TBuffer3D::kRawSizes | TBuffer3D::kRaw | TBuffer3D::kCore, false);
Lines changed: 180 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,180 @@
1+
// Copyright 2019-2026 CERN and copyright holders of ALICE O2.
2+
// See https://alice-o2.web.cern.ch/copyright for details of the copyright holders.
3+
// All rights not expressly granted are reserved.
4+
//
5+
// This software is distributed under the terms of the GNU General Public
6+
// License v3 (GPL Version 3), copied verbatim in the file "COPYING".
7+
//
8+
// In applying this license CERN does not waive the privileges and immunities
9+
// granted to it by virtue of its status as an Intergovernmental Organization
10+
// or submit itself to any jurisdiction.
11+
/// \author Sandro Wenzel <sandro.wenzel@cern.ch>
12+
/// \since 2026-09
13+
14+
#define BOOST_TEST_MODULE Test O2Tessellated class
15+
#define BOOST_TEST_MAIN
16+
#define BOOST_TEST_DYN_LINK
17+
#include <boost/test/unit_test.hpp>
18+
19+
#include "DetectorsBase/O2Tessellated.h"
20+
21+
#include "TGeoShape.h"
22+
23+
#include <cmath>
24+
#include <limits>
25+
#include <vector>
26+
27+
namespace
28+
{
29+
using o2::base::O2Tessellated;
30+
using Vertex_t = O2Tessellated::Vertex_t;
31+
32+
/// A small deterministic generator, so a failing ray is reproducible from its seed alone.
33+
class Rng
34+
{
35+
public:
36+
explicit Rng(unsigned long long seed) : mState(seed) {}
37+
double uniform(double low, double high)
38+
{
39+
mState = mState * 6364136223846793005ULL + 1442695040888963407ULL;
40+
const double unit = static_cast<double>((mState >> 11) & ((1ULL << 53) - 1)) / static_cast<double>(1ULL << 53);
41+
return low + unit * (high - low);
42+
}
43+
44+
private:
45+
unsigned long long mState;
46+
};
47+
48+
/// Add the twelve outward-wound triangles of an axis-aligned box.
49+
void addBox(O2Tessellated& shape, double cx, double cy, double cz, double hx, double hy, double hz)
50+
{
51+
const double x0 = cx - hx, x1 = cx + hx;
52+
const double y0 = cy - hy, y1 = cy + hy;
53+
const double z0 = cz - hz, z1 = cz + hz;
54+
const Vertex_t corner[8] = {{x0, y0, z0}, {x1, y0, z0}, {x1, y1, z0}, {x0, y1, z0}, {x0, y0, z1}, {x1, y0, z1}, {x1, y1, z1}, {x0, y1, z1}};
55+
// each quad is wound counter-clockwise seen from outside, so the facet normal points outward
56+
const int quad[6][4] = {{0, 3, 2, 1}, {4, 5, 6, 7}, {0, 1, 5, 4}, {2, 3, 7, 6}, {1, 2, 6, 5}, {0, 4, 7, 3}};
57+
for (const auto& face : quad) {
58+
shape.AddFacet(corner[face[0]], corner[face[1]], corner[face[2]]);
59+
shape.AddFacet(corner[face[0]], corner[face[2]], corner[face[3]]);
60+
}
61+
}
62+
63+
/// The Moeller-Trumbore distance used by O2Tessellated's leaf test, repeated here as the oracle.
64+
double rayTriangleReference(const double* origin, const double* dir, const Vertex_t& v0, const Vertex_t& v1,
65+
const Vertex_t& v2)
66+
{
67+
constexpr double EPS = 1.e-8;
68+
const double infinity = std::numeric_limits<double>::infinity();
69+
const double e1[3] = {v1[0] - v0[0], v1[1] - v0[1], v1[2] - v0[2]};
70+
const double e2[3] = {v2[0] - v0[0], v2[1] - v0[1], v2[2] - v0[2]};
71+
const double p[3] = {dir[1] * e2[2] - dir[2] * e2[1], dir[2] * e2[0] - dir[0] * e2[2],
72+
dir[0] * e2[1] - dir[1] * e2[0]};
73+
const double det = e1[0] * p[0] + e1[1] * p[1] + e1[2] * p[2];
74+
if (std::abs(det) <= EPS) {
75+
return infinity;
76+
}
77+
const double tvec[3] = {origin[0] - v0[0], origin[1] - v0[1], origin[2] - v0[2]};
78+
const double invDet = 1.0 / det;
79+
const double u = (tvec[0] * p[0] + tvec[1] * p[1] + tvec[2] * p[2]) * invDet;
80+
if (u < 0.0 || u > 1.0) {
81+
return infinity;
82+
}
83+
const double q[3] = {tvec[1] * e1[2] - tvec[2] * e1[1], tvec[2] * e1[0] - tvec[0] * e1[2],
84+
tvec[0] * e1[1] - tvec[1] * e1[0]};
85+
const double v = (dir[0] * q[0] + dir[1] * q[1] + dir[2] * q[2]) * invDet;
86+
if (v < 0.0 || u + v > 1.0) {
87+
return infinity;
88+
}
89+
const double t = e2[0] * q[0] + e2[1] * q[1] + e2[2] * q[2];
90+
return (t * invDet > 0.) ? t * invDet : infinity;
91+
}
92+
93+
/// The unpruned answer: the nearest facet over every facet of the mesh, entering or exiting.
94+
double bruteForce(const O2Tessellated& shape, const double* origin, const double* dir, bool entering)
95+
{
96+
double best = TGeoShape::Big();
97+
for (int facet = 0; facet < shape.GetNfacets(); ++facet) {
98+
const auto& description = shape.GetFacet(facet);
99+
const Vertex_t& v0 = shape.GetVertex(description[0]);
100+
const Vertex_t& v1 = shape.GetVertex(description[1]);
101+
const Vertex_t& v2 = shape.GetVertex(description[2]);
102+
const double e1[3] = {v1[0] - v0[0], v1[1] - v0[1], v1[2] - v0[2]};
103+
const double e2[3] = {v2[0] - v0[0], v2[1] - v0[1], v2[2] - v0[2]};
104+
const double normal[3] = {e1[1] * e2[2] - e1[2] * e2[1], e1[2] * e2[0] - e1[0] * e2[2],
105+
e1[0] * e2[1] - e1[1] * e2[0]};
106+
const double along = normal[0] * dir[0] + normal[1] * dir[1] + normal[2] * dir[2];
107+
// the same facing filter the shape applies: entering facets face the ray, exiting ones face away
108+
if (entering ? (along > 0.) : (along <= 0.)) {
109+
continue;
110+
}
111+
best = std::min(best, rayTriangleReference(origin, dir, v0, v1, v2));
112+
}
113+
return best;
114+
}
115+
116+
/// Eight boxes in a row, so every axial ray meets sixteen facets and the BVH has many leaves.
117+
void buildRow(O2Tessellated& shape)
118+
{
119+
for (int index = 0; index < 8; ++index) {
120+
addBox(shape, -21. + 6. * index, 0., 0., 2., 3., 4.);
121+
}
122+
shape.CloseShape(true, false, false);
123+
}
124+
} // namespace
125+
126+
BOOST_AUTO_TEST_CASE(PrunedRayQueriesEqualTheBruteForceMinimum)
127+
{
128+
O2Tessellated shape("row");
129+
buildRow(shape);
130+
BOOST_CHECK_EQUAL(shape.GetNfacets(), 96);
131+
132+
Rng rng(20260912);
133+
int outsideHits = 0;
134+
int insideHits = 0;
135+
for (int trial = 0; trial < 4000; ++trial) {
136+
// origins inside the row and well outside it, so both directions are exercised
137+
const double origin[3] = {rng.uniform(-40., 40.), rng.uniform(-12., 12.), rng.uniform(-12., 12.)};
138+
double dir[3] = {rng.uniform(-1., 1.), rng.uniform(-1., 1.), rng.uniform(-1., 1.)};
139+
const double norm = std::sqrt(dir[0] * dir[0] + dir[1] * dir[1] + dir[2] * dir[2]);
140+
if (norm < 1.e-6) {
141+
continue;
142+
}
143+
for (int index = 0; index < 3; ++index) {
144+
dir[index] /= norm;
145+
}
146+
147+
const double outside = shape.DistFromOutside(origin, dir, 1, TGeoShape::Big(), nullptr);
148+
const double inside = shape.DistFromInside(origin, dir, 1, TGeoShape::Big(), nullptr);
149+
const double outsideReference = bruteForce(shape, origin, dir, true);
150+
const double insideReference = bruteForce(shape, origin, dir, false);
151+
152+
BOOST_CHECK_EQUAL(outside, outsideReference);
153+
BOOST_CHECK_EQUAL(inside, insideReference);
154+
outsideHits += outsideReference < TGeoShape::Big() ? 1 : 0;
155+
insideHits += insideReference < TGeoShape::Big() ? 1 : 0;
156+
}
157+
// the case is only meaningful if the rays really hit the mesh; this sampling gives about 450
158+
// entering and 3000 exiting hits
159+
BOOST_CHECK_GT(outsideHits, 200);
160+
BOOST_CHECK_GT(insideHits, 200);
161+
}
162+
163+
BOOST_AUTO_TEST_CASE(APrunedRayFindsTheNearestOfManyFacetsAlongIt)
164+
{
165+
O2Tessellated shape("row");
166+
buildRow(shape);
167+
168+
// straight down the row: eight boxes, so sixteen entering and sixteen exiting facets are in line
169+
const double origin[3] = {-40., 0., 0.};
170+
const double dir[3] = {1., 0., 0.};
171+
BOOST_CHECK_EQUAL(shape.DistFromOutside(origin, dir, 1, TGeoShape::Big(), nullptr), 17.);
172+
BOOST_CHECK_EQUAL(shape.DistFromOutside(origin, dir, 1, TGeoShape::Big(), nullptr),
173+
bruteForce(shape, origin, dir, true));
174+
175+
// from inside the first box, the exit is its own far face and not a later box's
176+
const double inner[3] = {-21., 0., 0.};
177+
BOOST_CHECK_EQUAL(shape.DistFromInside(inner, dir, 1, TGeoShape::Big(), nullptr), 2.);
178+
BOOST_CHECK_EQUAL(shape.DistFromInside(inner, dir, 1, TGeoShape::Big(), nullptr),
179+
bruteForce(shape, inner, dir, false));
180+
}

0 commit comments

Comments
 (0)