Question

I'm trying to create my own torus with smooth shading. However, the normal seems to be wrong. Here is my code.

GLfloat NoMat[]             =   {   0.0f,   0.0f,   0.0f,   1.0f    };
GLfloat MatAmbient[]        =   {   0.7f,   0.7f,   0.7f,   1.0f    };
GLfloat MatAmbientColor[]   =   {   0.21f,  0.13f,  0.05f,  1.0f    };
GLfloat MatDiffuse[]        =   {   0.71f,  0.43f,  0.18f,  1.0f    };
GLfloat Shine               =   100.0f; 
GLfloat NoShine             =   0.0f;

glMaterialfv(GL_FRONT, GL_AMBIENT, MatAmbientColor);
glMaterialfv(GL_FRONT, GL_DIFFUSE, MatDiffuse);
glEnable(GL_NORMALIZE);

glMaterialfv(GL_FRONT, GL_SPECULAR, MatAmbient);
glMaterialf(GL_FRONT, GL_SHININESS, Shine);

int i, j, k;
double s, t, x, y, z;

for (i = 0; i < nsides; i++) {
    glBegin(GL_QUAD_STRIP);
    for (j = 0; j <= rings + 1; j++) {
        for (k = 1; k >= 0; k--) { //for both negative and positive
            s = (i + k) % nsides + 0.5;
            t = j % rings;

            x = (totalRadius + centerRadius * cos(s*2*M_PI/nsides)) * cos(t*2*M_PI/rings);
            z = (totalRadius + centerRadius * cos(s*2*M_PI/nsides)) * sin(t*2*M_PI/rings);
            y = centerRadius * sin(s*2*M_PI/nsides);
            glVertex3f(x, y, z);
            glNormal3f(x, y, z);
        }
    }
    glEnd();
}

However, the lighting does not work properly, as it behaves like flat shading instead of smooth shading. I've did some googling, but apparantly it seems that I need to use differention. However, I'm not too sure how to do this. Anyone has any idea?

Était-ce utile?

La solution

You're using the vertex positions for normals? This will work only (and only) for a unit radius sphere!

You need to calculate the normal. That is

d{x,y,z}/ds × d{x,y,z}/dt

The nice thing about a torus is, that you can evaluate this easily on paper, giving you an exact formula, instead of working with a numerical approximation.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top