-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtp_atlas_parser.py
More file actions
64 lines (50 loc) · 1.71 KB
/
tp_atlas_parser.py
File metadata and controls
64 lines (50 loc) · 1.71 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
from PIL import Image
import xml.etree.ElementTree as ET
def parse_tuple(s):
t = tuple(map(float, s.strip("{}").replace("},{",",").split(",")))
t = [round(e) for e in t]
return tuple(t)
def atlas_to_sprites(data, atlas, logging=False):
root = ET.fromstring(atlas)
frames_dict = root.find(".//dict")
frames_key_idx = None
for i, elem in enumerate(frames_dict):
if elem.tag == "key" and elem.text == "frames":
frames_key_idx = i
break
frames_dict = frames_dict[frames_key_idx+1]
sprites = {}
for i in range(0, len(frames_dict), 2):
name = frames_dict[i].text
val_dict = frames_dict[i+1]
def get_string(key_name):
for j in range(0, len(val_dict), 2):
if val_dict[j].text == key_name:
return val_dict[j+1].text
return None
tex_rect = parse_tuple(get_string("textureRect"))
spr_offset = parse_tuple(get_string("spriteOffset"))
spr_size = parse_tuple(get_string("spriteSize"))
spr_source = parse_tuple(get_string("spriteSourceSize"))
rotated = get_string("textureRotated") is not None
sprites[name] = {
"textureRect": tex_rect,
"spriteOffset": spr_offset,
"spriteSize": spr_size,
"spriteSourceSize": spr_source,
"rotated": rotated
}
logging and print(f"found {len(sprites)} sprites")
sprites_out = {}
for name, info in sprites.items():
x,y,w,h = info["textureRect"]
crop = data.crop((x,y,x+w,y+h))
if info["rotated"]:
crop = crop.rotate(-90, expand=True)
_final = Image.new("RGBA", info["spriteSourceSize"], (0,0,0,0))
ox, oy = info["spriteOffset"]
paste_x = (info["spriteSourceSize"][0]-crop.width)//2 + ox
paste_y = (info["spriteSourceSize"][1]-crop.height)//2 + oy
_final.paste(crop, (paste_x, paste_y))
sprites_out[name] = _final
return sprites_out