将结构数组传递给 OpenGL [英] Passing arrays of structs to OpenGL

查看:61
本文介绍了将结构数组传递给 OpenGL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常使用结构体来封装一段图形数据,比如颜色/像素.如果他们使用预期的数据类型,我是否可以将这些数组传递给 OpenGL,或者这是否违反了严格的别名规则?例如:

I often use a struct to encapsulate a piece of graphics data, like colors/pixels. Provided they use the expected data type, can I pass arrays of these to OpenGL, or does this violate strict aliasing rules? For example:

typedef struct Color {
    uint8_t v[4];
} Color;

Color colors[200];

for (int i = 0; i < 200; i++) {
    /* populate color data */
}

glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, colors);

与不那么抽象的版本对比:

Versus the less abstracted version:

uint8_t colors[200 * 4];

for (int i = 0; i < 200 * 4; i++) {
    /* populate color data */
}

glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, colors);

推荐答案

你可以让它工作,只要没有填充.仔细检查 4 == sizeof (Color).

You can make it work, as long as there is no padding. Double-check that 4 == sizeof (Color).

在某些情况下,您可能还需要使用 glPixelStoreiGL_UNPACK_ALIGNMENT 来让 OpenGL 知道连续行中的数组元素是密排的,末尾没有额外的填充一行.

In some cases you might also need to use glPixelStorei with GL_UNPACK_ALIGNMENT to let OpenGL know that array elements in sequential rows are close-packed, without extra padding at the end of a row.

OpenGL 和其他库函数中的实际读取操作对 C++ 编译器不可见,因此严格别名不适用于它们.该规则确实适用于您的代码,但由于您传递的是 const void*,编译器必须假设它可以为任何内容设置别名,并且不会在库调用中执行重新排序.

The actual read operations in OpenGL and other library functions aren't visible to the C++ compiler, so strict aliasing doesn't apply to them. The rule does apply to your code, but since you are passing a const void*, the compiler has to assume it can alias anything, and not perform reordering across the library call.

这篇关于将结构数组传递给 OpenGL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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