-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathresource_pack_generator.py
More file actions
829 lines (728 loc) · 33.1 KB
/
Copy pathresource_pack_generator.py
File metadata and controls
829 lines (728 loc) · 33.1 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
import os
import json
import copy
import shutil
import zipfile
"""
This script generates a pylon resource pack from supplied assets from the 'input' directory.
It will automatically create item model definitions and block models for pylon items based
on inputted json files & block states.
Pylon Blocks are not real blocks so you cannot use actual block states, you can recreate the
effect of them with complex item model definitions, but those are hard to do by hand, so this
will do it for you.
You can also supply item model definitions manually if there are any cases you need to handle
yourself.
This script automates:
- atlas appending
- item model definition creation
- this includes making the item model definition files for the vanilla items that back the pylon items provided (which you can provide specific model values for if needed)
- if you don't specify a model within the items/<id>.json file, it will look for an item model with the same id, then a block model with the same id, if it can't find either but can find a texture under its id, it will use the built-in "item/generated" model with that texture
- if it defaults to a provided block model, it will create a new item model that inherits from the block model so that the "fixed" display can be changed, as in block context "fixed" is a placed block, but in item context "fixed" is an item frame
- blockstate to item model conversion
- this includes both creating the item model definitions, and creating specific item model variants based on rotations
- merging item model definitions
"""
TRIM_TYPES = [
"helmet",
"chestplate",
"leggings",
"boots"
]
TRIMS = [
"quartz",
"iron",
"netherite",
"redstone",
"copper",
"gold",
"emerald",
"diamond",
"lapis",
"amethyst",
"resin"
]
SETTINGS_TEMPLATE = {
"name": "REPLACE_ME",
"version": "1.0.0",
"pack_squash": True
}
TEMPLATE_DIR = "template"
INPUT_DIR = "input"
OUTPUT_DIR = "output"
settings = SETTINGS_TEMPLATE.copy()
settingsPath = os.path.join(INPUT_DIR, "settings.json")
if os.path.exists(settingsPath):
with open(settingsPath, 'r') as f:
settings = json.load(f)
logWarnings = True
deleteTemp = False
tempDir = os.path.join(OUTPUT_DIR, "temp")
if os.path.exists(tempDir):
for root, dirs, files in os.walk(tempDir, topdown=False):
for name in files:
os.remove(os.path.join(root, name))
for name in dirs:
os.rmdir(os.path.join(root, name))
else:
os.makedirs(tempDir)
outputPath = os.path.join(OUTPUT_DIR, f"{settings['name']}.zip")
# unpack template/items/items.zip into template/items
if os.path.exists(os.path.join(TEMPLATE_DIR, "items", "items.zip")):
with zipfile.ZipFile(os.path.join(TEMPLATE_DIR, "items", "items.zip"), 'r') as zf:
zf.extractall(os.path.join(TEMPLATE_DIR, "items"))
else:
if logWarnings:
print(f"Warning: Template items.zip does not exist. (The generator may not work properly without it.)")
blockModelDefinitions = []
itemModelDefinitions = {}
## Generator Methods
def get_template(templatePath):
file_path = os.path.join(TEMPLATE_DIR, f"{templatePath}.json")
if not os.path.exists(file_path):
if logWarnings:
print(f"Warning: Template {templatePath} ('{file_path}') does not exist, skipping.")
return None
with open(file_path, 'r') as f:
return json.load(f)
def asset_saved(assetPath):
namespace, path = assetPath.split(':') if ':' in assetPath else ('minecraft', assetPath)
file_path = os.path.join(tempDir, "assets", namespace, path)
return os.path.exists(file_path)
def asset_exists(assetPath):
namespace, path = assetPath.split(':') if ':' in assetPath else ('minecraft', assetPath)
file_path = os.path.join(INPUT_DIR, "assets", namespace, path)
if os.path.exists(file_path):
return True
file_path = os.path.join(tempDir, "assets", namespace, path)
return os.path.exists(file_path)
def save_asset(assetPath, data):
if asset_saved(assetPath):
return
namespace, path = assetPath.split(':') if ':' in assetPath else ('minecraft', assetPath)
file_path = os.path.join(tempDir, "assets", namespace, path)
os.makedirs(os.path.dirname(file_path), exist_ok=True)
with open(file_path, 'w') as f:
json.dump(data, f, indent=None)
modelCache = {}
def get_model(modelPath, logWarnings=logWarnings):
namespace, path = modelPath.split(':') if ':' in modelPath else ('minecraft', modelPath)
if modelPath in modelCache:
return copy.deepcopy(modelCache[modelPath])
file_path = os.path.join(INPUT_DIR, "assets", namespace, "models", f"{path}.json")
if not os.path.exists(file_path):
output_file_path = os.path.join(tempDir, "assets", namespace, "models", f"{path}.json")
if os.path.exists(output_file_path):
with open(output_file_path, 'r') as f:
model = json.load(f)
modelCache[modelPath] = model
return copy.deepcopy(model)
if logWarnings:
print(f"Warning: model {modelPath} ('{file_path}') does not exist, skipping.")
return None
with open(file_path, 'r') as f:
model = json.load(f)
modelCache[modelPath] = model
return copy.deepcopy(model)
def save_model(modelPath, model):
namespace, path = modelPath.split(':') if ':' in modelPath else ('minecraft', modelPath)
asset_path = f"{namespace}:models/{path}"
save_asset(f"{asset_path}.json", model)
def texture_ever_exists(texturePath):
namespace, path = texturePath.split(':') if ':' in texturePath else ('minecraft', texturePath)
name = path.split('/')[-1] if '/' in path else path
path = path.rsplit('/', 1)[0] if '/' in path else ''
file_path = os.path.join(INPUT_DIR, "assets", namespace, "textures", path)
if os.path.exists(os.path.join(file_path, f"{name}.png")):
return True
for _, _, files in os.walk(file_path):
if f"{name}.png" in files:
return True
return False
def find_texture(texturePath):
namespace, path = texturePath.split(':') if ':' in texturePath else ('minecraft', texturePath)
name = path.split('/')[-1] if '/' in path else path
path = path.rsplit('/', 1)[0] if '/' in path else ''
# Check the expected location under textures/<path>
textures_dir = os.path.join(INPUT_DIR, "assets", namespace, "textures", path)
if os.path.exists(os.path.join(textures_dir, f"{name}.png")):
# Return resource path relative to the textures folder (no 'textures/' prefix)
rel = os.path.join(path, name).replace(os.sep, '/') if path else name
return f"{namespace}:{rel}"
# If not found at the expected location, search the whole textures folder for the file
search_root = os.path.join(INPUT_DIR, "assets", namespace, "textures")
for root, _, files in os.walk(search_root):
if f"{name}.png" in files:
rel_path = os.path.relpath(root, search_root)
rel = os.path.join(rel_path, name).replace(os.sep, '/') if rel_path != '.' else name
return f"{namespace}:{rel}"
return None
def save_item_definition(itemPath, itemDef):
namespace, itemId = itemPath.split(':') if ':' in itemPath else ('minecraft', itemPath)
save_asset(f"{namespace}:items/{itemId}.json", itemDef)
def create_block_model_variant(name, variant, displayType):
if "uvlock" in variant or "weight" in variant:
if logWarnings:
print(f"Warning: Block variant {name} contains uvlock or weight, which are not supported, skipping.")
return None
modelPath = variant["model"]
model = get_model(modelPath, False)
if model is None:
namespace, path = modelPath.split(':') if ':' in modelPath else ('minecraft', modelPath)
if texture_ever_exists(f"{namespace}:{path}"):
texturePath = find_texture(f"{namespace}:{path}")
modelPath = f"{namespace}:{path}"
model = {
"parent": "block/cube_all",
"textures": {
"all": texturePath,
"particle": texturePath
},
"display": {
"fixed": {}
}
}
if "author" in variant:
model["author"] = variant["author"]
save_model(modelPath, model)
else:
if logWarnings:
print(f"Warning: Block variant {name} root model {modelPath} could not be found, skipping.")
return None
if "x" in variant or "y" in variant or "z" in variant:
if "x" in variant:
x_rot = variant["x"] % 360
modelPath += f"_x{x_rot}"
if "y" in variant:
y_rot = variant["y"] % 360
modelPath += f"_y{y_rot}"
if "z" in variant:
z_rot = variant["z"] % 360
modelPath += f"_z{z_rot}"
if not get_model(modelPath, False) is None:
return modelPath # already exists
display = model["display"] if "display" in model else {}
fixed_display = display[displayType] if displayType in display else {}
fixed_rotation = fixed_display["rotation"] if "rotation" in fixed_display else [0, 0, 0]
if "x" in variant:
x_rot = variant["x"] % 360
fixed_rotation[0] = (fixed_rotation[0] + x_rot) % 360
if "y" in variant:
y_rot = variant["y"] % 360
fixed_rotation[1] = (fixed_rotation[1] + y_rot) % 360
if "z" in variant:
z_rot = variant["z"] % 360
fixed_rotation[2] = (fixed_rotation[2] + z_rot) % 360
fixed_display["rotation"] = fixed_rotation
display[displayType] = fixed_display
model["display"] = display
save_model(modelPath, model)
else:
save_model(modelPath, model)
return modelPath
## First copy over all non block/item definitions (as these are only used to generate actual assets, they are not directly assets themselves):
for namespace in os.listdir(os.path.join(INPUT_DIR, "assets")):
namespacePath = os.path.join(INPUT_DIR, "assets", namespace)
if not os.path.isdir(namespacePath):
continue
for root, dirs, files in os.walk(namespacePath):
for file in files:
relDir = os.path.relpath(root, namespacePath)
relFile = os.path.join(relDir, file) if relDir != '.' else file
relFile = relFile.replace("\\", "/")
if relFile.startswith("blocks/") or relFile.startswith("items/"):
continue
inputFilePath = os.path.join(root, file)
outputFilePath = os.path.join(tempDir, "assets", namespace, relFile)
os.makedirs(os.path.dirname(outputFilePath), exist_ok=True)
shutil.copyfile(inputFilePath, outputFilePath)
for file in os.listdir(INPUT_DIR):
inputFilePath = os.path.join(INPUT_DIR, file)
if os.path.isfile(inputFilePath) and file != "assets" and file != "settings.json":
outputFilePath = os.path.join(tempDir, file)
if file == "pack.mcmeta":
with open(inputFilePath, 'r', encoding='utf-8') as f:
contents = f.read()
contents = contents.replace("{version}", str(settings.get("version", "")))
with open(outputFilePath, 'w', encoding='utf-8', newline='\n') as f:
f.write(contents)
else:
shutil.copyfile(inputFilePath, outputFilePath)
## Generate from blockstate files:
for namespace in os.listdir(os.path.join(INPUT_DIR, "assets")):
namespacePath = os.path.join(INPUT_DIR, "assets", namespace)
if not os.path.isdir(namespacePath):
continue
blocksPath = os.path.join(namespacePath, "blocks")
if not os.path.exists(blocksPath):
continue
blockStates = []
for root, dirs, files in os.walk(blocksPath):
for file in files:
relDir = os.path.relpath(root, blocksPath)
relFile = os.path.join(relDir, file) if relDir != '.' else file
relFile = relFile.replace("\\", "/")
if os.path.isfile(os.path.join(root, file)):
blockStates.append(relFile)
for blockFile in blockStates:
if not blockFile.endswith(".json"):
if logWarnings:
print(f"Warning: Block file {blockFile} is not a json file, skipping.")
continue
blockFilePath = os.path.join(blocksPath, blockFile)
with open(blockFilePath, 'r') as f:
blockData = json.load(f)
if "multipart" in blockData:
if logWarnings:
print(f"Warning: Block file {blockFilePath} contains multipart definitions, which are not yet supported, skipping.")
continue
if "variants" in blockData and (not isinstance(blockData["variants"], dict) or len(blockData["variants"]) == 0):
if logWarnings:
print(f"Warning: Block file {blockFilePath} does not contain valid variants, skipping.")
continue
variants = blockData["variants"] if "variants" in blockData else {}
if len(variants) > 1 and ("properties" not in blockData or not isinstance(blockData["properties"], list)):
if logWarnings:
print(f"Warning: Block file {blockFilePath} does not contain a list of possible properties, skipping.")
continue
allPropertyKeys = blockData["properties"] if "properties" in blockData else []
allPropertyValues = {}
for key in allPropertyKeys:
allPropertyValues[key] = []
blockPath = blockFile[:-5]
blockName = blockPath.split('/')[-1] if '/' in blockPath else blockPath
blockNamespace = namespace
blockId = blockName
if "id" in blockData:
blockId = blockData["id"]
if "namespace" in blockData:
blockNamespace = blockData["namespace"]
blockKey = f"{blockNamespace}:{blockId}"
blockModel = {}
blockModelDefinition = {
"vanilla": blockData["vanilla"] if "vanilla" in blockData else "air",
"case": {
"when": blockKey
}
}
cases = []
displayType = blockData["display"] if "display" in blockData else "fixed"
if (variants == {}) :
modelPath = f"{namespace}:block/{blockName}"
if (get_model(modelPath, False) is not None):
model = get_model(modelPath, False)
else:
modelPath = f"{namespace}:block/{blockPath}"
model = get_model(modelPath, False)
if model is None:
if texture_ever_exists(f"{namespace}:block/{blockName}"):
texturePath = find_texture(f"{namespace}:block/{blockName}")
modelPath = texturePath
model = {
"parent": "block/cube_all",
"textures": {
"all": texturePath,
"particle": texturePath
},
"display": {
"fixed": {}
}
}
if "author" in blockData:
model["author"] = blockData["author"]
save_model(modelPath, model)
else:
if logWarnings:
print(f"Warning: Block file {blockFilePath} does not contain any variants and no model or texture to generate a model could be found for it, skipping.")
continue
variants[""] = {
"model": modelPath
}
for name, variant in variants.items():
if "model" not in variant:
if logWarnings:
print(f"Warning: Block variant {name} does not contain a model, skipping.")
continue
if "author" in blockData:
variant["author"] = blockData["author"]
properties = {}
for prop in name.split(','):
if '=' not in prop:
if name != "" and logWarnings:
print(f"Warning: Block variant {name} contains invalid property {prop}, skipping.")
continue
key, value = prop.split('=')
properties[key] = value
if key not in allPropertyKeys:
if logWarnings:
print(f"Warning: Block variant {name} contains property {key} which is not in the block's property list, ignoring it.")
if value not in allPropertyValues[key]:
allPropertyValues[key].append(value)
modelPath = create_block_model_variant(name, variant, displayType)
if modelPath is None:
continue
cases.append({
"properties": properties,
"model": modelPath
})
def build_select_from_cases(cases_list, propertyKeys, index=0):
if index >= len(propertyKeys):
return None
key = propertyKeys[index]
select = {
"type": "minecraft:select",
"property": "custom_model_data",
"index": index + 1, # plus one because the first index is the block model id itself
"cases": []
}
groups = {}
for case in cases_list:
value = case["properties"].get(key, None)
if value is None:
if logWarnings:
print(f"Warning: Case {case} does not contain property {key}, skipping.")
continue
groups.setdefault(value, []).append(case)
for value, group in groups.items():
if index == len(propertyKeys) - 1:
models = {c["model"] for c in group}
if len(models) > 1:
if logWarnings:
print(f"Warning: Multiple models for property {key}={value} at leaf, using first.")
model_choice = next(iter(models))
case_entry = {
"when": f"{key}={value}",
"model": {
"type": "minecraft:model",
"model": model_choice
}
}
else:
sub_select = build_select_from_cases(group, propertyKeys, index + 1)
if sub_select is None:
continue
case_entry = {
"when": f"{key}={value}",
"model": sub_select
}
select["cases"].append(case_entry)
return select if select["cases"] else None
if len(cases) == 1 and (not cases[0].get("properties")):
blockModel = {
"type": "minecraft:model",
"model": cases[0]["model"]
}
else:
blockModel = build_select_from_cases(cases, allPropertyKeys, 0)
blockModelDefinition["case"]["model"] = blockModel
blockModelDefinitions.append(blockModelDefinition)
## Append the block model cases to the vanilla item model definitions
# uses the select model type against the 0 index of custom_model_data
for modelDef in blockModelDefinitions:
vanillaItem = modelDef["vanilla"]
if not ":" in vanillaItem:
vanillaItem = f"minecraft:{vanillaItem}"
vanillaDefinition = itemModelDefinitions[vanillaItem] if vanillaItem in itemModelDefinitions else {
"model": {
"type": "minecraft:select",
"property": "custom_model_data",
"index": 0,
"cases": []
}
}
vanillaDefinition["model"]["cases"].append(modelDef["case"])
itemModelDefinitions[vanillaItem] = vanillaDefinition
## Now handle item definition files:
# First compile all of the different cases
for namespace in os.listdir(os.path.join(INPUT_DIR, "assets")):
namespacePath = os.path.join(INPUT_DIR, "assets", namespace)
if not os.path.isdir(namespacePath):
continue
itemsPath = os.path.join(namespacePath, "items")
if not os.path.exists(itemsPath):
continue
itemFiles = []
for root, dirs, files in os.walk(itemsPath):
for file in files:
relDir = os.path.relpath(root, itemsPath)
relFile = os.path.join(relDir, file) if relDir != '.' else file
relFile = relFile.replace("\\", "/")
if os.path.isfile(os.path.join(root, file)):
itemFiles.append(relFile)
for itemFile in itemFiles:
if not itemFile.endswith(".json"):
if logWarnings:
print(f"Warning: Item file {itemFile} is not a json file, skipping.")
continue
itemFilePath = os.path.join(itemsPath, itemFile)
with open(itemFilePath, 'r') as f:
itemData = json.load(f)
itemPath = itemFile[:-5]
itemName = itemPath.split('/')[-1] if '/' in itemPath else itemPath
itemNamespace = namespace
itemId = itemName
if "id" in itemData:
itemId = itemData["id"]
if "namespace" in itemData:
itemNamespace = itemData["namespace"]
itemKey = f"{itemNamespace}:{itemId}"
if "vanilla" not in itemData or not isinstance(itemData["vanilla"], str):
if logWarnings:
print(f"Warning: Item file {itemFilePath} does not contain a valid vanilla item id, skipping.")
continue
vanillaItem = itemData["vanilla"]
if not ":" in vanillaItem:
vanillaItem = f"minecraft:{vanillaItem}"
vanillaDefinition = itemModelDefinitions[vanillaItem] if vanillaItem in itemModelDefinitions else {
"model": {
"type": "minecraft:select",
"property": "custom_model_data",
"index": 0,
"cases": []
}
}
vanillaCases = vanillaDefinition["model"]["cases"] if "cases" in vanillaDefinition["model"] else []
if "fallback" in itemData:
if "fallback" in vanillaDefinition:
if logWarnings:
print(f"Warning: Item file {itemFilePath} contains a fallback but one is already defined for {vanillaItem}, overwriting fallback {vanillaDefinition['fallback']}.")
vanillaDefinition["fallback"] = itemData["fallback"]
if "oversized_in_gui" in itemData:
if itemData["oversized_in_gui"] != True:
if logWarnings:
print(f"Warning: Item file {itemFilePath} contains invalid oversized_in_gui value (should only ever be 'true'), skipping.")
continue
vanillaDefinition["oversized_in_gui"] = True
case = None
if "model" in itemData:
model = itemData["model"]
if isinstance(model, dict):
# TODO: validate model definition somehow
case = {
"when": f"{itemKey}",
"model": model
}
elif isinstance(model, str):
get_model(model, True)
case = {
"when": f"{itemKey}",
"model": {
"type": "minecraft:model",
"model": model
}
}
else:
if logWarnings:
print(f"Warning: Item file {itemFilePath} contains invalid model value (should be a full definition or inlined model reference), skipping.")
continue
else:
modelPath = f"{namespace}:item/{itemName}"
if (get_model(modelPath, False) is not None):
model = get_model(modelPath, False)
else:
modelPath = f"{namespace}:item/{itemPath}"
model = get_model(modelPath, False)
if model is None:
modelPath = f"{namespace}:block/{itemName}"
if (get_model(modelPath, False) is not None):
model = get_model(modelPath, False)
else:
modelPath = f"{namespace}:block/{itemPath}"
model = get_model(modelPath, False)
if model is not None:
if "display" in model and "fixed" in model["display"]:
model["display"]["fixed"] = {
"scale": [0.5, 0.5, 0.5]
}
modelPath = f"{namespace}:item/{itemPath}"
save_model(modelPath, model)
case = {
"when": f"{itemKey}",
"model": {
"type": "minecraft:model",
"model": modelPath
}
}
elif texture_ever_exists(f"{namespace}:item/{itemName}"):
texturePath = find_texture(f"{namespace}:item/{itemName}")
modelPath = texturePath
model = {
"parent": "item/generated",
"textures": {
"layer0": texturePath,
"particle": texturePath
}
}
if "author" in itemData:
model["author"] = itemData["author"]
save_model(modelPath, model)
case = {
"when": f"{itemKey}",
"model": {
"type": "minecraft:model",
"model": modelPath
}
}
elif texture_ever_exists(f"{namespace}:block/{itemName}"):
texturePath = find_texture(f"{namespace}:block/{itemName}")
modelPath = texturePath
model = {
"parent": "block/cube_all",
"textures": {
"all": texturePath
}
}
if "author" in itemData:
model["author"] = itemData["author"]
save_model(modelPath, model)
case = {
"when": f"{itemKey}",
"model": {
"type": "minecraft:model",
"model": modelPath
}
}
else:
if logWarnings:
print(f"Warning: Item file {itemFilePath} does not contain a model and no model or texture to generate a model could be found for it, skipping.")
continue
else:
case = {
"when": f"{itemKey}",
"model": {
"type": "minecraft:model",
"model": modelPath
}
}
if "tints" in itemData:
tints = itemData["tints"]
if not isinstance(tints, list) or len(tints) == 0:
if logWarnings:
print(f"Warning: Item file {itemFilePath} contains invalid tints value (should be a non-empty list), skipping.")
continue
elif not case["model"]["type"] == "minecraft:model":
if logWarnings:
print(f"Warning: Item file {itemFilePath} contains tints but its model type is not 'minecraft:model', skipping.")
continue
else:
case["model"]["tints"] = tints
if "create_trims" in itemData:
trimType = itemData["create_trims"]
if trimType not in TRIM_TYPES:
if logWarnings:
print(f"Warning: Item file {itemFilePath} contains invalid trimmable type {trimType} (must be one of {TRIM_TYPES}), skipping.")
continue
elif case["model"]["type"] != "minecraft:model":
if logWarnings:
print(f"Warning: Item file {itemFilePath} contains trimmable value but its model type is not 'minecraft:model', skipping.")
continue
modelPath = case["model"]["model"]
model = get_model(modelPath)
if model is None:
if logWarnings:
print(f"Warning: Item file {itemFilePath} trimmable model {modelPath} could not be found, skipping.")
continue
elif "parent" not in model or model["parent"] != "item/generated":
if logWarnings:
print(f"For automatic trims, item model {modelPath} must have parent 'item/generated', skipping.")
continue
trimCases = []
case = {
"when": f"{itemKey}",
"model": {
"type": "minecraft:select",
"property": "trim_material",
"cases": trimCases,
"fallback": case["model"]
}
}
for trim in TRIMS:
trimModelPath = f"{modelPath}_trim_{trim}"
trimModel = copy.deepcopy(model)
particleLayer = None
if "particle" in trimModel["textures"]:
particleLayer = trimModel["textures"].pop("particle")
trimModel["textures"][f"layer{len(trimModel['textures'])}"] = f"trims/items/{trimType}_trim_{trim}"
if particleLayer is not None:
trimModel["textures"]["particle"] = particleLayer
save_model(trimModelPath, trimModel)
trimCases.append({
"when": trim,
"model": {
"type": "minecraft:model",
"model": trimModelPath
}
})
vanillaCases.append(case)
vanillaDefinition["model"]["cases"] = vanillaCases
itemModelDefinitions[vanillaItem] = vanillaDefinition
# Then create each item definition
for itemPath, itemDef in itemModelDefinitions.items():
namespace, itemName = itemPath.split(':') if ':' in itemPath else ('minecraft', itemPath)
if "fallback" not in itemDef["model"]:
template = get_template(f"items/{itemName}")
if template is None:
template = {"model": {"type": "minecraft:model", "model": f"minecraft:item/{itemName}"} }
itemDef["model"]["fallback"] = template["model"]
save_item_definition(itemPath, itemDef)
# Add the atlas appends
itemAtlasSources = []
blockAtlasSources = []
# find all textures under assets/<namespace>/textures/item and assets/<namespace>/textures/block
for namespace in os.listdir(os.path.join(INPUT_DIR, "assets")):
namespacePath = os.path.join(INPUT_DIR, "assets", namespace)
if not os.path.isdir(namespacePath):
continue
texturesPath = os.path.join(namespacePath, "textures")
if not os.path.exists(texturesPath):
continue
for root, dirs, files in os.walk(texturesPath):
for file in files:
relDir = os.path.relpath(root, texturesPath)
relFile = os.path.join(relDir, file) if relDir != '.' else file
relFile = relFile.replace("\\", "/")
if not file.endswith(".png"):
continue
if relFile.startswith("item/"):
itemAtlasSources.append({
"type": "single",
"resource": f"{namespace}:{relFile[:-4]}"
})
elif relFile.startswith("block/"):
blockAtlasSources.append({
"type": "single",
"resource": f"{namespace}:{relFile[:-4]}"
})
save_asset("minecraft:atlases/items.json", {
"sources": itemAtlasSources
})
save_asset("minecraft:atlases/blocks.json", {
"sources": blockAtlasSources
})
# output logic:
if os.path.exists(outputPath):
if logWarnings:
print(f"Warning: Output file {outputPath} already exists, overwriting.")
os.remove(outputPath)
with zipfile.ZipFile(outputPath, 'w', zipfile.ZIP_DEFLATED) as zf:
for root, dirs, files in os.walk(tempDir):
for file in files:
filePath = os.path.join(root, file)
arcname = os.path.relpath(filePath, tempDir)
zf.write(filePath, arcname)
print(f"Resource pack '{settings['name']}' version {settings['version']} generated at '{outputPath}'.")
# clean up temp files
if os.path.exists(tempDir) and deleteTemp:
for root, dirs, files in os.walk(tempDir, topdown=False):
for name in files:
os.remove(os.path.join(root, name))
for name in dirs:
os.rmdir(os.path.join(root, name))
os.rmdir(tempDir)
# clean up template/items files (leave items.zip)
if os.path.exists(os.path.join(TEMPLATE_DIR, "items")):
for root, dirs, files in os.walk(os.path.join(TEMPLATE_DIR, "items"), topdown=False):
for name in files:
if name != "items.zip":
os.remove(os.path.join(root, name))
for name in dirs:
os.rmdir(os.path.join(root, name))