-
Notifications
You must be signed in to change notification settings - Fork 494
Expand file tree
/
Copy pathO2Tessellated.cxx
More file actions
1531 lines (1299 loc) · 45.9 KB
/
O2Tessellated.cxx
File metadata and controls
1531 lines (1299 loc) · 45.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2019-2020 CERN and copyright holders of ALICE O2.
// See https://alice-o2.web.cern.ch/copyright for details of the copyright holders.
// All rights not expressly granted are reserved.
//
// This software is distributed under the terms of the GNU General Public
// License v3 (GPL Version 3), copied verbatim in the file "COPYING".
//
// In applying this license CERN does not waive the privileges and immunities
// granted to it by virtue of its status as an Intergovernmental Organization
// or submit itself to any jurisdiction.
// Sandro Wenzel 2026
// An implementation of TGeoTessellated augmented with efficient navigation functions.
// Asked for integration into ROOT here https://github.com/root-project/root/pull/21045
// Will be deleted once we get this from ROOT.
#include <iostream>
#include <sstream>
#include "TGeoManager.h"
#include "TGeoMatrix.h"
#include "TGeoVolume.h"
#include "TVirtualGeoPainter.h"
#include "DetectorsBase/O2Tessellated.h"
#include "TBuffer3D.h"
#include "TBuffer3DTypes.h"
#include "TMath.h"
#include "TBuffer.h"
#include <array>
#include <vector>
// THIS IS THIRD PARTY CODE (TO BE PUT IN ROOT) WHICH DOES NOT NEED TO ADHERE TO OUR LINTING
// NOLINTBEGIN
// include the Third-party BVH headers
#include "bvh2_third_party.h"
// some kernels on top of BVH
#include "bvh2_extra_kernels.h"
#include <cmath>
#include <limits>
using namespace o2::base;
ClassImp(O2Tessellated);
using Vertex_t = Tessellated::Vertex_t;
////////////////////////////////////////////////////////////////////////////////
/// Compact consecutive equal vertices
int TGeoFacet::CompactFacet(Vertex_t* vert, int nvertices)
{
// Compact the common vertices and return new facet
if (nvertices < 2)
return nvertices;
int nvert = nvertices;
int i = 0;
while (i < nvert) {
if (vert[(i + 1) % nvert] == vert[i]) {
// shift last vertices left by one element
for (int j = i + 2; j < nvert; ++j)
vert[j - 1] = vert[j];
nvert--;
}
i++;
}
return nvert;
}
////////////////////////////////////////////////////////////////////////////////
/// Check if a connected neighbour facet has compatible normal
bool TGeoFacet::IsNeighbour(const TGeoFacet& other, bool& flip) const
{
// Find a connecting segment
bool neighbour = false;
int line1[2], line2[2];
int npoints = 0;
for (int i = 0; i < fNvert; ++i) {
auto ivert = fIvert[i];
// Check if the other facet has the same vertex
for (int j = 0; j < other.GetNvert(); ++j) {
if (ivert == other[j]) {
line1[npoints] = i;
line2[npoints] = j;
if (++npoints == 2) {
neighbour = true;
bool order1 = line1[1] == line1[0] + 1;
bool order2 = line2[1] == (line2[0] + 1) % other.GetNvert();
flip = (order1 == order2);
return neighbour;
}
}
}
}
return neighbour;
}
////////////////////////////////////////////////////////////////////////////////
/// Constructor. In case nfacets is zero, it is user's responsibility to
/// call CloseShape once all faces are defined.
O2Tessellated::O2Tessellated(const char* name, int nfacets) : TGeoBBox(name, 0, 0, 0)
{
fNfacets = nfacets;
if (nfacets)
fFacets.reserve(nfacets);
}
////////////////////////////////////////////////////////////////////////////////
/// Constructor providing directly the array of vertices. Facets have to be added
/// providing vertex indices rather than coordinates.
O2Tessellated::O2Tessellated(const char* name, const std::vector<Vertex_t>& vertices) : TGeoBBox(name, 0, 0, 0)
{
fVertices = vertices;
fNvert = fVertices.size();
}
////////////////////////////////////////////////////////////////////////////////
/// Construct from TGeoTessellated
O2Tessellated::O2Tessellated(TGeoTessellated const& tsl, bool check) : TGeoBBox(tsl.GetName(), 0, 0, 0)
{
fNfacets = tsl.GetNfacets();
fNvert = tsl.GetNvertices();
fNseg = tsl.GetNsegments();
// copy facet and vertex done
fVertices.reserve(fNvert);
fFacets.reserve(fNfacets);
for (int i = 0; i < fNfacets; ++i) {
fFacets.push_back(tsl.GetFacet(i));
}
for (int i = 0; i < fNvert; ++i) {
fVertices.push_back(tsl.GetVertex(i));
}
// finish remaining structures
CloseShape(check);
}
////////////////////////////////////////////////////////////////////////////////
/// Add a vertex checking for duplicates, returning the vertex index
int O2Tessellated::AddVertex(Vertex_t const& vert)
{
constexpr double tolerance = 1.e-10;
auto vertexHash = [&](Vertex_t const& vertex) {
// Compute hash for the vertex
long hash = 0;
// helper function to generate hash from integer numbers
auto hash_combine = [](long seed, const long value) {
return seed ^ (std::hash<long>{}(value) + 0x9e3779b9 + (seed << 6) + (seed >> 2));
};
for (int i = 0; i < 3; i++) {
// use tolerance to generate int with the desired precision from a real number for hashing
hash = hash_combine(hash, std::roundl(vertex[i] / tolerance));
}
return hash;
};
auto hash = vertexHash(vert);
bool isAdded = false;
int ivert = -1;
// Get the compatible vertices
auto range = fVerticesMap.equal_range(hash);
for (auto it = range.first; it != range.second; ++it) {
ivert = it->second;
if (fVertices[ivert] == vert) {
isAdded = true;
break;
}
}
if (!isAdded) {
ivert = fVertices.size();
fVertices.push_back(vert);
fVerticesMap.insert(std::make_pair(hash, ivert));
}
return ivert;
}
////////////////////////////////////////////////////////////////////////////////
/// Adding a triangular facet from vertex positions in absolute coordinates
bool O2Tessellated::AddFacet(const Vertex_t& pt0, const Vertex_t& pt1, const Vertex_t& pt2)
{
if (fDefined) {
Error("AddFacet", "Shape %s already fully defined. Not adding", GetName());
return false;
}
Vertex_t vert[3];
vert[0] = pt0;
vert[1] = pt1;
vert[2] = pt2;
int nvert = TGeoFacet::CompactFacet(vert, 3);
if (nvert < 3) {
Error("AddFacet", "Triangular facet at index %d degenerated. Not adding.", GetNfacets());
return false;
}
int ind[3];
for (auto i = 0; i < 3; ++i)
ind[i] = AddVertex(vert[i]);
fNseg += 3;
fFacets.emplace_back(ind[0], ind[1], ind[2]);
return true;
}
////////////////////////////////////////////////////////////////////////////////
/// Adding a triangular facet from indices of vertices
bool O2Tessellated::AddFacet(int i0, int i1, int i2)
{
if (fDefined) {
Error("AddFacet", "Shape %s already fully defined. Not adding", GetName());
return false;
}
if (fVertices.empty()) {
Error("AddFacet", "Shape %s Cannot add facets by indices without vertices. Not adding", GetName());
return false;
}
fNseg += 3;
fFacets.emplace_back(i0, i1, i2);
return true;
}
////////////////////////////////////////////////////////////////////////////////
/// Adding a quadrilateral facet from vertex positions in absolute coordinates
bool O2Tessellated::AddFacet(const Vertex_t& pt0, const Vertex_t& pt1, const Vertex_t& pt2, const Vertex_t& pt3)
{
if (fDefined) {
Error("AddFacet", "Shape %s already fully defined. Not adding", GetName());
return false;
}
Vertex_t vert[4];
vert[0] = pt0;
vert[1] = pt1;
vert[2] = pt2;
vert[3] = pt3;
int nvert = TGeoFacet::CompactFacet(vert, 4);
if (nvert < 3) {
Error("AddFacet", "Quadrilateral facet at index %d degenerated. Not adding.", GetNfacets());
return false;
}
int ind[4];
for (auto i = 0; i < nvert; ++i)
ind[i] = AddVertex(vert[i]);
fNseg += nvert;
if (nvert == 3)
fFacets.emplace_back(ind[0], ind[1], ind[2]);
else
fFacets.emplace_back(ind[0], ind[1], ind[2], ind[3]);
if (fNfacets > 0 && GetNfacets() == fNfacets)
CloseShape(false);
return true;
}
////////////////////////////////////////////////////////////////////////////////
/// Adding a quadrilateral facet from indices of vertices
bool O2Tessellated::AddFacet(int i0, int i1, int i2, int i3)
{
if (fDefined) {
Error("AddFacet", "Shape %s already fully defined. Not adding", GetName());
return false;
}
if (fVertices.empty()) {
Error("AddFacet", "Shape %s Cannot add facets by indices without vertices. Not adding", GetName());
return false;
}
fNseg += 4;
fFacets.emplace_back(i0, i1, i2, i3);
return true;
}
////////////////////////////////////////////////////////////////////////////////
/// Compute normal for a given facet
Vertex_t O2Tessellated::FacetComputeNormal(int ifacet, bool& degenerated) const
{
// Compute normal using non-zero segments
constexpr double kTolerance = 1.e-20;
auto const& facet = fFacets[ifacet];
int nvert = facet.GetNvert();
degenerated = true;
Vertex_t normal;
for (int i = 0; i < nvert - 1; ++i) {
Vertex_t e1 = fVertices[facet[i + 1]] - fVertices[facet[i]];
if (e1.Mag2() < kTolerance)
continue;
for (int j = i + 1; j < nvert; ++j) {
Vertex_t e2 = fVertices[facet[(j + 1) % nvert]] - fVertices[facet[j]];
if (e2.Mag2() < kTolerance)
continue;
normal = Vertex_t::Cross(e1, e2);
// e1 and e2 may be colinear
if (normal.Mag2() < kTolerance)
continue;
normal.Normalize();
degenerated = false;
break;
}
if (!degenerated)
break;
}
return normal;
}
////////////////////////////////////////////////////////////////////////////////
/// Check validity of facet
bool O2Tessellated::FacetCheck(int ifacet) const
{
constexpr double kTolerance = 1.e-10;
auto const& facet = fFacets[ifacet];
int nvert = facet.GetNvert();
bool degenerated = true;
FacetComputeNormal(ifacet, degenerated);
if (degenerated) {
std::cout << "Facet: " << ifacet << " is degenerated\n";
return false;
}
// Compute surface area
double surfaceArea = 0.;
for (int i = 1; i < nvert - 1; ++i) {
Vertex_t e1 = fVertices[facet[i]] - fVertices[facet[0]];
Vertex_t e2 = fVertices[facet[i + 1]] - fVertices[facet[0]];
surfaceArea += 0.5 * Vertex_t::Cross(e1, e2).Mag();
}
if (surfaceArea < kTolerance) {
std::cout << "Facet: " << ifacet << " has zero surface area\n";
return false;
}
return true;
}
////////////////////////////////////////////////////////////////////////////////
/// Close the shape: calculate bounding box and compact vertices
void O2Tessellated::CloseShape(bool check, bool fixFlipped, bool verbose)
{
if (fIsClosed && fBVH) {
return;
}
// Compute bounding box
fDefined = true;
fNvert = fVertices.size();
fNfacets = fFacets.size();
ComputeBBox();
BuildBVH();
if (fOutwardNormals.size() == 0) {
CalculateNormals();
} else {
// short check if the normal container is of correct size
if (fOutwardNormals.size() != fFacets.size()) {
std::cerr << "Inconsistency in normal container";
}
}
fIsClosed = true;
// Cleanup the vertex map
std::multimap<long, int>().swap(fVerticesMap);
if (fVertices.size() > 0) {
if (!check)
return;
// Check facets
for (auto i = 0; i < fNfacets; ++i)
FacetCheck(i);
fClosedBody = CheckClosure(fixFlipped, verbose);
}
}
////////////////////////////////////////////////////////////////////////////////
/// Check closure of the solid and check/fix flipped normals
bool O2Tessellated::CheckClosure(bool fixFlipped, bool verbose)
{
int* nn = new int[fNfacets];
bool* flipped = new bool[fNfacets];
bool hasorphans = false;
bool hasflipped = false;
for (int i = 0; i < fNfacets; ++i) {
nn[i] = 0;
flipped[i] = false;
}
for (int icrt = 0; icrt < fNfacets; ++icrt) {
// all neighbours checked?
if (nn[icrt] >= fFacets[icrt].GetNvert())
continue;
for (int i = icrt + 1; i < fNfacets; ++i) {
bool isneighbour = fFacets[icrt].IsNeighbour(fFacets[i], flipped[i]);
if (isneighbour) {
if (flipped[icrt])
flipped[i] = !flipped[i];
if (flipped[i])
hasflipped = true;
nn[icrt]++;
nn[i]++;
if (nn[icrt] == fFacets[icrt].GetNvert())
break;
}
}
if (nn[icrt] < fFacets[icrt].GetNvert())
hasorphans = true;
}
if (hasorphans && verbose) {
Error("Check", "Tessellated solid %s has following not fully connected facets:", GetName());
for (int icrt = 0; icrt < fNfacets; ++icrt) {
if (nn[icrt] < fFacets[icrt].GetNvert())
std::cout << icrt << " (" << fFacets[icrt].GetNvert() << " edges, " << nn[icrt] << " neighbours)\n";
}
}
fClosedBody = !hasorphans;
int nfixed = 0;
if (hasflipped) {
if (verbose)
Warning("Check", "Tessellated solid %s has following facets with flipped normals:", GetName());
for (int icrt = 0; icrt < fNfacets; ++icrt) {
if (flipped[icrt]) {
if (verbose)
std::cout << icrt << "\n";
if (fixFlipped) {
fFacets[icrt].Flip();
nfixed++;
}
}
}
if (nfixed && verbose)
Info("Check", "Automatically flipped %d facets to match first defined facet", nfixed);
}
delete[] nn;
delete[] flipped;
return !hasorphans;
}
////////////////////////////////////////////////////////////////////////////////
/// Compute bounding box
void O2Tessellated::ComputeBBox()
{
const double kBig = TGeoShape::Big();
double vmin[3] = {kBig, kBig, kBig};
double vmax[3] = {-kBig, -kBig, -kBig};
for (const auto& facet : fFacets) {
for (int i = 0; i < facet.GetNvert(); ++i) {
for (int j = 0; j < 3; ++j) {
vmin[j] = TMath::Min(vmin[j], fVertices[facet[i]].operator[](j));
vmax[j] = TMath::Max(vmax[j], fVertices[facet[i]].operator[](j));
}
}
}
fDX = 0.5 * (vmax[0] - vmin[0]);
fDY = 0.5 * (vmax[1] - vmin[1]);
fDZ = 0.5 * (vmax[2] - vmin[2]);
for (int i = 0; i < 3; ++i)
fOrigin[i] = 0.5 * (vmax[i] + vmin[i]);
}
////////////////////////////////////////////////////////////////////////////////
/// Returns numbers of vertices, segments and polygons composing the shape mesh.
void O2Tessellated::GetMeshNumbers(int& nvert, int& nsegs, int& npols) const
{
nvert = fNvert;
nsegs = fNseg;
npols = GetNfacets();
}
////////////////////////////////////////////////////////////////////////////////
/// Creates a TBuffer3D describing *this* shape.
/// Coordinates are in local reference frame.
TBuffer3D* O2Tessellated::MakeBuffer3D() const
{
const int nvert = fNvert;
const int nsegs = fNseg;
const int npols = GetNfacets();
auto buff = new TBuffer3D(TBuffer3DTypes::kGeneric, nvert, 3 * nvert, nsegs, 3 * nsegs, npols, 6 * npols);
if (buff) {
SetPoints(buff->fPnts);
SetSegsAndPols(*buff);
}
return buff;
}
////////////////////////////////////////////////////////////////////////////////
/// Prints basic info
void O2Tessellated::Print(Option_t*) const
{
std::cout << "=== Tessellated shape " << GetName() << " having " << GetNvertices() << " vertices and "
<< GetNfacets() << " facets\n";
}
////////////////////////////////////////////////////////////////////////////////
/// Fills TBuffer3D structure for segments and polygons.
void O2Tessellated::SetSegsAndPols(TBuffer3D& buff) const
{
const int c = GetBasicColor();
int* segs = buff.fSegs;
int* pols = buff.fPols;
int indseg = 0; // segment internal data index
int indpol = 0; // polygon internal data index
int sind = 0; // segment index
for (const auto& facet : fFacets) {
auto nvert = facet.GetNvert();
pols[indpol++] = c;
pols[indpol++] = nvert;
for (auto j = 0; j < nvert; ++j) {
int k = (j + 1) % nvert;
// segment made by next consecutive points
segs[indseg++] = c;
segs[indseg++] = facet[j];
segs[indseg++] = facet[k];
// add segment to current polygon and increment segment index
pols[indpol + nvert - j - 1] = sind++;
}
indpol += nvert;
}
}
////////////////////////////////////////////////////////////////////////////////
/// Fill tessellated points to an array.
void O2Tessellated::SetPoints(double* points) const
{
int ind = 0;
for (const auto& vertex : fVertices) {
vertex.CopyTo(&points[ind]);
ind += 3;
}
}
////////////////////////////////////////////////////////////////////////////////
/// Fill tessellated points in float.
void O2Tessellated::SetPoints(Float_t* points) const
{
int ind = 0;
for (const auto& vertex : fVertices) {
points[ind++] = vertex.x();
points[ind++] = vertex.y();
points[ind++] = vertex.z();
}
}
////////////////////////////////////////////////////////////////////////////////
/// Resize the shape by scaling vertices within maxsize and center to origin
void O2Tessellated::ResizeCenter(double maxsize)
{
using Vector3_t = Vertex_t;
if (!fDefined) {
Error("ResizeCenter", "Not all faces are defined");
return;
}
Vector3_t origin(fOrigin[0], fOrigin[1], fOrigin[2]);
double maxedge = TMath::Max(TMath::Max(fDX, fDY), fDZ);
double scale = maxsize / maxedge;
for (size_t i = 0; i < fVertices.size(); ++i) {
fVertices[i] = scale * (fVertices[i] - origin);
}
fOrigin[0] = fOrigin[1] = fOrigin[2] = 0;
fDX *= scale;
fDY *= scale;
fDZ *= scale;
}
////////////////////////////////////////////////////////////////////////////////
/// Fills a static 3D buffer and returns a reference.
const TBuffer3D& O2Tessellated::GetBuffer3D(int reqSections, Bool_t localFrame) const
{
static TBuffer3D buffer(TBuffer3DTypes::kGeneric);
FillBuffer3D(buffer, reqSections, localFrame);
const int nvert = fNvert;
const int nsegs = fNseg;
const int npols = GetNfacets();
if (reqSections & TBuffer3D::kRawSizes) {
if (buffer.SetRawSizes(nvert, 3 * nvert, nsegs, 3 * nsegs, npols, 6 * npols)) {
buffer.SetSectionsValid(TBuffer3D::kRawSizes);
}
}
if ((reqSections & TBuffer3D::kRaw) && buffer.SectionsValid(TBuffer3D::kRawSizes)) {
SetPoints(buffer.fPnts);
if (!buffer.fLocalFrame) {
TransformPoints(buffer.fPnts, buffer.NbPnts());
}
SetSegsAndPols(buffer);
buffer.SetSectionsValid(TBuffer3D::kRaw);
}
return buffer;
}
////////////////////////////////////////////////////////////////////////////////
/// Reads a single tessellated solid from an .obj file.
O2Tessellated* O2Tessellated::ImportFromObjFormat(const char* objfile, bool check, bool verbose)
{
using std::vector, std::string, std::ifstream, std::stringstream, std::endl;
vector<Vertex_t> vertices;
vector<string> sfacets;
struct FacetInd_t {
int i0 = -1;
int i1 = -1;
int i2 = -1;
int i3 = -1;
int nvert = 0;
FacetInd_t(int a, int b, int c)
{
i0 = a;
i1 = b;
i2 = c;
nvert = 3;
};
FacetInd_t(int a, int b, int c, int d)
{
i0 = a;
i1 = b;
i2 = c;
i3 = d;
nvert = 4;
};
};
vector<FacetInd_t> facets;
// List of geometric vertices, with (x, y, z [,w]) coordinates, w is optional and defaults to 1.0.
// struct vtx_t { double x = 0; double y = 0; double z = 0; double w = 1; };
// Texture coordinates in u, [,v ,w]) coordinates, these will vary between 0 and 1. v, w are optional and default to
// 0.
// struct tex_t { double u; double v; double w; };
// List of vertex normals in (x,y,z) form; normals might not be unit vectors.
// struct vn_t { double x; double y; double z; };
// Parameter space vertices in ( u [,v] [,w] ) form; free form geometry statement
// struct vp_t { double u; double v; double w; };
// Faces are defined using lists of vertex, texture and normal indices which start at 1.
// Polygons such as quadrilaterals can be defined by using more than three vertex/texture/normal indices.
// f v1//vn1 v2//vn2 v3//vn3 ...
// Records starting with the letter "l" specify the order of the vertices which build a polyline.
// l v1 v2 v3 v4 v5 v6 ...
string line;
int ind[4] = {0};
ifstream file(objfile);
if (!file.is_open()) {
::Error("O2Tessellated::ImportFromObjFormat", "Unable to open %s", objfile);
return nullptr;
}
while (getline(file, line)) {
stringstream ss(line);
string tag;
// We ignore everything which is not a vertex or a face
if (line.rfind('v', 0) == 0 && line.rfind("vt", 0) != 0 && line.rfind("vn", 0) != 0 && line.rfind("vn", 0) != 0) {
// Decode the vertex
double pos[4] = {0, 0, 0, 1};
ss >> tag >> pos[0] >> pos[1] >> pos[2] >> pos[3];
vertices.emplace_back(pos[0] * pos[3], pos[1] * pos[3], pos[2] * pos[3]);
}
else if (line.rfind('f', 0) == 0) {
// Decode the face
ss >> tag;
string word;
sfacets.clear();
while (ss >> word)
sfacets.push_back(word);
if (sfacets.size() > 4 || sfacets.size() < 3) {
::Error("O2Tessellated::ImportFromObjFormat", "Detected face having unsupported %zu vertices",
sfacets.size());
return nullptr;
}
int nvert = 0;
for (auto& sword : sfacets) {
stringstream ssword(sword);
string token;
getline(ssword, token, '/'); // just need the vertex index, which is the first token
// Convert string token to integer
ind[nvert++] = stoi(token) - 1;
if (ind[nvert - 1] < 0) {
::Error("O2Tessellated::ImportFromObjFormat", "Unsupported relative vertex index definition in %s",
objfile);
return nullptr;
}
}
if (nvert == 3)
facets.emplace_back(ind[0], ind[1], ind[2]);
else
facets.emplace_back(ind[0], ind[1], ind[2], ind[3]);
}
}
int nvertices = (int)vertices.size();
int nfacets = (int)facets.size();
if (nfacets < 3) {
::Error("O2Tessellated::ImportFromObjFormat", "Not enough faces detected in %s", objfile);
return nullptr;
}
string sobjfile(objfile);
if (verbose)
std::cout << "Read " << nvertices << " vertices and " << nfacets << " facets from " << sobjfile << endl;
auto tsl = new O2Tessellated(sobjfile.erase(sobjfile.find_last_of('.')).c_str(), vertices);
for (int i = 0; i < nfacets; ++i) {
auto facet = facets[i];
if (facet.nvert == 3)
tsl->AddFacet(facet.i0, facet.i1, facet.i2);
else
tsl->AddFacet(facet.i0, facet.i1, facet.i2, facet.i3);
}
tsl->CloseShape(check, true, verbose);
tsl->Print();
return tsl;
}
// implementation of some geometry helper functions in anonymous namespace
namespace
{
using Vertex_t = Tessellated::Vertex_t;
// The classic Moeller-Trumbore ray triangle-intersection kernel:
// - Compute triangle edges e1, e2
// - Compute determinant det
// - Reject parallel rays
// - Compute barycentric coordinates u, v
// - Compute ray parameter t
double rayTriangle(const Vertex_t& orig, const Vertex_t& dir, const Vertex_t& v0, const Vertex_t& v1,
const Vertex_t& v2, double rayEPS = 1e-8)
{
constexpr double EPS = 1e-8;
const double INF = std::numeric_limits<double>::infinity();
Vertex_t e1{v1[0] - v0[0], v1[1] - v0[1], v1[2] - v0[2]};
Vertex_t e2{v2[0] - v0[0], v2[1] - v0[1], v2[2] - v0[2]};
auto p = Vertex_t::Cross(dir, e2);
auto det = e1.Dot(p);
if (std::abs(det) <= EPS) {
return INF;
}
Vertex_t tvec{orig[0] - v0[0], orig[1] - v0[1], orig[2] - v0[2]};
auto invDet = 1.0 / det;
auto u = tvec.Dot(p) * invDet;
if (u < 0.0 || u > 1.0) {
return INF;
}
auto q = Vertex_t::Cross(tvec, e1);
auto v = dir.Dot(q) * invDet;
if (v < 0.0 || u + v > 1.0) {
return INF;
}
auto t = e2.Dot(q) * invDet;
return (t > rayEPS) ? t : INF;
}
template <typename T = float>
struct Vec3f {
T x, y, z;
};
template <typename T>
inline Vec3f<T> operator-(const Vec3f<T>& a, const Vec3f<T>& b)
{
return {a.x - b.x, a.y - b.y, a.z - b.z};
}
template <typename T>
inline Vec3f<T> cross(const Vec3f<T>& a, const Vec3f<T>& b)
{
return {a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x};
}
template <typename T>
inline T dot(const Vec3f<T>& a, const Vec3f<T>& b)
{
return a.x * b.x + a.y * b.y + a.z * b.z;
}
// Kernel to get closest/shortest distance between a point and a triangl (a,b,c).
// Performed by default in float since Safety can be approximate.
// Project point onto triangle plane
// If projection lies inside → distance to plane
// Otherwise compute min distance to the three edges
// Return squared distance
template <typename T = float>
T pointTriangleDistSq(const Vec3f<T>& p, const Vec3f<T>& a, const Vec3f<T>& b, const Vec3f<T>& c)
{
// Edges
Vec3f<T> ab = b - a;
Vec3f<T> ac = c - a;
Vec3f<T> ap = p - a;
auto d1 = dot(ab, ap);
auto d2 = dot(ac, ap);
if (d1 <= T(0.0) && d2 <= T(0.0)) {
return dot(ap, ap); // barycentric (1,0,0)
}
Vec3f<T> bp = p - b;
auto d3 = dot(ab, bp);
auto d4 = dot(ac, bp);
if (d3 >= T(0.0) && d4 <= d3) {
return dot(bp, bp); // (0,1,0)
}
T vc = d1 * d4 - d3 * d2;
if (vc <= 0.0f && d1 >= 0.0f && d3 <= 0.0f) {
T v = d1 / (d1 - d3);
Vec3f<T> proj = {a.x + v * ab.x, a.y + v * ab.y, a.z + v * ab.z};
Vec3f<T> d = p - proj;
return dot(d, d); // edge AB
}
Vec3f<T> cp = p - c;
T d5 = dot(ab, cp);
T d6 = dot(ac, cp);
if (d6 >= T(0.0f) && d5 <= d6) {
return dot(cp, cp); // (0,0,1)
}
T vb = d5 * d2 - d1 * d6;
if (vb <= 0.0f && d2 >= 0.0f && d6 <= 0.0f) {
T w = d2 / (d2 - d6);
Vec3f<T> proj = {a.x + w * ac.x, a.y + w * ac.y, a.z + w * ac.z};
Vec3f<T> d = p - proj;
return dot(d, d); // edge AC
}
T va = d3 * d6 - d5 * d4;
if (va <= 0.0f && (d4 - d3) >= 0.0f && (d5 - d6) >= 0.0f) {
T w = (d4 - d3) / ((d4 - d3) + (d5 - d6));
Vec3f<T> proj = {b.x + w * (c.x - b.x), b.y + w * (c.y - b.y), b.z + w * (c.z - b.z)};
Vec3f<T> d = p - proj;
return dot(d, d); // edge BC
}
// Inside face region
T denom = T(1.0f) / (va + vb + vc);
T v = vb * denom;
T w = vc * denom;
Vec3f<T> proj = {a.x + ab.x * v + ac.x * w, a.y + ab.y * v + ac.y * w, a.z + ab.z * v + ac.z * w};
Vec3f<T> d = p - proj;
return dot(d, d);
}
template <typename T>
inline Vec3f<T> normalize(const Vec3f<T>& v)
{
T len2 = dot(v, v);
if (len2 == T(0.0f)) {
std::cerr << "Degnerate triangle. Cannot determine normal";
return {0, 0, 0};
}
T invLen = T(1.0f) / std::sqrt(len2);
return {v.x * invLen, v.y * invLen, v.z * invLen};
}
template <typename T>
inline Vec3f<T> triangleNormal(const Vec3f<T>& a, const Vec3f<T>& b, const Vec3f<T>& c)
{
const Vec3f<T> e1 = b - a;
const Vec3f<T> e2 = c - a;
return normalize(cross(e1, e2));
}
} // end anonymous namespace
////////////////////////////////////////////////////////////////////////////////
/// DistFromOutside
Double_t O2Tessellated::DistFromOutside(const Double_t* point, const Double_t* dir, Int_t /*iact*/, Double_t stepmax,
Double_t* /*safe*/) const
{
// use the BVH intersector in combination with leaf ray-triangle testing
double local_step = Big(); // we need this otherwise the lambda get's confused
using Scalar = float;
using Vec3 = bvh::v2::Vec<Scalar, 3>;
using Node = bvh::v2::Node<Scalar, 3>;
using Bvh = bvh::v2::Bvh<Node>;
using Ray = bvh::v2::Ray<Scalar, 3>;
// let's fetch the bvh
auto mybvh = (Bvh*)fBVH;
if (!mybvh) {
assert(false);
return -1.;
}
auto truncate_roundup = [](double orig) {
float epsilon = std::numeric_limits<float>::epsilon() * std::fabs(orig);
// Add the bias to x before assigning it to y
return static_cast<float>(orig + epsilon);
};
// let's do very quick checks against the top node
const auto topnode_bbox = mybvh->get_root().get_bbox();
if ((-point[0] + topnode_bbox.min[0]) > stepmax) {
return Big();
}
if ((-point[1] + topnode_bbox.min[1]) > stepmax) {
return Big();
}
if ((-point[2] + topnode_bbox.min[2]) > stepmax) {
return Big();
}
if ((point[0] - topnode_bbox.max[0]) > stepmax) {
return Big();
}
if ((point[1] - topnode_bbox.max[1]) > stepmax) {
return Big();
}
if ((point[2] - topnode_bbox.max[2]) > stepmax) {
return Big();
}
// the ray used for bvh interaction
Ray ray(Vec3(point[0], point[1], point[2]), // origin
Vec3(dir[0], dir[1], dir[2]), // direction
0.0f, // minimum distance (could give stepmax ?)
truncate_roundup(local_step));
static constexpr bool use_robust_traversal = true;
Vertex_t dir_v{dir[0], dir[1], dir[2]};
// Traverse the BVH and apply concrete object intersection in BVH leafs
bvh::v2::GrowingStack<Bvh::Index> stack;
mybvh->intersect<false, use_robust_traversal>(ray, mybvh->get_root().index, stack, [&](size_t begin, size_t end) {
for (size_t prim_id = begin; prim_id < end; ++prim_id) {
auto objectid = mybvh->prim_ids[prim_id];
const auto& facet = fFacets[objectid];
const auto& n = fOutwardNormals[objectid];
// quick normal test. Coming from outside, the dot product must be negative
if (n.Dot(dir_v) > 0.) {
continue;
}
auto thisdist = rayTriangle(Vertex_t(point[0], point[1], point[2]), dir_v,
fVertices[facet[0]], fVertices[facet[1]], fVertices[facet[2]], 0.);
if (thisdist < local_step) {
local_step = thisdist;
}
}
return false; // go on after this
});
return local_step;
}
////////////////////////////////////////////////////////////////////////////////
/// DistFromOutside
Double_t O2Tessellated::DistFromInside(const Double_t* point, const Double_t* dir, Int_t /*iact*/, Double_t /*stepmax*/,
Double_t* /*safe*/) const
{
// use the BVH intersector in combination with leaf ray-triangle testing
double local_step = Big(); // we need this otherwise the lambda get's confused
using Scalar = float;
using Vec3 = bvh::v2::Vec<Scalar, 3>;