Search code examples
pythonopenglpyopenglopengl-compat

glOrtho doesent work it still gets mapped to default coordinates


so im using pyopengl in python to use opengl but when i use glOrtho in my reshape function to map my coordinates it doesn't work it still gets mapped to -1 - 1 here is my code:

from OpenGL.GLUT import *
from OpenGL.GL import *

width, height = 500,500

def rectangle(x, y, width, height, color, fill):
    if fill:
        glBegin(GL_POLYGON)
        glColor3ub(color[0], color[1], color[2])
        glVertex2f(x - width/2, y + height/2)
        glVertex2f(x + width/2, y + height/2)
        glVertex2f(x + width/2, y - height/2)
        glVertex2f(x - width/2, y - height/2)
        glColor3ub(255, 255, 255)
        glEnd()
    else:
        glBegin(GL_LINES)
        glColor3ub(color[0], color[1], color[2])
        glVertex2f(x - width/2, y + height/2)
        glVertex2f(x + width/2, y + height/2)
        glVertex2f(x + width/2, y - height/2)
        glVertex2f(x - width/2, y - height/2)
        glColor3ub(255, 255, 255)
        glEnd()

def draw():
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
    glClearColor(0.25, 0.25, 0.25, 1)
    glLoadIdentity()

    glBegin(GL_POLYGON)
    glVertex2f(1, 1)
    glVertex2f(-1, 1)
    glVertex2f(-1, -1)
    glVertex2f(100, -1)
    glEnd()

    glutSwapBuffers()


def reshape(w, h):
    glMatrixMode(GL_PROJECTION)
    glLoadIdentity()
    glOrtho(0, w, 0, h, 0, 1000)


glutInit()
glutInitDisplayMode(GLUT_RGBA) # Set the display mode to be colored
glutInitWindowSize(width, height)   # Set the w and h of your window
glutInitWindowPosition(0, 0)   # Set the position at which this windows should appear
window = glutCreateWindow("OpenGL") # Set a window title
glutReshapeFunc(reshape)
glutDisplayFunc(draw) # defines display func
glutIdleFunc(draw) # Keeps the window open
glutMainLoop()  # Keeps the above created window displaying/running in a loop

help me solve this problem i dont see a reason why it doesn't work


Solution

  • glOrtho doesn't work because in the glLoadIdentity() instruction in the draw function. glLoadIdentity() loads the Identity matrix. Change the matrix mode after glOrtho with glMatrixMode. This ensures that the projection matrix is preserved, but the identity matrix is loaded into the model view matrix. OpenGL is a state engine. Once a state has been changed, it is retained until it is changed again, even beyond frames.

    def reshape(w, h):
        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()
        glOrtho(0, w, 0, h, 0, 1000)
        glMatrixMode(GL_MODELVIEW)