Exemplo n.º 1
0
int RFBufferGo( struct RFBuffer *rb, int width, int height, int texturecount, struct Texture ** textures, int do_clear )
{
	int i;
	static const GLenum buffers[8] = {   GL_COLOR_ATTACHMENT0_EXT, GL_COLOR_ATTACHMENT1_EXT, GL_COLOR_ATTACHMENT2_EXT,
			GL_COLOR_ATTACHMENT3_EXT, GL_COLOR_ATTACHMENT4_EXT, GL_COLOR_ATTACHMENT5_EXT,
			GL_COLOR_ATTACHMENT6_EXT, GL_COLOR_ATTACHMENT7_EXT };

	for( i = 0; i < texturecount; i++ )
	{
		struct Texture * t = textures[i];
		if( t->width != width || t->height != height )
		{
			MakeDynamicTexture2D( t, width, height, rb->mtt );
		}
	}

	RenderW = width;
	RenderH = height;

	rb->width = width;
	rb->height = height;
	rb->outextures = texturecount;

	if( rb->use_depth_buffer )
	{
		glBindRenderbuffer( GL_RENDERBUFFER, rb->renderbuffer );
		glRenderbufferStorage( GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, width, height );
	}

	glBindFramebufferEXT( GL_FRAMEBUFFER_EXT, rb->outputbuffer );
	for( i = 0; i < texturecount; i++ )
	{
		struct Texture * t = textures[i];
		glFramebufferTexture2DEXT( GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT + i, 
			GL_TEXTURE_2D, t->texture, 0 );
	}

	if( rb->use_depth_buffer )
		glFramebufferRenderbufferEXT( GL_FRAMEBUFFER_EXT, 
			GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, rb->renderbuffer );

	glDrawBuffers( texturecount, buffers );
	glViewport( 0, 0, width, height );

	//Check to see if there were any errors with the framebuffer
	switch( (GLenum)glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT) )
	{
		case GL_FRAMEBUFFER_COMPLETE_EXT: break;  //GOOD!
		case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT_EXT:
			fprintf( stderr, "OpenGL Framebuffer error: GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT_EXT\n");
			return -1;
		case GL_FRAMEBUFFER_UNSUPPORTED_EXT:
			fprintf( stderr, "OpenGL Framebuffer error: GL_FRAMEBUFFER_UNSUPPORTED_EXT\n");
			return -2;
		case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT_EXT:
			fprintf( stderr, "OpenGL Framebuffer error: GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT_EXT\n");
			return -3;
		case GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS_EXT:
			fprintf( stderr, "OpenGL Framebuffer error: GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS_EXT\n");
			return -4;
		case GL_FRAMEBUFFER_INCOMPLETE_FORMATS_EXT:
			fprintf( stderr, "OpenGL Framebuffer error: GL_FRAMEBUFFER_INCOMPLETE_FORMATS_EXT\n");
			return -5;
		case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER_EXT:
			fprintf( stderr, "OpenGL Framebuffer error: GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER_EXT\n");
			return -6;
		case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER_EXT:
			fprintf( stderr, "OpenGL Framebuffer error: GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER_EXT\n");
			return -7;
		default:
			fprintf( stderr, "UNKNWON error with OpenGL Framebuffer\n");
			return -8;
	}

	if( do_clear )
		glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );


	return 0;
}
Exemplo n.º 2
0
 static void reshape(int w, int h)
 {
   glViewport(0, 0, w, h);
 }
void EDA_3D_CANVAS::Redraw()
{
    // SwapBuffer requires the window to be shown before calling
    if( !IsShownOnScreen() )
        return;

    wxString err_messages;
    WX_STRING_REPORTER errorReporter( &err_messages );
    STATUS_TEXT_REPORTER activityReporter( Parent(), 0 );

    // Display build time at the end of build
    unsigned strtime = GetRunningMicroSecs();

    SetCurrent( *m_glRC );

    // Set the OpenGL viewport according to the client size of this canvas.
    // This is done here rather than in a wxSizeEvent handler because our
    // OpenGL rendering context (and thus viewport setting) is used with
    // multiple canvases: If we updated the viewport in the wxSizeEvent
    // handler, changing the size of one canvas causes a viewport setting that
    // is wrong when next another canvas is repainted.
    wxSize size = GetClientSize();

    InitGL();

    if( isRealisticMode() && isEnabled( FL_RENDER_SHADOWS ) )
    {
        generateFakeShadowsTextures( &errorReporter, &activityReporter );
    }

    // *MUST* be called *after*  SetCurrent( ):
    glViewport( 0, 0, size.x, size.y );

    // clear color and depth buffers
    glClearColor( 0.95, 0.95, 1.0, 1.0 );
    glClearStencil( 0 );
    glClearDepth( 1.0 );
    glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT );

    glShadeModel( GL_SMOOTH );

    // Draw background
    glMatrixMode( GL_PROJECTION );
    glLoadIdentity();

    glMatrixMode( GL_MODELVIEW );
    glLoadIdentity();

    glDisable( GL_LIGHTING );
    glDisable( GL_COLOR_MATERIAL );
    glDisable( GL_DEPTH_TEST );
    glDisable( GL_TEXTURE_2D );

    // Draw the background ( rectangle with color gradient)
    glBegin( GL_QUADS );
    SetGLColor( GetPrm3DVisu().m_BgColor_Top, 1.0 );
    glVertex2f( -1.0, 1.0 );    // Top left corner

    SetGLColor( GetPrm3DVisu().m_BgColor, 1.0 );
    glVertex2f( -1.0,-1.0 );    // bottom left corner
    glVertex2f( 1.0,-1.0 );     // bottom right corner

    SetGLColor( GetPrm3DVisu().m_BgColor_Top, 1.0 );
    glVertex2f( 1.0, 1.0 );     // top right corner

    glEnd();
    glEnable( GL_DEPTH_TEST );


    // set viewing projection
    glMatrixMode( GL_PROJECTION );
    glLoadIdentity();

#define MAX_VIEW_ANGLE 160.0 / 45.0

    if( GetPrm3DVisu().m_Zoom > MAX_VIEW_ANGLE )
        GetPrm3DVisu().m_Zoom = MAX_VIEW_ANGLE;

     if( Parent()->ModeIsOrtho() )
     {
         // OrthoReductionFactor is chosen to provide roughly the same size as
         // Perspective View
         const double orthoReductionFactor = 400 / GetPrm3DVisu().m_Zoom;

         // Initialize Projection Matrix for Ortographic View
         glOrtho( -size.x / orthoReductionFactor, size.x / orthoReductionFactor,
                  -size.y / orthoReductionFactor, size.y / orthoReductionFactor, 1, 100 );
     }
     else
     {
         // Ratio width / height of the window display
         double ratio_HV = (double) size.x / size.y;

         // Initialize Projection Matrix for Perspective View
         gluPerspective( 45.0f * GetPrm3DVisu().m_Zoom, ratio_HV, 1, 100 );
     }

    // position viewer
    glMatrixMode( GL_MODELVIEW );
    glLoadIdentity();

    glTranslatef( 0.0f, 0.0f, -(m_ZBottom + m_ZTop) / 2.0f );

    // Setup light sources:
    SetLights();

    CheckGLError( __FILE__, __LINE__ );

    glMatrixMode( GL_MODELVIEW );    // position viewer

    // transformations
    GLfloat mat[4][4];

    // Translate motion first, so rotations don't mess up the orientation...
    glTranslatef( m_draw3dOffset.x, m_draw3dOffset.y, 0.0F );

    build_rotmatrix( mat, GetPrm3DVisu().m_Quat );
    glMultMatrixf( &mat[0][0] );

    glRotatef( GetPrm3DVisu().m_Rot[0], 1.0, 0.0, 0.0 );
    glRotatef( GetPrm3DVisu().m_Rot[1], 0.0, 1.0, 0.0 );
    glRotatef( GetPrm3DVisu().m_Rot[2], 0.0, 0.0, 1.0 );


    if( ! m_glLists[GL_ID_BOARD] || ! m_glLists[GL_ID_TECH_LAYERS] )
        CreateDrawGL_List( &errorReporter, &activityReporter );

    if( isEnabled( FL_AXIS ) && m_glLists[GL_ID_AXIS] )
        glCallList( m_glLists[GL_ID_AXIS] );

    // move the board in order to draw it with its center at 0,0 3D coordinates
    glTranslatef( -GetPrm3DVisu().m_BoardPos.x * GetPrm3DVisu().m_BiuTo3Dunits,
                  -GetPrm3DVisu().m_BoardPos.y * GetPrm3DVisu().m_BiuTo3Dunits,
                  0.0f );

    if( isEnabled( FL_MODULE ) )
    {
        if( ! m_glLists[GL_ID_3DSHAPES_SOLID_FRONT] )
            CreateDrawGL_List( &errorReporter, &activityReporter );
    }

    glEnable( GL_LIGHTING );

    glEnable( GL_BLEND );
    glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );

    if( isRealisticMode() && isEnabled( FL_RENDER_TEXTURES ) )
        glEnable( GL_TEXTURE_2D );
    else
        glDisable( GL_TEXTURE_2D );

    // Set material for the board
    glEnable( GL_COLOR_MATERIAL );
    SetOpenGlDefaultMaterial();

    //glLightModeli( GL_LIGHT_MODEL_TWO_SIDE, FALSE );

    // Board Body

    GLint shininess_value = 32;
    glMateriali( GL_FRONT_AND_BACK, GL_SHININESS, shininess_value );

    if( isEnabled( FL_SHOW_BOARD_BODY ) )
    {
        if( m_glLists[GL_ID_BODY] )
        {
            glCallList( m_glLists[GL_ID_BODY] );
        }
    }


    // Board

    // specify material parameters for the lighting model.
    shininess_value = 52;
    glMateriali( GL_FRONT_AND_BACK, GL_SHININESS, shininess_value );

    glm::vec4 specular( GetPrm3DVisu().m_CopperColor.m_Red   * 0.20f,
                        GetPrm3DVisu().m_CopperColor.m_Green * 0.20f,
                        GetPrm3DVisu().m_CopperColor.m_Blue  * 0.20f, 1.0f );
    glMaterialfv( GL_FRONT_AND_BACK, GL_SPECULAR, &specular.x );

    if( m_glLists[GL_ID_BOARD] )
    {
        glCallList( m_glLists[GL_ID_BOARD] );
    }


    // Tech layers

    shininess_value = 32;
    glMateriali( GL_FRONT_AND_BACK, GL_SHININESS, shininess_value );

    glm::vec4 specularTech( 0.0f, 0.0f, 0.0f, 1.0f );
    glMaterialfv( GL_FRONT_AND_BACK, GL_SPECULAR, &specularTech.x );

    if( m_glLists[GL_ID_TECH_LAYERS] )
    {
        glCallList( m_glLists[GL_ID_TECH_LAYERS] );
    }

    if( isEnabled( FL_COMMENTS ) || isEnabled( FL_ECO )  )
    {
        if( ! m_glLists[GL_ID_AUX_LAYERS] )
            CreateDrawGL_List( &errorReporter, &activityReporter );

        glCallList( m_glLists[GL_ID_AUX_LAYERS] );
    }

    //glLightModeli( GL_LIGHT_MODEL_TWO_SIDE, TRUE );

    // Draw Component Shadow

    if( isEnabled( FL_MODULE )  && isRealisticMode() &&
        isEnabled( FL_RENDER_SHADOWS ) )
    {
        glEnable( GL_CULL_FACE );
        glDisable( GL_DEPTH_TEST );

        glEnable( GL_COLOR_MATERIAL ) ;
        SetOpenGlDefaultMaterial();
        glColor4f( 1.0f, 1.0f, 1.0f, 1.0f );

        glEnable( GL_TEXTURE_2D );

        glEnable( GL_BLEND );
        glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );

        if( m_glLists[GL_ID_SHADOW_FRONT] )
        {
            glBindTexture( GL_TEXTURE_2D, m_text_fake_shadow_front );
            glCallList( m_glLists[GL_ID_SHADOW_FRONT] );
        }

        if( m_glLists[GL_ID_SHADOW_BACK] )
        {
            glBindTexture( GL_TEXTURE_2D, m_text_fake_shadow_back );
            glCallList( m_glLists[GL_ID_SHADOW_BACK] );
        }
        glColor4f( 1.0f, 1.0f, 1.0f, 1.0f );

        glEnable( GL_DEPTH_TEST );
        glDisable( GL_TEXTURE_2D );
        glDisable( GL_CULL_FACE );
    }

    glEnable( GL_COLOR_MATERIAL );
    SetOpenGlDefaultMaterial();

    glDisable( GL_BLEND );


    // Draw Solid Shapes

    if( isEnabled( FL_MODULE ) )
    {
        if( ! m_glLists[GL_ID_3DSHAPES_SOLID_FRONT] )
            CreateDrawGL_List( &errorReporter, &activityReporter );

        glCallList( m_glLists[GL_ID_3DSHAPES_SOLID_FRONT] );
    }

    glEnable( GL_BLEND );
    glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );


    // Grid uses transparency: draw it after all objects

    if( isEnabled( FL_GRID ) )
    {
        if( ! m_glLists[GL_ID_GRID] )
            CreateDrawGL_List( &errorReporter, &activityReporter );

        glCallList( m_glLists[GL_ID_GRID] );
    }


    // Draw Board Shadow

    if( isRealisticMode() && isEnabled( FL_RENDER_SHADOWS ) )
    {
        if( m_glLists[GL_ID_SHADOW_BOARD] )
        {
            glEnable( GL_BLEND );
            glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
            glColor4f( 1.0, 1.0, 1.0, 0.75f );
            glEnable( GL_CULL_FACE );
            glDisable( GL_COLOR_MATERIAL );
            glEnable( GL_TEXTURE_2D );
            glBindTexture( GL_TEXTURE_2D, m_text_fake_shadow_board );
            glCallList( m_glLists[GL_ID_SHADOW_BOARD] );
            glDisable( GL_CULL_FACE );
            glDisable( GL_TEXTURE_2D );
        }
    }

    // This list must be drawn last, because it contains the
    // transparent gl objects, which should be drawn after all
    // non transparent objects
    if(  isEnabled( FL_MODULE ) && m_glLists[GL_ID_3DSHAPES_TRANSP_FRONT] )
    {
        glEnable( GL_COLOR_MATERIAL );
        SetOpenGlDefaultMaterial();
        glEnable( GL_BLEND );
        glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
        glCallList( m_glLists[GL_ID_3DSHAPES_TRANSP_FRONT] );
    }

    // Debug bounding boxes
    /*
    glDisable( GL_BLEND );
    glDisable( GL_COLOR_MATERIAL );
    glDisable( GL_LIGHTING );
    glColor4f( 1.0f, 0.0f, 1.0f, 1.0f );
    m_fastAABBox_Shadow.GLdebug();

    glColor4f( 0.0f, 1.0f, 1.0f, 1.0f );
    m_boardAABBox.GLdebug();
    */

    SwapBuffers();

    // Show calculation time if some activity was reported
    if( activityReporter.HasMessage() )
    {
        // Calculation time in seconds
        double calculation_time = (double)( GetRunningMicroSecs() - strtime) / 1e6;

        activityReporter.Report( wxString::Format( _( "Build time %.3f s" ),
                                 calculation_time ) );
    }
    else
        activityReporter.Report( wxEmptyString );

    if( !err_messages.IsEmpty() )
        wxLogMessage( err_messages );

}
void reshape (int w, int h) {
    glViewport (0, 0, (GLsizei) w, (GLsizei) h);
    largura=w;
    altura=h;
}
Exemplo n.º 5
0
bool CRenderSystemGL::ResetRenderSystem(int width, int height, bool fullScreen, float refreshRate)
{
  m_width = width;
  m_height = height;

  glClearColor( 0.0f, 0.0f, 0.0f, 0.0f );

  CalculateMaxTexturesize();

  glViewport(0, 0, width, height);
  glScissor(0, 0, width, height);

  glEnable(GL_TEXTURE_2D);
  glEnable(GL_SCISSOR_TEST);

  //ati doesn't init the texture matrix correctly
  //so we have to do it ourselves
  glMatrixMode(GL_TEXTURE);
  glLoadIdentity();
  if (glewIsSupported("GL_ARB_multitexture"))
  {
    //clear error flags
    ResetGLErrors();

    GLint maxtex;
    glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS_ARB, &maxtex);

    //some sanity checks
    GLenum error = glGetError();
    if (error != GL_NO_ERROR)
    {
      CLog::Log(LOGERROR, "ResetRenderSystem() GL_MAX_TEXTURE_IMAGE_UNITS_ARB returned error %i", (int)error);
      maxtex = 3;
    }
    else if (maxtex < 1 || maxtex > 32)
    {
      CLog::Log(LOGERROR, "ResetRenderSystem() GL_MAX_TEXTURE_IMAGE_UNITS_ARB returned invalid value %i", (int)maxtex);
      maxtex = 3;
    }

    //reset texture matrix for all textures
    for (GLint i = 0; i < maxtex; i++)
    {
      glActiveTextureARB(GL_TEXTURE0 + i);
      glLoadIdentity();
    }
    glActiveTextureARB(GL_TEXTURE0);
  }

  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();

  glOrtho(0.0f, width-1, height-1, 0.0f, -1.0f, 1.0f);

  glMatrixMode(GL_MODELVIEW);
  glLoadIdentity();

  glBlendFunc(GL_SRC_ALPHA, GL_ONE);
  glEnable(GL_BLEND);          // Turn Blending On
  glDisable(GL_DEPTH_TEST);

  return true;
}
Exemplo n.º 6
0
	//functei care e chemata cand se schimba dimensiunea ferestrei initiale
	void notifyReshape(int width, int height, int previos_width, int previous_height){
		//reshape
		if(height==0) height=1;
		glViewport(0,0,width,height);
		projection_matrix = glm::perspective(90.0f, (float)width/(float)height,0.1f, 10000.0f);
	}
Exemplo n.º 7
0
void RiftAppSkeleton::display_sdk() //const
{
    ovrHmd hmd = m_Hmd;
    if (hmd == NULL)
        return;

    //const ovrFrameTiming hmdFrameTiming =
    ovrHmd_BeginFrame(m_Hmd, 0);

    bindFBO(m_renderBuffer);

    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    // For passing to EndFrame once rendering is done
    ovrPosef renderPose[2];
    ovrTexture eyeTexture[2];

    for (int eyeIndex=0; eyeIndex<ovrEye_Count; eyeIndex++)
    {
        const ovrEyeType eye = hmd->EyeRenderOrder[eyeIndex];
        const ovrPosef eyePose = ovrHmd_GetEyePose(m_Hmd, eye);
        m_eyeOri = eyePose.Orientation; // cache this for movement direction
        _StoreHmdPose(eyePose);

        const ovrGLTexture& otex = l_EyeTexture[eye];
        const ovrRecti& rvp = otex.OGL.Header.RenderViewport;
        glViewport(
            rvp.Pos.x,
            rvp.Pos.y,
            rvp.Size.w,
            rvp.Size.h
            );

        const OVR::Matrix4f proj = ovrMatrix4f_Projection(
            m_EyeRenderDesc[eye].Fov,
            0.01f, 10000.0f, true);

        const OVR::Matrix4f view = _MakeModelviewMatrix(
            eyePose,
            -OVR::Vector3f(m_EyeRenderDesc[eye].ViewAdjust), // not sure why negative...
            m_chassisYaw,
            m_chassisPos);

        const OVR::Matrix4f scaledView = _MakeModelviewMatrix(
            eyePose,
            -OVR::Vector3f(m_EyeRenderDesc[eye].ViewAdjust), // not sure why negative...
            m_chassisYaw,
            m_chassisPos,
            m_headSize);

        _resetGLState();

        _DrawScenes(&view.Transposed().M[0][0], &proj.Transposed().M[0][0], rvp, &scaledView.Transposed().M[0][0]);

        renderPose[eyeIndex] = eyePose;
        eyeTexture[eyeIndex] = l_EyeTexture[eye].Texture;
    }
    unbindFBO();

    ovrHmd_EndFrame(m_Hmd, renderPose, eyeTexture);

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
    glBindBuffer(GL_ARRAY_BUFFER, 0);
    glUseProgram(0);
}
// The MAIN function, from here we start the application and run the game loop
int main()
{
    // Init GLFW
    glfwInit();
    // Set all the required options for GLFW
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);

    // Create a GLFWwindow object that we can use for GLFW's functions
    GLFWwindow* window = glfwCreateWindow(WIDTH, HEIGHT, "LearnOpenGL", nullptr, nullptr);
    glfwMakeContextCurrent(window);

    // Set the required callback functions
    glfwSetKeyCallback(window, key_callback);

    // Set this to true so GLEW knows to use a modern approach to retrieving function pointers and extensions
    glewExperimental = GL_TRUE;
    // Initialize GLEW to setup the OpenGL Function pointers
    glewInit();

    // Define the viewport dimensions
    glViewport(0, 0, WIDTH, HEIGHT);


    // Build and compile our shader program
    Shader ourShader("basic.vs", "basic.frag");


    // Set up vertex data (and buffer(s)) and attribute pointers
    GLfloat vertices[] = {
        // Positions         // Colors
        0.5f, -0.5f, 0.0f,   1.0f, 0.0f, 0.0f,  // Bottom Right
        -0.5f, -0.5f, 0.0f,   0.0f, 1.0f, 0.0f,  // Bottom Left
        0.0f,  0.5f, 0.0f,   0.0f, 0.0f, 1.0f   // Top
    };
    GLuint VBO, VAO;
    glGenVertexArrays(1, &VAO);
    glGenBuffers(1, &VBO);
    // Bind the Vertex Array Object first, then bind and set vertex buffer(s) and attribute pointer(s).
    glBindVertexArray(VAO);

    glBindBuffer(GL_ARRAY_BUFFER, VBO);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

    // Position attribute
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), (GLvoid*)0);
    glEnableVertexAttribArray(0);
    // Color attribute
    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat)));
    glEnableVertexAttribArray(1);

    glBindVertexArray(0); // Unbind VAO


    // Game loop
    while (!glfwWindowShouldClose(window))
    {
        // Check if any events have been activiated (key pressed, mouse moved etc.) and call corresponding response functions
        glfwPollEvents();

        // Render
        // Clear the colorbuffer
        glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT);

        // Draw the triangle
        ourShader.Use();
        glBindVertexArray(VAO);
        glDrawArrays(GL_TRIANGLES, 0, 3);
        glBindVertexArray(0);

        // Swap the screen buffers
        glfwSwapBuffers(window);
    }
    // Properly de-allocate all resources once they've outlived their purpose
    glDeleteVertexArrays(1, &VAO);
    glDeleteBuffers(1, &VBO);
    // Terminate GLFW, clearing any resources allocated by GLFW.
    glfwTerminate();
    return 0;
}
Exemplo n.º 9
0
void RiftAppSkeleton::display_client() //const
{
    ovrHmd hmd = m_Hmd;
    if (hmd == NULL)
        return;

    //ovrFrameTiming hmdFrameTiming =
    ovrHmd_BeginFrameTiming(hmd, 0);

    bindFBO(m_renderBuffer, m_fboScale);

    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    for (int eyeIndex = 0; eyeIndex < ovrEye_Count; eyeIndex++)
    {
        const ovrEyeType eye = hmd->EyeRenderOrder[eyeIndex];
        const ovrPosef eyePose = ovrHmd_GetEyePose(hmd, eye);
        m_eyeOri = eyePose.Orientation; // cache this for movement direction
        _StoreHmdPose(eyePose);

        const ovrGLTexture& otex = l_EyeTexture[eye];
        const ovrRecti& rvp = otex.OGL.Header.RenderViewport;
        const ovrRecti rsc = {
            static_cast<int>(m_fboScale * rvp.Pos.x),
            static_cast<int>(m_fboScale * rvp.Pos.y),
            static_cast<int>(m_fboScale * rvp.Size.w),
            static_cast<int>(m_fboScale * rvp.Size.h)
        };
        glViewport(rsc.Pos.x, rsc.Pos.y, rsc.Size.w, rsc.Size.h);

        const OVR::Matrix4f proj = ovrMatrix4f_Projection(
            m_EyeRenderDesc[eye].Fov,
            0.01f, 10000.0f, true);

        ///@todo Should we be using this variable?
        //m_EyeRenderDesc[eye].DistortedViewport;

        const OVR::Matrix4f view = _MakeModelviewMatrix(
            eyePose,
            m_EyeRenderDesc[eye].ViewAdjust,
            m_chassisYaw,
            m_chassisPos);

        const OVR::Matrix4f scaledView = _MakeModelviewMatrix(
            eyePose,
            m_EyeRenderDesc[eye].ViewAdjust,
            m_chassisYaw,
            m_chassisPos,
            m_headSize);

        _resetGLState();

        _DrawScenes(&view.Transposed().M[0][0], &proj.Transposed().M[0][0], rsc, &scaledView.Transposed().M[0][0]);
    }
    unbindFBO();


    // Set full viewport...?
    const int w = m_Cfg.OGL.Header.RTSize.w;
    const int h = m_Cfg.OGL.Header.RTSize.h;
    glViewport(0, 0, w, h);

    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glDisable(GL_DEPTH_TEST);
    glDisable(GL_CULL_FACE);

    // Now draw the distortion mesh...
    for(int eyeNum = 0; eyeNum < 2; eyeNum++)
    {
        const ShaderWithVariables& eyeShader = eyeNum == 0 ?
            m_presentDistMeshL :
            m_presentDistMeshR;
        const GLuint prog = eyeShader.prog();
        glUseProgram(prog);
        //glBindVertexArray(eyeShader.m_vao);
        {
            const ovrDistortionMesh& mesh = m_DistMeshes[eyeNum];
            glBindBuffer(GL_ARRAY_BUFFER, 0);

            const int a_pos =  glGetAttribLocation(prog, "vPosition");
            glVertexAttribPointer(a_pos, 4, GL_FLOAT, GL_FALSE, sizeof(ovrDistortionVertex), &mesh.pVertexData[0].ScreenPosNDC.x);
            glEnableVertexAttribArray(a_pos);

            const int a_texR =  glGetAttribLocation(prog, "vTexR");
            if (a_texR > -1)
            {
                glVertexAttribPointer(a_texR, 2, GL_FLOAT, GL_FALSE, sizeof(ovrDistortionVertex), &mesh.pVertexData[0].TanEyeAnglesR);
                glEnableVertexAttribArray(a_texR);
            }

            const int a_texG =  glGetAttribLocation(prog, "vTexG");
            if (a_texG > -1)
            {
                glVertexAttribPointer(a_texG, 2, GL_FLOAT, GL_FALSE, sizeof(ovrDistortionVertex), &mesh.pVertexData[0].TanEyeAnglesG);
                glEnableVertexAttribArray(a_texG);
            }

            const int a_texB =  glGetAttribLocation(prog, "vTexB");
            if (a_texB > -1)
            {
                glVertexAttribPointer(a_texB, 2, GL_FLOAT, GL_FALSE, sizeof(ovrDistortionVertex), &mesh.pVertexData[0].TanEyeAnglesB);
                glEnableVertexAttribArray(a_texB);
            }

            ovrVector2f uvoff =
                m_uvScaleOffsetOut[2*eyeNum + 1];
                //DistortionData.UVScaleOffset[eyeNum][0];
            ovrVector2f uvscale =
                m_uvScaleOffsetOut[2*eyeNum + 0];
                //DistortionData.UVScaleOffset[eyeNum][1];

            glUniform2f(eyeShader.GetUniLoc("EyeToSourceUVOffset"), uvoff.x, uvoff.y);
            glUniform2f(eyeShader.GetUniLoc("EyeToSourceUVScale"), uvscale.x, uvscale.y);


#if 0
            // Setup shader constants
            DistortionData.Shaders->SetUniform2f(
                "EyeToSourceUVScale",
                DistortionData.UVScaleOffset[eyeNum][0].x,
                DistortionData.UVScaleOffset[eyeNum][0].y);
            DistortionData.Shaders->SetUniform2f(
                "EyeToSourceUVOffset",
                DistortionData.UVScaleOffset[eyeNum][1].x,
                DistortionData.UVScaleOffset[eyeNum][1].y);

            if (distortionCaps & ovrDistortionCap_TimeWarp)
            { // TIMEWARP - Additional shader constants required
                ovrMatrix4f timeWarpMatrices[2];
                ovrHmd_GetEyeTimewarpMatrices(HMD, (ovrEyeType)eyeNum, eyeRenderPoses[eyeNum], timeWarpMatrices);
                //WARNING!!! These matrices are transposed in SetUniform4x4f, before being used by the shader.
                DistortionData.Shaders->SetUniform4x4f("EyeRotationStart", Matrix4f(timeWarpMatrices[0]));
                DistortionData.Shaders->SetUniform4x4f("EyeRotationEnd", Matrix4f(timeWarpMatrices[1]));
            }

            // Perform distortion
            pRender->Render(
                &distortionShaderFill,
                DistortionData.MeshVBs[eyeNum],
                DistortionData.MeshIBs[eyeNum]);
#endif

            glActiveTexture(GL_TEXTURE0);
            glBindTexture(GL_TEXTURE_2D, m_renderBuffer.tex);
            glUniform1i(eyeShader.GetUniLoc("fboTex"), 0);

            // This is the only uniform that changes per-frame
            glUniform1f(eyeShader.GetUniLoc("fboScale"), m_fboScale);


            glDrawElements(
                GL_TRIANGLES,
                mesh.IndexCount,
                GL_UNSIGNED_SHORT,
                &mesh.pIndexData[0]);
        }
        glBindVertexArray(0);
        glUseProgram(0);
    }

    ovrHmd_EndFrameTiming(hmd);
}
Exemplo n.º 10
0
///@todo Even though this function shares most of its code with client rendering,
/// which appears to work fine, it is non-convergable. It appears that the projection
/// matrices for each eye are too far apart? Could be modelview...
void RiftAppSkeleton::display_stereo_undistorted() //const
{
    ovrHmd hmd = m_Hmd;
    if (hmd == NULL)
        return;

    //ovrFrameTiming hmdFrameTiming =
    ovrHmd_BeginFrameTiming(hmd, 0);

    bindFBO(m_renderBuffer, m_fboScale);

    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    for (int eyeIndex = 0; eyeIndex < ovrEye_Count; eyeIndex++)
    {
        ovrEyeType eye = hmd->EyeRenderOrder[eyeIndex];
        ovrPosef eyePose = ovrHmd_GetEyePose(hmd, eye);

        const ovrGLTexture& otex = l_EyeTexture[eye];
        const ovrRecti& rvp = otex.OGL.Header.RenderViewport;
        const ovrRecti rsc = {
            static_cast<int>(m_fboScale * rvp.Pos.x),
            static_cast<int>(m_fboScale * rvp.Pos.y),
            static_cast<int>(m_fboScale * rvp.Size.w),
            static_cast<int>(m_fboScale * rvp.Size.h)
        };
        glViewport(rsc.Pos.x, rsc.Pos.y, rsc.Size.w, rsc.Size.h);

        OVR::Quatf orientation = OVR::Quatf(eyePose.Orientation);
        OVR::Matrix4f proj = ovrMatrix4f_Projection(
            m_EyeRenderDesc[eye].Fov,
            0.01f, 10000.0f, true);

        //m_EyeRenderDesc[eye].DistortedViewport;
        OVR::Vector3f EyePos = m_chassisPos;
        OVR::Matrix4f view = OVR::Matrix4f(orientation.Inverted())
            * OVR::Matrix4f::RotationY(m_chassisYaw)
            * OVR::Matrix4f::Translation(-EyePos);
        OVR::Matrix4f eyeview = OVR::Matrix4f::Translation(m_EyeRenderDesc[eye].ViewAdjust) * view;

        _resetGLState();

        _DrawScenes(&eyeview.Transposed().M[0][0], &proj.Transposed().M[0][0], rvp);
    }
    unbindFBO();

    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glDisable(GL_DEPTH_TEST);
    glDisable(GL_CULL_FACE);

    // Present FBO to screen
    const GLuint prog = m_presentFbo.prog();
    glUseProgram(prog);
    m_presentFbo.bindVAO();
    {
        glActiveTexture(GL_TEXTURE0);
        glBindTexture(GL_TEXTURE_2D, m_renderBuffer.tex);
        glUniform1i(m_presentFbo.GetUniLoc("fboTex"), 0);

        // This is the only uniform that changes per-frame
        glUniform1f(m_presentFbo.GetUniLoc("fboScale"), m_fboScale);

        glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
    }
    glBindVertexArray(0);
    glUseProgram(0);

    ovrHmd_EndFrameTiming(hmd);
}
Exemplo n.º 11
0
int main(int, char**)
{
    // Setup window
    glfwSetErrorCallback(error_callback);
    if (!glfwInit())
        exit(1);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    GLFWwindow* window = glfwCreateWindow(1280, 720, "ImGui OpenGL3 example", NULL, NULL);
    glfwMakeContextCurrent(window);
    gl3wInit();

    // Setup ImGui binding
    ImGui_ImplGlfwGL3_Init(window, true);
    //ImGuiIO& io = ImGui::GetIO();
    //ImFont* my_font0 = io.Fonts->AddFontDefault();
    //ImFont* my_font1 = io.Fonts->AddFontFromFileTTF("../../extra_fonts/DroidSans.ttf", 16.0f);
    //ImFont* my_font2 = io.Fonts->AddFontFromFileTTF("../../extra_fonts/Karla-Regular.ttf", 16.0f);
    //ImFont* my_font3 = io.Fonts->AddFontFromFileTTF("../../extra_fonts/ProggyClean.ttf", 13.0f); my_font3->DisplayOffset.y += 1;
    //ImFont* my_font4 = io.Fonts->AddFontFromFileTTF("../../extra_fonts/ProggyTiny.ttf", 10.0f); my_font4->DisplayOffset.y += 1;
    //ImFont* my_font5 = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, io.Fonts->GetGlyphRangesJapanese());

    bool show_test_window = true;
    bool show_another_window = false;
    ImVec4 clear_color = ImColor(114, 144, 154);

    // Main loop
    while (!glfwWindowShouldClose(window))
    {
        ImGuiIO& io = ImGui::GetIO();
        glfwPollEvents();
        ImGui_ImplGlfwGL3_NewFrame();

        // 1. Show a simple window
        // Tip: if we don't call ImGui::Begin()/ImGui::End() the widgets appears in a window automatically called "Debug"
        {
            static float f;
            ImGui::Text("Hello, world!");
            ImGui::SliderFloat("float", &f, 0.0f, 1.0f);
            ImGui::ColorEdit3("clear color", (float*)&clear_color);
            if (ImGui::Button("Test Window")) show_test_window ^= 1;
            if (ImGui::Button("Another Window")) show_another_window ^= 1;
            ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
        }

        // 2. Show another simple window, this time using an explicit Begin/End pair
        if (show_another_window)
        {
            ImGui::SetNextWindowSize(ImVec2(200,100), ImGuiSetCond_FirstUseEver);
            ImGui::Begin("Another Window", &show_another_window);
            ImGui::Text("Hello");
            ImGui::End();
        }

        // 3. Show the ImGui test window. Most of the sample code is in ImGui::ShowTestWindow()
        if (show_test_window)
        {
            ImGui::SetNextWindowPos(ImVec2(650, 20), ImGuiSetCond_FirstUseEver);
            ImGui::ShowTestWindow(&show_test_window);
        }
        
        // Rendering
        glViewport(0, 0, (int)io.DisplaySize.x, (int)io.DisplaySize.y);
        glClearColor(clear_color.x, clear_color.y, clear_color.z, clear_color.w);
        glClear(GL_COLOR_BUFFER_BIT);
        ImGui::Render();
        glfwSwapBuffers(window);
    }

    // Cleanup
    ImGui_ImplGlfwGL3_Shutdown();
    glfwTerminate();

    return 0;
}
Exemplo n.º 12
0
BOOL Initialize ()					// Any GL Init Code & User Initialization Goes Here
{

	// Start Of User Initialization
	GLfloat angle		= 0.0f;									// Set Starting Angle To Zero

// #ifndef _MSC_VER

	GLfloat global_ambient[4] = {0.2f, 0.2f,  0.2f, 1.0f};		// Set Ambient Lighting To Fairly Dark Light (No Color)
	GLfloat light0pos[4] =      {0.0f, 5.0f, 10.0f, 1.0f};		// Set The Light Position
	GLfloat light0ambient[4] =  {0.2f, 0.2f,  0.2f, 1.0f};		// More Ambient Light
	GLfloat light0diffuse[4] =  {0.3f, 0.3f,  0.3f, 1.0f};		// Set The Diffuse Light A Bit Brighter
	GLfloat light0specular[4] = {0.8f, 0.8f,  0.8f, 1.0f};		// Fairly Bright Specular Lighting

	GLfloat lmodel_ambient[4] = {0.2f,0.2f,0.2f,1.0f};			// And More Ambient Light

// #else
/*
    GLfloat global_ambient[4];
    GLfloat light0pos[4];
    GLfloat light0ambient[4];
    GLfloat light0diffuse[4];
    GLfloat light0specular[4];
    GLfloat lmodel_ambient[4];

	global_ambient[0]=0.2f; 		            // Set Ambient Lighting To Fairly Dark Light (No Color)
    global_ambient[1]=0.2f;
	global_ambient[2]=0.2f;
	global_ambient[3]=1.0f;
	light0pos[0]= 0.0f; 	                    // Set The Light Position
	light0pos[1]= 5.0f;
	light0pos[2]= 10.0f;
    light0pos[3]= 1.0f;
	light0ambient[0]=0.2f;		                // More Ambient Light
	light0ambient[1]=0.2f;
	light0ambient[2]=0.2f;
    light0ambient[3]=1.0f;
	light0diffuse[0]=0.3f;		                // Set The Diffuse Light A Bit Brighter
	light0diffuse[1]=0.3f;
	light0diffuse[2]=0.3f;
    light0diffuse[3]=1.0f;
	light0specular[0]=0.8f;		                // Fairly Bright Specular Lighting
	light0specular[1]=0.8f;
	light0specular[2]=0.8f;
    light0specular[3]= 1.0f;
	lmodel_ambient[0]= 0.2f;			        // And More Ambient Light
	lmodel_ambient[1]= 0.2f;
	lmodel_ambient[2]= 0.2f;
    lmodel_ambient[3]= 1.0f;
*/

// #endif // _MSC_VER

	BlurTexture = EmptyTexture();								// Create Our Empty Texture

	glViewport(0 , 0,width ,height);	// Set Up A Viewport
	glMatrixMode(GL_PROJECTION);								// Select The Projection Matrix
	glLoadIdentity();											// Reset The Projection Matrix
	gluPerspective(50, (float)width/(float)height, 5,  2000); // Set Our Perspective
	glMatrixMode(GL_MODELVIEW);									// Select The Modelview Matrix
	glLoadIdentity();											// Reset The Modelview Matrix

	glEnable(GL_DEPTH_TEST);									// Enable Depth Testing

	glLightModelfv(GL_LIGHT_MODEL_AMBIENT,lmodel_ambient);		// Set The Ambient Light Model

	glLightModelfv(GL_LIGHT_MODEL_AMBIENT, global_ambient);		// Set The Global Ambient Light Model
	glLightfv(GL_LIGHT0, GL_POSITION, light0pos);				// Set The Lights Position
	glLightfv(GL_LIGHT0, GL_AMBIENT, light0ambient);			// Set The Ambient Light
	glLightfv(GL_LIGHT0, GL_DIFFUSE, light0diffuse);			// Set The Diffuse Light
	glLightfv(GL_LIGHT0, GL_SPECULAR, light0specular);			// Set Up Specular Lighting
	glEnable(GL_LIGHTING);										// Enable Lighting
	glEnable(GL_LIGHT0);										// Enable Light0

	glShadeModel(GL_SMOOTH);									// Select Smooth Shading

	glMateriali(GL_FRONT, GL_SHININESS, 128);
	glClearColor(0.0f, 0.0f, 0.0f, 0.5);						// Set The Clear Color To Black

	return TRUE;												// Return TRUE (Initialization Successful)
}
Exemplo n.º 13
0
// Отработка изменения размеров окна
void reshape_func( int width, int height ) {
   if (width <= 0 || height <= 0)
      return;
   glViewport(0, 0, width, height);
   TwWindowSize(width, height);
}
Exemplo n.º 14
0
void TV3DManager::display(RenderArgs* renderArgs, Camera& whichCamera) {
    double nearZ = DEFAULT_NEAR_CLIP; // near clipping plane
    double farZ = DEFAULT_FAR_CLIP; // far clipping plane

    // left eye portal
    int portalX = 0;
    int portalY = 0;
    QSize deviceSize = qApp->getDeviceSize() *
        qApp->getRenderResolutionScale();
    int portalW = deviceSize.width() / 2;
    int portalH = deviceSize.height();


    DependencyManager::get<GlowEffect>()->prepare(renderArgs);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    Camera eyeCamera;
    eyeCamera.setRotation(whichCamera.getRotation());
    eyeCamera.setPosition(whichCamera.getPosition());

    glEnable(GL_SCISSOR_TEST);
    glPushMatrix();
    forEachEye([&](eyeFrustum& eye){
        _activeEye = &eye;
        glViewport(portalX, portalY, portalW, portalH);
        glScissor(portalX, portalY, portalW, portalH);
        glMatrixMode(GL_PROJECTION);
        glLoadIdentity(); // reset projection matrix
        glFrustum(eye.left, eye.right, eye.bottom, eye.top, nearZ, farZ); // set left view frustum
        GLfloat p[4][4];
        // Really?
        glGetFloatv(GL_PROJECTION_MATRIX, &(p[0][0]));
        float cotangent = p[1][1];
        GLfloat fov = atan(1.0f / cotangent);
        glTranslatef(eye.modelTranslation, 0.0, 0.0); // translate to cancel parallax

        glMatrixMode(GL_MODELVIEW);
        glLoadIdentity();
        renderArgs->_renderSide = RenderArgs::MONO;
        qApp->displaySide(renderArgs, eyeCamera, false);
        qApp->getApplicationOverlay().displayOverlayTextureStereo(whichCamera, _aspect, fov);
        _activeEye = NULL;
    }, [&]{
        // render right side view
        portalX = deviceSize.width() / 2;
    });
    glPopMatrix();
    glDisable(GL_SCISSOR_TEST);

    auto finalFbo = DependencyManager::get<GlowEffect>()->render(renderArgs);
    auto fboSize = finalFbo->getSize();
    // Get the ACTUAL device size for the BLIT
    deviceSize = qApp->getDeviceSize();

    glBindFramebuffer(GL_READ_FRAMEBUFFER, gpu::GLBackend::getFramebufferID(finalFbo));
    glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
    glBlitFramebuffer(0, 0, fboSize.x, fboSize.y,
                      0, 0, deviceSize.width(), deviceSize.height(),
                        GL_COLOR_BUFFER_BIT, GL_NEAREST);
    glBindFramebuffer(GL_READ_FRAMEBUFFER, 0);

    // reset the viewport to how we started
    glViewport(0, 0, deviceSize.width(), deviceSize.height());
}
//Called whenever the window is resized. The new window size is given, in pixels.
//This is an opportunity to call glViewport or glScissor to keep up with the change in size.
void reshape (int w, int h)
{
    glViewport(0, 0, (GLsizei) w, (GLsizei) h);
}
void GeblGuiEditorBase::Draw(void)
{
	if(YSTRUE!=drawingMasterSwitch)
	{
		DrawGuiOnly();
		return;
	}

	// Do this at the beginning of Draw funtion.  This will allow one of the elements set SetNeedRedraw(YSTRUE) 
	// within drawing function so that Draw function will be called again in the next iteragion. >>
	SetNeedRedraw(YSFALSE);
	drawEnv.SetNeedRedraw(YSFALSE);
	threeDInterface.SetNeedRedraw(YSFALSE);
	// <<


	glEnable(GL_POLYGON_OFFSET_FILL);
	glPolygonOffset(1,1);


	if(NULL==slHd)
	{
		if(NULL!=GetTopStatusBar())
		{
			GetTopStatusBar()->ClearStringAll();
		}
		if(NULL!=GetBottomStatusBar())
		{
			GetBottomStatusBar()->ClearStringAll();
		}
	}

	if(NULL!=slHd && NULL!=GetTopStatusBar())
	{
		YsWString ful,pth,fil;
		slHd->GetFileName(ful);
		ful.SeparatePathFile(pth,fil);
		if(YSTRUE==slHd->IsModified())
		{
			fil.Append(L"(*)");
		}

		YsWString curMsg;
		if(0!=YsWString::Strcmp(fil,GetTopStatusBar()->GetString(curMsg,0)))
		{
			GetTopStatusBar()->SetString(0,fil);
		}
	}

	if(NULL!=slHd && NULL!=GetBottomStatusBar())
	{
		YsString str("Selection");
		YsString append;

		{
			YsArray <YsShellVertexHandle> selVtHd;
			slHd->GetSelectedVertex(selVtHd);
			if(0<selVtHd.GetN())
			{
				append.Printf("  Vertex:%d",(int)selVtHd.GetN());
				str.Append(append);
			}
		}
		{
			YsArray <YsShellPolygonHandle> selPlHd;
			slHd->GetSelectedPolygon(selPlHd);
			if(0<selPlHd.GetN())
			{
				append.Printf("  Polygon:%d",(int)selPlHd.GetN());
				str.Append(append);
			}
		}
		{
			YsArray <YsShellExt::ConstEdgeHandle> selCeHd;
			slHd->GetSelectedConstEdge(selCeHd);
			if(0<selCeHd.GetN())
			{
				append.Printf("  ConstEdge:%d",(int)selCeHd.GetN());
				str.Append(append);
			}
		}
		{
			YsArray <YsShellExt::FaceGroupHandle> selFgHd;
			slHd->GetSelectedFaceGroup(selFgHd);
			if(0<selFgHd.GetN())
			{
				append.Printf("  FaceGroup:%d",(int)selFgHd.GetN());
				str.Append(append);
			}
		}
		GetBottomStatusBar()->SetString(0,str);
	}


	int viewport[4];
	drawEnv.GetOpenGlCompatibleViewport(viewport);
	drawEnv.SetVerticalOrientation(YSTRUE);
	drawEnv.UpdateNearFar();


	glEnable(GL_BLEND);
	glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
	glEnable(GL_DEPTH_TEST);
	glDepthFunc(GL_LEQUAL);


	if(YsCoordSysModel==YSOPENGL)
	{
		glFrontFace(GL_CCW);
	}
	else
	{
		glFrontFace(GL_CW);
	}


	const YsMatrix4x4 &projMat=drawEnv.GetProjectionMatrix();
	const YsMatrix4x4 &viewMat=drawEnv.GetViewMatrix();
	const YsMatrix4x4 projViewMat=(projMat*viewMat);

	threeDInterface.SetViewport(viewport);
	threeDInterface.SetProjViewModelMatrix(projViewMat);


	glViewport(viewport[0],viewport[1],viewport[2],viewport[3]);

	GLfloat glProjMat[16];
	projMat.GetOpenGlCompatibleMatrix(glProjMat);

	GLfloat glModelviewMat[16];
	viewMat.GetOpenGlCompatibleMatrix(glModelviewMat);


	// glMatrixMode(GL_PROJECTION);
	// glLoadIdentity();
	// glMultMatrixf(glProjMat);
	// glMatrixMode(GL_MODELVIEW);
	// glLoadIdentity();
	// glMultMatrixf(glModelviewMat);


	YsGLSLSetShared3DRendererProjection(glProjMat);
	YsGLSLSetShared3DRendererModelView(glModelviewMat);


	YsVec3 lightDir=YsUnitVector(YsVec3(0.1,1.0,3.0));
	const GLfloat lightDirf[]={lightDir.xf(),lightDir.yf(),lightDir.zf()};
	YsGLSLSetShared3DRendererDirectionalLightInCameraCoordinatefv(0,lightDirf);
	YsGLSLSetShared3DRendererSpecularColor(config->GetSpecularColor());
	YsGLSLSetShared3DRendererAmbientColor(config->GetAmbientColor());
	YsGLSLSetShared3DRendererLightColor(0,config->GetLightColor());



	actuallyDrawVertex=drawVertex;
	actuallyDrawConstEdge=drawConstEdge;
	actuallyDrawPolygonEdge=drawPolygonEdge;
	actuallyDrawPolygon=drawPolygon;
	actuallyDrawShrunkPolygon=drawShrunkPolygon;
	actuallyDrawNonManifoldEdge=drawNonManifoldEdge;

	if(NULL!=UIBeforeDrawCallBack)
	{
		(*UIBeforeDrawCallBack)(*this);
	}

	glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);


	if(YSTRUE==viewDrawBackgroundGradation->GetCheck() && (NULL==guiExtension || YSTRUE!=guiExtension->DrawBackground()))
	{
// Linear interpolation looks to be too fast.  Probably need three colors.
		YsGLSLUsePlain2DRenderer(YsGLSLSharedPlain2DRenderer());
		YsGLSLUseWindowCoordinateInPlain2DDrawing(YsGLSLSharedPlain2DRenderer(),YSTRUE);

		glDepthMask(0);

		const GLfloat rect[12]=
		{
			0                   ,0,
			(GLfloat)viewport[2],0,
			0                   ,(GLfloat)viewport[3]/2.0f,
			(GLfloat)viewport[2],(GLfloat)viewport[3]/2.0f,
			0                   ,(GLfloat)viewport[3],
			(GLfloat)viewport[2],(GLfloat)viewport[3]
		};
		const GLfloat color[24]=
		{
			config->bgColor[0].Rf(),config->bgColor[0].Gf(),config->bgColor[0].Bf(),1,
			config->bgColor[0].Rf(),config->bgColor[0].Gf(),config->bgColor[0].Bf(),1,
			config->bgColor[1].Rf(),config->bgColor[1].Gf(),config->bgColor[1].Bf(),1,
			config->bgColor[1].Rf(),config->bgColor[1].Gf(),config->bgColor[1].Bf(),1,
			config->bgColor[2].Rf(),config->bgColor[2].Gf(),config->bgColor[2].Bf(),1,
			config->bgColor[2].Rf(),config->bgColor[2].Gf(),config->bgColor[2].Bf(),1
		};
		YsGLSLDrawPlain2DPrimitivefv(YsGLSLSharedPlain2DRenderer(),GL_TRIANGLE_STRIP,6,rect,color);

		glDepthMask(1);

		YsGLSLEndUsePlain2DRenderer(YsGLSLSharedPlain2DRenderer());
	}



	threeDInterface.Draw();


	if(NULL!=slHd && YSTRUE==slHd->NeedRemakeHighlightVertexBuffer())
	{
		slHd->GetHighlight().RemakeVertexBuffer(*slHd);
		slHd->SetNeedRemakeHighlightVertexBuffer(YSFALSE);
	}

	if(NEED_REMAKE_DRAWING_NONE!=needRemakeDrawingBuffer || (nullptr!=slHd && YSTRUE==slHd->GetTemporaryModification().Changed()))
	{
		RemakeDrawingBuffer(slHd,needRemakeDrawingBuffer);
		needRemakeDrawingBuffer=NEED_REMAKE_DRAWING_NONE;
		slHd->GetTemporaryModification().ClearChangeFlag();
	}
	if(NEED_REMAKE_DRAWING_NONE!=needRemakeDrawingBuffer_for_OtherShell && YSTRUE==actuallyDrawOtherShell)
	{
		YsArray <YsShellDnmContainer <YsShellExtEditGui>::Node *> allNode;
		shlGrp.GetNodePointerAll(allNode);
		for(YSSIZE_T nodeIdx=0; nodeIdx<allNode.GetN(); ++nodeIdx)
		{
			if(slHd!=allNode[nodeIdx])
			{
				RemakeDrawingBuffer(allNode[nodeIdx],needRemakeDrawingBuffer_for_OtherShell);
			}
		}
		needRemakeDrawingBuffer_for_OtherShell=NEED_REMAKE_DRAWING_NONE;
	}


	{
		GLfloat prevTfm[16];
		GLfloat curNodeTfm[16];
		if(YSTRUE==dnmEditMode)
		{
			YsMatrix4x4 curMat;
			{
				YsGLSLShaded3DRenderer renderer;
				renderer.GetModelView(prevTfm);
				curMat.CreateFromOpenGlCompatibleMatrix(prevTfm);
			}
			YsMatrix4x4 tfm=curMat*dnmState.GetNodeToRootTransformation(slHd);
			tfm.GetOpenGlCompatibleMatrix(curNodeTfm);
			YsGLSLSetShared3DRendererModelView(curNodeTfm);
		}


		YsShellExtDrawingBuffer &drawBuf=slHd->GetDrawingBuffer();
		if(YSTRUE==actuallyDrawVertex && NULL!=slHd)
		{
			GeblGuiFoundation::DrawVertex(*slHd,viewport);
		}
		if(0<drawBuf.selectedVertexPosBuffer.GetNumVertex() && NULL!=slHd)
		{
			GeblGuiFoundation::DrawSelectedVertex(*slHd,viewport);
		}
		if(0<drawBuf.selectedVertexLineBuffer.GetNumVertex() && NULL!=slHd)
		{
			GeblGuiFoundation::DrawSelectedVertexLine(*slHd);
		}
		if(YSTRUE==actuallyDrawPolygonEdge && NULL!=slHd)
		{
			GeblGuiFoundation::DrawPolygonEdge(*slHd);
		}
		if(YSTRUE==actuallyDrawShrunkPolygon && NULL!=slHd)
		{
			GeblGuiFoundation::DrawShrunkPolygon(*slHd);

		}
		if(0<drawBuf.selectedPolygonPosBuffer.GetNumVertex() && NULL!=slHd)
		{
			GeblGuiFoundation::DrawSelectedPolygon(*slHd);
		}
		if(YSTRUE==actuallyDrawConstEdge && 0<drawBuf.constEdgeVtxBuffer.GetNumVertex() && NULL!=slHd)
		{
			GeblGuiFoundation::DrawConstEdge(*slHd);
		}
		if(0<drawBuf.selectedConstEdgeVtxBuffer.GetNumVertex() && NULL!=slHd)
		{
			GeblGuiFoundation::DrawSelectedConstEdge(*slHd);
		}
		if(YSTRUE==dnmEditMode)
		{
			YsGLSLSetShared3DRendererModelView(prevTfm);
		}


		if(YSTRUE!=dnmEditMode)
		{
			DrawInGeometryEditMode();
		}
		else
		{
			DrawInDnmEditMode();
		}


		if(YSTRUE==dnmEditMode)
		{
			YsGLSLSetShared3DRendererModelView(curNodeTfm);
		}
		if(0<=drawBuf.selectedFaceGroupVtxBuffer.GetNumVertex() && NULL!=slHd)
		{
			GeblGuiFoundation::DrawSelectedFaceGroup(*slHd);
		}
		if(YSTRUE==dnmEditMode)
		{
			YsGLSLSetShared3DRendererModelView(prevTfm);
		}
	}




	if(NULL!=slHd && YSTRUE==actuallyDrawNonManifoldEdge)
	{
		if(YSTRUE==nonManifoldEdgeCache.IsModified(slHd))
		{
			nonManifoldEdgeCache.CacheNonManifoldEdge(slHd);
		}
		struct YsGLSL3DRenderer *renderer=YsGLSLSharedVariColor3DRenderer();
		YsGLSLUse3DRenderer(renderer);

		glLineWidth(3);
		YsGLSLDrawPrimitiveVtxColfv(renderer,GL_LINES,nonManifoldEdgeCache.lineVtxBuf.GetNi(),nonManifoldEdgeCache.lineVtxBuf,nonManifoldEdgeCache.lineColBuf);
		glLineWidth(1);

		YsGLSLEndUse3DRenderer(renderer);

		// The following could have easily be done by glPointSize.  However, stupid OpenGL ES 2.0 got rid of glPointSize.
		// OpenGL ES should be gone.  The hardware on the tablets and smart phones are good enough to support full-blown
		// OpenGL.  OpenGL ES will be remembered as a dark history of OpenGL.  That is bad.  Not as bad as Direct 3D though.
		renderer=YsGLSLSharedVariColorMarkerByPointSprite3DRenderer();
		YsGLSLUse3DRenderer(renderer);

#ifdef GL_PROGRAM_POINT_SIZE
		glEnable(GL_POINT_SPRITE);
		glEnable(GL_PROGRAM_POINT_SIZE);
#endif
		YsGLSLSet3DRendererUniformMarkerType(renderer,YSGLSL_MARKER_TYPE_RECT);
		YsGLSLSet3DRendererUniformMarkerDimension(renderer,3.0f);
		YsGLSLDrawPrimitiveVtxColfv(
		    renderer,GL_POINTS,
		    nonManifoldEdgeCache.pointVtxBuf.GetNi(),
		    nonManifoldEdgeCache.pointVtxBuf,
		    nonManifoldEdgeCache.pointColBuf);
#ifdef GL_PROGRAM_POINT_SIZE
		glDisable(GL_POINT_SPRITE);
		glDisable(GL_PROGRAM_POINT_SIZE);
#endif
		YsGLSLEndUse3DRenderer(renderer);
	}

	if(YSTRUE==drawHighlight)
	{
		auto &bufManager=YsGLBufferManager::GetSharedBufferManager();
		auto &highlight=slHd->GetHighlight();

		YsGLSLRenderer renderer(YsGLSLSharedFlat3DRenderer());

		const GLfloat blue[]={0.0f,0.0f,1.0f,1.0f};
		YsGLSLSet3DRendererUniformColorfv(renderer,blue);

		{
			auto unitPtr=bufManager.GetBufferUnit(highlight.highlightedEdgeVboHandle);
			if(nullptr!=unitPtr && YsGLBufferManager::Unit::EMPTY!=unitPtr->GetState())
			{
				unitPtr->GetActualBuffer()->DrawPrimitiveVtx(renderer,GL_LINES);
			}
		}

		glLineWidth(2);
		{
			auto unitPtr=bufManager.GetBufferUnit(highlight.highlightedThickEdgeVboHandle);
			if(nullptr!=unitPtr && YsGLBufferManager::Unit::EMPTY!=unitPtr->GetState())
			{
				unitPtr->GetActualBuffer()->DrawPrimitiveVtx(renderer,GL_LINES);
			}
		}
		glLineWidth(1);

		const GLfloat darkBlue[]={0.0f,0.0f,0.7f,1.0f};
		YsGLSLSet3DRendererUniformColorfv(renderer,darkBlue);
		{
			auto unitPtr=bufManager.GetBufferUnit(highlight.highlightedPolygonVboHandle);
			if(nullptr!=unitPtr && YsGLBufferManager::Unit::EMPTY!=unitPtr->GetState())
			{
				unitPtr->GetActualBuffer()->DrawPrimitiveVtx(renderer,GL_TRIANGLES);
			}
		}
	}

	if(NULL!=UIDrawCallBack3D)
	{
		UIDrawCallBack3D(*this);
	}
	if(draw3dCallBack)
	{
		draw3dCallBack();
	}


	refBmpStore->Draw();


	if(YSTRUE==drawAxis)
	{
		const GLfloat axisLength=5.0;
		GeblGuiFoundation::DrawAxis(axisLength,viewport,projMat,viewMat);
	}



	// 2D Drawing
	// glMatrixMode(GL_PROJECTION);
	// glLoadIdentity();
	// glOrtho(0.0,(double)viewport[2],(double)viewport[3],0.0,-1.0,1.0);
	// glMatrixMode(GL_MODELVIEW);
	// glLoadIdentity();

	YsGLSLUsePlain2DRenderer(YsGLSLSharedPlain2DRenderer());
	YsGLSLUseWindowCoordinateInPlain2DDrawing(YsGLSLSharedPlain2DRenderer(),YSTRUE);
	{
		if(YSTRUE==lBtnDown)
		{
			const GLfloat rect[8]=
			{
				(GLfloat)lBtnDownMx,(GLfloat)lBtnDownMy,
				(GLfloat)moveMx,    (GLfloat)lBtnDownMy,
				(GLfloat)moveMx,    (GLfloat)moveMy,
				(GLfloat)lBtnDownMx,(GLfloat)moveMy
			};
			const GLfloat color[16]=
			{
				0,0,0,0.8f,
				0,0,0,0.8f,
				0,0,0,0.8f,
				0,0,0,0.8f
			};
			YsGLSLDrawPlain2DPrimitivefv(YsGLSLSharedPlain2DRenderer(),GL_LINE_LOOP,4,rect,color);
		}
	}
	YsGLSLEndUsePlain2DRenderer(YsGLSLSharedPlain2DRenderer());

	glDisable(GL_DEPTH_TEST);

	FsGuiCanvas::Show();

	if(NULL!=UIDrawCallBack2D)
	{
		(*UIDrawCallBack2D)(*this);
	}

	FsSwapBuffers();
}
Exemplo n.º 17
0
void LightingExample::Reshape(int width, int height)
{
    glViewport(0, 0, width, height);
}
Exemplo n.º 18
0
void
reshape (int w, int h)
{
    glViewport (0, 0, w, h);
    centerProjection (w, h);
}
Exemplo n.º 19
0
void FFGLNode::inputsUpdated( qint64 pTimeStamp )
{
	NodeControlBase::inputsUpdated( pTimeStamp );

	if( !QOpenGLContext::currentContext() )
	{
		return;
	}

	InterfaceOpenGL			*GL = qobject_cast<InterfaceOpenGL *>( FreeframePlugin::instance()->app()->findInterface( IID_OPENGL ) );

	if( GL )
	{
		GL->checkErrors( __FILE__, __LINE__ );
	}

	initializeOpenGLFunctions();

	FF_Main_FuncPtr		MainFunc = mLibrary->func();

	if( !MainFunc )
	{
		return;
	}

	fugio::OpenGLTextureInterface	*DstTex = output<fugio::OpenGLTextureInterface *>( mPinOutputRender );

	QSize							 DstSze;

	if( DstTex )
	{
		if( !DstTex->dstTexId() )
		{
			return;
		}

		DstSze = QSize( DstTex->size().x(), DstTex->size().y() );

		initialiseInstance( QPoint( 0, 0 ), DstSze );
	}

	if( !mInstanceId )
	{
		return;
	}

	FFMixed					PMU;

	SetParameterStructTag	PrmSet;

	for( int i = 0 ; i < mParams.size() ; i++ )
	{
		QSharedPointer<fugio::PinInterface>		PrmPin = mParams.at( i );
		FreeframeLibrary::ParamEntry			PrmEnt = mLibrary->params().at( i );

		QVariant		PrmVal = variant( PrmPin );

		PrmSet.ParameterNumber = i;

		if( PrmEnt.mType == FF_TYPE_STANDARD )
		{
			PrmSet.NewParameterValue.FloatValue = qBound( 0.0f, PrmVal.value<float>(), 1.0f );

			PMU.PointerValue = &PrmSet;

			MainFunc( FF_SETPARAMETER, PMU, mInstanceId );
		}
		else if( PrmEnt.mType == FF_TYPE_BOOLEAN )
		{
			PrmSet.NewParameterValue.UIntValue = PrmVal.value<bool>() ? FF_TRUE : FF_FALSE;

			PMU.PointerValue = &PrmSet;

			MainFunc( FF_SETPARAMETER, PMU, mInstanceId );
		}

		PMU.UIntValue = i;

		PMU = MainFunc( FF_GETPARAMETERDISPLAY, PMU, mInstanceId );

		if( PMU.UIntValue != FF_FAIL )
		{
			PrmPin->setDisplayLabel( QString::fromLatin1( QByteArray( (const char *)PMU.PointerValue, 16 ) ) );
		}
	}

	if( DstTex )
	{
		GLint		FBOCur;

		glGetIntegerv( GL_FRAMEBUFFER_BINDING, &FBOCur );

		quint32	FBO = DstTex->fbo();

		if( FBO )
		{
			glBindFramebuffer( GL_FRAMEBUFFER, FBO );

			GLint		Viewport[ 4 ];

			glGetIntegerv( GL_VIEWPORT, Viewport );

			glViewport( 0, 0, DstSze.width(), DstSze.height() );

			render();

			glViewport( Viewport[ 0 ], Viewport[ 1 ], Viewport[ 2 ], Viewport[ 3 ] );
		}
	}

	pinUpdated( mPinOutputRender );
}
void    GLUI_Mouse_Interaction::draw_active_area( void )
{
  int orig;
  int win_h = glutGet( GLUT_WINDOW_HEIGHT ), win_w = glutGet(GLUT_WINDOW_WIDTH);
  
  if ( NOT glui )
    return;

  /*putchar( 'X' ); flushout;              */

  orig = set_to_glut_window();
	
  int text_height = 18; /* what a kludge              */

  int viewport_size = h-text_height;  /*MIN(w,h);              */

  glMatrixMode( GL_MODELVIEW );
  glPushMatrix();
  glLoadIdentity();
  glTranslatef( (float) win_w/2.0, (float) win_h/2.0, 0.0 );
  glRotatef( 180.0, 0.0, 1.0, 0.0 );
  glRotatef( 180.0, 0.0, 0.0, 1.0 );
  glTranslatef( (float) -win_w/2.0, (float) -win_h/2.0, 0.0 );

  glTranslatef( (float) this->x_abs + .5, (float) this->y_abs + .5, 0.0 );

  glTranslatef( (float)this->w/2.0, (float)viewport_size/2.0 + 2.0 , 0.0  );

  /***   Draw the interaction control's orthographic elements   ***/
  iaction_draw_active_area_ortho();	 
 
  /***   Setup and draw the interaction control's perspective elements   ***/

  /***  Set the viewport to just the square of the drawing area  ***/
  /* glViewport( this->x_abs , glui->main_panel->h - this->y_abs - this->h,*/
  /*glViewport( this->x_abs+1+(this->w/2-viewport_size/2),
    this->h-this->y_abs-viewport_size-1, 
    viewport_size, viewport_size );*/
	
  viewport_size -= 4;
  int offset = 0;
  if ( ((this->w-viewport_size) % 2) == 1 ) 
    offset = 1;

  glViewport( this->x_abs + (this->w-viewport_size)/2 + offset, 
	      win_h - this->y_abs - this->h + text_height, 
	      viewport_size, viewport_size );

  glMatrixMode( GL_PROJECTION );
  glLoadIdentity();
  glFrustum( -1.0*.08, 1.0*.08, -.08, .08, .1, 8.0 );
  glMatrixMode( GL_MODELVIEW );
  glPushMatrix();
  glLoadIdentity();
  glTranslatef( 0.0, 0.0, -3.2f );
  
  /*	glutSolidTeapot( 1.0 );              */
  iaction_draw_active_area_persp();

  glMatrixMode( GL_MODELVIEW );
  glPopMatrix();

  glui->set_viewport();
  glui->set_ortho_projection();

  glMatrixMode( GL_MODELVIEW );
  glPopMatrix();

  restore_window(orig);
}
Exemplo n.º 21
0
void sizeHandler(GLFWwindow* window,int xs,int ys)
{
	glfwMakeContextCurrent(window);
	glViewport(0, 0, xs, ys);
}
void EDA_3D_CANVAS::create_and_render_shadow_buffer( GLuint *aDst_gl_texture,
        GLuint aTexture_size, bool aDraw_body, int aBlurPasses )
{
    glDisable( GL_TEXTURE_2D );

    glViewport( 0, 0, aTexture_size, aTexture_size);

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

    // Render body and shapes

    if( aDraw_body && m_glLists[GL_ID_BODY] )
        glCallList( m_glLists[GL_ID_BODY] );

    if( m_glLists[GL_ID_3DSHAPES_SOLID_FRONT] )
        glCallList( m_glLists[GL_ID_3DSHAPES_SOLID_FRONT] );

    // Create and Initialize the float depth buffer

    float *depthbufferFloat = (float*) malloc( aTexture_size * aTexture_size * sizeof(float) );

    for( unsigned int i = 0; i < (aTexture_size * aTexture_size); i++ )
        depthbufferFloat[i] = 1.0f;

    glPixelStorei( GL_PACK_ALIGNMENT, 4 );
    glPixelStorei( GL_UNPACK_ALIGNMENT, 4 );
    glReadBuffer( GL_BACK_LEFT );
    glReadPixels( 0, 0,
                  aTexture_size, aTexture_size,
                  GL_DEPTH_COMPONENT, GL_FLOAT, depthbufferFloat );

    CheckGLError( __FILE__, __LINE__ );

    glEnable( GL_TEXTURE_2D );
    glGenTextures( 1, aDst_gl_texture );
    glBindTexture( GL_TEXTURE_2D, *aDst_gl_texture );

    CIMAGE imgDepthBuffer( aTexture_size, aTexture_size );
    CIMAGE imgDepthBufferAux( aTexture_size, aTexture_size );

    imgDepthBuffer.SetPixelsFromNormalizedFloat( depthbufferFloat );

    free( depthbufferFloat );

    // Debug texture image
    //wxString filename;
    //filename.Printf( "imgDepthBuffer_%04d", *aDst_gl_texture );
    //imgDepthBuffer.SaveAsPNG( filename );

    while( aBlurPasses > 0 )
    {
        aBlurPasses--;
        imgDepthBufferAux.EfxFilter( &imgDepthBuffer, FILTER_GAUSSIAN_BLUR );
        imgDepthBuffer.EfxFilter( &imgDepthBufferAux, FILTER_GAUSSIAN_BLUR );
    }

    // Debug texture image
    //filename.Printf( "imgDepthBuffer_blur%04d", *aDst_gl_texture );
    //imgDepthBuffer.SaveAsPNG( filename );

    unsigned char *depthbufferRGBA = (unsigned char*) malloc( aTexture_size * aTexture_size * 4 );
    unsigned char *pPixels = imgDepthBuffer.GetBuffer();

    // Convert it to a RGBA buffer
    for( unsigned int i = 0; i < (aTexture_size * aTexture_size); i++ )
    {
        depthbufferRGBA[i * 4 + 0] = 0;
        depthbufferRGBA[i * 4 + 1] = 0;
        depthbufferRGBA[i * 4 + 2] = 0;
        depthbufferRGBA[i * 4 + 3] = 255 - pPixels[i];                  // Store in alpha channel the inversion of the image
    }

    glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );
    glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );
    glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
    glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );

    glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, aTexture_size, aTexture_size, 0, GL_RGBA, GL_UNSIGNED_BYTE, depthbufferRGBA );

    free( depthbufferRGBA );

    CheckGLError( __FILE__, __LINE__ );
}
Exemplo n.º 23
0
static void reshape(int width, int height) {
    
    glViewport(0, 0, width, height);
}
Exemplo n.º 24
0
ENTRYPOINT void draw_wip24(ModeInfo *mi) {
    uint64_t frame_start = get_time();
    wip24_state* state = states + MI_SCREEN(mi);
    
    glXMakeCurrent(MI_DISPLAY(mi), MI_WINDOW(mi), *(state->glx_context));
    
    glBindFramebuffer(GL_FRAMEBUFFER, state->framebuffer);
    glDrawBuffer(GL_COLOR_ATTACHMENT0);
    glViewport(0, 0, MI_WIDTH(mi)/state->undersample, MI_HEIGHT(mi)/state->undersample);
    if (state->program) {
        glUseProgram(state->program);
        update_uniforms(mi, state);
        glRectf(-1.0f, -1.0f, 1.0f, 1.0f);
    }
    
    glBindFramebuffer(GL_FRAMEBUFFER, 0);
    glViewport(0, 0, MI_WIDTH(mi), MI_HEIGHT(mi));
    glUseProgram(0);
    glBindTexture(GL_TEXTURE_2D, state->fb_texture);
    glBegin(GL_QUADS);
    glTexCoord2f(0.0f, 0.0f);
    glVertex2f(-1.0f, -1.0f);
    glTexCoord2f(1.0f, 0.0f);
    glVertex2f(1.0f, -1.0f);
    glTexCoord2f(1.0f, 1.0f);
    glVertex2f(1.0f, 1.0f);
    glTexCoord2f(0.0f, 1.0f);
    glVertex2f(-1.0f, 1.0f);
    glEnd();
    
    if (mi->fps_p) do_fps(mi);
    
    print_texture_label(MI_DISPLAY(mi), state->font, MI_WIDTH(mi), MI_HEIGHT(mi),
                        get_boolean_resource(MI_DISPLAY(mi), "fpsTop", "FPSTop")?2:1,
                        state->shader_info);
    
    glXSwapBuffers(MI_DISPLAY(mi), MI_WINDOW(mi));
    
    state->time_delta = get_time() - frame_start;
    state->frame_count++;
    
    float dest = mi->pause / 1000.0f;
    float current = state->time_delta / 1000000.0f;
    
    float* undersample = state->undersamples + state->frame_count%4;
    if (current > (dest+1.0f)) *undersample += 0.1f;
    else if (current<(dest-1.0f) && state->undersample>1.0f) *undersample -= 0.1f;
    else goto no_reshape;
    
    state->undersample = (state->undersamples[0]+state->undersamples[1]+
                          state->undersamples[2]+state->undersamples[3]) / 2.0f;
    state->undersample = state->undersample>undersample_max ? undersample_max:state->undersample;
    reshape_wip24(mi, MI_WIDTH(mi), MI_HEIGHT(mi));
    no_reshape:
        ;
    
    mi->pause = dest>current ? dest-current : 0;
    
    if ((get_time() - state->start_time)/1000000000.0f > shader_duration)
        init_shader(mi, state);
}
Exemplo n.º 25
0
void windowResize(GLFWwindow *window, int width, int height) {
    glViewport(0, 0, width, height);
    int tweak = TwWindowSize(width, height);
}
void ResizeFunction(int Width, int Height)
{
	CurrentWidth = Width;
	CurrentHeight = Height;
	glViewport(0, 0, CurrentWidth, CurrentHeight);
}
Exemplo n.º 27
0
static void framebuffer_size_callback(GLFWwindow* window, int width, int height)
{
    printf("Framebuffer resized to %ix%i\n", width, height);

    glViewport(0, 0, width, height);
}
Exemplo n.º 28
0
void
ogl_olight_resize(int w, int h)
{
  glViewport(0, 0, w, h);
  ogl_olight_setMatrix();
}
Exemplo n.º 29
0
int main(int argc, char** argv)
{
	
	if (!glfwInit())	// 初始化glfw库
	{
		std::cout << "Error::GLFW could not initialize GLFW!" << std::endl;
		return -1;
	}

	// 开启OpenGL 3.3 core profile
	std::cout << "Start OpenGL core profile version 3.3" << std::endl;
	glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
	glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
	glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
	glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
	glfwWindowHint(GLFW_SAMPLES, 4); // 设置采样点个数 注意这里设置GLFW选项 不要写成了GL_SAMPLES

	// 创建窗口
	GLFWwindow* window = glfwCreateWindow(WINDOW_WIDTH, WINDOW_HEIGHT,
		"Demo of anti-aliasing(press O on, F off)", NULL, NULL);
	if (!window)
	{
		std::cout << "Error::GLFW could not create winddow!" << std::endl;
		glfwTerminate();
		std::system("pause");
		return -1;
	}
	// 创建的窗口的context指定为当前context
	glfwMakeContextCurrent(window);

	// 注册窗口键盘事件回调函数
	glfwSetKeyCallback(window, key_callback);
	// 注册鼠标事件回调函数
	glfwSetCursorPosCallback(window, mouse_move_callback);
	// 注册鼠标滚轮事件回调函数
	glfwSetScrollCallback(window, mouse_scroll_callback);
	// 鼠标捕获 停留在程序内
	glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);

	// 初始化GLEW 获取OpenGL函数
	glewExperimental = GL_TRUE; // 让glew获取所有拓展函数
	GLenum status = glewInit();
	if (status != GLEW_OK)
	{
		std::cout << "Error::GLEW glew version:" << glewGetString(GLEW_VERSION) 
			<< " error string:" << glewGetErrorString(status) << std::endl;
		glfwTerminate();
		std::system("pause");
		return -1;
	}

	// 设置视口参数
	glViewport(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT);
	
	//Section1 顶点属性数据
	// 指定立方体顶点属性数据 顶点位置 纹理
	GLfloat cubeVertices[] = {
		-0.5f, -0.5f, 0.5f, 0.0f, 0.0f,	// A
		0.5f, -0.5f, 0.5f, 1.0f, 0.0f,	// B
		0.5f, 0.5f, 0.5f,1.0f, 1.0f,	// C
		0.5f, 0.5f, 0.5f,1.0f, 1.0f,	// C
		-0.5f, 0.5f, 0.5f,0.0f, 1.0f,	// D
		-0.5f, -0.5f, 0.5f,0.0f, 0.0f,	// A


		-0.5f, -0.5f, -0.5f,0.0f, 0.0f,	// E
		-0.5f, 0.5f, -0.5f,0.0, 1.0f,   // H
		0.5f, 0.5f, -0.5f,1.0f, 1.0f,	// G
		0.5f, 0.5f, -0.5f,1.0f, 1.0f,	// G
		0.5f, -0.5f, -0.5f,1.0f, 0.0f,	// F
		-0.5f, -0.5f, -0.5f,0.0f, 0.0f,	// E

		-0.5f, 0.5f, 0.5f,0.0f, 1.0f,	// D
		-0.5f, 0.5f, -0.5f,1.0, 1.0f,   // H
		-0.5f, -0.5f, -0.5f,1.0f, 0.0f,	// E
		-0.5f, -0.5f, -0.5f,1.0f, 0.0f,	// E
		-0.5f, -0.5f, 0.5f,0.0f, 0.0f,	// A
		-0.5f, 0.5f, 0.5f,0.0f, 1.0f,	// D

		0.5f, -0.5f, -0.5f,1.0f, 0.0f,	// F
		0.5f, 0.5f, -0.5f,1.0f, 1.0f,	// G
		0.5f, 0.5f, 0.5f,0.0f, 1.0f,	// C
		0.5f, 0.5f, 0.5f,0.0f, 1.0f,	// C
		0.5f, -0.5f, 0.5f, 0.0f, 0.0f,	// B
		0.5f, -0.5f, -0.5f,1.0f, 0.0f,	// F

		0.5f, 0.5f, -0.5f,1.0f, 1.0f,	// G
		-0.5f, 0.5f, -0.5f,0.0, 1.0f,   // H
		-0.5f, 0.5f, 0.5f,0.0f, 0.0f,	// D
		-0.5f, 0.5f, 0.5f,0.0f, 0.0f,	// D
		0.5f, 0.5f, 0.5f,1.0f, 0.0f,	// C
		0.5f, 0.5f, -0.5f,1.0f, 1.0f,	// G

		-0.5f, -0.5f, 0.5f,0.0f, 0.0f,	// A
		-0.5f, -0.5f, -0.5f, 0.0f, 1.0f,// E
		0.5f, -0.5f, -0.5f,1.0f, 1.0f,	// F
		0.5f, -0.5f, -0.5f,1.0f, 1.0f,	// F
		0.5f, -0.5f, 0.5f,1.0f, 0.0f,	// B
		-0.5f, -0.5f, 0.5f,0.0f, 0.0f,	// A
	};
	// Section2 准备缓存对象
	GLuint cubeVAOId, cubeVBOId;
	glGenVertexArrays(1, &cubeVAOId);
	glGenBuffers(1, &cubeVBOId);
	glBindVertexArray(cubeVAOId);
	glBindBuffer(GL_ARRAY_BUFFER, cubeVBOId);
	glBufferData(GL_ARRAY_BUFFER, sizeof(cubeVertices), cubeVertices, GL_STATIC_DRAW);
	// 顶点位置数据
	glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 
		5 * sizeof(GL_FLOAT), (GLvoid*)0);
	glEnableVertexAttribArray(0);
	// 顶点纹理数据
	glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 
		5 * sizeof(GL_FLOAT), (GLvoid*)(3 * sizeof(GL_FLOAT)));
	glEnableVertexAttribArray(1);
	glBindVertexArray(0);

	// Section3 准备着色器程序
	Shader shader("scene.vertex", "scene.frag");
	
	glEnable(GL_MULTISAMPLE); // 开启multisample
	glEnable(GL_DEPTH_TEST);
	glDepthFunc(GL_LESS);
	glEnable(GL_CULL_FACE);
	// 开始游戏主循环
	while (!glfwWindowShouldClose(window))
	{
		GLfloat currentFrame = (GLfloat)glfwGetTime();
		deltaTime = currentFrame - lastFrame;
		lastFrame = currentFrame;
		glfwPollEvents(); // 处理例如鼠标 键盘等事件
		do_movement(); // 根据用户操作情况 更新相机属性

		glClearColor(0.18f, 0.04f, 0.14f, 1.0f);
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

		shader.use();
		glm::mat4 projection = glm::perspective(camera.mouse_zoom,
			(GLfloat)(WINDOW_WIDTH) / WINDOW_HEIGHT, 1.0f, 100.0f); // 投影矩阵
		glm::mat4 view = camera.getViewMatrix(); // 视变换矩阵
		glUniformMatrix4fv(glGetUniformLocation(shader.programId, "projection"),
			1, GL_FALSE, glm::value_ptr(projection));
		glUniformMatrix4fv(glGetUniformLocation(shader.programId, "view"),
			1, GL_FALSE, glm::value_ptr(view));
		glm::mat4 model;
		model = glm::mat4();
		model = glm::rotate(model, glm::radians(45.0f), glm::vec3(0.0f, 1.0f, 0.0f));
		glUniformMatrix4fv(glGetUniformLocation(shader.programId, "model"),
			1, GL_FALSE, glm::value_ptr(model));
		// 这里填写场景绘制代码
		glBindVertexArray(cubeVAOId);
		glDrawArrays(GL_TRIANGLES, 0, 36);
		glBindVertexArray(0);

		glBindVertexArray(0);
		glUseProgram(0);
		glfwSwapBuffers(window); // 交换缓存
	}
	// 释放资源
	glDeleteVertexArrays(1, &cubeVAOId);
	glDeleteBuffers(1, &cubeVBOId);
	glfwTerminate();
	return 0;
}