将OpenGL基元转换为OpenGLES

时间:2009-02-24 18:12:57

标签: c++ iphone opengl-es opengl-to-opengles

我正在尝试从OpenGL 1.5规范转换以下代码。到OpenGLES 1.1规范

(num_x and num_y are passed into the function by arguments)

::glBegin(GL_LINES);
for (int i=-num_x; i<=num_x; i++) 
{
    glVertex3i(i, 0, -num_y);
    glVertex3i(i, 0,  num_y); 
}

for (int i=-num_y; i<=num_y; i++) 
{
    glVertex3i(-num_x, 0, i);
    glVertex3i( num_x, 0, i);
}

::glEnd();

这是我相应的转换代码:(忽略我的循环效率低下,我试图让转换首先正常工作)

我正在尝试在这里构建两件事:

  • 绘制网格所需的所有x,y,z坐标的浮点数组
  • 所需所有顶点的索引数组。
  • 然后将两个数组传递给呈现它们的OpenGL。

数组应该是什么样子的一个例子:

GLshort indices[] = {3, 0, 1, 2, 
                     3, 3, 4, 5, 
                     3, 6, 7, 8, };
GLfloat vertexs[] = {3.0f, 0.0f, 0.0f,
                     6.0f, 0.0f, -0.5f ,
                     0,    0,     0,
                     6.0f, 0.0f,  0.5f,
                     3.0f, 0.0f,  0.0f,
                     0,    0,     0,
                     3,    0,     0,
                     0,    0,     0,
                     0,    6,     0};


int iNumOfVerticies = (num_x + num_y)*4*3;
int iNumOfIndicies = (iNumOfVerticies/3)*4;

GLshort* verticies = new short[iNumOfVerticies];
GLshort* indicies = new short[iNumOfIndicies];
int j = 0;
for(int i=-num_x; j < iNumOfVerticies &&  i<=num_x; i++,j+=6)
{
    verticies[j] = i;
    verticies[j+1] = 0;
    verticies[j+2] = -num_y;

    verticies[j+3] = i;
    verticies[j+4] = 0;
    verticies[j+5] = num_y;
 }

 for(int i=-num_y; j < iNumOfVerticies && i<=num_y;i++,j+=6)
 {
     verticies[j] = i;
     verticies[j+1] = 0;
     verticies[j+2] = -num_x;

     verticies[j+3] = i;
     verticies[j+4] = 0;
     verticies[j+5] = num_x;
 }

如果要传递,我还需要构建一个数组。我从'iphone'茶壶'的例子中借用了'数组结构'。

在每一行中,我们都有标记的数量,后面跟着引用的标记。

 int k = 0;
 for(j = 0; j < iNumOfIndicies; j++)
 {
      if (j%4==0)
      {
         indicies[j] = 3;
      }
      else
      {
         indicies[j] = k++;
      }

 }
 ::glEnableClientState(GL_VERTEX_ARRAY);
 ::glVertexPointer(3 ,GL_FLOAT, 0, verticies);

 for(int i = 0; i < iNumOfIndicies;i += indicies[i] + 1)
 {
       ::glDrawElements(  GL_LINES, indicies[i], GL_UNSIGNED_SHORT, &indicies[i+1] );
 }

 delete [] verticies;
 delete [] indicies;

请将代码问题添加为评论,而不是答案

1 个答案:

答案 0 :(得分:1)

我可以看到转换后的代码有些问题:

1.-为变量 verticies 使用错误的类型,它应该是:

GLfloat* verticies = new float[iNumOfVerticies];

2.-错误地填充 verticies ,第二个循环应该是:

for(int i=-num_y; j < iNumOfVerticies && i<=num_y;i++,j+=6)
{
    verticies[j] = -num_x;
    verticies[j+1] = 0;
    verticies[j+2] = i;

    verticies[j+3] = num_x;
    verticies[j+4] = 0;
    verticies[j+5] = i;
}

3.-错误填写指示,我认为你应该删除这些行:

if (j%4==0)
{
     indicies[j] = 3;
}
else

4.-错误使用 glDrawElements ,用这一行代替循环:

::glDrawElements(  GL_LINES, iNumOfIndicies, GL_UNSIGNED_SHORT, indicies);