C ++ GLSL数据对齐/填充 [英] C++ GLSL data alignment/padding

查看:443
本文介绍了C ++ GLSL数据对齐/填充的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个C ++类MATRIX4X4其中有16个浮标阵列,无虚方法:

I have a C++ class Matrix4x4 which has an array of 16 floats and no virtual methods:

class Matrix4x4
{
public:
    float values[16];

    Matrix4x4();
    Matrix4x4(float v0, float v1, float v2, float v3, float v4, float v5, float v6, float v7, float v8, float v9, float v10, float v11, float v12, float v13, float v14, float v15);
    Matrix4x4(const Quaternion &quat, const Vector3 &pos);
    void convertToQuatPos(Quaternion &quat, Vector3 &pos);
    void loadIdentity();
    void setValues(float v0, float v1, float v2, float v3, float v4, float v5, float v6, float v7, float v8, float v9, float v10, float v11, float v12, float v13, float v14, float v15);
    void setPerspective(float fov, float aspect, float nearPlane, float farPlane);
    void setOrthographic(float top, float left, float bottom, float right, float nearPlane, float farPlane);
    ...

    static void multiply3x3(const Matrix4x4 &m1, const Matrix4x4 &m2, Matrix4x4 &result);
    static void multiply4x4(const Matrix4x4 &m1, const Matrix4x4 &m2, Matrix4x4 &result);
    ...

    Matrix4x4 operator*(const Matrix4x4 &a);
    Vector3 operator*(const Vector3 &a);
    Vector4 operator*(const Vector4 &a);
};

我通过这些矩阵向量GLSL像这样(这里的骨头是一个std MATRIX4X4的::矢量):

I'm passing vectors of these matrices to GLSL like so (where bones is a std::vector of Matrix4x4):

glUniformMatrix4fv(glGetUniformLocation(shader->getProgram(), "boneMatrices"), bones.size(), false, (GLfloat*) &bones[0].values[0]);

这显然假定一个MATRIX4X4对象将只占用16彩车值得记忆,没有对齐或填充的问题。它工作正常使用MSVC,它是安全的假设,它应该适用于其他平台(Linux,OSX,Android在未来)等?我应该对准值阵列,并确保没有填充?

which obviously assumes that a Matrix4x4 object will take up only 16-floats worth of memory with no alignment or padding issues. It works fine using MSVC, is it safe to assume that it should work on other platforms (Linux, OSX, Android in the future) e.t.c? Should I be aligning the values array and ensuring there is no padding?

推荐答案

添加静态断言头至少可以充当反对(可能性很小)可能保护了的元素 MATRIX4X4 阵列填充:

Adding a static assertion to the header can at least act as a guard against the (very unlikely) possibility that elements of a Matrix4x4 array are padded:

#include <type_traits>
...

static_assert(
    (sizeof(Matrix4x4) == (sizeof(GLfloat) * 16) &&
     std::is_standard_layout<Matrix4x4>::value),

    "Matrix4x4 does not satisfy contiguous storage requirements");

请参阅: 的std :: is_standard_layout

这篇关于C ++ GLSL数据对齐/填充的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆