Search code examples
pythonopengltexturing

Texture mapping a curved rectangle in OpenGL [python]


I'm having some problems with the texture mapping in OpenGL in python. I'm trying to draw a rectangle that is curved on the top and on the bottom but so far I've been able to only get it curved on the bottom. Somehow the upper doesn't want to form a curved line. I'm using this function with a parameter of 0.2:

def DrawAWobble(y_wobble):
    R = y_wobble/2.0 - 1/(2.0*y_wobble)

    glBegin(GL_POLYGON)
    x = 0.0
    while x<2.1:
        glTexCoord2f(x*0.5, 1.0); glVertex2f(x/2 - 0.5, 0.5 + (R + math.sqrt(R**2 - (1 - x)**2 + 1)))
        x += 0.1

    x = 2.0
    while x>-0.1:
        glTexCoord2f(x*0.5, 0.0); glVertex2f(x/2 - 0.5, -0.5 + (R + math.sqrt(R**2 - (1 - x)**2 + 1)))
        x -= 0.1
    glEnd()

The result I'm getting is on the left, while I should get something like the right part of the image.

enter image description here


Solution

  • Tim, the commenteer, is right. The problem is GL_POLYGON. The issue is that the GPU has to figure out how to triangulate your arbitrary polygon, and it's doing in a way that's not preserving your mapping. What you probably want is to use a single quad strip or triangle strip for rendering this; instead of working around the edge of your polygon, alternate back and forth and work across. Something like this (obviously untested):

    def DrawAWobble(y_wobble,step=0.1):
        R = y_wobble/2.0 - 1/(2.0*y_wobble)
    
        glBegin(GL_QUAD_STRIP)
        x = 0.0
        while x<2.0+0.5*step:
            glTexCoord2f(0.5*x,0.0); glVertex2f(0.5*(x-1), -0.5 + R + (R*R-(1-x)*(1-x)+1)**0.5)
            glTexCoord2f(0.5*x,1.0); glVertex2f(0.5*(x-1),  0.5 + R + (R*R-(1-x)*(1-x)+1)**0.5)
            x += step
        glEnd()