c++ - 如何在 OpenGL 中进行 2D 缩放(GLFW,很高兴)?
问题描述
我正在尝试实现一个简单的绘画程序,现在我遇到了缩放问题,我不明白该怎么做?我试图从这里调整代码以适应我自己,但它不起作用,我只是得到一个黑屏。我的问题是什么?
不使用 glut 或 glew!
这是我的相机代码:
。H
class Camera2d
{
public:
Camera2d(const glm::vec3& pos = glm::vec3(0.f, 0.f, 0.f),
const glm::vec3& up = glm::vec3(0.f, 1.f, 0.f));
//~Camera2d();
void setZoom(const float& zoom);
float getZoom() const noexcept;
glm::mat4 getViewMatrix() const noexcept;
void mouseScrollCallback(const float& yOffset);
protected:
void update();
private:
// Camera zoom
float m_zoom;
// Euler Angles
float m_yaw;
float m_pitch;
public:
// Camera Attributes
glm::vec3 position;
glm::vec3 worldUp;
glm::vec3 front;
glm::vec3 up;
glm::vec3 right;
};
.cpp
Camera2d::Camera2d(
const glm::vec3& pos /* = glm::vec3(0.f, 0.f, 0.f) */,
const glm::vec3& up /* = glm::vec3(0.f, 1.f, 0.f) */
)
: m_zoom(45.f)
, m_yaw(-90.f)
, m_pitch(0.f)
, position(pos)
, worldUp(up)
, front(glm::vec3(0.f, 0.f, -1.f))
{
this->update();
}
void Camera2d::setZoom(const float& zoom)
{
this->m_zoom = zoom;
}
float Camera2d::getZoom() const noexcept
{
return this->m_zoom;
}
glm::mat4 Camera2d::getViewMatrix() const noexcept
{
return glm::lookAt(this->position, this->position + this->front, this->up);
}
void Camera2d::mouseScrollCallback(const float& yOffset)
{
if (m_zoom >= 1.f && m_zoom <= 45.f)
m_zoom -= yOffset;
else if (m_zoom <= 1.f)
m_zoom = 1.f;
else if (m_zoom >= 45.f)
m_zoom = 45.f;
}
void Camera2d::update()
{
// Calculate the new Front vector
glm::vec3 _front;
_front.x = cos(glm::radians(this->m_yaw)) * cos(glm::radians(this->m_pitch));
_front.y = sin(glm::radians(this->m_pitch));
_front.z = cos(glm::radians(this->m_pitch)) * sin(glm::radians(this->m_yaw));
this->front = glm::normalize(_front);
// Also re-calculate the Right and Up vector
this->right = glm::normalize(glm::cross(this->front, this->worldUp)); // Normalize the vectors, because their length gets closer to 0 the more you look up or down which results in slower movement.
this->up = glm::normalize(glm::cross(this->right, this->front));
}
并且主要我在渲染循环中尝试这样的事情
// pass projection matrix to shader
glm::mat4 projection = glm::perspective(glm::radians(camera.getZoom()),
static_cast<float>(WIDTH) / static_cast<float>(HEIGHT),
0.1f,
10000.f);
shaderProg.setMat4("projecton", projection);
// camera view transformation
glm::mat4 view = camera.getViewMatrix();
shaderProg.setMat4("view", view);
here i have just 1 model its my white bg-texture
glm::mat4 model = glm::translate(model, glm::vec3(0.f, 0.f, 0.f));
model = glm::rotate(model, glm::radians(0.f), glm::vec3(1.0f, 0.3f, 0.5f));
shaderProg.setMat4("model", model);
github上的所有代码:这里
解决方案
您在 2D 中工作,忘记相机,忘记投影,忘记遵循 OpenGL 教程,它们针对 3D 图形。
你需要的只是一个矩形来填充你的屏幕。从屏幕角落的顶点开始,从左上角开始逆时针移动: (-1,1,0) (-1,-1,0) (1,-1,0) (1 ,1,0)。忘掉 Z,你是在 2D 中工作的。
您在纹理上绘制,纹理坐标为 (0,1) (0,0) (1,0) (1,1),顺序与上述相同。缩放现在只是缩放矩形的问题。您有一个矩阵来确定比例,一个矩阵来确定位置。忘记旋转、前向量和所有这些东西。在顶点着色器中,您按此顺序缩放,然后像往常一样平移顶点。完毕。
例如,要进行交互,您可以让鼠标滚轮向上增加比例因子,而鼠标滚轮向下减少它。按住单击并移动鼠标以更改 (x,y) 位置。再次忘记 Z。将这些值放入顶点着色器并进行通常的转换。