Sign in to follow this  
brunooo

OpenGL Opengl drawing many textures!

Recommended Posts

Hello! I've beeing playing around with opengl doing 2D things. I draw a single and big texture (the scenario) to the screen, with that I got around 400 fps, so far so good. Than I decided to make some tiling, assembling tiles together making the big scenario! I am using 16x16 pixels tiles. In a 800x768 I get 50x48 tiles. I have two types of tiles, a green (grass) and a brown one (dirty), I use them as textures. So if I want all scenario to have grass I would make:
for (int x = 0;x < 50;x++)
{
    for (int y = 0;y < 48;y++)
    {
        glPushMatrix();
        glTranslatef(x*16,y*16,0.0f);
        glBindTexture(GL_TEXTURE_2D,grass);
        glBegin(GL_QUADS);
        ... // Vertexes and Texcoords
        glEnd();
        glPopMatrix();
    }
}
I thought that this would work, and it does work! But the fps drops to around 220! Why drawing many tiny textures to compose a big image is slower than drawing a big texture? What should I do? Any suggestions? Thank you!

Share this post


Link to post
Share on other sites
The texture binding is slow. And you call it 48*50 times per frame.
You could speed it up by drawing the only the green tiles, than only the dirty tiles, so you only have to bind 2 times per frame, and the extra if statement wont slow it down too much.
Same goes for the glBegin-glEnd. If you discard the translation, by applying the proper coordinates to the glVertex calls, you can only have 2 glBegin-glEnd pairs.
I hope thah helps.

Share this post


Link to post
Share on other sites
Quote:
Original post by brunooo
I thought that this would work, and it does work! But the fps drops to around 220! Why drawing many tiny textures to compose a big image is slower than drawing a big texture?
What should I do? Any suggestions?

In general practice, it's best to reduce the total number of computations and operations you have executing within any sort of loop. One slowdown in your example set of for-loops is the repeated binding of the grass texture. When using one texture in many places, you only need to bind it once. Try binding the texture outside of your for-loops and see what sort of improvements you get there.

Edit: szecs beat me to it!

Share this post


Link to post
Share on other sites
This was fast o.O

szecs, what should I do to speed it up?

Omega147, I cant bind the texture outside of the loop, in this example I am theoretically binding the same texture several times, I should check in the position what tile image it is. When my scenario gets detailed what I am going to do? I could have 10 different textures and bind one and check where it needs to be draw and so on, but what if I have 1000 different textures? :/

Share this post


Link to post
Share on other sites
Quote:
Original post by brunooo
Omega147, I cant bind the texture outside of the loop, in this example I am theoretically binding the same texture several times, I should check in the position what tile image it is. When my scenario gets detailed what I am going to do? I could have 10 different textures and bind one and check where it needs to be draw and so on, but what if I have 1000 different textures? :/

In that case, you might look into GameDev's Framebuffer tutorials: Part 1 and Part 2. The second part deals with multiple textures, which will probably interest you the most.

Share this post


Link to post
Share on other sites
In pseudo code, this should be faster:

glPushMatrix
glTranslatef( worldX, worldY, 0 );
glBegin()
for ( textures )
bindTexture()
for ( ties with that texture )
//verts and tex coords
glEnd()
glPopMatrix()


Notice the push/pop happen outside the tile loop.
The textures are set outside the loop.
There is no push/pop/translate in the main loop. The vert coords need to be in world space instead of doing translatef calls for each one.

Share this post


Link to post
Share on other sites
Omega147, thanks, I will take a look on that!

KulSeran, indeed calling glTranslatef only once gave me a performance improvement! But binding textures between glBegin and glEnd does not work, it draw weird things :p

Share this post


Link to post
Share on other sites
Quote:
Original post by szecs
The texture binding is slow. And you call it 48*50 times per frame.
You could speed it up by drawing the only the green tiles, than only the dirty tiles, so you only have to bind 2 times per frame, and the extra if statement wont slow it down too much.
Same goes for the glBegin-glEnd. If you discard the translation, by applying the proper coordinates to the glVertex calls, you can only have 2 glBegin-glEnd pairs.
I hope thah helps.


The answer is in there

bind green texture
loop through tiles
{ if(green[x,y])
draw tile(x,y)
}
bind dirt texture
loop through tiles
{ if(not green[x,y])
draw tile(x,y)
}

In draw tile, you can do the push-transform-draw-pop, or which is better, draw with proper coordinates (as I told you in my prev. post), this way, you could put them outside the loop, just as you could with the binding.
Texture binding and transformations aren't allowed between glBegin-glEnd

Share this post


Link to post
Share on other sites
Quote:
Original post by brunooo
binding textures between glBegin and glEnd does not work, it draw weird things :p

That's because binding textures between Begin and End is an illegal operation.

Also note that getting Begin ... End type rendering to be fast is very difficult for the driver. You'd be better off using vertex arrays in VBOs.

Share this post


Link to post
Share on other sites
If you have a list of these tiles then you could sort them based on the texture (since the texture id is a number should be simple).

Then bind first texture, render tiles untill tile has a different texture, bind the next texture and so on.

Best case its only going to bind 1 texture, worst case (unavoidable anyway) its going to bind every tile.

Sorting shouldn't take too long (you could do it in another thread while doing some of your other game logic if needs be, but with 200 fps I doubt it will be noticable). Its nice because its expandable without any extra work.

[source lang = "cpp"]
SortTiles();

unsigned int currentTexture = -1;

glBegin(GL_QUADS);
for(int i = 0; i < numTiles; i++)
{
if(currentTexture != tiles[i].texture)
{
glEnd();
currentTexture = tiles[i].texture;
glBindTexture(GL_TEXTURE_2D, currentTexture);
glBegin(GL_QUADS);
}
// vertices/tex to draw quad (use actual vertices not translate)
}
glEnd();


the begin/end pairs there look pretty nasty but I can't see any reason why its wrong to do it. As they do match up.

Share this post


Link to post
Share on other sites
Thank you, I will need to group the textures together to not bind them many times.

VBO's and Frame buffers will work on every computer with a gpu? Or it will only work on newer ones like I read that Shader only work in newer gpus (correct me if I am wrong). I want my game to run on my grandma computer with a very old gpu of 32 MB :) (At the moment it is working smoothly :D)

Share this post


Link to post
Share on other sites
Why it is a wrong method I posted?
Nanoha's approach has one drawback: if the texture changes many times (for example checked pattern), it will mean no speed boost.
glBindTexture(GL_TEXTURE_2D, texture1);
glBegin(GL_QUADS);
for(int i = 0; i < numTiles; i++)
{
if( tiles[i].texture == texture1)
{ vertices/tex to draw quad (use actual vertices not translate)
}
}
glEnd();
glBindTexture(GL_TEXTURE_2D, texture2);
glBegin(GL_QUADS);
for(int i = 0; i < numTiles; i++)
{
if( tiles[i].texture == texture2)
{ vertices/tex to draw quad (use actual vertices not translate)
}
}
glEnd();
glBindTexture(GL_TEXTURE_2D, texture3);
.
.
.//or place it in a loop too.




This way, you have exactly the same number of binding/begin-end, as your types of textures. The extra time spent in the more loops is negligible compared to the other methods. I'm beginning to think that my posts are invisible, or maybe I became the legendary ABARABA?

Share this post


Link to post
Share on other sites
To Szecs: Nanoha's approach is cleaner and more general (ie no advance knowledge of tile textures needed). He also mentioned to sort the tiles based on texture, so a checkerboard will not cause needless state changes :)

Share this post


Link to post
Share on other sites
Quote:
Original post by szecsor maybe I became the legendary ABARABA?


Lol Szecs, I did mine based on yours :P so your certainly not invisible. Its yours just a little more general/expandable. Each tile should be sorted based on texture first. So if its a checkbord type texture all the tiles would be sorted white first, then all the black ones so only 2 texture changes will be done.

If there are 200 different textures then yes, there will have to be 200 different texture changes but thats a problem with any method.

Share this post


Link to post
Share on other sites
Thanks again! I used stl map to group the textures with same texture object, and every loop I clear and refill it. I was not gaining performance than I profiled my program and found that the problem now is with stl maps :p, I will do something to not clear and refill it every time!

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
      628372
    • Total Posts
      2982305
  • 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