Skip to content

Geometry

Primitives ​

Ready-made geometries for the common shapes: boxes, spheres, cylinders and cones, tori, capsules, lathed profiles, planes, a full-screen triangle and point clouds.

Each primitive is a Geometry whose constructor fills in the attributes. Pass the rendering context and an options object; every option has a default, so new Box(gl) is a unit cube centred on the origin.

js
import {
  Renderer,
  Camera,
  Obj,
  Mesh,
  Lights,
  LitProgram,
  Box,
  Sphere,
  Cylinder,
  Torus,
  Capsule,
  Lathe,
  Plane,
  Vec2
} from 'wtc-gl'

// The lit primitives in two rows, each turning on the spot
export default function (container) {
  const renderer = new Renderer({
    dpr: Math.min(devicePixelRatio, 2),
    alpha: true,
    antialias: true
  })
  const { gl } = renderer
  container.appendChild(gl.canvas)

  const camera = new Camera({ fov: 35 })
  const scene = new Obj()
  const lights = new Lights()

  // A bowl for the lathe: a quarter circle of [distance from the axis, height]
  const bowl = Array.from({ length: 9 }, (_, i) => {
    const a = (i / 8) * (Math.PI / 2)
    return [Math.sin(a) * 0.55, 0.2 - Math.cos(a) * 0.55]
  })

  const shapes = [
    new Box(gl, { width: 0.8, height: 0.8, depth: 0.8 }),
    new Sphere(gl, { radius: 0.55, widthSegments: 32 }),
    new Cylinder(gl, { radiusTop: 0.4, radiusBottom: 0.4, radialSegments: 32 }),
    new Cylinder(gl, { radiusTop: 0, radiusBottom: 0.5, radialSegments: 32 }),
    new Torus(gl, { radialSegments: 16, tubularSegments: 48 }),
    new Capsule(gl, { capSegments: 8, radialSegments: 24 }),
    new Lathe(gl, { points: bowl, segments: 32 }),
    new Plane(gl, { width: 0.9, height: 0.9 })
  ]

  const meshes = shapes.map((geometry, i) => {
    // A colour round the hue wheel
    const hue = (i / shapes.length) * Math.PI * 2
    const colour = [0, 2, 4].map((k) => 0.62 + 0.3 * Math.cos(hue - k))
    const program = new LitProgram(gl, {
      lights,
      colour,
      specular: 0.3,
      // The bowl and plane are open, so light their backs too
      doubleSided: i >= 6
    })
    const mesh = new Mesh(gl, { geometry, program })
    mesh.position.x = ((i % 4) - 1.5) * 1.6
    mesh.position.y = i < 4 ? 0.8 : -0.8
    mesh.setParent(scene)
    return mesh
  })

  return {
    frame(time) {
      meshes.forEach((mesh, i) => {
        mesh.rotation.x = 0.5
        mesh.rotation.y = time * 0.4 + i
        mesh.updateRotation()
      })
      renderer.render({ scene, camera })
    },
    resize(width, height) {
      renderer.dimensions = new Vec2(width, height)
      camera.perspective({ aspect: width / height })
      camera.position.z = Math.max(6, 10 / (width / height))
    },
    dispose() {
      for (const mesh of meshes) {
        mesh.geometry.remove()
        mesh.program.remove()
      }
      renderer.dispose()
      gl.canvas.remove()
    }
  }
}

What each one provides ​

These shapes have the same four attributes, so any of them works with LitProgram, a texture map or your own shader:

AttributeTypeWhat it is
positionvec3The vertex position
normalvec3The surface normal, unit long
uvvec2Texture coordinates, 0 to 1
indexThe triangles, Uint32Array when needed

That's Plane, Box, Sphere, Cylinder, Torus, Capsule and Lathe, and also Tube and Extrude, though Extrude's uvs are in world units. Triangle has a 2D position and a uv, with no index, and PointCloud only has position.

Every primitive also takes attributes, extra attributes to add, such as an instanced attribute. The generated ones replace any with the same name.

Plane ​

A flat rectangle in the xy plane, facing +z.

js
import { Plane } from 'wtc-gl'

const plane = new Plane(gl, {
  width: 2,
  height: 1,
  widthSegments: 20,
  heightSegments: 10
})
OptionDefaultWhat it does
width1Size along x
height1Size along y
widthSegments1Divisions along x
heightSegments1Divisions along y

More segments give a vertex shader more vertices to move, for waves or cloth. A plane is one-sided: give a LitProgram doubleSided: true, or your own Program cullFace: null, to see it from behind.

Box ​

A box with width, height and depth (each 1 by default) along x, y and z, and widthSegments, heightSegments and depthSegments (each 1). Each face is a separate grid with its own uvs from 0 to 1, so the edges are hard and a texture appears once on every face.

js
import { Box } from 'wtc-gl'

const slab = new Box(gl, { width: 2, height: 0.5, depth: 1 })

Sphere ​

A UV sphere with its poles on the y axis.

OptionDefaultWhat it does
radius0.5The radius
widthSegments16Divisions around the y axis
heightSegmentsMath.ceil(widthSegments * 0.5)Divisions from pole to pole
phiStart0Where to start around the y axis, in radians
phiLengthMath.PI * 2How far to sweep around the y axis
thetaStart0Where to start down from the top pole
thetaLengthMath.PIHow far to sweep down

Sweeping less than the whole way leaves the sphere open: a phiLength of Math.PI is half a sphere cut down the middle, and a thetaLength of Math.PI / 2 a dome.

js
import { Sphere } from 'wtc-gl'

const dome = new Sphere(gl, {
  radius: 1,
  widthSegments: 48,
  thetaLength: Math.PI / 2
})

Cylinder and cone ​

A cylinder along the y axis.

OptionDefaultWhat it does
radiusTop0.5Radius at the top (+y). 0 makes a cone
radiusBottom0.5Radius at the bottom (-y)
height1Length along y
radialSegments8Divisions around the axis
heightSegments1Divisions along the axis
openEndedfalseLeave out both caps
thetaStart0Where to start, in radians, from +z towards +x
thetaLengthMath.PI * 2How far to sweep

Set radiusTop: 0 for a cone. A cap with no radius is left out, so the cone has only its base.

js
import { Cylinder } from 'wtc-gl'

const cone = new Cylinder(gl, {
  radiusTop: 0,
  radiusBottom: 0.5,
  radialSegments: 32
})

The default eight segments make an octagonal prism; use 32 or more for a round one.

Torus ​

A ring lying in the xy plane, so it faces the camera by default.

OptionDefaultWhat it does
radius0.5From the centre to the middle of the tube
tube0.2The tube's radius
radialSegments8Divisions around the tube
tubularSegments24Divisions around the ring
arcMath.PI * 2How far round the ring to go, from +x towards +y

An arc under a full turn leaves the ring open, with the tube's ends uncapped.

Capsule ​

A cylinder with a hemisphere on each end, along the y axis.

OptionDefaultWhat it does
radius0.25The radius of the cylinder and the hemispheres
height1The whole length, tip to tip
capSegments4Divisions in each quarter circle of the caps
radialSegments8Divisions around the axis
heightSegments1Divisions along the straight part

height includes the caps, like a Cylinder's, so a capsule fits the same space. A height under twice the radius gives a sphere.

Lathe ​

A 2D profile spun around the y axis, for vases, bowls, bottles and anything else that's round. Each point is [r, y], its distance from the axis and its height, or a Vec2. List them from bottom to top so the faces point outwards.

js
import { Lathe } from 'wtc-gl'

const bowl = new Lathe(gl, {
  points: [
    [0, 0],
    [0.4, 0],
    [0.6, 0.3],
    [0.65, 0.6]
  ],
  segments: 32
})
OptionDefaultWhat it does
pointsrequiredThe profile, bottom to top; at least two points
segments12Divisions around the axis
phiStart0Where to start, in radians, from +z towards +x
phiLengthMath.PI * 2How far to sweep

A point at r = 0 closes the shape on the axis. Tube, Extrude and Lathe has more on profiles, smooth and hard edges, and Lathe.build.

Triangle ​

A single triangle that covers clip space, -1 to 1 on x and y, for full-screen fragment shaders. Its position is 2D and its uv runs from 0 to 1 across the screen. Draw it without a camera, and output the position as it is:

glsl
#version 300 es
in vec2 position;
in vec2 uv;
out vec2 v_uv;

void main() {
  v_uv = uv;
  gl_Position = vec4(position, 0.0, 1.0);
}

One triangle rather than a two-triangle quad avoids shading the pixels along the diagonal twice. FragmentShader uses it; see your first shader.

PointCloud ​

A set of points with only a position attribute, for drawing with gl.POINTS.

OptionDefaultWhat it does
particles128The number of points
dimensions3Numbers per point: the position attribute's size
fillFunctionrandom, 0 to 1(positions, dimensions) => void, fills the positions
js
import { PointCloud, Mesh } from 'wtc-gl'

const cloud = new PointCloud(gl, {
  particles: 5000,
  fillFunction: (positions) => {
    for (let i = 0; i < positions.length; i++) {
      positions[i] = Math.random() * 2 - 1
    }
  }
})
const points = new Mesh(gl, { geometry: cloud, program, mode: gl.POINTS })

The vertex shader sets each point's size with gl_PointSize. For points that move every frame on the GPU, see TransformFeedback.

Changing a primitive ​

A primitive's options are read once, when it's made. To change the size or the number of segments, make a new one, swap it onto the mesh and remove the old one:

js
const old = mesh.geometry
mesh.geometry = new Sphere(gl, { widthSegments: segments })
old.remove()

To bend or move the shape itself, use the CPU tools, such as applyMatrix and toNonIndexed, which work on primitives like any other geometry.

See also ​