使用OpenGL shader做一个能变灰的精灵

.h


class GraySprite :public Sprite

{

public:

    GraySprite();

    GraySprite(constchar* fileName);

   void setGray(bool bGray);

private:

   bool m_bGray;

};



.cpp


GraySprite::GraySprite()

{

    this->initWithFile("HelloWorld.png");

    this->setAnchorPoint(Vec2(0.5,0.5));

}


GraySprite::GraySprite(constchar* fileName)

{

   this->initWithFile(fileName);

    this->setAnchorPoint(Vec2(0.5,0.5));

}


voidGraySprite::setGray(bool bGray)

{

   if (m_bGray==bGray) {

       return;

    }

   m_bGray = bGray;

   if (bGray) {

       GLchar* pszFragSource = (GLchar*)

        "#ifdef GL_ES \n \

        precision mediump float; \n \

        #endif \n \

        uniform sampler2D u_texture; \n \

        varying vec2 v_texCoord; \n \

        varying vec4 v_fragmentColor; \n \

        void main(void) \n \

        { \n \

        // Convert to greyscale using NTSC weightings \n \

        vec4 col = texture2D(u_texture, v_texCoord); \n \

        float grey = dot(col.rgb, vec3(0.299, 0.587, 0.114)); \n \

        gl_FragColor = vec4(grey, grey, grey, col.a); \n \

        }";

        

       GLProgram* pProgram = new GLProgram();

        pProgram->initWithByteArrays(ccPositionTextureColor_noMVP_vert, pszFragSource);

       this->setGLProgram(pProgram);

        pProgram->release();

        CHECK_GL_ERROR_DEBUG();

        

        pProgram =this->getGLProgram();

        pProgram->bindAttribLocation(GLProgram::ATTRIBUTE_NAME_POSITION,GLProgram::VERTEX_ATTRIB_POSITION);

        pProgram->bindAttribLocation(GLProgram::ATTRIBUTE_NAME_COLOR,GLProgram::VERTEX_ATTRIB_COLOR);

        pProgram->bindAttribLocation(GLProgram::ATTRIBUTE_NAME_TEX_COORD,GLProgram::VERTEX_ATTRIB_TEX_COORD);

        CHECK_GL_ERROR_DEBUG();

        

        pProgram->link();

        CHECK_GL_ERROR_DEBUG();

        

        pProgram->updateUniforms();

        CHECK_GL_ERROR_DEBUG();

    }

   else{

        setGLProgramState(GLProgramState::getOrCreateWithGLProgramName(GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR_NO_MVP));

    }

}



你可能感兴趣的:(cocos2dx)