我正在使用Cocos2d-X 2.2.3和Marmalade SDK 7.4开发游戏,我创建了一个片段着色器来减少我的一些精灵,或者换句话说,从它们中删除所有颜色并仅以阴影显示它们灰色(黑色和白色)。
我写的着色器是这样的:
#ifdef GL_ES
precision mediump float;
#endif
varying vec2 v_texCoord;
uniform sampler2D u_texture;
void main()
{
float grayScaleValue;
vec3 originalColor;
originalColor = texture2D(u_texture, v_texCoord).rgb;
grayScaleValue = 0.21 * originalColor.r + 0.72 * originalColor.g + 0.07 * originalColor.b;
gl_FragColor = vec4(grayScaleValue, grayScaleValue, grayScaleValue, 1);
}
我采用算法来计算this页面的灰度值。
我用来加载此着色器的代码如下:
// Please note that the class: GameObjectSprite is a subclass of CCSprite.
void GameObjectSprite::initShaders()
{
const GLchar *shaderSource = (const GLchar*) CCString::createWithContentsOfFile("shaders/Grayscale.fsh")->getCString();
shader = new CCGLProgram();
shader->initWithVertexShaderByteArray(ccPositionTextureA8Color_vert, shaderSource);
shader->addAttribute(kCCAttributeNamePosition, kCCVertexAttribFlag_Position);
shader->addAttribute(kCCAttributeNameColor, kCCVertexAttribFlag_TexCoords);
CHECK_GL_ERROR_DEBUG();
shader->link();
shader->updateUniforms();
CHECK_GL_ERROR_DEBUG();
this->setShaderProgram(shader);
this->getShaderProgram()->use();
}
不幸的是,我的着色器无法正常工作,并且精灵正在显示正常的颜色,就像我没有对其着色器进行任何更改一样。
答案 0 :(得分:0)
我设法解决了这个问题。我认为,正如@glampert所说我没有正确加载MVP矩阵。这是我的新代码:
void GameLayer::loadShaders()
{
CCGLProgram *shader;
const GLchar *fragmentShader;
shader = new CCGLProgram();
fragmentShader = CCString::stringWithContentsOfFile("Grayscale.fsh")->getCString();
shader->initWithVertexShaderByteArray(ccPositionTextureA8Color_vert, fragmentShader);
shader->addAttribute(kCCAttributeNamePosition, kCCVertexAttrib_Position);
shader->addAttribute(kCCAttributeNameTexCoord, kCCVertexAttrib_TexCoords);
CHECK_GL_ERROR_DEBUG();
shader->link();
shader->updateUniforms();
CHECK_GL_ERROR_DEBUG();
sprite->setShaderProgram(shader);
sprite->getShaderProgram()->use();
}
请注意,我更改了以下行的值:
shader->addAttribute(kCCAttributeNamePosition, kCCVertexAttribFlag_Position);
shader->addAttribute(kCCAttributeNameColor, kCCVertexAttribFlag_TexCoords);
要:
shader->addAttribute(kCCAttributeNamePosition, kCCVertexAttrib_Position);
shader->addAttribute(kCCAttributeNameTexCoord, kCCVertexAttrib_TexCoords);
另外,我不再使用sprite批处理节点来绘制我的精灵。