Example #1
0
bool checkOpenGL(){

    QGLWidget *glWidget = new QGLWidget;

    QGLContext* glContext = (QGLContext *) glWidget->context();
    GLCHK( glContext->makeCurrent() );

    int glMajorVersion, glMinorVersion;

    glMajorVersion = glContext->format().majorVersion();
    glMinorVersion = glContext->format().minorVersion();

    qDebug() << "Running the " + QString(AWESOME_BUMP_VERSION);
    qDebug() << "Checking OpenGL version...";
    qDebug() << "Widget OpenGL:" << QString("%1.%2").arg(glMajorVersion).arg(glMinorVersion);
    qDebug() << "Context valid:" << glContext->isValid() ;
    qDebug() << "OpenGL information:" ;
    qDebug() << "VENDOR:"       << (const char*)glGetString(GL_VENDOR) ;
    qDebug() << "RENDERER:"     << (const char*)glGetString(GL_RENDERER) ;
    qDebug() << "VERSION:"      << (const char*)glGetString(GL_VERSION) ;
    qDebug() << "GLSL VERSION:" << (const char*)glGetString(GL_SHADING_LANGUAGE_VERSION) ;

    Display3DSettings::openGLVersion = GL_MAJOR + (GL_MINOR * 0.1);

    delete glWidget;

    qDebug() << QString("Version: %1.%2").arg(glMajorVersion).arg(glMinorVersion);

    // check openGL version
    if( glMajorVersion < GL_MAJOR || (glMajorVersion == GL_MAJOR && glMinorVersion < GL_MINOR))
    {

        qDebug() << QString("Error: This version of AwesomeBump does not support openGL versions lower than %1.%2 :(").arg(GL_MAJOR).arg(GL_MINOR) ;
           return false;
    }
    return true;

}
Example #2
0
GraphicsView::GraphicsView(QWidget *parent) :
    QGraphicsView(parent),
    dt(1/100.0)
{
    // use opengl for rendering
    QGLWidget *widget = new QGLWidget(QGLFormat(QGL::SampleBuffers));
    widget->makeCurrent();
    setViewport(widget);
    setViewportUpdateMode(QGraphicsView::FullViewportUpdate);
    setCacheMode(QGraphicsView::CacheNone);

    // create graphics scene
    GraphicsScene *graphicsScene = new GraphicsScene(this);
    setScene(graphicsScene);

    // create world rendering thing
    WorldView* worldView = new WorldView(this, &worldModel);

    // make world rendering thing render when grahpics scene needs to draw stuff
    connect(graphicsScene, SIGNAL(render()), worldView, SLOT(render()));

    tick();
}
Example #3
0
GLView * GLView::create( NifSkope * window )
{
	QGLFormat fmt;
	static QList<QPointer<GLView> > views;

	QGLWidget * share = nullptr;
	for ( const QPointer<GLView>& v : views ) {
		if ( v )
			share = v;
	}

	// All new windows after the first window will share a format
	if ( share ) {
		fmt = share->format();
	} else {
		fmt.setSampleBuffers( Options::antialias() );
	}
	
	// OpenGL version
	fmt.setVersion( 2, 1 );
	// Ignored if version < 3.2
	//fmt.setProfile(QGLFormat::CoreProfile);

	// V-Sync
	fmt.setSwapInterval( 1 );
	fmt.setDoubleBuffer( true );

	fmt.setSamples( Options::antialias() ? 16 : 0 );

	fmt.setDirectRendering( true );
	fmt.setRgba( true );

	views.append( QPointer<GLView>( new GLView( fmt, window, share ) ) );

	return views.last();
}
Example #4
0
	//! Set the default painter to use when not drawing to FBO.
	//!
	//! This is the only place where we might be getting a painter from outside world,
	//! so we require that it uses a GL or GL2 paint engine.
	//!
	//! @param painter Painter to set.
	//! @param context GL context used by the renderer, for error checking.
	void setDefaultPainter(QPainter* const painter, const QGLContext* const context)
	{
		invariant();

#ifndef NDEBUG
		if(NULL != painter)
		{
			Q_ASSERT_X(painter->paintEngine()->type() == QPaintEngine::OpenGL ||
			           painter->paintEngine()->type() == QPaintEngine::OpenGL2,
			           Q_FUNC_INFO, 
			           "QGL StelRenderer backends need a QGLWidget to be set as the "
			           "viewport on the graphics view");
			QGLWidget* widget = dynamic_cast<QGLWidget*>(painter->device());
			Q_ASSERT_X(NULL != widget && widget->context() == context, Q_FUNC_INFO,
			           "Painter used with QGL StelRenderer backends needs to paint on a QGLWidget "
			           "with the same GL context as the one used by the renderer");
		}
#else
		Q_UNUSED(context);
#endif

		defaultPainter = painter;
		invariant();
	}
Example #5
0
void PacMan::initializeGL( QGLWidget & target ) {
  QImage pacman( "textures/pacman.png" );
  this->pacmanTexture = target.bindTexture( pacman );

  this->sphereList = glGenLists( 1 );
  this->sphereQuadric = gluNewQuadric();
  gluQuadricTexture( this->sphereQuadric, true );

  glNewList( this->sphereList, GL_COMPILE );
  {
    glBindTexture( GL_TEXTURE_2D, this->pacmanTexture );
    this->material.updateGlState( Material::Front );
    glRotatef( 180, 1.0f, 0.0f, 0.0f );
    gluSphere( this->sphereQuadric, this->radius, 360 / 5, 180 / 5 );
  }
  glEndList();
}
Example #6
0
void Ghost::initializeGL(QGLWidget& target) {
    QImage ghost("../gfx/ghost.png");
    _ghostTexture = target.bindTexture(ghost);

    _sphereList = glGenLists(1);
    _sphereQuadric = gluNewQuadric();
    gluQuadricTexture(_sphereQuadric, true);

    glNewList(_sphereList, GL_COMPILE);
    {
        glBindTexture(GL_TEXTURE_2D, _ghostTexture);
        _material.updateGlState(Material::Front);
        glRotatef(180, 1.0f, 0.0f, 0.0f);
        gluSphere(_sphereQuadric, _radius, 360/5, 180/5);
    }
    glEndList();
}
Example #7
0
void ApplicationOverlay::renderStatsAndLogs() {

    Application* application = Application::getInstance();

    QGLWidget* glWidget = application->getGLWidget();
    const OctreePacketProcessor& octreePacketProcessor = application->getOctreePacketProcessor();
    BandwidthMeter* bandwidthMeter = application->getBandwidthMeter();
    NodeBounds& nodeBoundsDisplay = application->getNodeBoundsDisplay();

    //  Display stats and log text onscreen
    glLineWidth(1.0f);
    glPointSize(1.0f);

    if (Menu::getInstance()->isOptionChecked(MenuOption::Stats)) {
        // let's set horizontal offset to give stats some margin to mirror
        int horizontalOffset = MIRROR_VIEW_WIDTH + MIRROR_VIEW_LEFT_PADDING * 2;
        int voxelPacketsToProcess = octreePacketProcessor.packetsToProcessCount();
        //  Onscreen text about position, servers, etc
        Stats::getInstance()->display(WHITE_TEXT, horizontalOffset, application->getFps(), application->getPacketsPerSecond(), application->getBytesPerSecond(), voxelPacketsToProcess);
        //  Bandwidth meter
        if (Menu::getInstance()->isOptionChecked(MenuOption::Bandwidth)) {
            Stats::drawBackground(0x33333399, glWidget->width() - 296, glWidget->height() - 68, 296, 68);
            bandwidthMeter->render(glWidget->width(), glWidget->height());
        }
    }

    //  Show on-screen msec timer
    if (Menu::getInstance()->isOptionChecked(MenuOption::FrameTimer)) {
        char frameTimer[10];
        quint64 mSecsNow = floor(usecTimestampNow() / 1000.0 + 0.5);
        sprintf(frameTimer, "%d\n", (int)(mSecsNow % 1000));
        int timerBottom =
            (Menu::getInstance()->isOptionChecked(MenuOption::Stats) &&
            Menu::getInstance()->isOptionChecked(MenuOption::Bandwidth))
            ? 80 : 20;
        drawText(glWidget->width() - 100, glWidget->height() - timerBottom, 0.30f, 0.0f, 0, frameTimer, WHITE_TEXT);
    }
    nodeBoundsDisplay.drawOverlay();
}
Example #8
0
void VideoWidget::initializeGL()
{
	glEnable(GL_MULTISAMPLE);

	QGLWidget *hidden = new QGLWidget( NULL, this );
	if ( hidden ) {
		hidden->hide();
		emit newSharedContext( hidden );
	}
	
	QGLWidget *thumb = new QGLWidget();
	if ( thumb ) {
		thumb->hide();
		emit newThumbContext( thumb );
	}
	
	QGLWidget *fences = new QGLWidget( NULL, this );
	if ( fences ) {
		fences->hide();
		emit newFencesContext( fences );
	}
}
Example #9
0
void RenderObject::Text::draw(QGLWidget& widget){
    Base::draw(widget);
    widget.renderText(_x, _y, _text, QFont("Time New Roman", _size));
}
Example #10
0
void GlSyncObjectMutex::
        test()
{
    string name = "GlSyncObjectMutex";
    int argc = 1;
    char * argv = &name[0];
    QApplication a(argc,&argv);
    QGLWidget w;
    w.makeCurrent ();
    thread t;

    // It should provide a mutex mechanism for OpenGL resources.
    try {
        unsigned vbo;
        GlException_SAFE_CALL( glGenBuffers (1, &vbo) );

        unsigned texture;
        GlException_SAFE_CALL( glGenTextures (1, &texture) );

        spinning_barrier barrier(2);

        // Most predictable benefit for large data sets, small datasets "might" work anyways
        int width = 1024;
        int height = 1024;
        const float N = 4*width*height;
        vector<float> result(N);
        vector<float> texture_init(N);
        vector<float> texture_update(N);

        auto resetVbosAndTexture = [&]()
        {
            for (unsigned i=0; i<N; i++)
            {
                result[i] = 1 + i;
                texture_init[i] = 2 + i;
                texture_update[i] = 3 + i;
            }

            GlException_SAFE_CALL( GlState::glBindBuffer (GL_ARRAY_BUFFER, vbo) );
            GlException_SAFE_CALL( glBufferData (GL_ARRAY_BUFFER, sizeof(float)*N, &texture_update[0], GL_DYNAMIC_COPY) );
            GlException_SAFE_CALL( GlState::glBindBuffer (GL_ARRAY_BUFFER, 0) );

            GlException_SAFE_CALL( glBindTexture (GL_TEXTURE_2D, texture) );
            GlException_SAFE_CALL( glTexImage2D (GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_FLOAT, &texture_init[0]) );
            // read with glGetTexImage to create an OpenGL client read state of the texture
            GlException_SAFE_CALL( glGetTexImage (GL_TEXTURE_2D, 0, GL_RGBA, GL_FLOAT, &result[0]) );
        };

        auto copyFromVboToTextureAsync = [&]()
        {
            GlException_SAFE_CALL( glBindTexture (GL_TEXTURE_2D, texture) );
            GlException_SAFE_CALL( GlState::glBindBuffer (GL_PIXEL_UNPACK_BUFFER, vbo) );
            GlException_SAFE_CALL( glTexSubImage2D  (GL_TEXTURE_2D, 0, 0, 0, width, height, GL_RGBA, GL_FLOAT, 0) );
            GlException_SAFE_CALL( GlState::glBindBuffer (GL_PIXEL_UNPACK_BUFFER, 0) );
        };

        auto copyFromTextureToResult = [&]()
        {
            GlException_SAFE_CALL( glBindTexture (GL_TEXTURE_2D, texture) );
            GlException_SAFE_CALL( glGetTexImage (GL_TEXTURE_2D, 0, GL_RGBA, GL_FLOAT, &result[0]) );
        };


        // Run OpenGL commands in a separate thread
        auto openglThread = [&](function<void()> f)
        {
            QGLWidget w2(0, &w);
            w2.makeCurrent ();

            f();

            // Finish all OpenGL commands on the gpu before destroying thread
            glFinish();
        };


        // Take 1. single threaded
        {
            resetVbosAndTexture();
            copyFromVboToTextureAsync();
            copyFromTextureToResult();

            EXCEPTION_ASSERT_EQUALS( 0, memcmp(&result[0], &texture_update[0], N*sizeof(float)));
        }


        // Take 2. multi-threaded, synchronized on cpu
        {
            resetVbosAndTexture();

            t = thread(openglThread, [&](){
                copyFromVboToTextureAsync();
                barrier.wait ();
                glFlush ();
                barrier.wait ();
            });

            barrier.wait ();
            copyFromTextureToResult();

            // should not have gotten all data from the other thread even though
            // the gl commands are issued (thanks to barrier.wait())
            EXCEPTION_ASSERT_NOTEQUALS( result[0], texture_update[0]);
            EXCEPTION_ASSERT_NOTEQUALS( result[N-1], texture_update[N-1]);
            EXCEPTION_ASSERT_EQUALS( result[0], texture_init[0]);
            EXCEPTION_ASSERT_EQUALS( result[N-1], texture_init[N-1]);
            EXCEPTION_ASSERT_EQUALS( 0, memcmp(&result[0], &texture_init[0], N*sizeof(float)));

            barrier.wait ();
            copyFromTextureToResult();
            t.join ();

            // Even after a glFlush() the texture state was not updated because this context
            // has used the texture more recently and discarded the update
            EXCEPTION_ASSERT_EQUALS( 0, memcmp(&result[0], &texture_init[0], N*sizeof(float)));
            EXCEPTION_ASSERT_NOTEQUALS( 0, memcmp(&result[0], &texture_update[0], N*sizeof(float)));
        }


        // Take 3. multi-threaded, synchronized cpu and gpu with glFlush after write
        {
            resetVbosAndTexture();

            t = thread(openglThread, [&](){
                copyFromVboToTextureAsync();
                glFlush ();
                barrier.wait ();
            });

            barrier.wait ();
            copyFromTextureToResult();
            t.join ();

            // the texture update is flushed to the gpu by the other thread
            // before this thread uses the texture

            // This time the transfer has finished
            EXCEPTION_ASSERT_EQUALS( result[0], texture_update[0]);
            EXCEPTION_ASSERT_EQUALS( result[N-1], texture_update[N-1]);
            EXCEPTION_ASSERT_EQUALS( 0, memcmp(&result[0], &texture_update[0], N*sizeof(float)));
        }


        // Take 4. multi-threaded, synchronized cpu and gpu with glClientWait before read, without glFlush
        {
            // unclear if/when GlSyncObjectMutex m(clientsync=false) is useful
            GlSyncObjectMutex m(true);

            resetVbosAndTexture();

            t = thread(openglThread, [&](){
                lock_guard<GlSyncObjectMutex> l(m);
                barrier.wait ();
                copyFromVboToTextureAsync();
                (void)l; // RAII, mark a synchronization point in the command queue
            });

            barrier.wait ();

            {
                lock_guard<GlSyncObjectMutex> l(m);
                copyFromTextureToResult();
                (void)l; // RAII
            }

            t.join ();

            // GlSyncObjectMutex will make sure that when the texture is
            // modified in different threads they first wait for the other
            // update is finished

            // This time the transfer has finished
            EXCEPTION_ASSERT_EQUALS( result[0], texture_update[0]);
            EXCEPTION_ASSERT_EQUALS( result[N-1], texture_update[N-1]);
            EXCEPTION_ASSERT_EQUALS( 0, memcmp(&result[0], &texture_update[0], N*sizeof(float)));
        }

        GlException_SAFE_CALL( glDeleteBuffers (1, &vbo) );
        GlException_SAFE_CALL( glDeleteTextures (1, &texture) );
    } catch (...) {
        if (t.joinable ())
            t.join ();
        throw;
    }
}
Example #11
0
Sprite::Sprite(const QString& name, const QVector3D& boundsMin, const QVector3D& boundsMax, 
               QGLWidget& glWidget)
   : imageDiffuse_("assets:/demo_data/sprites/" + name + "_diffuse_0.png")
   , imageNormal_("assets:/demo_data/sprites/" + name + "_normal_0.png")
   , imageOffset_("assets:/demo_data/sprites/" + name + "_offset_0.png")
   , boundsMin_(boundsMin)
   , boundsMax_(boundsMax)
   , pixelSize_(QVector2D(0.0f, 0.0f))
   , valid_(false)
   , creatorWidget_(glWidget)
{
    // All images must be successfully loaded
    if(imageDiffuse_.isNull())
    {
        qDebug() << "Failed to load diffuse image for sprite " << name;
        return;
    }
    if(imageNormal_.isNull())
    {
        qDebug() << "Failed to load normal image for sprite " << name;
        return;
    }
    if(imageOffset_.isNull())
    {
        qDebug() << "Failed to load offset image for sprite " << name;
        return;
    }

    // Image sizes must match
    if(!(imageDiffuse_.size() == imageNormal_.size() &&
         imageNormal_.size() == imageOffset_.size()))
    {
        qDebug() << "Image sizes in sprite " << name << " don't match";
        return;
    }

    pixelSize_ = QVector2D(imageDiffuse_.size().width(), imageDiffuse_.size().height());

    // Image sizes must be powers of two
    if(!isPowerOfTwo(imageDiffuse_.size().width()) ||
       !isPowerOfTwo(imageDiffuse_.size().height()))
    {
        qDebug() << "Non-power of two texture size for sprite " << name 
                 << " - not supported yet";
        return;
    }

    // Upload to GL textures.
    textureDiffuse_ = glWidget.bindTexture(imageDiffuse_, GL_TEXTURE_2D, GL_RGBA, 
                                           QGLContext::InvertedYBindOption);
    textureNormal_  = glWidget.bindTexture(imageNormal_,  GL_TEXTURE_2D, GL_RGB,
                                           QGLContext::InvertedYBindOption);
    textureOffset_  = glWidget.bindTexture(imageOffset_,  GL_TEXTURE_2D, GL_RGB,
                                           QGLContext::InvertedYBindOption);


    // Check that the textures were uploaded successfully.
    if(textureDiffuse_ == 0)
    {
        qDebug() << "Failed to create diffuse texture for sprite " << name;
        return;
    }
    if(textureNormal_ == 0)
    {
        qDebug() << "Failed to create normal texture for sprite " << name;
        return;
    }
    if(textureOffset_ == 0)
    {
        qDebug() << "Failed to create offset texture for sprite " << name;
        return;
    }

    valid_ = true;
}
Example #12
0
void NodeBounds::draw() {
    if (!(_showVoxelNodes || _showModelNodes || _showParticleNodes)) {
        _overlayText[0] = '\0';
        return;
    }

    NodeToJurisdictionMap& voxelServerJurisdictions = Application::getInstance()->getVoxelServerJurisdictions();
    NodeToJurisdictionMap& modelServerJurisdictions = Application::getInstance()->getModelServerJurisdictions();
    NodeToJurisdictionMap& particleServerJurisdictions = Application::getInstance()->getParticleServerJurisdictions();
    NodeToJurisdictionMap* serverJurisdictions;

    // Compute ray to find selected nodes later on.  We can't use the pre-computed ray in Application because it centers
    // itself after the cursor disappears.
    Application* application = Application::getInstance();
    QGLWidget* glWidget = application->getGLWidget();
    float mouseX = application->getMouseX() / (float)glWidget->width();
    float mouseY = application->getMouseY() / (float)glWidget->height();
    glm::vec3 mouseRayOrigin;
    glm::vec3 mouseRayDirection;
    application->getViewFrustum()->computePickRay(mouseX, mouseY, mouseRayOrigin, mouseRayDirection);

    // Variables to keep track of the selected node and properties to draw the cube later if needed
    Node* selectedNode = NULL;
    float selectedDistance = FLT_MAX;
    bool selectedIsInside = true;
    glm::vec3 selectedCenter;
    float selectedScale = 0;

    NodeList* nodeList = NodeList::getInstance();

    foreach (const SharedNodePointer& node, nodeList->getNodeHash()) {
        NodeType_t nodeType = node->getType();

        if (nodeType == NodeType::VoxelServer && _showVoxelNodes) {
            serverJurisdictions = &voxelServerJurisdictions;
        } else if (nodeType == NodeType::ModelServer && _showModelNodes) {
            serverJurisdictions = &modelServerJurisdictions;
        } else if (nodeType == NodeType::ParticleServer && _showParticleNodes) {
            serverJurisdictions = &particleServerJurisdictions;
        } else {
            continue;
        }

        QUuid nodeUUID = node->getUUID();
        if (serverJurisdictions->find(nodeUUID) != serverJurisdictions->end()) {
            const JurisdictionMap& map = serverJurisdictions->value(nodeUUID);

            unsigned char* rootCode = map.getRootOctalCode();

            if (rootCode) {
                VoxelPositionSize rootDetails;
                voxelDetailsForCode(rootCode, rootDetails);
                glm::vec3 location(rootDetails.x, rootDetails.y, rootDetails.z);
                location *= (float)TREE_SCALE;

                AABox serverBounds(location, rootDetails.s * TREE_SCALE);

                glm::vec3 center = serverBounds.getVertex(BOTTOM_RIGHT_NEAR)
                    + ((serverBounds.getVertex(TOP_LEFT_FAR) - serverBounds.getVertex(BOTTOM_RIGHT_NEAR)) / 2.0f);

                const float VOXEL_NODE_SCALE = 1.00f;
                const float MODEL_NODE_SCALE = 0.99f;
                const float PARTICLE_NODE_SCALE = 0.98f;

                float scaleFactor = rootDetails.s * TREE_SCALE;

                // Scale by 0.92 - 1.00 depending on the scale of the node.  This allows smaller nodes to scale in
                // a bit and not overlap larger nodes.
                scaleFactor *= 0.92 + (rootDetails.s * 0.08);

                // Scale different node types slightly differently because it's common for them to overlap.
                if (nodeType == NodeType::VoxelServer) {
                    scaleFactor *= VOXEL_NODE_SCALE;
                } else if (nodeType == NodeType::ModelServer) {
                    scaleFactor *= MODEL_NODE_SCALE;
                } else {
                    scaleFactor *= PARTICLE_NODE_SCALE;
                }

                float red, green, blue;
                getColorForNodeType(nodeType, red, green, blue);
                drawNodeBorder(center, scaleFactor, red, green, blue);

                float distance;
                BoxFace face;
                bool inside = serverBounds.contains(mouseRayOrigin);
                bool colliding = serverBounds.findRayIntersection(mouseRayOrigin, mouseRayDirection, distance, face);

                // If the camera is inside a node it will be "selected" if you don't have your cursor over another node
                // that you aren't inside.
                if (colliding && (!selectedNode || (!inside && (distance < selectedDistance || selectedIsInside)))) {
                    selectedNode = node.data();
                    selectedDistance = distance;
                    selectedIsInside = inside;
                    selectedCenter = center;
                    selectedScale = scaleFactor;
                }
            }
        }
    }

    if (selectedNode) {
        glPushMatrix();

        glTranslatef(selectedCenter.x, selectedCenter.y, selectedCenter.z);
        glScalef(selectedScale, selectedScale, selectedScale);

        NodeType_t selectedNodeType = selectedNode->getType();
        float red, green, blue;
        getColorForNodeType(selectedNode->getType(), red, green, blue);

        glColor4f(red, green, blue, 0.2);
        glutSolidCube(1.0);

        glPopMatrix();

        HifiSockAddr addr = selectedNode->getPublicSocket();
        QString overlay = QString("%1:%2  %3ms")
            .arg(addr.getAddress().toString())
            .arg(addr.getPort())
            .arg(selectedNode->getPingMs())
            .left(MAX_OVERLAY_TEXT_LENGTH);

        // Ideally we'd just use a QString, but I ran into weird blinking issues using
        // constData() directly, as if the data was being overwritten.
        strcpy(_overlayText, overlay.toLocal8Bit().constData());
    } else {
        _overlayText[0] = '\0';
    }
}
Example #13
0
CgContext::CgContext() :
   mbGpuSupported(false),
   mCgContext(0),
   mVertexIdentityProfile(CG_PROFILE_UNKNOWN),
   mFragmentIdentityProfile(CG_PROFILE_UNKNOWN)
{
   const QGLContext* pContext = QGLContext::currentContext();
   bool validGlContext = ( (pContext != NULL) && (pContext->isValid()) );
   QGLWidget* pGlWidget = NULL;
   if (!validGlContext)
   {
      //create a valid open gl context, so that the Cg
      //context can be initialized correctly
      class tmpGL : public QGLWidget {
      public:
         tmpGL(QWidget *parent) : QGLWidget(parent) {}
      protected:
         virtual void initializeGL() {}
         virtual void resizeGL(int w, int h) {}
         virtual void paintGL() {}
      private:
         tmpGL(const tmpGL& rhs) {}
         tmpGL& operator=(const tmpGL& rhs) { return *this; }
      };
      pGlWidget = new tmpGL(NULL);
      pGlWidget->makeCurrent();
   }

   glewInit();
   mCgContext = cgCreateContext();
   if (mCgContext)
   {
      bool bVertexCgProgramsSupported = true;
      bool bFragmentCgProgramsSupported = true;

      // Get the latest vertex profile or choose the CG_PROFILE_VP30 profile
      if (cgGLIsProfileSupported(cgGLGetLatestProfile(CG_GL_VERTEX)))
      {
         mVertexIdentityProfile = cgGLGetLatestProfile(CG_GL_VERTEX);
      }
      else if (cgGLIsProfileSupported(CG_PROFILE_VP30))
      {
         mVertexIdentityProfile = CG_PROFILE_VP30;
      }
      else
      {
         bVertexCgProgramsSupported = false;
      }

      // Set the optimal options
      cgGLSetOptimalOptions(mVertexIdentityProfile);

      // Get the latest fragment profile or choose the CG_PROFILE_FP30 profile
      if (cgGLIsProfileSupported(cgGLGetLatestProfile(CG_GL_FRAGMENT)))
      {
         mFragmentIdentityProfile = cgGLGetLatestProfile(CG_GL_FRAGMENT);
      }
      else if (cgGLIsProfileSupported(CG_PROFILE_FP30))
      {
         mFragmentIdentityProfile = CG_PROFILE_FP30;
      }
      else
      {
         bFragmentCgProgramsSupported = false;
      }

      // Set the optimal options
      cgGLSetOptimalOptions(mFragmentIdentityProfile);

      if ((bVertexCgProgramsSupported == true) && (bFragmentCgProgramsSupported == true))
      {
         mbGpuSupported = true;
      }
      else
      {
         cgDestroyContext(mCgContext);
         mCgContext = 0;
      }
   }

   if (pGlWidget != NULL)
   {
      delete pGlWidget;
   }
}
Example #14
0
//Renders a small magnification of the currently bound texture at the coordinates
void ApplicationOverlay::renderMagnifier(int mouseX, int mouseY)
{
    Application* application = Application::getInstance();
    QGLWidget* glWidget = application->getGLWidget();
    MyAvatar* myAvatar = application->getAvatar();
    const glm::vec3& viewMatrixTranslation = application->getViewMatrixTranslation();

    float leftX, rightX, leftZ, rightZ, topZ, bottomZ;

    const int widgetWidth = glWidget->width();
    const int widgetHeight = glWidget->height();
    const float magnification = 4.0f;

    // Get vertical FoV of the displayed overlay texture
    const float halfVerticalAngle = _oculusAngle / 2.0f;
    const float overlayAspectRatio = glWidget->width() / (float)glWidget->height();
    const float halfOverlayHeight = _distance * tan(halfVerticalAngle);

    // Get horizontal angle and angle increment from vertical angle and aspect ratio
    const float horizontalAngle = halfVerticalAngle * 2.0f * overlayAspectRatio;
    const float halfHorizontalAngle = horizontalAngle / 2;


    float magnifyWidth = 80.0f;
    float magnifyHeight = 60.0f;

    mouseX -= magnifyWidth / 2;
    mouseY -= magnifyHeight / 2;

    //clamp the magnification
    if (mouseX < 0) {
        magnifyWidth += mouseX;
        mouseX = 0;
    } else if (mouseX + magnifyWidth > widgetWidth) {
        magnifyWidth = widgetWidth - mouseX;
    }
    if (mouseY < 0) {
        magnifyHeight += mouseY;
        mouseY = 0;
    } else if (mouseY + magnifyHeight > widgetHeight) {
        magnifyHeight = widgetHeight - mouseY;
    }

    const float halfMagnifyHeight = magnifyHeight / 2.0f;

    float newWidth = magnifyWidth * magnification;
    float newHeight = magnifyHeight * magnification;

    // Magnification Texture Coordinates
    float magnifyULeft = mouseX / (float)widgetWidth;
    float magnifyURight = (mouseX + magnifyWidth) / (float)widgetWidth;
    float magnifyVBottom = 1.0f - mouseY / (float)widgetHeight;
    float magnifyVTop = 1.0f - (mouseY + magnifyHeight) / (float)widgetHeight;

    // Coordinates of magnification overlay
    float newMouseX = (mouseX + magnifyWidth / 2) - newWidth / 2.0f;
    float newMouseY = (mouseY + magnifyHeight / 2) + newHeight / 2.0f;

    // Get angle on the UI
    float leftAngle = (newMouseX / (float)widgetWidth) * horizontalAngle - halfHorizontalAngle;
    float rightAngle = ((newMouseX + newWidth) / (float)widgetWidth) * horizontalAngle - halfHorizontalAngle;

    float bottomAngle = (newMouseY / (float)widgetHeight) * _oculusAngle - halfVerticalAngle;
    float topAngle = ((newMouseY - newHeight) / (float)widgetHeight) * _oculusAngle - halfVerticalAngle;

    // Get position on hemisphere using angle
    if (_uiType == HEMISPHERE) {

        //Get new UV coordinates from our magnification window
        float newULeft = newMouseX / widgetWidth;
        float newURight = (newMouseX + newWidth) / widgetWidth;
        float newVBottom = 1.0 - newMouseY / widgetHeight;
        float newVTop = 1.0 - (newMouseY - newHeight) / widgetHeight;

        // Project our position onto the hemisphere using the UV coordinates
        float lX = sin((newULeft - 0.5f) * _textureFov);
        float rX = sin((newURight - 0.5f) * _textureFov);
        float bY = sin((newVBottom - 0.5f) * _textureFov);
        float tY = sin((newVTop - 0.5f) * _textureFov);

        float dist;
        //Bottom Left
        dist = sqrt(lX * lX + bY * bY);
        float blZ = sqrt(1.0f - dist * dist);
        //Top Left
        dist = sqrt(lX * lX + tY * tY);
        float tlZ = sqrt(1.0f - dist * dist);
        //Bottom Right
        dist = sqrt(rX * rX + bY * bY);
        float brZ = sqrt(1.0f - dist * dist);
        //Top Right
        dist = sqrt(rX * rX + tY * tY);
        float trZ = sqrt(1.0f - dist * dist);

        glBegin(GL_QUADS);

        glTexCoord2f(magnifyULeft, magnifyVBottom); glVertex3f(lX, tY, -tlZ);
        glTexCoord2f(magnifyURight, magnifyVBottom); glVertex3f(rX, tY, -trZ);
        glTexCoord2f(magnifyURight, magnifyVTop); glVertex3f(rX, bY, -brZ);
        glTexCoord2f(magnifyULeft, magnifyVTop); glVertex3f(lX, bY, -blZ);

        glEnd();

    } else {
        leftX = sin(leftAngle) * _distance;
        rightX = sin(rightAngle) * _distance;
        leftZ = -cos(leftAngle) * _distance;
        rightZ = -cos(rightAngle) * _distance;
        if (_uiType == CURVED_SEMICIRCLE) {
            topZ = -cos(topAngle * overlayAspectRatio) * _distance;
            bottomZ = -cos(bottomAngle * overlayAspectRatio) * _distance;
        } else {
            // Dont want to use topZ or bottomZ for SEMICIRCLE
            topZ = -99999;
            bottomZ = -99999;
        }

        float bottomY = (1.0 - newMouseY / (float)widgetHeight) * halfOverlayHeight * 2.0f - halfOverlayHeight;
        float topY = bottomY + (newHeight / widgetHeight) * halfOverlayHeight * 2;

        //TODO: Remove immediate mode in favor of VBO
        glBegin(GL_QUADS);

        glTexCoord2f(magnifyULeft, magnifyVBottom); glVertex3f(leftX, topY, max(topZ, leftZ));
        glTexCoord2f(magnifyURight, magnifyVBottom); glVertex3f(rightX, topY, max(topZ, rightZ));
        glTexCoord2f(magnifyURight, magnifyVTop); glVertex3f(rightX, bottomY, max(bottomZ, rightZ));
        glTexCoord2f(magnifyULeft, magnifyVTop); glVertex3f(leftX, bottomY, max(bottomZ, leftZ));

        glEnd();
    }
}
Example #15
0
void ApplicationOverlay::renderAudioMeter() {

    Application* application = Application::getInstance();

    QGLWidget* glWidget = application->getGLWidget();
    Audio* audio = application->getAudio();

    //  Display a single screen-size quad to create an alpha blended 'collision' flash
    if (audio->getCollisionFlashesScreen()) {
        float collisionSoundMagnitude = audio->getCollisionSoundMagnitude();
        const float VISIBLE_COLLISION_SOUND_MAGNITUDE = 0.5f;
        if (collisionSoundMagnitude > VISIBLE_COLLISION_SOUND_MAGNITUDE) {
            renderCollisionOverlay(glWidget->width(), glWidget->height(), audio->getCollisionSoundMagnitude());
        }
    }

    //  Audio VU Meter and Mute Icon
    const int MUTE_ICON_SIZE = 24;
    const int AUDIO_METER_INSET = 2;
    const int MUTE_ICON_PADDING = 10;
    const int AUDIO_METER_WIDTH = MIRROR_VIEW_WIDTH - MUTE_ICON_SIZE - AUDIO_METER_INSET - MUTE_ICON_PADDING;
    const int AUDIO_METER_SCALE_WIDTH = AUDIO_METER_WIDTH - 2 * AUDIO_METER_INSET;
    const int AUDIO_METER_HEIGHT = 8;
    const int AUDIO_METER_GAP = 5;
    const int AUDIO_METER_X = MIRROR_VIEW_LEFT_PADDING + MUTE_ICON_SIZE + AUDIO_METER_INSET + AUDIO_METER_GAP;

    int audioMeterY;
    if (Menu::getInstance()->isOptionChecked(MenuOption::Mirror)) {
        audioMeterY = MIRROR_VIEW_HEIGHT + AUDIO_METER_GAP + MUTE_ICON_PADDING;
    } else {
        audioMeterY = AUDIO_METER_GAP + MUTE_ICON_PADDING;
    }

    const float AUDIO_METER_BLUE[] = { 0.0, 0.0, 1.0 };
    const float AUDIO_METER_GREEN[] = { 0.0, 1.0, 0.0 };
    const float AUDIO_METER_RED[] = { 1.0, 0.0, 0.0 };
    const float AUDIO_GREEN_START = 0.25 * AUDIO_METER_SCALE_WIDTH;
    const float AUDIO_RED_START = 0.80 * AUDIO_METER_SCALE_WIDTH;
    const float CLIPPING_INDICATOR_TIME = 1.0f;
    const float AUDIO_METER_AVERAGING = 0.5;
    const float LOG2 = log(2.f);
    const float METER_LOUDNESS_SCALE = 2.8f / 5.f;
    const float LOG2_LOUDNESS_FLOOR = 11.f;
    float audioLevel = 0.f;
    float loudness = audio->getLastInputLoudness() + 1.f;

    _trailingAudioLoudness = AUDIO_METER_AVERAGING * _trailingAudioLoudness + (1.f - AUDIO_METER_AVERAGING) * loudness;
    float log2loudness = log(_trailingAudioLoudness) / LOG2;

    if (log2loudness <= LOG2_LOUDNESS_FLOOR) {
        audioLevel = (log2loudness / LOG2_LOUDNESS_FLOOR) * METER_LOUDNESS_SCALE * AUDIO_METER_SCALE_WIDTH;
    } else {
        audioLevel = (log2loudness - (LOG2_LOUDNESS_FLOOR - 1.f)) * METER_LOUDNESS_SCALE * AUDIO_METER_SCALE_WIDTH;
    }
    if (audioLevel > AUDIO_METER_SCALE_WIDTH) {
        audioLevel = AUDIO_METER_SCALE_WIDTH;
    }
    bool isClipping = ((audio->getTimeSinceLastClip() > 0.f) && (audio->getTimeSinceLastClip() < CLIPPING_INDICATOR_TIME));

    if ((audio->getTimeSinceLastClip() > 0.f) && (audio->getTimeSinceLastClip() < CLIPPING_INDICATOR_TIME)) {
        const float MAX_MAGNITUDE = 0.7f;
        float magnitude = MAX_MAGNITUDE * (1 - audio->getTimeSinceLastClip() / CLIPPING_INDICATOR_TIME);
        renderCollisionOverlay(glWidget->width(), glWidget->height(), magnitude, 1.0f);
    }

    audio->renderToolBox(MIRROR_VIEW_LEFT_PADDING + AUDIO_METER_GAP,
                         audioMeterY,
                         Menu::getInstance()->isOptionChecked(MenuOption::Mirror));

    audio->renderScope(glWidget->width(), glWidget->height());

    glBegin(GL_QUADS);
    if (isClipping) {
        glColor3f(1, 0, 0);
    } else {
        glColor3f(0.475f, 0.475f, 0.475f);
    }

    audioMeterY += AUDIO_METER_HEIGHT;

    glColor3f(0, 0, 0);
    //  Draw audio meter background Quad
    glVertex2i(AUDIO_METER_X, audioMeterY);
    glVertex2i(AUDIO_METER_X + AUDIO_METER_WIDTH, audioMeterY);
    glVertex2i(AUDIO_METER_X + AUDIO_METER_WIDTH, audioMeterY + AUDIO_METER_HEIGHT);
    glVertex2i(AUDIO_METER_X, audioMeterY + AUDIO_METER_HEIGHT);

    if (audioLevel > AUDIO_RED_START) {
        if (!isClipping) {
            glColor3fv(AUDIO_METER_RED);
        } else {
            glColor3f(1, 1, 1);
        }
        // Draw Red Quad
        glVertex2i(AUDIO_METER_X + AUDIO_METER_INSET + AUDIO_RED_START, audioMeterY + AUDIO_METER_INSET);
        glVertex2i(AUDIO_METER_X + AUDIO_METER_INSET + audioLevel, audioMeterY + AUDIO_METER_INSET);
        glVertex2i(AUDIO_METER_X + AUDIO_METER_INSET + audioLevel, audioMeterY + AUDIO_METER_HEIGHT - AUDIO_METER_INSET);
        glVertex2i(AUDIO_METER_X + AUDIO_METER_INSET + AUDIO_RED_START, audioMeterY + AUDIO_METER_HEIGHT - AUDIO_METER_INSET);
        audioLevel = AUDIO_RED_START;
    }
    if (audioLevel > AUDIO_GREEN_START) {
        if (!isClipping) {
            glColor3fv(AUDIO_METER_GREEN);
        } else {
            glColor3f(1, 1, 1);
        }
        // Draw Green Quad
        glVertex2i(AUDIO_METER_X + AUDIO_METER_INSET + AUDIO_GREEN_START, audioMeterY + AUDIO_METER_INSET);
        glVertex2i(AUDIO_METER_X + AUDIO_METER_INSET + audioLevel, audioMeterY + AUDIO_METER_INSET);
        glVertex2i(AUDIO_METER_X + AUDIO_METER_INSET + audioLevel, audioMeterY + AUDIO_METER_HEIGHT - AUDIO_METER_INSET);
        glVertex2i(AUDIO_METER_X + AUDIO_METER_INSET + AUDIO_GREEN_START, audioMeterY + AUDIO_METER_HEIGHT - AUDIO_METER_INSET);
        audioLevel = AUDIO_GREEN_START;
    }
    //   Draw Blue Quad
    if (!isClipping) {
        glColor3fv(AUDIO_METER_BLUE);
    } else {
        glColor3f(1, 1, 1);
    }
    // Draw Blue (low level) quad
    glVertex2i(AUDIO_METER_X + AUDIO_METER_INSET, audioMeterY + AUDIO_METER_INSET);
    glVertex2i(AUDIO_METER_X + AUDIO_METER_INSET + audioLevel, audioMeterY + AUDIO_METER_INSET);
    glVertex2i(AUDIO_METER_X + AUDIO_METER_INSET + audioLevel, audioMeterY + AUDIO_METER_HEIGHT - AUDIO_METER_INSET);
    glVertex2i(AUDIO_METER_X + AUDIO_METER_INSET, audioMeterY + AUDIO_METER_HEIGHT - AUDIO_METER_INSET);
    glEnd();
}
Example #16
0
void ApplicationOverlay::renderControllerPointer() {
    Application* application = Application::getInstance();
    QGLWidget* glWidget = application->getGLWidget();
    MyAvatar* myAvatar = application->getAvatar();

    const HandData* handData = Application::getInstance()->getAvatar()->getHandData();
    int numberOfPalms = handData->getNumPalms();

    for (unsigned int palmIndex = 2; palmIndex < 4; palmIndex++) {
        const PalmData* palmData = NULL;

        if (palmIndex >= handData->getPalms().size()) {
            return;
        }

        if (handData->getPalms()[palmIndex].isActive()) {
            palmData = &handData->getPalms()[palmIndex];
        } else {
            continue;
        }

        // Get directon relative to avatar orientation
        glm::vec3 direction = glm::inverse(myAvatar->getOrientation()) * palmData->getFingerDirection();

        // Get the angles, scaled between 0-1
        float xAngle = (atan2(direction.z, direction.x) + M_PI_2) + 0.5f;
        float yAngle = 1.0f - ((atan2(direction.z, direction.y) + M_PI_2) + 0.5f);

        float cursorRange = glWidget->width();

        int mouseX = cursorRange * xAngle;
        int mouseY = cursorRange * yAngle;

        //If the cursor is out of the screen then don't render it
        if (mouseX < 0 || mouseX >= glWidget->width() || mouseY < 0 || mouseY >= glWidget->height()) {
            continue;
        }

        float pointerWidth = 40;
        float pointerHeight = 40;
        float crossPad = 16;
        //if we have the oculus, we should make the cursor smaller since it will be
        //magnified
        if (OculusManager::isConnected()) {
            pointerWidth /= 4;
            pointerHeight /= 4;
            crossPad /= 4;

            _mouseX[_numMagnifiers] = mouseX;
            _mouseY[_numMagnifiers] = mouseY;
            _numMagnifiers++;

        }

        mouseX -= pointerWidth / 2.0f;
        mouseY += pointerHeight / 2.0f;

        glBegin(GL_QUADS);

        glColor3f(0.0f, 0.0f, 1.0f);

        //Horizontal crosshair
        glVertex2i(mouseX, mouseY - crossPad);
        glVertex2i(mouseX + pointerWidth, mouseY - crossPad);
        glVertex2i(mouseX + pointerWidth, mouseY - pointerHeight + crossPad);
        glVertex2i(mouseX, mouseY - pointerHeight + crossPad);

        //Vertical crosshair
        glVertex2i(mouseX + crossPad, mouseY);
        glVertex2i(mouseX + pointerWidth - crossPad, mouseY);
        glVertex2i(mouseX + pointerWidth - crossPad, mouseY - pointerHeight);
        glVertex2i(mouseX + crossPad, mouseY - pointerHeight);

        glEnd();
    }
}
Example #17
0
// Draws the FBO texture for Oculus rift. TODO: Draw a curved texture instead of plane.
void ApplicationOverlay::displayOverlayTextureOculus(Camera& whichCamera) {

    Application* application = Application::getInstance();

    QGLWidget* glWidget = application->getGLWidget();
    MyAvatar* myAvatar = application->getAvatar();
    const glm::vec3& viewMatrixTranslation = application->getViewMatrixTranslation();

  

    // Get vertical FoV of the displayed overlay texture
    const float halfVerticalAngle = _oculusAngle / 2.0f;
    const float overlayAspectRatio = glWidget->width() / (float)glWidget->height();
    const float halfOverlayHeight = _distance * tan(halfVerticalAngle);
    const float overlayHeight = halfOverlayHeight * 2.0f;

    // The more vertices, the better the curve
    const int numHorizontalVertices = 20;
    const int numVerticalVertices = 20;
    // U texture coordinate width at each quad
    const float quadTexWidth = 1.0f / (numHorizontalVertices - 1);
    const float quadTexHeight = 1.0f / (numVerticalVertices - 1);

    // Get horizontal angle and angle increment from vertical angle and aspect ratio
    const float horizontalAngle = halfVerticalAngle * 2.0f * overlayAspectRatio;
    const float angleIncrement = horizontalAngle / (numHorizontalVertices - 1);
    const float halfHorizontalAngle = horizontalAngle / 2;

    const float verticalAngleIncrement = _oculusAngle / (numVerticalVertices - 1);

    glActiveTexture(GL_TEXTURE0);
   
    glEnable(GL_BLEND);
    glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_CONSTANT_ALPHA, GL_ONE);
    glBindTexture(GL_TEXTURE_2D, getFramebufferObject()->texture());
    glEnable(GL_DEPTH_TEST);
    glDisable(GL_LIGHTING);
    glEnable(GL_TEXTURE_2D);

    glMatrixMode(GL_MODELVIEW);

    glPushMatrix();
    glLoadIdentity();
    // Transform to world space
    glm::quat rotation = whichCamera.getRotation();
    glm::vec3 axis2 = glm::axis(rotation);
    glRotatef(-glm::degrees(glm::angle(rotation)), axis2.x, axis2.y, axis2.z);
    glTranslatef(viewMatrixTranslation.x, viewMatrixTranslation.y, viewMatrixTranslation.z);

    // Translate to the front of the camera
    glm::vec3 pos = whichCamera.getPosition();
    glm::quat rot = myAvatar->getOrientation();
    glm::vec3 axis = glm::axis(rot);
   
    glTranslatef(pos.x, pos.y, pos.z);
    glRotatef(glm::degrees(glm::angle(rot)), axis.x, axis.y, axis.z);

    glColor3f(1.0f, 1.0f, 1.0f);

    glDepthMask(GL_TRUE);
    
    glEnable(GL_ALPHA_TEST);
    glAlphaFunc(GL_GREATER, 0.01f);

    float leftX, rightX, leftZ, rightZ, topZ, bottomZ;

    //Draw the magnifiers
    for (int i = 0; i < _numMagnifiers; i++) {
        renderMagnifier(_mouseX[i], _mouseY[i]);
    }

    glDepthMask(GL_FALSE);   
    glDisable(GL_ALPHA_TEST);

    //TODO: Remove immediate mode in favor of VBO
    if (_uiType == HEMISPHERE) {
        renderTexturedHemisphere();
    } else{
        glBegin(GL_QUADS);
        // Place the vertices in a semicircle curve around the camera
        for (int i = 0; i < numHorizontalVertices - 1; i++) {
            for (int j = 0; j < numVerticalVertices - 1; j++) {

                // Calculate the X and Z coordinates from the angles and radius from camera
                leftX = sin(angleIncrement * i - halfHorizontalAngle) * _distance;
                rightX = sin(angleIncrement * (i + 1) - halfHorizontalAngle) * _distance;
                leftZ = -cos(angleIncrement * i - halfHorizontalAngle) * _distance;
                rightZ = -cos(angleIncrement * (i + 1) - halfHorizontalAngle) * _distance;
                if (_uiType == 2) {
                    topZ = -cos((verticalAngleIncrement * (j + 1) - halfVerticalAngle) * overlayAspectRatio) * _distance;
                    bottomZ = -cos((verticalAngleIncrement * j - halfVerticalAngle) * overlayAspectRatio) * _distance;
                } else {
                    topZ = -99999;
                    bottomZ = -99999;
                }

                glTexCoord2f(quadTexWidth * i, (j + 1) * quadTexHeight); 
                glVertex3f(leftX, (j + 1) * quadTexHeight * overlayHeight - halfOverlayHeight, max(topZ, leftZ));
                glTexCoord2f(quadTexWidth * (i + 1), (j + 1) * quadTexHeight); 
                glVertex3f(rightX, (j + 1) * quadTexHeight * overlayHeight - halfOverlayHeight, max(topZ, rightZ));
                glTexCoord2f(quadTexWidth * (i + 1), j * quadTexHeight); 
                glVertex3f(rightX, j * quadTexHeight * overlayHeight - halfOverlayHeight, max(bottomZ, rightZ));
                glTexCoord2f(quadTexWidth * i, j * quadTexHeight); 
                glVertex3f(leftX, j * quadTexHeight * overlayHeight - halfOverlayHeight, max(bottomZ, leftZ));
            }
        }

        glEnd();
    }

    glPopMatrix();

    glDepthMask(GL_TRUE);
    glBindTexture(GL_TEXTURE_2D, 0);
    glDisable(GL_TEXTURE_2D);

    glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_CONSTANT_ALPHA, GL_ONE);
    glEnable(GL_LIGHTING);

}
Example #18
0
VertexBufferObjectAccess::pointer Mesh::getVertexBufferObjectAccess(
        accessType type,
        OpenCLDevice::pointer device) {
    if(!mIsInitialized)
        throw Exception("Surface has not been initialized.");

    if(mSurfaceIsBeingWrittenTo)
        throw Exception("Requesting access to a surface that is already being written to.");
    if (type == ACCESS_READ_WRITE) {
        if (isAnyDataBeingAccessed()) {
            throw Exception(
                    "Trying to get write access to an object that is already being accessed");
        }
        mSurfaceIsBeingWrittenTo = true;
        updateModifiedTimestamp();
    }
    if(!mVBOHasData) {
        // TODO create VBO
        // Have to have a drawable available before glewInit and glGenBuffers
#if defined(__APPLE__) || defined(__MACOSX)
#else
#if _WIN32
#else
        // If no Window is present, create a dummy gl context
        if(!QApplication::instance()) { // TODO make this work on all platforms
            SimpleWindow::initializeQtApp();

            // Need a drawable for this to work
            QGLWidget* widget = new QGLWidget;
            widget->show();
            widget->hide(); // TODO should probably delete widget as well
            std::cout << "created a drawable" << std::endl;
        }
#endif
#endif
        GLenum err = glewInit();
        if(err != GLEW_OK)
            throw Exception("GLEW init error");
        glGenBuffers(1, &mVBOID);
        glBindBuffer(GL_ARRAY_BUFFER, mVBOID);
        if(mHostHasData) {
            // If host has data, transfer it.
            // Create data arrays with vertices and normals interleaved
            uint counter = 0;
            float* data = new float[mNrOfTriangles*18];
            for(uint i = 0; i < mNrOfTriangles; i++) {
                Vector3ui triangle = mTriangles[i];
                for(uint j = 0; j < 3; j++) {
                    SurfaceVertex vertex = mVertices[triangle[j]];
                    for(uint k = 0; k < 3; k++) {
                        data[counter+k] = vertex.position[k];
                        //std::cout << data[counter+k] << std::endl;
                        data[counter+3+k] = vertex.normal[k];
                    }
                    //std::cout << "...." << std::endl;
                    counter += 6;
                }
            }
            glBufferData(GL_ARRAY_BUFFER, mNrOfTriangles*18*sizeof(float), data, GL_STATIC_DRAW);
            delete[] data;
        } else {
            glBufferData(GL_ARRAY_BUFFER, mNrOfTriangles*18*sizeof(float), NULL, GL_STATIC_DRAW);
        }
        glBindBuffer(GL_ARRAY_BUFFER, 0);
        glFinish();
        //std::cout << "Created VBO with ID " << mVBOID << " and " << mNrOfTriangles << " of triangles" << std::endl;
        // TODO Transfer data if any exist

        mVBOHasData = true;
        mVBODataIsUpToDate = true;

    } else {
        if(!mVBODataIsUpToDate) {
            // TODO Update data
        }
    }

    mVBODataIsBeingAccessed = true;

	VertexBufferObjectAccess::pointer accessObject(new VertexBufferObjectAccess(mVBOID, &mVBODataIsBeingAccessed, &mSurfaceIsBeingWrittenTo));
	return std::move(accessObject);
}
Example #19
0
hosted_button_id=RZ2A2ZB93827Y";

int main(int argc, char **argv)
{
    QApplication app (argc, argv);
    app.setOrganizationName("SfietKonstantin");
    app.setApplicationName("qfb-mobile");

//    QFB::QueryManager queryManager;
    QFB::LoginManager loginManager;
    TokenManager tokenManager;
    Me me;
//    PostUpdateRelay postUpdateRelay;

    qmlRegisterType<UserInfoHelper>("org.SfietKonstantin.qfb.mobile", 4, 0, "QFBUserInfoHelper");
//    qmlRegisterType<BackPixmapItem>("org.SfietKonstantin.qfb.mobile", 4, 0,
//                                    "QFBBackPixmapItem");
    qmlRegisterType<PostHelper>("org.SfietKonstantin.qfb.mobile", 4, 0, "QFBPostHelper");
//    qmlRegisterType<MobilePostValidator>("org.SfietKonstantin.qfb.mobile", 4, 0,
//                                         "QFBMobilePostValidator");

    QDeclarativeView view;
#ifdef MEEGO_EDITION_HARMATTAN
    QGLFormat format = QGLFormat::defaultFormat();
    format.setSampleBuffers(false);
    format.setSwapInterval(1);
    QGLWidget* glWidget = new QGLWidget(format);
    glWidget->setAutoFillBackground(false);
    view.setViewport(glWidget);
    PagePixmapProvider *pagePixmapProvider = new PagePixmapProvider(glWidget);
#else
    PagePixmapProvider *pagePixmapProvider = new PagePixmapProvider(&view);
#endif

#ifndef MEEGO_EDITION_HARMATTAN
    view.engine()->addImportPath(IMPORT_PATH);
#endif
    view.engine()->addImageProvider("pagepixmapprovider", pagePixmapProvider);
    view.engine()->setNetworkAccessManagerFactory(new NetworkAccessManagerFactory());
//    view.rootContext()->setContextProperty("QUERY_MANAGER", &queryManager);
    view.rootContext()->setContextProperty("LOGIN_MANAGER", &loginManager);
    view.rootContext()->setContextProperty("TOKEN_MANAGER", &tokenManager);
//    view.rootContext()->setContextProperty("POST_UPDATE_RELAY", &postUpdateRelay);
    view.rootContext()->setContextProperty("ME", &me);
    view.rootContext()->setContextProperty("DATA_PATH", DATA_PATH);
    view.rootContext()->setContextProperty("FACEBOOK_PAGE", FACEBOOK_PAGE);
    view.rootContext()->setContextProperty("PAYPAL_DONATE", PAYPAL_DONATE);
    view.rootContext()->setContextProperty("VERSION_MAJOR", QString::number(VERSION_MAJOR));
    view.rootContext()->setContextProperty("VERSION_MINOR", QString::number(VERSION_MINOR));
    view.rootContext()->setContextProperty("VERSION_PATCH", QString::number(VERSION_PATCH));

    // Friends specific
    QString clientId;
    QPluginLoader pluginLoader (CLIENT_ID_PLUGIN);
    if (pluginLoader.load()) {
        QObject *plugin = pluginLoader.instance();
        Interface *castedPlugin = qobject_cast<Interface *>(plugin);
        if (castedPlugin) {
            clientId = castedPlugin->clientId();
            qDebug() << "Client id loaded";
        }
    }

    if (clientId.isEmpty()) {
        if (app.arguments().count() == 2) {
            clientId = app.arguments().at(1);
        } else {
            qDebug() << "Failed to find the client id";
            return -1;
        }
    }
    view.rootContext()->setContextProperty("CLIENT_ID", clientId);
    // End Friends specific

    view.setSource(QUrl(MAIN_QML_FILE));
    view.showFullScreen();
    QObject::connect(view.engine(), SIGNAL(quit()), &app, SLOT(quit()));

    return app.exec();
}
Example #20
0
//Injecting mouse movements and clicks
void SixenseManager::emulateMouse(PalmData* palm, int index) {
    Application* application = Application::getInstance();
    MyAvatar* avatar = application->getAvatar();
    QGLWidget* widget = application->getGLWidget();
    QPoint pos;
    
    Qt::MouseButton bumperButton;
    Qt::MouseButton triggerButton;

    if (Menu::getInstance()->getInvertSixenseButtons()) {
        bumperButton = Qt::LeftButton;
        triggerButton = Qt::RightButton;
    } else {
        bumperButton = Qt::RightButton;
        triggerButton = Qt::LeftButton;
    }

    if (OculusManager::isConnected()) {
        pos = application->getApplicationOverlay().getOculusPalmClickLocation(palm);
    } else {
        // Get directon relative to avatar orientation
        glm::vec3 direction = glm::inverse(avatar->getOrientation()) * palm->getFingerDirection();

        // Get the angles, scaled between (-0.5,0.5)
        float xAngle = (atan2(direction.z, direction.x) + M_PI_2);
        float yAngle = 0.5f - ((atan2(direction.z, direction.y) + M_PI_2));

        // Get the pixel range over which the xAngle and yAngle are scaled
        float cursorRange = widget->width() * getCursorPixelRangeMult();

        pos.setX(widget->width() / 2.0f + cursorRange * xAngle);
        pos.setY(widget->height() / 2.0f + cursorRange * yAngle);

    }

    //If we are off screen then we should stop processing, and if a trigger or bumper is pressed,
    //we should unpress them.
    if (pos.x() == INT_MAX) {
        if (_bumperPressed[index]) {
            QMouseEvent mouseEvent(QEvent::MouseButtonRelease, pos, bumperButton, bumperButton, 0);

            application->mouseReleaseEvent(&mouseEvent);

            _bumperPressed[index] = false;
        }
        if (_triggerPressed[index]) {
            QMouseEvent mouseEvent(QEvent::MouseButtonRelease, pos, triggerButton, triggerButton, 0);

            application->mouseReleaseEvent(&mouseEvent);

            _triggerPressed[index] = false;
        }
        return;
    }

    //If position has changed, emit a mouse move to the application
    if (pos.x() != _oldX[index] || pos.y() != _oldY[index]) {
        QMouseEvent mouseEvent(static_cast<QEvent::Type>(CONTROLLER_MOVE_EVENT), pos, Qt::NoButton, Qt::NoButton, 0);

        //Only send the mouse event if the opposite left button isnt held down.
        //This is specifically for edit voxels
        if (triggerButton == Qt::LeftButton) {
            if (!_triggerPressed[(int)(!index)]) {
                application->mouseMoveEvent(&mouseEvent);
            }
        } else {
            if (!_bumperPressed[(int)(!index)]) {
                application->mouseMoveEvent(&mouseEvent);
            }
        } 
    }
    _oldX[index] = pos.x();
    _oldY[index] = pos.y();
    

    //We need separate coordinates for clicks, since we need to check if
    //a magnification window was clicked on
    int clickX = pos.x();
    int clickY = pos.y();
    //Checks for magnification window click
    application->getApplicationOverlay().getClickLocation(clickX, clickY);
    //Set pos to the new click location, which may be the same if no magnification window is open
    pos.setX(clickX);
    pos.setY(clickY);

    //Check for bumper press ( Right Click )
    if (palm->getControllerButtons() & BUTTON_FWD) {
        if (!_bumperPressed[index]) {
            _bumperPressed[index] = true;
        
            QMouseEvent mouseEvent(QEvent::MouseButtonPress, pos, bumperButton, bumperButton, 0);

            application->mousePressEvent(&mouseEvent);
        }
    } else if (_bumperPressed[index]) {
        QMouseEvent mouseEvent(QEvent::MouseButtonRelease, pos, bumperButton, bumperButton, 0);

        application->mouseReleaseEvent(&mouseEvent);

        _bumperPressed[index] = false;
    }

    //Check for trigger press ( Left Click )
    if (palm->getTrigger() == 1.0f) {
        if (!_triggerPressed[index]) {
            _triggerPressed[index] = true;

            QMouseEvent mouseEvent(QEvent::MouseButtonPress, pos, triggerButton, triggerButton, 0);

            application->mousePressEvent(&mouseEvent);
        }
    } else if (_triggerPressed[index]) {
        QMouseEvent mouseEvent(QEvent::MouseButtonRelease, pos, triggerButton, triggerButton, 0);

        application->mouseReleaseEvent(&mouseEvent);

        _triggerPressed[index] = false;
    }
}
Example #21
0
int main(int argc, char *argv[])
{
    // We don't need meego graphics system
    setenv("QT_GRAPHICSSYSTEM", "raster", 1);

#ifdef WINDOW_DEBUG
    // React to context-commander's fake events; required by test20.py
    // to be able to fake a phone call.
    setenv("CONTEXT_COMMANDING", "1", 1);
#endif

    // Don't load any Qt plugins
    QCoreApplication::setLibraryPaths(QStringList());
    MCompositeManager app(argc, argv);

    QGraphicsScene *scene = app.scene();
    QGraphicsView view(scene);

    view.setProperty("NoMStyle", true);
    view.setUpdatesEnabled(false);
    view.setAutoFillBackground(false);
    view.setBackgroundBrush(Qt::NoBrush);
    view.setForegroundBrush(Qt::NoBrush);
    view.setFrameShadow(QFrame::Plain);

    view.setWindowFlags(Qt::X11BypassWindowManagerHint);
    view.setAttribute(Qt::WA_NoSystemBackground);
#if QT_VERSION >= 0x040600
    view.move(-2, -2);
    view.setViewportUpdateMode(QGraphicsView::NoViewportUpdate);
    view.setOptimizationFlags(QGraphicsView::IndirectPainting);
#endif
    app.setSurfaceWindow(view.winId());

    view.setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    view.setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    view.setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed));
    view.setMinimumSize(QApplication::desktop()->width() + 2,
                        QApplication::desktop()->height() + 2);
    view.setMaximumSize(QApplication::desktop()->width() + 2,
                        QApplication::desktop()->height() + 2);

    QGLFormat fmt;
    fmt.setSamples(0);
    fmt.setSampleBuffers(false);

    QGLWidget *w = new QGLWidget(fmt);
    w->setAttribute(Qt::WA_PaintOutsidePaintEvent);
#ifndef GLES2_VERSION
    QPalette p = w->palette();
    p.setColor(QPalette::Background, QColor(Qt::black));
    w->setPalette(p);
    w->update();
#endif

    w->setAutoFillBackground(false);
    w->setMinimumSize(QApplication::desktop()->width(),
                      QApplication::desktop()->height());
    w->setMaximumSize(QApplication::desktop()->width(),
                      QApplication::desktop()->height());
    app.setGLWidget(w);
    view.setViewport(w);
    w->makeCurrent();
    view.show();

    // The directory is hard-coded for now. could be moved this
    // to $plugindir later.
    int testPlugin;
    const QStringList &args = app.arguments();
    app.prepareEvents();
    app.redirectWindows();
    for (testPlugin = 1; testPlugin < args.length(); testPlugin++)
        if (!args[testPlugin].isEmpty() && args[testPlugin][0] != '-')
            break;
    app.loadPlugins(testPlugin < args.length() ? args[testPlugin] : QString(),
                    "/usr/lib/mcompositor");

    return app.exec();
}
Example #22
0
/*!
  Empty method in Coin. Can be used by subclasses to be told
  when status change.
*/
void
SoFCSelection::redrawHighlighted(SoAction *  action , SbBool  doHighlight )
{
    //Base::Console().Log("SoFCSelection::redrawHighlighted() (%p) doHigh=%d \n",this,doHighlight?1:0);

#ifdef NO_FRONTBUFFER
#else
    // If we are about to highlight, and there is something else highlighted,
    // that something else needs to unhighlight.
    if (doHighlight && currenthighlight != NULL &&
        !(*((SoFullPath *)action->getCurPath()) == *currenthighlight)) {

        SoNode *tail = currenthighlight->getTail();
        if (tail->isOfType( SoFCSelection::getClassTypeId()))
            ((SoFCSelection *)tail)->redrawHighlighted(action, FALSE);
        else {
            // Just get rid of the path. It's no longer valid for redraw.
            currenthighlight->unref();
            currenthighlight = NULL;
        }
    }

    SoPath *pathToRender;
    // save the path to ourself for later de-highlight
    if (doHighlight) {
        if (currenthighlight != NULL)
            currenthighlight->unref();
        currenthighlight = (SoFullPath *) action->getCurPath()->copy();
        currenthighlight->ref();

        // We will be rendering this new path to highlight it
        pathToRender = currenthighlight;
        pathToRender->ref();
    }
    // delete our path if we are no longer highlighted
    else {
        if (currenthighlight) {
            // We will be rendering this old path to unhighlight it
            pathToRender = currenthighlight;
            pathToRender->ref();

            currenthighlight->unref();
            currenthighlight = NULL;
        }
    }

    // If highlighting is forced on for this node, we don't need this special render.
    if (highlightMode.getValue() != AUTO) {
        pathToRender->unref();
        return;
    }

    SoState *state = action->getState();

    //void* window;
    //void* context;
    //void *display;
    QGLWidget* window;
    SoGLRenderAction *glAction;
    //SoWindowElement::get(state, window, context, display, glAction);
    SoGLWidgetElement::get(state, window);
    SoGLRenderActionElement::get(state, glAction);

    // If we don't have a current window, then simply return...
    if (window == 0 /*|| context == NULL || display == NULL*/ || glAction == NULL)
        return;

    window->makeCurrent();
#ifndef WIN32
    // set the current window
    //glXMakeCurrent(display, window, context);
#endif
    // render into the front buffer (save the current buffering type)
    GLint whichBuffer;
    glGetIntegerv(GL_DRAW_BUFFER, &whichBuffer);
    if (whichBuffer != GL_FRONT)
        glDrawBuffer(GL_FRONT);

    highlighted = TRUE;
    glAction->apply(pathToRender);
    highlighted = FALSE;

    // restore the buffering type
    if (whichBuffer != GL_FRONT)
        glDrawBuffer((GLenum)whichBuffer);
    glFlush();

    pathToRender->unref();
#endif
}
Example #23
0
void setSwapInterval(QGLWidget const &glWidget, int *interval)
{
	typedef void (* PFNGLXQUERYDRAWABLEPROC)(Display *, GLXDrawable, int, unsigned int *);
	typedef void (* PFNGLXSWAPINTERVALEXTPROC)(Display *, GLXDrawable, int);
	typedef int (* PFNGLXGETSWAPINTERVALMESAPROC)(void);
	typedef int (* PFNGLXSWAPINTERVALMESAPROC)(unsigned);
	typedef int (* PFNGLXSWAPINTERVALSGIPROC)(int);
	PFNGLXSWAPINTERVALEXTPROC glXSwapIntervalEXT;
	PFNGLXQUERYDRAWABLEPROC glXQueryDrawable;
	PFNGLXGETSWAPINTERVALMESAPROC glXGetSwapIntervalMESA;
	PFNGLXSWAPINTERVALMESAPROC glXSwapIntervalMESA;
	PFNGLXSWAPINTERVALSGIPROC glXSwapIntervalSGI;
	QGLContext const &context = *glWidget.context();
	QX11Info const &xinfo = glWidget.x11Info();

	glXSwapIntervalEXT = (PFNGLXSWAPINTERVALEXTPROC) context.getProcAddress("glXSwapIntervalEXT");
	glXQueryDrawable = (PFNGLXQUERYDRAWABLEPROC) context.getProcAddress("glXQueryDrawable");
	if (glXSwapIntervalEXT && glXQueryDrawable)
	{
		unsigned clampedInterval;
		if (*interval < 0)
		{
			*interval = 0;
		}
		glXSwapIntervalEXT(xinfo.display(), glWidget.winId(), *interval);
		glXQueryDrawable(xinfo.display(), glWidget.winId(), GLX_SWAP_INTERVAL_EXT, &clampedInterval);
		*interval = clampedInterval;
		return;
	}

	glXSwapIntervalMESA = (PFNGLXSWAPINTERVALMESAPROC) context.getProcAddress("glXSwapIntervalMESA");
	glXGetSwapIntervalMESA = (PFNGLXGETSWAPINTERVALMESAPROC) context.getProcAddress("glXGetSwapIntervalMESA");
	if (glXSwapIntervalMESA && glXGetSwapIntervalMESA)
	{
		if (*interval < 0)
		{
			*interval = 0;
		}
		glXSwapIntervalMESA(*interval);
		*interval = glXGetSwapIntervalMESA();
		return;
	}

	glXSwapIntervalSGI = (PFNGLXSWAPINTERVALSGIPROC) context.getProcAddress("glXSwapIntervalSGI");
	if (glXSwapIntervalSGI)
	{
		if (*interval < 1)
		{
			*interval = 1;
		}
		if (glXSwapIntervalSGI(*interval))
		{
			// Error, revert to default
			*interval = 1;
			glXSwapIntervalSGI(1);
		}
		return;
	}

	*interval = -1;
}
void GlTraceFilterModel::checkExtensions()
{
	const GLubyte *extensionString, *versionString;
	int supportedMajor, supportedMinor;

	QGLWidget w;

	w.makeCurrent();
	extensionString = glGetString(GL_EXTENSIONS);
	versionString = glGetString(GL_VERSION);
	supportedMajor = versionString[0] - '0';
	supportedMinor = versionString[2] - '0';

	QByteArray extensions = QByteArray(
			reinterpret_cast<const char*>(extensionString));

#ifdef GLSLDB_WIN
	PFNWGLGETEXTENSIONSSTRINGARBPROC wglGetExtensionsStringARB = 0;
	wglGetExtensionsStringARB = (PFNWGLGETEXTENSIONSSTRINGARBPROC)wglGetProcAddress("wglGetExtensionsStringARB");
	if(wglGetExtensionsStringARB) {
		extensions.append(' ');
		extensions.append(QByteArray(reinterpret_cast<const char*>(wglGetExtensionsStringARB(wglGetCurrentDC()))));
	}
#elif defined(GLSLDB_LINUX)
	int supportedXMajor, supportedXMinor;
	const char *versionXString;

	versionXString = glXQueryServerString(XOpenDisplay(NULL), 0, GLX_VERSION);

	supportedXMajor = versionXString[0] - '0';
	supportedXMinor = versionXString[2] - '0';

	extensions.append(' ');
	extensions.append(
			QByteArray(
					reinterpret_cast<const char*>(glXQueryServerString(
							XOpenDisplay(NULL), 0, GLX_EXTENSIONS))));

	extensions.append(' ');
	extensions.append(
			QByteArray(
					reinterpret_cast<const char*>(glXGetClientString(
							XOpenDisplay(NULL), GLX_EXTENSIONS))));

	extensions.append(' ');
	extensions.append(
			QByteArray(
					reinterpret_cast<const char*>(glXQueryExtensionsString(
							XOpenDisplay(NULL), 0))));
#elif defined(GLSLDB_OSX)

#warning "FIXME: any OSX specific extensions wee need to add here?"

#endif

	QList<QByteArray> extList = extensions.split(' ');
	for (int i = 0; i < this->rootItem->childCount(); i++) {
		GlTraceFilterItem *item = this->rootItem->child(i);
		if (strstr(item->function->extname, "GL_VERSION_")
				== item->function->extname) {
			int major, minor;
			major = item->function->extname[11] - '0';
			minor = item->function->extname[13] - '0';
			if (major < supportedMajor
					|| (major == supportedMajor && minor <= supportedMinor)) {
				item->isSupported = true;
			} else {
				item->isSupported = false;
			}
		}
#if defined(_WIN32)
		else if (strstr(item->function->extname, "WGL_VERSION_") == item->function->extname) {
			item->isSupported = true;
		}
#elif defined(GLSLDB_LINUX)
		else if (strstr(item->function->extname, "GLX_VERSION_")
				== item->function->extname) {
			int major, minor;
			major = item->function->extname[12] - '0';
			minor = item->function->extname[14] - '0';
			if (major < supportedXMajor
					|| (major == supportedXMajor && minor <= supportedXMinor)) {
				item->isSupported = true;
			} else {
				item->isSupported = false;
			}
		}
#elif defined(GLSLDB_OSX)
#warning "FIXME: any OSX specific extensions wee need to add here?"
#endif
		else {
			item->isSupported = extList.contains(item->function->extname);
		}
	}
}
Example #25
0
void Layer::paint(QPainter *painter, const QStyleOptionGraphicsItem *option,
                  QWidget *widget)
{
  QtPainter *qvpainter = NULL;
#ifdef QT_OPENGL_LIB
  QPainter *fboPainter;
  QGLFramebufferObject *fbo = NULL;
  QGLWidget *qglWidget = qobject_cast<QGLWidget *>(widget);
  if (qglWidget) { // on-screen OpenGL
    QGLContext *context = const_cast<QGLContext *>(qglWidget->context());
    qvpainter = new OpenGLPainter(painter, context);
  } else if (cacheMode() != QGraphicsItem::NoCache &&
             QGLFramebufferObject::hasOpenGLFramebufferObjects()) {
    // caching, try FBO
    // if we have direct rendering and FBO support, make use of
    // FBO, but this could still just be in software

    // NOTE: In Qt 4.6, 'painter' would already target an FBO, if we
    // were using the 'OpenGL2' paint engine. We have decided to stick
    // with the original engine for now, as the OpenGL2 engine relies
    // heavily on shaders, which is slow for our use case.
    
    // Apparently, we must use the QGLContext associated with
    // the view being painted. Thus, PlotView tracks whether it is
    // inside a paintEvent, so we can get the current QGLWidget.
    OverlayScene *overlayScene = qobject_cast<OverlayScene *>(scene());
    if (overlayScene)
      qglWidget = qobject_cast<QGLWidget *>(overlayScene->view()->viewport());
    else {
      QList<QGraphicsView *> views = scene()->views();
      for (int i = 0; i < views.size() && !qglWidget; i++) {
        PlotView *view = qobject_cast<PlotView *>(views[i]);
        if (view && view->isPainting())
          qglWidget = qobject_cast<QGLWidget *>(view->viewport());
      }
    }
    if (qglWidget) {
      QSize size(painter->device()->width(), painter->device()->height());
      QGLContext *context = const_cast<QGLContext *>(qglWidget->context());
      // GC during paint callback may have reset this
      if (qglWidget->context() != QGLContext::currentContext())
        qglWidget->makeCurrent();
      // NOTE: need Qt 4.6 for antialiasing to work with FBOs
#if QT_VERSION >= 0x40600
      if (!fboMultisamplingFailed) {
        QGLFramebufferObjectFormat fboFormat;
        fboFormat.setAttachment(QGLFramebufferObject::CombinedDepthStencil);
        fboFormat.setSamples(4); // 4X antialiasing should be enough?
        qInstallMsgHandler(fboDebugMsgCatcher);
        fbo = new QGLFramebufferObject(size, fboFormat);
        qInstallMsgHandler(0);
        if (fboMultisamplingFailed) {
          delete fbo;
          fbo = NULL;
        }
      }
#endif
      if (!fbo)
        fbo = new QGLFramebufferObject(size);
      // clear the FBO
      fboPainter = new QPainter(fbo);
      fboPainter->setCompositionMode(QPainter::CompositionMode_Source);
      fboPainter->fillRect(0, 0, size.width(), size.height(), Qt::transparent);
      fboPainter->setCompositionMode(QPainter::CompositionMode_SourceOver);
      qvpainter = new OpenGLPainter(fboPainter, context);
      qvpainter->setTransform(painter->worldTransform());
    }
  }
#endif
  
  if (!qvpainter) // fallback to Qt renderer
    qvpainter = new QtPainter(painter);

  // NOTE: in QT 4.6 exposedRect will just be the bounding rect, by default
  paintPlot(qvpainter, option->exposedRect);

  delete qvpainter;
#ifdef QT_OPENGL_LIB
  if (fbo) { // silliness: download to image, only to upload to texture
    painter->setWorldMatrixEnabled(false);
    qglWidget->makeCurrent(); // gc during callback may have cleared this
    // need to tell Qt that 'fboImage' is actually premultiplied
    QImage fboImage = fbo->toImage();
    const uchar *data = fboImage.bits(); // no deep copy
    QImage premultImage = QImage(data,
                                 fboImage.width(),
                                 fboImage.height(),
                                 QImage::Format_ARGB32_Premultiplied);
    // Not sure why this can't be (0, 0)...
    painter->drawImage(QPointF(1, -1), premultImage);
    delete fboPainter;
    delete fbo;
  }
#endif
}
void GlOverviewGraphicsItem::draw(bool generatePixmap) {

  if(baseScene.getLayersList().empty())
    return;

  if (_frameWidth%2==1) {
    ++_frameWidth;
  }

  // Initialize the context avoid segfault when trying to render graph without any initialised gl context.
  QGLWidget *firstWidget = GlMainWidget::getFirstQGLWidget();
  firstWidget->makeCurrent();

  if(!overviewBorder.parentItem()) {

    //This flag is needed to don't display overview rectangle outside overview
    setFlag(QGraphicsItem::ItemClipsChildrenToShape);
    overview.setFlag(QGraphicsItem::ItemClipsChildrenToShape);
    overview.setShapeMode(QGraphicsPixmapItem::BoundingRectShape);
    setBrush(QBrush(QColor(255,255,255,255)));


    QPainterPath path;
    path.addRect(_frameWidth/2, _frameWidth/2, width-_frameWidth, height-_frameWidth);
    overviewBorder.setPath(path);
    overviewBorder.setParentItem(this);

    overview.setParentItem(&overviewBorder);

    //Init lines and polygons item
    for(unsigned int i=0; i<8; ++i) {
      line[i].setParentItem(&overview);

      if (i < 4) {
        poly[i].setParentItem(&overview);
        poly[i].setBrush(QBrush(QColor(0,0,0,64)));
        poly[i].setPen(Qt::NoPen);
      }
    }

  }

  Color backgroundColor = baseScene.getBackgroundColor();
  int bgV = backgroundColor.getV();

  for(unsigned int i=0; i<8; ++i) {
    if (bgV < 128) {
      line[i].setPen(QColor(255, 255, 255));
    }
    else {
      line[i].setPen(QColor(0, 0, 0));
    }

    if (i < 4) {
      if (bgV < 128) {
        poly[i].setBrush(QBrush(QColor(255,255,255,64)));
      }
      else {
        poly[i].setBrush(QBrush(QColor(0,0,0,64)));
      }
    }
  }

  // Backup initial viewport
  Vector<int,4> backupViewport=baseScene.getViewport();

  // Backup initial cameras
  vector<Camera> cameras;
  const vector<pair<string, GlLayer*> >& layerList=baseScene.getLayersList();

  for(vector<pair<string, GlLayer*> >::const_iterator it=layerList.begin(); it!=layerList.end(); ++it) {
    cameras.push_back((*it).second->getCamera());
  }

  // Compute visible part of the scene
  Camera &baseCamera=baseScene.getGraphCamera();

  vector<Coord> cameraBoundingBox;
  cameraBoundingBox.push_back(baseCamera.screenTo3DWorld(Coord(backupViewport[0],backupViewport[1],0)));
  cameraBoundingBox.push_back(baseCamera.screenTo3DWorld(Coord(backupViewport[0]+backupViewport[2],backupViewport[1],0)));
  cameraBoundingBox.push_back(baseCamera.screenTo3DWorld(Coord(backupViewport[0]+backupViewport[2],backupViewport[1]+backupViewport[3],0)));
  cameraBoundingBox.push_back(baseCamera.screenTo3DWorld(Coord(backupViewport[0],backupViewport[1]+backupViewport[3],0)));

  // This code modify cameraBoundingBox coords to have coords with (x,y,0)
  // If we don't do this we will have invalid polygon when we do worldTo2DScreen transformations
  Coord eyesVector=baseCamera.getEyes()-baseCamera.getCenter();

  eyesVector=eyesVector*(1.f/eyesVector[2]);

  for(unsigned int i=0; i<4; i++)
    cameraBoundingBox[i]=cameraBoundingBox[i]-eyesVector*cameraBoundingBox[i][2];

  // Change viewport of the scene to the overview viewport
  baseScene.setViewport(0,0,width, height);

  if(generatePixmap || _oldCameras.size()!=layerList.size()) {
    // Center the scene
    baseScene.centerScene();
    _oldCameras.clear();

    for(vector<pair<string, GlLayer*> >::const_iterator it=layerList.begin(); it!=layerList.end(); ++it) {
      _oldCameras.push_back(it->second->getCamera());
    }
  }
  else {
    unsigned int i=0;

    for(vector<pair<string, GlLayer*> >::const_iterator it=layerList.begin(); it!=layerList.end(); ++it) {
      it->second->getCamera().loadCameraParametersWith(_oldCameras[i]);
      ++i;
    }
  }

  // Project camera bounding box
  Camera &overviewCamera=baseScene.getGraphCamera();
  Coord p0=overviewCamera.worldTo2DScreen(cameraBoundingBox[0]);
  Coord p1=overviewCamera.worldTo2DScreen(cameraBoundingBox[1]);
  Coord p2=overviewCamera.worldTo2DScreen(cameraBoundingBox[2]);
  Coord p3=overviewCamera.worldTo2DScreen(cameraBoundingBox[3]);

  // Rotation of the coordinates to have no crossing lines
  while(p1[0]>p3[0]) {
    Coord tmp(p0);
    p0=p1;
    p1=p2;
    p2=p3;
    p3=tmp;
  }

  while(p1[1]<p3[1]) {
    Coord tmp(p0);
    p0=p3;
    p3=p2;
    p2=p1;
    p1=tmp;
  }


  if(generatePixmap) {
    bool edgesLabels=baseScene.getGlGraphComposite()->getRenderingParametersPointer()->isViewEdgeLabel();
    bool nodesLabels=baseScene.getGlGraphComposite()->getRenderingParametersPointer()->isViewNodeLabel();
    bool metaNodesLabels=baseScene.getGlGraphComposite()->getRenderingParametersPointer()->isViewMetaLabel();
    baseScene.getGlGraphComposite()->getRenderingParametersPointer()->setViewEdgeLabel(false);
    baseScene.getGlGraphComposite()->getRenderingParametersPointer()->setViewNodeLabel(false);
    baseScene.getGlGraphComposite()->getRenderingParametersPointer()->setViewMetaLabel(false);

    vector<bool> layersVisibility;

    const vector<pair<string, GlLayer*> > &layersList=baseScene.getLayersList();

    for(vector<pair<string, GlLayer*> >::const_iterator it=layersList.begin(); it!=layersList.end(); ++it) {
      layersVisibility.push_back(it->second->isVisible());

      if(it->second->isAWorkingLayer())
        it->second->setVisible(false);

      if(_hiddenLayers.count(it->first)!=0)
        it->second->setVisible(false);
    }

    // Draw the scene
    GlOffscreenRenderer::getInstance()->setViewPortSize(width-2*_frameWidth, height-2*_frameWidth);
    GlOffscreenRenderer::getInstance()->renderExternalScene(&baseScene, true);

    vector<bool>::iterator itTmp=layersVisibility.begin();

    for(vector<pair<string, GlLayer*> >::const_iterator it=layersList.begin(); it!=layersList.end(); ++it) {
      if((*itTmp)==true)
        it->second->setVisible(true);

      ++itTmp;
    }

    GlGraphRenderingParameters *param = baseScene.getGlGraphComposite()->getRenderingParametersPointer();
    param->setViewEdgeLabel(edgesLabels);
    param->setViewNodeLabel(nodesLabels);
    param->setViewMetaLabel(metaNodesLabels);
  }

  // invert applied camera transformations
  unsigned int i=0;

  for(vector<pair<string, GlLayer*> >::const_iterator it=layerList.begin(); it!=layerList.end(); ++it) {
    it->second->getCamera()=cameras[i];
    ++i;
  }

  // invert applied viewport
  baseScene.setViewport(backupViewport);

  if(generatePixmap) {
    // Load scene pixmap to the item
    QPixmap pixmap;
    QImage img = GlOffscreenRenderer::getInstance()->getImage();
    pixmap.convertFromImage(img);
    overview.setPos(_frameWidth, _frameWidth);
    overview.setPixmap(pixmap);
  }

  // set lines and polygons coordinates
  line[0].setLine(width-2*_frameWidth,0,p0[0],height-p0[1]);
  line[1].setLine(0,0,p1[0],height-p1[1]);
  line[2].setLine(0,height-2*_frameWidth,p2[0],height-p2[1]);
  line[3].setLine(width-2*_frameWidth,height-2*_frameWidth,p3[0],height-p3[1]);
  line[4].setLine(p0[0],height-p0[1], p1[0],height-p1[1]);
  line[5].setLine(p1[0],height-p1[1], p2[0],height-p2[1]);
  line[6].setLine(p2[0],height-p2[1], p3[0],height-p3[1]);
  line[7].setLine(p3[0],height-p3[1], p0[0],height-p0[1]);

  QVector<QPointF> tmpVect;
  tmpVect.push_back(QPointF(width-2*_frameWidth,0));
  tmpVect.push_back(QPointF(p0[0],height-p0[1]));
  tmpVect.push_back(QPointF(p1[0],height-p1[1]));
  tmpVect.push_back(QPointF(0,0));
  poly[0].setPolygon(QPolygonF(tmpVect));
  tmpVect.clear();
  tmpVect.push_back(QPointF(0,0));
  tmpVect.push_back(QPointF(p1[0],height-p1[1]));
  tmpVect.push_back(QPointF(p2[0],height-p2[1]));
  tmpVect.push_back(QPointF(0,height-2*_frameWidth));
  poly[1].setPolygon(QPolygonF(tmpVect));
  tmpVect.clear();
  tmpVect.push_back(QPointF(0,height-2*_frameWidth));
  tmpVect.push_back(QPointF(p2[0],height-p2[1]));
  tmpVect.push_back(QPointF(p3[0],height-p3[1]));
  tmpVect.push_back(QPointF(width-2*_frameWidth,height-2*_frameWidth));
  poly[2].setPolygon(QPolygonF(tmpVect));
  tmpVect.clear();
  tmpVect.push_back(QPointF(width-2*_frameWidth,height-2*_frameWidth));
  tmpVect.push_back(QPointF(p3[0],height-p3[1]));
  tmpVect.push_back(QPointF(p0[0],height-p0[1]));
  tmpVect.push_back(QPointF(width-2*_frameWidth,0));
  poly[3].setPolygon(QPolygonF(tmpVect));

  QPen pen(QColor(_frameColor[0], _frameColor[1], _frameColor[2], _frameColor[3]));
  pen.setWidth(_frameWidth);
  pen.setJoinStyle(Qt::MiterJoin);

  overviewBorder.setPen(pen);

}
Example #27
0
WaveformWidgetFactory::WaveformWidgetFactory() :
        m_type(WaveformWidgetType::Count_WaveformwidgetType),
        m_config(0),
        m_skipRender(false),
        m_frameRate(30),
        m_defaultZoom(3),
        m_zoomSync(false),
        m_overviewNormalized(false),
        m_openGLAvailable(false),
        m_openGLShaderAvailable(false),
        m_vsyncThread(NULL),
        m_frameCnt(0),
        m_actualFrameRate(0) {

    m_visualGain[All] = 1.5;
    m_visualGain[Low] = 1.0;
    m_visualGain[Mid] = 1.0;
    m_visualGain[High] = 1.0;

    if (QGLFormat::hasOpenGL()) {
        QGLFormat glFormat;
        glFormat.setDirectRendering(true);
        glFormat.setDoubleBuffer(true);
        glFormat.setDepth(false);
        // Disable waiting for vertical Sync
        // This can be enabled when using a single Threads for each QGLContext
        // Setting 1 causes QGLContext::swapBuffer to sleep until the next VSync
#if defined(__APPLE__)
        // On OS X, syncing to vsync has good performance FPS-wise and
        // eliminates tearing.
        glFormat.setSwapInterval(1);
#else
        // Otherwise, turn VSync off because it could cause horrible FPS on
        // Linux.
        // TODO(XXX): Make this configurable.
        // TOOD(XXX): What should we do on Windows?
        glFormat.setSwapInterval(0);
#endif


        glFormat.setRgba(true);
        QGLFormat::setDefaultFormat(glFormat);

        QGLFormat::OpenGLVersionFlags version = QGLFormat::openGLVersionFlags();

        int majorVersion = 0;
        int minorVersion = 0;
        if (version == QGLFormat::OpenGL_Version_None) {
            m_openGLVersion = "None";
        } else if (version & QGLFormat::OpenGL_Version_3_0) {
            majorVersion = 3;
        } else if (version & QGLFormat::OpenGL_Version_2_1) {
            majorVersion = 2;
            minorVersion = 1;
        } else if (version & QGLFormat::OpenGL_Version_2_0) {
            majorVersion = 2;
            minorVersion = 0;
        } else if (version & QGLFormat::OpenGL_Version_1_5) {
            majorVersion = 1;
            minorVersion = 5;
        } else if (version & QGLFormat::OpenGL_Version_1_4) {
            majorVersion = 1;
            minorVersion = 4;
        } else if (version & QGLFormat::OpenGL_Version_1_3) {
            majorVersion = 1;
            minorVersion = 3;
        } else if (version & QGLFormat::OpenGL_Version_1_2) {
            majorVersion = 1;
            minorVersion = 2;
        } else if (version & QGLFormat::OpenGL_Version_1_1) {
            majorVersion = 1;
            minorVersion = 1;
        }

        if (majorVersion != 0) {
            m_openGLVersion = QString::number(majorVersion) + "." +
                    QString::number(minorVersion);
        }

        m_openGLAvailable = true;

        QGLWidget* glWidget = new QGLWidget(); // create paint device
        // QGLShaderProgram::hasOpenGLShaderPrograms(); valgind error
        m_openGLShaderAvailable = QGLShaderProgram::hasOpenGLShaderPrograms(glWidget->context());
        delete glWidget;
    }

    evaluateWidgets();
    m_time.start();
}
Example #28
0
static void createGLSurface (QString qmlName, QDeclarativeView * view) {
  QmlPainterVideoSurface * timelineSurface = new QmlPainterVideoSurface;
  QGLWidget * g = (QGLWidget *) view->viewport();
  timelineSurface->setGLContext((QGLContext *) g->context());
  view->rootContext()->setContextProperty(qmlName, timelineSurface);
}
Example #29
0
MythRenderOpenGL* MythRenderOpenGL::Create(const QString &painter,
                                           QPaintDevice* device)
{
#ifdef USE_OPENGL_QT5
    MythRenderFormat format = QSurfaceFormat::defaultFormat();
    format.setDepthBufferSize(0);
    format.setSwapBehavior(QSurfaceFormat::DoubleBuffer);
# ifdef USING_OPENGLES
    format.setRenderableType(QSurfaceFormat::OpenGLES);
# endif
#else
    MythRenderFormat format = QGLFormat(QGL::NoDepthBuffer);
#endif

    bool setswapinterval = false;
    int synctovblank = -1;

#ifdef USING_X11
    synctovblank = CheckNVOpenGLSyncToVBlank();
#endif

    if (synctovblank < 0)
    {
        LOG(VB_GENERAL, LOG_WARNING, LOC + "Could not determine whether Sync "
                                           "to VBlank is enabled.");
    }
    else if (synctovblank == 0)
    {
        // currently only Linux NVidia is supported and there is no way of
        // forcing sync to vblank after the app has started. util-nvctrl will
        // warn the user and offer advice on settings.
    }
    else
    {
        LOG(VB_GENERAL, LOG_INFO, LOC + "Sync to VBlank is enabled (good!)");
    }

#if defined(Q_OS_MAC)
    LOG(VB_GENERAL, LOG_INFO, LOC + "Forcing swap interval for OS X.");
    setswapinterval = true;
#endif

    if (setswapinterval)
        format.setSwapInterval(1);

#if ANDROID
    int openGLVersionFlags = QGLFormat::OpenGL_ES_Version_2_0;
    LOG(VB_GENERAL, LOG_INFO, "OpenGL ES2 forced for Android");
#elif defined USE_OPENGL_QT5 && defined USING_OPENGLES
    int openGLVersionFlags = QGLFormat::OpenGL_ES_Version_2_0;
#else
    // Check OpenGL version supported
    QGLWidget *dummy = new QGLWidget;
    dummy->makeCurrent();
    QGLFormat qglFormat = dummy->format();
    int openGLVersionFlags = qglFormat.openGLVersionFlags();
    delete dummy;
#endif

#ifdef USING_OPENGLES
    if (!(openGLVersionFlags & QGLFormat::OpenGL_ES_Version_2_0))
    {
        LOG(VB_GENERAL, LOG_WARNING,
            "Using OpenGL ES 2.0 render, however OpenGL ES 2.0 "
            "version not supported");
    }
    if (device)
        return new MythRenderOpenGL2ES(format, device);
    return new MythRenderOpenGL2ES(format);
#else
    if ((openGLVersionFlags & QGLFormat::OpenGL_Version_2_0) &&
        (painter.contains(OPENGL2_PAINTER) || painter.contains(AUTO_PAINTER) ||
         painter.isEmpty()))
    {
        LOG(VB_GENERAL, LOG_INFO, "Trying the OpenGL 2.0 render");
        format.setVersion(2,0);
        if (device)
            return new MythRenderOpenGL2(format, device);
        return new MythRenderOpenGL2(format);
    }

    if (!(openGLVersionFlags & QGLFormat::OpenGL_Version_1_2))
    {
        LOG(VB_GENERAL, LOG_WARNING, "OpenGL 1.2 not supported, get new hardware!");
        return NULL;
    }

    LOG(VB_GENERAL, LOG_INFO, "Trying the OpenGL 1.2 render");
    format.setVersion(1,3);
    if (device)
        return new MythRenderOpenGL1(format, device);
    return new MythRenderOpenGL1(format);

#endif
}
Example #30
0
/*!
  Overridden from QGLWidget to render the scenegraph
*/
void QuarterWidget::paintEvent(QPaintEvent* event)
{
    std::clock_t begin = std::clock();

    if(!initialized) {
        glEnable(GL_DEPTH_TEST);
        this->getSoRenderManager()->reinitialize();
        initialized = true;
    }

    getSoRenderManager()->activate();

    glEnable(GL_DEPTH_TEST);
    glMatrixMode(GL_PROJECTION);

    QGLWidget* w = static_cast<QGLWidget*>(this->viewport());
    assert(w->isValid() && "No valid GL context found!");
    // We might have to process the delay queue here since we don't know
    // if paintGL() is called from Qt, and we might have some sensors
    // waiting to trigger (the redraw sensor has a lower priority than a
    // normal field sensor to guarantee that your sensor is processed
    // before the next redraw). Disable autorendering while we do this
    // to avoid recursive redraws.

    // We set the PRIVATE(this)->processdelayqueue = false in redraw()
    // to avoid processing the delay queue when paintGL() is triggered
    // by us, and we don't want to process the delay queue in those
    // cases

    PRIVATE(this)->autoredrawenabled = false;

    if(PRIVATE(this)->processdelayqueue && SoDB::getSensorManager()->isDelaySensorPending()) {
        // processing the sensors might trigger a redraw in another
        // context. Release this context temporarily
        w->doneCurrent();
        SoDB::getSensorManager()->processDelayQueue(false);
        w->makeCurrent();
    }

    assert(w->isValid() && "No valid GL context found!");

    glDrawBuffer(w->doubleBuffer() ? GL_BACK : GL_FRONT);

    w->makeCurrent();
    this->actualRedraw();

    //start the standard graphics view processing for all widgets and graphic items. As 
    //QGraphicsView initaliizes a QPainter which changes the Opengl context in an unpredictable 
    //manner we need to store the context and recreate it after Qt is done.
    glPushAttrib(GL_MULTISAMPLE_BIT_EXT);
    inherited::paintEvent(event);
    glPopAttrib();

    if (w->doubleBuffer()) { w->swapBuffers(); }

    PRIVATE(this)->autoredrawenabled = true;

    // process the delay queue the next time we enter this function,
    // unless we get here after a call to redraw().
    PRIVATE(this)->processdelayqueue = true;

    std::clock_t end = std::clock();
    renderTime = double(double(end-begin)/CLOCKS_PER_SEC)*1000.0;
}