title: Frustum plane calculus
body: <p>I'm writing a simple JavaScript 3D engine from scratch using Canvas and box like primitives (à la Minecraft) for the hell of it. I'm implementing as much optimizations as I can and so far I have back face culling and hidden face occlusion, but I can't figure out how to do frustum culling the optimal way.</p>
  
  <p>I've tried 2D culling, but that has one specific problem I can't solve: if a single vertex of a 4 point plane goes is behind the camera it is still drawn but completely distorted (x and y coordinates are reversed I think) - see image.</p>
  
  <p>I'm beginning to think this hasn't got a real solution without using much more complicated math and rendering sequences.</p>
  
  <p><img src="https://i.stack.imgur.com/2WzeO.png" alt="At first everything&#39;s ok"></p>
  
  <p><img src="https://i.stack.imgur.com/srUsb.jpg" alt="enter image description here"></p>
  
  <p>I've tried to limit the vertices x and y coordinates inside the 2D screen as long as at least one of the 4 vertices is still inside the screen (see below), but that completely distorts the square face (although I guess I can go with more fancy math and additional triangles).</p>
  
  <p><img src="https://i.stack.imgur.com/U3I3L.jpg" alt="enter image description here"></p>
  
  <p>I have some experience in OpenGL and it renders stuff completely differently so this isn't even a problem there.</p>
  
  <p>Do I have any chance of fixing it without pulling my hair?</p>
  
  <hr>
  
  <h2>Solution</h2>
  
  <p>The final solution was to test each of the 8 vertices against the near clipping plane in 3D <em>before</em> doing 2D projection and then screen clipping.</p>
  
  <p>This is the second clipping step, the first one is to test if the box is completely behind the clipping plane using bounding sphere of radius <code>sqrt(3/2)*boxSideLength</code>.</p>
  
  <p>Additional triangles (actually points in this case) was way too complicated and math intensive, this solution isn't perfect but quite pretty.</p>