Coverage for trimesh/path/exchange/dxf.py: 94%

368 statements  

« prev     ^ index     » next       coverage.py v7.17.0, created at 2026-11-12 17:18 +0000

1from collections import defaultdict 

2 

3import numpy as np 

4 

5from ... import grouping, resources, util 

6from ... import transformations as tf 

7from ...constants import log 

8from ...constants import tol_path as tol 

9from ...util import multi_dict 

10from ..arc import to_threepoint 

11from ..entities import Arc, BSpline, Line, Text 

12 

13# unit codes 

14_DXF_UNITS = { 

15 1: "inches", 

16 2: "feet", 

17 3: "miles", 

18 4: "millimeters", 

19 5: "centimeters", 

20 6: "meters", 

21 7: "kilometers", 

22 8: "microinches", 

23 9: "mils", 

24 10: "yards", 

25 11: "angstroms", 

26 12: "nanometers", 

27 13: "microns", 

28 14: "decimeters", 

29 15: "decameters", 

30 16: "hectometers", 

31 17: "gigameters", 

32 18: "AU", 

33 19: "light years", 

34 20: "parsecs", 

35} 

36# backwards, for reference 

37_UNITS_TO_DXF = {v: k for k, v in _DXF_UNITS.items()} 

38 

39# a string which we will replace spaces with temporarily 

40_SAFESPACE = "|<^>|" 

41 

42# save metadata to a DXF Xrecord starting here 

43# Valid values are 1-369 (except 5 and 105) 

44XRECORD_METADATA = 134 

45# the sentinel string for trimesh metadata 

46# this should be seen at XRECORD_METADATA 

47XRECORD_SENTINEL = "TRIMESH_METADATA:" 

48# the maximum line length before we split lines 

49XRECORD_MAX_LINE = 200 

50# the maximum index of XRECORDS 

51XRECORD_MAX_INDEX = 368 

52 

53 

54def load_dxf(file_obj, **kwargs): 

55 """ 

56 Load a DXF file to a dictionary containing vertices and 

57 entities. 

58 

59 Parameters 

60 ---------- 

61 file_obj: file or file- like object (has object.read method) 

62 

63 Returns 

64 ---------- 

65 result: dict, keys are entities, vertices and metadata 

66 """ 

67 

68 # in a DXF file, lines come in pairs, 

69 # a group code then the next line is the value 

70 # we are removing all whitespace then splitting with the 

71 # splitlines function which uses the universal newline method 

72 raw = file_obj.read() 

73 # if we've been passed bytes 

74 if hasattr(raw, "decode"): 

75 # search for the sentinel string indicating binary DXF 

76 # do it by encoding sentinel to bytes and subset searching 

77 if raw[:22].find(b"AutoCAD Binary DXF") != -1: 

78 # no converter to ASCII DXF available 

79 raise NotImplementedError("Binary DXF is not supported!") 

80 else: 

81 # we've been passed bytes that don't have the 

82 # header for binary DXF so try decoding as UTF-8 

83 raw = raw.decode("utf-8", errors="ignore") 

84 

85 # remove trailing whitespace 

86 raw = str(raw).strip() 

87 # without any spaces and in upper case 

88 cleaned = raw.replace(" ", "").strip().upper() 

89 

90 # blob with spaces and original case 

91 blob_raw = np.array(str.splitlines(raw)).reshape((-1, 2)) 

92 # if this reshape fails, it means the DXF is malformed 

93 blob = np.array(str.splitlines(cleaned)).reshape((-1, 2)) 

94 

95 # get the section which contains the header in the DXF file 

96 endsec = np.nonzero(blob[:, 1] == "ENDSEC")[0] 

97 

98 # store metadata 

99 metadata = {} 

100 

101 # try reading the header, which may be malformed 

102 header_start = np.nonzero(blob[:, 1] == "HEADER")[0] 

103 if len(header_start) > 0: 

104 header_end = endsec[np.searchsorted(endsec, header_start[0])] 

105 header_blob = blob[header_start[0] : header_end] 

106 

107 # store some properties from the DXF header 

108 metadata["DXF_HEADER"] = {} 

109 for key, group in [ 

110 ("$ACADVER", "1"), 

111 ("$DIMSCALE", "40"), 

112 ("$DIMALT", "70"), 

113 ("$DIMALTF", "40"), 

114 ("$DIMUNIT", "70"), 

115 ("$INSUNITS", "70"), 

116 ("$LUNITS", "70"), 

117 ]: 

118 value = get_key(header_blob, key, group) 

119 if value is not None: 

120 metadata["DXF_HEADER"][key] = value 

121 

122 # store unit data pulled from the header of the DXF 

123 # prefer LUNITS over INSUNITS 

124 # I couldn't find a table for LUNITS values but they 

125 # look like they are 0- indexed versions of 

126 # the INSUNITS keys, so for now offset the key value 

127 for offset, key in [(-1, "$LUNITS"), (0, "$INSUNITS")]: 

128 # get the key from the header blob 

129 units = get_key(header_blob, key, "70") 

130 # if it exists add the offset 

131 if units is None: 

132 continue 

133 metadata[key] = units 

134 units += offset 

135 # if the key is in our list of units store it 

136 if units in _DXF_UNITS: 

137 metadata["units"] = _DXF_UNITS[units] 

138 # warn on drawings with no units 

139 if "units" not in metadata: 

140 log.debug("DXF doesn't have units specified!") 

141 

142 # get the section which contains entities in the DXF file 

143 entity_start = np.nonzero(blob[:, 1] == "ENTITIES")[0][0] 

144 entity_end = endsec[np.searchsorted(endsec, entity_start)] 

145 

146 blocks = None 

147 check_entity = blob[entity_start:entity_end][:, 1] 

148 # only load blocks if an entity references them via an INSERT 

149 if "INSERT" in check_entity or "BLOCK" in check_entity: 

150 try: 

151 # which part of the raw file contains blocks 

152 block_start = np.nonzero(blob[:, 1] == "BLOCKS")[0][0] 

153 block_end = endsec[np.searchsorted(endsec, block_start)] 

154 

155 blob_block = blob[block_start:block_end] 

156 blob_block_raw = blob_raw[block_start:block_end] 

157 block_infl = np.nonzero((blob_block == ["0", "BLOCK"]).all(axis=1))[0] 

158 

159 # collect blocks by name 

160 blocks = {} 

161 for index in np.array_split(np.arange(len(blob_block)), block_infl): 

162 try: 

163 v, e, name = convert_entities( 

164 blob_block[index], blob_block_raw[index], return_name=True 

165 ) 

166 if len(e) > 0: 

167 blocks[name] = (v, e) 

168 except BaseException: 

169 pass 

170 except BaseException: 

171 log.error("failed to parse blocks!", exc_info=True) 

172 

173 # actually load referenced entities 

174 vertices, entities = convert_entities( 

175 blob[entity_start:entity_end], blob_raw[entity_start:entity_end], blocks=blocks 

176 ) 

177 

178 # return result as kwargs for trimesh.path.Path2D constructor 

179 result = {"vertices": vertices, "entities": entities, "metadata": metadata} 

180 

181 return result 

182 

183 

184def convert_entities(blob, blob_raw=None, blocks=None, return_name=False): 

185 """ 

186 Convert a chunk of entities into trimesh entities. 

187 

188 Parameters 

189 ------------ 

190 blob : (n, 2) str 

191 Blob of entities uppercased 

192 blob_raw : (n, 2) str 

193 Blob of entities not uppercased 

194 blocks : None or dict 

195 Blocks referenced by INSERT entities 

196 return_name : bool 

197 If True return the first '2' value 

198 

199 Returns 

200 ---------- 

201 """ 

202 

203 if blob_raw is None: 

204 blob_raw = blob 

205 

206 def info(e): 

207 """ 

208 Pull metadata based on group code, and return as a dict. 

209 """ 

210 # which keys should we extract from the entity data 

211 # DXF group code : our metadata key 

212 get = {"8": "layer", "2": "name"} 

213 # replace group codes with names and only 

214 # take info from the entity dict if it is in cand 

215 renamed = {get[k]: util.make_sequence(v)[0] for k, v in e.items() if k in get} 

216 return renamed 

217 

218 def convert_line(e): 

219 """ 

220 Convert DXF LINE entities into trimesh Line entities. 

221 """ 

222 # create a single Line entity 

223 entities.append(Line(points=len(vertices) + np.arange(2), **info(e))) 

224 # add the vertices to our collection 

225 vertices.extend( 

226 np.array([[e["10"], e["20"]], [e["11"], e["21"]]], dtype=np.float64) 

227 ) 

228 

229 def convert_circle(e): 

230 """ 

231 Convert DXF CIRCLE entities into trimesh Circle entities 

232 """ 

233 R = float(e["40"]) 

234 C = np.array([e["10"], e["20"]]).astype(np.float64) 

235 points = to_threepoint(center=C[:2], radius=R) 

236 entities.append( 

237 Arc(points=(len(vertices) + np.arange(3)), closed=True, **info(e)) 

238 ) 

239 vertices.extend(points) 

240 

241 def convert_arc(e): 

242 """ 

243 Convert DXF ARC entities into into trimesh Arc entities. 

244 """ 

245 # the radius of the circle 

246 R = float(e["40"]) 

247 # the center point of the circle 

248 C = np.array([e["10"], e["20"]], dtype=np.float64) 

249 # the start and end angle of the arc, in degrees 

250 # this may depend on an AUNITS header data 

251 A = np.radians(np.array([e["50"], e["51"]], dtype=np.float64)) 

252 # convert center/radius/angle representation 

253 # to three points on the arc representation 

254 points = to_threepoint(center=C[:2], radius=R, angles=A) 

255 # add a single Arc entity 

256 entities.append(Arc(points=len(vertices) + np.arange(3), closed=False, **info(e))) 

257 # add the three vertices 

258 vertices.extend(points) 

259 

260 def convert_polyline(e): 

261 """ 

262 Convert DXF LWPOLYLINE entities into trimesh Line entities. 

263 """ 

264 # load the points in the line 

265 lines = np.column_stack((e["10"], e["20"])).astype(np.float64) 

266 

267 # save entity info so we don't have to recompute 

268 polyinfo = info(e) 

269 

270 # 70 is the closed flag for polylines 

271 # if the closed flag is set make sure to close 

272 is_closed = "70" in e and int(e["70"][0]) & 1 

273 if is_closed: 

274 lines = np.vstack((lines, lines[:1])) 

275 

276 # 42 is the vertex bulge flag for LWPOLYLINE entities 

277 # "bulge" is autocad for "add a stupid arc using flags 

278 # in my otherwise normal polygon", it's like SVG arc 

279 # flags but somehow even more annoying 

280 if "42" in e: 

281 # get the actual bulge float values 

282 bulge = np.array(e["42"], dtype=np.float64) 

283 # what position were vertices stored at 

284 vid = np.nonzero(chunk[:, 0] == "10")[0] 

285 # what position were bulges stored at in the chunk 

286 bid = np.nonzero(chunk[:, 0] == "42")[0] 

287 # filter out endpoint bulge if we're not closed 

288 if not is_closed: 

289 bid_ok = bid < vid.max() 

290 bid = bid[bid_ok] 

291 bulge = bulge[bid_ok] 

292 # which vertex index is bulge value associated with 

293 bulge_idx = np.searchsorted(vid, bid) 

294 # convert stupid bulge to Line/Arc entities 

295 v, e = bulge_to_arcs( 

296 lines=lines, bulge=bulge, bulge_idx=bulge_idx, is_closed=is_closed 

297 ) 

298 for i in e: 

299 # offset added entities by current vertices length 

300 i.points += len(vertices) 

301 vertices.extend(v) 

302 entities.extend(e) 

303 # done with this polyline 

304 return 

305 

306 # we have a normal polyline so just add it 

307 # as single line entity and vertices 

308 entities.append(Line(points=np.arange(len(lines)) + len(vertices), **polyinfo)) 

309 vertices.extend(lines) 

310 

311 def convert_bspline(e): 

312 """ 

313 Convert DXF Spline entities into trimesh BSpline entities. 

314 """ 

315 # in the DXF there are n points and n ordered fields 

316 # with the same group code 

317 

318 points = np.column_stack((e["10"], e["20"])).astype(np.float64) 

319 knots = np.array(e["40"]).astype(np.float64) 

320 

321 # if there are only two points, save it as a line 

322 if len(points) == 2: 

323 # create a single Line entity 

324 entities.append(Line(points=len(vertices) + np.arange(2), **info(e))) 

325 # add the vertices to our collection 

326 vertices.extend(points) 

327 return 

328 

329 # check bit coded flag for closed 

330 # closed = bool(int(e['70'][0]) & 1) 

331 # check euclidean distance to see if closed 

332 closed = np.linalg.norm(points[0] - points[-1]) < tol.merge 

333 

334 # create a BSpline entity 

335 entities.append( 

336 BSpline( 

337 points=np.arange(len(points)) + len(vertices), 

338 knots=knots, 

339 closed=closed, 

340 **info(e), 

341 ) 

342 ) 

343 # add the vertices 

344 vertices.extend(points) 

345 

346 def convert_text(e): 

347 """ 

348 Convert a DXF TEXT entity into a native text entity. 

349 """ 

350 # text with leading and trailing whitespace removed 

351 text = e["1"].strip() 

352 # try getting optional height of text 

353 try: 

354 height = float(e["40"]) 

355 except BaseException: 

356 height = None 

357 try: 

358 # rotation angle converted to radians 

359 angle = np.radians(float(e["50"])) 

360 except BaseException: 

361 # otherwise no rotation 

362 angle = 0.0 

363 # origin point 

364 origin = np.array([e["10"], e["20"]], dtype=np.float64) 

365 # an origin-relative point (so transforms work) 

366 vector = origin + [np.cos(angle), np.sin(angle)] 

367 # try to extract a (horizontal, vertical) text alignment 

368 align = ["center", "center"] 

369 try: 

370 align[0] = ["left", "center", "right"][int(e["72"])] 

371 except BaseException: 

372 pass 

373 # append the entity 

374 entities.append( 

375 Text( 

376 origin=len(vertices), 

377 vector=len(vertices) + 1, 

378 height=height, 

379 text=text, 

380 align=align, 

381 ) 

382 ) 

383 # append the text origin and direction 

384 vertices.append(origin) 

385 vertices.append(vector) 

386 

387 def convert_insert(e): 

388 """ 

389 Convert an INSERT entity, which inserts a named group of 

390 entities (i.e. a "BLOCK") at a specific location. 

391 """ 

392 if blocks is None: 

393 return 

394 

395 # name of block to insert 

396 name = e["2"] 

397 # if we haven't loaded the block skip 

398 if name not in blocks: 

399 return 

400 # angle to rotate the block by 

401 angle = float(e.get("50", 0.0)) 

402 # the insertion point of the block 

403 offset = np.array([e.get("10", 0.0), e.get("20", 0.0)], dtype=np.float64) 

404 # what to scale the block by 

405 scale = np.array([e.get("41", 1.0), e.get("42", 1.0)], dtype=np.float64) 

406 

407 # the current entities and vertices of the referenced block. 

408 cv, ce = blocks[name] 

409 for i in ce: 

410 # copy the referenced entity as it may be included multiple times 

411 entities.append(i.copy()) 

412 # offset its vertices to the current index 

413 entities[-1].points += len(vertices) 

414 # transform the block's vertices based on the entity settings 

415 # DXF rotates counterclockwise, the opposite sign to `planar_matrix` 

416 vertices.extend( 

417 tf.transform_points( 

418 cv, tf.planar_matrix(offset=offset, theta=-np.radians(angle), scale=scale) 

419 ) 

420 ) 

421 

422 # find the start points of entities 

423 # DXF object to trimesh object converters 

424 loaders = { 

425 "LINE": (dict, convert_line), 

426 "LWPOLYLINE": (multi_dict, convert_polyline), 

427 "ARC": (dict, convert_arc), 

428 "CIRCLE": (dict, convert_circle), 

429 "SPLINE": (multi_dict, convert_bspline), 

430 "INSERT": (dict, convert_insert), 

431 "BLOCK": (dict, convert_insert), 

432 } 

433 

434 # store loaded vertices 

435 vertices = [] 

436 # store loaded entities 

437 entities = [] 

438 # an old-style polyline entity strings its data across 

439 # multiple vertex entities like a real asshole 

440 polyline = None 

441 # chunks of entities are divided by group-code-0 

442 inflection = np.nonzero(blob[:, 0] == "0")[0] 

443 

444 unsupported = defaultdict(lambda: 0) 

445 

446 # loop through chunks of entity information 

447 for index in np.array_split(np.arange(len(blob)), inflection): 

448 # if there is only a header continue 

449 if len(index) < 1: 

450 continue 

451 # chunk will be an (n, 2) array of (group code, data) pairs 

452 chunk = blob[index] 

453 # the string representing entity type 

454 entity_type = chunk[0][1] 

455 

456 # if we are referencing a block or insert by name make 

457 # sure the name key is in the original case vs upper-case 

458 if entity_type in ("BLOCK", "INSERT"): 

459 try: 

460 index_name = next(i for i, v in enumerate(chunk) if v[0] == "2") 

461 chunk[index_name][1] = blob_raw[index][index_name][1] 

462 except StopIteration: 

463 pass 

464 

465 # special case old- style polyline entities 

466 if entity_type == "POLYLINE": 

467 polyline = [dict(chunk)] 

468 # if we are collecting vertex entities 

469 elif polyline is not None and entity_type == "VERTEX": 

470 polyline.append(dict(chunk)) 

471 # the end of a polyline 

472 elif polyline is not None and entity_type == "SEQEND": 

473 # pull the geometry information for the entity 

474 lines = np.array([[i["10"], i["20"]] for i in polyline[1:]], dtype=np.float64) 

475 

476 is_closed = False 

477 # check for a closed flag on the polyline 

478 if "70" in polyline[0]: 

479 # flag is bit- coded integer 

480 flag = int(polyline[0]["70"]) 

481 # first bit represents closed 

482 is_closed = bool(flag & 1) 

483 if is_closed: 

484 lines = np.vstack((lines, lines[:1])) 

485 

486 # get the index of each bulged vertices 

487 bulge_idx = np.array( 

488 [i for i, e in enumerate(polyline) if "42" in e], dtype=np.int64 

489 ) 

490 # get the actual bulge value 

491 bulge = np.array( 

492 [float(e["42"]) for i, e in enumerate(polyline) if "42" in e], 

493 dtype=np.float64, 

494 ) 

495 # convert bulge to new entities 

496 cv, ce = bulge_to_arcs( 

497 lines=lines, bulge=bulge, bulge_idx=bulge_idx, is_closed=is_closed 

498 ) 

499 for i in ce: 

500 # offset entities by existing vertices 

501 i.points += len(vertices) 

502 vertices.extend(cv) 

503 entities.extend(ce) 

504 # we no longer have an active polyline 

505 polyline = None 

506 elif entity_type == "TEXT": 

507 # text entities need spaces preserved so take 

508 # group codes from clean representation (0- column) 

509 # and data from the raw representation (1- column) 

510 chunk_raw = blob_raw[index] 

511 # if we didn't use clean group codes we wouldn't 

512 # be able to access them by key as whitespace 

513 # is random and crazy, like: ' 1 ' 

514 chunk_raw[:, 0] = blob[index][:, 0] 

515 try: 

516 convert_text(dict(chunk_raw)) 

517 except BaseException: 

518 log.debug("failed to load text entity!", exc_info=True) 

519 # if the entity contains all relevant data we can 

520 # cleanly load it from inside a single function 

521 elif entity_type in loaders: 

522 # the chunker converts an (n,2) list into a dict 

523 chunker, loader = loaders[entity_type] 

524 # convert data to dict 

525 entity_data = chunker(chunk) 

526 # append data to the lists we're collecting 

527 loader(entity_data) 

528 elif entity_type != "ENTITIES": 

529 unsupported[entity_type] += 1 

530 if len(unsupported) > 0: 

531 log.debug( 

532 "skipping dxf entities: {}".format( 

533 ", ".join(f"{k}: {v}" for k, v in unsupported.items()) 

534 ) 

535 ) 

536 # stack vertices into single array 

537 vertices = util.vstack_empty(vertices).astype(np.float64) 

538 if return_name: 

539 name = blob_raw[blob[:, 0] == "2"][0][1] 

540 return vertices, entities, name 

541 

542 return vertices, entities 

543 

544 

545def export_dxf(path, only_layers=None): 

546 """ 

547 Export a 2D path object to a DXF file. 

548 

549 Parameters 

550 ---------- 

551 path : trimesh.path.path.Path2D 

552 Input geometry to export 

553 only_layers : None or set 

554 If passed only export the layers specified 

555 

556 Returns 

557 ---------- 

558 export : str 

559 Path formatted as a DXF file 

560 """ 

561 # get the template for exporting DXF files 

562 template = resources.get_json("templates/dxf.json") 

563 

564 def format_points(points, as_2D=False, increment=True): 

565 """ 

566 Format points into DXF- style point string. 

567 

568 Parameters 

569 ----------- 

570 points : (n,2) or (n,3) float 

571 Points in space 

572 as_2D : bool 

573 If True only output 2 points per vertex 

574 increment : bool 

575 If True increment group code per point 

576 Example: 

577 [[X0, Y0, Z0], [X1, Y1, Z1]] 

578 Result, new lines replaced with spaces: 

579 True -> 10 X0 20 Y0 30 Z0 11 X1 21 Y1 31 Z1 

580 False -> 10 X0 20 Y0 30 Z0 10 X1 20 Y1 30 Z1 

581 

582 Returns 

583 ----------- 

584 packed : str 

585 Points formatted with group code 

586 """ 

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

588 # get points in 3D 

589 three = util.stack_3D(points) 

590 if increment: 

591 group = np.tile( 

592 np.arange(len(three), dtype=np.int64).reshape((-1, 1)), (1, 3) 

593 ) 

594 else: 

595 group = np.zeros((len(three), 3), dtype=np.int64) 

596 group += [10, 20, 30] 

597 

598 if as_2D: 

599 group = group[:, :2] 

600 three = three[:, :2] 

601 # join into result string 

602 packed = "\n".join( 

603 f"{g:d}\n{v:.12g}" for g, v in zip(group.reshape(-1), three.reshape(-1)) 

604 ) 

605 

606 return packed 

607 

608 def entity_info(entity): 

609 """ 

610 Pull layer, color, and name information about an entity 

611 

612 Parameters 

613 ----------- 

614 entity : entity object 

615 Source entity to pull metadata 

616 

617 Returns 

618 ---------- 

619 subs : dict 

620 Has keys 'COLOR', 'LAYER', 'NAME' 

621 """ 

622 # TODO : convert RGBA entity.color to index 

623 subs = { 

624 "COLOR": 255, # default is ByLayer 

625 "LAYER": 0, 

626 "NAME": str(id(entity))[:16], 

627 } 

628 if hasattr(entity, "layer"): 

629 # make sure layer name is forced into ASCII 

630 subs["LAYER"] = util.to_ascii(entity.layer) 

631 return subs 

632 

633 def convert_line(line, vertices): 

634 """ 

635 Convert an entity to a discrete polyline 

636 

637 Parameters 

638 ------------- 

639 line : entity 

640 Entity which has 'e.discrete' method 

641 vertices : (n, 2) float 

642 Vertices in space 

643 

644 Returns 

645 ----------- 

646 as_dxf : str 

647 Entity exported as a DXF 

648 """ 

649 # get a discrete representation of entity 

650 points = line.discrete(vertices) 

651 # if one or fewer points return nothing 

652 if len(points) <= 1: 

653 return "" 

654 

655 # generate a substitution dictionary for template 

656 subs = entity_info(line) 

657 subs["POINTS"] = format_points(points, as_2D=True, increment=False) 

658 subs["TYPE"] = "LWPOLYLINE" 

659 subs["VCOUNT"] = len(points) 

660 # 1 is closed 

661 # 0 is default (open) 

662 subs["FLAG"] = int(bool(line.closed)) 

663 

664 result = template["line"].format(**subs) 

665 return result 

666 

667 def convert_arc(arc, vertices): 

668 # get the center of arc and include span angles 

669 info = arc.center(vertices, return_angle=True, return_normal=False) 

670 subs = entity_info(arc) 

671 center = info.center 

672 if len(center) == 2: 

673 center = np.append(center, 0.0) 

674 data = "10\n{:.12g}\n20\n{:.12g}\n30\n{:.12g}".format(*center) 

675 data += f"\n40\n{info.radius:.12g}" 

676 

677 if arc.closed: 

678 subs["TYPE"] = "CIRCLE" 

679 else: 

680 subs["TYPE"] = "ARC" 

681 # an arc is the same as a circle, with an added start 

682 # and end angle field 

683 data += "\n100\nAcDbArc" 

684 data += "\n50\n{:.12g}\n51\n{:.12g}".format(*np.degrees(info.angles)) 

685 subs["DATA"] = data 

686 result = template["arc"].format(**subs) 

687 

688 return result 

689 

690 def convert_bspline(spline, vertices): 

691 # points formatted with group code 

692 points = format_points(vertices[spline.points], increment=False) 

693 

694 # (n,) float knots, formatted with group code 

695 knots = ("40\n{:.12g}\n" * len(spline.knots)).format(*spline.knots)[:-1] 

696 

697 # bit coded 

698 flags = {"closed": 1, "periodic": 2, "rational": 4, "planar": 8, "linear": 16} 

699 

700 flag = flags["planar"] 

701 if spline.closed: 

702 flag = flag | flags["closed"] 

703 

704 normal = [0.0, 0.0, 1.0] 

705 n_code = [210, 220, 230] 

706 n_str = "\n".join(f"{i:d}\n{j:.12g}" for i, j in zip(n_code, normal)) 

707 

708 subs = entity_info(spline) 

709 subs.update( 

710 { 

711 "TYPE": "SPLINE", 

712 "POINTS": points, 

713 "KNOTS": knots, 

714 "NORMAL": n_str, 

715 "DEGREE": 3, 

716 "FLAG": flag, 

717 "FCOUNT": 0, 

718 "KCOUNT": len(spline.knots), 

719 "PCOUNT": len(spline.points), 

720 } 

721 ) 

722 # format into string template 

723 result = template["bspline"].format(**subs) 

724 

725 return result 

726 

727 def convert_text(txt, vertices): 

728 """ 

729 Convert a Text entity to DXF string. 

730 """ 

731 # start with layer info 

732 sub = entity_info(txt) 

733 # get the origin point of the text 

734 sub["ORIGIN"] = format_points(vertices[[txt.origin]], increment=False) 

735 # rotation angle in degrees 

736 sub["ANGLE"] = np.degrees(txt.angle(vertices)) 

737 # actual string of text with spaces escaped 

738 # force into ASCII to avoid weird encoding issues 

739 sub["TEXT"] = ( 

740 txt.text.replace(" ", _SAFESPACE) 

741 .encode("ascii", errors="ignore") 

742 .decode("ascii") 

743 ) 

744 # height of text 

745 sub["HEIGHT"] = txt.height 

746 result = template["text"].format(**sub) 

747 return result 

748 

749 def convert_generic(entity, vertices): 

750 """ 

751 For entities we don't know how to handle, return their 

752 discrete form as a polyline 

753 """ 

754 return convert_line(entity, vertices) 

755 

756 # make sure we're not losing a ton of 

757 # precision in the string conversion 

758 np.set_printoptions(precision=12) 

759 # trimesh entity to DXF entity converters 

760 conversions = { 

761 "Line": convert_line, 

762 "Text": convert_text, 

763 "Arc": convert_arc, 

764 "Bezier": convert_generic, 

765 "BSpline": convert_bspline, 

766 } 

767 collected = [] 

768 for e, layer in zip(path.entities, path.layers): 

769 name = type(e).__name__ 

770 # only export specified layers 

771 if only_layers is not None and layer not in only_layers: 

772 continue 

773 if name in conversions: 

774 converted = conversions[name](e, path.vertices).strip() 

775 if len(converted) > 0: 

776 # only save if we converted something 

777 collected.append(converted) 

778 else: 

779 log.debug("Entity type %s not exported!", name) 

780 

781 # join all entities into one string 

782 entities_str = "\n".join(collected) 

783 

784 # add in the extents of the document as explicit XYZ lines 

785 hsub = {f"EXTMIN_{k}": v for k, v in zip("XYZ", np.append(path.bounds[0], 0.0))} 

786 hsub.update({f"EXTMAX_{k}": v for k, v in zip("XYZ", np.append(path.bounds[1], 0.0))}) 

787 # apply a units flag defaulting to `1` 

788 hsub["LUNITS"] = _UNITS_TO_DXF.get(path.units, 1) 

789 # run the format for the header 

790 sections = [template["header"].format(**hsub).strip()] 

791 # do the same for entities 

792 sections.append(template["entities"].format(ENTITIES=entities_str).strip()) 

793 # and the footer 

794 sections.append(template["footer"].strip()) 

795 

796 # filter out empty sections 

797 # random whitespace causes AutoCAD to fail to load 

798 # although Draftsight, LibreCAD, and Inkscape don't care 

799 # what a giant legacy piece of shit 

800 # create the joined string blob 

801 blob = "\n".join(sections).replace(_SAFESPACE, " ") 

802 # run additional self- checks 

803 if tol.strict: 

804 # check that every line pair is (group code, value) 

805 lines = str.splitlines(str(blob)) 

806 # should be even number of lines 

807 assert (len(lines) % 2) == 0 

808 # group codes should all be convertible to int and positive 

809 assert all(int(i) >= 0 for i in lines[::2]) 

810 # make sure we didn't slip any unicode in there 

811 blob.encode("ascii") 

812 

813 return blob 

814 

815 

816def bulge_to_arcs(lines, bulge, bulge_idx, is_closed=False, metadata=None): 

817 """ 

818 Polylines can have "vertex bulge" which means the polyline 

819 has an arc tangent to segments, rather than meeting at a 

820 vertex. 

821 

822 From Autodesk reference: 

823 The bulge is the tangent of one fourth the included 

824 angle for an arc segment, made negative if the arc 

825 goes clockwise from the start point to the endpoint. 

826 A bulge of 0 indicates a straight segment, and a 

827 bulge of 1 is a semicircle. 

828 

829 Parameters 

830 ---------------- 

831 lines : (n, 2) float 

832 Polyline vertices in order 

833 bulge : (m,) float 

834 Vertex bulge value 

835 bulge_idx : (m,) float 

836 Which index of lines is bulge associated with 

837 is_closed : bool 

838 Is segment closed 

839 metadata : None, or dict 

840 Entity metadata to add 

841 

842 Returns 

843 --------------- 

844 vertices : (a, 2) float 

845 New vertices for poly-arc 

846 entities : (b,) entities.Entity 

847 New entities, either line or arc 

848 """ 

849 # make sure lines are 2D array 

850 lines = np.asanyarray(lines, dtype=np.float64) 

851 

852 # make sure inputs are numpy arrays 

853 bulge = np.asanyarray(bulge, dtype=np.float64) 

854 bulge_idx = np.asanyarray(bulge_idx, dtype=np.int64) 

855 

856 # filter out zero- bulged polylines 

857 ok = np.abs(bulge) > 1e-5 

858 bulge = bulge[ok] 

859 bulge_idx = bulge_idx[ok] 

860 

861 # metadata to apply to new entities 

862 if metadata is None: 

863 metadata = {} 

864 

865 # if there's no bulge, just return the input curve 

866 if len(bulge) == 0: 

867 index = np.arange(len(lines)) 

868 # add a single line entity and vertices 

869 entities = [Line(index, **metadata)] 

870 return lines, entities 

871 

872 # use bulge to calculate included angle of the arc 

873 angle = np.arctan(bulge) * 4.0 

874 # the indexes making up a bulged segment 

875 tid = np.column_stack((bulge_idx, bulge_idx - 1)) 

876 # if it's a closed segment modulus to start vertex 

877 if is_closed: 

878 tid %= len(lines) 

879 

880 # the vector connecting the two ends of the arc 

881 vector = lines[tid[:, 0]] - lines[tid[:, 1]] 

882 

883 # the length of the connector segment 

884 length = np.linalg.norm(vector, axis=1) 

885 

886 # perpendicular vectors by crossing vector with Z 

887 perp = np.cross( 

888 np.column_stack((vector, np.zeros(len(vector)))), 

889 np.ones((len(vector), 3)) * [0, 0, 1], 

890 ) 

891 # strip the zero Z 

892 perp = util.unitize(perp[:, :2]) 

893 

894 # midpoint of each line 

895 midpoint = lines[tid].mean(axis=1) 

896 

897 # calculate the signed radius of each arc segment 

898 radius = (length / 2.0) / np.sin(angle / 2.0) 

899 

900 # offset magnitude to point on arc 

901 offset = radius - np.cos(angle / 2) * radius 

902 

903 # convert each arc to three points: 

904 # start, any point on arc, end 

905 three = np.column_stack( 

906 (lines[tid[:, 0]], midpoint + perp * offset.reshape((-1, 1)), lines[tid[:, 1]]) 

907 ).reshape((-1, 3, 2)) 

908 

909 # if we're in strict mode make sure our arcs 

910 # have the same magnitude as the input data 

911 if tol.strict: 

912 from ..arc import arc_center 

913 

914 check_angle = [arc_center(i).span for i in three] 

915 assert np.allclose(np.abs(angle), np.abs(check_angle)) 

916 

917 check_radii = [arc_center(i).radius for i in three] 

918 assert np.allclose(check_radii, np.abs(radius)) 

919 

920 # collect new entities and vertices 

921 entities, vertices = [], [] 

922 # add the entities for each new arc 

923 for arc_points in three: 

924 entities.append(Arc(points=np.arange(3) + len(vertices), **metadata)) 

925 vertices.extend(arc_points) 

926 

927 # if there are unconsumed line 

928 # segments add them to drawing 

929 if (len(lines) - 1) > len(bulge): 

930 # indexes of line segments 

931 existing = util.stack_lines(np.arange(len(lines))) 

932 # remove line segments replaced with arcs 

933 for line_idx in grouping.boolean_rows( 

934 existing, np.sort(tid, axis=1), np.setdiff1d 

935 ): 

936 # add a single line entity and vertices 

937 entities.append(Line(points=np.arange(2) + len(vertices), **metadata)) 

938 vertices.extend(lines[line_idx].copy()) 

939 

940 # make sure vertices are clean numpy array 

941 vertices = np.array(vertices, dtype=np.float64) 

942 

943 return vertices, entities 

944 

945 

946def get_key(blob, field, code): 

947 """ 

948 Given a loaded (n, 2) blob and a field name 

949 get a value by code. 

950 """ 

951 try: 

952 line = blob[np.nonzero(blob[:, 1] == field)[0][0] + 1] 

953 except IndexError: 

954 return None 

955 if line[0] == code: 

956 try: 

957 return int(line[1]) 

958 except ValueError: 

959 return line[1] 

960 else: 

961 return None 

962 

963 

964# store the loaders we have available 

965_dxf_loaders = {"dxf": load_dxf}