C++/OpenGL 入门(5):利用GLM创建平移、旋转和缩放矩阵

来源:《Computer Graphics Programming in OpenGL Using C++ 》by V Scott Gordon John L Clevenger
内容:程序3.1 Program 3.1: Building Transformation Matrices in GLSL,书P56页,PDF75/403
说明:以下构造矩阵的函数模块

#include "include/glm/glm.hpp"

#include <iostream>

// 创建并返回一个平移矩阵;
glm::mat4 buildTranslate(float x, float y, float z)
{
	glm::mat4 trans = glm::mat4(1.0, 0.0, 0.0, 0.0,
		0.0, 1.0, 0.0, 0.0,
		0.0, 0.0, 1.0, 0.0,
		x, y, z, 1.0);
	return trans;
}
// builds and returns a matrix that performs a rotation around the X axis
// 创建并返回一个绕x轴旋转的矩阵
glm::mat4 buildRotateX(float rad)
{
	glm::mat4 xrot = glm::mat4(1.0, 0.0, 0.0, 0.0,
		0.0, cos(rad), -sin(rad), 0.0,
		0.0, sin(rad), cos(rad), 0.0,
		0.0, 0.0, 0.0, 1.0);
	return xrot;
}
// builds and returns a matrix that performs a rotation around the Y axis
// 创建并返回一个绕 Y 轴旋转的矩阵
glm::mat4 buildRotateY(float rad)
{
	glm::mat4 yrot = glm::mat4(cos(rad), 0.0, sin(rad), 0.0,
		0.0, 1.0, 0.0, 0.0,
		-sin(rad), 0.0, cos(rad), 0.0,
		0.0, 0.0, 0.0, 1.0);
	return yrot;
}
// builds and returns a matrix that performs a rotation around the Z axis
// 创建并返回一个绕 Z 轴旋转的矩阵
glm::mat4 buildRotateZ(float rad)
{
	glm::mat4 zrot = glm::mat4(cos(rad), -sin(rad), 0.0, 0.0,
		sin(rad), cos(rad), 0.0, 0.0,
		0.0, 0.0, 1.0, 0.0,
		0.0, 0.0, 0.0, 1.0);
	return zrot;
}
// builds and returns a scale matrix
// 创建并返回一个缩放矩阵
glm::mat4 buildScale(float x, float y, float z)
{
	glm::mat4 scale = glm::mat4(x, 0.0, 0.0, 0.0,
		0.0, y, 0.0, 0.0,
		0.0, 0.0, z, 0.0,
		0.0, 0.0, 0.0, 1.0);
	return scale;
}
  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
这是一个比较复杂的问题,需要一些基本的OpenGL知识。我会尽量给出一些指导,但是如果你是初学者,可能需要先学习一些OpenGL的基础知识。 首先,你需要一个3D模型,例如一个茶壶。你可以在网上找到一个茶壶模型,或者自己创建一个。然后,你需要使用OpenGL加载模型并将其渲染到屏幕上。 接下来,你需要实现平移旋转缩放。这可以通过矩阵变换来实现。例如,要平移一个物体,你可以使用以下代码: ```c++ glm::mat4 model = glm::mat4(1.0f); // 创建一个单位矩阵 model = glm::translate(model, glm::vec3(2.0f, 0.0f, 0.0f)); // 平移 ``` 这将创建一个单位矩阵,并将其平移2个单位。你可以将这个矩阵传递给OpenGL,以便在渲染时应用该变换。 类似地,你可以使用以下代码来旋转一个物体: ```c++ model = glm::rotate(model, angle, axis); // 旋转 ``` 其中,angle是旋转角度,axis是旋转轴。你可以将这个矩阵传递给OpenGL,以便在渲染时应用该变换。 最后,你可以使用以下代码来缩放一个物体: ```c++ model = glm::scale(model, glm::vec3(0.5f, 0.5f, 0.5f)); // 缩放 ``` 这将创建一个单位矩阵,并将其缩放为原来的一半。你可以将这个矩阵传递给OpenGL,以便在渲染时应用该变换。 最后,你需要添加光照。这可以通过使用OpenGL的光照功能来实现。你需要计算每个顶点的法向量,并将其传递给OpenGL。然后,你需要设置光源的位置和颜色,并将其传递给OpenGLOpenGL会根据这些信息计算每个像素的颜色。 这是一个比较复杂的问题,需要一些OpenGL知识。如果你是初学者,可能需要先学习一些OpenGL的基础知识。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值