【问题标题】:OpenGL vertex shader: weird matrix translationOpenGL顶点着色器:奇怪的矩阵转换
【发布时间】:2015-07-07 15:39:20
【问题描述】:

我正在尝试使用矩阵根据时间移动三角形。但它做了一些奇怪的事情:

应该怎么做: 在 x 轴上移动

它的作用: 三角形的顶点是固定的,其他点似乎以圆周运动的方式围绕它移动,并在 x、z 轴上缩放(我仍然在 2d 中,所以我没有深度)。

我的 C++ 代码:

    ...
    GLfloat timeValue = glfwGetTime();
    GLfloat offset = (sin(timeValue  * 4) / 2);

    GLfloat matrix[16] = {
        1, 0, 0, offset,
        0, 1, 0, 0,
        0, 0, 1, 0,
        0, 0, 0, 1
    };

    GLuint uniform_m_transform = glGetUniformLocation(shader_program, "m_transform");
    glUniformMatrix4fv(uniform_m_transform, 1, GL_FALSE, matrix);
    ...

我的顶点着色器:

#version 330 core
 layout (location = 0) in vec3 position;
 layout (location = 1) in vec3 color;

 out vec3 ourColor;
 uniform mat4 m_transform;

 void main()
 {
     ourColor = color;
     gl_Position = m_transform * vec4(position, 1.0);
 }

我不知道我做错了什么,根据教程,我设置为 offset 的矩阵属性应该改变 x 平移。

你知道我的错误是什么吗?

【问题讨论】:

    标签: c++ opengl matrix vertex-shader


    【解决方案1】:

    您提供的是行主矩阵,因此您需要指定转置:

    glUniformMatrix4fv(uniform_m_transform, 1, GL_TRUE, matrix);
    

    参考:glUniform,检查transpose参数。

    【讨论】:

    • 非常感谢!现在它起作用了!并感谢您的链接:)
    • @yxyx136:归结为矩阵元素的读取顺序。行顺序意味着构成矩阵的基向量(记住矩阵是向量的向量)首先按行索引,然后按列索引)。然而,OpenGL 本机假设,缓冲区中的元素构成矩阵是排在第一位的;因此,当将其编写为 C 数组时,它看起来是转置的(沿对角线翻转)。虽然起初这看起来很麻烦,但它在计算机图形方面有一定的好处,因为您通常需要处理矩阵的列向量,例如用于制作广告牌。
    • 感谢您的帮助!丹克!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多