Lab: Torus

How to 3D

Chapter 3: Meshes

Lab: Torus

In this chapter, you've been learning how to represent triangle meshes and generate algorithmic shapes like cones, cylinders, and spheres. Let's apply this knowledge by writing a renderer that generates a torus—a donut.

Form a group of no more than three people. Host, open your top-level repository directory in Visual Studio Code and run npm run dev to start up a web server. Then open the command palette via View / Command Palette and enter Live Share: Start Collaboration Session. Share the link with your group.

Torus

Your challenge is to render two spinnable models colored by their normals. Complete these steps:

Clone the transfit renderer to make a new renderer named torus. We use transfit because it deals with the viewport distortion and has no HTML inputs.
Change the center variable in resizeCanvas to [0, 0] and size to 1.
Make a very simple model in Blender. Make it small and centered at the origin. Export it as a glTF file.
Import the model and store its positions and normals in a vertex buffer.
Render the model at the origin colored by its normals.
Alter the vertex shader to apply only a rotation, not a scale or translate.
Use the radians to rotate the vertex around the x-axis instead of the z-axis. When you rotate a vertex around the x-axis, its x-coordinate stays constant. It's new yz-coordinates are computed from the old yz-coordinates using the sin and cosine functions.
Rotate the model when the up and down keys are pressed. Add a key listener in initialize with code like this:
window.addEventListener('keydown', event => {
  if (event.key === 'ArrowDown') {
    // ...
  }
});
window.addEventListener('keydown', event => {
  if (event.key === 'ArrowDown') {
    // ...
  }
});
Define a new prefab function named torus. Have it accept four parameters: the inner (or hole) radius, the outer radius, the longitude count, and the latitude count. Generate the torus geometry using a similar approach to how we generated a sphere: generate seed positions on one ring, and then rotate them. Unlike the sphere, wrap both latitude and longitude when forming triangles.
Generate the torus and compute its normals.
Render the torus as indexed triangles. Have it ring around the glTF model. Use the same shader.

Submission

To receive credit for your lab work, follow these steps:

Non-host, download the torus folder before the host closes the session.
Share a video of your spinning torus in a post in the #lab channel in Discord. No voiceover is necessary. Tag your group members with @.
Push your code to your individual GitHub repository that your instructor made for you.

Only labs submitted on time will be granted credit. Late labs or forgot-to-submits are not accepted because Monday at noon is when your instructor has time to grade.

← Reading glTF