Skip to content

Instantly share code, notes, and snippets.

@gyng
Last active April 29, 2022 11:05
Show Gist options
  • Select an option

  • Save gyng/8939105 to your computer and use it in GitHub Desktop.

Select an option

Save gyng/8939105 to your computer and use it in GitHub Desktop.
OpenGL torus with texture mapping and normals
/*
r = torus ring radius
c = torus tube radius
rSeg, cSeg = number of segments/detail
*/
void drawTorus(double, double, int, int, int);
void drawTorus(double r = 0.07, double c = 0.15,
int rSeg = 16, int cSeg = 8,
int texture = 0)
{
glFrontFace(GL_CW);
glBindTexture(GL_TEXTURE_2D, texture);
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
const double PI = 3.1415926535897932384626433832795;
const double TAU = 2 * PI;
for (int i = 0; i < rSeg; i++) {
glBegin(GL_QUAD_STRIP);
for (int j = 0; j <= cSeg; j++) {
for (int k = 0; k <= 1; k++) {
double s = (i + k) % rSeg + 0.5;
double t = j % (cSeg + 1);
double x = (c + r * cos(s * TAU / rSeg)) * cos(t * TAU / cSeg);
double y = (c + r * cos(s * TAU / rSeg)) * sin(t * TAU / cSeg);
double z = r * sin(s * TAU / rSeg);
double u = (i + k) / (float) rSeg;
double v = t / (float) cSeg;
glTexCoord2d(u, v);
glNormal3f(2 * x, 2 * y, 2 * z);
glVertex3d(2 * x, 2 * y, 2 * z);
}
}
glEnd();
}
glFrontFace(GL_CCW);
}
@duzenko
Copy link
Copy Markdown

duzenko commented Apr 23, 2022

I'm pretty sure normals are incorrect here

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment