Last active
August 19, 2023 19:27
-
-
Save machinaut/15fc8021db676abcda576b12555386e1 to your computer and use it in GitHub Desktop.
Subdivide Icosahedrons to make nice spheres
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
from itertools import combinations, chain | |
import numpy as np | |
from pyhull.convex_hull import ConvexHull | |
from stl import Mode | |
from stl.mesh import Mesh | |
def subdivide(shape): | |
''' Take a triangulated sphere and subdivide each face. ''' | |
# https://gamedevdaily.io/d7956b825db4 - Icosahedron section | |
hull = ConvexHull(shape) # Use this to get a list of vertices (faces). | |
radius = np.mean(np.linalg.norm(shape, axis=1)) # Estimate radius | |
edges = set(chain(*[combinations(v, 2) for v in hull.vertices])) | |
midpoints = np.mean(hull.points.take(list(edges), axis=0), axis=1) | |
newpoints = midpoints / np.linalg.norm(midpoints, axis=1)[:, None] * radius | |
return np.vstack((hull.points, newpoints)) # Add new points to old points | |
def points_to_mesh(points): | |
''' Given a set points, make a STL mesh of the convex hull. ''' | |
hull = ConvexHull(points) | |
mesh = Mesh(np.zeros(len(hull.vertices), dtype=Mesh.dtype)) | |
for i, vertex in enumerate(hull.vertices): | |
mesh.vectors[i] = hull.points[vertex][::-1] # Turn it inside out | |
return mesh | |
# Construct Icosahedron from 3 Golden Rectangles | |
phi = (1 + 5 ** .5) / 2 # Golden ratio | |
plane = np.dstack(np.meshgrid([1, -1], [phi, -phi], [0])).reshape(-1, 3) | |
icosahedron = np.vstack([np.roll(plane, i) for i in range(3)]) | |
# Save to STL files so we can view in GitHub | |
sphere = icosahedron | |
for i in range(4): | |
points_to_mesh(sphere).save('sphere{}.stl'.format(i), mode=Mode.ASCII) | |
sphere = subdivide(sphere) # Finer spheres by subdividing |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment