0

0

C++如何实现一个简单的向量数学库_为C++图形学编程编写Vec3和Mat4类

冰火之心

冰火之心

发布时间:2025-12-23 16:07:02

|

566人浏览过

|

来源于php中文网

原创

答案:文章介绍了在C++图形学编程中实现基础数学库的方法,包含Vec3类用于三维向量运算如加减、点积、叉积和单位化,Mat4类实现4x4矩阵的乘法与向量变换,支持平移、旋转、缩放及透视投影等操作,并通过Transform工具类提供常用变换函数,最后给出组合变换的使用示例,适用于教学和原型开发。

c++如何实现一个简单的向量数学库_为c++图形学编程编写vec3和mat4类

在C++图形学编程中,向量(Vec3)和4x4矩阵(Mat4)是基础中的基础。实现一个简单的数学库能帮助你理解底层运算,同时为后续的渲染、变换、光照计算打下基础。下面教你如何从零开始写一个轻量级但实用的 Vec3 和 Mat4 类。

Vec3:三维向量类

Vec3 表示三维空间中的点或方向,支持加减、数乘、点积、叉积等操作。

基本结构:

// Vec3.h #pragma once #include

class Vec3 { public: float x, y, z;

// 构造函数
Vec3() : x(0), y(0), z(0) {}
Vec3(float x, float y, float z) : x(x), y(y), z(z) {}

// 向量加法
Vec3 operator+(const Vec3& other) const {
    return Vec3(x + other.x, y + other.y, z + other.z);
}

// 向量减法
Vec3 operator-(const Vec3& other) const {
    return Vec3(x - other.x, y - other.y, z - other.z);
}

// 数乘
Vec3 operator*(float scalar) const {
    return Vec3(x * scalar, y * scalar, z * scalar);
}

// 点积
float dot(const Vec3& other) const {
    return x * other.x + y * other.y + z * other.z;
}

// 叉积
Vec3 cross(const Vec3& other) const {
    return Vec3(
        y * other.z - z * other.y,
        z * other.x - x * other.z,
        x * other.y - y * other.x
    );
}

// 向量长度
float length() const {
    return std::sqrt(x*x + y*y + z*z);
}

// 单位化
Vec3 normalize() const {
    float len = length();
    return len != 0 ? *this * (1.0f / len) : Vec3(0, 0, 0);
}

};

立即学习C++免费学习笔记(深入)”;

// 支持 scalar vector inline Vec3 operator(float scalar, const Vec3& v) { return v * scalar; }

Mat4:4x4矩阵类

Mat4 用于表示空间变换:平移、旋转、缩放和投影。我们用列主序存储16个浮点数。

AskAI
AskAI

无代码AI模型构建器,可以快速微调GPT-3模型,创建聊天机器人

下载
// Mat4.h #pragma once

class Mat4 { public: float m[16]; // 列主序:m[0-3] 是第一列

// 单位矩阵构造
Mat4() {
    for (int i = 0; i zuojiankuohaophpcn 16; i++) {
        m[i] = (i % 5 == 0) ? 1.0f : 0.0f; // 对角线为1
    }
}

// 手动设置元素
void set(int row, int col, float value) {
    m[col * 4 + row] = value; // 列主序索引
}

// 矩阵乘法
Mat4 operator*(const Mat4& other) const {
    Mat4 result;
    for (int i = 0; i zuojiankuohaophpcn 4; i++) {
        for (int j = 0; j zuojiankuohaophpcn 4; j++) {
            float sum = 0;
            for (int k = 0; k zuojiankuohaophpcn 4; k++) {
                sum += m[i * 4 + k] * other.m[k * 4 + j];
            }
            result.m[i * 4 + j] = sum;
        }
    }
    return result;
}

// 矩阵与向量相乘(齐次坐标)
Vec3 operator*(const Vec3& v) const {
    float x = m[0]*v.x + m[4]*v.y + m[8]*v.z + m[12];
    float y = m[1]*v.x + m[5]*v.y + m[9]*v.z + m[13];
    float z = m[2]*v.x + m[6]*v.y + m[10]*v.z + m[14];
    float w = m[3]*v.x + m[7]*v.y + m[11]*v.z + m[15];
    if (w != 0 && w != 1) {
        return Vec3(x/w, y/w, z/w);
    }
    return Vec3(x, y, z);
}

};

常用变换函数

静态函数生成特定变换矩阵,方便调用。

// TransformUtils.h #pragma once #include "Mat4.h" #include

class Transform { public: // 平移矩阵 static Mat4 translate(float x, float y, float z) { Mat4 mat; mat.set(0, 3, x); mat.set(1, 3, y); mat.set(2, 3, z); return mat; }

// 缩放矩阵
static Mat4 scale(float x, float y, float z) {
    Mat4 mat;
    mat.set(0, 0, x);
    mat.set(1, 1, y);
    mat.set(2, 2, z);
    return mat;
}

// 绕X轴旋转
static Mat4 rotateX(float rad) {
    Mat4 mat;
    float c = cosf(rad);
    float s = sinf(rad);
    mat.set(1, 1, c); mat.set(1, 2, -s);
    mat.set(2, 1, s); mat.set(2, 2, c);
    return mat;
}

// 绕Y轴旋转
static Mat4 rotateY(float rad) {
    Mat4 mat;
    float c = cosf(rad);
    float s = sinf(rad);
    mat.set(0, 0, c); mat.set(0, 2, s);
    mat.set(2, 0, -s); mat.set(2, 2, c);
    return mat;
}

// 绕Z轴旋转
static Mat4 rotateZ(float rad) {
    Mat4 mat;
    float c = cosf(rad);
    float s = sinf(rad);
    mat.set(0, 0, c); mat.set(0, 1, -s);
    mat.set(1, 0, s); mat.set(1, 1, c);
    return mat;
}

// 透视投影矩阵(简化版)
static Mat4 perspective(float fov, float aspect, float near, float far) {
    Mat4 mat;
    float f = 1.0f / tanf(fov * 0.5f);
    mat.set(0, 0, f / aspect);
    mat.set(1, 1, f);
    mat.set(2, 2, (far + near) / (near - far));
    mat.set(2, 3, (2 * far * near) / (near - far));
    mat.set(3, 2, -1);
    mat.set(3, 3, 0);
    return mat;
}

};

使用示例

#include "Vec3.h" #include "TransformUtils.h" #include iostream>

int main() { Vec3 pos(1, 0, 0);

Mat4 model = Transform::translate(2, 0, 0);
Mat4 rot   = Transform::rotateZ(3.14159f / 4.0f);
Mat4 scale = Transform::scale(2, 2, 2);

Mat4 transform = model * rot * scale;
Vec3 transformed = transform * pos;

std::cout zuojiankuohaophpcnzuojiankuohaophpcn "Transformed: (" 
          zuojiankuohaophpcnzuojiankuohaophpcn transformed.x zuojiankuohaophpcnzuojiankuohaophpcn ", " 
          zuojiankuohaophpcnzuojiankuohaophpcn transformed.y zuojiankuohaophpcnzuojiankuohaophpcn ", " 
          zuojiankuohaophpcnzuojiankuohaophpcn transformed.z zuojiankuohaophpcnzuojiankuohaophpcn ")\n";

return 0;

}

基本上就这些。这个简易数学库没有过度优化,但足够教学和原型开发使用。你可以逐步添加更多功能,比如欧拉角转矩阵、LookAt 矩阵、逆矩阵等。关键是理解每一步运算的几何意义。

相关专题

更多
css中float用法
css中float用法

css中float属性允许元素脱离文档流并沿其父元素边缘排列,用于创建并排列、对齐文本图像、浮动菜单边栏和重叠元素。想了解更多float的相关内容,可以阅读本专题下面的文章。

558

2024.04.28

C++中int、float和double的区别
C++中int、float和double的区别

本专题整合了c++中int和double的区别,阅读专题下面的文章了解更多详细内容。

99

2025.10.23

c语言const用法
c语言const用法

const是关键字,可以用于声明常量、函数参数中的const修饰符、const修饰函数返回值、const修饰指针。详细介绍:1、声明常量,const关键字可用于声明常量,常量的值在程序运行期间不可修改,常量可以是基本数据类型,如整数、浮点数、字符等,也可是自定义的数据类型;2、函数参数中的const修饰符,const关键字可用于函数的参数中,表示该参数在函数内部不可修改等等。

523

2023.09.20

string转int
string转int

在编程中,我们经常会遇到需要将字符串(str)转换为整数(int)的情况。这可能是因为我们需要对字符串进行数值计算,或者需要将用户输入的字符串转换为整数进行处理。php中文网给大家带来了相关的教程以及文章,欢迎大家前来学习阅读。

315

2023.08.02

int占多少字节
int占多少字节

int占4个字节,意味着一个int变量可以存储范围在-2,147,483,648到2,147,483,647之间的整数值,在某些情况下也可能是2个字节或8个字节,int是一种常用的数据类型,用于表示整数,需要根据具体情况选择合适的数据类型,以确保程序的正确性和性能。本专题为大家提供相关的文章、下载、课程内容,供大家免费下载体验。

538

2024.08.29

c++怎么把double转成int
c++怎么把double转成int

本专题整合了 c++ double相关教程,阅读专题下面的文章了解更多详细内容。

52

2025.08.29

C++中int的含义
C++中int的含义

本专题整合了C++中int相关内容,阅读专题下面的文章了解更多详细内容。

197

2025.08.29

class在c语言中的意思
class在c语言中的意思

在C语言中,"class" 是一个关键字,用于定义一个类。想了解更多class的相关内容,可以阅读本专题下面的文章。

465

2024.01.03

高德地图升级方法汇总
高德地图升级方法汇总

本专题整合了高德地图升级相关教程,阅读专题下面的文章了解更多详细内容。

2

2026.01.16

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
React 教程
React 教程

共58课时 | 3.7万人学习

Pandas 教程
Pandas 教程

共15课时 | 0.9万人学习

ASP 教程
ASP 教程

共34课时 | 3.6万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号