예제 #1
0
enum piglit_result
piglit_display(void)
{
    GLint  max_stencil;
    GLint  stencil_bits;
    unsigned i;
    GLboolean pass = GL_TRUE;
    float expected[4] = {0.5, 0.5, 0.5, 0.5};
    int w = piglit_width / (5 * 2 + 1);
    int h = w;
    int start_y = (piglit_height - h) / 2;

    piglit_ortho_projection(piglit_width, piglit_height, GL_FALSE);

    glGetIntegerv(GL_STENCIL_BITS, & stencil_bits);
    max_stencil = (1U << stencil_bits) - 1;
    printf("Stencil bits = %u, maximum stencil value = 0x%08x\n",
           stencil_bits, max_stencil);

    glClearStencil(0);
    glClearColor(0.2, 0.2, 0.8, 0);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT |
            GL_STENCIL_BUFFER_BIT);

    /* This is the "reference" square.
     */

    glDisable(GL_STENCIL_TEST);
    glColor3f(0.5, 0.5, 0.5);
    piglit_draw_rect(w * 1, start_y, w, h);

    glEnable(GL_STENCIL_TEST);

    /* Draw the first two squares using the two non-wrap (i.e., saturate)
     * modes.
     */

    glStencilFunc(GL_ALWAYS, 0, ~0);
    glStencilOp(GL_KEEP, GL_KEEP, GL_INCR);

    glColor3f(0.9, 0.9, 0.9);

    for (i = 0 ; i < (max_stencil + 5) ; i++) {
        piglit_draw_rect(w * 3, start_y, w, h);
    }

    glStencilFunc(GL_EQUAL, max_stencil, ~0);
    glColor3f(0.5, 0.5, 0.5);
    piglit_draw_rect(w * 3, start_y, w, h);

    glStencilFunc(GL_ALWAYS, 0, ~0);
    glStencilOp(GL_KEEP, GL_KEEP, GL_DECR);

    glColor3f(0.9, 0.9, 0.9);

    for (i = 0 ; i < (max_stencil + 5) ; i++) {
        piglit_draw_rect(w * 5, start_y, w, h);
    }

    glStencilFunc(GL_EQUAL, 0, ~0);
    glColor3f(0.5, 0.5, 0.5);
    piglit_draw_rect(w * 5, start_y, w, h);

    /* Draw the last two squares using the two wrap modes.
     */

    glStencilFunc(GL_ALWAYS, 0, ~0);
    glStencilOp(GL_KEEP, GL_KEEP, GL_INCR_WRAP);

    glColor3f(0.9, 0.9, 0.9);

    for (i = 0 ; i < (max_stencil + 5) ; i++) {
        piglit_draw_rect(w * 7, start_y, w, h);
    }

    glStencilFunc(GL_EQUAL, 4, ~0);
    glColor3f(0.5, 0.5, 0.5);
    piglit_draw_rect(w * 7, start_y, w, h);

    glStencilFunc(GL_ALWAYS, 0, ~0);
    glStencilOp(GL_KEEP, GL_KEEP, GL_DECR_WRAP);

    glColor3f(0.9, 0.9, 0.9);

    for (i = 0 ; i < 5 ; i++) {
        piglit_draw_rect(w * 9, start_y, w, h);
    }

    glStencilFunc(GL_EQUAL, (max_stencil - 4), ~0);
    glColor3f(0.5, 0.5, 0.5);
    piglit_draw_rect(w * 9, start_y, w, h);

    pass = piglit_probe_pixel_rgb(w * 1.5, piglit_height / 2, expected);
    pass = piglit_probe_pixel_rgb(w * 3.5, piglit_height / 2, expected);
    pass = piglit_probe_pixel_rgb(w * 5.5, piglit_height / 2, expected);
    pass = piglit_probe_pixel_rgb(w * 7.5, piglit_height / 2, expected);
    pass = piglit_probe_pixel_rgb(w * 9.5, piglit_height / 2, expected);

    glutSwapBuffers();

    return pass ? PIGLIT_PASS : PIGLIT_FAIL;
}
예제 #2
0
//////////////////////////////////////////////////////////////////
// This function does any needed initialization on the rendering
// context. 
void SetupRC()
    {
    M3DVector3f vPoints[3] = {{ 0.0f, -0.4f, 0.0f },
                             { 10.0f, -0.4f, 0.0f },
                             { 5.0f, -0.4f, -5.0f }};
    int iSphere;
    int i;
    
    // Grayish background
    glClearColor(fLowLight[0], fLowLight[1], fLowLight[2], fLowLight[3]);
   
    // Clear stencil buffer with zero, increment by one whenever anybody
    // draws into it. When stencil function is enabled, only write where
    // stencil value is zero. This prevents the transparent shadow from drawing
    // over itself
    glStencilOp(GL_INCR, GL_INCR, GL_INCR);
    glClearStencil(0);
    glStencilFunc(GL_EQUAL, 0x0, 0x01);
    
    // Cull backs of polygons
    glCullFace(GL_BACK);
    glFrontFace(GL_CCW);
    glEnable(GL_CULL_FACE);
    glEnable(GL_DEPTH_TEST);
    glEnable(GL_MULTISAMPLE_ARB);
    
    // Setup light parameters
    glLightModelfv(GL_LIGHT_MODEL_AMBIENT, fNoLight);
    glLightfv(GL_LIGHT0, GL_AMBIENT, fLowLight);
    glLightfv(GL_LIGHT0, GL_DIFFUSE, fBrightLight);
    glLightfv(GL_LIGHT0, GL_SPECULAR, fBrightLight);
    glEnable(GL_LIGHTING);
    glEnable(GL_LIGHT0);
    
    glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
    
    // Calculate shadow matrix
    M3DVector4f pPlane;
    m3dGetPlaneEquation(pPlane, vPoints[0], vPoints[1], vPoints[2]);
    m3dMakePlanarShadowMatrix(mShadowMatrix, pPlane, fLightPos);
    
    // Mostly use material tracking
    glEnable(GL_COLOR_MATERIAL);
    glColorMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE);
    glMaterialfv(GL_FRONT, GL_SPECULAR, fBrightLight);
    glMateriali(GL_FRONT, GL_SHININESS, 128);
  
    
    // Randomly place the sphere inhabitants
    for(iSphere = 0; iSphere < NUM_SPHERES; iSphere++)
        {
        // Pick a random location between -20 and 20 at .1 increments
        spheres[iSphere].SetOrigin(((float)((rand() % 400) - 200) * 0.1f), 0.0, (float)((rand() % 400) - 200) * 0.1f);
        }
      
    // Set up texture maps
    glEnable(GL_TEXTURE_2D);
    glGenTextures(NUM_TEXTURES, textureObjects);
    glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
    
    
    for(i = 0; i < NUM_TEXTURES; i++)
        {
        GLbyte *pBytes;
        GLint iWidth, iHeight, iComponents;
        GLenum eFormat;
        
        glBindTexture(GL_TEXTURE_2D, textureObjects[i]);
        
        // Load this texture map
        pBytes = gltLoadTGA(szTextureFiles[i], &iWidth, &iHeight, &iComponents, &eFormat);
        gluBuild2DMipmaps(GL_TEXTURE_2D, iComponents, iWidth, iHeight, eFormat, GL_UNSIGNED_BYTE, pBytes);
        free(pBytes);
        
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
        }
        
    // Create display lists
    groundList = glGenLists(3);
    sphereList = groundList + 1;
    torusList = sphereList + 1;
    
    // Create sphere display list
    glNewList(sphereList, GL_COMPILE);
       gltDrawSphere(0.1f, 40, 20);
    glEndList();

    // Create torus display list
    glNewList(torusList, GL_COMPILE);
       gltDrawTorus(0.35, 0.15, 61, 37);
    glEndList();
    
    // Create the ground display list
    glNewList(groundList, GL_COMPILE);
        DrawGround();
    glEndList();
    }
예제 #3
0
bool Window::open() {
	// Initialise GLFW
	if( !glfwInit() )
	{
		fprintf( stderr, "Failed to initialize GLFW\n" );
		return false;
	}

	glfwOpenWindowHint(GLFW_FSAA_SAMPLES, ANTIALIASING); // 4x antialiasing
	glfwOpenWindowHint(GLFW_OPENGL_VERSION_MAJOR, 4); // We want OpenGL 4.1
	glfwOpenWindowHint(GLFW_OPENGL_VERSION_MINOR, 1);
	glfwOpenWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
	glfwOpenWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
	glfwOpenWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); //We don't want the old OpenGL

	// Open a window and create its OpenGL context
	if( !glfwOpenWindow( WINDOW_WIDTH, WINDOW_HEIGHT, 8,8,8,8, 0,0, WINDOW_MODE ) )
	{
		fprintf( stderr, "Failed to open GLFW window\n" );
		glfwTerminate();
		return false;
	}
	int w,h;
	glfwGetWindowSize(&w,&h);
	glViewport(0,0,w,h);

	glfwEnable(GLFW_AUTO_POLL_EVENTS);

	// set window callback for when the window is resized
	glfwSetWindowSizeCallback((GLFWwindowsizefun)resize);

	// set window position
	glfwSetWindowPos(WINDOW_WIDTH/4,WINDOW_HEIGHT/4);

	// Initialize GLEW
	glewExperimental=true; // Needed in core profile
	if (glewInit() != GLEW_OK) {
		fprintf(stderr, "Failed to initialize GLEW\n");
		return false;
	}

	glfwSetWindowTitle( WINDOW_TITLE );
	
	int version_major, version_minor, version_revision;
	glfwGetGLVersion(&version_major, &version_minor, &version_revision);
	printf("Using OpenGL version %d.%d\n",version_major,version_minor);
	printf("width %u height %u mode %d aa %u\n",WINDOW_WIDTH,WINDOW_HEIGHT,WINDOW_MODE,ANTIALIASING);	
	printf("Window opened successfully\n");

	// Ensure we can capture the escape key being pressed below
	glfwEnable( GLFW_STICKY_KEYS );
	
	// set clear color
	glClearColor(0,0,0,0);
	// set clear depth
	glClearDepth(1);
	// set clear stencil buffer
	glClearStencil(0);

	//glViewport(0, 0, WINDOW_HEIGHT, WINDOW_WIDTH);  // aspect ratio 1:1.333
	//glOrtho(0.5f, -0.5f, -0.666f, 0.666f, -1.0f, 1.0f); // matching aspect ratio with 0,0 centered
	
	glScalef(1.0f, 1.0f, 1.0f);

	// Create vertex array object
	glGenVertexArrays(1, &vaoID);
	glBindVertexArray(vaoID);

	return true;
}
// Inherited from BatchRenderer
void SceneObject_Decal_BatchRenderer::Execute()
{
	if(!GetScene()->m_renderingDeferred)
		return;

	glEnable(GL_STENCIL_TEST);
	glClearStencil(0);
	glClear(GL_STENCIL_BUFFER_BIT);

	glDepthFunc(GL_LEQUAL);
	
	glDepthMask(false);

	glEnable(GL_POLYGON_OFFSET_FILL);
	
	for(unsigned int i = 0, numDecals = m_pDecals.size(); i < numDecals;)
	{
		// Stencil in batches of 8
		glColorMask(false, false, false, false);
		Shader::Unbind();

		glPolygonOffset(2.0f, 2.0f);

		// Mark parts where depth test fails
		glStencilFunc(GL_ALWAYS, 0xff, 0xff);
		glStencilOp(GL_KEEP, GL_REPLACE, GL_KEEP);

		unsigned int firstDecalInBatchIndex = i;

		// Stencil out regions with stencil mask
		for(unsigned int j = 0; j < 8 && i < numDecals; j++, i++)
		{
			glStencilMask(m_decalIndices[j]);
			m_pDecals[i]->Render_Batch_NoTexture();
		}

		glColorMask(true, true, true, true);

		// Stencil test
		glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
	
		glPolygonOffset(-2.0f, -2.0f);

		// Re-render, second pass
		i = firstDecalInBatchIndex;

		GetScene()->RebindGBufferRenderShader();

		for(unsigned int j = 0; j < 8 && i < numDecals; j++, i++)
		{
			glStencilFunc(GL_EQUAL, 0xff, m_decalIndices[j]);

			m_pDecals[i]->Render_Batch_Textured();
		}

		glClear(GL_STENCIL_BUFFER_BIT);
	}

	GetScene()->SetCurrentGBufferRenderShader(Scene::e_plain);

	glDisable(GL_POLYGON_OFFSET_FILL);
	glDepthMask(true);

	glDepthFunc(GL_LESS);

	glDisable(GL_STENCIL_TEST);
}
예제 #5
0
void PGRAPH_OpenGL::ClearStencil(u32 value)
{
    glClearStencil(value);
    checkRendererError("ClearStencil");
}
void LLDrawPoolWater::render(S32 pass)
{
    LLFastTimer ftm(LLFastTimer::FTM_RENDER_WATER);
    if (mDrawFace.empty() || LLDrawable::getCurrentFrame() <= 1)
    {
        return;
    }

    //do a quick 'n dirty depth sort
    for (std::vector<LLFace*>::iterator iter = mDrawFace.begin();
            iter != mDrawFace.end(); iter++)
    {
        LLFace* facep = *iter;
        facep->mDistance = -facep->mCenterLocal.mV[2];
    }

    std::sort(mDrawFace.begin(), mDrawFace.end(), LLFace::CompareDistanceGreater());
    static const LLCachedControl<bool> render_transparent_water("RenderTransparentWater",false);
    if(!render_transparent_water)
    {
        // render water for low end hardware
        renderOpaqueLegacyWater();
        return;
    }

    LLGLEnable blend(GL_BLEND);

    if ((mVertexShaderLevel > 0) && !sSkipScreenCopy)
    {
        shade();
        return;
    }

    LLVOSky *voskyp = gSky.mVOSkyp;

    stop_glerror();

    if (!gGLManager.mHasMultitexture)
    {
        // Ack!  No multitexture!  Bail!
        return;
    }

    LLFace* refl_face = voskyp->getReflFace();

    gPipeline.disableLights();

    LLGLDepthTest gls_depth(GL_TRUE, GL_FALSE);

    LLGLDisable cullFace(GL_CULL_FACE);

    // Set up second pass first
    mWaterImagep->addTextureStats(1024.f*1024.f);
    gGL.getTexUnit(1)->activate();
    gGL.getTexUnit(1)->enable(LLTexUnit::TT_TEXTURE);
    gGL.getTexUnit(1)->bind(mWaterImagep) ;

    LLVector3 camera_up = LLViewerCamera::getInstance()->getUpAxis();
    F32 up_dot = camera_up * LLVector3::z_axis;

    LLColor4 water_color;
    if (LLViewerCamera::getInstance()->cameraUnderWater())
    {
        water_color.setVec(1.f, 1.f, 1.f, 0.4f);
    }
    else
    {
        water_color.setVec(1.f, 1.f, 1.f, 0.5f*(1.f + up_dot));
    }

    glColor4fv(water_color.mV);

    // Automatically generate texture coords for detail map
    glEnable(GL_TEXTURE_GEN_S); //texture unit 1
    glEnable(GL_TEXTURE_GEN_T); //texture unit 1
    glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR);
    glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR);

    // Slowly move over time.
    F32 offset = fmod(gFrameTimeSeconds*2.f, 100.f);
    F32 tp0[4] = {16.f/256.f, 0.0f, 0.0f, offset*0.01f};
    F32 tp1[4] = {0.0f, 16.f/256.f, 0.0f, offset*0.01f};
    glTexGenfv(GL_S, GL_OBJECT_PLANE, tp0);
    glTexGenfv(GL_T, GL_OBJECT_PLANE, tp1);

    gGL.getTexUnit(1)->setTextureColorBlend(LLTexUnit::TBO_MULT, LLTexUnit::TBS_TEX_COLOR, LLTexUnit::TBS_PREV_COLOR);
    gGL.getTexUnit(1)->setTextureAlphaBlend(LLTexUnit::TBO_REPLACE, LLTexUnit::TBS_PREV_ALPHA);

    gGL.getTexUnit(0)->activate();

    glClearStencil(1);
    glClear(GL_STENCIL_BUFFER_BIT);
    LLGLEnable gls_stencil(GL_STENCIL_TEST);
    glStencilOp(GL_KEEP, GL_REPLACE, GL_KEEP);
    glStencilFunc(GL_ALWAYS, 0, 0xFFFFFFFF);

    for (std::vector<LLFace*>::iterator iter = mDrawFace.begin();
            iter != mDrawFace.end(); iter++)
    {
        LLFace *face = *iter;
        if (voskyp->isReflFace(face))
        {
            continue;
        }
        gGL.getTexUnit(0)->bind(face->getTexture());
        face->renderIndexed();
    }

    // Now, disable texture coord generation on texture state 1
    gGL.getTexUnit(1)->activate();
    gGL.getTexUnit(1)->unbind(LLTexUnit::TT_TEXTURE);
    gGL.getTexUnit(1)->disable();
    glDisable(GL_TEXTURE_GEN_S); //texture unit 1
    glDisable(GL_TEXTURE_GEN_T); //texture unit 1

    // Disable texture coordinate and color arrays
    gGL.getTexUnit(0)->activate();
    gGL.getTexUnit(0)->unbind(LLTexUnit::TT_TEXTURE);

    stop_glerror();

    if (gSky.mVOSkyp->getCubeMap())
    {
        gSky.mVOSkyp->getCubeMap()->enable(0);
        gSky.mVOSkyp->getCubeMap()->bind();

        glMatrixMode(GL_TEXTURE);
        glLoadIdentity();
        LLMatrix4 camera_mat = LLViewerCamera::getInstance()->getModelview();
        LLMatrix4 camera_rot(camera_mat.getMat3());
        camera_rot.invert();

        glLoadMatrixf((F32 *)camera_rot.mMatrix);

        glMatrixMode(GL_MODELVIEW);
        LLOverrideFaceColor overrid(this, 1.f, 1.f, 1.f,  0.5f*up_dot);

        gGL.getTexUnit(0)->setTextureBlendType(LLTexUnit::TB_MULT);

        for (std::vector<LLFace*>::iterator iter = mDrawFace.begin();
                iter != mDrawFace.end(); iter++)
        {
            LLFace *face = *iter;
            if (voskyp->isReflFace(face))
            {
                //refl_face = face;
                continue;
            }

            if (face->getGeomCount() > 0)
            {
                face->renderIndexed();
            }
        }

        gGL.getTexUnit(0)->setTextureBlendType(LLTexUnit::TB_MULT);

        gSky.mVOSkyp->getCubeMap()->disable();

        gGL.getTexUnit(0)->unbind(LLTexUnit::TT_TEXTURE);
        gGL.getTexUnit(0)->enable(LLTexUnit::TT_TEXTURE);
        glMatrixMode(GL_TEXTURE);
        glLoadIdentity();
        glMatrixMode(GL_MODELVIEW);

    }

    glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);

    if (refl_face)
    {
        glStencilFunc(GL_NOTEQUAL, 0, 0xFFFFFFFF);
        renderReflection(refl_face);
    }

    gGL.getTexUnit(0)->setTextureBlendType(LLTexUnit::TB_MULT);
}
예제 #7
0
/**
 * @return whether setting the video mode was successful
 * 
 * Sets SDL video mode options/settings
 */
bool SpringApp::SetSDLVideoMode ()
{
	int sdlflags = SDL_OPENGL | SDL_RESIZABLE;

	//conditionally_set_flag(sdlflags, SDL_FULLSCREEN, fullscreen);
	sdlflags |= fullscreen ? SDL_FULLSCREEN : 0;

	SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5);
	SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 5);
	SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5);

#ifdef __APPLE__
	const int defaultDepthSize = 32;
#else
	const int defaultDepthSize = 16;
#endif
	SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, configHandler.GetInt("DepthBufferBits", defaultDepthSize));
	SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, configHandler.GetInt("StencilBufferBits", 1));

	SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);

	FSAA = MultisampleTest();

	SDL_Surface *screen = SDL_SetVideoMode(screenWidth, screenHeight, 0, sdlflags);
	if (!screen) {
		handleerror(NULL,"Could not set video mode","ERROR",MBF_OK|MBF_EXCL);
		return false;
	}

	// Something in SDL_SetVideoMode (OpenGL drivers?) messes with the FPU control word.
	// Set single precision floating point math.
	streflop_init<streflop::Simple>();

	if (FSAA) {
 		FSAA = MultisampleVerify();
	}

	// setup GL smoothing
	const int defaultSmooth = 0; // FSAA ? 0 : 3;  // until a few things get fixed
	const int lineSmoothing = configHandler.GetInt("SmoothLines", defaultSmooth);
	if (lineSmoothing > 0) {
		GLenum hint = GL_FASTEST;
		if (lineSmoothing >= 3) {
			hint = GL_NICEST;
		} else if (lineSmoothing >= 2) {
			hint = GL_DONT_CARE;
		}
		glEnable(GL_LINE_SMOOTH);
		glHint(GL_LINE_SMOOTH_HINT, hint);
	}
	const int pointSmoothing = configHandler.GetInt("SmoothPoints", defaultSmooth);
	if (pointSmoothing > 0) {
		GLenum hint = GL_FASTEST;
		if (pointSmoothing >= 3) {
			hint = GL_NICEST;
		} else if (pointSmoothing >= 2) {
			hint = GL_DONT_CARE;
		}
		glEnable(GL_POINT_SMOOTH);
		glHint(GL_POINT_SMOOTH_HINT, hint);
	}

	SetVSync();

	// there must be a way to see if this is necessary, compare old/new context pointers?
	if (!!configHandler.GetInt("FixAltTab", 0)) {
		// free GL resources
		GLContext::Free();

		// initialize any GL resources that were lost
		GLContext::Init();
	}

	// initialize the stencil
	glClearStencil(0);
	glClear(GL_STENCIL_BUFFER_BIT); SDL_GL_SwapBuffers();
	glClear(GL_STENCIL_BUFFER_BIT); SDL_GL_SwapBuffers();

	return true;
}
void EDA_3D_CANVAS::Redraw()
{
    // SwapBuffer requires the window to be shown before calling
    if( !IsShown() )
        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

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

}
예제 #9
0
inline void clear(int s)
{
	glClearStencil(s);
}
예제 #10
0
파일: Cre8Render.cpp 프로젝트: xoorath/cre8
  void Cre8Render::InitializeLambdas()
  {
    // Here we provide the fetch methods for these variables. We will only need to fetch the values if they're requested.
    MultiTexturingSupported.SetMethod(  [](c8bool& out) {       out = GLEW_ARB_multitexture;});
    VersionMinor.SetMethod(             [](si32& out) {         glGetIntegerv(GL_MINOR_VERSION, &out); });
    VersionMajor.SetMethod(             [](si32& out) {         glGetIntegerv(GL_MAJOR_VERSION, &out); });
    MaxTextureUnits.SetMethod(          [](si32& out) {         glGetIntegerv(GL_MAX_TEXTURE_UNITS, &out); });
    MaxTextureSize.SetMethod(           [](si32& out) {         glGetIntegerv(GL_MAX_TEXTURE_SIZE, &out); });
    GLSLVersion.SetMethod(              [](const char*& out) {  out = (char*)glGetString(GL_SHADING_LANGUAGE_VERSION); });
    GLEWVersion.SetMethod(              [](const char*& out) {  out = (char*)glewGetString(GLEW_VERSION); });

    m_Textures = new Cre8RenderValue<tTextureID>[MaxTextureUnits.GetValue()];

    Cre8RenderValue<tTextureID>* a = &m_Textures[0];
    Cre8RenderValue<tTextureID>* b = &m_Textures[1];
    Cre8RenderValue<tTextureID>* c = &m_Textures[2];

    for(si32 i = 0; i < MaxTextureUnits.GetValue(); ++i)
    {
      const int ci = i;
      auto textureFunc = [ci](const tTextureID& val) 
      {
        if(g_Cre8Render->MultiTexturingSupported == true)
        {
          glActiveTextureARB(GL_TEXTURE0_ARB + ci);
          glEnable(GL_ARB_texture_non_power_of_two);
          glBindTexture(GL_ARB_texture_non_power_of_two, val);
        }
        else
        {
          glBindTexture(GL_TEXTURE_2D, val);
        }
      };
      m_Textures[i].SetMethod(0, textureFunc);
    }

    ClearAccum.SetMethod(ColorRGBf(0, 0, 0),  [](const ColorRGBf& val) {  glClearAccum(val[0], val[1], val[2], 1.f); });
    ClearColor.SetMethod(ColorRGBf(0, 0, 0),  [](const ColorRGBf& val) {  glClearColor(val[0], val[1], val[2], 1.f); });
    ClearDepth.SetMethod(1.f,                 [](const r32& val) {        glClearDepth((double)val); });
    ClearIndex.SetMethod(1.f,                 [](const r32& val) {        glClearIndex(val); });
    ClearStencil.SetMethod(0,                 [](const si32& val) {       glClearStencil(val); });
    
    EnableAttribute.AlphaTest.SetMethod(false,            enableBitLambda(GL_ALPHA_TEST));
    EnableAttribute.AutoNormal.SetMethod(false,           enableBitLambda(GL_AUTO_NORMAL));
    EnableAttribute.Blend.SetMethod(false,                enableBitLambda(GL_BLEND));
    EnableAttribute.colorMaterial.SetMethod(false,        enableBitLambda(GL_COLOR_MATERIAL));
    EnableAttribute.CullFace.SetMethod(false,             enableBitLambda(GL_CULL_FACE));
    EnableAttribute.DepthTest.SetMethod(false,            enableBitLambda(GL_DEPTH_TEST));
    EnableAttribute.Dither.SetMethod(false,               enableBitLambda(GL_DITHER));
    EnableAttribute.Fog.SetMethod(false,                  enableBitLambda(GL_FOG));
    EnableAttribute.Lighting.SetMethod(false,             enableBitLambda(GL_LIGHTING));
    EnableAttribute.LineSmooth.SetMethod(false,           enableBitLambda(GL_LINE_SMOOTH));
    EnableAttribute.LineStipple.SetMethod(false,          enableBitLambda(GL_LINE_STIPPLE));
    EnableAttribute.ColorLogicOp.SetMethod(false,         enableBitLambda(GL_COLOR_LOGIC_OP));
    EnableAttribute.IndexLogicOp.SetMethod(false,         enableBitLambda(GL_INDEX_LOGIC_OP));
    EnableAttribute.Normalize.SetMethod(false,            enableBitLambda(GL_NORMALIZE));
    EnableAttribute.PointSmooth.SetMethod(false,          enableBitLambda(GL_POINT_SMOOTH));
    EnableAttribute.PolygonOffsetLine.SetMethod(false,    enableBitLambda(GL_POLYGON_OFFSET_LINE));
    EnableAttribute.PolygonOffsetFill.SetMethod(false,    enableBitLambda(GL_POLYGON_OFFSET_FILL));
    EnableAttribute.PolygonOffsetPoint.SetMethod(false,   enableBitLambda(GL_POLYGON_OFFSET_POINT));
    EnableAttribute.PolygonSmooth.SetMethod(false,        enableBitLambda(GL_POLYGON_SMOOTH));
    EnableAttribute.PolygonStipple.SetMethod(false,       enableBitLambda(GL_POLYGON_STIPPLE));
    EnableAttribute.ScissorTest.SetMethod(false,          enableBitLambda(GL_SCISSOR_TEST));
    EnableAttribute.StencilTest.SetMethod(false,          enableBitLambda(GL_STENCIL_TEST));
    EnableAttribute.Texture1d.SetMethod(false,            enableBitLambda(GL_TEXTURE_1D));
    EnableAttribute.Texture2d.SetMethod(false,            enableBitLambda(GL_TEXTURE_2D));
  }
예제 #11
0
void RendererBase::ClearStencil(int stencil)
{
    glClearStencil(stencil);
}
void TextureBackground::clear(DrawEnv  *pEnv)
{
#if !defined(OSG_OGL_COREONLY) || defined(OSG_CHECK_COREONLY)
    TextureBaseChunk *tex = getTexture();

    if(tex == NULL)
    {
        glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        return;
    }

    glPushAttrib(GL_POLYGON_BIT | GL_DEPTH_BUFFER_BIT | 
                 GL_LIGHTING_BIT);

    glDisable(GL_LIGHTING);

#if 1
    // original mode
    glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
#else
    // for testing the grid
    glColor3f(1.0f, 1.0f, 1.0f);
    glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
#endif
    glClear(GL_DEPTH_BUFFER_BIT);

    glDisable(GL_DEPTH_TEST);
    glDepthFunc(GL_ALWAYS);
    glDepthMask(GL_FALSE);

    glMatrixMode(GL_MODELVIEW);
    glPushMatrix();
    glLoadIdentity();

    glMatrixMode(GL_PROJECTION);
    glPushMatrix();

    glLoadIdentity();
    glOrtho(0, 1, 0, 1, 0, 1);

    glColor4fv(getColor().getValuesRGBA());

    tex->activate(pEnv);

    if(tex->isTransparent())
    {
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
        glEnable(GL_BLEND);
    }
    if(osgAbs(getRadialDistortion()) < TypeTraits<Real32>::getDefaultEps())
    {
	    if(getMFTexCoords()->size() < 4)
	    {
	        // set some default texture coordinates.
	        glBegin(GL_QUADS);
                glTexCoord2f(0.0f, 0.0f);
                glVertex3f(0.0f, 0.0f, 0.0f);
                glTexCoord2f(1.0f, 0.0f);
                glVertex3f(1.0f, 0.0f, 0.0f);
                glTexCoord2f(1.0f, 1.0f);
                glVertex3f(1.0f, 1.0f, 0.0f);
                glTexCoord2f(0.0f, 1.0f);
                glVertex3f(0.0f, 1.0f, 0.0f);
	        glEnd();
	    }
	    else
	    {
	        glBegin(GL_QUADS);
            {
                glTexCoord2f(getTexCoords(0).getValues()[0],
                             getTexCoords(0).getValues()[1]);
                glVertex3f(0.0f, 0.0f, 0.0f);
                glTexCoord2f(getTexCoords(1).getValues()[0],
                             getTexCoords(1).getValues()[1]);
                glVertex3f(1.0f, 0.0f, 0.0f);
                glTexCoord2f(getTexCoords(2).getValues()[0],
                             getTexCoords(2).getValues()[1]);
                glVertex3f(1.0f, 1.0f, 0.0f);
                glTexCoord2f(getTexCoords(3).getValues()[0],
                             getTexCoords(3).getValues()[1]);
                glVertex3f(0.0f, 1.0f, 0.0f);
            }
	        glEnd();
	    }
    }
    else // map texture to distortion grid
    {
        updateGrid();
	    Int16 xxmax=getHor()+2,yymax=getVert()+2;

	    UInt32 gridCoords=xxmax*yymax;
	    UInt32 indexArraySize=xxmax*((getVert()+1)*2);

	    if(_vertexCoordArray.size()==gridCoords &&
	       _textureCoordArray.size()==gridCoords &&
	       _indexArray.size()==indexArraySize)
	    {
	        // clear background, because possibly the distortion grid 
            // could not cover th whole window
	        glClearColor(.5f, 0.5f, 0.5f, 1.0f);
	        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	        std::vector<UInt32>::iterator i;
	        UInt32 yMax=getVert()+1;
	        for(UInt32 y=0;y<yMax;y++)
	        {
		        glBegin(GL_TRIANGLE_STRIP);
		        std::vector<UInt32>::iterator begin=_indexArray.begin()+(y*2*xxmax);
		        std::vector<UInt32>::iterator end=begin+2*xxmax;
		        for(std::vector<UInt32>::iterator i=begin;i!=end;i++)
		        {
		            glTexCoord2fv(_textureCoordArray[*i].getValues());
		            glVertex2fv(_vertexCoordArray[*i].getValues());

		        }
		        glEnd();
	        }
	    }
    }
    if(tex->isTransparent())
    {
        glDisable(GL_BLEND);
    }

    tex->deactivate(pEnv);

    Int32 bit = getClearStencilBit();
    
    if (bit >= 0)
    {
        glClearStencil(bit);
        glClear(GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
    }
    else
    {
        glClear(GL_DEPTH_BUFFER_BIT);
    }

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

    glPopAttrib();

    glColor3f(1.0f, 1.0f, 1.0f);
#endif
}
예제 #13
0
void StereoPainter::paint() {
	int width = getCanvas()->getSize().x;
	int height = getCanvas()->getSize().y;

	// Special handling for side-by-side stereo
	if (stereoMode_ == SIDE_BY_SIDE) {
		getCamera()->setRatio(float(width / 2) / height);
	}

	// Add headtracking offset
	if (trackingEnabled_ && headTracker_) {
		headTracker_->adaptCameraToHead();
	}

    switch (stereoMode_) {
		default: 
            // Falls through..
		case MONOSCOPIC:
			{
				glDrawBuffer(GL_BACK);
				glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

				// Render middle view
				// NOTE: Special headtracking frustums might require the stereo handling process
				// of the camera look() method so we set the eye separation to 0 and render
				// the left eye view instead of just:
				// getCamera()->look(Camera::EYE_MIDDLE);
				float initialEyeSep = getCamera()->getEyeSeparation();
				getCamera()->setEyeSeparation(0);
				getCamera()->look(Camera::EYE_LEFT);
				getCamera()->setEyeSeparation(initialEyeSep);
				render();
			}
			break;

		case FRAME_SEQUENTIAL:

            glDrawBuffer(GL_BACK);
			glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

			// Render left eye view
			getCamera()->look(Camera::EYE_LEFT);
			render();

			getCanvas()->swap();

			// Render right eye view
			getCamera()->look(Camera::EYE_RIGHT);
			render();

			// For continuous rendering refresh canvas
			getCanvas()->update();
			break;

		case SIDE_BY_SIDE:
  
            glDrawBuffer(GL_BACK);   
			glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

			// Render left eye view
			glViewport(0, 0, width / 2, height);
			getCamera()->look(Camera::EYE_LEFT);
			render();

			// Render right eye view
			glViewport(width / 2, 0, width / 2, height);
			getCamera()->look(Camera::EYE_RIGHT);
			render();

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

		case ANAGLYPH:

            glDrawBuffer(GL_BACK);
			glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

			// Render left eye view
			glColorMask(GL_TRUE, GL_FALSE, GL_FALSE, GL_TRUE);
			getCamera()->look(Camera::EYE_LEFT);
			render();

			glClear(GL_DEPTH_BUFFER_BIT);

			// Render right eye view
			glColorMask(GL_FALSE, GL_FALSE, GL_TRUE, GL_TRUE);
			getCamera()->look(Camera::EYE_RIGHT);
			render();


			glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
			break;

		case QUADRO_PAGE_FLIPPING:
			// Render left eye view
    		glDrawBuffer(GL_BACK_LEFT);
			glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
			getCamera()->look(Camera::EYE_LEFT);
			render();

			// Render right eye view
			glDrawBuffer(GL_BACK_RIGHT);
			glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
			getCamera()->look(Camera::EYE_RIGHT);
			render();
	
			break;

	   case VERTICAL_INTERLACED: 
			glDisable(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
			glDisable(GL_LIGHTING);
			glDisable(GL_DEPTH_TEST);

			glEnable(GL_STENCIL_TEST);
			glClearStencil(0);
			glClear(GL_STENCIL_BUFFER_BIT);
			glStencilMask(0xFFFFFFFF);
			glStencilFunc(GL_ALWAYS, 1, 0xFFFFFFFF);
			glStencilOp(GL_REPLACE, GL_REPLACE, GL_REPLACE);

			glMatrixMode(GL_PROJECTION);
			glPushMatrix();
				glLoadIdentity();
				glOrtho(0, width, 0, height, -1, 1);

				glMatrixMode(GL_MODELVIEW);
				glPushMatrix();
				glLoadIdentity();
					glBegin(GL_LINES);
					for(int x = 0; x < width; x += 2) {
						glVertex2i(x, 0);
						glVertex2i(x, height);
					}
					glEnd();
				glPopMatrix();

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

			glEnable(GL_LIGHTING);
			glEnable(GL_DEPTH_TEST);
			glEnable(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
			glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);

			glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

			// Render right eye view
			getCamera()->look(Camera::EYE_RIGHT);
			glStencilFunc(GL_EQUAL, 1, 0xFFFFFFFF);
			render();
			
			// Render left eye view
			getCamera()->look(Camera::EYE_LEFT);
			glStencilFunc(GL_EQUAL, 0, 0xFFFFFFFF);
			render();

			glDisable(GL_STENCIL_TEST);
			break;
	}

	// Reset camera
	if (trackingEnabled_ && headTracker_) {
		headTracker_->resetCamera();
	}

  	// Special handling for side-by-side stereo
	if (stereoMode_ == SIDE_BY_SIDE) {
		getCamera()->setRatio((float)width / height);
	}
}
예제 #14
0
static void
add_stencil_clip_rectangle (CoglFramebuffer *framebuffer,
                            CoglMatrixEntry *modelview_entry,
                            float x_1,
                            float y_1,
                            float x_2,
                            float y_2,
                            CoglBool first)
{
  CoglMatrixStack *projection_stack =
    _cogl_framebuffer_get_projection_stack (framebuffer);
  CoglContext *ctx = cogl_framebuffer_get_context (framebuffer);

  /* NB: This can be called while flushing the journal so we need
   * to be very conservative with what state we change.
   */

  _cogl_context_set_current_projection_entry (ctx,
                                              projection_stack->last_entry);
  _cogl_context_set_current_modelview_entry (ctx, modelview_entry);

  if (first)
    {
      GE( ctx, glEnable (GL_STENCIL_TEST) );

      /* Initially disallow everything */
      GE( ctx, glClearStencil (0) );
      GE( ctx, glClear (GL_STENCIL_BUFFER_BIT) );

      /* Punch out a hole to allow the rectangle */
      GE( ctx, glStencilFunc (GL_NEVER, 0x1, 0x1) );
      GE( ctx, glStencilOp (GL_REPLACE, GL_REPLACE, GL_REPLACE) );

      _cogl_rectangle_immediate (framebuffer,
                                 ctx->stencil_pipeline,
                                 x_1, y_1, x_2, y_2);
    }
  else
    {
      /* Add one to every pixel of the stencil buffer in the
	 rectangle */
      GE( ctx, glStencilFunc (GL_NEVER, 0x1, 0x3) );
      GE( ctx, glStencilOp (GL_INCR, GL_INCR, GL_INCR) );
      _cogl_rectangle_immediate (framebuffer,
                                 ctx->stencil_pipeline,
                                 x_1, y_1, x_2, y_2);

      /* Subtract one from all pixels in the stencil buffer so that
	 only pixels where both the original stencil buffer and the
	 rectangle are set will be valid */
      GE( ctx, glStencilOp (GL_DECR, GL_DECR, GL_DECR) );

      _cogl_context_set_current_projection_entry (ctx, &ctx->identity_entry);
      _cogl_context_set_current_modelview_entry (ctx, &ctx->identity_entry);

      _cogl_rectangle_immediate (framebuffer,
                                 ctx->stencil_pipeline,
                                 -1.0, -1.0, 1.0, 1.0);
    }

  /* Restore the stencil mode */
  GE( ctx, glStencilFunc (GL_EQUAL, 0x1, 0x1) );
  GE( ctx, glStencilOp (GL_KEEP, GL_KEEP, GL_KEEP) );
}
예제 #15
0
bool SkEGLContext::init(const int width, const int height) {
    HINSTANCE hInstance = (HINSTANCE)GetModuleHandle(NULL);

    WNDCLASS wc;
    wc.cbClsExtra = 0;
    wc.cbWndExtra = 0;
    wc.hbrBackground = NULL;
    wc.hCursor = LoadCursor(NULL, IDC_ARROW);
    wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
    wc.hInstance = hInstance;
    wc.lpfnWndProc = (WNDPROC) DefWindowProc;
    wc.lpszClassName = TEXT("Griffin");
    wc.lpszMenuName = NULL;
    wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
 
    if (!RegisterClass(&wc)) {
        SkDebugf("Could not register window class.\n");
        return false;
    }

    if (!(
        this->fWindow = CreateWindow(
        TEXT("Griffin"),
        TEXT("The Invisible Man"),
        WS_OVERLAPPEDWINDOW,
        10, 10,                 // x, y
        200, 200,               // width, height
        NULL, NULL,             // parent, menu
        hInstance, NULL)        // hInstance, param
        ))
    {
        SkDebugf("Could not create window.\n");
        return false;
    }

    if (!(this->fDeviceContext = GetDC(this->fWindow))) {
        SkDebugf("Could not get device context.\n");
        return false;
    }
    
    PIXELFORMATDESCRIPTOR pfd;
    ZeroMemory(&pfd, sizeof(pfd));
    pfd.nSize = sizeof(pfd);
    pfd.nVersion = 1;
    pfd.dwFlags = PFD_DRAW_TO_WINDOW |
                  PFD_SUPPORT_OPENGL |
                  PFD_DOUBLEBUFFER;
    pfd.iPixelType = PFD_TYPE_RGBA;
    pfd.cColorBits = 32;
    pfd.cDepthBits = 24;
    pfd.cStencilBits = 8;
    pfd.iLayerType = PFD_MAIN_PLANE;
    
    int pixelFormat = 0;
    if (!(pixelFormat = ChoosePixelFormat(this->fDeviceContext, &pfd))) {
	    SkDebugf("No matching pixel format descriptor.\n");
        return false;
    }
    
    if (!SetPixelFormat(this->fDeviceContext, pixelFormat, &pfd)) {
	    SkDebugf("Could not set the pixel format %d.\n", pixelFormat);
        return false;
    }
    
    if (!(this->fGlRenderContext = wglCreateContext(this->fDeviceContext))) {
	    SkDebugf("Could not create rendering context.\n");
        return false;
    }

    if (!(wglMakeCurrent(this->fDeviceContext, this->fGlRenderContext))) {
        SkDebugf("Could not set the context.\n");
        return false;
    }

    //TODO: in the future we need to use this context
    // to test for WGL_ARB_create_context
    // and then create a new window / context.

    //Setup the framebuffers
    const char* glExts =
        reinterpret_cast<const char *>(glGetString(GL_EXTENSIONS));
    if (!skEGLCheckExtension(
          "GL_EXT_framebuffer_object"
          , glExts))
    {
        SkDebugf("GL_EXT_framebuffer_object not found.\n");
        return false;
    }
    SK_EGL_DECLARE_PROC(GenFramebuffers)
    SK_EGL_DECLARE_PROC(BindFramebuffer)
    SK_EGL_DECLARE_PROC(GenRenderbuffers)
    SK_EGL_DECLARE_PROC(BindRenderbuffer)
    SK_EGL_DECLARE_PROC(RenderbufferStorage)
    SK_EGL_DECLARE_PROC(FramebufferRenderbuffer)
    SK_EGL_DECLARE_PROC(CheckFramebufferStatus)

    SK_EGL_GET_PROC_SUFFIX(GenFramebuffers, EXT)
    SK_EGL_GET_PROC_SUFFIX(BindFramebuffer, EXT)
    SK_EGL_GET_PROC_SUFFIX(GenRenderbuffers, EXT)
    SK_EGL_GET_PROC_SUFFIX(BindRenderbuffer, EXT)
    SK_EGL_GET_PROC_SUFFIX(RenderbufferStorage, EXT)
    SK_EGL_GET_PROC_SUFFIX(FramebufferRenderbuffer, EXT)
    SK_EGL_GET_PROC_SUFFIX(CheckFramebufferStatus, EXT)

    GLuint cbID;
    GLuint dsID;
    SkEGLGenFramebuffers(1, &fFBO);
    SkEGLBindFramebuffer(SK_EGL_FRAMEBUFFER, fFBO);
    SkEGLGenRenderbuffers(1, &cbID);
    SkEGLBindRenderbuffer(SK_EGL_RENDERBUFFER, cbID);
    SkEGLRenderbufferStorage(SK_EGL_RENDERBUFFER, GL_RGBA, width, height);
    SkEGLFramebufferRenderbuffer(SK_EGL_FRAMEBUFFER
                                 , SK_EGL_COLOR_ATTACHMENT0
                                 , SK_EGL_RENDERBUFFER, cbID);
    SkEGLGenRenderbuffers(1, &dsID);
    SkEGLBindRenderbuffer(SK_EGL_RENDERBUFFER, dsID);
    SkEGLRenderbufferStorage(SK_EGL_RENDERBUFFER, SK_EGL_DEPTH_STENCIL
                             , width, height);
    SkEGLFramebufferRenderbuffer(SK_EGL_FRAMEBUFFER
                                 , SK_EGL_DEPTH_STENCIL_ATTACHMENT
                                 , SK_EGL_RENDERBUFFER
                                 , dsID);
    glViewport(0, 0, width, height);
    glClearStencil(0);
    glClear(GL_STENCIL_BUFFER_BIT);

    GLenum status = SkEGLCheckFramebufferStatus(SK_EGL_FRAMEBUFFER);
    return SK_EGL_FRAMEBUFFER_COMPLETE == status;
}
예제 #16
0
파일: Main.cpp 프로젝트: gazandic/GrafikaGL
void render(void)
{
    glMatrixMode(GL_MODELVIEW);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    //initial position // Move right and into the screen
    for (int i = 0; i < 27; i++)
    {
        glLoadIdentity();
        glRotatef(xRotated, 0.3, 0.0, 0.0);
        // // rotation about Y axis
        glRotatef(yRotated, 0.0, 0.3, 0.0);
        // rotation about Z axis
        glRotatef(zRotated, 0.0, 0.0, 0.3);
        glTranslatef(list[i].getX(), list[i].getY(), list[i].getZ());
        glRotatef(list[i].getXRotated(), 0.3, 0.0, 0.0);
        // // rotation about Y axis
        glRotatef(list[i].getYRotated(), 0.0, 0.3, 0.0);
        // rotation about Z axis
        glRotatef(list[i].getZRotated(), 0.0, 0.0, 0.3);

        glClearStencil(0);
        glClear(GL_STENCIL_BUFFER_BIT);

        // Render the thick wireframe version.

        glStencilFunc(GL_NOTEQUAL, 1, 0xFFFF);
        glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);

        glLineWidth(3);
        glPolygonMode(GL_FRONT, GL_LINE);
        glColor3f(1.0f, 1.0f, 1.0f);
        glBegin(GL_QUADS); // Begin drawing the color cube with 6 quads
        // Top face (y = 0.3f)
        // Define vertices in counter-clockwise (CCW) order with normal pointing out
        glColor3f(1.0f, 1.0f, 0.0f); // Yellow

        //glGenTextures( 1, &texture1 );
        glBindTexture(GL_TEXTURE_2D, texture1);
        glTexCoord2d(0.0, 0.0);
        glVertex3f(fsize, fsize, -fsize);
        glTexCoord2d(1.0, 0.0);
        glVertex3f(-fsize, fsize, -fsize);
        glTexCoord2d(0.0, 1.0);
        glVertex3f(-fsize, fsize, fsize);
        glTexCoord2d(1.0, 1.0);
        glVertex3f(fsize, fsize, fsize);
        // Bottom face (y = -fsize)
        glColor3f(1.0f, 1.0f, 1.0f); // White
        //glGenTextures( 1, &texture2 );

        glTexCoord2d(0.0, 0.0);
        glVertex3f(fsize, -fsize, fsize);
        glTexCoord2d(0.0, 1.0);
        glVertex3f(-fsize, -fsize, fsize);
        glTexCoord2d(1.0, 0.0);
        glVertex3f(-fsize, -fsize, -fsize);
        glTexCoord2d(1.0, 1.0);
        glVertex3f(fsize, -fsize, -fsize);
        // Front face  (z = fsize)
        glColor3f(1.0f, 0.0f, 0.0f); // Red
        glTexCoord2d(0.0, 0.0);
        glVertex3f(fsize, fsize, fsize);
        glTexCoord2d(0.0, 1.0);
        glVertex3f(-fsize, fsize, fsize);
        glTexCoord2d(1.0, 0.0);
        glVertex3f(-fsize, -fsize, fsize);
        glTexCoord2d(1.0, 1.0);
        glVertex3f(fsize, -fsize, fsize);

        // Back face (z = -fsize)
        glColor3f(1.0f, 0.5f, 0.0f); // Orange
        glTexCoord2d(0.0, 0.0);
        glVertex3f(fsize, -fsize, -fsize);
        glTexCoord2d(0.0, 1.0);
        glVertex3f(-fsize, -fsize, -fsize);
        glTexCoord2d(1.0, 0.0);
        glVertex3f(-fsize, fsize, -fsize);
        glTexCoord2d(1.0, 1.0);
        glVertex3f(fsize, fsize, -fsize);

        // Left face (x = -fsize)
        glColor3f(0.0f, 0.0f, 1.0f); // Blue
        glTexCoord2d(0.0, 0.0);
        glVertex3f(-fsize, fsize, fsize);
        glTexCoord2d(0.0, 1.0);
        glVertex3f(-fsize, fsize, -fsize);
        glTexCoord2d(1.0, 0.0);
        glVertex3f(-fsize, -fsize, -fsize);
        glTexCoord2d(1.0, 1.0);
        glVertex3f(-fsize, -fsize, fsize);

        // Right face (x = fsize)
        glColor3f(0.0f, 1.0f, 0.0f); // Green
        glTexCoord2d(0.0, 0.0);
        glVertex3f(fsize, fsize, -fsize);
        glTexCoord2d(0.0, 1.0);
        glVertex3f(fsize, fsize, fsize);
        glTexCoord2d(1.0, 0.0);
        glVertex3f(fsize, -fsize, fsize);
        glTexCoord2d(1.0, 1.0);
        glVertex3f(fsize, -fsize, -fsize);

        glEnd(); // End of drawing color-cube
    }

    glutSwapBuffers();
}
예제 #17
0
void ClearRenderContext (TColor col) {
	glDepthMask (GL_TRUE);
	glClearColor (col.r, col.g, col.b, col.a);
	glClearStencil (0);
	glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
}
예제 #18
0
// this is the code that actually draws the window
// it puts a lot of the work into other routines to simplify things
void TrainView::draw()
{
	glViewport(0,0,w(),h());

	// clear the window, be sure to clear the Z-Buffer too
	glClearColor(0,0,.3f,0);		// background should be blue
	// we need to clear out the stencil buffer since we'll use
	// it for shadows
	glClearStencil(0);
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
	glEnable(GL_DEPTH);

	// Blayne prefers GL_DIFFUSE
    glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);

	// prepare for projection
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	setProjection();		// put the code to set up matrices here

	// TODO: you might want to set the lighting up differently
	// if you do, 
	// we need to set up the lights AFTER setting up the projection

	// enable the lighting
	glEnable(GL_COLOR_MATERIAL);
	glEnable(GL_DEPTH_TEST);
	glEnable(GL_LIGHTING);
	glEnable(GL_LIGHT0);
	// top view only needs one light
	if (tw->topCam->value()) {
		glDisable(GL_LIGHT1);
		glDisable(GL_LIGHT2);
	} else {
		glEnable(GL_LIGHT1);
		glEnable(GL_LIGHT2);
	}
	// set the light parameters
	GLfloat lightPosition1[] = {0,1,1,0}; // {50, 200.0, 50, 1.0};
	GLfloat lightPosition2[] = {1, 0, 0, 0};
	GLfloat lightPosition3[] = {0, -1, 0, 0};
	GLfloat yellowLight[] = {0.5f, 0.5f, .1f, 1.0};
	GLfloat whiteLight[] = {1.0f, 1.0f, 1.0f, 1.0};
	GLfloat blueLight[] = {.1f,.1f,.3f,1.0};
	GLfloat grayLight[] = {.3f, .3f, .3f, 1.0};

	glLightfv(GL_LIGHT0, GL_POSITION, lightPosition1);
	glLightfv(GL_LIGHT0, GL_DIFFUSE, whiteLight);
	glLightfv(GL_LIGHT0, GL_AMBIENT, grayLight);

	glLightfv(GL_LIGHT1, GL_POSITION, lightPosition2);
	glLightfv(GL_LIGHT1, GL_DIFFUSE, yellowLight);

	glLightfv(GL_LIGHT2, GL_POSITION, lightPosition3);
	glLightfv(GL_LIGHT2, GL_DIFFUSE, blueLight);



	// now draw the ground plane
	setupFloor();
	glDisable(GL_LIGHTING);
	drawFloor(200,10);
	glEnable(GL_LIGHTING);
	setupObjects();

	// we draw everything twice - once for real, and then once for
	// shadows
	drawStuff();

	// this time drawing is for shadows (except for top view)
	if (!tw->topCam->value()) {
		setupShadows();
		drawStuff(true);
		unsetupShadows();
	}
	
}
예제 #19
0
QSGRenderer::ClipType QSGRenderer::updateStencilClip(const QSGClipNode *clip)
{
    if (!clip) {
        glDisable(GL_STENCIL_TEST);
        glDisable(GL_SCISSOR_TEST);
        return NoClip;
    }

    ClipType clipType = NoClip;

    glDisable(GL_SCISSOR_TEST);

    m_current_stencil_value = 0;
    m_current_scissor_rect = QRect();
    while (clip) {
        QMatrix4x4 m = m_current_projection_matrix;
        if (clip->matrix())
            m *= *clip->matrix();

        // TODO: Check for multisampling and pixel grid alignment.
        bool isRectangleWithNoPerspective = clip->isRectangular()
                && qFuzzyIsNull(m(3, 0)) && qFuzzyIsNull(m(3, 1));
        bool noRotate = qFuzzyIsNull(m(0, 1)) && qFuzzyIsNull(m(1, 0));
        bool isRotate90 = qFuzzyIsNull(m(0, 0)) && qFuzzyIsNull(m(1, 1));

        if (isRectangleWithNoPerspective && (noRotate || isRotate90)) {
            QRectF bbox = clip->clipRect();
            qreal invW = 1 / m(3, 3);
            qreal fx1, fy1, fx2, fy2;
            if (noRotate) {
                fx1 = (bbox.left() * m(0, 0) + m(0, 3)) * invW;
                fy1 = (bbox.bottom() * m(1, 1) + m(1, 3)) * invW;
                fx2 = (bbox.right() * m(0, 0) + m(0, 3)) * invW;
                fy2 = (bbox.top() * m(1, 1) + m(1, 3)) * invW;
            } else {
                Q_ASSERT(isRotate90);
                fx1 = (bbox.bottom() * m(0, 1) + m(0, 3)) * invW;
                fy1 = (bbox.left() * m(1, 0) + m(1, 3)) * invW;
                fx2 = (bbox.top() * m(0, 1) + m(0, 3)) * invW;
                fy2 = (bbox.right() * m(1, 0) + m(1, 3)) * invW;
            }

            if (fx1 > fx2)
                qSwap(fx1, fx2);
            if (fy1 > fy2)
                qSwap(fy1, fy2);

            GLint ix1 = qRound((fx1 + 1) * m_device_rect.width() * qreal(0.5));
            GLint iy1 = qRound((fy1 + 1) * m_device_rect.height() * qreal(0.5));
            GLint ix2 = qRound((fx2 + 1) * m_device_rect.width() * qreal(0.5));
            GLint iy2 = qRound((fy2 + 1) * m_device_rect.height() * qreal(0.5));

            if (!(clipType & ScissorClip)) {
                m_current_scissor_rect = QRect(ix1, iy1, ix2 - ix1, iy2 - iy1);
                glEnable(GL_SCISSOR_TEST);
                clipType |= ScissorClip;
            } else {
                m_current_scissor_rect &= QRect(ix1, iy1, ix2 - ix1, iy2 - iy1);
            }
            glScissor(m_current_scissor_rect.x(), m_current_scissor_rect.y(),
                      m_current_scissor_rect.width(), m_current_scissor_rect.height());
        } else {
            if (!(clipType & StencilClip)) {
                if (!m_clip_program.isLinked()) {
                    m_clip_program.addShaderFromSourceCode(QOpenGLShader::Vertex,
                        "attribute highp vec4 vCoord;       \n"
                        "uniform highp mat4 matrix;         \n"
                        "void main() {                      \n"
                        "    gl_Position = matrix * vCoord; \n"
                        "}");
                    m_clip_program.addShaderFromSourceCode(QOpenGLShader::Fragment,
                        "void main() {                                   \n"
                        "    gl_FragColor = vec4(0.81, 0.83, 0.12, 1.0); \n" // Trolltech green ftw!
                        "}");
                    m_clip_program.bindAttributeLocation("vCoord", 0);
                    m_clip_program.link();
                    m_clip_matrix_id = m_clip_program.uniformLocation("matrix");
                }

                glClearStencil(0);
                glClear(GL_STENCIL_BUFFER_BIT);
                glEnable(GL_STENCIL_TEST);
                glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
                glDepthMask(GL_FALSE);

                if (m_vertex_buffer_bound) {
                    glBindBuffer(GL_ARRAY_BUFFER, 0);
                    m_vertex_buffer_bound = false;
                }
                if (m_index_buffer_bound) {
                    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
                    m_index_buffer_bound = false;
                }

                m_clip_program.bind();
                m_clip_program.enableAttributeArray(0);

                clipType |= StencilClip;
            }

            glStencilFunc(GL_EQUAL, m_current_stencil_value, 0xff); // stencil test, ref, test mask
            glStencilOp(GL_KEEP, GL_KEEP, GL_INCR); // stencil fail, z fail, z pass

            const QSGGeometry *g = clip->geometry();
            Q_ASSERT(g->attributeCount() > 0);
            const QSGGeometry::Attribute *a = g->attributes();
            glVertexAttribPointer(0, a->tupleSize, a->type, GL_FALSE, g->sizeOfVertex(), g->vertexData());

            m_clip_program.setUniformValue(m_clip_matrix_id, m);
            if (g->indexCount()) {
                glDrawElements(g->drawingMode(), g->indexCount(), g->indexType(), g->indexData());
            } else {
                glDrawArrays(g->drawingMode(), 0, g->vertexCount());
            }

            ++m_current_stencil_value;
        }

        clip = clip->clipList();
    }

    if (clipType & StencilClip) {
        m_clip_program.disableAttributeArray(0);
        glStencilFunc(GL_EQUAL, m_current_stencil_value, 0xff); // stencil test, ref, test mask
        glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP); // stencil fail, z fail, z pass
        bindable()->reactivate();
    } else {
        glDisable(GL_STENCIL_TEST);
    }

    return clipType;
}
예제 #20
0
enum piglit_result
piglit_display(void)
{
	GLboolean pass = GL_TRUE;
	int i;
	static float red[]   = {1.0, 0.0, 0.0, 0.0};
	static float green[] = {0.0, 1.0, 0.0, 0.0};
	static float blue[]  = {0.0, 0.0, 1.0, 0.0};
	static float square[100];

	piglit_ortho_projection(piglit_width, piglit_height, GL_FALSE);

	/* whole window gray -- none should be visible */
	glClearColor(0.5, 0.5, 0.5, 0.0);
	glClear(GL_COLOR_BUFFER_BIT);

	/* Clear stencil to 0, which will be drawn red */
	glClearStencil(0);
	glClear(GL_STENCIL_BUFFER_BIT);

	/* quad at 10, 10 that will be drawn green. */
	for (i = 0; i < 100; i++)
		square[i] = 1.0;
	glRasterPos2i(10, 10);
	glDrawPixels(10, 10, GL_STENCIL_INDEX, GL_FLOAT, square);

	/* quad at 30, 10 that will be drawn blue. */
	for (i = 0; i < 100; i++)
		square[i] = 2.0;
	glRasterPos2i(30, 10);
	glDrawPixels(10, 10, GL_STENCIL_INDEX, GL_FLOAT, square);

	glDisable(GL_SCISSOR_TEST);
	glEnable(GL_STENCIL_TEST);
	glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);

	/* First quad -- stencil == 0 gets red */
	glStencilFunc(GL_EQUAL, 0, ~0);
	glColor4fv(red);
	piglit_draw_rect(0, 0, piglit_width, piglit_height);

	/* Second quad -- stencil == 1 gets green */
	glStencilFunc(GL_EQUAL, 1, ~0);
	glColor4fv(green);
	piglit_draw_rect(0, 0, piglit_width, piglit_height);

	/* Last quad -- stencil == 2 gets blue */
	glStencilFunc(GL_EQUAL, 2, ~0);
	glColor4fv(blue);
	piglit_draw_rect(0, 0, piglit_width, piglit_height);

	assert(glGetError() == 0);

	pass &= piglit_probe_rect_rgb(0, 0, piglit_width, 10, red);

	pass &= piglit_probe_rect_rgb(0, 10, 10, 10, red);
	pass &= piglit_probe_rect_rgb(10, 10, 10, 10, green);
	pass &= piglit_probe_rect_rgb(20, 10, 10, 10, red);
	pass &= piglit_probe_rect_rgb(30, 10, 10, 10, blue);
	pass &= piglit_probe_rect_rgb(40, 10, piglit_width-40, 10, red);

	pass &= piglit_probe_rect_rgb(0, 20, piglit_width, piglit_height - 20,
				      red);

	glutSwapBuffers();

	return pass ? PIGLIT_PASS : PIGLIT_FAIL;
}
예제 #21
0
/**
 * @param argc argument count
 * @param argv array of argument strings
 *
 * Executes the application
 * (contains main game loop)
 */
int SpringApp::Run (int argc, char *argv[])
{
	INIT_SYNCIFY;
	CheckCmdLineFile (argc, argv);
	cmdline = BaseCmd::initialize(argc,argv);

	if (!Initialize ())
		return -1;

#ifdef WIN32
	SDL_EventState (SDL_SYSWMEVENT, SDL_ENABLE);
#endif

	SDL_Event event;
	bool done = false;

	while (!done) {
		ENTER_UNSYNCED;
		while (SDL_PollEvent(&event)) {
			switch (event.type) {
				case SDL_VIDEORESIZE: {
					screenWidth = event.resize.w;
					screenHeight = event.resize.h;
#ifndef WIN32
					// HACK   We don't want to break resizing on windows (again?),
					//        so someone should test this very well before enabling it.
					SetSDLVideoMode();
#endif
					InitOpenGL();
					activeController->ResizeEvent();
					break;
				}
				case SDL_VIDEOEXPOSE: {
					// re-initialize the stencil
					glClearStencil(0);
					glClear(GL_STENCIL_BUFFER_BIT); SDL_GL_SwapBuffers();
					glClear(GL_STENCIL_BUFFER_BIT); SDL_GL_SwapBuffers();
					SetupViewportGeometry();
					break;
				}
				case SDL_QUIT: {
					done = true;
					break;
				}
				case SDL_ACTIVEEVENT: {
					if (event.active.state & SDL_APPACTIVE) {
						gu->active = !!event.active.gain;
					}
					break;
				}
				case SDL_MOUSEMOTION:
				case SDL_MOUSEBUTTONDOWN:
				case SDL_MOUSEBUTTONUP:
				case SDL_SYSWMEVENT: {
					mouseInput->HandleSDLMouseEvent (event);
					break;
				}
				case SDL_KEYDOWN: {
					int i = event.key.keysym.sym;
					
					const bool isRepeat = !!keys[i];

					UpdateSDLKeys ();

					if (activeController) {
						if (i <= SDLK_DELETE) {
							i = tolower(i);
						}
						else if (i == SDLK_RSHIFT) { i = SDLK_LSHIFT; }
						else if (i == SDLK_RCTRL)  { i = SDLK_LCTRL;  }
						else if (i == SDLK_RMETA)  { i = SDLK_LMETA;  }
						else if (i == SDLK_RALT)   { i = SDLK_LALT;   }
						
						if (keyBindings) {
							const int fakeMetaKey = keyBindings->GetFakeMetaKey();
							if (fakeMetaKey >= 0) {
								keys[SDLK_LMETA] |= keys[fakeMetaKey];
							}
						}

						activeController->KeyPressed(i,isRepeat);

#ifndef NEW_GUI
						if (activeController->userWriting){ 
							// use unicode for printed characters
							i = event.key.keysym.unicode;
							if ((i >= SDLK_SPACE) && (i <= SDLK_DELETE))
								if (activeController->ignoreNextChar ||
								    activeController->ignoreChar == char(i)) {
									activeController->ignoreNextChar = false;
								} else {
									activeController->userInput += char(i);
								}
						}
#endif
					}
					break;
				}
				case SDL_KEYUP: {
					int i = event.key.keysym.sym;

					UpdateSDLKeys();

					if (activeController) {
						if (i <= SDLK_DELETE) {
							i = tolower(i);
						}
						else if (i == SDLK_RSHIFT) { i = SDLK_LSHIFT; }
						else if (i == SDLK_RCTRL)  { i = SDLK_LCTRL;  }
						else if (i == SDLK_RMETA)  { i = SDLK_LMETA;  }
						else if (i == SDLK_RALT)   { i = SDLK_LALT;   }

						if (keyBindings) {
							const int fakeMetaKey = keyBindings->GetFakeMetaKey();
							if (fakeMetaKey >= 0) {
								keys[SDLK_LMETA] |= keys[fakeMetaKey];
							}
						}

						activeController->KeyReleased(i);
					}
					break;
				}
			}
		}
		if (globalQuit) 
			break;
	
		if (!Update())
			break;
	}
	ENTER_MIXED;

	// Shutdown
	Shutdown();
	return 0;
}
예제 #22
0
bool SpringApp::MainEventHandler(const SDL_Event& event)
{
	switch (event.type) {
		case SDL_VIDEORESIZE: {
			GML_MSTMUTEX_LOCK(sim); // MainEventHandler

			Watchdog::ClearTimer(WDT_MAIN, true);
			globalRendering->viewSizeX = event.resize.w;
			globalRendering->viewSizeY = event.resize.h;
#ifndef WIN32
			// HACK   We don't want to break resizing on windows (again?),
			//        so someone should test this very well before enabling it.
			SetSDLVideoMode();
#endif
			InitOpenGL();
			activeController->ResizeEvent();

			break;
		}
		case SDL_VIDEOEXPOSE: {
			GML_MSTMUTEX_LOCK(sim); // MainEventHandler

			Watchdog::ClearTimer(WDT_MAIN, true);
			// re-initialize the stencil
			glClearStencil(0);
			glClear(GL_STENCIL_BUFFER_BIT); SDL_GL_SwapBuffers();
			glClear(GL_STENCIL_BUFFER_BIT); SDL_GL_SwapBuffers();
			SetupViewportGeometry();

			break;
		}
		case SDL_QUIT: {
			gu->globalQuit = true;
			break;
		}
		case SDL_ACTIVEEVENT: {
			Watchdog::ClearTimer(WDT_MAIN, true);

			//! deactivate sounds and other
			if (event.active.state & (SDL_APPACTIVE | (globalRendering->fullScreen ? SDL_APPINPUTFOCUS : 0))) {
				globalRendering->active = !!event.active.gain;
				if (ISound::IsInitialized()) {
					sound->Iconified(!event.active.gain);
				}
			}

			//! update keydown table
			if (event.active.gain) {
				keyInput->Update(event.key.keysym.unicode, ((keyBindings != NULL)? keyBindings->GetFakeMetaKey(): -1));
			}

			//! unlock mouse
			if (mouse && mouse->locked) {
				mouse->ToggleMiddleClickScroll();
			}

			//! release all keyboard keys
			if ((event.active.state & (SDL_APPACTIVE | SDL_APPINPUTFOCUS)) && !event.active.gain) {
				for (boost::uint16_t i = 1; i < SDLK_LAST; ++i) {
					if (keyInput->IsKeyPressed(i)) {
						SDL_Event event;
						event.type = event.key.type = SDL_KEYUP;
						event.key.state = SDL_RELEASED;
						event.key.keysym.sym = (SDLKey)i;
						event.key.keysym.unicode = i;
						//event.keysym.mod =;
						//event.keysym.scancode =;
						SDL_PushEvent(&event);
					}
				}
			}

			//! simulate mouse release to prevent hung buttons
			if ((event.active.state & (SDL_APPACTIVE | SDL_APPMOUSEFOCUS)) && !event.active.gain) {
				for (int i = 1; i <= NUM_BUTTONS; ++i) {
					if (mouse && mouse->buttons[i].pressed) {
						SDL_Event event;
						event.type = event.button.type = SDL_MOUSEBUTTONUP;
						event.button.state = SDL_RELEASED;
						event.button.which = 0;
						event.button.button = i;
						event.button.x = -1;
						event.button.y = -1;
						SDL_PushEvent(&event);
					}
				}

				//! and make sure to un-capture mouse
				if(SDL_WM_GrabInput(SDL_GRAB_QUERY) == SDL_GRAB_ON)
					SDL_WM_GrabInput(SDL_GRAB_OFF);
			}

			break;
		}
		case SDL_KEYDOWN: {
			const boost::uint16_t sym = keyInput->GetNormalizedKeySymbol(event.key.keysym.sym);
			const bool isRepeat = !!keyInput->GetKeyState(sym);

			keyInput->Update(event.key.keysym.unicode, ((keyBindings != NULL)? keyBindings->GetFakeMetaKey(): -1));

			if (activeController) {
				activeController->KeyPressed(sym, isRepeat);

				if (activeController->userWriting){
					// use unicode for printed characters
					const boost::uint16_t usym = keyInput->GetCurrentKeyUnicodeChar();

					if ((usym >= SDLK_SPACE) && (usym <= 255)) {
						CGameController* ac = activeController;

						if (ac->ignoreNextChar || (ac->ignoreChar == (char)usym)) {
							ac->ignoreNextChar = false;
						} else {
							if (usym < 255 && (!isRepeat || ac->userInput.length() > 0)) {
								const int len = (int)ac->userInput.length();
								const char str[2] = { (char)usym, 0 };

								ac->writingPos = std::max(0, std::min(len, ac->writingPos));
								ac->userInput.insert(ac->writingPos, str);
								ac->writingPos++;
							}
						}
					}
				}
				activeController->ignoreNextChar = false;
			}
			break;
		}
		case SDL_KEYUP: {
			keyInput->Update(event.key.keysym.unicode, ((keyBindings != NULL)? keyBindings->GetFakeMetaKey(): -1));

			if (activeController) {
				activeController->KeyReleased(keyInput->GetNormalizedKeySymbol(event.key.keysym.sym));
			}
			break;
		}
		default:
			break;
	}

	return false;
}
void PolygonBackground::clear(DrawEnv *pEnv)
{
#if !defined(OSG_OGL_COREONLY) || defined(OSG_CHECK_COREONLY)
    if(pEnv->getPixelWidth()  == 0 ||
       pEnv->getPixelHeight() == 0 )
    {
        FWARNING(("Port has zero size: nothing to render to!\n"));
        return;
    }

    if(getMFPositions()->size() == 0 ||
       getMFPositions()->size() != getMFTexCoords()->size())
    {
        FWARNING(("PolygonBackground::clear: positions and texcoords have "
                  "different/ invalid sizes (%" PRISize " vs. %" PRISize ")!\n",
                  getMFPositions()->size(), getMFTexCoords()->size()));
        return;
    }

    Int32 bit = getClearStencilBit();      // 0x0

    if(bit >= 0)
    {
        glClearStencil(bit);

        glClear(GL_COLOR_BUFFER_BIT |
                GL_DEPTH_BUFFER_BIT |
                GL_STENCIL_BUFFER_BIT);
    }
    else
    {
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    }

    glPushAttrib(GL_ALL_ATTRIB_BITS);

    glDisable(GL_DEPTH_TEST);
    glDepthFunc(GL_ALWAYS);

    if(getCleanup())
        glDepthMask(GL_FALSE);

    Real32 aspectX = 1.0f, aspectY = 1.0f;

    if(getAspectHeight() != 0 && getAspectWidth() != 0)
    {
        aspectX = (Real32(pEnv->getPixelHeight()) / getAspectHeight()) /
                  (Real32(pEnv->getPixelWidth ()) / getAspectWidth ());
    }

    Real32 sFac        = getScale() > 0 ? getScale() : 1.0f;
    UInt32 fullWidth;
    UInt32 fullHeight;

    if(!getTile())
    {
        beginOrthoRender(pEnv, getNormalizedX(), getNormalizedY(),
                               fullWidth,        fullHeight       );

        Real32 t = 0;

        if(getAspectHeight() != 0 && getAspectWidth() != 0 &&
           fullHeight        != 0 && fullHeight       != 0   )
        {
            aspectX = (Real32(fullHeight) / getAspectHeight()) /
                      (Real32(fullWidth ) / getAspectWidth ());

            t  = Real32(fullWidth) * (1.0f - aspectX) * 0.5f;
            t *= Real32(pEnv->getPixelWidth()) / fullWidth;
        }

        glTranslatef(t,       0.0f,    0.0f);
        glScalef    (aspectX, aspectY, 1.0f);

        Real32 tW = (1.0f - sFac) * 0.5f * Real32(pEnv->getPixelWidth ());
        Real32 tH = (1.0f - sFac) * 0.5f * Real32(pEnv->getPixelHeight());

        glTranslatef(tW,   tH,   0.0f);
        glScalef    (sFac, sFac, 1.0f);
    }
    else
    {
        glScalef(sFac,    sFac,    1.0f);
        glScalef(aspectX, aspectY, 1.0f);

        beginOrthoRender(pEnv, getNormalizedX(), getNormalizedY(),
                               fullWidth,        fullHeight       );
    }


    getMaterial()->getState()->activate(pEnv);

    const Vec3f *tc  = &getMFTexCoords()->front();
    const Pnt2f *pos = &getMFPositions()->front();

    glBegin(GL_POLYGON);

    for (UInt16 i=0; i < getMFPositions()->size(); i++)
    {
        glTexCoord3fv( tc[i].getValues());
        glVertex2fv  (pos[i].getValues());
    }

    glEnd();

    getMaterial()->getState()->deactivate(pEnv);

    glScalef(1, 1, 1);

    if(getCleanup())
    {
        if(bit >= 0)
        {
            glClear(GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
        }
        else
        {
            glClear(GL_DEPTH_BUFFER_BIT);
        }
    }

    endOrthoRender(pEnv);

    glPopAttrib();
#endif
}
예제 #24
0
파일: gl.cpp 프로젝트: dschaefer/swt-opengl
M(void, glClearStencil, jint s) {
	glClearStencil(s);
}
예제 #25
0
void test_stencil(void)
{
    GLint numStencilBits;
    GLuint stencilValues[NumTests] = {
        0x7, // Result of test 0
        0x0, // Result of test 1
        0x2, // Result of test 2
        0xff // Result of test 3.  We need to fill this value in a run-time
    };
    int i;

    RD_START("stencil", "");

    display = get_display();

    /* get an appropriate EGL frame buffer configuration */
    ECHK(eglChooseConfig(display, config_attribute_list, &config, 1, &num_config));
    DEBUG_MSG("num_config: %d", num_config);

    /* create an EGL rendering context */
    ECHK(context = eglCreateContext(display, config, EGL_NO_CONTEXT, context_attribute_list));

    surface = make_window(display, config, 400, 240);

    ECHK(eglQuerySurface(display, surface, EGL_WIDTH, &width));
    ECHK(eglQuerySurface(display, surface, EGL_HEIGHT, &height));

    DEBUG_MSG("Buffer: %dx%d", width, height);

    /* connect the context to the surface */
    ECHK(eglMakeCurrent(display, surface, surface, context));

    program = get_program(vertex_shader_source, fragment_shader_source);

    GCHK(glBindAttribLocation(program, 0, "aPosition"));

    link_program(program);

    /* now set up our uniform. */
    GCHK(uniform_location = glGetUniformLocation(program, "uColor"));

    GCHK(glClearColor(0.0, 0.0, 0.0, 0.0));
    GCHK(glClearStencil(0x1));
    GCHK(glClearDepthf(0.75));

    GCHK(glEnable(GL_DEPTH_TEST));
    GCHK(glEnable(GL_STENCIL_TEST));

    // Set the viewport
    GCHK(glViewport(0, 0, width, height));

    // Clear the color, depth, and stencil buffers.  At this
    //   point, the stencil buffer will be 0x1 for all pixels
    GCHK(glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT));

    // Use the program object
    GCHK(glUseProgram(program));

    // Load the vertex position
    GCHK(glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, vVertices));

    GCHK(glEnableVertexAttribArray(0));

    // Test 0:
    //
    // Initialize upper-left region.  In this case, the
    //   stencil-buffer values will be replaced because the
    //   stencil test for the rendered pixels will fail the
    //   stencil test, which is
    //
    //        ref   mask   stencil  mask
    //      ( 0x7 & 0x3 ) < ( 0x1 & 0x7 )
    //
    //   The value in the stencil buffer for these pixels will
    //   be 0x7.
    //
    GCHK(glStencilFunc(GL_LESS, 0x7, 0x3));
    GCHK(glStencilOp(GL_REPLACE, GL_DECR, GL_DECR));
    GCHK(glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_BYTE, indices[0]));

    // Test 1:
    //
    // Initialize the upper-right region.  Here, we'll decrement
    //   the stencil-buffer values where the stencil test passes
    //   but the depth test fails.  The stencil test is
    //
    //        ref  mask    stencil  mask
    //      ( 0x3 & 0x3 ) > ( 0x1 & 0x3 )
    //
    //    but where the geometry fails the depth test.  The
    //    stencil values for these pixels will be 0x0.
    //
    GCHK(glStencilFunc(GL_GREATER, 0x3, 0x3));
    GCHK(glStencilOp(GL_KEEP, GL_DECR, GL_KEEP));
    GCHK(glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_BYTE, indices[1]));

    // Test 2:
    //
    // Initialize the lower-left region.  Here we'll increment
    //   (with saturation) the stencil value where both the
    //   stencil and depth tests pass.  The stencil test for
    //   these pixels will be
    //
    //        ref  mask     stencil  mask
    //      ( 0x1 & 0x3 ) == ( 0x1 & 0x3 )
    //
    //   The stencil values for these pixels will be 0x2.
    //
    GCHK(glStencilFunc(GL_EQUAL, 0x1, 0x3));
    GCHK(glStencilOp(GL_KEEP, GL_INCR, GL_INCR));
    GCHK(glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_BYTE, indices[2]));

    // Test 3:
    //
    // Finally, initialize the lower-right region.  We'll invert
    //   the stencil value where the stencil tests fails.  The
    //   stencil test for these pixels will be
    //
    //        ref   mask    stencil  mask
    //      ( 0x2 & 0x1 ) == ( 0x1 & 0x1 )
    //
    //   The stencil value here will be set to ~((2^s-1) & 0x1),
    //   (with the 0x1 being from the stencil clear value),
    //   where 's' is the number of bits in the stencil buffer
    //
    GCHK(glStencilFunc(GL_EQUAL, 0x2, 0x1));
    GCHK(glStencilOp(GL_INVERT, GL_KEEP, GL_KEEP));
    GCHK(glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_BYTE, indices[3]));

    // Since we don't know at compile time how many stencil bits are present,
    //   we'll query, and update the value correct value in the
    //   stencilValues arrays for the fourth tests.  We'll use this value
    //   later in rendering.
    GCHK(glGetIntegerv(GL_STENCIL_BITS, &numStencilBits));

    stencilValues[3] = ~(((1 << numStencilBits) - 1) & 0x1) & 0xff;

    // Use the stencil buffer for controlling where rendering will
    //   occur.  We disable writing to the stencil buffer so we
    //   can test against them without modifying the values we
    //   generated.
    GCHK(glStencilMask(0x0));

    for (i = 0; i < NumTests; i++) {
        GCHK(glStencilFunc(GL_EQUAL, stencilValues[i], 0xff));
        GCHK(glUniform4fv(uniform_location, 1, colors[i]));
        GCHK(glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_BYTE, indices[4]));
    }

    ECHK(eglSwapBuffers(display, surface));
    GCHK(glFlush());

    ECHK(eglDestroySurface(display, surface));

    usleep(1000000);

    dump_bmp(display, surface, "stencil.bmp");

    ECHK(eglTerminate(display));

    RD_END();
}
bool initGL()
{
    //Initialize GLEW
    GLenum glewError = glewInit();
    if( glewError != GLEW_OK )
    {
        printf( "Error initializing GLEW! %s\n", glewGetErrorString( glewError ) );
        return false;
    }

    //Make sure OpenGL 2.1 is supported
    if( !GLEW_VERSION_2_1 )
    {
        printf( "OpenGL 2.1 not supported!\n" );
        return false;
    }

    //Set the viewport
    glViewport( 0.f, 0.f, SCREEN_WIDTH, SCREEN_HEIGHT );

    //Initialize Projection Matrix
    glMatrixMode( GL_PROJECTION );
    glLoadIdentity();
    glOrtho( 0.0, SCREEN_WIDTH, SCREEN_HEIGHT, 0.0, 1.0, -1.0 );

    //Initialize Modelview Matrix
    glMatrixMode( GL_MODELVIEW );
    glLoadIdentity();

    //Initialize clear color
    glClearColor( 0.f, 0.f, 0.f, 1.f );

    //Enable texturing
    glEnable( GL_TEXTURE_2D );

    //Set blending
    glEnable( GL_BLEND );
    glDisable( GL_DEPTH_TEST );
    glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );

    //Initialize stencil clear value
    glClearStencil( 0 );

    //Check for error
    GLenum error = glGetError();
    if( error != GL_NO_ERROR )
    {
        printf( "Error initializing OpenGL! %s\n", gluErrorString( error ) );
        return false;
    }

    //Initialize DevIL and DevILU
    ilInit();
    iluInit();
    ilClearColour( 255, 255, 255, 000 );

    //Check for error
    ILenum ilError = ilGetError();
    if( ilError != IL_NO_ERROR )
    {
        printf( "Error initializing DevIL! %s\n", iluErrorString( ilError ) );
        return false;
    }

    return true;
}
예제 #27
0
파일: hw2.c 프로젝트: MaikuMori/gfx
void hw2_init(void)
{
    printf("\nInitializing homework 2 ...\n");

    //Set defaults.
    mouse_button[LEFT_BUTTON] = 0;
    mouse_button[RIGHT_BUTTON] = 0;
    camera_position.x = 25;
    camera_position.y = 45;
    memset(voxel_map, 1, VOXEL_COUNT);

    glfwSetWindowTitle("GFX Homework: 2.1.a");

    //Add callbacks.
    glfwSetMouseButtonCallback(mouse_click_handler);
    glfwSetMousePosCallback(mouse_pos_handler);
    glfwSetKeyCallback(key_handler);

    //Check for OpenGL 2.1+
    if(!GLEW_VERSION_2_1) {
        error("OpenGL 2.1+ required to view this homework.");
        return;
    }

    //Setup OpenGL.
    //Change the window size and OpenGL viewport.
    glfwSetWindowSize(TEXTURE_WIDTH, TEXTURE_HEIGHT);
    glViewport(0, 0, TEXTURE_WIDTH, TEXTURE_HEIGHT);
    //Reset projection matrix.
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    //Setup perspective projection.
    gluPerspective(60.0f, (float)(TEXTURE_WIDTH) / TEXTURE_HEIGHT, 1.0f, 1000.0f);
    //Reset model view matrix.
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);

    //Going to need depth test and we're going to cull faces to improve performance.
    glEnable(GL_DEPTH_TEST);
    glDepthMask(GL_TRUE);
    glDepthFunc(GL_LEQUAL);
    glDepthRange(0.0f, 1.0f);

    glEnable(GL_CULL_FACE);
    glCullFace(GL_BACK);
    glFrontFace(GL_CCW);

    //Slightly adjusting clear colors to work around lazy coding.
    glClearColor(0.01f, 0.01f, 0.01f, 0);
    glClearStencil(0);
    glClearDepth(1.0f);

    //Move camera.
    move_camera(0, 0, (GLfloat)(VOXEL_COUNT_Z * voxel_spacing + (VOXEL_COUNT_X * 4.5)), 0, 0, 0);

    //Generate the cube VBO.
    glGenBuffers(1, &voxel_vbo);
    glBindBuffer(GL_ARRAY_BUFFER, voxel_vbo);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices)+sizeof(normals)+sizeof(colors), 0, GL_STATIC_DRAW);
    glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(vertices), vertices);                             
    glBufferSubData(GL_ARRAY_BUFFER, sizeof(vertices), sizeof(normals), normals);                
    glBufferSubData(GL_ARRAY_BUFFER, sizeof(vertices)+sizeof(normals), sizeof(colors), colors);

    //Load shaders.
    //phong = load_shaders("Shaders/phong.vert", "Shaders/phong.frag");
    simple_color = load_shaders("Shaders/color.vert", "Shaders/color.frag");

    if(simple_color == NULL) {
        error("Failed to load shaders.");
        return;
    }
    //Use color shader which simply colors objects in one color.
    glUseProgram(simple_color->program);
    //Get the obj_color variable location in color_picker shader.
    obj_color_location = glGetUniformLocation(simple_color->program, "obj_color");

    init_done = GL_TRUE;
    
    printf("DONE!\n");

    printf("Using %d voxels!\n", VOXEL_COUNT);

    print_help();
}
예제 #28
0
void Display::InitializeOpenGL() {
	DebugMessage( "Initializing OpenGl...", 3 );
	glClearColor( 0.0f, 0.0f, 0.0f, 1.0f );
	glClearDepth( 1.0f );
	glClearStencil( 0 );
}
예제 #29
0
static void
redraw(void)
{
  int start, end;

  if (reportSpeed) {
    start = glutGet(GLUT_ELAPSED_TIME);
  }

  /* Clear; default stencil clears to zero. */
  if ((stencilReflection && renderReflection) || (stencilShadow && renderShadow) || (haloScale > 1.0)) {
    glStencilMask(0xffffffff);
    glClearStencil(0x4);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
  } else {
    /* Avoid clearing stencil when not using it. */
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  }

  /* Reposition the light source. */
  lightPosition[0] = 15*cos(lightAngle);
  lightPosition[1] = lightHeight;
  lightPosition[2] = 15*sin(lightAngle);
  if (directionalLight) {
    lightPosition[3] = 0.0;
  } else {
    lightPosition[3] = 1.0;
  }

  shadowMatrix(floorShadow, floorPlane, lightPosition);

  glPushMatrix();
    /* Perform scene rotations based on user mouse input. */
    glRotatef(angle2, 1.0, 0.0, 0.0);
    glRotatef(angle, 0.0, 1.0, 0.0);
     
    /* Tell GL new light source position. */
    glLightfv(GL_LIGHT0, GL_POSITION, lightPosition);

    if (renderReflection) {
      if (stencilReflection) {
        /* We can eliminate the visual "artifact" of seeing the "flipped"
  	   model underneath the floor by using stencil.  The idea is
	   draw the floor without color or depth update but so that 
	   a stencil value of one is where the floor will be.  Later when
	   rendering the model reflection, we will only update pixels
	   with a stencil value of 1 to make sure the reflection only
	   lives on the floor, not below the floor. */

        /* Don't update color or depth. */
        glDisable(GL_DEPTH_TEST);
        glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);

        /* Draw 1 into the stencil buffer. */
        glEnable(GL_STENCIL_TEST);
        glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);
        glStencilFunc(GL_ALWAYS, 1, 0x1);
	glStencilMask(0x1);

        /* Now render floor; floor pixels just get their stencil set to 1. */
        drawFloor();

        /* Re-enable update of color and depth. */ 
        glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
        glEnable(GL_DEPTH_TEST);

        /* Now, only render where stencil is set to 1. */
        glStencilFunc(GL_EQUAL, 1, 0x1);  /* draw if ==1 */
        glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
      }

      glPushMatrix();

        /* The critical reflection step: Reflect 3D model through the floor
           (the Y=0 plane) to make a relection. */
        glScalef(1.0, -1.0, 1.0);

	/* Reflect the light position. */
        glLightfv(GL_LIGHT0, GL_POSITION, lightPosition);

        /* To avoid our normals getting reversed and hence botched lighting
	   on the reflection, turn on normalize.  */
        glEnable(GL_NORMALIZE);
        glCullFace(GL_FRONT);

        /* Draw the reflected model. */
	glPushMatrix();
	  glTranslatef(0, 8.01, 0);
          drawModel();
	glPopMatrix();
	drawPillar();

        /* Disable noramlize again and re-enable back face culling. */
        glDisable(GL_NORMALIZE);
        glCullFace(GL_BACK);

      glPopMatrix();

      /* Switch back to the unreflected light position. */
      glLightfv(GL_LIGHT0, GL_POSITION, lightPosition);

      if (stencilReflection) {
        glDisable(GL_STENCIL_TEST);
      }
    }

    /* Back face culling will get used to only draw either the top or the
       bottom floor.  This let's us get a floor with two distinct
       appearances.  The top floor surface is reflective and kind of red.
       The bottom floor surface is not reflective and blue. */

    /* Draw "bottom" of floor in blue. */
    glFrontFace(GL_CW);  /* Switch face orientation. */
    glColor4f(0.1, 0.1, 0.7, 1.0);
    drawFloor();
    glFrontFace(GL_CCW);

    if (renderShadow && stencilShadow) {
     /* Draw the floor with stencil value 2.  This helps us only 
	draw the shadow once per floor pixel (and only on the
        floor pixels). */
      glEnable(GL_STENCIL_TEST);
      glStencilFunc(GL_ALWAYS, 0x2, 0x2);
      glStencilMask(0x2);
      glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);
    }

    /* Draw "top" of floor.  Use blending to blend in reflection. */
    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    glColor4f(1.0, 1.0, 1.0, 0.3);
    drawFloor();
    glDisable(GL_BLEND);

    if (renderShadow && stencilShadow) {
      glDisable(GL_STENCIL_TEST);
    }

    if (renderDinosaur) {
      drawPillar();

      if (haloScale > 1.0) {
	/* If halo effect is enabled, draw the model with its stencil set to 6
	   (arbitary value); later, we'll make sure not to update pixels tagged
	   as 6. */
        glEnable(GL_STENCIL_TEST);
        glStencilFunc(GL_ALWAYS, 0x0, 0x4);
        glStencilMask(0x4);
        glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);
      } 

      /* Draw "actual" dinosaur (or other model), not its reflection. */
      glPushMatrix();
        glTranslatef(0, 8.01, 0);
        drawModel();
      glPopMatrix();
    }

    /* Begin shadow render. */
    if (renderShadow) {

      /* Render the projected shadow. */

      if (stencilShadow) {

        /* Now, only render where stencil is set above 5 (ie, 6 where
	   the top floor is).  Update stencil with 2 where the shadow
	   gets drawn so we don't redraw (and accidently reblend) the
	   shadow). */
	glEnable(GL_STENCIL_TEST);
        glStencilFunc(GL_NOTEQUAL, 0x0, 0x2);
        glStencilMask(0x2);
        glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);
      }

      /* To eliminate depth buffer artifacts, we use polygon offset
	 to raise the depth of the projected shadow slightly so
	 that it does not depth buffer alias with the floor. */
      if (offsetShadow) {
	switch (polygonOffsetVersion) {
	case EXTENSION:
#ifdef GL_EXT_polygon_offset
	  glEnable(GL_POLYGON_OFFSET_EXT);
	  break;
#endif
#ifdef GL_VERSION_1_1
	case ONE_DOT_ONE:
          glEnable(GL_POLYGON_OFFSET_FILL);
	  break;
#endif
	case MISSING:
	  /* Oh well. */
	  break;
	}
      }

      /* Render 50% black shadow color on top of whatever the
         floor appareance is. */
      glEnable(GL_BLEND);
      glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
      glDisable(GL_LIGHTING);  /* Force the 50% black. */
      glColor4f(0.0, 0.0, 0.0, 0.5);

      glPushMatrix();
	/* Project the shadow. */
        glMultMatrixf((GLfloat *) floorShadow);
	glPushMatrix();
          glTranslatef(0, 8.01, 0);
          drawModel();
	glPopMatrix();
	drawPillar();
      glPopMatrix();

      glDisable(GL_BLEND);
      glEnable(GL_LIGHTING);

      if (offsetShadow) {
	switch (polygonOffsetVersion) {
#ifdef GL_EXT_polygon_offset
	case EXTENSION:
	  glDisable(GL_POLYGON_OFFSET_EXT);
	  break;
#endif
#ifdef GL_VERSION_1_1
	case ONE_DOT_ONE:
          glDisable(GL_POLYGON_OFFSET_FILL);
	  break;
#endif
	case MISSING:
	  /* Oh well. */
	  break;
	}
      }
      if (stencilShadow) {
        glDisable(GL_STENCIL_TEST);
      }
    } /* End shadow render. */

    /* Begin light source location render. */
    glPushMatrix();
      glDisable(GL_LIGHTING);
      glColor3f(1.0, 1.0, 0.0);
      if (directionalLight) {
        /* Draw an arrowhead. */
        glDisable(GL_CULL_FACE);
        glTranslatef(lightPosition[0], lightPosition[1], lightPosition[2]);
        glRotatef(lightAngle * -180.0 / M_PI, 0, 1, 0);
        glRotatef(atan(lightHeight/12) * 180.0 / M_PI, 0, 0, 1);
        glBegin(GL_TRIANGLE_FAN);
  	  glVertex3f(0, 0, 0);
	  glVertex3f(2, 1, 1);
	  glVertex3f(2, -1, 1);
	  glVertex3f(2, -1, -1);
	  glVertex3f(2, 1, -1);
	  glVertex3f(2, 1, 1);
        glEnd();
        /* Draw a white line from light direction. */
        glColor3f(1.0, 1.0, 1.0);
        glBegin(GL_LINES);
	  glVertex3f(0.1, 0, 0);
	  glVertex3f(5, 0, 0);
        glEnd();
        glEnable(GL_CULL_FACE);
      } else {
        /* Draw a yellow ball at the light source. */
        glTranslatef(lightPosition[0], lightPosition[1], lightPosition[2]);
        glutSolidSphere(1.0, 5, 5);
      }
      glEnable(GL_LIGHTING);
    glPopMatrix();
    /* End light source location render. */

    /* Add a halo effect around the 3D model. */
    if (haloScale > 1.0) {

      glDisable(GL_LIGHTING);

      if (blendedHalo) {
	/* If we are doing a nice blended halo, enable blending and
	   make sure we only blend a halo pixel once and that we do
	   not draw to pixels tagged as 6 (where the model is). */
	glEnable(GL_BLEND);
	glEnable(GL_STENCIL_TEST);
	glColor4f(0.8, 0.8, 0.0, 0.3);  /* 30% sorta yellow. */
        glStencilFunc(GL_EQUAL, 0x4, 0x4);
        glStencilMask(0x4);
        glStencilOp(GL_KEEP, GL_KEEP, GL_INVERT);
      } else {
	/* Be cheap; no blending.  Just draw yellow halo but not updating
	   pixels where the model is.  We don't update stencil at all. */
        glDisable(GL_BLEND);
	glEnable(GL_STENCIL_TEST);
	glColor3f(0.5, 0.5, 0.0);  /* Half yellow. */
        glStencilFunc(GL_EQUAL, 0x4, 0x4);
        glStencilMask(0x4);
        glStencilOp(GL_KEEP, GL_KEEP, GL_INVERT);
      }

      glPushMatrix();
        glTranslatef(0, 8.01, 0);
        glScalef(haloScale, haloScale, haloScale);
        drawModel();
      glPopMatrix();

      if (blendedHalo) {
        glDisable(GL_BLEND);
      }
      glDisable(GL_STENCIL_TEST);
      glEnable(GL_LIGHTING);
    }
    /* End halo effect render. */

  glPopMatrix();

  if (reportSpeed) {
    glFinish();
    end = glutGet(GLUT_ELAPSED_TIME);
    printf("Speed %.3g frames/sec (%d ms)\n", 1000.0/(end-start), end-start);
  }

  glutSwapBuffers();
}
예제 #30
0
PIGLIT_GL_TEST_CONFIG_END

enum piglit_result
piglit_display(void)
{
	GLint i, j;
	GLuint width = 16, height = 16;
	GLint x = 12, y = 12;
	GLfloat buf[IMAGE_WIDTH][IMAGE_HEIGHT];
	GLfloat depth_val = 0.75, stencil_val = 2.0;
	GLfloat green[4] = {0.0, 1.0, 0.0, 0.0};
	bool pass = true;

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

	glColor4fv(green);
	piglit_draw_rect(0, 0, width, height);

	glRasterPos2i(x, y);
	glCopyPixels(0, 0, width, height, GL_COLOR);
	pass = pass && piglit_probe_rect_rgba(x, y, width, height, green);

	/* Initialize depth data */
	for (i = 0; i < IMAGE_HEIGHT; i++) {
		for(j = 0; j < IMAGE_WIDTH; j++)
			buf[i][j] = depth_val;
	}

	glClearDepth(0.0);
	glClear(GL_DEPTH_BUFFER_BIT);
	glEnable(GL_DEPTH_TEST);
	glDepthFunc(GL_ALWAYS);

	glRasterPos2i(0, 0);
	glDrawPixels(width, height,
		     GL_DEPTH_COMPONENT, GL_FLOAT, buf);
	glRasterPos2i(x, y);
	glCopyPixels(0, 0, width, height, GL_DEPTH);
	pass = piglit_probe_rect_depth(x, y, width, height, depth_val)
	       && pass;

	/* Initialize stencil data */
	for (i = 0; i < IMAGE_HEIGHT; i++) {
		for(j = 0; j < IMAGE_WIDTH; j++)
			buf[i][j] = stencil_val;
	}

	glClearStencil(0.0);
	glClear(GL_STENCIL_BUFFER_BIT);

	glRasterPos2i(0, 0);
	glDrawPixels(width, height,
		     GL_STENCIL_INDEX, GL_FLOAT, buf);
	glRasterPos2i(x, y);
	glCopyPixels(0, 0, width, height, GL_STENCIL);
	pass = piglit_probe_rect_stencil(x, y, width, height, stencil_val)
	       && pass;

	return pass ? PIGLIT_PASS : PIGLIT_FAIL;
}