-
Notifications
You must be signed in to change notification settings - Fork 1
/
scmodels.py
1251 lines (1021 loc) · 38.5 KB
/
scmodels.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
# sudo apt install libglew-dev libosmesa-dev pngcrush
import sys, os, shutil, collections, json, subprocess, stat, hashlib, traceback, time
from datetime import datetime
from glob import glob
from io import StringIO
# TODO:
# - some models I added _v2 to are actually a completely different model
# - delete all thumbs.db and .ztmp
# - add to alias when renaming
master_json = {}
master_json_name = 'database/models.json'
hash_json_name = 'database/hashes.json'
replacements_json_name = 'database/replacements.json'
alias_json_name = 'database/alias.json'
versions_json_name = 'database/versions.json'
tags_json_name = 'database/tags.json'
groups_json_name = 'database/groups.json'
start_dir = os.getcwd()
models_path = 'models/player/'
install_path = 'install/'
hlms_path = os.path.join(start_dir, 'hlms')
modelguy_path = os.path.join(start_dir, 'modelguy')
posterizer_path = '/home/pi/mediancut-posterizer/posterize'
pngcrush_path = 'pngcrush'
magick_path = 'convert'
debug_render = False
FL_CRASH_MODEL = 1 # model that crashes the game or model viewer
# assumes chdir'd to the model directory beforehand
def fix_case_sensitivity_problems(model_dir, expected_model_path, expected_bmp_path, work_path):
global start_dir
global models_path
all_files = [file for file in os.listdir('.') if os.path.isfile(file)]
icase_model = ''
icase_preview = ''
for file in all_files:
if (file.lower() == expected_model_path.lower()):
icase_model = file
if (file.lower() == expected_bmp_path.lower()):
icase_preview = file
icase_model_original = icase_model
icase_preview_original = icase_preview
icase_model = os.path.splitext(icase_model)[0]
icase_preview = os.path.splitext(icase_preview)[0]
if (icase_model and icase_model != model_dir) or \
(icase_preview and icase_preview != model_dir) or \
(icase_model and icase_preview and icase_model != icase_preview):
print("\nFound case-sensitive differences:\n")
print("DIR (1): " + model_dir)
print("MDL (2): " + icase_model)
print("BMP (3): " + icase_preview)
while True:
x = input("\nWhich capitalization should be used? (enter 1, 2, or 3) ")
correct_name = model_dir
if x == '1':
correct_name = model_dir
elif x == '2':
correct_name = icase_model
elif x == '3':
correct_name = icase_preview
else:
continue
rename_model(model_dir, correct_name, work_path)
return correct_name
return model_dir
def get_sorted_dirs(path):
all_dirs = [dir for dir in os.listdir(path) if os.path.isdir(os.path.join(path,dir))]
return sorted(all_dirs, key=str.casefold)
def get_model_modified_date(mdl_name, work_path):
mdl_path = os.path.join(work_path, mdl_name, mdl_name + ".mdl")
return int(os.path.getmtime(mdl_path))
def rename_model(old_dir_name, new_name, work_path):
global master_json
global master_json_name
global start_dir
os.chdir(start_dir)
old_dir = os.path.join(work_path, old_dir_name)
new_dir = os.path.join(work_path, new_name)
if not os.path.isdir(old_dir):
print("Can't rename '%s' because that dir doesn't exist" % old_dir)
return False
if (old_dir_name != new_name and os.path.exists(new_dir)):
print("Can't rename folder to %s. That already exists." % new_dir)
return False
if old_dir != new_dir:
os.rename(old_dir, new_dir)
print("Renamed %s -> %s" % (old_dir, new_dir))
os.chdir(new_dir)
all_files = [file for file in os.listdir('.') if os.path.isfile(file)]
mdl_files = []
tmdl_files = []
bmp_files = []
png_files = []
json_files = []
for file in all_files:
if ".mdl" in file.lower():
mdl_files.append(file)
#if ".mdl" in file.lower() and (file == old_dir_name + "t.mdl" or file == old_dir_name + "T.mdl"):
# tmdl_files.append(file)
if ".bmp" in file.lower():
bmp_files.append(file)
if '_large.png' in file.lower() or '_small.png' in file.lower() or '_tiny.png' in file.lower():
png_files.append(file)
if ".json" in file.lower():
json_files.append(file)
if len(mdl_files) > 1:
print("Multiple mdl files to rename. Don't know what to do")
sys.exit()
return False
if len(tmdl_files) > 1:
print("Multiple T mdl files to rename. Don't know what to do")
sys.exit()
return False
if len(bmp_files) > 1:
print("Multiple bmp files to rename. Don't know what to do")
sys.exit()
return False
if len(json_files) > 1:
print("Multiple json files to rename. Don't know what to do")
sys.exit()
return False
if len(png_files) > 3:
print("Too many PNG files found. Don't know what to do")
sys.exit()
return False
def rename_file(file_list, new_name, ext):
if len(file_list) > 0:
old_file_name = file_list[0]
new_file_name = new_name + ext
if old_file_name != new_file_name:
os.rename(old_file_name, new_file_name)
print("Renamed %s -> %s" % (old_file_name, new_file_name))
rename_file(bmp_files, new_name, '.bmp')
rename_file(mdl_files, new_name, '.mdl')
rename_file(tmdl_files, new_name, 't.mdl')
rename_file(json_files, new_name, '.json')
for png_file in png_files:
old_file_name = png_file
new_file_name = ''
if '_large' in old_file_name:
new_file_name = new_name + "_large.png"
elif '_small' in old_file_name:
new_file_name = new_name + "_small.png"
elif '_tiny' in old_file_name:
new_file_name = new_name + "_tiny.png"
if old_file_name != new_file_name:
os.rename(old_file_name, new_file_name)
print("Renamed %s -> %s" % (old_file_name, new_file_name))
return True
def handle_renamed_model(model_dir, work_path):
all_files = [file for file in os.listdir('.') if os.path.isfile(file)]
model_files = []
for file in all_files:
if '.mdl' in file.lower():
model_files.append(file)
while len(model_files) >= 1:
print("\nThe model file(s) in this folder do not match the folder name:\n")
print("0) " + model_dir)
for idx, file in enumerate(model_files):
print("%s) %s" % (idx+1, file))
print("r) Enter a new name")
print("d) Delete this model")
x = input("\nWhich model should be used? ")
if x == 'd':
os.chdir(start_dir)
shutil.rmtree(os.path.join(work_path, model_dir))
return ''
elif x == '0':
if (not rename_model(model_dir, model_dir, work_path)):
continue
return model_dir
elif x == 'r':
x = input("What should the model name be? ")
if (not rename_model(model_dir, x, work_path)):
continue
return x
elif x.isnumeric():
x = int(x) - 1
if x < 0 or x >= len(model_files):
continue
correct_name = os.path.splitext(model_files[idx-1])[0]
if (not rename_model(model_dir, correct_name, work_path)):
continue
return correct_name
else:
continue
return model_dir
else:
while True:
x = input("\nNo models exist in this folder! Delete it? (y/n) ")
if x == 'y':
os.chdir(start_dir)
shutil.rmtree(os.path.join(work_path, model_dir))
break
if x == 'n':
break
return model_dir
def get_lowest_polycount():
global hlms_path
global models_path
global start_dir
all_dirs = get_sorted_dirs(models_path)
total_dirs = len(all_dirs)
lowest_count = 99999
for idx, dir in enumerate(all_dirs):
model_name = dir
json_path = model_name + ".json"
os.chdir(start_dir)
os.chdir(os.path.join(models_path, dir))
if os.path.exists(json_path):
with open(json_path) as f:
json_dat = f.read()
dat = json.loads(json_dat, object_pairs_hook=collections.OrderedDict)
tri_count = int(dat['tri_count'])
if tri_count < 300 and tri_count >= 0:
#print("%s = %s" % (model_name, tri_count))
print(model_name)
def check_for_broken_models():
global hlms_path
global models_path
global start_dir
all_dirs = get_sorted_dirs(models_path)
total_dirs = len(all_dirs)
for idx, dir in enumerate(all_dirs):
model_name = dir
mdl_path = model_name + ".mdl"
os.chdir(start_dir)
os.chdir(os.path.join(models_path, dir))
if os.path.isfile(mdl_path):
try:
args = [hlms_path, './' + mdl_path]
output = subprocess.check_output(args)
except Exception as e:
output = e
print(e)
print("Bad model: %s" % model_name)
else:
print("Missing model: %s" % model_name)
def generate_info_json(model_name, mdl_path, output_path):
data = {}
output = ''
if os.path.exists(output_path):
os.remove(output_path)
try:
args = [modelguy_path, 'info', mdl_path, output_path]
output = subprocess.check_output(args)
except Exception as e:
output = e
print(e)
def update_models(work_path, skip_existing=True, skip_on_error=False, errors_only=True, info_only=False, update_master_json=False):
global master_json
global master_json_name
global hash_json_name
global magick_path
global pngcrush_path
global posterizer_path
global hlms_path
global start_dir
all_dirs = get_sorted_dirs(work_path)
total_dirs = len(all_dirs)
list_file = None
if update_master_json:
list_file = open("database/model_names.txt","w")
failed_models = []
longname_models = []
hash_json = {}
for idx, dir in enumerate(all_dirs):
model_name = dir
print("IDX: %s / %s: %s " % (idx, total_dirs-1, model_name), end='\r')
#garg.mdl build/asdf 1000x1600 0 1 1
if len(dir) > 22:
longname_models.append(dir)
os.chdir(start_dir)
os.chdir(os.path.join(work_path, dir))
mdl_path = model_name + ".mdl"
bmp_path = model_name + ".bmp"
if not os.path.isfile(mdl_path) or not os.path.isfile(bmp_path):
if not skip_on_error:
model_name = dir = fix_case_sensitivity_problems(dir, mdl_path, bmp_path, work_path)
mdl_path = model_name + ".mdl"
bmp_path = model_name + ".bmp"
if not os.path.isfile(mdl_path):
model_name = dir = handle_renamed_model(dir, work_path)
mdl_path = model_name + ".mdl"
bmp_path = model_name + ".bmp"
if not os.path.isfile(mdl_path):
continue
if errors_only:
continue
mdl_path = model_name + ".mdl"
bmp_path = model_name + ".bmp"
render_path = model_name + "000.png"
sequence = "0"
frames = "1"
loops = "1"
info_json_path = model_name + ".json"
tiny_thumb = model_name + "_tiny.png"
small_thumb = model_name + "_small.png"
large_thumb = model_name + "_large.png"
thumbnails_generated = os.path.isfile(tiny_thumb) and os.path.isfile(small_thumb) and os.path.isfile(large_thumb)
anything_updated = False
broken_model = False
try:
if (not os.path.isfile(info_json_path) or not skip_existing):
print("\nGenerating info json...")
anything_updated = True
generate_info_json(model_name, mdl_path, info_json_path)
else:
pass #print("Info json already generated")
if ((not thumbnails_generated or not skip_existing) and not info_only):
print("\nRendering hi-rez image...")
anything_updated = True
with open(os.devnull, 'w') as devnull:
args = [hlms_path, mdl_path, model_name, "1000x1600", sequence, frames, loops]
null_stdout=None if debug_render else devnull
subprocess.check_call(args, stdout=null_stdout)
def create_thumbnail(name, size, posterize_colors):
print("Creating %s thumbnail..." % name)
temp_path = "./%s_%s_temp.png" % (model_name, name)
final_path = "./%s_%s.png" % (model_name, name)
subprocess.check_call([magick_path, "./" + render_path, "-resize", size, temp_path], stdout=null_stdout)
subprocess.check_call([posterizer_path, posterize_colors, temp_path, final_path], stdout=null_stdout)
subprocess.check_call([pngcrush_path, "-ow", "-s", final_path], stdout=null_stdout)
os.remove(temp_path)
create_thumbnail("large", "500x800", "255")
create_thumbnail("small", "125x200", "16")
create_thumbnail("tiny", "20x32", "8")
os.remove(render_path)
else:
pass #print("Thumbnails already generated")
except Exception as e:
print(e)
traceback.print_exc()
failed_models.append(model_name)
broken_model = True
anything_updated = False
if not skip_on_error:
sys.exit()
if update_master_json:
list_file.write("%s\n" % model_name)
if update_master_json:
filter_dat = {}
if os.path.isfile(info_json_path):
with open(info_json_path) as f:
json_dat = f.read()
infoJson = json.loads(json_dat, object_pairs_hook=collections.OrderedDict)
totalPolys = 0
totalPolysLd = 0
hasLdModel = False
for body in infoJson["bodies"]:
models = body["models"]
polys = int(models[0]["polys"])
if len(models) > 1:
hasLdModel = True
totalPolysLd += polys
polys = int(models[len(models)-1]["polys"])
totalPolys += polys
else:
totalPolys += polys
filter_dat['polys'] = totalPolys
#filter_dat['polys_ld'] = totalPolysLd
filter_dat['size'] = infoJson["size"]
flags = 0
if broken_model:
flags |= FL_CRASH_MODEL
filter_dat['flags'] = flags
hash = infoJson['md5']
if hash not in hash_json:
hash_json[hash] = [model_name]
else:
hash_json[hash].append(model_name)
master_json[model_name] = filter_dat
os.chdir(start_dir)
if update_master_json:
with open(master_json_name, 'w') as outfile:
json.dump(master_json, outfile)
with open(hash_json_name, 'w') as outfile:
json.dump(hash_json, outfile)
list_file.close()
print("\nFinished!")
if len(failed_models):
print("\nFailed to update these models:")
for fail in failed_models:
print(fail)
if len(longname_models):
print("\nThe following models have names longer than 22 characters and should be renamed:")
for fail in longname_models:
print(fail)
def write_updated_models_list():
global models_path
global master_json_name
oldJson = {}
if os.path.exists(master_json_name):
with open(master_json_name) as f:
json_dat = f.read()
oldJson = json.loads(json_dat, object_pairs_hook=collections.OrderedDict)
all_dirs = get_sorted_dirs(models_path)
list_file = open("updated.txt","w")
for idx, dir in enumerate(all_dirs):
if dir not in oldJson:
list_file.write("%s\n" % dir)
list_file.close()
def validate_model_isolated():
boxId = 1 # TODO: unique id per request
fileSizeQuota = '--fsize=8192' # max written/modified file size in KB
processMax = '--processes=1'
maxTime = '--time=60'
modelName = 'white.mdl'
print("Cleaning up")
try:
args = ['isolate', '--box-id=%d' % boxId, '--cleanup']
output = subprocess.check_output(args)
except Exception as e:
print(e)
print(output)
print("Initializing isolate")
output = ''
try:
args = ['isolate', '--box-id=%d' % boxId, '--init']
print(' '.join(args))
output = subprocess.check_output(args)
except Exception as e:
print(e)
print(output)
return False
output = output.decode('utf-8').replace("\n", '')
boxPath = os.path.join(output, "box")
hlmsPath = os.path.join(boxPath, "hlms")
print("Isolate path: %s" % boxPath)
print("Copying files")
shutil.copyfile(modelName, os.path.join(boxPath, modelName))
shutil.copyfile('hlms', os.path.join(boxPath, 'hlms'))
os.chmod(os.path.join(boxPath, 'hlms'), stat.S_IRWXU)
success = False
print("Running hlms")
output = ''
try:
args = ['isolate', fileSizeQuota, processMax, maxTime, '--box-id=%d' % boxId, '--run', '--', './hlms', modelName, 'asdf', '16x16', '0', '1', '1']
print(' '.join(args))
output = subprocess.check_output(args)
except Exception as e:
print(e)
print(output)
success = False
print("Cleaning up")
try:
args = ['isolate', '--box-id=%d' % boxId, '--cleanup']
output = subprocess.check_output(args)
except Exception as e:
print(e)
print(output)
return success
def create_list_file():
global hlms_path
global models_path
global start_dir
all_dirs = get_sorted_dirs(models_path)
total_dirs = len(all_dirs)
lower_dirs = [dir.lower() for dir in all_dirs]
list_file = open("models.txt","w")
min_replace_polys = 143 # set this to the default LD poly count ("player-10up")
for idx, dir in enumerate(all_dirs):
model_name = dir
json_path = model_name + ".json"
os.chdir(start_dir)
os.chdir(os.path.join(models_path, dir))
if (idx % 100 == 0):
print("Progress: %d / %d" % (idx, len(all_dirs)))
if os.path.exists(json_path):
with open(json_path) as f:
json_dat = f.read()
dat = json.loads(json_dat, object_pairs_hook=collections.OrderedDict)
tri_count = int(dat['tri_count'])
replace_model = '' # blank = use default LD model
if '2d_' + model_name.lower() in lower_dirs:
replace_model = '2d_' + model_name
if tri_count < min_replace_polys:
replace_model = model_name
list_file.write("%s / %d / %s / %s\n" % (model_name.lower(), tri_count, '', replace_model.lower()))
list_file.close()
def hash_md5(model_file, t_model_file):
hash_md5 = hashlib.md5()
with open(model_file, "rb") as f:
for chunk in iter(lambda: f.read(4096), b""):
hash_md5.update(chunk)
if t_model_file:
with open(t_model_file, "rb") as f:
for chunk in iter(lambda: f.read(4096), b""):
hash_md5.update(chunk)
return hash_md5.hexdigest()
def load_all_model_hashes(path):
global start_dir
print("Loading model hashes in path: %s" % path)
all_dirs = get_sorted_dirs(path)
total_dirs = len(all_dirs)
model_hashes = {}
for idx, dir in enumerate(all_dirs):
model_name = dir
json_path = model_name + ".json"
os.chdir(start_dir)
os.chdir(os.path.join(path, dir))
if (idx % 100 == 0):
print("Progress: %d / %d" % (idx, len(all_dirs)), end="\r")
if os.path.exists(json_path):
with open(json_path) as f:
json_dat = f.read()
dat = json.loads(json_dat, object_pairs_hook=collections.OrderedDict)
if 'md5' not in dat:
os.remove(json_path)
print("\nMissing hash for %s. Deleted the json for it." % json_path)
continue
hash = dat['md5']
if hash not in model_hashes:
model_hashes[hash] = [model_name]
else:
model_hashes[hash].append(model_name)
else:
print("\nMissing info JSON for %s" % model_name)
print("Progress: %d / %d" % (len(all_dirs), len(all_dirs)))
os.chdir(start_dir)
return model_hashes
# it takes a long time to load model hashes for thousands of models, so the list of hashes is saved
# in a single file whenever the database is updated. This loads much faster.
def load_cached_model_hashes():
global hash_json_name
with open(hash_json_name) as f:
json_dat = f.read()
return json.loads(json_dat, object_pairs_hook=collections.OrderedDict)
return None
def find_duplicate_models(work_path):
model_hashes = load_all_model_hashes(work_path)
print("\nAll duplicates:")
for hash in model_hashes:
if len(model_hashes[hash]) > 1:
print("%s" % model_hashes[hash])
to_delete = []
for hash in model_hashes:
if len(model_hashes[hash]) > 1:
print("")
for idx, model in enumerate(model_hashes[hash]):
print("%d) %s" % (idx, model))
keepIdx = int(input("Which model to keep (pick a number)?"))
for idx, model in enumerate(model_hashes[hash]):
if idx == keepIdx:
continue
to_delete.append(model)
'''
print("\nDuplicates with %s prefix:" % prefix)
prefix = "bio_"
for hash in model_hashes:
if len(model_hashes[hash]) > 1:
total_rem = 0
for model in model_hashes[hash]:
if model.lower().startswith(prefix):
to_delete.append(model)
total_rem += 1
if total_rem == len(model_hashes[hash]):
print("WOW HOW THAT HAPPEN %s" % model_hashes[hash])
input("Press enter if this is ok")
'''
'''
print("\nDuplicates with the same names:")
for hash in model_hashes:
if len(model_hashes[hash]) > 1:
same_names = True
first_name = model_hashes[hash][0].lower()
for name in model_hashes[hash]:
if name.lower() != first_name:
same_names = False
break
if not same_names:
continue
print("%s" % model_hashes[hash])
to_delete += model_hashes[hash][1:]
'''
all_dirs = get_sorted_dirs(work_path)
all_dirs_lower = [dir.lower() for dir in all_dirs]
unique_dirs_lower = sorted(list(set(all_dirs_lower)))
for ldir in unique_dirs_lower:
matches = []
for idx, dir2 in enumerate(all_dirs_lower):
if dir2 == ldir:
matches.append(all_dirs[idx])
if len(matches) > 1:
msg = ', '.join(["%s (%s)" % (dir, get_model_modified_date(dir, work_path)) for dir in matches])
print("Conflicting model names: %s" % msg)
if (len(to_delete) == 0):
print("\nNo duplicates to remove")
return False
print("\nMarked for deletion:")
for dir in to_delete:
print(dir)
input("Press enter to delete the above %s models" % len(to_delete))
os.chdir(start_dir)
for dir in to_delete:
shutil.rmtree(os.path.join(work_path, dir))
return True
def get_latest_version_name(model_name, versions_json):
for vergroup in versions_json:
for veridx in range(0, len(vergroup)):
if vergroup[veridx] == model_name:
return vergroup[0]
return model_name
def fix_json():
global versions_json_name
global tags_json_name
global groups_json_name
global replacements_json_name
versions_json = None
tags_json = None
groups_json = None
replacements_json = None
with open(versions_json_name) as f:
versions_json = json.loads(f.read(), object_pairs_hook=collections.OrderedDict)
with open(tags_json_name) as f:
tags_json = json.loads(f.read(), object_pairs_hook=collections.OrderedDict)
with open(groups_json_name) as f:
groups_json = json.loads(f.read(), object_pairs_hook=collections.OrderedDict)
num_updates = 0
if os.path.exists(replacements_json_name):
print("-- Checking replacements")
new_replacement_json = {}
with open(replacements_json_name) as f:
replacements_json = json.loads(f.read(), object_pairs_hook=collections.OrderedDict)
for key, replacements in replacements_json.items():
print("%s " % (key), end='\r')
for idx in range(0, len(replacements)):
latest_name = get_latest_version_name(replacements[idx], versions_json)
if latest_name != replacements[idx]:
print("%s -> %s " % (replacements[idx], latest_name))
replacements[idx] = latest_name
num_updates += 1
latest_name = get_latest_version_name(key, versions_json)
if latest_name != key:
new_replacement_json[latest_name] = replacements
print("%s -> %s " % (key, latest_name))
num_updates += 1
else:
new_replacement_json[key] = replacements
replacements_json = new_replacement_json
print("-- Checking tags")
for key, group in tags_json.items():
print("%s " % (key), end='\r')
for idx in range(0, len(group)):
latest_name = get_latest_version_name(group[idx], versions_json)
if latest_name != group[idx]:
print("%s -> %s " % (group[idx], latest_name))
group[idx] = latest_name
num_updates += 1
tags_json[key] = sorted(tags_json[key])
print("\n-- Checking groups")
for key, group in groups_json.items():
print("%s " % (key), end='\r')
for idx in range(0, len(group)):
latest_name = get_latest_version_name(group[idx], versions_json)
if latest_name != group[idx]:
print("%s -> %s " % (group[idx], latest_name))
group[idx] = latest_name
num_updates += 1
# don't sort so that most appropraite model can be placed as group thumbnail
#groups_json[key] = sorted(groups_json[key])
with open(tags_json_name, 'w') as outfile:
tags_json = dict(sorted(tags_json.items()))
json.dump(tags_json, outfile, indent=4)
print("Wrote %s " % tags_json_name)
with open(groups_json_name, 'w') as outfile:
groups_json = dict(sorted(groups_json.items()))
json.dump(groups_json, outfile, indent=4)
print("Wrote %s " % groups_json_name)
with open(replacements_json_name, 'w') as outfile:
groups_json = dict(sorted(groups_json.items()))
json.dump(replacements_json, outfile, indent=4)
print("Wrote %s " % replacements_json_name)
print("\nUpdated %d model references to the latest version" % num_updates)
def install_new_models(new_versions_mode=False):
global models_path
global install_path
global alias_json_name
global versions_json_name
global start_dir
new_dirs = get_sorted_dirs(install_path)
if len(new_dirs) == 0:
print("No models found in %s" % install_path)
sys.exit()
alt_names = {}
if os.path.exists(alias_json_name):
with open(alias_json_name) as f:
json_dat = f.read()
alt_names = json.loads(json_dat, object_pairs_hook=collections.OrderedDict)
# First generate info jsons, if needed
print("-- Generating info JSONs for new models")
update_models(install_path, True, True, False, True, False)
print("\n-- Checking for duplicates")
any_dups = False
install_hashes = load_all_model_hashes(install_path)
for hash in install_hashes:
if len(install_hashes[hash]) > 1:
msg = ''
for model in install_hashes[hash]:
msg += ' ' + model
print("ERROR: Duplicate models in install folder:" + msg)
any_dups = True
model_hashes = load_cached_model_hashes()
dups = []
for hash in install_hashes:
if hash in model_hashes:
print("ERROR: %s is a duplicate of %s" % (install_hashes[hash], model_hashes[hash]))
dups += install_hashes[hash]
any_dups = True
primary_name = model_hashes[hash][0].lower()
for alt in install_hashes[hash]:
alt = alt.lower()
if alt == primary_name:
continue
if primary_name not in alt_names:
alt_names[primary_name] = []
if alt not in alt_names[primary_name]:
alt_names[primary_name].append(alt)
with open(alias_json_name, 'w') as outfile:
json.dump(alt_names, outfile, indent=4)
if len(dups) > 0 and input("\nDelete the duplicate models in the install folder? (y/n)") == 'y':
for dup in dups:
path = os.path.join(install_path, dup)
shutil.rmtree(path)
new_dirs = get_sorted_dirs(install_path)
old_dirs = [dir for dir in os.listdir(models_path) if os.path.isdir(os.path.join(models_path,dir))]
old_dirs_lower = [dir.lower() for dir in old_dirs]
alt_name_risk = False
for dir in new_dirs:
lowernew = dir.lower()
is_unique_name = True
for idx, old in enumerate(old_dirs):
if lowernew == old.lower():
if new_versions_mode:
is_unique_name = False
else:
print("ERROR: %s already exists" % old)
any_dups = True
#rename_model(old, old + "_v2", models_path)
if is_unique_name and new_versions_mode:
any_dups = True
print("ERROR: %s is not an update to any model. No model with that name exists." % dir)
if not new_versions_mode:
# not checking alias in new version mode because the models will be renamed
# altough technically there can be an alias problem still, but that should be really rare
for key, val in alt_names.items():
for alt in val:
if alt.lower() == lowernew:
print("WARNING: %s is a known alias of %s" % (lowernew, key))
alt_name_risk = True
if any_dups:
if new_versions_mode:
print("No models were added because some models have no known older version.")
else:
print("No models were added due to duplicates.")
return
too_long_model_names = False
for dir in new_dirs:
if len(dir) > 22:
too_long_model_names = True
print("Model name too long: %s" % dir)
if too_long_model_names:
# the game refuses to load models with long names, and servers refuse to transfer them to clients
print("No models were added due to invalid model names.")
return
if alt_name_risk:
x = input("\nContinue adding models even though people probably have different versions of these installed? (y/n): ")
if x != 'y':
return
print("\n-- Lowercasing files")
for dir in new_dirs:
all_files = [file for file in os.listdir(os.path.join(install_path, dir))]
mdl_files = []
for file in all_files:
if file != file.lower():
src = os.path.join(install_path, dir, file)
dst = os.path.join(install_path, dir, file.lower())
if os.path.exists(dst):
print("Lowercase file already exists: %s" % dst)
sys.exit()
else:
print("Rename: %s -> %s" % (file, file.lower()))
os.rename(src, dst)
if dir != dir.lower():
print("Rename: %s -> %s" % (dir, dir.lower()))
os.rename(os.path.join(install_path, dir), os.path.join(install_path, dir.lower()))
new_dirs = [dir.lower() for dir in new_dirs]
if new_versions_mode:
print("\n-- Adding version suffixes")
renames = []
versions_json = None
with open(versions_json_name) as f:
json_dat = f.read()
versions_json = json.loads(json_dat, object_pairs_hook=collections.OrderedDict)
for dir in new_dirs:
found_ver = ''
version_list_size = 1
group_idx = -1
for groupidx in range(0, len(versions_json)):
group = versions_json[groupidx]
for idx in range(0, len(group)):
if group[idx] == dir:
found_ver = group[0]
version_list_size = len(group)
group_idx = groupidx
break
if found_ver:
break
new_name = dir + "_v2"
if found_ver:
fidx = found_ver.rfind("_v")