Fix tabs in test shader.
[bsnes:xml-shaders.git] / reference / shaderview.py
1 #!/usr/bin/python
2 import sys, time
3 import os
4 import os.path
5 import OpenGL
6 from OpenGL.GL import *
7 from OpenGL.GLUT import *
8 from OpenGL.GL import framebufferobjects
9 import texreader
10 import shaderreader
11
12
13 BASEDIR = os.path.abspath(os.path.dirname(__file__))
14
15
16 def load_textures(texturePath):
17         res = []
18
19         for name in os.listdir(texturePath):
20                 if not name.endswith(".ppm"):
21                         continue
22
23                 fullpath = os.path.join(texturePath, name)
24                 res.append(
25                                 (name, texreader.textureFromFile(fullpath))
26                         )
27
28         res.sort()
29
30         return res
31
32
33 def scale_integer(windowW, windowH, inputW, inputH):
34         """
35         Calculates the image as the largest integer multiple of raw frame size.
36         """
37         scaleX = windowW / inputW
38         scaleY = windowH / inputH
39
40         if scaleX > 0 and scaleY > 0:
41                 scale = min(scaleX, scaleY)
42                 finalW = scale * inputW
43                 finalH = scale * inputH
44         else:
45                 if scaleX == 0:
46                         finalW = windowW
47                 else:
48                         finalW = inputW
49
50                 if scaleY == 0:
51                         finalH = windowH
52                 else:
53                         finalH = inputH
54
55         return finalW, finalH
56
57
58 def scale_aspect(windowW, windowH, inputW, inputH):
59         """
60         Calculates the image as the largest multiple of the raw frame size.
61         """
62         scale = min(
63                         float(windowW) / float(inputW),
64                         float(windowH) / float(inputH),
65                 )
66
67         return inputW * scale, inputH * scale
68
69
70 def scale_max(windowW, windowH, inputW, inputH):
71         """
72         Stretch the image to the largest possible size, regardless of aspect.
73         """
74         return windowW, windowH
75
76
77 SCALE_METHODS = [
78                 ("Integer", scale_integer),
79                 ("Aspect-correct", scale_aspect),
80                 ("Maximized", scale_max),
81         ]
82
83
84 class GLUTDemo(object):
85
86         def __init__(self, shaderFile, texturePath):
87                 self.start = time.clock()
88                 self.framecount = 0
89
90                 glutInitDisplayMode(GLUT_RGBA)
91
92                 glutInitWindowSize(640, 480)
93                 self.window = glutCreateWindow("XML Shader Demo - Esc to exit")
94                 self.windowW = None
95                 self.windowH = None
96
97                 glutDisplayFunc(self._draw_scene)
98                 glutIdleFunc(self._handle_idle)
99                 glutReshapeFunc(self._handle_resize)
100                 glutKeyboardFunc(self._handle_key)
101
102                 glClearColor(0.0, 0.0, 0.0, 0.0)
103                 glEnable(GL_TEXTURE_2D)
104
105                 with open(shaderFile, "r") as handle:
106                         self.shaderPasses = shaderreader.parse_shader(handle.read())
107
108                 self.textures = load_textures(texturePath)
109                 textureMenu = glutCreateMenu(self._set_texture)
110                 for index, (filename, _) in enumerate(self.textures):
111                         glutAddMenuEntry(filename, index)
112
113                 self.inputTexture = None
114                 self._set_texture(0)
115
116                 self.framebufferID = framebufferobjects.glGenFramebuffers(1)
117                 self.framebufferTexture1, self.framebufferTexture2 = \
118                                 glGenTextures(2)
119
120                 scaleMenu = glutCreateMenu(self._set_scale_method)
121                 for index, (desc, _) in enumerate(SCALE_METHODS):
122                         glutAddMenuEntry(desc, index)
123
124                 self._set_scale_method(0)
125
126                 self.masterMenu = glutCreateMenu(lambda _: 0)
127                 glutAddSubMenu("Test pattern", textureMenu)
128                 glutAddSubMenu("Scale method", scaleMenu)
129                 glutAttachMenu(GLUT_RIGHT_BUTTON)
130
131         def _set_texture(self, textureIndex):
132
133                 _, self.inputTexture = self.textures[textureIndex]
134
135                 # According to the OpenGL docs, a glutCreateMenu callback doesn't need
136                 # to return anything. PyOpenGL seems to think differently.
137                 return 0
138
139         def _set_scale_method(self, index):
140                 self.scaleMethod = SCALE_METHODS[index][1]
141
142                 # According to the OpenGL docs, a glutCreateMenu callback doesn't need
143                 # to return anything. PyOpenGL seems to think differently.
144                 return 0
145
146         def _setUniform(self, setter, program, name, *values):
147                 loc = glGetUniformLocation(program, name)
148                 if loc < 0:
149                         return
150
151                 setter(loc, *values)
152
153         def _draw_texture(self, shaderPass, texture, x, y, width, height):
154                 if shaderPass is not None:
155                         glUseProgram(shaderPass.programID)
156
157                         self._setUniform(glUniform2f, shaderPass.programID,
158                                         "rubyInputSize", texture.width, texture.height)
159                         self._setUniform(glUniform2f, shaderPass.programID,
160                                         "rubyOutputSize", width, height)
161                         self._setUniform(glUniform2f, shaderPass.programID,
162                                         "rubyTextureSize", texture.width, texture.height)
163                         self._setUniform(glUniform1i, shaderPass.programID,
164                                         "rubyFrameCount", self.framecount)
165
166                         if shaderPass.filterMethod == shaderreader.ATTR_FILTER_LINEAR:
167                                 filterID = GL_LINEAR
168                         else:
169                                 filterID = GL_NEAREST
170
171                 else:
172                         # There's no shader pass to tell us what to do, so go with a safe
173                         # default.
174                         if shaderreader.ATTR_FILTER_DEFAULT == shaderreader.ATTR_FILTER_LINEAR:
175                                 filterID = GL_LINEAR
176                         else:
177                                 filterID = GL_NEAREST
178
179                 glBindTexture(GL_TEXTURE_2D, texture.textureID)
180
181                 glTexParameter(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, filterID)
182                 glTexParameter(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, filterID)
183
184                 glClear(GL_COLOR_BUFFER_BIT)
185
186                 glBegin(GL_QUADS)                   # Start drawing a 4 sided polygon
187
188                 glTexCoord2f(0,   0  ); glVertex(x,       y,      )
189                 glTexCoord2f(1.0, 0  ); glVertex(x+width, y,      )
190                 glTexCoord2f(1.0, 1.0); glVertex(x+width, y+height)
191                 glTexCoord2f(0,   1.0); glVertex(x,       y+height)
192
193                 glEnd()                             # We are done with the polygon
194
195                 if shaderPass is not None:
196                         glUseProgram(0)
197
198         def _draw_texture_to_fbo(self, shaderPass, fromTexture, finalW, finalH):
199
200                 # How big should the output of this pass be?
201                 outputW, outputH = shaderPass.calculateFramebufferSize(
202                                 fromTexture.width, fromTexture.height, finalW, finalH,
203                         )
204
205                 # If this pass doesn't specify a size, default to the input.
206                 if outputW is None: outputW = fromTexture.width
207                 if outputH is None: outputH = fromTexture.height
208
209                 # Make a texture exactly that big.
210                 toTexture = texreader.Texture(outputW, outputH)
211
212                 # Configure OpenGL to render to the texture.
213                 framebufferobjects.glBindFramebuffer(
214                                 framebufferobjects.GL_FRAMEBUFFER,
215                                 self.framebufferID,
216                         )
217                 framebufferobjects.glFramebufferTexture2D(
218                                 framebufferobjects.GL_FRAMEBUFFER,
219                                 framebufferobjects.GL_COLOR_ATTACHMENT0,
220                                 GL_TEXTURE_2D,
221                                 toTexture.textureID,
222                                 0,
223                         )
224
225                 # Are we all set?
226                 framebufferobjects.checkFramebufferStatus()
227
228                 glViewport(0, 0, int(outputW), int(outputH))
229                 glMatrixMode(GL_PROJECTION)
230                 glLoadIdentity()
231                 # A framebufferobject will always have the underlying texture's (0,0)
232                 # at the lower-left, so align our coordinate system to match.
233                 glOrtho(0, outputW, 0, outputH, -1, 1)
234
235                 self._draw_texture(shaderPass, fromTexture, 0, 0, outputW, outputH)
236
237                 # Detach all the things we set up.
238                 framebufferobjects.glBindFramebuffer(
239                                 framebufferobjects.GL_FRAMEBUFFER,
240                                 0,
241                         )
242
243                 return toTexture
244
245         def _draw_scene(self):
246                 if None in (self.inputTexture, self.windowW, self.windowH):
247                         return
248
249                 finalW, finalH = self.scaleMethod(
250                                 self.windowW, self.windowH,
251                                 self.inputTexture.width, self.inputTexture.height,
252                         )
253
254                 finalX = (self.windowW - finalW) / 2
255                 finalY = (self.windowH - finalH) / 2
256
257                 # Will we need an implicit pass at the end of this?
258                 requiresImplicitPass = self.shaderPasses[-1].requiresImplicitPass()
259
260                 # Render all but the last pass
261                 fromTexture = self.inputTexture
262                 for shaderPass in self.shaderPasses[:-1]:
263                         fromTexture = self._draw_texture_to_fbo(
264                                         shaderPass, fromTexture, finalW, finalH)
265
266                 # If the last pass expects to be rendered at some specific scale, we'd
267                 # better respect its wishes.
268                 if requiresImplicitPass:
269                         fromTexture = self._draw_texture_to_fbo(
270                                         self.shaderPasses[-1], fromTexture, finalW, finalH)
271                         lastPass = None
272                 else:
273                         lastPass = self.shaderPasses[-1]
274
275                 glViewport(0, 0, self.windowW, self.windowH)
276                 glMatrixMode(GL_PROJECTION)
277                 glLoadIdentity()
278                 # After all the shader passes, the (0,0) corner of the resulting
279                 # texture is supposed to appear at the top-left, so let's set our
280                 # coordinate system appropriately.
281                 glOrtho(0, self.windowW, self.windowH, 0, -1, 1)
282
283                 self._draw_texture(lastPass, fromTexture,
284                                 finalX, finalY, finalW, finalH,
285                         )
286
287                 glFlush()
288
289         def _handle_key(self, key, x, y):
290                 if key == '\x1b': # Escape
291                         self._shutdown()
292
293         def _handle_resize(self, width, height):
294                 self.windowW = max(width, 1)
295                 self.windowH = max(height, 1)
296
297         def _handle_idle(self):
298                 now = time.clock()
299                 if now > self.start + 1:
300                         fps = self.framecount / (now - self.start)
301                         sys.stdout.write("FPS: %0.1f\r" % fps)
302                         sys.stdout.flush()
303                         self.framecount = 0
304                         self.start = now
305
306                 glutPostWindowRedisplay(self.window)
307                 self.framecount += 1
308
309         def _shutdown(self):
310                 # clean up textures we've allocated.
311                 for _, texture in self.textures:
312                         texture.destroy()
313
314                 # There's no clean way to kill GLUT.
315                 sys.exit(0)
316
317 if __name__ == "__main__":
318         argv = glutInit(sys.argv)
319
320         if len(argv) != 2:
321                 print >> sys.stderr, "Usage: %s /path/to/shaderfile" % (argv[0],)
322                 sys.exit(1)
323
324         shaderFile = argv[1]
325         texturePath = os.path.join(BASEDIR, "test-patterns")
326         demo = GLUTDemo(shaderFile, texturePath)
327
328         glutMainLoop()