Search code examples
opengltexturesbmp

What's wrong with my bmp imporer?


So I kinda made a small bmp importer in order to be able to use texture in opengl but after I load the picture and stuff instead of a texture it just puts the color brown on the ... sqare I have also tried with more than 1 texture and i got the same resault. Here's some code:

int LoadBitmap ( char *filename) {
  BITMAPFILEHEADER fileheader;
  BITMAPINFOHEADER fileinfo;
  RGBTRIPLE rgb;
  unsigned char *texture;
  FILE *f=fopen(filename,"r");
  num_texture++;
  fread(&fileheader,sizeof(fileheader),1,f);
  fread(&fileinfo,sizeof(fileinfo),1,f);
  cout<<fileinfo.biWidth<<" "<<fileinfo.biHeight<<endl;

  texture=new unsigned char[fileinfo.biWidth*fileinfo.biHeight*4];
  int j=0;
  for(int i=0;i<fileinfo.biWidth*fileinfo.biHeight;i++)
  {
    fread(&rgb,sizeof(rgb),1,f);

    texture[j]=rgb.rgbtRed;
    texture[j+1]=rgb.rgbtGreen;
    texture[j+2]=rgb.rgbtBlue;
    texture[j+3]=255;
    j+=4;
  }
  fclose(f);

  glBindTexture(GL_TEXTURE_2D,num_texture);

  glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
  glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
  glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);

  glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);


  glTexImage2D(GL_TEXTURE_2D,0,4,fileinfo.biWidth,fileinfo.biHeight,0,GL_RGBA,GL_UNSIGNED_BYTE,texture);
  gluBuild2DMipmaps(GL_TEXTURE_2D,4,fileinfo.biWidth,fileinfo.biHeight,GL_RGBA,GL_UNSIGNED_BYTE,texture);

  delete[] texture;
  return num_texture;
  return 0;
}

and here is the drawing part:

glEnable(GL_TEXTURE_2D);
int a=LoadBitmap("texture1.bmp");
glBindTexture(GL_TEXTURE_2D,a);
glBegin(GL_QUADS);
  glTexCoord2f(0,0);
  glVertex3f(-10,-10,0 );
  glTexCoord2f(0,1);
  glVertex3f(-10,10,0);
  glTexCoord2f(1,1);
  glVertex3f(10,10,0 );
  glTexCoord2f(1,0);
  glVertex3f(10,-10,0 );
 glEnd();

Solution

  • FILE *f=fopen(filename,"r");
    

    You may want to try opening the file in binary mode, it may simply be detecting an end of file, or otherwise mangling the input.

    FILE *f=fopen(filename,"rb");
    

    You also make some assumptions about the actual format of the file, but assuming you generated the BMPs yourself, I guess that might be ok.