title: Depth Buffer not working
body: <p>In my XNA 3D game, for some reason, the depth buffer is off and ignored - even though I've done everything I can find to enable it (which admittedly isn't much, but it's supposed to be simple... not to mention default)</p>
  
  <p>Before the models are rendered:</p>
  
  <pre><code>global.GraphicsDevice.DepthStencilState = DepthStencilState.Default;
  </code></pre>
  
  <p>Somewhere earlier:</p>
  
  <pre><code>graphics.PreferredDepthStencilFormat = DepthFormat.Depth24Stencil8;
  graphics.ApplyChanges();
  </code></pre>
  
  <p>the models are rendered using a Vertex/Index list with device.DrawUserIndexedPrimitives and a BasicEffect.</p>
  
  <p>It comes out like this:</p>
  
  <p><img src="https://i.stack.imgur.com/yC3nA.png" alt="Rendered scene"></p>
  
  <p>The purple object is very far from the camera, and is drawn 1st.</p>
  
  <p>The gray object is very near the camera, and is drawn 2nd.</p>
  
  <p>The blue object is medium-distance to the camera and is drawn 3rd.</p>
  
  <p>The gray object is rendering <i>behind</i> the blue object - that is correct if you're going off the draw order, but I want it to organize by distance from the camera (Using the depth buffer), in which case the gray object should draw in front of the blue object.</p>
  
  <p>(And, no, just quickly sorting them manually, while it may provide a temporary solution, is not the way to fix this problem)</p>
  
  <ul>
  <li>Update: This is directly related to the fact that I'm rendering onto a RenderTarget2D instead of straight onto the screen. (If I render on-screen instead of to the rendertarget, the depth is calculated correctly. The rendertarget is needed for other parts of the program... or an equivalent system.)</li>
  </ul>