Opengl在辅助线程中渲染(纹理)

时间:2014-10-30 17:02:55

标签: c multithreading opengl pthreads

我希望使用pthread库渲染Textures。这是我希望通过将更新纹理的线程渲染的函数。最初我的纹理通过init函数加载并由display function(在主线程中)呈现。

void *moveMap(void *x)
{
printf("move called\n");
  tim.tv_sec = 0;
  tim.tv_nsec = 500000000;
  glBindTexture(GL_TEXTURE_2D, texName[0]);

int index;   
  for(index=pathLength;index>=0;index--)
 {
    printf("Go %d %d\n", Path[index][0], Path[index][1]);
    glTexSubImage2D(GL_TEXTURE_2D, 0, Path[index][0]*20, Path[index][1]*20, surface->w, surface->h, GL_RGB,GL_UNSIGNED_BYTE, surface->pixels);
    display();       
  }        
}

void mouse(int button, int state, int x, int y)
{
   if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN)
   {
      pressedXCoord=x/20;
      pressedYCoord=y/20;
      printf("Pressed on %d %d\n",x/20,y/20);
   }
   if (button == GLUT_LEFT_BUTTON && state == GLUT_UP)
   {
      releasedXCoord=x/20;
      releasedYCoord=y/20;
      printf("Released on %d %d\n",x/20,y/20);
      findPath(pressedXCoord,pressedYCoord,releasedXCoord,releasedYCoord);
      if(pthread_create(&inc_x_thread, NULL, moveMap, NULL)) {
        fprintf(stderr, "Error creating thread\n");
        return 1;
      }
   }  
}

findpath函数基本上计算两个坐标之间的最短路径,函数moveMap通过该路径更新纹理。当我调用moveMap函数而没有线程纹理时会根据需要更新,但是当通过线程调用时它不会。

1 个答案:

答案 0 :(得分:0)

OpenGL不适用于多个线程,它期望所有调用都来自单个线程。

您可以使用glutIdleFunc一次进行一些复制:

void idleCopy(void){
    if(copyIndex==0)return;

    printf("Go %d %d\n", Path[copyIndex][0], Path[copyIndex][1]);
    glTexSubImage2D(GL_TEXTURE_2D, 0, Path[copyIndex][0]*20, Path[copyIndex][1]*20, surface->w, surface->h, GL_RGB,GL_UNSIGNED_BYTE, surface->pixels);
    glutPostRedisplay();    
    copyIndex--;
    if(copyIndex==0)glutIdleFunc(null);//disable callback

}

和鼠标():

if (button == GLUT_LEFT_BUTTON && state == GLUT_UP)
{
   releasedXCoord=x/20;
   releasedYCoord=y/20;
   printf("Released on %d %d\n",x/20,y/20);
   findPath(pressedXCoord,pressedYCoord,releasedXCoord,releasedYCoord);
   glutIdleFunc(&idleCopy);
}