OpenGL点在片段着色器中精灵旋转

Pie*_*ice 5 c++ opengl glsl

我正在学习本教程,以了解更多关于OpenGL,特别是点精灵的内容.但是我坚持在页面末尾的一个练习中:

尝试通过更改片段着色器将点精灵旋转45度.

在本章中以及之前的章节中没有关于此类事情的提示.我没有找到任何关于如何做的文档.这些是我的顶点和片段着色器:

顶点着色器

#version 140

attribute vec2 coord2d;

varying vec4 f_color;

uniform float offset_x;
uniform float scale_x;
uniform float point_size;

void main(void) {
    gl_Position = vec4((coord2d.x + offset_x) * scale_x, coord2d.y, 0.0, 1.0);
    f_color = vec4(coord2d.xy / 2.0 + 0.5, 1.0, 1.0);
    gl_PointSize = point_size;
}
Run Code Online (Sandbox Code Playgroud)

片段着色器

#version 140

varying vec4 f_color;

uniform sampler2D texture;

void main(void) {
    gl_FragColor = texture2D(texture, gl_PointCoord) * f_color;
}
Run Code Online (Sandbox Code Playgroud)

我想在FS中使用2x2矩阵来旋转gl_PointCoord,但我不知道如何填充矩阵来完成它.我应该把它作为制服直接传递给FS吗?

Nic*_*las 9

传统方法是将矩阵传递给着色器,无论是顶点还是片段.如果您不知道如何填写旋转矩阵,Google和维基百科可以提供帮助.

最重要的是你要碰到的是2D旋转不够的简单事实.gl_PointCoord从[0,1]开始.纯旋转矩阵围绕原点旋转,原点是点坐标空间中的左下角.因此,您需要的不仅仅是纯旋转矩阵.

您需要一个3x3矩阵,它具有零件旋转和零件平移.该矩阵应如下生成(使用GLM进行数学运算):

glm::mat4 currMat(1.0f);
currMat = glm::translate(currMat, glm::vec3(0.5f, 0.5f, 0.0f));
currMat = glm::rotate(currMat, angle, glm::vec3(0.0f, 0.0f, 1.0f));
currMat = glm::translate(currMat, glm::vec3(-0.5f, -0.5f, 0.0f));
Run Code Online (Sandbox Code Playgroud)

然后currMat,您将作为4x4矩阵传递到着色器.你的着色器这样做:

vec2 texCoord = (rotMatrix * vec4(gl_PointCoord, 0, 1)).xy
gl_FragColor = texture2D(texture, texCoord) * f_color;
Run Code Online (Sandbox Code Playgroud)

我将把它作为练习,如何将第4列的翻译移动到第3列,以及如何将其作为3x3矩阵传递.当然,在这种情况下,你将为vec3(gl_PointCoord, 1)矩阵乘法做.