Ejemplo n.º 1
0
void DrawShader::drawTextureShader(bool isReflection, Shader& shader, const std::vector<Drawable>& drawables,
      const glm::mat4& viewMatrix, const glm::vec3& sunDir, float sunIntensity, 
      int lightning, const FrameBufferObject& reflection_fbo) {

   shader.sendUniform(Uniform::PROJECTION, uniforms, gProjectionMatrix);
   shader.sendUniform(Uniform::VIEW, uniforms, viewMatrix);

   shader.sendUniform(Uniform::LIGHTNING, uniforms, lightning);
   SendSun(shader, uniforms, sunIntensity, sunDir);

   for (auto& drawable : drawables) {
      if (drawable.draw_template.shader_type == ShaderType::TEXTURE ||
          drawable.draw_template.shader_type == ShaderType::DEFERRED) { 
         {
         // Per-Drawable Texture Shader Setup
            //SendHeightMap(shader, drawable);
            SendBones(shader, drawable);
            SendTexture(shader, drawable);

            if (!isReflection && drawable.draw_template.effects.count(EffectType::IS_WATER)) {
               shader.sendUniform(Uniform::IS_WATER, uniforms, 1);
               shader.sendUniform(Uniform::REFLECTION_TEXTURE, uniforms, reflection_fbo.texture_slot());  
               reflection_fbo.texture().enable(texture_cache_);
            }
            else
               shader.sendUniform(Uniform::IS_WATER, uniforms, 0);

            drawable.draw_template.material.sendMaterial(shader, uniforms);
         }
         if (!drawable.draw_template.effects.count(EffectType::IS_WATER) || !isReflection)
            drawModelTransforms(shader, drawable, viewMatrix, true, uniforms);
      }
   }
}
void DepthPeelingStage::postProcess(DrawEnv *pEnv, bool isPing)
{
    Window *win = pEnv->getWindow();

    if(win->hasExtOrVersion(_uiFramebufferObjectExt, 0x0300, 0x0200) == false)
    {
        FNOTICE(("Framebuffer objects not supported on Window %p!\n", win));
        return;
    }

    DepthPeelingStageData *pData =
        pEnv->getData<DepthPeelingStageData *>(_iDataSlotId);

    if(!pData)
        return;

    FrameBufferObject *pBlendFBO  = pData->getBlendFBO();
    pBlendFBO->activate(pEnv);

    ChunkMaterial *pMaterial;
    if (isPing)
        pMaterial = pData->getPeelPingMaterial();
    else
        pMaterial = pData->getPeelPongMaterial();

    pEnv->activateState(pMaterial->getState(), NULL);

    drawQuad();

    pEnv->deactivateState();

    pBlendFBO->deactivate(pEnv);
}
void FrameBufferObjectBase::onCreate(const FrameBufferObject *source)
{
    Inherited::onCreate(source);

    if(source != NULL)
    {
        FrameBufferObject *pThis = static_cast<FrameBufferObject *>(this);

        MFUnrecFrameBufferAttachmentPtr::const_iterator ColorAttachmentsIt  =
            source->_mfColorAttachments.begin();
        MFUnrecFrameBufferAttachmentPtr::const_iterator ColorAttachmentsEnd =
            source->_mfColorAttachments.end  ();

        while(ColorAttachmentsIt != ColorAttachmentsEnd)
        {
            pThis->pushToColorAttachments(*ColorAttachmentsIt);

            ++ColorAttachmentsIt;
        }

        pThis->setDepthAttachment(source->getDepthAttachment());

        pThis->setStencilAttachment(source->getStencilAttachment());
    }
}
void ShaderShadowMapEngine::updatePointLightRenderTargets(SSMEngineData *data)
{
    if(data->getMFRenderTargets()->empty() == true)
    {
        for(UInt16 i = 0; i < 6; ++i)
        {
            FrameBufferObjectUnrecPtr newTarget =
                FrameBufferObject::createLocal();
            newTarget->setWidth          (this->getWidth           ( ));
            newTarget->setHeight         (this->getHeight          ( ));
            newTarget->setDepthAttachment(data->getShadowTexBuffers(i));

            data->editMFRenderTargets()->push_back(newTarget);
        }
    }
    else
    {
        for(UInt16 i = 0; i < 6; ++i)
        {
            FrameBufferObject *target = data->getRenderTargets(i);

            if((target->getWidth () != this->getWidth ()) ||
               (target->getHeight() != this->getHeight())   )
            {
                target->setWidth (this->getWidth ());
                target->setHeight(this->getHeight());
            }
        }
    }
}
Ejemplo n.º 5
0
void TextRenderer::
render_fps(RenderContext const& ctx, FrameBufferObject& target,
           float application_fps, float rendering_fps) const {

    target.bind(ctx);

    math::mat4 fs_projection = scm::math::make_ortho_matrix(
                                  0.0f, static_cast<float>(target.width()),
                                  0.0f, static_cast<float>(target.height()),
                                  -1.0f, 1.0f);

    text_renderer_->projection_matrix(fs_projection);

    frame_counter_text_->text_string("Application FPS: "
                            + string_utils::to_string(application_fps)
                            + "\nRendering FPS: "
                            + string_utils::to_string(rendering_fps));

    math::vec2i text_ur = math::vec2i(40, target.height()
                            - frame_counter_text_->text_bounding_box().y + 10);

    text_renderer_->draw_outlined(
                            ctx.render_context, text_ur, frame_counter_text_);

    target.unbind(ctx);
}
Ejemplo n.º 6
0
int         FrameBufferObjectsRepository::releaseFbo(IFrameBufferObject* p)
{
    FrameBufferObject* pp = static_cast<FrameBufferObject*>(p);
    FboMap::iterator iR = m_FBOs.begin();
    while(iR != m_FBOs.end())
    {
        if(iR->second.p == pp)
        {
            iR->second.refCnt--;
            if(iR->second.refCnt == 0)
            {
                LOGD("Delete FBO %s and remove it from repository\n", pp->getName());
                pp->invalidate();
                delete pp;
                m_FBOs.erase(iR);
                return 0;
            } else {
                LOGD("Released FBO %s to refCnt=%d\n", pp->getName(), iR->second.refCnt);
                return iR->second.refCnt;
            }
        }
        ++iR;
    }
    return -1;
}
Ejemplo n.º 7
0
void DrawShader::SendShadow(Shader& shader, const UniformLocationMap& uniforms,
         const FrameBufferObject& shadow_map_fbo_,
         const glm::vec3& deerPos, const glm::vec3& sunDir) {
      shadow_map_fbo_.texture().enable(texture_cache_);
      shader.sendUniform(Uniform::HAS_SHADOWS, uniforms, 1);
      shader.sendUniform(Uniform::SHADOW_MAP_TEXTURE, uniforms, shadow_map_fbo_.texture_slot());
      SendInverseShadow(shader, uniforms, sunDir, deerPos);
}
Ejemplo n.º 8
0
//-----------------------------------------------------------------------------
void Widget3d::pushFrameBuffer(const FrameBufferObject& iF /*=FrameBufferObject()*/)
{
  mFrameBuffers.push_back(iF);
  GLint frameBufferId = 0;
  if(iF.isValid())
    frameBufferId = iF.getFrameBufferId();
  glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, frameBufferId);  
}
Ejemplo n.º 9
0
void ObjectManager::deleteEqFrameBufferObject( const void* key )
{
    FBOHash::iterator i = _impl->eqFrameBufferObjects.find(key);
    if( i == _impl->eqFrameBufferObjects.end( ))
        return;

    FrameBufferObject* frameBufferObject = i->second;
    _impl->eqFrameBufferObjects.erase( i );

    frameBufferObject->exit();
    delete frameBufferObject;
}
void FrameBufferObjectBase::execSyncV(      FieldContainer    &oFrom,
                                        ConstFieldMaskArg  whichField,
                                        AspectOffsetStore &oOffsets,
                                        ConstFieldMaskArg  syncMode,
                                  const UInt32             uiSyncInfo)
{
    FrameBufferObject *pThis = static_cast<FrameBufferObject *>(this);

    pThis->execSync(static_cast<FrameBufferObject *>(&oFrom),
                    whichField,
                    oOffsets,
                    syncMode,
                    uiSyncInfo);
}
Ejemplo n.º 11
0
//Deletes all of the created objects here.
void CloseFunc(){
	window.window_handle = -1;
	cylinder.TakeDown();torus.TakeDown();square.TakeDown();square2.TakeDown();
	disc.TakeDown();sphere.TakeDown();sphere2.TakeDown();tiger.TakeDown();goldeen.TakeDown();
	stadium.TakeDown();coin.TakeDown();ss.TakeDown();healthBar.TakeDown();
	shark.TakeDown();bird.TakeDown();sb.TakeDown();arena.TakeDown();skyboxUW.TakeDown();fbo.TakeDown();rain2.TakeDown();
	tri2.TakeDown();skybox.TakeDown();skybox2.TakeDown();skybox3.TakeDown();egg.TakeDown();snow2.TakeDown();
	star.TakeDown();magneton.TakeDown();haunter.TakeDown();frog.TakeDown();
	sph1.TakeDown(); enm.TakeDown(); usr.TakeDown();sq4.TakeDown();soldier.TakeDown();userTeam.TakeDown();cpuTeam.TakeDown();
}
void DisplayFilterStage::resizeStageData(DisplayFilterStageData *pData,
                                         Int32                   iPixelWidth,
                                         Int32                   iPixelHeight)
{
    FrameBufferObject *pFBO = pData->getTarget();

    if(pFBO == NULL)
        return;

    TextureBuffer *pTexBuffer = 
        dynamic_cast<TextureBuffer *>(pFBO->getColorAttachments(0));

    if(pTexBuffer == NULL)
        return;

    TextureObjChunk *pTex = pTexBuffer->getTexture();

    if(pTex == NULL)
        return;

    Image *pImg = pTex->getImage();

    if(pImg == NULL)
        return;

    pImg->set(Image::OSG_RGB_PF, 
              iPixelWidth, 
              iPixelHeight,
              1,
              1,
              1,
              0.0,
              0,
              Image::OSG_UINT8_IMAGEDATA,
              false);

    pFBO->setSize(iPixelWidth, iPixelHeight);

    pData->setWidth (iPixelWidth );
    pData->setHeight(iPixelHeight);

    commitChanges();
}
Ejemplo n.º 13
0
void DrawShader::drawModelTransforms(
      Shader& shader,
      const Drawable& drawable,
      const glm::mat4& view,
      const FrameBufferObject& deferred_diffuse_fbo,
      const FrameBufferObject& deferred_position_fbo,
      const FrameBufferObject& deferred_normal_fbo,
      bool needsModel,
      const UniformLocationMap& uniforms) {
   for(const auto& instance : drawable.draw_instances) {
      if (instance.material) {
         instance.material->sendMaterial(shader, uniforms);
      }

      const auto model_view = view * instance.model_transform;
      shader.sendUniform(Uniform::MODEL_VIEW_PROJECTION, uniforms, gProjectionMatrix * model_view);
      SendModelAndNormal(shader, uniforms, model_view, instance.model_transform, needsModel);
      for (int i = 0; i < LAST_DEFERRED; ++i) {
         const auto deferred_type(static_cast<DeferredType>(i));
         switch (deferred_type) {
            case DEFERRED_DIFFUSE:
               deferred_diffuse_fbo.bind();
               break;
            case DEFERRED_POSITION:
               deferred_position_fbo.bind();
               break;
            case DEFERRED_NORMAL:
               deferred_normal_fbo.bind();
               break;
            default: break;
         }
         shader.sendUniform(Uniform::OUTPUT_SHADER_TYPE, uniforms, i);
         shader.drawMesh(drawable.draw_template.mesh);
      }
   }
}
Ejemplo n.º 14
0
int main(int argc, char * argv[])
{
	window.timer_period = 1000 / 60;

	glutInit(&argc , argv);

	glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH);
	glutInitWindowPosition(0 , 0);
	glutInitWindowSize(512 , 512);

	if ((window.window_handle = glutCreateWindow("Frame Buffer Demo")) < 1)
	{
		cerr << "Window creation failed." << endl;
		return 0;
	}
	
	if (glewInit() != GLEW_OK)
	{
		cerr << "Glew failed to initialize." << endl;
		return 0;
	} 

	if (!fbo.Initialize(glm::ivec2(512, 512), 2, true))
	{
		cerr << "Frame buffer failed to initialize." << endl;
		return 0;
	}
	glutDisplayFunc(DisplayFunc);
	glutReshapeFunc(ReshapeFunc);
	glutKeyboardFunc(KeyboardFunc);
	glutTimerFunc(window.timer_period, TimerFunc, 0);
	glutSetOption(GLUT_ACTION_ON_WINDOW_CLOSE, GLUT_ACTION_CONTINUE_EXECUTION);
	glutCloseFunc(CloseFunc);
	glutMainLoop();
	return 0;
}
Ejemplo n.º 15
0
void HDRStage::resizeStageData(HDRStageData *pData,
                               Int32         iPixelWidth,
                               Int32         iPixelHeight)
{
    FrameBufferObject *pSceneFBO = this->getRenderTarget();

    pSceneFBO->resizeAll(iPixelWidth, iPixelHeight);


    FrameBufferObject *pShrinkFBO = pData->getShrinkRenderTarget();

    pShrinkFBO->resizeAll(iPixelWidth / 2, iPixelHeight / 2);


    FrameBufferObject *pBlurFBO = pData->getBlurRenderTarget();

    pBlurFBO->resizeAll(iPixelWidth  / 4,
                        iPixelHeight / 4);


    SimpleSHLChunk *pHBlurShader = pData->getHBlurShader();

    std::string szNewFragProg =         
        generate1DConvolutionFilterFPString(getBlurWidth(), 
                                            false, 
                                            true, 
                                            iPixelWidth  / 2, 
                                            iPixelHeight / 2);

    pHBlurShader->setFragmentProgram(szNewFragProg);

    szNewFragProg = generate1DConvolutionFilterFPString(getBlurWidth(),  
                                                        true, 
                                                        true, 
                                                        iPixelWidth  / 2, 
                                                        iPixelHeight / 2);

    SimpleSHLChunkUnrecPtr pVBlurShader = pData->getVBlurShader();

    pVBlurShader->setFragmentProgram(szNewFragProg);

    commitChanges();
} 
void DepthPeelingStage::resizeStageData(DepthPeelingStageData *pData,
                                        Int32                  iPixelWidth,
                                        Int32                  iPixelHeight)
{
    FrameBufferObject *pSceneFBO = pData->getBlendFBO();

    pSceneFBO->resizeAll(iPixelWidth, iPixelHeight);


    FrameBufferObject *pPeelPingFBO = pData->getPeelPingFBO();

    pPeelPingFBO->resizeAll(iPixelWidth, iPixelHeight);

    FrameBufferObject *pPeelPongFBO = pData->getPeelPongFBO();

    pPeelPongFBO->resizeAll(iPixelWidth, iPixelHeight);

    commitChanges();
}
Ejemplo n.º 17
0
static void AttachCubeSide(int i, FrameBufferObject & reflection_fbo, std::ostream & error_output)
{
	switch (i)
	{
		case 0:
		reflection_fbo.SetCubeSide(FrameBufferTexture::POSX);
		break;

		case 1:
		reflection_fbo.SetCubeSide(FrameBufferTexture::NEGX);
		break;

		case 2:
		reflection_fbo.SetCubeSide(FrameBufferTexture::POSY);
		break;

		case 3:
		reflection_fbo.SetCubeSide(FrameBufferTexture::NEGY);
		break;

		case 4:
		reflection_fbo.SetCubeSide(FrameBufferTexture::POSZ);
		break;

		case 5:
		reflection_fbo.SetCubeSide(FrameBufferTexture::NEGZ);
		break;

		default:
		error_output << "Reached odd spot while attaching cubemap side. How many sides are in a cube, anyway? " << i << "?" << std::endl;
		assert(0);
		break;
	};

	CheckForOpenGLErrors("cubemap generation: FBO cube side attachment", error_output);
}
Ejemplo n.º 18
0
Archivo: main.cpp Proyecto: c-day/Warp
int main(int argc, char * argv[])
{
	glutInit(&argc , argv);
	glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE);
	glutInitWindowPosition(0 , 0);
	glutInitWindowSize(window_width, window_height);
	glutCreateWindow("Warp");
	glutDisplayFunc(DisplayFunc);
	glutTimerFunc(1000 / 60, TimerFunc, 1000 / 60);
	glutReshapeFunc(ReshapeFunc);
	glutSpecialFunc(SpecialFunc);
	glutKeyboardFunc(KeyboardFunc);
	glutMouseFunc(MouseFunc);
	glutMotionFunc(MotionFunc);
	glutCloseFunc(CloseFunc);
	glutSetOption(GLUT_ACTION_ON_WINDOW_CLOSE, GLUT_ACTION_CONTINUE_EXECUTION);
	glEnable(GL_DEPTH_TEST);

	ilInit();
	iluInit();
	ilutInit();
	ilutRenderer(ILUT_OPENGL);

	if (glewInit() != GLEW_OK)
	{
		cerr << "GLEW failed to initialize." << endl;
		return 0;
	}
			
	if (!shader.Initialize("stub.vert", "stub.frag"))
	{
		return 0;
	}

	if (!background.Initialize("back.vert", "back.frag"))
	{
		return 0;
	}


	image_1_handle = ilutGLLoadImage("lotr-scene.jpg");
	image_1_w = ilGetInteger(IL_IMAGE_WIDTH);
	image_1_h = ilGetInteger(IL_IMAGE_HEIGHT);
	
	tex_handle = ilutGLLoadImage("Home-Theater.jpg");
	tex_w = ilGetInteger(IL_IMAGE_WIDTH);
	tex_h = ilGetInteger(IL_IMAGE_HEIGHT);

	left_overlay_handle = ilutGLLoadImage("left-over.jpg");
	right_overlay_handle = ilutGLLoadImage("right-over.jpg");
	left_curtain_handle = ilutGLLoadImage("left-curtain.jpg");

	cout << "Image 1: " << image_1_w << " x " << image_1_h << endl;
	cout << "Background: " << tex_w << " x " << tex_h << endl;
	
	if (!frame.Initialize(glm::ivec2(image_1_w, image_1_h), 1, true))
	{
		cerr << "Frame buffer 1 failed to initialize." << endl;
		return 0;
	}

	cout << "Window Size: " << window_width << " x " << window_height << endl;
	cout << "Frame buffer 1 size: " << frame.size.x << " x " << frame.size.y << endl;

	glutMainLoop();
	return 0;
}
Ejemplo n.º 19
0
FrameBufferObject::Binder::Binder( const FrameBufferObject& fbo ) :
    m_fbo( fbo )
{
    KVS_ASSERT( fbo.isCreated() );
    fbo.bind();
}
Ejemplo n.º 20
0
int main(int argc, char * argv[])
{
	glewInit();
	glutInit(&argc, argv);
	glutInitWindowSize(1024, 512);
	glutInitWindowPosition(0, 0);
	glutInitDisplayMode(GLUT_RGBA | GLUT_DEPTH | GLUT_DOUBLE);

	//Initialize object's colors / values
	torus.color = vec3(1.0f, 0.1f, 0.0f);
	square.color1 = vec3(1.0, 1.0, 1.0);
	square2.color1 = vec3(0.95f, 0.1f, 0.7f);
	square2.color2 = vec3(1.0f, 1.0f, 0.0f);
	disc.color = vec3(0.1f, 0.5f, 1.0f);
	sphere.color = vec3(0.15f, 0.45f, 0.0f);
	sphere2.color = vec3(0.45f, 0.05f, 0.25f);
	cylinder.color = vec3(0.0f, 0.5f, 0.0f);
	arena.texID = 18;
	egg.texID = 20;
	star.texID = 22;
	magneton.texID = 25;
	haunter.texID = 26;
	frog.texID = 27;
	goldeen.texID = 76;
	rain2.color = vec3(0.4f, 0.4f, 1.0f);
	snow2.color = vec3(1.0f, 1.0f, 1.0f);
	fontfilename = "Pokemon.ttf";

	//Initialize the precipitation
	numParts = 300;
	partX = new float[numParts];
	partY = new float[numParts];
	partOffset = new float[numParts];
	for(int i=0; i<numParts; i++){
		partX[i] = (float)(rand() % 1200);
		partX[i] = (partX[i] - 600)/100;

		partY[i] = (float)(rand() % 1200);
		partY[i] = (partY[i] - 600)/100;
		partOffset[i] = (float)(rand() % 360 + 1);
	}
	sphere.lava = true;sphere2.lava = false; //Initialize sphere statuses

	window.window_handle = glutCreateWindow("Solar System");
	glutReshapeFunc(ReshapeFunc);
	glutCloseFunc(CloseFunc);
	
	glutMotionFunc(mouseMovement);
	glutPassiveMotionFunc(mouseMovement); //check for mouse movement
	glutKeyboardFunc(KeyboardFunc);
	glutSpecialFunc(SpecialFunc);
	glutTimerFunc(window.interval, TimerFunc, 0);
	
	glutSetOption(GLUT_ACTION_ON_WINDOW_CLOSE, GLUT_ACTION_CONTINUE_EXECUTION);
	
	//Initialize everything

	if (glewInit() != GLEW_OK)
	{
		cerr << "GLEW failed to initialize." << endl;
		return 0;
	}

	init_resources();
	glutDisplayFunc(DisplayFunc);

	if (!fbo.Initialize(glm::ivec2(512, 512), 1, true)){
		cerr << "Frame buffer failed to initialize." << endl;
		return 0;
	}

	sph1.color = vec3(1.0f, 0.85f, 0.0f);
	if (!sph1.Initialize(8,1.0f, "phong3.vert", "phong3.frag")){return 0;}
	enm.color = vec3(0.75f, 0.0f, 0.75f);
	if (!enm.Initialize(2,0.05f, "phong.vert", "phong.frag")){return 0;}
	usr.color = vec3(0.0f, 0.0f, 0.5f);
	if (!usr.Initialize(2,0.05f, "phong.vert", "phong.frag")){return 0;}
	//if (!sb.Initialize()){return 0;}
	//if (!coin.Initialize()){return 0;}
	//if (!stadium.Initialize(0)){return 0;}
	if (!skybox.Initialize(0, 5000, "basic_skybox_shader.vert", "basic_skybox_shader.frag")){return 0;}
	if (!skybox2.Initialize(1, 5025, "basic_skybox_shader.vert", "basic_skybox_shader.frag")){return 0;}
	if (!skybox3.Initialize(2, 5050, "basic_skybox_shader.vert", "basic_skybox_shader.frag")){return 0;}
	if (!skyboxUW.Initialize(3, 5075, "basic_skybox_shader.vert", "basic_skybox_shader.frag")){return 0;}


	arena.order = 1;
	
	if (!sphere.Initialize(15, 1, "sphereShader2.vert", "sphereShader2.frag")){return 0;}
	if (!sphere2.Initialize(15, 1, "sphereShader2.vert", "sphereShader2.frag")){return 0;}
	if (!rain2.Initialize(2, 0.02f, "phong.vert", "phong.frag")){return 0;}
	if (!snow2.Initialize(3, 0.02f, "phong.vert", "phong.frag")){return 0;}
	//if (!egg.Initialize(15, 1, "./textures/alienEgg.jpg", "basic_texture_shader.vert", "basic_texture_shader.frag")){return 0;}
	if (!square.Initialize(1, 3.0f, "phong.vert", "phong.frag")) {return 0;}
	if (!sq4.Initialize(1, 5.0f, "basic_texture_shader.vert", "basic_texture_shader.frag")) {return 0;}
	if (!disc.Initialize(8, 1.0f, "phong3.vert", "phong3.frag")) {return 0;}
	if (!healthBar.Initialize(2, 1.0f, 1.f, 1.f, "phong3.vert", "phong3.frag")) {return 0;}
	if (!soldier.Initialize()) {return 0;}
	if (!ss.Initialize()) {return 0;}

	userTeam.userTeam = true;
	if (!userTeam.Initialize()) {return 0;}
	if (!cpuTeam.Initialize()) {return 0;}

	glutMainLoop();
}
void DeferredShadingStage::updateStageData(
    DSStageData         *data,
    FrameBufferObject   *shadingTarget,
    RenderPartition     *parentPart    )
{
    FrameBufferObject *gBufferTarget = data->getGBufferTarget();

    Int32 targetWidth;
    Int32 targetHeight;
    Int32 targetLeft;
    Int32 targetBottom;

    if(shadingTarget != NULL)
    {
        targetWidth  = shadingTarget->getWidth ();
        targetHeight = shadingTarget->getHeight();

        targetLeft   = 0;
        targetBottom = 0;
    }
    else
    {
        targetWidth  = parentPart->getDrawEnv().getPixelWidth ();
        targetHeight = parentPart->getDrawEnv().getPixelHeight();

        targetLeft   = parentPart->getDrawEnv().getPixelLeft  ();
        targetBottom = parentPart->getDrawEnv().getPixelBottom();
    }

    if(gBufferTarget->getWidth () != targetWidth ||
       gBufferTarget->getHeight() != targetHeight  )
    {
        _targetSizeChanged = true;
    }

    if(_targetSizeChanged == true)
    {
        gBufferTarget->setSize(targetWidth, targetHeight);
    }

    if(getMFPixelFormats()->size() != getMFPixelTypes()->size())
    {
        SWARNING << "DeferredShadingStage::updateStageData: "
                 << "Number of PixelFormats and PixelTypes inconsistent."
                 << std::endl;
    }

    UInt32 lightCount  =        getMFLights      ()->size();
    UInt32 bufferCount = osgMin(getMFPixelFormats()->size(),
                                getMFPixelTypes  ()->size() );

    // buffers changed - remove them here, recreate below
    if((_changeCache & (PixelFormatsFieldMask |
                        PixelTypesFieldMask    )) != 0)
    {
        gBufferTarget->editMFColorAttachments()->clear (                    );
        gBufferTarget->editMFColorAttachments()->resize(bufferCount, NULL   );
        gBufferTarget->editMFDrawBuffers     ()->clear (                    );
        gBufferTarget->editMFDrawBuffers     ()->resize(bufferCount, GL_NONE);
    }

    for(UInt32 i = 0; i < bufferCount; ++i)
    {
        TextureBuffer *buf =
            dynamic_cast<TextureBuffer *>(gBufferTarget->getColorAttachments(i));

        if(buf == NULL)
        {
            TextureBufferUnrecPtr newBuf =
                createGBuffer(i, targetWidth, targetHeight);
            buf = newBuf;

            gBufferTarget->editMFColorAttachments()->replace(i, newBuf                      );
            gBufferTarget->editMFDrawBuffers     ()->replace(i, GL_COLOR_ATTACHMENT0_EXT + i);
        }
        else
        {
            updateGBuffer(buf, i, targetWidth, targetHeight);
        }
    }

    if((_changeCache & LightsFieldMask) != 0)
    {
        data->editMFLightChunks         ()->resize(    lightCount, NULL);
        data->editMFShadingStates       ()->resize(1 + lightCount, NULL);
        data->editMFShadingProgramChunks()->resize(1 + lightCount, NULL);
    }

    // update shading states
    if((_changeCache & (PixelFormatsFieldMask   |
                        PixelTypesFieldMask     |
                        AmbientProgramFieldMask |
                        LightProgramsFieldMask  |
                        LightsFieldMask          )) != 0)
    {
        // copy ambient and light programs
        DSStageData::MFShadingProgramChunksType::const_iterator spcIt  =
            data->editMFShadingProgramChunks()->begin();
        DSStageData::MFShadingProgramChunksType::const_iterator spcEnd =
            data->editMFShadingProgramChunks()->end  ();

        for(UInt32 progIdx = 0; spcIt != spcEnd; ++spcIt, ++progIdx)
        {
            if(*spcIt == NULL)
            {
                ShaderProgramChunkUnrecPtr newSPC =
                    ShaderProgramChunk::createLocal();
                //*spcIt = newSPC;

                data->editMFShadingProgramChunks()->replace(progIdx, newSPC);
            }

            (*spcIt)->clearVertexShaders  ();
            (*spcIt)->clearGeometryShaders();
            (*spcIt)->clearFragmentShaders();

            if(progIdx == 0 && getAmbientProgram() != NULL)
            {
                // ambient program
                copyProgramChunk(*spcIt, getAmbientProgram());

                // TODO: there must be a better way to add this uniform
                (*spcIt)->getFragmentShader(0)->addUniformVariable(
                    "vpOffset", Vec2f(targetLeft,
                                      targetBottom));
            }
            else
            {
                // light programs
                if(_mfLightPrograms.size() == 1)
                {
                    copyProgramChunk(*spcIt, getLightPrograms(0));

                    // TODO: there must be a better way to add this uniform
                    (*spcIt)->getFragmentShader(0)->addUniformVariable(
                        "vpOffset", Vec2f(targetLeft,
                                          targetBottom));
                }
                else if(_mfLightPrograms.size() == _mfLights.size())
                {
                    copyProgramChunk(*spcIt, getLightPrograms(progIdx - 1));

                    // TODO: there must be a better way to add this uniform
                    (*spcIt)->getFragmentShader(0)->addUniformVariable(
                        "vpOffset", Vec2f(targetLeft,
                                          targetBottom));
                }
                else
                {
                    SWARNING << "DeferredShadingStage::updateStageData: "
                             << "Number of Lights and LightPrograms "
                             << "inconsistent." << std::endl;
                }
            }
        }

        // create light chunks
        DSStageData::MFLightChunksType::const_iterator lcIt  =
            data->editMFLightChunks()->begin();
        DSStageData::MFLightChunksType::const_iterator lcEnd =
            data->editMFLightChunks()->end  ();

        for(UInt32 lightIdx = 0; lcIt != lcEnd; ++lcIt, ++lightIdx)
        {
            if(*lcIt == NULL)
            {
                DSLightChunkUnrecPtr newLC = DSLightChunk::createLocal();
                //*lcIt = newLC;
                data->editMFLightChunks()->replace(lightIdx, newLC);
            }

            updateLightChunk(*lcIt, getLights(lightIdx));
        }

        // populate shading states
        DSStageData::MFShadingStatesType::const_iterator stateIt  =
            data->editMFShadingStates()->begin();
        DSStageData::MFShadingStatesType::const_iterator stateEnd =
            data->editMFShadingStates()->end  ();

        for(UInt32 stateIdx = 0; stateIt != stateEnd; ++stateIt, ++stateIdx)
        {
            if(*stateIt == NULL)
            {
                StateUnrecPtr newState = State::createLocal();
                //*stateIt = newState;
                data->editMFShadingStates()->replace(stateIdx, newState);
            }

            // remove all chunks
            (*stateIt)->clearChunks();

            // add G Buffer textures
            for(UInt32 bufferIdx = 0;
                bufferIdx < bufferCount; ++bufferIdx)
            {
                TextureBuffer   *buf    = static_cast<TextureBuffer *>(
                    gBufferTarget->getColorAttachments(bufferIdx));
                TextureObjChunk *bufTex = buf->getTexture();

                (*stateIt)->addChunk(bufTex, bufferIdx);
            }

            // add ambient/light programs and light chunks
            if(stateIdx == 0)
            {
                if(getAmbientProgram() != NULL)
                {
                    (*stateIt)->addChunk(
                        data->getShadingProgramChunks(stateIdx));
                }
            }
            else
            {
                (*stateIt)->addChunk(
                    data->getShadingProgramChunks(stateIdx    ));
                (*stateIt)->addChunk(
                    data->getLightChunks         (stateIdx - 1));
            }

            // add blend chunk to light states
            if(stateIdx > 0)
            {
                (*stateIt)->addChunk(data->getBlendChunk());
            }
        }
    }

    _changeCache       = TypeTraits<BitVector>::BitsClear;
    _targetSizeChanged = false;
}
void ShaderShadowMapEngine::handleSpotLightEnter(
    SpotLight *spotL, RenderAction *ract, SSMEngineData *data)
{
    RenderPartition *parentPart    = ract->getActivePartition();
//    Real             cosSpotCutOff = osgCos(spotL->getSpotCutOff());

    Matrix matEyeToWorld  (parentPart->getCameraToWorld());
    Matrix matWorldToLight;
    Matrix matEyeToLight;

    calcSpotLightMatrices(matWorldToLight, matEyeToLight, 
                          spotL,           matEyeToWorld );

    Real32  lightNear;
    Real32  lightFar;

    calcPointLightRange(spotL, 0.001f,
                        parentPart->getNear(), parentPart->getFar(),
                        lightNear,             lightFar             );

    if(getShadowNear() != 0.f)
    {
        lightNear = getShadowNear();
    }

    if(getShadowFar() != 0.f)
    {
        lightFar  = getShadowFar();
    }

    Matrix matLightProj;
    Matrix matLightProjTrans;

    MatrixPerspective(matLightProj, 
                      spotL->getSpotCutOff(), 1.f,
                      lightNear, lightFar         );
    
    updateShadowTexImage  (data);
    updateShadowTexBuffers(data);
    updateRenderTargets   (data);

    Int32          shadowTexUnit = (this->getForceTextureUnit() > 0) ?
                                    this->getForceTextureUnit()      : 7;
    ShaderProgram *shadowFP      = this->getShadowFragmentProgram();

    if(shadowFP == NULL)
    {
        ShaderProgramUnrecPtr newShadowFP = ShaderProgram::createLocal();
        newShadowFP->setShaderType(GL_FRAGMENT_SHADER);
        newShadowFP->setProgram   (_spotFPCode       );

        newShadowFP->addUniformVariable("SSME_matEyeToLight", matEyeToLight);
        newShadowFP->addUniformVariable("SSME_matLightProj",  matLightProj );
        newShadowFP->addUniformVariable("SSME_texShadow",     shadowTexUnit);

        this->setShadowFragmentProgram(newShadowFP);
        shadowFP = newShadowFP;
    }
    else
    {
        shadowFP->updateUniformVariable("SSME_matEyeToLight", matEyeToLight);
        shadowFP->updateUniformVariable("SSME_matLightProj",  matLightProj );
    }

    commitChanges();

    this->pushPartition(ract);
    {
        RenderPartition   *part   = ract->getActivePartition( );
        Window            *win    = ract->getWindow         ( );
        FrameBufferObject *target = data->getRenderTargets  (0);
        Background        *back   = data->getBackground     ( );

        part->setRenderTarget(target);
        part->setWindow      (win   );

        part->calcViewportDimension(0.f, 0.f, 1.f, 1.f,
                                    target->getWidth (),
                                    target->getHeight() );

        part->setupProjection(matLightProj, matLightProjTrans);
        part->setupViewing   (matWorldToLight                );

        part->setNear        (parentPart->getNear());
        part->setFar         (parentPart->getFar ());

        part->calcFrustum    (                     );

        part->setBackground  (back                 );

        // force material for shadow map generation
        part->overrideMaterial(data->getLightPassMaterials(0),
                               ract->getActNode           ( ) );

        this->recurseFrom(ract, spotL);
        ract->useNodeList(false      );

        // undo override
        part->overrideMaterial(NULL,
                               ract->getActNode           ( ) );
    }
    this->popPartition(ract);
}
void ShaderShadowMapEngine::handleDirectionalLightEnter(
    DirectionalLight *dirL, RenderAction *ract, SSMEngineData *data)
{
    RenderPartition *parentPart = ract      ->getActivePartition();
    FrustumVolume    camFrust   = parentPart->getFrustum        ();

    Matrix matEyeToWorld  (parentPart->getCameraToWorld());
    Matrix matWorldToLight;
    Matrix matEyeToLight;

    calcDirectionalLightMatrices(matWorldToLight, matEyeToLight,
                                 dirL,            matEyeToWorld );

    // place light camera outside the scene bounding box:
    //  - project camera frustum and scene bounding box into a
    //    coordinate system where the directional light shines
    //    along the -z axis.
    //  - compute 2 AABBs that contain the projected frustum and
    //    scene BB
    //  - width and height of the ortho projection are determined from
    //    the frustum AABB, while near and far are determined by the
    //    scene AABB (offscreen objects cast shadows into the view volume)
          Pnt3f      camVerts  [10];
          Pnt3f      sceneVerts[10];
    const Matrix    &matSceneToWorld = ract->topMatrix ();
          BoxVolume  sceneBB         = ract->getActNode()->getVolume();

    camFrust.getCorners(camVerts  [0], camVerts  [1],
                        camVerts  [2], camVerts  [3],
                        camVerts  [4], camVerts  [5],
                        camVerts  [6], camVerts  [7] );
    sceneBB .getCorners(sceneVerts[0], sceneVerts[1],
                        sceneVerts[2], sceneVerts[3],
                        sceneVerts[4], sceneVerts[5],
                        sceneVerts[6], sceneVerts[7] );

    camVerts  [8].setValues(TypeTraits<Real32>::getMax(),
                            TypeTraits<Real32>::getMax(),
                            TypeTraits<Real32>::getMax() );
    camVerts  [9].setValues(TypeTraits<Real32>::getMin(),
                            TypeTraits<Real32>::getMin(),
                            TypeTraits<Real32>::getMin() );
    sceneVerts[8].setValues(TypeTraits<Real32>::getMax(),
                            TypeTraits<Real32>::getMax(),
                            TypeTraits<Real32>::getMax() );
    sceneVerts[9].setValues(TypeTraits<Real32>::getMin(),
                            TypeTraits<Real32>::getMin(),
                            TypeTraits<Real32>::getMin() );

    for(UInt32 i = 0; i < 8; ++i)
    {
        matWorldToLight.mult(camVerts  [i], camVerts  [i]);

        matSceneToWorld.mult(sceneVerts[i], sceneVerts[i]);
        matWorldToLight.mult(sceneVerts[i], sceneVerts[i]);

        camVerts  [8][0] = osgMin(camVerts  [8][0], camVerts  [i][0]);
        camVerts  [9][0] = osgMax(camVerts  [9][0], camVerts  [i][0]);
        camVerts  [8][1] = osgMin(camVerts  [8][1], camVerts  [i][1]);
        camVerts  [9][1] = osgMax(camVerts  [9][1], camVerts  [i][1]);

        sceneVerts[8][0] = osgMin(sceneVerts[8][0], sceneVerts[i][0]);
        sceneVerts[9][0] = osgMax(sceneVerts[9][0], sceneVerts[i][0]);
        sceneVerts[8][1] = osgMin(sceneVerts[8][1], sceneVerts[i][1]);
        sceneVerts[9][1] = osgMax(sceneVerts[9][1], sceneVerts[i][1]);
        sceneVerts[8][2] = osgMin(sceneVerts[8][2], sceneVerts[i][2]);
        sceneVerts[9][2] = osgMax(sceneVerts[9][2], sceneVerts[i][2]);
    }

    // these points are the corners of the ortho shadow view volume
    Pnt3f lightMin(osgMax(camVerts[8][0], sceneVerts[8][0]),
                   osgMax(camVerts[8][1], sceneVerts[8][1]),
                   -sceneVerts[9][2]);
    
    Pnt3f lightMax(osgMin(camVerts[9][0], sceneVerts[9][0]),
                   osgMin(camVerts[9][1], sceneVerts[9][1]),
                   -sceneVerts[8][2]);

    // enlarge by 2% in x, y, z direction
    lightMin[0] -= (lightMax[0] - lightMin[0]) * 0.01f;
    lightMin[1] -= (lightMax[1] - lightMin[1]) * 0.01f; 
    lightMin[2] -= (lightMax[2] - lightMin[2]) * 0.01f;

    lightMax[0] += (lightMax[0] - lightMin[0]) * 0.01f;
    lightMax[1] += (lightMax[1] - lightMin[1]) * 0.01f;
    lightMax[2] += (lightMax[2] - lightMin[2]) * 0.01f;

    Matrix matLightProj;
    Matrix matLightProjTrans;

    MatrixOrthogonal(matLightProj,
                     lightMin[0], lightMax[0],
                     lightMin[1], lightMax[1],
                     lightMin[2], lightMax[2] );

    updateShadowTexImage  (data);
    updateShadowTexBuffers(data);
    updateRenderTargets   (data);

    Int32 shadowTexUnit = (this->getForceTextureUnit() > 0) ?
                           this->getForceTextureUnit()      : 7;

    ShaderProgram *shadowFP = this->getShadowFragmentProgram();

    if(shadowFP == NULL)
    {
        ShaderProgramUnrecPtr newShadowFP = ShaderProgram::createLocal();
        newShadowFP->setShaderType(GL_FRAGMENT_SHADER);
        newShadowFP->setProgram   (_dirFPCode        );

        newShadowFP->addUniformVariable("SSME_matEyeToLight", matEyeToLight);
        newShadowFP->addUniformVariable("SSME_matLightProj",  matLightProj );
        newShadowFP->addUniformVariable("SSME_texShadow",     shadowTexUnit);

        this->setShadowFragmentProgram(newShadowFP);
        shadowFP = newShadowFP;
    }
    else
    {
        shadowFP->updateUniformVariable("SSME_matEyeToLight", matEyeToLight);
        shadowFP->updateUniformVariable("SSME_matLightProj",  matLightProj );
    }

    commitChanges();

    this->pushPartition(ract);
    {
        RenderPartition   *part   = ract->getActivePartition( );
        Window            *win    = ract->getWindow         ( );
        FrameBufferObject *target = data->getRenderTargets  (0);
        Background        *back   = data->getBackground     ( );

        part->setRenderTarget(target);
        part->setWindow      (win   );

        part->calcViewportDimension(0.f, 0.f, 1.f, 1.f,
                                    target->getWidth (),
                                    target->getHeight() );

        part->setupProjection(matLightProj, matLightProjTrans);
        part->setupViewing   (matWorldToLight                );

        part->setNear        (parentPart->getNear());
        part->setFar         (parentPart->getFar ());

        part->calcFrustum    (                     );

        part->setBackground  (back                 );

        // force material for shadow map generation
        part->overrideMaterial(data->getLightPassMaterials(0),
                               ract->getActNode           ( ) );

        this->recurseFrom(ract, dirL);
        ract->useNodeList(false     );

        // undo override
        part->overrideMaterial(NULL,
                               ract->getActNode           ( ) );
    }
    this->popPartition(ract);
}
void ShaderShadowMapEngine::handlePointLightEnter(
    PointLight *pointL, RenderAction *ract, SSMEngineData *data)
{
    RenderPartition *parentPart = ract->getActivePartition();

    Matrix matEyeToWorld(parentPart->getCameraToWorld());
    Matrix matLightProj;

    Real32 lightNear;
    Real32 lightFar;

    calcPointLightRange(pointL, 0.001f,
                        parentPart->getNear(), parentPart->getFar(),
                        lightNear,             lightFar             );

    MatrixPerspective(matLightProj, Pi / 4.f, 1.f,
                      lightNear, lightFar         );

    Matrix matWorldToLight;
    Matrix matEyeToLight;

    calcPointLightMatrices(matWorldToLight, matEyeToLight,
                           pointL,          matEyeToWorld );

    updatePointLightShadowTexImage  (data);
    updatePointLightShadowTexBuffers(data);
    updatePointLightRenderTargets   (data);

    Int32 shadowTexUnit = (this->getForceTextureUnit() > 0) ?
                           this->getForceTextureUnit()      : 7;

    ShaderProgram *shadowFP = this->getShadowFragmentProgram();

    if(shadowFP == NULL)
    {
        ShaderProgramUnrecPtr newShadowFP = ShaderProgram::createLocal();
        newShadowFP->setShaderType(GL_FRAGMENT_SHADER);
        newShadowFP->setProgram   (_pointFPCode      );

        newShadowFP->addUniformVariable("SSME_matEyeToLight", matEyeToLight);
        newShadowFP->addUniformVariable("SSME_matLightProj",  matLightProj );
        newShadowFP->addUniformVariable("SSME_texShadow",     shadowTexUnit);

        this->setShadowFragmentProgram(newShadowFP);
        shadowFP = newShadowFP;
    }
    else
    {
        shadowFP->updateUniformVariable("SSME_matEyeToLight", matEyeToLight);
        shadowFP->updateUniformVariable("SSME_matLightProj",  matLightProj );
    }

    commitChanges();

    // schedule rendering of cube faces
    for(UInt16 i = 0; i < 6; ++i)
    {
        Matrix matWorldToLightFace(matWorldToLight);
        matWorldToLightFace.multLeft(_matCubeFaceInv[i]);

        this->pushPartition(ract);
        {
            RenderPartition   *part   = ract->getActivePartition( );
            Window            *win    = ract->getWindow         ( );
            FrameBufferObject *target = data->getRenderTargets  (i);
            Background        *back   = data->getBackground     ( );

            part->setRenderTarget(target);
            part->setWindow      (win   );

            part->calcViewportDimension(0.f, 0.f, 1.f, 1.f,
                                        target->getWidth (),
                                        target->getHeight() );

            part->setupProjection(matLightProj, Matrix::identity());
            part->setupViewing   (matWorldToLightFace             );

            part->setNear        (parentPart->getNear());
            part->setFar         (parentPart->getFar ());

            part->calcFrustum    (                     );

            part->setBackground  (back                 );

            // force material for shadow map generation
            part->overrideMaterial(data->getLightPassMaterials(0),
                                   ract->getActNode           ( ) );

            this->recurseFrom(ract, pointL);
            ract->useNodeList(false       );

            // undo override
            part->overrideMaterial(NULL,
                                   ract->getActNode           ( ) );
        }
        this->popPartition(ract);
    }
}
void DeferredShadingStage::setupShadingPartition(
    RenderPartition *part, RenderAction *ract, DSStageData *data)
{
    Window            *win    = ract->getWindow           ();
    FrameBufferObject *target = data->getShadingTarget    ();
    Camera            *cam    = this->getCamera           ();
    Background        *back   = this->getBackground       ();

    part->setRenderTarget(target);
    part->setWindow      (win   );

    if(target != NULL)
    {
        part->calcViewportDimension(this->getLeft    (),
                                    this->getBottom  (),
                                    this->getRight   (),
                                    this->getTop     (),

                                    target->getWidth (),
                                    target->getHeight() );
    }
    else if(win != NULL)
    {
        part->calcViewportDimension(this->getLeft  (),
                                    this->getBottom(),
                                    this->getRight (),
                                    this->getTop   (),

                                    win->getWidth  (),
                                    win->getHeight () );
    }
    else
    {
        SWARNING << "DeferredShadingStage::setupShadingPartition: "
                 << "No target or window." << std::endl;
    }

    // setup ortho projection
    Matrix matProjection;
    Matrix matProjectionTranslation;
    Matrix matViewing;

    matProjectionTranslation.setIdentity();
    matViewing              .setIdentity();

    MatrixOrthogonal(matProjection,
                     -1.f, 1.f,
                     -1.f, 1.f,
                     -1.f, 1.f );

    part->setupProjection(matProjection, matProjectionTranslation);
    part->setupViewing   (matViewing                             );

    part->setNear(-1.f);
    part->setFar ( 1.f);

    // setup VPCamera matrices to original projection -- TODO copy from GBuffer pass?
    cam->getProjection           (matProjection,
                                  part->getViewportWidth (),
                                  part->getViewportHeight() );
    cam->getProjectionTranslation(matProjectionTranslation,
                                  part->getViewportWidth (),
                                  part->getViewportHeight() );

    Matrix matProjectionFull = matProjection;
    matProjectionFull.mult(matProjectionTranslation);

    Matrix matToWorld;
    Matrix matWorldToScreen;

    cam->getViewing(matViewing, part->getViewportWidth (),
                                part->getViewportHeight() );
    matToWorld.invertFrom(matViewing);

    matWorldToScreen = matProjectionFull;
    matWorldToScreen.mult(matToWorld);

    part->setVPCameraMatrices(matProjectionFull,
                              matProjection,
                              matProjectionTranslation,
                              matViewing,
                              matToWorld,
                              matWorldToScreen          );

    part->setBackground(back);

    part->setSetupMode(RenderPartition::ProjectionSetup |
                       RenderPartition::BackgroundSetup  );
}
Ejemplo n.º 26
0
void DrawShader::Draw(glm::vec3 flowerFade,
      const FrameBufferObject& shadow_map_fbo_,
      const FrameBufferObject& reflection_fbo,
      const FrameBufferObject& deferred_diffuse_fbo_,
      const FrameBufferObject& deferred_position_fbo_,
      const FrameBufferObject& deferred_normal_fbo_,
      const vector<CulledDrawable>& culledDrawables,
      const glm::mat4& viewMatrix,
      int useBlinnPhong,
      const glm::vec3& deerPos,
      const glm::vec3& sunDir,
      float sunIntensity,
      int lightning) {

   glm::mat4 curView; //For deferred shading.

   for(auto& shader_pair : shaders.getMap()) {
      Shader& shader = shader_pair.second;
      shader.use();
      switch (shader_pair.first) {
         case ShaderType::SHADOW:
            if(printCurrentShaderName)
               printf("Shadow\n");
            {
               const auto shadow_view = glm::lookAt(sunDir + deerPos, deerPos, glm::vec3(0.0, 1.0, 0.0));
               const auto view_projection = kShadowProjection * shadow_view;
               // Shadow Culling.
               Frustum frustum(view_projection);
               const auto shadow_drawables = frustum.cullShadowDrawables(culledDrawables);
               if(!debug) {
                  shadow_map_fbo_.bind();
                  glClear(GL_DEPTH_BUFFER_BIT);
               }
               {
                  glPolygonMode(GL_FRONT, GL_FILL);
                  const auto drawables = Drawable::fromCulledDrawables(shadow_drawables, CullType::VIEW_CULLING);
                  for (auto& drawable : drawables) {
                     SendBones(shader, drawable);
                     if (drawable.draw_template.effects.count(EffectType::CASTS_SHADOW)) {
                        SendTexture(shader, drawable);
                        for(auto& instance : drawable.draw_instances) {
                           shader.sendUniform(Uniform::MODEL_VIEW_PROJECTION, uniforms,
                                 view_projection * instance.model_transform);
                           shader.sendUniform(Uniform::MODEL, uniforms, instance.model_transform);
                           shader.drawMesh(drawable.draw_template.mesh);
                        }
                     }
                  }
               }

               if(!debug) {
                  glBindFramebuffer(GL_FRAMEBUFFER, 0);
                  shadow_map_fbo_.texture().enable(texture_cache_);
               }
            }
            break;

         case ShaderType::REFLECTION:
            if (!gReflections) break;
            {
               reflection_fbo.bind();
               glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
               // Cheap hack: just use view culling.
               auto drawables = Drawable::fromCulledDrawables(culledDrawables, CullType::VIEW_CULLING);
               // scale everything across the ground.
               const auto scale = glm::scale(glm::mat4(), glm::vec3(1, -1, 1));
               for (std::vector<Drawable>::iterator iter = drawables.begin(); iter != drawables.end();) {
                  // Cheap hack to get rid of the ground plane. DEADLINE
                  // APPROACHES.
                  if (iter->draw_template.height_map) {
                     iter = drawables.erase(iter);
                  } else {
                     for (auto& instance : iter->draw_instances) {
                        instance.model_transform = scale * instance.model_transform;
                     }
                     ++iter;
                  }
               }
               const auto reflectSunDir = glm::vec3(scale * glm::vec4(sunDir, 0));

               shader.sendUniform(Uniform::HAS_SHADOWS, uniforms, 0);
               shader.sendUniform(Uniform::USE_BLINN_PHONG, uniforms, useBlinnPhong);

               glFrontFace(GL_CW);
               drawTextureShader(true, shader, drawables, viewMatrix, reflectSunDir, sunIntensity,
                     lightning, reflection_fbo);
               glFrontFace(GL_CCW);
            }
            break;

         case ShaderType::TEXTURE:
            if (!useTextureShader) break;
            if(printCurrentShaderName)
               printf("Texture\n");

            glBindFramebuffer(GL_FRAMEBUFFER, 0);

            {
               const auto drawables = Drawable::fromCulledDrawables(culledDrawables, CullType::VIEW_CULLING);
               shader.sendUniform(Uniform::USE_BLINN_PHONG, uniforms, useBlinnPhong);

               SendShadow(shader, uniforms, shadow_map_fbo_, deerPos, sunDir);
               SendScreenSize(shader, uniforms);
               
               drawTextureShader(false, shader, drawables, viewMatrix, sunDir, sunIntensity,
                     lightning, reflection_fbo);
            }
            break;

         case ShaderType::SKYBOX:
            if(printCurrentShaderName)
               printf("Skybox\n");
            shader.sendUniform(Uniform::PROJECTION, uniforms, gProjectionMatrix);

            for (auto& drawable : culledDrawables) {
               if (drawable.draw_template.shader_type == ShaderType::SKYBOX) {
                  /* doesn't use drawModelTransforms because no normals */
                  for(const auto& instance : drawable.draw_instances) {
                     shader.sendUniform(Uniform::TEXTURE, uniforms,
                           (*drawable.draw_template.texture).texture_slot());
                     (*drawable.draw_template.texture).enable(texture_cache_);

                     if (drawable.draw_template.effects.count(EffectType::IS_TITLE_SCREEN)) {
                        shader.sendUniform(Uniform::IS_TITLE_SCREEN, uniforms, 1);
                        curView = glm::lookAt( glm::vec3(2.0f, 0.f,0.0f),glm::vec3(0.f, 0.f, 0.f),glm::vec3( 0.0f, 1.0f, 0.0f ) ); 
                     }
                     else {
                        shader.sendUniform(Uniform::IS_TITLE_SCREEN, uniforms, 0);
                        curView = viewMatrix;
                     }

                     shader.sendUniform(Uniform::MODEL_VIEW, uniforms, 
                           curView * instance.instance.model_transform);
                     shader.drawMesh(drawable.draw_template.mesh);
                  }
               }
            }
            break;

         case ShaderType::DEFERRED:
            if (useTextureShader) break;
            if(printCurrentShaderName)
               printf("Deferred\n");
            for (size_t i = 0; i < LAST_DEFERRED; ++i) {
               DeferredType deferred_type = static_cast<DeferredType>(i);
               switch (deferred_type) {
                  case DEFERRED_DIFFUSE:
                     deferred_diffuse_fbo_.bind();
                     break;
                  case DEFERRED_POSITION:
                     deferred_position_fbo_.bind();
                     break;
                  case DEFERRED_NORMAL:
                     deferred_normal_fbo_.bind();
                     break;
                  default: break;
               }
               glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
            }

            SendShadow(shader, uniforms, shadow_map_fbo_, deerPos, sunDir);

            for (auto& drawable : culledDrawables) {
               Drawable newDrawable = Drawable::fromCulledDrawable(drawable, CullType::VIEW_CULLING);
               if (newDrawable.draw_template.shader_type == ShaderType::DEFERRED) {

               if (drawable.draw_template.effects.count(EffectType::IS_FLOWER))
                  shader.sendUniform(Uniform::FLOWER_FADE, uniforms, glm::vec3(1.0f));
               else 
                  shader.sendUniform(Uniform::FLOWER_FADE, uniforms, flowerFade);

                  newDrawable.draw_template.material.sendMaterial(shader, uniforms);
                  //SendHeightMap(shader, newDrawable);
                  SendBones(shader, newDrawable);
                  SendTexture(shader, newDrawable);
                  {
                     const int vary_material = drawable.draw_template.effects.count(EffectType::VARY_MATERIAL);
                     shader.sendUniform(Uniform::VARY_MATERIAL, uniforms, vary_material);
                  }
                  drawModelTransforms(shader, newDrawable, viewMatrix,
                        deferred_diffuse_fbo_,
                        deferred_position_fbo_,
                        deferred_normal_fbo_,
                        true, uniforms);
               }
            }
            glBindFramebuffer(GL_FRAMEBUFFER, 0);
            break;

         case ShaderType::FINAL_LIGHT_PASS:
            if (useTextureShader) break;
            glm::mat4 lookAt = glm::lookAt( glm::vec3(2.0f, 0.f,0.0f),glm::vec3(0.f, 0.f, 0.f),glm::vec3( 0.0f, 1.0f, 0.0f ) );
            glBindFramebuffer(GL_FRAMEBUFFER, 0);
            glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

            deferred_diffuse_fbo_.texture().enable(texture_cache_);
            shader.sendUniform(Uniform::FINAL_PASS_DIFFUSE_TEXTURE, uniforms, deferred_diffuse_fbo_.texture_slot());
            deferred_position_fbo_.texture().enable(texture_cache_);
            shader.sendUniform(Uniform::FINAL_PASS_POSITION_TEXTURE, uniforms, deferred_position_fbo_.texture_slot());
            deferred_normal_fbo_.texture().enable(texture_cache_);
            shader.sendUniform(Uniform::FINAL_PASS_NORMAL_TEXTURE, uniforms, deferred_normal_fbo_.texture_slot());

            SendSun(shader, uniforms, sunIntensity, sunDir);
            shader.sendUniform(Uniform::PROJECTION, uniforms, gProjectionMatrix);
            SendScreenSize(shader, uniforms);
            shader.sendUniform(Uniform::LIGHTNING, uniforms, lightning);

            for (auto& drawable : culledDrawables) {
               Drawable newDrawable = Drawable::fromCulledDrawable(drawable, CullType::VIEW_CULLING);

               if(newDrawable.draw_template.shader_type == ShaderType::FINAL_LIGHT_PASS) {

                  if (drawable.draw_template.effects.count(EffectType::IS_WATER)) {
                     shader.sendUniform(Uniform::IS_WATER, uniforms, 1);
                     shader.sendUniform(Uniform::TEXTURE, uniforms, reflection_fbo.texture_slot());  
                     reflection_fbo.texture().enable(texture_cache_);
                  }
                  else
                     shader.sendUniform(Uniform::IS_WATER, uniforms, 0);

                  shader.sendUniform(Uniform::IS_FIREFLY, uniforms, 0);
                  if (drawable.draw_template.effects.count(EffectType::IS_GOD_RAY)) {
                     shader.sendUniform(Uniform::IS_GOD_RAY, uniforms, 1);
                     if(drawable.draw_template.effects.count(EffectType::IS_FIREFLY))
                        shader.sendUniform(Uniform::IS_FIREFLY, uniforms, 1);
                     curView = viewMatrix;
                  }
                  else if(drawable.draw_template.effects.count(EffectType::IS_WATER)) {
                     curView = viewMatrix;
                  }
                  else {
                     shader.sendUniform(Uniform::IS_GOD_RAY, uniforms, 0);
                     curView = lookAt;
                  }

                  for(const auto& instance : drawable.draw_instances) {
                     if (drawable.draw_template.effects.count(EffectType::IS_GOD_RAY)) {
                        glm::vec3 ray_pos = glm::vec3(instance.instance.model_transform * glm::vec4(0,0,0,1));
                        shader.sendUniform(Uniform::GOD_RAY_CENTER, uniforms, ray_pos);
                     }
                     shader.sendUniform(Uniform::MODEL, uniforms, instance.instance.model_transform);
                     shader.sendUniform(Uniform::VIEW, uniforms, curView);
                     shader.sendUniform(Uniform::NORMAL, uniforms,
                           glm::transpose(glm::inverse(curView * instance.instance.model_transform)));
                     shader.drawMesh(drawable.draw_template.mesh);
                  }
               }
            }
            break;
      }
   }
}
Ejemplo n.º 27
0
Action::ResultE PostShaderStage::renderEnter(Action *action)
{
    RenderAction *a = dynamic_cast<RenderAction *>(action);

    a->disableDefaultPartition();

    this->beginPartitionGroup(a);
    {
        this->pushPartition(a);
        {
            RenderPartition   *pPart    = a->getActivePartition();
            FrameBufferObject *pTarget  = this->getRenderTarget();
            Viewarea          *pArea    = a->getViewarea();
            Camera            *pCam     = a->getCamera  ();
            Background        *pBack    = a->getBackground();
            
            if(pTarget == NULL)
            {
                this->initData(a);

                pTarget  = this->getRenderTarget();
            }

            pPart->setRenderTarget(pTarget);
            
#ifdef OSG_DEBUGX
            std::string szMessage("RenderPartition\n");
            pPart->setDebugString(szMessage          );
#endif

            if(pArea != NULL)
            {
//                pPart->setViewport(pPort         );
                pPart->setWindow  (a->getWindow());
                
                if(pTarget != NULL)
                {
#if 0
                    pPart->calcViewportDimension(pArea->getLeft  (),
                                                 pArea->getBottom(),
                                                 pArea->getRight (),
                                                 pArea->getTop   (),
                                                 
                                                 pTarget->getWidth    (),
                                                 pTarget->getHeight   ());

#endif
                    pPart->calcViewportDimension(0.f,
                                                 0.f,
                                                 1.f,
                                                 1.f,
                                                 
                                                 pTarget->getWidth    (),
                                                 pTarget->getHeight   ());

                }
                else
                {
                    pPart->calcViewportDimension(pArea->getLeft  (),
                                                 pArea->getBottom(),
                                                 pArea->getRight (),
                                                 pArea->getTop   (),
                                                 
                                                 a->getWindow()->getWidth (),
                                                 a->getWindow()->getHeight());
                }
                
                if(pCam != NULL)
                {
                    Matrix m, t;
                    
                    // set the projection
                    pCam->getProjection          (m, 
                                                  pPart->getViewportWidth (), 
                                                  pPart->getViewportHeight());
                    
                    pCam->getProjectionTranslation(t, 
                                                   pPart->getViewportWidth (), 
                                                   pPart->getViewportHeight());
                    
                    pPart->setupProjection(m, t);
                    
                    pCam->getViewing(m, 
                                     pPart->getViewportWidth (),
                                     pPart->getViewportHeight());
                    
                    
                    pPart->setupViewing(m);
                    
                    pPart->setNear     (pCam->getNear());
                    pPart->setFar      (pCam->getFar ());
                    
                    pPart->calcFrustum();
                }
                
                pPart->setBackground(pBack);
            }
            
            this->recurseFromThis(a);
        }
        this->popPartition(a);
        
        this->pushPartition(a,
                            (RenderPartition::CopyWindow      |
                             RenderPartition::CopyViewportSize),
                            RenderPartition::SimpleCallback    );
        {
            RenderPartition *pPart  = a->getActivePartition();

#ifdef OSG_DEBUGX
            std::string szMessage("PostProcessPartition\n");
            pPart->setDebugString(szMessage          );
#endif
           
            Matrix m, t;
                
            m.setIdentity();
            t.setIdentity();
                
            MatrixOrthogonal( m,
                              0.f, 1.f,
                              0.f, 1.f,
                             -1.f, 1.f);
            
            pPart->setupProjection(m, t);
                
            RenderPartition::SimpleDrawCallback f;
                
            f = boost::bind(&PostShaderStage::postProcess, this, _1);
                
            pPart->dropFunctor(f);
        }
        this->popPartition(a);
    }
    this->endPartitionGroup(a);

    RenderPassVector::iterator passIt = _vPostProcessPasses.begin();

    //Update the uniform parameters to the shader
    for(; passIt != _vPostProcessPasses.end(); ++passIt)
    {
        (*passIt)->updateUniformVariables(a);
    }

    return Action::Skip;
}
void
DepthPeelingStage::setupRenderScene(RenderAction* a,
                                    Int32         iVPWidth,
                                    Int32         iVPHeight,
                                    bool          isInitial,
                                    bool          isPing    )
{
    this->pushPartition(a);
    {
        RenderPartition   *pPart   = a->getActivePartition();
        FrameBufferObject *pTarget = NULL;
        Viewarea          *pArea   = a->getViewarea       ();
        Camera            *pCam    = a->getCamera         ();
        Background        *pBack   = NULL;


        DepthPeelingStageDataUnrecPtr pData =
            a->getData<DepthPeelingStageData *>(_iDataSlotId);

        if(!pData)
        {
            this->initData(a, iVPWidth, iVPHeight);
        }
        else
        {
            this->updateData(a, iVPWidth, iVPHeight);
        }
        pData = a->getData<DepthPeelingStageData *>(_iDataSlotId);

        if (isInitial)
        {
            pTarget = pData->getBlendFBO();
            pBack   = a->getBackground  ();
        }
        else
        {
            if (isPing)
                pTarget = pData->getPeelPingFBO();
            else
                pTarget = pData->getPeelPongFBO();

            pBack = pData->getBackground();
        }
        pPart->setRenderTarget(pTarget);

        if(pArea != NULL)
        {
            pPart->setWindow  (a->getWindow());

            if(pTarget != NULL)
            {
                pPart->calcViewportDimension(pArea->getLeft  (),
                                                pArea->getBottom(),
                                                pArea->getRight (),
                                                pArea->getTop   (),

                                                pTarget->getWidth    (),
                                                pTarget->getHeight   ());
            }
            else
            {
                pPart->calcViewportDimension(pArea->getLeft  (),
                                                pArea->getBottom(),
                                                pArea->getRight (),
                                                pArea->getTop   (),

                                                a->getWindow()->getWidth (),
                                                a->getWindow()->getHeight());
            }

            if(pCam != NULL)
            {
                Matrix m, t;

                // set the projection
                pCam->getProjection          (m,
                                                pPart->getViewportWidth (),
                                                pPart->getViewportHeight());

                pCam->getProjectionTranslation(t,
                                                pPart->getViewportWidth (),
                                                pPart->getViewportHeight());

                pPart->setupProjection(m, t);

                pCam->getViewing(m,
                                    pPart->getViewportWidth (),
                                    pPart->getViewportHeight());


                pPart->setupViewing(m);

                pPart->setNear     (pCam->getNear());
                pPart->setFar      (pCam->getFar ());

                pPart->calcFrustum();
            }

            pPart->setBackground(pBack);
        }

        pPart->addSetupModeBit(RenderPartition::BackgroundSetup);

        pPart->pushState();
        if (!isInitial)
        {
            FrameBufferObject* fbo           =
                isPing ? pData->getPeelPongFBO() : pData->getPeelPingFBO();
            TextureBuffer*     texbuf        =
                static_cast<TextureBuffer *>(fbo->getDepthAttachment());
            TextureObjChunk*   depthTexChunk = texbuf->getTexture();

            pPart->addOverride(depthTexChunk->getClassId() + getDepthTexUnit(),
                               depthTexChunk                                   );
            pPart->addOverride(pData->getSpvIsPeelChunk()->getClassId(),
                               pData->getSpvIsPeelChunk()               );
        }
        else
        {
            pPart->addOverride(pData->getSpvIsInitialChunk()->getClassId(),
                               pData->getSpvIsInitialChunk()               );
        }

        pPart->addOverride(pData->getDepthChunk()->getClassId(),
                           pData->getDepthChunk()               );

        this->recurseFromThis(a);
        a->useNodeList(false);

        pPart->popState();
    }
    this->popPartition(a);
}
Ejemplo n.º 29
0
Archivo: main.cpp Proyecto: c-day/Warp
void RenderIntoBuffer(FrameBufferObject fbo, GLuint handle) 
{
	fbo.Bind();
	glDisable(GL_DEPTH_TEST);
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	glOrtho(-fbo.size.x/2, fbo.size.x/2, -fbo.size.y/2, fbo.size.y/2, 1, 10);

	if (sh_vertices.size() == 0)
	{
		for (float i = -1.0; i <= 1.0; i += 0.01f)
		{
			for (float j = -1.0; j <= 1.0; j += 0.01f )
			{
				sh_vertices.push_back(glm::vec2( j, i ));
				sh_vertices.push_back(glm::vec2( j + 0.01, i ));
				sh_vertices.push_back(glm::vec2( j + 0.01, i + 0.01));
				sh_vertices.push_back(glm::vec2( j, i + 0.01));

				tex_vertices.push_back(glm::vec2( (j+1)/2.0f, (i+1)/2.0f ));
				tex_vertices.push_back(glm::vec2( ((j + 0.01)+1)/2.0f, (i+1)/2.0f ));
				tex_vertices.push_back(glm::vec2( ((j + 0.01)+1)/2.0f, ((i + 0.01)+1)/2.0f));
				tex_vertices.push_back(glm::vec2( (j+1)/2.0f, ((i + 0.01)+1)/2.0f));
				//Uncomment the code below to see the vertices
				/*
				cout << "Vertex Coords: " << i << ", " << j << " - ";
				cout << i + 0.01 << ", " << j << " - ";
				cout << i + 0.01 << ", " << j + 0.01 << " - ";
				cout << i << ", " << j + 0.01 << endl;
				//*/
			}
		}

		glGenBuffers(1, &vertex_coordinate_handle);
		assert(vertex_coordinate_handle != (GLuint) -1);
		glBindBuffer(GL_ARRAY_BUFFER, vertex_coordinate_handle);
		glBufferData(GL_ARRAY_BUFFER, sh_vertices.size() * sizeof(glm::vec2), &sh_vertices[0], GL_STATIC_DRAW);

		glGenBuffers(1, &tex_coord_handle);
		assert(tex_coord_handle != (GLuint) -1);
		glBindBuffer(GL_ARRAY_BUFFER, tex_coord_handle);
		glBufferData(GL_ARRAY_BUFFER, tex_vertices.size() * sizeof(glm::vec2), &tex_vertices[0], GL_STATIC_DRAW);

		glGenVertexArrays(1, &vertex_array_handle);
		glBindVertexArray(vertex_array_handle);
		glEnableVertexAttribArray(0);
		glEnableVertexAttribArray(1);

		glBindBuffer(GL_ARRAY_BUFFER, vertex_coordinate_handle);
		glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, (GLubyte *) NULL);
		glBindBuffer(GL_ARRAY_BUFFER, tex_coord_handle);
		glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, (GLubyte *) NULL);

		glBindVertexArray(0);
		glBindBuffer(GL_ARRAY_BUFFER, 0);
	}
	
	shader.Use();
	glUniform2i(shader.size_handle, fbo.size.x, fbo.size.y);
	glUniform2f(shader.mouse_handle, mouse.x, mouse.y);
	glUniform2f(shader.mouse_start_handle, mouse_start.x, mouse_start.y);

	glBindTexture(GL_TEXTURE_2D, handle);
	glUniform1i(shader.image_handle, GL_TEXTURE0 + handle);

	glViewport(0, 0, fbo.size.x, fbo.size.y);

	glClearColor(0, 0, 0.5, 0);
	glClear(GL_COLOR_BUFFER_BIT);

	assert(vertex_array_handle != (GLuint) -1);
	glBindVertexArray(vertex_array_handle);
	glDrawArrays(GL_QUADS, 0, (GLsizei) sh_vertices.size());

	glBindVertexArray(0);
	glUseProgram(0);
	glEnable(GL_DEPTH_TEST);
	fbo.Unbind();
}
Ejemplo n.º 30
0
Archivo: main.cpp Proyecto: c-day/Warp
void CloseFunc()
{
	shader.TakeDown();
	frame.TakeDown();
}