HTML and CSS Reference
In-Depth Information
Enhanced depth sorting
Depth sorting, or z-sorting, is something we discussed in Chapter 15, when you applied perspective to the
shapes. In that case, you sorted the array of objects (which had 3D properties) by their zpos property.
But now, you are not dealing with multiple objects. Whenever a particular polygon is drawn, it is drawn on
top of any that have been drawn earlier. Rather than swapping an object's depth, you need to determine
the order that each polygon is drawn. Specifically, you want to draw the ones that are farthest away first;
then you draw the rest, working your way forward, so that the closest polygons are drawn last, covering
anything they might be in front of.
So how do you do that? Well, you have all the polygons in an array called triangles . When you draw the
shape, you iterate through this array drawing each triangle from first element through the end. You must
sort this array so that the triangle that is farthest away is in element zero, and the one closest to the viewer
is in the last element of the array.
This is similar to what we did when sorting the array of objects, but here, the triangles are just a collection
of three Point3d objects. They don't have a single property that describes the overall depth of the triangle.
However, it is easy enough to create such a property. It turns out that the value that works best is the
minimum z value of the three points within a triangle. In other words, if a triangle had three points with
depths 200, 250, and 300, we should say this triangle is at a z position of 200.
We can use the Math.min function to determine the minimum z value of all three points. We do this within
a new getDepth method that we add to our Triangle class. Here's that function to add to the file
triangle.js :
Triangle.prototype.getDepth = function () {
return Math.min(this.pointA.z, this.pointB.z, this.pointC.z);
};
Now you can sort the array of triangle objects and know which to draw first and which to draw last. Again,
you want to sort it in descending order so that the one with the highest depth (farthest away) is first. You
calculate this in the drawFrame animation loop, before you draw any of the triangles. Here's the updated
section of our example in 02-extruded-a-depth.html :
function depth (a, b) {
return (b.getDepth() - a.getDepth());
}
(function drawFrame () {
window.requestAnimationFrame(drawFrame, canvas);
context.clearRect(0, 0, canvas.width, canvas.height);
angleX = (mouse.y - vpY) * 0.0005;
angleY = (mouse.x - vpX) * 0.0005;
points.forEach(move);
triangles.sort(depth);
triangles.forEach(draw);
}());
 
Search WWH ::




Custom Search