# XNA Transparency depending on drawing order?

I am drawing two 3D objects, both of them can fade from opaque to transparent independently, and they can intersect between them (so you cannot say when one of them is before the other one). Look at the image for a better understanding (one of the object is a terrain and the other one an area):

Now, if I apply transparency to both of them, and draw the terrain before the area, the terrain is not transparent respecting to the area, but the area is:

And finally, if I draw the area before the terrain, then the area is not transparent respecting of the terrain:

QUESTION: How can I make all the objects transparent to the rest of objects without depending on the drawing order?

• What settings do you use for DepthStencilState and BlendState in your render settings? This isn't a complete explanation, but it discusses the strategy of using them: blogs.msdn.com/b/shawnhar/archive/2010/04/02/… – Seth Battin May 15 '13 at 0:28

In general rendering intersecting transparent objects correctly is not easy to get working. Most games try to avoid the situation instead of making it work.

Here's one way to handle your specific case of just two objects.

1. Render the terrain into the depth buffer only (disable colour writes).
2. Disable depth writes, and re-enable colour writes.
3. Render the area with a depth test of greater. This draws the bit of it that's under the terrain.
4. Switch the depth test back to less than or equal to.
5. Render the terrain.
6. Render the area. This will draw the bit of it that's above the terrain.

That sort of approach doesn't easily generalize to more than two objects though. For that you'll need some sort of order independent transparency system, which are generally expensive on the GPU. For example: http://research.microsoft.com/apps/pubs/default.aspx?id=70307

You have to set the Graphics device settings and restore them when drawing in XNA. The drawing order is coincidence and I am guessing you have SpriteBatch somewhere in there when you swap the order causing the graphics device settings to get altered.