Skip to content

Instantly share code, notes, and snippets.

@KrabCode
Created April 3, 2020 12:59
Show Gist options
  • Select an option

  • Save KrabCode/6b77ba9701fb4bdb2befe55e76f5750d to your computer and use it in GitHub Desktop.

Select an option

Save KrabCode/6b77ba9701fb4bdb2befe55e76f5750d to your computer and use it in GitHub Desktop.
PShape createSphere(float r, int detail) {
PShape res = createShape();
float deg5 = TWO_PI / 5f;
float deg6 = acos((1f + sqrt(5f)) / (5f + sqrt(5f)));
PVector top = new PVector(0, r, 0);
PVector[] sides = new PVector[5];
for (int i = 0; i < 5; i++) {
sides[i] = new PVector(
r * sin(deg6) * cos(deg5 * i),
r * cos(deg6),
r * sin(deg6) * sin(deg5 * i));
}
res.disableStyle();
res.beginShape(TRIANGLES);
for (int i = 0; i < 5; i++) {
trig(res, r, top, sides[(i + 1) % 5], sides[i], detail);
trig(res, r, sides[i], flip(sides[(i + 3) % 5]), flip(sides[(i + 2) % 5]), detail);
trig(res, r, flip(sides[i]), sides[(i + 2) % 5], sides[(i + 3) % 5], detail);
trig(res, r, flip(top), flip(sides[i]), flip(sides[(i + 1) % 5]), detail);
}
res.endShape();
return res;
}
PVector flip(PVector v) {
return new PVector(-v.x, -v.y, -v.z);
}
void trig(PShape ps, float r, PVector p1, PVector p2, PVector p3, int detail) {
if (detail > 1) {
PVector mid12 = PVector.add(p1, p2);
mid12.setMag(r);
PVector mid23 = PVector.add(p2, p3);
mid23.setMag(r);
PVector mid13 = PVector.add(p1, p3);
mid13.setMag(r);
detail--;
trig(ps, r, p1, mid12, mid13, detail);
trig(ps, r, p2, mid23, mid12, detail);
trig(ps, r, p3, mid13, mid23, detail);
trig(ps, r, mid12, mid23, mid13, detail);
} else {
PVector dir = PVector.add(p1, p2);
dir.add(p3);
normal(ps, dir);
vertex(ps, p1);
vertex(ps, p2);
vertex(ps, p3);
}
}
void vertex(PShape ps, PVector v) {
ps.vertex(v.x, v.y, v.z);
}
void normal(PShape ps, PVector v) {
ps.normal(v.x, v.y, v.z);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment