Project
Loading...
Searching...
No Matches
GeometryManager.cxx
Go to the documentation of this file.
1// Copyright 2019-2020 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
14
15#include <fairlogger/Logger.h> // for LOG
16#include <TCollection.h> // for TIter
17#include <TFile.h>
18#include <TGeoMatrix.h> // for TGeoHMatrix
19#include <TGeoNavigator.h> // for TGeoNavigator
20#include <TGeoNode.h> // for TGeoNode
21#include <TGeoPhysicalNode.h> // for TGeoPhysicalNode, TGeoPNEntry
22#include <string>
23#include <cassert>
24#include <cstddef> // for NULL
25#include <numeric>
26
32
33#ifdef O2_WITH_VECGEOM
34#include "TGeo2VecGeom/RootGeoManager.h"
35#include <VecGeom/base/Version.h>
36#include <VecGeom/management/GeoManager.h>
37#include <VecGeom/management/ABBoxManager.h>
38#include <VecGeom/management/BVHManager.h>
39#include <VecGeom/navigation/GlobalLocator.h>
40#include <VecGeom/navigation/NavigationState.h>
41#include <VecGeom/navigation/NewSimpleNavigator.h>
42#include <VecGeom/navigation/BVHNavigator.h>
43#include <VecGeom/navigation/SimpleLevelLocator.h>
44#if VECGEOM_VERSION >= 0x020000
45#include <VecGeom/navigation/SimpleABBoxLevelLocator.h>
46#else
47#include <VecGeom/navigation/BVHLevelLocator.h>
48#endif
49#include <VecGeom/navigation/VNavigator.h>
50#include <VecGeom/volumes/LogicalVolume.h>
51#include <mutex>
52// The BVH navigator of the VNavigator family, which Geant4 navigation needs on every volume.
53#if __has_include(<VecGeom/navigation/BVHNavigatorV.h>)
54#define O2_VECGEOM_HAS_BVH_VNAVIGATOR
55#include <VecGeom/navigation/BVHNavigatorV.h>
56#include <VecGeom/navigation/BVHLevelLocator.h>
57#include <VecGeom/navigation/BVHSafetyEstimator.h>
58#include <VecGeom/navigation/SimpleSafetyEstimator.h>
59#endif
60#endif
61
62using namespace o2::detectors;
63using namespace o2::base;
64
68std::mutex GeometryManager::sTGMutex;
69
70//______________________________________________________________________
71Bool_t GeometryManager::getOriginalMatrix(const char* symname, TGeoHMatrix& m)
72{
73 m.Clear();
74 if (!gGeoManager || !gGeoManager->IsClosed()) {
75 LOG(error) << "No active geometry or geometry not yet closed!";
76 ;
77 return kFALSE;
78 }
79 std::lock_guard<std::mutex> guard(sTGMutex);
80 if (!gGeoManager->GetListOfPhysicalNodes()) {
81 LOG(warning) << "gGeoManager doesn't contain any aligned nodes!";
82
83 if (!gGeoManager->cd(symname)) {
84 LOG(error) << "Volume path " << symname << " not valid!";
85 return kFALSE;
86 } else {
87 m = *gGeoManager->GetCurrentMatrix();
88 return kTRUE;
89 }
90 }
91
92 TGeoPNEntry* pne = gGeoManager->GetAlignableEntry(symname);
93 const char* path = nullptr;
94
95 if (pne) {
96 m = *pne->GetGlobalOrig();
97 return kTRUE;
98 } else {
99 LOG(warning) << "The symbolic volume name " << symname
100 << "does not correspond to a physical entry. Using it as a volume path!";
101 path = symname;
102 }
103
104 return getOriginalMatrixFromPath(path, m);
105}
106
107//______________________________________________________________________
108Bool_t GeometryManager::getOriginalMatrixFromPath(const char* path, TGeoHMatrix& m)
109{
110 m.Clear();
111
112 if (!gGeoManager || !gGeoManager->IsClosed()) {
113 LOG(error) << "Can't get the original global matrix! gGeoManager doesn't exist or it is still opened!";
114 return kFALSE;
115 }
116 std::lock_guard<std::mutex> guard(sTGMutex);
117 if (!gGeoManager->CheckPath(path)) {
118 LOG(error) << "Volume path " << path << " not valid!";
119 return kFALSE;
120 }
121
122 TIter next(gGeoManager->GetListOfPhysicalNodes());
123 gGeoManager->cd(path);
124
125 while (gGeoManager->GetLevel()) {
126 TGeoPhysicalNode* physNode = nullptr;
127 next.Reset();
128 TGeoNode* node = gGeoManager->GetCurrentNode();
129
130 while ((physNode = (TGeoPhysicalNode*)next())) {
131 if (physNode->GetNode() == node) {
132 break;
133 }
134 }
135
136 TGeoMatrix* lm = nullptr;
137 if (physNode) {
138 lm = physNode->GetOriginalMatrix();
139 if (!lm) {
140 lm = node->GetMatrix();
141 }
142 } else {
143 lm = node->GetMatrix();
144 }
145
146 m.MultiplyLeft(lm);
147
148 gGeoManager->CdUp();
149 }
150 return kTRUE;
151}
152
153//______________________________________________________________________
154TGeoHMatrix* GeometryManager::getMatrix(TGeoPNEntry* pne)
155{
156 // Get the global transformation matrix for a given PNEntry
157 // by quering the TGeoManager
158
159 if (!gGeoManager || !gGeoManager->IsClosed()) {
160 LOG(error) << "Can't get the global matrix! gGeoManager doesn't exist or it is still opened!";
161 return nullptr;
162 }
163
164 // if matrix already known --> return it
165 TGeoPhysicalNode* pnode = pne->GetPhysicalNode();
166 if (pnode) {
167 return pnode->GetMatrix();
168 }
169
170 // otherwise calculate it from title and attach via TGeoPhysicalNode
171 pne->SetPhysicalNode(new TGeoPhysicalNode(pne->GetTitle()));
172 return pne->GetPhysicalNode()->GetMatrix();
173}
174
175//______________________________________________________________________
176TGeoHMatrix* GeometryManager::getMatrix(const char* symname)
177{
178 // Get the global transformation matrix for a given alignable volume
179 // identified by its symbolic name 'symname' by quering the TGeoManager
180
181 if (!gGeoManager || !gGeoManager->IsClosed()) {
182 LOG(error) << "No active geometry or geometry not yet closed!";
183 return nullptr;
184 }
185
186 TGeoPNEntry* pne = gGeoManager->GetAlignableEntry(symname);
187 if (!pne) {
188 return nullptr;
189 }
190
191 return getMatrix(pne);
192}
193
194//______________________________________________________________________
195const char* GeometryManager::getSymbolicName(DetID detid, int sensid)
196{
200 int id = getSensID(detid, sensid);
201 TGeoPNEntry* pne = gGeoManager->GetAlignableEntryByUID(id);
202 if (!pne) {
203 LOG(error) << "Failed to find alignable entry with index " << id << ": Det" << detid << " Sens.Vol:" << sensid << ") !";
204 return nullptr;
205 }
206 return pne->GetName();
207}
208
209TGeoPNEntry* GeometryManager::getPNEntry(DetID detid, Int_t sensid)
210{
214 int id = getSensID(detid, sensid);
215 TGeoPNEntry* pne = gGeoManager->GetAlignableEntryByUID(id);
216 if (!pne) {
217 LOG(error) << "The sens.vol " << sensid << " of det " << detid << " does not correspond to a physical entry!";
218 }
219 return pne;
220}
221
222//______________________________________________________________________
223TGeoHMatrix* GeometryManager::getMatrix(DetID detid, Int_t sensid)
224{
228 static TGeoHMatrix matTmp;
229 TGeoPNEntry* pne = getPNEntry(detid, sensid);
230 if (!pne) {
231 return nullptr;
232 }
233
234 TGeoPhysicalNode* pnode = pne->GetPhysicalNode();
235 if (pnode) {
236 return pnode->GetMatrix();
237 }
238
239 const char* path = pne->GetTitle();
240 gGeoManager->PushPath(); // Preserve the modeler state.
241 if (!gGeoManager->cd(path)) {
242 gGeoManager->PopPath();
243 LOG(error) << "Volume path " << path << " not valid!";
244 return nullptr;
245 }
246 matTmp = *gGeoManager->GetCurrentMatrix();
247 gGeoManager->PopPath();
248 return &matTmp;
249}
250
251//______________________________________________________________________
252Bool_t GeometryManager::getOriginalMatrix(DetID detid, int sensid, TGeoHMatrix& m)
253{
257 m.Clear();
258
259 const char* symname = getSymbolicName(detid, sensid);
260 if (!symname) {
261 return kFALSE;
262 }
263
264 return getOriginalMatrix(symname, m);
265}
266
267//______________________________________________________________________
268bool GeometryManager::applyAlignment(const std::vector<const std::vector<o2::detectors::AlignParam>*> algPars)
269{
271 for (auto dv : algPars) {
272 if (dv && !applyAlignment(*dv)) {
273 return false;
274 }
275 }
276 return true;
277}
278
279//______________________________________________________________________
280bool GeometryManager::applyAlignment(const std::vector<o2::detectors::AlignParam>& algPars, bool keepPhysicalNodes)
281{
283 int nvols = algPars.size();
284 std::vector<int> ord(nvols);
285 std::iota(std::begin(ord), std::end(ord), 0); // sort to apply alignment in correct hierarchy
286 std::sort(std::begin(ord), std::end(ord), [&algPars](int a, int b) { return algPars[a].getLevel() < algPars[b].getLevel(); });
287
288 bool res = true;
289 auto pns = gGeoManager->GetListOfPhysicalNodes();
290 for (int i = 0; i < nvols; i++) {
291 int npn = pns->GetEntriesFast();
292 if (!algPars[ord[i]].applyToGeometry(GeometryManagerParam::Instance().printLevel)) {
293 res = false;
294 LOG(error) << "Error applying alignment object for volume" << algPars[ord[i]].getSymName();
295 }
296 if (!keepPhysicalNodes) { // delete the nodes this alignment created, so their memory is reused by the next one
297 for (int k = pns->GetEntriesFast() - 1; k >= npn; k--) {
298 auto pn = static_cast<TGeoPhysicalNode*>(pns->RemoveAt(k));
299 if (auto pne = gGeoManager->GetAlignableEntry(algPars[ord[i]].getSymName().c_str()); pne && pne->GetPhysicalNode() == pn) {
300 pne->SetPhysicalNode(nullptr);
301 }
302 delete pn;
303 }
304 pns->Compress();
305 }
306 }
307 return res;
308}
309
310// ================= methods for nested MatBudgetExt class ================
311
312//______________________________________________________________________
314{
315 double nrm = 1. / step;
316 meanRho *= nrm;
317 meanA *= nrm;
318 meanZ *= nrm;
319 meanZ2A *= nrm;
320 if (nrm > 0.) {
321 length = step;
322 }
323}
324
325//______________________________________________________________________
326void GeometryManager::accountMaterial(const TGeoMaterial* material, GeometryManager::MatBudgetExt& bd)
327{
328 bd.meanRho = material->GetDensity();
329 bd.meanX2X0 = material->GetRadLen();
330 bd.meanA = material->GetA();
331 bd.meanZ = material->GetZ();
332 if (material->IsMixture()) {
333 TGeoMixture* mixture = (TGeoMixture*)material;
334 Double_t norm = 0.;
335 bd.meanZ2A = 0.;
336 for (Int_t iel = 0; iel < mixture->GetNelements(); iel++) {
337 norm += mixture->GetWmixt()[iel];
338 bd.meanZ2A += mixture->GetZmixt()[iel] * mixture->GetWmixt()[iel] / mixture->GetAmixt()[iel];
339 }
340 bd.meanZ2A /= norm;
341 } else {
342 bd.meanZ2A = bd.meanZ / bd.meanA;
343 }
344}
345
346//_____________________________________________________________________________________
347GeometryManager::MatBudgetExt GeometryManager::meanMaterialBudgetExt(float x0, float y0, float z0, float x1, float y1, float z1)
348{
349 //
350 // TODO? It seems there is no real nead for extended material budget, consider eliminating it
351 //
352 // Calculate mean material budget and material properties (extended version) between
353 // the points "0" and "1".
354 //
355 // see MatBudgetExt data members for provided information
356 //
357 // Origin: Marian Ivanov, Marian.Ivanov@cern.ch
358 //
359 // Corrections and improvements by
360 // Andrea Dainese, Andrea.Dainese@lnl.infn.it,
361 // Andrei Gheata, Andrei.Gheata@cern.ch
362 //
363 // Ported to O2: ruben.shahoyan@cern.ch
364 //
365 if (!gGeoManager) {
366 throw std::runtime_error("meanMaterialBudgetExt requires geometry loaded");
367 }
368 double length, startD[3] = {x0, y0, z0};
369 double dir[3] = {x1 - x0, y1 - y0, z1 - z0};
370 if ((length = dir[0] * dir[0] + dir[1] * dir[1] + dir[2] * dir[2]) < TGeoShape::Tolerance() * TGeoShape::Tolerance()) {
371 return MatBudgetExt(); // return empty struct
372 }
373 length = TMath::Sqrt(length);
374 double invlen = 1. / length;
375 for (int i = 3; i--;) {
376 dir[i] *= invlen;
377 }
378 std::lock_guard<std::mutex> guard(sTGMutex);
379 // Initialize start point and direction
380 TGeoNode* currentnode = gGeoManager->InitTrack(startD, dir);
381 if (!currentnode) {
382 LOG(error) << "start point out of geometry: " << x0 << ':' << y0 << ':' << z0;
383 return MatBudgetExt(); // return empty struct
384 }
385
386 MatBudgetExt budTotal, budStep;
387 accountMaterial(currentnode->GetVolume()->GetMedium()->GetMaterial(), budStep);
388 budStep.length = length;
389
390 // Locate next boundary within length without computing safety.
391 // Propagate either with length (if no boundary found) or just cross boundary
392 gGeoManager->FindNextBoundaryAndStep(length, kFALSE);
393 Double_t stepTot = 0.0; // Step made
394 Double_t step = gGeoManager->GetStep();
395 // If no boundary within proposed length, return current step data
396 if (!gGeoManager->IsOnBoundary()) {
397 budStep.meanX2X0 = budStep.length / budStep.meanX2X0;
398 return MatBudgetExt(budStep);
399 }
400 // Try to cross the boundary and see what is next
401 Int_t nzero = 0;
402 while (length > TGeoShape::Tolerance()) {
403 if (step < 2. * TGeoShape::Tolerance()) {
404 nzero++;
405 } else {
406 nzero = 0;
407 }
408 if (nzero > 3) {
409 // This means navigation has problems on one boundary
410 // Try to cross by making a small step
411 const double* curPos = gGeoManager->GetCurrentPoint();
412 LOG(warning) << "Cannot cross boundary at (" << curPos[0] << ',' << curPos[1] << ',' << curPos[2] << ')';
413 budTotal.normalize(stepTot);
414 budTotal.nCross = -1; // flag failed navigation
415 return MatBudgetExt(budTotal);
416 }
417 stepTot += step;
418
419 budTotal.meanRho += step * budStep.meanRho;
420 budTotal.meanX2X0 += step / budStep.meanX2X0;
421 budTotal.meanA += step * budStep.meanA;
422 budTotal.meanZ += step * budStep.meanZ;
423 budTotal.meanZ2A += step * budStep.meanZ2A;
424 budTotal.nCross++;
425
426 if (step >= length) {
427 break;
428 }
429 currentnode = gGeoManager->GetCurrentNode();
430 if (!currentnode) {
431 break;
432 }
433 length -= step;
434 accountMaterial(currentnode->GetVolume()->GetMedium()->GetMaterial(), budStep);
435 gGeoManager->FindNextBoundaryAndStep(length, kFALSE);
436 step = gGeoManager->GetStep();
437 }
438 budTotal.normalize(stepTot);
439 return MatBudgetExt(budTotal);
440}
441
442//_____________________________________________________________________________________
443o2::base::MatBudget GeometryManager::meanMaterialBudget(float x0, float y0, float z0, float x1, float y1, float z1,
444 TGeoNavigator* nav)
445{
446 //
447 // Calculate mean material budget and material properties between
448 // the points "0" and "1".
449 //
450 // see MatBudget data members for provided information
451 //
452 // Origin: Marian Ivanov, Marian.Ivanov@cern.ch
453 //
454 // Corrections and improvements by
455 // Andrea Dainese, Andrea.Dainese@lnl.infn.it,
456 // Andrei Gheata, Andrei.Gheata@cern.ch
457 //
458 // Ported to O2: ruben.shahoyan@cern.ch
459 //
460 // Multi-threaded execution: pass a navigator owned by the calling thread.
461 //
462
463 double length, startD[3] = {x0, y0, z0};
464 double dir[3] = {x1 - x0, y1 - y0, z1 - z0};
465 if ((length = dir[0] * dir[0] + dir[1] * dir[1] + dir[2] * dir[2]) < TGeoShape::Tolerance() * TGeoShape::Tolerance()) {
466 return o2::base::MatBudget(); // return empty struct
467 }
468 length = TMath::Sqrt(length);
469 double invlen = 1. / length;
470 for (int i = 3; i--;) {
471 dir[i] *= invlen;
472 }
473 // A caller that passes its own navigator owns it exclusively, so no locking is needed. A caller
474 // that passes none shares gGeoManager's current navigator and must still serialize. Deciding
475 // this from the argument keeps the choice local: it does not depend on -- and cannot be broken
476 // by -- process-global state such as TGeoManager::GetMaxThreads().
477 std::unique_lock<std::mutex> guard(sTGMutex, std::defer_lock);
478 if (!nav) {
479 guard.lock();
480 nav = gGeoManager->GetCurrentNavigator();
481 }
482 // Initialize start point and direction
483 TGeoNode* currentnode = nav->InitTrack(startD, dir);
484 if (!currentnode) {
485 LOG(error) << "start point out of geometry: " << x0 << ':' << y0 << ':' << z0;
486 return o2::base::MatBudget(); // return empty struct
487 }
488
489 o2::base::MatBudget budTotal, budStep;
490 accountMaterial(currentnode->GetVolume()->GetMedium()->GetMaterial(), budStep);
491 budStep.length = length;
492
493 // Locate next boundary within length without computing safety.
494 // Propagate either with length (if no boundary found) or just cross boundary
495 nav->FindNextBoundaryAndStep(length, kFALSE);
496 Double_t stepTot = 0.0; // Step made
497 Double_t step = nav->GetStep();
498 // If no boundary within proposed length, return current step data
499 if (!nav->IsOnBoundary()) {
500 budStep.meanX2X0 = budStep.length / budStep.meanX2X0;
501 return o2::base::MatBudget(budStep);
502 }
503 // Try to cross the boundary and see what is next
504 Int_t nzero = 0;
505 while (length > TGeoShape::Tolerance()) {
506 if (step < 2. * TGeoShape::Tolerance()) {
507 nzero++;
508 } else {
509 nzero = 0;
510 }
511 if (nzero > 3) {
512 // This means navigation has problems on one boundary
513 // Try to cross by making a small step
514 const double* curPos = nav->GetCurrentPoint();
515 LOG(warning) << "Cannot cross boundary at (" << curPos[0] << ',' << curPos[1] << ',' << curPos[2] << ')';
516 budTotal.meanRho /= stepTot;
517 budTotal.length = stepTot;
518 return o2::base::MatBudget(budTotal);
519 }
520 stepTot += step;
521
522 budTotal.meanRho += step * budStep.meanRho;
523 budTotal.meanX2X0 += step / budStep.meanX2X0;
524
525 if (step >= length) {
526 break;
527 }
528 currentnode = nav->GetCurrentNode();
529 if (!currentnode) {
530 break;
531 }
532 length -= step;
533 accountMaterial(currentnode->GetVolume()->GetMedium()->GetMaterial(), budStep);
534 nav->FindNextBoundaryAndStep(length, kFALSE);
535 step = nav->GetStep();
536 }
537 budTotal.meanRho /= stepTot;
538 budTotal.length = stepTot;
539 return o2::base::MatBudget(budTotal);
540}
541
542//_________________________________
543void GeometryManager::applyMisalignent(bool applyMisalignment)
544{
546 if (!isGeometryLoaded()) {
547 LOG(fatal) << "geometry is not loaded";
548 }
549 if (applyMisalignment) {
550 auto& aligner = Aligner::Instance();
551 aligner.applyAlignment();
552 }
553}
554
555//_________________________________
556void GeometryManager::loadGeometry(std::string_view simPrefix, bool applyMisalignment, bool preferAlignedFile)
557{
558 auto loadGeom = [](const std::string_view fname) {
559 LOG(info) << "Loading geometry from " << fname;
560 TFile flGeom(fname.data());
561 if (flGeom.IsZombie()) {
562 LOG(fatal) << "Failed to open file " << fname;
563 }
564 // try under the standard CCDB name
565 if (!flGeom.Get(std::string(o2::base::NameConf::CCDBOBJECT).c_str()) &&
566 !flGeom.Get(std::string(o2::base::NameConf::GEOMOBJECTNAME_FAIR).c_str())) {
567 LOG(fatal) << "Did not find geometry named " << o2::base::NameConf::CCDBOBJECT << " or " << o2::base::NameConf::GEOMOBJECTNAME_FAIR;
568 }
569 };
570
571 if (preferAlignedFile) {
574 } else {
576 loadGeom(o2::base::NameConf::getGeomFileName(simPrefix));
577 applyMisalignent(applyMisalignment);
578 }
579}
580
581#ifdef O2_WITH_VECGEOM
582
583namespace
584{
588bool usesBvhAcceleration(vecgeom::LogicalVolume const* vol)
589{
590 return vol->GetDaughtersp()->size() > 2;
591}
592
596void ensureVecGeomWorldBuilt()
597{
598 GeometryManager::buildVecGeomGeometry(true);
599}
600} // namespace
601
602void GeometryManager::buildVecGeomGeometry(bool flattenAssemblies, int booleanThreshold)
603{
604 static std::once_flag onceFlag;
605 std::call_once(onceFlag, [flattenAssemblies, booleanThreshold]() {
606 if (!gGeoManager) {
607 LOG(fatal) << "Cannot build VecGeom geometry: no TGeo geometry loaded (call GeometryManager::loadGeometry() first)";
608 }
609 // Translate geometry and material pointers, then build acceleration structures.
610 tgeo2vecgeom::RootGeoManager::Instance().SetMaterialConversionHook([](TGeoMaterial const* m) { return (void*)m; });
611 LOG(info) << "VecGeom conversion: flattenAssemblies=" << flattenAssemblies;
612 tgeo2vecgeom::RootGeoManager::Instance().SetFlattenAssemblies(flattenAssemblies);
613#if __has_include(<VecGeom/management/BooleanFactory.h>)
614 // Applied when the conversion closes the geometry.
615 LOG(info) << "VecGeom conversion: booleanThreshold=" << booleanThreshold;
616 vecgeom::GeoManager::Instance().SetBooleanOptimizationThreshold(booleanThreshold > 0 ? booleanThreshold : 0);
617#else
618 if (booleanThreshold > 0) {
619 LOG(warning) << "VecGeom without BooleanFactory: Boolean solids are kept as converted";
620 }
621#endif
622 tgeo2vecgeom::RootGeoManager::Instance().LoadRootGeometry();
623
624 // Acceleration structures must be built before the navigators/locators reference them.
625#if VECGEOM_VERSION < 0x020000
626 // VecGeom 2 has no ABBoxManager: the BVH below is built directly.
627 vecgeom::ABBoxManager::Instance().InitABBoxesForCompleteGeometry();
628#endif
629 // Builds a BVH per logical volume.
630 vecgeom::BVHManager::Init();
631
632 // For each logical volume, set a navigator (used for ComputeStep), a matched level locator
633 // (used for point relocation after a boundary crossing via GlobalLocator) and, where the
634 // VNavigator family is complete, the safety estimator LogicalVolume::GetSafetyEstimator()
635 // hands out, which is separate from the one a navigator uses internally.
636 for (auto& lvol : vecgeom::GeoManager::Instance().GetLogicalVolumesMap()) {
637 auto* vol = lvol.second;
638 if (!usesBvhAcceleration(vol)) {
639 vol->SetNavigator(vecgeom::NewSimpleNavigator<>::Instance());
640#ifdef O2_VECGEOM_HAS_BVH_VNAVIGATOR
641 vol->SetLevelLocator(vol->ContainsAssembly() ? vecgeom::SimpleAssemblyLevelLocator::GetInstance()
642 : vecgeom::SimpleLevelLocator::GetInstance());
643 vol->SetSafetyEstimator(vecgeom::SimpleSafetyEstimator::Instance());
644#else
645 vol->SetLevelLocator(vecgeom::SimpleLevelLocator::GetInstance());
646#endif
647 } else {
648#if defined(O2_VECGEOM_HAS_BVH_VNAVIGATOR)
649 vol->SetNavigator(vecgeom::BVHNavigatorV<>::Instance());
650 vol->SetLevelLocator(vol->ContainsAssembly() ? vecgeom::BVHAssemblyAwareLevelLocator::GetInstance()
651 : vecgeom::BVHLevelLocator::GetInstance());
652 vol->SetSafetyEstimator(vecgeom::BVHSafetyEstimator::Instance());
653#elif VECGEOM_VERSION >= 0x020000
654 // VecGeom 2 turned BVHNavigator into a plain class with static entry points instead of a
655 // VNavigator singleton, so there is nothing to attach: vecGeomMaterialBudget() calls it
656 // directly.
657 //
658 // The locator changes too, and not by choice. BVHLevelLocator does not compile in 2.1.0 or
659 // 2.1.1 -- the header is byte-identical in both -- because its four LevelLocate() calls
660 // have no match among the single templated BVH::LevelLocate(int exclude_item_id, ...) that
661 // v2 ships. It survived two releases because nothing in VecGeom includes that header
662 // except itself, so upstream CI never compiles it; O2 appears to be its only consumer.
663 //
664 // SimpleABBoxLevelLocator is the accelerated stand-in, using the ABBoxes built just above.
665 // Three of the four methods could be rebuilt on the templated API (the idiom is in
666 // BVHNavigator itself: bvh->LevelInside<BVHNavigator>(exclude_id, point, id, dlp)), but
667 // the direction-aware LevelLocateExclVol has no v2 counterpart at all, so this stays a
668 // fallback rather than a reimplementation. Revert to BVHLevelLocator once upstream fixes
669 // or removes it, and measure: whether ABBox location costs anything real here is unknown.
670 vol->SetLevelLocator(vecgeom::SimpleABBoxLevelLocator::GetInstance());
671#else
672 vol->SetNavigator(vecgeom::BVHNavigator<>::Instance());
673 vol->SetLevelLocator(vecgeom::BVHLevelLocator::GetInstance());
674#endif
675 }
676 }
677 });
678}
679
680//_____________________________________________________________________________________
681o2::base::MatBudget GeometryManager::vecGeomMaterialBudget(float x0, float y0, float z0, float x1, float y1, float z1)
682{
683 // Mean material budget between "0" and "1" via VecGeom's BVH-accelerated ray/boundary
684 // intersection, instead of TGeo.
685 ensureVecGeomWorldBuilt();
686
687 using Vector3D = vecgeom::Vector3D<vecgeom::Precision>;
688
689 double length, start[3] = {x0, y0, z0};
690 double dir[3] = {x1 - x0, y1 - y0, z1 - z0};
691 if ((length = dir[0] * dir[0] + dir[1] * dir[1] + dir[2] * dir[2]) < TGeoShape::Tolerance() * TGeoShape::Tolerance()) {
692 return o2::base::MatBudget(); // return empty struct
693 }
694 length = std::sqrt(length);
695 double invlen = 1. / length;
696 for (int i = 3; i--;) {
697 dir[i] *= invlen;
698 }
699
700 // Only the allocation differs between VecGeom versions; everything below works on pointers in
701 // both, which also keeps the std::swap() at the end of the loop a pointer swap rather than a
702 // copy of the state itself.
703 //
704 // VecGeom 1 builds NavigationState as NavStatePath, a variable-size object that must be told the
705 // maximum depth at construction and can only be made through MakeInstance(). VecGeom 2 dropped
706 // NavStatePath and MakeInstance with it: NavigationState is NavStateIndex or NavStateTuple, both
707 // fixed-size value types, so a thread_local object is the direct equivalent.
708#if VECGEOM_VERSION >= 0x020000
709 thread_local static vecgeom::NavigationState newnavstateStorage, currnavstateStorage, startCacheStorage;
710 thread_local static vecgeom::NavigationState* newnavstate = &newnavstateStorage;
711 thread_local static vecgeom::NavigationState* currnavstate = &currnavstateStorage;
712 thread_local static vecgeom::NavigationState* startCache = &startCacheStorage;
713#else
714 thread_local static vecgeom::NavigationState* newnavstate = vecgeom::NavigationState::MakeInstance(vecgeom::GeoManager::Instance().getMaxDepth());
715 thread_local static vecgeom::NavigationState* currnavstate = vecgeom::NavigationState::MakeInstance(vecgeom::GeoManager::Instance().getMaxDepth());
716 thread_local static vecgeom::NavigationState* startCache = vecgeom::NavigationState::MakeInstance(vecgeom::GeoManager::Instance().getMaxDepth());
717#endif
718 thread_local static bool startCacheValid = false;
719
720 Vector3D currPoint(x0, y0, z0);
721 Vector3D dirr(dir[0], dir[1], dir[2]);
722 constexpr double kPush = 1.E-6; // mimick the nudging of TGeo's FindNextBoundaryAndStep
723 auto world = vecgeom::GeoManager::Instance().GetWorld();
724 o2::base::MatBudget budTot, budStep;
725 budStep.length = length;
726
727 // Locate the starting volume, reusing the path from the previous call when still valid.
728 if (startCacheValid && !startCache->IsOutside()) {
729 startCache->CopyTo(currnavstate);
730 vecgeom::Transformation3D m;
731 currnavstate->TopMatrix(m);
732 vecgeom::GlobalLocator::RelocatePointFromPath(m.Transform(currPoint), *currnavstate);
733 } else {
734 currnavstate->Clear();
735 vecgeom::GlobalLocator::LocateGlobalPoint(world, currPoint, *currnavstate, true);
736 }
737 if (currnavstate->IsOutside() || currnavstate->Top() == nullptr) {
738 LOG(error) << "start point out of geometry: " << x0 << ':' << y0 << ':' << z0;
739 startCacheValid = false;
740 return o2::base::MatBudget();
741 }
742 currnavstate->CopyTo(startCache);
743 startCacheValid = true;
744
745 double stepTot = 0.;
746 double remainingDist = length;
747 Int_t nzero = 0;
748 while (remainingDist > 1.E-10) {
749 auto* lvol = currnavstate->Top()->GetLogicalVolume();
750 // Not LogicalVolume::GetMaterialPtr(): VecGeom 2 dropped the material slot from the logical
751 // volume. TGeo2VecGeom keeps what its conversion hook returned, indexed by logical volume id,
752 // and serves it for both VecGeom versions.
753 accountMaterial(static_cast<TGeoMaterial*>(tgeo2vecgeom::RootGeoManager::Instance().GetMaterialPtr(lvol)), budStep);
754#if VECGEOM_VERSION >= 0x020000
755 const double step =
756 usesBvhAcceleration(lvol)
757 ? static_cast<double>(vecgeom::BVHNavigator::ComputeStepAndPropagatedState(currPoint, dirr, remainingDist, *currnavstate, *newnavstate))
758 : static_cast<double>(lvol->GetNavigator()->ComputeStepAndPropagatedState(currPoint, dirr, remainingDist, *currnavstate, *newnavstate));
759#else
760 const double step = static_cast<double>(lvol->GetNavigator()->ComputeStepAndPropagatedState(currPoint, dirr, remainingDist, *currnavstate, *newnavstate));
761#endif
762 if (step < 2.E-10) {
763 nzero++;
764 } else {
765 nzero = 0;
766 }
767 if (nzero > 3) {
768 // This means navigation has problems on one boundary
769 LOG(warning) << "Cannot cross boundary at (" << currPoint[0] << ',' << currPoint[1] << ',' << currPoint[2] << ')';
770 budTot.meanRho /= stepTot;
771 budTot.length = stepTot;
772 return o2::base::MatBudget(budTot);
773 }
774
775 remainingDist -= step;
776 stepTot += step;
777 budTot.meanRho += step * budStep.meanRho;
778 budTot.meanX2X0 += step / budStep.meanX2X0;
779 currPoint = currPoint + (step + kPush) * dirr;
780 std::swap(currnavstate, newnavstate);
781 }
782 budTot.meanRho /= stepTot;
783 budTot.length = stepTot;
784 return o2::base::MatBudget(budTot);
785}
786
787#endif // O2_WITH_VECGEOM
788
789//_____________________________________________________________________________________
791{
792#ifdef O2_WITH_VECGEOM
793 ensureVecGeomWorldBuilt();
794 return true;
795#else
796 return false;
797#endif
798}
799
800//_____________________________________________________________________________________
801bool GeometryManager::vecGeomLocate(double x, double y, double z, std::vector<TGeoNode*>& chain)
802{
803 chain.clear();
804#ifdef O2_WITH_VECGEOM
805 ensureVecGeomWorldBuilt();
806 // One state per thread, as for the material budget above, and allocated the
807 // same way: see the comment there on NavStatePath vs NavStateIndex.
808#if VECGEOM_VERSION >= 0x020000
809 thread_local vecgeom::NavigationState stateStorage;
810 thread_local vecgeom::NavigationState* state = &stateStorage;
811#else
812 thread_local vecgeom::NavigationState* state =
813 vecgeom::NavigationState::MakeInstance(vecgeom::GeoManager::Instance().getMaxDepth());
814#endif
815 state->Clear();
816 const vecgeom::Vector3D<vecgeom::Precision> point(x, y, z);
817 if (vecgeom::GlobalLocator::LocateGlobalPoint(vecgeom::GeoManager::Instance().GetWorld(), point, *state, true) ==
818 nullptr) {
819 return false;
820 }
821 auto const& converter = tgeo2vecgeom::RootGeoManager::Instance();
822 for (int level = 0; level < (int)state->GetCurrentLevel(); ++level) {
823 auto const* placed = state->At(level);
824 auto const* node = placed != nullptr ? converter.tgeonode(placed) : nullptr;
825 if (node == nullptr) {
826 chain.clear();
827 return false;
828 }
829 chain.push_back(const_cast<TGeoNode*>(node));
830 }
831 return !chain.empty();
832#else
833 (void)x;
834 (void)y;
835 (void)z;
836 return false;
837#endif
838}
Definition of the base alignment parameters class.
Definition of the GeometryManager class.
std::unique_ptr< expressions::Node > node
int32_t i
GPUChain * chain
char error[CURL_ERROR_SIZE]
SurfaceTrackState state
Definition of the Names Generator class.
uint32_t res
Definition RawData.h:0
static const char * getSymbolicName(o2::detectors::DetID detid, int sensid)
static Bool_t getOriginalMatrix(o2::detectors::DetID detid, int sensid, TGeoHMatrix &m)
static void loadGeometry(std::string_view geomFilePath="", bool applyMisalignment=false, bool preferAlignedFile=true)
static bool applyAlignment(const std::vector< o2::detectors::AlignParam > &algPars, bool keepPhysicalNodes=true)
static o2::base::MatBudget meanMaterialBudget(float x0, float y0, float z0, float x1, float y1, float z1, TGeoNavigator *nav=nullptr)
static MatBudgetExt meanMaterialBudgetExt(float x0, float y0, float z0, float x1, float y1, float z1)
static int getSensID(o2::detectors::DetID detid, int sensid)
static bool vecGeomLocate(double x, double y, double z, std::vector< TGeoNode * > &chain)
static TGeoHMatrix * getMatrix(const char *symname)
static TGeoPNEntry * getPNEntry(o2::detectors::DetID detid, Int_t sensid)
static void applyMisalignent(bool applyMisalignment=true)
static std::string getAlignedGeomFileName(const std::string_view prefix="")
Definition NameConf.cxx:47
static std::string getGeomFileName(const std::string_view prefix="")
Definition NameConf.cxx:41
static constexpr std::string_view CCDBOBJECT
Definition NameConf.h:66
static constexpr std::string_view GEOMOBJECTNAME_FAIR
Definition NameConf.h:83
Static class with identifiers, bitmasks and names for ALICE detectors.
Definition DetID.h:60
GLint GLenum GLint x
Definition glcorearb.h:403
const GLfloat * m
Definition glcorearb.h:4066
GLuint GLfloat GLfloat GLfloat GLfloat y1
Definition glcorearb.h:5034
GLuint GLfloat GLfloat GLfloat x1
Definition glcorearb.h:5034
GLboolean GLboolean GLboolean b
Definition glcorearb.h:1233
GLint y
Definition glcorearb.h:270
GLuint GLsizei GLsizei * length
Definition glcorearb.h:790
typedef void(APIENTRYP PFNGLCULLFACEPROC)(GLenum mode)
GLuint GLfloat x0
Definition glcorearb.h:5034
GLsizei const GLchar *const * path
Definition glcorearb.h:3591
GLint level
Definition glcorearb.h:275
GLboolean GLboolean GLboolean GLboolean a
Definition glcorearb.h:1233
GLuint GLfloat GLfloat y0
Definition glcorearb.h:5034
GLdouble GLdouble GLdouble z
Definition glcorearb.h:843
float float float float z1
Definition MathUtils.h:82
ROOT::Math::DisplacementVector3D< ROOT::Math::Cartesian3D< T >, ROOT::Math::DefaultCoordinateSystemTag > Vector3D
value_T step
Definition TrackUtils.h:42
float length
length in material
Definition MatCell.h:55
float meanRho
mean density, g/cm^3
Definition MatCell.h:30
float meanX2X0
fraction of radiaton lenght
Definition MatCell.h:31
LOG(info)<< "Compressed in "<< sw.CpuTime()<< " s"