title: How to correct for perspective when plotting a 3D triangle with texture?
body: <p>I have been working on a 3D rendering project as a technical excersise to see if I can replicate what a lot of the 3D frameworks do already: all the way from loading the model to plotting the triangles to a buffer ready to be drawn.</p>
  
  <p>Here is a sample of what I have managed to produce
  <img src="https://i.stack.imgur.com/Hcphk.png" alt="Render of program output"></p>
  
  <p>As you can see from the screenshot I have hit a snag plotting the textures on the surface. This <a href="http://en.wikipedia.org/wiki/Texture_mapping" rel="nofollow noreferrer">Wikipedia link</a> I have found explains about affine vs non-affine.
  Some other links similar to this one about <a href="http://www.lysator.liu.se/~mikaelk/doc/perspectivetexture/" rel="nofollow noreferrer">perspective correct texture mapping</a> go into it in more detail.</p>
  
  <p>I still do not understand how I can correct my UV coordinates when plotting a pixel.</p>
  
  <p><strong>How my engine currently works with a triangle:</strong>
  Convert 3D vertex data into 2D screen data
  call draw triangle passing depth between 0 &amp; 1 and texture details
  within draw triangle each vertical line is draw by interpolating along the 3 edges of the triangle</p>
  
  <p>I have made the changes in the links but I get divide by zero errors. If I ignore them nothing is drawn.</p>
  
  <p><strong>The question</strong></p>
  
  <p>How can I correct the UV co-ordinate selected at each pixel. Currently at each pixel I know the depth between 0.0 and 1.0, the apparent UV.</p>
  
  <p>Any help would be much appreciated. Thank you in advance.</p>
  
  <p>Tom :)</p>
  
  <p><strong>UPDATE:</strong></p>
  
  <p>Solution, use Andreas Brinck's answer. It works fine. Below is a screenshot of it now working.</p>
  
  <p><img src="https://i.stack.imgur.com/Wq1ut.png" alt="working correct perspective texture mapping"></p>