#include "DeferredShader.h" #include "FrameBufferObject.h" #include "RenderState.h" using namespace std; namespace CHCDemoEngine { static void PrintGLerror(char *msg) { GLenum errCode; const GLubyte *errStr; if ((errCode = glGetError()) != GL_NO_ERROR) { errStr = gluErrorString(errCode); fprintf(stderr,"OpenGL ERROR: %s: %s\n", errStr, msg); } } static CGprogram sCgDeferredProgram; static CGparameter sColorsTexParam; static CGparameter sPositionsTexParam; static CGparameter sNormalsTexParam; DeferredShader::DeferredShader(int w, int h): mWidth(w), mHeight(h) {} DeferredShader::~DeferredShader() { if (sCgDeferredProgram) cgDestroyProgram(sCgDeferredProgram); } void DeferredShader::Init(CGcontext context) { sCgDeferredProgram = cgCreateProgramFromFile(context, CG_SOURCE, "src/shaders/deferred.cg", RenderState::sCgFragmentProfile, "main", NULL); if (sCgDeferredProgram != NULL) { cgGLLoadProgram(sCgDeferredProgram); // we need size of texture for scaling sPositionsTexParam = cgGetNamedParameter(sCgDeferredProgram, "positions"); sColorsTexParam = cgGetNamedParameter(sCgDeferredProgram, "colors"); sNormalsTexParam = cgGetNamedParameter(sCgDeferredProgram, "normals"); } else cerr << "deferred program failed to load" << endl; PrintGLerror("init"); } void DeferredShader::Render(FrameBufferObject *fbo) { FrameBufferObject::Release(); GLuint colorsTex = fbo->GetColorBuffer(0)->GetTexture(); GLuint positionsTex = fbo->GetColorBuffer(1)->GetTexture(); GLuint normalsTex = fbo->GetColorBuffer(2)->GetTexture(); glPushAttrib(GL_VIEWPORT_BIT); glViewport(0, 0, mWidth, mHeight); glDisable(GL_ALPHA_TEST); glDisable(GL_TEXTURE_2D); glDisable(GL_LIGHTING); glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); const float offs = 0.5f; glOrtho(-offs, offs, -offs, offs, 0, 1); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); cgGLEnableProfile(RenderState::sCgFragmentProfile); cgGLBindProgram(sCgDeferredProgram); cgGLSetTextureParameter(sColorsTexParam, colorsTex); cgGLEnableTextureParameter(sColorsTexParam); cgGLSetTextureParameter(sPositionsTexParam, positionsTex); cgGLEnableTextureParameter(sPositionsTexParam); cgGLSetTextureParameter(sNormalsTexParam, normalsTex); cgGLEnableTextureParameter(sNormalsTexParam); glColor3f(1.0f, 1.0f, 1.0f); glBegin(GL_QUADS); float offs2 = 0.5f; glTexCoord2f(0, 0); glVertex3f(-offs2, -offs2, -0.5f); glTexCoord2f(1, 0); glVertex3f( offs2, -offs2, -0.5f); glTexCoord2f(1, 1); glVertex3f( offs2, offs2, -0.5f); glTexCoord2f(0, 1); glVertex3f(-offs2, offs2, -0.5f); glEnd(); cgGLDisableTextureParameter(sColorsTexParam); cgGLDisableTextureParameter(sPositionsTexParam); cgGLDisableTextureParameter(sNormalsTexParam); cgGLDisableProfile(RenderState::sCgFragmentProfile); glEnable(GL_LIGHTING); glDisable(GL_TEXTURE_2D); glMatrixMode(GL_PROJECTION); glPopMatrix(); glMatrixMode(GL_MODELVIEW); glPopMatrix(); glPopAttrib(); PrintGLerror("deferred shading"); } } // namespace