void Tutorial05::initializeGL() { // initialize OpenGL initializeOpenGLFunctions(); // Dark blue background glClearColor(0.0f, 0.0f, 0.3f, 0.0f); // Enable depth test glEnable(GL_DEPTH_TEST); // Accept fragment if it closer to the camera than the former one glDepthFunc(GL_LESS); bool success; // load and compile vertex shader success = shaderProgram.addShaderFromSourceFile(QOpenGLShader::Vertex, ":/TransformVertexShader.vert"); // load and compile fragment shader success = shaderProgram.addShaderFromSourceFile(QOpenGLShader::Fragment, ":/TextureFragmentShader.frag"); programID = shaderProgram.programId(); // Projection matrix : 45° Field of View, 4:3 ratio, display range : 0.1 unit <-> 100 units QMatrix4x4 projection; projection.perspective(45.0, 4.0/3.0, 0.1, 100.0); // Camera matrix QMatrix4x4 view; view.lookAt( QVector3D(4,3,3), // Camera is at (4,3,3), in World Space QVector3D(0,0,0), // and looks at the origin QVector3D(0,1,0) // Head is up (set to 0,-1,0 to look upside-down) ); // Model matrix : an identity matrix (model will be at the origin) QMatrix4x4 model; model.setToIdentity(); // Our ModelViewProjection : multiplication of our 3 matrices MVP = projection * view * model; // Remember, matrix multiplication is the other way around shaderProgram.link(); // Get a handle for our "MVP" uniform MatrixID = glGetUniformLocation(programID, "MVP"); // Get a handle for our buffers vertexPosition_modelspaceID = glGetAttribLocation(programID, "vertexPosition_modelspace"); vertexUVID = glGetAttribLocation(programID, "vertexUV"); // Load the texture Qt methods QImage image = QImage(":/uvtemplate.bmp").mirrored(); mTexture = new QOpenGLTexture(image); mTexture->setMinificationFilter(QOpenGLTexture::LinearMipMapLinear); mTexture->setMagnificationFilter(QOpenGLTexture::Linear); shaderProgram.setUniformValue("myTextureSampler", 0); //enable texturing glEnable(GL_TEXTURE_2D); //generate textures //bind the texture mTexture->bind(); // ... nice trilinear filtering. //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); //glGenerateMipmap(GL_TEXTURE_2D); glGenBuffers(1, &vertexbuffer); glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer); glBufferData(GL_ARRAY_BUFFER, sizeof(g_vertex_buffer_data), g_vertex_buffer_data, GL_STATIC_DRAW); glGenBuffers(1, &uvbuffer); glBindBuffer(GL_ARRAY_BUFFER, uvbuffer); glBufferData(GL_ARRAY_BUFFER, sizeof(g_uv_buffer_data), g_uv_buffer_data, GL_STATIC_DRAW); }
void tst_QVectorArray::transform() { QMatrix4x4 m; m.translate(-1.0f, 2.5f, 5.0f); m.rotate(45.0f, 1.0f, 1.0f, 1.0f); m.scale(23.5f); QVector2DArray v2array; QVector3DArray v3array; QVector4DArray v4array; QVector2DArray v2arrayb; QVector3DArray v3arrayb; QVector4DArray v4arrayb; for (int index = 0; index < 64; ++index) { v2array.append(index * 4, index * 4 + 1); v3array.append(index * 4, index * 4 + 1, index * 4 + 2); v4array.append(index * 4, index * 4 + 1, index * 4 + 2, index * 4 + 3); v2arrayb.append(index * 4, index * 4 + 1); v3arrayb.append(index * 4, index * 4 + 1, index * 4 + 2); v4arrayb.append(index * 4, index * 4 + 1, index * 4 + 2, index * 4 + 3); } // Perform a simple in-place transform. v2array.transform(m); v3array.transform(m); v4array.transform(m); QCOMPARE(v2array.size(), 64); QCOMPARE(v3array.size(), 64); QCOMPARE(v4array.size(), 64); for (int index = 0; index < 64; ++index) { QVector2D v2(index * 4, index * 4 + 1); QVector3D v3(index * 4, index * 4 + 1, index * 4 + 2); QVector4D v4(index * 4, index * 4 + 1, index * 4 + 2, index * 4 + 3); QVERIFY(fuzzyCompare(v2array[index], (m * QVector3D(v2)).toVector2D())); QVERIFY(fuzzyCompare(v3array[index], m * v3)); QVERIFY(fuzzyCompare(v4array[index], m * v4)); } // Increase ref-count on an array and check that detach occurs. v2array = v2arrayb; v3array = v3arrayb; v4array = v4arrayb; QVERIFY(v2array.constData() == v2arrayb.constData()); QVERIFY(v3array.constData() == v3arrayb.constData()); QVERIFY(v4array.constData() == v4arrayb.constData()); v2array.transform(m); v3array.transform(m); v4array.transform(m); QVERIFY(v2array.constData() != v2arrayb.constData()); QVERIFY(v3array.constData() != v3arrayb.constData()); QVERIFY(v4array.constData() != v4arrayb.constData()); QCOMPARE(v2array.size(), 64); QCOMPARE(v3array.size(), 64); QCOMPARE(v4array.size(), 64); for (int index = 0; index < 64; ++index) { QVector2D v2(index * 4, index * 4 + 1); QVector3D v3(index * 4, index * 4 + 1, index * 4 + 2); QVector4D v4(index * 4, index * 4 + 1, index * 4 + 2, index * 4 + 3); QVERIFY(fuzzyCompare(v2array[index], (m * QVector3D(v2)).toVector2D())); QVERIFY(fuzzyCompare(v3array[index], m * v3)); QVERIFY(fuzzyCompare(v4array[index], m * v4)); QVERIFY(fuzzyCompare(v2arrayb[index], v2)); QVERIFY(fuzzyCompare(v3arrayb[index], v3)); QVERIFY(fuzzyCompare(v4arrayb[index], v4)); } // Perform the test again, with translated() this time. v2array = v2arrayb.transformed(m); v3array = v3arrayb.transformed(m); v4array = v4arrayb.transformed(m); QCOMPARE(v2array.size(), 64); QCOMPARE(v3array.size(), 64); QCOMPARE(v4array.size(), 64); for (int index = 0; index < 64; ++index) { QVector2D v2(index * 4, index * 4 + 1); QVector3D v3(index * 4, index * 4 + 1, index * 4 + 2); QVector4D v4(index * 4, index * 4 + 1, index * 4 + 2, index * 4 + 3); QVERIFY(fuzzyCompare(v2array[index], (m * QVector3D(v2)).toVector2D())); QVERIFY(fuzzyCompare(v3array[index], m * v3)); QVERIFY(fuzzyCompare(v4array[index], m * v4)); QVERIFY(fuzzyCompare(v2arrayb[index], v2)); QVERIFY(fuzzyCompare(v3arrayb[index], v3)); QVERIFY(fuzzyCompare(v4arrayb[index], v4)); } }
void SatGL::RenderTrail(Satellite *sat, QMatrix4x4 projection, float distance, QQuaternion quat, bool trackon) // QMatrix4x4 modelview, bool trackon) { QVector<GLfloat> postrail; double tsince, // Time since epoch (in minutes) jul_epoch, // Julian date of epoch jul_utc; // Julian UTC date QSgp4Date nowutc = QSgp4Date::NowUTC(); jul_utc = nowutc.Julian(); jul_epoch = Julian_Date_of_Epoch(sat->GetEpoch()); QMatrix4x4 model; model.translate(0.0, 0.0, distance); model.rotate(quat); QMatrix4x4 modelview; modelview = model; QMatrix4x4 modelocta; QColor col(0,255,255); QEci qeci; QVector3D pos; double id; int nbrVertices = 0; tsince = (jul_utc - jul_epoch) * MIN_PER_DAY; // in minutes for( id = tsince - 5; id < tsince; id++ ) { (*sat).qsgp4->getPosition(id, qeci); QGeodetic qgeo = qeci.ToGeo(); LonLat2PointRad(qgeo.latitude, qgeo.longitude, &pos, 1.001f); if(id < tsince && id >= tsince - 5 ) { modelocta = model; modelocta.translate(pos.x(), pos.y(), pos.z()); modelocta.scale(0.004f); octa->render(projection, modelocta, col); } } if(trackon) { for( id = tsince - opts.realminutesshown + 1; id <= tsince + opts.realminutesshown; id++ ) // nbr of id's = 2 * opts.realminutesshown { (*sat).qsgp4->getPosition(id, qeci); QGeodetic qgeo = qeci.ToGeo(); LonLat2PointRad(qgeo.latitude, qgeo.longitude, &pos, 1.001f); postrail.append(pos.x()); postrail.append(pos.y()); postrail.append(pos.z()); } positionsTrail.bind(); if(tdiff != opts.realminutesshown) { tdiff = opts.realminutesshown; positionsTrail.allocate(postrail.data(), postrail.size() * sizeof(GLfloat)); } else { positionsTrail.write(0, postrail.data(), postrail.size() * sizeof(GLfloat)); } nbrVertices = positionsTrail.size() / (3 * sizeof(GLfloat)); positionsTrail.release(); QOpenGLVertexArrayObject::Binder vaoBinder(&vaotrail); program->bind(); program->setUniformValue("MVP", projection * modelview); QMatrix3x3 norm = modelview.normalMatrix(); program->setUniformValue("NormalMatrix", norm); QColor rendercolor(opts.sattrackcolor); program->setUniformValue("outcolor", QVector4D(rendercolor.redF(), rendercolor.greenF(), rendercolor.blueF(), 1.0f)); glDrawArrays(GL_LINE_STRIP, 0, nbrVertices); } }
bool BrainSurfaceTreeItem::addData(const Surface& tSurface, Qt3DCore::QEntity* parent) { //Create renderable 3D entity m_pParentEntity = parent; m_pRenderable3DEntity = new Renderable3DEntity(parent); m_pRenderable3DEntityActivationOverlay = new Renderable3DEntity(parent); QMatrix4x4 m; Qt3DCore::QTransform* transform = new Qt3DCore::QTransform(); m.rotate(180, QVector3D(0.0f, 1.0f, 0.0f)); m.rotate(-90, QVector3D(1.0f, 0.0f, 0.0f)); transform->setMatrix(m); m_pRenderable3DEntity->addComponent(transform); m_pRenderable3DEntityActivationOverlay->addComponent(transform); //Create color from curvature information with default gyri and sulcus colors QByteArray arrayCurvatureColor = createCurvatureVertColor(tSurface.curv()); //Set renderable 3D entity mesh and color data m_pRenderable3DEntity->setMeshData(tSurface.rr(), tSurface.nn(), tSurface.tris(), -tSurface.offset(), arrayCurvatureColor); //Generate activation overlay surface // MatrixX3f overlayAdds = tSurface.rr(); // for(int i = 0; i<tSurface.nn().rows(); i++) { // RowVector3f direction = tSurface.nn().row(i); // direction.normalize(); // overlayAdds.row(i) = direction*0.0001; // } // m_pRenderable3DEntityActivationOverlay->setMeshData(tSurface.rr()+overlayAdds, tSurface.nn(), tSurface.tris(), -tSurface.offset(), matCurvatureColor); //Add data which is held by this BrainSurfaceTreeItem QVariant data; data.setValue(arrayCurvatureColor); this->setData(data, BrainSurfaceTreeItemRoles::SurfaceCurrentColorVert); this->setData(data, BrainSurfaceTreeItemRoles::SurfaceCurvatureColorVert); data.setValue(tSurface.rr()); this->setData(data, BrainSurfaceTreeItemRoles::SurfaceVert); data.setValue(tSurface.tris()); this->setData(data, BrainSurfaceTreeItemRoles::SurfaceTris); data.setValue(tSurface.nn()); this->setData(data, BrainSurfaceTreeItemRoles::SurfaceNorm); data.setValue(tSurface.curv()); this->setData(data, BrainSurfaceTreeItemRoles::SurfaceCurv); data.setValue(tSurface.offset()); this->setData(data, BrainSurfaceTreeItemRoles::SurfaceOffset); data.setValue(m_pRenderable3DEntity); this->setData(data, BrainSurfaceTreeItemRoles::SurfaceRenderable3DEntity); data.setValue(m_pRenderable3DEntityActivationOverlay); this->setData(data, BrainSurfaceTreeItemRoles::SurfaceRenderable3DEntityAcivationOverlay); //Add surface meta information as item children m_pItemSurfColorInfoOrigin = new BrainTreeMetaItem(BrainTreeMetaItemTypes::SurfaceColorInfoOrigin, "Color from curvature"); connect(m_pItemSurfColorInfoOrigin, &BrainTreeMetaItem::colorInfoOriginChanged, this, &BrainSurfaceTreeItem::onColorInfoOriginOrCurvColorChanged); *this<<m_pItemSurfColorInfoOrigin; data.setValue(QString("Color from curvature")); m_pItemSurfColorInfoOrigin->setData(data, BrainTreeMetaItemRoles::SurfaceColorInfoOrigin); m_pItemSurfColSulci = new BrainTreeMetaItem(BrainTreeMetaItemTypes::SurfaceColorSulci, "Sulci color"); connect(m_pItemSurfColSulci, &BrainTreeMetaItem::curvColorsChanged, this, &BrainSurfaceTreeItem::onColorInfoOriginOrCurvColorChanged); *this<<m_pItemSurfColSulci; data.setValue(QColor(50,50,50)); m_pItemSurfColSulci->setData(data, BrainTreeMetaItemRoles::SurfaceColorSulci); m_pItemSurfColSulci->setData(data, Qt::DecorationRole); m_pItemSurfColGyri = new BrainTreeMetaItem(BrainTreeMetaItemTypes::SurfaceColorGyri, "Gyri color"); connect(m_pItemSurfColGyri, &BrainTreeMetaItem::curvColorsChanged, this, &BrainSurfaceTreeItem::onColorInfoOriginOrCurvColorChanged); *this<<m_pItemSurfColGyri; data.setValue(QColor(125,125,125)); m_pItemSurfColGyri->setData(data, BrainTreeMetaItemRoles::SurfaceColorGyri); m_pItemSurfColGyri->setData(data, Qt::DecorationRole); BrainTreeMetaItem *itemSurfFileName = new BrainTreeMetaItem(BrainTreeMetaItemTypes::SurfaceFileName, tSurface.fileName()); itemSurfFileName->setEditable(false); *this<<itemSurfFileName; data.setValue(tSurface.fileName()); itemSurfFileName->setData(data, BrainTreeMetaItemRoles::SurfaceFileName); BrainTreeMetaItem *itemSurfType = new BrainTreeMetaItem(BrainTreeMetaItemTypes::SurfaceType, tSurface.surf()); itemSurfType->setEditable(false); *this<<itemSurfType; data.setValue(tSurface.surf()); itemSurfType->setData(data, BrainTreeMetaItemRoles::SurfaceType); BrainTreeMetaItem *itemSurfPath = new BrainTreeMetaItem(BrainTreeMetaItemTypes::SurfaceFilePath, tSurface.filePath()); itemSurfPath->setEditable(false); *this<<itemSurfPath; data.setValue(tSurface.filePath()); itemSurfPath->setData(data, BrainTreeMetaItemRoles::SurfaceFilePath); return true; }
void Patch::translate(const QVector3D &t) { mat.translate(t); }
void TApplication::RenderToFBO() { Fbo->bind(); glEnable(GL_DEPTH_TEST); glEnable(GL_MULTISAMPLE); Shader.bind(); glViewport(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT); glClearColor(0.0, 0.0, 0.0, 0.0); glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); QMatrix4x4 view; view.lookAt(QVector3D(0.0, 0.0, 6.0), QVector3D(0.0, 0.0, 0.0), QVector3D(0.0, 1.0, 0.0)); QMatrix4x4 projection; projection.perspective(45.0f, float(WINDOW_WIDTH) / float(WINDOW_HEIGHT), 0.1f, 10.0f); Shader.setUniformValue("projection", projection); Shader.setUniformValue("view", view); Shader.setUniformValue("lightIntensities", QVector3D(1.0, 1.0, 1.0)); Shader.setUniformValue("lightPosition", QVector3D(-30.0, 30.0, 30.0)); QMatrix4x4 model; model.translate(0, 0, 0.0); model.rotate(AngleX, 1.0, 0.0, 0.0); model.rotate(AngleY, 0.0, 1.0, 0.0); model.rotate(AngleZ, 0.0, 0.0, 1.0); model.scale(0.42); QMatrix3x3 normalMatrix = model.normalMatrix(); Shader.setUniformValue("model", model); Shader.setUniformValue("normalMatrix", normalMatrix); VertexBuff->bind(); GLint attribute; GLint offset = 0; attribute = Shader.attributeLocation("gl_Vertex"); Shader.enableAttributeArray(attribute); Shader.setAttributeBuffer(attribute, GL_FLOAT, offset, 3, sizeof(TVertex)); offset += sizeof(QVector3D); attribute = Shader.attributeLocation("gl_Normal"); Shader.enableAttributeArray(attribute); Shader.setAttributeBuffer(attribute, GL_FLOAT, offset, 3, sizeof(TVertex)); offset += sizeof(QVector3D); attribute = Shader.attributeLocation("vertTexCoord"); Shader.enableAttributeArray(attribute); Shader.setAttributeBuffer(attribute, GL_FLOAT, offset, 2, sizeof(TVertex)); offset += sizeof(QVector2D); attribute = Shader.attributeLocation("tangent"); Shader.enableAttributeArray(attribute); Shader.setAttributeBuffer(attribute, GL_FLOAT, offset, 3, sizeof(TVertex)); offset += sizeof(QVector3D); attribute = Shader.attributeLocation("bitangent"); Shader.enableAttributeArray(attribute); Shader.setAttributeBuffer(attribute, GL_FLOAT, offset, 3, sizeof(TVertex)); offset += sizeof(QVector3D); VertexBuff->release(); Texture->bind(0, QOpenGLTexture::ResetTextureUnit); Shader.setUniformValue("texture", 0); NormalMap->bind(1, QOpenGLTexture::ResetTextureUnit); Shader.setUniformValue("normalMap", 1); glDrawArrays(GL_TRIANGLES, 0, 3 * ObjectSize); Shader.disableAttributeArray("gl_Vertex"); Shader.disableAttributeArray("gl_Normal"); Shader.disableAttributeArray("vertTexCoord"); Shader.disableAttributeArray("tangent"); Shader.disableAttributeArray("bitangent"); Texture->release(0, QOpenGLTexture::ResetTextureUnit); NormalMap->release(1, QOpenGLTexture::ResetTextureUnit); Shader.disableAttributeArray("coord2d"); Shader.disableAttributeArray("v_color"); Shader.release(); /* /// DEBUG INFO QMatrix4x4 modelView = view * model; glMatrixMode(GL_PROJECTION); glLoadMatrixf(projection.data()); glMatrixMode(GL_MODELVIEW); glLoadMatrixf(modelView.data()); // glDisable(GL_DEPTH_TEST); glColor3f(1, 1, 1); glBegin(GL_LINES); for (size_t i = 0; i < Obj.size(); i += 3) { const TVertex& v1 = Obj[i]; const TVertex& v2 = Obj[i + 1]; const TVertex& v3 = Obj[i + 2]; glVertex3f(v1.Position.x(), v1.Position.y(), v1.Position.z()); glVertex3f(v2.Position.x(), v2.Position.y(), v2.Position.z()); glVertex3f(v1.Position.x(), v1.Position.y(), v1.Position.z()); glVertex3f(v3.Position.x(), v3.Position.y(), v3.Position.z()); glVertex3f(v2.Position.x(), v2.Position.y(), v2.Position.z()); glVertex3f(v3.Position.x(), v3.Position.y(), v3.Position.z()); } glEnd(); // normals glColor3f(0,0,1); glBegin(GL_LINES); for (size_t i = 0; i < Obj.size(); ++i) { const TVertex& v = Obj[i]; QVector3D p = v.Position; p *= 1.02; glVertex3f(p.x(), p.y(), p.z()); QVector3D n = v.Normal.normalized(); p += n * 0.8; glVertex3f(p.x(), p.y(), p.z()); } glEnd(); // tangent glColor3f(1,0,0); glBegin(GL_LINES); for (size_t i = 0; i < Obj.size(); ++i) { const TVertex& v = Obj[i]; QVector3D p = v.Position; p *= 1.02; glVertex3f(p.x(), p.y(), p.z()); QVector3D n = v.Tangent.normalized(); p += n * 0.8; glVertex3f(p.x(), p.y(), p.z()); } glEnd(); // bitangent glColor3f(0,1,0); glBegin(GL_LINES); for (size_t i = 0; i < Obj.size(); ++i) { const TVertex& v = Obj[i]; QVector3D p = v.Position; p *= 1.02; glVertex3f(p.x(), p.y(), p.z()); QVector3D n = v.Bitangent.normalized(); p += n * 0.3; glVertex3f(p.x(), p.y(), p.z()); } glEnd(); */ Fbo->release(); }
void GLWidget::paintMesh() { QMatrix4x4 mMatrix; QMatrix4x4 vMatrix; QMatrix4x4 cameraTransformation; cameraTransformation.rotate(alpha, 0, 1, 0); cameraTransformation.rotate(beta, 1, 0, 0); QVector3D cameraPosition = cameraTransformation * QVector3D(0, 0, distance); QVector3D cameraUpDirection = cameraTransformation * QVector3D(0, 1, 0); vMatrix.lookAt(cameraPosition, lastCenterPosition, cameraUpDirection); mMatrix.setToIdentity(); QMatrix4x4 mvMatrix; mvMatrix = vMatrix * mMatrix; QMatrix3x3 normalMatrix; normalMatrix = mvMatrix.normalMatrix(); QMatrix4x4 lightTransformation; lightTransformation.rotate(lightAngle, 0, 1, 0); QVector3D lightPosition = lightTransformation * QVector3D(0, 10, 10); shaderProgram.bind(); shaderProgram.setUniformValue("mvpMatrix", pMatrix * mvMatrix); shaderProgram.setUniformValue("mvMatrix", mvMatrix); shaderProgram.setUniformValue("normalMatrix", normalMatrix); shaderProgram.setUniformValue("lightPosition", vMatrix * lightPosition); shaderProgram.setUniformValue("ambientColor", QColor(32, 32, 32)); shaderProgram.setUniformValue("diffuseColor", QColor(128, 128, 128)); shaderProgram.setUniformValue("specularColor", QColor(255, 255, 255)); shaderProgram.setUniformValue("ambientReflection", (GLfloat) 1.0); shaderProgram.setUniformValue("diffuseReflection", (GLfloat) 1.0); shaderProgram.setUniformValue("specularReflection", (GLfloat) 1.0); shaderProgram.setUniformValue("shininess", (GLfloat) 100.0); glPointSize(INITIAL_POINT_SIZE); renderGrid(); renderMesh(mode); shaderProgram.release(); mMatrix.setToIdentity(); mMatrix.translate(lightPosition); mMatrix.rotate(lightAngle, 0, 1, 0); mMatrix.rotate(45, 1, 0, 0); // mMatrix.scale(0.1); coloringShaderProgram.bind(); coloringShaderProgram.setUniformValue("mvpMatrix", pMatrix * vMatrix * mMatrix); coloringShaderProgram.setAttributeArray("vertex", lightSource.getSpotlightVertices().constData()); coloringShaderProgram.enableAttributeArray("vertex"); coloringShaderProgram.setAttributeArray("color", lightSource.getSpotlightColors().constData()); coloringShaderProgram.enableAttributeArray("color"); glDrawArrays(GL_TRIANGLES, 0, lightSource.getSpotlightVertices().size()); coloringShaderProgram.disableAttributeArray("vertex"); coloringShaderProgram.disableAttributeArray("color"); coloringShaderProgram.release(); }
bool SegmentListOLCI::TestForSegmentGLerr(int x, int realy, float distance, const QMatrix4x4 &m, bool showallsegments, QString &segmentname) { bool isselected = false; qDebug() << QString("Nbr of segments = %1").arg(segmentlist.count()); QList<Segment*>::iterator segit = segmentlist.begin(); QVector2D winvec1, winvec2, winvecend1, winvecend2, winvecend3, winvecend4; QVector3D vecZ = m.row(2).toVector3D(); segmentname = ""; while ( segit != segmentlist.end() ) { if(showallsegments ? true : (*segit)->segmentshow) { for(int i = 0; i < (*segit)->winvectorfirst.length()-1; i++) { winvecend1.setX((*segit)->winvectorfirst.at(i).x()); winvecend1.setY((*segit)->winvectorfirst.at(i).y()); winvecend2.setX((*segit)->winvectorfirst.at(i+1).x()); winvecend2.setY((*segit)->winvectorfirst.at(i+1).y()); winvecend3.setX((*segit)->winvectorlast.at(i).x()); winvecend3.setY((*segit)->winvectorlast.at(i).y()); winvecend4.setX((*segit)->winvectorlast.at(i+1).x()); winvecend4.setY((*segit)->winvectorlast.at(i+1).y()); // first last // winvecend1 ------------------------------------ winvecend3 // | p01 | p03 // | | // | | // | | // | | // | | // | p02 | p04 // winvecend2 ------------------------------------ winvecend4 // qreal angle = ArcCos(QVector3D::dotProduct( vecZ, (*segit)->vecvector.at(i))); //qDebug() << QString("angle = %1").arg(angle * 180.0 / PI); if (angle < PI/2 + (asin(1/distance))) { struct point p01; p01.x = (int)winvecend1.x(); p01.y = (int)winvecend1.y(); struct point p02; p02.x = (int)winvecend2.x(); p02.y = (int)winvecend2.y(); struct point p03; p03.x = (int)winvecend3.x(); p03.y = (int)winvecend3.y(); struct point p04; p04.x = (int)winvecend4.x(); p04.y = (int)winvecend4.y(); QPoint points[4] = { QPoint(p01.x, p01.y), QPoint(p02.x, p02.y), QPoint(p04.x, p04.y), QPoint(p03.x, p03.y) }; int result = pnpoly( 4, points, x, realy); if (result) { if((*segit)->ToggleSelected()) { qDebug() << QString("segment selected is = %1").arg((*segit)->fileInfo.fileName()); isselected = true; segmentname = (*segit)->fileInfo.fileName(); qApp->processEvents(); } break; } } } } ++segit; } return isselected; }
void RayCastRenderer::render_impl(const QQuaternion & rotation, const QVector3D & scale, const QVector3D & translation, const QQuaternion & /* camera_rotation */, GLuint /* vbo_positions */, GLuint /* vbo_colors */, size_t /* part_cnt */, const QVector3D & volume_size) //float peel_depth, //int detail { if (!isDataValid()) { WARNM("Not rendering because: Failed to create 3D texture for data"); return; } // Transformacna model-view matica QMatrix4x4 mv; mv.translate(0.0f, 0.0f, -1.0f); mv.translate(translation); mv.rotate(rotation); mv.scale(scale); // Uprava rozmerov volumetrickych dat, tak aby presne sedeli na jednotkovu kocku float max_size = std::max(volume_size.x(), std::max(volume_size.y(), volume_size.z())); mv.scale((volume_size.x() / max_size), (volume_size.y() / max_size), (volume_size.z() / max_size)); mv.scale(volume_size.x(), volume_size.y(), volume_size.z()); //mv.scale(volume_size.x() / 2.0f, volume_size.y() / 2.0f, volume_size.z() / 2.0f); //mv.scale(volume_size.x() / 4.0f, volume_size.y() / 4.0f, volume_size.z() / 4.0f); //mv.scale(volume_size.x() / 8.0f, volume_size.y() / 8.0f, volume_size.z() / 8.0f); // nabindovanie textur, geometrie, povolenie cullingu, depth testovania a HW blendingu (robi sa v shaderi) OGLF->glActiveTexture(GL_TEXTURE0); OGLF->glBindTexture(GL_TEXTURE_1D, m_transfer_func.textureId()); OGLF->glActiveTexture(GL_TEXTURE1); OGLF->glBindTexture(GL_TEXTURE_2D, m_color_attach); OGLF->glActiveTexture(GL_TEXTURE2); OGLF->glBindTexture(GL_TEXTURE_3D, m_data.textureId()); m_vao.bind(); OGLF->glEnable(GL_DEPTH_TEST); OGLF->glDepthMask(GL_FALSE); OGLF->glEnable(GL_CULL_FACE); // blending je potreba povolit, aby neboli casti ciar z bounding box-u prekryte // farbou vzduchu vo volumetrickych datach OGLF->glEnable(GL_BLEND); //OGLF->glDisable(GL_BLEND); // Kreslenie sceny do framebufferu (vygenerovanie exit pointov)s OGLF->glBindFramebuffer(GL_FRAMEBUFFER, m_fbo); OGLF->glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); OGLF->glCullFace(GL_FRONT); m_prog_gen_back_faces.bind(); m_prog_gen_back_faces.setUniformValue("mvp", m_proj * mv); OGLF->glDrawElements(GL_TRIANGLES, g_cube_indices_cnt, GL_UNSIGNED_INT, nullptr); // Ray-casting OGLF->glBindFramebuffer(GL_FRAMEBUFFER, m_default_fbo); // Toto uz netreba, pretoze defaultny frame buffer clearuje base class // a pripadne este aj kresli bounding box ak treba //OGLF->glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); OGLF->glCullFace(GL_BACK); int detail = 1000; //5000; float default_step = 1.0f / max_size; float step; if (detail <= 0) step = default_step; else step = 1.0f / float(detail); //qDebug() << "step=" << step << ", default_step=" << default_step << ", correction factor=" << (step / default_step); m_prog_ray_cast.bind(); m_prog_ray_cast.setUniformValue("mvp", m_proj * mv); m_prog_ray_cast.setUniformValue("step", step); //m_prog_ray_cast.setUniformValue("offset", peel_depth); m_prog_ray_cast.setUniformValue("offset", 0.0f); m_prog_ray_cast.setUniformValue("alpha_correction_factor", step / default_step); m_prog_ray_cast.setUniformValue("tex_transfer_func", 0); m_prog_ray_cast.setUniformValue("tex_back_faces", 1); m_prog_ray_cast.setUniformValue("tex_volume_data", 2); //m_prog_ray_cast.setUniformValue("use_tf", m_use_transfer_func); if (m_use_lighting && m_use_transfer_func) { m_prog_ray_cast.setUniformValue("method", 1); m_prog_ray_cast.setUniformValue("La", m_light_ambient_col); m_prog_ray_cast.setUniformValue("Ld", m_light_diffuse_col); m_prog_ray_cast.setUniformValue("light_pos", m_light_pos); } else if (m_use_transfer_func) { m_prog_ray_cast.setUniformValue("method", 2); } else { m_prog_ray_cast.setUniformValue("method", 3); } OGLF->glEnable(GL_DEPTH_TEST); OGLF->glDrawElements(GL_TRIANGLES, g_cube_indices_cnt, GL_UNSIGNED_INT, nullptr); // Odbindovanie programu, geometrie, textur a zakazanie cullingu OGLF->glUseProgram(0); OGLF->glDisable(GL_BLEND); OGLF->glDisable(GL_CULL_FACE); OGLF->glDepthMask(GL_TRUE); OGLF->glDisable(GL_DEPTH_TEST); OGLF->glBindVertexArray(0); OGLF->glActiveTexture(GL_TEXTURE2); OGLF->glBindTexture(GL_TEXTURE_3D, 0); OGLF->glActiveTexture(GL_TEXTURE1); OGLF->glBindTexture(GL_TEXTURE_2D, 0); OGLF->glActiveTexture(GL_TEXTURE0); OGLF->glBindTexture(GL_TEXTURE_1D, 0); }
void TriangleWindow::render() { const qreal retinaScale = devicePixelRatio(); glViewport(0, 0, width() * retinaScale, height() * retinaScale); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glEnable(GL_VERTEX_PROGRAM_POINT_SIZE); //glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); m_program->bind(); QMatrix4x4 matrix; matrix.perspective(60.0f, 1.0 * _width/_height, 0.1f, 300.0f); matrix.translate(_camX, _camY, _camZ); matrix.rotate(20, 1, 0, 0); matrix.rotate(_angle, 0, 1, 0); matrix.translate(-70, 0, -60); m_program->setUniformValue(m_matrixUniform, matrix); vao.bind(); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, texture->textureId()); glDrawArrays(GL_TRIANGLES, 0, _map.size()); vao.release(); m_program->release(); if(allSeasons[currentSeason] == "WINTER") { _fall->setPointSize(4.0); _fall->setFaster(0.0); _fall->setPointColor(QVector4D(0.9, 0.9, 0.9, 0.0)); } else if(allSeasons[currentSeason] == "AUTUMN") { _fall->setPointSize(1.0); _fall->setFaster(1.0); _fall->setPointColor(QVector4D(0.0, 0.9, 0.9, 0.5)); } else return; particuleShader->bind(); particuleShader->setUniformValue(particuleMatrixUniform, matrix); particuleShader->setUniformValue(particulePointSize, _fall->getPointSize()); particuleShader->setUniformValue(particulePointColor, _fall->getPointColor()); fallVao.bind(); fallVbo.bind(); size_t fallSize = _fall->getParticules().size()*sizeof(QVector3D); fallVbo.write(0, _fall->getParticules().constData(), fallSize); glDrawArrays(GL_POINTS, 0, _fall->getParticules().size()); fallVao.release(); particuleShader->release(); ++m_frame; }
void SegmentListOLCI::ShowWinvec(QPainter *painter, float distance, const QMatrix4x4 modelview) { QList<Segment*>::iterator segit = segmentlist.begin(); QVector2D winvecend1, winvecend2, winvecend3, winvecend4; QVector3D vecZ = modelview.row(2).toVector3D(); // static GLfloat mat[16]; // const float *data = modelview.constData(); // for (int index = 0; index < 16; ++index) // mat[index] = data[index]; //modelview.inverted( &ok ); while ( segit != segmentlist.end() ) { if( (*segit)->segmentshow) { for(int i = 0; i < (*segit)->winvectorfirst.length()-1; i++) { winvecend1.setX((*segit)->winvectorfirst.at(i).x()); winvecend1.setY((*segit)->winvectorfirst.at(i).y()); winvecend2.setX((*segit)->winvectorfirst.at(i+1).x()); winvecend2.setY((*segit)->winvectorfirst.at(i+1).y()); winvecend3.setX((*segit)->winvectorlast.at(i).x()); winvecend3.setY((*segit)->winvectorlast.at(i).y()); winvecend4.setX((*segit)->winvectorlast.at(i+1).x()); winvecend4.setY((*segit)->winvectorlast.at(i+1).y()); //qDebug() << "winvec1 x = " << winvec1.x() << " y = " << winvec1.y(); // first last // winvecend1 ------------------------------------ winvecend3 // | p01 | p03 // | | // | | // | | // | | // | | // | p02 | p04 // winvecend2 ------------------------------------ winvecend4 // qreal angle = ArcCos(QVector3D::dotProduct( vecZ, (*segit)->vecvector.at(i))); if (angle < PI/2) // + (asin(1/distance))) { painter->drawLine((int)winvecend1.x(), (painter->device())->height() - (int)winvecend1.y(), (int)winvecend3.x(), (painter->device())->height() - (int)winvecend3.y() ); painter->drawLine((int)winvecend1.x(), (painter->device())->height() - (int)winvecend1.y(), (int)winvecend2.x(), (painter->device())->height() - (int)winvecend2.y() ); painter->drawLine((int)winvecend3.x(), (painter->device())->height() - (int)winvecend3.y(), (int)winvecend4.x(), (painter->device())->height() - (int)winvecend4.y() ); // painter->drawLine((int)winvec1.x(), (painter->device())->height() - (int)winvec1.y(), (int)winvecend1.x(), (painter->device())->height() - (int)winvecend1.y() ); // painter->drawLine((int)winvec2.x(), (painter->device())->height() - (int)winvec2.y(), (int)winvecend2.x(), (painter->device())->height() - (int)winvecend2.y() ); // painter->drawLine((int)winvec1.x(), (painter->device())->height() - (int)winvec1.y(), (int)winvecend3.x(), (painter->device())->height() - (int)winvecend3.y() ); // painter->drawLine((int)winvec2.x(), (painter->device())->height() - (int)winvec2.y(), (int)winvecend4.x(), (painter->device())->height() - (int)winvecend4.y() ); } } } ++segit; } }
void Canvas::paintGL() { #ifndef NDEBUG logToFile("Painting started."); #endif gl()->glClear(GL_COLOR_BUFFER_BIT); if (ready()) { // Calculate the transformMatrix. double ratio = samplesRecorded/getInfoTable()->getVirtualWidth(); QMatrix4x4 matrix; matrix.ortho(QRectF(getInfoTable()->getPosition()*ratio, 0, width()*ratio, height())); gl()->glUseProgram(signalProgram->getGLProgram()); GLuint location = gl()->glGetUniformLocation(signalProgram->getGLProgram(), "transformMatrix"); checkNotErrorCode(location, static_cast<GLuint>(-1), "glGetUniformLocation() failed."); gl()->glUniformMatrix4fv(location, 1, GL_FALSE, matrix.data()); gl()->glUseProgram(eventProgram->getGLProgram()); location = gl()->glGetUniformLocation(eventProgram->getGLProgram(), "transformMatrix"); checkNotErrorCode(location, static_cast<GLuint>(-1), "glGetUniformLocation() failed."); gl()->glUniformMatrix4fv(location, 1, GL_FALSE, matrix.data()); location = gl()->glGetUniformLocation(eventProgram->getGLProgram(), "divideBy"); checkNotErrorCode(location, static_cast<GLuint>(-1), "glGetUniformLocation() failed."); gl()->glUniform1i(location, eventMode); location = gl()->glGetUniformLocation(eventProgram->getGLProgram(), "eventWidth"); checkNotErrorCode(location, static_cast<GLuint>(-1), "glGetUniformLocation() failed."); gl()->glUniform1f(location, 0.45*height()/signalProcessor->getTrackCount()); gl()->glUseProgram(rectangleLineProgram->getGLProgram()); location = gl()->glGetUniformLocation(rectangleLineProgram->getGLProgram(), "transformMatrix"); checkNotErrorCode(location, static_cast<GLuint>(-1), "glGetUniformLocation() failed."); gl()->glUniformMatrix4fv(location, 1, GL_FALSE, matrix.data()); // Create the data block range needed. int firstSample = static_cast<unsigned int>(floor(getInfoTable()->getPosition()*ratio)); int lastSample = static_cast<unsigned int>(ceil((getInfoTable()->getPosition() + width())*ratio)); auto fromTo = DataFile::sampleRangeToBlockRange(make_pair(firstSample, lastSample), signalProcessor->getBlockSize()); set<int> indexSet; for (int i = fromTo.first; i <= fromTo.second; ++i) { indexSet.insert(i); } // Get events. vector<tuple<int, int, int>> allChannelEvents; vector<tuple<int, int, int, int>> singleChannelEvents; currentEventTable()->getEventsForRendering(firstSample, lastSample, &allChannelEvents, &singleChannelEvents); // Draw. drawTimeLines(); drawAllChannelEvents(allChannelEvents); while (indexSet.empty() == false) { SignalBlock block = signalProcessor->getAnyBlock(indexSet); drawSingleChannelEvents(block, singleChannelEvents); drawSignal(block); gl()->glFlush(); indexSet.erase(block.getIndex()); //logToFile("Block " << block.getIndex() << " painted."); } drawPositionIndicator(); drawCross(); glBindVertexArray(0); } gl()->glFinish(); checkGLMessages(); #ifndef NDEBUG logToFile("Painting finished."); #endif }
void GraphicsLayer13::setModelview(const QMatrix4x4& matrix) { GLfloat modelview[16]; convertMatrix(matrix.constData(), modelview); glLoadMatrixf(modelview); }
/*! Returns the spotDirection() for this light after transforming it from world co-ordinates to eye co-ordinates using the top-left 3x3 submatrix within \a transform. The returned result is suitable to be applied to the GL_SPOT_DIRECTION property of \c{glLight()}, assuming that the modelview transformation in the GL context is set to the identity. \sa eyePosition() */ QVector3D QGLLightParameters::eyeSpotDirection (const QMatrix4x4& transform) const { Q_D(const QGLLightParameters); return transform.mapVector(d->spotDirection); }
//! [3] void GlWidget::paintGL() { //! [3] glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); QMatrix4x4 mMatrix; QMatrix4x4 vMatrix; QMatrix4x4 cameraTransformation; cameraTransformation.rotate(alpha, 0, 1, 0); cameraTransformation.rotate(beta, 1, 0, 0); QVector3D cameraPosition = cameraTransformation * QVector3D(0, 0, distance); QVector3D cameraUpDirection = cameraTransformation * QVector3D(0, 1, 0); vMatrix.lookAt(cameraPosition, QVector3D(0, 0, 0), cameraUpDirection); mMatrix.setToIdentity(); QMatrix4x4 mvMatrix; mvMatrix = vMatrix * mMatrix; QMatrix3x3 normalMatrix; normalMatrix = mvMatrix.normalMatrix(); QMatrix4x4 lightTransformation; lightTransformation.rotate(lightAngle, 0, 1, 0); QVector3D lightPosition = lightTransformation * QVector3D(0, 1, 1); lightingShaderProgram.bind(); lightingShaderProgram.setUniformValue("mvpMatrix", pMatrix * mvMatrix); lightingShaderProgram.setUniformValue("mvMatrix", mvMatrix); lightingShaderProgram.setUniformValue("normalMatrix", normalMatrix); lightingShaderProgram.setUniformValue("lightPosition", vMatrix * lightPosition); lightingShaderProgram.setUniformValue("ambientColor", QColor(32, 32, 32)); lightingShaderProgram.setUniformValue("diffuseColor", QColor(128, 128, 128)); lightingShaderProgram.setUniformValue("specularColor", QColor(255, 255, 255)); lightingShaderProgram.setUniformValue("ambientReflection", (GLfloat) 1.0); lightingShaderProgram.setUniformValue("diffuseReflection", (GLfloat) 1.0); lightingShaderProgram.setUniformValue("specularReflection", (GLfloat) 1.0); lightingShaderProgram.setUniformValue("shininess", (GLfloat) 100.0); lightingShaderProgram.setUniformValue("texture", 0); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, cubeTexture); glActiveTexture(0); //! [4] cubeBuffer.bind(); int offset = 0; lightingShaderProgram.setAttributeBuffer("vertex", GL_FLOAT, offset, 3, 0); lightingShaderProgram.enableAttributeArray("vertex"); offset += numCubeVertices * 3 * sizeof(GLfloat); lightingShaderProgram.setAttributeBuffer("normal", GL_FLOAT, offset, 3, 0); lightingShaderProgram.enableAttributeArray("normal"); offset += numCubeVertices * 3 * sizeof(GLfloat); lightingShaderProgram.setAttributeBuffer("textureCoordinate", GL_FLOAT, offset, 2, 0); lightingShaderProgram.enableAttributeArray("textureCoordinate"); cubeBuffer.release(); glDrawArrays(GL_TRIANGLES, 0, numCubeVertices); //! [4] lightingShaderProgram.disableAttributeArray("vertex"); lightingShaderProgram.disableAttributeArray("normal"); lightingShaderProgram.disableAttributeArray("textureCoordinate"); lightingShaderProgram.release(); mMatrix.setToIdentity(); mMatrix.translate(lightPosition); mMatrix.rotate(lightAngle, 0, 1, 0); mMatrix.rotate(45, 1, 0, 0); mMatrix.scale(0.1); coloringShaderProgram.bind(); coloringShaderProgram.setUniformValue("mvpMatrix", pMatrix * vMatrix * mMatrix); //! [5] spotlightBuffer.bind(); offset = 0; coloringShaderProgram.setAttributeBuffer("vertex", GL_FLOAT, offset, 3, 0); coloringShaderProgram.enableAttributeArray("vertex"); offset += numSpotlightVertices * 3 * sizeof(GLfloat); coloringShaderProgram.setAttributeBuffer("color", GL_FLOAT, offset, 3, 0); coloringShaderProgram.enableAttributeArray("color"); spotlightBuffer.release(); glDrawArrays(GL_TRIANGLES, 0, numSpotlightVertices); //! [5] coloringShaderProgram.disableAttributeArray("vertex"); coloringShaderProgram.disableAttributeArray("color"); coloringShaderProgram.release(); //! [6] }
void MainWidget::paintGL() { makeCurrent(); QPainter painter; painter.begin(this); painter.beginNativePainting(); glClearColor(0.0f, 0.0f, 0.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Enable depth buffer if(bDepthTest) glEnable(GL_DEPTH_TEST); QQuaternion quat = this->trackball.rotation(); // Calculate model view transformation QMatrix4x4 modelviewearth; modelviewearth.translate(0.0, 0.0, distance); modelviewearth.rotate(quat); QMatrix4x4 rotmatrix; rotmatrix.rotate(quat); programskybox.bind(); skybox->render(projection, modelviewearth, rotmatrix); programskybox.release(); if(bWireFrame) // Draw as wireframe glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); else glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); if(bTexture) { if(bNoBump) { programearthnobump.bind(); textureearth->bind(0); geometries->render(projection, modelviewearth, bNoBump); textureearth->release(); programearthnobump.release(); } else { programearth.bind(); textureearth->bind(0); texturenormal->bind(1); geometries->render(projection, modelviewearth, bNoBump); texturenormal->release(); textureearth->release(); programearth.release(); } } glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); if(bBorders) { programgshhs.bind(); gshhs->render(projection, modelviewearth); gshhs->rendersoc(projection, modelviewearth); programgshhs.release(); } glDisable(GL_DEPTH_TEST); painter.endNativePainting(); QString framesPerSecond; if (const int elapsed = m_time.elapsed()) { framesPerSecond.setNum(m_frames /(elapsed / 1000.0), 'f', 2); painter.setPen(Qt::white); painter.drawText(20, 40, framesPerSecond + " paintGL calls / s"); } //this->setWindowTitle(framesPerSecond + " paintGL calls / s" ); painter.end(); if (!(m_frames % 100)) { m_time.start(); m_frames = 0; } ++m_frames; }
void MyGLWidget::draw() { #ifdef MOBILE_OS const qreal retinaScale = devicePixelRatio(); glViewport(0, 0, width() * retinaScale, height() * retinaScale); glClear(GL_COLOR_BUFFER_BIT); m_program->bind(); QMatrix4x4 matrix; matrix.ortho(0.0f,width(), 0.f,height(), -1, 1); m_program->setUniformValue(m_matrixUniform, matrix); GLfloat vertices[] = { 0.0f, 0.f, 0.0f, 100.f, 100.0f, 0.0f, }; GLfloat colors[] = { 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, }; GLfloat texts[] = { 0.0f, 0.f, 0.0f, 1.f, 1.0f, 0.0f }; auto obj = m_app_seg.get_dsc_obj(); static GLfloat vptr[100000];// = new GLfloat[obj.get_no_faces()*3*2]; static GLfloat cptr[100000];// = new GLfloat[obj.get_no_faces()*3*3]; int idx = 0; for(auto fkey : obj->faces()){ auto tris = obj->get_pos(fkey); for(int i = 0; i < 3; i++){ auto v = tris[i]; vptr[idx*6 + i*2 + 0] = v[0]; vptr[idx*6 + i*2 + 1] = v[1]; cptr[idx*9 + i*3 + 0] = v[0]/600.f; cptr[idx*9 + i*3 + 1] = v[0]/600.f; cptr[idx*9 + i*3 + 2] = v[0]/600.f; } idx ++; } // for(int i = 0; i < obj.get_no_faces()*3; i++){ // printf("%f %f %f %f %f\n", vptr[i*2], vptr[i*2 + 1], // cptr[i*3], cptr[i*3 + 1], cptr[i*3 + 2]); // } // glVertexAttribPointer(m_posAttr, 2, GL_FLOAT, GL_FALSE, 0, vptr); // glVertexAttribPointer(m_colAttr, 3, GL_FLOAT, GL_FALSE, 0, cptr); // glEnableVertexAttribArray(0); // glEnableVertexAttribArray(1); // glDrawArrays(GL_TRIANGLES, 0, obj->get_no_faces()*3); // glDisableVertexAttribArray(1); // glDisableVertexAttribArray(0); static GLfloat edge_v[10000]; GLfloat edge_cl[10000]; int eidx = 0; for(auto ekey : obj->halfedges()){ auto hew = obj->walker(ekey); { Vec2 v0 = obj->get_pos(hew.vertex()); Vec2 v1 = obj->get_pos(hew.opp().vertex()); edge_v[eidx*4] = v0[0]; edge_v[eidx*4 + 1] = v0[1]; edge_v[eidx*4 + 2] = v1[0]; edge_v[eidx*4 + 3] = v1[1]; for(int i = 0; i < 2; i++){ edge_cl[eidx*6 + i*3] = 1.0; edge_cl[eidx*6 + i*3 + 1] = 0.0; edge_cl[eidx*6 + i*3 + 2] = 0.0; } } eidx++; } int num = obj->get_no_halfedges(); cout << num; // for(int i = 0; i < obj->get_no_halfedges(); i++){ // printf("%f %f %f %f %f\n", edge_v[i*2], edge_v[i*2 + 1], // edge_cl[i*3], edge_cl[i*3 + 1], edge_cl[i*3 + 2]); // } glVertexAttribPointer(m_posAttr, 2, GL_FLOAT, GL_FALSE, 0, edge_v); glVertexAttribPointer(m_colAttr, 3, GL_FLOAT, GL_FALSE, 0, edge_cl); glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); glDrawArrays(GL_LINES, 0, 2*obj->get_no_halfedges()); glDisableVertexAttribArray(1); glDisableVertexAttribArray(0); m_program->release(); ++m_frame; printf("Display: %d \n", m_frame); #else qglColor(Qt::red); glBegin(GL_QUADS); glNormal3f(0,0,-1); glVertex3f(-1,-1,0); glVertex3f(-1,1,0); glVertex3f(1,1,0); glVertex3f(1,-1,0); glEnd(); glBegin(GL_TRIANGLES); glNormal3f(0,-1,0.707); glVertex3f(-1,-1,0); glVertex3f(1,-1,0); glVertex3f(0,0,1.2); glEnd(); glBegin(GL_TRIANGLES); glNormal3f(1,0, 0.707); glVertex3f(1,-1,0); glVertex3f(1,1,0); glVertex3f(0,0,1.2); glEnd(); glBegin(GL_TRIANGLES); glNormal3f(0,1,0.707); glVertex3f(1,1,0); glVertex3f(-1,1,0); glVertex3f(0,0,1.2); glEnd(); glBegin(GL_TRIANGLES); glNormal3f(-1,0,0.707); glVertex3f(-1,1,0); glVertex3f(-1,-1,0); glVertex3f(0,0,1.2); glEnd(); #endif }
void Renderer::render() { if (m_exiting) return; QOpenGLContext *ctx = m_glwidget->context(); if (!ctx) // QOpenGLWidget not yet initialized return; // Grab the context. m_grabMutex.lock(); emit contextWanted(); m_grabCond.wait(&m_grabMutex); QMutexLocker lock(&m_renderMutex); m_grabMutex.unlock(); if (m_exiting) return; Q_ASSERT(ctx->thread() == QThread::currentThread()); // Make the context (and an offscreen surface) current for this thread. The // QOpenGLWidget's fbo is bound in the context. m_glwidget->makeCurrent(); if (!m_inited) { m_inited = true; initializeOpenGLFunctions(); QMutexLocker initLock(initMutex()); QOpenGLShader *vshader = new QOpenGLShader(QOpenGLShader::Vertex, this); const char *vsrc = "attribute highp vec4 vertex;\n" "attribute mediump vec3 normal;\n" "uniform mediump mat4 matrix;\n" "varying mediump vec4 color;\n" "void main(void)\n" "{\n" " vec3 toLight = normalize(vec3(0.0, 0.3, 1.0));\n" " float angle = max(dot(normal, toLight), 0.0);\n" " vec3 col = vec3(0.40, 1.0, 0.0);\n" " color = vec4(col * 0.2 + col * 0.8 * angle, 1.0);\n" " color = clamp(color, 0.0, 1.0);\n" " gl_Position = matrix * vertex;\n" "}\n"; vshader->compileSourceCode(vsrc); QOpenGLShader *fshader = new QOpenGLShader(QOpenGLShader::Fragment, this); const char *fsrc = "varying mediump vec4 color;\n" "void main(void)\n" "{\n" " gl_FragColor = color;\n" "}\n"; fshader->compileSourceCode(fsrc); program.addShader(vshader); program.addShader(fshader); program.link(); vertexAttr = program.attributeLocation("vertex"); normalAttr = program.attributeLocation("normal"); matrixUniform = program.uniformLocation("matrix"); m_fAngle = 0; m_fScale = 1; createGeometry(); vbo.create(); vbo.bind(); const int verticesSize = vertices.count() * 3 * sizeof(GLfloat); vbo.allocate(verticesSize * 2); vbo.write(0, vertices.constData(), verticesSize); vbo.write(verticesSize, normals.constData(), verticesSize); m_elapsed.start(); } //qDebug("%p elapsed %lld", QThread::currentThread(), m_elapsed.restart()); glClearColor(0.1f, 0.2f, 0.2f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glFrontFace(GL_CW); glCullFace(GL_FRONT); glEnable(GL_CULL_FACE); glEnable(GL_DEPTH_TEST); QMatrix4x4 modelview; modelview.rotate(m_fAngle, 0.0f, 1.0f, 0.0f); modelview.rotate(m_fAngle, 1.0f, 0.0f, 0.0f); modelview.rotate(m_fAngle, 0.0f, 0.0f, 1.0f); modelview.scale(m_fScale); modelview.translate(0.0f, -0.2f, 0.0f); program.bind(); program.setUniformValue(matrixUniform, modelview); paintQtLogo(); program.release(); glDisable(GL_DEPTH_TEST); glDisable(GL_CULL_FACE); m_fAngle += 1.0f; // Make no context current on this thread and move the QOpenGLWidget's // context back to the gui thread. m_glwidget->doneCurrent(); ctx->moveToThread(qGuiApp->thread()); // Schedule composition. Note that this will use QueuedConnection, meaning // that update() will be invoked on the gui thread. QMetaObject::invokeMethod(m_glwidget, "update"); }
void set_transform(QMatrix4x4 m) { m_trans = m; m_invtrans = m.inverted(); }
// handles zoom and translation QMatrix4x4 OrthographicCamera::getViewMatrix(int width, int height) { QMatrix4x4 m; m.setToIdentity(); return m; }
void Scene::deferredRendering(RenderTarget * target) { if(target->isEnableClipPlane ()) { glEnable(GL_CLIP_PLANE0); glClipPlane(GL_CLIP_PLANE0, target->getClipPlane()); } if(!this->spotLights.empty ()) { this->shadowPassForSpot(spotLights[0],target); } if(this->directionLight.getIntensity ()>0) { this->shadowPassDirectional (target); } geometryPass(target); if(target->isEnableClipPlane ()) { glDisable(GL_CLIP_PLANE0); } glEnable(GL_BLEND); glBlendEquation(GL_FUNC_ADD); glBlendFunc(GL_ONE, GL_ONE); target->getGBuffer ()->BindForReading(bloom_fbo1->buffer ()); lightPass(target); bloom_fbo1->BindForReading (bloom_fbo2); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); pickBright(); bloom_fbo2->BindForReading (bloom_fbo3); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); gaussianBlur_H (2); bloom_fbo3->BindForReading (NULL); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); gaussianBlur_V (2); if(target->type () == RenderTarget::TargetType::ON_SCREEN) { bloom_fbo1->BindForReading (NULL); } else { bloom_fbo1->BindForReading (target->resultBuffer ()); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); } ShaderProgram * shader =ShaderPool::getInstance ()->get("deffered_simple"); shader->use (); QMatrix4x4 m; m.setToIdentity (); m_quad->setShaderProgram (shader); auto camera =target->camera (); shader->setUniformMat4v ("g_MVP_matrix",m.data ()); shader->setUniform2Float ("g_screen_size",1024,768); shader->setUniformInteger ("g_color_map",0); shader->setUniformInteger ("g_position_map",1); shader->setUniformInteger ("g_normal_map",2); if(camera) { shader->setUniform3Float ("g_eye_position", camera->pos ().x(), camera->pos ().y(), camera->pos ().z()); } m_quad->draw (true); }
QMatrix4x4 PerspectiveCamera::getViewMatrix(int width, int height) { QMatrix4x4 m; m.lookAt(eye(), lookat(), upDir()); return m; }
void Patch::rotate(qreal deg, QVector3D axis) { mat.rotate(deg, axis); }
void Viewer::drawVisualHints() { CGAL::QGLViewer::drawVisualHints(); if(d->distance_is_displayed) { glDisable(GL_DEPTH_TEST); QMatrix4x4 mvpMatrix; double mat[16]; camera()->getModelViewProjectionMatrix(mat); for(int i=0; i < 16; i++) { mvpMatrix.data()[i] = (float)mat[i]; } if(!isOpenGL_4_3()) { //draws the distance //nullifies the translation d->rendering_program_dist.bind(); d->rendering_program_dist.setUniformValue("mvp_matrix", mvpMatrix); d->rendering_program_dist.setUniformValue("point_size", GLfloat(6.0f)); d->vao.bind(); glDrawArrays(GL_POINTS, 0, static_cast<GLsizei>(2)); glDrawArrays(GL_LINES, 0, static_cast<GLsizei>(2)); d->vao.release(); d->rendering_program_dist.release(); glEnable(GL_DEPTH_TEST); } else { QOpenGLShaderProgram* program = getShaderProgram(PROGRAM_SOLID_WIREFRAME); program->bind(); QVector2D vp(width(), height()); program->setUniformValue("viewport", vp); program->setUniformValue("near",(GLfloat)camera()->zNear()); program->setUniformValue("far",(GLfloat)camera()->zFar()); program->setUniformValue("width", GLfloat(3.0f)); program->setAttributeValue("colors", QColor(Qt::black)); program->setUniformValue("mvp_matrix", mvpMatrix); QMatrix4x4 f_mat; f_mat.setToIdentity(); program->setUniformValue("f_matrix", f_mat); d->vao.bind(); glDrawArrays(GL_LINES, 0, static_cast<GLsizei>(2)); d->vao.release(); program->release(); program = getShaderProgram(PROGRAM_NO_SELECTION); program->bind(); program->setAttributeValue("colors", QColor(Qt::black)); program->setAttributeValue("point_size", 6.0f); program->setUniformValue("mvp_matrix", mvpMatrix); program->setUniformValue("f_matrix", f_mat); d->vao.bind(); glDrawArrays(GL_POINTS, 0, static_cast<GLsizei>(2)); d->vao.release(); program->release(); } } if (!d->painter->isActive()) d->painter->begin(this); //So that the text is drawn in front of everything d->painter->beginNativePainting(); glDisable(GL_DEPTH_TEST); d->painter->endNativePainting(); //Prints the displayMessage QFont font = QFont(); QFontMetrics fm(font); TextItem *message_text = new TextItem(float(10 + fm.width(d->message)/2), float(height()-20), 0, d->message, false, QFont(), Qt::gray ); if (d->_displayMessage) { d->textRenderer->addText(message_text); } d->textRenderer->draw(this); if (d->_displayMessage) d->textRenderer->removeText(message_text); }
void CoverSwitchEffect::paintScreen(int mask, QRegion region, ScreenPaintData& data) { effects->paintScreen(mask, region, data); if (mActivated || stop || stopRequested) { QMatrix4x4 origProjection; QMatrix4x4 origModelview; ShaderManager *shaderManager = ShaderManager::instance(); if (effects->numScreens() > 1) { // unfortunatelly we have to change the projection matrix in dual screen mode QRect fullRect = effects->clientArea(FullArea, activeScreen, effects->currentDesktop()); float fovy = 60.0f; float aspect = 1.0f; float zNear = 0.1f; float zFar = 100.0f; float ymax = zNear * tan(fovy * M_PI / 360.0f); float ymin = -ymax; float xmin = ymin * aspect; float xmax = ymax * aspect; float xTranslate = 0.0; float yTranslate = 0.0; float xminFactor = 1.0; float xmaxFactor = 1.0; float yminFactor = 1.0; float ymaxFactor = 1.0; if (area.x() == 0 && area.width() != fullRect.width()) { // horizontal layout: left screen xminFactor = (float)area.width() / (float)fullRect.width(); xmaxFactor = ((float)fullRect.width() - (float)area.width() * 0.5f) / ((float)fullRect.width() * 0.5f); xTranslate = (float)fullRect.width() * 0.5f - (float)area.width() * 0.5f; } if (area.x() != 0 && area.width() != fullRect.width()) { // horizontal layout: right screen xminFactor = ((float)fullRect.width() - (float)area.width() * 0.5f) / ((float)fullRect.width() * 0.5f); xmaxFactor = (float)area.width() / (float)fullRect.width(); xTranslate = (float)fullRect.width() * 0.5f - (float)area.width() * 0.5f; } if (area.y() == 0 && area.height() != fullRect.height()) { // vertical layout: top screen yminFactor = ((float)fullRect.height() - (float)area.height() * 0.5f) / ((float)fullRect.height() * 0.5f); ymaxFactor = (float)area.height() / (float)fullRect.height(); yTranslate = (float)fullRect.height() * 0.5f - (float)area.height() * 0.5f; } if (area.y() != 0 && area.height() != fullRect.height()) { // vertical layout: bottom screen yminFactor = (float)area.height() / (float)fullRect.height(); ymaxFactor = ((float)fullRect.height() - (float)area.height() * 0.5f) / ((float)fullRect.height() * 0.5f); yTranslate = (float)fullRect.height() * 0.5f - (float)area.height() * 0.5f; } QMatrix4x4 projection; projection.frustum(xmin * xminFactor, xmax * xmaxFactor, ymin * yminFactor, ymax * ymaxFactor, zNear, zFar); QMatrix4x4 modelview; modelview.translate(xTranslate, yTranslate, 0.0); if (shaderManager->isShaderBound()) { GLShader *shader = shaderManager->pushShader(ShaderManager::GenericShader); origProjection = shader->getUniformMatrix4x4("projection"); origModelview = shader->getUniformMatrix4x4("modelview"); shader->setUniform("projection", projection); shader->setUniform("modelview", origModelview * modelview); shaderManager->popShader(); } else { #ifndef KWIN_HAVE_OPENGLES glMatrixMode(GL_PROJECTION); pushMatrix(); loadMatrix(projection); glMatrixMode(GL_MODELVIEW); pushMatrix(modelview); #endif } } QList< EffectWindow* > tempList = currentWindowList; int index = tempList.indexOf(selected_window); if (animation || start || stop) { if (!start && !stop) { if (direction == Right) index++; else index--; if (index < 0) index = tempList.count() + index; if (index >= tempList.count()) index = index % tempList.count(); } foreach (Direction direction, scheduled_directions) { if (direction == Right) index++; else index--; if (index < 0) index = tempList.count() + index; if (index >= tempList.count()) index = index % tempList.count(); } } int leftIndex = index - 1; if (leftIndex < 0) leftIndex = tempList.count() - 1; int rightIndex = index + 1; if (rightIndex == tempList.count()) rightIndex = 0; EffectWindow* frontWindow = tempList[ index ]; leftWindows.clear(); rightWindows.clear(); bool evenWindows = (tempList.count() % 2 == 0) ? true : false; int leftWindowCount = 0; if (evenWindows) leftWindowCount = tempList.count() / 2 - 1; else leftWindowCount = (tempList.count() - 1) / 2; for (int i = 0; i < leftWindowCount; i++) { int tempIndex = (leftIndex - i); if (tempIndex < 0) tempIndex = tempList.count() + tempIndex; leftWindows.prepend(tempList[ tempIndex ]); } int rightWindowCount = 0; if (evenWindows) rightWindowCount = tempList.count() / 2; else rightWindowCount = (tempList.count() - 1) / 2; for (int i = 0; i < rightWindowCount; i++) { int tempIndex = (rightIndex + i) % tempList.count(); rightWindows.prepend(tempList[ tempIndex ]); } if (reflection) { // no reflections during start and stop animation // except when using a shader if ((!start && !stop) || ShaderManager::instance()->isValid()) paintScene(frontWindow, leftWindows, rightWindows, true); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); #ifndef KWIN_HAVE_OPENGLES glPolygonMode(GL_FRONT, GL_FILL); #endif QRect fullRect = effects->clientArea(FullArea, activeScreen, effects->currentDesktop()); // we can use a huge scale factor (needed to calculate the rearground vertices) // as we restrict with a PaintClipper painting on the current screen float reflectionScaleFactor = 100000 * tan(60.0 * M_PI / 360.0f) / area.width(); float vertices[] = { -area.width() * 0.5f, area.height(), 0.0, area.width() * 0.5f, area.height(), 0.0, (float)area.width()*reflectionScaleFactor, area.height(), -5000, -(float)area.width()*reflectionScaleFactor, area.height(), -5000 }; // foreground if (start) { mirrorColor[0][3] = timeLine.currentValue(); } else if (stop) { mirrorColor[0][3] = 1.0 - timeLine.currentValue(); } else { mirrorColor[0][3] = 1.0; } int y = 0; // have to adjust the y values to fit OpenGL // in OpenGL y==0 is at bottom, in Qt at top if (effects->numScreens() > 1) { QRect fullArea = effects->clientArea(FullArea, 0, 1); if (fullArea.height() != area.height()) { if (area.y() == 0) y = fullArea.height() - area.height(); else y = fullArea.height() - area.y() - area.height(); } } // use scissor to restrict painting of the reflection plane to current screen glScissor(area.x(), y, area.width(), area.height()); glEnable(GL_SCISSOR_TEST); if (shaderManager->isValid() && m_reflectionShader->isValid()) { shaderManager->pushShader(m_reflectionShader); QMatrix4x4 windowTransformation; windowTransformation.translate(area.x() + area.width() * 0.5f, 0.0, 0.0); m_reflectionShader->setUniform("windowTransformation", windowTransformation); m_reflectionShader->setUniform("u_frontColor", QVector4D(mirrorColor[0][0], mirrorColor[0][1], mirrorColor[0][2], mirrorColor[0][3])); m_reflectionShader->setUniform("u_backColor", QVector4D(mirrorColor[1][0], mirrorColor[1][1], mirrorColor[1][2], mirrorColor[1][3])); // TODO: make this one properly QVector<float> verts; QVector<float> texcoords; verts.reserve(18); texcoords.reserve(12); texcoords << 1.0 << 0.0; verts << vertices[6] << vertices[7] << vertices[8]; texcoords << 1.0 << 0.0; verts << vertices[9] << vertices[10] << vertices[11]; texcoords << 0.0 << 0.0; verts << vertices[0] << vertices[1] << vertices[2]; texcoords << 0.0 << 0.0; verts << vertices[0] << vertices[1] << vertices[2]; texcoords << 0.0 << 0.0; verts << vertices[3] << vertices[4] << vertices[5]; texcoords << 1.0 << 0.0; verts << vertices[6] << vertices[7] << vertices[8]; GLVertexBuffer *vbo = GLVertexBuffer::streamingBuffer(); vbo->reset(); vbo->setData(6, 3, verts.data(), texcoords.data()); vbo->render(GL_TRIANGLES); shaderManager->popShader(); } else { #ifndef KWIN_HAVE_OPENGLES glPushMatrix(); if (effects->numScreens() > 1 && area.x() != fullRect.x()) { // have to change the reflection area in horizontal layout and right screen glTranslatef(-area.x(), 0.0, 0.0); } glTranslatef(area.x() + area.width() * 0.5f, 0.0, 0.0); glColor4fv(mirrorColor[0]); glBegin(GL_POLYGON); glVertex3f(vertices[0], vertices[1], vertices[2]); glVertex3f(vertices[3], vertices[4], vertices[5]); // rearground glColor4fv(mirrorColor[1]); glVertex3f(vertices[6], vertices[7], vertices[8]); glVertex3f(vertices[9], vertices[10], vertices[11]); glEnd(); glPopMatrix(); #endif } glDisable(GL_SCISSOR_TEST); glDisable(GL_BLEND); } paintScene(frontWindow, leftWindows, rightWindows); if (effects->numScreens() > 1) { if (shaderManager->isShaderBound()) { GLShader *shader = shaderManager->pushShader(ShaderManager::GenericShader); shader->setUniform("projection", origProjection); shader->setUniform("modelview", origModelview); shaderManager->popShader(); } else { #ifndef KWIN_HAVE_OPENGLES popMatrix(); // revert change of projection matrix glMatrixMode(GL_PROJECTION); popMatrix(); glMatrixMode(GL_MODELVIEW); #endif } } // Render the caption frame if (windowTitle) { double opacity = 1.0; if (start) opacity = timeLine.currentValue(); else if (stop) opacity = 1.0 - timeLine.currentValue(); if (animation) captionFrame->setCrossFadeProgress(timeLine.currentValue()); captionFrame->render(region, opacity); } if ((thumbnails && (!dynamicThumbnails || (dynamicThumbnails && currentWindowList.size() >= thumbnailWindows))) && !(start || stop)) { BoxSwitchEffectProxy *proxy = static_cast<BoxSwitchEffectProxy*>(effects->getProxy("boxswitch")); if (proxy) proxy->paintWindowsBox(region); } }
void QtWebPageSGNode::setScale(float scale) { QMatrix4x4 matrix; matrix.scale(scale); setMatrix(matrix); }
/** * @brief GlSphere::makeSurface North pole is (0,radius, 0), south pole is (0, -radius, 0) * We use true normals. On a sphere vertex and normal have the same direction. * @param pointContainer */ void GLSphere::makeSurface(QVector<GLPoint> *pointContainer, QVector<GLuint> *indexContainer) { GLBody::makeSurface(pointContainer, indexContainer); QVector3D southPole = -v_Z; //unit vector, must be scaled by radius later QVector3D northPole = v_Z; QVector3D vertex; QVector3D normal; QVector3D texCoord; QMatrix4x4 longitudeMatrix; QMatrix4x4 latitudeMatrix; int iSouthPole = 0; //indices for the poles int iNorthPole = 0; //start with south pole m_firstPoint = m_points->size(); m_firstIndex = m_indices->size(); iSouthPole = m_firstPoint; m_points->append(GLPoint(southPole * m_radius, //vertex southPole, //normal QVector3D(0.5, 0.0, 0.0),//texCoord at 0 longitude m_color)); int firstRow = 1; int lastRow = m_stacks - 1; int slice; int duplicates = 1; for(slice = 0; slice < m_slices; slice ++) { longitudeMatrix.setToIdentity();//always start from scratch longitudeMatrix.rotate(slice * 360.0 / m_slices, -v_Z); if(slice == m_slices / 2) //we need to switch from end of texture to start of texture here duplicates = 2; else duplicates = 1; for(int duplicate = 0; duplicate < duplicates; duplicate++) // create an extra column of points for(int stack = firstRow; stack <= lastRow; stack ++) // to switch from end of texture to start of texture { latitudeMatrix.setToIdentity(); //always start from scratch latitudeMatrix.rotate(stack * 180.0 / m_stacks, v_Y); vertex = (southPole * latitudeMatrix) * longitudeMatrix; normal = vertex; vertex *= m_radius; double texX = (double)slice / (double) m_slices + 0.5; if(texX > 1.01) texX -= 1.0; if(duplicate == 1) texX = 0.0; texCoord = QVector3D(texX, (double)stack / (double)m_stacks, 0.0); //floats required!! m_points->append(GLPoint(vertex, normal, texCoord, m_color)); } } //end with north pole iNorthPole = m_points->size(); m_points->append(GLPoint(northPole * m_radius, //vertex northPole, //normal QVector3D(0.5, 1.0, 0.0),//texCoord at 0 longitude m_color)); m_nextPoint = m_points->size(); for(int i = m_firstPoint; i < m_nextPoint; i++) //move to final position (*m_points)[i].move(m_center); int rows = m_stacks - 1; for(slice = 0; slice < m_slices; slice += 2) { //go upwards from south pole to north pole m_indices->append(iSouthPole); for(int stack = firstRow; stack <= lastRow; stack ++) { m_indices->append(iSouthPole + rows * slice + stack); //left meridian m_indices->append(iSouthPole + rows * slice + rows + stack ); //right meridian } m_indices->append(iNorthPole); //now go downwards back to southpole for(int stack = lastRow; stack >= firstRow; stack --) { m_indices->append(iSouthPole + rows * slice + rows + stack); //left meridian m_indices->append(iSouthPole + rows * slice + rows + rows + stack); //right meridian } //southpole will be added in next slice } //Close the sphere //go upwards from south pole to north pole m_indices->append(iSouthPole); for(int stack = firstRow; stack <= lastRow; stack ++) { m_indices->append(iSouthPole + rows * slice + stack); //left meridian = last meridian m_indices->append(iSouthPole + stack ); //right meridian = first meridian } m_indices->append(iNorthPole); m_indices->append(iSouthPole); //finally add south pole m_nextIndex = m_indices->size(); }
void NormalMapScene::render() { //dumpTextureUnitConfiguration(); // Enable depth buffer writes (QQ2 disables them) glDepthMask( true ); // Clear the buffer with the current clearing color glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); m_mesh->material()->bind(); QOpenGLShaderProgramPtr shader = m_mesh->material()->shader(); { QMutexLocker locker( &m_mutex ); // Set the usual view/projection matrices QMatrix4x4 modelViewMatrix = m_camera->viewMatrix() * m_modelMatrix; QMatrix3x3 normalMatrix = modelViewMatrix.normalMatrix(); QMatrix4x4 mvp = m_camera->viewProjectionMatrix() * m_modelMatrix; shader->setUniformValue( "modelViewMatrix", modelViewMatrix ); shader->setUniformValue( "normalMatrix", normalMatrix ); shader->setUniformValue( "projectionMatrix", m_camera->projectionMatrix() ); shader->setUniformValue( "mvp", mvp ); } // Set the lighting parameters shader->setUniformValue( "light.position", QVector4D( 0.0f, 0.0f, 0.0f, 1.0f ) ); shader->setUniformValue( "light.intensity", QVector3D( 1.0f, 1.0f, 1.0f ) ); // Set the material properties shader->setUniformValue( "material.Ka", QVector3D( 0.1f, 0.1f, 0.1f ) ); shader->setUniformValue( "material.Kd", QVector3D( 0.9f, 0.9f, 0.9f ) ); shader->setUniformValue( "material.Ks", QVector3D( 0.2f, 0.2f, 0.2f ) ); shader->setUniformValue( "material.shininess", 20.0f ); // Let the mesh setup the remainder of its state and draw itself #if !defined(Q_OS_MAC) m_mesh->render(); #else glPushClientAttrib( GL_CLIENT_VERTEX_ARRAY_BIT ); m_mesh->bindBuffers(); m_mesh->render(); glPopClientAttrib(); #endif // Unbind shader shader->release(); // Restore texture unit state // - remove sampler objects // - set active texture unit back to the first unit #if !defined(Q_OS_MAC) m_funcs->glBindSampler( 0, 0 ); m_funcs->glBindSampler( 1, 0 ); #endif m_funcs->glActiveTexture( GL_TEXTURE0 ); //dumpTextureUnitConfiguration(); }
void SatGL::render(QMatrix4x4 projection, float distance, QQuaternion quat ) { QMatrix4x4 modelview; modelview.translate(0.0, 0.0, distance); modelview.rotate(quat); QVector<GLfloat> positions; QList<Satellite>::iterator sat = sats->GetSatlist()->begin(); int nbrSats = 0; int nbrVertices; QMatrix4x4 modelocta; QColor col(255, 0, 0); float alt; while ( sat != sats->GetSatlist()->end() ) { if( (*sat).active == true) { QVector3D pos, posnorm; (*sat).GetSatellitePosition(pos, posnorm, alt); positions.append(0.0f); positions.append(0.0f); positions.append(0.0f); positions.append(pos.x()); positions.append(pos.y()); positions.append(pos.z()); modelocta = modelview; modelocta.translate(posnorm.x(), posnorm.y(), posnorm.z()); modelocta.scale(0.005f); octa->render(projection, modelocta, col); QColor horizoncolour(opts.sathorizoncolor); horizon->render(projection, distance, quat, posnorm, alt, horizoncolour); nbrSats++; } ++sat; } positionsBuf.bind(); if(nbrSats != nbrActiveSats) { nbrActiveSats = nbrSats; positionsBuf.allocate(positions.data(), positions.size() * sizeof(GLfloat)); qDebug() << "positionsBuf.size() != nbrActiveSats * 2 * 3 * sizeof(GLfloat)"; qDebug() << "nbrActiveSats = " << nbrActiveSats << " positionsBuf.size() = " << positionsBuf.size(); } else { positionsBuf.write(0, positions.data(), positions.size() * sizeof(GLfloat)); } nbrVertices = positionsBuf.size() / (3 * sizeof(GLfloat)); positionsBuf.release(); QOpenGLVertexArrayObject::Binder vaoBinder(&vao); program->bind(); program->setUniformValue("MVP", projection * modelview); QMatrix3x3 norm = modelview.normalMatrix(); program->setUniformValue("NormalMatrix", norm); QColor rendercolor(255, 0, 0); program->setUniformValue("outcolor", QVector4D(rendercolor.redF(), rendercolor.greenF(), rendercolor.blueF(), 1.0f)); glDrawArrays(GL_LINES, 0, nbrVertices); sat = sats->GetSatlist()->begin(); while ( sat != sats->GetSatlist()->end() ) { if( (*sat).active == true) { if( (*sat).GetCatalogueNbr() == sats->GetSelectedSat() ) RenderTrail(&(*sat), projection, distance, quat, true); else RenderTrail(&(*sat), projection, distance, quat, false); } ++sat; } // QMatrix4x4 mod; // mod.setToIdentity(); // mod.translate(0.0, 0.0, distance); // mod.rotate(quat); // modelocta = mod; // modelocta.translate(0.0, 1.0, 0.0); // modelocta.scale(0.009f); // octa->render(projection, modelocta, col); // modelocta = mod; // modelocta.translate(0.0, 0.0, 1.0); // modelocta.scale(0.009f); // octa->render(projection, modelocta, col); // modelocta = mod; // modelocta.translate(1.0, 0.0, 0.0); // modelocta.scale(0.009f); // octa->render(projection, modelocta, col); }
void PSMoveForm::parseMoveData(MoveData d) { setButtons(d.buttons); ui->tempLcdNumber->display(d.temperature); if (d.battery <= 5) { for (int i = 0; i < 5; i++) { mBatteryCheckBoxes[i].setChecked(i < d.battery); } mBatteryLayout->setCurrentIndex(0); } else { mBatteryLayout->setCurrentIndex(1); } //emit setRumble(d.buttons.trigger); /*const QVector3D acc = d.accelerometer.normalized() * 128 + QVector3D(128, 128, 128); const QColor rgb(acc.x(), acc.y(), acc.z()); static int w = 0; if (w++ == 10) { w = 0; emit setRgb(rgb); }*/ //QVector3D normalisedAcc = d.accelerometer / 32768; //QVector3D normalisedMag = d.mag / 32768; //normalisedAcc.normalize(); //normalisedMag = QVector3D::crossProduct(normalisedMag.normalized(), normalisedAcc).normalized(); //QVector3D north = QVector3D::crossProduct(normalisedMag, normalisedAcc).normalized(); bool movePressedB = d.buttons.buttonsPressed.contains(MoveButtons::Move); if (!mPrevMovePressed && movePressedB) { //mOne = normalisedAcc; //mTwo = normalisedMag; //mThree = north; qDebug() << "acc:" << d.accelerometer; qDebug() << "mag:" << d.mag; emit movePressed(); } mPrevMovePressed = movePressedB; /*float one = std::acos(QVector3D::dotProduct(normalisedAcc, mOne)); float two = std::acos(QVector3D::dotProduct(normalisedMag, mTwo)); float three = std::acos(QVector3D::dotProduct(north, mThree));*/ //qDebug() << QString::number(one, 'g', 4) << QString::number(two, 'g', 4) << QString::number(three, 'g', 4); /*ui->accXProgressBar->setValue(one * 180 / M_PI); ui->accYProgressBar->setValue(two * 180 / M_PI); ui->accZProgressBar->setValue(three * 180 / M_PI);*/ if (ui->accGroupBox->isChecked()) { ui->accXProgressBar->setValue(d.accelerometer.x()); ui->accYProgressBar->setValue(d.accelerometer.y()); ui->accZProgressBar->setValue(d.accelerometer.z()); } if (ui->gyroGroupBox->isChecked()) { ui->gyroXProgressBar->setValue(d.gyro.x()); ui->gyroYProgressBar->setValue(d.gyro.y()); ui->gyroZProgressBar->setValue(d.gyro.z()); } if (ui->magGroupBox->isChecked()) { ui->magXProgressBar->setValue(d.mag.x()); ui->magYProgressBar->setValue(d.mag.y()); ui->magZProgressBar->setValue(d.mag.z()); } bool triPressed = d.buttons.buttonsPressed.contains(MoveButtons::Triangle); if (triPressed && !mPrevTriPressed) { emit setTopRightCorner(); } mPrevTriPressed = triPressed; bool squPressed = d.buttons.buttonsPressed.contains(MoveButtons::Square); if (squPressed && !mPrevSquPressed) { emit setBottomLeftCorner(); } mPrevSquPressed = squPressed; #if 0 QVector3D acc = d.accelerometer; QVector3D mag = d.mag; acc.normalize(); mag.normalize(); QMatrix4x4 m; m.setRow(2, acc); QVector3D east = QVector3D::crossProduct(acc, -mag); m.setRow(0, east); QVector3D north = QVector3D::crossProduct(acc, -mag); m.setRow(1, north); //qDebug() << mag; // QVector3D gyro = d.gyro / 32768; // acc.setX(mAccFilters[0]->step(acc.x())); // acc.setY(mAccFilters[1]->step(acc.y())); // acc.setZ(mAccFilters[2]->step(acc.z())); // mag.setX(mMagFilters[0]->step(mag.x())); // mag.setY(mMagFilters[1]->step(mag.y())); // mag.setZ(mMagFilters[2]->step(mag.z())); QVector3D newY = acc; QVector3D newZ = mag; newZ.setZ(-newZ.z()); QVector3D newX = QVector3D::crossProduct(newZ, newY).normalized(); QMatrix4x4 newMat; newMat.setRow(0, newX); newMat.setRow(1, newY); newMat.setRow(2, newZ); newMat.setRow(3, QVector4D(0, 0, 0, 1)); float qq1 = q0; float qq2 = q1; float qq3 = q2; float qq4 = q3; QQuaternion quat(qq1, qq2, qq3, qq4); QVector3D vec(1, 1, 1); emit setMatrix(newMat); //emit setVector(quat.rotatedVector(vec)); #endif }