Example #1
0
void NightModeGraphicsEffect::draw(QPainter* painter)
{
	int pixelRatio = painter->device()->devicePixelRatio();
	QSize size(painter->device()->width() * pixelRatio, painter->device()->height() * pixelRatio);
	if (fbo && fbo->size() != size)
	{
		delete fbo;
		fbo = NULL;
	}
	if (!fbo)
	{
		QGLFramebufferObjectFormat format;
		format.setAttachment(QGLFramebufferObject::CombinedDepthStencil);
		format.setInternalTextureFormat(GL_RGBA);
		fbo = new NightModeGraphicsEffectFbo(size, format, pixelRatio);
	}
	QPainter fboPainter(fbo);
	drawSource(&fboPainter);

	painter->save();
	painter->beginNativePainting();
	program->bind();
	const GLfloat pos[] = {-1, -1, +1, -1, -1, +1, +1, +1};
	const GLfloat texCoord[] = {0, 0, 1, 0, 0, 1, 1, 1};
	program->setUniformValue(vars.source, 0);
	program->setAttributeArray(vars.pos, pos, 2);
	program->setAttributeArray(vars.texCoord, texCoord, 2);
	program->enableAttributeArray(vars.pos);
	program->enableAttributeArray(vars.texCoord);
	glBindTexture(GL_TEXTURE_2D, fbo->texture());
	glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
	program->release();
	painter->endNativePainting();
	painter->restore();
}
Example #2
0
void CubeObj::drawgl(GLWidget &gl, QMatrix4x4 & cameramat  ) {

    QMatrix4x4 mobj = cameramat;

    mobj *= getMatrix();
    mobj.scale(scale);

    static  QColor color ( 1.0f, 0, 0.5f, 1 );

    QGLShaderProgram * sp = gl.program;

    if ( pro.actualobject == this ) {
        sp = gl.program2;
    }

    for ( int i=0; i <6; i++) {

        sp->enableAttributeArray(PROGRAM_VERTEX_ATTRIBUTE);
        sp->enableAttributeArray(PROGRAM_TEXCOORD_ATTRIBUTE);
        sp->setAttributeArray   (PROGRAM_VERTEX_ATTRIBUTE, vertices.constData());
        sp->setAttributeArray   (PROGRAM_TEXCOORD_ATTRIBUTE, texCoords.constData());
        sp->bind();
        sp->setUniformValue("matrix", mobj);
        sp->setUniformValue("color", QVector4D (1,0,0,0.2f));
        gl.glBindTexture(GL_TEXTURE_2D, this->textureIDs[i] );
        gl.glDrawArrays(GL_QUADS, i*4, 4 );
    }


    if ( pro.getManger().edges ) {
        gl.glDisable(GL_CULL_FACE);
        sp = gl.solidcolorp;

        sp->enableAttributeArray(PROGRAM_VERTEX_ATTRIBUTE);
        sp->enableAttributeArray(PROGRAM_TEXCOORD_ATTRIBUTE);
        sp->setAttributeArray   (PROGRAM_VERTEX_ATTRIBUTE, vertices.constData());
        sp->setAttributeArray   (PROGRAM_TEXCOORD_ATTRIBUTE, texCoords.constData());
        sp->bind();
        sp->setUniformValue("matrix", mobj);
        sp->setUniformValue("color", QVector4D (0,1,0,0.8f));

        if ( pro.actualobject == this ) {
            sp->setUniformValue("color", QVector4D (1,0.8f,1,0.8f));
        }
        glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
        gl.glLineWidth(2);
        gl.glDrawArrays(GL_QUADS, 0, 24 );
        gl.glEnable(GL_CULL_FACE);
        glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
    }

}
Example #3
0
void FiberRenderer::setShaderVars( PropertyGroup& props )
{
    QGLShaderProgram* program = GLFunctions::getShader( "fiber" );

    program->bind();

    intptr_t offset = 0;
    // Tell OpenGL programmable pipeline how to locate vertex position data
    int numFloats = 6;

    int vertexLocation = program->attributeLocation( "a_position" );
    program->enableAttributeArray( vertexLocation );
    glVertexAttribPointer( vertexLocation, 3, GL_FLOAT, GL_FALSE, sizeof(float) * numFloats, (const void *) offset );
    offset += sizeof(float) * 3;

    int normalLocation = program->attributeLocation( "a_normal" );
    program->enableAttributeArray( normalLocation );
    glVertexAttribPointer( normalLocation, 3, GL_FLOAT, GL_FALSE, sizeof(float) * numFloats, (const void *) offset );
    offset += sizeof(float) * 3;

    program->setUniformValue( "u_colorMode", props.get( Fn::Property::D_COLORMODE ).toInt() );
    program->setUniformValue( "u_mriSource", props.get( Fn::Property::D_STIPPLE_PROB_MASK ).toInt() );
    program->setUniformValue( "u_colormap", props.get( Fn::Property::D_COLORMAP ).toInt() );
    program->setUniformValue( "u_color", 1.0, 0.0, 0.0, 1.0 );

    if ( props.get( Fn::Property::D_COLORMODE ).toInt() == 3 )
    {
        float texMin = props.get( Fn::Property::D_MIN ).toFloat();
        float texMax = props.get( Fn::Property::D_MAX ).toFloat();
        program->setUniformValue( "u_lowerThreshold", ( props.get( Fn::Property::D_LOWER_THRESHOLD ).toFloat() - texMin ) / ( texMax - texMin ) );
        program->setUniformValue( "u_upperThreshold", ( props.get( Fn::Property::D_UPPER_THRESHOLD ).toFloat() - texMin ) / ( texMax - texMin ) );
        program->setUniformValue( "u_selectedMin", ( props.get( Fn::Property::D_SELECTED_MIN ).toFloat() - texMin ) / ( texMax - texMin ) );
        program->setUniformValue( "u_selectedMax", ( props.get( Fn::Property::D_SELECTED_MAX ).toFloat() - texMin ) / ( texMax - texMin ) );
    }
    else
    {
        program->setUniformValue( "u_selectedMin", props.get( Fn::Property::D_SELECTED_MIN ).toFloat() );
        program->setUniformValue( "u_selectedMax", props.get( Fn::Property::D_SELECTED_MAX ).toFloat() );
        program->setUniformValue( "u_lowerThreshold", props.get( Fn::Property::D_LOWER_THRESHOLD ).toFloat() );
        program->setUniformValue( "u_upperThreshold", props.get( Fn::Property::D_UPPER_THRESHOLD ).toFloat() );
    }
    program->setUniformValue( "u_cutdx", props.get( Fn::Property::D_DX ).toFloat() );
    program->setUniformValue( "u_cutdy", props.get( Fn::Property::D_DY ).toFloat() );
    program->setUniformValue( "u_cutdz", props.get( Fn::Property::D_DZ ).toFloat() );
    program->setUniformValue( "u_cutx", props.get( Fn::Property::D_NX ).toFloat() / 10.f );
    program->setUniformValue( "u_cuty", props.get( Fn::Property::D_NY ).toFloat() / 10.f );
    program->setUniformValue( "u_cutz", props.get( Fn::Property::D_NZ ).toFloat() / 10.f );
}
Example #4
0
void SliceRenderer::setShaderVars( QString target )
{
    QGLShaderProgram* program = GLFunctions::getShader( "slice" );
    int vertexLocation = program->attributeLocation( "a_position" );
    program->enableAttributeArray( vertexLocation );
    glVertexAttribPointer( vertexLocation, 3, GL_FLOAT, GL_FALSE, sizeof(float) * 3, 0 );
    GLFunctions::setTextureUniforms( program, target );
}
Example #5
0
void TriMesh::drawEdges(QGLShaderProgram& prog,
                        const TransformState& transState) const
{
    transState.translate(offset()).setUniforms(prog.programId());
    prog.enableAttributeArray("position");
    prog.setAttributeArray("position", GL_FLOAT, &m_verts[0], 3);
    if (m_colors.size() == m_verts.size())
    {
        prog.enableAttributeArray("color");
        prog.setAttributeArray("color", GL_FLOAT, &m_colors[0], 3);
    }
    else
        prog.setAttributeValue("color", GLfloat(1), GLfloat(1), GLfloat(1));
    glDrawElements(GL_LINES, (GLsizei)m_edges.size(),
                   GL_UNSIGNED_INT, &m_edges[0]);
    prog.disableAttributeArray("color");
    prog.disableAttributeArray("position");
}
void FiberRenderer::setShaderVars( PropertyGroup* props )
{
    QGLShaderProgram* program = GLFunctions::getShader( "fiber" );

    program->bind();

    long int offset = 0;
    // Tell OpenGL programmable pipeline how to locate vertex position data

    int vertexLocation = program->attributeLocation( "a_position" );
    program->enableAttributeArray( vertexLocation );
    glVertexAttribPointer( vertexLocation, 3, GL_FLOAT, GL_FALSE, sizeof(float) * 10, (const void *) offset );

    offset += sizeof(float) * 3;
    int normalLocation = program->attributeLocation( "a_normal" );
    program->enableAttributeArray( normalLocation );
    glVertexAttribPointer( normalLocation, 3, GL_FLOAT, GL_FALSE, sizeof(float) * 10, (const void *) offset );

    offset += sizeof(float) * 3;
    int colorLocation = program->attributeLocation( "a_color" );
    program->enableAttributeArray( colorLocation );
    glVertexAttribPointer( colorLocation, 3, GL_FLOAT, GL_FALSE, sizeof(float) * 10, (const void *) offset );

    offset += sizeof(float) * 3;
    int extraLocation = program->attributeLocation( "a_extra" );
    program->enableAttributeArray( extraLocation );
    glVertexAttribPointer( extraLocation, 1, GL_FLOAT, GL_FALSE, sizeof(float) * 10, (const void *) offset );

    program->setUniformValue( "u_colorMode", props->get( Fn::Property::COLORMODE ).toInt() );
    program->setUniformValue( "u_colormap", props->get( Fn::Property::COLORMAP ).toInt() );
    program->setUniformValue( "u_color", 1.0, 0.0, 0.0, 1.0 );
    program->setUniformValue( "u_selectedMin", props->get( Fn::Property::SELECTED_MIN ).toFloat() );
    program->setUniformValue( "u_selectedMax", props->get( Fn::Property::SELECTED_MAX ).toFloat() );
    program->setUniformValue( "u_lowerThreshold", props->get( Fn::Property::LOWER_THRESHOLD ).toFloat() );
    program->setUniformValue( "u_upperThreshold", props->get( Fn::Property::UPPER_THRESHOLD ).toFloat() );
    program->setUniformValue( "u_dx", props->get( Fn::Property::DX ).toFloat() );
    program->setUniformValue( "u_dy", props->get( Fn::Property::DY ).toFloat() );
    program->setUniformValue( "u_dz", props->get( Fn::Property::DZ ).toFloat() );
    program->setUniformValue( "u_x", props->get( Fn::Property::NX ).toFloat() / 10.f );
    program->setUniformValue( "u_y", props->get( Fn::Property::NY ).toFloat() / 10.f );
    program->setUniformValue( "u_z", props->get( Fn::Property::NZ ).toFloat() / 10.f );
}
Example #7
0
void BinghamRenderer::setShaderVars( PropertyGroup& props )
{
    QGLShaderProgram* program = GLFunctions::getShader( "qball" );
    program->bind();

    intptr_t offset = 0;
    // Tell OpenGL programmable pipeline how to locate vertex position data
    int vertexLocation = program->attributeLocation( "a_position" );
    program->enableAttributeArray( vertexLocation );
    glVertexAttribPointer( vertexLocation, 3, GL_FLOAT, GL_FALSE, sizeof(float) * 7, (const void *) offset );

    offset += sizeof(float) * 3;
    int offsetLocation = program->attributeLocation( "a_offset" );
    program->enableAttributeArray( offsetLocation );
    glVertexAttribPointer( offsetLocation, 3, GL_FLOAT, GL_FALSE, sizeof(float) * 7, (const void *) offset );

    offset += sizeof(float) * 3;
    int radiusLocation = program->attributeLocation( "a_radius" );
    program->enableAttributeArray( radiusLocation );
    glVertexAttribPointer( radiusLocation, 3, GL_FLOAT, GL_FALSE, sizeof(float) * 7, (const void *) offset );
}
Example #8
0
void AxisRenderer::render(const AxisCamera &camera, QGLShaderProgram &program, QGLBuffer &vertBuffer, QGLBuffer &indexBuffer, bool selected)
{
    qDebug()<<"[AxisRender] start of render";

    initializeGLFunctions();

    //bind the program for use
    if(!program.bind()){
        QMessageBox::critical(0, "Error", "Could not bind program for use");
        qFatal("Could not bind program for use");
    }

    qDebug()<<"[AxisRender] Drawing";

    //set up shader locations
    program.bind();
    GLint vertLoc = program.attributeLocation("vertex");
    Q_ASSERT(vertLoc != -1);
    GLint colorLoc = program.uniformLocation("color");
    Q_ASSERT(colorLoc != -1);
    GLint mvpLoc = program.uniformLocation("modelToCamera");
    Q_ASSERT(mvpLoc != -1);

    //set default color to a cyan
    QVector4D color(0.0f, .5f, 1.0f, 1.0f);

    //modify the color for selected geometry
    if(selected){
        qDebug()<<"[AxisRender] adding selection color";
        color = color + QVector4D(1.0f, 0.0f, 0.0f, 0.0f);
    }

    //set the uniform values
    program.setUniformValueArray(colorLoc, &color, 1);
    program.setUniformValueArray(mvpLoc, &camera.getProjMatrix(), 1);

    //bind and set the vertex buffer for attribute
    vertBuffer.bind();
    program.enableAttributeArray(vertLoc);
    program.setAttributeBuffer(vertLoc, GL_FLOAT, 0, 4);

    //bind the index buffer for the draw call
    indexBuffer.bind();

    qDebug()<<"[AxisRender] Drawing";

    //draw the index buffer NOTE: Hard set to 24 values for a box!
    glDrawElements(GL_LINES, 24, GL_UNSIGNED_INT, NULL);
}
Example #9
0
 /// @overload QGLWidget
 void initializeGL(){     
     printf("OpenGL %d.%d\n",this->format().majorVersion(),this->format().minorVersion());
     
     ///--- Create an array object to store properties
     {
         bool success = vao.create();
         Q_ASSERT(success);
         vao.bind();
     }
     
     ///--- Load/compile shaders
     {
         bool vok = program.addShaderFromSourceCode(QGLShader::Vertex, vshader);
         bool fok = program.addShaderFromSourceCode(QGLShader::Fragment, fshader);
         bool lok = program.link ();
         Q_ASSERT(lok && vok && fok);
         bool success = program.bind();
         Q_ASSERT(success);
     }
     
     ///--- Create vertex buffer/attributes "position"
     {
         static float vertices[] = {
             -1.0000,-1.0000,+0.0000,
             +1.0000,-1.0000,+0.0000,
             -1.0000,+1.0000,+0.0000,
             +1.0000,+1.0000,+0.0000,};
         
         vertexbuffer = QGLBuffer(QGLBuffer::VertexBuffer);
         bool success = vertexbuffer.create();
         Q_ASSERT(success);
         vertexbuffer.setUsagePattern( QGLBuffer::StaticDraw ); 
         success = vertexbuffer.bind();
         Q_ASSERT(success);
         vertexbuffer.allocate( vertices, sizeof(vertices) );
         program.setAttributeBuffer("position", GL_FLOAT, 0, 3 );
         program.enableAttributeArray("position");
     }
     
     ///--- Unbind to avoid pollution
     vao.release();
     program.release();
     
     ///--- Background
     glClearColor(1.0, 1.0, 1.0, 1.0);
             
     ///--- Setup opengl flags
     glDisable(GL_DEPTH_TEST);
 }
Example #10
0
void TextRenderer::renderOverlay( QString text, int x, int y, int width, int height, int renderMode )
{
     glActiveTexture( GL_TEXTURE13 );
    glBindTexture( GL_TEXTURE_2D, m_fontTextureGLuint[0] );

    glBindBuffer( GL_ARRAY_BUFFER, vboIds[ 0 ] );

    QGLShaderProgram* program = GLFunctions::getShader( "text" );
    program->bind();

    // Offset for position
    intptr_t offset = 0;
    // Tell OpenGL programmable pipeline how to locate vertex position data
    int vertexLocation = program->attributeLocation( "a_position" );
    program->enableAttributeArray( vertexLocation );
    glVertexAttribPointer( vertexLocation, 3, GL_FLOAT, GL_FALSE, 3*sizeof(float), (const void *) offset );

    program->setUniformValue( "u_x", (float)x );
    program->setUniformValue( "u_y", (float)y );
    program->setUniformValue( "u_z", -0.6f );
    program->setUniformValue( "u_width", (float)width );
    program->setUniformValue( "u_height", (float)height );
    program->setUniformValue( "u_scaleX", 1.0f );
    program->setUniformValue( "u_scaleY", 1.0f );
    program->setUniformValue( "u_sizeX", m_textSizeX  / (float)width );
    program->setUniformValue( "u_sizeY", m_textSizeY  / (float)height );
    program->setUniformValue( "u_textColor", m_textColor.redF(), m_textColor.greenF(), m_textColor.blueF() );

    program->setUniformValue( "u_alpha", 1.0f );
    program->setUniformValue( "u_renderMode", renderMode );
    program->setUniformValue( "u_canvasSize", width, height );
    program->setUniformValue( "fontTex", 13 );
    program->setUniformValue( "D0", 9 );
    program->setUniformValue( "D1", 10 );
    program->setUniformValue( "D2", 11 );
    program->setUniformValue( "P0", 12 );
    program->setUniformValue( "u_overlay", 1 );

    for ( int i = 0; i < text.size(); ++i )
    {
        QChar c = text.at( i );
        program->setUniformValue( "u_char", (float)m_characterPositions[ c ] );
        program->setUniformValue( "u_pos", (float)i );
        glDrawArrays( GL_TRIANGLE_STRIP, 0, 4 );
    }

    glBindBuffer( GL_ARRAY_BUFFER, 0 );
}
Example #11
0
void AxisRenderer::drawBrush(const M3DEditLevel::Box &brush, QGLShaderProgram &program, const AxisCamera &camera)
{
    QVector<QVector3D> temp = brush.getVerticies();
    QVector<GLfloat> verts;

    //fill vector with brush verticies
    for(int i = 0; i < temp.size(); ++i){
        QVector3D vert = temp[i];
        verts.push_back(vert.x());
        verts.push_back(vert.y());
        verts.push_back(vert.z());
        verts.push_back(1.0f);
    }

    QVector<unsigned int> indicies = brush.getLineIndex();

    //bind brush buffer and fill with verticies
    QGLBuffer brushBuffer(QGLBuffer::VertexBuffer);
    brushBuffer.create();
    brushBuffer.bind();
    brushBuffer.allocate(verts.data(), sizeof(GLfloat) * verts.size());

    //bind index buffer and fill with indicies
    QGLBuffer brushIndex(QGLBuffer::IndexBuffer);
    brushIndex.create();
    brushIndex.bind();
    brushIndex.allocate(indicies.data(), sizeof(unsigned int) * indicies.size());

    //set up uniforms
    program.bind();
    program.setUniformValueArray("color", &QVector4D(1.0f, 1.0f, 1.0f, 1.0f), 1);
    program.setUniformValueArray("modelToCamera", &camera.getProjMatrix(), 1);

    //set up buffers
    brushBuffer.bind();
    program.enableAttributeArray("vertex");
    program.setAttributeBuffer("vertex", GL_FLOAT, 0, 4);

    //draw brush. NOTE: Fixed 24 indicies for a box only!
    brushIndex.bind();
    glDrawElements(GL_LINES, 24, GL_UNSIGNED_INT, 0);


}
Example #12
0
void AxisRenderer::drawCamLine(QVector3D from, QVector3D to, QGLShaderProgram &program, const AxisCamera &camera)
{
    const GLfloat color[] ={1.0f, 0.0f, 0.0f, 1.0f}; //default red color

    //temp vector to hold line verticies
    std::vector<GLfloat> bufferData;

    //from verticies
    bufferData.push_back(from.x());
    bufferData.push_back(from.y());
    bufferData.push_back(from.z());
    bufferData.push_back(1.0f);

    //to verticies
    bufferData.push_back(to.x());
    bufferData.push_back(to.y());
    bufferData.push_back(to.z());
    bufferData.push_back(1.0f);

    program.bind();

    //create and fill line buffer with verticies
    QGLBuffer line(QGLBuffer::VertexBuffer);
    line.create();
    line.bind();
    line.allocate(bufferData.data(), sizeof(GLfloat) * 8);

    //get locations
    GLuint colorLoc = program.uniformLocation("color");
    Q_ASSERT(colorLoc != -1);
    GLuint mvpLoc = program.uniformLocation("modelToCamera");
    Q_ASSERT(mvpLoc != -1);

    //setup line for drawing
    line.bind();
    program.enableAttributeArray("vertex");
    program.setAttributeBuffer("vertex", GL_FLOAT, 0, 4);
    program.setUniformValueArray(colorLoc, color, 1, 4);
    program.setUniformValueArray(mvpLoc, &(camera.getProjMatrix()), 1);

    glDrawArrays(GL_LINES, 0, 2);
}
/*!
    \reimp
*/
void QGLPerVertexColorEffect::setActive(QGLPainter *painter, bool flag)
{
#if defined(QGL_FIXED_FUNCTION_ONLY)
    Q_UNUSED(painter);
    if (flag) {
        glEnableClientState(GL_VERTEX_ARRAY);
        glEnableClientState(GL_COLOR_ARRAY);
    } else {
        glDisableClientState(GL_VERTEX_ARRAY);
        glDisableClientState(GL_COLOR_ARRAY);
    }
#else
    Q_UNUSED(painter);
    Q_D(QGLPerVertexColorEffect);
#if !defined(QGL_SHADERS_ONLY)
    if (painter->isFixedFunction()) {
        d->isFixedFunction = true;
        if (flag) {
            glEnableClientState(GL_VERTEX_ARRAY);
            glEnableClientState(GL_COLOR_ARRAY);
        } else {
            glDisableClientState(GL_VERTEX_ARRAY);
            glDisableClientState(GL_COLOR_ARRAY);
        }
        return;
    }
#endif
    static char const pvColorVertexShader[] =
        "attribute highp vec4 vertex;\n"
        "attribute mediump vec4 color;\n"
        "uniform highp mat4 matrix;\n"
        "varying mediump vec4 qColor;\n"
        "void main(void)\n"
        "{\n"
        "    gl_Position = matrix * vertex;\n"
        "    qColor = color;\n"
        "}\n";

    static char const pvColorFragmentShader[] =
        "varying mediump vec4 qColor;\n"
        "void main(void)\n"
        "{\n"
        "    gl_FragColor = qColor;\n"
        "}\n";

    QGLShaderProgram *program =
        painter->cachedProgram(QLatin1String("qt.color.pervertex"));
    d->program = program;
    if (!program) {
        if (!flag)
            return;
        program = new QGLShaderProgram();
        program->addShaderFromSourceCode(QGLShader::Vertex, pvColorVertexShader);
        program->addShaderFromSourceCode(QGLShader::Fragment, pvColorFragmentShader);
        program->bindAttributeLocation("vertex", QGL::Position);
        program->bindAttributeLocation("color", QGL::Color);
        if (!program->link()) {
            qWarning("QGLPerVertexColorEffect::setActive(): could not link shader program");
            delete program;
            program = 0;
            return;
        }
        painter->setCachedProgram(QLatin1String("qt.color.pervertex"), program);
        d->program = program;
        d->matrixUniform = program->uniformLocation("matrix");
        program->bind();
        program->enableAttributeArray(QGL::Position);
        program->enableAttributeArray(QGL::Color);
    } else if (flag) {
        d->matrixUniform = program->uniformLocation("matrix");
        program->bind();
        program->enableAttributeArray(QGL::Position);
        program->enableAttributeArray(QGL::Color);
    } else {
        program->disableAttributeArray(QGL::Position);
        program->disableAttributeArray(QGL::Color);
        program->release();
    }
#endif
}
Example #14
0
void FiberRenderer::draw( QMatrix4x4 p_matrix, QMatrix4x4 mv_matrix, int width, int height, int renderMode, PropertyGroup& props )
{
    float alpha = props.get( Fn::Property::D_ALPHA ).toFloat();
    if ( renderMode == 0 ) // picking
    {
        return;
    }
    else if ( renderMode == 1 ) // we are drawing opaque objects
    {
        if ( alpha < 1.0 )
        {
            // obviously not opaque
            return;
        }
    }
    else // we are drawing tranparent objects
    {
        if ( !(alpha < 1.0 ) )
        {
            // not transparent
            return;
        }
    }

    if ( m_updateExtraData )
    {
    	updateExtraData( m_selectedExtraData );
    }

    QGLShaderProgram* program = GLFunctions::getShader( "fiber" );
    program->bind();

    GLFunctions::setupTextures();
    GLFunctions::setTextureUniforms( GLFunctions::getShader( "fiber" ), "maingl" );

    // Set modelview-projection matrix
    program->setUniformValue( "mvp_matrix", p_matrix * mv_matrix );
    program->setUniformValue( "mv_matrixInvert", mv_matrix.inverted() );
    program->setUniformValue( "mv_matrixTI", mv_matrix.transposed().inverted() );
    program->setUniformValue( "userTransformMatrix", props.get( Fn::Property::D_TRANSFORM ).value<QMatrix4x4>() );

    initGeometry();

    glBindBuffer( GL_ARRAY_BUFFER, vbo );
    setShaderVars( props );

    glBindBuffer( GL_ARRAY_BUFFER, dataVbo );
    int extraLocation = program->attributeLocation( "a_extra" );
    program->enableAttributeArray( extraLocation );
    glVertexAttribPointer( extraLocation, 1, GL_FLOAT, GL_FALSE, sizeof(float), 0 );

    glBindBuffer( GL_ARRAY_BUFFER, indexVbo );
    int indexLocation = program->attributeLocation( "a_indexes" );
    program->enableAttributeArray( indexLocation );
    glVertexAttribPointer( indexLocation, 1, GL_FLOAT, GL_FALSE, sizeof(float), 0 );

    program->setUniformValue( "u_alpha", alpha );
    program->setUniformValue( "u_renderMode", renderMode );
    program->setUniformValue( "u_canvasSize", width, height );
    program->setUniformValue( "D0", 9 );
    program->setUniformValue( "D1", 10 );
    program->setUniformValue( "D2", 11 );
    program->setUniformValue( "P0", 12 );
    program->setUniformValue( "C5", 13 );
    program->setUniformValue( "u_fibGrowth", props.get( Fn::Property::D_FIBER_GROW_LENGTH).toFloat() );

    program->setUniformValue( "u_lighting", props.get( Fn::Property::D_LIGHT_SWITCH ).toBool() );
    program->setUniformValue( "u_lightAmbient", props.get( Fn::Property::D_LIGHT_AMBIENT ).toFloat() );
    program->setUniformValue( "u_lightDiffuse", props.get( Fn::Property::D_LIGHT_DIFFUSE ).toFloat() );
    program->setUniformValue( "u_materialAmbient", props.get( Fn::Property::D_MATERIAL_AMBIENT ).toFloat() );
    program->setUniformValue( "u_materialDiffuse", props.get( Fn::Property::D_MATERIAL_DIFFUSE ).toFloat() );
    program->setUniformValue( "u_materialSpecular", props.get( Fn::Property::D_MATERIAL_SPECULAR ).toFloat() );
    program->setUniformValue( "u_materialShininess", props.get( Fn::Property::D_MATERIAL_SHININESS ).toFloat() );

    glLineWidth( props.get( Fn::Property::D_FIBER_THICKNESS ).toFloat() );

    std::vector<bool>*selected = m_selector->getSelection();

    int percent = props.get( Fn::Property::D_FIBER_THIN_OUT ).toFloat() * 10;

    for ( unsigned int i = 0; i < m_fibs->size(); ++i )
    {
        if ( ( i % 1000 ) > percent )
        {
            continue;
        }

        if ( selected->at( i ) )
        {
            QColor c = m_fibs->at( i ).customColor();
            program->setUniformValue( "u_color", c.redF(), c.greenF(), c.blueF(), 1.0 );
            c = m_fibs->at( i ).globalColor();
            program->setUniformValue( "u_globalColor", c.redF(), c.greenF(), c.blueF(), 1.0 );
            glDrawArrays( GL_LINE_STRIP, m_startIndexes[i], m_pointsPerLine[i] );
        }
        else
        {
            if ( Models::getGlobal( Fn::Property::G_UNSELECTED_FIBERS_GREY ).toBool() )
            {
                program->setUniformValue( "u_color", .4f, .4f, .4f, 1.0 );
                program->setUniformValue( "u_globalColor", .4f, .4f, .4f, 1.0 );
                glDrawArrays( GL_LINE_STRIP, m_startIndexes[i], m_pointsPerLine[i] );
            }
        }
    }


    glBindBuffer( GL_ARRAY_BUFFER, 0 );
}
Example #15
0
void TextRenderer::renderLabel( QMatrix4x4 p_matrix, QMatrix4x4 mv_matrix, QString text, float x, float y, float z, float alpha, int width, int height, int renderMode )
{
    switch ( renderMode )
    {
        case 0:
            break;
        case 1:
        {
            if ( alpha < 1.0 ) // obviously not opaque
            {
                return;
            }
            break;
        }
        default:
        {
            if ( alpha == 1.0  ) // not transparent
            {
                return;
            }
            break;
        }
    }

    glActiveTexture( GL_TEXTURE13 );
    glBindTexture( GL_TEXTURE_2D, m_fontTextureGLuint[0] );

    glBindBuffer( GL_ARRAY_BUFFER, vboIds[ 0 ] );

    QGLShaderProgram* program = GLFunctions::getShader( "text" );
    program->bind();

    // Offset for position
    intptr_t offset = 0;
    // Tell OpenGL programmable pipeline how to locate vertex position data
    int vertexLocation = program->attributeLocation( "a_position" );
    program->enableAttributeArray( vertexLocation );
    glVertexAttribPointer( vertexLocation, 3, GL_FLOAT, GL_FALSE, 3*sizeof(float), (const void *) offset );

    program->setUniformValue( "mvp_matrix", p_matrix * mv_matrix );
    program->setUniformValue( "u_x", x );
    program->setUniformValue( "u_y", y );
    program->setUniformValue( "u_z", z );
    program->setUniformValue( "u_width", (float)width );
    program->setUniformValue( "u_height", (float)height );
    program->setUniformValue( "u_scaleX", 1.0f );
    program->setUniformValue( "u_scaleY", 1.0f );
    program->setUniformValue( "u_sizeX", m_textSizeX  / (float)width );
    program->setUniformValue( "u_sizeY", m_textSizeY  / (float)height );
    program->setUniformValue( "u_textColor", m_textColor.redF(), m_textColor.greenF(), m_textColor.blueF() );

    program->setUniformValue( "u_alpha", 1.0f );
    program->setUniformValue( "u_renderMode", renderMode );
    program->setUniformValue( "u_canvasSize", width, height );
    program->setUniformValue( "fontTex", 13 );
    program->setUniformValue( "D0", 9 );
    program->setUniformValue( "D1", 10 );
    program->setUniformValue( "D2", 11 );
    program->setUniformValue( "P0", 12 );
    program->setUniformValue( "u_overlay", 0 );

    for ( int i = 0; i < text.size(); ++i )
    {
        QChar c = text.at( i );
        program->setUniformValue( "u_char", (float)m_characterPositions[ c ] );
        program->setUniformValue( "u_pos", (float)i );
        glDrawArrays( GL_TRIANGLE_STRIP, 0, 4 );
    }

    glBindBuffer( GL_ARRAY_BUFFER, 0 );
}
Example #16
0
void AxisRenderer::renderOrigin(QGLShaderProgram &program, const AxisCamera &camera)
{
    qDebug()<<"[AxisRender] drawing origin lines";
    initializeGLFunctions();

    //data for the xline
    const GLfloat xline[] = {
        0.0f, 0.0f, 0.0f, 1.0f,
        5.0f, 0.0f, 0.0f, 1.0f
    };

    //data for the yline
    const GLfloat yline[] = {
        0.0f, 0.0f, 0.0f, 1.0f,
        0.0f, 5.0f, 0.0f, 1.0f
    };

    //data for the zline
    const GLfloat zline[] = {
        0.0f, 0.0f, 0.0f, 1.0f,
        0.0f, 0.0f, 5.0f, 1.0f
    };

    //data for each line color
    const GLfloat xcolor[] = { 1.0f, 0.0f, 0.0f, 1.0f};
    const GLfloat ycolor[] = { 0.0f, 1.0f, 0.0f, 1.0f};
    const GLfloat zcolor[] = { 1.0f, 0.0f, 1.0f, 1.0f};

    //fill buffer for xline
    QGLBuffer xbuff(QGLBuffer::VertexBuffer);
    xbuff.create();
    xbuff.bind();
    xbuff.setUsagePattern(QGLBuffer::StaticDraw);
    xbuff.allocate(xline, sizeof(xline));

    //fill buffer for yline
    QGLBuffer ybuff(QGLBuffer::VertexBuffer);
    ybuff.create();
    ybuff.bind();
    ybuff.setUsagePattern(QGLBuffer::StaticDraw);
    ybuff.allocate(yline, sizeof(yline));

    //fill buffer for zline
    QGLBuffer zbuff(QGLBuffer::VertexBuffer);
    zbuff.create();
    zbuff.bind();
    zbuff.setUsagePattern(QGLBuffer::StaticDraw);
    zbuff.allocate(zline, sizeof(zline));

    program.bind();

    //set the uniforms
    GLuint colorLoc = program.uniformLocation("color");
    Q_ASSERT(colorLoc != -1);
    GLuint mvpLoc = program.uniformLocation("modelToCamera");
    Q_ASSERT(mvpLoc != -1);
    program.setUniformValueArray(mvpLoc, &(camera.getProjMatrix()), 1);

    //bind then draw xline
    xbuff.bind();
    program.enableAttributeArray("vertex");
    program.setAttributeBuffer("vertex", GL_FLOAT, 0, 4);
    program.setUniformValueArray(colorLoc, xcolor, 1, 4);

    glDrawArrays(GL_LINES, 0, 2);

    //bind then draw yline
    ybuff.bind();
    program.setAttributeBuffer("vertex", GL_FLOAT, 0, 4);
    program.setUniformValueArray(colorLoc, ycolor, 1, 4);

    glDrawArrays(GL_LINES, 0, 2);

    //bind then draw zline
    zbuff.bind();
    program.setAttributeBuffer("vertex", GL_FLOAT, 0, 4);
    program.setUniformValueArray(colorLoc, zcolor, 1, 4);

    glDrawArrays(GL_LINES, 0, 2);

    //destroy the buffers(Probably should be created and stored for longer than one call but context issue)
    xbuff.bind();
    xbuff.destroy();

    ybuff.bind();
    ybuff.destroy();

    zbuff.bind();
    zbuff.destroy();

}
Example #17
0
DrawCount PointArray::drawPoints(QGLShaderProgram& prog, const TransformState& transState,
                                 double quality, bool incrementalDraw) const
{
    GLuint vao = getVAO("points");
    glBindVertexArray(vao);

    GLuint vbo = getVBO("point_buffer");
    glBindBuffer(GL_ARRAY_BUFFER, vbo);

    TransformState relativeTrans = transState.translate(offset());
    relativeTrans.setUniforms(prog.programId());
    //printActiveShaderAttributes(prog.programId());
    std::vector<ShaderAttribute> activeAttrs = activeShaderAttributes(prog.programId());
    // Figure out shader locations for each point field
    // TODO: attributeLocation() forces the OpenGL usage here to be
    // synchronous.  Does this matter?  (Alternative: bind them ourselves.)
    std::vector<const ShaderAttribute*> attributes;
    for (size_t i = 0; i < m_fields.size(); ++i)
    {
        const GeomField& field = m_fields[i];
        if (field.spec.isArray())
        {
            for (int j = 0; j < field.spec.count; ++j)
            {
                std::string name = tfm::format("%s[%d]", field.name, j);
                attributes.push_back(findAttr(name, activeAttrs));
            }
        }
        else
        {
            attributes.push_back(findAttr(field.name, activeAttrs));
        }
    }
    // Zero out active attributes in case they don't have associated fields
    GLfloat zeros[16] = {0};
    for (size_t i = 0; i < activeAttrs.size(); ++i)
    {
        prog.setAttributeValue((int)i, zeros, activeAttrs[i].rows,
                               activeAttrs[i].cols);
    }
    // Enable attributes which have associated fields
    for (size_t i = 0; i < attributes.size(); ++i)
    {
        if (attributes[i])
            prog.enableAttributeArray(attributes[i]->location);
    }

    DrawCount drawCount;
    ClipBox clipBox(relativeTrans);

    // Draw points in each bucket, with total number drawn depending on how far
    // away the bucket is.  Since the points are shuffled, this corresponds to
    // a stochastic simplification of the full point cloud.
    V3f relCamera = relativeTrans.cameraPos();
    std::vector<const OctreeNode*> nodeStack;
    nodeStack.push_back(m_rootNode.get());
    while (!nodeStack.empty())
    {
        const OctreeNode* node = nodeStack.back();
        nodeStack.pop_back();
        if (clipBox.canCull(node->bbox))
            continue;
        if (!node->isLeaf())
        {
            for (int i = 0; i < 8; ++i)
            {
                OctreeNode* n = node->children[i];
                if (n)
                    nodeStack.push_back(n);
            }
            continue;
        }
        size_t idx = node->beginIndex;
        if (!incrementalDraw)
            node->nextBeginIndex = node->beginIndex;

        DrawCount nodeDrawCount = node->drawCount(relCamera, quality, incrementalDraw);
        drawCount += nodeDrawCount;

        idx = node->nextBeginIndex;
        if (nodeDrawCount.numVertices == 0)
            continue;

        if (m_fields.size() < 1)
            continue;

        long bufferSize = 0;
        for (size_t i = 0; i < m_fields.size(); ++i)
        {
            const GeomField &field = m_fields[i];
            unsigned int arraySize = field.spec.arraySize();
            unsigned int vecSize = field.spec.vectorSize();

            // tfm::printfln("FIELD-NAME: %s", field.name);
            // tfm::printfln("AS: %i, VS: %i, FSS: %i, FSES: %i, GLBTFSS: %i", arraySize, vecSize, field.spec.size(), field.spec.elsize, sizeof(glBaseType(field.spec)));

            bufferSize += arraySize * vecSize * field.spec.elsize; //sizeof(glBaseType(field.spec));
        }

        bufferSize = bufferSize * (GLsizei)nodeDrawCount.numVertices;

        // TODO: might be able to do something more efficient here, for example use glBufferSubData to avoid re-allocation of memory by glBufferData
        // INITIALIZE THE BUFFER TO FULL SIZE
        // tfm::printfln("INIT BUFFER: %i, BS: %i", vbo, bufferSize);

        glBufferData(GL_ARRAY_BUFFER, (GLsizeiptr)bufferSize, NULL, GL_STREAM_DRAW);
        /// ========================================================================
        /// ========================================================================
        GLintptr bufferOffset = 0;

        for (size_t i = 0, k = 0; i < m_fields.size(); k+=m_fields[i].spec.arraySize(), ++i)
        {
            const GeomField& field = m_fields[i];
            int arraySize = field.spec.arraySize();
            int vecSize = field.spec.vectorSize();

            // TODO: should use a single data-array that isn't split into vertex / normal / color / etc. sections, but has interleaved data ?
            // OpenGL has a stride value in glVertexAttribPointer for exactly this purpose, which should be used for better efficiency
            // here we write only the current attribute data into this the buffer (e.g. all positions, then all colors)
            bufferSize = arraySize * vecSize * field.spec.elsize * (GLsizei)nodeDrawCount.numVertices; //sizeof(glBaseType(field.spec))

            char* bufferData = field.data.get() + idx*field.spec.size();
            glBufferSubData(GL_ARRAY_BUFFER, bufferOffset, bufferSize, bufferData);

            // tfm::printfln("UPDATE BUFFER: %i, BS: %i", vbo, bufferSize);

            for (int j = 0; j < arraySize; ++j)
            {
                const ShaderAttribute* attr = attributes[k+j];
                if (!attr)
                    continue;

                // we have to create an intermediate buffer offsets for glVertexAttribPointer, but we can still upload the whole data array earlier !?
                GLintptr intermediate_bufferOffset = bufferOffset + j*field.spec.elsize;

                if (attr->baseType == TypeSpec::Int || attr->baseType == TypeSpec::Uint)
                {
                    glVertexAttribIPointer(attr->location, vecSize,
                                           glBaseType(field.spec), 0, (const GLvoid *)intermediate_bufferOffset);
                }
                else
                {
                    glVertexAttribPointer(attr->location, vecSize,
                                          glBaseType(field.spec),
                                          field.spec.fixedPoint, 0, (const GLvoid *)intermediate_bufferOffset);
                }

                glEnableVertexAttribArray(attr->location);
            }

            bufferOffset += bufferSize;
        }

        glDrawArrays(GL_POINTS, 0, (GLsizei)nodeDrawCount.numVertices);
        node->nextBeginIndex += nodeDrawCount.numVertices;
    }
    //tfm::printf("Drew %d of total points %d, quality %f\n", totDraw, m_npoints, quality);

    // Disable all attribute arrays - leaving these enabled seems to screw with
    // the OpenGL fixed function pipeline in unusual ways.
    for (size_t i = 0; i < attributes.size(); ++i)
    {
        if (attributes[i])
            prog.disableAttributeArray(attributes[i]->location);
    }

    glBindBuffer(GL_ARRAY_BUFFER, 0);
    glBindVertexArray(0);

    return drawCount;
}
Example #18
0
DrawCount PointArray::drawPoints(QGLShaderProgram& prog, const TransformState& transState,
                                 double quality, bool incrementalDraw) const
{
    TransformState relativeTrans = transState.translate(offset());
    relativeTrans.setUniforms(prog.programId());
    //printActiveShaderAttributes(prog.programId());
    std::vector<ShaderAttribute> activeAttrs = activeShaderAttributes(prog.programId());
    // Figure out shader locations for each point field
    // TODO: attributeLocation() forces the OpenGL usage here to be
    // synchronous.  Does this matter?  (Alternative: bind them ourselves.)
    std::vector<const ShaderAttribute*> attributes;
    for (size_t i = 0; i < m_fields.size(); ++i)
    {
        const GeomField& field = m_fields[i];
        if (field.spec.isArray())
        {
            for (int j = 0; j < field.spec.count; ++j)
            {
                std::string name = tfm::format("%s[%d]", field.name, j);
                attributes.push_back(findAttr(name, activeAttrs));
            }
        }
        else
        {
            attributes.push_back(findAttr(field.name, activeAttrs));
        }
    }
    // Zero out active attributes in case they don't have associated fields
    GLfloat zeros[16] = {0};
    for (size_t i = 0; i < activeAttrs.size(); ++i)
    {
        prog.setAttributeValue((int)i, zeros, activeAttrs[i].rows,
                               activeAttrs[i].cols);
    }
    // Enable attributes which have associated fields
    for (size_t i = 0; i < attributes.size(); ++i)
    {
        if (attributes[i])
            prog.enableAttributeArray(attributes[i]->location);
    }

    DrawCount drawCount;
    ClipBox clipBox(relativeTrans);

    // Draw points in each bucket, with total number drawn depending on how far
    // away the bucket is.  Since the points are shuffled, this corresponds to
    // a stochastic simplification of the full point cloud.
    V3f relCamera = relativeTrans.cameraPos();
    std::vector<const OctreeNode*> nodeStack;
    nodeStack.push_back(m_rootNode.get());
    while (!nodeStack.empty())
    {
        const OctreeNode* node = nodeStack.back();
        nodeStack.pop_back();
        if (clipBox.canCull(node->bbox))
            continue;
        if (!node->isLeaf())
        {
            for (int i = 0; i < 8; ++i)
            {
                OctreeNode* n = node->children[i];
                if (n)
                    nodeStack.push_back(n);
            }
            continue;
        }
        size_t idx = node->beginIndex;
        if (!incrementalDraw)
            node->nextBeginIndex = node->beginIndex;

        DrawCount nodeDrawCount = node->drawCount(relCamera, quality, incrementalDraw);
        drawCount += nodeDrawCount;

        idx = node->nextBeginIndex;
        if (nodeDrawCount.numVertices == 0)
            continue;
        for (size_t i = 0, k = 0; i < m_fields.size(); k+=m_fields[i].spec.arraySize(), ++i)
        {
            const GeomField& field = m_fields[i];
            int arraySize = field.spec.arraySize();
            int vecSize = field.spec.vectorSize();
            for (int j = 0; j < arraySize; ++j)
            {
                const ShaderAttribute* attr = attributes[k+j];
                if (!attr)
                    continue;
                char* data = field.data.get() + idx*field.spec.size() +
                             j*field.spec.elsize;
                if (attr->baseType == TypeSpec::Int || attr->baseType == TypeSpec::Uint)
                {
                    glVertexAttribIPointer(attr->location, vecSize,
                                           glBaseType(field.spec), 0, data);
                }
                else
                {
                    glVertexAttribPointer(attr->location, vecSize,
                                          glBaseType(field.spec),
                                          field.spec.fixedPoint, 0, data);
                }
            }
        }
        glDrawArrays(GL_POINTS, 0, (GLsizei)nodeDrawCount.numVertices);
        node->nextBeginIndex += nodeDrawCount.numVertices;
    }
    //tfm::printf("Drew %d of total points %d, quality %f\n", totDraw, m_npoints, quality);

    // Disable all attribute arrays - leaving these enabled seems to screw with
    // the OpenGL fixed function pipeline in unusual ways.
    for (size_t i = 0; i < attributes.size(); ++i)
    {
        if (attributes[i])
            prog.disableAttributeArray(attributes[i]->location);
    }
    return drawCount;
}
Example #19
0
void DatasetIsoline::draw( QMatrix4x4 pMatrix, QMatrix4x4 mvMatrix, int width, int height, int renderMode, QString target )
{
    bool renderAnySlice =  m_properties["maingl"].get( Fn::Property::D_RENDER_AXIAL ).toBool() ||
                           m_properties["maingl"].get( Fn::Property::D_RENDER_CORONAL ).toBool() ||
                           m_properties["maingl"].get( Fn::Property::D_RENDER_SAGITTAL ).toBool();
    if ( !properties( target ).get( Fn::Property::D_ACTIVE ).toBool() || ! renderAnySlice )
    {
        return;
    }

    if ( m_dirty )
    {
        initGeometry();
    }

    float alpha = 1.0; //GLFunctions::sliceAlpha[target];

    switch ( renderMode )
    {
        case 0:
            break;
        case 1:
        {
            if ( alpha < 1.0 ) // obviously not opaque
            {
                return;
            }
            break;
        }
        default:
        {
            if ( alpha == 1.0  ) // not transparent
            {
                return;
            }
            break;
        }
    }

    QGLShaderProgram* program = GLFunctions::getShader( "stipple" );

    if ( ( m_vertCountAxial + m_vertCountCoronal + m_vertCountSagittal ) > 0 )
    {
        program->bind();

        intptr_t offset = 0;
        // Tell OpenGL programmable pipeline how to locate vertex position data
        GLFunctions::f->glBindBuffer( GL_ARRAY_BUFFER, vbo0 );

        int vertexLocation = program->attributeLocation( "a_position" );
        program->enableAttributeArray( vertexLocation );
        GLFunctions::f->glVertexAttribPointer( vertexLocation, 3, GL_FLOAT, GL_FALSE, sizeof(float) * 8, (const void *) offset );

        offset += sizeof(float) * 3;
        int offsetLocation = program->attributeLocation( "a_vec" );
        program->enableAttributeArray( offsetLocation );
        GLFunctions::f->glVertexAttribPointer( offsetLocation, 3, GL_FLOAT, GL_FALSE, sizeof(float) * 8, (const void *) offset );

        offset += sizeof(float) * 3;
        int dirLocation = program->attributeLocation( "a_dir2" );
        program->enableAttributeArray( dirLocation );
        GLFunctions::f->glVertexAttribPointer( dirLocation, 2, GL_FLOAT, GL_FALSE, sizeof(float) * 8, (const void *) offset );
        GLFunctions::f->glBindBuffer( GL_ARRAY_BUFFER, 0 );

        GLFunctions::f->glBindBuffer( GL_ARRAY_BUFFER, vbo1 );
        int colorLocation = program->attributeLocation( "a_color" );
        program->enableAttributeArray( colorLocation );
        GLFunctions::f->glVertexAttribPointer( colorLocation, 4, GL_FLOAT, GL_FALSE, 0, 0 );
        GLFunctions::f->glBindBuffer( GL_ARRAY_BUFFER, 0 );

        // Set modelview-projection matrix
        program->setUniformValue( "mvp_matrix", pMatrix * mvMatrix );
        program->setUniformValue( "u_scaling", 1.0f );

        program->setUniformValue( "u_alpha", 1.0f );
        program->setUniformValue( "u_renderMode", renderMode );
        program->setUniformValue( "u_canvasSize", width, height );
        program->setUniformValue( "D0", 9 );
        program->setUniformValue( "D1", 10 );
        program->setUniformValue( "D2", 11 );
        program->setUniformValue( "P0", 12 );

        program->setUniformValue( "u_aVec", 1., 0., 0. );
        program->setUniformValue( "u_bVec", 0., 1., 0. );
        program->setUniformValue( "u_orient", 0 );

        program->setUniformValue( "u_glyphThickness", m_properties["maingl"].get( Fn::Property::D_LINE_WIDTH ).toFloat() );
        program->setUniformValue( "u_glyphSize", m_properties["maingl"].get( Fn::Property::D_STIPPLE_GLYPH_SIZE ).toFloat() );
        program->setUniformValue( "u_constantThickness", true );

        if ( m_properties["maingl"].get( Fn::Property::D_RENDER_AXIAL ).toBool() && m_vertCountAxial > 0 )
        {
            glDrawArrays( GL_TRIANGLES, 0, m_vertCountAxial );
            GLFunctions::getAndPrintGLError( "render stipples: opengl error" );
        }

        if ( m_properties["maingl"].get( Fn::Property::D_RENDER_CORONAL ).toBool() && m_vertCountCoronal > 0 )
        {
            program->setUniformValue( "u_aVec", 1., 0., 0. );
            program->setUniformValue( "u_bVec", 0., 0., 1. );
            program->setUniformValue( "u_orient", 1 );

            glDrawArrays( GL_TRIANGLES, m_vertCountAxial, m_vertCountCoronal );
            GLFunctions::getAndPrintGLError( "render stipples: opengl error" );
        }

        if ( m_properties["maingl"].get( Fn::Property::D_RENDER_SAGITTAL ).toBool() && m_vertCountSagittal > 0 )
        {
            program->setUniformValue( "u_aVec", 0., 1., 0. );
            program->setUniformValue( "u_bVec", 0., 0., 1. );
            program->setUniformValue( "u_orient", 2 );

            glDrawArrays( GL_TRIANGLES, m_vertCountAxial + m_vertCountCoronal, m_vertCountSagittal );
            GLFunctions::getAndPrintGLError( "render stipples: opengl error" );
        }
    }

    if ( ( m_stripeVertCountAxial + m_stripeVertCountCoronal + m_stripeVertCountSagittal ) > 0 )
    {
        program->bind();

        intptr_t offset = 0;
        // Tell OpenGL programmable pipeline how to locate vertex position data
        GLFunctions::f->glBindBuffer( GL_ARRAY_BUFFER, vbo2 );

        int vertexLocation = program->attributeLocation( "a_position" );
        program->enableAttributeArray( vertexLocation );
        GLFunctions::f->glVertexAttribPointer( vertexLocation, 3, GL_FLOAT, GL_FALSE, sizeof(float) * 8, (const void *) offset );

        offset += sizeof(float) * 3;
        int offsetLocation = program->attributeLocation( "a_vec" );
        program->enableAttributeArray( offsetLocation );
        GLFunctions::f->glVertexAttribPointer( offsetLocation, 3, GL_FLOAT, GL_FALSE, sizeof(float) * 8, (const void *) offset );

        offset += sizeof(float) * 3;
        int dirLocation = program->attributeLocation( "a_dir2" );
        program->enableAttributeArray( dirLocation );
        GLFunctions::f->glVertexAttribPointer( dirLocation, 2, GL_FLOAT, GL_FALSE, sizeof(float) * 8, (const void *) offset );
        GLFunctions::f->glBindBuffer( GL_ARRAY_BUFFER, 0 );

        GLFunctions::f->glBindBuffer( GL_ARRAY_BUFFER, vbo3 );
        int colorLocation = program->attributeLocation( "a_color" );
        program->enableAttributeArray( colorLocation );
        GLFunctions::f->glVertexAttribPointer( colorLocation, 4, GL_FLOAT, GL_FALSE, 0, 0 );
        GLFunctions::f->glBindBuffer( GL_ARRAY_BUFFER, 0 );

        // Set modelview-projection matrix
        program->setUniformValue( "mvp_matrix", pMatrix * mvMatrix );
        program->setUniformValue( "u_scaling", 1.0f );

        program->setUniformValue( "u_alpha", 1.0f );
        program->setUniformValue( "u_renderMode", renderMode );
        program->setUniformValue( "u_canvasSize", width, height );
        program->setUniformValue( "D0", 9 );
        program->setUniformValue( "D1", 10 );
        program->setUniformValue( "D2", 11 );
        program->setUniformValue( "P0", 12 );

        program->setUniformValue( "u_aVec", 1., 0., 0. );
        program->setUniformValue( "u_bVec", 0., 1., 0. );
        program->setUniformValue( "u_orient", 0 );

        program->setUniformValue( "u_glyphThickness", m_properties["maingl"].get( Fn::Property::D_ISOLINE_STRIPES_WIDTH ).toFloat() );
        program->setUniformValue( "u_glyphSize", m_properties["maingl"].get( Fn::Property::D_STIPPLE_GLYPH_SIZE ).toFloat() );
        program->setUniformValue( "u_constantThickness", true );

        if ( m_properties["maingl"].get( Fn::Property::D_RENDER_AXIAL ).toBool() && m_stripeVertCountAxial > 0 )
        {
            glDrawArrays( GL_TRIANGLES, 0, m_stripeVertCountAxial );
            GLFunctions::getAndPrintGLError( "render stipples: opengl error" );
        }

        if ( m_properties["maingl"].get( Fn::Property::D_RENDER_CORONAL ).toBool() && m_stripeVertCountCoronal > 0 )
        {
            program->setUniformValue( "u_aVec", 1., 0., 0. );
            program->setUniformValue( "u_bVec", 0., 0., 1. );
            program->setUniformValue( "u_orient", 1 );

            glDrawArrays( GL_TRIANGLES, m_stripeVertCountAxial, m_stripeVertCountCoronal );
            GLFunctions::getAndPrintGLError( "render stipples: opengl error" );
        }

        if ( m_properties["maingl"].get( Fn::Property::D_RENDER_SAGITTAL ).toBool() && m_stripeVertCountSagittal > 0 )
        {
            program->setUniformValue( "u_aVec", 0., 1., 0. );
            program->setUniformValue( "u_bVec", 0., 0., 1. );
            program->setUniformValue( "u_orient", 2 );

            glDrawArrays( GL_TRIANGLES, m_stripeVertCountAxial + m_stripeVertCountCoronal, m_stripeVertCountSagittal );
            GLFunctions::getAndPrintGLError( "render stipples: opengl error" );
        }
    }
}
Example #20
0
    /// @overload QGLWidget
    void initializeGL(){     
        printf("OpenGL %d.%d\n",this->format().majorVersion(),this->format().minorVersion());
 
        ///--- Background
        glClearColor(1.0, 1.0, 1.0, 1.0);
        
        ///--- Viewport (simple, for unresizeable window)
        glViewport(0, 0, this->width(), this->height());
        
        ///--- Setup opengl flags
        glEnable(GL_DEPTH_TEST);
        
        ///--- Create the triangle index buffer
        {
            assert(mesh.is_triangle_mesh());
            triangles.clear();
            for(auto f: mesh.faces())
                for(auto v: mesh.vertices(f))
                    triangles.push_back(v.idx());
        }
        
        ///--- Create an array object to store properties
        {
            bool success = vao.create();
            assert(success);
            vao.bind();
        }
        
        ///--- Load/compile shaders
        {
            bool vok = program.addShaderFromSourceFile(QGLShader::Vertex, ":/vshader.glsl");
            bool fok = program.addShaderFromSourceFile(QGLShader::Fragment, ":/fshader.glsl");
            bool lok = program.link ();
            assert(lok && vok && fok);
            bool success = program.bind();
            assert(success);
        }
        
        ///--- Create vertex buffer/attributes "position"
        {
            auto vpoints = mesh.get_vertex_property<Vec3>("v:point");
            bool success = vertexbuffer.create();
            assert(success);
            vertexbuffer.setUsagePattern( QGLBuffer::StaticDraw ); 
            success = vertexbuffer.bind();
            assert(success);
            vertexbuffer.allocate( vpoints.data(), sizeof(Vec3) * mesh.n_vertices() );
            program.setAttributeBuffer("vpoint", GL_FLOAT, 0, 3 );
            program.enableAttributeArray("vpoint");
        }
        
        ///--- Create vertex buffer/attributes "normal"
        {
            auto vnormal = mesh.get_vertex_property<Vec3>("v:normal");
            bool success = normalbuffer.create();
            assert(success);
            normalbuffer.setUsagePattern( QGLBuffer::StaticDraw ); 
            success = normalbuffer.bind();
            assert(success);
            normalbuffer.allocate( vnormal.data(), sizeof(Vec3) * mesh.n_vertices() );
            program.setAttributeBuffer("vnormal", GL_FLOAT, 0, 3 );
            program.enableAttributeArray("vnormal");
        }
        
        ///--- Create the index "triangle" buffer
        {
            bool success = indexbuffer.create();
            assert(success);
            indexbuffer.setUsagePattern( QGLBuffer::StaticDraw ); 
            success = indexbuffer.bind();
            assert(success);
            indexbuffer.allocate(&triangles[0], triangles.size()*sizeof(unsigned int));
        }
        
#ifdef WITH_QGLVIEWER
        ///--- Setup camera
        {        
            Box3 bbox = OpenGP::bounding_box(mesh);
            camera()->setType(qglviewer::Camera::ORTHOGRAPHIC);
            camera()->setSceneCenter(qglviewer::tr(bbox.center()));
            camera()->setSceneRadius(bbox.diagonal().norm()/2.0);
            camera()->showEntireScene();
        }
#endif
        
        ///--- Unbind to avoid pollution
        vao.release();
        program.release();
    }
Example #21
0
void DatasetPlane::draw( QMatrix4x4 pMatrix, QMatrix4x4 mvMatrix, int width, int height, int renderMode, QString target )
{
    if ( !properties( target ).get( Fn::Property::D_ACTIVE ).toBool() )
    {
        return;
    }

    QVector3D h0 = m_properties["maingl"].get( Fn::Property::D_HANDLE_0 ).value<QVector3D>();
    QVector3D h1 = m_properties["maingl"].get( Fn::Property::D_HANDLE_1 ).value<QVector3D>();
    QVector3D h2 = m_properties["maingl"].get( Fn::Property::D_HANDLE_2 ).value<QVector3D>();

    if ( m_properties["maingl"].get( Fn::Property::D_SHOW_PLANE_HANDLES ).toBool() )
    {
        QColor color = m_properties["maingl"].get( Fn::Property::D_HANDLE_COLOR ).value<QColor>();
        color.setAlpha( 254 );
        GLFunctions::renderSphere( pMatrix, mvMatrix, h0.x(), h0.y(), h0.z(), 5, 5, 5,
                                  color, m_handle0, width, height, renderMode );
        GLFunctions::renderSphere( pMatrix, mvMatrix, h1.x(), h1.y(), h1.z(), 5, 5, 5,
                                  color, m_handle1, width, height, renderMode );
        GLFunctions::renderSphere( pMatrix, mvMatrix, h2.x(), h2.y(), h2.z(), 5, 5, 5,
                                  color, m_handle2, width, height, renderMode );
    }

    if ( dirty )
    {
        initGeometry();
    }

    float alpha = GLFunctions::sliceAlpha[target];

    switch ( renderMode )
    {
        case 0:
            break;
        case 1:
        {
            if ( alpha < 1.0 ) // obviously not opaque
            {
                return;
            }
            break;
        }
        default:
        {
            if ( alpha == 1.0  ) // not transparent
            {
                return;
            }
            break;
        }
    }

    if ( !GLFunctions::setupTextures() )
    {
        return;
    }
    QGLShaderProgram* program = GLFunctions::getShader( "slice" );

    program->bind();
    GLFunctions::f->glBindBuffer( GL_ARRAY_BUFFER, vbo0 );

    intptr_t offset = 0;
    // Tell OpenGL programmable pipeline how to locate vertex position data
    int vertexLocation = program->attributeLocation( "a_position" );
    program->enableAttributeArray( vertexLocation );
    GLFunctions::f->glVertexAttribPointer( vertexLocation, 3, GL_FLOAT, GL_FALSE, sizeof(float) * 3, (const void *) offset );

    // Set modelview-projection matrix
    program->setUniformValue( "mvp_matrix", pMatrix * mvMatrix );

    program->setUniformValue( "u_alpha", alpha );
    program->setUniformValue( "u_renderMode", renderMode );
    program->setUniformValue( "u_canvasSize", width, height );
    program->setUniformValue( "D0", 9 );
    program->setUniformValue( "D1", 10 );
    program->setUniformValue( "D2", 11 );
    program->setUniformValue( "P0", 12 );

    GLFunctions::setTextureUniforms( program, target );

    // Draw cube geometry using indices from VBO 0
    glDrawArrays( GL_TRIANGLE_STRIP, 0, 4 );
    GLFunctions::f->glBindBuffer( GL_ARRAY_BUFFER, 0 );

}
Example #22
0
void AxisRenderer::drawGrid(int gridSize, QGLShaderProgram &program,const AxisCamera &camera)
{
    qDebug()<< "[AxisRender] Drawing Grid";

    int gridNumber = camera.getGridFactor() * 2; //double size of grid to ensure it covers entire view
    float lineLimit = gridNumber * gridSize; //bounds of grid for this size and number

    qDebug()<< "[AxisRender] lineLimit = " << lineLimit;

    //general xline for grid
    float lineX[] = {lineLimit, 0.0f, 0.0f, 1.0f,
                     -lineLimit, 0.0f, 0.0f, 1.0f};

    //general yline for grid
    float lineY[] = { 0.0f, lineLimit, 0.0f, 1.0f,
                    0.0f, -lineLimit, 0.0f, 1.0f};

    //general zline for grid
    float lineZ[] = {0.0f, 0.0f, lineLimit, 1.0f,
                    0.0f, 0.0f, -lineLimit, 1.0f};

    //bind and fill xline buffer
    program.bind();
    QGLBuffer bufferX(QGLBuffer::VertexBuffer);
    bufferX.setUsagePattern(QGLBuffer::StaticDraw);
    bufferX.create();
    bufferX.bind();
    bufferX.allocate(lineX,sizeof(lineX));

    //bind and fill yline buffer
    QGLBuffer bufferY(QGLBuffer::VertexBuffer);
    bufferY.setUsagePattern(QGLBuffer::StaticDraw);
    bufferY.create();
    bufferY.bind();
    bufferY.allocate(lineY, sizeof(lineY));

    //bind and fill zline buffer
    QGLBuffer bufferZ(QGLBuffer::VertexBuffer);
    bufferZ.setUsagePattern(QGLBuffer::StaticDraw);
    bufferZ.create();
    bufferZ.bind();
    bufferZ.allocate(lineZ, sizeof(lineZ));

    QMatrix4x4 mvp;
    QMatrix4x4 vp = camera.getProjMatrix();
    QMatrix4x4 m;

    //find the offest based on camera position
    QVector3D pos = camera.getPosistion();
    int xoff = pos.x() / gridSize;
    int yoff = pos.y() / gridSize;
    int zoff = pos.z() / gridSize;

    //set color uniform to grey
    QVector4D color(0.3f, 0.3f, 0.3f, 1.0f);
    program.setUniformValueArray("color", &color, 1);

    //draw each line
    program.enableAttributeArray("vertex");
    for(int i = -gridNumber; i <= gridNumber; ++i){
        //x lines only for XY and XZ Axis
        if(camera.getLock() == XY || camera.getLock() == XZ)
        {
            bufferX.bind();
            program.setAttributeBuffer("vertex", GL_FLOAT, 0, 4);

            //use model matrix to translate each line with offset
            m.setToIdentity();
            m.translate(0.0f + (xoff * gridSize), (i + yoff) * gridSize, (i + zoff) * gridSize);

            mvp = vp * m ;//set mvp up

            //set mvp uniform then draw
            program.setUniformValueArray("modelToCamera", &mvp, 1);
            glDrawArrays(GL_LINES, 0, 2);
        }

        //y lines for XY and YZ axis only
        if(camera.getLock() == XY || camera.getLock() == YZ)
        {
            bufferY.bind();
            program.setAttributeBuffer("vertex", GL_FLOAT, 0, 4);

            //use model matrix to translate each line with offset
            m.setToIdentity();
            m.translate((i + xoff) * gridSize, 0.0f + (yoff * gridSize) ,(i + zoff) * gridSize);
            mvp = vp * m;

            //set mvp uniform and draw
            program.setUniformValueArray("modelToCamera", &mvp, 1);
            glDrawArrays(GL_LINES, 0, 2);
        }

        //z lines
        if(camera.getLock() == XZ || camera.getLock() == YZ)
        {
            bufferZ.bind();
            program.setAttributeBuffer("vertex", GL_FLOAT, 0, 4);

            //use model matrix to translate each line with offset
            m.setToIdentity();
            m.translate((i + xoff) * gridSize, (i + yoff) * gridSize ,0.0f + (zoff * gridSize));
            mvp = vp * m;

            //set mvp uniform then draw
            program.setUniformValueArray("modelToCamera", &mvp, 1);
            glDrawArrays(GL_LINES, 0, 2);
        }
    }
}