-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathshx_decoder.py
More file actions
990 lines (893 loc) · 36.8 KB
/
Copy pathshx_decoder.py
File metadata and controls
990 lines (893 loc) · 36.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
#!/usr/bin/env python3
"""Batch-oriented AutoCAD SHX/SHP stroke font decoder.
This module handles AutoCAD compiled SHX shape/font files, not ESRI .shx
spatial indexes. It favors partial recovery and archival output over exact
round-tripping.
"""
from __future__ import annotations
import html
import json
import math
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Dict, Iterable, List, Optional, Tuple
SPECIAL_NAMES = {
0: "end",
1: "pen_down",
2: "pen_up",
3: "scale_div",
4: "scale_mul",
5: "push",
6: "pop",
7: "subshape",
8: "move",
9: "move_many",
10: "octant_arc",
11: "fraction_arc",
12: "bulge_arc",
13: "bulge_arc_many",
14: "vertical_text",
}
NORMALIZED_CAP_HEIGHT = 21.0
VECTOR_DIRECTIONS = [
(1.0, 0.0),
(1.0, 0.5),
(1.0, 1.0),
(0.5, 1.0),
(0.0, 1.0),
(-0.5, 1.0),
(-1.0, 1.0),
(-1.0, 0.5),
(-1.0, 0.0),
(-1.0, -0.5),
(-1.0, -1.0),
(-0.5, -1.0),
(0.0, -1.0),
(0.5, -1.0),
(1.0, -1.0),
(1.0, -0.5),
]
def u16le(data: bytes, offset: int) -> int:
if offset + 2 > len(data):
raise ValueError("short uint16")
return int.from_bytes(data[offset : offset + 2], "little")
def i8(value: int) -> int:
return value - 256 if value >= 128 else value
def clean_number(value: float) -> float:
if abs(value) < 1e-9:
return 0.0
rounded = round(value, 6)
return int(rounded) if rounded == int(rounded) else rounded
def decode_latin1_name(data: bytes) -> str:
return data.decode("latin1", errors="replace").strip("\x00")
def decode_arc_control_byte(arc_byte: int) -> Tuple[bool, int, int]:
clockwise = bool(arc_byte & 0x80)
value = arc_byte & 0x7F
start_octant = (value >> 4) & 0x07
octants = value & 0x0F
if octants == 0:
octants = 8
return clockwise, start_octant, octants
@dataclass
class ShapeRecord:
code: int
byte_count: int
body: bytes
name: str = ""
opcode_bytes: bytes = b""
parse_errors: List[str] = field(default_factory=list)
raw_commands: List[Dict[str, Any]] = field(default_factory=list)
paths: List[List[Dict[str, Any]]] = field(default_factory=list)
polylines: List[List[List[float]]] = field(default_factory=list)
bbox: Optional[Dict[str, float]] = None
advance_width: Optional[float] = None
curve_count: int = 0
unsupported_opcodes: List[int] = field(default_factory=list)
def split_name_and_opcodes(self) -> None:
if b"\x00" in self.body:
name_bytes, opcodes = self.body.split(b"\x00", 1)
self.name = decode_latin1_name(name_bytes)
self.opcode_bytes = opcodes
else:
self.name = ""
self.opcode_bytes = self.body
def unicode_char(self, likely_font: bool) -> Optional[str]:
if not likely_font:
return None
if 0 <= self.code <= 0x10FFFF:
try:
return chr(self.code)
except ValueError:
return None
return None
@dataclass
class SHXDocument:
source_path: Path
appears_autocad_shx: bool
signature: str
format_kind: str
classification: str
header_info: Dict[str, Any]
records: List[ShapeRecord]
parse_errors: List[str] = field(default_factory=list)
unsupported_format: bool = False
def records_by_code(self) -> Dict[int, ShapeRecord]:
return {record.code: record for record in self.records}
def likely_font(self) -> bool:
return "font" in self.classification
def opcode_types(self) -> List[str]:
seen = set()
for record in self.records:
for command in record.raw_commands:
seen.add(command["op"])
return sorted(seen)
def unsupported_opcodes(self) -> List[int]:
seen = set()
for record in self.records:
seen.update(record.unsupported_opcodes)
return sorted(seen)
def shape_count(self) -> int:
return len(self.records)
def to_json_obj(self) -> Dict[str, Any]:
metrics = compute_font_metrics(self.records, self.likely_font())
likely_font = self.likely_font()
return {
"source_file": self.source_path.name,
"appears_autocad_shx": self.appears_autocad_shx,
"format_kind": self.format_kind,
"classification": self.classification,
"signature": self.signature,
"header_info": self.header_info,
"metrics": metrics,
"scale": metrics["scale"],
"shape_count": self.shape_count(),
"opcode_types": self.opcode_types(),
"unsupported_opcodes": self.unsupported_opcodes(),
"parse_errors": self.parse_errors,
"glyphs": [record_to_json(record, likely_font) for record in self.records],
}
def record_to_json(record: ShapeRecord, likely_font: bool) -> Dict[str, Any]:
char = record.unicode_char(likely_font)
return {
"shape_number": record.code,
"character_code": f"U+{record.code:04X}" if likely_font else None,
"unicode": char,
"name": record.name,
"byte_count": record.byte_count,
"advance_width": record.advance_width,
"raw_opcode_bytes_hex": record.opcode_bytes.hex(" "),
"raw_opcode_sequence": record.raw_commands,
"decoded_stroke_geometry": record.paths,
"polylines": record.polylines,
"bounding_box": record.bbox,
"unsupported_opcodes": sorted(set(record.unsupported_opcodes)),
"parse_errors": record.parse_errors,
}
def compute_font_metrics(records: List[ShapeRecord], likely_font: bool) -> Dict[str, Any]:
boxes = [record.bbox for record in records if record.bbox]
global_bbox = None
if boxes:
global_bbox = {
"min_x": clean_number(min(box["min_x"] for box in boxes)),
"min_y": clean_number(min(box["min_y"] for box in boxes)),
"max_x": clean_number(max(box["max_x"] for box in boxes)),
"max_y": clean_number(max(box["max_y"] for box in boxes)),
}
cap_heights: List[float] = []
if likely_font:
by_code = {record.code: record for record in records}
for code in list(range(ord("A"), ord("Z") + 1)) + list(range(ord("0"), ord("9") + 1)):
bbox = by_code.get(code).bbox if by_code.get(code) else None
if bbox:
cap_heights.append(float(bbox["max_y"] - bbox["min_y"]))
if cap_heights:
cap_heights.sort()
source_cap_height = cap_heights[len(cap_heights) // 2]
elif global_bbox:
source_cap_height = float(global_bbox["max_y"] - global_bbox["min_y"])
else:
source_cap_height = None
normalized_scale = NORMALIZED_CAP_HEIGHT / source_cap_height if source_cap_height else 1.0
return {
"source_cap_height": clean_number(source_cap_height) if source_cap_height else None,
"normalized_cap_height": clean_number(NORMALIZED_CAP_HEIGHT),
"normalized_scale": clean_number(normalized_scale),
"scale": clean_number(normalized_scale),
"scale_basis": "median height of A-Z and 0-9, targeting SIMPLEX cap height",
"global_bbox": global_bbox,
}
class SHXParser:
def __init__(self, path: Path):
self.path = Path(path)
self.data = self.path.read_bytes()
self.errors: List[str] = []
def parse(self) -> SHXDocument:
marker = self.data.find(b"\x1a")
if marker < 0:
return SHXDocument(
self.path,
False,
"",
"unknown",
"not AutoCAD SHX",
{"error": "missing 0x1A signature terminator"},
[],
["missing AutoCAD SHX signature terminator"],
True,
)
signature = self.data[:marker].decode("latin1", errors="replace").strip()
appears = signature.startswith("AutoCAD-86 ")
format_kind = self._format_kind(signature)
records: List[ShapeRecord] = []
header_info: Dict[str, Any] = {"signature_marker_offset": marker}
unsupported_format = False
try:
if format_kind == "unifont":
records, header_info = self._parse_unifont(marker + 1)
elif format_kind == "shapes":
records, header_info = self._parse_shapes(marker + 1)
elif format_kind == "bigfont":
header_info = self._parse_bigfont_header(marker + 1)
unsupported_format = True
self.errors.append("bigfont index/data layout is recognized but not decoded in this pass")
else:
unsupported_format = True
self.errors.append(f"unsupported AutoCAD SHX signature: {signature!r}")
except Exception as exc: # noqa: BLE001 - batch recovery should continue.
unsupported_format = True
self.errors.append(f"fatal parse error: {exc}")
for record in records:
record.split_name_and_opcodes()
classification = classify_document(format_kind, records, unsupported_format)
doc = SHXDocument(
self.path,
appears,
signature,
format_kind,
classification,
header_info,
records,
self.errors,
unsupported_format,
)
self._decode_records(doc)
return doc
def _format_kind(self, signature: str) -> str:
lowered = signature.lower()
if "unifont" in lowered:
return "unifont"
if "bigfont" in lowered:
return "bigfont"
if "shapes" in lowered:
return "shapes"
return "unknown"
def _parse_unifont(self, pos: int) -> Tuple[List[ShapeRecord], Dict[str, Any]]:
declared_count = u16le(self.data, pos)
pos += 2
records: List[ShapeRecord] = []
while pos + 4 <= len(self.data):
code = u16le(self.data, pos)
byte_count = u16le(self.data, pos + 2)
pos += 4
if byte_count < 0 or pos + byte_count > len(self.data):
self.errors.append(f"record {code} exceeds file bounds at offset {pos}")
break
body = self.data[pos : pos + byte_count]
pos += byte_count
records.append(ShapeRecord(code=code, byte_count=byte_count, body=body))
if len(records) != declared_count:
self.errors.append(f"declared {declared_count} records, recovered {len(records)}")
return records, {"declared_record_count": declared_count, "record_layout": "sequential"}
def _parse_shapes(self, pos: int) -> Tuple[List[ShapeRecord], Dict[str, Any]]:
first_shape = u16le(self.data, pos)
last_shape = u16le(self.data, pos + 2)
entry_count = u16le(self.data, pos + 4)
table_start = pos + 6
body_start = table_start + entry_count * 4
records: List[ShapeRecord] = []
if body_start > len(self.data):
self.errors.append("shape index table extends beyond file")
return records, {
"first_shape": first_shape,
"last_shape": last_shape,
"declared_record_count": entry_count,
"record_layout": "indexed",
}
body_pos = body_start
for i in range(entry_count):
entry = table_start + i * 4
code = u16le(self.data, entry)
byte_count = u16le(self.data, entry + 2)
if body_pos + byte_count > len(self.data):
body = self.data[body_pos:]
self.errors.append(f"shape {code} exceeds file bounds at body offset {body_pos}")
records.append(ShapeRecord(code=code, byte_count=byte_count, body=body))
break
body = self.data[body_pos : body_pos + byte_count]
body_pos += byte_count
records.append(ShapeRecord(code=code, byte_count=byte_count, body=body))
return records, {
"first_shape": first_shape,
"last_shape": last_shape,
"declared_record_count": entry_count,
"body_offset": body_start,
"record_layout": "indexed",
}
def _parse_bigfont_header(self, pos: int) -> Dict[str, Any]:
vals = []
for off in range(pos, min(pos + 16, len(self.data)), 2):
if off + 2 <= len(self.data):
vals.append(u16le(self.data, off))
return {
"record_layout": "bigfont-unsupported",
"first_header_words": vals,
"file_size": len(self.data),
}
def _decode_records(self, doc: SHXDocument) -> None:
record_map = doc.records_by_code()
for record in doc.records:
if record.code == 0 and record.name:
continue
if not record.opcode_bytes:
continue
decoder = OpcodeDecoder(record_map, subshape_width=1 if doc.format_kind == "shapes" else 2)
decoder.decode(record, record.opcode_bytes)
class OpcodeDecoder:
def __init__(self, record_map: Dict[int, ShapeRecord], subshape_width: int = 2):
self.record_map = record_map
self.subshape_width = subshape_width
def decode(self, record: ShapeRecord, data: bytes) -> None:
state = GeometryState()
commands = self._execute(data, state, record, depth=0)
record.raw_commands = commands
record.paths = normalize_paths(state.paths)
record.polylines = paths_to_polylines(record.paths)
record.bbox = compute_bbox(record.paths)
record.advance_width = clean_number(state.x) if data else None
record.curve_count = state.curve_count
def _execute(
self,
data: bytes,
state: "GeometryState",
record: ShapeRecord,
depth: int,
) -> List[Dict[str, Any]]:
commands: List[Dict[str, Any]] = []
if depth > 12:
record.parse_errors.append("subshape recursion limit reached")
return commands
i = 0
while i < len(data):
offset = i
op = data[i]
i += 1
if op == 0:
commands.append({"offset": offset, "op": "end"})
break
if op == 1:
state.pen_down = True
commands.append({"offset": offset, "op": "pen_down"})
elif op == 2:
state.pen_down = False
state.current_path = None
commands.append({"offset": offset, "op": "pen_up"})
elif op == 3:
factor, i = read_u8_arg(data, i, record, "scale_div")
if factor:
state.scale /= factor
commands.append({"offset": offset, "op": "scale_div", "factor": factor})
elif op == 4:
factor, i = read_u8_arg(data, i, record, "scale_mul")
if factor:
state.scale *= factor
commands.append({"offset": offset, "op": "scale_mul", "factor": factor})
elif op == 5:
state.stack.append((state.x, state.y))
commands.append({"offset": offset, "op": "push"})
elif op == 6:
if state.stack:
state.x, state.y = state.stack.pop()
state.current_path = None
commands.append({"offset": offset, "op": "pop"})
elif op == 7:
if i + self.subshape_width > len(data):
record.parse_errors.append(f"short subshape at byte {offset}")
break
if self.subshape_width == 1:
code = data[i]
else:
code = u16le(data, i)
i += self.subshape_width
commands.append({"offset": offset, "op": "subshape", "shape_number": code})
sub = self.record_map.get(code)
if sub and sub.opcode_bytes:
parent_pen_down = state.pen_down
state.pen_down = True
state.current_path = None
self._execute(sub.opcode_bytes, state, record, depth + 1)
state.pen_down = parent_pen_down
state.current_path = None
elif op == 8:
if i + 2 > len(data):
record.parse_errors.append(f"short move at byte {offset}")
break
dx, dy = i8(data[i]), i8(data[i + 1])
i += 2
state.move_by(dx, dy)
commands.append({"offset": offset, "op": "move", "dx": dx, "dy": dy})
elif op == 9:
points = []
while i + 2 <= len(data):
dx, dy = i8(data[i]), i8(data[i + 1])
i += 2
points.append([dx, dy])
if dx == 0 and dy == 0:
break
state.move_by(dx, dy)
commands.append({"offset": offset, "op": "move_many", "deltas": points})
elif op == 10:
if i + 2 > len(data):
record.parse_errors.append(f"short octant arc at byte {offset}")
break
radius, arc_byte = data[i], data[i + 1]
i += 2
state.octant_arc(radius, arc_byte)
commands.append({
"offset": offset,
"op": "octant_arc",
"radius": radius,
"arc_byte": i8(arc_byte),
"raw_arc_byte": arc_byte,
})
elif op == 11:
if i + 5 > len(data):
record.parse_errors.append(f"short fraction arc at byte {offset}")
break
start_offset = data[i]
end_offset = data[i + 1]
high_radius = data[i + 2]
radius = data[i + 3]
arc_byte = data[i + 4]
i += 5
full_radius = high_radius * 256 + radius
state.fraction_arc(full_radius, arc_byte, start_offset, end_offset)
commands.append({
"offset": offset,
"op": "fraction_arc",
"radius": full_radius,
"arc_byte": i8(arc_byte),
"raw_arc_byte": arc_byte,
"start_offset": start_offset,
"end_offset": end_offset,
"approximate": True,
})
elif op == 12:
if i + 3 > len(data):
record.parse_errors.append(f"short bulge arc at byte {offset}")
break
dx, dy, bulge = i8(data[i]), i8(data[i + 1]), i8(data[i + 2])
i += 3
state.bulge_arc(dx, dy, bulge)
commands.append({"offset": offset, "op": "bulge_arc", "dx": dx, "dy": dy, "bulge": bulge})
elif op == 13:
arcs = []
while i + 2 <= len(data):
dx, dy = i8(data[i]), i8(data[i + 1])
i += 2
if dx == 0 and dy == 0:
break
if i >= len(data):
record.parse_errors.append(f"short bulge_arc_many bulge at byte {offset}")
break
bulge = i8(data[i])
i += 1
state.bulge_arc(dx, dy, bulge)
arcs.append({"dx": dx, "dy": dy, "bulge": bulge})
commands.append({"offset": offset, "op": "bulge_arc_many", "arcs": arcs})
elif op == 14:
skip_to = skip_one_command(data, i)
commands.append({"offset": offset, "op": "vertical_text", "skipped_bytes": list(data[i:skip_to])})
i = skip_to
else:
length = op >> 4
direction = op & 0x0F
ux, uy = VECTOR_DIRECTIONS[direction]
dx, dy = ux * length, uy * length
state.move_by(dx, dy)
commands.append({
"offset": offset,
"op": "vector",
"byte": op,
"length": length,
"direction": direction,
"dx": clean_number(dx),
"dy": clean_number(dy),
})
return commands
def read_u8_arg(data: bytes, pos: int, record: ShapeRecord, name: str) -> Tuple[int, int]:
if pos >= len(data):
record.parse_errors.append(f"short {name} argument")
return 0, pos
return data[pos], pos + 1
def skip_one_command(data: bytes, pos: int) -> int:
if pos >= len(data):
return pos
op = data[pos]
pos += 1
if op in (3, 4):
return min(len(data), pos + 1)
if op == 7:
return min(len(data), pos + 2)
if op in (8, 10):
return min(len(data), pos + 2)
if op == 9:
while pos + 2 <= len(data):
dx, dy = data[pos], data[pos + 1]
pos += 2
if dx == 0 and dy == 0:
break
return pos
if op == 12:
return min(len(data), pos + 3)
return pos
@dataclass
class GeometryState:
x: float = 0.0
y: float = 0.0
scale: float = 1.0
pen_down: bool = True
stack: List[Tuple[float, float]] = field(default_factory=list)
paths: List[List[Dict[str, Any]]] = field(default_factory=list)
current_path: Optional[List[Dict[str, Any]]] = None
curve_count: int = 0
def ensure_path(self) -> None:
if self.current_path is None:
self.current_path = [{"type": "M", "x": self.x, "y": self.y}]
self.paths.append(self.current_path)
def move_by(self, dx: float, dy: float) -> None:
x = self.x + dx * self.scale
y = self.y + dy * self.scale
if self.pen_down:
self.ensure_path()
self.current_path.append({"type": "L", "x": x, "y": y})
self.x = x
self.y = y
def octant_arc(self, radius: int, arc_byte: int) -> None:
if radius == 0:
return
clockwise, start_octant, octants = decode_arc_control_byte(arc_byte)
direction = -1 if clockwise else 1
r = radius * self.scale
start = math.radians(start_octant * 45)
sweep = math.radians(direction * octants * 45)
cx = self.x - math.cos(start) * r
cy = self.y - math.sin(start) * r
self.arc_from_center(cx, cy, r, r, start, sweep)
def fraction_arc(self, radius: int, arc_byte: int, start_offset: int, end_offset: int) -> None:
if radius == 0:
return
clockwise, start_octant, octants = decode_arc_control_byte(arc_byte)
direction = -1 if clockwise else 1
start_fraction = start_offset / 256.0
end_fraction = end_offset / 256.0
start = math.radians((start_octant + direction * start_fraction) * 45)
sweep_octants = max(0.001, octants - start_fraction + end_fraction)
sweep = math.radians(direction * sweep_octants * 45)
r = radius * self.scale
cx = self.x - math.cos(start) * r
cy = self.y - math.sin(start) * r
self.arc_from_center(cx, cy, r, r, start, sweep)
def bulge_arc(self, dx: int, dy: int, bulge_byte: int) -> None:
if bulge_byte == 0:
self.move_by(dx, dy)
return
x0, y0 = self.x, self.y
x1 = x0 + dx * self.scale
y1 = y0 + dy * self.scale
chord = math.hypot(x1 - x0, y1 - y0)
if chord == 0:
return
bulge = bulge_byte / 127.0
theta = 4 * math.atan(bulge)
radius = chord * (1 + bulge * bulge) / (4 * abs(bulge))
mx, my = (x0 + x1) * 0.5, (y0 + y1) * 0.5
nx, ny = -(y1 - y0) / chord, (x1 - x0) / chord
center_offset = chord * (1 - bulge * bulge) / (4 * bulge)
cx, cy = mx + nx * center_offset, my + ny * center_offset
start = math.atan2(y0 - cy, x0 - cx)
self.arc_from_center(cx, cy, radius, radius, start, theta)
def arc_from_center(self, cx: float, cy: float, rx: float, ry: float, start: float, sweep: float) -> None:
segments = max(1, math.ceil(abs(sweep) / (math.pi / 2)))
delta = sweep / segments
if self.pen_down:
self.ensure_path()
for idx in range(segments):
a0 = start + delta * idx
a1 = a0 + delta
k = 4 / 3 * math.tan((a1 - a0) / 4)
p0x = cx + rx * math.cos(a0)
p0y = cy + ry * math.sin(a0)
p1x = cx + rx * math.cos(a1)
p1y = cy + ry * math.sin(a1)
c1x = p0x - k * rx * math.sin(a0)
c1y = p0y + k * ry * math.cos(a0)
c2x = p1x + k * rx * math.sin(a1)
c2y = p1y - k * ry * math.cos(a1)
if self.pen_down:
self.current_path.append({
"type": "C",
"x1": c1x,
"y1": c1y,
"x2": c2x,
"y2": c2y,
"x": p1x,
"y": p1y,
})
self.curve_count += 1
self.x, self.y = p1x, p1y
def normalize_paths(paths: List[List[Dict[str, Any]]]) -> List[List[Dict[str, Any]]]:
out: List[List[Dict[str, Any]]] = []
for path in paths:
new_path = []
for cmd in path:
new_cmd = {"type": cmd["type"]}
for key, value in cmd.items():
if key != "type":
new_cmd[key] = clean_number(float(value))
new_path.append(new_cmd)
out.append(new_path)
return out
def paths_to_polylines(paths: List[List[Dict[str, Any]]], curve_steps: int = 12) -> List[List[List[float]]]:
polylines: List[List[List[float]]] = []
for path in paths:
current: List[List[float]] = []
last = (0.0, 0.0)
for cmd in path:
if cmd["type"] == "M":
if current:
polylines.append(current)
current = [[cmd["x"], cmd["y"]]]
last = (cmd["x"], cmd["y"])
elif cmd["type"] == "L":
current.append([cmd["x"], cmd["y"]])
last = (cmd["x"], cmd["y"])
elif cmd["type"] == "C":
for step in range(1, curve_steps + 1):
t = step / curve_steps
x, y = cubic_point(last, (cmd["x1"], cmd["y1"]), (cmd["x2"], cmd["y2"]), (cmd["x"], cmd["y"]), t)
current.append([clean_number(x), clean_number(y)])
last = (cmd["x"], cmd["y"])
if current:
polylines.append(current)
return polylines
def cubic_point(p0: Tuple[float, float], p1: Tuple[float, float], p2: Tuple[float, float], p3: Tuple[float, float], t: float) -> Tuple[float, float]:
mt = 1 - t
x = mt**3 * p0[0] + 3 * mt**2 * t * p1[0] + 3 * mt * t**2 * p2[0] + t**3 * p3[0]
y = mt**3 * p0[1] + 3 * mt**2 * t * p1[1] + 3 * mt * t**2 * p2[1] + t**3 * p3[1]
return x, y
def compute_bbox(paths: List[List[Dict[str, Any]]]) -> Optional[Dict[str, float]]:
values: List[Tuple[float, float]] = []
for path in paths:
for cmd in path:
for x_key, y_key in (("x", "y"), ("x1", "y1"), ("x2", "y2")):
if x_key in cmd and y_key in cmd:
values.append((cmd[x_key], cmd[y_key]))
if not values:
return None
xs, ys = zip(*values)
return {
"min_x": clean_number(min(xs)),
"min_y": clean_number(min(ys)),
"max_x": clean_number(max(xs)),
"max_y": clean_number(max(ys)),
}
def classify_document(format_kind: str, records: List[ShapeRecord], unsupported_format: bool) -> str:
if unsupported_format and format_kind == "bigfont":
return "bigfont text/symbol font (layout not decoded)"
if format_kind == "unifont":
return "text font"
if format_kind == "shapes":
codes = {record.code for record in records}
printable = sum(1 for code in codes if 32 <= code <= 126)
if printable >= 60:
return "text font compiled as shape library"
if printable >= 20:
return "symbol font or partial text font"
return "shape library"
return "unknown"
def write_json(doc: SHXDocument, path: Path) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(doc.to_json_obj(), indent=2, ensure_ascii=False), encoding="utf-8")
def write_report(doc: SHXDocument, path: Path) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
lines = [
f"# {doc.source_path.name}",
"",
f"- Appears AutoCAD SHX: `{doc.appears_autocad_shx}`",
f"- Signature: `{doc.signature}`",
f"- Format kind: `{doc.format_kind}`",
f"- Classification: `{doc.classification}`",
f"- Shapes/glyphs found: `{doc.shape_count()}`",
f"- Opcode types: `{', '.join(doc.opcode_types()) or 'none'}`",
f"- Unsupported opcodes: `{', '.join(str(v) for v in doc.unsupported_opcodes()) or 'none'}`",
"",
"## Header",
"",
"```json",
json.dumps(doc.header_info, indent=2, ensure_ascii=False),
"```",
"",
"## Parse Errors",
"",
]
if doc.parse_errors:
lines.extend(f"- {err}" for err in doc.parse_errors)
else:
lines.append("- none")
bad_records = [record for record in doc.records if record.parse_errors or record.unsupported_opcodes]
lines.extend(["", "## Record Warnings", ""])
if bad_records:
for record in bad_records[:200]:
lines.append(
f"- `{record.code}` / `0x{record.code:04X}`: "
f"errors={record.parse_errors or []}; unsupported={sorted(set(record.unsupported_opcodes))}"
)
else:
lines.append("- none")
path.write_text("\n".join(lines) + "\n", encoding="utf-8")
def write_shp(doc: SHXDocument, path: Path) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
lines = [
";;",
f";; Reconstructed SHP-like text from {doc.source_path.name}",
";; This is archival/debug output, not guaranteed AutoCAD-round-trippable.",
";;",
"",
]
for record in doc.records:
name = record.name if record.name else f"shape_{record.code:04X}"
tokens = opcode_bytes_to_shp_tokens(record.opcode_bytes)
lines.append(f"*{record.code:05X},{len(record.opcode_bytes)},{name}")
lines.append(",".join(tokens) if tokens else "0")
lines.append("")
path.write_text("\n".join(lines), encoding="utf-8")
def opcode_bytes_to_shp_tokens(data: bytes) -> List[str]:
tokens: List[str] = []
i = 0
while i < len(data):
op = data[i]
i += 1
if op in SPECIAL_NAMES:
tokens.append(str(op))
if op in (3, 4) and i < len(data):
tokens.append(str(data[i]))
i += 1
elif op == 7 and i + 2 <= len(data):
tokens.append(f"{u16le(data, i):05X}")
i += 2
elif op in (8, 10) and i + 2 <= len(data):
a, b = i8(data[i]), i8(data[i + 1])
i += 2
if op == 10:
tokens.append(f"({a},{data[i - 1]:03X})")
else:
tokens.append(f"({a},{b})")
elif op == 9:
while i + 2 <= len(data):
a, b = i8(data[i]), i8(data[i + 1])
i += 2
tokens.append(f"({a},{b})")
if a == 0 and b == 0:
break
elif op == 12 and i + 3 <= len(data):
a, b, c = i8(data[i]), i8(data[i + 1]), i8(data[i + 2])
i += 3
tokens.append(f"({a},{b},{c})")
elif op == 11 and i + 5 <= len(data):
a, b, c, d, e = data[i], data[i + 1], data[i + 2], data[i + 3], data[i + 4]
i += 5
tokens.append(f"({a},{b},{c},{d},{e:03X})")
elif op == 13:
while i + 2 <= len(data):
a, b = i8(data[i]), i8(data[i + 1])
i += 2
if a == 0 and b == 0:
tokens.append(f"({a},{b})")
break
if i >= len(data):
break
c = i8(data[i])
i += 1
tokens.append(f"({a},{b},{c})")
else:
tokens.append(f"{op:03X}")
return tokens
def write_svg_specimen(doc: SHXDocument, path: Path) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
records = [record for record in doc.records if record.code != 0]
cols = 16
cell_w, cell_h = 88, 106
label_h = 18
rows = max(1, math.ceil(len(records) / cols))
width, height = cols * cell_w, rows * cell_h
boxes = [record.bbox for record in records if record.bbox]
if boxes:
global_bbox = {
"min_x": min(box["min_x"] for box in boxes),
"min_y": min(box["min_y"] for box in boxes),
"max_x": max(box["max_x"] for box in boxes),
"max_y": max(box["max_y"] for box in boxes),
}
else:
global_bbox = {"min_x": 0.0, "min_y": 0.0, "max_x": 1.0, "max_y": 1.0}
global_w = max(1.0, global_bbox["max_x"] - global_bbox["min_x"])
global_h = max(1.0, global_bbox["max_y"] - global_bbox["min_y"])
specimen_scale = min((cell_w - 20) / global_w, (cell_h - label_h - 20) / global_h)
global_cx = global_bbox["min_x"] + global_w / 2
global_cy = global_bbox["min_y"] + global_h / 2
parts = [
f'<svg xmlns="http://www.w3.org/2000/svg" width="{width}" height="{height}" viewBox="0 0 {width} {height}">',
'<rect width="100%" height="100%" fill="#111"/>',
'<style>text{font:10px monospace;fill:#aaa}.box{fill:none;stroke:#333}.glyph{fill:none;stroke:#f4f1e8;stroke-width:1;vector-effect:non-scaling-stroke;stroke-linecap:round;stroke-linejoin:round}.warn{stroke:#8a4;stroke-dasharray:3 3}</style>',
]
for idx, record in enumerate(records):
col, row = idx % cols, idx // cols
x, y = col * cell_w, row * cell_h
parts.append(f'<rect class="box" x="{x + 4}" y="{y + 4}" width="{cell_w - 8}" height="{cell_h - 8}"/>')
label = f"{record.code:04X}"
if doc.likely_font() and 32 <= record.code <= 0x10FFFF:
ch = chr(record.code)
if ch.isprintable() and not ch.isspace():
label += f" {ch}"
parts.append(f'<text x="{x + 8}" y="{y + label_h}">{html.escape(label)}</text>')
if record.paths:
d = svg_path_data(record.paths)
tx = x + cell_w / 2 - global_cx * specimen_scale
ty = y + label_h + (cell_h - label_h) / 2 + global_cy * specimen_scale
parts.append(
f'<path class="glyph" transform="translate({tx:.3f} {ty:.3f}) '
f'scale({specimen_scale:.3f} {-specimen_scale:.3f})" d="{d}"/>'
)
else:
cls = "box warn" if record.parse_errors or record.unsupported_opcodes else "box"
parts.append(f'<rect class="{cls}" x="{x + 24}" y="{y + 34}" width="{cell_w - 48}" height="{cell_h - 58}"/>')
parts.append("</svg>")
path.write_text("\n".join(parts), encoding="utf-8")
def svg_path_data(paths: List[List[Dict[str, Any]]]) -> str:
chunks: List[str] = []
for path in paths:
for cmd in path:
if cmd["type"] == "M":
chunks.append(f'M {cmd["x"]} {cmd["y"]}')
elif cmd["type"] == "L":
chunks.append(f'L {cmd["x"]} {cmd["y"]}')
elif cmd["type"] == "C":
chunks.append(f'C {cmd["x1"]} {cmd["y1"]} {cmd["x2"]} {cmd["y2"]} {cmd["x"]} {cmd["y"]}')
return " ".join(chunks)
def decode_file(path: Path) -> SHXDocument:
return SHXParser(path).parse()
def write_all_outputs(doc: SHXDocument, output_dir: Path) -> None:
stem = doc.source_path.stem
write_report(doc, output_dir / "reports" / f"{stem}.report.md")
write_json(doc, output_dir / "json" / f"{stem}.json")
write_svg_specimen(doc, output_dir / "svg" / f"{stem}_specimen.svg")
write_shp(doc, output_dir / "shp" / f"{stem}_reconstructed.shp")
def batch_decode(input_dir: Path, output_dir: Path) -> List[SHXDocument]:
paths = sorted(
p for p in Path(input_dir).iterdir()
if p.is_file() and p.suffix.lower() == ".shx"
)
docs: List[SHXDocument] = []
log_lines = []
for path in paths:
doc = decode_file(path)
write_all_outputs(doc, output_dir)
docs.append(doc)
log_lines.append(
f"{path.name}: autocad={doc.appears_autocad_shx} kind={doc.format_kind} "
f"class={doc.classification} shapes={doc.shape_count()} errors={len(doc.parse_errors)}"
)
log_path = output_dir / "logs" / "batch_log.txt"
log_path.parent.mkdir(parents=True, exist_ok=True)
log_path.write_text("\n".join(log_lines) + ("\n" if log_lines else ""), encoding="utf-8")
return docs