C#/OpenTK - 将着色器应用于加载的纹理时出现问题。纹理按比例缩小并翻转

C#/OpenTK - Problems applying shaders to loaded texture. Texture is scaled down and flipped

我一直在想办法让它发挥作用。我正在使用 C# 的 OpenTK 来修改图像。现在我能够成功加载图像,但是当我尝试使用着色器修改图像时,我开始遇到问题。我有 3 个基本方法:

所以这是我遇到的 2 个问题:

这是我成功加载为纹理的图像:Loaded Texture

这是 LoadTexture 的代码:

      public int LoadTexture(string file)
    {
        Bitmap bitmap = new Bitmap(file);

        int tex;
        GL.Hint(HintTarget.PerspectiveCorrectionHint, HintMode.Nicest);

        GL.GenTextures(1, out tex);
        GL.BindTexture(TextureTarget.Texture2D, tex);

        BitmapData data = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height),
       ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

        GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, data.Width, data.Height, 0,
        OpenTK.Graphics.OpenGL.PixelFormat.Bgra, PixelType.UnsignedByte, data.Scan0);
        bitmap.UnlockBits(data);


        GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear);
        GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear);
        GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)TextureWrapMode.Repeat);
        GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)TextureWrapMode.Repeat);

        return tex;
    }

这里是 DrawImage 的代码:

        public static void DrawImage(int image)
    {


        GL.MatrixMode(MatrixMode.Projection);
        GL.PushMatrix();
        GL.LoadIdentity();

        GL.Ortho(0, 1920, 0, 1080, -1, 1);

        GL.MatrixMode(MatrixMode.Modelview);
        GL.PushMatrix();
        GL.LoadIdentity();

        GL.Disable(EnableCap.Lighting);

        GL.Enable(EnableCap.Texture2D);

        GL.ActiveTexture(TextureUnit.Texture0);
        GL.BindTexture(TextureTarget.Texture2D, image);

        GL.Begin(PrimitiveType.Quads);

        GL.TexCoord2(0,1);
        GL.Vertex3(0, 0, 0);

        GL.TexCoord2(1, 1);
        GL.Vertex3(1920, 0, 0);

        GL.TexCoord2(1, 0);
        GL.Vertex3(1920, 1080, 0);

        GL.TexCoord2(0, 0);
        GL.Vertex3(0, 1080, 0);


        GL.End();

        AddShaders();

        GL.Disable(EnableCap.Texture2D);
        GL.PopMatrix();

        GL.MatrixMode(MatrixMode.Projection);
        GL.PopMatrix();

        GL.MatrixMode(MatrixMode.Modelview);

        ErrorCode ec = GL.GetError();
        if (ec != 0)
            System.Console.WriteLine(ec.ToString());
        Console.Read();

    }

这是 AddShaders 的代码:

      private static void AddShaders()
    {

        /***********Vert Shader********************/
        var vertShader = GL.CreateShader(ShaderType.VertexShader);
        GL.ShaderSource(vertShader, @"attribute vec3 a_position;
                                        varying vec2 vTexCoord;
                                        void main() {
                                        vTexCoord = a_position.xy;
                                        gl_Position = vec4(a_position, 1);
                                        }");
        GL.CompileShader(vertShader);


        /***********Frag Shader ****************/
        var fragShader = GL.CreateShader(ShaderType.FragmentShader);
        GL.ShaderSource(fragShader, @"uniform sampler2D sTexture;
                                      varying vec2 vTexCoord;
                                void main ()
                                {
                                    vec4    color   = texture2D (sTexture, vTexCoord);
                                    color.r = 0.5;
                                    // Save the result
                                    gl_FragColor    = color;
                                }");
        GL.CompileShader(fragShader);

        var program = GL.CreateProgram();
        GL.AttachShader(program, vertShader);
        GL.AttachShader(program, fragShader);
        GL.LinkProgram(program);
        GL.ClearColor(Color.AliceBlue);

        // OpenGL expects vertices to be defined counter clockwise by default
        float[] vertices = {
                // Left bottom triangle
                -1f, 1f, 0f,
                -1f, -1f, 0f,
                1f, -1, 0f,
                // Right top triangle
                1f, -1f, 0f,
                1f, 1f, 0f,
                -1f, 1f, 0f
        };

        var buffer = GL.GenBuffer();
        var positionLocation = GL.GetAttribLocation(program, "a_position");
        GL.EnableVertexAttribArray(positionLocation);
        GL.BindBuffer(BufferTarget.ArrayBuffer, buffer);
        GL.VertexAttribPointer(positionLocation, 3, VertexAttribPointerType.Float,false,0,0);
        GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(vertices.Length * sizeof(ushort)), vertices, BufferUsageHint.StaticDraw);

        GL.DrawArrays(PrimitiveType.Triangles, 0, vertices.Length);
        GL.UseProgram(program);

    }  

我已经对此研究了几天,但我完全被困住了。感谢任何能看到我做错了什么的人。对我而言,它必须是一些小而愚蠢的东西!

编辑:当我删除 AddShaders 中的所有顶点相关代码时,我得到了我想要的输出,除了它的 1/4 大小并在屏幕右上角翻转。所以,不知何故,我的着色器甚至不关心顶点。为什么要缩小到 1/4 尺寸并翻转?

EDIT2:好的,多亏了 Robert Rouhani,我几乎完成了这项工作! Progress 三角形的顶点好像乱了??

这是我的新代码。我将功能重构为方法,停止每帧创建程序/缓冲区等。现在我有 class 级变量来保存 GL 特定数据,为应用程序创建 GL 程序的方法,创建着色器,创建缓冲区等。我也知道 1920x1080 硬编码是硬编码的。这是我的盘子,使动态。

    string file = "lambo2.png";
    int program;
    int vertShader;
    int fragShader;
    int buffer;
    int positionLocation;
    int texture;
    float[] vertices = {
                // Left bottom triangle
                -1f, -1f, 0f,
                1f, -1f, 0f,
                1f, 1f, 0f,
                // Right top triangle
                1f, 1f, 0f,
                  -1f, 1f, 0f,
                 -1f, -1f, 0f
        };


    private void CreateProgram()
    {
        program = GL.CreateProgram();
        GL.AttachShader(program, vertShader);
        GL.AttachShader(program, fragShader);
        GL.LinkProgram(program);
    }
    private void CreateShaders()
    {
        /***********Vert Shader********************/
        vertShader = GL.CreateShader(ShaderType.VertexShader);
        GL.ShaderSource(vertShader, @"attribute vec3 a_position;
                                        varying vec2 vTexCoord;
                                        void main() {
                                        vTexCoord = (a_position.xy + 1) / 2;
                                        gl_Position = vec4(a_position, 1);
                                        }");
        GL.CompileShader(vertShader);


        /***********Frag Shader ****************/
        fragShader = GL.CreateShader(ShaderType.FragmentShader);
        GL.ShaderSource(fragShader, @"precision highp float;
        uniform sampler2D sTexture;
                                       varying vec2 vTexCoord;
                                 void main ()
                                 {
                                     vec4    color   = texture2D (sTexture, vTexCoord);
                                     if(color.r < 0.3){color.r = 1.0;}
                                     // Save the result
                                     gl_FragColor    = color;
                                 }");
        //   GL.ShaderSource(fragShader, System.IO.File.ReadAllText(@"C:\Users\Matt\Desktop\hue-shader-backup.ps"));
        GL.CompileShader(fragShader);
    }
    private void InitBuffers()
    {
        buffer = GL.GenBuffer();
        positionLocation = GL.GetAttribLocation(program, "a_position");
        GL.EnableVertexAttribArray(positionLocation);
        GL.BindBuffer(BufferTarget.ArrayBuffer, buffer);
        GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(vertices.Length * sizeof(ushort)), vertices, BufferUsageHint.StaticDraw);
        GL.VertexAttribPointer(positionLocation, 3, VertexAttribPointerType.Float, false, 0, 0);
    }
    private void Init()
    {
        texture = LoadTexture(file);
        CreateShaders();
        CreateProgram();
        InitBuffers();
    }
    public int LoadTexture(string file)
    {
        Bitmap bitmap = new Bitmap(file);

        int tex;
        GL.Hint(HintTarget.PerspectiveCorrectionHint, HintMode.Nicest);

        GL.GenTextures(1, out tex);
        GL.BindTexture(TextureTarget.Texture2D, tex);
        bitmap.RotateFlip(RotateFlipType.RotateNoneFlipY);
        BitmapData data = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height),
       ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

        GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, data.Width, data.Height, 0,
        OpenTK.Graphics.OpenGL.PixelFormat.Bgra, PixelType.UnsignedByte, data.Scan0);
        bitmap.UnlockBits(data);


        GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear);
        GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear);
        GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)TextureWrapMode.ClampToEdge);
        GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)TextureWrapMode.ClampToEdge);

        return tex;
    }

    public void DrawImage(int image)
    {

        GL.Viewport(new Rectangle(0, 0, 1920, 1080));
        GL.MatrixMode(MatrixMode.Projection);
        GL.PushMatrix();
        GL.LoadIdentity();


        GL.Ortho(0, 1920, 0, 1080, 0, 1);

        GL.MatrixMode(MatrixMode.Modelview);
        GL.PushMatrix();
        GL.LoadIdentity();

        GL.Disable(EnableCap.Lighting);

        GL.Enable(EnableCap.Texture2D);

        GL.ActiveTexture(TextureUnit.Texture0);
        GL.BindTexture(TextureTarget.Texture2D, image);

        GL.Begin(PrimitiveType.Quads);

        GL.TexCoord2(0, 1);
        GL.Vertex3(0, 0, 0);

        GL.TexCoord2(1, 1);
        GL.Vertex3(1920, 0, 0);

        GL.TexCoord2(1, 0);
        GL.Vertex3(1920, 1080, 0);

        GL.TexCoord2(0, 0);
        GL.Vertex3(0, 1080, 0);

        GL.End();
        RunShaders();





        GL.Disable(EnableCap.Texture2D);
        GL.PopMatrix();

        GL.MatrixMode(MatrixMode.Projection);
        GL.PopMatrix();

        GL.MatrixMode(MatrixMode.Modelview);


        ErrorCode ec = GL.GetError();
        if (ec != 0)
            System.Console.WriteLine(ec.ToString());
        Console.Read();
    }
    private void RunShaders()
    {

        GL.ClearColor(Color.AliceBlue);
        GL.UseProgram(program);
        GL.DrawArrays(PrimitiveType.Triangles, 0, vertices.Length / 3);

        ErrorCode ec = GL.GetError();
        if (ec != 0)
            System.Console.WriteLine(ec.ToString());
        Console.Read();

    }

要开始回答而不是继续评论。你仍然有一些复杂的小问题。您应该注释掉 GL.BeginGL.End 之间的所有内容,因为 RunShaders 函数应该将您需要的所有内容绘制到屏幕上。还要注释掉 GL.Ortho 行,如果您使用的是 [-1, 1] 范围内的顶点,则不需要它。

其次,您的问题是您只将一半的顶点缓冲区上传到 GPU。在 GL.BufferData 行的 InitBuffers 中,将 sizeof(ushort) 更改为 sizeof(float),因为您的顶点是浮点数(4 字节长)而不是 ushorts(2 字节长)。

GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(vertices.Length * sizeof(float)), vertices, BufferUsageHint.StaticDraw);

这应该能让你的程序正常工作。