Simplify texreader.parse_ppm()
[bsnes:xml-shaders.git] / reference / texreader.py
1 #!/usr/bin/python
2 import re
3 import string
4
5 TOKEN_RE = re.compile("[^" + string.whitespace + "]+")
6 WS_RE = re.compile("[" + string.whitespace + "]+")
7
8
9 class TexReaderException(Exception):
10         pass
11
12
13 def parse_ppm(data):
14         """
15         Parse the PPM data from the given byte string.
16         """
17         try:
18                 magic, widthStr, heightStr, sampleMaxStr, pixelData = \
19                                 data.split(None, 4)
20         except ValueError:
21                 raise TexReaderException("Can't parse data: %r..." % (data[:40],))
22
23         if magic != "P6":
24                 raise TexReaderException("Unrecognised magic %r" % (magic,))
25
26         try:
27                 width = int(widthStr)
28                 height = int(heightStr)
29                 sampleMax = int(sampleMaxStr)
30         except ValueError, e:
31                 raise TexReaderException("Can't parse data: %s" % (str(e),))
32
33         if sampleMax != 255:
34                 raise TexReaderException("Textures must have 8 bits per channel.")
35
36         if len(pixelData) != (width * height * 3):
37                 raise TexReaderException("Got %d bytes of pixel data, expected %d"
38                                 % (len(pixelData), width * height * 3))
39
40         # Now to convert this packed RGB pixel data to RGBA data that OpenGL can
41         # understand.
42         pixels = []
43         for pxOffset in range(0, (width * height * 3), 3):
44                 pixels.append(pixelData[pxOffset:pxOffset+3])
45                 pixels.append("\xff")
46
47         return (width, height, "".join(pixels))
48
49
50 if __name__ == "__main__":
51         import sys
52         with open(sys.argv[1]) as handle:
53                 data = handle.read()
54                 print parse_ppm(data)