2D Top-Left Coordinate System in Modern OpenGL

Normally, The positioning of things in OpenGL seems not understandable at least for me. When I coding a game I used a top-left origin coordinate system, however, it's not general standard in game development.  

OpenGL uses a clipping area as a coordinate system like below:

But if we resize according to viewport:

    def render(self):
        glViewPort(0, 0, self.width, self.height)
We convert to clip space to screen space briefly and specified our canvas dimension to the OpenGL.

OpenGL have to know our screen dimension to conversion operation in vertex shader. So I'm going to use a uniform function to manipulate vertex shader:
#version 330 core

layout (location = 0) in vec2 position;
layout (location = 1) in vec3 color;

uniform vec2 screen_dim;

out vec3 passColor;

void main(){
    vec2 pos_RatioTo1 = position / screen_dim;
    vec2 clip_space = (pos_RatioTo1 * 2.0) - 1;

    gl_Position = vec4(clip_space, 0.0, 1.0);
    passColor = color;
I typed two methods called addUnform and setUniform2f to make easier to usage in ShaderProgram class.
def addUniform(self, uniformName):
    self.uniforms[uniformName] = glGetUniformLocation(self.programID, uniformName)

def setUniform2f(self, uniformName, value)
    glUniform2f(self.uniforms[uniformName], value)
So I changed app source by updates above:
def generate(self):
    self.shader = ShaderProgram("./shaders/vs.glsl", "./shaders/fs.glsl")

def render(self):
    glViewport(0, 0, self.width, self.height)


    self.shader.setUniform2f("screen_dim", Vector2(self.width, self.height))
So I reorganized positions of vertices like that:
self.buffer['pos'] = [(200, 50), (500, 500), (800,  50)]
Let's examine the result:
opengl coordinate system

But It's not a top-left coordinate system. It's bottom-left coordinate system. So I have to change glPosition variable value in vertex shader source code like this:
gl_Position = vec4(clip_space * vec2(1, -1), 0.0, 1.0);
This multiply operation just reverses of y-axis direction as opposite entirely. There is no affect on the x-axis by knowledge from school math and the result:
top-left coordinate system in OpenGL

No comments:

Post a Comment