Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-12-03 10:57:48

0001 //------------------------------- -*- C++ -*- -------------------------------//
0002 // Copyright Celeritas contributors: see top-level COPYRIGHT file for details
0003 // SPDX-License-Identifier: (Apache-2.0 OR MIT)
0004 //---------------------------------------------------------------------------//
0005 //! \file orange/univ/SimpleUnitTracker.hh
0006 //---------------------------------------------------------------------------//
0007 #pragma once
0008 
0009 #include "corecel/Assert.hh"
0010 #include "corecel/math/Algorithms.hh"
0011 #include "corecel/math/ArrayUtils.hh"
0012 #include "orange/OrangeData.hh"
0013 #include "orange/OrangeTypes.hh"
0014 #include "orange/SenseUtils.hh"
0015 #include "orange/detail/BvhEnclosingVolFinder.hh"
0016 #include "orange/detail/BvhIntersectingVolFinder.hh"
0017 #include "orange/surf/LocalSurfaceVisitor.hh"
0018 
0019 #include "detail/InfixEvaluator.hh"
0020 #include "detail/LogicEvaluator.hh"
0021 #include "detail/SenseCalculator.hh"
0022 #include "detail/SurfaceFunctors.hh"
0023 #include "detail/Types.hh"
0024 #include "detail/Utils.hh"
0025 
0026 #if !CELER_DEVICE_COMPILE
0027 #    include "corecel/io/Logger.hh"
0028 #    include "corecel/io/Repr.hh"
0029 #endif
0030 
0031 namespace celeritas
0032 {
0033 //---------------------------------------------------------------------------//
0034 /*!
0035  * Track a particle in a universe of well-connected volumes.
0036  *
0037  * The simple unit tracker is based on a set of non-overlapping volumes
0038  * comprised of surfaces. It is a faster but less "user-friendly" version of
0039  * the masked unit tracker because it requires all volumes to be exactly
0040  * defined by their connected surfaces. It does \em not check for overlaps.
0041  *
0042  * All IDs inside the simple unit tracker are \em local and
0043  * implementation-specific,  with the exception that daughter IDs are *global*
0044  * (but also implementation-specific).
0045  */
0046 class SimpleUnitTracker
0047 {
0048   public:
0049     //!@{
0050     //! \name Type aliases
0051     using ParamsRef = NativeCRef<OrangeParamsData>;
0052     using Initialization = detail::Initialization;
0053     using Intersection = detail::Intersection;
0054     using LocalState = detail::LocalState;
0055     using LogicEvaluator
0056         = std::conditional_t<orange_tracking_logic == LogicNotation::infix,
0057                              detail::InfixEvaluator,
0058                              detail::PostfixEvaluator>;
0059     using VolumeView = detail::LocalVolumeView;
0060     //!@}
0061 
0062   public:
0063     // Construct with parameters (unit definitions and this one's ID)
0064     inline CELER_FUNCTION SimpleUnitTracker(ParamsRef const& params,
0065                                             SimpleUnitId id);
0066 
0067     //// ACCESSORS ////
0068 
0069     //! Number of local volumes
0070     CELER_FUNCTION LocalVolumeId::size_type num_volumes() const
0071     {
0072         return unit_record_.volumes.size();
0073     }
0074 
0075     //! Number of local surfaces
0076     CELER_FUNCTION LocalSurfaceId::size_type num_surfaces() const
0077     {
0078         return unit_record_.surfaces.size();
0079     }
0080 
0081     //! SimpleUnitRecord for this tracker
0082     CELER_FUNCTION SimpleUnitRecord const& unit_record() const
0083     {
0084         return unit_record_;
0085     }
0086 
0087     // DaughterId of universe embedded in a given volume
0088     inline CELER_FUNCTION DaughterId daughter(LocalVolumeId vol) const;
0089 
0090     // Volume level relative to the "top" canonical volume in the universe
0091     inline CELER_FUNCTION vol_level_uint local_vol_level(
0092         LocalVolumeId vol) const;
0093 
0094     // Local volume ID of the parent canonical volume, if any
0095     inline CELER_FUNCTION LocalVolumeId local_parent(LocalVolumeId vol) const;
0096 
0097     //// OPERATIONS ////
0098 
0099     // Find the local volume from a position
0100     inline CELER_FUNCTION Initialization initialize(
0101         LocalState const& state) const;
0102 
0103     // Find the new volume by crossing a surface
0104     inline CELER_FUNCTION Initialization cross_boundary(
0105         LocalState const& state) const;
0106 
0107     // DEPRECATED: search for intersection without limit
0108     inline CELER_FUNCTION Intersection intersect(LocalState const& state) const;
0109 
0110     // Calculate nearby distance to an exiting face for the current volume
0111     inline CELER_FUNCTION Intersection intersect(LocalState const& state,
0112                                                  real_type max_dist) const;
0113 
0114     // Calculate closest distance to a surface in any direction
0115     inline CELER_FUNCTION real_type safety(Real3 const& pos,
0116                                            LocalVolumeId vol) const;
0117 
0118     // Calculate the local surface normal
0119     inline CELER_FUNCTION Real3 normal(Real3 const& pos,
0120                                        LocalSurfaceId surf) const;
0121 
0122   private:
0123     //// DATA ////
0124 
0125     ParamsRef const& params_;
0126     SimpleUnitRecord const& unit_record_;
0127 
0128     //// METHODS ////
0129 
0130     // Get volumes that have the given surface as a "face" (connectivity)
0131     inline CELER_FUNCTION LdgSpan<LocalVolumeId const> get_neighbors(
0132         LocalSurfaceId) const;
0133 
0134     template<class F>
0135     inline CELER_FUNCTION LocalVolumeId find_volume_where(Real3 const& pos,
0136                                                           F&& predicate) const;
0137 
0138     inline CELER_FUNCTION Intersection simple_intersect(
0139         LocalState const&, VolumeView const&, size_type) const;
0140     inline CELER_FUNCTION Intersection complex_intersect(
0141         LocalState const&, VolumeView const&, size_type, Sense, real_type) const;
0142     inline CELER_FUNCTION Intersection background_intersect(LocalState const&,
0143                                                             real_type) const;
0144 
0145     // Create a Surfaces object from the params
0146     inline CELER_FUNCTION LocalSurfaceVisitor make_surface_visitor() const;
0147 
0148     // Create a Volumes object from the params
0149     inline CELER_FUNCTION VolumeView make_local_volume(
0150         LocalVolumeId vol_id) const;
0151 };
0152 
0153 //---------------------------------------------------------------------------//
0154 // INLINE DEFINITIONS
0155 //---------------------------------------------------------------------------//
0156 /*!
0157  * Construct with reference to persistent parameter data.
0158  *
0159  * \todo When adding multiple universes, this will calculate range of
0160  * LocalVolumeIds that belong to this unit. For now we assume all volumes and
0161  * surfaces belong to us.
0162  */
0163 CELER_FUNCTION SimpleUnitTracker::SimpleUnitTracker(ParamsRef const& params,
0164                                                     SimpleUnitId suid)
0165     : params_(params), unit_record_(params.simple_units[suid])
0166 {
0167     CELER_EXPECT(params_);
0168 }
0169 
0170 //---------------------------------------------------------------------------//
0171 /*!
0172  * Find the local volume from a position.
0173  *
0174  * To avoid edge cases and inconsistent logical/physical states, it is
0175  * prohibited to initialize from an arbitrary point directly onto a surface.
0176  *
0177  * \todo This prohibition currently also extends to *internal* surfaces, even
0178  * if both sides of that surface are "in" the current cell. We may need to
0179  * relax that.
0180  */
0181 CELER_FUNCTION auto SimpleUnitTracker::initialize(
0182     LocalState const& state) const -> Initialization
0183 {
0184     CELER_EXPECT(params_);
0185     CELER_EXPECT(!state.surface && !state.volume);
0186 
0187     // Use the BVH to locate a position that's inside, and save whether it's on
0188     // a surface in the found volume
0189     detail::OnFace on_surface;
0190     auto is_inside = [this, &state, &on_surface](LocalVolumeId id) -> bool {
0191         on_surface = {};
0192         VolumeView vol = this->make_local_volume(id);
0193         auto calc_senses = detail::SenseCalculator(
0194             this->make_surface_visitor(), vol, state.pos, on_surface);
0195         return LogicEvaluator(vol.logic())(calc_senses);
0196     };
0197     LocalVolumeId id = this->find_volume_where(state.pos, is_inside);
0198 
0199     if (on_surface)
0200     {
0201         // Prohibit initialization on a surface
0202         id = {};
0203     }
0204     else if (!id)
0205     {
0206         // Not found: replace with background volume (if any)
0207         id = unit_record_.background;
0208     }
0209 
0210     return Initialization{id, {}};
0211 }
0212 
0213 //---------------------------------------------------------------------------//
0214 /*!
0215  * Find the local volume on the opposite side of a surface.
0216  */
0217 CELER_FUNCTION auto SimpleUnitTracker::cross_boundary(
0218     LocalState const& state) const -> Initialization
0219 {
0220     CELER_EXPECT(state.surface && state.volume);
0221 
0222     detail::OnLocalSurface on_surface;
0223     auto is_inside
0224         = [this, &state, &on_surface](LocalVolumeId const& id) -> bool {
0225         if (id == state.volume)
0226         {
0227             // Cannot cross surface into the same volume
0228             return false;
0229         }
0230 
0231         VolumeView vol = this->make_local_volume(id);
0232         detail::OnFace face{detail::find_face(vol, state.surface)};
0233         auto calc_senses = detail::SenseCalculator(
0234             this->make_surface_visitor(), vol, state.pos, face);
0235 
0236         if (LogicEvaluator(vol.logic())(calc_senses))
0237         {
0238             // Inside: find and save the local surface ID, and end the search
0239             on_surface = get_surface(vol, face);
0240             return true;
0241         }
0242         return false;
0243     };
0244 
0245     auto neighbors = this->get_neighbors(state.surface.id());
0246 
0247     // If this surface has 2 neighbors or fewer (excluding the current cell),
0248     // use linear search to check neighbors. Otherwise, traverse the BVH tree.
0249     if (neighbors.size() < 3)
0250     {
0251         for (LocalVolumeId id : neighbors)
0252         {
0253             if (is_inside(id))
0254             {
0255                 return {id, on_surface};
0256             }
0257         }
0258     }
0259     else
0260     {
0261         if (LocalVolumeId id = this->find_volume_where(state.pos, is_inside))
0262         {
0263             return {id, on_surface};
0264         }
0265     }
0266 
0267     return {unit_record_.background, state.surface};
0268 }
0269 
0270 //---------------------------------------------------------------------------//
0271 /*!
0272  * Search for an intersection without a distance limit.
0273  *
0274  * \deprecated Provide a physically reasonable upper bound to the distance
0275  * to reduce search cost and avoid a redundant method.
0276  */
0277 CELER_FORCEINLINE_FUNCTION auto SimpleUnitTracker::intersect(
0278     LocalState const& state) const -> Intersection
0279 {
0280     return this->intersect(state, NumericLimits<real_type>::max());
0281 }
0282 
0283 //---------------------------------------------------------------------------//
0284 /*!
0285  * Calculate distance-to-intercept for the next local surface.
0286  *
0287  * The algorithm is:
0288  * - If the volume is the "background" then search externally for the next
0289  *   volume with \c background_intersect (equivalent of DistanceToIn for
0290  *   Geant4)
0291  * - Use the current volume to find potential intersecting surfaces and maximum
0292  *   number of intersections.
0293  * - Loop over all surfaces and calculate the distance to intercept based on
0294  *   the given physical and logical state. Save to the thread-local buffer
0295  *   *only* intersections that are valid (either finite *or* less than the
0296  *   user-supplied maximum). The buffer contains the distances, the face
0297  *   indices, and an index used for sorting (if the volume has internal
0298  *   surfaces).
0299  * - If no intersecting surfaces are found, return immediately. (Rely on the
0300  *   caller to set the "maximum distance" if we're not searching to infinity.)
0301  * - If the volume has no special cases, find the closest surface by calling \c
0302  *   simple_intersect.
0303  * - If the volume has internal surfaces call \c complex_intersect.
0304  */
0305 CELER_FUNCTION auto SimpleUnitTracker::intersect(
0306     LocalState const& state, real_type max_dist) const -> Intersection
0307 {
0308     CELER_EXPECT(state.volume);
0309     CELER_EXPECT(max_dist > 0);
0310 
0311     // Resize temporaries based on volume properties
0312     VolumeView vol = this->make_local_volume(state.volume);
0313     CELER_ASSERT(state.temp_next.size >= vol.max_intersections());
0314 
0315     if (vol.implicit_vol())
0316     {
0317         // Search all the volumes "externally"
0318         return this->background_intersect(state, max_dist);
0319     }
0320 
0321     // Find all valid (nearby or finite, depending on F) surface intersection
0322     // distances inside this volume. Fill the `isect` array if the tracking
0323     // algorithm requires sorting.
0324     detail::CalcIntersections calc_intersections{
0325         max_dist,
0326         state.pos,
0327         state.dir,
0328         state.surface ? vol.find_face(state.surface.id()) : FaceId{},
0329         vol.simple_intersection(),
0330         state.temp_next};
0331     LocalSurfaceVisitor visit_surface(params_, unit_record_.surfaces);
0332     for (LocalSurfaceId surface : vol.faces())
0333     {
0334         visit_surface(calc_intersections, surface);
0335     }
0336     CELER_ASSERT(calc_intersections.face_idx() == vol.num_faces());
0337     size_type num_isect = calc_intersections.isect_idx();
0338     CELER_ASSERT(num_isect <= vol.max_intersections());
0339 
0340     if (num_isect == 0)
0341     {
0342         // No intersection (no surfaces in this volume, no finite distances, or
0343         // no "nearby" distances depending on F)
0344         return {};
0345     }
0346     else if (vol.simple_intersection())
0347     {
0348         // No internal surfaces nor implicit volume: the closest distance is
0349         // the next boundary
0350         return this->simple_intersect(state, vol, num_isect);
0351     }
0352     else if (vol.internal_surfaces())
0353     {
0354         // Internal surfaces: sort valid intersection distances in ascending
0355         // order and find the closest surface that puts us outside.
0356         celeritas::sort(state.temp_next.isect,
0357                         state.temp_next.isect + num_isect,
0358                         [&state](size_type a, size_type b) {
0359                             return state.temp_next.distance[a]
0360                                    < state.temp_next.distance[b];
0361                         });
0362         // Call with a target sense of "inside," because we are seeking a
0363         // surface for which crossing will result leaving the volume
0364         return this->complex_intersect(state,
0365                                        vol,
0366                                        num_isect,
0367                                        Sense::outside,
0368                                        numeric_limits<real_type>::infinity());
0369     }
0370 
0371     CELER_ASSERT_UNREACHABLE();  // Unexpected set of flags
0372 }
0373 
0374 //---------------------------------------------------------------------------//
0375 /*!
0376  * Calculate nearest distance to a surface in any direction.
0377  *
0378  * The safety calculation uses a very limited method for calculating the safety
0379  * distance: it's the nearest distance to any surface, for a certain subset of
0380  * surfaces.  Other surface types will return a safety distance of zero.
0381  * Complex surfaces might return the distance to internal surfaces that do not
0382  * represent the edge of a volume. Such distances are conservative but will
0383  * necessarily slow down the simulation.
0384  */
0385 CELER_FUNCTION real_type SimpleUnitTracker::safety(Real3 const& pos,
0386                                                    LocalVolumeId vol_id) const
0387 {
0388     CELER_EXPECT(vol_id);
0389 
0390     VolumeView vol = this->make_local_volume(vol_id);
0391     if (!vol.simple_safety())
0392     {
0393         // Has a tricky surface: we can't use the simple algorithm to calculate
0394         // the safety, so return a conservative estimate.
0395         return 0;
0396     }
0397 
0398     // Calculate minimum distance to all local faces
0399     real_type result = numeric_limits<real_type>::infinity();
0400     LocalSurfaceVisitor visit_surface(params_, unit_record_.surfaces);
0401     detail::CalcSafetyDistance calc_safety{pos};
0402     for (LocalSurfaceId surface : vol.faces())
0403     {
0404         result = celeritas::min(result, visit_surface(calc_safety, surface));
0405     }
0406 
0407     CELER_ENSURE(result >= 0);
0408     return result;
0409 }
0410 
0411 //---------------------------------------------------------------------------//
0412 /*!
0413  * Calculate the local surface normal.
0414  */
0415 CELER_FUNCTION auto SimpleUnitTracker::normal(
0416     Real3 const& pos, LocalSurfaceId surf) const -> Real3
0417 {
0418     CELER_EXPECT(surf);
0419 
0420     LocalSurfaceVisitor visit_surface(params_, unit_record_.surfaces);
0421     return visit_surface(detail::CalcNormal{pos}, surf);
0422 }
0423 
0424 //---------------------------------------------------------------------------//
0425 // PRIVATE INLINE DEFINITIONS
0426 //---------------------------------------------------------------------------//
0427 /*!
0428  * Get volumes that have the given surface as a "face" (connectivity).
0429  */
0430 CELER_FUNCTION auto SimpleUnitTracker::get_neighbors(LocalSurfaceId surf) const
0431     -> LdgSpan<LocalVolumeId const>
0432 {
0433     CELER_EXPECT(surf < this->num_surfaces());
0434 
0435     ConnectivityRecord const& conn
0436         = params_.connectivity_records[unit_record_.connectivity[surf]];
0437 
0438     CELER_ENSURE(!conn.neighbors.empty());
0439     return params_.local_volume_ids[conn.neighbors];
0440 }
0441 
0442 //---------------------------------------------------------------------------//
0443 /*!
0444  * Search the BVH to find where the predicate is true for the point.
0445  *
0446  * The predicate should have the signature \code bool(LocalVolumeId) \endcode.
0447  */
0448 template<class F>
0449 CELER_FUNCTION LocalVolumeId SimpleUnitTracker::find_volume_where(
0450     Real3 const& pos, F&& predicate) const
0451 {
0452     detail::BvhEnclosingVolFinder find_volume{unit_record_.bvh_tree,
0453                                               params_.bvh_tree_data};
0454     return find_volume(pos, predicate);
0455 }
0456 
0457 //---------------------------------------------------------------------------//
0458 /*!
0459  * Calculate distance to the next boundary for nonreentrant volumes.
0460  */
0461 CELER_FUNCTION auto SimpleUnitTracker::simple_intersect(
0462     LocalState const& state, VolumeView const& vol, size_type num_isect) const
0463     -> Intersection
0464 {
0465     CELER_EXPECT(num_isect > 0);
0466 
0467     // Crossing any surface will leave the volume; perform a linear search for
0468     // the smallest (but positive) distance
0469     size_type distance_idx
0470         = celeritas::min_element(state.temp_next.distance,
0471                                  state.temp_next.distance + num_isect,
0472                                  Less<real_type>{})
0473           - state.temp_next.distance;
0474     CELER_ASSERT(distance_idx < num_isect);
0475 
0476     // Determine the crossing surface
0477     LocalSurfaceId surface;
0478     {
0479         FaceId face = state.temp_next.face[distance_idx];
0480         CELER_ASSERT(face);
0481         surface = vol.get_surface(face);
0482         CELER_ASSERT(surface);
0483     }
0484 
0485     Sense cur_sense;
0486     if (surface == state.surface.id())
0487     {
0488         // Crossing the same surface that we're currently on and inside (e.g.
0489         // on the inside surface of a sphere, and the next intersection is the
0490         // other side)
0491         cur_sense = state.surface.sense();
0492     }
0493     else
0494     {
0495         LocalSurfaceVisitor visit_surface(params_, unit_record_.surfaces);
0496         SignedSense ss = visit_surface(detail::CalcSense{state.pos}, surface);
0497         CELER_ASSERT(ss != SignedSense::on);
0498         cur_sense = to_sense(ss);
0499     }
0500 
0501     // Post-surface sense will be on the other side of the surface
0502     Intersection result;
0503     result.surface = {surface, cur_sense};
0504     result.distance = state.temp_next.distance[distance_idx];
0505     return result;
0506 }
0507 
0508 //---------------------------------------------------------------------------//
0509 /*!
0510  * Calculate boundary distance if internal surfaces are present.
0511  *
0512  * In "complex" volumes, crossing a surface can still leave the particle in its
0513  * original state.
0514  *
0515  * We have to iteratively track through all surfaces, in order of minimum
0516  * distance, to determine whether crossing them in sequence will cause us
0517  * change our sense with respect to the volume.
0518  *
0519  * The target_sense argument denotes whether a valid intersection is one that
0520  * puts us inside or outside the volume.
0521  *
0522  * \pre The `state.temp_next.isect` array must be sorted by the caller by
0523  * ascending distance.
0524  */
0525 CELER_FUNCTION auto SimpleUnitTracker::complex_intersect(
0526     LocalState const& state,
0527     VolumeView const& vol,
0528     size_type num_isect,
0529     Sense target_sense,
0530     real_type max_distance) const -> Intersection
0531 {
0532     CELER_ASSERT(num_isect > 0);
0533 
0534     // Position and face state of the test point as we move across progressive
0535     // surfaces.
0536     // TODO: use rvalue references for local state since it's temporary; update
0537     // its \c pos in place
0538     Real3 pos{state.pos};
0539     detail::OnFace on_face(detail::find_face(vol, state.surface));
0540 
0541     detail::SenseCalculator calc_sense{
0542         this->make_surface_visitor(), vol, pos, on_face};
0543 
0544     // Calculate local senses, taking current face into account
0545     // Current senses should put us inside the volume
0546     LogicEvaluator is_inside(vol.logic());
0547 
0548     // Log a warning if the current sense already matches the target sense
0549 #if !CELER_DEVICE_COMPILE
0550     if constexpr (CELERITAS_DEBUG)
0551     {
0552         if (is_inside(calc_sense) == (target_sense == Sense::inside))
0553         {
0554             CELER_LOG_LOCAL(warning)
0555                 << "Calculated surface sense at position " << repr(pos)
0556                 << " already matches target sense";
0557         }
0558     }
0559 #endif
0560 
0561     // previous isect distance for move delta
0562     real_type previous_distance{0};
0563 
0564     // Loop over distances and surface indices to cross by iterating over
0565     // temp_next.isect[:num_isect].
0566     // Evaluate the logic expression at each crossing to determine whether
0567     // we're actually leaving the volume.
0568     for (size_type isect_idx = 0; isect_idx != num_isect; ++isect_idx)
0569     {
0570         // Index into the distance/face arrays
0571         size_type const isect = state.temp_next.isect[isect_idx];
0572         real_type const distance = state.temp_next.distance[isect];
0573 
0574         if (distance >= max_distance)
0575         {
0576             // No intersection within search range; exit early
0577             return {};
0578         }
0579 
0580         // Update face state *before* movement, then position
0581         on_face = [&] {
0582             FaceId face{state.temp_next.face[isect]};
0583 
0584             // Calculate sense from old position
0585             return detail::OnFace{face, flip_sense(calc_sense(face))};
0586         }();
0587         axpy(distance - previous_distance, state.dir, &pos);
0588 
0589         // Intersection is found if is_inside is true and the target sense
0590         // is inside, or vice-versa
0591         if (is_inside(calc_sense) == (target_sense == Sense::inside))
0592         {
0593             // Flipping this sense puts us outside the current volume: in
0594             // other words, only after crossing all the internal surfaces along
0595             // this direction do we hit a surface that actually puts us
0596             // outside.
0597             CELER_ENSURE(distance > 0 && !std::isinf(distance));
0598             // Return the intersecting face and *pre*-crossing sense.
0599             return {
0600                 {vol.get_surface(on_face.id()), flip_sense(on_face.sense())},
0601                 distance};
0602         }
0603         previous_distance = distance;
0604     }
0605 
0606     // No intersection: perhaps leaving an exterior volume? Perhaps geometry
0607     // error.
0608     return {};
0609 }
0610 
0611 //---------------------------------------------------------------------------//
0612 /*!
0613  * Calculate the distance from the background volume to enter any other volume.
0614  *
0615  * This function is accelerated by the BVH, which is given a functor for
0616  * calculating the distance to intersection from *outside* a given volume. That
0617  * operation is implemented by calling complex_intersect, which checks that the
0618  * sense changes after crossing a candidate surface. A volume is "simple" when
0619  * it has no internal surfaces, from which it follows that for a ray
0620  * originating inside a simple volume, crossing the nearest surface is
0621  * guaranteed to change the sense to "outside." When the ray originates outside
0622  * the volume, however, the absence of internal surfaces is not sufficient to
0623  * guarantee a sense change will occur, so the candidate surfaces must still be
0624  * checked. The example below illustrates this: a ray originating at point P
0625  * does not undergo a sense change when it crosses the nearest surface of
0626  * volume V.
0627  * \verbatim
0628               ^          ^
0629        P ->   |          |
0630               |          |
0631        <------|----------|------>
0632               |          |
0633               | interior |
0634               | of V     |
0635               |          |
0636        <------|----------|------>
0637               |          |
0638               |          |
0639               v          v
0640    \endverbatim
0641  * For rays originating outside a volume, the sense-change check can be skipped
0642  * only if the volume is defined by a single closed surface, e.g., a sphere, an
0643  * ellipsoid, or a toroid. Because this function does not make this
0644  * distinction, it uses complex_intersect for all volumes.
0645  */
0646 CELER_FUNCTION auto SimpleUnitTracker::background_intersect(
0647     LocalState const& state, real_type max_distance) const -> Intersection
0648 {
0649     // Functor for calculating the distance to intersection, starting outside
0650     // the given volume.
0651     auto is_intersecting
0652         = [this, &state](LocalVolumeId vol_id,
0653                          real_type cur_max_dist) -> Intersection {
0654         VolumeView vol = this->make_local_volume(vol_id);
0655 
0656         // No volume is "simple" because we are starting from the outside
0657         constexpr bool is_simple = false;
0658         detail::CalcIntersections calc_intersections{
0659             cur_max_dist,
0660             state.pos,
0661             state.dir,
0662             state.surface ? vol.find_face(state.surface.id()) : FaceId{},
0663             is_simple,
0664             state.temp_next};
0665 
0666         LocalSurfaceVisitor visit_surface(params_, unit_record_.surfaces);
0667         for (LocalSurfaceId surface : vol.faces())
0668         {
0669             visit_surface(calc_intersections, surface);
0670         }
0671 
0672         size_type num_isect = calc_intersections.isect_idx();
0673         if (num_isect == 0)
0674         {
0675             // No intersection in this unit
0676             return {};
0677         }
0678 
0679         // Sort valid intersection distances in ascending order
0680         celeritas::sort(state.temp_next.isect,
0681                         state.temp_next.isect + num_isect,
0682                         [&state](size_type a, size_type b) {
0683                             return state.temp_next.distance[a]
0684                                    < state.temp_next.distance[b];
0685                         });
0686 
0687         // Call complex_intersect with a target sense of "inside," because we
0688         // are seeking a surface for which crossing will result in entering the
0689         // volume
0690         return this->complex_intersect(
0691             state, vol, num_isect, Sense::inside, cur_max_dist);
0692     };
0693 
0694     detail::BvhIntersectingVolFinder find_intersection{unit_record_.bvh_tree,
0695                                                        params_.bvh_tree_data};
0696 
0697     return find_intersection(
0698         {state.pos, state.dir}, is_intersecting, max_distance);
0699 }
0700 
0701 //---------------------------------------------------------------------------//
0702 /*!
0703  * Create a surface visitor from the params for this unit.
0704  */
0705 CELER_FORCEINLINE_FUNCTION LocalSurfaceVisitor
0706 SimpleUnitTracker::make_surface_visitor() const
0707 {
0708     return LocalSurfaceVisitor{params_, unit_record_.surfaces};
0709 }
0710 
0711 //---------------------------------------------------------------------------//
0712 /*!
0713  * Create a Volume view object from the params for this unit.
0714  */
0715 CELER_FORCEINLINE_FUNCTION auto SimpleUnitTracker::make_local_volume(
0716     LocalVolumeId vol_id) const -> VolumeView
0717 {
0718     return VolumeView{params_, unit_record_, vol_id};
0719 }
0720 
0721 //---------------------------------------------------------------------------//
0722 /*!
0723  * DaughterId of universe embedded in a given volume.
0724  */
0725 CELER_FUNCTION DaughterId SimpleUnitTracker::daughter(LocalVolumeId vol) const
0726 {
0727     CELER_EXPECT(vol < unit_record_.volumes.size());
0728     return params_.volume_records[unit_record_.volumes[vol]].daughter_id;
0729 }
0730 
0731 //---------------------------------------------------------------------------//
0732 /*!
0733  * Volume level relative to the "top" canonical volume in the universe.
0734  *
0735  * When representing a Geant4 geometry, this will be zero for the top-level
0736  * volume, one if it's a volume instance that's been "inlined" into this
0737  * universe as a volume, two if it's a volume inlined inside that one, etc.
0738  */
0739 CELER_FUNCTION auto SimpleUnitTracker::local_vol_level(LocalVolumeId vol) const
0740     -> vol_level_uint
0741 {
0742     CELER_EXPECT(unit_record_.local_vol_level.empty()
0743                  || vol < unit_record_.volumes.size());
0744     if (unit_record_.local_vol_level.empty())
0745         return 0;
0746 
0747     OpaqueId<vol_level_uint> level_ptr = unit_record_.local_vol_level[vol];
0748     vol_level_uint local_vol_level = params_.vl_uints[level_ptr];
0749     return local_vol_level;
0750 }
0751 
0752 //---------------------------------------------------------------------------//
0753 /*!
0754  * Local volume ID of the parent canonical volume, if any.
0755  *
0756  * This gives the within-universe implementation volume ID of the canonical
0757  * volume that "encloses" (i.e., has a level one less than) the given local
0758  * volume. If the local parent volume is null, then the parent is the placement
0759  * of the current ORANGE universe as a daughter.
0760  */
0761 CELER_FUNCTION LocalVolumeId SimpleUnitTracker::local_parent(
0762     LocalVolumeId vol) const
0763 {
0764     CELER_EXPECT(unit_record_.local_parent.empty()
0765                  || vol < unit_record_.volumes.size());
0766     if (unit_record_.local_parent.empty())
0767         return {};
0768 
0769     OpaqueId<LocalVolumeId> lv_ptr = unit_record_.local_parent[vol];
0770     return params_.local_volume_ids[lv_ptr];
0771 }
0772 
0773 //---------------------------------------------------------------------------//
0774 }  // namespace celeritas