예제 #1
0
void CShadowHandler::CreateShadows()
{
	fb.Bind();

	glDisable(GL_BLEND);
	glDisable(GL_LIGHTING);
	glDisable(GL_ALPHA_TEST);
	glDisable(GL_TEXTURE_2D);

	glShadeModel(GL_FLAT);
	glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
	glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
	glDepthMask(GL_TRUE);
	glEnable(GL_DEPTH_TEST);

	glViewport(0, 0, shadowMapSize, shadowMapSize);

	// glClearColor(0, 0, 0, 0);
	// glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	glClear(GL_DEPTH_BUFFER_BIT);

	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	glOrtho(0, 1, 0, 1, 0, -1);

	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();


	const ISkyLight* L = sky->GetLight();

	// sun direction is in world-space, invert it
	sunDirZ = -L->GetLightDir();
	sunDirX = (sunDirZ.cross(UpVector)).ANormalize();
	sunDirY = (sunDirX.cross(sunDirZ)).ANormalize();

	SetShadowMapSizeFactors();

	// NOTE:
	//     the xy-scaling factors from CalcMinMaxView do not change linearly
	//     or smoothly with camera movements, creating visible artefacts (eg.
	//     large jumps in shadow resolution)
	//
	//     therefore, EITHER use "fixed" scaling values such that the entire
	//     map barely fits into the sun's frustum (by pretending it is embedded
	//     in a sphere and taking its diameter), OR variable scaling such that
	//     everything that can be seen by the camera maximally fills the sun's
	//     frustum (choice of projection-style is left to the user and can be
	//     changed at run-time)
	//
	//     the first option means larger maps will have more blurred/aliased
	//     shadows if the depth buffer is kept at the same size, but no (map)
	//     geometry is ever omitted
	//
	//     the second option means shadows have higher average resolution, but
	//     become less sharp as the viewing volume increases (through eg.camera
	//     rotations) and geometry can be omitted in some cases
	//
	// NOTE:
	//     when DynamicSun is enabled, the orbit is always circular in the xz
	//     plane, instead of elliptical when the map has an aspect-ratio != 1
	//
	const float xyScale =
		(shadowProMode == SHADOWPROMODE_CAM_CENTER)? GetOrthoProjectedFrustumRadius(camera, centerPos):
		(shadowProMode == SHADOWPROMODE_MAP_CENTER)? GetOrthoProjectedMapRadius(-sunDirZ, centerPos):
		1.0f;
	const float xScale = xyScale;
	const float yScale = xyScale;
	const float zScale = globalRendering->viewRange;

	shadowMatrix[ 0] = sunDirX.x / xScale;
	shadowMatrix[ 1] = sunDirY.x / yScale;
	shadowMatrix[ 2] = sunDirZ.x / zScale;

	shadowMatrix[ 4] = sunDirX.y / xScale;
	shadowMatrix[ 5] = sunDirY.y / yScale;
	shadowMatrix[ 6] = sunDirZ.y / zScale;

	shadowMatrix[ 8] = sunDirX.z / xScale;
	shadowMatrix[ 9] = sunDirY.z / yScale;
	shadowMatrix[10] = sunDirZ.z / zScale;

	// rotate the target position into sun-space for the translation
	shadowMatrix[12] = (-sunDirX.dot(centerPos) / xScale);
	shadowMatrix[13] = (-sunDirY.dot(centerPos) / yScale);
	shadowMatrix[14] = (-sunDirZ.dot(centerPos) / zScale) + 0.5f;

	glLoadMatrixf(shadowMatrix.m);

	// set the shadow-parameter registers
	// NOTE: so long as any part of Spring rendering still uses
	// ARB programs at run-time, these lines can not be removed
	// (all ARB programs share the same environment)
	glProgramEnvParameter4fARB(GL_VERTEX_PROGRAM_ARB, 16, shadowTexProjCenter.x, shadowTexProjCenter.y, 0.0f, 0.0f);
	glProgramEnvParameter4fARB(GL_VERTEX_PROGRAM_ARB, 17, shadowTexProjCenter.z, shadowTexProjCenter.z, 0.0f, 0.0f);
	glProgramEnvParameter4fARB(GL_VERTEX_PROGRAM_ARB, 18, shadowTexProjCenter.w, shadowTexProjCenter.w, 0.0f, 0.0f);

	if (globalRendering->haveGLSL) {
		for (int i = 0; i < SHADOWGEN_PROGRAM_LAST; i++) {
			shadowGenProgs[i]->Enable();
			shadowGenProgs[i]->SetUniform4fv(0, &shadowTexProjCenter.x);
			shadowGenProgs[i]->Disable();
		}
	}

	if (L->GetLightIntensity() > 0.0f) {
		// move view into sun-space
		const float3 oldup = camera->up;

		camera->right = sunDirX;
		camera->up = sunDirY;

		DrawShadowPasses();

		camera->up = oldup;
	}

	glShadeModel(GL_SMOOTH);
	glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);

	// we do this later to save render context switches (this is one of the slowest opengl operations!)
	// fb.Unbind();
	// glViewport(globalRendering->viewPosX,0,globalRendering->viewSizeX,globalRendering->viewSizeY);
}
예제 #2
0
void teclaPremida(unsigned char key, int x, int y){

	switch(key){
			case 'a':
				if(f >= -3.5){

					f = f - 0.1;
				}
				glutPostRedisplay();
				break;

			case 'd':
				if(f <= 3.5){

					f = f + 0.1;
				}
				glutPostRedisplay();
				break;

			case '1':
				glMatrixMode( GL_PROJECTION );
				glLoadIdentity();
				if(windowWidth<=windowHeight){
					glOrtho(-4.0,4.0,-4.0*ar,4.0*ar,-4.0,4.0);
				}
				else{
					glOrtho(-4.0/ar,4.0/ar,-4.0,4.0,-4.0,4.0);
				}
				glMatrixMode(GL_MODELVIEW);
				glLoadIdentity ();
				glutPostRedisplay();
				gluLookAt(0.0, 0.0, 4.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
				break;

			case '2':
				glMatrixMode( GL_PROJECTION );
				glLoadIdentity();
				gluPerspective(90.0, ar, 0.1, 16.0);
				glMatrixMode(GL_MODELVIEW);
				glLoadIdentity ();
				if(windowWidth<=windowHeight){
					gluLookAt(0.0, -7.0*ar, 3.0, 0.0, 16.0, -1.0, 0.0, 0.0, 1.0);
				}
				else{
					gluLookAt(0.0, -8.0, 3.0, 0.0, 0.0, 16.0, -1.0, 0.0, 1.0);
				}
				glTranslatef(-f, 0.0, 0.0);
				glutPostRedisplay();
				break;

			case '3':
				glMatrixMode( GL_PROJECTION );
				glLoadIdentity();
				gluPerspective(90.0, ar, -4.0, 4.0);
				glMatrixMode(GL_MODELVIEW);
				glLoadIdentity ();
				if(windowWidth<=windowHeight){
					gluLookAt(0.0, -7.0*ar, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0);
				}
				else{
					gluLookAt(0.0, -7.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0);
				}
				glTranslatef(-f, 0.0, 0.0);
				glutPostRedisplay();
				break;
	}
}
예제 #3
0
int main(int argc, char **argv)
{
    int array_size_2d,totpoints,i;
    float rcol,gcol,bcol;

    FILE *fp_col;

    // The following parameters are usually read from a file, but
    // hard code them for the demo:
    ni=320;
    nj=112;
    vxin=0.04;
    roout=1.0;
    tau=0.51;
    // End of parameter list

    // Write parameters to screen
    printf ("ni = %d\n", ni);
    printf ("nj = %d\n", nj);
    printf ("vxin = %f\n", vxin);
    printf ("roout = %f\n", roout);
    printf ("tau = %f\n", tau);
    

    totpoints=ni*nj;    
    array_size_2d=ni*nj*sizeof(float);

    // Allocate memory for arrays
    
    f0 = malloc(array_size_2d);
    f1 = malloc(array_size_2d);
    f2 = malloc(array_size_2d);
    f3 = malloc(array_size_2d);
    f4 = malloc(array_size_2d);
    f5 = malloc(array_size_2d);
    f6 = malloc(array_size_2d);
    f7 = malloc(array_size_2d);
    f8 = malloc(array_size_2d);

    tmpf0 = malloc(array_size_2d);
    tmpf1 = malloc(array_size_2d);
    tmpf2 = malloc(array_size_2d);
    tmpf3 = malloc(array_size_2d);
    tmpf4 = malloc(array_size_2d);
    tmpf5 = malloc(array_size_2d);
    tmpf6 = malloc(array_size_2d);
    tmpf7 = malloc(array_size_2d);
    tmpf8 = malloc(array_size_2d);

    plotvar = malloc(array_size_2d);
    
    plot_rgba = malloc(ni*nj*sizeof(unsigned int));

    solid = malloc(ni*nj*sizeof(int));

    //
    // Some factors used to calculate the f_equilibrium values
    // 
    faceq1 = 4.f/9.f;
    faceq2 = 1.f/9.f;
    faceq3 = 1.f/36.f;


    //
    // Initialise f's by setting them to the f_equilibirum values assuming
    // that the whole domain is at velocity vx=vxin vy=0 and density ro=roout
    //
    for (i=0; i<totpoints; i++) {
	f0[i] = faceq1 * roout * (1.f                             - 1.5f*vxin*vxin);
	f1[i] = faceq2 * roout * (1.f + 3.f*vxin + 4.5f*vxin*vxin - 1.5f*vxin*vxin);
	f2[i] = faceq2 * roout * (1.f                             - 1.5f*vxin*vxin);
	f3[i] = faceq2 * roout * (1.f - 3.f*vxin + 4.5f*vxin*vxin - 1.5f*vxin*vxin);
	f4[i] = faceq2 * roout * (1.f                             - 1.5f*vxin*vxin);
	f5[i] = faceq3 * roout * (1.f + 3.f*vxin + 4.5f*vxin*vxin - 1.5f*vxin*vxin);
	f6[i] = faceq3 * roout * (1.f - 3.f*vxin + 4.5f*vxin*vxin - 1.5f*vxin*vxin);
	f7[i] = faceq3 * roout * (1.f - 3.f*vxin + 4.5f*vxin*vxin - 1.5f*vxin*vxin);
	f8[i] = faceq3 * roout * (1.f + 3.f*vxin + 4.5f*vxin*vxin - 1.5f*vxin*vxin);
	plotvar[i] = vxin;
	solid[i] = 1;
    }

    //
    // Read in colourmap data for OpenGL display 
    //
    fp_col = fopen("cmap.dat","r");
    if (fp_col==NULL) {
	printf("Error: can't open cmap.dat \n");
	return 1;
    }
    // allocate memory for colourmap (stored as a linear array of int's)
    fscanf (fp_col, "%d", &ncol);
    cmap_rgba = (unsigned int *)malloc(ncol*sizeof(unsigned int));
    // read colourmap and store as int's
    for (i=0;i<ncol;i++){
	fscanf(fp_col, "%f%f%f", &rcol, &gcol, &bcol);
	cmap_rgba[i]=((int)(255.0f) << 24) | // convert colourmap to int
	    ((int)(bcol * 255.0f) << 16) |
	    ((int)(gcol * 255.0f) <<  8) |
	    ((int)(rcol * 255.0f) <<  0);
    }
    fclose(fp_col);


    //
    // Iinitialise OpenGL display - use glut
    //
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
    glutInitWindowSize(ni, nj);      // Window of ni x nj pixels
    glutInitWindowPosition(50, 50);  // position
    glutCreateWindow("2D LB");       // title

    // Check for OpenGL extension support 
    printf("Loading extensions: %s\n", glewGetErrorString(glewInit()));
    if(!glewIsSupported(
                        "GL_VERSION_2_0 " 
                        "GL_ARB_pixel_buffer_object "
                        "GL_EXT_framebuffer_object "
                        )){
        fprintf(stderr, "ERROR: Support for necessary OpenGL extensions missing.");
        fflush(stderr);
        return;
    }

    // Set up view
    glClearColor(0.0, 0.0, 0.0, 0.0);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(0,ni,0.,nj, -200.0, 200.0);


    // Create texture which we use to display the result and bind to gl_Tex
    glEnable(GL_TEXTURE_2D);
    glGenTextures(1, &gl_Tex);                     // Generate 2D texture
    glBindTexture(GL_TEXTURE_2D, gl_Tex);          // bind to gl_Tex
    // texture properties:
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
    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_RGBA8, ni, nj, 0, 
                 GL_RGBA, GL_UNSIGNED_BYTE, NULL);


    // Create pixel buffer object and bind to gl_PBO. We store the data we want to
    // plot in memory on the graphics card - in a "pixel buffer". We can then 
    // copy this to the texture defined above and send it to the screen
    glGenBuffers(1, &gl_PBO);
    glBindBuffer(GL_PIXEL_UNPACK_BUFFER_ARB, gl_PBO);
    printf("Buffer created.\n");
    

    // Set the call-back functions and start the glut loop
    printf("Starting GLUT main loop...\n");
    glutDisplayFunc(display);
    glutReshapeFunc(resize);
    glutIdleFunc(display);
    glutMouseFunc(mouse);
    glutMotionFunc(mouse_motion); 
    glutMainLoop();

    return 0;
}
예제 #4
0
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 );

}
예제 #5
0
파일: video.c 프로젝트: aaronjer/SPARToR
void render()
{
  const SDL_VideoInfo *vidinfo;
  int x,y,w,h;
  int i;
  char buf[1000];
  Uint32 vidfr = (metafr-1);
  Uint32 vidfrmod = vidfr%maxframes;

  Uint32 render_start = SDL_GetTicks();
  static Uint32 total_start = 0;
  Uint32 tmp;

  if( metafr==0 || vidfr<=drawnfr ) //==0 prevent never-draw bug
    return;

  if( soon==1 )
    setvideo(soon_w,soon_h,soon_full,0);
  if( soon>0 )
    soon--;

  vidinfo  = SDL_GetVideoInfo();
  w = v_w  = vidinfo->current_w;
  h = v_h  = vidinfo->current_h;
  pad_left = 0;
  pad_top  = 0;
  if( v_center ) {
    pad_left = (w - NATIVEW*scale)/2;
    pad_top  = (h - NATIVEH*scale)/2;
  }

  glMatrixMode(GL_TEXTURE);
  glLoadIdentity();
  glScalef(1.0f/256.0f, 1.0f/256.0f, 1);

  glColor4f(1.0f,1.0f,1.0f,1.0f);
  glEnable(GL_TEXTURE_2D);
  if( v_usealpha )
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  else
    glBlendFunc(GL_ONE, GL_ZERO);
  glEnable(GL_BLEND);

  glAlphaFunc(GL_GREATER,0.01);
  glEnable(GL_ALPHA_TEST);

  glDepthFunc(GL_LEQUAL);
  glEnable(GL_DEPTH_TEST);

  glClear(GL_DEPTH_BUFFER_BIT);

  // viewport and matrixes for game objects
  glViewport(pad_left,h-NATIVEH*scale-pad_top,NATIVEW*scale,NATIVEH*scale);
  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();
  glOrtho(0,NATIVEW,NATIVEH,0,-NATIVEH*3-1,NATIVEH*3+1);
  glMatrixMode(GL_MODELVIEW);
  glLoadIdentity();
  int camx = NATIVEW/2-(int)v_camx, camy = NATIVEH/2-(int)v_camy;
  glTranslatef(camx,camy,0);

  SJGL_SetTex( (GLuint)-1 ); //forget previous texture name
  mod_predraw(vidfr);

  //display objects
  for(i=0;i<maxobjs;i++) {
    OBJ_t *o = fr[vidfrmod].objs+i;
    if( o->flags&OBJF_VIS )
      mod_draw(i,o); // have the mod draw the actual thing
  }

  mod_postdraw(vidfr);

  glDisable(GL_DEPTH_TEST);

  //display hulls and object numbers
  if( v_drawhulls ) {
    glBindTexture( GL_TEXTURE_2D, 0 );
    glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );

    if( mycontext ) {
      CONTEXT_t *co = fr[vidfrmod].objs[mycontext].data;
      int x,y,z;
      for( z=0; z<co->z; z++ )
        for( y=0; y<co->y; y++ )
          for( x=0; x<co->x; x++ ) {
            int pos = co->x*co->y*z + co->x*y + x;
            int flags;

            if( co->dmap[ pos ].flags & CBF_NULL )
              flags = co->map[  pos ].flags;
            else
              flags = co->dmap[ pos ].flags;

            if( flags & CBF_SOLID ) {
              glColor4f(1,0,0,1);
              SJGL_Blit( &(SDL_Rect){0,0,16,16}, x*16,   y*16,   z );
              SJGL_Blit( &(SDL_Rect){0,0,12,12}, x*16+2, y*16+2, z );
            } else if( flags & CBF_PLAT ) {
              glColor4f(0,1,0,1);
              SJGL_Blit( &(SDL_Rect){0,0,16, 2}, x*16,   y*16,   z );
            }
          }
    }

    glColor4f(1,1,1,1);
    for(i=0;i<maxobjs;i++) {
      OBJ_t *o = fr[vidfrmod].objs+i;
      V *pos  = flex(o,OBJF_POS);
      V *hull = flex(o,OBJF_HULL);
      if( pos && hull ) {
        SDL_Rect rect = (SDL_Rect){0, 0, hull[1].x-hull[0].x, hull[1].y-hull[0].y};
        SJGL_Blit( &rect, pos->x+hull[0].x, pos->y+hull[0].y, 0 );
      }
    }

    glPolygonMode( GL_FRONT_AND_BACK, GL_FILL );

    for(i=0;i<maxobjs;i++) {
      OBJ_t *o = fr[vidfrmod].objs+i;
      V *pos  = flex(o,OBJF_POS);
      if( pos ) {
        sprintf(buf,"%d",i);
        SJF_DrawText(pos->x, pos->y, buf);
      }
    }
  }

  // viewport and matrixes for HUD
  glViewport(0,0,w,h);
  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();
  glOrtho(0,w,h,0,-1,1);
  glMatrixMode(GL_MODELVIEW);
  glLoadIdentity();

  //paint black over the border areas, subtractively with v_oob
  {
    int outerl = 0;   int innerl = pad_left;
    int outert = 0;   int innert = pad_top;
    int outerr = w;   int innerr = pad_left + NATIVEW*scale;
    int outerb = h;   int innerb = pad_top  + NATIVEH*scale;
    glDisable(GL_TEXTURE_2D);
    glPushAttrib(GL_COLOR_BUFFER_BIT);
    if( v_oob ) {
      glColor4f(0.02,0.02,0.02,0.02);
      glBlendFunc(GL_ONE,GL_ONE);
      if( GLEW_EXT_blend_equation_separate )
        glBlendEquation(GL_FUNC_REVERSE_SUBTRACT);
    }
    else
      glColor4f(0,0,0,1.0f);
    glBegin(GL_QUADS);
    glVertex2i(outerl,outert); glVertex2i(outerr,outert); glVertex2i(outerr,innert); glVertex2i(outerl,innert); //top
    glVertex2i(outerl,innerb); glVertex2i(outerr,innerb); glVertex2i(outerr,outerb); glVertex2i(outerl,outerb); //bottom
    glVertex2i(outerl,innert); glVertex2i(innerl,innert); glVertex2i(innerl,innerb); glVertex2i(outerl,innerb); //left
    glVertex2i(innerr,innert); glVertex2i(outerr,innert); glVertex2i(outerr,innerb); glVertex2i(innerr,innerb); //right
    glEnd();
    glPopAttrib();
    glEnable(GL_TEXTURE_2D);
    glColor4f(1.0f,1.0f,1.0f,1.0f);
  }

  SJGL_SetTex( (GLuint)-1 ); //forget previous texture name
  mod_outerdraw(vidfr,w,h);

  //display console
  if(console_open) {
    int conh = h/2 - 40;
    if(conh<40) conh = 40;
    glColor4f(0.15,0.15,0.15,0.85);
    glDisable(GL_TEXTURE_2D);
    glBegin(GL_QUADS);
    glVertex2i(0,   0); glVertex2i(w,   0);
    glVertex2i(w,conh); glVertex2i(0,conh);
    glEnd();
    glEnable(GL_TEXTURE_2D);
    glColor4f(1.0f,1.0f,1.0f,1.0f);
    x = 10;
    y = conh-20;
    if((ticks/200)%2)
      SJF_DrawChar(x+SJF_TextExtents(SJC.buf[0]), y, '_');
    for(i=0;y>0;i++) {
      if(SJC.buf[i])
        SJF_DrawText(x,y,SJC.buf[i]);
      y -= 10;
    }
    if( SJC.buf[0] && SJC.buf[0][0] ) {
      char s[10];
      sprintf(s,"%d",SJC.buf[0][strlen(SJC.buf[0])-1]);
      SJF_DrawText(w-20,conh-20,s);
    }
  }

  //display stats
  total_time += (tmp = SDL_GetTicks()) - total_start;
  render_time += tmp - render_start;
  total_start = tmp;
  Uint32 unaccounted_time = total_time - (idle_time + render_time + adv_move_time + adv_collide_time + adv_game_time);
  if( v_showstats ) {
    Uint32 denom = vidfrmod+1;
    sprintf(buf,"idle_time %4d"       ,       idle_time/denom);
    SJF_DrawText(w-20-SJF_TextExtents(buf),10,buf);
    sprintf(buf,"render_time %4d"     ,     render_time/denom);
    SJF_DrawText(w-20-SJF_TextExtents(buf),20,buf);
    sprintf(buf,"adv_move_time %4d"   ,   adv_move_time/denom);
    SJF_DrawText(w-20-SJF_TextExtents(buf),30,buf);
    sprintf(buf,"adv_collide_time %4d",adv_collide_time/denom);
    SJF_DrawText(w-20-SJF_TextExtents(buf),40,buf);
    sprintf(buf,"adv_game_time %4d"   ,   adv_game_time/denom);
    SJF_DrawText(w-20-SJF_TextExtents(buf),50,buf);
    sprintf(buf,"unaccounted_time %4d",unaccounted_time/denom);
    SJF_DrawText(w-20-SJF_TextExtents(buf),60,buf);
    sprintf(buf,"adv_frames  %2.2f"   ,(float)adv_frames/(float)denom);
    SJF_DrawText(w-20-SJF_TextExtents(buf),70,buf);
    sprintf(buf,"fr: idx=%d meta=%d vid=%d hot=%d",metafr%maxframes,metafr,vidfr,hotfr);
    SJF_DrawText(w-20-SJF_TextExtents(buf),80,buf);
  }

  SDL_GL_SwapBuffers();
  setdrawnfr(vidfr);

  if( (int)vidfrmod==maxframes-1 ) { // reset time stats
    total_time       = 0;
    idle_time        = 0;
    render_time      = 0;
    adv_move_time    = 0;
    adv_collide_time = 0;
    adv_game_time    = 0;
    adv_frames       = 0;
  }
}
예제 #6
0
/**
 * Draws all points of the objects in OpenGl with SDL in cartesian coordinates
 */
void drawObjects(struct system *System,
                 struct tip *Tip,
                 struct space *Space,
                 struct graphene *Graphene,
                 struct substrate *Substrate)
{
	SDL_Event event;
	Uint8 running = 1;
	GLfloat angleH = 0.0f;
	GLfloat angleV = -90.0f;
	GLfloat rescaleX = WIDTH/System->size.x;
	GLfloat rescaleY = HEIGHT/System->size.z;

	while (running)
	{
		glMatrixMode (GL_PROJECTION);
		glLoadIdentity ();
		glClearColor(0.0, 0.0, 0.0, 0.0); // Black background color
		glClear(GL_COLOR_BUFFER_BIT); // Black screen
		glColor4f(1.0, 1.0, 1.0, 0.0); // White color for Objects
		glOrtho(-WIDTH/2, WIDTH/2, HEIGHT/2, -HEIGHT/2, HEIGHT/2, -HEIGHT/2);
		glRotatef(angleV, 1.0f, 0.0f, 0.0f); // Show the x-z plane of the system
		glRotatef(angleH, 0.0f, 0.0f, 1.0f); // Rotate around Z
		glTranslatef(-0.0f, -0.0f, -120.0f);
		glPointSize(1.0f);
		glLineWidth(2.0f);
		glMatrixMode (GL_MODELVIEW);

		// Draw objects
		glBegin(GL_POINTS);

		for (Uint32 i = 0; i < Tip->numPoints; i++)
		{
			glColor3f (Tip->points[i].potential/System->potential, 0.5f, 0.0f);
			glVertex3f(Tip->points[i].x * rescaleX,
			           Tip->points[i].y * rescaleY,
			           Tip->points[i].z * rescaleY);
		}

		for (Uint32 i = 0; i < Space->numPoints; i++)
		{
			glColor3f (Space->points[i].potential/System->potential, 0.5f, 0.5f);
			glVertex3f(Space->points[i].x * rescaleX,
			           Space->points[i].y * rescaleY,
			           Space->points[i].z * rescaleY);
		}

		for (Uint32 i = 0; i < Graphene->numPoints; i++)
		{
			glColor3f (Graphene->points[i].potential/System->potential, 0.5f, 0.5f);
			glVertex3f(Graphene->points[i].x * rescaleX,
			           Graphene->points[i].y * rescaleY,
			           Graphene->points[i].z * rescaleY);
		}

		for (Uint32 i = 0; i < Substrate->numPoints; i++)
		{
			glColor3f (Substrate->points[i].potential/System->potential, 0.0f, 0.5f);
			glVertex3f(Substrate->points[i].x * rescaleX,
			           Substrate->points[i].y * rescaleY,
			           Substrate->points[i].z * rescaleY);
		}

		glColor3f (1.0f, 1.0f, 1.0f);
		glVertex3f(0.0f, 0.0f, 0.0f); // Center of the System
		glEnd();

		SDL_GL_SwapBuffers();
		SDL_Delay(150);

		while (SDL_PollEvent (&event))
		{
			if(event.type == SDL_QUIT)
			{
				running = 0;
			}
			else if (event.key.keysym.sym == SDLK_ESCAPE)
			{
				running = 0;
			}
			else if(event.button.button == SDL_BUTTON_LEFT && event.button.state == SDL_PRESSED)
			{
				angleH += 10.0f;
			}
			else if(event.button.button == SDL_BUTTON_RIGHT && event.button.state == SDL_PRESSED)
			{
				angleH -= 10.0f;
			}
			else if(event.button.button == SDL_BUTTON_WHEELUP && event.button.state == SDL_PRESSED)
			{
				angleV += 5.0f;
			}
			else if(event.button.button == SDL_BUTTON_WHEELDOWN && event.button.state == SDL_PRESSED)
			{
				angleV -= 5.0f;
			}
		}
	}
}
예제 #7
0
bool Engine::BootGL()
{
	const GLubyte* card = glGetString(GL_VERSION);
	if(!card)
	{
		DevError("Unable to detect OpenGL version, critical error!!!");
		return false;
	}
	else
	{
		DevDrop("OpenGL Version detected:%s",card);
	}



	SDL_GL_SetAttribute(SDL_GL_RED_SIZE,	8);
	SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE,	8);
	SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE,	8);
	SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER,	8);
	SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
	SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 8);
//	SDL_GLattr(SDL_GL_SWAP_CONTROL,0);
	
	glEnableClientState(GL_VERTEX_ARRAY);
	glEnableClientState(GL_COLOR_ARRAY);

	glEnable(GL_DEPTH_TEST);
	glEnable(GL_BLEND);
	glEnable(GL_TEXTURE_2D);

	GLenum glewError = glewInit();
	if(glewError != GLEW_OK)
	{
		DevError("Error initializing GLEW!!! Aborting Startup!!!");
		Sleep(5000);
		exit(0);
	}
	else
	{
		DevDrop("GLEW Successfully initialized.");
	}

	if(GLEW_ARB_vertex_shader && GLEW_ARB_fragment_shader)
		DevDrop("GLSL Prepared");
	else
		DevError("GLSL Not prepared");
	
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	glShadeModel (GL_SMOOTH);
	glDepthFunc(GL_LEQUAL);
	glAlphaFunc ( GL_GREATER, 0.45 ) ;
	glEnable ( GL_ALPHA_TEST ) ;
	glClearColor(0.0,0.0,0.0,1.0);
	glViewport(0, 0, Window->w,Window->h);
	glOrtho(0.0,(GLdouble)Window->w, (GLdouble)Window->h,0.0,0.0,1.0);

	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	
	#ifdef _DEBUG
	DevDrop("OpenGL Booted!");
	#endif // _DEBUG

	GraphicsM.SetupFBO();
	
	return true;
}
예제 #8
0
/*
==================
RB_RenderFlares

Because flares are simulating an occular effect, they should be drawn after
everything (all views) in the entire frame has been drawn.

Because of the way portals use the depth buffer to mark off areas, the
needed information would be lost after each view, so we are forced to draw
flares after each view.

The resulting artifact is that flares in mirrors or portals don't dim properly
when occluded by something in the main view, and portal flares that should
extend past the portal edge will be overwritten.
==================
*/
void RB_RenderFlares( void )
{
	flare_t  *f;
	flare_t  **prev;
	qboolean draw;

	if ( !r_flares->integer )
	{
		return;
	}

	// (SA) turned light flares back on.  must evaluate problem id had with this
	RB_AddDlightFlares();
	RB_AddCoronaFlares();

	// perform z buffer readback on each flare in this view
	draw = qfalse;
	prev = &r_activeFlares;

	while ( ( f = *prev ) != NULL )
	{
		// throw out any flares that weren't added last frame
		if ( f->addedFrame < backEnd.viewParms.frameCount - 1 )
		{
			*prev = f->next;
			f->next = r_inactiveFlares;
			r_inactiveFlares = f;
			continue;
		}

		// don't draw any here that aren't from this scene / portal
		f->drawIntensity = 0;

		if ( f->frameSceneNum == backEnd.viewParms.frameSceneNum && f->inPortal == backEnd.viewParms.isPortal )
		{
			RB_TestFlare( f );

			if ( f->drawIntensity )
			{
				draw = qtrue;
			}
			else
			{
				// this flare has completely faded out, so remove it from the chain
				*prev = f->next;
				f->next = r_inactiveFlares;
				r_inactiveFlares = f;
				continue;
			}
		}

		prev = &f->next;
	}

	if ( !draw )
	{
		return; // none visible
	}

	if ( backEnd.viewParms.isPortal )
	{
		glDisable( GL_CLIP_PLANE0 );
	}

	glPushMatrix();
	glLoadIdentity();
	glMatrixMode( GL_PROJECTION );
	glPushMatrix();
	glLoadIdentity();
	glOrtho( backEnd.viewParms.viewportX, backEnd.viewParms.viewportX + backEnd.viewParms.viewportWidth,
	         backEnd.viewParms.viewportY, backEnd.viewParms.viewportY + backEnd.viewParms.viewportHeight, -99999, 99999 );

	for ( f = r_activeFlares; f; f = f->next )
	{
		if ( f->frameSceneNum == backEnd.viewParms.frameSceneNum && f->inPortal == backEnd.viewParms.isPortal && f->drawIntensity )
		{
			RB_RenderFlare( f );
		}
	}

	glPopMatrix();
	glMatrixMode( GL_MODELVIEW );
	glPopMatrix();
}
예제 #9
0
void init(void){
  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();
  glOrtho(0.0, 1.0, 0.0, 1.0, -1.0, 1.0);
}
예제 #10
0
// This is the main rendering function that you have to implement and provide to ImGui (via setting up 'RenderDrawListsFn' in the ImGuiIO structure)
// If text or lines are blurry when integrating ImGui in your engine:
// - in your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f)
void ImGui_ImplGLUT_RenderDrawLists(ImDrawData* draw_data)
{
    // We are using the OpenGL fixed pipeline to make the example code simpler to read!
    // A probable faster way to render would be to collate all vertices from all cmd_lists into a single vertex buffer.
    // Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled, vertex/texcoord/color pointers.
    glPushAttrib(GL_ENABLE_BIT | GL_COLOR_BUFFER_BIT | GL_TRANSFORM_BIT);
    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    glDisable(GL_CULL_FACE);
    glDisable(GL_DEPTH_TEST);
    glEnable(GL_SCISSOR_TEST);
    glEnableClientState(GL_VERTEX_ARRAY);
    glEnableClientState(GL_TEXTURE_COORD_ARRAY);
    glEnableClientState(GL_COLOR_ARRAY);
    glEnable(GL_TEXTURE_2D);
    //glUseProgram(0); // You may want this if using this code in an OpenGL 3+ context

    // Setup orthographic projection matrix
    const float width = ImGui::GetIO().DisplaySize.x;
    const float height = ImGui::GetIO().DisplaySize.y;
    glMatrixMode(GL_PROJECTION);
    glPushMatrix();
    glLoadIdentity();
    glOrtho(0.0f, width, height, 0.0f, -1.0f, +1.0f);
    glMatrixMode(GL_MODELVIEW);
    glPushMatrix();
    glLoadIdentity();

    // Render command lists
#define OFFSETOF(TYPE, ELEMENT) ((size_t)&(((TYPE *)0)->ELEMENT))
    for (int n = 0; n < draw_data->CmdListsCount; n++)
    {
        const ImDrawList* cmd_list = draw_data->CmdLists[n];
        const unsigned char* vtx_buffer = (const unsigned char*)&cmd_list->VtxBuffer.front();
        const ImDrawIdx* idx_buffer = &cmd_list->IdxBuffer.front();
        glVertexPointer(2, GL_FLOAT, sizeof(ImDrawVert), (void*)(vtx_buffer + OFFSETOF(ImDrawVert, pos)));
        glTexCoordPointer(2, GL_FLOAT, sizeof(ImDrawVert), (void*)(vtx_buffer + OFFSETOF(ImDrawVert, uv)));
        glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(ImDrawVert), (void*)(vtx_buffer + OFFSETOF(ImDrawVert, col)));

        for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.size(); cmd_i++)
        {
            const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
            if (pcmd->UserCallback)
            {
                pcmd->UserCallback(cmd_list, pcmd);
            }
            else
            {
                glBindTexture(GL_TEXTURE_2D, (GLuint)(intptr_t)pcmd->TextureId);
                glScissor((int)pcmd->ClipRect.x, (int)(height - pcmd->ClipRect.w), (int)(pcmd->ClipRect.z - pcmd->ClipRect.x), (int)(pcmd->ClipRect.w - pcmd->ClipRect.y));
                glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, GL_UNSIGNED_SHORT, idx_buffer);
            }
            idx_buffer += pcmd->ElemCount;
        }
    }
#undef OFFSETOF

    // Restore modified state
    glDisableClientState(GL_COLOR_ARRAY);
    glDisableClientState(GL_TEXTURE_COORD_ARRAY);
    glDisableClientState(GL_VERTEX_ARRAY);
    glBindTexture(GL_TEXTURE_2D, 0);
    glMatrixMode(GL_MODELVIEW);
    glPopMatrix();
    glMatrixMode(GL_PROJECTION);
    glPopMatrix();
    glPopAttrib();
}
예제 #11
0
int main(int argc, char *argv[])
{
    SDL_Surface *screen;

    // Slightly different SDL initialization
    if ( SDL_Init(SDL_INIT_VIDEO) != 0 ) {
        printf("Unable to initialize SDL: %s\n", SDL_GetError());
        return 1;
    }

    SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 ); // *new*

    screen = SDL_SetVideoMode( 640, 480, 16, SDL_OPENGL ); // *changed*
    if ( !screen ) {
        printf("Unable to set video mode: %s\n", SDL_GetError());
        return 1;
    }

    // Set the OpenGL state after creating the context with SDL_SetVideoMode

    glClearColor( 0, 0, 0, 0 );

    glEnable( GL_TEXTURE_2D ); // Needed when we're using the fixed-function pipeline.

    glViewport( 0, 0, 640, 480 );

    glMatrixMode( GL_PROJECTION );
    glPushMatrix(); // just for testing
    glLoadIdentity();

    glOrtho( 0, 640, 480, 0, -1000, 1000 );

    glMatrixMode( GL_MODELVIEW );
    glLoadIdentity();

    // Load the OpenGL texture

    GLuint texture; // Texture object handle
    SDL_Surface *surface; // Gives us the information to make the texture

    if ( (surface = IMG_Load("screenshot.png")) ) {

        // Check that the image's width is a power of 2
        if ( (surface->w & (surface->w - 1)) != 0 ) {
            printf("warning: image.bmp's width is not a power of 2\n");
        }

        // Also check if the height is a power of 2
        if ( (surface->h & (surface->h - 1)) != 0 ) {
            printf("warning: image.bmp's height is not a power of 2\n");
        }

        // Have OpenGL generate a texture object handle for us
        glGenTextures( 1, &texture );

        // Bind the texture object
        glBindTexture( GL_TEXTURE_2D, texture );

        // Set the texture's stretching properties
        glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
        glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );

        //SDL_LockSurface(surface);

        // Add some greyness
        memset(surface->pixels, 0x66, surface->w*surface->h);

        // Edit the texture object's image data using the information SDL_Surface gives us
        glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, surface->w, surface->h, 0,
                      GL_RGBA, GL_UNSIGNED_BYTE, surface->pixels );

        //SDL_UnlockSurface(surface);
    }
    else {
        printf("SDL could not load image.bmp: %s\n", SDL_GetError());
        SDL_Quit();
        return 1;
    }

    // Free the SDL_Surface only if it was successfully created
    if ( surface ) {
        SDL_FreeSurface( surface );
    }

    // Clear the screen before drawing
    glClear( GL_COLOR_BUFFER_BIT );

    // Bind the texture to which subsequent calls refer to
    glBindTexture( GL_TEXTURE_2D, texture );

    glEnable(GL_FOG);
    GLfloat fogColor[] = { 1.0, 0.5, 0.5, 0.05 };
    glFogfv(GL_FOG_COLOR, fogColor);

    assert(glIsEnabled(GL_FOG));

    glBegin( GL_QUADS );
        glTexCoord2i( 0, 0 ); glVertex3f( 10, 10, -1 );
        glTexCoord2i( 1, 0 ); glVertex3f( 300, 10, -1 );
        glTexCoord2i( 1, 1 ); glVertex3f( 300, 128, -1 );
        glTexCoord2i( 0, 1 ); glVertex3f( 10, 128, -1 );

        glTexCoord2f( 0, 0.5 ); glVertex3f( 410, 10, -5 );
        glTexCoord2f( 1, 0.5 ); glVertex3f( 600, 10, -6 );
        glTexCoord2f( 1, 1   ); glVertex3f( 630, 200, -7 );
        glTexCoord2f( 0.5, 1 ); glVertex3f( 310, 250, -8 );
    glEnd();

    glBegin( GL_TRIANGLE_STRIP );
        glTexCoord2i( 0, 0 ); glVertex3f( 100, 300, -1 );
        glTexCoord2i( 1, 0 ); glVertex3f( 300, 300, -1 );
        glTexCoord2i( 1, 1 ); glVertex3f( 300, 400, -1 );
        glTexCoord2i( 0, 1 ); glVertex3f( 500, 410, -1 );
    glEnd();

    glDisable(GL_TEXTURE_2D);

    glColor3ub(90, 255, 255);
    glBegin( GL_QUADS );
        glVertex3f( 10, 410, -5 );
        glVertex3f( 300, 410, -50 );
        glVertex3f( 300, 480, -100 );
        glVertex3f( 10, 470, -5 );
    glEnd();

    glBegin( GL_QUADS );
        glColor3f(1.0, 0, 1.0);   glVertex3f( 410, 410, -10 );
        glColor3f(0, 1.0, 0);     glVertex3f( 600, 410, -10 );
        glColor3f(0, 0, 1.0);     glVertex3f( 600, 480, -10 );
        glColor3f(1.0, 1.0, 1.0); glVertex3f( 410, 470, -10 );
    glEnd();

    SDL_GL_SwapBuffers();

#ifndef __EMSCRIPTEN__
    // Wait for 3 seconds to give us a chance to see the image
    SDL_Delay(30000);
#endif

    // Now we can delete the OpenGL texture and close down SDL
    glDeleteTextures( 1, &texture );

    SDL_Quit();

    return 0;
}
예제 #12
0
void
DrawScene(void)
{

    /* clear the draw buffer */
    glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);

    // clear the rasterization framebuffer
    memset(framebuffer, 0, 3*framebuffer_width*framebuffer_height);

    if (scene == 1)
        DrawTriangles();
    else if (scene == 2)
        TestRasterizationSpeed();
    else if (scene == 4)
        DrawPixels();

    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

    if (scene != 9)
    {
        if (zoom)
            glOrtho(0, framebuffer_width, 0, framebuffer_height, -1, 1);
        else
            glOrtho(0, screen_width, 0, screen_height, -1, 1);

        // Draw textured quad

        glEnable(GL_TEXTURE_2D);
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB8,
            framebuffer_width, framebuffer_height,
            0, GL_RGB, GL_UNSIGNED_BYTE, framebuffer);

        glColor3f(1, 1, 1);
        glBegin(GL_QUADS);
            glTexCoord2i(0, 0);
            glVertex2i(0, 0);
            glTexCoord2i(1, 0);
            glVertex2i(framebuffer_width, 0);
            glTexCoord2i(1, 1);
            glVertex2i(framebuffer_width, framebuffer_height);
            glTexCoord2i(0, 1);
            glVertex2i(0, framebuffer_height);
        glEnd();
    }
    else
    {
        if (zoom)
            glOrtho(-0.5, framebuffer_width-0.5, -0.5, framebuffer_height-0.5, -1, 1);
        else
            glOrtho(-0.5, screen_width-0.5, -0.5, screen_height-0.5, -1, 1);

        DrawTrianglesOpenGL();

        glDisable(GL_TEXTURE_2D);
        glColor3f(1, 1, 0);
        glBegin(GL_POINTS);
            glVertex2i(0, 0);
            glVertex2i(framebuffer_width-1, framebuffer_height-1);
        glEnd();

    }

    // finally, swap the draw buffers to make the triangles appear on screen
    glutSwapBuffers();
}
예제 #13
0
void DrawEEOrientation() {
/* **************************************************************************************************************************** */
	/*
	 * Draw Grey border
	 */
	SetEEOrientView(WindowWidth, WindowHeight); 
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	glOrtho(0, _EEW_W_, 0, _EEW_H_, -1, 1);
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();
	glDisable(GL_LIGHTING);
	glColor3f(1, 1, 1);
	glColor3f(0.5, 0.5, 0.5);
	glBegin(GL_TRIANGLE_STRIP);
		glVertex2f(0, 0);
		glVertex2f(_EEW_B_, _EEW_B_);
		glVertex2f(0, _EEW_H_);
		glVertex2f(_EEW_B_, _EEW_H_-_EEW_B_);
		glVertex2f(_EEW_W_, _EEW_H_);
		glVertex2f(_EEW_W_-_EEW_B_, _EEW_H_-_EEW_B_);
		glVertex2f(_EEW_W_, 0);
		glVertex2f(_EEW_W_-_EEW_B_, _EEW_B_);
		glVertex2f(0, 0);
		glVertex2f(_EEW_B_, _EEW_B_);
	glEnd();
	glEnable(GL_LIGHTING);
/* **************************************************************************************************************************** */
	/* Set persp. proj. */
	SetEEOrientView(WindowWidth, WindowHeight); 
/* **************************************************************************************************************************** */
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();
    glTranslatef(0.0f,0.0f,-25.0f);
    glRotatef(ynew,1.0,0.0,0.0);
    glRotatef(xnew,0.0,1.0,0.0);
    glRotatef(ONew[0], 1.0, 0.0, 0.0);
    glRotatef(ONew[1], 0.0, 1.0, 0.0);
    glRotatef(ONew[2], 0.0, 0.0, 1.0);
/* **************************************************************************************************************************** */
#define _ARROW_L_	(5)
/* **************************************************************************************************************************** */
	/* 
	 * Display Arrow
	 */

	GLUquadricObj	*gluAxesObj_1;
	gluAxesObj_1	= gluNewQuadric();

	glPushMatrix();
	glColor3f(1, 1, 0);
	glScalef(_ARROW_L_, 0.5, 0.5);
	glRotatef(90, 0, 1, 0);
	gluCylinder(gluAxesObj_1, 1.0, 1.0, 1.0, 15, 15);
	glPopMatrix();
	glPushMatrix();
	glTranslatef(_ARROW_L_, 0, 0);
	glRotatef(-90, 0, 1, 0);
	gluDisk(gluAxesObj_1, 0.5, 1.5, 15, 15);
	glTranslatef(0, 0, -2);
	gluCylinder(gluAxesObj_1, 0.0, 1.5, 2.0, 15, 15);
	glPopMatrix();
/* **************************************************************************************************************************** */
}
예제 #14
0
/**
 * Draw quad with fragment shader that compares fragment.z against the
 * depth texture value (draw on left side of window).
 * We draw on the left side of the window to easily convert gl_FragCoord
 * into a texture coordinate.
 */
static void
draw_sphere_with_fragment_shader_compare(void)
{
   glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);

   glViewport(0 * SIZE, 0, SIZE, SIZE);

   glMatrixMode(GL_MODELVIEW);
   glLoadIdentity();
   glMatrixMode(GL_PROJECTION);
   glLoadIdentity();
   glOrtho(-1.0, 1.0, -1.0, 1.0, -1, 1.0);

   glBindTexture(TexTarget, DepthTex);

   piglit_UseProgram(ShaderProg);

   glEnable(GL_DEPTH_TEST);

   if (1) {
      draw_sphere();
   }
   else {
      /* To test using gl_TexCoord[0].xy instead of gl_FragCoord.xy in the shader
       */
      static const GLfloat sPlane[4] = {0.5, 0, 0, 0.5};
      static const GLfloat tPlane[4] = {0, 0.5, 0, 0.5};

      glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR);
      glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR);
      glTexGenfv(GL_S, GL_EYE_PLANE, sPlane);
      glTexGenfv(GL_T, GL_EYE_PLANE, tPlane);
      glEnable(GL_TEXTURE_GEN_S);
      glEnable(GL_TEXTURE_GEN_T);
      
      draw_sphere();

      glDisable(GL_TEXTURE_GEN_S);
      glDisable(GL_TEXTURE_GEN_T);
   }

   glDisable(GL_DEPTH_TEST);

   piglit_UseProgram(0);

#if DEBUG
   {
      GLfloat *z = read_float_z_image(0, 0);
      GLfloat min, max, center;

      find_float_min_max_center(z, SIZE * SIZE, &min, &max, &center);
      printf("rendered  min %f  max %f  center %f\n", min, max, center);

      free(z);
   }
   {
      GLuint *z = read_uint_z_image(0, 0);
      GLuint min, max, center;

      find_uint_min_max_center(z, SIZE * SIZE, &min, &max, &center);
      printf("rendered  min 0x%x  max 0x%x  center 0x%x\n", min, max, center);

      free(z);
   }
#endif /* DEBUG */
}
예제 #15
0
// OpenGL2 Render function.
// (this used to be set in io.RenderDrawListsFn and called by ImGui::Render(), but you can now call this directly from your main loop)
// Note that this implementation is little overcomplicated because we are saving/setting up/restoring every OpenGL state explicitly, in order to be able to run within any OpenGL engine that doesn't do so. 
void ImGui_ImplSdlGL2_RenderDrawData(ImDrawData* draw_data)
{
    // Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates)
    ImGuiIO& io = ImGui::GetIO();
    int fb_width = (int)(io.DisplaySize.x * io.DisplayFramebufferScale.x);
    int fb_height = (int)(io.DisplaySize.y * io.DisplayFramebufferScale.y);
    if (fb_width == 0 || fb_height == 0)
        return;
    draw_data->ScaleClipRects(io.DisplayFramebufferScale);

    // We are using the OpenGL fixed pipeline to make the example code simpler to read!
    // Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled, vertex/texcoord/color pointers, polygon fill.
    GLint last_texture; glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture);
    GLint last_polygon_mode[2]; glGetIntegerv(GL_POLYGON_MODE, last_polygon_mode);
    GLint last_viewport[4]; glGetIntegerv(GL_VIEWPORT, last_viewport);
    GLint last_scissor_box[4]; glGetIntegerv(GL_SCISSOR_BOX, last_scissor_box); 
    glPushAttrib(GL_ENABLE_BIT | GL_COLOR_BUFFER_BIT | GL_TRANSFORM_BIT);
    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    glDisable(GL_CULL_FACE);
    glDisable(GL_DEPTH_TEST);
    glEnable(GL_SCISSOR_TEST);
    glEnableClientState(GL_VERTEX_ARRAY);
    glEnableClientState(GL_TEXTURE_COORD_ARRAY);
    glEnableClientState(GL_COLOR_ARRAY);
    glEnable(GL_TEXTURE_2D);
    glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
    //glUseProgram(0); // You may want this if using this code in an OpenGL 3+ context where shaders may be bound

    // Setup viewport, orthographic projection matrix
    glViewport(0, 0, (GLsizei)fb_width, (GLsizei)fb_height);
    glMatrixMode(GL_PROJECTION);
    glPushMatrix();
    glLoadIdentity();
    glOrtho(0.0f, io.DisplaySize.x, io.DisplaySize.y, 0.0f, -1.0f, +1.0f);
    glMatrixMode(GL_MODELVIEW);
    glPushMatrix();
    glLoadIdentity();

    // Render command lists
    for (int n = 0; n < draw_data->CmdListsCount; n++)
    {
        const ImDrawList* cmd_list = draw_data->CmdLists[n];
        const ImDrawVert* vtx_buffer = cmd_list->VtxBuffer.Data;
        const ImDrawIdx* idx_buffer = cmd_list->IdxBuffer.Data;
        glVertexPointer(2, GL_FLOAT, sizeof(ImDrawVert), (const GLvoid*)((const char*)vtx_buffer + IM_OFFSETOF(ImDrawVert, pos)));
        glTexCoordPointer(2, GL_FLOAT, sizeof(ImDrawVert), (const GLvoid*)((const char*)vtx_buffer + IM_OFFSETOF(ImDrawVert, uv)));
        glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(ImDrawVert), (const GLvoid*)((const char*)vtx_buffer + IM_OFFSETOF(ImDrawVert, col)));

        for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
        {
            const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
            if (pcmd->UserCallback)
            {
                pcmd->UserCallback(cmd_list, pcmd);
            }
            else
            {
                glBindTexture(GL_TEXTURE_2D, (GLuint)(intptr_t)pcmd->TextureId);
                glScissor((int)pcmd->ClipRect.x, (int)(fb_height - pcmd->ClipRect.w), (int)(pcmd->ClipRect.z - pcmd->ClipRect.x), (int)(pcmd->ClipRect.w - pcmd->ClipRect.y));
                glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer);
            }
            idx_buffer += pcmd->ElemCount;
        }
    }

    // Restore modified state
    glDisableClientState(GL_COLOR_ARRAY);
    glDisableClientState(GL_TEXTURE_COORD_ARRAY);
    glDisableClientState(GL_VERTEX_ARRAY);
    glBindTexture(GL_TEXTURE_2D, (GLuint)last_texture);
    glMatrixMode(GL_MODELVIEW);
    glPopMatrix();
    glMatrixMode(GL_PROJECTION);
    glPopMatrix();
    glPopAttrib();
    glPolygonMode(GL_FRONT, (GLenum)last_polygon_mode[0]); glPolygonMode(GL_BACK, (GLenum)last_polygon_mode[1]);
    glViewport(last_viewport[0], last_viewport[1], (GLsizei)last_viewport[2], (GLsizei)last_viewport[3]);
    glScissor(last_scissor_box[0], last_scissor_box[1], (GLsizei)last_scissor_box[2], (GLsizei)last_scissor_box[3]);
}
예제 #16
0
파일: render.c 프로젝트: kz04px/Bot_Project
void render_main(void* a)
{
  char String[256];
  char Temp[128];
  EnableOpenGL(main_display.hWnd, &main_display.hDC, &main_display.hRC);
  glClearColor(0.0, 0.0, 0.0, 0.0); // Black
  glViewport(0, 0, main_display.w, main_display.h);

  while(!main_display.quit)
  {
    glViewport(0, 0, main_display.w, main_display.h);
    glClear(GL_COLOR_BUFFER_BIT);

    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

    glOrtho(-1.0/main_display.view_zoom, 1.0/main_display.view_zoom,
        -main_display.r/main_display.view_zoom, main_display.r/main_display.view_zoom,
        -1, 1);
    glTranslatef(-main_display.view_X, -main_display.view_Y, 1.0);

    draw_Background(main_display.world);
    draw_pellets(main_display.world);
    draw_bots(main_display.world);
    draw_edge_bots(viewer_display.world);

    SwapBuffers(main_display.hDC);

    static int count = 0;
    if(main_display.display_statistics && count%30 == 0)
    {
      sprintf(String, " Generation: %i\r\n", main_display.world->generation);
      sprintf(Temp, " Frame: %i\r\n", main_display.world->frame);
      strcat(String, Temp);
      sprintf(Temp, " World width: %i\r\n", main_display.world->width);
      strcat(String, Temp);
      sprintf(Temp, " World height: %i\r\n", main_display.world->height);
      strcat(String, Temp);
      sprintf(Temp, " Average fitness: %i\r\n\r\n", main_display.world->average_fitness);
      strcat(String, Temp);

      sprintf(Temp, " Bots: %i\r\n", main_display.world->num_bots);
      strcat(String, Temp);
      sprintf(Temp, " Most bots: %i\r\n", main_display.world->bots_most);
      strcat(String, Temp);
      sprintf(Temp, " Max bots: %i\r\n", main_display.world->max_bots);
      strcat(String, Temp);
      sprintf(Temp, " Bots added: %i\r\n", main_display.world->bots_added);
      strcat(String, Temp);
      sprintf(Temp, " Bots removed: %i\r\n\r\n", main_display.world->bots_removed);
      strcat(String, Temp);

      sprintf(Temp, " Pellets: %i\r\n", main_display.world->num_pellets);
      strcat(String, Temp);
      sprintf(Temp, " Max pellets: %i\r\n", main_display.world->max_pellets);
      strcat(String, Temp);
      SetWindowText(main_display.hstatistics, String);
    }
    count++;
    Sleep(20);
  }
  DisableOpenGL(main_display.hWnd, main_display.hDC, main_display.hRC);
}
예제 #17
0
파일: main.cpp 프로젝트: JoaoS/CG
void display(void)
{
	if (noite)
		glClearColor(GRAY1);
	else
		glClearColor(GRAY2);
	
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
    if(end_game == 0)
	{
        //================================================================= Viewport1
        glViewport (0, hScreen/4, wScreen/4, hScreen/4);
        glMatrixMode(GL_PROJECTION);
        glLoadIdentity();
        glOrtho (-xC,xC, -xC,xC, -zC,zC);
        glMatrixMode(GL_MODELVIEW);
        glLoadIdentity();	
        gluLookAt( 0, 10,0, 0,0,0, 0, 0, -1);
	   //--------------------- Informacao
        sprintf(texto,"Nivel : %d",level+1);
        desenhaTexto(texto,-8,1,0,18);
        if(clock_active ==1)
        {    
            t2 = clock() - t1;
            sprintf(texto,"Tempo : %.2f",((float)t2)/CLOCKS_PER_SEC);
            desenhaTexto(texto,-8,1,4,12);
        }
        if(noite)
            strcpy(texto, "Noite : Activo\n");
        else
            strcpy(texto, "Noite : Inactivo\n");
        desenhaTexto(texto,-8,1,8,12);
        if(ligaLuz)
            strcpy(texto, "Luz tecto : Activo\n");
        else
            strcpy(texto, "Luz tecto : Inactivo\n");
        desenhaTexto(texto,-8,1,12,12);
        if(ligaFoco)
            strcpy(texto, "Luz foco : Activo\n");
        else
            strcpy(texto, "Luz foco : Inactivo\n");
        desenhaTexto(texto,-8,1,16,12);

	   //================================================================= Viewport2
	   glEnable(GL_LIGHTING);  
	   glViewport (wScreen/4, hScreen/4, 0.75*wScreen, 0.75*hScreen);
	   glMatrixMode(GL_PROJECTION);
	   glLoadIdentity();
	   gluPerspective(99.0, wScreen/hScreen, 0.1, 100.0);
	   glMatrixMode(GL_MODELVIEW);
	   glLoadIdentity();
	   gluLookAt(obsPini[0], obsPini[1], obsPini[2], obsPfin[0], obsPfin[1], obsPfin[2], 0, 1, 0);
	   /* desenha objectos */
	   iluminacao();
	   drawScene();
       glutSwapBuffers();
    }
    else
    {   
        glViewport (0, 0, wScreen, hScreen);
        glMatrixMode(GL_PROJECTION);
        glLoadIdentity();
        glOrtho (-xC,xC, -xC,xC, -zC,zC);
        glMatrixMode(GL_MODELVIEW);
        glLoadIdentity();   
        gluLookAt( 0, 10,0, 0,0,0, 0, 0, -1);
        strcpy(texto,"FIM");
        desenhaTexto(texto,0,0,-8,24);
        sprintf(texto,"Tempo Nivel 1 : %.2f",((float)level_time[0])/CLOCKS_PER_SEC);
        desenhaTexto(texto,-8,0,-4,24);
        sprintf(texto,"Tempo Nivel 2 : %.2f",((float)level_time[1])/CLOCKS_PER_SEC);
        desenhaTexto(texto,-8,0,0,24);
        sprintf(texto,"Tempo Nivel 3 : %.2f",((float)level_time[2])/CLOCKS_PER_SEC);
        desenhaTexto(texto,-8,0,4,24);
        strcpy(texto,"Pressione ESC para sair");
        desenhaTexto(texto,-4,0,8,24);
        glutSwapBuffers();
    }
}
예제 #18
0
파일: render.c 프로젝트: kz04px/Bot_Project
void render_viewer(void* a)
{
  char String[256];
  char Temp[128];
  EnableOpenGL(viewer_display.hWnd, &viewer_display.hDC, &viewer_display.hRC);
  glClearColor(0.0, 0.0, 0.0, 0.0); // Black

  while(!viewer_display.quit)
  {
    if(viewer_display.display)
    {
      glViewport(0, 0, viewer_display.w, viewer_display.h);
      glClear(GL_COLOR_BUFFER_BIT);
      glMatrixMode(GL_MODELVIEW);
      glLoadIdentity();

      // draw viewing area
      if(viewer_display.world->selected >= 0)
      {
        glOrtho(-1.0/viewer_display.view_zoom, 1.0/viewer_display.view_zoom,
            -viewer_display.r/viewer_display.view_zoom, viewer_display.r/viewer_display.view_zoom,
            -1, 1);
        glTranslatef(-viewer_display.world->bots[viewer_display.world->selected].x, -viewer_display.world->bots[viewer_display.world->selected].y, 1.0);

        draw_Background(viewer_display.world);
        draw_pellets(viewer_display.world);
        draw_bots(viewer_display.world);
        glPopMatrix();

        static int count = 0;
        if(viewer_display.display_statistics && count%30 == 0)
        {
          int i;
          // display inputs
          sprintf(String, " Brain inputs:\r\n");
          for(i = 0; i < viewer_display.world->bots[viewer_display.world->selected].nn.layer_sizes[0]; ++i)
          {
            sprintf(Temp, "  %i: %.4g\r\n", i, viewer_display.world->bots[viewer_display.world->selected].nn.input[0][i]);
            strcat(String, Temp);
          }
          // display outputs
          sprintf(Temp, " Brain outputs:\r\n");
          strcat(String, Temp);
          for(i = 0; i < viewer_display.world->bots[viewer_display.world->selected].nn.layer_sizes[2]; ++i)
          {
            sprintf(Temp, "  %i: %.4g\r\n", i, viewer_display.world->bots[viewer_display.world->selected].nn.output[2][i]);
            strcat(String, Temp);
          }
          /*
          sprintf(String, " s_bot: %i\r\n", viewer_display.world->selected);
          sprintf(Temp, " age: %i\r\n", viewer_display.world->bots[viewer_display.world->selected].age);
          strcat(String, Temp);
          sprintf(Temp, " energy: %i\r\n", viewer_display.world->bots[viewer_display.world->selected].energy);
          strcat(String, Temp);
          sprintf(Temp, " dead: %i\r\n", viewer_display.world->bots[viewer_display.world->selected].dead);
          strcat(String, Temp);

          // position & rotation
          sprintf(Temp, " x: %i\r\n", (int)viewer_display.world->bots[viewer_display.world->selected].x);
          strcat(String, Temp);
          sprintf(Temp, " y: %i\r\n", (int)viewer_display.world->bots[viewer_display.world->selected].y);
          strcat(String, Temp);
          sprintf(Temp, " r: %i\r\n", (int)viewer_display.world->bots[viewer_display.world->selected].r);
          strcat(String, Temp);

          // eyes
          sprintf(Temp, " eyes: %i\r\n", viewer_display.world->bots[viewer_display.world->selected].num_eyes);
          strcat(String, Temp);
          sprintf(Temp, "  %.4g %.4g %.4g %.4g\r\n", viewer_display.world->bots[viewer_display.world->selected].eyes[0].in_strength,
                                                     viewer_display.world->bots[viewer_display.world->selected].eyes[0].in_red,
                                                     viewer_display.world->bots[viewer_display.world->selected].eyes[0].in_green,
                                                     viewer_display.world->bots[viewer_display.world->selected].eyes[0].in_blue);
          strcat(String, Temp);
          sprintf(Temp, "  %.4g %.4g %.4g %.4g\r\n", viewer_display.world->bots[viewer_display.world->selected].eyes[1].in_strength,
                                                     viewer_display.world->bots[viewer_display.world->selected].eyes[1].in_red,
                                                     viewer_display.world->bots[viewer_display.world->selected].eyes[1].in_green,
                                                     viewer_display.world->bots[viewer_display.world->selected].eyes[1].in_blue);
          strcat(String, Temp);
          sprintf(Temp, "  %.4g %.4g %.4g %.4g\r\n", viewer_display.world->bots[viewer_display.world->selected].eyes[2].in_strength,
                                                     viewer_display.world->bots[viewer_display.world->selected].eyes[2].in_red,
                                                     viewer_display.world->bots[viewer_display.world->selected].eyes[2].in_green,
                                                     viewer_display.world->bots[viewer_display.world->selected].eyes[2].in_blue);
          strcat(String, Temp);

          // Body colour
          sprintf(Temp, " Colour:\r\n");
          strcat(String, Temp);
          sprintf(Temp, "  %.4g\r\n", viewer_display.world->bots[viewer_display.world->selected].red);
          strcat(String, Temp);
          sprintf(Temp, "  %.4g\r\n", viewer_display.world->bots[viewer_display.world->selected].green);
          strcat(String, Temp);
          sprintf(Temp, "  %.4g\r\n", viewer_display.world->bots[viewer_display.world->selected].blue);
          strcat(String, Temp);
          */

          SetWindowText(viewer_display.hstatistics, String);
        }
        count++;
      }
      SwapBuffers(viewer_display.hDC);
    }
    Sleep(20);
  }
  DisableOpenGL(viewer_display.hWnd, viewer_display.hDC, viewer_display.hRC);
}
예제 #19
0
파일: gl-main.c 프로젝트: n1tehawk/mupdf
static void run_main_loop(void)
{
	glViewport(0, 0, window_w, window_h);
	glClearColor(0.3f, 0.3f, 0.3f, 1.0f);
	glClear(GL_COLOR_BUFFER_BIT);

	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	glOrtho(0, window_w, window_h, 0, -1, 1);

	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();

	ui_begin();

	if (search_active)
	{
		float start_time = glfwGetTime();

		if (ui.key == KEY_ESCAPE)
			search_active = 0;

		/* ignore events during search */
		ui.key = ui.mod = 0;
		ui.down = ui.middle = ui.right = 0;

		while (glfwGetTime() < start_time + 0.2)
		{
			search_hit_count = fz_search_page_number(ctx, doc, search_page, search_needle,
					search_hit_bbox, nelem(search_hit_bbox));
			if (search_hit_count)
			{
				search_active = 0;
				search_hit_page = search_page;
				jump_to_page(search_hit_page);
				break;
			}
			else
			{
				search_page += search_dir;
				if (search_page < 0 || search_page == fz_count_pages(ctx, doc))
				{
					search_active = 0;
					break;
				}
			}
		}

		/* keep searching later */
		if (search_active)
			ui_needs_update = 1;
	}

	do_app();

	canvas_w = window_w - canvas_x;
	canvas_h = window_h - canvas_y;

	do_canvas();

	if (showinfo)
		do_info();

	if (showoutline)
		do_outline(outline, canvas_x);

	if (showsearch)
	{
		int state = ui_input(canvas_x, 0, canvas_x + canvas_w, ui.lineheight+4, &search_input);
		if (state == -1)
		{
			ui.focus = NULL;
			showsearch = 0;
		}
		else if (state == 1)
		{
			ui.focus = NULL;
			showsearch = 0;
			search_page = -1;
			if (search_needle)
			{
				fz_free(ctx, search_needle);
				search_needle = NULL;
			}
			if (search_input.end > search_input.text)
			{
				search_needle = fz_strdup(ctx, search_input.text);
				search_active = 1;
				search_page = currentpage;
			}
		}
		ui_needs_update = 1;
	}

	if (search_active)
	{
		char buf[256];
		sprintf(buf, "Searching page %d of %d.", search_page + 1, fz_count_pages(ctx, doc));
		ui_label_draw(canvas_x, 0, canvas_x + canvas_w, ui.lineheight+4, buf);
	}

	ui_end();

	glfwSwapBuffers(window);

	ogl_assert(ctx, "swap buffers");
}
예제 #20
0
//////////////////////////////////////////////////////////////////////////
// 游戏结束
void CGameCore::GameOver( DWORD inc )
{

	//////////////////////////////////////////////////////////////////////////
	// 单人模式
	if (1 == g_MenuStateMain)
	{
		// 计算得分
		TTscore = timeFlash*100+300.0*excellentNum;

		// 记录高分
		switch(g_MenuStateSub)
		{
		case 1:		// 常规游戏
			if (timeFlash > HIGHtime[g_MenuStateSub])
			{
				HIGHtime[g_MenuStateSub] = timeFlash;
			}
			if (excellentNum > HIGHexce[g_MenuStateSub])
			{
				HIGHexce[g_MenuStateSub] = excellentNum;
			}
			if (TTscore > HIGHscore[g_MenuStateSub])
			{
				HIGHscore[g_MenuStateSub] = TTscore;
			}
			break;
		case 2:		// 高速模式
			if (timeFlash > HIGHtime[g_MenuStateSub])
			{
				HIGHtime[g_MenuStateSub] = timeFlash;
			}
			if (excellentNum > HIGHexce[g_MenuStateSub])
			{
				HIGHexce[g_MenuStateSub] = excellentNum;
			}
			if (TTscore > HIGHscore[g_MenuStateSub])
			{
				HIGHscore[g_MenuStateSub] = TTscore;
			}
			break;
		case 3:		// 多弹模式
			if (timeFlash > HIGHtime[g_MenuStateSub])
			{
				HIGHtime[g_MenuStateSub] = timeFlash;
			}
			if (excellentNum > HIGHexce[g_MenuStateSub])
			{
				HIGHexce[g_MenuStateSub] = excellentNum;
			}
			if (TTscore > HIGHscore[g_MenuStateSub])
			{
				HIGHscore[g_MenuStateSub] = TTscore;
			}
			break;
		}

		glColor3f(1,1,1);
		// 画出游戏模式
		g_myModel.TextureSquareTGA(0,5,0,6,2,g_MenuStateSub+5);
		// 按回车开始游戏
		g_myModel.TextureSquareTGA(0,1.5,0,9,1,20);
		// 时间
		g_myModel.TextureSquareTGA(-2.2,-1.5,0,1.3,0.7,21);
		// 绝妙
		g_myModel.TextureSquareTGA(0.5,-1.5,0,1.3,0.7,22);
		// 得分
		g_myModel.TextureSquareTGA(3.0,-1.5,0,1.3,0.7,23);
		// 本次
		g_myModel.TextureSquareTGA(-4.5,-2.65,0,1.3,0.7,24);

		if (g_MenuStateSub != 4 && g_MenuStateSub != 5)
		{
			// 最高
			g_myModel.TextureSquareTGA(-4.5,-3.9,0,1.3,0.7,26);
		}

		glMatrixMode(GL_PROJECTION);	

		glPushMatrix();								
		glLoadIdentity();						
		glOrtho(0,g_Width,0,g_Height,-1,1);				// 设置为正投影
		glMatrixMode(GL_MODELVIEW);						

		glColor3f(0.0,1.0,0.0);
		// 当前时间
		g_myModel.glPrint(g_Width*300/800, g_Height*190/600,"%.2f",timeFlash);
		// 当前绝妙
		g_myModel.glPrint(g_Width*410/800, g_Height*190/600,"%d",excellentNum);
		// 当前总分
		g_myModel.glPrint(g_Width*490/800, g_Height*190/600,"%d",TTscore);
		// 低难度模式没有记录
		if (g_MenuStateSub != 4 && g_MenuStateSub != 5)
		{
			// 最高时间
			g_myModel.glPrint(g_Width*300/800, g_Height*140/600,"%.2f",HIGHtime[g_MenuStateSub]);
			// 最高绝妙
			g_myModel.glPrint(g_Width*410/800, g_Height*140/600,"%d",HIGHexce[g_MenuStateSub]);
			// 最高总分
			g_myModel.glPrint(g_Width*490/800, g_Height*140/600,"%d",HIGHscore[g_MenuStateSub]);
		}

		glMatrixMode(GL_PROJECTION);
		glPopMatrix();
		glMatrixMode(GL_MODELVIEW);
	}

	//////////////////////////////////////////////////////////////////////////
	// 双人游戏
	if (2 == g_MenuStateMain)
	{
		// 画出游戏模式
		g_myModel.TextureSquareTGA(0,6,0,6,2,g_MenuStateSub+10);
		// 按回车开始游戏
		g_myModel.TextureSquareTGA(0,-2.5,0,8,0.7,20);
		// 时间
		g_myModel.TextureSquareTGA(-0.5,-4.5,0,1.3,0.7,21);
		// 绝妙 玩家1
		g_myModel.TextureSquareTGA(-6,-3.5,0,1.3,0.7,22);
		// 绝妙 玩家2
		g_myModel.TextureSquareTGA(6,-3.5,0,1.3,0.7,22);

		switch(win)
		{
		case 0:
			// 平局
			g_myModel.TextureSquareTGA( 6, 2, 0, 5.5, 5.5, 29);
			g_myModel.TextureSquareTGA(-6, 2, 0, 5.5, 5.5, 29);
			break;
		case 1:
			// 玩家1 胜
			g_myModel.TextureSquareTGA(-6, 2, 0, 5.5, 5.5, 28);
			g_myModel.TextureSquareTGA( 6, 2, 0, 5.5, 5.5, 27);
			break;
		case 2:
			// 玩家2 胜
			g_myModel.TextureSquareTGA(-6, 2, 0, 5.5, 5.5, 27);
			g_myModel.TextureSquareTGA( 6, 2, 0, 5.5, 5.5, 28);
			break;
		}
	}
	

	// 开始游戏
	if ( KEY_UP(13) || KEY_UP(32) )
	{
		gameOver = false;
		InitGame();
	}
	// 返回上级菜单
	if (KEY_UP(27))
	{
		g_GameState = 1;
		initGame = false;
	}
}
예제 #21
0
void EDA_3D_CANVAS::generateFakeShadowsTextures( REPORTER* aErrorMessages, REPORTER* aActivity )
{
    if( m_shadow_init == true )
    {
        return;
    }

    // Init info 3d parameters and create gl lists:
    CreateDrawGL_List( aErrorMessages, aActivity );

    DBG( unsigned strtime = GetRunningMicroSecs() );

    m_shadow_init = true;

    glClearColor( 0, 0, 0, 1 );

    glMatrixMode( GL_PROJECTION );
    glLoadIdentity();

    const float zDistMax = Millimeter2iu( 3.5 ) * GetPrm3DVisu().m_BiuTo3Dunits;

    glOrtho( -GetPrm3DVisu().m_BoardSize.x * GetPrm3DVisu().m_BiuTo3Dunits / 2.0f,
             GetPrm3DVisu().m_BoardSize.x * GetPrm3DVisu().m_BiuTo3Dunits / 2.0f,
             -GetPrm3DVisu().m_BoardSize.y * GetPrm3DVisu().m_BiuTo3Dunits / 2.0f,
             GetPrm3DVisu().m_BoardSize.y * GetPrm3DVisu().m_BiuTo3Dunits / 2.0f,
             0.0, zDistMax );

    float zpos = GetPrm3DVisu().GetLayerZcoordBIU( F_Paste ) * GetPrm3DVisu().m_BiuTo3Dunits;

    // Render FRONT shadow
    glMatrixMode( GL_MODELVIEW );
    glLoadIdentity();
    glTranslatef( 0.0f, 0.0f, zpos );
    glRotatef( 180.0f, 0.0f, 1.0f, 0.0f );

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

    create_and_render_shadow_buffer( &m_text_fake_shadow_front, 512, false, 1 );

    zpos = GetPrm3DVisu().GetLayerZcoordBIU( B_Paste ) * GetPrm3DVisu().m_BiuTo3Dunits;

    // Render BACK shadow
    glMatrixMode( GL_MODELVIEW );
    glLoadIdentity();
    glTranslatef( 0.0f, 0.0f, fabs( zpos ) );


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

    create_and_render_shadow_buffer( &m_text_fake_shadow_back, 512, false, 1 );


    // Render ALL BOARD shadow
    glMatrixMode( GL_PROJECTION );
    glLoadIdentity();

    // Normalization scale to convert bouding box
    // to normalize 3D units between -1.0 and +1.0

    S3D_VERTEX v = m_fastAABBox_Shadow.Max() - m_fastAABBox_Shadow.Min();
    float BoundingBoxBoardiuTo3Dunits = 2.0f / glm::max( v.x, v.y );

    //float zDistance = (m_lightPos.z * zDistMax) / sqrt( (m_lightPos.z - m_fastAABBox_Shadow.Min().z) );
    float zDistance = (m_lightPos.z - m_fastAABBox_Shadow.Min().z) / 3.0f;

    glOrtho( -v.x * BoundingBoxBoardiuTo3Dunits / 2.0f,
              v.x * BoundingBoxBoardiuTo3Dunits / 2.0f,
             -v.y * BoundingBoxBoardiuTo3Dunits / 2.0f,
              v.y * BoundingBoxBoardiuTo3Dunits / 2.0f,
             0.0f, zDistance );

    glMatrixMode( GL_MODELVIEW );
    glLoadIdentity();

    // fits the bouding box to scale this size
    glScalef( BoundingBoxBoardiuTo3Dunits, BoundingBoxBoardiuTo3Dunits, 1.0f );

    // Place the eye in the lowerpoint of boudingbox and turn arround and look up to the model
    glTranslatef( 0.0f, 0.0f, m_fastAABBox_Shadow.Min().z );
    glRotatef( 180.0, 0.0f, 1.0f, 0.0f );

    // move the bouding box in order to draw it with its center at 0,0 3D coordinates
    glTranslatef( -(m_fastAABBox_Shadow.Min().x + v.x / 2.0f), -(m_fastAABBox_Shadow.Min().y + v.y / 2.0f), 0.0f );

    create_and_render_shadow_buffer( &m_text_fake_shadow_board, 512, true, 10 );

    DBG( printf( "  generateFakeShadowsTextures total time %f ms\n", (double) (GetRunningMicroSecs() - strtime) / 1000.0 ) );
}
예제 #22
0
void updateCamera() {

	float m_ele = 0;
	float m_azi=0;

	btVector3 m_cameraPosition(12,20,12);
	btVector3 m_cameraTargetPosition(0,10,0);

	btVector3 m_cameraUp(0,1,0);
	int m_forwardAxis=2;
	btScalar m_cameraDistance = 130;

	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();


	float m_frustumZNear=1;
	float m_frustumZFar=1000;

	if (m_glutScreenWidth == 0 && m_glutScreenHeight == 0)
		return;

	float aspect;
	btVector3 extents;

	if (m_glutScreenWidth > m_glutScreenHeight) 
	{
		aspect = m_glutScreenWidth / (float)m_glutScreenHeight;
		extents.setValue(aspect * 1.0f, 1.0f,0);
	} else 
	{
		aspect = m_glutScreenHeight / (float)m_glutScreenWidth;
		extents.setValue(1.0f, aspect*1.f,0);
	}


	if (m_ortho)
	{
		// reset matrix
		glLoadIdentity();
		extents *= m_cameraDistance;
		btVector3 lower = m_cameraTargetPosition - extents;
		btVector3 upper = m_cameraTargetPosition + extents;
		glOrtho(lower.getX(), upper.getX(), lower.getY(), upper.getY(),-1000,1000);

		glMatrixMode(GL_MODELVIEW);
		glLoadIdentity();
	} else
	{
		if (m_glutScreenWidth > m_glutScreenHeight) 
		{
			glFrustum (-aspect * m_frustumZNear, aspect * m_frustumZNear, -m_frustumZNear, m_frustumZNear, m_frustumZNear, m_frustumZFar);
		} else 
		{
			glFrustum (-aspect * m_frustumZNear, aspect * m_frustumZNear, -m_frustumZNear, m_frustumZNear, m_frustumZNear, m_frustumZFar);
		}
		glMatrixMode(GL_MODELVIEW);
		glLoadIdentity();
		gluLookAt(m_cameraPosition[0], m_cameraPosition[1], m_cameraPosition[2], 
			m_cameraTargetPosition[0], m_cameraTargetPosition[1], m_cameraTargetPosition[2], 
			m_cameraUp.getX(),m_cameraUp.getY(),m_cameraUp.getZ());
	}

}
예제 #23
0
파일: sketcher.cpp 프로젝트: pmindek/csl
void Sketcher::renderSelection(QGLShaderProgram *shader, Selection *selection)
{
	glPushAttrib(GL_ALL_ATTRIB_BITS);
	glPushClientAttrib(GL_CLIENT_ALL_ATTRIB_BITS);

	selection->getSelectionMask()->bind();

	glMatrixMode(GL_MODELVIEW);
	glPushMatrix();
	glViewport(0, 0, selection->getSelectionMask()->size().width(), selection->getSelectionMask()->size().height());


	glMatrixMode(GL_PROJECTION);
	glPushMatrix();
	glLoadIdentity();
	glOrtho(-1.0, +1.0, -1.0, +1.0, -1.0, +1.0);
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();

	glClearColor(0.0, 1.0, 0.0, 1.0);
	glClear(GL_COLOR_BUFFER_BIT);

	shader->bind();
	shader->setUniformValue("texture", textureIndex);

	//glActiveTexture(GL_TEXTURE3);
	this->createSelectionTexture(selection);
	//glActiveTexture(GL_TEXTURE0);

	glDisable(GL_TEXTURE_2D);

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

	glEnable(GL_COLOR_MATERIAL);
	glColor4f(1.0, 0.0, 1.0, 1.0);
	glBegin(GL_QUADS);
		glVertex2f( 1.0, -1.0);
		glVertex2f(-1.0, -1.0);
		glVertex2f(-1.0,  1.0);
		glVertex2f( 1.0,  1.0);
	glEnd();
	glEnable(GL_COLOR_MATERIAL);

	shader->release();

	selection->getSelectionMask()->release();

	/*QImage p = selection->getSelectionMask()->toImage();
	p.save("c:/users/mindek/documents/a.png");*/

	selection->setRendered();


	glMatrixMode(GL_PROJECTION);
	glPopMatrix();
	glMatrixMode(GL_MODELVIEW);
	glPopMatrix();

	glPopClientAttrib();
	glPopAttrib();

	emit selectionRendered();
}
예제 #24
0
void gluOrtho2D(float left, float right, float bottom, float top) {
    glOrtho(left, right, bottom, top, -1.0, 1.0);
}
예제 #25
0
void TerrainQuadtree::generateTextures() {
	// prepare viewport and projection
	//glDisable(GL_DEPTH_TEST);

	// do not setup the proj more than once
	if (this->parent == NULL) {
		glViewport(0, 0, this->textureSize, this->textureSize);
		glMatrixMode(GL_PROJECTION);
		glPolygonMode(GL_FRONT, GL_FILL);
		glLoadIdentity();
		glOrtho(0.0, (double)this->textureSize, 0.0, (double)this->textureSize, 0.0, 1.0);
		glMatrixMode(GL_MODELVIEW);
		glLoadIdentity();
		glTranslated(0.0, 0.0, -1.0);

		generationScreenList = glGenLists(1);
		glNewList(generationScreenList, GL_COMPILE);
		glBegin(GL_QUADS);
		glTexCoord2f(0.0, 0.0);
		glVertex3f(0.0, 0.0, 0.0);
		glTexCoord2f(1.0, 0.0);
		glVertex3f(this->textureSize, 0.0, 0.0);
		glTexCoord2f(1.0, 1.0);
		glVertex3f(this->textureSize, this->textureSize, 0.0);
		glTexCoord2f(0.0, 1.0);
		glVertex3f(0.0, this->textureSize, 0.0);
		glEnd();
		glEndList();
	}

	// generate topography
	glBindFramebuffer(GL_FRAMEBUFFER, this->framebuffer);
	glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, this->topoTexture->id, 0);
	this->positionTexture->bind(GL_TEXTURE0);

	this->generatorShader->bind();
	glUniform1i(glGetUniformLocation(this->generatorShader->program, "positionTexture"), 0);
	glCallList(generationScreenList);
	this->generatorShader->unbind();
	//glBindFramebuffer(GL_FRAMEBUFFER, 0);

	// generate normals
	//glBindFramebuffer(GL_FRAMEBUFFER, this->framebuffer);
	glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, this->normalTexture->id, 0);
	this->topoTexture->bind(GL_TEXTURE1);

	this->generatorShaderN->bind();
	glUniform1f(glGetUniformLocation(this->generatorShaderN->program, "size"), (float)this->textureSize);
	glUniform1f(glGetUniformLocation(this->generatorShaderN->program, "radius"), this->planet->radius);
	glUniform1i(glGetUniformLocation(this->generatorShaderN->program, "topoTexture"), 1);
	glUniform1i(glGetUniformLocation(this->generatorShaderN->program, "positionTexture"), 0);
	glCallList(generationScreenList);
	this->generatorShaderN->unbind();
	//glBindFramebuffer(GL_FRAMEBUFFER, 0);

	// generate colors
	//glBindFramebuffer(GL_FRAMEBUFFER, this->framebuffer);
	glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, this->colorTexture->id, 0);
	this->generatorShaderC->bind();
	glUniform1i(glGetUniformLocation(this->generatorShaderC->program, "topoTexture"), 1);
	glCallList(generationScreenList);
	this->generatorShaderC->unbind();
	//glBindFramebuffer(GL_FRAMEBUFFER, 0);

	//glEnable(GL_DEPTH_TEST);
	this->ready = true;
}
예제 #26
0
void GLUTSimLightController::draw() {
  int w = glutGet(GLUT_WINDOW_WIDTH);
  int h = glutGet(GLUT_WINDOW_HEIGHT);
  float light_position[4] = {0.0, 0.0, -1.0, 0.0};

  glViewport(0, 0, w, h);

  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();
  gluPerspective(35, (double) w/h, 0.1, 100.0);

  glMatrixMode(GL_MODELVIEW);
  glLoadIdentity();

  glClearColor(0, 0, 0, 1);
  glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);

  glLightfv(GL_LIGHT0, GL_POSITION, light_position);

  glTranslatef(0, 0, -3);

  glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, 1);

  glEnable(GL_DEPTH_TEST);
  glEnable(GL_POINT_SMOOTH);

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

  glEnable(GL_LIGHT0);
  glEnable(GL_NORMALIZE);

  struct Light {
    float radius;
    float color[3];
    float position[2];
  } lights[4] = {
    { .2, {  0, 0,.8 }, { -.5, -.5 } },
    { .2, { .8, 0, 0 }, {  .5, -.5 } },
    { .2, {  0,.8, 0 }, {  .5,  .5 } },
    { .2, { .9,.9,.9 }, { -.5,  .5 } },
  };
  for (unsigned i = 0; i != 4; ++i) {
    Light &l = lights[i];

    if (lights_enabled[i]) {
      glColor3fv(l.color);
      draw_circle_filled(l.position[0], l.position[1], l.radius);
    }
  }

  // Draw the beat monitor.
  const double beat_monitor_dim_time = .05;
  double elapsed = get_elapsed_time_in_seconds();
  if (elapsed - last_beat_time <= beat_monitor_dim_time) {
    double v = 1 - (elapsed - last_beat_time) / beat_monitor_dim_time;
    glColor3f(v, v, v);
    glRectf(-.9, -.9, -.7, -.8);
  }

  // Draw the 2D overlays.
  glEnable(GL_BLEND);
  glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();
  glOrtho(0, w, 0, h, -1, 1);

  glMatrixMode(GL_MODELVIEW);
  glLoadIdentity();

  const int textHeight = 15;
  char buffer[256];
  int y = 0;
  sprintf(buffer, "Time: %.4fs\n", elapsed);
  glColor3f(1, 1, 1);
  glutDrawString(10, 10 + textHeight*y++, buffer);

  if (true) {
    num_frames++;
    double fps = num_frames / elapsed;
    sprintf(buffer, "FPS: %.4fs\n", fps);
    glColor3f(1, 1, 1);
    glutDrawString(10, 10 + textHeight*y++, buffer);
  }

  if (light_manager) {
    double bpm = light_manager->GetRecentBPM();
    sprintf(buffer, "BPM: %.4fs\n", bpm);
    glColor3f(1, 1, 1);
    glutDrawString(10, 10 + textHeight*y++, buffer);
  }

  if (light_manager) {
    sprintf(buffer, "Program: %s\n", light_manager->GetProgramName().c_str());
    glColor3f(1, 1, 1);
    glutDrawString(10, 10 + textHeight*y++, buffer);
  }

  if (light_manager) {
    sprintf(buffer, "Strobe Enabled: %s\n",
            light_manager->GetStrobeEnabled() ? "yes" : "no");
    glColor3f(1, 1, 1);
    glutDrawString(10, 10 + textHeight*y++, buffer);
  }

  glFlush();

  glutSwapBuffers();
}
예제 #27
0
static void
draw(void)
{
   static char frbuf[80] = "";

   dojoy();

   glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

   glEnable(GL_TEXTURE_2D);
   glEnable(GL_DEPTH_TEST);
   if (fog)
      glEnable(GL_FOG);
   else
      glDisable(GL_FOG);

   glPushMatrix();
   calcposobs();

   gluLookAt(obs[0], obs[1], obs[2],
	     obs[0] + dir[0], obs[1] + dir[1], obs[2] + dir[2],
	     0.0, 0.0, 1.0);

   drawbase();
   drawobj();

   glColor3f(1.0, 1.0, 1.0);
   glDisable(GL_TEXTURE_2D);

   glPushMatrix();
   glTranslatef(lightpos[0], lightpos[1], lightpos[2]);
   glCallList(lightdlist);
   glPopMatrix();

   glPopMatrix();

   glDisable(GL_DEPTH_TEST);
   glDisable(GL_FOG);

   glMatrixMode(GL_PROJECTION);
   glPushMatrix();
   glLoadIdentity();
   glOrtho(-0.5, 639.5, -0.5, 479.5, -1.0, 1.0);
   glMatrixMode(GL_MODELVIEW);

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

   if (showcheckmap) {
      glEnable(GL_TEXTURE_2D);
      glBindTexture(GL_TEXTURE_2D, checkid);
      glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);

      glBegin(GL_QUADS);
      glTexCoord2f(1.0f, 0.0f);
      glVertex2i(10, 30);
      glTexCoord2f(1.0f, 1.0f);
      glVertex2i(10 + 90, 30);
      glTexCoord2f(0.0f, 1.0f);
      glVertex2i(10 + 90, 30 + 90);
      glTexCoord2f(0.0f, 0.0f);
      glVertex2i(10, 30 + 90);
      glEnd();

      glDisable(GL_TEXTURE_2D);
      glBegin(GL_LINE_LOOP);
      glVertex2i(10, 30);
      glVertex2i(10 + 90, 30);
      glVertex2i(10 + 90, 30 + 90);
      glVertex2i(10, 30 + 90);
      glEnd();
      glRasterPos2i(105, 65);
      printstring(GLUT_BITMAP_HELVETICA_18, "Plane Texture Map");
   }

   if (showreflectmap) {
      glEnable(GL_TEXTURE_2D);
      glBindTexture(GL_TEXTURE_2D, reflectid);
      glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);

      glBegin(GL_QUADS);
      glTexCoord2f(1.0f, 0.0f);
      glVertex2i(540, 30);
      glTexCoord2f(1.0f, 1.0f);
      glVertex2i(540 + 90, 30);
      glTexCoord2f(0.0f, 1.0f);
      glVertex2i(540 + 90, 30 + 90);
      glTexCoord2f(0.0f, 0.0f);
      glVertex2i(540, 30 + 90);
      glEnd();

      glDisable(GL_TEXTURE_2D);
      glBegin(GL_LINE_LOOP);
      glVertex2i(540, 30);
      glVertex2i(540 + 90, 30);
      glVertex2i(540 + 90, 30 + 90);
      glVertex2i(540, 30 + 90);
      glEnd();
      glRasterPos2i(360, 65);
      printstring(GLUT_BITMAP_HELVETICA_18, "Sphere Texture Map");
   }

   glDisable(GL_TEXTURE_2D);

   glRasterPos2i(10, 10);
   printstring(GLUT_BITMAP_HELVETICA_18, frbuf);
   glRasterPos2i(360, 470);
   printstring(GLUT_BITMAP_HELVETICA_10,
	       "Ray V1.0 Written by David Bucciarelli ([email protected])");

   if (help)
      printhelp();

   glMatrixMode(GL_PROJECTION);
   glPopMatrix();
   glMatrixMode(GL_MODELVIEW);

   updatemaps();

   glutSwapBuffers();

   Frames++;
   {
      GLint t = glutGet(GLUT_ELAPSED_TIME);
      if (t - T0 >= 2000) {
         GLfloat seconds = (t - T0) / 1000.0;
         GLfloat fps = Frames / seconds;
         sprintf(frbuf, "Frame rate: %f", fps);
         T0 = t;
         Frames = 0;
      }
   }
}
예제 #28
0
void draw(HyperspaceSaverSettings *inSettings){
	if(inSettings->first){
		if(inSettings->dUseTunnels){  // only tunnels use caustic textures
			glDisable(GL_FOG);
			// Caustic textures can only be created after rendering context has been created
			// because they have to be drawn and then read back from the framebuffer.
#ifdef WIN32
			if(doingPreview) // super fast for Windows previewer
				inSettings->theCausticTextures = new causticTextures(8, inSettings->numAnimTexFrames, 32, 32, 1.0f, 0.01f, 10.0f);
			else  // normal
#endif
				inSettings->theCausticTextures = new causticTextures(8, inSettings->numAnimTexFrames, 100, 256, 1.0f, 0.01f, 20.0f);
			glEnable(GL_FOG);
		}
		if(inSettings->dShaders){
#ifdef WIN32
			if(doingPreview) // super fast for Windows previewer
				inSettings->theWNCM = new wavyNormalCubeMaps(inSettings->numAnimTexFrames, 32);
			else  // normal
#endif
				inSettings->theWNCM = new wavyNormalCubeMaps(inSettings->numAnimTexFrames, 128);
		}
		glViewport(inSettings->viewport[0], inSettings->viewport[1], inSettings->viewport[2], inSettings->viewport[3]);
		inSettings->first = 0;
	}

	// Variables for printing text
	static float computeTime = 0.0f;
	static float drawTime = 0.0f;
	//static rsTimer computeTimer, drawTimer;
	// start compute time timer
	//computeTimer.tick();

	glMatrixMode(GL_MODELVIEW);

	// Camera movements
	static float camHeading[3] = {0.0f, 0.0f, 0.0f};  // current, target, and last
	static int changeCamHeading = 1;
	static float camHeadingChangeTime[2] = {20.0f, 0.0f};  // total, elapsed
	static float camRoll[3] = {0.0f, 0.0f, 0.0f};  // current, target, and last
	static int changeCamRoll = 1;
	static float camRollChangeTime[2] = {1.0f, 0.0f};  // total, elapsed
	camHeadingChangeTime[1] += inSettings->frameTime;
	if(camHeadingChangeTime[1] >= camHeadingChangeTime[0]){  // Choose new direction
		camHeadingChangeTime[0] = rsRandf(15.0f) + 5.0f;
		camHeadingChangeTime[1] = 0.0f;
		camHeading[2] = camHeading[1];  // last = target
		if(changeCamHeading){
			// face forward most of the time
			if(rsRandi(6))
				camHeading[1] = 0.0f;
			// face backward the rest of the time
			else if(rsRandi(2))
				camHeading[1] = RS_PI;
			else
				camHeading[1] = -RS_PI;
			changeCamHeading = 0;
		}
		else
			changeCamHeading = 1;
	}
	float t = camHeadingChangeTime[1] / camHeadingChangeTime[0];
	t = 0.5f * (1.0f - cosf(RS_PI * t));
	camHeading[0] = camHeading[1] * t + camHeading[2] * (1.0f - t);
	camRollChangeTime[1] += inSettings->frameTime;
	if(camRollChangeTime[1] >= camRollChangeTime[0]){  // Choose new roll angle
		camRollChangeTime[0] = rsRandf(5.0f) + 10.0f;
		camRollChangeTime[1] = 0.0f;
		camRoll[2] = camRoll[1];  // last = target
		if(changeCamRoll){
			camRoll[1] = rsRandf(RS_PIx2*2) - RS_PIx2;
			changeCamRoll = 0;
		}
		else
			changeCamRoll = 1;
	}
	t = camRollChangeTime[1] / camRollChangeTime[0];
	t = 0.5f * (1.0f - cosf(RS_PI * t));
	camRoll[0] = camRoll[1] * t + camRoll[2] * (1.0f - t);

	static float pathDir[3] = {0.0f, 0.0f, -1.0f};
	inSettings->thePath->moveAlongPath(float(inSettings->dSpeed) * inSettings->frameTime * 0.04f);
	inSettings->thePath->update(inSettings->frameTime);
	inSettings->thePath->getPoint(inSettings->dDepth + 2, inSettings->thePath->step, inSettings->camPos);
	inSettings->thePath->getBaseDirection(inSettings->dDepth + 2, inSettings->thePath->step, pathDir);
	float pathAngle = atan2f(-pathDir[0], -pathDir[2]);

	glLoadIdentity();
	glRotatef((pathAngle + camHeading[0]) * RS_RAD2DEG, 0, 1, 0);
	glRotatef(camRoll[0] * RS_RAD2DEG, 0, 0, 1);
	glGetFloatv(GL_MODELVIEW_MATRIX, inSettings->billboardMat);
	glLoadIdentity();
	glRotatef(-camRoll[0] * RS_RAD2DEG, 0, 0, 1);
	glRotatef((-pathAngle - camHeading[0]) * RS_RAD2DEG, 0, 1, 0);
	glTranslatef(inSettings->camPos[0]*-1, inSettings->camPos[1]*-1, inSettings->camPos[2]*-1);
	glGetDoublev(GL_MODELVIEW_MATRIX, inSettings->modelMat);
	inSettings->unroll = camRoll[0] * RS_RAD2DEG;

	if(inSettings->dUseGoo){
		// calculate diagonal fov
		float diagFov = 0.5f * float(inSettings->dFov) / RS_RAD2DEG;
		diagFov = tanf(diagFov);
		diagFov = sqrtf(diagFov * diagFov + (diagFov * inSettings->aspectRatio * diagFov * inSettings->aspectRatio));
		diagFov = 2.0f * atanf(diagFov);
		inSettings->theGoo->update(inSettings->camPos[0], inSettings->camPos[2], pathAngle + camHeading[0], diagFov, inSettings);
	}

	// measure compute time
	//computeTime += computeTimer.tick();
	// start draw time timer
	//drawTimer.tick();

	// clear
	glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
	glClear(GL_COLOR_BUFFER_BIT);

	// draw stars
	glCullFace(GL_BACK);
	glEnable(GL_CULL_FACE);
	glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE);
	glEnable(GL_BLEND);
	glEnable(GL_TEXTURE_2D);
	glActiveTextureARB(GL_TEXTURE2_ARB);
	glBindTexture(GL_TEXTURE_2D, NULL);
	glActiveTextureARB(GL_TEXTURE1_ARB);
	glBindTexture(GL_TEXTURE_2D, NULL);
	glActiveTextureARB(GL_TEXTURE0_ARB);
	glBindTexture(GL_TEXTURE_2D, inSettings->flaretex[0]);
	static float temppos[2];
	for(int i=0; i<inSettings->dStars; i++){
		temppos[0] = inSettings->stars[i]->pos[0] - inSettings->camPos[0];
		temppos[1] = inSettings->stars[i]->pos[2] - inSettings->camPos[2];
		if(temppos[0] > inSettings->depth){
			inSettings->stars[i]->pos[0] -= inSettings->depth * 2.0f;
			inSettings->stars[i]->lastPos[0] -= inSettings->depth * 2.0f;
		}
		if(temppos[0] < inSettings->depth*-1){
			inSettings->stars[i]->pos[0] += inSettings->depth * 2.0f;
			inSettings->stars[i]->lastPos[0] += inSettings->depth * 2.0f;
		}
		if(temppos[1] > inSettings->depth){
			inSettings->stars[i]->pos[2] -= inSettings->depth * 2.0f;
			inSettings->stars[i]->lastPos[2] -= inSettings->depth * 2.0f;
		}
		if(temppos[1] < inSettings->depth*-1){
			inSettings->stars[i]->pos[2] += inSettings->depth * 2.0f;
			inSettings->stars[i]->lastPos[2] += inSettings->depth * 2.0f;
		}
		inSettings->stars[i]->draw(inSettings->camPos, inSettings->unroll, inSettings->modelMat, inSettings->projMat, inSettings->viewport);
	}
	glDisable(GL_CULL_FACE);

	// pick animated texture frame
	static float textureTime = 0.0f;
	textureTime += inSettings->frameTime;
	// loop frames every 2 seconds
	const float texFrameTime(2.0f / float(inSettings->numAnimTexFrames));
	while(textureTime > texFrameTime){
		textureTime -= texFrameTime;
		inSettings->whichTexture ++;
	}
	while(inSettings->whichTexture >= inSettings->numAnimTexFrames)
		inSettings->whichTexture -= inSettings->numAnimTexFrames;

	// alpha component gets normalmap lerp value
	const float lerp = textureTime / texFrameTime;

	// draw goo
	if(inSettings->dUseGoo){
		// calculate color
		static float goo_rgb_phase[3] = {-0.1f, -0.1f, -0.1f};
		static float goo_rgb_speed[3] = {rsRandf(0.02f) + 0.02f, rsRandf(0.02f) + 0.02f, rsRandf(0.02f) + 0.02f};
		float goo_rgb[4];
		for(int i=0; i<3; i++){
			goo_rgb_phase[i] += goo_rgb_speed[i] * inSettings->frameTime;
			if(goo_rgb_phase[i] >= RS_PIx2)
				goo_rgb_phase[i] -= RS_PIx2;
			goo_rgb[i] = sinf(goo_rgb_phase[i]);
			if(goo_rgb[i] < 0.0f)
				goo_rgb[i] = 0.0f;
		}
		// setup textures
		if(inSettings->dShaders){
			goo_rgb[3] = lerp;
			glDisable(GL_TEXTURE_2D);
			glEnable(GL_TEXTURE_CUBE_MAP_ARB);
			glActiveTextureARB(GL_TEXTURE2_ARB);
			glBindTexture(GL_TEXTURE_CUBE_MAP_ARB, inSettings->nebulatex);
			glActiveTextureARB(GL_TEXTURE1_ARB);
			glBindTexture(GL_TEXTURE_CUBE_MAP_ARB, inSettings->theWNCM->texture[(inSettings->whichTexture + 1) % inSettings->numAnimTexFrames]);
			glActiveTextureARB(GL_TEXTURE0_ARB);
			glBindTexture(GL_TEXTURE_CUBE_MAP_ARB, inSettings->theWNCM->texture[inSettings->whichTexture]);
			glUseProgramObjectARB(gooProgram);
		}
		else{
			goo_rgb[3] = 1.0f;
			glBindTexture(GL_TEXTURE_2D, inSettings->nebulatex);
			glEnable(GL_TEXTURE_2D);
			glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
			glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
			glEnable(GL_TEXTURE_GEN_S);
			glEnable(GL_TEXTURE_GEN_T);
		}
		// draw it
		glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
		glBlendFunc(GL_SRC_ALPHA, GL_ONE);
		glEnable(GL_BLEND);
		glColor4fv(goo_rgb);
		inSettings->theGoo->draw();
		if(inSettings->dShaders){
			glDisable(GL_TEXTURE_CUBE_MAP_ARB);
			glUseProgramObjectARB(0);
		}
		else{
			glDisable(GL_TEXTURE_GEN_S);
			glDisable(GL_TEXTURE_GEN_T);
		}
	}

	// update starburst
	static float starBurstTime = 300.0f;  // burst after 5 minutes
	starBurstTime -= inSettings->frameTime;
	if(starBurstTime <= 0.0f){
		float pos[] = {inSettings->camPos[0] + (pathDir[0] * inSettings->depth * (0.5f + rsRandf(0.5f))),
			rsRandf(2.0f) - 1.0f,
			inSettings->camPos[2] + (pathDir[2] * inSettings->depth * (0.5f + rsRandf(0.5f)))};
		inSettings->theStarBurst->restart(pos);  // it won't actually restart unless it's ready to
		starBurstTime = rsRandf(240.0f) + 60.0f;  // burst again within 1-5 minutes
	}
	if(inSettings->dShaders)
		inSettings->theStarBurst->draw(lerp, inSettings);
	else
		inSettings->theStarBurst->draw(inSettings);

	// draw tunnel
	if(inSettings->dUseTunnels){
		inSettings->theTunnel->make(inSettings->frameTime, inSettings->dShaders);
		glCullFace(GL_BACK);
		glEnable(GL_CULL_FACE);
		glEnable(GL_TEXTURE_2D);
		if(inSettings->dShaders){
			glActiveTextureARB(GL_TEXTURE1_ARB);
			glBindTexture(GL_TEXTURE_2D, inSettings->theCausticTextures->caustictex[(inSettings->whichTexture + 1) % inSettings->numAnimTexFrames]);
			glActiveTextureARB(GL_TEXTURE0_ARB);
			glBindTexture(GL_TEXTURE_2D, inSettings->theCausticTextures->caustictex[inSettings->whichTexture]);
			glUseProgramObjectARB(tunnelProgram);
			inSettings->theTunnel->draw(lerp);
			glUseProgramObjectARB(0);
		}
		else{
			glBindTexture(GL_TEXTURE_2D, inSettings->theCausticTextures->caustictex[inSettings->whichTexture]);
			inSettings->theTunnel->draw();
		}
		glDisable(GL_CULL_FACE);
	}

	// draw sun with lens flare
	glDisable(GL_FOG);
	float flarepos[3] = {0.0f, 2.0f, 0.0f};
	glBindTexture(GL_TEXTURE_2D, inSettings->flaretex[0]);
	inSettings->sunStar->draw(inSettings->camPos, inSettings->unroll, inSettings->modelMat, inSettings->projMat, inSettings->viewport);
	float diff[3] = {flarepos[0] - inSettings->camPos[0], flarepos[1] - inSettings->camPos[1], flarepos[2] - inSettings->camPos[2]};
	float alpha = 0.5f - 0.005f * sqrtf(diff[0] * diff[0] + diff[1] * diff[1] + diff[2] * diff[2]);
	if(alpha > 0.0f)
		flare(flarepos, 1.0f, 1.0f, 1.0f, alpha, inSettings);
	glEnable(GL_FOG);

	// measure draw time
	//drawTime += drawTimer.tick();

	// write text
	static float totalTime = 0.0f;
	totalTime += inSettings->frameTime;
	static std::vector<std::string> strvec;
	static int frames = 0;
	++frames;
	if(frames == 60){
		strvec.clear();
		std::string str1 = "         FPS = " + to_string(60.0f / totalTime);
		strvec.push_back(str1);
		std::string str2 = "compute time = " + to_string(computeTime / 60.0f);
		strvec.push_back(str2);
		std::string str3 = "   draw time = " + to_string(drawTime / 60.0f);
		strvec.push_back(str3);
		totalTime = 0.0f;
		computeTime = 0.0f;
		drawTime = 0.0f;
		frames = 0;
	}
	if(inSettings->kStatistics){
		glMatrixMode(GL_PROJECTION);
		glPushMatrix();
		glLoadIdentity();
		glOrtho(0.0f, 50.0f * inSettings->aspectRatio, 0.0f, 50.0f, -1.0f, 1.0f);

		glMatrixMode(GL_MODELVIEW);
		glPushMatrix();
		glLoadIdentity();
		glTranslatef(1.0f, 48.0f, 0.0f);

		glColor3f(1.0f, 0.6f, 0.0f);
		inSettings->textwriter->draw(strvec);

		glPopMatrix();
		glMatrixMode(GL_PROJECTION);
		glPopMatrix();
	}
	
#ifdef WIN32
	wglSwapLayerBuffers(hdc, WGL_SWAP_MAIN_PLANE);
#endif
#ifdef RS_XSCREENSAVER
	glXSwapBuffers(xdisplay, xwindow);
#endif
}
예제 #29
0
void displayfunc()
   {
   unsigned int i;

   GLuint texid;

   clearbuffer(0,0,0);

   for (i=0; i<height; i++)
      memcpy(&image[i*components*imgwidth],
             &volume[(long long)frame*components*width*height+i*components*width],components*width);

   glGenTextures(1,&texid);
   glBindTexture(GL_TEXTURE_2D,texid);

   glPixelStorei(GL_UNPACK_ALIGNMENT,1);
   if (components==1) glTexImage2D(GL_TEXTURE_2D,0,GL_LUMINANCE,imgwidth,imgheight,0,GL_LUMINANCE,GL_UNSIGNED_BYTE,image);
   else if (components==3) glTexImage2D(GL_TEXTURE_2D,0,GL_RGB,imgwidth,imgheight,0,GL_RGB,GL_UNSIGNED_BYTE,image);
   else if (components==4) glTexImage2D(GL_TEXTURE_2D,0,GL_RGBA,imgwidth,imgheight,0,GL_RGBA,GL_UNSIGNED_BYTE,image);
   else ERRORMSG();

   glDepthMask(GL_FALSE);
   glDisable(GL_DEPTH_TEST);
   glDisable(GL_DITHER);
   glDisable(GL_CULL_FACE);

   glMatrixMode(GL_TEXTURE);
   glPushMatrix();
   glLoadIdentity();
   glTranslatef(0.5f/imgwidth,0.5f/imgheight,0.0f);
   glScalef((float)(width-1)/imgwidth,(float)(height-1)/imgheight,0.0f);
   glMatrixMode(GL_PROJECTION);
   glPushMatrix();
   glLoadIdentity();
   glOrtho(0.0f,winwidth-1,0.0f,winheight-1,-1.0f,1.0f);
   glMatrixMode(GL_MODELVIEW);
   glPushMatrix();
   glLoadIdentity();

   if (width*winheight<winwidth*height)
      {
      glTranslatef((winwidth-width*winheight/height)/2.0f,0.0f,0.0f);
      glScalef(width*winheight/height,winheight,0.0f);
      }
   else
      {
      glTranslatef(0.0f,(winheight-height*winwidth/width)/2.0f,0.0f);
      glScalef(winwidth,height*winwidth/width,0.0f);
      }

   glTexEnvi(GL_TEXTURE_ENV,GL_TEXTURE_ENV_MODE,GL_MODULATE);

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

   glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S,GL_CLAMP);
   glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T,GL_CLAMP);

   glEnable(GL_TEXTURE_2D);

   glColor3f(1.0f,1.0f,1.0f);
   glBegin(GL_TRIANGLE_FAN);
   glTexCoord2f(0.0f,1.0f);
   glVertex3f(0.0f,0.0f,0.0f);
   glTexCoord2f(1.0f,1.0f);
   glVertex3f(1.0f,0.0f,0.0f);
   glTexCoord2f(1.0f,0.0f);
   glVertex3f(1.0f,1.0f,0.0f);
   glTexCoord2f(0.0f,0.0f);
   glVertex3f(0.0f,1.0f,0.0f);
   glEnd();

   glDisable(GL_TEXTURE_2D);
   glDeleteTextures(1,&texid);

   glDepthMask(GL_TRUE);
   glEnable(GL_DEPTH_TEST);
   glEnable(GL_DITHER);
   glEnable(GL_CULL_FACE);

   glMatrixMode(GL_TEXTURE);
   glPopMatrix();
   glMatrixMode(GL_PROJECTION);
   glPopMatrix();
   glMatrixMode(GL_MODELVIEW);
   glPopMatrix();

   glutSwapBuffers();
   waitfor(1.0/fps);

   if (!pausing)
      if (frame<depth-1) frame++;
      else frame=0;

   if (frame==depth-1) pausing=TRUE;
   }
예제 #30
0
파일: cg200.c 프로젝트: jasongi/teapot
/*
 =======================================================================================================================
    Display function. Where the magic happens and everything is drawn.
 =======================================================================================================================
 */
void display(void)
{
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();

	/* adjust for zoom value */
	gluPerspective(50 * zoom, (float) glutGet(GLUT_WINDOW_WIDTH) / (float) glutGet(GLUT_WINDOW_HEIGHT), 0.001, 40.0);
	glMatrixMode(GL_MODELVIEW);

	/* do rotation things */
	alpha = alpha + (float) inc;
	if(alpha > (float) 360.0) alpha -= (float) 360.0;
	beta = beta + (float) inc2;
	if(beta > (float) 360.0) beta -= (float) 360.0;

	/* normalise any normals which aren't in unit form */
	glEnable(GL_NORMALIZE);
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	/* draw the fog */
	fog();
	glPushMatrix();

	/* translate whole scene so we can actually see it */
	glTranslatef((float) 0.0, -(float) 0.5, -(float) 5);

	/* rotate by rotation values */
	glRotatef(beta, (float) 1.0, (float) 0.0, (float) 0.0);
	glRotatef(-alpha, (float) 0.0, (float) 1.0, (float) 0.0);

	/* it was a bit big... */
	glScalef(0.50, 0.50, 0.50);

	/* set shade mode */
	glShadeModel(shademode);
	glPushMatrix();

	/* draw the floor */
	glScalef(scale * 5, scale * 5, scale * 5);
	glRotatef(180, 0, 1.0, 1.0);
	drawCheck(20, 20, BLUE, YELLOW);	/* draw ground */
	glPopMatrix();

	/* set up the lights */
	glTranslatef(0.3, 0, 1.25);
	glEnable(GL_LIGHTING);

	/* this is a positioned light */
	glEnable(GL_LIGHT0);

	/* this is a directed light */
	glEnable(GL_LIGHT1);

	/* this is a spotlight (not initiated til later) */
	glEnable(GL_LIGHT2);

	/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
	/* set the ambient light */
	GLfloat ambientColor[] = { 0.2, 0.2, 0.2, 1.0 };
	/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/

	glLightModelfv(GL_LIGHT_MODEL_AMBIENT, ambientColor);

	/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
	GLfloat lightColor0[] = { 0.5, 0.5, 0.5, 1.0 };
	GLfloat lightPos0[] = { 0.0f, 1.5f, -1.0f, 0.0f };
	/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/

	glLightfv(GL_LIGHT0, GL_DIFFUSE, lightColor0);
	glLightfv(GL_LIGHT0, GL_POSITION, lightPos0);

	/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
	GLfloat lightColor1[] = { 0.8f, 0.8f, 0.8f, 1.0f };
	GLfloat lightPos1[] = { 1.0f, 2.0f, -2.0f, 0.0f };
	/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/

	glLightfv(GL_LIGHT1, GL_DIFFUSE, lightColor1);
	glLightfv(GL_LIGHT1, GL_POSITION, lightPos1);

	/* draw the table */
	glPushMatrix();
	glTranslatef(-0.3, 0, -1.25);
	glRotatef(180, 0, 1.0, 1.0);

	/*~~~~~~~~~~~~~~~~~~~~~~~*/
	float	cylbase = 0.60;
	float	cyltop = 0.15;
	float	cylheight = 1.0;
	float	tableheight = 0.10;
	float	tablecirc = 0.90;
	/*~~~~~~~~~~~~~~~~~~~~~~~*/

	setMaterial(finTable);
	setColor(TABLE2);
	gluCylinder(quadratic, cylbase, cyltop, cylheight, splines * LOD, splines * LOD);
	glTranslatef(0, 0, cylheight);
	gluDisk(quadratic, 0.0, cyltop, splines * LOD, splines * LOD);
	gluCylinder(quadratic, tablecirc, tablecirc, tableheight, splines * LOD, splines * LOD);
	gluDisk(quadratic, 0.0, tablecirc, splines * LOD, splines * LOD);
	glTranslatef(0, 0, tableheight);
	gluDisk(quadratic, 0.0, tablecirc, splines * LOD, splines * LOD);
	setMaterial(finDefault);
	glPopMatrix();
	glPushMatrix();

	/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
	/* initiate the spotlight */
	GLfloat light_ambient2[] = { 0.0, 0.0, 0.0, 1.0 };
	GLfloat light_diffuse2[] = { 0.0, 0.3, 0, 1.0 };
	GLfloat light_specular2[] = { 0.0, 0.3, 0, 1.0 };
	GLfloat lightPos2[] = { 0.0f, 3.0f, 0.0f, 0.0f };
	GLfloat spot_direction[] = { 0, -1.0, 0 };
	/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/

	glLightfv(GL_LIGHT2, GL_AMBIENT, light_ambient2);
	glLightfv(GL_LIGHT2, GL_DIFFUSE, light_diffuse2);
	glLightfv(GL_LIGHT2, GL_SPECULAR, light_specular2);
	glLightf(GL_LIGHT2, GL_SPOT_CUTOFF, 30.0);
	glLightfv(GL_LIGHT2, GL_POSITION, lightPos2);
	glLightfv(GL_LIGHT2, GL_SPOT_DIRECTION, spot_direction);

	/* draw the chairs and rotate them around the table */
	glRotatef(270, 0.0, 1.0, 0.0);
	glTranslatef(-1.5, 0, 1.5);
	glPushMatrix();
	glRotatef(90, 0, 1.0, 0.0);
	chair();
	glPopMatrix();
	glPushMatrix();
	glTranslatef(0.3, 0, -1.25);
	glRotatef(90, 0, 1.0, 0.0);
	glTranslatef(-0.3, 0, 1.25);
	glRotatef(90, 0, 1.0, 0.0);
	chair();
	glPopMatrix();
	glPushMatrix();
	glTranslatef(0.3, 0, -1.25);
	glRotatef(180, 0, 1.0, 0.0);
	glTranslatef(-0.3, 0, 1.25);
	glRotatef(90, 0, 1.0, 0.0);
	chair();
	glPopMatrix();
	glPushMatrix();
	glTranslatef(0.3, 0, -1.25);
	glRotatef(270, 0, 1.0, 0.0);
	glTranslatef(-0.3, 0, 1.25);
	glRotatef(90, 0, 1.0, 0.0);
	chair();
	glPopMatrix();

	/* draw the cups/forks and rotate around the table */
	glPushMatrix();
	glTranslatef(0.35, 1.1, -0.25);
	cups();
	glPushMatrix();
	glTranslatef(-0.05, 0, -1.0);
	glRotatef(90, 0, 1.0, 0);
	glTranslatef(0.05, 0, 1.0);
	cups();
	glPopMatrix();
	glPushMatrix();
	glTranslatef(-0.05, 0, -1.0);
	glRotatef(180, 0, 1.0, 0);
	glTranslatef(0.05, 0, 1.0);
	cups();
	glPopMatrix();
	glPushMatrix();
	glTranslatef(-0.05, 0, -1.0);
	glRotatef(270, 0, 1.0, 0);
	glTranslatef(0.05, 0, 1.0);
	cups();
	glPopMatrix();
	glPopMatrix();

	/* draw the teapot */
	glPushMatrix();

	/* put on table */
	glTranslatef(0.3, 1.3, -1.25);

	/*~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
	/* trans values for animation */
	static int		rotateval = 1;
	static int		rotatevalx = 0;
	static float	transvaly = 0;
	static float	transvalx = 0;
	/* clock values for animation */
	static int		beginslow = 0;
	static int		slowclock = 0;
	static int		pourclock = 0;
	/*~~~~~~~~~~~~~~~~~~~~~~~~~~~*/

	/* only animate when playing */
	if(ani_play)
	{
		{
			/*~~~*/
			int ii;
			/*~~~*/

			for(ii = 0; ii < speed; ii++)
			{
				{

					/* section where teapot slows */
					if((beginslow))
					{
						{
							if(((20 - slowclock / 10) > 0))
							{
								rotateval = rotateval + (20 - slowclock / 10);
								slowclock++;
							}
							else
							{
								{

									/* section where teapot is pouring */
									if(pourclock < 90)
									{
										{
											rotatevalx = pourclock / 2;
											transvaly = ((double) pourclock) / (double) 200;
											transvalx = ((double) pourclock) / (double) 400;
										}
									}
									else if(pourclock < 135)
									{	/* teapot in mid air */
										rotatevalx = 45;
										transvaly = 90.0 / 200;
										transvalx = 90.0 / 400;
									}
									else if(pourclock < 225)
									{
										{	/* teapot is being set down */
											rotatevalx = 45 - (pourclock - 135) / 2;
											transvaly = 90.0 / 200 - ((double) pourclock - 135) / (double) 200;
											transvalx = 90.0 / 400 - ((double) pourclock - 135) / (double) 400;
										}
									}
									else if(pourclock < 300)
									{		/* teapot is back on table */
										rotatevalx = 0;
										transvaly = 0;
										transvalx = 0;
									}
									else
									{
										{	/* reset variables for next play */
											ani_play = 0;
											ani_clock = 0;
											rotateval = 1;
											ani_direction = 0;
											slowclock = 0;
											pourclock = -speed;
											beginslow = 0;
											rotatevalx = 0;
											transvaly = 0;
											transvalx = 0;
										}
									}

									pourclock++;
								}
							}
						}
					}
					else if(ani_clock < 200)
					{			/* teapot is speeding up it's spin */
						rotateval = rotateval + ani_clock / 10;
					}
					else if(ani_clock < 500)
					{
						{		/* teapot is at constant spin */
							rotateval = rotateval + 20;
							if(ani_clock == 300)
							{	/* choose the cup it will stop at */
								ani_direction = rand() % 4 + 1;
							}
						}
					}

					if(rotateval > 360) rotateval -= 360;
					if
					(
						(!beginslow)
					&&	(ani_direction != 0)
					&&	(
							(
								(rotateval >= ani_direction * 90 - SLOWMAGIC - 20)
							&&	(rotateval <= ani_direction * 90 - SLOWMAGIC)
							)
						||	(
									(rotateval >= ani_direction * 90 - SLOWMAGIC + 340)
								&&	(rotateval <= ani_direction * 90 - SLOWMAGIC + 360)
								)
						)
					)
					{			/* choose opportune moment to slow down */
						beginslow = 1;
						rotateval = ani_direction * 90 - SLOWMAGIC + 360;
						if(rotateval > 360) rotateval -= 360;
					}

					ani_clock++;
				}
			}
		}	/* apply transformations */
	}

	glRotatef(rotateval, 0, 1.0, 0);
	glTranslatef(transvalx, transvaly, 0);
	glRotatef(-rotatevalx, 0, 0, 1.0);

	/* apply texture */
	glBindTexture(GL_TEXTURE_2D, texture[1]);
	glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
	glEnable(GL_TEXTURE_2D);

	/* apply finish */
	setMaterial(finPot);
	glutSolidTeapot(0.2);
	setMaterial(finDefault);
	glDisable(GL_TEXTURE_2D);
	glPopMatrix();
	glPopMatrix();
	glPopMatrix();

	/* 3D stuff is done */
	glFlush();

	/* draw text overlay */
	glDisable(GL_NORMALIZE);
	glDisable(GL_LIGHTING);
	glMatrixMode(GL_PROJECTION);
	glPushMatrix();
	glLoadIdentity();
	glOrtho(0, glutGet(GLUT_WINDOW_WIDTH), glutGet(GLUT_WINDOW_HEIGHT), 0, -1, 1);
	glMatrixMode(GL_MODELVIEW);
	glPushMatrix();
	glLoadIdentity();

	/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
	char	speedstring[20];
	char	str[500] = "<Z> and <z>: zoom in/out\n<X> or <x>: Start/Stop X rotation\n<Y> or <y> Start/Stop Y Rotation\n<A> or <a>: Start animation\n<F> or <f>: Speed up animation\n<S> or <s>: Slow down animation\n<T> or <t>: Pause animation\n<C> or <c>: Resume the animation\n<p>: switch the rendering to the flat shaded polygonization.\n<P> switch the rendering to the smooth shaded polygonization.\n<q> or <Q>: change fog mode\nspeed: ";
	/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/

	sprintf(speedstring, "%d", speed);
	strcat(str, speedstring);
	strcat(str, "\nLOD: ");
	sprintf(speedstring, "%d", LOD);
	strcat(str, speedstring);
	strcat(str, "\nFog Mode: ");
	switch(fogfilter)
	{
		{
		case 0: strcat(str, "GL_EXP"); break;
		case 1: strcat(str, "GL_EXP2"); break;
		case 2: strcat(str, "GL_LINEAR"); break;
		case 3: strcat(str, "NO FOG"); break;
		}
	}

	bitmap_output(30, 30, str, GLUT_BITMAP_HELVETICA_12);
	glPopMatrix();
	glMatrixMode(GL_PROJECTION);
	glPopMatrix();

	/* draw transparent box for text */
	glMatrixMode(GL_PROJECTION);
	glPushMatrix();
	glLoadIdentity();
	glOrtho(0, glutGet(GLUT_WINDOW_WIDTH), glutGet(GLUT_WINDOW_HEIGHT), 0, -1, 1);
	glMatrixMode(GL_MODELVIEW);
	glPushMatrix();
	glLoadIdentity();
	glEnable(GL_BLEND);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	glColor4f((float) 0, (float) 0, (float) 0, (float) 0.6);
	glRecti(30 - 10, 30 - 20, 40 + 350, 30 + 250);
	glPopMatrix();
	glMatrixMode(GL_PROJECTION);
	glPopMatrix();
	glFlush();
	glutSwapBuffers();
}