Subtractive blending with OpenGL? - c++

I would like to for example draw shapes A, B, C then set the blender, then draw shape D and everywhere where shape D is, the scene shows my background color of (1,1,1,0). Thanks

I'm not aware of that being possible directly. There are a few possibilities to get the same effect though. The cleanest would probably be to start by filling the stencil buffer with 1's, then drawing shape D into the stencil buffer with 0's, then draw everything else (with the stencil buffer enabled, of course).

Much simpler than other answers :
Display shapes A, B and C the normal way
glDisable(GL_DEPTH_TEST);
glDisable(GL_ALPHA_TEST);
glDisable(GL_BLEND);
Display shape D with color (1,1,1,0)
and you're done.

glBlendEquation can do it.

Related

OpenGL How to use a invisible mask to hide objects behind it

I have an OpenGL problem to solve. I have an object/mesh A, an object/mesh B and a background texture C.
Initially the framebuffer is filled with background texture C. We draw both A & B in the framebuffer. We want to keep object A visible, and object B always invisible.
In the beginning, A is in front of B. During rotation, at a certain angle, B is in front of A based on the depth test result, but since B is always invisible, B's part should be filled with background C.
Does anyone know a simple approach to solve this issue?
Is stencil test a good approach? Basically set object B with a color, compare the color of B with background C, and show the background C when the test fail.
Does anyone have any sample code I can read?
The easiest solution is to:
draw C;
draw B with the colour mask preventing writes to the frame buffer (but don't touch the depth mask, so that writes are still made to the depth buffer);
draw A, subject to the depth test.
The specific thing to use is glColorMask — if you supply GL_FALSE for each channel via that then subsequent geometry won't write any colour output. But assuming you haven't touched glDepthMask it'll still write depth output.
So, you've probably currently got the code:
drawBackground(C);
render(A);
render(B);
You'd just adapt that to:
drawBackground(C);
glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
render(B);
glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
render(A);

Drawing a Circle on a plane, Boolean Subtraction - OpenGL

I'm hoping to draw a plane in OpenGL, using C++, with a hole in the center, much like the green of a golf course for example.
I was wondering what the easiest way to achieve this is?
It's fairly simple to draw a circle and a plane (tutorials all over google will show this for those curious), but I was wondering if there is a boolean subtraction technique like you can get when modelling in 3Ds Max or similar software? Where you create both objects, then take the intersection/union etc to leave a new object/shape? In this case subtract the circle from the plane, creating a hole.
Another way I thought of doing it is giving the circle alpha values and making it transparent, but then of course it still leaves the planes surface visible anyway.
Any help or points in the right direction?
I would avoid messing around with transparency, blending mode, and the like. Just create a mesh with the shape you need and draw it. Remember OpenGL is for graphics, not modelling.
There are a couple ways you could do this. The first way is the one you already stated which is to draw the circle as transparent. The caveat is that you must draw the circle first before you draw the plane so that the alpha blending will blend the circle with the background. Then when you render the plane the parts that are covered by the circle will be discarded in the depth test.
The second method you could try is with texture mapping. You could create a texture that is basically a mask with everything set to opaque white except the circle portion which is set to have an alpha value of 0. In your shader you would then multiply your fragment color by this mask texture color so that the portions where the circle is located are now transparent.
Both of these methods would work with shapes other than a circle as well.
I suggest the stencil buffer. Use the stencil buffer to mark the area where you want the hole to be by masking the color and depth buffers and drawing only to the stencil buffer, then unmask your color and depth, avoid drawing to the stencil buffer, and draw your plane with a stencil function telling OpenGL to discard all pixels where the stencil buffer "markings" are.

Rendering two smaller textures onto a bigger texture

When I render a two textures onto a bigger texture.
Consider:
ID3D10Texture2D A
ID3D10Texture2D B
ID3D10Texture2D C
If I first draw Texture B, the full width of Texture A and then draw Texture C only on half of Texture A. Why is that Texture C is erasing the area of itself from Texture B?
I then draw Texture A onto the backbuffer to see the results.
I did some additional testing and found out that the alpha of Texture C is also affecting the alpha of Texture B such that if the alpha of texture C is too low, you can't really see texture B. How can such an issue be resolved? In fact, how could this even be an issue? Because, I rendered C after B. ##
blendDesc.BlendEnable[0] = TRUE;
blendDesc.RenderTargetWriteMask[0] = D3D10_COLOR_WRITE_ENABLE_ALL;
blendDesc.SrcBlend = D3D10_BLEND_SRC_ALPHA;
blendDesc.DestBlend = D3D10_BLEND_INV_SRC_ALPHA;
blendDesc.BlendOp = D3D10_BLEND_OP_ADD;
blendDesc.SrcBlendAlpha = D3D10_BLEND_ONE;
blendDesc.DestBlendAlpha = D3D10_BLEND_ZERO;
blendDesc.BlendOpAlpha = D3D10_BLEND_OP_ADD;
hr = aDXDevice->CreateBlendState(&blendDesc, &this->g_pBlendState);
NOTE: Texture B spans the full width, but texture C is only placed halfway ontop of texture B. Since Texture B is the solid red image, texture C + texture B should NOT be transparent.
Not pretend to be an answer, it's just a guess.
Possible cause of blending issue is a proliferation of states into next draw call.
All DirectX (and also GL) states are not being reset on end of frame, they persists until changed or context reset.
So, probably you have a blend state
hr = aDXDevice->CreateBlendState(&blendDesc, &this->g_pBlendState);
and you applying it after drawing B, but before drawing C:
DrawB();
aDXDevice->OMSetBlendState(&g_pBlendState, ...);
DrawC();
First frame draws as you expect, but on next frames g_pBlendState is still active. So B drawing without alpha only on a first frame.
What you need is two blend states, one for each blending mode, and apply it each frame:
aDXDevice->CreateBlendState(&blendDescForB, &blendStateForB); // no alpna
aDXDevice->CreateBlendState(&blendDescForC, &blendStateForC); // alpha enabled
aDXDevice->OMSetBlendState(blendStateForB, ...);
DrawB();
aDXDevice->OMSetBlendState(blendStateForC, ...);
DrawC();
For quick debugging of that issue you can try to apply ID3D10Device::ClearState after Present(). But just for debugging.
Note, that there are one point counter my hypothesis: blending of A not being touched.
Not sure of exact details but remember that OpenGL is a 3D library do it takes into account depth when it comes to determining which object occlude other objects. OpenGL also uses floating point numbers for vertices which means even if the numbers look equal then many well not be. The only safe way to ensure that one object is in front of the other is to draw it so. For 2D drawing generally, it is best to ensure that your objects to not overlap at all.

is there any conflict between GL_DEPTH_TEST and alpha blending in openGL?

I'm drawing some "2D" pictures.
Let's say, pic A in the background draw first, pic B in foreground draw later than A.
and there are some transparent area in B.
So when i enable GL_DEPTH_TEST, B should cover A but those transparent area.
the actual result i got here is strange, the B did cover A, but the transparent area show the very background instead of A which it should be.
i use
glFrustum as GL_PROJECTION,
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA),
glDepthFunc(GL_LEQUAL)
is there some settings i missing or what?
There shouldn't be any conflict of the sort you discuss. The depth buffer can hold only one depth per pixel, so transparency can be an issue because it's not really accurate to say that each pixel is composed of data from a single depth.
The net effect is that if you draw something partially transparent then try to draw something behind it, the depth buffer says not to draw. So while you should be able to see the thing behind, you can't.
In your case, what you're seeing would be expected behaviour if you were drawing B (in the foreground) and then A (in the background). Is it possible some aspect of your code is giving you an unexpected drawing order?

opengl - blending with previous contents of framebuffer

I am rendering to a texture through a framebuffer object, and when I draw transparent primitives, the primitives are blended properly with other primitives drawn in that single draw step, but they are not blended properly with the previous contents of the framebuffer.
Is there a way to properly blend the contents of the texture with the new data coming in?
EDIT: More information requsted, I will attempt to explain more clearly;
The blendmode I am using is GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA. (I believe that is typically the standard blendmode)
I am creating an application that tracks mouse movement. It draws lines connecting the previous mouse position to the current mouse position, and as I do not want to draw the lines over again each frame, I figured I would draw to a texture, never clear the texture and then just draw a rectangle with that texture on it to display it.
This all works fine, except that when I draw shapes with alpha less than 1 onto the texture, it does not blend properly with the texture's previous contents. Let's say I have some black lines with alpha = .6 drawn onto the texture. A couple draw cycles later, I then draw a black circle with alpha = .4 over those lines. The lines "underneath" the circle are completely overwritten. Although the circle is not flat black (It blends properly with the white background) there are no "darker lines" underneath the circle as you would expect.
If I draw the lines and the circle in the same frame however, they blend properly. My guess is that the texture just does not blend with it's previous contents. It's like it's only blending with the glclearcolor. (Which, in this case is <1.0f, 1.0f, 1.0f, 1.0f>)
I think there are two possible problems here.
Remember that all of the overlay lines are blended twice here. Once when they are blended into the FBO texture, and again when the FBO texture is blended over the scene.
So the first possibility is that you don't have blending enabled when drawing one line over another in the FBO overlay. When you draw into an RGBA surface with blending off, the current alpha is simply written directly into the FBO overlay's alpha channel. Then later when you blend the whole FBO texture over the scene, that alpha makes your lines translucent. So if you have blending against "the world" but not between overlay elements, it is possible that no blending is happening.
Another related problem: when you blend one line over another in "standard" blend mode (src alpha, 1 - src alpha) in the FBO, the alpha channel of the "blended" part is going to contain a blend of the alphas of the two overlay elements. This is probably not what you want.
For example, if you draw two 50% alpha lines over each other in the overlay, to get the equivalent effect when you blit the FBO, you need the FBO's alpha to be...75%. (That is, 1 - (1-.5) * (1-0.5), which is what would happen if you just drew two 50% alpha lines over your scene. But when you draw the two 50% lines, you'll get 50% alpha in the FBO (a blend of 50% with...50%.
This brings up the final issue: by pre-mixing the lines with each other before you blend them over the world, you are changing the draw order. Whereas you might have had:
blend(blend(blend(background color, model), first line), second line);
now you will have
blend(blend(first line, second line), blend(background color, model)).
In other words, pre-mixing the overlay lines into an FBO changes the order of blending and thus changes the final look in a way you may not want.
First, the simple way to get around this: don't use an FBO. I realize this is a "go redesign your app" kind of answer, but using an FBO is not the cheapest thing, and modern GL cards are very good at drawing lines. So one option would be: instead of blending lines into an FBO, write the line geometry into a vertex buffer object (VBO). Simply extend the VBO a little bit each time. If you are drawing less than, say, 40,000 lines at a time, this will almost certainly be as fast as what you were doing before.
(One tip if you go this route: use glBufferSubData to write the lines in, not glMapBuffer - mapping can be expensive and doesn't work on sub-ranges on many drivers...better to just let the driver copy the few new vertices.)
If that isn't an option (for example, if you draw a mix of shape types or use a mix of GL state, such that "remembering" what you did is a lot more complex than just accumulating vertices) then you may want to change how you draw into the VBO.
Basically what you'll need to do is enable separate blending; initialize the overlay to black + 0% alpha (0,0,0,0) and blend by "standard blending" the RGB but additive blending the alpha channels. This still isn't quite correct for the alpha channel but it's generally a lot closer - without this, over-drawn areas will be too transparent.
Then, when drawing the FBO, use "pre-multiplied" alpha, that is, (one, one-minus-src-alph).
Here's why that last step is needed: when you draw into the FBO, you have already multiplied every draw call by its alpha channel (if blending is on). Since you are drawing over black, a green (0,1,0,0.5) line is now dark green (0,0.5,0,0.5). If alpha is on and you blend normally again, the alpha is reapplied and you'l have 0,0.25,0,0.5.). By simply using the FBO color as is, you avoid the second alpha multiplication.
This is sometimes called "pre-multiplied" alpha because the alpha has already been multiplied into the RGB color. In this case you want it to get correct results, but in other cases, programmers use it for speed. (By pre-multiplying, it removes a mult per pixel when the blend op is performed.)
Hope that helps! Getting blending right when the layers are not mixed in order gets really tricky, and separate blend isn't available on old hardware, so simply drawing the lines every time may be the path of least misery.
Clear the FBO with transparent black (0, 0, 0, 0), draw into it back-to-front with
glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
and draw the FBO with
glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
to get the exact result.
As Ben Supnik wrote, the FBO contains colour already multiplied with the alpha channel, so instead of doing that again with GL_SRC_ALPHA, it is drawn with GL_ONE. The destination colour is attenuated normally with GL_ONE_MINUS_SRC_ALPHA.
The reason for blending the alpha channel in the buffer this way is different:
The formula to combine transparency is
resultTr = sTr * dTr
(I use s and d because of the parallel to OpenGL's source and destination, but as you can see the order doesn't matter.)
Written with opacities (alpha values) this becomes
1 - rA = (1 - sA) * (1 - dA)
<=> rA = 1 - (1 - sA) * (1 - dA)
= 1 - 1 + sA + dA - sA * dA
= sA + (1 - sA) * dA
which is the same as the blend function (source and destination factors) (GL_ONE, GL_ONE_MINUS_SRC_ALPHA) with the default blend equation GL_FUNC_ADD.
As an aside:
The above answers the specific problem from the question, but if you can easily choose the draw order it may in theory be better to draw premultiplied colour into the buffer front-to-back with
glBlendFunc(GL_ONE_MINUS_DST_ALPHA, GL_ONE);
and otherwise use the same method.
My reasoning behind this is that the graphics card may be able to skip shader execution for regions that are already solid. I haven't tested this though, so it may make no difference in practice.
As Ben Supnik said, the best way to do this is rendering the entire scene with separate blend functions for color and alpha. If you are using the classic non premultiplied blend function try glBlendFuncSeparateOES(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE) to render your scene to FBO. and glBlendFuncSeparateOES(GL_ONE, GL_ONE_MINUS_SRC_ALPHA) to render the FBO to screen.
It is not 100% accurate, but in most of the cases that will create no unexpected transparency.
Keep in mind that old Hardware and some mobile devices (mostly OpenGL ES 1.x devices, like the original iPhone and 3G) does not support separated blend functions. :(