Sign in to follow this  
Bozebo

OpenGL app crash while loading textures

Recommended Posts

I have a texture class and a method to load raw image files into it. It works completely fine if I leave size as default but whenever I pass anything else to it my program just crashes. I don't think the array can be going out of range but it seems to be what is happening, no matter how much I look at it I can't find any problems - it even crashes if I pass size as a value smaller than 128 (not making any value too big to store). If I use a raw image of dimensions 256x256 and leave the size parameter empty it works correctly (loads half the bytes as a 128x128 texture - which displays oddly of course - but the function is doing it's job correctly). The variables size and path are not used/set anywhere else, so there can't be some strange global issue going on. Can anybody see the problem that I cannot?
class texture{
  public:
  GLuint texture; //texture resource
  
  //24bpp raw image file
  bool loadRawRGB(char* path,int size = 128){
    int bytes = size * size * 3; //3 bytes per pixel
    BYTE data[bytes]; //buffer to hold raw image data
    FILE * file; //file handle
    
    //open and read texture data
    file = fopen(path,"rb"); //attempt to open the file
    if(!file) //don't continue if it couldn't be opened
      return false;
    
    fread(&data,bytes,1,file); //copy file contents into the buffer
    fclose(file); //close the file
    
    //allocate a texture resource
    glGenTextures(1,&texture);
    //set as target
    glBindTexture(GL_TEXTURE_2D,texture);
    //tell opengl to make a the texture piramid
    gluBuild2DMipmaps(GL_TEXTURE_2D,3,size,size,GL_RGB,GL_UNSIGNED_BYTE,&data);
       
    //free buffer
    free(&data);
    
    return true;
  }
};

//example use
texture brickWall;
brickWall.loadRawRGB("resources/textures/brickWall.raw");


Thanks for your time. [Edited by - Bozebo on March 18, 2010 1:47:46 PM]

Share this post


Link to post
Share on other sites
Quote:
Original post by HuntsMan
BYTE data[bytes];

Use new to create a dynamic array of bytes, not a stack one.


no... I couldn't see why that would help, but I tried it anyway:


int bytes = size * size * 3; //3 bytes per pixel
BYTE * data;
data = new BYTE[bytes]; //buffer to hold raw image data
FILE * file; //file handle






Exact same issue. The problem is nothing to do with dynamic arrays. This is really annoying it is holding me back; there doesn't seem to be anything wrong with it :S

edit:
Seems I am wrong about smaller values than 128 not working, I must have been doing something wrong because I tested that again now with a dynamic array and without and it seems to work, now I still cannot get 512 working. Surely an array can have 512x512x3 = 786432 indexes? If not how do I load the texture, load it in 2 parts?

[Edited by - Bozebo on March 18, 2010 8:19:09 PM]

Share this post


Link to post
Share on other sites
I'm actually suprised the compiler lets you allocate an array onto the stack when it doesn't know the size at compile time. You would normally have to do what HuntsMan suggested and use a dynamic array, since it is dynamically sized.

Also, why are you calling free? If it is stack allocated then there is nothing to free, and if it is created with new[] then it should be destroyed with delete [].

Do you know which line it crashes on? That would be a major help obviously. Put a breakpoint in and step through to find which line causes it.

Share this post


Link to post
Share on other sites
OK. Right I've edited this I think I have figured it out.

There were a few different issues, the one I ended up with here was I forgot to change:
gluBuild2DMipmaps(GL_TEXTURE_2D,3,size,size,GL_RGB,GL_UNSIGNED_BYTE,&data);
to:
gluBuild2DMipmaps(GL_TEXTURE_2D,3,size,size,GL_RGB,GL_UNSIGNED_BYTE,data);

Silly really, data was a pointer already.

It is being odd but I need to work with it a bit and check I am loading the texture correctly, no crashes now but the texture appears mostly black with some small areas of dull brown.

[Edited by - Bozebo on March 18, 2010 9:45:34 PM]

Share this post


Link to post
Share on other sites
I wasn't expecting that one either. I had my money on it being the free (although I'd have also though that would've crashed no matter the size.)

The most likely cause is incorrect format/internalFormat values, although that should just raise an error, not crash. I haven't used any of the GLU stuff for a while, so thats a shot in the dark.

You should really be using either the GL_GENERATE_MIPMAP texture parameter or (even better) the glGenerateMipMap function, they're both full of hardware accelerated goodness. They should both be available on most machines.

Does it crash when just using glTexImage2D instead?

Share this post


Link to post
Share on other sites
glTexImage2D(GL_TEXTURE_2D,0,3,size,size,0,GL_RGB,GL_UNSIGNED_BYTE,data);
makes the texure completely white :S

GL_GENERATE_MIPMAP and glGenerateMipMap are both unrecognised, where do I get a new OpenGL version from? It might be that I have some old version which doesn't like textures of 512x512?

edit:
[url=http://www.gamedev.net/community/forums/showfaq.asp?forum_id=25#q5]FAQ[/url]
Oh. "Although the current OpenGL version is 1.5 (as of 2004/03/29)"
Still outdated.

edit:
(ok why doesn't that link work?)

Share this post


Link to post
Share on other sites
Yip, the bain of everyone who uses OpenGL. The extensions =P
GLEW and GLee are your options on this one. I use GLEW myself, it pretty much reduces the whole thing down to 1 function call which gives you access to everything.

However, back to your white texture. Chances are now all you'll have to do is turn off mipmapping for that texture (just as a test obviously).
Just put this before your call to glTexImage2D and it should be able to see if that works.

glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );

I seem to remember that being the cause last time I got a full white texture, I'm still not sure why it was because of the mipmapping.

Edit: To make links work you just the html tags for it. < a href="target"></a > (without the spaces)

Share this post


Link to post
Share on other sites
Oops, I forgot the gamedev.net forums use some html >_< I got confused because I was using bbcode tags for code blocks.

anyway:
No I wasn't actually using mipmapping before, oddly. I recycled that function from somewhere else to start with and didn't realise I should have been better off using glTexImage2D.

This is where I load some textures to test the simple scene I am making:

//choose filtering options
if(linear){
glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
} else {
//nearest-neighbour filtering
glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST);
glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST);
}

//colours of this texture chosen to test blending of the particles etc
//also good for seeing world scale
texture texChecks;
texChecks.loadRawRGB("resources/textures/checkered2.raw");

//brick wall texture
texture texBricks;
texBricks.loadRawRGB("resources/textures/brick080.raw",512);




Annoyingly none of the opaque textures are working, they are all white now.

I have a loadRawRGBA method in the texture class, which is used to load a pane of glass and some particle textures, that method basically gives an alpha value the same as the pixel's red value (yes cheap, but all I wanted was some basic "greyscale" alpha - and it let me play about with the texture formats a bit).

I am still really confused :S

Just to make sure here is my current loadRawRGB method:

bool loadRawRGB(char* path,int size = 128){
int bytes = size * size * 3;
BYTE * data;
data = new BYTE[bytes];
//BYTE * data[bytes];
FILE * file;

file = fopen(path,"rb");
if(!file)
return false;

fread(data,bytes,1,file);
fclose(file);

glGenTextures(1,&texture);
glBindTexture(GL_TEXTURE_2D,texture);
glTexImage2D(GL_TEXTURE_2D,0,3,size,size,0,GL_RGB,GL_UNSIGNED_BYTE,data);

return true;
}





I am so puzzled, if I go back to gluBuild2DMipmaps(GL_TEXTURE_2D,3,size,size,GL_RGB,GL_UNSIGNED_BYTE,data); and just avoid any textures larger than 128x128 it works fine, with glTexImage2D none of them work. I don't understand the purpose of border, but I assume it should be 0? Setting it to 1 doesn't help.

Share this post


Link to post
Share on other sites
Texture parameters can only be applied to the currently bound texture, they can't be applied globally. In the code you posted, there is no texture bound when you set the minification filter. Also the min/magnification filters are also set via glTexParameteri not glTexParameterf as your code states, they're integer flags, not floating point values =].

So when you load the texture, it takes the default per-texture values. According to the docs the default value for the minification filter is GL_NEAREST_MIPMAP_LINEAR, meaning that mipmaps are enabled. =P

Try pasting the code I posted between your calls to glBindTexture and glTexImage2D.

Share this post


Link to post
Share on other sites
Ok. I have taken that into account and the blasted thing is still messing up :O

The problem now seems to be a bit more related to what I should be able to understand however, the texture is being loaded but it doesn't seem to be loading as the right format but I am so sure I'm doing it right :S

Take a look at what I am working on, and see this screenshot of the problem:



I have seen that before when working on the texture loading but I can't see how it is still happening :S The function should be fine because the grass texture is good (128x128 texture). And I am so sure I exported the image properly from gimp (I exported it again to make sure). You have been a great help, and solved filtering problems I would have encountered later if I wasn't corrected now.

current state of the method:

//24bpp raw image file
bool loadRawRGB(char* path,int size = 128){
/*
using pow is far slower than * for small integers, I made a small program to test this.
*/

int bytes = size * size * 3; //3 bytes per pixel
BYTE * data;
data = new BYTE[bytes]; //buffer to hold raw image data
//BYTE * data[bytes];
FILE * file; //file handle

//errorMsg("variables initialised");

//open and read texture data
file = fopen(path,"rb"); //attempt to open the file
if(!file) //don't continue if it couldn't be opened
return false;

//errorMsg("file opened");

fread(data,bytes,1,file); //copy file contents into the buffer
fclose(file); //close the file

//errorMsg("file read");

//allocate a texture resource
glGenTextures(1,&texture);
//set as target
glBindTexture(GL_TEXTURE_2D,texture);
//choose filtering options
//if(linear){
//bilinear filtering
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
//} else {
//nearest-neighbour filtering
//glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST);
//glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST);
//}
//tell opengl to make a the texture piramid
//gluBuild2DMipmaps(GL_TEXTURE_2D,3,size,size,GL_RGB,GL_UNSIGNED_BYTE,data);
glTexImage2D(GL_TEXTURE_2D,0,3,size,size,0,GL_RGB,GL_UNSIGNED_BYTE,data);
//errorMsg("texture associated");

return true;
}



I tried with glBuild2DMipmaps instead of glTexImage2D commented and it still loaded the same way.

I need to sleep on this (4AM here) and check back tomorrow.

Can't wait to get all this sorted so I can make some more interesting stuff, and no doubt overcome various other difficulties >_<

Share this post


Link to post
Share on other sites
I loaded the bricks raw file into photoshop and found out that it is a 512x512 CYMK image apparently. With 4 texture chanels, not 3. Which obviously causes a few problems for your file loading which assumes RGB =P

I saved it back out as a RGB and it now works fine in the app. If you need me to send you it then let me know, but if you can do it yourself it'd be much quicker than downloading a raw texture file. [smile]

Share this post


Link to post
Share on other sites
Yes! Got it working thanks for the help.

gimp insisted it was the format I was looking for. Had to stick the tga on my camera as a usb pen, take it to my flatmate's machine and export it with photoshop ^_^

Now I need to tackle model loading, and take a look at direct input.

One other question that no doubt I will end up making a thread for later.
When ordering transparent objects by the z-depth, is there a trick to do this or do I calculate the distance from the camera object?

Once I have a class structure setting up a list and ordering it appropriately shouldn't be an issue, if that is the correct way.

Share this post


Link to post
Share on other sites
Sorting based on distance from the camera should do the trick. It's not technically right, since the sorting should really be done in eye space to get the best results, but it's easier and you'll never notice any differences unless you're really looking for them. Neither method is perfect though, there are still some cases where it can screw up. [smile]

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this  

  • Announcements

  • Forum Statistics

    • Total Topics
      628357
    • Total Posts
      2982225
  • Similar Content

    • By test opty
      Hi all,
       
      I'm starting OpenGL using a tut on the Web. But at this point I would like to know the primitives needed for creating a window using OpenGL. So on Windows and using MS VS 2017, what is the simplest code required to render a window with the title of "First Rectangle", please?
       
       
    • By DejayHextrix
      Hi, New here. 
      I need some help. My fiance and I like to play this mobile game online that goes by real time. Her and I are always working but when we have free time we like to play this game. We don't always got time throughout the day to Queue Buildings, troops, Upgrades....etc.... 
      I was told to look into DLL Injection and OpenGL/DirectX Hooking. Is this true? Is this what I need to learn? 
      How do I read the Android files, or modify the files, or get the in-game tags/variables for the game I want? 
      Any assistance on this would be most appreciated. I been everywhere and seems no one knows or is to lazy to help me out. It would be nice to have assistance for once. I don't know what I need to learn. 
      So links of topics I need to learn within the comment section would be SOOOOO.....Helpful. Anything to just get me started. 
      Thanks, 
      Dejay Hextrix 
    • By mellinoe
      Hi all,
      First time poster here, although I've been reading posts here for quite a while. This place has been invaluable for learning graphics programming -- thanks for a great resource!
      Right now, I'm working on a graphics abstraction layer for .NET which supports D3D11, Vulkan, and OpenGL at the moment. I have implemented most of my planned features already, and things are working well. Some remaining features that I am planning are Compute Shaders, and some flavor of read-write shader resources. At the moment, my shaders can just get simple read-only access to a uniform (or constant) buffer, a texture, or a sampler. Unfortunately, I'm having a tough time grasping the distinctions between all of the different kinds of read-write resources that are available. In D3D alone, there seem to be 5 or 6 different kinds of resources with similar but different characteristics. On top of that, I get the impression that some of them are more or less "obsoleted" by the newer kinds, and don't have much of a place in modern code. There seem to be a few pivots:
      The data source/destination (buffer or texture) Read-write or read-only Structured or unstructured (?) Ordered vs unordered (?) These are just my observations based on a lot of MSDN and OpenGL doc reading. For my library, I'm not interested in exposing every possibility to the user -- just trying to find a good "middle-ground" that can be represented cleanly across API's which is good enough for common scenarios.
      Can anyone give a sort of "overview" of the different options, and perhaps compare/contrast the concepts between Direct3D, OpenGL, and Vulkan? I'd also be very interested in hearing how other folks have abstracted these concepts in their libraries.
    • By aejt
      I recently started getting into graphics programming (2nd try, first try was many years ago) and I'm working on a 3d rendering engine which I hope to be able to make a 3D game with sooner or later. I have plenty of C++ experience, but not a lot when it comes to graphics, and while it's definitely going much better this time, I'm having trouble figuring out how assets are usually handled by engines.
      I'm not having trouble with handling the GPU resources, but more so with how the resources should be defined and used in the system (materials, models, etc).
      This is my plan now, I've implemented most of it except for the XML parts and factories and those are the ones I'm not sure of at all:
      I have these classes:
      For GPU resources:
      Geometry: holds and manages everything needed to render a geometry: VAO, VBO, EBO. Texture: holds and manages a texture which is loaded into the GPU. Shader: holds and manages a shader which is loaded into the GPU. For assets relying on GPU resources:
      Material: holds a shader resource, multiple texture resources, as well as uniform settings. Mesh: holds a geometry and a material. Model: holds multiple meshes, possibly in a tree structure to more easily support skinning later on? For handling GPU resources:
      ResourceCache<T>: T can be any resource loaded into the GPU. It owns these resources and only hands out handles to them on request (currently string identifiers are used when requesting handles, but all resources are stored in a vector and each handle only contains resource's index in that vector) Resource<T>: The handles given out from ResourceCache. The handles are reference counted and to get the underlying resource you simply deference like with pointers (*handle).  
      And my plan is to define everything into these XML documents to abstract away files:
      Resources.xml for ref-counted GPU resources (geometry, shaders, textures) Resources are assigned names/ids and resource files, and possibly some attributes (what vertex attributes does this geometry have? what vertex attributes does this shader expect? what uniforms does this shader use? and so on) Are reference counted using ResourceCache<T> Assets.xml for assets using the GPU resources (materials, meshes, models) Assets are not reference counted, but they hold handles to ref-counted resources. References the resources defined in Resources.xml by names/ids. The XMLs are loaded into some structure in memory which is then used for loading the resources/assets using factory classes:
      Factory classes for resources:
      For example, a texture factory could contain the texture definitions from the XML containing data about textures in the game, as well as a cache containing all loaded textures. This means it has mappings from each name/id to a file and when asked to load a texture with a name/id, it can look up its path and use a "BinaryLoader" to either load the file and create the resource directly, or asynchronously load the file's data into a queue which then can be read from later to create the resources synchronously in the GL context. These factories only return handles.
      Factory classes for assets:
      Much like for resources, these classes contain the definitions for the assets they can load. For example, with the definition the MaterialFactory will know which shader, textures and possibly uniform a certain material has, and with the help of TextureFactory and ShaderFactory, it can retrieve handles to the resources it needs (Shader + Textures), setup itself from XML data (uniform values), and return a created instance of requested material. These factories return actual instances, not handles (but the instances contain handles).
       
       
      Is this a good or commonly used approach? Is this going to bite me in the ass later on? Are there other more preferable approaches? Is this outside of the scope of a 3d renderer and should be on the engine side? I'd love to receive and kind of advice or suggestions!
      Thanks!
    • By nedondev
      I 'm learning how to create game by using opengl with c/c++ coding, so here is my fist game. In video description also have game contain in Dropbox. May be I will make it better in future.
      Thanks.
  • Popular Now