Coverage for trimesh/proximity.py: 85%

205 statements  

« prev     ^ index     » next       coverage.py v7.17.0, created at 2026-11-22 02:08 +0000

1""" 

2proximity.py 

3--------------- 

4 

5Query mesh- point proximity. 

6""" 

7 

8import numpy as np 

9 

10from . import util 

11from .constants import log_time, tol 

12from .grouping import group_min 

13from .triangles import closest_point as _corresponding 

14from .triangles import points_to_barycentric 

15from .typed import ArrayLike 

16from .util import diagonal_dot 

17 

18try: 

19 from scipy.spatial import cKDTree 

20except BaseException as E: 

21 from .exceptions import ExceptionWrapper 

22 

23 cKDTree = ExceptionWrapper(E) 

24 

25# raise a `MemoryError` rather than allocate more than this 

26_MEMORY_LIMIT = 16 * 2**30 

27 

28 

29def nearby_faces(mesh, points: ArrayLike): 

30 """ 

31 For each point find nearby faces relatively quickly. 

32 

33 The closest point on the mesh to the queried point is guaranteed to be 

34 on one of the faces listed. 

35 

36 Does this by finding the nearest vertex on the mesh to each point, and 

37 then returns all the faces that intersect the axis aligned bounding box 

38 centered at the queried point and extending to the nearest vertex. 

39 

40 Parameters 

41 ---------- 

42 mesh : trimesh.Trimesh 

43 Mesh to query. 

44 points : (n, 3) float 

45 Points in space 

46 

47 Returns 

48 ----------- 

49 candidates : (points,) int 

50 Sequence of indexes for mesh.faces 

51 """ 

52 points = np.asanyarray(points, dtype=np.float64) 

53 # empty points lists should get empty candidates 

54 if len(points) == 0: 

55 return [] 

56 

57 # mishapen points should error 

58 if not util.is_shape(points, (-1, 3)): 

59 raise ValueError("points must be (n,3)!") 

60 

61 # an r-tree containing the axis aligned bounding box for every triangle 

62 rtree = mesh.triangles_tree 

63 # a kd-tree containing every vertex of the mesh 

64 kdtree = cKDTree(mesh.vertices[mesh.referenced_vertices]) 

65 

66 # query in chunks of points that can't exceed the limit even if every 

67 # face is a candidate and stop before `closest_point` uses ~400b each 

68 chunk = max(1, _MEMORY_LIMIT // (16 * len(mesh.faces))) 

69 candidates, total = [], 0 

70 for start in range(0, len(points), chunk): 

71 query = points[start : start + chunk] 

72 # the nearest vertex bounds the distance to the surface 

73 distance = kdtree.query(query)[0].reshape((-1, 1)) + tol.merge 

74 try: 

75 # use the batch API added in 1.4.0 and fixed to actually work in 1.4.1 

76 ids, counts = rtree.intersection_v(query - distance, query + distance) 

77 hits = np.array_split(ids, np.cumsum(counts)[:-1]) 

78 except BaseException: 

79 # fall back to a list comprehension 

80 hits = [ 

81 list(rtree.intersection(b)) 

82 for b in np.hstack((query - distance, query + distance)) 

83 ] 

84 total += sum(map(len, hits)) 

85 if total * 400 > _MEMORY_LIMIT: 

86 raise MemoryError(f"{total} candidate faces exceeds `_MEMORY_LIMIT`") 

87 candidates.extend(hits) 

88 return candidates 

89 

90 

91def closest_point_naive(mesh, points): 

92 """ 

93 Given a mesh and a list of points find the closest point 

94 on any triangle. 

95 

96 Does this by constructing a very large intermediate array and 

97 comparing every point to every triangle. 

98 

99 Parameters 

100 ---------- 

101 mesh : Trimesh 

102 Takes mesh to have same interfaces as `closest_point` 

103 points : (m, 3) float 

104 Points in space 

105 

106 Returns 

107 ---------- 

108 closest : (m, 3) float 

109 Closest point on triangles for each point 

110 distance : (m,) float 

111 Distances between point and triangle 

112 triangle_id : (m,) int 

113 Index of triangle containing closest point 

114 """ 

115 # get triangles from mesh 

116 triangles = mesh.triangles.view(np.ndarray) 

117 # establish that input points are sane 

118 points = np.asanyarray(points, dtype=np.float64) 

119 if not util.is_shape(triangles, (-1, 3, 3)): 

120 raise ValueError("triangles shape incorrect") 

121 if not util.is_shape(points, (-1, 3)): 

122 raise ValueError("points must be (n,3)") 

123 

124 # create a giant tiled array of each point tiled len(triangles) times 

125 points_tiled = np.tile(points, (1, len(triangles))) 

126 on_triangle = np.array( 

127 [_corresponding(triangles, i.reshape((-1, 3))) for i in points_tiled] 

128 ) 

129 

130 # distance squared 

131 distance_2 = [((i - q) ** 2).sum(axis=1) for i, q in zip(on_triangle, points)] 

132 

133 triangle_id = np.array([i.argmin() for i in distance_2]) 

134 

135 # closest cartesian point 

136 closest = np.array([g[i] for i, g in zip(triangle_id, on_triangle)]) 

137 distance = np.array([g[i] for i, g in zip(triangle_id, distance_2)]) ** 0.5 

138 

139 return closest, distance, triangle_id 

140 

141 

142def closest_point(mesh, points): 

143 """ 

144 Given a mesh and a list of points find the closest point 

145 on any triangle. 

146 

147 Parameters 

148 ---------- 

149 mesh : trimesh.Trimesh 

150 Mesh to query 

151 points : (m, 3) float 

152 Points in space 

153 

154 Returns 

155 ---------- 

156 closest : (m, 3) float 

157 Closest point on triangles for each point 

158 distance : (m,) float 

159 Distance to mesh. 

160 triangle_id : (m,) int 

161 Index of triangle containing closest point 

162 """ 

163 points = np.asanyarray(points, dtype=np.float64) 

164 if not util.is_shape(points, (-1, 3)): 

165 raise ValueError("points must be (n,3)!") 

166 

167 # do a tree- based query for faces near each point 

168 candidates = nearby_faces(mesh, points) 

169 # view triangles as an ndarray so we don't have to recompute 

170 # the MD5 during all of the subsequent advanced indexing 

171 triangles = mesh.triangles.view(np.ndarray) 

172 

173 # create the corresponding list of triangles 

174 # and query points to send to the closest_point function 

175 all_candidates = np.concatenate(candidates) 

176 

177 num_candidates = list(map(len, candidates)) 

178 tile_idxs = np.repeat(np.arange(len(points)), num_candidates) 

179 query_point = points[tile_idxs, :] 

180 

181 query_tri = triangles[all_candidates] 

182 

183 # do the computation for closest point 

184 query_close = _corresponding(query_tri, query_point) 

185 query_group = np.cumsum(num_candidates)[:-1] 

186 

187 # vectors and distances for 

188 # closest point to query point 

189 query_vector = query_point - query_close 

190 query_distance = util.diagonal_dot(query_vector, query_vector) 

191 

192 # get best two candidate indices by arg-sorting the per-query_distances 

193 qds = np.array_split(query_distance, query_group) 

194 idxs = np.int32([qd.argsort()[:2] if len(qd) > 1 else [0, 0] for qd in qds]) 

195 idxs[1:] += query_group.reshape(-1, 1) 

196 

197 # points, distances and triangle ids for best two candidates 

198 two_points = query_close[idxs] 

199 two_dists = query_distance[idxs] 

200 two_candidates = all_candidates[idxs] 

201 

202 # the first candidate is the best result for unambiguous cases 

203 result_close = query_close[idxs[:, 0]] 

204 result_tid = two_candidates[:, 0] 

205 result_distance = two_dists[:, 0] 

206 

207 # however: same closest point on two different faces 

208 # find the best one and correct triangle ids if necessary 

209 check_distance = np.ptp(two_dists, axis=1) < tol.merge 

210 check_magnitude = np.all(np.abs(two_dists) > tol.merge, axis=1) 

211 

212 # mask results where corrections may be apply 

213 c_mask = np.bitwise_and(check_distance, check_magnitude) 

214 

215 # get two face normals for the candidate points 

216 normals = mesh.face_normals[two_candidates[c_mask]] 

217 # compute normalized surface-point to query-point vectors 

218 vectors = query_vector[idxs[c_mask]] / two_dists[c_mask].reshape(-1, 2, 1) ** 0.5 

219 # compare enclosed angle for both face normals 

220 dots = (normals * vectors).sum(axis=2) 

221 

222 # take the idx with the most positive angle 

223 # allows for selecting the correct candidate triangle id 

224 c_idxs = dots.argmax(axis=1) 

225 

226 # correct triangle ids where necessary 

227 # closest point and distance remain valid 

228 result_tid[c_mask] = two_candidates[c_mask, c_idxs] 

229 result_distance[c_mask] = two_dists[c_mask, c_idxs] 

230 result_close[c_mask] = two_points[c_mask, c_idxs] 

231 

232 # we were comparing the distance squared so 

233 # now take the square root in one vectorized operation 

234 result_distance **= 0.5 

235 

236 return result_close, result_distance, result_tid 

237 

238 

239def signed_distance(mesh, points): 

240 """ 

241 Find the signed distance from a mesh to a list of points. 

242 

243 * Points OUTSIDE the mesh will have NEGATIVE distance 

244 * Points within tol.merge of the surface will have POSITIVE distance 

245 * Points INSIDE the mesh will have POSITIVE distance 

246 

247 Parameters 

248 ----------- 

249 mesh : trimesh.Trimesh 

250 Mesh to query. 

251 points : (n, 3) float 

252 Points in space 

253 

254 Returns 

255 ---------- 

256 signed_distance : (n,) float 

257 Signed distance from point to mesh 

258 """ 

259 # make sure we have a numpy array 

260 points = np.asanyarray(points, dtype=np.float64) 

261 

262 # find the closest point on the mesh to the queried points 

263 closest, distance, triangle_id = closest_point(mesh, points) 

264 

265 # we only care about nonzero distances 

266 nonzero = distance > tol.merge 

267 

268 if not nonzero.any(): 

269 return distance 

270 

271 # For closest points that project directly in to the triangle, compute sign from 

272 # triangle normal Project each point in to the closest triangle plane 

273 nonzero = np.where(nonzero)[0] 

274 normals = mesh.face_normals[triangle_id] 

275 projection = ( 

276 points[nonzero] 

277 - ( 

278 normals[nonzero].T 

279 * diagonal_dot(points[nonzero] - closest[nonzero], normals[nonzero]) 

280 ).T 

281 ) 

282 

283 # Determine if the projection lies within the closest triangle 

284 barycentric = points_to_barycentric(mesh.triangles[triangle_id[nonzero]], projection) 

285 ontriangle = ~( 

286 ((barycentric < -tol.merge) | (barycentric > 1 + tol.merge)).any(axis=1) 

287 ) 

288 

289 # Where projection does lie in the triangle, compare vector to projection to the 

290 # triangle normal to compute sign 

291 sign = np.sign( 

292 diagonal_dot( 

293 normals[nonzero[ontriangle]], 

294 points[nonzero[ontriangle]] - projection[ontriangle], 

295 ) 

296 ) 

297 distance[nonzero[ontriangle]] *= -1.0 * sign 

298 

299 # For all other triangles, resort to raycasting against the entire mesh 

300 inside = mesh.ray.contains_points(points[nonzero[~ontriangle]]) 

301 sign = (inside.astype(int) * 2) - 1.0 

302 

303 # apply sign to previously computed distance 

304 distance[nonzero[~ontriangle]] *= sign 

305 

306 return distance 

307 

308 

309class NearestQueryResult: 

310 """ 

311 Stores the nearest points and attributes for nearest points queries. 

312 """ 

313 

314 def __init__(self): 

315 self.nearest = None 

316 self.distances = None 

317 self.normals = None 

318 self.triangle_indices = None 

319 self.barycentric_coordinates = None 

320 self.interpolated_normals = None 

321 self.vertex_indices = None 

322 

323 def has_normals(self): 

324 return self.normals is not None or self.interpolated_normals is not None 

325 

326 

327class ProximityQuery: 

328 """ 

329 Proximity queries for the current mesh. 

330 """ 

331 

332 def __init__(self, mesh): 

333 self._mesh = mesh 

334 

335 @log_time 

336 def on_surface(self, points): 

337 """ 

338 Given list of points, for each point find the closest point 

339 on any triangle of the mesh. 

340 

341 Parameters 

342 ---------- 

343 points : (m,3) float, points in space 

344 

345 Returns 

346 ---------- 

347 closest : (m, 3) float 

348 Closest point on triangles for each point 

349 distance : (m,) float 

350 Distance to surface 

351 triangle_id : (m,) int 

352 Index of closest triangle for each point. 

353 """ 

354 return closest_point(mesh=self._mesh, points=points) 

355 

356 def vertex(self, points): 

357 """ 

358 Given a set of points, return the closest vertex index to each point 

359 

360 Parameters 

361 ---------- 

362 points : (n, 3) float 

363 Points in space 

364 

365 Returns 

366 ---------- 

367 distance : (n,) float 

368 Distance from source point to vertex. 

369 vertex_id : (n,) int 

370 Index of mesh.vertices for closest vertex. 

371 """ 

372 tree = self._mesh.kdtree 

373 return tree.query(points) 

374 

375 def signed_distance(self, points): 

376 """ 

377 Find the signed distance from a mesh to a list of points. 

378 

379 * Points OUTSIDE the mesh will have NEGATIVE distance 

380 * Points within tol.merge of the surface will have POSITIVE distance 

381 * Points INSIDE the mesh will have POSITIVE distance 

382 

383 Parameters 

384 ----------- 

385 points : (n, 3) float 

386 Points in space 

387 

388 Returns 

389 ---------- 

390 signed_distance : (n,) float 

391 Signed distance from point to mesh. 

392 """ 

393 return signed_distance(self._mesh, points) 

394 

395 

396def longest_ray(mesh, points, directions): 

397 """ 

398 Find the lengths of the longest rays which do not intersect the mesh 

399 cast from a list of points in the provided directions. 

400 

401 Parameters 

402 ----------- 

403 points : (n, 3) float 

404 Points in space. 

405 directions : (n, 3) float 

406 Directions of rays. 

407 

408 Returns 

409 ---------- 

410 signed_distance : (n,) float 

411 Length of rays. 

412 """ 

413 points = np.asanyarray(points, dtype=np.float64) 

414 if not util.is_shape(points, (-1, 3)): 

415 raise ValueError("points must be (n,3)!") 

416 

417 directions = np.asanyarray(directions, dtype=np.float64) 

418 if not util.is_shape(directions, (-1, 3)): 

419 raise ValueError("directions must be (n,3)!") 

420 

421 if len(points) != len(directions): 

422 raise ValueError("number of points must equal number of directions!") 

423 

424 _faces, rays, locations = mesh.ray.intersects_id( 

425 points, directions, return_locations=True, multiple_hits=True 

426 ) 

427 if len(rays) > 0: 

428 distances = np.linalg.norm(locations - points[rays], axis=1) 

429 else: 

430 distances = np.array([]) 

431 

432 # Reject intersections at distance less than tol.planar 

433 rays = rays[distances > tol.planar] 

434 distances = distances[distances > tol.planar] 

435 

436 # Add infinite length for those with no valid intersection 

437 no_intersections = np.setdiff1d(np.arange(len(points)), rays) 

438 rays = np.concatenate((rays, no_intersections)) 

439 distances = np.concatenate((distances, np.repeat(np.inf, len(no_intersections)))) 

440 return group_min(rays, distances) 

441 

442 

443def max_tangent_sphere( 

444 mesh, points, inwards=True, normals=None, threshold=1e-6, max_iter=100 

445): 

446 """ 

447 Find the center and radius of the sphere which is tangent to 

448 the mesh at the given point and at least one more point with no 

449 non-tangential intersections with the mesh. 

450 

451 Masatomo Inui, Nobuyuki Umezu & Ryohei Shimane (2016) 

452 Shrinking sphere: 

453 A parallel algorithm for computing the thickness of 3D objects, 

454 Computer-Aided Design and Applications, 13:2, 199-207, 

455 DOI: 10.1080/16864360.2015.1084186 

456 

457 Parameters 

458 ---------- 

459 points : (n, 3) float 

460 Points in space. 

461 inwards : bool 

462 Whether to have the sphere inside or outside the mesh. 

463 normals : (n, 3) float or None 

464 Normals of the mesh at the given points 

465 if is None computed automatically. 

466 

467 Returns 

468 ---------- 

469 centers : (n,3) float 

470 Centers of spheres 

471 radii : (n,) float 

472 Radii of spheres 

473 """ 

474 points = np.asanyarray(points, dtype=np.float64) 

475 if not util.is_shape(points, (-1, 3)): 

476 raise ValueError("points must be (n,3)!") 

477 

478 if normals is not None: 

479 normals = np.asanyarray(normals, dtype=np.float64) 

480 if not util.is_shape(normals, (-1, 3)): 

481 raise ValueError("normals must be (n,3)!") 

482 

483 if len(points) != len(normals): 

484 raise ValueError("number of points must equal number of normals!") 

485 else: 

486 normals = mesh.face_normals[closest_point(mesh, points)[2]] 

487 

488 if inwards: 

489 normals = -normals 

490 

491 # Find initial tangent spheres 

492 distances = longest_ray(mesh, points, normals) 

493 radii = distances * 0.5 

494 not_converged = np.ones(len(points), dtype=bool) # boolean mask 

495 

496 # If ray is infinite, find the vertex which is furthest from our point 

497 # when projected onto the ray. I.e. find v which maximises 

498 # (v-p).n = v.n - p.n. 

499 # We use a loop rather a vectorised approach to reduce memory cost 

500 # it also seems to run faster. 

501 for i in np.where(np.isinf(distances))[0]: 

502 projections = np.dot(mesh.vertices - points[i], normals[i]) 

503 

504 # If no points lie outside the tangent plane, then the radius is infinite 

505 # otherwise we have a point outside the tangent plane, take the one with maximal 

506 # projection 

507 if projections.max() < tol.planar: 

508 radii[i] = np.inf 

509 not_converged[i] = False 

510 else: 

511 vertex = mesh.vertices[projections.argmax()] 

512 radii[i] = np.dot(vertex - points[i], vertex - points[i]) / ( 

513 2 * np.dot(vertex - points[i], normals[i]) 

514 ) 

515 

516 # Compute centers 

517 centers = points + normals * np.nan_to_num(radii.reshape(-1, 1)) 

518 centers[np.isinf(radii)] = [np.nan, np.nan, np.nan] 

519 

520 # Our iterative process terminates when the difference in sphere 

521 # radius is less than threshold*D 

522 D = np.linalg.norm(mesh.bounds[1] - mesh.bounds[0]) 

523 convergence_threshold = threshold * D 

524 n_iter = 0 

525 while not_converged.sum() > 0 and n_iter < max_iter: 

526 n_iter += 1 

527 n_points, n_dists, _n_faces = mesh.nearest.on_surface(centers[not_converged]) 

528 

529 # If the distance to the nearest point is the same as the distance 

530 # to the start point then we are done. 

531 done = ( 

532 np.abs( 

533 n_dists 

534 - np.linalg.norm(centers[not_converged] - points[not_converged], axis=1) 

535 ) 

536 < tol.planar 

537 ) 

538 not_converged[np.where(not_converged)[0][done]] = False 

539 

540 # Otherwise find the radius and center of the sphere tangent to the mesh 

541 # at the point and the nearest point. 

542 diff = n_points[~done] - points[not_converged] 

543 old_radii = radii[not_converged].copy() 

544 radii[not_converged] = diagonal_dot(diff, diff) / ( 

545 2 * diagonal_dot(diff, normals[not_converged]) 

546 ) 

547 centers[not_converged] = points[not_converged] + normals[not_converged] * radii[ 

548 not_converged 

549 ].reshape(-1, 1) 

550 

551 # If change in radius is less than threshold we have converged 

552 cvged = old_radii - radii[not_converged] < convergence_threshold 

553 not_converged[np.where(not_converged)[0][cvged]] = False 

554 

555 return centers, radii 

556 

557 

558def thickness(mesh, points, exterior=False, normals=None, method="max_sphere"): 

559 """ 

560 Find the thickness of the mesh at the given points. 

561 

562 Parameters 

563 ---------- 

564 points : (n, 3) float 

565 Points in space 

566 exterior : bool 

567 Whether to compute the exterior thickness 

568 (a.k.a. reach) 

569 normals : (n, 3) float 

570 Normals of the mesh at the given points 

571 If is None computed automatically. 

572 method : string 

573 One of 'max_sphere' or 'ray' 

574 

575 Returns 

576 ---------- 

577 thickness : (n,) float 

578 Thickness at given points. 

579 """ 

580 points = np.asanyarray(points, dtype=np.float64) 

581 if not util.is_shape(points, (-1, 3)): 

582 raise ValueError("points must be (n,3)!") 

583 

584 if normals is not None: 

585 normals = np.asanyarray(normals, dtype=np.float64) 

586 if not util.is_shape(normals, (-1, 3)): 

587 raise ValueError("normals must be (n,3)!") 

588 

589 if len(points) != len(normals): 

590 raise ValueError("number of points must equal number of normals!") 

591 else: 

592 normals = mesh.face_normals[closest_point(mesh, points)[2]] 

593 

594 if method == "max_sphere": 

595 _centers, radius = max_tangent_sphere( 

596 mesh=mesh, points=points, inwards=not exterior, normals=normals 

597 ) 

598 thickness = radius * 2 

599 return thickness 

600 

601 elif method == "ray": 

602 if exterior: 

603 return longest_ray(mesh, points, normals) 

604 else: 

605 return longest_ray(mesh, points, -normals) 

606 else: 

607 raise ValueError('Invalid method, use "max_sphere" or "ray"')