-
Notifications
You must be signed in to change notification settings - Fork 3
/
converter.py
1569 lines (1355 loc) · 54.8 KB
/
converter.py
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
"""
Minecraft Resource Pack Converter Module
This module handles the conversion of Minecraft resource pack files between different formats.
It supports both Custom Model Data and Item Model conversion modes with comprehensive features:
Features:
- Bilingual support (English/Chinese)
- Both GUI and console interfaces
- Progress tracking and reporting
- ZIP file handling
- Directory structure management
- Detailed processing reports
- Error handling and recovery
The module can be used both as a standalone command-line tool and as part of a GUI application.
Author: RiceChen_
Version: 1.3
"""
import json
import os
import shutil
import zipfile
from datetime import datetime
from rich.console import Console
from rich.table import Table
from rich.panel import Panel
from rich.progress import (
BarColumn,
MofNCompleteColumn,
Progress,
TaskProgressColumn,
TextColumn,
TimeElapsedColumn,
TimeRemainingColumn,
TransferSpeedColumn,
)
# Global variables
CURRENT_LANG = "zh"
console = Console()
CustomProgress = None
# Language translations
TRANSLATIONS = {
"processing_start": {
"zh": "開始處理檔案...",
"en": "Starting file processing..."
},
"adjusting_structure": {
"zh": "調整資料夾結構...",
"en": "Adjusting folder structure..."
},
"moving_files": {
"zh": "移動檔案中",
"en": "Moving files"
},
"processing_files": {
"zh": "處理檔案中",
"en": "Processing files"
},
"creating_zip": {
"zh": "建立ZIP檔案...",
"en": "Creating ZIP file..."
},
"compressing_files": {
"zh": "壓縮檔案中",
"en": "Compressing files"
},
"moved_models": {
"zh": "已將物品模型從 {} 移動到 {}",
"en": "Moved item models from {} to {}"
},
"process_complete": {
"zh": "處理完成!",
"en": "Processing complete!"
},
"converted_files_count": {
"zh": "已轉換 {} 個檔案",
"en": "Converted {} files"
},
"output_file": {
"zh": "輸出檔案",
"en": "Output file"
},
"current_file": {
"zh": "當前檔案:{}",
"en": "Current file: {}"
},
"input_dir_error": {
"zh": "錯誤:找不到輸入資料夾 '{}'",
"en": "Error: Input directory '{}' not found"
},
"error_occurred": {
"zh": "發生錯誤:{}",
"en": "Error occurred: {}"
},
"file_table_title": {
"zh": "檔案處理報告",
"en": "File Processing Report"
},
"file_name": {
"zh": "檔案名稱",
"en": "File Name"
},
"file_type": {
"zh": "類型",
"en": "Type"
},
"file_status": {
"zh": "狀態",
"en": "Status"
},
"status_converted": {
"zh": "已轉換",
"en": "Converted"
},
"status_copied": {
"zh": "已複製",
"en": "Copied"
},
}
def get_text(key, *args):
"""Get translated text"""
text = TRANSLATIONS.get(key, {}).get(CURRENT_LANG, f"Missing translation: {key}")
return text.format(*args) if args else text
def get_progress_bar():
"""Create appropriate progress bar based on console type"""
if hasattr(console, 'status_label') and hasattr(console, 'progress_bar') and CustomProgress:
return CustomProgress(console)
return Progress(
TextColumn("[bold blue]{task.description}"),
BarColumn(complete_style="green", finished_style="green"),
TaskProgressColumn(),
MofNCompleteColumn(),
TimeElapsedColumn(),
TextColumn("•"),
TimeRemainingColumn(),
TransferSpeedColumn(),
refresh_per_second=10,
expand=True
)
def is_damage_model(json_data):
"""
Check if JSON data represents a damage-based model
Args:
json_data (dict): Input JSON data
Returns:
bool: True if it's a damage-based model, False otherwise
"""
if "overrides" not in json_data:
return False
# Check for damage-based predicates without custom_model_data
for override in json_data.get("overrides", []):
predicate = override.get("predicate", {})
if ("damaged" in predicate and "damage" in predicate and
"custom_model_data" not in predicate):
return True
return False
def is_potion_model(json_data, file_path=""):
"""
Check if the JSON data represents a potion model based on file path
Args:
json_data (dict): Input JSON data (kept for backwards compatibility)
file_path (str): Path to the JSON file
Returns:
bool: True if it's a potion model, False otherwise
"""
normalized_path = os.path.basename(file_path).lower()
potion_files = [
"potion.json",
"splash_potion.json",
"lingering_potion.json"
]
return normalized_path in potion_files
def is_chest_model(json_data, file_path=""):
"""
Check if the JSON data represents a chest or trapped chest model based on file path
Args:
json_data (dict): Input JSON data (kept for backwards compatibility)
file_path (str): Path to the JSON file
Returns:
tuple: (bool, str) - (is chest model, chest type)
"""
normalized_path = os.path.basename(file_path).lower()
if normalized_path == "chest.json":
return True, "chest"
elif normalized_path == "trapped_chest.json":
return True, "trapped_chest"
return False, None
def has_mixed_custom_damage(json_data):
"""
Check if JSON data contains both custom_model_data and damage predicates
Args:
json_data (dict): Input JSON data
Returns:
bool: True if mixed predicates exist
"""
if "overrides" not in json_data:
return False
cmd_with_damage = False
for override in json_data["overrides"]:
predicate = override.get("predicate", {})
if ("custom_model_data" in predicate and
"damaged" in predicate and
"damage" in predicate):
cmd_with_damage = True
break
return cmd_with_damage
def convert_damage_model(json_data, base_texture=""):
"""
Convert damage-based model JSON format to the new format.
Args:
json_data (dict): Original JSON data containing damage model information
base_texture (str): Base texture path to use as fallback
Returns:
dict: Converted JSON in new format for damage-based models
"""
# Extract base texture or parent path if not provided
if not base_texture:
base_texture = json_data.get("textures", {}).get("layer0", "")
if not base_texture:
base_texture = json_data.get("parent", "")
# Create basic structure for damage model
new_format = {
"model": {
"type": "range_dispatch",
"property": "damage",
"fallback": {
"type": "model",
"model": base_texture
},
"entries": []
}
}
# Add display settings if present
if "display" in json_data:
new_format["display"] = json_data["display"]
# Filter and sort overrides that have damage predicates
damage_overrides = [
override for override in json_data.get("overrides", [])
if ("damaged" in override.get("predicate", {}) and
"damage" in override.get("predicate", {}) and
"custom_model_data" not in override.get("predicate", {}))
]
damage_overrides.sort(
key=lambda x: float(x.get("predicate", {}).get("damage", 0))
)
# Add entries for each damage threshold
for override in damage_overrides:
model_path = override["model"]
# Apply path normalization
if ":" not in model_path:
model_path = f"minecraft:{model_path}"
predicate = override.get("predicate", {})
entry = {
"threshold": float(predicate["damage"]),
"model": {
"type": "model",
"model": model_path
}
}
new_format["model"]["entries"].append(entry)
return new_format
def convert_mixed_custom_damage_model(json_data):
"""
Convert a model that has both custom_model_data and damage predicates.
Args:
json_data (dict): Original JSON data containing model information
Returns:
dict: Converted JSON in new format
"""
# Extract base texture or parent
base_texture = json_data.get("textures", {}).get("layer0", "")
parent_path = json_data.get("parent", "")
base_path = base_texture or parent_path
if ":" not in base_path and base_path.startswith("item/"):
base_path = f"minecraft:{base_path}"
elif ":" not in base_path:
base_path = f"minecraft:item/{base_path}"
# Create basic structure
new_format = {
"model": {
"type": "range_dispatch",
"property": "custom_model_data",
"fallback": {
"type": "model",
"model": base_path
},
"entries": []
}
}
# Group overrides by custom_model_data
cmd_groups = {}
for override in json_data.get("overrides", []):
predicate = override.get("predicate", {})
cmd = predicate.get("custom_model_data")
if cmd is None:
continue
if cmd not in cmd_groups:
cmd_groups[cmd] = {
"base_model": None,
"damage_states": []
}
# Check if this is a damage state
if "damaged" in predicate and "damage" in predicate:
cmd_groups[cmd]["damage_states"].append({
"damage": float(predicate["damage"]),
"model": override["model"]
})
else:
cmd_groups[cmd]["base_model"] = override["model"]
# Process each custom_model_data group
for cmd, group in sorted(cmd_groups.items()):
base_model = group["base_model"] or base_path
damage_states = sorted(group["damage_states"], key=lambda x: x["damage"])
# Create entry for this CMD
cmd_entry = {
"threshold": int(cmd),
"model": {
"type": "range_dispatch",
"property": "damage",
"fallback": {
"type": "model",
"model": base_model
},
"entries": []
}
}
# Add damage states
for state in damage_states:
damage_entry = {
"threshold": state["damage"],
"model": {
"type": "model",
"model": state["model"]
}
}
cmd_entry["model"]["entries"].append(damage_entry)
new_format["model"]["entries"].append(cmd_entry)
# Add display settings if present
if "display" in json_data:
new_format["display"] = json_data["display"]
return new_format
def convert_mixed_damage_model(json_data, cmd_value, base_model):
"""
Convert a model that has both custom_model_data and damage predicates for a specific CMD value.
Args:
json_data (dict): Original JSON data containing model information
cmd_value (int): The custom_model_data value to process
base_model (str): Base model path to use as fallback
Returns:
dict: Converted JSON in new format for mixed damage model
"""
# Create the basic structure
new_json = {
"model": {
"type": "range_dispatch",
"property": "damage",
"fallback": {
"type": "model",
"model": base_model
},
"entries": []
}
}
# Filter damage states for this CMD value
damage_states = []
for override in json_data.get("overrides", []):
predicate = override.get("predicate", {})
if (predicate.get("custom_model_data") == cmd_value and
"damage" in predicate and "damaged" in predicate):
damage_states.append({
"damage": float(predicate["damage"]),
"model": override["model"]
})
# Sort damage states by threshold
damage_states.sort(key=lambda x: x["damage"])
# Add damage state entries
for state in damage_states:
entry = {
"threshold": state["damage"],
"model": {
"type": "model",
"model": state["model"]
}
}
new_json["model"]["entries"].append(entry)
return new_json
def convert_json_format(json_data, is_item_model=False, file_path=""):
"""
Convert JSON format with special handling for different model types
Args:
json_data (dict): Original JSON data to convert
is_item_model (bool): Whether in Item Model mode
file_path (str): Path to the JSON file
Returns:
dict: Converted JSON in new format
"""
# Extract and normalize base texture path or parent path
base_texture = json_data.get("textures", {}).get("layer0", "")
parent_path = json_data.get("parent", "")
base_path = base_texture or parent_path
# First check for mixed custom_model_data and damage model
if has_mixed_custom_damage(json_data):
return convert_mixed_custom_damage_model(json_data)
# Then check for pure damage model
if is_damage_model(json_data):
# Create damage-based conversion structure
new_format = {
"model": {
"type": "range_dispatch",
"property": "damage",
"fallback": {
"type": "model",
"model": base_path
},
"entries": []
}
}
# Filter and sort overrides that only have damage predicates (no custom_model_data)
damage_overrides = [
override for override in json_data.get("overrides", [])
if ("damaged" in override.get("predicate", {}) and
"damage" in override.get("predicate", {}) and
"custom_model_data" not in override.get("predicate", {}))
]
damage_overrides.sort(
key=lambda x: float(x.get("predicate", {}).get("damage", 0))
)
# Add entries for each damage threshold
for override in damage_overrides:
model_path = override["model"]
# Apply the same path normalization logic as custom_model_data mode
if ":" not in model_path:
model_path = f"minecraft:{model_path}"
predicate = override.get("predicate", {})
entry = {
"threshold": float(predicate["damage"]),
"model": {
"type": "model",
"model": model_path
}
}
new_format["model"]["entries"].append(entry)
return new_format
# Special handling for potions
is_potion = is_potion_model(json_data, file_path)
if is_potion:
textures = json_data.get("textures", {})
if textures.get("layer0") == "item/splash_potion_overlay":
base_path = "minecraft:item/splash_potion"
elif textures.get("layer0") == "item/lingering_potion_overlay":
base_path = "minecraft:item/lingering_potion"
else:
base_path = "minecraft:item/potion"
# Special handling for chests
is_chest, chest_type = is_chest_model(json_data, file_path)
if is_chest:
base_path = f"item/{chest_type}"
else:
# Normal path normalization for non-chest items
if base_texture and not is_potion:
# Special handling for crossbow_standby
if base_path == "item/crossbow_standby":
base_path = "item/crossbow"
elif base_path == "minecraft:item/crossbow_standby":
base_path = "minecraft:item/crossbow"
# Normal path normalization for textures
if not parent_path: # Only normalize if it's a texture path
if base_path.startswith("minecraft:item/"):
base_path = base_path
elif base_path.startswith("item/"):
base_path = f"minecraft:{base_path}"
elif not base_path.startswith("minecraft:"):
base_path = f"minecraft:item/{base_path}"
# Create fallback structure based on type
if is_chest:
fallback = {
"type": "minecraft:special",
"base": base_path,
"model": {
"type": "minecraft:chest",
"texture": "minecraft:normal"
}
}
elif is_potion:
fallback = {
"type": "model",
"model": base_path,
"tints": [{
"type": "minecraft:potion",
"default": -13083194
}]
}
else:
fallback = {
"type": "model",
"model": base_path
}
# Create basic structure
new_format = {
"model": {
"type": "range_dispatch" if not is_item_model else "model",
"property": "custom_model_data" if not is_item_model else None,
"fallback": fallback,
"entries": [] if not is_item_model else None
}
}
# Add display settings if present
if "display" in json_data:
new_format["display"] = json_data["display"]
if "overrides" not in json_data:
return new_format
# Detect model type and group overrides
is_bow = not is_chest and "bow" in base_path and "crossbow" not in base_path
is_crossbow = not is_chest and "crossbow" in base_path
# Handle different model types
if is_crossbow:
# Group overrides by custom_model_data for crossbow
cmd_groups = {}
for override in json_data["overrides"]:
if "predicate" not in override or "model" not in override:
continue
predicate = override["predicate"]
cmd = predicate.get("custom_model_data")
if cmd is None:
continue
if cmd not in cmd_groups:
cmd_groups[cmd] = {
"base": None,
"pulling_states": [],
"arrow": None,
"firework": None
}
if "pulling" in predicate:
pull_value = predicate.get("pull", 0.0)
cmd_groups[cmd]["pulling_states"].append({
"pull": pull_value,
"model": override["model"]
})
elif "charged" in predicate:
if predicate.get("firework", 0):
cmd_groups[cmd]["firework"] = override["model"]
else:
cmd_groups[cmd]["arrow"] = override["model"]
else:
cmd_groups[cmd]["base"] = override["model"]
for cmd, group in cmd_groups.items():
pulling_states = sorted(group["pulling_states"], key=lambda x: x.get("pull", 0))
base_model = group["base"] or pulling_states[0]["model"] if pulling_states else base_path
entry = {
"threshold": int(cmd),
"model": {
"type": "minecraft:condition",
"property": "minecraft:using_item",
"on_false": {
"type": "minecraft:select",
"property": "minecraft:charge_type",
"fallback": {
"type": "minecraft:model",
"model": base_model
},
"cases": []
},
"on_true": {
"type": "minecraft:range_dispatch",
"property": "minecraft:crossbow/pull",
"fallback": {
"type": "minecraft:model",
"model": pulling_states[0]["model"] if pulling_states else base_model
},
"entries": []
}
}
}
cases = entry["model"]["on_false"]["cases"]
if group["arrow"]:
cases.append({
"model": {
"type": "minecraft:model",
"model": group["arrow"]
},
"when": "arrow"
})
if group["firework"]:
cases.append({
"model": {
"type": "minecraft:model",
"model": group["firework"]
},
"when": "rocket"
})
if pulling_states:
entries = entry["model"]["on_true"]["entries"]
for state in pulling_states[1:]:
entries.append({
"threshold": state.get("pull", 0.0),
"model": {
"type": "minecraft:model",
"model": state["model"]
}
})
new_format["model"]["entries"].append(entry)
elif is_bow:
# Group overrides by custom_model_data for bow
cmd_groups = {}
for override in json_data["overrides"]:
if "predicate" not in override or "model" not in override:
continue
predicate = override["predicate"]
cmd = predicate.get("custom_model_data")
if cmd is None:
continue
if cmd not in cmd_groups:
cmd_groups[cmd] = {
"base": None,
"pulling_states": []
}
if "pulling" in predicate:
pull_value = predicate.get("pull", 0.0)
cmd_groups[cmd]["pulling_states"].append({
"pull": pull_value,
"model": override["model"]
})
else:
cmd_groups[cmd]["base"] = override["model"]
for cmd, group in cmd_groups.items():
pulling_states = sorted(group["pulling_states"], key=lambda x: x.get("pull", 0))
base_model = group["base"] or pulling_states[0]["model"] if pulling_states else base_path
entry = {
"threshold": int(cmd),
"model": {
"type": "minecraft:condition",
"property": "minecraft:using_item",
"on_false": {
"type": "minecraft:model",
"model": base_model
},
"on_true": {
"type": "minecraft:range_dispatch",
"property": "minecraft:use_duration",
"scale": 0.05,
"fallback": {
"type": "minecraft:model",
"model": base_model
},
"entries": []
}
}
}
if pulling_states:
for state in pulling_states:
if state["model"] != base_model:
entry["model"]["on_true"]["entries"].append({
"threshold": state.get("pull", 0.0),
"model": {
"type": "minecraft:model",
"model": state["model"]
}
})
new_format["model"]["entries"].append(entry)
else:
# Handle normal items and chests
for override in json_data["overrides"]:
if "predicate" in override and "custom_model_data" in override["predicate"]:
model_path = override["model"]
if is_chest:
entry = {
"threshold": int(override["predicate"]["custom_model_data"]),
"model": {
"type": "minecraft:select",
"property": "minecraft:local_time",
"pattern": "MM-dd",
"cases": [
{
"model": {
"type": "minecraft:special",
"base": model_path,
"model": {
"type": "minecraft:chest",
"texture": "minecraft:christmas"
}
},
"when": [
"12-24",
"12-25",
"12-26"
]
}
],
"fallback": {
"type": "minecraft:special",
"base": model_path,
"model": {
"type": "minecraft:chest",
"texture": "minecraft:normal"
}
}
}
}
else:
entry = {
"threshold": int(override["predicate"]["custom_model_data"]),
"model": {
"type": "model",
"model": model_path
}
}
new_format["model"]["entries"].append(entry)
return new_format
def process_mixed_damage_models(json_data, output_path):
"""
Process models that have both custom_model_data and damage predicates
"""
if "overrides" not in json_data:
return
# Group overrides by custom_model_data
cmd_groups = {}
for override in json_data.get("overrides", []):
predicate = override.get("predicate", {})
cmd = predicate.get("custom_model_data")
if cmd is None:
continue
if cmd not in cmd_groups:
cmd_groups[cmd] = {
"base_model": None,
"damage_states": []
}
# Check if this is a base model (no damage predicate)
if "damage" not in predicate and "damaged" not in predicate:
cmd_groups[cmd]["base_model"] = override["model"]
else:
# Add to damage states if it has damage predicate
if "damage" in predicate:
cmd_groups[cmd]["damage_states"].append({
"damage": float(predicate["damage"]),
"model": override["model"]
})
# Process each custom_model_data group
for cmd, group in cmd_groups.items():
if not group["base_model"]:
continue
# Create the file structure based on the model path
model_path = group["base_model"]
if ":" in model_path:
namespace, path = model_path.split(":", 1)
file_name = os.path.join(output_path, namespace, path) + ".json"
else:
file_name = os.path.join(output_path, model_path + ".json")
# Ensure directory exists
os.makedirs(os.path.dirname(file_name), exist_ok=True)
# Sort damage states by threshold
damage_states = sorted(group["damage_states"], key=lambda x: x["damage"])
# Create the new JSON structure
new_json = {
"model": {
"type": "range_dispatch",
"property": "damage",
"fallback": {
"type": "model",
"model": group["base_model"]
},
"entries": []
}
}
# Add damage state entries
for state in damage_states:
entry = {
"threshold": state["damage"],
"model": {
"type": "model",
"model": state["model"]
}
}
new_json["model"]["entries"].append(entry)
# Write the new JSON file
with open(file_name, 'w', encoding='utf-8') as f:
json.dump(new_json, f, indent=4)
def convert_item_model_format(json_data, output_path, input_path=""):
"""
Convert JSON format for Item Model mode with comprehensive handling of all model types
Args:
json_data (dict): Original JSON data containing model overrides
output_path (str): Base path for output files
input_path (str): Original input file path for type detection
"""
if "overrides" not in json_data or not json_data["overrides"]:
return None
# Group overrides by custom_model_data
cmd_groups = {}
for override in json_data["overrides"]:
if "predicate" not in override or "model" not in override:
continue
predicate = override["predicate"]
cmd = predicate.get("custom_model_data")
if cmd is None:
continue
# Initialize group structure if needed
if cmd not in cmd_groups:
cmd_groups[cmd] = {
"base": None, # Base model (without damage)
"damage_states": [], # List of damage states
"pulling_states": [], # For bow/crossbow pulling states
"arrow": None, # For crossbow with arrow
"firework": None, # For crossbow with firework
"has_damage": False # Flag for damage-based models
}
# Check for damage states
if "damage" in predicate and "damaged" in predicate:
cmd_groups[cmd]["has_damage"] = True
cmd_groups[cmd]["damage_states"].append({
"damage": float(predicate["damage"]),
"model": override["model"]
})
# Check for bow/crossbow states
elif "pulling" in predicate:
pull_value = predicate.get("pull", 0.0)
cmd_groups[cmd]["pulling_states"].append({
"pull": pull_value,
"model": override["model"]
})
elif "charged" in predicate:
if predicate.get("firework", 0):
cmd_groups[cmd]["firework"] = override["model"]
else:
cmd_groups[cmd]["arrow"] = override["model"]
else:
# This is a base model for this CMD
cmd_groups[cmd]["base"] = override["model"]
# Process each custom_model_data group
for cmd, group in cmd_groups.items():
if not group["base"]:
continue
# Create file structure based on the base model path
model_path = group["base"]
if ":" in model_path:
namespace, path = model_path.split(":", 1)
file_name = os.path.join(output_path, namespace, path) + ".json"
else:
file_name = os.path.join(output_path, model_path + ".json")
os.makedirs(os.path.dirname(file_name), exist_ok=True)
# Handle models with damage states
if group["has_damage"] and group["damage_states"]:
# Sort damage states by threshold
damage_states = sorted(group["damage_states"], key=lambda x: x["damage"])
new_json = {
"model": {
"type": "range_dispatch",
"property": "damage",
"fallback": {
"type": "model",
"model": model_path
},
"entries": []
}
}
# Add sorted damage states
for state in damage_states:
entry = {
"threshold": state["damage"],
"model": {
"type": "model",
"model": state["model"]
}
}
new_json["model"]["entries"].append(entry)
# Handle potion models
elif is_potion_model(json_data, input_path):
new_json = {
"model": {
"type": "model",
"model": model_path,
"tints": [{
"type": "minecraft:potion",
"default": -13083194
}]
}
}
# Handle chest models
elif is_chest_model(json_data, input_path)[0]: