1) Composing

Let’s start with defining the simplest 3D shape, Cube. If we had a real solid object, we would not perceive most of what constitutes it, we would only see the surface. While creating a virtual version of it, the only approach that makes sense is to model only the surfaces.

The surface of a cube is composed of 6 square faces, attached to 8 vertices. Using just lists of numbers, it can be defined like this:

// list of 8 corner points as (x, y, z) triplets

points = [[1,1,1],[1,1,-1],…,[-1,-1,-1]] // list of 6 faces (4 indices each referring to the point list)

faces = [[0,1,3,2],[0,1,5,4],…,[4,5,7,6]]

Now we need to render the cube. The simplest approach for it is performing parallel projection after depth sort i.e. sort the faces by z-coordinates & render them on (x, y) plane by simply ignoring the z-coordinate values of the points.

For the cube we just defined, only one of the square faces will be visible after projection. To change the view, we need to alter the orientation of the cube. For this, we can perform two 2D rotations, one by angle `θ` around the z-axis & another by angle `ϕ`around the x-axis. To rotate a point around origin on a plane, we can use the following equations:

x' = x cos(α) - y sin(α)

y' = x sin(α) + y cos(α)

Here, x & y can be replaced by the coordinates that are affected by the rotation. Note that although you do not need to understand where these equations come from for using them, I would highly recommend studying a little about linear transformations to develop a feel for why it works.

We can alter the angles θ & ϕ according to cursor movements so that user can re-orient the object however s/he wants. We can also set up constant angular velocities for both of these parameters & update these angular distances in a game loop, which will result in nice rotating animations.

The embedded codepen implements this using HTML5 Canvas 2D API

As an exercise, the following problems can be played with before moving on to the next task: