How to rotate a cone around a line?

742 views Asked by At

I have a line in 3d:

void line() {
    glBegin(GL_LINES);
    glColor3f(1.0f, 0.0f, 0.0f);
    glVertex3f(-3.0f, 10.0f, 0);
    glVertex3f(7.0f, -10.0f, 0);
    glEnd();
}

And a cone:

void cone(GLdouble r, GLdouble h, int n) {

    GLdouble fi;
    double dphi = 2*M_PI / n;

    glBegin(GL_LINE_LOOP);
    for (fi = 0; fi < 2*M_PI; fi += dphi) {
        glVertex3f(0, 0, h);
        glVertex3f(r*cos(fi), r*sin(fi), 0);
        glVertex3f(r*cos(fi+dphi), r*sin(fi+dphi), 0);
    }
    glEnd();
}

Now, the line is supposed to lie on the cone's "mantle" (I'm not sure of the expression, but here's a picture):

enter image description here

This part I managed to do.

However, I don't know how to rotate the cone around the line in a way so it stays attached to the line? I'm not sure how to better describe it, but basically it should rotate around the line.

I tried using the following, but to no avail:

void rotate_around_line(GLdouble x0, GLdouble y0, GLdouble z0, GLdouble u1, GLdouble u2, GLdouble u3, GLdouble kut)
{
    double vek[3] = { u1 - x0, u2 - y0, u3 - z0 };

    double norm = sqrt(vek[0] * vek[0] + vek[1] * vek[1] + vek[2] * vek[2]);

    vek[0] /= norm;
    vek[1] /= norm;
    vek[2] /= norm;

    double d1 = sqrt(vek[1] * vek[1] + vek[2] * vek[2]);
    if (d1 == 0.0D)
    {
        glRotatef(kut, 1, 0, 0);
        return;
    }

    double d2 = 180*(asin(vek[1] / d1)) / M_PI;;
    double d3 = 180*(asin(vek[0])) / M_PI;

    glTranslatef(x0, y0, z0);
    glRotatef(-d2, 1, 0, 0);
    glRotatef(d3, 0, 1, 0);
    glRotatef(kut, 0, 0, 1);
    glRotatef(-d3, 0, 1, 0);
    glRotatef(d2, 1, 0, 0);
    glTranslatef(-x0, -y0, -z0);

}
1

There are 1 answers

3
ratchet freak On BEST ANSWER

you only need 1 rotate call

void rotate_around_line(GLdouble x0, GLdouble y0, GLdouble z0, GLdouble u1, GLdouble u2, GLdouble u3, GLdouble kut)
{
    double vek[3] = { u1 - x0, u2 - y0, u3 - z0 };


    glTranslatef(x0, y0, z0);
    glRotatef(-kut, vek[0], vek[1], vek[2]);
    glTranslatef(-x0, -y0, -z0);
}

the last 3 parameters of glRotatef form the axis around which you want to rotate.