Search code examples
openglpygametexturespyopenglopengl-compat

How to scale pyopengl texture size to pygame window size?


Windows size : 640 * 480

Texture size : 1280 * 720

Hello, How can I scale the texture to the pygame window?


Solution

  • You've setup an orthographic projection:

    glOrtho(0, self.windowWidth, self.windowHeight, 0, -1, 1)
    

    If you want the texture to fill the whole window, then you have to draw a quad corresponding to the orthographic projection and the texture coordinates form (0, 0) to (1, 1):

    glEnable(GL_TEXTURE_2D)
    
    glBegin(GL_QUAD)
    
    glTexCoord2f(0, 0)
    glVertex2f(0, 0)
    
    glTexCoord2f(1, 0)
    glVertex2f(self.windowWidth, 0)
    
    glTexCoord2f(1, 1)
    glVertex2f(self.windowWidth, self.windowHeight)
    
    glTexCoord2f(0, 1)
    glVertex2f(0, self.windowHeight)
    
    glEnd()
    

    If you wan to keep the aspect ratio of the texture, then you have to scale the size of the quad. For instance:

    left = 0
    top = 0
    width = self.windowWidth
    height = self.windowHeight
    
    sx = self.windowWidth / textureWidth 
    sy = self.windowHeight / textureHeight 
    if sx > sy:
        width *= sy / sx
        left = (self.windowWidth - width) / 2
    else:
        height *= sx / sy  
        top = (self.windowHeight - height) / 2
    
    glEnable(GL_TEXTURE_2D)
    
    glBegin(GL_QUAD)
    glTexCoord2f(0, 0)
    glVertex2f(left, top)
    glTexCoord2f(1, 0)
    glVertex2f(left + width, top)
    glTexCoord2f(1, 1)
    glVertex2f(left + width, top + height)
    glTexCoord2f(0, 1)
    glVertex2f(left, top + height)
    glEnd()