6 from OpenGL.GL import *
7 from OpenGL.GLUT import *
8 from OpenGL.GL import framebufferobjects
13 BASEDIR = os.path.abspath(os.path.dirname(__file__))
16 def load_textures(texturePath):
19 for name in os.listdir(texturePath):
20 if not name.endswith(".ppm"):
23 fullpath = os.path.join(texturePath, name)
25 (name, texreader.textureFromFile(fullpath))
31 def scale_integer(windowW, windowH, inputW, inputH):
33 Calculates the image as the largest integer multiple of raw frame size.
35 scaleX = windowW / inputW
36 scaleY = windowH / inputH
38 if scaleX > 0 and scaleY > 0:
39 scale = min(scaleX, scaleY)
40 finalW = scale * inputW
41 finalH = scale * inputH
56 def scale_aspect(windowW, windowH, inputW, inputH):
58 Calculates the image as the largest multiple of the raw frame size.
61 float(windowW) / float(inputW),
62 float(windowH) / float(inputH),
65 return inputW * scale, inputH * scale
68 def scale_max(windowW, windowH, inputW, inputH):
70 Stretch the image to the largest possible size, regardless of aspect.
72 return windowW, windowH
76 ("Integer", scale_integer),
77 ("Aspect-correct", scale_aspect),
78 ("Maximized", scale_max),
82 class GLUTDemo(object):
84 def __init__(self, shaderFile, texturePath):
85 self.start = time.clock()
88 glutInitDisplayMode(GLUT_RGBA)
90 glutInitWindowSize(640, 480)
91 self.window = glutCreateWindow("XML Shader Demo - Esc to exit")
95 glutDisplayFunc(self._draw_scene)
96 glutIdleFunc(self._handle_idle)
97 glutReshapeFunc(self._handle_resize)
98 glutKeyboardFunc(self._handle_key)
100 glClearColor(0.0, 0.0, 0.0, 0.0)
101 glEnable(GL_TEXTURE_2D)
103 with open(shaderFile, "r") as handle:
104 self.shaderPasses = shaderreader.parse_shader(handle.read())
106 self.textures = load_textures(texturePath)
107 textureMenu = glutCreateMenu(self._set_texture)
108 for index, (filename, _) in enumerate(self.textures):
109 glutAddMenuEntry(filename, index)
111 self.inputTexture = None
114 self.framebufferID = framebufferobjects.glGenFramebuffers(1)
115 self.framebufferTexture1, self.framebufferTexture2 = \
118 scaleMenu = glutCreateMenu(self._set_scale_method)
119 for index, (desc, _) in enumerate(SCALE_METHODS):
120 glutAddMenuEntry(desc, index)
122 self._set_scale_method(0)
124 self.masterMenu = glutCreateMenu(lambda _: 0)
125 glutAddSubMenu("Test pattern", textureMenu)
126 glutAddSubMenu("Scale method", scaleMenu)
127 glutAttachMenu(GLUT_RIGHT_BUTTON)
129 def _set_texture(self, textureIndex):
131 _, self.inputTexture = self.textures[textureIndex]
133 # According to the OpenGL docs, a glutCreateMenu callback doesn't need
134 # to return anything. PyOpenGL seems to think differently.
137 def _set_scale_method(self, index):
138 self.scaleMethod = SCALE_METHODS[index][1]
140 # According to the OpenGL docs, a glutCreateMenu callback doesn't need
141 # to return anything. PyOpenGL seems to think differently.
144 def _setUniform(self, program, name, x, y):
145 loc = glGetUniformLocation(program, name)
150 glUniform2f(loc, x, y)
152 def _draw_texture(self, shaderPass, texture, x, y, width, height):
153 if shaderPass is not None:
154 glUseProgram(shaderPass.programID)
156 self._setUniform(shaderPass.programID, 'rubyInputSize',
157 texture.width, texture.height)
158 self._setUniform(shaderPass.programID, 'rubyOutputSize',
160 self._setUniform(shaderPass.programID, 'rubyTextureSize',
161 texture.width, texture.height)
162 loc = glGetUniformLocation(shaderPass.programID, 'rubyFrameCount')
164 glUniform1i(loc, self.framecount)
166 if shaderPass.filterMethod == shaderreader.ATTR_FILTER_LINEAR:
169 filterID = GL_NEAREST
172 # There's no shader pass to tell us what to do, so go with a safe
176 glBindTexture(GL_TEXTURE_2D, texture.textureID)
178 glTexParameter(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, filterID)
179 glTexParameter(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, filterID)
181 glClear(GL_COLOR_BUFFER_BIT)
183 glBegin(GL_QUADS) # Start drawing a 4 sided polygon
185 glTexCoord2f(0, 0 ); glVertex(x, y, )
186 glTexCoord2f(1.0, 0 ); glVertex(x+width, y, )
187 glTexCoord2f(1.0, 1.0); glVertex(x+width, y+height)
188 glTexCoord2f(0, 1.0); glVertex(x, y+height)
190 glEnd() # We are done with the polygon
192 if shaderPass is not None:
195 def _draw_texture_to_fbo(self, shaderPass, fromTexture, finalW, finalH):
197 # How big should the output of this pass be?
198 outputW, outputH = shaderPass.calculateFramebufferSize(
199 fromTexture.width, fromTexture.height, finalW, finalH,
202 # If this pass doesn't specify a size, default to the input.
203 if outputW is None: outputW = fromTexture.width
204 if outputH is None: outputH = fromTexture.height
206 # Make a texture exactly that big.
207 toTexture = texreader.Texture(outputW, outputH)
209 # Configure OpenGL to render to the texture.
210 framebufferobjects.glBindFramebuffer(
211 framebufferobjects.GL_FRAMEBUFFER,
214 framebufferobjects.glFramebufferTexture2D(
215 framebufferobjects.GL_FRAMEBUFFER,
216 framebufferobjects.GL_COLOR_ATTACHMENT0,
223 framebufferobjects.checkFramebufferStatus()
225 glViewport(0, 0, int(outputW), int(outputH))
226 glMatrixMode(GL_PROJECTION)
228 # A framebufferobject will always have the underlying texture's (0,0)
229 # at the lower-left, so align our coordinate system to match.
230 glOrtho(0, outputW, 0, outputH, -1, 1)
232 self._draw_texture(shaderPass, fromTexture, 0, 0, outputW, outputH)
234 # Detach all the things we set up.
235 framebufferobjects.glBindFramebuffer(
236 framebufferobjects.GL_FRAMEBUFFER,
242 def _draw_scene(self):
243 if None in (self.inputTexture, self.windowW, self.windowH):
246 finalW, finalH = self.scaleMethod(
247 self.windowW, self.windowH,
248 self.inputTexture.width, self.inputTexture.height,
251 finalX = (self.windowW - finalW) / 2
252 finalY = (self.windowH - finalH) / 2
254 # Will we need an implicit pass at the end of this?
255 requiresImplicitPass = self.shaderPasses[-1].requiresImplicitPass()
257 # Render all but the last pass
258 fromTexture = self.inputTexture
259 for shaderPass in self.shaderPasses[:-1]:
260 fromTexture = self._draw_texture_to_fbo(
261 shaderPass, fromTexture, finalW, finalH)
263 # If the last pass expects to be rendered at some specific scale, we'd
264 # better respect its wishes.
265 if requiresImplicitPass:
266 fromTexture = self._draw_texture_to_fbo(
267 self.shaderPasses[-1], fromTexture, finalW, finalH)
270 lastPass = self.shaderPasses[-1]
272 glViewport(0, 0, self.windowW, self.windowH)
273 glMatrixMode(GL_PROJECTION)
275 # After all the shader passes, the (0,0) corner of the resulting
276 # texture is supposed to appear at the top-left, so let's set our
277 # coordinate system appropriately.
278 glOrtho(0, self.windowW, self.windowH, 0, -1, 1)
280 self._draw_texture(lastPass, fromTexture,
281 finalX, finalY, finalW, finalH,
286 def _handle_key(self, key, x, y):
287 if key == '\x1b': # Escape
290 def _handle_resize(self, width, height):
291 self.windowW = max(width, 1)
292 self.windowH = max(height, 1)
294 def _handle_idle(self):
296 if now > self.start + 1:
297 fps = self.framecount / (now - self.start)
298 sys.stdout.write("FPS: %0.1f\r" % fps)
303 glutPostWindowRedisplay(self.window)
307 # clean up textures we've allocated.
308 for _, texture in self.textures:
311 # There's no clean way to kill GLUT.
314 if __name__ == "__main__":
315 argv = glutInit(sys.argv)
318 print >> sys.stderr, "Usage: %s /path/to/shaderfile" % (argv[0],)
322 texturePath = os.path.join(BASEDIR, "test-patterns")
323 demo = GLUTDemo(shaderFile, texturePath)