Reputation: 2886
I'm doing some experimenting with Silverlight 5 [beta] DrawingSurface
I have 2 images (PNG) with transparency in them, lets call them Im1 and Im2. The images are mapped to 2 simple polygons (6 vertices each)
When I place Im2 over Im1 I can see Im1 through the transparent parts of Im2. When I place Im1 over Im2 I can't see Im2 and I see a black area instead of a transparent.
I'm using AlphaBlend:
device.BlendState = BlendState.AlphaBlend;
And as you can guess, Im2 is drawn after Im1.
What am I doing wrong? Shader issue? Should I manually manage a Z-buffer?
Thank you for your help
Upvotes: 0
Views: 597
Reputation: 27245
Take a look at this answer here.
Basically you can't use the depth-buffer with transparency. The depth buffer has no concept of "blending" - a pixel in the depth-buffer will store the topmost value - even if the colour of the pixel being rendered is translucent or transparent. Anything "under" the value stored in the depth-buffer is skipped.
There are two solutions to this: You can use alpha testing so that completely transparent pixels are not written to the depth buffer (doesn't help with translucent pixels). Or you can sort transparent objects by depth, so that a closer polygon never has a chance to occlude a further-away one.
You can do alpha-testing in a pixel shader or by using the AlphaTestEffect
(if SL5 supports either of these?). Sorting polygons is something you will have to implement yourself (if you were using the full XNA, SpriteBatch
can do this for you - but I don't think SL5 has that class).
Alternately, if depth is irrelevant and you are rendering in a back-to-front order, simply disable the depth buffer by using DepthStencilState.None
.
Upvotes: 1
Reputation: 137198
You need to sort the transparent polygons by depth before drawing.
The code will be evaluating the colour on Im1
first (as it's the first one in the scene) and at that point there will be nothing behind it so "show through". Then when it evaluates the colour of Im2
it won't update Im1
.
Sorting the polygons first will ensure that when the colour is evaluated it will have the correct background.
I'm not familiar with XNA so I can't say whether there's something built in, but when we've had to do this in the past we had to do the sorting by ourselves.
Upvotes: 0