""" Generates the two figures used on the assignment 0 webpage. media/mesh_trefoil.png - a triangle mesh of a trefoil knot, flat shaded with its wireframe drawn on top media/turntable.gif - an icosphere rotating while its subdivision level cycles from 0 to 3 Everything is drawn by a small software rasteriser built on numpy + Pillow: orthographic camera, back-face culling, painter's algorithm for depth, and Lambertian shading from a single directional light. No mesh files or images are downloaded; the geometry is generated procedurally. python3 generate_media.py """ import numpy as np from PIL import Image, ImageDraw BG = (26, 30, 34) # matches the .viewport panel in style.css FACE = np.array([105, 143, 181], float) # steel blue EDGE = (150, 173, 196) LIGHT = np.array([0.45, 0.75, 0.5]) LIGHT /= np.linalg.norm(LIGHT) # ----------------------------------------------------------------- meshes def icosahedron(): t = (1.0 + 5.0 ** 0.5) / 2.0 v = np.array([ [-1, t, 0], [1, t, 0], [-1, -t, 0], [1, -t, 0], [0, -1, t], [0, 1, t], [0, -1, -t], [0, 1, -t], [t, 0, -1], [t, 0, 1], [-t, 0, -1], [-t, 0, 1], ], float) f = np.array([ [0, 11, 5], [0, 5, 1], [0, 1, 7], [0, 7, 10], [0, 10, 11], [1, 5, 9], [5, 11, 4], [11, 10, 2], [10, 7, 6], [7, 1, 8], [3, 9, 4], [3, 4, 2], [3, 2, 6], [3, 6, 8], [3, 8, 9], [4, 9, 5], [2, 4, 11], [6, 2, 10], [8, 6, 7], [9, 8, 1], ], int) return v / np.linalg.norm(v[0]), f def subdivide(v, f): """One loop of midpoint subdivision, projected back onto the sphere.""" v = list(v) cache, out = {}, [] def mid(a, b): key = (min(a, b), max(a, b)) if key not in cache: m = (v[a] + v[b]) / 2.0 v.append(m / np.linalg.norm(m)) cache[key] = len(v) - 1 return cache[key] for a, b, c in f: ab, bc, ca = mid(a, b), mid(b, c), mid(c, a) out += [[a, ab, ca], [b, bc, ab], [c, ca, bc], [ab, bc, ca]] return np.array(v), np.array(out, int) def icosphere(level): v, f = icosahedron() for _ in range(level): v, f = subdivide(v, f) return v, f def trefoil(n_path=140, n_ring=16, radius=0.32): """Tube swept along a trefoil knot, triangulated as a closed grid.""" t = np.linspace(0, 2 * np.pi, n_path, endpoint=False) curve = np.stack([ np.sin(t) + 2 * np.sin(2 * t), np.cos(t) - 2 * np.cos(2 * t), -np.sin(3 * t), ], axis=1) # Analytic first and second derivatives. Both are periodic in t, so the # Frenet frame below closes up exactly at t = 2*pi. Carrying a frame along # the curve numerically instead leaves a visible seam where it rejoins. d1 = np.stack([ np.cos(t) + 4 * np.cos(2 * t), -np.sin(t) + 4 * np.sin(2 * t), -3 * np.cos(3 * t), ], axis=1) d2 = np.stack([ -np.sin(t) - 8 * np.sin(2 * t), -np.cos(t) + 8 * np.cos(2 * t), 9 * np.sin(3 * t), ], axis=1) tan = d1 / np.linalg.norm(d1, axis=1, keepdims=True) normals = d2 - tan * np.sum(d2 * tan, axis=1, keepdims=True) normals /= np.linalg.norm(normals, axis=1, keepdims=True) binorm = np.cross(tan, normals) a = np.linspace(0, 2 * np.pi, n_ring, endpoint=False) ring = (np.cos(a)[:, None] * normals[:, None, :] + np.sin(a)[:, None] * binorm[:, None, :]) verts = (curve[:, None, :] + radius * ring).reshape(-1, 3) faces = [] for i in range(n_path): for j in range(n_ring): i2, j2 = (i + 1) % n_path, (j + 1) % n_ring p00, p01 = i * n_ring + j, i * n_ring + j2 p10, p11 = i2 * n_ring + j, i2 * n_ring + j2 # wound so the face normal points away from the centreline faces += [[p00, p11, p10], [p00, p01, p11]] verts -= verts.mean(0) verts /= np.abs(verts).max() return verts, np.array(faces, int) # --------------------------------------------------------------- rendering def rot(yaw, pitch): cy, sy = np.cos(yaw), np.sin(yaw) cx, sx = np.cos(pitch), np.sin(pitch) ry = np.array([[cy, 0, sy], [0, 1, 0], [-sy, 0, cy]]) rx = np.array([[1, 0, 0], [0, cx, -sx], [0, sx, cx]]) return rx @ ry def render(verts, faces, size, yaw, pitch=0.42, scale=0.40, wireframe=True, ss=3): """Draw one frame. Renders at ss times the size, then downsamples.""" w = size * ss img = Image.new("RGB", (w, w), BG) draw = ImageDraw.Draw(img) p = verts @ rot(yaw, pitch).T tri = p[faces] normal = np.cross(tri[:, 1] - tri[:, 0], tri[:, 2] - tri[:, 0]) ln = np.linalg.norm(normal, axis=1, keepdims=True) normal = normal / np.where(ln == 0, 1, ln) front = normal[:, 2] > 0 # back-face culling tri, normal = tri[front], normal[front] order = np.argsort(tri[:, :, 2].mean(1)) # painter's algorithm tri, normal = tri[order], normal[order] lam = np.clip(normal @ LIGHT, 0, 1) shade = 0.22 + 0.78 * lam ** 0.9 # ambient + diffuse sx = w * 0.5 + tri[:, :, 0] * w * scale sy = w * 0.5 - tri[:, :, 1] * w * scale for k in range(len(tri)): pts = [(sx[k, 0], sy[k, 0]), (sx[k, 1], sy[k, 1]), (sx[k, 2], sy[k, 2])] col = tuple(int(c) for c in np.clip(FACE * shade[k], 0, 255)) if wireframe: draw.polygon(pts, fill=col, outline=EDGE, width=max(1, ss // 2)) else: draw.polygon(pts, fill=col) return img.resize((size, size), Image.LANCZOS) # ----------------------------------------------------------------- outputs def make_still(path): v, f = trefoil() img = render(v, f, 620, yaw=0.9, pitch=0.5, scale=0.42, wireframe=True) img.save(path, optimize=True) return img.size def make_gif(path, frames=32, size=260): meshes = [icosphere(i) for i in range(4)] imgs = [] for i in range(frames): yaw = 2 * np.pi * i / frames level = int(i / frames * 4) % 4 # 0,1,2,3 across the loop v, f = meshes[level] img = render(v, f, size, yaw=yaw, pitch=0.38, scale=0.40, wireframe=True, ss=2) imgs.append(img.quantize(colors=32, method=Image.MEDIANCUT)) imgs[0].save(path, save_all=True, append_images=imgs[1:], duration=90, loop=0, optimize=True) if __name__ == "__main__": print("still :", make_still("media/mesh_trefoil.png")) make_gif("media/turntable.gif") print("done")