Uniform is a global variables to using communicate from CPU to GPU in shaders. That's what I understand from Uniform. For example, if we want to manipulate the shader at CPU side, we can use uniforms for it.

Uniforms is defined in shader sources. They can be accessed by uniform methods of OpenGL in CPU. Let's make an example:

#version 330 core

in vec3 aPos;

uniform vec3 uMove;

void main()
    gl_Position = vec4(aPos + uMove, 1.0);
I added a uniform variable called uMove to the vertex shader. Let's reach this uniform via OpenGL method as follows:
private void Draw()

            // draw triangle
            int uniformLocation_Move = GL.GetUniformLocation(shader.ShaderProgram, "uMove");
            GL.Uniform3(uniformLocation_Move, positionRectangle);

            // GL.DrawArrays(PrimitiveType.Triangles, 0, 3);
            GL.DrawElements(PrimitiveType.Triangles, 6, DrawElementsType.UnsignedInt, 0);
I opened Window class and added new property called ActiveKey and the keyboard key value will be assigned when the user pressed the key via EventHandler that I added like in the below:
    public class Window : RenderWindow

        public Keyboard.Key ActiveKey {get; set;}


        private void InitWindowSettings()
            view = new View(new FloatRect(0, 0, this.Size.X, this.Size.Y));
            this.Closed += (o, e) => { this.Close(); };
            this.Resized += (o, e) => { Resize((int)e.Width, (int)e.Height); };
            this.KeyPressed += (o, e) => { ActiveKey = e.Code; };
            GL.Viewport(0, 0, (int)this.Size.X, (int)this.Size.Y);
Turn back to the App class and change the update method like this:
        private void Update()
            if(window.ActiveKey == Keyboard.Key.A) positionRectangle -= new OpenTK.Mathematics.Vector3(0.01f, 0f, 0f);
            if(window.ActiveKey == Keyboard.Key.D) positionRectangle += new OpenTK.Mathematics.Vector3(0.01f, 0f, 0f);
            if(window.ActiveKey == Keyboard.Key.W) positionRectangle += new OpenTK.Mathematics.Vector3(0f, 0.01f, 0f);
            if(window.ActiveKey == Keyboard.Key.S) positionRectangle -= new OpenTK.Mathematics.Vector3(0f, 0.01f, 0f);
            window.ActiveKey = Keyboard.Key.Unknown;
After that, we can move the rectangle with keyboard on the screen. This is an ugly code. Normally, we have to organize the project as well. But it's just for learning stage.

No comments:

Post a Comment