# OpenGL strangeness w / transparency and Z buffer (2d map editor)

This topic is 4898 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts


for(int y = 0; y < visable_y_tiles; y++)
{
for(int x = 0; x < visable_x_tiles; x++)
{

//DRAWN WITH A Z VALUE OF 0
draw_tile(map[y][x]);

if(show_solidity)
{
//THESE ARE DRAWN WITH A Z VALUE OF 5
if(map[y][x] IS SOLID)
}
}
}

for(each free floating map object)
{
obj.Render();  <--------- DRAWS WITH A Z VALUE OF 0
}

---------- NOW SOMEWHERE ELSE IN THE CODE ---------------

Free_Floating_Map_Object::Render()
{

//DRAWN WITH A Z VALUE OF 0

//DRAWN WITH A Z VALUE OF 5
}


sorry for such a long post. this is one of those weird bugs that take a long time to explain. i hope im missing something obvious. in the psuedo code i show the order in which i drawn things and the Z value each thing has. the way i have it set up is closer to 10 means closer to the screen, and further from 10 means further into the screen. thanks alot for any help!!

##### Share on other sites
What do you have your near/far values set in gluPerspective()?

This could be a z-buffer resolution issue. If your far plane is set to something really large, or near is something really small, then the precision of your z-values near your image plane might be much worse than 1. If your quad at 5 was getting mapped to the same depth as a quad at 0, that could explain it.

This seems a little weird, but that was my first thought.

##### Share on other sites
When you said you have znear = -10, zfar = 10, are those the near/far plane values for gluPerspective?

If they are, then you are misunderstanding what they are. znear can NEVER be zero or negative. You can set it to something like .001.

What this means is the distance from the camera to the image plane. It doesn't make sense to have an image plane behind the camera. If you want a range from -10 to 10, set your camera at -11, near at 1, and far at 21.

If this is what you have done, I appologize. If not, try this and see if it helps.

##### Share on other sites
hey anonymous, thanks for the reply. actually, im using those values in the call to glOrtho() and set my zNear to -10 and zFar to 10,and i make 0,0 the top left corner and w/h of screen res the bottom right corner.... I dont use gluPerspective at all.. i probably should have mentioned that in the post [smile]. thanks for anymore help.

##### Share on other sites
Hmm....is it possible that you still have the S or N texture bound when you draw your tiles?

Have you tried reversing the order in which you draw the tiles that dissapear and the tiles that remain visible?

##### Share on other sites
hi renderer, i think your a little confused on whats happening. i think its due to the shrunken screenshot. anyway, no tiles are disapearing. the building is not a bunch of tiles, it is a single quad that represents a "free floating map object". this FFMO is disapearing when i want to "view solidity". checking off "view solidity" just means to draw an S or an N quad over each tile based on if they were solid or non solid. it just allows me to see if a tile is solid or not.

anyway, when i im showing solidity, for some reason my building disapears. im not sure why, since, the S and N quads are on a much higher Z level (meaning they should be drawn over the building), so if they are above the building, how come i cant see the building given that the S and N textures are transparent? in fact, i can even see the tiles that are underneath the building. the building and the tiles both have a Z of 0 and the S and N have a Z of 5. also, the tiles are drawn first, so the building *should* be on top of the tiles. it just doesnt really make sence... where did my building go?

to give you a better idea, heres a non shrunked screeny. first, this is what the map looks like in normal view, without "showing solidity"

next, heres what it looks like when i "view solidity"

do you see what im talking about? the building just vanishes! given the fact the building and tiles both have the same Z value, and the building is drawn after the tiles, i should be seeing a building right now!!

anyway, heres what it should look like, although in the real version there would be no tiles drawn over the building since the building and tiles share the same Z and the building is drawn last. i made this in Paint Shop Pro:

thanks for any help

##### Share on other sites
Hmm...can't tell if it's OpenGL or possibly just a bug somewhere in your code. I'd try rearanging the order you draw...draw the building before the S/N quads and see what happens.

##### Share on other sites
ok, wow, im so confused...

i took your advise and tried rendering the S/N quad AFTER i render the building. this worked! i can see my building now, the S/N is drawn over the building, and i can still see the building since the S/N has a transparent background.

this doesnt make any sence! why would i have to draw the S/N AFTER the building? why cant i draw it before? i have verified the Z values, so i dont get it... to sum it up:

-draw my tiles at 0 Z value
-draw my S/N at 5 Z value
-draw my building at 0 Z value

the building disapears, even through the S/N has a transparent background!

-draw my tiles at 0 Z value
-draw my building at 0 Z value
-draw my S/N at 5 Z value

this works! the S/N is drawn over the building, and since it has a transparent background, i can still see the building.

why does my building disapear using the first method? why dont my tiles disapear, too, since they share the same Z value? well, i guess they dont disapear because they are drawn before the S/N, but like i said, the S/N is transparent, so anything under it, i should see... it just doesnt make any sence.

thanks a lot for any further help. i'd really like to figure out why this is happening. i dont like not understanding something as important as the basics of rendering. does it have to do with transparency or something? the other thing is, i dont want to have to draw my S/N after i draw the buildings. I'd like to draw the S/N immediately after i draw the tiles, since they share the same rendering loop. i dont want to have to draw in 2 passes. thanks again.

##### Share on other sites
Quote:
 this doesnt make any sence! why would i have to draw the S/N AFTER the building? why cant i draw it before? i have verified the Z values, so i dont get it... to sum it up:

You do have depth checking enabled, right?

##### Share on other sites
you mean depth testing, right? then yes, i do have that enabled, otherwise i dont think all the other stuff that messes with the Z axis would be working (and it is...). heres all the code i use to set-up OpenGL.

void System::Init_OpenGL(){	/* Enable Texture Mapping ( NEW ) */	glEnable(GL_TEXTURE_2D);    /* Enable smooth shading */    glShadeModel(GL_SMOOTH);    /* Set the background black */    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);    /* Depth buffer setup */    glClearDepth(1.0f);    /* Enables Depth Testing */    glEnable(GL_DEPTH_TEST);    /* The Type Of Depth Test To Do */    glDepthFunc(GL_LEQUAL);    /* Really Nice Perspective Calculations */    glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);	glHint(GL_POINT_SMOOTH_HINT,GL_NICEST);			glEnable(GL_BLEND);	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);	/* Setup our viewport. */    glViewport(0,0,SCREEN_RW,SCREEN_RH);    /* change to the projection matrix and set our viewing volume. */    glMatrixMode(GL_PROJECTION);    	glLoadIdentity();	glOrtho(0,SCREEN_RW,SCREEN_RH,0,-10.0f,10.0f);    glMatrixMode(GL_MODELVIEW);  /* Reset The View */    glLoadIdentity();	// DISABLE V SYNC !!!	typedef void (APIENTRY * WGLSWAPINTERVALEXT) (int);	WGLSWAPINTERVALEXT wglSwapIntervalEXT = (WGLSWAPINTERVALEXT) wglGetProcAddress("wglSwapIntervalEXT");	if (wglSwapIntervalEXT) 	   wglSwapIntervalEXT(0); // disable vertical synchronisation  }

##### Share on other sites
Quote:
 Original post by graveyard fillaok, wow, im so confused...-draw my tiles at 0 Z value-draw my S/N at 5 Z value-draw my building at 0 Z valuethe building disapears, even through the S/N has a transparent background!-draw my tiles at 0 Z value-draw my building at 0 Z value-draw my S/N at 5 Z valuethis works! the S/N is drawn over the building, and since it has a transparent background, i can still see the building.

Hmm, when you draw the S/N at 5, do the transparent parts change the depth buffer? Are you using alpha blending, or alpha test to throw away transparent pixels? This would make all the difference. If you are blending an alpha of 0 with the background, you will see the background, but the depth value will be set at 5, and when you draw your building at depth 0, all pixels will fail the depth test. If you use alpha test to throw away pixels with alpha of 0, then it won't set the depth buffer for those pixels.

I think this makes sense...but I'm not strong on alpha blending...

##### Share on other sites
Yes that's it, look at the init code. Instead of doing blending, you can do
glEnable(GL_ALPHA_TEST);
glAlphaFunc(GL_EQUAL, 1);

That will cause any transparent parts to not be drawn.

If you want to smooth out the edges of your S/N, you might want to change 1 to something like .5 and use GL_GREATER. If you still enable blending, the partially opaque edges will be blended with whatever pixel color is there when it draws (i.e. the tile). When you draw the building later, it won't look like it blended with the building, but instead some of the tile will show through (i.e. the portion that blended with the S/N). This may not look very good.

##### Share on other sites
hi,

thanks a lot anonymouse and renderer. im still confused though. first of all, i MUST keep blending enabled. this is because i use blending in a lot of different things.

secondly, i still dont understand why this is happening. i really just dont get it. what is meant exactly by "all pixels will fail the depth test" ??

lastly, how could i get everything working with blending still enabled? liked i said, i need it still for things. thanks a lot guys for all your help.

##### Share on other sites
First of all, put those 2 lines of code in your init code and see if it fixes everything.

Now for the explanation..

When you say something is transparent and blended, as each pixel is being drawn into the frame buffer, it gets blended with whatever pixel is already there, according to the blending rules (i.e. SRC_ALPHA, ONE_MINUS_SRC_ALPHA). If you draw something else with a z value behind that pixel at a later time, OpenGL doesn't "re-blend" your pixels. Think about this...it would have to keep track of every single transparent pixel drawn.

So if you want to use an overlay with completely transparent pixels, but still want to draw something "behind" it at a later point, the only way to do this is to not have drawn that pixel at all. That's what the GL_ALPHA_TEST does. Based on the alpha value of each pixel, you can either draw it or throw it away. If you still want to gave blending, you can indeed use both.

Try this:
glEnable(GL_ALPHA_TEST);
glAlphaFunc(GL_GREATER, 0);

That will blend anything with alpha greater than 0, and throw away anything that's completely transparent.

The key issue is that when you blend a transparent pixel with the background, the depth value for that pixel is now the depth of the transparent pixel. If you try and draw something "behind it", it will fail the depth test (i.e. it won't overwrite the pixel because the depth of the new pixel is "behind" what's already there).

If this is still confusing, I suggest you read up on how the depth buffer works (OpenGL red book is a good place to start).

##### Share on other sites
that did it... thanks a lot man. i think i understand what your saying... theres only a few parts i didnt get..

"If you draw something else with a z value behind that pixel at a later time, OpenGL doesn't "re-blend" your pixels. Think about this...it would have to keep track of every single transparent pixel drawn."

did you mean draw something else with a z value closer to the screen then that pixel ?

also,
"That will blend anything with alpha greater than 0, and throw away anything that's completely transparent."

what do you mean by alpha greater then 0, exactly?

last, what does it mean exactly by "Failing the depth test"?

im gunna have to start checking out the Red Book again. thanks a lot for your help.

##### Share on other sites
"If you draw something else with a z value behind that pixel at a later time, OpenGL doesn't "re-blend" your pixels. Think about this...it would have to keep track of every single transparent pixel drawn."

What i mean is that if you draw something at say -2, then draw a 50% transparent object at +2, you will see half of the color of the pixel from -2 and half from +2...right?
Now if you draw something at 0 afterwards, you see no change.
BUT, if you draw something at -2, then something at 0, then something at +2 with 50% transparency, the you will see 50% of the pixel at 0 and 50% at 2.

Why does drawing order matter? Because of the depth buffer. Each pixel that gets rasterized for every single primative goes through the "depth test". OpenGL looks at the depth of the pixel currently at that location and check is the new one is closer to the camera or farther. If it is farther away, it doesn't have to do anything, because it is covered by the closer pixel. This is why you can draw your triangles in any order for a normal mesh (no transparency). If you turn off depth test, you will see that whatever primatives you drew last end up in front.

So the catch is that blending order matters! If you want to draw 4 semi-transparent objects one on top of another, you have to draw the furthest one away first, becuase if you draw a closer on first, the farther one will fail the depth test (i.e. not get drawn at all).

"That will blend anything with alpha greater than 0, and throw away anything that's completely transparent."

what do you mean by alpha greater then 0, exactly?

Alpha values range from 0 to 255 (or in float, 0 to 1), with zero being completely transparent and 1 being completely solid (opaque). If you want to use blending, you need to keep pixels with alpha values greater than 0 (because they are semi opaque), but if you don't want to worry about drawning order for your S/N with completely transparent pixels, you can throw away all pixels with alpha values of 0 (using GL_ALPHA_TEST).

last, what does it mean exactly by "Failing the depth test"?
The current pixel being drawn is further away from the camera than a pixel in the same location that's already been drawn. That pixel fails the depth test and as a result does not get drawn.

im gunna have to start checking out the Red Book again. thanks a lot for your help.

Yup, I've read through several sections at least 4 or 5 times and I'm only finally starting to get a really good handle of what's goin on.

##### Share on other sites
thanks a lot renderer. i didnt know how alpha blending and the Z buffer worked, but now i have a pretty good idea. so OpenGL optimizes by throwing away pixels that *shouldnt* be seen then (this is the depth test?)? i think i get it. just to be sure, i DONT have to do anything special now, right? since now i have it so that things which have an alpha value of zero are just never even drawn to the screen, this will solve my problems, correct?

but this brings up another issue. what about objects who are 2%, or 50%, or 80% transparent? do i have to sort these objects somehow? i really, really hope not. i thought i was finnally done with all my sorting algo's =).

the other thing is, im a little confused when you say things with 50% or xy% transparency. when you say this, do you mean they are given their transparency level by the call to glColor4f(), IE, given their transparency by the quad they are drawn on? OR, do you mean things with per pixel alpha blending? IE, a .png image file which makes use of per pixel blending, having some pixels with 0% trans and others with 50%... ive never used these before, so i could be wrong, but im pretty sure that is possible. are these 2 things treated the same by OpenGL, or are they different? currently i just use 0% transparency in my textures, so i dont know.

thanks again for all your help

##### Share on other sites
The alpha channel applies to both situations. If you have a colored quad (each vertex has a glColor4f(r,g,b,a)) then it blends the colors between the 4 vertices (including the alpha channel) so each pixel has some alpha value. Similarly, if you have a texture mapped quad, and that texture was loaded from a png with transparency levels, or generated from wherever, then when that texture gets applied to a quad and the quad is drawn, each pixel that gets drawn has some transparency.

As far as needing to sort things for blending...short answer yes, but only in certain situations. Since blending occours only once (when that pixel is drawn), and blending occours with whatever pixel is CURRENTLY behind that pixel, you need to make sure that you have the right pixels already drawn before you draw something to be blended on top. If you are drawing multiple semi-transparent objects on top of one another, then they need to be sorted back-to-front. If you were say drawing a 50% blue tinted window on a house, then you need to make sure everything inside the house is already drawn first, if you are looking from the outside, or that everything outside the house is already drawn, if you are looking from the inside.

Hope this makes things clear. Good luck with your programming.

##### Share on other sites
i still dont really fully understand how / why its all happening, but i think i get the gist of it. so basically, the only time i should worry is if i wanted to draw 2 partially transparent objects over-lapping and both objects had varying Z values which i was depending on to "sort" them. in your house with blue window example, i would only have to worry if something outside / in the house was also partially transparent, right? if this is the case, then this isnt really that big of a deal. i guess no partial transparency in my tile layering system, kind of a bummer.

i guess its not THAT bad to get around.anything which is partially transparent, ill have to store togeather. then, each frame, ill sort() this list of partially transparent stuff by the Y axis, putting things that are further up on the screen to the front of the list. then i just render front to back. this will make it so something above another object is drawn first. so if i have 2 partially transparent guys and guy A is standing above guy B, the top part of guy B's body will overlap the bottom part of guy A.

the hard part will be figuring out what objects are partially transparent and knowing to put them in that special list. it also sort of makes it sloppy because now i have things grouped togeather, but in that system things would be in different places, which is unorganized.

actually, now that i think about it, instead of sorting the transparent object by their Y value, i should do it by their Z value, right? since their Z value already tells me what order to draw them, and that is whats screwing things up in the first place anyway. so i would sort() by Z value and put all things further from the camera in the front of the list, and then draw front to back. this should stop things from not getting rendered, correct? maybe ill just try to avoid this by just not making anything partially transparent that needs to be sorted for drawing.

thanks again for all your help!!!

##### Share on other sites
hey renderer (or whoever),

i was thinking, its kind of difficult to group all semi-transparent objects togeather and sort them. does anyone have any suggestions on how to do this?

actually, i was thinking it might just be easier to throw away the whole idea of using the Z axis. because i can get a "layered" effect by just rendering in multiple passes, and i wont have this issue with transparent objects. do you think i should say screw it, and just get rid of the Z axis? or, should i try to figured out a method to sort transparent objects? its really disapointing, too. using the Z axis for a layered effect was VERY convenient, and not only that, but it also would make rendering faster, since i would be able to stick all my tiles into a single vertex array and render them all at once, rather then sticking them in multiple vertex arrays and rendering it multiple passes. same goes for my other objects which are layered besides tiles...

thanks for any help or suggestions.

##### Share on other sites
sorry, but im going to shamelessly bump this. i really need your guys opinions on this, before i move on.

what do you think will be cleaner/easier/better ? should i just get this whole Z axis idea out of my head, and render in multiple passes (slower, less convenient). or, should i keep the Z axis, and somehow figure out a way to sort any semi-transparent objects which have varying Z values?

thanks a lot for any help!

• 12
• 10
• 11
• 18
• 13
• ### Similar Content

• Good Evening,
I want to make a 2D game which involves displaying some debug information. Especially for collision, enemy sights and so on ...
First of I was thinking about all those shapes which I need will need for debugging purposes: circles, rectangles, lines, polygons.
I am really stucked right now because of the fundamental question:
Where do I store my vertices positions for each line (object)? Currently I am not using a model matrix because I am using orthographic projection and set the final position within the VBO. That means that if I add a new line I would have to expand the "points" array and re-upload (recall glBufferData) it every time. The other method would be to use a model matrix and a fixed vbo for a line but it would be also messy to exactly create a line from (0,0) to (100,20) calculating the rotation and scale to make it fit.
If I proceed with option 1 "updating the array each frame" I was thinking of having 4 draw calls every frame for the lines vao, polygons vao and so on.
In addition to that I am planning to use some sort of ECS based architecture. So the other question would be:
Should I treat those debug objects as entities/components?
For me it would make sense to treat them as entities but that's creates a new issue with the previous array approach because it would have for example a transform and render component. A special render component for debug objects (no texture etc) ... For me the transform component is also just a matrix but how would I then define a line?
Treating them as components would'nt be a good idea in my eyes because then I would always need an entity. Well entity is just an id !? So maybe its a component?
Regards,
LifeArtist
• By QQemka
Hello. I am coding a small thingy in my spare time. All i want to achieve is to load a heightmap (as the lowest possible walking terrain), some static meshes (elements of the environment) and a dynamic character (meaning i can move, collide with heightmap/static meshes and hold a varying item in a hand ). Got a bunch of questions, or rather problems i can't find solution to myself. Nearly all are deal with graphics/gpu, not the coding part. My c++ is on high enough level.
Let's go:
Heightmap - i obviously want it to be textured, size is hardcoded to 256x256 squares. I can't have one huge texture stretched over entire terrain cause every pixel would be enormous. Thats why i decided to use 2 specified textures. First will be a tileset consisting of 16 square tiles (u v range from 0 to 0.25 for first tile and so on) and second a 256x256 buffer with 0-15 value representing index of the tile from tileset for every heigtmap square. Problem is, how do i blend the edges nicely and make some computationally cheap changes so its not obvious there are only 16 tiles? Is it possible to generate such terrain with some existing program?
Collisions - i want to use bounding sphere and aabb. But should i store them for a model or entity instance? Meaning i have 20 same trees spawned using the same tree model, but every entity got its own transformation (position, scale etc). Storing collision component per instance grats faster access + is precalculated and transformed (takes additional memory, but who cares?), so i stick with this, right? What should i do if object is dynamically rotated? The aabb is no longer aligned and calculating per vertex min/max everytime object rotates/scales is pretty expensive, right?
Drawing aabb - problem similar to above (storing aabb data per instance or model). This time in my opinion per model is enough since every instance also does not have own vertex buffer but uses the shared one (so 20 trees share reference to one tree model). So rendering aabb is about taking the model's aabb, transforming with instance matrix and voila. What about aabb vertex buffer (this is more of a cosmetic question, just curious, bumped onto it in time of writing this). Is it better to make it as 8 points and index buffer (12 lines), or only 2 vertices with min/max x/y/z and having the shaders dynamically generate 6 other vertices and draw the box? Or maybe there should be just ONE 1x1x1 cube box template moved/scaled per entity?
What if one model got a diffuse texture and a normal map, and other has only diffuse? Should i pass some bool flag to shader with that info, or just assume that my game supports only diffuse maps without fancy stuff?
There were several more but i forgot/solved them at time of writing
• By RenanRR
Hi All,
I'm reading the tutorials from learnOpengl site (nice site) and I'm having a question on the camera (https://learnopengl.com/Getting-started/Camera).
I always saw the camera being manipulated with the lookat, but in tutorial I saw the camera being changed through the MVP arrays, which do not seem to be camera, but rather the scene that changes:
#version 330 core layout (location = 0) in vec3 aPos; layout (location = 1) in vec2 aTexCoord; out vec2 TexCoord; uniform mat4 model; uniform mat4 view; uniform mat4 projection; void main() { gl_Position = projection * view * model * vec4(aPos, 1.0f); TexCoord = vec2(aTexCoord.x, aTexCoord.y); } then, the matrix manipulated:
..... glm::mat4 projection = glm::perspective(glm::radians(fov), (float)SCR_WIDTH / (float)SCR_HEIGHT, 0.1f, 100.0f); ourShader.setMat4("projection", projection); .... glm::mat4 view = glm::lookAt(cameraPos, cameraPos + cameraFront, cameraUp); ourShader.setMat4("view", view); .... model = glm::rotate(model, glm::radians(angle), glm::vec3(1.0f, 0.3f, 0.5f)); ourShader.setMat4("model", model);
So, some doubts:
- Why use it like that?
- Is it okay to manipulate the camera that way?
-in this way, are not the vertex's positions that changes instead of the camera?
- I need to pass MVP to all shaders of object in my scenes ?

What it seems, is that the camera stands still and the scenery that changes...
it's right?

Thank you

• Sampling a floating point texture where the alpha channel holds 4-bytes of packed data into the float. I don't know how to cast the raw memory to treat it as an integer so I can perform bit-shifting operations.

int rgbValue = int(textureSample.w);//4 bytes of data packed as color
// algorithm might not be correct and endianness might need switching.
vec3 extractedData = vec3(  rgbValue & 0xFF000000,  (rgbValue << 8) & 0xFF000000, (rgbValue << 16) & 0xFF000000);
extractedData /= 255.0f;

• While writing a simple renderer using OpenGL, I faced an issue with the glGetUniformLocation function. For some reason, the location is coming to be -1.
Anyone has any idea .. what should I do?