/*! Construct a new QuadPlane with \a size, subdivided \a level times. By default the plane is 100.0f x 100.0f, and is subdivided 3 times - that is into an 8 x 8 grid. It is centered on the origin, and lies in the z = 0 plane. */ QuadPlane::QuadPlane(QObject *parent, QSizeF size, int level) : QGLSceneNode(parent) { setObjectName(QLatin1String("QuadPlane")); if (level > 8) level = 8; if (level < 1) level = 1; int divisions = 1; for ( ; level--; divisions *= 2) {} // integer 2**n QSizeF div = size / float(divisions); QSizeF half = size / 2.0f; QGLBuilder builder; QGeometryData zip; QGeometryData zip2; for (int yy = 0; yy <= divisions; ++yy) { float y = half.height() - float(yy) * div.height(); float texY = float(yy) / divisions; for (int xx = 0; xx <= divisions; ++xx) { float x = half.width() - float(xx) * div.width(); float texX = float(xx) / divisions; zip.appendVertex(QVector3D(x, y, 0)); zip.appendTexCoord(QVector2D(1.0f - texX, 1.0f - texY)); } if (yy > 0) builder.addQuadsInterleaved(zip, zip2); zip2 = zip; zip2.detach(); zip.clear(); } QGLSceneNode *n = builder.finalizedSceneNode(); addNode(n); }
static bool qCalculateNormal(int i, int j, int k, QGeometryData &p, QVector3D *vec = 0) { QVector3D norm; QVector3D *n = &norm; if (vec) n = vec; bool nullTriangle = false; *n = QVector3D::crossProduct(p.vertexAt(j) - p.vertexAt(i), p.vertexAt(k) - p.vertexAt(j)); if (qFskIsNull(n->x())) n->setX(0.0f); if (qFskIsNull(n->y())) n->setY(0.0f); if (qFskIsNull(n->z())) n->setZ(0.0f); if (n->isNull()) { nullTriangle = true; } else { setNormals(i, j, k, p, *n); } return nullTriangle; }
/*! Add \a triangles - a series of one or more triangles - to this builder. The data is broken into groups of 3 vertices, each processed as a triangle. If \a triangles has less than 3 vertices this function exits without doing anything. Any vertices at the end of the list under a multiple of 3 are ignored. If no normals are supplied in \a triangles, a normal is calculated; as the cross-product \c{(b - a) x (c - a)}, for each group of 3 logical vertices \c{a(triangle, i), b(triangle, i+1), c(triangle, i+2)}. In the case of a degenerate triangle, where the cross-product is null, that triangle is skipped. Supplying normals suppresses this behaviour (and means any degenerate triangles will be added to the geometry). \b{Raw Triangle Mode} If \a triangles has indices specified then no processing of any kind is done and all the geometry is simply dumped in to the builder. This \b{raw triangle} mode is for advanced use, and it is assumed that the user knows what they are doing, in particular that the indices supplied are correct, and normals are supplied and correct. Normals are not calculated in raw triangle mode, and skipping of null triangles is likewise not performed. See the section on \l{raw-triangle-mode}{raw triangle mode} in the class documentation above. \sa addQuads(), operator>>() */ void QGLBuilder::addTriangles(const QGeometryData &triangles) { if (triangles.count() < 3) return; if (triangles.indexCount() > 0) { // raw triangle mode if (dptr->currentSection == 0) newSection(); dptr->currentSection->appendGeometry(triangles); dptr->currentSection->appendIndices(triangles.indices()); dptr->currentNode->setCount(dptr->currentNode->count() + triangles.indexCount()); } else { QGeometryData t = triangles; bool calcNormal = !t.hasField(QGL::Normal); if (calcNormal) { QVector3DArray nm(t.count()); t.appendNormalArray(nm); } bool skip = false; int k = 0; for (int i = 0; i < t.count() - 2; i += 3) { if (calcNormal) skip = qCalculateNormal(i, i+1, i+2, t); if (!skip) dptr->addTriangle(i, i+1, i+2, t, k); } dptr->currentNode->setCount(dptr->currentNode->count() + k); } }
/*! Sets the digit to be drawn. */ void ScoreDigit::setValue(int value) { if (m_Value == value) { return; } m_Value = value; QGeometryData geometryData = children()[0]->geometry(); geometryData.texCoord(0).setX(0.1f * m_Value); geometryData.texCoord(1).setX(0.1f * m_Value + 0.1f); geometryData.texCoord(2).setX(0.1f * m_Value + 0.1f); geometryData.texCoord(3).setX(0.1f * m_Value); }
/*! Add a series of quads by 'interleaving' \a top and \a bottom. This function behaves like quadStrip(), where the odd-numbered vertices in the input primitive are from \a top and the even-numbered vertices from \a bottom. It is trivial to do extrusions using this function: \code // create a series of quads for an extruded edge along -Y addQuadsInterleaved(topEdge, topEdge.translated(QVector3D(0, -1, 0)); \endcode N quad faces are generated where \c{N == min(top.count(), bottom.count() - 1}. If \a top or \a bottom has less than 2 elements, this functions does nothing. Each face is formed by the \c{i'th} and \c{(i + 1)'th} vertices of \a bottom, followed by the \c{(i + 1)'th} and \c{i'th} vertices of \a top. If the vertices in \a top and \a bottom are the perimeter vertices of two polygons then this function can be used to generate quads which form the sides of a \l{http://en.wikipedia.org/wiki/Prism_(geometry)}{prism} with the polygons as the prisms top and bottom end-faces. \image quad-extrude.png In the diagram above, the \a top is shown in orange, and the \a bottom in dark yellow. The first generated quad, (a, b, c, d) is generated in the order shown by the blue arrow. To create such a extruded prismatic solid, complete with top and bottom cap polygons, given just the top edge do this: \code QGeometryData top = buildTopEdge(); QGeometryData bottom = top.translated(QVector3D(0, 0, -1)); builder.addQuadsInterleaved(top, bottom); builder.addTriangulatedFace(top); builder.addTriangulatedFace(bottom.reversed()); \endcode The \a bottom QGeometryData must be \b{reversed} so that the correct winding for an outward facing polygon is obtained. */ void QGLBuilder::addQuadsInterleaved(const QGeometryData &top, const QGeometryData &bottom) { if (top.count() < 2 || bottom.count() < 2) return; QGeometryData zipped = bottom.interleavedWith(top); bool calcNormal = !zipped.hasField(QGL::Normal); if (calcNormal) { QVector3DArray nm(zipped.count()); zipped.appendNormalArray(nm); } bool skip = false; QVector3D norm; int k = 0; for (int i = 0; i < zipped.count() - 2; i += 2) { if (calcNormal) skip = qCalculateNormal(i, i+2, i+3, zipped, &norm); if (!skip) dptr->addTriangle(i, i+2, i+3, zipped, k); if (skip) skip = qCalculateNormal(i, i+3, i+1, zipped, &norm); if (!skip) { if (calcNormal) setNormals(i, i+3, i+1, zipped, norm); dptr->addTriangle(i, i+3, i+1, zipped, k); } } dptr->currentNode->setCount(dptr->currentNode->count() + k); }
void tst_QGLBuilder::addQuadBenchMarks(const QVector3DArray &data, int type) { int size = data.size(); if (type == Test_3) { QBENCHMARK { TestBuilder builder; builder.newSection(QGL::Smooth); builder.section()->setMapThreshold(3); for (int i = 0; (i+3) < size; i += 4) { QGeometryData op; op.appendVertex(data[i], data[i+1], data[i+2], data[i+3]); builder.addQuads(op); } builder.finalizedSceneNode(); } }
/*! Add \a quads - a series of one or more quads - to this builder. If \a quads has less than four vertices this function exits without doing anything. One normal per quad is calculated if \a quads does not have normals. For this reason quads should have all four vertices in the same plane. If the vertices do not lie in the same plane, use addTriangleStrip() to add two adjacent triangles instead. Since internally \l{geometry-building}{quads are stored as two triangles}, each quad is actually divided in half into two triangles. Degenerate triangles are skipped in the same way as addTriangles(). \sa addTriangles(), addTriangleStrip() */ void QGLBuilder::addQuads(const QGeometryData &quads) { if (quads.count() < 4) return; QGeometryData q = quads; bool calcNormal = !q.hasField(QGL::Normal); if (calcNormal) { QVector3DArray nm(q.count()); q.appendNormalArray(nm); } bool skip = false; int k = 0; QVector3D norm; for (int i = 0; i < q.count(); i += 4) { if (calcNormal) skip = qCalculateNormal(i, i+1, i+2, q, &norm); if (!skip) dptr->addTriangle(i, i+1, i+2, q, k); if (skip) skip = qCalculateNormal(i, i+2, i+3, q, &norm); if (!skip) { if (calcNormal) setNormals(i, i+2, i+3, q, norm); dptr->addTriangle(i, i+2, i+3, q, k); } } dptr->currentNode->setCount(dptr->currentNode->count() + k); }
/*! Adds to this section a set of connected triangles defined by \a strip. N triangular faces are generated, where \c{N == strip.count() - 2}. The triangles are generated from vertices 0, 1, & 2, then 2, 1 & 3, then 2, 3 & 4, and so on. In other words every second triangle has the first and second vertices switched, as a new triangle is generated from each successive set of three vertices. If \a strip has less than three vertices this function exits without doing anything. Normals are calculated as for addTriangle(), given the above ordering. This function is very similar to the OpenGL mode GL_TRIANGLE_STRIP. It generates triangles along a strip whose two sides are the even and odd vertices. \sa addTriangulatedFace() */ void QGLBuilder::addTriangleStrip(const QGeometryData &strip) { if (strip.count() < 3) return; QGeometryData s = strip; bool calcNormal = !s.hasField(QGL::Normal); if (calcNormal) { QVector3DArray nm(s.count()); s.appendNormalArray(nm); } bool skip = false; int k = 0; for (int i = 0; i < s.count() - 2; ++i) { if (i % 2) { if (calcNormal) skip = qCalculateNormal(i+1, i, i+2, s); if (!skip) dptr->addTriangle(i+1, i, i+2, s, k); } else { if (calcNormal) skip = qCalculateNormal(i, i+1, i+2, s); if (!skip) dptr->addTriangle(i, i+1, i+2, s, k); } } dptr->currentNode->setCount(dptr->currentNode->count() + k); }
/*! Adds to this section a set of quads defined by \a strip. If \a strip has less than four vertices this function exits without doing anything. The first quad is formed from the 0'th, 2'nd, 3'rd and 1'st vertices. The second quad is formed from the 2'nd, 4'th, 5'th and 3'rd vertices, and so on, as shown in this diagram: \image quads.png One normal per quad is calculated if \a strip does not have normals. For this reason quads should have all four vertices in the same plane. If the vertices do not lie in the same plane, use addTriangles() instead. Since internally \l{geometry-building}{quads are stored as two triangles}, each quad is actually divided in half into two triangles. Degenerate triangles are skipped in the same way as addTriangles(). \sa addQuads(), addTriangleStrip() */ void QGLBuilder::addQuadStrip(const QGeometryData &strip) { if (strip.count() < 4) return; QGeometryData s = strip; bool calcNormal = !s.hasField(QGL::Normal); if (calcNormal) { QVector3DArray nm(s.count()); s.appendNormalArray(nm); } bool skip = false; QVector3D norm; int k = 0; for (int i = 0; i < s.count() - 3; i += 2) { if (calcNormal) skip = qCalculateNormal(i, i+2, i+3, s, &norm); if (!skip) dptr->addTriangle(i, i+2, i+3, s, k); if (skip) skip = qCalculateNormal(i, i+3, i+1, s, &norm); if (!skip) { if (calcNormal) setNormals(i, i+3, i+1, s, norm); dptr->addTriangle(i, i+3, i+1, s, k); } } dptr->currentNode->setCount(dptr->currentNode->count() + k); }
void QGLBezierPatchesPrivate::subdivide(QGLBuilder *list) const { QGeometryData prim; int count = positions.size(); for (int posn = 0; (posn + 15) < count; posn += 16) { // Construct a QGLBezierPatch object from the next high-level patch. QGLBezierPatch patch; int vertex; for (int vertex = 0; vertex < 16; ++vertex) patch.points[vertex] = positions[posn + vertex]; QVector2D tex1, tex2; if (!textureCoords.isEmpty()) { tex1 = textureCoords[(posn / 16) * 2]; tex2 = textureCoords[(posn / 16) * 2 + 1]; } else { tex1 = QVector2D(0.0f, 0.0f); tex2 = QVector2D(1.0f, 1.0f); } qreal xtex = tex1.x(); qreal ytex = tex1.y(); qreal wtex = tex2.x() - xtex; qreal htex = tex2.y() - ytex; for (int corner = 0; corner < 4; ++corner) { vertex = posn + cornerOffsets[corner]; QVector3D n = patch.normal(cornerS[corner], cornerT[corner]); patch.indices[corner] = prim.count(); prim.appendVertex(patch.points[cornerOffsets[corner]]); prim.appendNormal(n); prim.appendTexCoord (QVector2D(xtex + wtex * cornerS[corner], ytex + htex * cornerT[corner])); } // Subdivide the patch and generate the final triangles. patch.recursiveSubDivide(&prim, subdivisionDepth, xtex, ytex, wtex, htex); } list->addTriangles(prim); }
ImageViewer::ImageViewer(int w, int h) { // the body QGLBuilder builder; builder.newSection(QGL::Faceted); builder.addPane(QSizeF(w, h)); body = builder.finalizedSceneNode(); body->setMaterial(new QGLMaterial()); body->setEffect(QGL::FlatReplaceTexture2D); // prev button QVector3DArray vertices; vertices.append(-w * 0.4, 0, 0.01); vertices.append(-w * 0.3, -h * 0.1, 0.01); vertices.append(-w * 0.3, h * 0.1, 0.01); QGeometryData triangle; triangle.appendVertexArray(vertices); QGLBuilder prevBuilder; prevBuilder.newSection(QGL::Faceted); prevBuilder.addTriangles(triangle); prevBtn = prevBuilder.finalizedSceneNode(); prevBtn->setEffect(QGL::FlatColor); // next button vertices.clear(); vertices.append(w * 0.4, 0, 0); vertices.append(w * 0.3, h * 0.1, 0.01); vertices.append(w * 0.3, -h * 0.1, 0.01); triangle.clear(); triangle.appendVertexArray(vertices); QGLBuilder nextBuilder; nextBuilder.newSection(QGL::Faceted); nextBuilder.addTriangles(triangle); nextBtn = nextBuilder.finalizedSceneNode(); nextBtn->setEffect(QGL::FlatColor); }
/*! Adds to this section a polygonal face made of triangular sub-faces, defined by \a face. The 0'th vertex is used for the center, while the subsequent vertices form the perimeter of the face, which must at minimum be a triangle. If \a face has less than four vertices this function exits without doing anything. This function provides functionality similar to the OpenGL mode GL_POLYGON, except it divides the face into sub-faces around a \b{central point}. The center and perimeter vertices must lie in the same plane (unlike triangle fan). If they do not normals will be incorrectly calculated. \image triangulated-face.png Here the sub-faces are shown divided by green lines. Note how this function handles some re-entrant (non-convex) polygons, whereas addTriangleFan will not support such polygons. If required, the center point can be calculated using the center() function of QGeometryData: \code QGeometryData face; face.appendVertex(perimeter.center()); // perimeter is a QGeometryData face.appendVertices(perimeter); builder.addTriangulatedFace(face); \endcode N sub-faces are generated where \c{N == face.count() - 2}. Each triangular sub-face consists of the center; followed by the \c{i'th} and \c{((i + 1) % N)'th} vertex. The last face generated then is \c{(center, face[N - 1], face[0]}, the closing face. Note that the closing face is automatically created, unlike addTriangleFan(). If no normals are supplied in the vertices of \a face, normals are calculated as per addTriangle(). One normal is calculated, since a face's vertices lie in the same plane. Degenerate triangles are skipped in the same way as addTriangles(). \sa addTriangleFan(), addTriangles() */ void QGLBuilder::addTriangulatedFace(const QGeometryData &face) { if (face.count() < 4) return; QGeometryData f; f.appendGeometry(face); int cnt = f.count(); bool calcNormal = !f.hasField(QGL::Normal); if (calcNormal) { QVector3DArray nm(cnt); f.appendNormalArray(nm); } bool skip = false; QVector3D norm; int k = 0; for (int i = 1; i < cnt; ++i) { int n = i + 1; if (n == cnt) n = 1; if (calcNormal) { skip = qCalculateNormal(0, i, n, f); if (norm.isNull() && !skip) { norm = f.normalAt(0); for (int i = 0; i < cnt; ++i) f.normal(i) = norm; } } if (!skip) dptr->addTriangle(0, i, n, f, k); } dptr->currentNode->setCount(dptr->currentNode->count() + k); }
/*! Adds to this section a set of connected triangles defined by \a fan. N triangular faces are generated, where \c{N == fan.count() - 2}. Each face contains the 0th vertex in \a fan, followed by the i'th and i+1'th vertex - where i takes on the values from 1 to \c{fan.count() - 1}. If \a fan has less than three vertices this function exits without doing anything. This function is similar to the OpenGL mode GL_TRIANGLE_FAN. It generates a number of triangles all sharing one common vertex, which is the 0'th vertex of the \a fan. Normals are calculated as for addTriangle(), given the above ordering. There is no requirement or assumption that all triangles lie in the same plane. Degenerate triangles are skipped in the same way as addTriangles(). \sa addTriangulatedFace() */ void QGLBuilder::addTriangleFan(const QGeometryData &fan) { if (fan.count() < 3) return; QGeometryData f = fan; bool calcNormal = !f.hasField(QGL::Normal); if (calcNormal) { QVector3DArray nm(f.count()); f.appendNormalArray(nm); } int k = 0; bool skip = false; for (int i = 1; i < f.count() - 1; ++i) { if (calcNormal) skip = qCalculateNormal(0, i, i+1, f); if (!skip) dptr->addTriangle(0, i, i+1, f, k); } dptr->currentNode->setCount(dptr->currentNode->count() + k); }
void tst_QGeometryData::interleaveWith() { QVector3D a(1.1, 1.2, 1.3); QVector3D b(2.1, 2.2, 2.3); QVector3D c(3.1, 3.2, 3.3); QVector3D d(4.1, 4.2, 4.3); QVector3D vx(0.7071, 0.7071, 0.0); QVector2D at(0.11, 0.12); QVector2D bt(0.21, 0.22); QVector2D ct(0.31, 0.32); QVector2D dt(0.41, 0.42); QVector2D tx(1.0, 1.0); QGeometryData data; data.appendVertex(a, b, c, d); data.appendTexCoord(at, bt, ct, dt); QGeometryData dat2; // count is the smaller of the two - nothing in this null case // also make sure the argument doesnt somehow change - its a const // so it shouldn't... dat2.interleaveWith(data); QCOMPARE(data.count(), 4); QCOMPARE(data.vertex(0), a); QCOMPARE(dat2.count(), 0); QCOMPARE(dat2.count(QGL::Position), 0); QCOMPARE(dat2.fields(), quint32(0)); // dat2 is smaller and has less fields dat2.appendVertex(a + vx, b + vx); dat2.interleaveWith(data); QCOMPARE(data.count(), 4); QCOMPARE(data.vertex(0), a); QCOMPARE(dat2.count(), 4); QCOMPARE(dat2.count(QGL::Position), 4); QCOMPARE(dat2.count(QGL::TextureCoord0), 0); QCOMPARE(dat2.fields(), QGL::fieldMask(QGL::Position)); QCOMPARE(dat2.vertex(0), a + vx); QCOMPARE(dat2.vertex(1), a); QCOMPARE(dat2.vertex(2), b + vx); QCOMPARE(dat2.vertex(3), b); // full zip with both sides have 4 verts & textures dat2.clear(); for (int i = 0; i < data.count(); ++i) { dat2.appendVertex(data.vertex(i) + vx); dat2.appendTexCoord(data.texCoord(i) + tx); } dat2.interleaveWith(data); QCOMPARE(dat2.count(), 8); QCOMPARE(dat2.count(QGL::Position), 8); QCOMPARE(dat2.count(QGL::TextureCoord0), 8); QCOMPARE(dat2.fields(), QGL::fieldMask(QGL::Position) | QGL::fieldMask(QGL::TextureCoord0)); QCOMPARE(dat2.vertex(0), a + vx); QCOMPARE(dat2.vertex(1), a); QCOMPARE(dat2.vertex(4), c + vx); QCOMPARE(dat2.vertex(7), d); QCOMPARE(dat2.texCoord(0), at + tx); QCOMPARE(dat2.texCoord(3), bt); QCOMPARE(dat2.texCoord(7), dt); }
void tst_QGeometryData::copy() { QVector3D a(1.1, 1.2, 1.3); QVector3D b(2.1, 2.2, 2.3); QVector3D c(3.1, 3.2, 3.3); QVector3D d(4.1, 4.2, 4.3); { QGeometryData data; QCOMPARE(data.count(), 0); QCOMPARE(data.fields(), (quint32)0); QGeometryData other; other.appendVertex(QVector3D()); QCOMPARE(other.count(), 1); QCOMPARE(other.fields(), QGL::fieldMask(QGL::Position)); other = aFunc(data); // assignment op - throw away previous d QCOMPARE(other.count(), 1); QCOMPARE(other.fields(), QGL::fieldMask(QGL::Position)); QVector3D res = other.vertices().at(0); QCOMPARE(res, avec); } { QGeometryData data; data.appendVertex(a, b, c, d); QGeometryData other; QCOMPARE(other.count(), 0); QCOMPARE(other.fields(), (quint32)0); other = aFunc(data); // assignment operator other.appendVertex(a); QCOMPARE(other.count(), 6); QCOMPARE(other.fields(), QGL::fieldMask(QGL::Position)); QCOMPARE(other.vertices().count(), 6); QCOMPARE(other.vertices().at(0), a); QCOMPARE(other.vertices().at(1), b); QCOMPARE(other.vertices().at(4), avec); QCOMPARE(other.vertices().at(5), a); } }
static QGeometryData aFunc(const QGeometryData& g) // not a copy but a ref { QGeometryData d = g; // copy constructor d.appendVertex(avec); return d; // assingment operator }
void tst_QGeometryData::appendVertexNormal() { QVector3D a(1.1, 1.2, 1.3); QVector3D b(2.1, 2.2, 2.3); QVector3D c(3.1, 3.2, 3.3); QVector3D d(4.1, 4.2, 4.3); QVector3D an(5.1, 5.2, 5.3); QVector3D bn(6.1, 6.2, 6.3); QVector3D cn(7.1, 7.2, 7.3); QVector3D dn(8.1, 8.2, 8.3); { QGeometryData data; data.appendVertex(a); data.appendNormal(an); QCOMPARE(data.count(), 1); QCOMPARE(data.fields(), QGL::fieldMask(QGL::Position) | QGL::fieldMask(QGL::Normal)); QCOMPARE(data.vertices().count(), 1); QCOMPARE(data.vertices().at(0), a); } { QGeometryData data; data.appendVertex(a, b); data.appendNormal(an, bn); QCOMPARE(data.count(), 2); QCOMPARE(data.fields(), QGL::fieldMask(QGL::Position) | QGL::fieldMask(QGL::Normal)); QCOMPARE(data.vertices().count(), 2); QCOMPARE(data.vertices().at(0), a); QCOMPARE(data.vertex(1), b); QCOMPARE(data.normals().count(), 2); QCOMPARE(data.normal(0), an); QCOMPARE(data.normals().at(1), bn); } { QGeometryData data; data.appendVertex(a, b, c); data.appendNormal(an, bn, cn); QCOMPARE(data.count(), 3); QCOMPARE(data.fields(), QGL::fieldMask(QGL::Position) | QGL::fieldMask(QGL::Normal)); QCOMPARE(data.vertices().count(), 3); QCOMPARE(data.vertices().at(0), a); QCOMPARE(data.vertices().at(1), b); QCOMPARE(data.vertices().at(2), c); QCOMPARE(data.normals().count(), 3); QCOMPARE(data.normal(0), an); QCOMPARE(data.normals().at(1), bn); QCOMPARE(data.normal(2), cn); } { QGeometryData data; data.appendVertex(a, b, c, d); data.appendNormal(an, bn, cn, dn); QCOMPARE(data.count(), 4); QCOMPARE(data.fields(), QGL::fieldMask(QGL::Position) | QGL::fieldMask(QGL::Normal)); QCOMPARE(data.vertices().count(), 4); QCOMPARE(data.vertices().at(0), a); QCOMPARE(data.vertices().at(1), b); QCOMPARE(data.vertices().at(2), c); QCOMPARE(data.vertices().at(3), d); QCOMPARE(data.normals().count(), 4); QCOMPARE(data.normals().at(0), an); QCOMPARE(data.normals().at(1), bn); QCOMPARE(data.normals().at(2), cn); QCOMPARE(data.normals().at(3), dn); } { QGeometryData data; data.appendVertex(a, b, c, d); data.appendNormal(an, bn, cn, dn); data.appendVertex(a, b, c, d); data.appendNormal(an, bn, cn, dn); data.appendVertex(a); data.appendNormal(an); QCOMPARE(data.count(), 9); QCOMPARE(data.fields(), QGL::fieldMask(QGL::Position) | QGL::fieldMask(QGL::Normal)); QCOMPARE(data.vertices().count(), 9); QCOMPARE(data.vertices().at(0), a); QCOMPARE(data.vertices().at(1), b); QCOMPARE(data.vertices().at(5), b); QCOMPARE(data.vertices().at(8), a); QCOMPARE(data.normals().count(), 9); QCOMPARE(data.normals().at(0), an); QCOMPARE(data.normals().at(1), bn); QCOMPARE(data.normals().at(5), bn); QCOMPARE(data.normals().at(8), an); } }
QGeometryData MgGeometriesData::sphere(qreal radius,int divisions) { QGeometryData geometry; // Determine the number of slices and stacks to generate. static int const slicesAndStacks[] = { 4, 4, 8, 4, 8, 8, 16, 8, 16, 16, 32, 16, 32, 32, 64, 32, 64, 64, 128, 64, 128, 128 }; if (divisions < 1) divisions = 1; else if (divisions > 10) divisions = 10; int stacks = slicesAndStacks[divisions * 2 - 1]; int slices = slicesAndStacks[divisions * 2 - 2]; // Precompute sin/cos values for the slices and stacks. const int maxSlices = 128 + 1; const int maxStacks = 128 + 1; qreal sliceSin[maxSlices]; qreal sliceCos[maxSlices]; qreal stackSin[maxStacks]; qreal stackCos[maxStacks]; for (int slice = 0; slice < slices; ++slice) { qreal angle = 2 * M_PI * slice / slices; sliceSin[slice] = qFastSin(angle); sliceCos[slice] = qFastCos(angle); } sliceSin[slices] = sliceSin[0]; // Join first and last slice. sliceCos[slices] = sliceCos[0]; for (int stack = 0; stack <= stacks; ++stack) { qreal angle = M_PI * stack / stacks; stackSin[stack] = qFastSin(angle); stackCos[stack] = qFastCos(angle); } stackSin[0] = 0.0f; // Come to a point at the poles. stackSin[stacks] = 0.0f; // Create the stacks. for (int stack = 0; stack < stacks; ++stack) { QGeometryData prim; qreal z = radius * stackCos[stack]; qreal nextz = radius * stackCos[stack + 1]; qreal s = stackSin[stack]; qreal nexts = stackSin[stack + 1]; qreal c = stackCos[stack]; qreal nextc = stackCos[stack + 1]; qreal r = radius * s; qreal nextr = radius * nexts; for (int slice = 0; slice <= slices; ++slice) { prim.appendVertex (QVector3D(nextr * sliceSin[slice], nextr * sliceCos[slice], nextz)); prim.appendNormal (QVector3D(sliceSin[slice] * nexts, sliceCos[slice] * nexts, nextc)); prim.appendVertex (QVector3D(r * sliceSin[slice], r * sliceCos[slice], z)); prim.appendNormal (QVector3D(sliceSin[slice] * s, sliceCos[slice] * s, c)); } geometry.appendGeometry(prim); } return geometry; }
QT_BEGIN_NAMESPACE /*! \class QGLCylinder \brief The QGLCylinder class represents the geometry of a simple cylinder/cone in 3D space. \since 4.8 \ingroup qt3d \ingroup qt3d::geometry The following example creates a cone with a top diameter of 1 unit, a bottom diameter of 2 units in diameter and height of 3 units. It then draws it at (10, 25, 0) in a QGLPainter: \code QGLBuilder builder; builder << QGLCylinder(1.0,2.0,3.0); QGLSceneNode *node = builder.finalizedSceneNode(); painter.translate(10, 25, 0); node->draw(&painter); \endcode Note that the bottom circle of the cylinder will always be centred at (0,0,0) unless otherwise transformed after cylinder creation. The QGLCylinder class specifies positions, normals and 2D texture co-ordinates for all of the vertices that make up the cylinder. The texture co-ordinates are fixed at construction time. This is because constructing the cylinder can involve generating additional vertices which need to interpolate the texture co-ordinates of their neighboring vertices. The QGLCylinder is divided into slices and layers. The slices value indicate number of triangular sections into which the top and bottom circles of the cylinder are broken into. Consequently it also sets the number of facets which run the length of the cylinder. More slices results in a smoother circumference. The layers value indicates the number of longitudinal sections the cylinder is broken into. Fewer layers means that the side facets of the cylinder will be made up of fewer, very long, triangles, while a higher number of layers will produce many and smaller triangles. Often it is desirable to avoid large triangles as they may cause inefficiencies in texturing/lighting on certain platforms. The end-caps and sides of the cylinder are independent sections of the scene-graph, and so may be textured separately. Textures are wrapped around the sides of thecylinder in such a way that the texture may distort across the x axis if the top and bottom diameters of the cylinder differ (ie. the cylinder forms a truncated cone). Textures begin and end at the centre points of the top and bottom end-caps of the cylinder. This wrapping means that textures on either end-cap may be distorted. Texture coordinates are assigned as shown below. \image cylinder-texture-coords.png It is worth noting that the cylinder class can, in fact, be used to generate any regular solid polygonal prism. A rectangular prism can be created, for example, by creating a 4 sided cylinder. Likewise a hexagonal prism is simply a 6 sided cylinder. With this knowledge, and an understanding of the texture coordinate mapping, it is possible to make custom textures which will be usable with these three dimensional objects. \sa QGLBuilder */ /*! \fn QGLCylinder::QGLCylinder(float diameterTop, float diameterBase , float height, int slices, int layers, bool top, bool base) Constructs the geometry for a cylinder with top of diameter \a diameterTop, a base of diameter \a diameterBase, and a height of \a height. The resultant mesh will be divided around the vertical axis of the cylinder into \a slices individual wedges, and shall be formed of \a layers stacked to form the cylinder. If the values for \a top or \a base are true, then the cylinder will be created with solid endcaps. Otherwise, it shall form a hollow pipe. units on a side. */ /*! \fn float QGLCylinder::diameterTop() const Returns the diameter of the top of the cylinder. The default value is 1. \sa setDiameterTop() */ /*! \fn void QGLCylinder::setDiameterTop(float diameter) Sets the diameter of the top of this cylinder to \a diameter. \sa diameterTop() */ /*! \fn float QGLCylinder::diameterBottom() const Returns the diameter of the bottom of the cylinder. The default value is 1. \sa setDiameterBottom() */ /*! \fn void QGLCylinder::setDiameterBottom(float diameter) Sets the diameter of the bottom of this cylinder to \a diameter. \sa diameterBottom() */ /*! \fn float QGLCylinder::height() const Returns the height of the cylinder. The default value is 1.0 \sa setDiameterBottom() */ /*! \fn void QGLCylinder::setHeight(float height) Sets the height of this cylinder to \a height. \sa diameterBottom() */ /*! \fn int QGLCylinder::slices() const Returns the number of triangular slices the cylinder is divided into around its polar axis. The default is 6. \sa setSlices() */ /*! \fn int QGLCylinder::setSlices(int slices) Sets the number of triangular \a slices the cylinder is divided into around its polar axis. \sa slices() */ /*! \fn int QGLCylinder::layers() const Returns the number of cylindrical layers the cylinder is divided into along its height. The default is 3. \sa setLayers() */ /*! \fn int QGLCylinder::setLayers(int layers) Sets the number of stacked \a layers the cylinder is divided into along its height. \sa layers() */ /*! \fn bool QGLCylinder::topEnabled() const Returns true if the top of the cyclinder will be created when building the mesh. The default is true. \sa setTopEnabled() */ /*! \fn void QGLCylinder::setTopEnabled(bool top) Set whether the top end-cap of the cylinder will be created when building the mesh. If \a top is true, the end-cap will be created. \sa topEnabled() */ /*! \fn bool QGLCylinder::baseEnabled() const Returns true if the base of the cyclinder will be created when building the mesh. The default is true. \sa setBaseEnabled() */ /*! \fn void QGLCylinder::setBaseEnabled(bool base) Set whether the base end-cap of the cylinder will be created when building the mesh. If \a base is true, the end-cap will be created. \sa baseEnabled() */ /*! \relates QGLCylinder Builds the geometry for \a cylinder within the specified geometry \a builder. */ QGLBuilder& operator<<(QGLBuilder& builder, const QGLCylinder& cylinder) { int nCaps = (cylinder.topEnabled()?1:0) + (cylinder.baseEnabled()?1:0); Q_ASSERT(cylinder.layers() >= 1 + nCaps); float numSlices = float(cylinder.slices()); float numLayers = float(cylinder.layers() - nCaps); // minus top and base caps float topRadius = cylinder.diameterTop() / 2.0f; float bottomRadius = cylinder.diameterBottom() / 2.0f; float angle = 0.0f; float angleIncrement = (2.0f * M_PI) / numSlices; float radius = topRadius; float radiusIncrement = float(bottomRadius-topRadius) / numLayers; float height = float(cylinder.height()); float heightDecrement = height / numLayers; height *= 0.5f; float textureHeight = 1.0f; float textureDecrement = 1.0f / numLayers; QGeometryData oldLayer; // layer 0: Top cap { QGeometryData newLayer; //Generate a circle of vertices for this layer. for (int i=0; i<cylinder.slices(); i++) { newLayer.appendVertex(QVector3D(radius * cosf(angle), radius * sinf(angle), height)); angle+=angleIncrement; } angle = 0.0f; QVector3D center = newLayer.center(); // Generate texture coordinates (including an extra seam vertex for textures). newLayer.appendVertex(newLayer.vertex(0)); newLayer.generateTextureCoordinates(); for (int i = 0; i < newLayer.count(); ++i) newLayer.texCoord(i).setY(textureHeight); if (cylinder.topEnabled()) { QGeometryData top; builder.newSection(); builder.currentNode()->setObjectName(QStringLiteral("Cylinder Top")); top.appendVertex(center); top.appendVertexArray(newLayer.vertices()); //Generate a circle of texture vertices for this layer. top.appendTexCoord(QVector2D(0.5f, 0.5f)); for (int i=1; i<top.count(); i++) { top.appendTexCoord(QVector2D(0.5f * cosf(angle) + 0.5f, 0.5f * sinf(angle) + 0.5f)); angle+=angleIncrement; } angle = 0; builder.addTriangulatedFace(top); } oldLayer.clear(); oldLayer.appendGeometry(newLayer); } // intermediate layers for (int layerCount=0; layerCount<(cylinder.layers()-nCaps); ++layerCount) { radius+=radiusIncrement; height-=heightDecrement; textureHeight-=textureDecrement; QGeometryData newLayer; //Generate a circle of vertices for this layer. for (int i=0; i<cylinder.slices(); ++i) { newLayer.appendVertex(QVector3D(radius * cosf(angle), radius * sinf(angle), height)); angle+=angleIncrement; } angle = 0.0f; // Generate texture coordinates (including an extra seam vertex for textures). newLayer.appendVertex(newLayer.vertex(0)); newLayer.generateTextureCoordinates(); for (int i = 0; i < newLayer.count(); ++i) newLayer.texCoord(i).setY(textureHeight); if (layerCount==0) { builder.newSection(); builder.currentNode()->setObjectName(QStringLiteral("Cylinder Sides")); } builder.addQuadsInterleaved(oldLayer, newLayer); oldLayer.clear(); oldLayer.appendGeometry(newLayer); } // last layer: Base cap if (cylinder.baseEnabled()) { builder.newSection(); builder.currentNode()->setObjectName(QStringLiteral("Cylinder Base")); QGeometryData base; { QVector3DArray vvv = oldLayer.vertices(); for (int i=0; i<vvv.size()-1; ++i) base.appendVertex(vvv.at(i)); QVector3D center = base.center(); base.appendVertex(vvv.at(0)); base.appendVertex(center); } //Generate a circle of texture vertices for this layer. for (int i=1; i<base.count(); i++) { base.appendTexCoord(QVector2D(0.5f * cosf(angle) + 0.5f, 0.5f * sinf(angle) + 0.5f)); angle+=angleIncrement; } base.appendTexCoord(QVector2D(0.5f, 0.5f)); angle = 0.0f; //we need to reverse the above to draw it properly - windings! builder.addTriangulatedFace(base.reversed()); } return builder; }
void tst_QGLRender::sequence() { QSKIP("QWidget: Cannot create a QWidget when no GUI is being used"); QSharedPointer<QGLMaterialCollection> palette(new QGLMaterialCollection()); // create a yellow lit material QGLMaterial *mat = new QGLMaterial; mat->setAmbientColor(Qt::yellow); int ix0 = palette->addMaterial(mat); // create a blue lit material mat = new QGLMaterial; mat->setAmbientColor(Qt::blue); int ix1 = palette->addMaterial(mat); // create a grey textured material int tx0; { QImage uv(1024, 1024, QImage::Format_ARGB32); uv.fill(qRgba(196, 196, 196, 196)); mat = new QGLMaterial; mat->setAmbientColor(Qt::gray); QGLTexture2D *tex = new QGLTexture2D; tex->setImage(uv); mat->setTexture(tex); tx0 = palette->addMaterial(mat); } QGLSceneNode *scene = new QGLSceneNode; scene->setPalette(palette); QGLSceneNode *node = 0; QGLSceneNode *prim; { QGLBuilder builder(palette); QVector3D a(-1.0f, -1.0f, 0.0f); QVector3D b(1.0f, -1.0f, 0.0f); QVector3D c(1.0f, 1.0f, 0.0f); QGeometryData p; p.appendVertex(a, b, c); p.generateTextureCoordinates(); builder.addTriangles(p); prim = builder.currentNode(); prim->setMaterialIndex(ix0); builder.newSection(); QVector3D d(-1.2f, -1.2f, 0.0f); QVector3D e(1.2f, -1.2f, 0.0f); QVector3D f(1.2f, 1.2f, 0.0f); QVector3D g(-1.2f, 1.2f, 0.0f); QGeometryData q; q.appendVertex(d, e, f, g); q.generateTextureCoordinates(); builder.addQuads(q); prim = builder.currentNode(); prim->setMaterialIndex(ix1); node = builder.finalizedSceneNode(); } scene->addNode(node); QGLSceneNode *cl = prim->clone(scene); cl->setMaterialIndex(tx0); cl->setEffect(QGL::LitDecalTexture2D); TestView widget(scene); if (!widget.context()->isValid()) QSKIP("GL Implementation not valid"); TestPainter *ptr = new TestPainter(&widget); widget.paintGL(ptr); QList<int> starts = ptr->starts(); QList<int> counts = ptr->counts(); QCOMPARE(starts.at(0), 0); QCOMPARE(counts.at(0), 3); QCOMPARE(starts.at(1), 3); QCOMPARE(counts.at(1), 6); }
/*! \relates QGLSphere Builds the geometry for \a sphere within the specified display \a list. */ QGLBuilder& operator<<(QGLBuilder& list, const QGLSphere& sphere) { qreal scale = sphere.diameter(); int divisions = qMax(sphere.subdivisionDepth() - 1, 0); // define a 0 division sphere as 4 points around the equator, 4 points around the bisection at poles. // each division doubles the number of points. // since each pass of each loop does half a sphere, we multiply by 2 rather than 4. int total = 2*(1 << divisions); //list.begin(QGL::TRIANGLE); //QGeometryData *prim = list.currentPrimitive(); QGeometryData prim; const QVector3D initialVector(0, 0, 1); const QVector3D zAxis(0, 0, 1); const QVector3D yAxis(0, 1, 0); for(int vindex = 0; vindex < total; vindex++) { qreal vFrom = qreal(vindex) / qreal(total); qreal vTo = qreal(vindex+1) / qreal(total); QQuaternion ryFrom = QQuaternion::fromAxisAndAngle(yAxis, 180.0f * vFrom); QQuaternion ryTo = QQuaternion::fromAxisAndAngle(yAxis, 180.0f * vTo); for (int uindex = 0; uindex < 2*total; uindex++) { qreal uFrom = qreal(uindex) / qreal(total); qreal uTo = qreal(uindex+1) / qreal(total); QQuaternion rzFrom = QQuaternion::fromAxisAndAngle(zAxis, 180.0f * uFrom); QQuaternion rzTo = QQuaternion::fromAxisAndAngle(zAxis, 180.0f * uTo); // four points QVector3D na, nb, nc, nd; QVector3D va, vb, vc, vd; na = ryFrom.rotatedVector(initialVector); na = rzFrom.rotatedVector(na); nb = ryTo.rotatedVector(initialVector); nb = rzFrom.rotatedVector(nb); nc = ryTo.rotatedVector(initialVector); nc = rzTo.rotatedVector(nc); nd = ryFrom.rotatedVector(initialVector); nd = rzTo.rotatedVector(nd); QVector2D ta(uFrom/2.0f, 1.0-vFrom); QVector2D tb(uFrom/2.0f, 1.0-vTo); QVector2D tc(uTo/2.0f, 1.0-vTo); QVector2D td(uTo/2.0f, 1.0-vFrom); va = na * scale / 2.0f; vb = nb * scale / 2.0f; vc = nc * scale / 2.0f; vd = nd * scale / 2.0f; prim.appendVertex(va, vb, vc); prim.appendNormal(na, nb, nc); prim.appendTexCoord(ta, tb, tc); prim.appendVertex(va, vc, vd); prim.appendNormal(na, nc, nd); prim.appendTexCoord(ta, tc, td); } } list.addTriangles(prim); return list; }
/*! \relates QGLIcoSphere Builds the geometry for \a sphere within the specified display \a list. */ QGLBuilder& operator<<(QGLBuilder& list, const QGLIcoSphere& sphere) { qreal scale = sphere.diameter(); int depth = sphere.subdivisionDepth(); qreal tiny= 1.0f; qreal large = phi*tiny; float ico[12][3] = { { 0.0f, tiny, large }, // A - 0 { 0.0f, tiny, -large }, // B - 1 { 0.0f, -tiny, large }, // C - 2 { 0.0f, -tiny, -large }, // D - 3 { tiny, large, 0.0f }, // E - 4 { tiny, -large, 0.0f }, // F - 5 { -tiny, large, 0.0f }, // G - 6 { -tiny, -large, 0.0f }, // H - 7 { large, 0.0f, tiny}, // I - 8 { large, 0.0f, -tiny}, // J - 9 { -large, 0.0f, tiny}, // K - 10 { -large, 0.0f, -tiny} // L - 11 }; int face[20][3] = { { 4, 0, 8 }, // E-A-I { 6, 0, 4 }, // G-A-E { 6, 10, 0 }, // G-K-A { 11, 10, 6 }, // L-K-G { 0, 2, 8 }, // A-C-I { 10, 2, 0 }, // K-C-A { 10, 7, 2 }, // K-H-C { 11, 7, 10 }, // L-H-K { 2, 5, 8 }, // C-F-I { 7, 5, 2 }, // H-F-C { 7, 3, 5 }, // H-D-F { 11, 3, 7 }, // L-D-H { 5, 9, 8 }, // F-J-I { 3, 9, 5 }, // D-J-F { 3, 1, 9 }, // D-B-J { 11, 1, 3 }, // L-B-D { 9, 4, 8 }, // J-E-I { 1, 4, 9 }, // B-E-J { 1, 6, 4 }, // B-G-E { 11, 6, 1 } // L-G-B }; const float u0 = 0.0f; const float u1 = 0.173205081f; const float u2 = 0.346410162f; const float u3 = 0.519615242f; const float u4 = 0.692820323f; const float u5 = 0.866025402f; const float v9 = 0.0f; const float v8 = 0.111111111f; const float v7 = 0.222222222f; const float v6 = 0.333333333f; const float v5 = 0.444444444f; const float v4 = 0.555555555f; const float v3 = 0.666666666f; const float v2 = 0.777777777f; const float v1 = 0.888888888f; const float v0 = 1.0f; float tex[20][3][2] = { { { u0, v1 }, { u1, v2 }, { u1, v0 } }, // E-A-I { { u0, v3 }, { u1, v2 }, { u0, v1 } }, // G-A-E { { u0, v3 }, { u1, v4 }, { u1, v2 } }, // G-K-A { { u0, v5 }, { u1, v4 }, { u0, v3 } }, // L-K-G { { u1, v2 }, { u2, v3 }, { u2, v1 } }, // A-C-I { { u1, v4 }, { u2, v3 }, { u1, v2 } }, // K-C-A { { u1, v4 }, { u2, v5 }, { u2, v3 } }, // K-H-C { { u1, v6 }, { u2, v5 }, { u1, v4 } }, // L-H-K { { u2, v3 }, { u3, v4 }, { u3, v2 } }, // C-F-I { { u2, v5 }, { u3, v4 }, { u2, v3 } }, // H-F-C { { u2, v5 }, { u3, v6 }, { u3, v4 } }, // H-D-F { { u2, v7 }, { u3, v6 }, { u2, v5 } }, // L-D-H { { u3, v4 }, { u4, v5 }, { u4, v3 } }, // F-J-I { { u3, v6 }, { u4, v5 }, { u3, v4 } }, // D-J-F { { u3, v6 }, { u4, v7 }, { u4, v5 } }, // D-B-J { { u3, v8 }, { u4, v7 }, { u3, v6 } }, // L-B-D { { u4, v5 }, { u5, v6 }, { u5, v4 } }, // J-E-I { { u4, v7 }, { u5, v6 }, { u4, v5 } }, // B-E-J { { u4, v7 }, { u5, v8 }, { u5, v6 } }, // B-G-E { { u4, v9 }, { u5, v8 }, { u4, v7 } } // L-G-B }; // Generate the initial vertex list from a plain icosahedron. QVector3DArray vertices; QVector3DArray normals; QVector2DArray texCoords; for (int ix = 0; ix < 20; ++ix) { QVector3D n0(ico[face[ix][0]][0], ico[face[ix][0]][1], ico[face[ix][0]][2]); QVector3D n1(ico[face[ix][1]][0], ico[face[ix][1]][1], ico[face[ix][1]][2]); QVector3D n2(ico[face[ix][2]][0], ico[face[ix][2]][1], ico[face[ix][2]][2]); QVector2D t0(tex[ix][0][0], tex[ix][0][1]); QVector2D t1(tex[ix][1][0], tex[ix][1][1]); QVector2D t2(tex[ix][2][0], tex[ix][2][1]); n0 = n0.normalized(); n1 = n1.normalized(); n2 = n2.normalized(); QVector3D v0 = n0 * scale / 2.0f; QVector3D v1 = n1 * scale / 2.0f; QVector3D v2 = n2 * scale / 2.0f; vertices.append(v0, v1, v2); normals.append(n0, n1, n2); texCoords.append(t0, t1, t2); } // Subdivide the icosahedron. while (depth-- > 1) { QVector3DArray newVertices; QVector3DArray newNormals; QVector2DArray newTexCoords; int count = vertices.count(); for (int i = 0; i < count; i+= 3) { QVector3D v0 = vertices.at(i); QVector3D v1 = vertices.at(i+1); QVector3D v2 = vertices.at(i+2); QVector3D n0 = normals.at(i); QVector3D n1 = normals.at(i+1); QVector3D n2 = normals.at(i+2); QVector2D t0 = texCoords.at(i); QVector2D t1 = texCoords.at(i+1); QVector2D t2 = texCoords.at(i+2); QVector3D n01 = (v0 + v1).normalized(); QVector3D n12 = (v1 + v2).normalized(); QVector3D n20 = (v2 + v0).normalized(); QVector3D v01 = n01 * scale / 2.0f; QVector3D v12 = n12 * scale / 2.0f; QVector3D v20 = n20 * scale / 2.0f; QVector2D t01 = (t0 + t1) / 2; QVector2D t12 = (t1 + t2) / 2; QVector2D t20 = (t2 + t0) / 2; newVertices.append(v0, v01, v20); newNormals.append(n0, n01, n20); newTexCoords.append(t0, t01, t20); newVertices.append(v01, v1, v12); newNormals.append(n01, n1, n12); newTexCoords.append(t01, t1, t12); newVertices.append(v01, v12, v20); newNormals.append(n01, n12, n20); newTexCoords.append(t01, t12, t20); newVertices.append(v20, v12, v2); newNormals.append(n20, n12, n2); newTexCoords.append(t20, t12, t2); } vertices = newVertices; normals = newNormals; texCoords = newTexCoords; } // Add the final vertices to the builder. QGeometryData prim; prim.appendVertexArray(vertices); prim.appendNormalArray(normals); prim.appendTexCoordArray(texCoords); list.addTriangles(prim); return list; }
/*! \relates QGLCubeSphere Builds the geometry for \a sphere within the specified display \a list. */ QGLBuilder& operator<<(QGLBuilder& list, const QGLCubeSphere& sphere) { /* A-----H | | | | A-----D-----E-----H-----A | | | | | | | | | | B-----C-----F-----G-----B | | | | B-----G ^ d e | c f y x--> */ qreal scale = sphere.diameter(); int depth = sphere.subdivisionDepth(); const qreal offset = 1.0f; float cube[8][3] = { { -offset, offset, -offset}, // A - 0 { -offset, -offset, -offset }, // B - 1 { -offset, -offset, offset }, // C - 2 { -offset, offset, offset }, // D - 3 { offset, offset, offset }, // E - 4 { offset, -offset, offset }, // F - 5 { offset, -offset, -offset }, // G - 6 { offset, offset, -offset }, // H - 7 }; int face[6][4] = { { 0, 1, 2, 3 }, // A-B-C-D { 3, 2, 5, 4 }, // D-C-F-E { 4, 5, 6, 7 }, // E-F-G-H { 7, 6, 1, 0 }, // H-G-B-A { 0, 3, 4, 7 }, // A-D-E-H { 2, 1, 6, 5 }, // C-B-G-F }; const float v3 = 0.0f; const float v2 = 0.333333333f; const float v1 = 0.666666666f; const float v0 = 1.0f; const float u0 = 0.0f; const float u1 = 0.25f; const float u2 = 0.5f; const float u3 = 0.75f; const float u4 = 1.0f; float tex[6][4][2] = { { {u0, v1}, {u0, v2}, {u1, v2}, {u1, v1} }, // A-B-C-D { {u1, v1}, {u1, v2}, {u2, v2}, {u2, v1} }, // D-C-F-E { {u2, v1}, {u2, v2}, {u3, v2}, {u3, v1} }, // E-F-G-H { {u3, v1}, {u3, v2}, {u4, v2}, {u4, v1} }, // H-G-B-A { {u1, v0}, {u1, v1}, {u2, v1}, {u2, v0} }, // A-D-E-H { {u1, v2}, {u1, v3}, {u2, v3}, {u2, v2} }, // C-B-G-F }; // Generate the initial vertex list from a plain cube. QVector3DArray vertices; QVector3DArray normals; QVector2DArray texCoords; for (int ix = 0; ix < 6; ++ix) { QVector3D n0(cube[face[ix][0]][0], cube[face[ix][0]][1], cube[face[ix][0]][2]); QVector3D n1(cube[face[ix][1]][0], cube[face[ix][1]][1], cube[face[ix][1]][2]); QVector3D n2(cube[face[ix][2]][0], cube[face[ix][2]][1], cube[face[ix][2]][2]); QVector3D n3(cube[face[ix][3]][0], cube[face[ix][3]][1], cube[face[ix][3]][2]); QVector2D t0(tex[ix][0][0], tex[ix][0][1]); QVector2D t1(tex[ix][1][0], tex[ix][1][1]); QVector2D t2(tex[ix][2][0], tex[ix][2][1]); QVector2D t3(tex[ix][3][0], tex[ix][3][1]); n0 = n0.normalized(); n1 = n1.normalized(); n2 = n2.normalized(); n3 = n3.normalized(); QVector3D v0 = n0 * scale / 2.0f; QVector3D v1 = n1 * scale / 2.0f; QVector3D v2 = n2 * scale / 2.0f; QVector3D v3 = n3 * scale / 2.0f; vertices.append(v0, v1, v2, v3); normals.append(n0, n1, n2, n3); texCoords.append(t0, t1, t2, t3); } // Subdivide the cube. while (depth-- > 1) { QVector3DArray newVertices; QVector3DArray newNormals; QVector2DArray newTexCoords; int count = vertices.count(); for (int i = 0; i < count; i+= 4) { QVector3D v0 = vertices.at(i); QVector3D v1 = vertices.at(i+1); QVector3D v2 = vertices.at(i+2); QVector3D v3 = vertices.at(i+3); QVector3D n0 = normals.at(i); QVector3D n1 = normals.at(i+1); QVector3D n2 = normals.at(i+2); QVector3D n3 = normals.at(i+3); QVector2D t0 = texCoords.at(i); QVector2D t1 = texCoords.at(i+1); QVector2D t2 = texCoords.at(i+2); QVector2D t3 = texCoords.at(i+3); QVector3D n01 = (v0 + v1).normalized(); QVector3D n12 = (v1 + v2).normalized(); QVector3D n23 = (v2 + v3).normalized(); QVector3D n30 = (v3 + v0).normalized(); QVector3D nc = (v0 + v1 + v2 + v3).normalized(); QVector3D v01 = n01 * scale / 2.0f; QVector3D v12 = n12 * scale / 2.0f; QVector3D v23 = n23 * scale / 2.0f; QVector3D v30 = n30 * scale / 2.0f; QVector3D vc = nc * scale / 2.0f; QVector2D t01 = (t0 + t1) / 2; QVector2D t12 = (t1 + t2) / 2; QVector2D t23 = (t2 + t3) / 2; QVector2D t30 = (t3 + t0) / 2; QVector2D tc = (t2 + t0) / 2; newVertices.append(v0, v01, vc, v30); newNormals.append(n0, n01, nc, n30); newTexCoords.append(t0, t01, tc, t30); newVertices.append(v01, v1, v12, vc); newNormals.append(n01, n1, n12, nc); newTexCoords.append(t01, t1, t12, tc); newVertices.append(vc, v12, v2, v23); newNormals.append(nc, n12, n2, n23); newTexCoords.append(tc, t12, t2, t23); newVertices.append(v30, vc, v23, v3); newNormals.append(n30, nc, n23, n3); newTexCoords.append(t30, tc, t23, t3); } vertices = newVertices; normals = newNormals; texCoords = newTexCoords; } // Add the final vertices to the display list. QGeometryData prim; prim.appendVertexArray(vertices); prim.appendNormalArray(normals); prim.appendTexCoordArray(texCoords); list.addTriangles(prim); return list; }
void MgGeometriesData::rotateGeometry(QGeometryData & data,const QQuaternion & rotation) { for (int i = 0; i < data.count(); ++i) data.vertex(i) = rotation.rotatedVector(data.vertexAt(i)); }
void tst_QGeometryData::createDefault() { QGeometryData data; QCOMPARE(data.count(), 0); QCOMPARE(data.attributes().count(), 0); QCOMPARE(data.fields(), quint32(0)); QCOMPARE(data.vertices().count(), 0); data.normalizeNormals(); QCOMPARE(data.boundingBox(), QBox3D()); QCOMPARE(data.commonNormal(), QVector3D()); // copy constructor on initialization - null default QGeometryData other = data; QCOMPARE(other.count(), 0); QCOMPARE(other.attributes().count(), 0); QCOMPARE(other.fields(), quint32(0)); // copy constructor on default QGeometryData copy(data); QCOMPARE(copy.count(), 0); QCOMPARE(copy.attributes().count(), 0); QCOMPARE(copy.fields(), quint32(0)); }
void tst_QGeometryData::appendVertex() { QVector3D a(1.1, 1.2, 1.3); QVector3D b(2.1, 2.2, 2.3); QVector3D c(3.1, 3.2, 3.3); QVector3D d(4.1, 4.2, 4.3); { QGeometryData data; data.appendVertex(a); QCOMPARE(data.count(), 1); QCOMPARE(data.fields(), QGL::fieldMask(QGL::Position)); QCOMPARE(data.vertices().count(), 1); QCOMPARE(data.vertices().at(0), a); } { QGeometryData data; data.appendVertex(a, b); QCOMPARE(data.count(), 2); QCOMPARE(data.fields(), QGL::fieldMask(QGL::Position)); QCOMPARE(data.vertices().count(), 2); QCOMPARE(data.vertices().at(0), a); QCOMPARE(data.vertices().at(1), b); } { QGeometryData data; data.appendVertex(a, b, c); QCOMPARE(data.count(), 3); QCOMPARE(data.fields(), QGL::fieldMask(QGL::Position)); QCOMPARE(data.vertices().count(), 3); QCOMPARE(data.vertices().at(0), a); QCOMPARE(data.vertices().at(1), b); QCOMPARE(data.vertices().at(2), c); } { QGeometryData data; data.appendVertex(a, b, c, d); QCOMPARE(data.count(), 4); QCOMPARE(data.fields(), QGL::fieldMask(QGL::Position)); QCOMPARE(data.vertices().count(), 4); QCOMPARE(data.vertices().at(0), a); QCOMPARE(data.vertices().at(1), b); QCOMPARE(data.vertices().at(2), c); QCOMPARE(data.vertices().at(3), d); } { QGeometryData data; data.appendVertex(a, b, c, d); data.appendVertex(a, b, c, d); data.appendVertex(a); QCOMPARE(data.count(), 9); QCOMPARE(data.fields(), QGL::fieldMask(QGL::Position)); QCOMPARE(data.vertices().count(), 9); QCOMPARE(data.vertices().at(0), a); QCOMPARE(data.vertices().at(1), b); QCOMPARE(data.vertices().at(5), b); QCOMPARE(data.vertices().at(8), a); } }
//------------------------------------------------------------------------------ QGLBuilder& operator << ( QGLBuilder& builder, const QGLEllipsoid& ellipsoid ) { // Determine the number of slices and stacks to generate. static int const numberOfSlicesForSubdivisionDepth[] = { 8, 8, 16, 16, 32, 32, 64, 64, 128, 128 }; static int const numberOfStacksForSubdivisionDepth[] = { 4, 8, 8, 16, 16, 32, 32, 64, 64, 128 }; const unsigned int numberOfSlices = numberOfSlicesForSubdivisionDepth[ ellipsoid.GetSubdivisionDepth() - 1 ]; const unsigned int numberOfStacks = numberOfStacksForSubdivisionDepth[ ellipsoid.GetSubdivisionDepth() - 1 ]; // Precompute sin/cos values for the slices. const unsigned int maxSlices = 128 + 1; const unsigned int maxStacks = 128 + 1; qreal sliceSin[ maxSlices ]; qreal sliceCos[ maxSlices ]; for( unsigned int slice = 0; slice < numberOfSlices; ++slice ) { const qreal angle = 2 * M_PI * (numberOfSlices - 1 - slice) / numberOfSlices; sliceSin[slice] = qFastSin(angle); sliceCos[slice] = qFastCos(angle); } // Join first and last slice. sliceSin[numberOfSlices] = sliceSin[0]; sliceCos[numberOfSlices] = sliceCos[0]; // Precompute sin/cos values for the stacks. qreal stackSin[ maxStacks ]; qreal stackCos[ maxStacks ]; for( unsigned int stack = 0; stack <= numberOfStacks; ++stack ) { // Efficiently handle end-points which also ensure geometry comes to a point at the poles (no round-off). if( stack == 0 ) { stackSin[stack] = 0.0f; stackCos[stack] = 1.0f; } else if( stack == numberOfStacks ) { stackSin[stack] = 0.0f; stackCos[stack] = -1.0f; } else { const qreal angle = M_PI * stack / numberOfStacks; stackSin[stack] = qFastSin(angle); stackCos[stack] = qFastCos(angle); } } // Half the dimensions of the ellipsoid for calculations below (centroid of ellipsoid is 0, 0, 0.) const qreal xRadius = 0.5 * ellipsoid.GetXDiameter(); const qreal yRadius = 0.5 * ellipsoid.GetYDiameter(); const qreal zRadius = 0.5 * ellipsoid.GetZDiameter(); const qreal oneOverXRadiusSquared = 1.0 / (xRadius * xRadius); const qreal oneOverYRadiusSquared = 1.0 / (yRadius * yRadius); const qreal oneOverZRadiusSquared = 1.0 / (zRadius * zRadius); // Create the stacks. for( unsigned int stack = 0; stack < numberOfStacks; ++stack ) { QGeometryData quadStrip; for( unsigned int slice = 0; slice <= numberOfSlices; ++slice ) { // Equation for ellipsoid surface is x^2/xRadius^2 + y^2/yRadius^2 + z^2/zRadius^2 = 1 // Location of vertices can be specified in terms of "polar coordinates". const qreal nextx = xRadius * stackSin[stack+1] * sliceSin[slice]; const qreal nexty = yRadius * stackSin[stack+1] * sliceCos[slice]; const qreal nextz = zRadius * stackCos[stack+1]; quadStrip.appendVertex( QVector3D( nextx, nexty, nextz) ); // Equation for ellipsoid surface is Surface = x^2/xRadius^2 + y^2/yRadius^2 + z^2/zRadius^2 - 1 // Gradient for ellipsoid is x/xRadius^2*Nx> + y/yRadius^2*Ny> + z/zRadius^2*Nz> // Gradient for sphere simplifies to x*Nx> + y*Ny> + z*Nz> // const qreal nextGradientx = stackSin[stack+1] * sliceSin[slice]; // const qreal nextGradienty = stackSin[stack+1] * sliceCos[slice]; // const qreal nextGradientz = stackCos[stack+1]; const qreal nextGradientx = nextx * oneOverXRadiusSquared; const qreal nextGradienty = nexty * oneOverYRadiusSquared; const qreal nextGradientz = nextz * oneOverZRadiusSquared; const qreal nextGradientMagSquared = nextGradientx * nextGradientx + nextGradienty * nextGradienty + nextGradientz * nextGradientz; const qreal oneOverNextGradientMagnitude = 1.0 / sqrt( nextGradientMagSquared ); quadStrip.appendNormal( oneOverNextGradientMagnitude * QVector3D( nextGradientx, nextGradienty, nextGradientz ) ); quadStrip.appendTexCoord( QVector2D(1.0f - qreal(slice) / numberOfSlices, 1.0f - qreal(stack + 1) / numberOfStacks) ); const qreal x = xRadius * stackSin[stack] * sliceSin[slice]; const qreal y = yRadius * stackSin[stack] * sliceCos[slice]; const qreal z = zRadius * stackCos[stack]; quadStrip.appendVertex( QVector3D( x, y, z) ); // const qreal gradientx = stackSin[stack] * sliceSin[slice]; // const qreal gradienty = stackSin[stack] * sliceCos[slice]; // const qreal gradientz = stackCos[stack]; const qreal gradientx = x * oneOverXRadiusSquared; const qreal gradienty = y * oneOverYRadiusSquared; const qreal gradientz = z * oneOverZRadiusSquared; const qreal gradientMagSquared = gradientx * gradientx + gradienty * gradienty + gradientz * gradientz; const qreal oneOverGradientMagnitude = 1.0 / sqrt( gradientMagSquared ); quadStrip.appendNormal( oneOverGradientMagnitude * QVector3D( gradientx, gradienty, gradientz) ); quadStrip.appendTexCoord( QVector2D(1.0f - qreal(slice) / numberOfSlices, 1.0f - qreal(stack) / numberOfStacks) ); } // The quad strip stretches from pole to pole. builder.addQuadStrip( quadStrip ); } return builder; }
PlyLoader::PlyLoader( const std::string& file, boost::optional< QColor4ub > color, double scale ) : color_( color ), scale_( scale ) { std::ifstream stream( file.c_str() ); std::string line; std::getline( stream, line ); if( line != "ply" ) { COMMA_THROW( comma::exception, "expected ply file; got \"" << line << "\" in " << file ); } unsigned int numVertex = 0; unsigned int numFace = 0; bool has_normals = false; std::vector< std::string > fields; while( stream.good() && !stream.eof() && line != "end_header" ) { std::getline( stream, line ); if( line.empty() ) { continue; } std::vector< std::string > v = comma::split( comma::strip( line ), ' ' ); if( v[0] == "element" ) // quick and dirty { if( v[1] == "vertex" ) { numVertex = boost::lexical_cast< unsigned int >( v[2] ); } else if( v[1] == "face" ) { numFace = boost::lexical_cast< unsigned int >( v[2] ); } } else if( v[0] == "format" && v[1] != "ascii" ) { COMMA_THROW( comma::exception, "only ascii supported; got: " << v[1] ); } else if( line == "property float x" ) { fields.push_back( "point/x" ); } else if( line == "property float y" ) { fields.push_back( "point/y" ); } else if( line == "property float z" ) { fields.push_back( "point/z" ); } else if( line == "property float nx" ) { fields.push_back( "normal/x" ); has_normals = true; } else if( line == "property float ny" ) { fields.push_back( "normal/y" ); } else if( line == "property float nz" ) { fields.push_back( "normal/z" ); } else if( line == "property uchar red" ) { fields.push_back( "r" ); } else if( line == "property uchar green" ) { fields.push_back( "g" ); } else if( line == "property uchar blue" ) { fields.push_back( "b" ); } else if( line == "property uchar alpha" ) { fields.push_back( "a" ); } } comma::csv::options csv; csv.fields = comma::join( fields, ',' ); csv.full_xpath = true; csv.delimiter = ' '; comma::csv::ascii< ply_vertex > ascii( csv ); QGeometryData geometry; QArray< QVector3D > vertices; QArray< QColor4ub > colors; for( unsigned int i = 0; i < numVertex; i++ ) { std::string s; if( stream.eof() ) { break; } std::getline( stream, s ); if( s.empty() ) { continue; } ply_vertex v; if( color_ ) { v.color = *color_; } // quick and dirty ascii.get( v, s ); if( numFace > 0 ) { geometry.appendVertex( QVector3D( v.point.x() * scale_, v.point.y() * scale_, v.point.z() * scale_ ) ); if( has_normals ) { geometry.appendNormal( QVector3D( v.normal.x(), v.normal.y(), v.normal.z() ) ); } geometry.appendColor( v.color ); } else { vertices.append( QVector3D( v.point.x() * scale_, v.point.y() * scale_, v.point.z() * scale_ ) ); // todo: normals? colors.append( v.color ); } } if( numFace > 0 ) { for( unsigned int i = 0; i < numFace; i++ ) // quick and dirty { std::string s; if( stream.eof() ) { break; } std::getline( stream, s ); if( s.empty() ) { continue; } std::vector< std::string > v = comma::split( comma::strip( s ), ' ' ); unsigned int vertices_per_face = boost::lexical_cast< unsigned int >( v[0] ); if( ( vertices_per_face + 1 ) != v.size() ) { COMMA_THROW( comma::exception, "invalid line \"" << s << "\"" ); } QGL::IndexArray indices; switch( vertices_per_face ) { case 3: for( unsigned int i = 0; i < 3; ++i ) { indices.append( boost::lexical_cast< unsigned int >( v[i+1] ) ); } break; case 4: // quick and dirty for now: triangulate boost::array< unsigned int, 4 > a; for( unsigned int i = 0; i < 4; ++i ) { a[i] = boost::lexical_cast< unsigned int >( v[i+1] ); } indices.append( a[0] ); indices.append( a[1] ); indices.append( a[2] ); indices.append( a[0] ); indices.append( a[2] ); indices.append( a[3] ); break; default: // never here break; } geometry.appendIndices( indices ); } QGLBuilder builder; builder.addTriangles( geometry ); //switch( vertices_per_face ) //{ // case 3: builder.addTriangles( geometry ); break; // case 4: builder.addQuads( geometry ); break; // default: COMMA_THROW( comma::exception, "only triangles and quads supported; but got " << vertices_per_face << " vertices per face" ); //} m_sceneNode = builder.finalizedSceneNode(); } else { m_vertices.addAttribute( QGL::Position, vertices ); // todo: normals? m_vertices.addAttribute( QGL::Color, colors ); m_vertices.upload(); m_sceneNode = NULL; } stream.close(); }
/*! Helper function to calculate the normal for and set it on vertices in \a i, \a j and \a k in triangle data \a p. If the triangle in data \a p is a null triangle (area == 0) then the function returns false, otherwise it returns true. */ static inline void setNormals(int i, int j, int k, QGeometryData &p, const QVector3D &n) { p.normal(i) = n; p.normal(j) = n; p.normal(k) = n; }