]> git.tdb.fi Git - libs/gl.git/blob - scripts/maketex.py
Use the correct aspect mask for uploading texture data
[libs/gl.git] / scripts / maketex.py
1 #!/usr/bin/python3
2
3 def escape(str):
4         result = ""
5         for c in str:
6                 if c=='"':
7                         result += '\\"'
8                 elif c=='\\':
9                         result += '\\\\'
10                 elif ord(c)<0x20:
11                         result += "\\{:03o}".format(ord(c))
12                 else:
13                         result += c
14         return result
15
16 def values(data, size):
17         for y in range(size[1]-1, -1, -1):
18                 for x in range(size[0]):
19                         yield data[x+y*size[0]]
20
21 def values_multi(data, size):
22         for y in range(size[1]-1, -1, -1):
23                 for x in range(size[0]):
24                         for c in data[x+y*size[0]]:
25                                 yield c
26
27 def make_tex(fn, mipmap=False, srgb=False):
28         from PIL import Image
29         import base64
30         import codecs
31
32         img = Image.open(fn)
33
34         fmt = "".join(img.getbands())
35         if fmt=="LA":
36                 fmt = "LUMINANCE8_ALPHA8"
37         elif fmt=="L":
38                 fmt = "LUMINANCE8"
39
40         if srgb:
41                 fmt = "S"+fmt
42
43         result = "storage {} {} {};\n".format(fmt, img.size[0], img.size[1])
44         if mipmap:
45                 result += "generate_mipmap true;\n"
46
47         if len(img.getbands())==1:
48                 pixels = values(img.getdata(), img.size)
49         else:
50                 pixels = values_multi(img.getdata(), img.size)
51         result += "raw_data ={}=;\n".format(codecs.decode(base64.b64encode(bytes(pixels)), "ascii"))
52
53         return result
54
55 if __name__=="__main__":
56         import os
57         import argparse
58
59         parser = argparse.ArgumentParser()
60         parser.add_argument("-o", "--output", metavar="FILE", help="Output filename")
61         parser.add_argument("-m", "--mipmap", action="store_true", help="Enable mipmaps")
62         parser.add_argument("--srgb", action="store_const", const=True, help="Use sRGB color space")
63         parser.add_argument("image")
64
65         args = parser.parse_args()
66
67         out_fn = args.output
68         if not out_fn:
69                 out_fn = os.path.splitext(args.image)[0]+".tex2d"
70         out = open(out_fn, "w")
71         out.write(make_tex(args.image, args.mipmap, args.srgb))