When tinkering with a new graphics API or raytracing kernel, I often want to use procedurally-generated shapes to avoid worrying about loading art assets.
Hence my motivation for authoring a single-file, zero-dependency, C99 library that can generate simple shapes and perform basic operations on them. These operations include:
Applying affine transformations
Computing surface normals
Welding colocated vertices
The library provides a set of functions that populate fields of the following structure.
The two optional fields might be null, but every other field is guaranteed to have valid values. The PAR_SHAPES_T macro defaults to uint16_t, which can be overridden if desired.
When you’re done extracting the data you need from the mesh, be sure to free it:
Platonic Solids
The above scene was constructed like so:
Upon creation, platonic solids are welded and do not have normals or texture coordinates.
Since normals can only be per-vertex, you might need to “unweld” a mesh (i.e., dereference its index buffer) in order to perform lighting with facet normals. Here’s how to unweld the dodecahedron and populate its normals field:
Note that unwelding a mesh creates a rather silly index buffer: 0, 1, 2, etc. You can leave the index buffer untouched by passing false to the unweld function, although that makes the mesh invalid.
Parametric Surfaces
The shapes library can also generate various parametric surfaces. Unlike the platonic solids, these shapes are populated with smooth normals and texture coordinates, right out of the box.
The above scene was constructed like so:
All parametric generators take two tessellation levels: slices and stacks, which control the number of divisions across the UV domain.
If the ready-made surfaces are insufficient, clients can use a callback function to create a custom parametric surface:
Spheres
The shapes library provides two ways of generating spheres, and both have a fixed size and position: radius=1 and center=(0,0,0). Clients can easily scale / translate the result as needed.
In the above image, the left and center spheres are subdivided, and the right sphere is parametric.
Miscellaneous
The library also provides generator functions for various shapes beyond what was covered here; see the header file for more information.
Here are links to the library and the github repo that it lives in.