void ViewportViewPerspective::initializeViewport(const QVector3D& surfmin, const QVector3D& surfmax, int width, int height)
{
    // add margin to max/min
    QVector3D diff = 0.01 * _margin * (surfmax - surfmin);
    QVector3D min = surfmin - diff;
    QVector3D max = surfmax + diff;

    // calculate the midpoint of the bounding box, which is used as the center of the
    // model for rotating the model
    _midpoint = 0.5 * (min + max);

    QVector3D panpoint = _midpoint;
    panpoint.setX(panpoint.x() + _panX);
    panpoint.setY(panpoint.y() + _panY);
    panpoint.setZ(panpoint.z() + _panZ);

    // calculate the distance of the camera to the center of the model, following from
    // the field of view from the camera
    float dist = sqrt((max.y() - min.y()) * (max.y() - min.y())
                      + (max.z() - min.z()) * (max.z() - min.z()));
    if (dist == 0)
        dist = 1E-2f;
    if (atan(_field_of_view) != 0) {
        _distance = 1.5 * dist / atan(_field_of_view);
        if (_distance > 1E5)
            _distance = 1E5;
    }
    else
        _distance = 1E5;

    // build the vertex transformation matrix from the perspective
    // and the angle, elevation

    float aspect_ratio = 1.0;
    if (height != 0)
        aspect_ratio = width / static_cast<float>(height);
    _proj = QMatrix4x4();

    // create projection
    _proj.perspective(RadToDeg(_field_of_view) / _zoom, aspect_ratio, 0.1f, 40.0f);
    
    // find the camera location
    QMatrix4x4 model;
    model.translate(_panX, _panY, _panZ);
    model.rotate(-_elevation, 1, 0, 0);
    model.rotate(_angle, 0, 0, 1);
    _camera_location = model.map(QVector3D(max.x() + _distance, 0, 0));
    
    // view matrix
    QMatrix4x4 view;
    view.lookAt(_camera_location, panpoint, QVector3D(0,0,1));
    
    _view = view;

    finishSetup();
}
예제 #2
0
coordinates::coordinates( float size, float thickness ):
    m_node( new QGLSceneNode() )
{
    QGLBuilder builder;
    builder << QGLCylinder( thickness, thickness, size, 12 );
    QGLSceneNode* cylinder = builder.finalizedSceneNode();
    cylinder->setPosition( QVector3D( 0, 0, 0.5 * size ) );
    cylinder->setEffect( QGL::LitMaterial );

    QGLBuilder arrowBuilder;
    arrowBuilder << QGLCylinder( 0.01, 2 * thickness, size / 3, 12 );
    QGLSceneNode* arrow = arrowBuilder.finalizedSceneNode();
    arrow->setPosition( QVector3D( 0, 0, size ) );
    arrow->setEffect( QGL::LitMaterial );
    
    
    QGLSceneNode* x = new QGLSceneNode( m_node );
    x->addNode(cylinder);
    QMatrix4x4 matrix;
    QQuaternion q = QQuaternion::fromAxisAndAngle(0.0f, 1.0f, 0.0f, 90.0f);
    matrix.rotate( q );
    x->setLocalTransform( matrix );
    QGLSceneNode* xArrow = new QGLSceneNode( m_node );
    xArrow->addNode( arrow );
    xArrow->setLocalTransform( matrix );
    QGLMaterial* xMaterial = new QGLMaterial;
    xMaterial->setDiffuseColor( QColor( 255, 0, 0, 128 ) );
    x->setMaterial( xMaterial );
    xArrow->setMaterial( xMaterial );
    
    QGLSceneNode* y = new QGLSceneNode( m_node );
    y->addNode(cylinder);
    q = QQuaternion::fromAxisAndAngle(1.0f, 0.0f, 0.0f, -90.0f);
    matrix.rotate( q );
    y->setLocalTransform( matrix );
    QGLSceneNode* yArrow = new QGLSceneNode( m_node );
    yArrow->addNode( arrow );
    yArrow->setLocalTransform( matrix );
    QGLMaterial* yMaterial = new QGLMaterial;
    yMaterial->setDiffuseColor(Qt::green);
    y->setMaterial( yMaterial );
    QGLMaterial* yArrowMaterial = new QGLMaterial;
    yArrowMaterial->setDiffuseColor( QColor( 0, 255, 0, 128 ) );
    yArrow->setMaterial( yArrowMaterial );
    
    QGLSceneNode* z = new QGLSceneNode( m_node );
    z->addNode(cylinder);
    QGLSceneNode* zArrow = new QGLSceneNode( m_node );
    zArrow->addNode( arrow );
    QGLMaterial* zMaterial = new QGLMaterial;
    zMaterial->setDiffuseColor(Qt::blue);
    z->setMaterial( zMaterial );
    QGLMaterial* zArrowMaterial = new QGLMaterial;
    zArrowMaterial->setDiffuseColor( QColor( 0, 0, 255, 128 ) );
    zArrow->setMaterial( zArrowMaterial );
}
예제 #3
0
void CompasWidget::paintGL(){
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	glEnable(GL_DEPTH_TEST);
	glEnable(GL_CULL_FACE);
	m_world.setToIdentity();
	m_world.rotate(180.0f - (m_xRot / 16.0f), 1, 0, 0);
	m_world.rotate(m_yRot / 16.0f, 0, 1, 0);
	m_world.rotate(m_zRot / 16.0f, 0, 0, 1);

	/*


	QOpenGLVertexArrayObject::Binder vaoBinder(&m_vao);
	m_program->bind();
	m_program->setUniformValue(m_projMatrixLoc, m_proj);
	m_program->setUniformValue(m_mvMatrixLoc, m_camera * m_world);
	QMatrix3x3 normalMatrix = m_world.normalMatrix();
	m_program->setUniformValue(m_normalMatrixLoc, normalMatrix);

	glDrawArrays(GL_TRIANGLES, 0, m_logo.vertexCount());

	m_program->release();
*/

	QOpenGLFunctions *f = context()->functions();
	const bool newFrameReady=true;
	if (newFrameReady) {//new frame ready
		f->glFrontFace(GL_CW); // because our cube's vertex data is such

		f->glBindTexture(GL_TEXTURE_2D, m_fbo2->texture());

		m_program2->bind();
		QOpenGLVertexArrayObject::Binder vaoBinder(m_vao2);
		// If VAOs are not supported, set the vertex attributes every time.
		if (!m_vao2->isCreated()){
			setupVertexAttribs2();
		}

		static GLfloat angle = 0;
		QMatrix4x4 m;
		m.translate(0, 0, -20);
		m.rotate(90, 0, 0, 1);
		m.rotate(angle, 0.5, 1, 0);
		angle += 0.5f;

		m_program2->setUniformValue(m_matrixLoc, m_proj * m);

		// Draw the cube.
		f->glDrawArrays(GL_TRIANGLES, 0, 36);

		m_program2->release();

	}


}
예제 #4
0
void Renderer::render()
{
    QMutexLocker locker(&m_windowLock);

    if (m_windows.isEmpty())
        return;

    HelloWindow *surface = m_windows.at(m_currentWindow);
    QColor color = surface->color();

    m_currentWindow = (m_currentWindow + 1) % m_windows.size();

    if (!m_context->makeCurrent(surface))
        return;

    QSize viewSize = surface->size();

    locker.unlock();

    if (!m_initialized) {
        initialize();
        m_initialized = true;
    }

    QOpenGLFunctions *f = m_context->functions();
    f->glViewport(0, 0, viewSize.width() * surface->devicePixelRatio(), viewSize.height() * surface->devicePixelRatio());

    f->glClearColor(0.1f, 0.1f, 0.2f, 1.0f);
    f->glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    f->glFrontFace(GL_CW);
    f->glCullFace(GL_FRONT);
    f->glEnable(GL_CULL_FACE);
    f->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.translate(0.0f, -0.2f, 0.0f);

    m_program->bind();
    m_program->setUniformValue(matrixUniform, modelview);
    m_program->setUniformValue(colorUniform, color);
    paintQtLogo();
    m_program->release();

    f->glDisable(GL_DEPTH_TEST);
    f->glDisable(GL_CULL_FACE);

    m_context->swapBuffers(surface);

    m_fAngle += 1.0f;

    QTimer::singleShot(0, this, SLOT(render()));
}
예제 #5
0
void LogoRenderer::render()
{	
	//glClearColor(0.5f, 0.5f, 0.7f, 1.0f);
	glClearColor(0, 0, 0, 1);
	
	glEnable(GL_CULL_FACE);
	glFrontFace(GL_CW);
    glCullFace(GL_BACK);
	glEnable(GL_DEPTH_TEST);
	glEnable(GL_BLEND);
	glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	glPointSize(5.0);
	//glClearDepth(1.0f);
	
	glDisable(GL_SCISSOR_TEST);
    glEnable(GL_STENCIL_TEST);
	
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
	
	handleEvents();
	handleLogic();
	
	drawStuff();
	
	glDisable(GL_DEPTH_TEST);
    glDisable(GL_CULL_FACE);
	
	return;
	
    glDepthMask(true);

    glClearColor(0.5f, 0.5f, 0.7f, 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);

    program1.bind();
    program1.setUniformValue(matrixUniform1, modelview);
    paintQtLogo();
    program1.release();

    glDisable(GL_DEPTH_TEST);
    glDisable(GL_CULL_FACE);

    m_fAngle += 1.0f;
}
예제 #6
0
파일: scene.cpp 프로젝트: 0ctobyte/cs488
void SceneNode::rotate(char axis, double angle)
{
  QMatrix4x4 m;

  if(axis == 'x') m.rotate(angle, 1.0, 0.0, 0.0);
  else if(axis == 'y') m.rotate(angle, 0.0, 1.0, 0.0); 
  else if(axis == 'z') m.rotate(angle, 0.0, 0.0, 1.0);

  set_transform(get_transform() * m);
}
예제 #7
0
QMatrix4x4 Transform::GetMatrix() const
{
    QMatrix4x4 transformation;
    transformation.translate(m_pos);
    //Should use quaternions for the following
    transformation.rotate(m_rotation.z(),QVector3D(0.0f,0.0f,1.0f));
    transformation.rotate(m_rotation.y(),QVector3D(0.0f,1.0f,0.0f));
    transformation.rotate(m_rotation.x(),QVector3D(1.0f,0.0f,0.0f));
    transformation.scale(m_scale);

    return transformation;
}
예제 #8
0
void CameraShader::apply() {
    QMatrix4x4 mv;
    mv.setToIdentity();
    // ModelView.rotate(eye, at, up);

    mv.rotate(-_pitch, 1.0, 0.0, 0.0);
    mv.rotate(  -_yaw, 0.0, 1.0, 0.0);
    mv.rotate( -_roll, 0.0, 0.0, 1.0);
    mv.translate(-_position.x, -_position.y, -_position.z);

    _shaderProgram->setUniformValue("ModelView", mv);
}
예제 #9
0
void Renderable3DEntity::updateTransform()
{
    QMatrix4x4 m;

    //Do the translation after rotating, otherwise rotation around the x,y,z axis would be screwed up
    m.translate(m_position);
    m.rotate(m_fRotX, QVector3D(1.0f, 0.0f, 0.0f));
    m.rotate(m_fRotY, QVector3D(0.0f, 1.0f, 0.0f));
    m.rotate(m_fRotZ, QVector3D(0.0f, 0.0f, 1.0f));

    m_pTransform->setMatrix(m);
}
예제 #10
0
void Camera::updateRotation( float pitch, float yaw, float roll)
{
    QMatrix4x4 cameraTransformation;
    cameraTransformation.setToIdentity();
    cameraTransformation.rotate(-roll, m_cameraForwardVector.toVector3D());
    cameraTransformation.rotate(-pitch, m_cameraRightVector.toVector3D());
    cameraTransformation.rotate(yaw, m_cameraUpVector.toVector3D());

    m_cameraForwardVector = m_cameraForwardVector * cameraTransformation;
    m_cameraRightVector = m_cameraRightVector * cameraTransformation;
    m_cameraUpVector = m_cameraUpVector * cameraTransformation;
}
예제 #11
0
void LogoRenderer::render()
{
#if 1
    QString fileName="c:\\shareproject\\jpg\\512img004.jpg";
    QImage image(fileName);
    if (image.isNull()) {
        qDebug()<<"image.isNull";
        return;
    }

    image = image.convertToFormat(QImage::Format_RGB888);
    //image = image.convertToFormat(QImage::Format_ARGB32);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, image.width(), image.height(), 0,
        //GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, image.bits());
        GL_RGB, GL_UNSIGNED_BYTE, image.bits());
    glDrawArrays(GL_TRIANGLES, 0, 6);
    QImage imagefrag(512,384,QImage::Format_RGB888);
    unsigned char *pixels = (unsigned char *) imagefrag.bits();
    glReadPixels(0, 0, 512, 384, GL_RGB, GL_UNSIGNED_BYTE, (GLvoid *)pixels);
    imagefrag.save("c:\\shareproject\\jpg\\512img005_frag2.jpg");
#endif
#if 0
    glDepthMask(true);

    glClearColor(0.5f, 0.5f, 0.7f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );

    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);

    program1.bind();
    program1.setUniformValue(matrixUniform1, modelview);
    paintQtLogo();
    program1.release();

    glDisable(GL_DEPTH_TEST);
    glDisable(GL_CULL_FACE);

    m_fAngle += 1.0f;
#endif
}
예제 #12
0
파일: qtrenderer.cpp 프로젝트: msorvig/tmp
void QtRenderer::render()
{
    QMutexLocker locker(&m_windowLock);

    if (m_windows.isEmpty())
        return;

    HelloWindow *surface = m_windows.at(m_currentWindow);
    QColor color = surface->color();

    m_currentWindow = (m_currentWindow + 1) % m_windows.size();

    if (!m_context->makeCurrent(surface))
        return;
    
    m_fboController->bind(surface->size());
    m_fboController->bindAndDraw();
    m_fboController->release();

    QSize viewSize = surface->size();

    locker.unlock();

    if (!m_initialized) {
        initialize();
        m_initialized = true;
    }


    //f->glClearColor(0.1f, 0.1f, 0.2f, 1.0f);

    QOpenGLFunctions *f = m_context->functions();
    f->glViewport(0, 0, viewSize.width() * surface->devicePixelRatio(), viewSize.height() * surface->devicePixelRatio());
    f->glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    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.translate(0.0f, -0.2f, 0.0f);

    m_program->setUniformValue(matrixUniform, modelview);
    m_program->setUniformValue(colorUniform, color);

    m_context->functions()->glDrawArrays(GL_TRIANGLES, 0, vertices.size());

    m_context->swapBuffers(surface);

    m_fAngle += 1.0f;

    QTimer::singleShot(250, this, SLOT(render()));
}
예제 #13
0
static QMatrix4x4 CreateMatrix(PositionDesc & desc)
{
	QMatrix4x4 cameraMatrix;
	cameraMatrix.setToIdentity();
	QVector3D position(desc._xPos, desc._yPos, desc._zPos);
	cameraMatrix.rotate(desc._azimuth, 0, 0, 1);
	QVector3D vec(0, 0, 1);
	QVector3D vec2(cos(qDegreesToRadians(desc._azimuth)), sin(qDegreesToRadians(desc._azimuth)), 0);
	QVector3D axis = QVector3D::crossProduct(vec, vec2);
	cameraMatrix.rotate(desc._elevation, axis);
	cameraMatrix.translate(position);
	return cameraMatrix;
}
예제 #14
0
void AwesomeCamera::rotateView(float z_angle,float x_angle){

//    rotM.setToIdentity();


    double cosPhi = cos(mouse_sens*(-z_angle)/180*M_PI);
    double sinPhi = sin(mouse_sens*(-z_angle)/180*M_PI);


    direction      = QVector3D(cosPhi*direction.x()+sinPhi*direction.z(),direction.y(),
                               cosPhi*direction.z()-sinPhi*direction.x());

    QMatrix4x4 rotMat;
    rotMat.setToIdentity();
    rotMat.rotate(mouse_sens*(-x_angle),QVector3D::crossProduct(direction,QVector3D(0,1,0)));
    QVector3D tmpVec = (rotMat*QVector4D(direction)).toVector3D();
    tmpVec.normalize();
    double angleTheta = QVector3D::dotProduct(tmpVec,QVector3D(0,1,0));
    if(qAbs(angleTheta) < 0.9){
        rotMat.setToIdentity();
        rotMat.rotate(mouse_sens*(-x_angle)*(1-qAbs(angleTheta)),QVector3D::crossProduct(direction,QVector3D(0,1,0)));
        QVector3D tmpVec = (rotMat*QVector4D(direction)).toVector3D();
        tmpVec.normalize();
        direction = tmpVec;
    }

    side_direction = QVector3D(cosPhi*side_direction.x()+sinPhi*side_direction.z(),0,
                               cosPhi*side_direction.z()-sinPhi*side_direction.x());

    updown_direction = QVector3D::crossProduct(direction,side_direction);



/*
    rot_angles[0] += mouse_sens*(z_angle);//przesuniecie X
    rot_angles[1] -= mouse_sens*(x_angle);//przesuniecie Y
    if(rot_angles[1] > 90) rot_angles[1] = 90;
    if(rot_angles[1] <-90) rot_angles[1] = -90;
//    przesuniecie do przodu
    direction = QVector3D(-sin(rot_angles[0]/180*M_PI),sin(rot_angles[1]/180*M_PI),cos(rot_angles[0]/180*M_PI));
//    przesuniece na boki
    side_direction = QVector3D(sin((rot_angles[0]+90)/180*M_PI),0,-cos((rot_angles[0]+90)/180*M_PI));
//    przesuwanie gora dol
    updown_direction = QVector3D::crossProduct(direction,side_direction);
*/

    direction.normalize();
    side_direction.normalize();
    updown_direction.normalize();

}
예제 #15
0
void Dragon2Widget::mouseMoveEvent( QMouseEvent * e )
{
    if(e->buttons() != Qt::NoButton)
    {
        setCursor(Qt::ClosedHandCursor);
        auto t = (e->pos() - _lastMousePos);
        QMatrix4x4 rotMat;
        rotMat.rotate(-t.x() / 10.0 * M_PI, 0, 1, 0);
        rotMat.rotate(t.y() / 10.0 * M_PI, 1, 0, 0);
        _modelMatrix = rotMat * _modelMatrix;
        _lastMousePos = e->pos();
        update();
    }
}
예제 #16
0
void SphereVision::computeViewMatrix()
{
    viewMatrix.setToIdentity();

    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);

    viewMatrix.lookAt(cameraPosition, QVector3D(0, 0, 0), cameraUpDirection);

}
예제 #17
0
void Visu3D::paintGL()
{
    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;

    shaderProgram.bind();

    shaderProgram.setUniformValue("mvpMatrix", pMatrix * mvMatrix); // modele-vue-projection
    shaderProgram.setUniformValue("greyMax", (float) lvlOfGreyMax);

    verticesDataBuffer.bind();
    shaderProgram.setAttributeBuffer("vertex", GL_FLOAT, 0, 3, 0);
    shaderProgram.enableAttributeArray("vertex");
    verticesDataBuffer.release();

    greyDataBuffer.bind();
    shaderProgram.setAttributeBuffer("inGrey", GL_FLOAT, 0, 1, 0);
    shaderProgram.enableAttributeArray("inGrey");
    greyDataBuffer.release();

    glDrawArrays(GL_TRIANGLES, 0, verticesData.size());

    shaderProgram.disableAttributeArray("vertex");
    shaderProgram.disableAttributeArray("inGrey");
    shaderProgram.release();

    glClear(GL_DEPTH_BUFFER_BIT); // On annule le test de profondeur afin
                                  //que le repere soit devant
    QMatrix4x4 mvpMatrix = pMatrix * mvMatrix; // Matrice de transfo pour que le repere tourne
                                               //en meme temps que la scene

    makeLandMark(mvpMatrix);

}
예제 #18
0
	template <typename R> void call(R *r) {
		const auto &view = r->getViewMatrix();
		const auto &projection = r->getProjectionMatrix();
		for (auto &con : r->getScenario().getWorld().cellCellConnections) {
			auto &cc = con.second;
			shader.bind();
			cube.vao.bind();
			QColor color = QColor::fromHsvF(0.7, 0.7, 0.7);
			shader.setUniformValue(shader.uniformLocation("color"), color);
			shader.setUniformValue(shader.uniformLocation("projection"), projection);
			shader.setUniformValue(shader.uniformLocation("view"), view);
			// first
			QMatrix4x4 model;
			auto ab =
			    toQV3D(cc.targets.first.b.X.rotated(cc.cells.first->getOrientationRotation()) *
			           cc.targets.first.d);
			model.translate(toQV3D(cc.cells.first->getPosition()) + ab * 0.5);
			auto dp = ab.normalized().x();
			if (dp != 1 && dp != -1) {
				model.rotate(acos(dp) * 180.0 / M_PI,
				             QVector3D::crossProduct(QVector3D(1, 0, 0), ab));
				model.scale(ab.length() * 0.5, 1.0, 1.0);
				QMatrix4x4 nmatrix = (model).inverted().transposed();
				shader.setUniformValue(shader.uniformLocation("model"), model);
				shader.setUniformValue(shader.uniformLocation("normalMatrix"), nmatrix);
				GL->glDrawElements(GL_TRIANGLES, cube.indices.size(), GL_UNSIGNED_INT, 0);
			}
			// second
			color = QColor::fromHsvF(0.3, 0.7, 0.7);
			shader.setUniformValue(shader.uniformLocation("color"), color);
			model = QMatrix4x4();
			ab = toQV3D(
			    cc.targets.second.b.X.rotated(cc.cells.second->getOrientationRotation()) *
			    cc.targets.second.d);
			model.translate(toQV3D(cc.cells.second->getPosition()) + ab * 0.5);
			dp = ab.normalized().x();
			if (dp != 1 && dp != -1) {
				model.rotate(acos(dp) * 180.0 / M_PI,
				             QVector3D::crossProduct(QVector3D(1, 0, 0), ab));
				model.scale(ab.length() * 0.5, 1.0, 1.0);
				QMatrix4x4 nmatrix = (model).inverted().transposed();
				shader.setUniformValue(shader.uniformLocation("model"), model);
				shader.setUniformValue(shader.uniformLocation("normalMatrix"), nmatrix);
				GL->glDrawElements(GL_TRIANGLES, cube.indices.size(), GL_UNSIGNED_INT, 0);
			}
			cube.vao.release();
			shader.release();
		}
	}
예제 #19
0
void CCamera::convertGlobalVectorToTerrainVector(QVector3D *vec)
{
    QMatrix4x4 transform;
    QVector3D earthPoint;

    earthPoint.setX(earthPointX);
    earthPoint.setY(earthPointY);
    earthPoint.setZ(earthPointZ);
    (*vec) -= earthPoint;
    transform.rotate(earthPointLon, 0.0, 1.0, 0.0);
    (*vec) = (*vec) * transform;
    transform.setToIdentity();
    transform.rotate(-earthPointLat+90.0, 1.0, 0.0, 0.0);
    (*vec) = (*vec) * transform;
}
예제 #20
0
파일: view3D.cpp 프로젝트: GBeret/mne-cpp
void View3D::createCoordSystem(Qt3DCore::QEntity* parent)
{
    m_pCoordSysEntity = QSharedPointer<Qt3DCore::QEntity>::create(parent);

    //create geometry
    QSharedPointer<Qt3DExtras::QCylinderGeometry> pAxis =  QSharedPointer<Qt3DExtras::QCylinderGeometry>::create();
    pAxis->setRadius(0.001f);
    pAxis->setLength(30);
    pAxis->setRings(100);
    pAxis->setSlices(20);

    //create mesh
    GeometryMultiplier *pCoordSysMesh = new GeometryMultiplier(pAxis);
    QVector<QColor> vColors;
    vColors.reserve(3);
    QVector<QMatrix4x4> vTransforms;
    vTransforms.reserve(3);
    QMatrix4x4 transformMat;

    // Y - red
    transformMat.setToIdentity();
    vTransforms.push_back(transformMat);
    vColors.push_back(QColor(255, 0, 0));

    // X - blue
    transformMat.setToIdentity();
    transformMat.rotate(90.0f, QVector3D(0,0,1));
    vTransforms.push_back(transformMat);
    vColors.push_back(QColor(0, 0, 255));

    // Z - green
    transformMat.setToIdentity();
    transformMat.rotate(90.0f, QVector3D(1,0,0));
    vTransforms.push_back(transformMat);
    vColors.push_back(QColor(0, 255, 0));

    //Set transforms and colors
    pCoordSysMesh->setTransforms(vTransforms);
    pCoordSysMesh->setColors(vColors);

    //Add material
    GeometryMultiplierMaterial* pCoordSysMaterial = new GeometryMultiplierMaterial;
    pCoordSysMaterial->setAmbient(QColor(0,0,0));
    pCoordSysMaterial->setAlpha(1.0f);

    m_pCoordSysEntity->addComponent(pCoordSysMesh);
    m_pCoordSysEntity->addComponent(pCoordSysMaterial);
}
예제 #21
0
void GLPointCloudViewer::renderCloud(QOpenGLShaderProgram* program, GLPointCloud* cloud)
{
    if (program == nullptr || !program->bind())
        return;

    // Calculate model view transformation
    QMatrix4x4 view;
    view.translate(0, 0, distance);
    view.rotate(rotation);

    int projection_matrix_location = program->uniformLocation("projectionMatrix");
    if (projection_matrix_location > -1)
        program->setUniformValue("projectionMatrix", projection);
    else
        std::cerr << "Error: Shader does not have attribute 'projectionMatrix'" << std::endl;


    int view_matrix_location = program->uniformLocation("viewMatrix");
    if (view_matrix_location > -1)
        program->setUniformValue("viewMatrix", view);
    else
        std::cerr << "Error: Shader does not have attribute 'viewMatrix'" << std::endl;


    int model_matrix_location = program->uniformLocation("modelMatrix");
    if (model_matrix_location > -1)
        program->setUniformValue("modelMatrix", cloud->transform());
    else
        std::cerr << "Error: Shader does not have attribute 'modelMatrix'" << std::endl;

    cloud->render(program);
}
예제 #22
0
파일: ray.cpp 프로젝트: kaajo/ARayCasting
float Ray::intersectionWithPolygonAlt(Ray &ray, const QVector<QVector4D> polygon, QVector3D &normal, QVector3D &intersection, Ray &mirror)
{
    if(polygon.size() < 3) return std::numeric_limits<float>::max();

    normal = QVector3D::crossProduct((polygon[1] - polygon[0]).toVector3D(), (polygon[2] - polygon[1]).toVector3D());

    float distanceFromOrigin = QVector3D::dotProduct(normal, polygon[1].toVector3D() - polygon[0].toVector3D());

    QVector4D ba = ray.endPoint() - ray.startPoint();
    QVector4D pa = polygon[2] - ray.startPoint();

    float nDotA = QVector3D::dotProduct(normal, pa.toVector3D());
    float nDotBA = QVector3D::dotProduct(normal, ba.toVector3D());

    intersection = ray.startPoint().toVector3D() + (((distanceFromOrigin - nDotA)/nDotBA) * ba.toVector3D());

    QVector3D vector(QVector4D(intersection,1.0f)- ray.startPoint());

    QMatrix4x4 mat;
    mat.rotate(180, normal);

    vector = mat * vector;

    mirror = Ray(QVector4D(intersection,1.0), QVector4D(vector+intersection,1.0f));

    return calcAngleSum(intersection, polygon);
}
void SurfaceGraph::paintGL()
{
    // Clear color and depth buffer
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    texture->bind();

    // Calculate model view transformation
    QMatrix4x4 matrix;
    matrix.translate(0.0, 0.0, -5.0);
    matrix.rotate(rotation);
    matrix.scale(zoom,zoom,zoom);

    // Set modelview-projection matrix
    program.setUniformValue("mvp_matrix", projection * matrix);

    // Use texture unit 0 (which file to use)
    program.setUniformValue("texture", 0);

    // Draw geometry
    geometries->drawGeometry(&program);

    if (display_lines)
    {
        geometries->drawLineGeometry(&program);
        geometries->drawPointGeometry(&program);
    }
}
예제 #24
0
/*!
    Returns the transformation matrix to apply to the projection matrix
    to present the scene as viewed from the camera position.

    The \a aspectRatio specifies the aspect ratio of the window the
    camera view is being displayed in.  An \a aspectRatio of 1 indicates that
    the window is square.  An \a aspectRatio greater than 1 indicates that
    the window is wider than it is high.  An \a aspectRatio less than 1
    indicates that the window is higher than it is wide.

    \sa apply(), modelViewMatrix()
*/
QMatrix4x4 Camera::projectionMatrix(qreal aspectRatio) const
{
    Q_D(const Camera);
    QMatrix4x4 m;
    if (!d->adjustForAspectRatio)
        aspectRatio = 1.0f;
    if (d->screenRotation != 0) {
        m.rotate((qreal)(d->screenRotation), 0.0f, 0.0f, 1.0f);
        if (d->screenRotation == 90 || d->screenRotation == 270) {
            if (aspectRatio != 0.0f)
                aspectRatio = 1.0f / aspectRatio;
        }
    }
    if (d->projectionType == Perspective && d->fieldOfView != 0.0f) {
        m.perspective(d->fieldOfView, aspectRatio,
                      d->nearPlane, d->farPlane);
    } else {
        qreal halfWidth = d->viewSize.width() / 2.0f;
        qreal halfHeight = d->viewSize.height() / 2.0f;
        if (aspectRatio > 1.0f) {
            halfWidth *= aspectRatio;
        } else if (aspectRatio > 0.0f && aspectRatio < 1.0f) {
            halfHeight /= aspectRatio;
        }
        if (d->projectionType == Perspective) {
            m.frustum(-halfWidth, halfWidth, -halfHeight, halfHeight,
                      d->nearPlane, d->farPlane);
        } else {
            m.ortho(-halfWidth, halfWidth, -halfHeight, halfHeight,
                    d->nearPlane, d->farPlane);
        }
    }
    return m;
}
예제 #25
0
void Window::mouseMoveEvent(QMouseEvent *event)
{
    if (!m_mouseDown) {
        m_terrain->pick(QPointF(event->localPos().x() / 1024, event->localPos().y() / 768), m_projection, m_view);
        return;
    }

    QPointF delta = event->localPos() - m_mousePos;

    QMatrix4x4 mat;
    mat.rotate(m_camera.orientation);

    QVector3D pitchAxis = QVector3D(mat(0, 0), mat(0, 1), mat(0, 2));
    pitchAxis.normalize();

    m_camera.orientation *= QQuaternion::fromAxisAndAngle(pitchAxis, perSecond(delta.y() / 200));
    m_camera.orientation.normalize();

    QVector3D yawAxis = QVector3D(mat(1, 0), mat(1, 1), mat(1, 2));
    yawAxis.normalize();

    m_camera.orientation *= QQuaternion::fromAxisAndAngle(yawAxis, perSecond(delta.x() / 200));
    m_camera.orientation.normalize();


    m_needsUpdate = true;

    m_mousePos = event->localPos();
}
void QSGAnimatorNode::preprocess()
{
    QSGNode::preprocess();
    if (m_controller->isInitialized()) {
        if (m_transformNode) {
            qreal x = m_controller->registeredProperty("x")->value().toReal();
            qreal y = m_controller->registeredProperty("y")->value().toReal();
            QMatrix4x4 m = m_controller->transformMatrix();
            QPointF transformOrigin = m_controller->registeredProperty("transformOriginPoint")->value().toPointF();
            qreal scale = m_controller->registeredProperty("scale")->value().toReal();
            qreal rotation = m_controller->registeredProperty("rotation")->value().toReal();
            m.translate(transformOrigin.x(), transformOrigin.y());
            m.translate(x, y);
            m.scale(scale);
            m.rotate(rotation, 0, 0, 1);
            m.translate(-transformOrigin.x(), -transformOrigin.y());
            m_transformNode->setMatrix(m);

            if (m_controller->isUpdating())
                m_transformNode->markDirty(QSGNode::DirtyMatrix);
        }

        if (m_opacityNode) {
            qreal opacity = m_controller->registeredProperty("opacity")->value().toReal();
            m_opacityNode->setOpacity(qMin(qreal(MAX_OPACITY), qMax(qreal(MIN_OPACITY), opacity)));

            if (m_controller->isUpdating())
                m_opacityNode->markDirty(QSGNode::DirtyOpacity);
        }
    }
}
예제 #27
0
QMatrix4x4 ModelInterface::getMatrix(const aiMatrix4x4* m)
{
    QMatrix4x4 nodeMatrix;

    if(m->IsIdentity())
        return nodeMatrix;

    aiQuaternion rotation;
    aiVector3D   position;
    aiVector3D   scale;

    m->Decompose(scale, rotation, position);

    QVector3D   qscale(scale.x,scale.y, scale.z);
    QVector3D   qposition(position.x, position.y, position.z);
    QQuaternion qrotation(rotation.w, rotation.x, rotation.y, rotation.z);

    if(!qscale.isNull())
        nodeMatrix.scale(qscale);

    if(!qposition.isNull())
        nodeMatrix.translate(qposition);

    if(!qrotation.isNull())
        nodeMatrix.rotate(qrotation);

    return nodeMatrix;
}
void ParticleExplosionNode2::draw(std::stack<QMatrix4x4> &MVStack, QMatrix4x4 cameraMatrix, QMatrix4x4 projectionMatrix, QOpenGLShaderProgram *shader) {
    //If the node is a leaf, draw its contents
    if(leaf) {
        GBuffer::activeGBuffer()->drawToFinal();
        Shaders::bind(Shaders::particleProgram);
//    Scene::passLights(cameraMatrix, Shaders::phongProgram);
        MVStack.push(MVStack.top());

        MVStack.top().translate(this->translation);

        //Convert the quat to a matrix, may be a performance leak.
        QMatrix4x4 tempRot;
        tempRot.rotate(this->rotation.normalized());
        MVStack.top() *= tempRot;

		lastCameraRotation = Camera::M4toQuat(cameraMatrix);

        glUniformMatrix4fv(Shaders::particleProgram->uniformLocation("modelViewMatrix"), 1, GL_FALSE, MVStack.top().constData());
        glUniformMatrix4fv(Shaders::particleProgram->uniformLocation("perspectiveMatrix"), 1, GL_FALSE, projectionMatrix.constData());

        glActiveTexture(GL_TEXTURE0);
        glBindTexture(GL_TEXTURE_2D, sprite);
        glUniform1i(Shaders::particleProgram->uniformLocation("sprite"), 0);

        drawParticles();

        MVStack.pop();
        Shaders::release(Shaders::particleProgram);
        GBuffer::activeGBuffer()->bindGeometryPass();
    } else {
        //Else, recurse into its children
        std::for_each(children.begin(), children.end(), [&MVStack, cameraMatrix, projectionMatrix, shader](SceneGraph *s){s->draw(MVStack, cameraMatrix, projectionMatrix, shader);});
    }
}
예제 #29
0
void Camera::rotate(float dx, float dy)
{
    float roty = 1.5f * dx / mWidth;
    float rotx = 1.5f * dy / mHeight;
    float phi = rotx;
    float theta = roty;

    QVector3D cameraW = (mLookAtPosition - mCameraPosition).normalized();
    QVector3D cameraU = QVector3D::crossProduct(cameraW, mUpVector).normalized();

    QQuaternion q = (QQuaternion(theta, QVector3D(0.0, 1.0, 0.0)) * QQuaternion(phi, cameraU)).normalized();
    QMatrix4x4 rotMat = QMatrix4x4();
    rotMat.rotate(q);

    QVector3D tmp = mCameraPosition - mLookAtPosition;
    QVector4D myPoint = QVector4D(tmp, 1.0);
    QVector4D myVector = QVector4D(mUpVector);

    QVector4D newPos = rotMat * myPoint;
    QVector4D tmp1 = rotMat * myVector;

    // Hacky fix for some degeneracy
    newPos.setY(-newPos.y());
    tmp1.setY(-tmp1.y());

    mCameraPosition = QVector3D(newPos) + mLookAtPosition;
    mUpVector = QVector3D(tmp1).normalized();
    setViewMatrix(mCameraPosition, mLookAtPosition, mUpVector);
}
void ProjectileNode::draw(std::stack<QMatrix4x4> &MVStack, QMatrix4x4 cameraMatrix, QMatrix4x4 projectionMatrix, QOpenGLShaderProgram *shader) {

	Shaders::bind(shader);
	MVStack.push(MVStack.top());

	MVStack.top().translate(this->translation);

	//Convert the quat to a matrix, may be a performance leak.
	QMatrix4x4 tempRot;
	tempRot.rotate(this->rotation.normalized());
	MVStack.top() *= tempRot;

	//If the node is a leaf, draw its contents
	if(leaf) {
		glUniformMatrix4fv(shader->uniformLocation("modelViewMatrix"), 1, GL_FALSE, MVStack.top().constData());
		glUniformMatrix4fv(shader->uniformLocation("perspectiveMatrix"), 1, GL_FALSE, projectionMatrix.constData());
		glUniformMatrix4fv(shader->uniformLocation("normalMatrix"), 1, GL_FALSE, MVStack.top().inverted().transposed().constData());
		int r = (id & 0x000000FF) >>  0;
		int g = (id & 0x0000FF00) >>  8;
		int b = (id & 0x00FF0000) >> 16;
		glUniform4f(shader->uniformLocation("id"), r/255.0f, g/255.0f, b/255.0f, 1.0f);

		glUniform4fv(shader->uniformLocation("color"), 1, color);

		this->primitive->draw();
	} else {