-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgbfpib.pyw
2174 lines (2041 loc) · 117 KB
/
gbfpib.pyw
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
from __future__ import annotations
import asyncio
from contextlib import asynccontextmanager
from dataclasses import dataclass
from typing import Generator
import time
import os
import sys
import shutil
import traceback
import argparse
from base64 import b64encode
import json
from io import BytesIO
import importlib.util
from tkinter import messagebox, filedialog, simpledialog
import tkinter as Tk
import tkinter.ttk as ttk
import subprocess
from zipfile import ZipFile
# class to manipulate a vector2-type structure (X, Y)
# call the 'i' property to obtain an integer tuple to use with Pillow
dataclass(slots=True)
class v2():
x : int|float = 0
y : int|float = 0
def __init__(self : v2, X : int|float, Y : int|float):
self.x = X
self.y = Y
# operators
def __add__(self : v2, other : v2|tuple|list|int|float) -> v2:
if isinstance(other, float) or isinstance(other, int):
return v2(self.x + other, self.y + other)
else:
return v2(self.x + other[0], self.y + other[1])
def __radd__(self : v2, other : v2|tuple|list|int|float) -> v2:
return self.__add__(other)
def __mul__(self : v2, other : v2|tuple|list|int|float) -> v2:
if isinstance(other, float) or isinstance(other, int):
return v2(self.x * other, self.y * other)
else:
return v2(self.x * other[0], self.y * other[1])
def __rmul__(self : v2, other : v2|tuple|list|int|float) -> v2:
return self.__mul__(other)
# for access via []
def __getitem__(self : v2, key : int) -> int|float:
if key == 0:
return self.x
elif key == 1:
return self.y
else:
raise IndexError("Index out of range")
def __setitem__(self : v2, key : int, value : int|float) -> None:
if key == 0:
self.x = value
elif key == 1:
self.y = value
else:
raise IndexError("Index out of range")
# len is fixed at 2
def __len__(self : v2) -> int:
return 2
# to convert to an integer tuple (needed for pillow)
@property
def i(self : v2) -> tuple[int, int]:
return (int(self.x), int(self.y))
# wrapper class to store and manipulate Image objects
# handle the close() calls on destruction
dataclass(slots=True)
class IMG():
parent : PartyBuilder = None
image : Image = None
buffer : BytesIO = None
def __init__(self : IMG, src : str|bytes|IMG|Image) -> None:
self.image = None
self.buffer = None
match src: # possible types
case str(): # path to a local file
self.image = Image.open(src)
self.convert('RGBA')
case bytes(): # bytes (usually received from a network request)
self.buffer = BytesIO(src) # need a readable buffer for it, and it must stays alive
self.image = Image.open(self.buffer)
self.convert('RGBA')
case IMG(): # another IMG wrapper
self.image = src.image.copy()
case _: # an Image instance. NOTE: I use 'case _' because of how import Pillow, the type isn't loaded at this point
self.image = src
def __del__(self : IMG) -> None:
if self.image is not None:
self.image.close()
if self.buffer is not None:
self.buffer.close()
def convert(self : IMG, itype : str) -> None:
tmp = self.image
self.image = tmp.convert(itype)
tmp.close()
def copy(self : IMG) -> IMG:
return IMG(self)
def paste(self : IMG, other : IMG, offset : tuple[int, int]) -> None:
self.image.paste(other.image, offset, other.image)
def crop(self : IMG, size : tuple[int, int]|tuple[int, int, int, int]) -> IMG:
# depending on the tuple size
if len(size) == 4:
return IMG(self.image.crop(size))
elif len(size) == 2:
return IMG(self.image.crop((0, 0, *size)))
raise ValueError("Invalid size of the tuple passed to IMG.crop(). Expected 2 or 4, received {}.".format(len(size)))
def resize(self : IMG, size : v2|tuple[int, int]) -> IMG:
match size:
case v2():
return IMG(self.image.resize(size.i, Image.Resampling.LANCZOS))
case tuple():
return IMG(self.image.resize(size, Image.Resampling.LANCZOS))
raise TypeError("Invalid type passed to IMG.resize(). Expected v2 or tuple[int, int], received {}.".format(type(size)))
def alpha(self : IMG, layer : IMG) -> IMG:
return IMG(Image.alpha_composite(self.image, layer.image))
# Main class
class PartyBuilder():
NULL_CHARACTER = [3030182000, 3020072000] # null character id list (lyria, cat...), need to be hardcoded
COLORS = { # color for estimated advantage
1:(243, 48, 33),
2:(85, 176, 250),
3:(227, 124, 32),
4:(55, 232, 16),
5:(253, 216, 67),
6:(176, 84, 251)
}
COLORS_EN = { # color string
1:"Fire",
2:"Water",
3:"Earth",
4:"Wind",
5:"Light",
6:"Dark"
}
COLORS_JP = { # color string
1:"火",
2:"水",
3:"土",
4:"風",
5:"光",
6:"闇"
}
AUXILIARY_CLS = [100401, 300301, 300201, 120401, 140401] # aux classes
# IDs for special weapons
DARK_OPUS_IDS = [
"1040310600","1040310700","1040415000","1040415100","1040809400","1040809500","1040212500","1040212600","1040017000","1040017100","1040911000","1040911100",
"1040310600_02","1040310700_02","1040415000_02","1040415100_02","1040809400_02","1040809500_02","1040212500_02","1040212600_02","1040017000_02","1040017100_02","1040911000_02","1040911100_02",
"1040310600_03","1040310700_03","1040415000_03","1040415100_03","1040809400_03","1040809500_03","1040212500_03","1040212600_03","1040017000_03","1040017100_03","1040911000_03","1040911100_03"
]
ULTIMA_IDS = [
"1040011900","1040012000","1040012100","1040012200","1040012300","1040012400",
"1040109700","1040109800","1040109900","1040110000","1040110100","1040110200",
"1040208800","1040208900","1040209000","1040209100","1040209200","1040209300",
"1040307800","1040307900","1040308000","1040308100","1040308200","1040308300",
"1040410800","1040410900","1040411000","1040411100","1040411200","1040411300",
"1040507400","1040507500","1040507600","1040507700","1040507800","1040507900",
"1040608100","1040608200","1040608300","1040608400","1040608500","1040608600",
"1040706900","1040707000","1040707100","1040707200","1040707300","1040707400",
"1040807000","1040807100","1040807200","1040807300","1040807400","1040807500",
"1040907500","1040907600","1040907700","1040907800","1040907900","1040908000"
]
ORIGIN_DRACONIC_IDS = [
"1040815900","1040316500","1040712800","1040422200","1040915600","1040516500"
]
# User Agent (required for the wiki)
USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/132.0.0.0 Safari/537.36 Rosetta/Dev'
def __init__(self : PartyBuilder) -> None:
self.gbftmr = None # will contain a GBFTMR instance if configured properly
self.bookmark : str|None = None # cached copy of bookmarklet.txt
self.japanese : bool = False # True if the data is japanese, False if not
self.classes : dict[str, str] = None # cached classes
self.class_modified : bool = False
self.prev_lang : str = None # Language used in the previous run
self.babyl : bool = False # True if the data contains more than 5 allies
self.sandbox : bool = False # True if the data contains more than 10 weapons
self.pending : set[str] = set() # pending download
self.cache : dict[str, IMG] = {} # memory cache
self.emp_cache : dict[str, dict] = {} # emp cache
self.sumcache : dict[str, str] = {} # wiki summon cache
self.fonts : dict[str, ImageFont] = {'mini':None, 'small':None, 'medium':None, 'big':None} # font to use during the processing
self.quality : float = 1 # quality ratio in use currently
self.definition : tuple[int, int] = None # image size
self.running : bool = False # True if the image building is in progress
self.settings : dict[str, str|int|bool] = {} # settings.json data
self.manifest : dict[str, str] = {} # manifest.json data
# load stuff (import libraries, load JSON...)
self.startup_check()
self.load()
# finish the initialization
self.dummy_layer : IMG = self.blank_image()
self.name : str = "GBFPIB " + self.manifest.get('version', '')
self.client : aiohttp.ClientSession = None # container for the HTTP client
if self.manifest.get('pending', False):
self.manifest['pending'] = False
self.saveManifest()
# init the HTTP client
@asynccontextmanager
async def init_client(self : PartyBuilder) -> Generator[aiohttp.ClientSession, None, None]:
try:
self.client = aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=20))
yield self.client
finally:
await self.client.close()
# transform an exception to a readable string
def pexc(self : PartyBuilder, e : Exception) -> str:
return "".join(traceback.format_exception(type(e), e, e.__traceback__))
# load manifest.json
def loadManifest(self : PartyBuilder) -> None:
try:
with open("manifest.json") as f:
self.manifest = json.load(f)
except:
pass
# save manifest.json
def saveManifest(self : PartyBuilder) -> None:
try:
with open("manifest.json", 'w') as outfile:
json.dump(self.manifest, outfile)
except:
pass
# load classes.json
def loadClasses(self : PartyBuilder) -> None:
try:
self.class_modified = False
with open("classes.json", mode="r", encoding="utf-8") as f:
self.classes = json.load(f)
except:
self.classes = {}
# save classes.json
def saveClasses(self : PartyBuilder) -> None:
try:
if self.class_modified:
with open("classes.json", mode='w', encoding='utf-8') as outfile:
json.dump(self.classes, outfile)
except:
pass
# import third-party modules
def importRequirements(self : PartyBuilder) -> None:
global aiohttp
import aiohttp
global Image
global ImageFont
global ImageDraw
from PIL import Image, ImageFont, ImageDraw
global pyperclip
import pyperclip
# ran on class creation
def startup_check(self : PartyBuilder) -> None:
self.loadManifest()
if self.manifest.get('pending', False):
if messagebox.askyesno(title="Info", message="I will now attempt to update required dependencies.\nDo you accept?\nElse it will be ignored if the application can start."):
try:
subprocess.check_call([sys.executable, "-m", "pip", "install", "-r", "requirements.txt"])
self.importRequirements()
messagebox.showinfo("Info", "Installation successful.")
except Exception as e:
print(self.pexc(e))
if sys.platform == "win32": # Windows
import ctypes
is_admin : bool
try: is_admin = ctypes.windll.shell32.IsUserAnAdmin() # check for admin
except: is_admin = False
if not is_admin:
if messagebox.askyesno(title="Error", message="An error occured: {}\nDo you want to restart the application with administrator permissions?".format(e)):
ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, " ".join(sys.argv), None, 1) # restart as admin
else:
messagebox.showerror("Error", "An error occured: {}\nFurther troubleshooting is needed.\nYou might need to install the dependancies manually, check the README for details.")
else:
messagebox.showerror("Error", "An error occured: {}\nFurther troubleshooting is needed.\nYou might need to install the dependancies manually, check the README for details.")
os._exit(0)
else:
try:
self.importRequirements()
except Exception as e:
print(self.pexc(e))
if messagebox.askyesno(title="Error", message="An error occured while importing the dependencies: {}\nThey might be outdated or missing.\nRestart and attempt to install them now?".format(e)):
self.manifest['pending'] = True
self.saveManifest()
self.restart()
os._exit(0)
print("Granblue Fantasy Party Image Builder", self.manifest.get('version', ''))
# load settings.json
def load(self : PartyBuilder) -> None:
try:
with open('settings.json') as f:
self.settings = json.load(f)
except:
print("Failed to load settings.json")
while True:
print("An empty settings.json file will be created, continue? (y/n)")
match input().lower():
case 'n':
os._exit(0)
case 'y':
break
self.save()
# save settings.json
def save(self : PartyBuilder) -> None:
try:
with open('settings.json', 'w') as outfile:
json.dump(self.settings, outfile)
except:
pass
# retrieve an image from the given path/url
async def get(self : PartyBuilder, path : str, remote : bool = True, forceDownload : bool = False) -> bytes:
# check language
if self.japanese:
path = path.replace('assets_en', 'assets')
# check if retrieval is pending
while path in self.pending:
await asyncio.sleep(0.005)
self.pending.add(path)
try:
# retrieve
if forceDownload or path not in self.cache:
try: # get from disk cache if enabled
if forceDownload:
raise Exception() # go to exception/download block
if self.settings.get('caching', False):
with open("cache/" + b64encode(path.encode('utf-8')).decode('utf-8'), "rb") as f:
self.cache[path] = IMG(f.read())
await asyncio.sleep(0)
else:
raise Exception()
except: # else request it from gbf
if remote:
print("[GET] *Downloading File", path)
response : aiohttp.Response = await self.client.get('https://' + self.settings.get('endpoint', 'prd-game-a-granbluefantasy.akamaized.net/') + path, headers={'connection':'keep-alive'})
async with response:
if response.status != 200:
raise Exception("HTTP Error code {} for url: {}".format(response.status, 'https://' + self.settings.get('endpoint', 'prd-game-a-granbluefantasy.akamaized.net/') + path))
io : bytes = await response.read()
self.cache[path] = IMG(io)
if self.settings.get('caching', False):
try:
with open("cache/" + b64encode(path.encode('utf-8')).decode('utf-8'), "wb") as f:
f.write(io)
await asyncio.sleep(0)
except Exception as e:
print(self.pexc(e))
pass
else:
with open(path, "rb") as f:
self.cache[path] = IMG(f.read())
await asyncio.sleep(0)
# end
self.pending.remove(path)
return self.cache[path]
except Exception as ex:
self.pending.remove(path) # failsafe
raise ex
# paste an image onto our list of images for given range
async def paste(self : PartyBuilder, imgs : list[IMG], indexes : range, file : str|IMG, offset : tuple[int, int], *, resize : tuple[int, int]|None = None, transparency : bool = False, crop : tuple[int, int]|tuple[int, int, int, int]|None = None) -> list[IMG]:
# get file
if isinstance(file, str):
if self.japanese:
file = file.replace('_EN', '')
file = await self.get(file, remote=False)
# crop
if crop is not None:
file = file.crop(crop)
# resize
if resize is not None:
file = file.resize(resize)
# paste
if not transparency:
for i in indexes:
imgs[i].paste(file, offset)
else:
layer = self.dummy_layer.copy()
layer.paste(file, offset)
for i in indexes:
imgs[i] = imgs[i].alpha(layer)
await asyncio.sleep(0)
# return
return imgs
# download and paste an image onto our list of images for given range
async def pasteDL(self : PartyBuilder, imgs : list[IMG], indexes : range, path : str, offset : tuple[int, int], *, resize : tuple[int, int]|None = None, transparency : bool = False, crop : tuple[int, int]|tuple[int, int, int, int]|None = None) -> list: # dl an image and call pasteImage()
return await self.paste(imgs, indexes, await self.get(path), offset, resize=resize, transparency=transparency, crop=crop)
# write text on images
def text(self : PartyBuilder, imgs : list[IMG], indexes : range, *args, **kwargs) -> None:
for i in indexes:
ImageDraw.Draw(imgs[i].image, 'RGBA').text(*args, **kwargs)
# write multiline text on images
def multiline_text(self : PartyBuilder, imgs : list[IMG], indexes : range, *args, **kwargs) -> None:
for i in indexes:
ImageDraw.Draw(imgs[i].image, 'RGBA').multiline_text(*args, **kwargs)
# search in the gbf.wiki cargo table to match a summon name to its id
async def get_support_summon_from_wiki(self : PartyBuilder, name : str) -> str|None:
try:
name = name.lower()
if name in self.sumcache: return self.sumcache[name]
response : aiohttp.Response = await self.client.get("https://gbf.wiki/index.php?title=Special:CargoExport&tables=summons&fields=id,name&format=json&limit=20000", headers={'connection':'close', 'User-Agent':self.USER_AGENT})
async with response:
if response.status != 200: raise Exception()
data : list = await response.json()
for summon in data:
if summon["name"].lower() == name:
self.sumcache[name] = summon["id"]
return summon["id"]
return None
except:
return None
# get character portraits based on uncap levels
def get_uncap_id(self : PartyBuilder, cs : int) -> str:
return {2:'02', 3:'02', 4:'02', 5:'03', 6:'04'}.get(cs, '01')
# get character uncap star based on uncap levels
def get_uncap_star(self : PartyBuilder, cs : int, cl : int) -> str:
match cs:
case 4: return "assets/star_1.png"
case 5: return "assets/star_2.png"
case 6:
if cl <= 110: return "assets/star_4_1.png"
elif cl <= 120: return "assets/star_4_2.png"
elif cl <= 130: return "assets/star_4_3.png"
elif cl <= 140: return "assets/star_4_4.png"
elif cl <= 150: return "assets/star_4_5.png"
case _: return "assets/star_0.png"
# get summon star based on uncap levels
def get_summon_star(self : PartyBuilder, se : int, sl : int) -> str:
match se:
case 3: return "assets/star_1.png"
case 4: return "assets/star_2.png"
case 5: return "assets/star_3.png"
case 6:
if sl <= 210: return "assets/star_4_1.png"
elif sl <= 220: return "assets/star_4_2.png"
elif sl <= 230: return "assets/star_4_3.png"
elif sl <= 240: return "assets/star_4_4.png"
elif sl <= 250: return "assets/star_4_5.png"
case _: return "assets/star_0.png"
# get portrait of character for given skin
def get_character_look(self : PartyBuilder, export : dict, i : int) -> str:
style = ("" if str(export['cst'][i]) == '1' else "_st{}".format(export['cst'][i])) # style check
# get uncap
if style != "":
uncap = "01"
else:
uncap = self.get_uncap_id(export['cs'][i])
cid = export['c'][i]
# Beginning of the part to fix some exceptions
if str(cid).startswith('371'):
match cid:
case 3710098000: # seox skin
if export['cl'][i] > 80:
cid = 3040035000 # eternal seox
else:
cid = 3040262000 # event seox
case 3710122000: # seofon skin
cid = 3040036000 # eternal seofon
case 3710143000: # vikala skin
if export['ce'][i] == 3:
cid = 3040408000 # apply earth vikala
elif export['ce'][i] == 6:
if export['cl'][i] > 50:
cid = 3040252000 # SSR dark vikala
else:
cid = 3020073000 # R dark vikala
case 3710154000: # clarisse skin
match export['ce'][i]:
case 2: cid = 3040413000 # water
case 3: cid = 3040067000 # earth
case 5: cid = 3040121000 # light
case 6: cid = 3040206000 # dark
case _: cid = 3040046000 # fire
case 3710165000: # diantha skin
match export['ce'][i]:
case 2:
if export['cl'][i] > 70:
cid = 3040129000 # water SSR
else:
cid = 3030150000 # water SR
case 3:
cid = 3040296000 # earth
case 3710172000: # tsubasa skin
cid = 3040180000
case 3710176000: # mimlemel skin
if export['ce'][i] == 1:
cid = 3040292000 # apply fire mimlemel
elif export['ce'][i] == 3:
cid = 3030220000 # apply earth halloween mimlemel
elif export['ce'][i] == 4:
if export['cn'][i] in ('Mimlemel', 'ミムルメモル'):
cid = 3030043000 # first sr wind mimlemel
else:
cid = 3030166000 # second sr wind mimlemel
case 3710191000: # cidala skin 1
if export['ce'][i] == 3:
cid = 3040377000 # apply earth cidala
elif export['ce'][i] == 5:
cid = 3040512000 # apply dark cidala
case 3710195000: # cidala skin 2
if export['ce'][i] == 3:
cid = 3040377000 # apply earth cidala
elif export['ce'][i] == 5:
cid = 3040512000 # apply dark cidala
# End of the exceptions
# Return string
if cid in self.NULL_CHARACTER:
if export['ce'][i] == 99:
return "{}_{}{}_0{}".format(cid, uncap, style, export['pce'])
else:
return "{}_{}{}_0{}".format(cid, uncap, style, export['ce'][i])
else:
return "{}_{}{}".format(cid, uncap, style)
# get MC portrait without skin
async def get_mc_job_look(self : PartyBuilder, skin : str, job : int) -> str:
sjob : str = str((job//100) * 100 + 1)
if sjob in self.classes:
return "{}_{}_{}".format(sjob, self.classes[sjob], '_'.join(skin.split('_')[2:]))
else:
tasks = []
# look for job MH
for mh in ["sw", "kn", "sp", "ax", "wa", "gu", "me", "bw", "mc", "kr"]:
tasks.append(self.get_mc_job_look_sub(sjob, mh))
for r in await asyncio.gather(*tasks):
if r is not None:
self.class_modified = True
self.classes[sjob] = r
return "{}_{}_{}".format(sjob, self.classes[sjob], '_'.join(skin.split('_')[2:]))
return ""
# subroutine of get_mc_job_look
async def get_mc_job_look_sub(self : PartyBuilder, job : str, mh : str) -> str|None:
response : aiohttp.Response = await self.client.head("https://prd-game-a5-granbluefantasy.akamaized.net/assets_en/img/sp/assets/leader/s/{}_{}_0_01.jpg".format(job, mh))
async with response:
if response.status != 200:
return None
return mh
def process_special_weapon(self : PartyBuilder, export : dict, i : int, j : int) -> bool:
if export['wsn'][i][j] is not None and export['wsn'][i][j] == "skill_job_weapon":
if j == 2: # skill 3, ultima, opus
if export['w'][i] in self.DARK_OPUS_IDS:
bar_gain = 0
hp_cut = 0
turn_dmg = 0
prog = 0
ca_dmg = 0
ca_dmg_cap = 0
auto_amp_sp = 0
skill_amp_sp = 0
ca_amp_sp = 0
for m in export['mods']:
try:
match m['icon_img']:
case '04_icon_ca_gage.png':
bar_gain = float(m['value'].replace('%', ''))
case '03_icon_hp_cut.png':
hp_cut = float(m['value'].replace('%', ''))
case '03_icon_turn_dmg.png':
turn_dmg = float(m['value'].replace('%', ''))
case '01_icon_e_atk_01.png':
prog = float(m['value'].replace('%', ''))
case '04_icon_ca_dmg.png':
ca_dmg = float(m['value'].replace('%', ''))
case '04_icon_ca_dmg_cap.png':
ca_dmg_cap = float(m['value'].replace('%', ''))
case '04_icon_normal_dmg_amp_other.png':
auto_amp_sp = float(m['value'].replace('%', ''))
case '04_icon_ability_dmg_amplify_other.png':
skill_amp_sp = float(m['value'].replace('%', ''))
case '04_icon_ca_dmg_amplify_other.png':
ca_amp_sp = float(m['value'].replace('%', ''))
except:
pass
if hp_cut >= 30: # temptation
export['wsn'][i][j] = "assets_en/img/sp/assets/item/skillplus/s/14014.jpg"
return True
elif auto_amp_sp >= 10: # extremity
export['wsn'][i][j] = "assets_en/img/sp/assets/item/skillplus/s/14005.jpg"
return True
elif skill_amp_sp >= 10: # sagacity
export['wsn'][i][j] = "assets_en/img/sp/assets/item/skillplus/s/14006.jpg"
return True
elif ca_amp_sp >= 10: # supremacy
export['wsn'][i][j] = "assets_en/img/sp/assets/item/skillplus/s/14007.jpg"
return True
elif bar_gain <= -50 and bar_gain > -200: # falsehood
export['wsn'][i][j] = "assets_en/img/sp/assets/item/skillplus/s/14017.jpg"
return True
elif prog > 0: # progression
export['wsn'][i][j] = "assets_en/img/sp/assets/item/skillplus/s/14004.jpg"
return True
elif ca_dmg >= 100 and ca_dmg_cap >= 30: # forbiddance
export['wsn'][i][j] = "assets_en/img/sp/assets/item/skillplus/s/14015.jpg"
return True
elif turn_dmg >= 5: # depravity
export['wsn'][i][j] = "assets_en/img/sp/assets/item/skillplus/s/14016.jpg"
return True
elif export['w'][i] in self.ULTIMA_IDS:
seraphic = 0
heal_cap = 0
bar_gain = 0
cap_up = 0
for m in export['mods']:
try:
match m['icon_img']:
case '04_icon_elem_amplify.png':
seraphic = float(m['value'].replace('%', ''))
case '04_icon_dmg_cap.png':
cap_up = float(m['value'].replace('%', ''))
case '04_icon_ca_gage.png':
bar_gain = float(m['value'].replace('%', ''))
case '03_icon_heal_cap.png':
heal_cap = float(m['value'].replace('%', ''))
except:
pass
if seraphic >= 25: # tria
export['wsn'][i][2] = "assets_en/img/sp/assets/item/skillplus/s/17003.jpg"
return True
elif heal_cap >= 50 and bar_gain >= 10: # dio / tessera better guess (EXPERIMENTAL)
count = 0
for a in export['wsn']:
for b in a:
if b is None: continue
elif "heal_limit_m" in b: count += 1
elif "heal_limit" in b: count += 1
if count >= 3: export['wsn'][i][2] = "assets_en/img/sp/assets/item/skillplus/s/17004.jpg"
elif count == 2: return False # unsure
else: export['wsn'][i][2] = "assets_en/img/sp/assets/item/skillplus/s/17002.jpg"
return True
elif heal_cap >= 50: # dio
export['wsn'][i][2] = "assets_en/img/sp/assets/item/skillplus/s/17002.jpg"
return True
elif bar_gain >= 10: # tessera
export['wsn'][i][2] = "assets_en/img/sp/assets/item/skillplus/s/17004.jpg"
return True
elif cap_up >= 10: # ena
export['wsn'][i][2] = "assets_en/img/sp/assets/item/skillplus/s/17001.jpg"
return True
elif j == 1: # skill 2, hexa draconic
if export['w'][i] in self.ORIGIN_DRACONIC_IDS:
seraphic = 0
for m in export['mods']:
try:
match m['icon_img']:
case '04_icon_plain_amplify.png':
seraphic = float(m['value'].replace('%', ''))
except:
pass
if seraphic >= 10: # oblivion teluma
export['wsn'][i][j] = "assets_en/img/sp/assets/item/skillplus/s/15009.jpg"
return True
return False
def blank_image(self : PartyBuilder, size : tuple = (1800, 2160)) -> IMG:
i = Image.new('RGB', size, "black")
im_a = Image.new("L", size, "black")
i.putalpha(im_a)
im_a.close()
return IMG(i)
async def make_party(self : PartyBuilder, export : dict) -> str|tuple[str, list[IMG]]:
try:
imgs : list[IMG] = [self.blank_image(), self.blank_image()]
print("[CHA] * Drawing Party...")
# setting offsets and background
if self.babyl:
offset : v2 = v2(15, 10) # offset of party section
nchara : int = 12 # max character (12 for babyl because MC is counted)
csize : v2 = v2(180, 180) # character portrait size
skill_width : int = 420 # skill name width
pos : v2 = offset + v2(30, 0) # first character (MC) position
jsize : v2 = v2(54, 45) # job icon size
roffset : v2 = v2(-6, -6) # ring offset
rsize : v2 = v2(60, 60) # ring icon size
ssize : v2 = v2(50, 50) # star icon size
soffset : v2 = csize + v2(- csize.y, - ssize.y * 5 // 3) # star offset
poffset : v2 = csize + v2(-105, -45) # plus mark offset
ssoffset : v2 = pos + v2(0, 10 + csize.y) # subskill offset
stoffset : v2 = ssoffset + v2(3, 3) # subskill text offset
plsoffset : v2 = ssoffset + v2(447, 0) # shield/manatura offset
# background
await self.paste(imgs, range(1), "assets/bg.png", (pos + (-15, -15)).i, resize=(csize*(8,2)+(40,55)).i, transparency=True)
else:
offset : v2 = v2(15, 10)
nchara : int = 5
csize : v2 = v2(250, 250)
skill_width : int = 420
pos : v2 = offset + (skill_width - csize.x, 0)
jsize : v2 = v2(72, 60)
roffset : v2 = v2(-10, -10)
rsize : v2 = v2(90, 90)
ssize : v2 = v2(66, 66)
soffset : v2 = csize + (- csize.x + ssize.x //2, - ssize.y)
poffset : v2 = csize + (-110, -40)
noffset : v2 = v2(9, csize.y + 10)
loffset : v2 = v2(10, csize.y + 6 + 60)
ssoffset : v2 = offset + (0, csize.y)
stoffset : v2 = ssoffset + (3, 3)
plsoffset : v2 = ssoffset + (0, -150)
# background
await self.paste(imgs, range(1), "assets/bg.png", (pos + (-15, -10)).i, resize=(csize*(6,1)+(30+25,175)).i, transparency=True)
# mc
print("[CHA] |--> MC Skin:", export['pcjs'])
print("[CHA] |--> MC Job:", export['p'])
print("[CHA] |--> MC Master Level:", export['cml'])
print("[CHA] |--> MC Proof Level:", export['cbl'])
# class
class_id = await self.get_mc_job_look(export['pcjs'], export['p'])
await self.pasteDL(imgs, range(1), "assets_en/img/sp/assets/leader/s/{}.jpg".format(class_id), pos.i, resize=csize.i)
# job icon
await self.pasteDL(imgs, range(1), "assets_en/img/sp/ui/icon/job/{}.png".format(export['p']), pos.i, resize=jsize.i, transparency=True)
if export['cbl'] == '6':
await self.pasteDL(imgs, range(1), "assets_en/img/sp/ui/icon/job/ico_perfection.png", (pos + (0, jsize[1])).i, resize=jsize.i, transparency=True)
# skin
if class_id != export['pcjs']:
await self.pasteDL(imgs, range(1, 2), "assets_en/img/sp/assets/leader/s/{}.jpg".format(export['pcjs']), pos.i, resize=csize.i)
await self.pasteDL(imgs, range(1, 2), "assets_en/img/sp/ui/icon/job/{}.png".format(export['p']), pos.i, resize=jsize, transparency=True)
# allies
for i in range(0, nchara):
await asyncio.sleep(0)
if self.babyl:
if i < 4:
pos = offset + (csize.x * i + 30, 0)
elif i < 8:
pos = offset + (csize.x * i + 40, 0)
else:
pos = offset + (csize.x * (i - 4) + 40, 10 + csize.y * (i // 8))
if i == 0:
continue # quirk of babyl party, mc is at index 0
else:
pos = offset + (skill_width + csize.x * i, 0)
if i >= 3:
pos = pos + (25, 0)
# portrait
if i >= len(export['c']) or export['c'][i] is None: # empty
await self.pasteDL(imgs, range(1), "assets_en/img/sp/tower/assets/npc/s/3999999999.jpg", pos.i, resize=csize.i)
continue
print("[CHA] |--> Ally #{}:".format(i+1), export['c'][i], export['cn'][i], "Lv {}".format(export['cl'][i]), "Uncap-{}".format(export['cs'][i]), "+{}".format(export['cp'][i]), "Has Ring" if export['cwr'][i] else "No Ring")
# portrait
cid = self.get_character_look(export, i)
await self.pasteDL(imgs, range(1), "assets_en/img/sp/assets/npc/s/{}.jpg".format(cid), pos.i, resize=csize.i)
# skin
has_skin : bool
if cid != export['ci'][i]:
await self.pasteDL(imgs, range(1, 2), "assets_en/img/sp/assets/npc/s/{}.jpg".format(export['ci'][i]), pos.i, resize=csize.i)
has_skin = True
else:
has_skin = False
# star
await self.paste(imgs, range(2 if has_skin else 1), self.get_uncap_star(export['cs'][i], export['cl'][i]), (pos + soffset).i, resize=ssize.i, transparency=True)
# rings
if export['cwr'][i] == True:
await self.pasteDL(imgs, range(2 if has_skin else 1), "assets_en/img/sp/ui/icon/augment2/icon_augment2_l.png", (pos + roffset).i, resize=rsize.i, transparency=True)
# plus
if export['cp'][i] > 0:
self.text(imgs, range(2 if has_skin else 1), (pos + poffset).i, "+{}".format(export['cp'][i]), fill=(255, 255, 95), font=self.fonts['small'], stroke_width=6, stroke_fill=(0, 0, 0))
if not self.babyl:
# name
await self.paste(imgs, range(1), "assets/chara_stat.png", (pos + (0, csize.y)).i, resize=(csize.x, 60), transparency=True)
if len(export['cn'][i]) > 11: name = export['cn'][i][:11] + ".."
else: name = export['cn'][i]
self.text(imgs, range(1), (pos + noffset).i, name, fill=(255, 255, 255), font=self.fonts['mini'])
# skill count
await self.paste(imgs, range(1), "assets/skill_count_EN.png", (pos + (0, csize.y + 60)).i, resize=(csize.x, 60), transparency=True)
self.text(imgs, range(1), (pos + loffset + (150, 0)).i, str(export['cb'][i+1]), fill=(255, 255, 255), font=self.fonts['medium'], stroke_width=4, stroke_fill=(0, 0, 0))
await asyncio.sleep(0)
# mc sub skills
await self.paste(imgs, range(2), "assets/subskills.png", ssoffset.i, resize=(420, 147))
count : int = 0
f : str
voff : int
for i in range(len(export['ps'])):
if export['ps'][i] is not None:
print("[CHA] |--> MC Skill #{}:".format(i), export['ps'][i])
if len(export['ps'][i]) > 20:
f = 'mini'
voff = 5
elif len(export['ps'][i]) > 15:
f = 'small'
voff = 2
else:
f = 'medium'
voff = 0
self.text(imgs, range(2), (stoffset + (0, 48*count+voff)).i, export['ps'][i], fill=(255, 255, 255), font=self.fonts[f])
count += 1
await asyncio.sleep(0)
# paladin shield/manadiver familiar
if export['cpl'][0] is not None:
print("[CHA] |--> Paladin shields:", export['cpl'][0], "|", export['cpl'][1])
await self.pasteDL(imgs, range(1), "assets_en/img/sp/assets/shield/s/{}.jpg".format(export['cpl'][0]), plsoffset.i, resize=(150, 150))
if export['cpl'][1] is not None and export['cpl'][1] != export['cpl'][0] and export['cpl'][1] > 0: # skin
await self.pasteDL(imgs, range(1, 2), "assets_en/img/sp/assets/shield/s/{}.jpg".format(export['cpl'][1]), plsoffset.i, resize=(150, 150))
await self.paste(imgs, range(1, 2), "assets/skin.png", (plsoffset + (0, -70)).i, (153, 171))
elif export['fpl'][0] is not None:
print("[CHA] |--> Manadiver Manatura:", export['fpl'][0], "|", export['fpl'][1])
await self.pasteDL(imgs, range(1), "assets_en/img/sp/assets/familiar/s/{}.jpg".format(export['fpl'][0]), plsoffset.i, resize=(150, 150))
if export['fpl'][1] is not None and export['fpl'][1] != export['fpl'][0] and export['fpl'][1] > 0: # skin
await self.pasteDL(imgs, range(1, 2), "assets_en/img/sp/assets/familiar/s/{}.jpg".format(export['fpl'][1]), plsoffset.i, resize=(150, 150))
await self.paste(imgs, range(1, 2), "assets/skin.png", (plsoffset + (0, -45)).i, resize=(76, 85))
elif self.babyl: # to fill the blank space
await self.paste(imgs, range(2), "assets/characters_EN.png", (ssoffset, (skill_width, 0)).i, resize=(276, 75), transparency=True)
return ('party', imgs)
except Exception as e:
return self.pexc(e)
async def make_summon(self : PartyBuilder, export : dict) -> str|tuple:
try:
imgs : list[IMG] = [self.blank_image(), self.blank_image()]
print("[SUM] * Drawing Summons...")
offset : v2 = v2(170, 425) # offset of this section
variants : list[dict] = [
{
"size":v2(271, 472),
"empty":"assets_en/img/sp/assets/summon/ls/2999999999.jpg",
"summon":"assets_en/img/sp/assets/summon/party_main/{}.jpg"
},
{
"size":v2(266, 200),
"empty":"assets_en/img/sp/assets/summon/m/2999999999.jpg",
"summon":"assets_en/img/sp/assets/summon/party_sub/{}.jpg"
},
{
"size":v2(273, 155),
"empty":"assets_en/img/sp/assets/summon/m/2999999999.jpg",
"summon":"assets_en/img/sp/assets/summon/m/{}.jpg"
}
]
# background setup
await self.paste(imgs, range(1), "assets/bg.png", (offset + (-15, -15)).i, resize=(100 + (variants[0]["size"].x + variants[1]["size"].x) * 2+ 48, variants[0]["size"].y + 143), transparency=True)
pos : v2
idx : int
for i in range(0, 7):
await asyncio.sleep(0)
if i == 0: # main summon
pos = offset + (0, 0)
idx = 0
elif i < 5: # secondary summons
pos = offset + (variants[0]["size"].x + 50 + 18, 0)
pos += (((i - 1) % 2) * variants[1]["size"].x, 266 * ((i - 1) // 2)) # modulo% to set on a 2x2 grid
idx = 1
else: # sub summons
pos = offset + (variants[0]["size"].x + 100 + 18, 102)
pos += (2*variants[1]["size"].x, (i - 5) * (variants[2]["size"].y + 60)) # sub summon pos
idx = 2
if i == 5: # add sub summon marker
await self.paste(imgs, range(1), "assets/subsummon_EN.png", (pos.x + 45, pos.y - 72 - 30), resize=(180, 72), transparency=True)
# portraits
if export['s'][i] is None:
await self.pasteDL(imgs, range(1), variants[idx]["empty"], pos.i, resize=variants[idx]["size"].i)
continue
else:
print("[SUM] |--> Summon #{}:".format(i+1), export['ss'][i], "Uncap Lv{}".format(export['se'][i]), "Lv{}".format(export['sl'][i]))
await self.pasteDL(imgs, range(1), variants[idx]["summon"].format(export['ss'][i]), pos.i, resize=variants[idx]["size"].i)
# main summon skin
has_skin : bool
if i == 0 and export['ssm'] is not None:
await self.pasteDL(imgs, range(1, 2), variants[idx]["summon"].format(export['ssm']), pos.i, resize=variants[idx]["size"].i)
await self.paste(imgs, range(1, 2), "assets/skin.png", (pos + (variants[idx]["size"].x - 85, 15)).i, resize=(76, 85))
has_skin = True
else:
has_skin = False
# star
await self.paste(imgs, range(2 if has_skin else 1), self.get_summon_star(export['se'][i], export['sl'][i]), pos.i, resize=(66, 66), transparency=True)
# quick summon
if export['qs'] is not None and export['qs'] == i:
await self.paste(imgs, range(2 if has_skin else 1), "assets/quick.png", (pos + (0, 66)).i, resize=(66, 66), transparency=True)
# level
await self.paste(imgs, range(1), "assets/chara_stat.png", (pos + (0, variants[idx]["size"].y)).i, resize=(variants[idx]["size"].x, 60), transparency=True)
self.text(imgs, range(1), (pos + (6 , variants[idx]["size"].y + 9)).i, "Lv{}".format(export['sl'][i]), fill=(255, 255, 255), font=self.fonts['small'])
# plus
if export['sp'][i] > 0:
self.text(imgs, range(2 if has_skin else 1), (pos + variants[idx]["size"] + (-95, -50)), "+{}".format(export['sp'][i]), fill=(255, 255, 95), font=self.fonts['medium'], stroke_width=6, stroke_fill=(0, 0, 0))
await asyncio.sleep(0)
# stats
spos = offset + variants[0]["size"] + (50+18, 60) # position
await self.paste(imgs, range(1), "assets/chara_stat.png", spos.i, resize=(variants[1]["size"].x * 2, 60), transparency=True)
await self.paste(imgs, range(1), "assets/atk.png", (spos + (9, 9)).i, resize=(90, 39), transparency=True)
await self.paste(imgs, range(1), "assets/hp.png", (spos + (variants[1]["size"].x + 9, 9)).i, resize=(66, 39), transparency=True)
self.text(imgs, range(1), (spos + (120, 9)).i, "{}".format(export['satk']), fill=(255, 255, 255), font=self.fonts['small'])
self.text(imgs, range(1), (spos + (variants[1]["size"].x + 80, 9)).i, "{}".format(export['shp']), fill=(255, 255, 255), font=self.fonts['small'])
return ('summon', imgs)
except Exception as e:
return self.pexc(e)
async def make_weapon(self : PartyBuilder, export : dict, do_hp : bool, do_opus : bool) -> str|tuple:
try:
imgs = [self.blank_image(), self.blank_image()]
print("[WPN] * Drawing Weapons...")
# setting offsets
offset : v2
if self.sandbox:
offset = v2(25, 1050)
else:
offset = v2(170, 1050)
skill_box_height : int = 144
skill_icon_size : int = 72
ax_icon_size : int = 86
ax_separator : int = skill_box_height
mh_size : v2 = v2(300, 630)
sub_size : v2 = v2(288, 165)
self.multiline_text(imgs, range(2), (1540, 2125), self.name, fill=(120, 120, 120, 255), font=self.fonts['mini'])
await self.paste(imgs, range(1), "assets/grid_bg.png", (offset + (-15, -15)).i, resize=(mh_size.x+(4 if self.sandbox else 3)*sub_size.x+60, 1425+(240 if self.sandbox else 0)), transparency=True)
if self.sandbox:
await self.paste(imgs, range(1), "assets/grid_bg_extra.png", (offset.x+mh_size.x+30+sub_size.x*3, offset.y), resize=(288, 1145), transparency=True)
for i in range(0, len(export['w'])):
await asyncio.sleep(0)
wt : str = "ls" if i == 0 else "m"
pos : v2
size : v2
bsize : v2
if i == 0: # mainhand
pos = offset
size = mh_size
bsize = size
elif i >= 10: # sandbox
if not self.sandbox: break
size = sub_size
pos = offset + (bsize.x + 30, 0) + (size + (0, skill_box_height)) * (3, (i - 1) % 3)
else: # others
size = sub_size
pos = offset + (bsize.x + 30, 0) + (size + (0, skill_box_height)) * ((i - 1) % 3, (i - 1) // 3)
# dual blade class
if i <= 1 and export['p'] in self.AUXILIARY_CLS:
await self.paste(imgs, range(1), ("assets/mh_dual.png" if i == 0 else "assets/aux_dual.png"), (pos, (-2, -2)).i, resize=(size, (5, 5+skill_box_height)).i, transparency=True)
# portrait
if export['w'][i] is None or export['wl'][i] is None:
if i >= 10:
await self.paste(imgs, range(1), "assets/arca_slot.png", pos.i, resize=size.i)
else:
await self.pasteDL(imgs, range(1), "assets_en/img/sp/assets/weapon/{}/1999999999.jpg".format(wt), pos.i, resize=size.i)
continue
# ax and awakening check
has_ax : bool = len(export['waxt'][i]) > 0
has_awakening : bool = (export['wakn'][i] is not None and export['wakn'][i]['is_arousal_weapon'] and export['wakn'][i]['level'] is not None and export['wakn'][i]['level'] > 1)
pos_shift : int = - skill_icon_size if (has_ax and has_awakening) else 0 # vertical shift of the skill boxes (if both ax and awk are presents)
# portrait draw
print("[WPN] |--> Weapon #{}".format(i+1), str(export['w'][i]), ", AX:", has_ax, ", Awakening:", has_awakening)
await self.pasteDL(imgs, range(1), "assets_en/img/sp/assets/weapon/{}/{}.jpg".format(wt, export['w'][i]), pos.i, resize=size.i)
# skin
has_skin : bool = False
if i <= 1 and export['wsm'][i] is not None:
if i == 0 or (i == 1 and export['p'] in self.AUXILIARY_CLS): # aux class check for 2nd weapon
await self.pasteDL(imgs, range(1, 2), "assets_en/img/sp/assets/weapon/{}/{}.jpg".format(wt, export['wsm'][i]), pos.i, resize=size.i)
await self.paste(imgs, range(1, 2), "assets/skin.png", (pos + (size.x-76, 0)).i, resize=(76, 85), transparency=True)
has_skin = True
# skill box
nbox : int = 1 # number of skill boxes to draw
if has_ax:
nbox += 1
if has_awakening:
nbox += 1