好的,这就是我的。我有一个 1d 位图(或位数组、位集、位串,但我现在将其称为位图)包含生命生成的康威游戏中的存活或死亡状态。 (x, y)
处的单元格由 y * map_width + x
处的位表示。
现在我的生活游戏“引擎”正在运行,如果我现在可以渲染一些图形内容就好了。我认为 OpenGL 是一个不错的选择,但我不知道我应该如何开始以及是否有任何特定的函数或着色器(我对着色器一无所知)可以有效地将位图渲染到具有黑色和白色像素的二维平面。
如果你现在认为“不,你这个白痴 opengl 不好用......”,请尽管说出来,我愿意改变。
编辑
我忘了说我使用了一个紧凑的位数组,每个字节存储 8 位,并使用掩码来检索这些字节。这是我手工制作的图书馆东西:
#include <stdint.h> // uint32_t
#include <stdlib.h> // malloc()
#include <string.h> // memset()
#include <limits.h> // CHAR_BIT
typedef uint32_t word_t;
enum {
WORD_SIZE = sizeof(word_t), // size of one word in bytes
BITS_PER_WORD = sizeof(word_t) * CHAR_BIT, // size of one word in bits
MAX_WORD_VALUE = UINT32_MAX // max value of one word
};
typedef struct {
word_t *words;
int nwords;
int nbytes;
} bitmap_t;
inline int WORD_OFFSET(int b) { return b / BITS_PER_WORD; }
inline int BIT_OFFSET(int b) { return b % BITS_PER_WORD; }
inline void setbit(bitmap_t bitmap, int n) { bitmap.words[WORD_OFFSET(n)] |= (1 << BIT_OFFSET(n)); }
inline void flipbit(bitmap_t bitmap, int n) { bitmap.words[WORD_OFFSET(n)] ^= (1 << BIT_OFFSET(n)); }
inline void clearbit(bitmap_t bitmap, int n) { bitmap.words[WORD_OFFSET(n)] &= ~(1 << BIT_OFFSET(n)); }
inline int getbit(bitmap_t bitmap, int n) { return (bitmap.words[WORD_OFFSET(n)] & (1 << BIT_OFFSET(n))) != 0; }
inline void clearall(bitmap_t bitmap) {
int i;
for (i = bitmap.nwords - 1; i >= 0; i--) {
bitmap.words[i] = 0;
}
}
inline void setall(bitmap_t bitmap) {
int i;
for (i = bitmap.nwords - 1; i >= 0; i--) {
bitmap.words[i] = MAX_WORD_VALUE;
}
}
bitmap_t bitmap_create(int nbits) {
bitmap_t bitmap;
bitmap.nwords = nbits / BITS_PER_WORD + 1;
bitmap.nbytes = bitmap.nwords * WORD_SIZE;
bitmap.words = malloc(bitmap.nbytes);
if (bitmap.words == NULL) { // could not allocate memory
printf("ERROR: Could not allocate (enough) memory.");
exit(1);
}
clearall(bitmap);
return bitmap;
}
void bitmap_free(bitmap_t bitmap) {
free(bitmap.words);
}
最佳答案
这是我的 OGL 生命游戏实现的代码。
这会上传纹理(每次要更新数据时都这样做):
glTexImage2D( GL_TEXTURE_2D, 0, 1, game->width, game->height, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, game->culture[game->phase] );
game->culture[phase]
是 char*
类型的数据数组,大小为 width * height
(相位在两个交替之间切换正在写入或读取的数组)。
因为使用了 GL_LUMINANCE
,颜色将只有黑色和白色。
另外,你需要用这个设置矩形(每一帧,但我想你已经知道了)
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glBegin(GL_QUADS); // Draw A Quad
glVertex3f(-1.0f, 1.0f, 0.0f); // Top Left
glTexCoord2i( 1, 0 );
glVertex3f( 1.0f, 1.0f, 0.0f); // Top Right
glTexCoord2i( 1, 1 );
glVertex3f( 1.0f,-1.0f, 0.0f); // Bottom Right
glTexCoord2i( 0, 1 );
glVertex3f(-1.0f,-1.0f, 0.0f); // Bottom Left
glTexCoord2i( 0, 0 );
glEnd();
当然,您可以使用缓冲区并将“模型”保存在 GPU 内存中,但对于只有一个四边形的情况,这并不是真正必要的。
关于c - 将位图/位数组渲染到二维平面的最佳方式(使用 OpenGL),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5206508/