minigeo 0.5.7__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
minigeo/__init__.py ADDED
@@ -0,0 +1,61 @@
1
+ """
2
+ minigeo: describe simple 3D geometry and draw it as SVG, with matplotlib or with plotly.
3
+
4
+ Example:
5
+ >>> from minigeo import Box, Cylinder, Scene
6
+ >>> scene = Scene()
7
+ >>> table = scene.add(Box([0, 0, 0], size=(2, 1, 0.1)), fill="peru")
8
+ >>> scene.add(Cylinder(table.anchor("top"), radius=0.1, height=0.2))
9
+ """
10
+
11
+ from importlib.metadata import PackageNotFoundError, version
12
+
13
+ from .frames import Frame
14
+ from .geometry import (
15
+ Angle,
16
+ Axis,
17
+ Box,
18
+ Circle,
19
+ Cone,
20
+ Cylinder,
21
+ Dimension,
22
+ Line,
23
+ Plane,
24
+ Point,
25
+ Polygon,
26
+ Rectangle,
27
+ Sphere,
28
+ Transform,
29
+ Vector,
30
+ )
31
+ from .groups import Group
32
+ from .scene import Scene
33
+ from .style import Style
34
+
35
+ try:
36
+ __version__ = version(__name__)
37
+ except PackageNotFoundError: # pragma: no cover - package not installed
38
+ __version__ = "unknown"
39
+
40
+ __all__ = [
41
+ "Angle",
42
+ "Axis",
43
+ "Box",
44
+ "Circle",
45
+ "Cone",
46
+ "Cylinder",
47
+ "Dimension",
48
+ "Frame",
49
+ "Group",
50
+ "Line",
51
+ "Plane",
52
+ "Point",
53
+ "Polygon",
54
+ "Rectangle",
55
+ "Scene",
56
+ "Sphere",
57
+ "Style",
58
+ "Transform",
59
+ "Vector",
60
+ "__version__",
61
+ ]
minigeo/anchors.py ADDED
@@ -0,0 +1,123 @@
1
+ """
2
+ Named points on geometries, in the spirit of TikZ.
3
+
4
+ Shapes and groups use words like ``"top front left"``; lines use positions like ``"near end"``.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import numpy as np
10
+
11
+ # Each anchor word picks one side of the shape along one of its local axes.
12
+ ANCHOR_WORDS = {
13
+ "left": (0, -1),
14
+ "right": (0, +1),
15
+ "front": (1, -1),
16
+ "back": (1, +1),
17
+ "bottom": (2, -1),
18
+ "top": (2, +1),
19
+ }
20
+
21
+
22
+ def anchor_direction(anchor: str | np.ndarray) -> np.ndarray:
23
+ """
24
+ Translate an anchor into a position within the shape's local bounding box.
25
+
26
+ The result has one entry per local axis: -1 is the low side, +1 the high side, 0 the middle.
27
+
28
+ Args:
29
+ anchor: Either ``"center"`` or a combination of the words left/right (x'),
30
+ front/back (y'), bottom/top (z') in any order, separated by spaces, ``-`` or ``_``,
31
+ e.g. ``"top"``, ``"top front"``, ``"bottom-back-left"``. Or three numbers, where
32
+ ``(0, 0, 0.5)`` is halfway between the center and the top.
33
+
34
+ Example:
35
+ >>> anchor_direction("top front left")
36
+ array([-1., -1., 1.])
37
+ """
38
+ if not isinstance(anchor, str):
39
+ direction = np.asarray(anchor, dtype=float)
40
+ if direction.shape != (3,):
41
+ raise ValueError(f"A numeric anchor needs three values, got {anchor!r}.")
42
+ return direction
43
+
44
+ words = anchor.lower().replace("-", " ").replace("_", " ").split()
45
+ direction = np.zeros(3)
46
+ if words == ["center"]:
47
+ return direction
48
+
49
+ used_axes = set()
50
+ for word in words:
51
+ if word not in ANCHOR_WORDS:
52
+ raise ValueError(
53
+ f"Unknown anchor word {word!r} in {anchor!r}; use {', '.join(ANCHOR_WORDS)} or 'center'."
54
+ )
55
+ axis, side = ANCHOR_WORDS[word]
56
+ if axis in used_axes:
57
+ raise ValueError(f"Anchor {anchor!r} names the same axis twice.")
58
+ used_axes.add(axis)
59
+ direction[axis] = side
60
+ if not words:
61
+ raise ValueError("Empty anchor name.")
62
+ return direction
63
+
64
+
65
+ def point_in_bounding_box(vertices: np.ndarray, anchor: str | np.ndarray) -> np.ndarray:
66
+ """
67
+ Return the anchor point on the axis-aligned bounding box of ``vertices``.
68
+
69
+ Example:
70
+ >>> point_in_bounding_box(box.local_vertices, "top") # middle of the top face
71
+ """
72
+ low, high = vertices.min(axis=0), vertices.max(axis=0)
73
+ middle, half_size = (low + high) / 2, (high - low) / 2
74
+ return middle + anchor_direction(anchor) * half_size
75
+
76
+
77
+ # TikZ's names for positions along a path, from 0 (start) to 1 (end).
78
+ LINE_POSITIONS = {
79
+ "start": 0.0,
80
+ "very near start": 0.125,
81
+ "near start": 0.25,
82
+ "midway": 0.5,
83
+ "center": 0.5,
84
+ "near end": 0.75,
85
+ "very near end": 0.875,
86
+ "end": 1.0,
87
+ }
88
+
89
+
90
+ def line_position(anchor: str | float) -> float:
91
+ """
92
+ Translate a TikZ position name (e.g. ``"near end"``) or a number into a fraction of the way.
93
+
94
+ Example:
95
+ >>> line_position("near start")
96
+ 0.25
97
+ """
98
+ if not isinstance(anchor, str):
99
+ return float(anchor)
100
+ name = " ".join(anchor.lower().replace("-", " ").replace("_", " ").split())
101
+ if name not in LINE_POSITIONS:
102
+ raise ValueError(f"Unknown line anchor {anchor!r}; use {', '.join(LINE_POSITIONS)} or a number.")
103
+ return LINE_POSITIONS[name]
104
+
105
+
106
+ def point_on_segment(start: np.ndarray, end: np.ndarray, anchor: str | float) -> np.ndarray:
107
+ """Return the point ``anchor`` along the straight segment from ``start`` to ``end``."""
108
+ start, end = np.asarray(start, dtype=float), np.asarray(end, dtype=float)
109
+ return start + line_position(anchor) * (end - start)
110
+
111
+
112
+ def resolve_pivot(about: np.ndarray | str | None, owner) -> np.ndarray | None:
113
+ """
114
+ Turn the ``about`` argument of ``rotate`` into a point.
115
+
116
+ ``None`` stays ``None`` (rotate about the origin), ``"center"`` becomes ``owner.center``,
117
+ and anything else is treated as a point.
118
+ """
119
+ if isinstance(about, str):
120
+ if about != "center":
121
+ raise ValueError(f"Unknown pivot {about!r}; use 'center' or a point.")
122
+ return owner.center
123
+ return about
@@ -0,0 +1,7 @@
1
+ """
2
+ Backends draw a :class:`~minigeo.scene.Scene`.
3
+
4
+ Each backend is a module with a ``render(scene, **options)`` function. It only handles the
5
+ neutral primitives from :mod:`minigeo.render`, and imports its plotting library itself, so
6
+ that the library is only needed when the backend is used.
7
+ """
@@ -0,0 +1,342 @@
1
+ """
2
+ Fast ray casting with numba, for the ray tracer (optional: ``pip install "minigeo[fast]"``).
3
+
4
+ The numpy ray tracer casts many parallel rays at once and tests every surface against the
5
+ rays inside its outline; its cost grows with the number of triangles. Here each ray walks a
6
+ *bounding volume hierarchy* instead: a tree of boxes around groups of surfaces, so it only
7
+ tests the few surfaces near its path. The walk runs as compiled code, for many rays in
8
+ parallel on all processor cores.
9
+
10
+ The results are the same as those of the numpy path (up to rounding), for triangles and for
11
+ exact spheres and cylinders (see :mod:`minigeo.exact`). Rays need not be parallel, so this is
12
+ also the way to perspective cameras and random sampling later.
13
+
14
+ The compiled code is cached on disk, so only the first use on a machine takes a few seconds.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import numpy as np
20
+
21
+ try:
22
+ import numba
23
+ except ImportError: # the extra is not installed
24
+ numba = None
25
+
26
+ #: Surfaces per leaf of the tree.
27
+ LEAF_SIZE = 4
28
+
29
+ #: Rays handled one after another by each parallel task.
30
+ CHUNK = 256
31
+
32
+ TRIANGLE, SPHERE, CYLINDER = 0, 1, 2
33
+
34
+
35
+ def available() -> bool:
36
+ """Whether numba is installed."""
37
+ return numba is not None
38
+
39
+
40
+ class Accelerator:
41
+ """
42
+ A bounding volume hierarchy over triangles and exact shapes, and the kernel that walks it.
43
+
44
+ Args:
45
+ triangles: ``(m, 3, 3)`` corners of the triangles.
46
+ kinds: For each exact shape, ``"sphere"`` or ``"cylinder"``.
47
+ from_world: For each exact shape, its ``(4, 4)`` map from world to unit shape.
48
+ boxes: For each exact shape, the ``(8, 3)`` corners of a box around it.
49
+ """
50
+
51
+ def __init__(
52
+ self, triangles: np.ndarray, kinds: list[str], from_world: list[np.ndarray], boxes: list[np.ndarray]
53
+ ):
54
+ if numba is None:
55
+ raise ImportError('Fast ray casting needs numba: pip install "minigeo[fast]"')
56
+ triangles = np.asarray(triangles, dtype=np.float64).reshape(-1, 3, 3)
57
+ self.v0 = np.ascontiguousarray(triangles[:, 0])
58
+ self.e1 = np.ascontiguousarray(triangles[:, 1] - triangles[:, 0])
59
+ self.e2 = np.ascontiguousarray(triangles[:, 2] - triangles[:, 0])
60
+ self.area = np.linalg.norm(np.cross(self.e1, self.e2), axis=1) # twice the area
61
+ self.inverse = np.ascontiguousarray(np.array(from_world, dtype=np.float64).reshape(-1, 4, 4))
62
+
63
+ m, q = len(triangles), len(kinds)
64
+ self.kind = np.array(
65
+ [TRIANGLE] * m + [SPHERE if k == "sphere" else CYLINDER for k in kinds], dtype=np.int64
66
+ )
67
+ self.ref = np.concatenate([np.arange(m), np.arange(q)]).astype(np.int64)
68
+ low = [triangles.min(axis=1)] if m else []
69
+ high = [triangles.max(axis=1)] if m else []
70
+ if q:
71
+ corners = np.array(boxes, dtype=np.float64)
72
+ low.append(corners.min(axis=1))
73
+ high.append(corners.max(axis=1))
74
+ low = np.concatenate(low) if low else np.zeros((0, 3))
75
+ high = np.concatenate(high) if high else np.zeros((0, 3))
76
+ self.tree = _build_tree(low, high)
77
+
78
+ def cast(
79
+ self, origins: np.ndarray, directions: np.ndarray, start: np.ndarray, stop: np.ndarray | None = None
80
+ ):
81
+ """
82
+ The nearest hit of each ray ``origin + t * direction`` with ``start < t < stop``.
83
+
84
+ ``directions`` is ``(n, 3)``, or ``(3,)`` for parallel rays. ``stop`` (default: no
85
+ limit) lets rays that only look nearby, e.g. for ambient occlusion, skip the rest.
86
+
87
+ Returns:
88
+ (distance, primitive, part): ``distance`` is inf where nothing was hit;
89
+ ``primitive`` indexes triangles first, then exact shapes (-1: nothing);
90
+ ``part`` is 0 for the side of a cylinder or a sphere, 1 for the bottom, 2 for the top.
91
+ """
92
+ origins = np.ascontiguousarray(origins, dtype=np.float64).reshape(-1, 3)
93
+ directions = np.ascontiguousarray(np.atleast_2d(directions), dtype=np.float64)
94
+ start = np.ascontiguousarray(start, dtype=np.float64)
95
+ count = len(origins)
96
+ stop = np.full(count, np.inf) if stop is None else np.ascontiguousarray(stop, dtype=np.float64)
97
+ distance = np.full(count, np.inf)
98
+ primitive = np.full(count, -1, dtype=np.int64)
99
+ part = np.zeros(count, dtype=np.int64)
100
+ if count and len(self.kind):
101
+ low, high, left, right, first, size, axes, order = self.tree
102
+ _walk(origins, directions, start, stop, low, high, left, right, first, size, axes, order,
103
+ self.kind, self.ref, self.v0, self.e1, self.e2, self.area, self.inverse,
104
+ distance, primitive, part) # fmt: skip
105
+ return distance, primitive, part
106
+
107
+
108
+ def _build_tree(low: np.ndarray, high: np.ndarray):
109
+ """
110
+ Build the tree. Each node is split where the *surface area heuristic* expects the fewest
111
+ tests: a ray hits a box with a chance proportional to its surface, so a split is cheap if
112
+ small boxes hold many surfaces. Candidate splits are the borders of 16 bins of the
113
+ surfaces' centers along each axis.
114
+
115
+ Returns arrays per node: box ``low``/``high``, children ``left``/``right`` (-1 for leaves),
116
+ the ``axis`` it is split along, and the leaves' range ``first``/``size`` into ``order``,
117
+ the reordered primitive indices.
118
+ """
119
+ count = len(low)
120
+ centers = (low + high) / 2
121
+ order = np.arange(count, dtype=np.int64)
122
+ nodes_low, nodes_high, left, right, first, size, axes = [], [], [], [], [], [], []
123
+
124
+ def node(begin: int, end: int) -> int:
125
+ index = len(nodes_low)
126
+ members = order[begin:end]
127
+ box_low, box_high = low[members].min(axis=0), high[members].max(axis=0)
128
+ nodes_low.append(box_low)
129
+ nodes_high.append(box_high)
130
+ left.append(-1)
131
+ right.append(-1)
132
+ first.append(begin)
133
+ size.append(end - begin)
134
+ axes.append(0)
135
+ if end - begin > LEAF_SIZE:
136
+ split = _best_split(low[members], high[members], centers[members], _area(box_low, box_high))
137
+ if split is not None:
138
+ axis, below = split
139
+ order[begin:end] = np.concatenate([members[below], members[~below]])
140
+ middle = begin + int(below.sum())
141
+ size[index] = 0 # an inner node
142
+ axes[index] = axis
143
+ left[index] = node(begin, middle)
144
+ right[index] = node(middle, end)
145
+ return index
146
+
147
+ if count:
148
+ node(0, count)
149
+ as_array = lambda values, kind: np.ascontiguousarray(np.array(values, dtype=kind)) # noqa: E731
150
+ return (
151
+ as_array(nodes_low, np.float64).reshape(-1, 3),
152
+ as_array(nodes_high, np.float64).reshape(-1, 3),
153
+ as_array(left, np.int64),
154
+ as_array(right, np.int64),
155
+ as_array(first, np.int64),
156
+ as_array(size, np.int64),
157
+ as_array(axes, np.int64),
158
+ order,
159
+ )
160
+
161
+
162
+ BINS = 16
163
+
164
+
165
+ def _area(low: np.ndarray, high: np.ndarray) -> np.ndarray:
166
+ """Half the surface area of boxes (enough for comparing them)."""
167
+ extent = np.maximum(high - low, 0)
168
+ return extent[..., 0] * extent[..., 1] + extent[..., 1] * extent[..., 2] + extent[..., 2] * extent[..., 0]
169
+
170
+
171
+ def _best_split(low: np.ndarray, high: np.ndarray, centers: np.ndarray, parent_area: float):
172
+ """
173
+ The cheapest split of a node's surfaces as ``(axis, below)``, where ``below`` marks the
174
+ surfaces going to the first child; None if keeping them in one leaf is cheaper.
175
+ """
176
+ count = len(low)
177
+ best_cost, best = float(count), None # cost of a leaf: test every surface
178
+ for axis in range(3):
179
+ lo, hi = centers[:, axis].min(), centers[:, axis].max()
180
+ if hi - lo < 1e-12:
181
+ continue
182
+ bins = np.minimum(((centers[:, axis] - lo) / (hi - lo) * BINS).astype(int), BINS - 1)
183
+ counts = np.bincount(bins, minlength=BINS)
184
+ bin_low = np.full((BINS, 3), np.inf)
185
+ bin_high = np.full((BINS, 3), -np.inf)
186
+ np.minimum.at(bin_low, bins, low)
187
+ np.maximum.at(bin_high, bins, high)
188
+ # boxes and counts of everything below and above each of the BINS - 1 borders
189
+ below_low = np.minimum.accumulate(bin_low, axis=0)[:-1]
190
+ below_high = np.maximum.accumulate(bin_high, axis=0)[:-1]
191
+ above_low = np.minimum.accumulate(bin_low[::-1], axis=0)[::-1][1:]
192
+ above_high = np.maximum.accumulate(bin_high[::-1], axis=0)[::-1][1:]
193
+ below_count = np.cumsum(counts)[:-1]
194
+ above_count = count - below_count
195
+ cost = 0.5 + (
196
+ _area(below_low, below_high) * below_count + _area(above_low, above_high) * above_count
197
+ ) / max(parent_area, 1e-300)
198
+ cost[(below_count == 0) | (above_count == 0)] = np.inf
199
+ border = int(np.argmin(cost))
200
+ if cost[border] < best_cost:
201
+ best_cost, best = float(cost[border]), (axis, bins <= border)
202
+ if best is None and count > 4 * LEAF_SIZE: # e.g. all centers in one point: split in halves anyway
203
+ half = np.zeros(count, dtype=bool)
204
+ half[np.argsort(centers[:, 0], kind="stable")[: count // 2]] = True
205
+ return 0, half
206
+ return best
207
+
208
+
209
+ if numba is not None:
210
+
211
+ @numba.njit(cache=True, inline="always")
212
+ def _hit_box(ox, oy, oz, ix, iy, iz, low, high, near, far):
213
+ """Whether the ray enters the box between ``near`` and ``far`` (slab test)."""
214
+ t0 = (low[0] - ox) * ix
215
+ t1 = (high[0] - ox) * ix
216
+ if t0 > t1:
217
+ t0, t1 = t1, t0
218
+ near = max(near, t0)
219
+ far = min(far, t1)
220
+ t0 = (low[1] - oy) * iy
221
+ t1 = (high[1] - oy) * iy
222
+ if t0 > t1:
223
+ t0, t1 = t1, t0
224
+ near = max(near, t0)
225
+ far = min(far, t1)
226
+ t0 = (low[2] - oz) * iz
227
+ t1 = (high[2] - oz) * iz
228
+ if t0 > t1:
229
+ t0, t1 = t1, t0
230
+ near = max(near, t0)
231
+ far = min(far, t1)
232
+ return near <= far
233
+
234
+ @numba.njit(cache=True, inline="always")
235
+ def _hit_triangle(ox, oy, oz, dx, dy, dz, v0, e1, e2, area, start, best):
236
+ """Distance to a triangle (Möller-Trumbore), or inf; edges count as inside."""
237
+ px = dy * e2[2] - dz * e2[1]
238
+ py = dz * e2[0] - dx * e2[2]
239
+ pz = dx * e2[1] - dy * e2[0]
240
+ det = e1[0] * px + e1[1] * py + e1[2] * pz
241
+ length = np.sqrt(dx * dx + dy * dy + dz * dz)
242
+ if abs(det) <= 1e-12 * area * length:
243
+ return np.inf # seen edge-on
244
+ inverse = 1.0 / det
245
+ sx, sy, sz = ox - v0[0], oy - v0[1], oz - v0[2]
246
+ u = (sx * px + sy * py + sz * pz) * inverse
247
+ if u < -1e-9 or u > 1 + 1e-9:
248
+ return np.inf
249
+ qx = sy * e1[2] - sz * e1[1]
250
+ qy = sz * e1[0] - sx * e1[2]
251
+ qz = sx * e1[1] - sy * e1[0]
252
+ v = (dx * qx + dy * qy + dz * qz) * inverse
253
+ if v < -1e-9 or u + v > 1 + 1e-9:
254
+ return np.inf
255
+ t = (e2[0] * qx + e2[1] * qy + e2[2] * qz) * inverse
256
+ return t if start < t < best else np.inf
257
+
258
+ @numba.njit(cache=True, inline="always")
259
+ def _hit_exact(kind, matrix, ox, oy, oz, dx, dy, dz, start, best):
260
+ """Distance and part of the nearest hit with the unit sphere or cylinder, or (inf, 0)."""
261
+ ux = matrix[0, 0] * ox + matrix[0, 1] * oy + matrix[0, 2] * oz + matrix[0, 3]
262
+ uy = matrix[1, 0] * ox + matrix[1, 1] * oy + matrix[1, 2] * oz + matrix[1, 3]
263
+ uz = matrix[2, 0] * ox + matrix[2, 1] * oy + matrix[2, 2] * oz + matrix[2, 3]
264
+ vx = matrix[0, 0] * dx + matrix[0, 1] * dy + matrix[0, 2] * dz
265
+ vy = matrix[1, 0] * dx + matrix[1, 1] * dy + matrix[1, 2] * dz
266
+ vz = matrix[2, 0] * dx + matrix[2, 1] * dy + matrix[2, 2] * dz
267
+ found, part = np.inf, 0
268
+ if kind == SPHERE:
269
+ a = vx * vx + vy * vy + vz * vz
270
+ b = 2 * (ux * vx + uy * vy + uz * vz)
271
+ c = ux * ux + uy * uy + uz * uz - 1
272
+ discriminant = b * b - 4 * a * c
273
+ if discriminant >= 0:
274
+ root = np.sqrt(discriminant)
275
+ for t in ((-b - root) / (2 * a), (-b + root) / (2 * a)):
276
+ if start < t < best and t < found:
277
+ found = t
278
+ return found, 0
279
+ a = vx * vx + vy * vy
280
+ if a > 1e-15: # the side
281
+ b = 2 * (ux * vx + uy * vy)
282
+ c = ux * ux + uy * uy - 1
283
+ discriminant = b * b - 4 * a * c
284
+ if discriminant >= 0:
285
+ root = np.sqrt(discriminant)
286
+ for t in ((-b - root) / (2 * a), (-b + root) / (2 * a)):
287
+ if start < t < best and t < found and abs(uz + t * vz) <= 0.5:
288
+ found, part = t, 0
289
+ if abs(vz) > 1e-15: # the bottom and the top
290
+ for z, which in ((-0.5, 1), (0.5, 2)):
291
+ t = (z - uz) / vz
292
+ x, y = ux + t * vx, uy + t * vy
293
+ if start < t < best and t < found and x * x + y * y <= 1:
294
+ found, part = t, which
295
+ return found, part
296
+
297
+ @numba.njit(parallel=True, cache=True)
298
+ def _walk(origins, directions, start, stop, low, high, left, right, first, size, axes, order,
299
+ kind, ref, v0, e1, e2, area, inverse, distance, primitive, part): # fmt: skip
300
+ count = origins.shape[0]
301
+ shared = directions.shape[0] == 1
302
+ chunks = (count + CHUNK - 1) // CHUNK
303
+ for chunk in numba.prange(chunks):
304
+ stack = np.empty(128, dtype=np.int64)
305
+ for r in range(chunk * CHUNK, min(count, (chunk + 1) * CHUNK)):
306
+ d = 0 if shared else r
307
+ ox, oy, oz = origins[r, 0], origins[r, 1], origins[r, 2]
308
+ dx, dy, dz = directions[d, 0], directions[d, 1], directions[d, 2]
309
+ ix = 1.0 / dx if dx != 0 else np.inf
310
+ iy = 1.0 / dy if dy != 0 else np.inf
311
+ iz = 1.0 / dz if dz != 0 else np.inf
312
+ tmin = start[r]
313
+ best, hit, which = stop[r], -1, 0
314
+ stack[0] = 0
315
+ depth = 1
316
+ while depth > 0:
317
+ depth -= 1
318
+ node = stack[depth]
319
+ if not _hit_box(ox, oy, oz, ix, iy, iz, low[node], high[node], tmin, best):
320
+ continue
321
+ if size[node] == 0: # visit the nearer child first: push it last
322
+ if directions[d, axes[node]] > 0:
323
+ stack[depth], stack[depth + 1] = right[node], left[node]
324
+ else:
325
+ stack[depth], stack[depth + 1] = left[node], right[node]
326
+ depth += 2
327
+ continue
328
+ for k in range(first[node], first[node] + size[node]):
329
+ p = order[k]
330
+ index = ref[p]
331
+ if kind[p] == TRIANGLE:
332
+ t = _hit_triangle(ox, oy, oz, dx, dy, dz, v0[index], e1[index], e2[index],
333
+ area[index], tmin, best) # fmt: skip
334
+ if t < best:
335
+ best, hit, which = t, p, 0
336
+ else:
337
+ t, piece = _hit_exact(kind[p], inverse[index], ox, oy, oz, dx, dy, dz, tmin, best)
338
+ if t < best:
339
+ best, hit, which = t, p, piece
340
+ distance[r] = best if hit >= 0 else np.inf
341
+ primitive[r] = hit
342
+ part[r] = which