最新教程和源码请访问公众号
本来采用更改图片像素点变灰,现在需要还原,便用shader,发现变灰和还原后悔改变图片的位置,于是又寻找解决办法~
变灰和还原的函数
void addGray(Sprite* sprite)
{
if(sprite)
{
GLProgram * p = new GLProgram();
p->initWithFilenames("gray.vsh", "gray.fsh");
p->bindAttribLocation(GLProgram::ATTRIBUTE_NAME_POSITION, GLProgram::VERTEX_ATTRIB_POSITION);
p->bindAttribLocation(GLProgram::ATTRIBUTE_NAME_COLOR, GLProgram::VERTEX_ATTRIB_COLOR);
p->bindAttribLocation(GLProgram::ATTRIBUTE_NAME_TEX_COORD, GLProgram::VERTEX_ATTRIB_TEX_COORDS);
p->link();
p->updateUniforms();
sprite->setShaderProgram(p);
}
}
网上down的gray.vsh变灰后改变位置解决办法:CC_MVPMatrix 改为CC_PMatrix
void removeGray(Sprite* sprite)
{
CCGLProgram* p = CCShaderCache::sharedShaderCache()->programForKey(GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR_NO_MVP);
sprite->setShaderProgram(p);
}
还原本应该设置为GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR,但是有会发生位置改变~所以改为GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR_NO_MVP
使用自己的shader,会崩溃,解决办法:
std::string GLProgram::logForOpenGLObject(GLuint object, GLInfoFunction infoFunc, GLLogFunction logFunc) const
{
std::string ret;
GLint logLength = 0, charsWritten = 0;
//infoFunc(object, GL_INFO_LOG_LENGTH, &logLength); //这里就崩溃了~~ 不知道为什么
glGetShaderiv(object, GL_INFO_LOG_LENGTH, &logLength); //直接改成调用opengel函数,
if (logLength < 1)
return "";
char *logBytes = (char*)malloc(logLength);
// logFunc(object, logLength, &charsWritten, logBytes); //同上
glGetShaderInfoLog(object, logLength, &charsWritten, logBytes);
ret = logBytes;
free(logBytes);
return ret;
}
文件:
gray.fsh:
varying vec4 v_fragmentColor;
varying vec2 v_texCoord;
void main()
{
vec4 v_orColor = v_fragmentColor * texture2D(CC_Texture0, v_texCoord);
float gray = dot(v_orColor.rgb, vec3(0.299, 0.587, 0.114));
gl_FragColor = vec4(gray, gray, gray, v_orColor.a);
}
gray.vsh:
attribute vec4 a_position;
attribute vec2 a_texCoord;
attribute vec4 a_color;
varying vec4 v_fragmentColor;
varying vec2 v_texCoord;
void main()
{
gl_Position = CC_PMatrix * a_position;
v_fragmentColor = a_color;
v_texCoord = a_texCoord;
}