Coverage for trimesh/path/entities.py: 90%

241 statements  

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

1""" 

2entities.py 

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

4 

5Basic geometric primitives which only store references to 

6vertex indices rather than vertices themselves. 

7""" 

8 

9from copy import deepcopy 

10from logging import getLogger 

11 

12import numpy as np 

13 

14from .. import util 

15from ..typed import Hashable 

16from ..util import ABC 

17from .arc import arc_center, discretize_arc 

18from .curve import discretize_bezier, discretize_bspline 

19 

20log = getLogger(__name__) 

21 

22 

23class Entity(ABC): 

24 def __init__( 

25 self, points, closed=None, layer=None, metadata=None, color=None, **kwargs 

26 ): 

27 # points always reference vertex indices and are int 

28 self.points = np.asanyarray(points, dtype=np.int64) 

29 # save explicit closed 

30 if closed is not None: 

31 self.closed = closed 

32 # save the passed layer 

33 if layer is not None: 

34 self.layer = layer 

35 if metadata is not None: 

36 self.metadata.update(metadata) 

37 

38 self._cache = {} 

39 

40 # save the passed color 

41 self.color = color 

42 # save any other kwargs for general use 

43 self.kwargs = kwargs 

44 

45 @property 

46 def metadata(self): 

47 """ 

48 Get any metadata about the entity. 

49 

50 Returns 

51 --------- 

52 metadata : dict 

53 Bag of properties. 

54 """ 

55 if not hasattr(self, "_metadata"): 

56 self._metadata = {} 

57 # note that we don't let a new dict be assigned 

58 return self._metadata 

59 

60 @property 

61 def layer(self) -> Hashable: 

62 """ 

63 Get the layer the entity resides on as a shortcut 

64 to putting it in the entity metadata. 

65 

66 Returns 

67 ---------- 

68 layer : Hashable 

69 Layer identifier, None if unset. 

70 """ 

71 return self.metadata.get("layer") 

72 

73 @layer.setter 

74 def layer(self, value: Hashable): 

75 """ 

76 Set the current layer of the entity. 

77 

78 Parameters 

79 ---------- 

80 value : Hashable 

81 Layer identifier 

82 """ 

83 self.metadata["layer"] = value 

84 

85 def to_dict(self) -> dict: 

86 """ 

87 Returns a dictionary with all of the information 

88 about the entity. 

89 

90 Returns 

91 ----------- 

92 as_dict : dict 

93 Has keys 'type', 'points', 'closed' 

94 """ 

95 return { 

96 "type": self.__class__.__name__, 

97 "points": self.points.tolist(), 

98 "closed": self.closed, 

99 } 

100 

101 @property 

102 def closed(self): 

103 """ 

104 If the first point is the same as the end point 

105 the entity is closed 

106 

107 Returns 

108 ----------- 

109 closed : bool 

110 Is the entity closed or not? 

111 """ 

112 return len(self.points) > 2 and self.points[0] == self.points[-1] 

113 

114 @property 

115 def nodes(self): 

116 """ 

117 Returns an (n,2) list of nodes, or vertices on the path. 

118 Note that this generic class function assumes that all of the 

119 reference points are on the path which is true for lines and 

120 three point arcs. 

121 

122 If you were to define another class where that wasn't the case 

123 (for example, the control points of a bezier curve), 

124 you would need to implement an entity- specific version of this 

125 function. 

126 

127 The purpose of having a list of nodes is so that they can then be 

128 added as edges to a graph so we can use functions to check 

129 connectivity, extract paths, etc. 

130 

131 The slicing on this function is essentially just tiling points 

132 so the first and last vertices aren't repeated. Example: 

133 

134 self.points = [0,1,2] 

135 returns: [[0,1], [1,2]] 

136 """ 

137 return ( 

138 np.column_stack((self.points, self.points)).reshape(-1)[1:-1].reshape((-1, 2)) 

139 ) 

140 

141 @property 

142 def end_points(self): 

143 """ 

144 Returns the first and last points. Also note that if you 

145 define a new entity class where the first and last vertices 

146 in self.points aren't the endpoints of the curve you need to 

147 implement this function for your class. 

148 

149 Returns 

150 ------------- 

151 ends : (2,) int 

152 Indices of the two end points of the entity 

153 """ 

154 return self.points[[0, -1]] 

155 

156 @property 

157 def is_valid(self): 

158 """ 

159 Is the current entity valid. 

160 

161 Returns 

162 ----------- 

163 valid : bool 

164 Is the current entity well formed 

165 """ 

166 return True 

167 

168 def reverse(self, direction=-1): 

169 """ 

170 Reverse the current entity in place. 

171 

172 Parameters 

173 ---------------- 

174 direction : int 

175 If positive will not touch direction 

176 If negative will reverse self.points 

177 """ 

178 if direction < 0: 

179 self._direction = -1 

180 else: 

181 self._direction = 1 

182 

183 def _orient(self, curve): 

184 """ 

185 Reverse a curve if a flag is set. 

186 

187 Parameters 

188 -------------- 

189 curve : (n, dimension) float 

190 Curve made up of line segments in space 

191 

192 Returns 

193 ------------ 

194 orient : (n, dimension) float 

195 Original curve, but possibly reversed 

196 """ 

197 if hasattr(self, "_direction") and self._direction < 0: 

198 return curve[::-1] 

199 return curve 

200 

201 def bounds(self, vertices): 

202 """ 

203 Return the AABB of the current entity. 

204 

205 Parameters 

206 ----------- 

207 vertices : (n, dimension) float 

208 Vertices in space 

209 

210 Returns 

211 ----------- 

212 bounds : (2, dimension) float 

213 Coordinates of AABB, in (min, max) form 

214 """ 

215 bounds = np.array( 

216 [vertices[self.points].min(axis=0), vertices[self.points].max(axis=0)] 

217 ) 

218 return bounds 

219 

220 def length(self, vertices): 

221 """ 

222 Return the total length of the entity. 

223 

224 Parameters 

225 -------------- 

226 vertices : (n, dimension) float 

227 Vertices in space 

228 

229 Returns 

230 --------- 

231 length : float 

232 Total length of entity 

233 """ 

234 diff = np.diff(self.discrete(vertices), axis=0) ** 2 

235 length = (np.dot(diff, [1] * vertices.shape[1]) ** 0.5).sum() 

236 return length 

237 

238 def explode(self): 

239 """ 

240 Split the entity into multiple entities. 

241 

242 Returns 

243 ------------ 

244 explode : list of Entity 

245 Current entity split into multiple entities. 

246 """ 

247 return [self.copy()] 

248 

249 def copy(self): 

250 """ 

251 Return a copy of the current entity. 

252 

253 Returns 

254 ------------ 

255 copied : Entity 

256 Copy of current entity 

257 """ 

258 copied = deepcopy(self) 

259 # only copy metadata if set 

260 if hasattr(self, "_metadata"): 

261 copied._metadata = deepcopy(self._metadata) 

262 # check for very annoying subtle copy failures 

263 assert id(copied._metadata) != id(self._metadata) 

264 assert id(copied.points) != id(self.points) 

265 return copied 

266 

267 def __hash__(self): 

268 """ 

269 Return a hash that represents the current entity. 

270 

271 Returns 

272 ---------- 

273 hashed : int 

274 Hash of current class name, points, and closed 

275 """ 

276 return hash(self._bytes()) 

277 

278 def _bytes(self): 

279 """ 

280 Get hashable bytes that define the current entity. 

281 

282 Returns 

283 ------------ 

284 data : bytes 

285 Hashable data defining the current entity 

286 """ 

287 # give consistent ordering of points for hash 

288 if self.points[0] > self.points[-1]: 

289 return self.__class__.__name__.encode("utf-8") + self.points.tobytes() 

290 else: 

291 return self.__class__.__name__.encode("utf-8") + self.points[::-1].tobytes() 

292 

293 

294class Text(Entity): 

295 """ 

296 Text to annotate a 2D or 3D path. 

297 """ 

298 

299 def __init__( 

300 self, 

301 origin, 

302 text, 

303 height=None, 

304 vector=None, 

305 normal=None, 

306 align=None, 

307 layer=None, 

308 color=None, 

309 metadata=None, 

310 ): 

311 """ 

312 An entity for text labels. 

313 

314 Parameters 

315 -------------- 

316 origin : int 

317 Index of a single vertex for text origin 

318 text : str 

319 The text to label 

320 height : float or None 

321 The height of text 

322 vector : int or None 

323 An vertex index for which direction text 

324 is written along unitized: vector - origin 

325 normal : int or None 

326 A vertex index for the plane normal: 

327 vector is along unitized: normal - origin 

328 align : (2,) str or None 

329 Where to draw from for [horizontal, vertical]: 

330 'center', 'left', 'right' 

331 """ 

332 # where is text placed 

333 self.origin = origin 

334 # what direction is the text pointing 

335 self.vector = vector 

336 # what is the normal of the text plane 

337 self.normal = normal 

338 # how high is the text entity 

339 self.height = height 

340 # what layer is the entity on 

341 if layer is not None: 

342 self.layer = layer 

343 

344 if metadata is not None: 

345 self.metadata.update(metadata) 

346 

347 # what color is the entity 

348 self.color = color 

349 

350 # None or (2,) str 

351 if align is None: 

352 # if not set make everything centered 

353 align = ["center", "center"] 

354 elif isinstance(align, str): 

355 # if only one is passed set for both 

356 # horizontal and vertical 

357 align = [align, align] 

358 elif len(align) != 2: 

359 # otherwise raise rror 

360 raise ValueError("align must be (2,) str") 

361 

362 self.align = align 

363 

364 # make sure text is a string 

365 if hasattr(text, "decode"): 

366 self.text = text.decode("utf-8") 

367 else: 

368 self.text = str(text) 

369 

370 @property 

371 def origin(self): 

372 """ 

373 The origin point of the text. 

374 

375 Returns 

376 ----------- 

377 origin : int 

378 Index of vertices 

379 """ 

380 return self.points[0] 

381 

382 @origin.setter 

383 def origin(self, value): 

384 value = int(value) 

385 if not hasattr(self, "points") or np.ptp(self.points) == 0: 

386 self.points = np.ones(3, dtype=np.int64) * value 

387 else: 

388 self.points[0] = value 

389 

390 @property 

391 def vector(self): 

392 """ 

393 A point representing the text direction 

394 along the vector: vertices[vector] - vertices[origin] 

395 

396 Returns 

397 ---------- 

398 vector : int 

399 Index of vertex 

400 """ 

401 return self.points[1] 

402 

403 @vector.setter 

404 def vector(self, value): 

405 if value is None: 

406 return 

407 self.points[1] = int(value) 

408 

409 @property 

410 def normal(self): 

411 """ 

412 A point representing the plane normal along the 

413 vector: vertices[normal] - vertices[origin] 

414 

415 Returns 

416 ------------ 

417 normal : int 

418 Index of vertex 

419 """ 

420 return self.points[2] 

421 

422 @normal.setter 

423 def normal(self, value): 

424 if value is None: 

425 return 

426 self.points[2] = int(value) 

427 

428 def plot(self, vertices, show=False): 

429 """ 

430 Plot the text using matplotlib. 

431 

432 Parameters 

433 -------------- 

434 vertices : (n, 2) float 

435 Vertices in space 

436 show : bool 

437 If True, call plt.show() 

438 """ 

439 if vertices.shape[1] != 2: 

440 raise ValueError("only for 2D points!") 

441 

442 import matplotlib.pyplot as plt # noqa 

443 

444 # get rotation angle in degrees 

445 angle = np.degrees(self.angle(vertices)) 

446 

447 # TODO: handle text size better 

448 plt.text( 

449 *vertices[self.origin], 

450 s=self.text, 

451 rotation=angle, 

452 ha=self.align[0], 

453 va=self.align[1], 

454 size=18, 

455 ) 

456 

457 if show: 

458 plt.show() 

459 

460 def angle(self, vertices): 

461 """ 

462 If Text is 2D, get the rotation angle in radians. 

463 

464 Parameters 

465 ----------- 

466 vertices : (n, 2) float 

467 Vertices in space referenced by self.points 

468 

469 Returns 

470 --------- 

471 angle : float 

472 Rotation angle in radians 

473 """ 

474 

475 if vertices.shape[1] != 2: 

476 raise ValueError("angle only valid for 2D points!") 

477 

478 # get the vector from origin 

479 direction = vertices[self.vector] - vertices[self.origin] 

480 # get the rotation angle in radians 

481 angle = np.arctan2(*direction[::-1]) 

482 

483 return angle 

484 

485 def length(self, vertices): 

486 return 0.0 

487 

488 def discrete(self, *args, **kwargs): 

489 return np.array([]) 

490 

491 @property 

492 def closed(self): 

493 return False 

494 

495 @property 

496 def is_valid(self): 

497 return True 

498 

499 @property 

500 def nodes(self): 

501 return np.array([]) 

502 

503 @property 

504 def end_points(self): 

505 return np.array([]) 

506 

507 def _bytes(self): 

508 data = b"".join([b"Text", self.points.tobytes(), self.text.encode("utf-8")]) 

509 return data 

510 

511 

512class Line(Entity): 

513 """ 

514 A line or poly-line entity 

515 """ 

516 

517 def discrete(self, vertices, scale=1.0): 

518 """ 

519 Discretize into a world- space path. 

520 

521 Parameters 

522 ------------ 

523 vertices: (n, dimension) float 

524 Points in space 

525 scale : float 

526 Size of overall scene for numerical comparisons 

527 

528 Returns 

529 ------------- 

530 discrete: (m, dimension) float 

531 Path in space composed of line segments 

532 """ 

533 return self._orient(vertices[self.points]) 

534 

535 @property 

536 def closed(self): 

537 return len(self.points) > 2 and self.points[0] == self.points[-1] 

538 

539 @closed.setter 

540 def closed(self, value: bool): 

541 current = self.points[0] == self.points[-1] 

542 if value and not current: 

543 # case where we've been asked to close the line 

544 # this seems pretty obvious that we should just append the first pointOB 

545 self.points = np.concatenate((self.points, [self.points[0]])) 

546 elif not value and current: 

547 # case where we've been asked to *disconnect* a closed path 

548 log.debug("ignoring `Line.closed = False`") 

549 

550 @property 

551 def is_valid(self): 

552 """ 

553 Is the current entity valid. 

554 

555 Returns 

556 ----------- 

557 valid : bool 

558 Is the current entity well formed 

559 """ 

560 valid = np.any((self.points - self.points[0]) != 0) 

561 return valid 

562 

563 def explode(self): 

564 """ 

565 If the current Line entity consists of multiple line 

566 break it up into n Line entities. 

567 

568 Returns 

569 ---------- 

570 exploded: (n,) Line entities 

571 """ 

572 # copy over the current layer 

573 layer = self.layer 

574 points = ( 

575 np.column_stack((self.points, self.points)).ravel()[1:-1].reshape((-1, 2)) 

576 ) 

577 exploded = [Line(i, layer=layer) for i in points] 

578 return exploded 

579 

580 def _bytes(self): 

581 # give consistent ordering of points for hash 

582 if self.points[0] > self.points[-1]: 

583 return b"Line" + self.points.tobytes() 

584 else: 

585 return b"Line" + self.points[::-1].tobytes() 

586 

587 def to_dict(self) -> dict: 

588 """ 

589 Returns a dictionary with all of the information 

590 about the Line. `closed` is not additional information 

591 for a Line like it is for Arc where the value determines 

592 if it is a partial or complete circle. Rather it is a check 

593 which indicates the first and last points are identical, 

594 and thus should not be included in the export 

595 

596 Returns 

597 ----------- 

598 as_dict 

599 Has keys 'type', 'points' 

600 """ 

601 return { 

602 "type": self.__class__.__name__, 

603 "points": self.points.tolist(), 

604 } 

605 

606 

607class Arc(Entity): 

608 @property 

609 def closed(self): 

610 """ 

611 A boolean flag for whether the arc is closed (a circle) or not. 

612 

613 Returns 

614 ---------- 

615 closed : bool 

616 If set True, Arc will be a closed circle 

617 """ 

618 return getattr(self, "_closed", False) 

619 

620 @closed.setter 

621 def closed(self, value): 

622 """ 

623 Set the Arc to be closed or not, without 

624 changing the control points 

625 

626 Parameters 

627 ------------ 

628 value : bool 

629 Should this Arc be a closed circle or not 

630 """ 

631 self._closed = bool(value) 

632 

633 @property 

634 def is_valid(self): 

635 """ 

636 Is the current Arc entity valid. 

637 

638 Returns 

639 ----------- 

640 valid : bool 

641 Does the current Arc have exactly 3 control points 

642 """ 

643 return len(np.unique(self.points)) == 3 

644 

645 def _bytes(self): 

646 # give consistent ordering of points for hash 

647 order = int(self.points[0] > self.points[-1]) * 2 - 1 

648 return b"Arc" + bytes(self.closed) + self.points[::order].tobytes() 

649 

650 def length(self, vertices): 

651 """ 

652 Return the arc length of the 3-point arc. 

653 

654 Parameter 

655 ---------- 

656 vertices : (n, d) float 

657 Vertices for overall drawing. 

658 

659 Returns 

660 ----------- 

661 length : float 

662 Length of arc. 

663 """ 

664 # find the actual radius and angle span 

665 if self.closed: 

666 # we don't need the angular span as 

667 # it's indicated as a closed circle 

668 fit = self.center(vertices, return_normal=False, return_angle=False) 

669 return np.pi * fit.radius * 2 

670 # get the angular span of the circular arc 

671 fit = self.center(vertices, return_normal=False, return_angle=True) 

672 return fit.span * fit.radius 

673 

674 def discrete(self, vertices, scale=1.0): 

675 """ 

676 Discretize the arc entity into line sections. 

677 

678 Parameters 

679 ------------ 

680 vertices : (n, dimension) float 

681 Points in space 

682 scale : float 

683 Size of overall scene for numerical comparisons 

684 

685 Returns 

686 ------------- 

687 discrete : (m, dimension) float 

688 Path in space made up of line segments 

689 """ 

690 

691 return self._orient( 

692 discretize_arc(vertices[self.points], close=self.closed, scale=scale) 

693 ) 

694 

695 def center(self, vertices, **kwargs): 

696 """ 

697 Return the center information about the arc entity. 

698 

699 Parameters 

700 ------------- 

701 vertices : (n, dimension) float 

702 Vertices in space 

703 

704 Returns 

705 ------------- 

706 info : dict 

707 With keys: 'radius', 'center' 

708 """ 

709 return arc_center(vertices[self.points], **kwargs) 

710 

711 def bounds(self, vertices): 

712 """ 

713 Return the AABB of the arc entity. 

714 

715 Parameters 

716 ----------- 

717 vertices: (n, dimension) float 

718 Vertices in space 

719 

720 Returns 

721 ----------- 

722 bounds : (2, dimension) float 

723 Coordinates of AABB in (min, max) form 

724 """ 

725 if util.is_shape(vertices, (-1, 2)) and self.closed: 

726 # if we have a closed arc (a circle), we can return the actual bounds 

727 # this only works in two dimensions, otherwise this would return the 

728 # AABB of an sphere 

729 info = self.center(vertices, return_normal=False, return_angle=False) 

730 bounds = np.array( 

731 [info.center - info.radius, info.center + info.radius], dtype=np.float64 

732 ) 

733 else: 

734 # since the AABB of a partial arc is hard, approximate 

735 # the bounds by just looking at the discrete values 

736 discrete = self.discrete(vertices) 

737 bounds = np.array( 

738 [discrete.min(axis=0), discrete.max(axis=0)], dtype=np.float64 

739 ) 

740 return bounds 

741 

742 

743class Curve(Entity): 

744 """ 

745 The parent class for all wild curves in space. 

746 """ 

747 

748 @property 

749 def nodes(self): 

750 # a point midway through the curve 

751 mid = self.points[len(self.points) // 2] 

752 return [[self.points[0], mid], [mid, self.points[-1]]] 

753 

754 

755class Bezier(Curve): 

756 """ 

757 An open or closed Bezier curve 

758 """ 

759 

760 def discrete(self, vertices, scale=1.0, count=None): 

761 """ 

762 Discretize the Bezier curve. 

763 

764 Parameters 

765 ------------- 

766 vertices : (n, 2) or (n, 3) float 

767 Points in space 

768 scale : float 

769 Scale of overall drawings (for precision) 

770 count : int 

771 Number of segments to return 

772 

773 Returns 

774 ------------- 

775 discrete : (m, 2) or (m, 3) float 

776 Curve as line segments 

777 """ 

778 return self._orient( 

779 discretize_bezier(vertices[self.points], count=count, scale=scale) 

780 ) 

781 

782 

783class BSpline(Curve): 

784 """ 

785 An open or closed B- Spline. 

786 """ 

787 

788 def __init__(self, points, knots, layer=None, metadata=None, color=None, **kwargs): 

789 self.points = np.asanyarray(points, dtype=np.int64) 

790 self.knots = np.asanyarray(knots, dtype=np.float64) 

791 if layer is not None: 

792 self.layer = layer 

793 if metadata is not None: 

794 self.metadata.update(metadata) 

795 self._cache = {} 

796 self.kwargs = kwargs 

797 self.color = color 

798 

799 def discrete(self, vertices, count=None, scale=1.0): 

800 """ 

801 Discretize the B-Spline curve. 

802 

803 Parameters 

804 ------------- 

805 vertices : (n, 2) or (n, 3) float 

806 Points in space 

807 scale : float 

808 Scale of overall drawings (for precision) 

809 count : int 

810 Number of segments to return 

811 

812 Returns 

813 ------------- 

814 discrete : (m, 2) or (m, 3) float 

815 Curve as line segments 

816 """ 

817 discrete = discretize_bspline( 

818 control=vertices[self.points], knots=self.knots, count=count, scale=scale 

819 ) 

820 return self._orient(discrete) 

821 

822 def _bytes(self): 

823 # give consistent ordering of points for hash 

824 if self.points[0] > self.points[-1]: 

825 return b"BSpline" + self.knots.tobytes() + self.points.tobytes() 

826 else: 

827 return b"BSpline" + self.knots[::-1].tobytes() + self.points[::-1].tobytes() 

828 

829 def to_dict(self) -> dict: 

830 """ 

831 Returns a dictionary with all of the information 

832 about the entity. 

833 """ 

834 return { 

835 "type": self.__class__.__name__, 

836 "points": self.points.tolist(), 

837 "knots": self.knots.tolist(), 

838 "closed": self.closed, 

839 }