cocos2dx中使用自定义uniform变量

cocos2dx引擎本身提供了一定数量的uniform

static const char * COCOS2D_SHADER_UNIFORMS =
        "uniform mat4 CC_PMatrix;\n"
        "uniform mat4 CC_MVMatrix;\n"
        "uniform mat4 CC_MVPMatrix;\n"
        "uniform mat3 CC_NormalMatrix;\n"
        "uniform vec4 CC_Time;\n"
        "uniform vec4 CC_SinTime;\n"
        "uniform vec4 CC_CosTime;\n"
        "uniform vec4 CC_Random01;\n"
        "uniform sampler2D CC_Texture0;\n"
        "uniform sampler2D CC_Texture1;\n"
        "uniform sampler2D CC_Texture2;\n"
        "uniform sampler2D CC_Texture3;\n"
        "//CC INCLUDES END\n\n";

但并不能满足我们所有的需要,这时就需要使用自定义uniform
首先写好我们的shader,带上自定义uniform变量

const char* vert = R"( attribute vec4 a_position; attribute vec2 a_texCoord; varying vec2 v_texCoord; void main() { gl_Position = CC_PMatrix * a_position; v_texCoord = a_texCoord; } )";

const char* frag = R"( varying vec2 v_texCoord; // 自定义uniform变量 uniform float custom; void main() { vec4 col = texture2D(CC_Texture0, v_texCoord); gl_FragColor = col*custom; gl_FragColor.a = col.a; } )";

下一步就需要在程序中设置这个uniform变量的值,我们可以每一帧对他进行一些改变,从而产生一些动画效果。

GLProgram* p = GLProgram::createWithByteArrays(vert, frag);
GLProgramCache::getInstance()->addGLProgram(p, "custom");

auto sprite = Sprite::create("HelloWorld.png");
addChild(sprite);
sprite->setPosition(visibleSize.width / 2, visibleSize.height / 2);
auto shaderState = GLProgramState::getOrCreateWithGLProgramName("custom");
//设置自定义uniform变量的值
shaderState->setUniformFloat("custom", 0.2f);
sprite->setGLProgramState(shaderState);

你可能感兴趣的:(cocos2d-x)