#include #include using namespace std; static void push_vertex(vector &verts, GLfloat x, GLfloat y, GLfloat z, Color c) { verts.push_back(x); verts.push_back(y); verts.push_back(z); verts.push_back(c.r); verts.push_back(c.g); verts.push_back(c.b); } Cylinder::Cylinder(float ep, float r, unsigned nb_fac, Color c) :ep(ep), r(r), nb_fac(nb_fac), c(c), angle(2*M_PI/nb_fac), face_size(nb_fac * 3), side_size((nb_fac+1) * 2) { vector verts((2*face_size + side_size) * 3 * 2); build_faces(verts); build_side(verts); vbo.create(); qDebug() << "verts.size() " << verts.size() << "nb_fac:" << nb_fac << "face_size:" << face_size << "side_size:" << side_size; vbo.bind(); vbo.allocate(verts.data(), verts.size() * sizeof (GLfloat)); vbo.release(); } void Cylinder::build_face(float z, vector &verts) { Color color(c); for (unsigned j = 0; j < nb_fac; j++) { push_vertex(verts, 0, 0, z, color); push_vertex(verts, cos(angle*j) * r, sin(angle*j) * r, z, color); push_vertex(verts, cos(angle*(j+1)) * r, sin(angle*(j+1)) * r, z, color); if (j % (nb_fac/4) == 0) { if (j % (nb_fac/2) == 0) { color.r *= .8; color.g *= .8; color.b *= .8; } else { color = c; } } } } void Cylinder::build_faces(vector &verts) { build_face(-ep/2, verts); build_face(ep/2, verts); } void Cylinder::build_side(vector &verts) { Color color(c.r*.7, c.g*.7, c.b*.7); for (unsigned i = 0; i < nb_fac+1; i++) { push_vertex(verts, cos(angle*i) * r, sin(angle*i) * r, -ep/2, color); push_vertex(verts, cos(angle*i) * r, sin(angle*i) * r, ep/2, color); } } void Cylinder::draw(QOpenGLFunctions &f, int pos, int col) { vbo.bind(); f.glEnableVertexAttribArray(pos); f.glVertexAttribPointer(pos, 3, GL_FLOAT, GL_FALSE, 3 * sizeof (GLfloat), nullptr); f.glEnableVertexAttribArray(col); f.glVertexAttribPointer(col, 3, GL_FLOAT, GL_FALSE, 3 * sizeof (GLfloat), (void *) (3 * sizeof (GLfloat))); f.glDrawArrays(GL_TRIANGLES, 0, face_size); f.glDrawArrays(GL_TRIANGLES, face_size, face_size); f.glDrawArrays(GL_QUAD_STRIP, face_size * 2, side_size); f.glDisableVertexAttribArray(pos); f.glDisableVertexAttribArray(col); vbo.release(); }