Repository navigation
Expand file tree
/
Copy pathSDF File Editor V0.1.py
More file actions
1195 lines (992 loc) · 49.8 KB
/
Copy pathSDF File Editor V0.1.py
File metadata and controls
1195 lines (992 loc) · 49.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
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# sdf_viewer_final.py
# Working Suspension File Editor
from __future__ import annotations
import struct, json
from dataclasses import dataclass
from pathlib import Path
import tkinter as tk
from tkinter import ttk, filedialog, messagebox, scrolledtext
try:
import ctypes
ctypes.windll.shcore.SetProcessDpiAwareness(1)
except Exception:
pass
# ==================== ENCODING RULES ====================
ENCODING_RULES = {
bytes([0x03, 0x02]): (('b', 'b', 'f'), "Byte, Byte, Float"),
bytes([0x23, 0x00]): (('f', 'b', 'b'), "Float, Byte, Byte"),
bytes([0x23, 0x02]): (('f', 'b', 'f'), "Float, Byte, Float"),
bytes([0x83, 0x00]): (('b', 'f', 'b'), "Byte, Float, Byte"),
bytes([0x83, 0x02]): (('b', 'f', 'f'), "Byte, Float, Float"),
bytes([0xA3, 0x00]): (('f', 'f', 'b'), "Float, Float, Byte"),
bytes([0xA3, 0x02]): (('f', 'f', 'f'), "Float, Float, Float"),
bytes([0x05, 0x00]): (('b', 'b', 'b', 'b', 'b'), "Byte×5"),
bytes([0xA5, 0x2A]): (('f', 'f', 'f', 'f', 'f'), "Float×5"),
bytes([0xA3, 0x01]): (('f', 'f', 'i'), "Float, Float, Integer"),
bytes([0x03, 0x00]): (('b', 'b', 'b'), "Byte×3"),
bytes([0x53, 0x02]): (('i', 'i', 'f'), "Integer, Integer, Float"),
bytes([0x82, 0x05]): (('f',), "Float×1"),
bytes([0x13, 0x00]): (('i', 'b', 'b'), "Integer, Byte, Byte"),
bytes([0x13, 0x02]): (('i', 'b', 'f'), "Integer, Byte, Float"),
bytes([0x93, 0x02]): (('i', 'f', 'f'), "Integer, Float, Float"),
bytes([0xaf, 0xa2]): (('f', 'f'), "Float×2"),
bytes([0xaf, 0x52]): (('i', 'i'), "Integer×2"),
bytes([0x53, 0x00]): (('f', 'i', 'b'), "Float, Integer, Byte"),
bytes([0x02]): (('b', 'b'), "Byte×2"),
bytes([0x21]): (('f',), "Float×1"),
bytes([0xA2]): (('f', 'f'), "Float×2"),
}
# ==================== KNOWN SIGNATURES ====================
SIG_BODY_MASS = bytes.fromhex("67 0B 57 AB 01")
SIG_GEN_MASS = bytes.fromhex("67 0B 57 AB 21")
SIG_INERT = bytes.fromhex("BB B3 9F 0B")
SIG_POS = bytes.fromhex("42 44 42 09 FE EA")
SIG_ORI = bytes.fromhex("AA B5 DB 49")
# Suspension signatures
SIG_JOINT_HINGE = bytes.fromhex("A2 13 89 7D 23 00")
SIG_BAR_POS = bytes.fromhex("42 09 FE EA A3 02")
SIG_BAR_NEG = bytes.fromhex("5A 44 C7 E0 A3 02")
MAX_LOOKAHEAD = 16384
@dataclass
class Field:
name: str
at: int
fmt: tuple[str, ...]
values: tuple[int|float, ...]
encoding_suffix: bytes = None
def clone(self):
return Field(self.name, self.at, self.fmt, self.values, self.encoding_suffix)
@dataclass
class Element:
index: int
kind: str
start: int
end: int
fields: list[Field]
display_name: str
auto_name: str = ""
identifier: bytes = None # For suspension elements
def clone(self):
return Element(self.index, self.kind, self.start, self.end,
[f.clone() for f in self.fields], self.display_name, self.auto_name, self.identifier)
# ==================== AUTO-NAMING RULES ====================
def auto_name_element(e: Element) -> str:
mass = e.fields[0].values[0] if e.fields else 0
inertia = e.fields[1].values if len(e.fields) > 1 else (0, 0, 0)
position = e.fields[2].values if len(e.fields) > 2 else (0, 0, 0)
mass_enc = e.fields[0].encoding_suffix if e.fields else None
inert_enc = e.fields[1].encoding_suffix if len(e.fields) > 1 else None
pos_enc = e.fields[2].encoding_suffix if len(e.fields) > 2 else None
if e.kind == "BODY" and mass == 0:
if inert_enc == bytes([0x03, 0x00]) and pos_enc == bytes([0x03, 0x00]):
return "body?"
if e.kind == "BODY" and mass > 0 and mass < 10:
if inert_enc == bytes([0xA3, 0x02]):
return "unknown_body?"
if e.kind == "GENERIC" and mass == 1:
if inert_enc == bytes([0x03, 0x00]) and pos_enc == bytes([0x03, 0x00]):
return "fuel_tank_or_driver_head?"
if e.kind == "GENERIC" and 20 <= mass <= 25:
if pos_enc == bytes([0xA3, 0x02]):
x, y, z = position
if z < 0:
if mass < 23:
return "fl_spindle?" if x > 0 else "fr_spindle?"
else:
return "fl_wheel?" if x > 0 else "fr_wheel?"
else:
if mass < 23:
return "rl_spindle?" if x > 0 else "rr_spindle?"
else:
return "rl_wheel?" if x > 0 else "rr_wheel?"
if e.kind == "GENERIC" and mass == 22:
if pos_enc == bytes([0xA3, 0x02]):
x, y, z = position
ix, iy, iz = inertia
if max(inertia) > 1.0:
return "rl_wheel?" if x > 0 else "rr_wheel?"
else:
return "rl_spindle?" if x > 0 else "rr_spindle?"
return f"unknown_{e.index+1:02d}?"
# ==================== LOW-LEVEL HELPERS ====================
def read_values(data: bytes, pos: int, fmt: tuple[str, ...]):
vals = []
cur = pos
for f in fmt:
if f == 'f':
if cur + 4 > len(data): return None
vals.append(struct.unpack_from('<f', data, cur)[0]); cur += 4
elif f == 'i':
if cur + 4 > len(data): return None
vals.append(struct.unpack_from('<i', data, cur)[0]); cur += 4
elif f == 'b':
if cur + 1 > len(data): return None
vals.append(data[cur]); cur += 1
else:
return None
return (tuple(vals), cur)
def find_after(data: bytes, sig: bytes, start: int, max_la: int) -> int:
end = min(len(data), start + max_la)
return data.find(sig, start, end)
def detect_encoding_at(data: bytes, pos: int) -> tuple[bytes, tuple[str, ...], str] | None:
for suffix_len in [2, 1]:
if pos + suffix_len > len(data):
continue
suffix = data[pos:pos + suffix_len]
if suffix in ENCODING_RULES:
fmt_types, desc = ENCODING_RULES[suffix]
return (suffix, fmt_types, desc)
return None
def find_with_encoding(data: bytes, sig_prefix: bytes, start: int, max_la: int) -> tuple | None:
sig_pos = find_after(data, sig_prefix, start, max_la)
if sig_pos < 0:
return None
encoding_pos = sig_pos + len(sig_prefix)
encoding = detect_encoding_at(data, encoding_pos)
if encoding:
suffix, fmt, desc = encoding
return (sig_pos, suffix, fmt, desc)
return None
# ==================== PARSERS ====================
def parse_body_at(data: bytes, i: int) -> Element | None:
if data[i:i+len(SIG_BODY_MASS)] != SIG_BODY_MASS:
return None
p = i + len(SIG_BODY_MASS)
r = read_values(data, p, ('b',))
if not r: return None
mass_vals, p = r
mass_field = Field("mass", i + len(SIG_BODY_MASS), ('b',), mass_vals, bytes([0x01]))
found = find_with_encoding(data, SIG_INERT, p, MAX_LOOKAHEAD)
if not found: return None
pos_inert, suffix_inert, fmt_inert, desc_inert = found
r = read_values(data, pos_inert + len(SIG_INERT) + len(suffix_inert), fmt_inert)
if not r: return None
inert_vals, after_inert = r
inert_field = Field(f"inertia", pos_inert + len(SIG_INERT) + len(suffix_inert),
fmt_inert, inert_vals, suffix_inert)
found = find_with_encoding(data, SIG_POS, after_inert, MAX_LOOKAHEAD)
if not found: return None
pos_pos, suffix_pos, fmt_pos, desc_pos = found
r = read_values(data, pos_pos + len(SIG_POS) + len(suffix_pos), fmt_pos)
if not r: return None
pos_vals, after_pos = r
pos_field = Field(f"position", pos_pos + len(SIG_POS) + len(suffix_pos),
fmt_pos, pos_vals, suffix_pos)
found = find_with_encoding(data, SIG_ORI, after_pos, MAX_LOOKAHEAD)
if not found: return None
pos_ori, suffix_ori, fmt_ori, desc_ori = found
r = read_values(data, pos_ori + len(SIG_ORI) + len(suffix_ori), fmt_ori)
if not r: return None
ori_vals, after_ori = r
ori_field = Field(f"orientation", pos_ori + len(SIG_ORI) + len(suffix_ori),
fmt_ori, ori_vals, suffix_ori)
fields = [mass_field, inert_field, pos_field, ori_field]
return Element(index=-1, kind="BODY", start=i, end=after_ori, fields=fields, display_name="body")
def parse_generic_at(data: bytes, i: int) -> Element | None:
if data[i:i+len(SIG_GEN_MASS)] != SIG_GEN_MASS:
return None
r = read_values(data, i + len(SIG_GEN_MASS), ('f',))
if not r: return None
mass_vals, after_mass = r
mass_field = Field("mass", i + len(SIG_GEN_MASS), ('f',), mass_vals, bytes([0x21]))
found = find_with_encoding(data, SIG_INERT, after_mass, MAX_LOOKAHEAD)
if not found: return None
pos_inert, suffix_inert, fmt_inert, desc_inert = found
r = read_values(data, pos_inert + len(SIG_INERT) + len(suffix_inert), fmt_inert)
if not r: return None
inert_vals, after_inert = r
inert_field = Field(f"inertia", pos_inert + len(SIG_INERT) + len(suffix_inert),
fmt_inert, inert_vals, suffix_inert)
found = find_with_encoding(data, SIG_POS, after_inert, MAX_LOOKAHEAD)
if not found: return None
pos_pos, suffix_pos, fmt_pos, desc_pos = found
r = read_values(data, pos_pos + len(SIG_POS) + len(suffix_pos), fmt_pos)
if not r: return None
pos_vals, after_pos = r
pos_field = Field(f"position", pos_pos + len(SIG_POS) + len(suffix_pos),
fmt_pos, pos_vals, suffix_pos)
found = find_with_encoding(data, SIG_ORI, after_pos, MAX_LOOKAHEAD)
if not found: return None
pos_ori, suffix_ori, fmt_ori, desc_ori = found
r = read_values(data, pos_ori + len(SIG_ORI) + len(suffix_ori), fmt_ori)
if not r: return None
ori_vals, after_ori = r
ori_field = Field(f"orientation", pos_ori + len(SIG_ORI) + len(suffix_ori),
fmt_ori, ori_vals, suffix_ori)
fields = [mass_field, inert_field, pos_field, ori_field]
return Element(index=-1, kind="GENERIC", start=i, end=after_ori, fields=fields, display_name="")
# NEW: Suspension parsers
def parse_joint_hinge_at(data: bytes, i: int) -> Element | None:
if i < 1: return None
if data[i:i+len(SIG_JOINT_HINGE)] != SIG_JOINT_HINGE: return None
identifier_byte = data[i-1:i]
full_identifier = identifier_byte + SIG_JOINT_HINGE
pos = i + len(SIG_JOINT_HINGE)
r = read_values(data, pos, ('f', 'b', 'b'))
if not r: return None
axis_vals, end_pos = r
fields = [Field("axis", pos, ('f', 'b', 'b'), axis_vals, bytes([0x23, 0x00]))]
return Element(-1, "JOINT&HINGE", i-1, end_pos, fields, "joint_hinge", "", full_identifier)
def parse_bar_at(data: bytes, i: int) -> Element | None:
# BAR has a 2-byte identifier BEFORE the position signature
# Format: [ID1 ID2] [42 09 FE EA A3 02] [pos values...] [5A 44 C7 E0 A3 02] [neg values...]
if i < 2: return None
if data[i:i+len(SIG_BAR_POS)] != SIG_BAR_POS: return None
# Capture 2-byte identifier before the signature
identifier_prefix = data[i-2:i]
full_identifier = identifier_prefix + SIG_BAR_POS
pos = i + len(SIG_BAR_POS)
r = read_values(data, pos, ('f', 'f', 'f'))
if not r: return None
pos_vals, after_pos = r
fields = [Field("pos", pos, ('f', 'f', 'f'), pos_vals, bytes([0xA3, 0x02]))]
neg_pos = find_after(data, SIG_BAR_NEG, after_pos, MAX_LOOKAHEAD)
if neg_pos < 0: return None
neg_data_pos = neg_pos + len(SIG_BAR_NEG)
r = read_values(data, neg_data_pos, ('f', 'f', 'f'))
if not r: return None
neg_vals, end_pos = r
fields.append(Field("neg", neg_data_pos, ('f', 'f', 'f'), neg_vals, bytes([0xA3, 0x02])))
return Element(-1, "BAR", i-2, end_pos, fields, "bar", "", full_identifier)
# ==================== SCANNER ====================
def scan(data: bytes) -> tuple[list[Element], list[Element]]:
"""Scan and return (body_elements, suspension_elements)"""
body_elems = []
susp_elems = []
i, n = 0, len(data)
# PHASE 1: Scan for ALL body elements first
while i < n:
e = None
if data.startswith(SIG_BODY_MASS, i):
e = parse_body_at(data, i)
elif data.startswith(SIG_GEN_MASS, i):
e = parse_generic_at(data, i)
if e:
e.index = len(body_elems)
e.auto_name = auto_name_element(e)
if not e.display_name or e.display_name.startswith("elem_"):
e.display_name = e.auto_name
body_elems.append(e)
i = e.end
else:
i += 1
# Find where body section ends (last body element's end position)
if body_elems:
last_body_end = max(e.end for e in body_elems)
else:
last_body_end = 0
# PHASE 2: Scan for suspension elements starting AFTER body section
i = last_body_end
while i < n:
e = None
# Check for JOINT&HINGE
if i >= 1 and data[i:i+len(SIG_JOINT_HINGE)] == SIG_JOINT_HINGE:
e = parse_joint_hinge_at(data, i)
if e:
e.index = len(susp_elems)
# Auto-name based on order: FL, FR, RL, RR
axis_val = e.fields[0].values[0] if e.fields else 0
corner_names = ["fl", "fr", "rl", "rr"]
if e.index < 4:
corner = corner_names[e.index]
e.display_name = f"{corner}_wheel_hinge?"
else:
e.display_name = f"joint_hinge_{e.index+1:02d}"
susp_elems.append(e)
i = e.end
continue
# Check for BAR
if data[i:i+len(SIG_BAR_POS)] == SIG_BAR_POS:
e = parse_bar_at(data, i)
if e:
e.index = len(susp_elems)
# Auto-name BARs based on order (5 per corner: FL, FR, RL, RR)
# Each corner has: forward_upper, rearward_upper, forward_lower, rearward_lower, tie_rod
bar_offset = e.index - 4 # Subtract 4 JOINT&HINGE elements
if bar_offset >= 0 and bar_offset < 20:
corner_idx = bar_offset // 5
arm_idx = bar_offset % 5
corners = ["fl", "fr", "rl", "rr"]
arms = ["forward_upper", "rearward_upper", "forward_lower", "rearward_lower", "tie_rod"]
if corner_idx < 4 and arm_idx < 5:
corner = corners[corner_idx]
arm = arms[arm_idx]
e.display_name = f"{corner}_{arm}?"
else:
e.display_name = f"bar_{e.index+1:02d}"
else:
e.display_name = f"bar_{e.index+1:02d}"
susp_elems.append(e)
i = e.end
continue
i += 1
return (body_elems, susp_elems)
# ==================== SAVE FUNCTION ====================
def save_to_binary(body_elements: list[Element], susp_elements: list[Element], original_data: bytes) -> bytes:
data = bytearray(original_data)
for elem in body_elements + susp_elements:
for field in elem.fields:
offset = field.at
for val, fmt in zip(field.values, field.fmt):
if fmt == 'b':
if offset < len(data): data[offset] = int(val) & 0xFF
offset += 1
elif fmt == 'f':
if offset + 3 < len(data): struct.pack_into('<f', data, offset, float(val))
offset += 4
elif fmt == 'i':
if offset + 3 < len(data): struct.pack_into('<i', data, offset, int(val))
offset += 4
return bytes(data)
# ==================== EXPORT FUNCTIONS ====================
def format_value(val) -> str:
if isinstance(val, float):
if abs(val) < 0.0001 or abs(val) > 10000:
return f"{val:.6e}"
else:
return f"{val:.6f}".rstrip('0').rstrip('.')
return str(val)
def format_type_string(fmt: tuple[str, ...]) -> str:
type_names = {'b': 'byte', 'f': 'float', 'i': 'int'}
return "(" + ", ".join(type_names.get(f, f) for f in fmt) + ")"
def generate_report(body_elements, susp_elements) -> str:
lines = ["=" * 120, "SDF ELEMENTS REPORT - BODY AND SUSPENSION", "=" * 120, ""]
# Body section
lines.extend(["=" * 120, "BODY INFORMATION", "=" * 120, "", f"Total Body Elements: {len(body_elements)}", ""])
for e in body_elements:
lines.append(f"Element #{e.index+1:02d}: {e.kind}")
lines.append(f" Name: {e.display_name}")
if e.auto_name:
lines.append(f" Auto-name: {e.auto_name}")
lines.append(f" Offsets: 0x{e.start:06X} - 0x{e.end:06X}")
lines.append(" Fields:")
for fld in e.fields:
enc_str = fld.encoding_suffix.hex(' ').upper() if fld.encoding_suffix else "N/A"
val_str = ", ".join(format_value(v) for v in fld.values)
type_str = format_type_string(fld.fmt)
lines.append(f" {fld.name:12s} Encoding: {enc_str:10s} Types: {type_str:25s} Values: [{val_str}]")
lines.append("")
# Suspension section
if susp_elements:
lines.extend(["=" * 120, "SUSPENSION INFORMATION", "=" * 120, "",
f"Total Suspension Elements: {len(susp_elements)}", ""])
for e in susp_elements:
id_str = f" ({e.identifier.hex(' ').upper()})" if e.identifier else ""
lines.append(f"Element #{e.index+1:02d}: {e.kind}{id_str}")
lines.append(f" Name: {e.display_name}")
lines.append(f" Offsets: 0x{e.start:06X} - 0x{e.end:06X}")
lines.append(" Fields:")
for fld in e.fields:
enc_str = fld.encoding_suffix.hex(' ').upper() if fld.encoding_suffix else "N/A"
val_str = ", ".join(format_value(v) for v in fld.values)
type_str = format_type_string(fld.fmt)
lines.append(f" {fld.name:12s} Encoding: {enc_str:10s} Types: {type_str:25s} Values: [{val_str}]")
lines.append("")
# Summary
lines.extend(["=" * 120, "SUMMARY", "=" * 120, "",
f"Body Elements: {len(body_elements)}",
f"Suspension Elements: {len(susp_elements)}",
f"Total Elements: {len(body_elements) + len(susp_elements)}", "", "=" * 120])
return "\n".join(lines)
# ==================== GUI ====================
class Viewer(tk.Tk):
def __init__(self):
super().__init__()
self.title("SDF File Editor & Hex Viewer")
self.geometry("1400x750")
self.data: bytes | None = None
self.path: Path | None = None
self.body_elements: list[Element] = []
self.susp_elements: list[Element] = []
self.labels: dict[str,str] = {}
self.modified: bool = False
self._build_ui()
def _build_ui(self):
style = ttk.Style(self)
style.configure("Treeview", rowheight=28)
# ===== Menus =====
mb = tk.Menu(self)
mfile = tk.Menu(mb, tearoff=0)
mfile.add_command(label="Open…", command=self.on_open)
mfile.add_command(label="Save", command=self.on_save, state='disabled')
mfile.add_command(label="Save As…", command=self.on_save_as, state='disabled')
mfile.add_separator()
mfile.add_command(label="Exit", command=self.destroy)
mb.add_cascade(label="File", menu=mfile)
self._mfile = mfile
mtools = tk.Menu(mb, tearoff=0)
mtools.add_command(label="Apply auto-names", command=self.apply_auto_names, state='disabled')
mtools.add_command(label="Save labels", command=self.save_labels, state='disabled')
mtools.add_command(label="Import labels…", command=self.import_labels, state='disabled')
mb.add_cascade(label="Tools", menu=mtools)
self._mtools = mtools
mexport = tk.Menu(mb, tearoff=0)
mexport.add_command(label="View Report…", command=self.view_report, state='disabled')
mexport.add_command(label="Copy to Clipboard", command=self.copy_report, state='disabled')
mexport.add_command(label="Save Report…", command=self.save_report_file, state='disabled')
mb.add_cascade(label="Export", menu=mexport)
self._mexport = mexport
self.config(menu=mb)
# ===== Paned layout (left / middle / right) =====
pw = ttk.Panedwindow(self, orient='horizontal')
pw.pack(fill='both', expand=True, padx=8, pady=8)
# -- Left (info) --
left = ttk.Frame(pw, width=350)
pw.add(left, weight=0)
self.info = tk.StringVar(value="Open an .sdf file.\n\nCLICK on any value to edit inline.\nModified values shown in blue.\n\nFile → Save to write changes.")
ttk.Label(left, textvariable=self.info, wraplength=330, justify='left').pack(anchor='nw')
self.summary = tk.StringVar(value="")
ttk.Label(left, textvariable=self.summary, wraplength=330, justify='left', foreground="#444").pack(anchor='nw', pady=(8,0))
# -- Middle (Tree with V+H scrollbars) --
middle = ttk.Frame(pw)
pw.add(middle, weight=3)
tree_frame = ttk.Frame(middle)
tree_frame.pack(fill='both', expand=True)
self.tree = ttk.Treeview(tree_frame, columns=("type", "value"),
show='tree headings', selectmode='browse')
self.tree.heading("#0", text="Element / Field")
self.tree.heading("type", text="Type [Encoding]")
self.tree.heading("value", text="Value (click to edit)")
# make all columns stretchable so the sash resize is useful
self.tree.column("#0", width=350, stretch=True, anchor='w')
self.tree.column("type", width=260, stretch=True, anchor='w')
self.tree.column("value", width=700, stretch=True, anchor='w')
vsb = ttk.Scrollbar(tree_frame, orient="vertical", command=self.tree.yview)
hsb = ttk.Scrollbar(tree_frame, orient="horizontal", command=self.tree.xview)
self.tree.configure(yscrollcommand=vsb.set, xscrollcommand=hsb.set)
# grid so the horizontal scrollbar sits at the bottom
tree_frame.columnconfigure(0, weight=1)
tree_frame.rowconfigure(0, weight=1)
self.tree.grid(row=0, column=0, sticky='nsew')
vsb.grid(row=0, column=1, sticky='ns')
hsb.grid(row=1, column=0, sticky='ew')
self.tree.bind("<Button-1>", self.on_tree_click)
self.tree.bind("<Double-1>", self.on_tree_double_click)
self.tree.bind("<<TreeviewSelect>>", self.on_tree_select)
self.tree.tag_configure('modified', foreground='blue')
# (Optional) nudge widths once after the widget appears
def _autosize_cols(_evt=None):
# keep name readable; distribute remaining space
w = max(self.tree.winfo_width(), 1)
self.tree.column("#0", width=max(320, int(w*0.30)))
self.tree.column("type", width=max(220, int(w*0.22)))
self.tree.column("value", width=max(480, int(w*0.46)))
self.tree.bind("<Configure>", _autosize_cols)
# -- Right (Hex view with V+H scrollbars) --
right = ttk.Frame(pw, width=520)
pw.add(right, weight=2)
hex_label = ttk.Label(right, text="Hex View", font=("", 10, "bold"))
hex_label.pack(anchor='nw', pady=(0, 5))
hex_frame = ttk.Frame(right)
hex_frame.pack(fill='both', expand=True)
self.hex_text = tk.Text(hex_frame, wrap=tk.NONE, font=("Courier", 9),
width=60, bg="#f5f5f5", relief=tk.SUNKEN, bd=1)
hex_vsb = ttk.Scrollbar(hex_frame, orient="vertical", command=self.hex_text.yview)
hex_hsb = ttk.Scrollbar(hex_frame, orient="horizontal", command=self.hex_text.xview)
self.hex_text.configure(yscrollcommand=hex_vsb.set, xscrollcommand=hex_hsb.set)
hex_frame.grid_rowconfigure(0, weight=1)
hex_frame.grid_columnconfigure(0, weight=1)
self.hex_text.grid(row=0, column=0, sticky='nsew')
hex_vsb.grid(row=0, column=1, sticky='ns')
hex_hsb.grid(row=1, column=0, sticky='ew')
# Hex highlighting tags
self.hex_text.tag_configure('highlight', background='#ffff00', foreground='#000000')
self.hex_text.tag_configure('element_highlight', background='#90ee90', foreground='#000000')
self.hex_text.config(state='disabled')
# ===== Status bar =====
self.status = tk.StringVar(value="Ready")
ttk.Label(self, textvariable=self.status, anchor='w').pack(fill='x', padx=8, pady=(0,8))
def mark_modified(self):
if not self.modified:
self.modified = True
self.title(self.title() + " *")
self._mfile.entryconfig("Save", state='normal')
def labels_path(self) -> Path | None:
return None if not self.path else self.path.with_suffix(self.path.suffix + ".labels.json")
def load_labels(self):
self.labels = {}
p = self.labels_path()
if p and p.exists():
try: self.labels = json.loads(p.read_text(encoding="utf-8"))
except Exception: self.labels = {}
def save_labels(self):
p = self.labels_path()
if not p: return
try:
p.write_text(json.dumps(self.labels, indent=2, ensure_ascii=False), encoding="utf-8")
self.status.set(f"Saved labels → {p.name}")
except Exception as e:
messagebox.showwarning("Save labels failed", str(e))
def import_labels(self):
"""Import labels from another .labels.json file"""
filepath = filedialog.askopenfilename(
title="Import Labels",
filetypes=[("Label files", "*.labels.json"), ("JSON files", "*.json"), ("All files", "*.*")],
initialdir=self.path.parent if self.path else None
)
if not filepath:
return
try:
# Load the labels from the selected file
imported_labels = json.loads(Path(filepath).read_text(encoding="utf-8"))
# Show preview dialog
preview = tk.Toplevel(self)
preview.title("Import Labels - Preview")
preview.geometry("700x500")
preview.transient(self)
preview.grab_set()
ttk.Label(preview, text=f"Import labels from: {Path(filepath).name}",
font=("", 10, "bold")).pack(pady=(10, 5))
ttk.Label(preview, text=f"Found {len(imported_labels)} labels",
foreground="#666").pack(pady=(0, 10))
# Create preview list
frame = ttk.Frame(preview)
frame.pack(fill='both', expand=True, padx=10, pady=(0, 10))
text = scrolledtext.ScrolledText(frame, wrap=tk.WORD, font=("Courier", 9), height=20)
text.pack(fill='both', expand=True)
# Show what will be imported
lines = ["Labels to import:", "=" * 60, ""]
for key, value in sorted(imported_labels.items()):
lines.append(f"{key:20s} → {value}")
text.insert('1.0', '\n'.join(lines))
text.config(state='disabled')
# Merge options
merge_var = tk.BooleanVar(value=True)
ttk.Checkbutton(preview, text="Merge with existing labels (uncheck to replace all)",
variable=merge_var).pack(pady=5)
def do_import():
if merge_var.get():
# Merge: update existing + add new
self.labels.update(imported_labels)
action = "merged"
else:
# Replace: clear existing and use imported
self.labels = imported_labels.copy()
action = "replaced"
# Apply labels to elements
for e in self.body_elements:
key = f"body:{e.index}"
if key in self.labels:
e.display_name = self.labels[key]
for e in self.susp_elements:
key = f"susp:{e.index}"
if key in self.labels:
e.display_name = self.labels[key]
self.fill_tree()
self.status.set(f"Imported {len(imported_labels)} labels ({action})")
preview.destroy()
# Ask to save
if messagebox.askyesno("Save Labels?",
f"Labels {action}. Save to current file's label file?"):
self.save_labels()
btn_frame = ttk.Frame(preview)
btn_frame.pack(fill='x', padx=10, pady=(0, 10))
ttk.Button(btn_frame, text="Import", command=do_import).pack(side='left', padx=5)
ttk.Button(btn_frame, text="Cancel", command=preview.destroy).pack(side='left', padx=5)
except json.JSONDecodeError as e:
messagebox.showerror("Import Failed", f"Invalid JSON file:\n{e}")
except Exception as e:
messagebox.showerror("Import Failed", str(e))
def on_open(self):
path = filedialog.askopenfilename(
title="Open SDF / binary",
filetypes=[("SDF files", "*.sdf"), ("All files", "*.*")]
)
if not path: return
if self.modified:
result = messagebox.askyesnocancel("Unsaved Changes",
"Save changes before opening new file?")
if result is None: return
elif result: self.on_save()
try:
data = Path(path).read_bytes()
except Exception as e:
messagebox.showerror("Open failed", str(e)); return
self.path = Path(path)
self.data = data
self.modified = False
self.title(f"SDF File Editor & Hex Viewer - {self.path.name}")
self.load_labels()
# NEW: Scan returns TWO lists
self.body_elements, self.susp_elements = scan(self.data)
# Load labels for body elements
for e in self.body_elements:
key = f"body:{e.index}"
if key in self.labels:
e.display_name = self.labels[key]
# Load labels for suspension elements
for e in self.susp_elements:
key = f"susp:{e.index}"
if key in self.labels:
e.display_name = self.labels[key]
# Calculate summary
total = len(self.body_elements)
body_cnt = sum(1 for e in self.body_elements if e.kind == "BODY")
msg = f"Body: {total} elements\n BODY={body_cnt}, GENERIC={total - body_cnt}"
# NEW: Add suspension summary
if self.susp_elements:
susp_total = len(self.susp_elements)
joint_cnt = sum(1 for e in self.susp_elements if e.kind == "JOINT&HINGE")
bar_cnt = susp_total - joint_cnt
msg += f"\n\nSuspension: {susp_total} elements\n JOINT&HINGE={joint_cnt}, BAR={bar_cnt}"
self.summary.set(msg)
self.fill_tree()
self._mtools.entryconfig("Apply auto-names", state='normal')
self._mtools.entryconfig("Save labels", state='normal')
self._mtools.entryconfig("Import labels…", state='normal')
self._mfile.entryconfig("Save As…", state='normal')
# NEW: Enable export menu
self._mexport.entryconfig("View Report…", state='normal')
self._mexport.entryconfig("Copy to Clipboard", state='normal')
self._mexport.entryconfig("Save Report…", state='normal')
self.status.set(f"Loaded {self.path.name}")
# NEW: Generate hex view
self.update_hex_view()
def update_hex_view(self):
"""Generate and display hex view of the file"""
if not self.data:
return
self.hex_text.config(state='normal')
self.hex_text.delete('1.0', tk.END)
# Generate hex dump (16 bytes per line)
lines = []
for i in range(0, len(self.data), 16):
# Offset
offset = f"{i:08X} "
# Hex bytes
hex_part = ""
ascii_part = ""
for j in range(16):
if i + j < len(self.data):
byte = self.data[i + j]
hex_part += f"{byte:02X} "
# ASCII representation
ascii_part += chr(byte) if 32 <= byte < 127 else '.'
else:
hex_part += " "
ascii_part += " "
# Add extra space in the middle
if j == 7:
hex_part += " "
lines.append(f"{offset}{hex_part} |{ascii_part}|")
self.hex_text.insert('1.0', '\n'.join(lines))
self.hex_text.config(state='disabled')
def highlight_hex_range(self, start_offset: int, end_offset: int, tag: str = 'highlight'):
"""Highlight a byte range in the hex view"""
if not self.data:
return
self.hex_text.config(state='normal')
# Remove previous highlights
self.hex_text.tag_remove('highlight', '1.0', tk.END)
self.hex_text.tag_remove('element_highlight', '1.0', tk.END)
# Calculate positions for highlighting
# Each line: "OFFSET XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX |................|"
# Format: 8 chars offset + 2 spaces + 48 chars hex + 2 spaces + 18 chars ascii
for offset in range(start_offset, min(end_offset, len(self.data))):
line_num = offset // 16
byte_in_line = offset % 16
# Calculate text position for hex part
# Line format: "00000000 XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX |................|"
# 01234567890123456789...
col_start = 10 + (byte_in_line * 3)
if byte_in_line >= 8:
col_start += 1 # Extra space after 8th byte
# Highlight hex bytes
hex_start = f"{line_num + 1}.{col_start}"
hex_end = f"{line_num + 1}.{col_start + 2}"
self.hex_text.tag_add(tag, hex_start, hex_end)
# Highlight ASCII representation
ascii_col = 61 + byte_in_line
ascii_start = f"{line_num + 1}.{ascii_col}"
ascii_end = f"{line_num + 1}.{ascii_col + 1}"
self.hex_text.tag_add(tag, ascii_start, ascii_end)
# Scroll to show the highlighted range
if start_offset < len(self.data):
line_num = start_offset // 16
self.hex_text.see(f"{line_num + 1}.0")
self.hex_text.config(state='disabled')
def on_tree_select(self, event=None):
"""Handle tree selection to highlight corresponding hex bytes"""
selection = self.tree.selection()
if not selection:
return
item = selection[0]
tags = self.tree.item(item, 'tags')
if not tags:
return
tag = tags[0]
# Parse tag to get element/field info
if tag.startswith("elem:"):
# Element selected - highlight entire element range
parts = tag.split(':')
prefix = parts[1]
elem_idx = int(parts[2])
elem = self.body_elements[elem_idx] if prefix == "body" else self.susp_elements[elem_idx]
self.highlight_hex_range(elem.start, elem.end, 'element_highlight')
elif tag.startswith("field:"):
# Field selected - highlight field data range
parts = tag.split(':')
prefix = parts[1]
elem_idx = int(parts[2])
field_idx = int(parts[3])
elem = self.body_elements[elem_idx] if prefix == "body" else self.susp_elements[elem_idx]
field = elem.fields[field_idx]
# Calculate field size
field_size = sum(4 if f == 'f' or f == 'i' else 1 for f in field.fmt)
self.highlight_hex_range(field.at, field.at + field_size, 'highlight')
elif tag.startswith("value:"):
# Individual value selected - highlight just that value
parts = tag.split(':')
prefix = parts[1]
elem_idx = int(parts[2])
field_idx = int(parts[3])
val_idx = int(parts[4])
elem = self.body_elements[elem_idx] if prefix == "body" else self.susp_elements[elem_idx]
field = elem.fields[field_idx]
# Calculate offset to this specific value
offset = field.at
for i in range(val_idx):
fmt_type = field.fmt[i]
if fmt_type == 'f' or fmt_type == 'i':
offset += 4
else:
offset += 1
# Highlight this value
fmt_type = field.fmt[val_idx]
size = 4 if (fmt_type == 'f' or fmt_type == 'i') else 1
self.highlight_hex_range(offset, offset + size, 'highlight')
def on_save(self):
if not self.path or not self.data:
self.on_save_as()
return
try:
new_data = save_to_binary(self.body_elements, self.susp_elements, self.data)
self.path.write_bytes(new_data)
self.data = new_data
self.modified = False
self.title(self.title().rstrip(" *"))
self.status.set(f"Saved to {self.path.name}")
messagebox.showinfo("Saved", f"File saved successfully:\n{self.path}")
except Exception as e:
messagebox.showerror("Save Failed", str(e))
def on_save_as(self):
if not self.data: return
filepath = filedialog.asksaveasfilename(
title="Save SDF File As",
defaultextension=".sdf",
filetypes=[("SDF files", "*.sdf"), ("All files", "*.*")],
initialfile=f"{self.path.stem}_modified.sdf" if self.path else "modified.sdf"
)
if not filepath: return
try:
new_data = save_to_binary(self.body_elements, self.susp_elements, self.data)
Path(filepath).write_bytes(new_data)
self.path = Path(filepath)
self.data = new_data
self.modified = False
self.title(f"SDF Body/Generic Elements Viewer (Editable) - {self.path.name}")
self.status.set(f"Saved to {self.path.name}")
messagebox.showinfo("Saved", f"File saved successfully:\n{filepath}")
except Exception as e:
messagebox.showerror("Save Failed", str(e))
def fill_tree(self):
self.tree.delete(*self.tree.get_children())
root = self.tree.insert('', 'end',
text=f"File: {self.path.name if self.path else '(unsaved)'}",
values=('', ''), open=True)
# Body Information section
body_info = self.tree.insert(root, 'end',
text="Body Information",
values=('', f"{len(self.body_elements)} elements"),
open=True)
for e in self.body_elements:
self._add_element_to_tree(body_info, e, "body")
# NEW: Suspension section
if self.susp_elements:
susp_info = self.tree.insert(root, 'end',
text="Suspension",
values=('', f"{len(self.susp_elements)} elements"),
open=True)
for e in self.susp_elements:
self._add_element_to_tree(susp_info, e, "susp")
def _add_element_to_tree(self, parent, e: Element, prefix: str):
"""Helper to add element to tree"""
# Format element name
elem_text = f"{e.index+1:02d}. {e.display_name}"
if e.identifier:
elem_text += f" ({e.identifier.hex(' ').upper()})"
enode = self.tree.insert(parent, 'end',
text=elem_text,
values=(f"{e.kind}", f"@0x{e.start:06X} - 0x{e.end:06X}"),
open=True,
tags=(f"elem:{prefix}:{e.index}",))
for field_idx, fld in enumerate(e.fields):
type_str = format_type_string(fld.fmt)
enc_str = fld.encoding_suffix.hex(' ').upper() if fld.encoding_suffix else "N/A"
if len(fld.values) == 1:
val_summary = format_value(fld.values[0])
else:
val_summary = f"({', '.join(format_value(v) for v in fld.values)})"
field_node = self.tree.insert(enode, 'end',