為了讓jsb也能順利跑起濾鏡效果,在手機側折騰了2天,因為每次在真機上運行總要耗那么半分鍾,而且偶爾還遇到apk文件無法刪除導致運行失敗的情況。
這個調試起來,實在讓人煩躁加沮喪。
還好,測試上百輪,翻jsb代碼+各種猜測實驗之后,終於順利的把前3個系列的例子都通通在Android上跑起來了,也算是把兼容問題調通了。
如下圖所示,右上角的小圖是多紋理效果,通過擴展cc.Node自行控制繪制頂點實現的;下方的兩個小圖是普通的cc.Sprite,對其加入了shaderProgram
總結一下,這里有幾個坑:
1、一些html5跑得很順利的接口(包括出現在官方例子中)在JSB中並沒有實現或綁定錯誤。
例如:initWithVertexShaderByteArray、
setUniformLocationF32
initWithVertexShaderByteArray是運行發現出錯的時候發現的,建議改用initWithString;
setUniformLocationF32很隱蔽,運行后沒有任何提示,但后來在jsb對應函數中打log,發現壓根就沒執行到那一步。建議使用gl.uniform1f,設置int等也一樣使用gl.uniform1i等。
2、JSB的gl.uniform1f,並沒有正確傳遞float值,接口錯誤把float強制以int32接收了,結果導致float的小數位都被截斷。
bool JSB_glUniform1f(JSContext *cx, uint32_t argc, jsval *vp) { JSB_PRECONDITION2( argc == 2, cx, false, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); bool ok = true; int32_t arg0; int32_t arg1; ok &= jsval_to_int32( cx, *argvp++, &arg0 ); ok &= jsval_to_int32( cx, *argvp++, &arg1 ); JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); GLfloat arg1a = (GLfloat)arg1; CCLOG("UNIFORM, %f", arg1a); //調試加入的代碼,輸出0.0000。實際傳入的是0.9 glUniform1f((GLint)arg0 , (GLfloat)arg1 ); JS_SET_RVAL(cx, vp, JSVAL_VOID); return true; }
3、3.0final和3.1兩個版本在fragment shader的處理上略有差別。3.0的html5版本,不會自動在fragment shader中加入uniform
CC_Texture0到4,但從3.0的jsb和3.1 jsb和html5都會自動增加這幾個uniform。
這個自動加入的問題是,如果原來shader手工寫上了CC_Texture0,就會無法正確編譯fragment shader。
這里建議是:
如果所有紋理都是自己手工綁定,那么這里可以用tex0等其他名字;
如果是擴展cc.Sprite的功能,則需要依賴框架給shader綁定紋理,所以這里需要保留使用CC_Texture0。可以不做聲明,直接在main中使用這個CC_Texture0。
varying vec2 v_texCoord; void main() { vec4 texColor = texture2D(CC_Texture0, v_texCoord); float gray = texColor.r * 0.299 + texColor.g * 0.587 + texColor.b * 0.114; gl_FragColor = vec4(gray,gray,gray,1); }
4、jsb中,如果剛新建glprogram就設置gl的uniform參數,之后可能會發現參數沒生效。原因可能是該Node/sprite在初始化的時候把glprogram重置過,丟掉了參數。
這個問題在html5版本中不存在。
這里建議是:
通過override(覆蓋)Node的draw方法或者sprite的update方法(並調用scheduleUpdate),讓每一幀從新設置gl參數。
sprite.scheduleUpdate(); sprite.update = function(){ program.use(); program.setUniformsForBuiltins(); var degreeLocation = program.getUniformLocationForName("u_degree"); gl.uniform1f( degreeLocation, degree); };
完整代碼:
var trace = function() { cc.log(Array.prototype.join.call(arguments, ", ")); }; var Filter = { DEFAULT_VERTEX_SHADER: "attribute vec4 a_position; \n" + "attribute vec2 a_texCoord; \n" + "varying mediump vec2 v_texCoord; \n" + "void main() \n" + "{ \n" + " gl_Position = (CC_PMatrix * CC_MVMatrix) * a_position; \n" + " v_texCoord = a_texCoord; \n" + "}", GRAY_SCALE_FRAGMENT_SHADER: "varying vec2 v_texCoord; \n" //+ "uniform sampler2D CC_Texture0; \n" //cocos2d 3.0jsb 3.1jsb/html5開始自動加入這個屬性,不需要手工聲明 + "void main() \n" + "{ \n" + " vec4 texColor = texture2D(CC_Texture0, v_texCoord); \n" + " float gray = texColor.r * 0.299 + texColor.g * 0.587 + texColor.b * 0.114; \n" + " gl_FragColor = vec4(gray,gray,gray,1); \n" + "}", SEPIA_FRAGMENT_SHADER: "varying vec2 v_texCoord; \n" //+ "uniform sampler2D CC_Texture0; \n" + "uniform float u_degree; \n" + "void main() \n" + "{ \n" + " vec4 texColor = texture2D(CC_Texture0, v_texCoord); \n" + " float r = texColor.r * 0.393 + texColor.g * 0.769 + texColor.b * 0.189; \n" + " float g = texColor.r * 0.349 + texColor.g * 0.686 + texColor.b * 0.168; \n" + " float b = texColor.r * 0.272 + texColor.g * 0.534 + texColor.b * 0.131; \n" + " gl_FragColor = mix(texColor, vec4(r, g, b, texColor.a), float(u_degree)); \n" + "}", programs:{}, /** * 灰度 * @param sprite */ grayScale: function (sprite) { var program = Filter.programs["grayScale"]; if(!program){ program = new cc.GLProgram(); program.retain(); //jsb需要retain一下,否則會被回收了 program.initWithString(Filter.DEFAULT_VERTEX_SHADER, Filter.GRAY_SCALE_FRAGMENT_SHADER); program.addAttribute(cc.ATTRIBUTE_NAME_POSITION, cc.VERTEX_ATTRIB_POSITION); //cocos會做初始化的工作 program.addAttribute(cc.ATTRIBUTE_NAME_TEX_COORD, cc.VERTEX_ATTRIB_TEX_COORDS); program.link(); program.updateUniforms(); Filter.programs["grayScale"] = program; } gl.useProgram(program.getProgram()); sprite.shaderProgram = program; }, /** * 造舊 * @param sprite * @param degree 舊的程度 0~1 */ sepia: function (sprite, degree) { var program = Filter.programs["sepia"+degree]; if(!program){ program = new cc.GLProgram(); program.retain(); program.initWithString(Filter.DEFAULT_VERTEX_SHADER, Filter.SEPIA_FRAGMENT_SHADER); program.addAttribute(cc.ATTRIBUTE_NAME_POSITION, cc.VERTEX_ATTRIB_POSITION); //cocos會做初始化的工作 program.addAttribute(cc.ATTRIBUTE_NAME_TEX_COORD, cc.VERTEX_ATTRIB_TEX_COORDS); program.link(); program.updateUniforms(); /* 這兩句只在html5中有效,在jsb中失效。原因可能是native版本繪制sprite前把這個glprogram重置了,丟掉了參數。 var degreeLocation = program.getUniformLocationForName("u_degree"); gl.uniform1f(degreeLocation, degree); */ Filter.programs["sepia"+degree] = program; } gl.useProgram(program.getProgram()); sprite.shaderProgram = program; sprite.scheduleUpdate(); sprite.update = function(){ program.use(); program.setUniformsForBuiltins(); var degreeLocation = program.getUniformLocationForName("u_degree"); gl.uniform1f( degreeLocation, degree); //這個函數由於jsb實現有問題,在手機側實際只能傳遞整數,需要注意。html5是正常的。 }; } }; cc.GLNode = cc.GLNode || cc.Node.extend({ ctor:function(){ this._super(); this.init(); }, _initRendererCmd:function(){ this._rendererCmd = new cc.CustomRenderCmdWebGL(this, function(){ cc.kmGLMatrixMode(cc.KM_GL_MODELVIEW); cc.kmGLPushMatrix(); cc.kmGLLoadMatrix(this._stackMatrix); this.draw(); cc.kmGLPopMatrix(); }); } }); var ShaderLayer = cc.Layer.extend({ sprite:null, ctor:function () { this._super(); if( 'opengl' in cc.sys.capabilities ) { var node1 = new cc.Sprite("res/item_2.png"); var node2 = new cc.Sprite("res/item_3.png"); this.addChild(node1,11); this.addChild(node2,12); node1.x = 500; node2.x = 200; node1.y = node2.y = 130; Filter.grayScale(node1); Filter.sepia(node2, 1); var glnode = new cc.GLNode(); this.addChild(glnode,1); this.glnode = glnode; var winSize = cc.director.getWinSize(); glnode.x = winSize.width/2; glnode.y = winSize.height/2; glnode.width = 128; glnode.height = 128; glnode.anchorX = 0.5; glnode.anchorY = 0.5; var MULTI_TEXTURES_FRAGMENT_SHADER = "precision lowp float; \n" + "varying vec2 v_texCoord; \n" + "uniform sampler2D tex0; \n" //為了避免跟自動加入的CC_Texture0沖突,改名 + "uniform sampler2D tex1; \n" + "void main() \n" + "{ \n" + " vec4 color1 = texture2D(tex0, v_texCoord); \n" + " vec4 color2 = texture2D(tex1, v_texCoord); \n" + " gl_FragColor = vec4(color1.r*color2.r, color1.g*color2.g, color1.b*color2.b, color1.a*color2.a); \n" + "}"; var DEFAULT_VERTEX_SHADER = "attribute vec4 a_position; \n" + "attribute vec2 a_texCoord; \n" + "varying mediump vec2 v_texCoord; \n" + "void main() \n" + "{ \n" + " gl_Position = (CC_PMatrix * CC_MVMatrix) * a_position; \n" + " v_texCoord = a_texCoord; \n" + "}"; this.shader = new cc.GLProgram(); this.shader.retain(); this.shader.initWithString(DEFAULT_VERTEX_SHADER, MULTI_TEXTURES_FRAGMENT_SHADER); this.shader.addAttribute(cc.ATTRIBUTE_NAME_POSITION, cc.VERTEX_ATTRIB_POSITION); this.shader.addAttribute(cc.ATTRIBUTE_NAME_TEX_COORD, cc.VERTEX_ATTRIB_TEX_COORDS); this.shader.link(); this.shader.updateUniforms(); //綁定位置,這個是cocos封裝后必須做的事。詳細可以看代碼 this.initGL(); var p = this.shader.getProgram(); this.tex1Location = gl.getUniformLocation(p, "tex0"); //如果frag shader最終沒有用某個uniform,該uniform會被優化刪掉 this.tex2Location = gl.getUniformLocation(p, "tex1"); glnode.draw = function() { this.shader.use(); //使用這個shader來繪制,封裝了gl的use。跟指定glnode.shaderProgram類似 this.shader.setUniformsForBuiltins(); //設置坐標系變換 gl.activeTexture(gl.TEXTURE0); //webgl中一共32個,可以看cocos2d列的常量 gl.bindTexture(gl.TEXTURE_2D, this.tex1.getName()); gl.uniform1i(this.tex1Location, 0); //把CC_Texture0指向gl.TEXTURE0 gl.activeTexture(gl.TEXTURE1); gl.bindTexture(gl.TEXTURE_2D, this.tex2.getName()); gl.uniform1i(this.tex2Location, 1); cc.glEnableVertexAttribs( cc.VERTEX_ATTRIB_FLAG_TEX_COORDS | cc.VERTEX_ATTRIB_FLAG_POSITION); //實際對gl的api做了封裝,增加了這兩個屬性的位置映射。用於vertexAttribPointer // Draw fullscreen Square gl.bindBuffer(gl.ARRAY_BUFFER, this.squareVertexPositionBuffer); gl.vertexAttribPointer(cc.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, 0, 0); gl.bindBuffer(gl.ARRAY_BUFFER, this.squareVertexTextureBuffer); gl.vertexAttribPointer(cc.VERTEX_ATTRIB_TEX_COORDS, 2, gl.FLOAT, false, 0, 0); gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4); gl.activeTexture(gl.TEXTURE1); gl.bindTexture(gl.TEXTURE_2D, null); //使用完必須置為空,否則影響其他node gl.activeTexture(gl.TEXTURE0); //另外必須設置回第0個,否則cocos2d框架中如果沒有顯示設置第0個,就會錯誤使用了上邊的TEXTURE1 gl.bindTexture(gl.TEXTURE_2D, null); gl.bindBuffer(gl.ARRAY_BUFFER, null); }.bind(this); } }, initGL:function() { var tex1 = cc.textureCache.addImage("res/item_2.png"); var tex2 = cc.textureCache.addImage("res/item_3.png"); this.tex1 = tex1; this.tex2 = tex2; // // Square // var squareVertexPositionBuffer = this.squareVertexPositionBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, squareVertexPositionBuffer); var vertices = [ 128, 128, 0, 128, 128, 0, 0, 0 ]; gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW); var squareVertexTextureBuffer = this.squareVertexTextureBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, squareVertexTextureBuffer); var texcoords = [ 0, 0, 1, 0, 0, 1, 1, 1 ]; gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(texcoords), gl.STATIC_DRAW); gl.bindBuffer(gl.ARRAY_BUFFER, null); } }); var HelloWorldScene = cc.Scene.extend({ onEnter:function () { this._super(); var layer = new ShaderLayer(); this.addChild(layer); cc.eventManager.addListener({ event: cc.EventListener.KEYBOARD, onKeyReleased: function(keyCode, event) { if (keyCode == cc.KEY.back) { cc.director.end(); } }}, this); } });