diff --git a/CCBoot.js b/CCBoot.js index ebb0d6f42d..c23be52534 100644 --- a/CCBoot.js +++ b/CCBoot.js @@ -58,7 +58,7 @@ _p = null; * @name cc.ENGINE_VERSION */ var engineVersion; -engineVersion = '1.1.2'; +engineVersion = '1.2.0-beta.1'; window['CocosEngine'] = cc.ENGINE_VERSION = engineVersion; /** diff --git a/CCDebugger.js b/CCDebugger.js index 8b825c87c7..3a54773167 100644 --- a/CCDebugger.js +++ b/CCDebugger.js @@ -35,7 +35,6 @@ cc._LogInfos = { }, configuration: { - dumpInfo: "cocos2d: **** WARNING **** CC_ENABLE_PROFILERS is defined. Disable it when you finish profiling (from CCMacro.js)", loadConfigFile: "Expected 'data' dict, but not found. Config file: %s", loadConfigFile_2: "Please load the resource first : %s", }, diff --git a/cocos2d/actions/CCActionCamera.js b/cocos2d/actions/CCActionCamera.js deleted file mode 100644 index 9f57d1a1f8..0000000000 --- a/cocos2d/actions/CCActionCamera.js +++ /dev/null @@ -1,277 +0,0 @@ -/**************************************************************************** - Copyright (c) 2008-2010 Ricardo Quesada - Copyright (c) 2011-2012 cocos2d-x.org - Copyright (c) 2013-2014 Chukong Technologies Inc. - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -/** - * Base class for cc.Camera actions - * @class - * @extends ActionInterval - */ -cc.ActionCamera = cc.ActionInterval.extend({ - _centerXOrig:0, - _centerYOrig:0, - _centerZOrig:0, - _eyeXOrig:0, - _eyeYOrig:0, - _eyeZOrig:0, - _upXOrig:0, - _upYOrig:0, - _upZOrig:0, - - /** - * Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function. - */ - ctor:function(){ - var _t = this; - cc.ActionInterval.prototype.ctor.call(_t); - - _t._centerXOrig=0; - _t._centerYOrig=0; - _t._centerZOrig=0; - _t._eyeXOrig=0; - _t._eyeYOrig=0; - _t._eyeZOrig=0; - _t._upXOrig=0; - _t._upYOrig=0; - _t._upZOrig=0; - }, - - /** - * called before the action start. It will also set the target. - * - * @param {_ccsg.Node} target - */ - startWithTarget:function (target) { - var _t = this; - cc.ActionInterval.prototype.startWithTarget.call(_t, target); - - var camera = target.getCamera(); - var centerXYZ = camera.getCenter(); - _t._centerXOrig = centerXYZ.x; - _t._centerYOrig = centerXYZ.y; - _t._centerZOrig = centerXYZ.z; - - var eyeXYZ = camera.getEye(); - _t._eyeXOrig = eyeXYZ.x; - _t._eyeYOrig = eyeXYZ.y; - _t._eyeZOrig = eyeXYZ.z; - - var upXYZ = camera.getUp(); - _t._upXOrig = upXYZ.x; - _t._upYOrig = upXYZ.y; - _t._upZOrig = upXYZ.z; - }, - - /** - * to copy object with deep copy. - * returns a new clone of the action - * - * @returns {ActionCamera} - */ - clone:function(){ - return new cc.ActionCamera(); - }, - - /** - * returns a reversed action.
- * For example:
- * - The action will be x coordinates of 0 move to 100.
- * - The reversed action will be x of 100 move to 0. - * - Will be rewritten - * - */ - reverse:function () { - return new cc.ReverseTime(this); - } -}); - -/** - * Orbits the camera around the center of the screen using spherical coordinates. - * - * @param {Number} t time - * @param {Number} radius - * @param {Number} deltaRadius - * @param {Number} angleZ - * @param {Number} deltaAngleZ - * @param {Number} angleX - * @param {Number} deltaAngleX - * - * @class - * @extends ActionCamera - */ -cc.OrbitCamera = cc.ActionCamera.extend({ - _radius: 0.0, - _deltaRadius: 0.0, - _angleZ: 0.0, - _deltaAngleZ: 0.0, - _angleX: 0.0, - _deltaAngleX: 0.0, - _radZ: 0.0, - _radDeltaZ: 0.0, - _radX: 0.0, - _radDeltaX: 0.0, - - /** - * Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function.
- * creates a cc.OrbitCamera action with radius, delta-radius, z, deltaZ, x, deltaX. - * @param {Number} t time - * @param {Number} radius - * @param {Number} deltaRadius - * @param {Number} angleZ - * @param {Number} deltaAngleZ - * @param {Number} angleX - * @param {Number} deltaAngleX - */ - ctor:function(t, radius, deltaRadius, angleZ, deltaAngleZ, angleX, deltaAngleX){ - cc.ActionCamera.prototype.ctor.call(this); - - deltaAngleX !== undefined && this.initWithDuration(t, radius, deltaRadius, angleZ, deltaAngleZ, angleX, deltaAngleX); - }, - - /** - * initializes a cc.OrbitCamera action with radius, delta-radius, z, deltaZ, x, deltaX - * @param {Number} t time - * @param {Number} radius - * @param {Number} deltaRadius - * @param {Number} angleZ - * @param {Number} deltaAngleZ - * @param {Number} angleX - * @param {Number} deltaAngleX - * @return {Boolean} - */ - initWithDuration:function (t, radius, deltaRadius, angleZ, deltaAngleZ, angleX, deltaAngleX) { - if (cc.ActionInterval.prototype.initWithDuration.call(this, t)) { - var _t = this; - _t._radius = radius; - _t._deltaRadius = deltaRadius; - _t._angleZ = angleZ; - _t._deltaAngleZ = deltaAngleZ; - _t._angleX = angleX; - _t._deltaAngleX = deltaAngleX; - - _t._radDeltaZ = cc.degreesToRadians(deltaAngleZ); - _t._radDeltaX = cc.degreesToRadians(deltaAngleX); - return true; - } - return false; - }, - - /** - * positions the camera according to spherical coordinates - * @return {Object} - */ - sphericalRadius:function () { - var newRadius, zenith, azimuth; - var camera = this.target.getCamera(); - var eyeXYZ = camera.getEye(); - var centerXYZ = camera.getCenter(); - - var x = eyeXYZ.x - centerXYZ.x, y = eyeXYZ.y - centerXYZ.y, z = eyeXYZ.z - centerXYZ.z; - - var r = Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2) + Math.pow(z, 2)); - var s = Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2)); - if (s === 0.0) - s = cc.macro.FLT_EPSILON; - if (r === 0.0) - r = cc.macro.FLT_EPSILON; - - zenith = Math.acos(z / r); - if (x < 0) - azimuth = Math.PI - Math.asin(y / s); - else - azimuth = Math.asin(y / s); - newRadius = r / cc.Camera.getZEye(); - return {newRadius:newRadius, zenith:zenith, azimuth:azimuth}; - }, - - /** - * called before the action start. It will also set the target. - * - * @param {_ccsg.Node} target - */ - startWithTarget:function (target) { - var _t = this; - cc.ActionInterval.prototype.startWithTarget.call(_t, target); - var retValue = _t.sphericalRadius(); - if (isNaN(_t._radius)) - _t._radius = retValue.newRadius; - - if (isNaN(_t._angleZ)) - _t._angleZ = cc.radiansToDegrees(retValue.zenith); - - if (isNaN(_t._angleX)) - _t._angleX = cc.radiansToDegrees(retValue.azimuth); - - _t._radZ = cc.degreesToRadians(_t._angleZ); - _t._radX = cc.degreesToRadians(_t._angleX); - }, - - /** - * to copy object with deep copy. - * returns a new clone of the action - * - * @returns {ActionCamera} - */ - clone:function(){ - var a = new cc.OrbitCamera(), _t = this; - a.initWithDuration(_t._duration, _t._radius, _t._deltaRadius, _t._angleZ, _t._deltaAngleZ, _t._angleX, _t._deltaAngleX); - return a; - }, - - /** - * Called once per frame. Time is the number of seconds of a frame interval. - * - * @param {Number} dt - */ - update:function (dt) { - dt = this._computeEaseTime(dt); - var r = (this._radius + this._deltaRadius * dt) * cc.Camera.getZEye(); - var za = this._radZ + this._radDeltaZ * dt; - var xa = this._radX + this._radDeltaX * dt; - - var i = Math.sin(za) * Math.cos(xa) * r + this._centerXOrig; - var j = Math.sin(za) * Math.sin(xa) * r + this._centerYOrig; - var k = Math.cos(za) * r + this._centerZOrig; - - this.target.getCamera().setEye(i, j, k); - this.target.setNodeDirty(); - } -}); - -/** - * creates a cc.OrbitCamera action with radius, delta-radius, z, deltaZ, x, deltaX - * @method - * @param {Number} t time - * @param {Number} radius - * @param {Number} deltaRadius - * @param {Number} angleZ - * @param {Number} deltaAngleZ - * @param {Number} angleX - * @param {Number} deltaAngleX - * @return {OrbitCamera} - */ -cc.orbitCamera = function (t, radius, deltaRadius, angleZ, deltaAngleZ, angleX, deltaAngleX) { - return new cc.OrbitCamera(t, radius, deltaRadius, angleZ, deltaAngleZ, angleX, deltaAngleX); -}; diff --git a/cocos2d/actions/CCActionInterval.js b/cocos2d/actions/CCActionInterval.js index 7cc3efe592..74c9232cb8 100644 --- a/cocos2d/actions/CCActionInterval.js +++ b/cocos2d/actions/CCActionInterval.js @@ -560,7 +560,6 @@ cc.Repeat = cc.ActionInterval.extend({ // don't set a instant action back or update it, it has no use because it has no duration if (!this._actionInstant) { if (this._total === locTimes) { - locInnerAction.update(1); locInnerAction.stop(); } else { // issue #390 prevent jerk, use right update diff --git a/cocos2d/audio/CCAudio.js b/cocos2d/audio/CCAudio.js index 9d7f8c2658..9eff41ffa2 100644 --- a/cocos2d/audio/CCAudio.js +++ b/cocos2d/audio/CCAudio.js @@ -273,7 +273,6 @@ JS.mixin(cc.Audio.prototype, { * @method playMusic * @param {String} url - The path of the music file without filename extension. * @param {Boolean} loop - Whether the music loop or not. - * @param {Boolean} immediate - Whether immediately play music. * @example * //example * cc.audioEngine.playMusic(path, false); diff --git a/cocos2d/clipping-nodes/CCClippingNodeCanvasRenderCmd.js b/cocos2d/clipping-nodes/CCClippingNodeCanvasRenderCmd.js index 426649e05c..064e859509 100644 --- a/cocos2d/clipping-nodes/CCClippingNodeCanvasRenderCmd.js +++ b/cocos2d/clipping-nodes/CCClippingNodeCanvasRenderCmd.js @@ -25,7 +25,6 @@ //-------------------------- ClippingNode's canvas render cmd -------------------------------- cc.ClippingNode.CanvasRenderCmd = function(renderable){ _ccsg.Node.CanvasRenderCmd.call(this, renderable); - this._needDraw = false; this._rendererClipCmd = new cc.CustomRenderCmd(this, this._drawStencilCommand); this._rendererRestoreCmd = new cc.CustomRenderCmd(this, this._restoreCmdCallback); diff --git a/cocos2d/clipping-nodes/CCClippingNodeWebGLRenderCmd.js b/cocos2d/clipping-nodes/CCClippingNodeWebGLRenderCmd.js index c610683f41..7e9596da77 100644 --- a/cocos2d/clipping-nodes/CCClippingNodeWebGLRenderCmd.js +++ b/cocos2d/clipping-nodes/CCClippingNodeWebGLRenderCmd.js @@ -32,25 +32,16 @@ function setProgram (node, program) { for (var i = 0; i < children.length; i++) setProgram(children[i], program); -}; +} cc.ClippingNode.WebGLRenderCmd = function(renderable){ _ccsg.Node.WebGLRenderCmd.call(this, renderable); - this._needDraw = false; this._beforeVisitCmd = new cc.CustomRenderCmd(this, this._onBeforeVisit); this._afterDrawStencilCmd = new cc.CustomRenderCmd(this, this._onAfterDrawStencil); this._afterVisitCmd = new cc.CustomRenderCmd(this, this._onAfterVisit); - this._currentStencilFunc = null; - this._currentStencilRef = null; - this._currentStencilValueMask = null; - this._currentStencilFail = null; - this._currentStencilPassDepthFail = null; - this._currentStencilPassDepthPass = null; - this._currentStencilWriteMask = null; this._currentStencilEnabled = null; - this._currentDepthWriteMask = null; this._mask_layer_le = null; }; @@ -74,9 +65,10 @@ proto.initStencilBits = function(){ proto.transform = function(parentCmd, recursive){ var node = this._node; - _ccsg.Node.WebGLRenderCmd.prototype.transform.call(this, parentCmd, recursive); - if(node._stencil) + this.originTransform(parentCmd, recursive); + if(node._stencil) { node._stencil._renderCmd.transform(this, recursive); + } }; proto.visit = function(parentCmd){ @@ -92,13 +84,13 @@ proto.visit = function(parentCmd){ // if stencil buffer disabled if (cc.ClippingNode.stencilBits < 1) { // draw everything, as if there where no stencil - _ccsg.Node.WebGLRenderCmd.prototype.visit.call(this, parentCmd); + this.originVisit(parentCmd); return; } if (!node._stencil || !node._stencil.visible) { if (node.inverted) - _ccsg.Node.WebGLRenderCmd.prototype.visit.call(this, parentCmd); // draw everything + this.originVisit(parentCmd); // draw everything return; } @@ -108,8 +100,8 @@ proto.visit = function(parentCmd){ cc.log("Nesting more than " + cc.ClippingNode.stencilBits + "stencils is not supported. Everything will be drawn without stencil for this node and its children."); cc.ClippingNode.WebGLRenderCmd._visit_once = false; } - // draw everything, as if there where no stencil - _ccsg.Node.WebGLRenderCmd.prototype.visit.call(this, parentCmd); + // draw everything, as if there were no stencil + this.originVisit(parentCmd); return; } @@ -121,7 +113,7 @@ proto.visit = function(parentCmd){ this._syncStatus(parentCmd); currentStack.top = this._stackMatrix; - //this._stencil._stackMatrix = this._stackMatrix; + // node._stencil._stackMatrix = node._stackMatrix; node._stencil._renderCmd.visit(this); cc.renderer.pushRenderCommand(this._afterDrawStencilCmd); @@ -153,33 +145,6 @@ proto.setStencil = function(stencil){ node._stencil._parent = node; }; -proto._drawFullScreenQuadClearStencil = function () { - // draw a fullscreen solid rectangle to clear the stencil buffer - var projStack = cc.math.projection_matrix_stack; - //cc.math.glMatrixMode(cc.math.KM_GL_PROJECTION); - //cc.math.glPushMatrix(); - //cc.math.glLoadIdentity(); - projStack.push(); - projStack.top.identity(); - - //cc.math.glMatrixMode(cc.math.KM_GL_MODELVIEW); - //cc.math.glPushMatrix(); - //cc.math.glLoadIdentity(); - var modelViewStack = cc.math.modelview_matrix_stack; - modelViewStack.push(); - modelViewStack.top.identity(); - - cc._drawingUtil.drawSolidRect(cc.p(-1, -1), cc.p(1, 1), cc.color(255, 255, 255, 255)); - - //cc.math.glMatrixMode(cc.math.KM_GL_PROJECTION); - //cc.math.glPopMatrix(); - projStack.pop(); - - //cc.math.glMatrixMode(cc.math.KM_GL_MODELVIEW); - //cc.math.glPopMatrix(); - modelViewStack.pop(); -}; - proto._onBeforeVisit = function(ctx){ var gl = ctx || cc._renderContext, node = this._node; cc.ClippingNode.WebGLRenderCmd._layer++; @@ -193,56 +158,51 @@ proto._onBeforeVisit = function(ctx){ this._mask_layer_le = mask_layer | mask_layer_l; // manually save the stencil state this._currentStencilEnabled = gl.isEnabled(gl.STENCIL_TEST); - this._currentStencilWriteMask = gl.getParameter(gl.STENCIL_WRITEMASK); - this._currentStencilFunc = gl.getParameter(gl.STENCIL_FUNC); - this._currentStencilRef = gl.getParameter(gl.STENCIL_REF); - this._currentStencilValueMask = gl.getParameter(gl.STENCIL_VALUE_MASK); - this._currentStencilFail = gl.getParameter(gl.STENCIL_FAIL); - this._currentStencilPassDepthFail = gl.getParameter(gl.STENCIL_PASS_DEPTH_FAIL); - this._currentStencilPassDepthPass = gl.getParameter(gl.STENCIL_PASS_DEPTH_PASS); + gl.clear(gl.DEPTH_BUFFER_BIT); // enable stencil use gl.enable(gl.STENCIL_TEST); - gl.stencilMask(mask_layer); - this._currentDepthWriteMask = gl.getParameter(gl.DEPTH_WRITEMASK); gl.depthMask(false); gl.stencilFunc(gl.NEVER, mask_layer, mask_layer); - gl.stencilOp(!node.inverted ? gl.ZERO : gl.REPLACE, gl.KEEP, gl.KEEP); + gl.stencilOp(gl.REPLACE, gl.KEEP, gl.KEEP); - this._drawFullScreenQuadClearStencil(); - - gl.stencilFunc(gl.NEVER, mask_layer, mask_layer); - gl.stencilOp(!node.inverted ? gl.REPLACE : gl.ZERO, gl.KEEP, gl.KEEP); + gl.stencilMask(mask_layer); + gl.clear(gl.STENCIL_BUFFER_BIT); if (node.alphaThreshold < 1) { //TODO desktop var program = cc.shaderCache.programForKey(cc.macro.SHADER_POSITION_TEXTURECOLORALPHATEST); - var alphaValueLocation = gl.getUniformLocation(program.getProgram(), cc.macro.UNIFORM_ALPHA_TEST_VALUE_S); // set our alphaThreshold cc.gl.useProgram(program.getProgram()); - program.setUniformLocationWith1f(alphaValueLocation, node.alphaThreshold); + program.setUniformLocationWith1f(cc.UNIFORM_ALPHA_TEST_VALUE_S, node.alphaThreshold); + program.setUniformLocationWithMatrix4fv(cc.UNIFORM_MVMATRIX_S, cc.renderer.mat4Identity.mat); setProgram(node._stencil, program); } }; proto._onAfterDrawStencil = function(ctx){ var gl = ctx || cc._renderContext; - gl.depthMask(this._currentDepthWriteMask); + gl.depthMask(true); - gl.stencilFunc(gl.EQUAL, this._mask_layer_le, this._mask_layer_le); + gl.stencilFunc(!this._node.inverted ? gl.EQUAL : gl.NOTEQUAL, this._mask_layer_le, this._mask_layer_le); gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP); }; proto._onAfterVisit = function(ctx){ var gl = ctx || cc._renderContext; - gl.stencilFunc(this._currentStencilFunc, this._currentStencilRef, this._currentStencilValueMask); - gl.stencilOp(this._currentStencilFail, this._currentStencilPassDepthFail, this._currentStencilPassDepthPass); - gl.stencilMask(this._currentStencilWriteMask); - if (!this._currentStencilEnabled) - gl.disable(gl.STENCIL_TEST); - - // we are done using this layer, decrement cc.ClippingNode.WebGLRenderCmd._layer--; + + if (this._currentStencilEnabled) { + var mask_layer = 0x1 << cc.ClippingNode.WebGLRenderCmd._layer; + var mask_layer_l = mask_layer - 1; + var mask_layer_le = mask_layer | mask_layer_l; + + gl.stencilMask(mask_layer); + gl.stencilFunc(gl.EQUAL, mask_layer_le, mask_layer_le); + } + else { + gl.disable(gl.STENCIL_TEST); + } }; diff --git a/cocos2d/core/CCCamera.js b/cocos2d/core/CCCamera.js deleted file mode 100644 index c55aaed99a..0000000000 --- a/cocos2d/core/CCCamera.js +++ /dev/null @@ -1,282 +0,0 @@ -/**************************************************************************** - Copyright (c) 2008-2010 Ricardo Quesada - Copyright (c) 2011-2012 cocos2d-x.org - Copyright (c) 2013-2014 Chukong Technologies Inc. - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -/** - *

- * A CCCamera is used in every CCNode.
- * The OpenGL gluLookAt() function is used to locate the camera.
- *
- * If the object is transformed by any of the scale, rotation or position attributes, then they will override the camera.
- *
- * IMPORTANT: Either your use the camera or the rotation/scale/position properties. You can't use both.
- * World coordinates won't work if you use the camera.
- *
- * Limitations:
- * - Some nodes, like CCParallaxNode, CCParticle uses world node coordinates, and they won't work properly if you move them (or any of their ancestors)
- * using the camera.
- *
- * - It doesn't work on batched nodes like CCSprite objects when they are parented to a CCSpriteBatchNode object.
- *
- * - It is recommended to use it ONLY if you are going to create 3D effects. For 2D effecs, use the action CCFollow or position/scale/rotate. * - *

- */ -cc.Camera = cc._Class.extend({ - _eyeX:null, - _eyeY:null, - _eyeZ:null, - - _centerX:null, - _centerY:null, - _centerZ:null, - - _upX:null, - _upY:null, - _upZ:null, - - _dirty:false, - _lookupMatrix:null, - /** - * constructor of cc.Camera - */ - ctor:function () { - this._lookupMatrix = new cc.math.Matrix4(); - this.restore(); - }, - - /** - * Description of cc.Camera - * @return {String} - */ - description:function () { - return ""; - }, - - /** - * sets the dirty value - * @param value - */ - setDirty:function (value) { - this._dirty = value; - }, - - /** - * get the dirty value - * @return {Boolean} - */ - isDirty:function () { - return this._dirty; - }, - - /** - * sets the camera in the default position - */ - restore:function () { - this._eyeX = this._eyeY = 0.0; - this._eyeZ = cc.Camera.getZEye(); - - this._centerX = this._centerY = this._centerZ = 0.0; - - this._upX = 0.0; - this._upY = 1.0; - this._upZ = 0.0; - - this._lookupMatrix.identity(); - - this._dirty = false; - }, - - /** - * Sets the camera using gluLookAt using its eye, center and up_vector - */ - locate:function () { - if (this._dirty) { - var eye = new cc.math.Vec3(this._eyeX, this._eyeY , this._eyeZ), - center = new cc.math.Vec3(this._centerX, this._centerY, this._centerZ), - up = new cc.math.Vec3(this._upX, this._upY, this._upZ); - this._lookupMatrix.lookAt(eye, center, up); - this._dirty = false; - } - cc.math.glMultMatrix( this._lookupMatrix); - }, - - _locateForRenderer: function(matrix){ - if (this._dirty) { - var eye = new cc.math.Vec3(this._eyeX, this._eyeY , this._eyeZ), - center = new cc.math.Vec3(this._centerX, this._centerY, this._centerZ), - up = new cc.math.Vec3(this._upX, this._upY, this._upZ); - this._lookupMatrix.lookAt(eye, center, up); - this._dirty = false; - } - matrix.multiply(this._lookupMatrix); - }, - - /** - * sets the eye values in points - * @param {Number} eyeX - * @param {Number} eyeY - * @param {Number} eyeZ - * @deprecated This function will be deprecated sooner or later please use setEye instead. - */ - setEyeXYZ:function (eyeX, eyeY, eyeZ) { - this.setEye(eyeX,eyeY,eyeZ); - }, - - /** - * sets the eye values in points - * @param {Number} eyeX - * @param {Number} eyeY - * @param {Number} eyeZ - */ - setEye:function (eyeX, eyeY, eyeZ) { - this._eyeX = eyeX ; - this._eyeY = eyeY ; - this._eyeZ = eyeZ ; - - this._dirty = true; - }, - - /** - * sets the center values in points - * @param {Number} centerX - * @param {Number} centerY - * @param {Number} centerZ - * @deprecated This function will be deprecated sooner or later please use setCenter instead. - */ - setCenterXYZ:function (centerX, centerY, centerZ) { - this.setCenter(centerX,centerY,centerZ); - }, - - /** - * sets the center values in points - * @param {Number} centerX - * @param {Number} centerY - * @param {Number} centerZ - */ - setCenter:function (centerX, centerY, centerZ) { - this._centerX = centerX ; - this._centerY = centerY ; - this._centerZ = centerZ ; - - this._dirty = true; - }, - - /** - * sets the up values - * @param {Number} upX - * @param {Number} upY - * @param {Number} upZ - * @deprecated This function will be deprecated sooner or later. - */ - setUpXYZ:function (upX, upY, upZ) { - this.setUp(upX, upY, upZ); - }, - - /** - * sets the up values - * @param {Number} upX - * @param {Number} upY - * @param {Number} upZ - */ - setUp:function (upX, upY, upZ) { - this._upX = upX; - this._upY = upY; - this._upZ = upZ; - - this._dirty = true; - }, - - /** - * get the eye vector values in points (return an object like {x:1,y:1,z:1} in HTML5) - * @param {Number} eyeX - * @param {Number} eyeY - * @param {Number} eyeZ - * @return {Object} - * @deprecated This function will be deprecated sooner or later, please use getEye instead. - */ - getEyeXYZ:function (eyeX, eyeY, eyeZ) { - return {x:this._eyeX , y:this._eyeY , z: this._eyeZ }; - }, - - /** - * get the eye vector values in points (return an object like {x:1,y:1,z:1} in HTML5) - * @return {Object} - */ - getEye:function () { - return {x:this._eyeX , y:this._eyeY , z: this._eyeZ }; - }, - - /** - * get the center vector values int points (return an object like {x:1,y:1,z:1} in HTML5) - * @param {Number} centerX - * @param {Number} centerY - * @param {Number} centerZ - * @return {Object} - * @deprecated This function will be deprecated sooner or later,please use getCenter instead. - */ - getCenterXYZ:function (centerX, centerY, centerZ) { - return {x:this._centerX ,y:this._centerY ,z:this._centerZ }; - }, - - /** - * get the center vector values int points (return an object like {x:1,y:1,z:1} in HTML5) - * @return {Object} - */ - getCenter:function () { - return {x:this._centerX ,y:this._centerY ,z:this._centerZ }; - }, - - /** - * get the up vector values (return an object like {x:1,y:1,z:1} in HTML5) - * @param {Number} upX - * @param {Number} upY - * @param {Number} upZ - * @return {Object} - * @deprecated This function will be deprecated sooner or later,please use getUp instead. - */ - getUpXYZ:function (upX, upY, upZ) { - return {x:this._upX,y:this._upY,z:this._upZ}; - }, - - /** - * get the up vector values (return an object like {x:1,y:1,z:1} in HTML5) - * @return {Object} - */ - getUp:function () { - return {x:this._upX,y:this._upY,z:this._upZ}; - }, - - _DISALLOW_COPY_AND_ASSIGN:function (CCCamera) { - - } -}); - -/** - * returns the Z eye - * @return {Number} - */ -cc.Camera.getZEye = function () { - return cc.macro.FLT_EPSILON; -}; diff --git a/cocos2d/core/CCConfiguration.js b/cocos2d/core/CCConfiguration.js index a27ee0f88b..d6b35a4b1a 100644 --- a/cocos2d/core/CCConfiguration.js +++ b/cocos2d/core/CCConfiguration.js @@ -216,17 +216,6 @@ cc.configuration = /** @lends cc.configuration# */{ this._valueDict[key] = value; }, - /** - * Dumps the current configuration on the console - */ - dumpInfo: function(){ - if(cc.macro.ENABLE_GL_STATE_CACHE === 0){ - cc.log(""); - cc.log(cc._LogInfos.configuration.dumpInfo); - cc.log("") - } - }, - /** * gathers OpenGL / GPU information */ diff --git a/cocos2d/core/CCDirector.js b/cocos2d/core/CCDirector.js index 1c42eaa9df..55e45ddc3f 100644 --- a/cocos2d/core/CCDirector.js +++ b/cocos2d/core/CCDirector.js @@ -220,17 +220,15 @@ cc.Director = Class.extend(/** @lends cc.Director# */{ calculateDeltaTime: function () { var now = Date.now(); - // new delta time. if (this._nextDeltaTimeZero) { this._deltaTime = 0; this._nextDeltaTimeZero = false; } else { this._deltaTime = (now - this._lastUpdate) / 1000; + if ((cc.game.config[cc.game.CONFIG_KEY.debugMode] > 0) && (this._deltaTime > 1)) + this._deltaTime = 1 / 60.0; } - if ((cc.game.config[cc.game.CONFIG_KEY.debugMode] > 0) && (this._deltaTime > 0.2)) - this._deltaTime = 1 / 60.0; - this._lastUpdate = now; }, @@ -268,6 +266,7 @@ cc.Director = Class.extend(/** @lends cc.Director# */{ var renderer = cc.renderer; if (renderer.childrenOrderDirty) { renderer.clearRenderCommands(); + cc.renderer.assignedZ = 0; this._runningScene._renderCmd._curLevel = 0; //level start from 0; this._runningScene.visit(); renderer.resetFlag(); @@ -284,12 +283,6 @@ cc.Director = Class.extend(/** @lends cc.Director# */{ if (this._beforeVisitScene) this._beforeVisitScene(); - // visit EC - if (this._scene) { - // clear flags - clearFlags(this._scene); - } - // update the scene this._visitScene(); @@ -592,10 +585,12 @@ cc.Director = Class.extend(/** @lends cc.Director# */{ for (id in persistNodes) { node = persistNodes[id]; var existNode = scene.getChildByUuid(id); - // Scene contains the persist node, should not reattach, should update the persist node if (existNode) { - persistNodes[id] = existNode; - existNode._persistNode = true; + // scene also contains the persist node, select the old one + var index = existNode.getSiblingIndex(); + existNode._destroyImmediate(); + node.parent = scene; + node.setSiblingIndex(index); } else { node.parent = scene; @@ -1497,14 +1492,4 @@ cc.Director.PROJECTION_CUSTOM = 3; * @constant * @type {Number} */ -cc.Director.PROJECTION_DEFAULT = cc.Director.PROJECTION_3D; - -// clear dirtyFlags for EC -function clearFlags (node) { - var children = node._children; - for (var i = 0, len = children.length; i < len; i++) { - var child = children[i]; - child._dirtyFlags = 0; - clearFlags(child); - } -} +cc.Director.PROJECTION_DEFAULT = cc.Director.PROJECTION_2D; \ No newline at end of file diff --git a/cocos2d/core/CCDirectorWebGL.js b/cocos2d/core/CCDirectorWebGL.js index 83d1bf07b9..7fa15d2a9c 100644 --- a/cocos2d/core/CCDirectorWebGL.js +++ b/cocos2d/core/CCDirectorWebGL.js @@ -30,17 +30,6 @@ require('../kazmath'); var math = cc.math; -var GLToClipTransform = function (transformOut) { - //var projection = new math.Matrix4(); - //math.glGetMatrix(math.KM_GL_PROJECTION, projection); - math.glGetMatrix(math.KM_GL_PROJECTION, transformOut); - - var modelview = new math.Matrix4(); - math.glGetMatrix(math.KM_GL_MODELVIEW, modelview); - - transformOut.multiply(modelview); -}; - cc.game.once(cc.game.EVENT_RENDERER_INITED, function () { // Do nothing under other render mode @@ -95,10 +84,10 @@ cc.game.once(cc.game.EVENT_RENDERER_INITED, function () { math.glMatrixMode(math.KM_GL_PROJECTION); math.glLoadIdentity(); var orthoMatrix = math.Matrix4.createOrthographicProjection( - -ox, - size.width - ox, - -oy, - size.height - oy, + 0, + size.width, + 0, + size.height, -1024, 1024); math.glMultMatrix(orthoMatrix); math.glMatrixMode(math.KM_GL_MODELVIEW); @@ -159,7 +148,6 @@ cc.game.once(cc.game.EVENT_RENDERER_INITED, function () { // Configuration. Gather GPU info var conf = cc.configuration; conf.gatherGPUInfo(); - conf.dumpInfo(); // set size //_t._winSizeInPoints = _t._openGLView.getDesignResolutionSize(); @@ -185,40 +173,6 @@ cc.game.once(cc.game.EVENT_RENDERER_INITED, function () { gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); }; - _p._beforeVisitScene = function () { - math.glPushMatrix(); - }; - - _p._afterVisitScene = function () { - math.glPopMatrix(); - }; - - _p.convertToGL = function (uiPoint) { - var transform = new math.Matrix4(); - GLToClipTransform(transform); - - var transformInv = transform.inverse(); - - // Calculate z=0 using -> transform*[0, 0, 0, 1]/w - var zClip = transform.mat[14] / transform.mat[15]; - var glSize = this._openGLView.getDesignResolutionSize(); - var glCoord = new math.Vec3(2.0 * uiPoint.x / glSize.width - 1.0, 1.0 - 2.0 * uiPoint.y / glSize.height, zClip); - glCoord.transformCoord(transformInv); - return cc.p(glCoord.x, glCoord.y); - }; - - _p.convertToUI = function (glPoint) { - var transform = new math.Matrix4(); - GLToClipTransform(transform); - - var clipCoord = new math.Vec3(glPoint.x, glPoint.y, 0.0); - // Need to calculate the zero depth from the transform. - clipCoord.transformCoord(transform); - - var glSize = this._openGLView.getDesignResolutionSize(); - return cc.p(glSize.width * (clipCoord.x * 0.5 + 0.5), glSize.height * (-clipCoord.y * 0.5 + 0.5)); - }; - _p.getVisibleSize = function () { //if (this._openGLView) { return this._openGLView.getVisibleSize(); @@ -266,9 +220,6 @@ cc.game.once(cc.game.EVENT_RENDERER_INITED, function () { _p.setGLDefaultValues = function () { var _t = this; _t.setAlphaBlending(true); - // XXX: Fix me, should enable/disable depth test according the depth format as cocos2d-iphone did - // [self setDepthTest: view_.depthFormat]; - _t.setDepthTest(false); _t.setProjection(_t._projection); // set other opengl default values diff --git a/cocos2d/core/CCDrawingPrimitivesWebGL.js b/cocos2d/core/CCDrawingPrimitivesWebGL.js index b773476546..eca726063a 100644 --- a/cocos2d/core/CCDrawingPrimitivesWebGL.js +++ b/cocos2d/core/CCDrawingPrimitivesWebGL.js @@ -35,9 +35,9 @@ cc.DrawingPrimitiveWebGL = cc._Class.extend(/** @lends cc.DrawingPrimitiveWebGL# _renderContext:null, _initialized:false, _shader: null, - _colorLocation:-1, + _colorLocation: "u_color", _colorArray: null, - _pointSizeLocation:-1, + _pointSizeLocation: "u_pointSize", _pointSize:-1, /** * contructor of cc.DrawingPrimitiveWebGL @@ -61,8 +61,8 @@ cc.DrawingPrimitiveWebGL = cc._Class.extend(/** @lends cc.DrawingPrimitiveWebGL# // Position and 1 color passed as a uniform (to similate glColor4ub ) // _t._shader = cc.shaderCache.programForKey(macro.SHADER_POSITION_UCOLOR); - _t._colorLocation = _t._renderContext.getUniformLocation(_t._shader.getProgram(), "u_color"); - _t._pointSizeLocation = _t._renderContext.getUniformLocation(_t._shader.getProgram(), "u_pointSize"); + _t._shader._addUniformLocation(_t._colorLocation); + _t._shader._addUniformLocation(_t._pointSizeLocation); _t._initialized = true; } @@ -85,8 +85,8 @@ cc.DrawingPrimitiveWebGL = cc._Class.extend(/** @lends cc.DrawingPrimitiveWebGL# var glContext = this._renderContext; this._shader.use(); this._shader.setUniformForModelViewAndProjectionMatrixWithMat4(); - cc.gl.enableVertexAttribs(macro.VERTEX_ATTRIB_FLAG_POSITION); - glContext.uniform4fv(this._colorLocation, this._colorArray); + glContext.enableVertexAttribArray(macro.VERTEX_ATTRIB_FLAG_POSITION); + this._shader.setUniformLocationWith4fv(this._colorLocation, this._colorArray); this._shader.setUniformLocationWith1f(this._pointSizeLocation, this._pointSize); var pointBuffer = glContext.createBuffer(); @@ -114,8 +114,8 @@ cc.DrawingPrimitiveWebGL = cc._Class.extend(/** @lends cc.DrawingPrimitiveWebGL# var glContext = this._renderContext; this._shader.use(); this._shader.setUniformForModelViewAndProjectionMatrixWithMat4(); - cc.gl.enableVertexAttribs(macro.VERTEX_ATTRIB_FLAG_POSITION); - glContext.uniform4fv(this._colorLocation, this._colorArray); + glContext.enableVertexAttribArray(macro.VERTEX_ATTRIB_FLAG_POSITION); + this._shader.setUniformLocationWith4fv(this._colorLocation, this._colorArray); this._shader.setUniformLocationWith1f(this._pointSizeLocation, this._pointSize); var pointBuffer = glContext.createBuffer(); @@ -149,8 +149,8 @@ cc.DrawingPrimitiveWebGL = cc._Class.extend(/** @lends cc.DrawingPrimitiveWebGL# var glContext = this._renderContext; this._shader.use(); this._shader.setUniformForModelViewAndProjectionMatrixWithMat4(); - cc.gl.enableVertexAttribs(macro.VERTEX_ATTRIB_FLAG_POSITION); - glContext.uniform4fv(this._colorLocation, this._colorArray); + glContext.enableVertexAttribArray(macro.VERTEX_ATTRIB_FLAG_POSITION); + this._shader.setUniformLocationWith4fv(this._colorLocation, this._colorArray); var pointBuffer = glContext.createBuffer(); glContext.bindBuffer(glContext.ARRAY_BUFFER, pointBuffer); @@ -204,8 +204,8 @@ cc.DrawingPrimitiveWebGL = cc._Class.extend(/** @lends cc.DrawingPrimitiveWebGL# var glContext = this._renderContext; this._shader.use(); this._shader.setUniformForModelViewAndProjectionMatrixWithMat4(); - cc.gl.enableVertexAttribs(macro.VERTEX_ATTRIB_FLAG_POSITION); - glContext.uniform4fv(this._colorLocation, this._colorArray); + glContext.enableVertexAttribArray(macro.VERTEX_ATTRIB_FLAG_POSITION); + this._shader.setUniformLocationWith4fv(this._colorLocation, this._colorArray); var pointBuffer = glContext.createBuffer(); glContext.bindBuffer(glContext.ARRAY_BUFFER, pointBuffer); @@ -235,8 +235,8 @@ cc.DrawingPrimitiveWebGL = cc._Class.extend(/** @lends cc.DrawingPrimitiveWebGL# var glContext = this._renderContext; this._shader.use(); this._shader.setUniformForModelViewAndProjectionMatrixWithMat4(); - cc.gl.enableVertexAttribs(macro.VERTEX_ATTRIB_FLAG_POSITION); - glContext.uniform4fv(this._colorLocation, this._colorArray); + glContext.enableVertexAttribArray(macro.VERTEX_ATTRIB_FLAG_POSITION); + this._shader.setUniformLocationWith4fv(this._colorLocation, this._colorArray); var pointBuffer = glContext.createBuffer(); glContext.bindBuffer(glContext.ARRAY_BUFFER, pointBuffer); @@ -283,8 +283,8 @@ cc.DrawingPrimitiveWebGL = cc._Class.extend(/** @lends cc.DrawingPrimitiveWebGL# var glContext = this._renderContext; this._shader.use(); this._shader.setUniformForModelViewAndProjectionMatrixWithMat4(); - cc.gl.enableVertexAttribs(macro.VERTEX_ATTRIB_FLAG_POSITION); - glContext.uniform4fv(this._colorLocation, this._colorArray); + glContext.enableVertexAttribArray(macro.VERTEX_ATTRIB_FLAG_POSITION); + this._shader.setUniformLocationWith4fv(this._colorLocation, this._colorArray); var pointBuffer = glContext.createBuffer(); glContext.bindBuffer(glContext.ARRAY_BUFFER, pointBuffer); @@ -321,8 +321,8 @@ cc.DrawingPrimitiveWebGL = cc._Class.extend(/** @lends cc.DrawingPrimitiveWebGL# var glContext = this._renderContext; this._shader.use(); this._shader.setUniformForModelViewAndProjectionMatrixWithMat4(); - cc.gl.enableVertexAttribs(macro.VERTEX_ATTRIB_FLAG_POSITION); - glContext.uniform4fv(this._colorLocation, this._colorArray); + glContext.enableVertexAttribArray(macro.VERTEX_ATTRIB_FLAG_POSITION); + this._shader.setUniformLocationWith4fv(this._colorLocation, this._colorArray); var pointBuffer = glContext.createBuffer(); glContext.bindBuffer(glContext.ARRAY_BUFFER, pointBuffer); @@ -360,8 +360,8 @@ cc.DrawingPrimitiveWebGL = cc._Class.extend(/** @lends cc.DrawingPrimitiveWebGL# var glContext = this._renderContext; this._shader.use(); this._shader.setUniformForModelViewAndProjectionMatrixWithMat4(); - cc.gl.enableVertexAttribs(macro.VERTEX_ATTRIB_FLAG_POSITION); - glContext.uniform4fv(this._colorLocation, this._colorArray); + glContext.enableVertexAttribArray(macro.VERTEX_ATTRIB_FLAG_POSITION); + this._shader.setUniformLocationWith4fv(this._colorLocation, this._colorArray); var pointBuffer = glContext.createBuffer(); glContext.bindBuffer(glContext.ARRAY_BUFFER, pointBuffer); @@ -420,8 +420,8 @@ cc.DrawingPrimitiveWebGL = cc._Class.extend(/** @lends cc.DrawingPrimitiveWebGL# var glContext = this._renderContext; this._shader.use(); this._shader.setUniformForModelViewAndProjectionMatrixWithMat4(); - cc.gl.enableVertexAttribs(macro.VERTEX_ATTRIB_FLAG_POSITION); - glContext.uniform4fv(this._colorLocation, this._colorArray); + glContext.enableVertexAttribArray(macro.VERTEX_ATTRIB_FLAG_POSITION); + this._shader.setUniformLocationWith4fv(this._colorLocation, this._colorArray); var pointBuffer = glContext.createBuffer(); glContext.bindBuffer(glContext.ARRAY_BUFFER, pointBuffer); @@ -463,4 +463,4 @@ cc.DrawingPrimitiveWebGL = cc._Class.extend(/** @lends cc.DrawingPrimitiveWebGL# if(this._renderContext.lineWidth) this._renderContext.lineWidth(width); } -}); \ No newline at end of file +}); diff --git a/cocos2d/core/CCGame.js b/cocos2d/core/CCGame.js index 995465ed5f..15b7f5d507 100644 --- a/cocos2d/core/CCGame.js +++ b/cocos2d/core/CCGame.js @@ -668,7 +668,6 @@ var game = /** @lends cc.game# */{ this._renderContext = cc._renderContext = cc.webglContext = cc.create3DContext(localCanvas, { 'stencil': true, - 'preserveDrawingBuffer': true, 'antialias': !cc.sys.isMobile, 'alpha': true }); @@ -677,10 +676,15 @@ var game = /** @lends cc.game# */{ if (this._renderContext) { cc.renderer = cc.rendererWebGL; win.gl = this._renderContext; // global variable declared in CCMacro.js + cc.renderer.init(); cc.shaderCache._init(); cc._drawingUtil = new cc.DrawingPrimitiveWebGL(this._renderContext); cc.textureCache._initializingRenderer(); + cc.glExt = {}; + cc.glExt.instanced_arrays = win.gl.getExtension("ANGLE_instanced_arrays"); + cc.glExt.element_uint = win.gl.getExtension("OES_element_index_uint"); } else { + cc._renderType = game.RENDER_TYPE_CANVAS; cc.renderer = cc.rendererCanvas; this._renderContext = cc._renderContext = new cc.CanvasContextWrapper(localCanvas.getContext("2d")); cc._drawingUtil = cc.DrawingPrimitiveCanvas ? new cc.DrawingPrimitiveCanvas(this._renderContext) : null; diff --git a/cocos2d/core/CCNode.js b/cocos2d/core/CCNode.js index 08ee4ca8b2..c5910124e6 100644 --- a/cocos2d/core/CCNode.js +++ b/cocos2d/core/CCNode.js @@ -454,6 +454,7 @@ var Node = cc.Class({ set: function (value) { this.groupIndex = cc.game.groupList.indexOf(value); + this.emit('group-changed'); } } }, @@ -478,9 +479,9 @@ var Node = cc.Class({ } }, - statics: { - _DirtyFlags: require('./utils/misc').DirtyFlags - }, + //statics: { + // _DirtyFlags: require('./utils/misc').DirtyFlags + //}, // OVERRIDES @@ -610,7 +611,6 @@ var Node = cc.Class({ if (constructor) { findComponents(this, constructor, components); } - return components; }, @@ -629,7 +629,6 @@ var Node = cc.Class({ if (constructor) { return findChildComponent(this._children, constructor); } - return null; }, @@ -648,7 +647,6 @@ var Node = cc.Class({ if (constructor) { findChildComponents(this._children, constructor, components); } - return components; }, @@ -783,6 +781,10 @@ var Node = cc.Class({ } } if (ctor._requireComponent) { + if (index === this._components.length) { + // If comp should be last component, increase the index because required component added + ++index; + } var depend = this.addComponent(ctor._requireComponent); if (!depend) { // depend conflicts @@ -1443,6 +1445,10 @@ if (CC_JSB) { * @event child-reorder * @param {Event} event */ +/** + * @event group-changed + * @param {Event} event + */ /** * !#en * Note: This event is only emitted from the top most node whose active value did changed, diff --git a/cocos2d/core/base-nodes/CCAtlasNodeCanvasRenderCmd.js b/cocos2d/core/base-nodes/CCAtlasNodeCanvasRenderCmd.js index 65fc0cc62e..1bd3407fbb 100644 --- a/cocos2d/core/base-nodes/CCAtlasNodeCanvasRenderCmd.js +++ b/cocos2d/core/base-nodes/CCAtlasNodeCanvasRenderCmd.js @@ -28,7 +28,6 @@ (function(){ cc.AtlasNode.CanvasRenderCmd = function(renderableObject){ _ccsg.Node.CanvasRenderCmd.call(this, renderableObject); - this._needDraw = false; this._colorUnmodified = cc.Color.WHITE; this._textureToRender = null; }; diff --git a/cocos2d/core/base-nodes/CCAtlasNodeWebGLRenderCmd.js b/cocos2d/core/base-nodes/CCAtlasNodeWebGLRenderCmd.js index 5a8382e186..1a14b4da41 100644 --- a/cocos2d/core/base-nodes/CCAtlasNodeWebGLRenderCmd.js +++ b/cocos2d/core/base-nodes/CCAtlasNodeWebGLRenderCmd.js @@ -34,6 +34,9 @@ this._colorF32Array = null; this._uniformColor = null; + this._matrix = new cc.math.Matrix4(); + this._matrix.identity(); + //shader stuff this._shaderProgram = cc.shaderCache.programForKey(cc.macro.SHADER_POSITION_TEXTURE_UCOLOR); this._uniformColor = cc._renderContext.getUniformLocation(this._shaderProgram.getProgram(), "u_color"); @@ -57,8 +60,16 @@ proto.rendering = function (ctx) { var context = ctx || cc._renderContext, node = this._node; + var wt = this._worldTransform, mat = this._matrix.mat; + mat[0] = wt.a; + mat[4] = wt.c; + mat[12] = wt.tx; + mat[1] = wt.b; + mat[5] = wt.d; + mat[13] = wt.ty; + this._shaderProgram.use(); - this._shaderProgram._setUniformForMVPMatrixWithMat4(this._stackMatrix); + this._shaderProgram._setUniformForMVPMatrixWithMat4(this._matrix); cc.gl.blendFunc(node._blendFunc.src, node._blendFunc.dst); if (this._uniformColor && this._colorF32Array) { @@ -116,10 +127,14 @@ } }; - proto._updateColor = function(){ - var locDisplayedColor = this._displayedColor; - this._colorF32Array = new Float32Array([locDisplayedColor.r / 255.0, locDisplayedColor.g / 255.0, - locDisplayedColor.b / 255.0, this._displayedOpacity / 255.0]); + proto._updateColor = function () { + if (this._colorF32Array) { + var locDisplayedColor = this._displayedColor; + this._colorF32Array[0] = locDisplayedColor.r / 255.0; + this._colorF32Array[1] = locDisplayedColor.g / 255.0; + this._colorF32Array[2] = locDisplayedColor.b / 255.0; + this._colorF32Array[3] = this._displayedOpacity / 255.0; + } }; proto.getTexture = function(){ @@ -142,4 +157,4 @@ node._itemsPerColumn = 0 | (size.height / node._itemHeight); node._itemsPerRow = 0 | (size.width / node._itemWidth); }; -})(); \ No newline at end of file +})(); diff --git a/cocos2d/core/base-nodes/CCSGNode.js b/cocos2d/core/base-nodes/CCSGNode.js index 7e06ab97f3..f3697ee4a4 100644 --- a/cocos2d/core/base-nodes/CCSGNode.js +++ b/cocos2d/core/base-nodes/CCSGNode.js @@ -1321,6 +1321,7 @@ _ccsg.Node = cc.Class({ child.arrivalOrder = cc.s_globalOrderOfArrival; cc.s_globalOrderOfArrival++; child._setLocalZOrder(zOrder); + this._renderCmd.setDirtyFlag(_ccsg.Node._dirtyFlags.orderDirty); }, /** @@ -1776,17 +1777,9 @@ _ccsg.Node = cc.Class({ * @return {cc.AffineTransform} */ getNodeToWorldTransform: function () { - var t; - if (this._renderCmd && cc._renderType === cc.game.RENDER_TYPE_CANVAS) { - t = this._renderCmd._worldTransform; - } - else { - //TODO renderCmd has a WorldTransform - t = this.getNodeToParentTransform(); - for (var p = this._parent; p !== null; p = p.parent) { - t = cc.affineTransformConcat(t, p.getNodeToParentTransform()); - } - } + var t = this.getNodeToParentTransform(); + for (var p = this._parent; p !== null; p = p.parent) + t = cc.affineTransformConcat(t, p.getNodeToParentTransform()); return t; }, @@ -1832,6 +1825,7 @@ _ccsg.Node = cc.Class({ * @return {cc.Vec2} */ convertToWorldSpace: function (nodePoint) { + nodePoint = nodePoint || cc.v2(0, 0); return cc.pointApplyAffineTransform(nodePoint, this.getNodeToWorldTransform()); }, @@ -1854,6 +1848,7 @@ _ccsg.Node = cc.Class({ * @return {cc.Vec2} */ convertToWorldSpaceAR: function (nodePoint) { + nodePoint = nodePoint || cc.v2(0, 0); var pt = cc.pAdd(nodePoint, this._renderCmd.getAnchorPointInPoints()); return this.convertToWorldSpace(pt); }, diff --git a/cocos2d/core/base-nodes/CCSGNodeCanvasRenderCmd.js b/cocos2d/core/base-nodes/CCSGNodeCanvasRenderCmd.js index 5a117598fe..93aa690b19 100644 --- a/cocos2d/core/base-nodes/CCSGNodeCanvasRenderCmd.js +++ b/cocos2d/core/base-nodes/CCSGNodeCanvasRenderCmd.js @@ -35,7 +35,7 @@ cc.CustomRenderCmd = function (target, func) { }; }; -_ccsg.Node._dirtyFlags = { +var dirtyFlags = _ccsg.Node._dirtyFlags = { transformDirty: 1 << 0, visibleDirty: 1 << 1, colorDirty: 1 << 2, @@ -44,23 +44,26 @@ _ccsg.Node._dirtyFlags = { orderDirty: 1 << 5, textDirty: 1 << 6, gradientDirty: 1 << 7, - contentDirty: 1<<8, + textureDirty: 1 << 8, + contentDirty: 1 << 9, COUNT: 9 }; -cc.js.get(_ccsg.Node._dirtyFlags, 'all', function () { - var count = _ccsg.Node._dirtyFlags.COUNT; +cc.js.get(dirtyFlags, 'all', function () { + var count = dirtyFlags.COUNT; return (1 << count) - 1; }, false); _ccsg.Node._requestDirtyFlag = function (key) { - cc.assert(!_ccsg.Node._dirtyFlags[key], cc._LogInfos.Node._requestDirtyFlag, key); + cc.assert(!dirtyFlags[key], cc._LogInfos.Node._requestDirtyFlag, key); - var count = _ccsg.Node._dirtyFlags.COUNT; + var count = dirtyFlags.COUNT; var value = 1 << count; - _ccsg.Node._dirtyFlags[key] = value; - _ccsg.Node._dirtyFlags.COUNT++; + dirtyFlags[key] = value; + dirtyFlags.COUNT++; return value; }; +var ONE_DEGREE = Math.PI / 180; + //-------------------------Base ------------------------- _ccsg.Node.RenderCmd = function(renderable){ this._dirtyFlag = 1; //need update the transform at first. @@ -100,16 +103,16 @@ _ccsg.Node.RenderCmd.prototype = { setCascadeColorEnabledDirty: function(){ this._cascadeColorEnabledDirty = true; - this.setDirtyFlag(_ccsg.Node._dirtyFlags.colorDirty); + this.setDirtyFlag(dirtyFlags.colorDirty); }, setCascadeOpacityEnabledDirty:function(){ this._cascadeOpacityEnabledDirty = true; - this.setDirtyFlag(_ccsg.Node._dirtyFlags.opacityDirty); + this.setDirtyFlag(dirtyFlags.opacityDirty); }, getParentToNodeTransform: function(){ - if(this._dirtyFlag & _ccsg.Node._dirtyFlags.transformDirty) + if(this._dirtyFlag & dirtyFlags.transformDirty) this._inverse = cc.affineTransformInvert(this.getNodeToParentTransform()); return this._inverse; }, @@ -120,7 +123,7 @@ _ccsg.Node.RenderCmd.prototype = { var locAPP = this._anchorPointInPoints, locSize = this._node._contentSize, locAnchorPoint = this._node._anchorPoint; locAPP.x = locSize.width * locAnchorPoint.x; locAPP.y = locSize.height * locAnchorPoint.y; - this.setDirtyFlag(_ccsg.Node._dirtyFlags.transformDirty); + this.setDirtyFlag(dirtyFlags.transformDirty); }, setDirtyFlag: function(dirtyFlag){ @@ -135,6 +138,194 @@ _ccsg.Node.RenderCmd.prototype = { return null; }, + transform: function (parentCmd, recursive) { + var node = this._node, + pt = parentCmd ? parentCmd._worldTransform : null, + t = this._transform, + wt = this._worldTransform; //get the world transform + + var hasRotation = node._rotationX || node._rotationY; + var hasSkew = node._skewX || node._skewY; + var sx = node._scaleX, sy = node._scaleY; + var appX = this._anchorPointInPoints.x, appY = this._anchorPointInPoints.y; + var a = 1, b = 0, c = 0, d = 1; + if (hasRotation || hasSkew) { + // position + t.tx = node._position.x; + t.ty = node._position.y; + + // rotation + if (hasRotation) { + var rotationRadiansX = node._rotationX * ONE_DEGREE; + c = Math.sin(rotationRadiansX); + d = Math.cos(rotationRadiansX); + if (node._rotationY === node._rotationX) { + a = d; + b = -c; + } + else { + var rotationRadiansY = node._rotationY * ONE_DEGREE; + a = Math.cos(rotationRadiansY); + b = -Math.sin(rotationRadiansY); + } + } + + // scale + t.a = a *= sx; + t.b = b *= sx; + t.c = c *= sy; + t.d = d *= sy; + + // skew + if (hasSkew) { + var skx = Math.tan(node._skewX * ONE_DEGREE); + var sky = Math.tan(node._skewY * ONE_DEGREE); + if (skx === Infinity) + skx = 99999999; + if (sky === Infinity) + sky = 99999999; + t.a = a + b * sky; + t.b = b + a * sky; + t.c = c + d * skx; + t.d = d + c * skx; + } + + if (appX || appY) { + t.tx -= t.a * appX + t.c * appY; + t.ty -= t.b * appX + t.d * appY; + // adjust anchorPoint + if (node._ignoreAnchorPointForPosition) { + t.tx += appX; + t.ty += appY; + } + } + + if (pt) { + // cc.AffineTransformConcat is incorrect at get world transform + wt.a = t.a * pt.a + t.b * pt.c; //a + wt.b = t.a * pt.b + t.b * pt.d; //b + wt.c = t.c * pt.a + t.d * pt.c; //c + wt.d = t.c * pt.b + t.d * pt.d; //d + wt.tx = pt.a * t.tx + pt.c * t.ty + pt.tx; + wt.ty = pt.d * t.ty + pt.ty + pt.b * t.tx; + } else { + wt.a = t.a; + wt.b = t.b; + wt.c = t.c; + wt.d = t.d; + wt.tx = t.tx; + wt.ty = t.ty; + } + } + else { + t.a = sx; + t.b = 0; + t.c = 0; + t.d = sy; + t.tx = node._position.x; + t.ty = node._position.y; + + if (appX || appY) { + t.tx -= t.a * appX; + t.ty -= t.d * appY; + // adjust anchorPoint + if (node._ignoreAnchorPointForPosition) { + t.tx += appX; + t.ty += appY; + } + } + + if (pt) { + wt.a = t.a * pt.a + t.b * pt.c; + wt.b = t.a * pt.b + t.b * pt.d; + wt.c = t.c * pt.a + t.d * pt.c; + wt.d = t.c * pt.b + t.d * pt.d; + wt.tx = t.tx * pt.a + t.ty * pt.c + pt.tx; + wt.ty = t.tx * pt.b + t.ty * pt.d + pt.ty; + } else { + wt.a = t.a; + wt.b = t.b; + wt.c = t.c; + wt.d = t.d; + wt.tx = t.tx; + wt.ty = t.ty; + } + } + + if (node._additionalTransformDirty) { + this._transform = cc.affineTransformConcat(t, node._additionalTransform); + } + + if (this._currentRegion) { + this._updateCurrentRegions(); + this._notifyRegionStatus && this._notifyRegionStatus(_ccsg.Node.CanvasRenderCmd.RegionStatus.DirtyDouble); + } + + if (recursive) { + var locChildren = this._node._children; + if (!locChildren || locChildren.length === 0) + return; + var i, len; + for (i = 0, len = locChildren.length; i < len; i++) { + locChildren[i]._renderCmd.transform(this, recursive); + } + } + + this._cacheDirty = true; + }, + + getNodeToParentTransform: function () { + if (this._dirtyFlag & dirtyFlags.transformDirty) { + this.transform(); + } + return this._transform; + }, + + _propagateFlagsDown: function(parentCmd) { + //return; + var locFlag = this._dirtyFlag; + var parentNode = parentCmd ? parentCmd._node : null; + + // There is a possibility: + // The parent element changed color, child element not change + // This will cause the parent element changed color + // But while the child element does not enter the circulation + // Here will be reset state in last + // In order the child elements get the parent state + if(parentNode && parentNode._cascadeColorEnabled && (parentCmd._dirtyFlag & dirtyFlags.colorDirty)) + locFlag |= dirtyFlags.colorDirty; + + if(parentNode && parentNode._cascadeOpacityEnabled && (parentCmd._dirtyFlag & dirtyFlags.opacityDirty)) + locFlag |= dirtyFlags.opacityDirty; + + if(parentCmd && (parentCmd._dirtyFlag & dirtyFlags.transformDirty)) + locFlag |= dirtyFlags.transformDirty; + + this._dirtyFlag = locFlag; + }, + + visit: function (parentCmd) { + var node = this._node, renderer = cc.renderer; + + parentCmd = parentCmd || this.getParentRenderCmd(); + if (parentCmd) { + this._curLevel = parentCmd._curLevel + 1; + } + this._propagateFlagsDown(parentCmd); + + // quick return if not visible + if (!node._visible) + return; + + if (isNaN(node._customZ)) { + node._vertexZ = renderer.assignedZ; + renderer.assignedZ += renderer.assignedZStep; + } + + this._syncStatus(parentCmd); + this.visitChildren(); + }, + _updateDisplayColor: function (parentColor) { var node = this._node; var locDispColor = this._displayedColor, locRealColor = node._realColor; @@ -174,7 +365,7 @@ _ccsg.Node.RenderCmd.prototype = { } } } - this._dirtyFlag = this._dirtyFlag & _ccsg.Node._dirtyFlags.colorDirty ^ this._dirtyFlag; + this._dirtyFlag &= ~dirtyFlags.colorDirty; }, _updateDisplayOpacity: function (parentOpacity) { @@ -209,7 +400,7 @@ _ccsg.Node.RenderCmd.prototype = { } } } - this._dirtyFlag = this._dirtyFlag & _ccsg.Node._dirtyFlags.opacityDirty ^ this._dirtyFlag; + this._dirtyFlag &= ~dirtyFlags.opacityDirty; }, _syncDisplayColor : function (parentColor) { @@ -240,9 +431,9 @@ _ccsg.Node.RenderCmd.prototype = { _updateColor: function(){}, updateStatus: function () { - var flags = _ccsg.Node._dirtyFlags, locFlag = this._dirtyFlag; - var colorDirty = locFlag & flags.colorDirty, - opacityDirty = locFlag & flags.opacityDirty; + var locFlag = this._dirtyFlag; + var colorDirty = locFlag & dirtyFlags.colorDirty, + opacityDirty = locFlag & dirtyFlags.opacityDirty; if(colorDirty) this._updateDisplayColor(); @@ -251,120 +442,22 @@ _ccsg.Node.RenderCmd.prototype = { if(colorDirty || opacityDirty) this._updateColor(); - if(locFlag & flags.transformDirty){ + + if(locFlag & dirtyFlags.transformDirty){ //update the transform this.transform(this.getParentRenderCmd(), true); - this._dirtyFlag = this._dirtyFlag & _ccsg.Node._dirtyFlags.transformDirty ^ this._dirtyFlag; + this._dirtyFlag &= ~dirtyFlags.transformDirty; } }, - getNodeToParentTransform: function () { - var node = this._node; - if (this._dirtyFlag & _ccsg.Node._dirtyFlags.transformDirty) { - var t = this._transform;// quick reference - // base position - t.tx = node._position.x; - t.ty = node._position.y; - - // rotation Cos and Sin - var a = 1, b = 0, - c = 0, d = 1; - if (node._rotationX) { - var rotationRadiansX = node._rotationX * 0.017453292519943295; //0.017453292519943295 = (Math.PI / 180); for performance - c = Math.sin(rotationRadiansX); - d = Math.cos(rotationRadiansX); - } - - if (node._rotationY) { - var rotationRadiansY = node._rotationY * 0.017453292519943295; //0.017453292519943295 = (Math.PI / 180); for performance - a = Math.cos(rotationRadiansY); - b = -Math.sin(rotationRadiansY); - } - t.a = a; - t.b = b; - t.c = c; - t.d = d; - - var lScaleX = node._scaleX, lScaleY = node._scaleY; - var appX = this._anchorPointInPoints.x, appY = this._anchorPointInPoints.y; - - // Firefox on Vista and XP crashes - // GPU thread in case of scale(0.0, 0.0) - var sx = (lScaleX < 0.000001 && lScaleX > -0.000001) ? 0.000001 : lScaleX, - sy = (lScaleY < 0.000001 && lScaleY > -0.000001) ? 0.000001 : lScaleY; - - // scale - if (lScaleX !== 1 || lScaleY !== 1) { - a = t.a *= sx; - b = t.b *= sx; - c = t.c *= sy; - d = t.d *= sy; - } - - // skew - if (node._skewX || node._skewY) { - // offset the anchorpoint - var skx = Math.tan(-node._skewX * Math.PI / 180); - var sky = Math.tan(-node._skewY * Math.PI / 180); - if (skx === Infinity) - skx = 99999999; - if (sky === Infinity) - sky = 99999999; - var xx = appY * skx; - var yy = appX * sky; - t.a = a - c * sky; - t.b = b - d * sky; - t.c = c - a * skx; - t.d = d - b * skx; - t.tx += a * xx + c * yy; - t.ty += b * xx + d * yy; - } - - // adjust anchorPoint - t.tx -= a * appX + c * appY; - t.ty -= b * appX + d * appY; - - // if ignore anchorPoint - if (node._ignoreAnchorPointForPosition) { - t.tx += appX; - t.ty += appY; - } - - if (node._additionalTransformDirty) - this._transform = cc.affineTransformConcat(t, node._additionalTransform); - } - return this._transform; - }, - _propagateFlagsDown: function(parentCmd) { - //return; - var flags = _ccsg.Node._dirtyFlags, locFlag = this._dirtyFlag; - var parentNode = parentCmd ? parentCmd._node : null; - - // There is a possibility: - // The parent element changed color, child element not change - // This will cause the parent element changed color - // But while the child element does not enter the circulation - // Here will be reset state in last - // In order the child elements get the parent state - if(parentNode && parentNode._cascadeColorEnabled && (parentCmd._dirtyFlag & flags.colorDirty)) - locFlag |= flags.colorDirty; - - if(parentNode && parentNode._cascadeOpacityEnabled && (parentCmd._dirtyFlag & flags.opacityDirty)) - locFlag |= flags.opacityDirty; - - if(parentCmd && (parentCmd._dirtyFlag & flags.transformDirty)) - locFlag |= flags.transformDirty; - - this._dirtyFlag = locFlag; - }, _syncStatus: function (parentCmd) { // In the visit logic does not restore the _dirtyFlag // Because child elements need parent's _dirtyFlag to change himself - var flags = _ccsg.Node._dirtyFlags, locFlag = this._dirtyFlag; + var locFlag = this._dirtyFlag; - var colorDirty = locFlag & flags.colorDirty, - opacityDirty = locFlag & flags.opacityDirty, - transformDirty = locFlag & flags.transformDirty; + var colorDirty = locFlag & dirtyFlags.colorDirty, + opacityDirty = locFlag & dirtyFlags.opacityDirty, + transformDirty = locFlag & dirtyFlags.transformDirty; if (colorDirty) //update the color @@ -379,10 +472,11 @@ _ccsg.Node.RenderCmd.prototype = { if (transformDirty) //update the transform - this.transform(parentCmd, true); + this.transform(parentCmd); }, visitChildren: function(){ + var renderer = cc.renderer; var node = this._node; var i, children = node._children, child; var len = children.length; @@ -391,21 +485,28 @@ _ccsg.Node.RenderCmd.prototype = { // draw children zOrder < 0 for (i = 0; i < len; i++) { child = children[i]; - if (child._localZOrder < 0) + if (child._localZOrder < 0) { child._renderCmd.visit(this); - else + } + else { break; + } } - cc.renderer.pushRenderCommand(this); - for (; i < len; i++) + + renderer.pushRenderCommand(this); + for (; i < len; i++) { children[i]._renderCmd.visit(this); + } } else { - cc.renderer.pushRenderCommand(this); + renderer.pushRenderCommand(this); } this._dirtyFlag = 0; } }; +_ccsg.Node.RenderCmd.prototype.originVisit = _ccsg.Node.RenderCmd.prototype.visit; +_ccsg.Node.RenderCmd.prototype.originTransform = _ccsg.Node.RenderCmd.prototype.transform; + //-----------------------Canvas --------------------------- //The _ccsg.Node's render command for Canvas @@ -427,7 +528,7 @@ _ccsg.Node.CanvasRenderCmd.RegionStatus = { var proto = _ccsg.Node.CanvasRenderCmd.prototype = Object.create(_ccsg.Node.RenderCmd.prototype); proto.constructor = _ccsg.Node.CanvasRenderCmd; proto._notifyRegionStatus = function(status) { - if(this._needDraw && this._regionFlag < status) { + if (this._needDraw && this._regionFlag < status) { this._regionFlag = status; } }; @@ -452,57 +553,6 @@ proto._updateCurrentRegions = function() { this._currentRegion.updateRegion(this.getLocalBB(), this._worldTransform); }; -proto.transform = function (parentCmd, recursive) { - // transform for canvas - var t = this.getNodeToParentTransform(), - worldT = this._worldTransform; //get the world transform - this._cacheDirty = true; - if (parentCmd) { - var pt = parentCmd._worldTransform; - // cc.AffineTransformConcat is incorrect at get world transform - worldT.a = t.a * pt.a + t.b * pt.c; //a - worldT.b = t.a * pt.b + t.b * pt.d; //b - worldT.c = t.c * pt.a + t.d * pt.c; //c - worldT.d = t.c * pt.b + t.d * pt.d; //d - - worldT.tx = pt.a * t.tx + pt.c * t.ty + pt.tx; - worldT.ty = pt.d * t.ty + pt.ty + pt.b * t.tx; - } else { - worldT.a = t.a; - worldT.b = t.b; - worldT.c = t.c; - worldT.d = t.d; - worldT.tx = t.tx; - worldT.ty = t.ty; - } - - this._updateCurrentRegions(); - this._notifyRegionStatus && this._notifyRegionStatus(_ccsg.Node.CanvasRenderCmd.RegionStatus.DirtyDouble); - if (recursive) { - var locChildren = this._node._children; - if (!locChildren || locChildren.length === 0) - return; - var i, len; - for (i = 0, len = locChildren.length; i < len; i++) { - locChildren[i]._renderCmd.transform(this, recursive); - } - } -}; - -proto.visit = function (parentCmd) { - var node = this._node; - this._propagateFlagsDown(parentCmd); - // quick return if not visible - if (!node._visible) - return; - - parentCmd = parentCmd || this.getParentRenderCmd(); - if (parentCmd) - this._curLevel = parentCmd._curLevel + 1; - this._syncStatus(parentCmd); - this.visitChildren(); -}; - proto.setDirtyFlag = function (dirtyFlag, child) { _ccsg.Node.RenderCmd.prototype.setDirtyFlag.call(this, dirtyFlag, child); this._setCacheDirty(child); //TODO it should remove from here. diff --git a/cocos2d/core/base-nodes/CCSGNodeWebGLRenderCmd.js b/cocos2d/core/base-nodes/CCSGNodeWebGLRenderCmd.js index 8f0d6bac10..a61f3b959c 100644 --- a/cocos2d/core/base-nodes/CCSGNodeWebGLRenderCmd.js +++ b/cocos2d/core/base-nodes/CCSGNodeWebGLRenderCmd.js @@ -23,19 +23,9 @@ ****************************************************************************/ // ------------------------------ The ccsg.Node's render command for WebGL ---------------------------------- -var math = cc.math; - _ccsg.Node.WebGLRenderCmd = function (renderable) { _ccsg.Node.RenderCmd.call(this, renderable); - - var mat4 = new math.Matrix4(), mat = mat4.mat; - mat[2] = mat[3] = mat[6] = mat[7] = mat[8] = mat[9] = mat[11] = mat[14] = 0.0; - mat[10] = mat[15] = 1.0; - this._transform4x4 = mat4; - this._stackMatrix = new math.Matrix4(); this._shaderProgram = null; - - this._camera = null; }; var proto = _ccsg.Node.WebGLRenderCmd.prototype = Object.create(_ccsg.Node.RenderCmd.prototype); @@ -43,60 +33,6 @@ proto.constructor = _ccsg.Node.WebGLRenderCmd; proto._updateColor = function(){}; -proto.visit = function (parentCmd) { - var node = this._node; - this._propagateFlagsDown(parentCmd); - // quick return if not visible - if (!node._visible) - return; - - parentCmd = parentCmd || this.getParentRenderCmd(); - if (node._parent && node._parent._renderCmd) - this._curLevel = node._parent._renderCmd._curLevel + 1; - - var currentStack = cc.current_stack; - - //optimize performance for javascript - currentStack.stack.push(currentStack.top); - this._syncStatus(parentCmd); - currentStack.top = this._stackMatrix; - this.visitChildren(); - //optimize performance for javascript - currentStack.top = currentStack.stack.pop(); -}; - -proto.transform = function (parentCmd, recursive) { - var t4x4 = this._transform4x4, stackMatrix = this._stackMatrix, node = this._node; - parentCmd = parentCmd || this.getParentRenderCmd(); - var parentMatrix = (parentCmd ? parentCmd._stackMatrix : cc.current_stack.top); - - // Convert 3x3 into 4x4 matrix - var trans = this.getNodeToParentTransform(); - - this._dirtyFlag = this._dirtyFlag & _ccsg.Node._dirtyFlags.transformDirty ^ this._dirtyFlag; - - var t4x4Mat = t4x4.mat; - t4x4Mat[0] = trans.a; - t4x4Mat[4] = trans.c; - t4x4Mat[12] = trans.tx; - t4x4Mat[1] = trans.b; - t4x4Mat[5] = trans.d; - t4x4Mat[13] = trans.ty; - - // Update Z vertex manually - t4x4Mat[14] = node._vertexZ; - - //optimize performance for Javascript - math.mat4Multiply(stackMatrix, parentMatrix, t4x4); - - if(!recursive || !node._children || node._children.length === 0) - return; - var i, len, locChildren = node._children; - for(i = 0, len = locChildren.length; i< len; i++){ - locChildren[i]._renderCmd.transform(this, recursive); - } -}; - proto.setShaderProgram = function (shaderProgram) { this._shaderProgram = shaderProgram; }; diff --git a/cocos2d/core/base-ui/CCWidgetManager.js b/cocos2d/core/base-ui/CCWidgetManager.js index df5889a02a..5ea2b125b7 100644 --- a/cocos2d/core/base-ui/CCWidgetManager.js +++ b/cocos2d/core/base-ui/CCWidgetManager.js @@ -156,10 +156,12 @@ function visitNode (node) { var widget = node._widget; if (widget) { alignToParent(node, widget); - widgetManager._nodesWithWidget.push(node); - if (!CC_EDITOR && widget.isAlignOnce) { + if ((!CC_EDITOR || _Scene.AnimUtils.curAnimState) && widget.isAlignOnce) { widget.enabled = false; } + else { + widgetManager._nodesWithWidget.push(node); + } } var children = node._children; for (var i = 0; i < children.length; i++) { @@ -179,14 +181,31 @@ function refreshScene () { visitNode(scene); widgetManager._nodesOrderDirty = false; } else { - var nodes = widgetManager._nodesWithWidget; - for (var i = 0, len = nodes.length; i < len; i++) { - var node = nodes[i]; - alignToParent(node, node._widget); + var i, node, nodes = widgetManager._nodesWithWidget, len = nodes.length; + if (CC_EDITOR && _Scene.AnimUtils.curAnimState) { + // always check isAlignOnce because animation mode maybe changed + for (i = len - 1; i >= 0; i--) { + node = nodes[i]; + var widget = node._widget; + if (widget.isAlignOnce) { + // widget contains in _nodesWithWidget should aligned at least once + widget.enabled = false; + } + else { + alignToParent(node, widget); + } + } + } + else { + for (i = 0; i < len; i++) { + node = nodes[i]; + alignToParent(node, node._widget); + } } } widgetManager.isAligning = false; } + } var adjustWidgetToAllowMovingInEditor = CC_EDITOR && function (event) { diff --git a/cocos2d/core/collider/CCCollisionManager.js b/cocos2d/core/collider/CCCollisionManager.js index f1ad0298b8..e24c170593 100644 --- a/cocos2d/core/collider/CCCollisionManager.js +++ b/cocos2d/core/collider/CCCollisionManager.js @@ -295,6 +295,8 @@ var CollisionManager = cc.Class({ if (index !== -1) { this._removeList.splice(index, 1); } + + collider.node.on('group-changed', this.onNodeGroupChanged, this); }, removeCollider: function (collider) { @@ -322,12 +324,24 @@ var CollisionManager = cc.Class({ } } } + + collider.node.off('group-changed', this.onNodeGroupChanged, this); } else { cc.error('collider not added or already removed'); } }, + onNodeGroupChanged: function (event) { + var node = event.currentTarget; + var colliders = node.getComponents(cc.Collider); + + for (var i = 0, l = colliders.length; i < l; i++) { + this.removeCollider(colliders[i]); + this.addCollider(colliders[i]); + } + }, + drawColliders: function () { if (!this._enabledDebugDraw || !this._debugDrawer) { return; diff --git a/cocos2d/core/components/CCAnimation.js b/cocos2d/core/components/CCAnimation.js index 907e39a424..86e66b3a6b 100644 --- a/cocos2d/core/components/CCAnimation.js +++ b/cocos2d/core/components/CCAnimation.js @@ -346,7 +346,7 @@ var Animation = cc.Class({ this._init(); var state = this._nameToState[name]; - if (CC_EDITOR && !state) { + if (CC_EDITOR && (!state || !cc.js.array.contains(this._clips, state.clip))) { this._didInit = false; if (this.animator) { @@ -488,6 +488,8 @@ var Animation = cc.Class({ }, _createStates: function() { + this._nameToState = {}; + // create animation states var state = null; var defaultClipState = false; diff --git a/cocos2d/core/components/CCButton.js b/cocos2d/core/components/CCButton.js index e1a7522a97..b6e8a7996d 100644 --- a/cocos2d/core/components/CCButton.js +++ b/cocos2d/core/components/CCButton.js @@ -102,24 +102,28 @@ var Button = cc.Class({ extends: require('./CCComponent'), ctor: function () { - this._pressed = false; - this._hovered = false; - + this._resetState(); this._sprite = null; - this._fromColor = null; - this._toColor = null; - this._time = 0; - this._transitionFinished = true; if(CC_EDITOR) { this._previousNormalSprite = null; } }, + _resetState: function () { + this._pressed = false; + this._hovered = false; + + this._fromColor = null; + this._toColor = null; + this._time = 0; + this._transitionFinished = true; + }, + editor: CC_EDITOR && { menu: 'i18n:MAIN_MENU.component.ui/Button', help: 'i18n:COMPONENT.help_url.button', - inspector: 'app://editor/page/inspector/button/button.html', + inspector: 'packages://inspector/inspectors/comps/button.js', executeInEditMode: true }, @@ -145,6 +149,10 @@ var Button = cc.Class({ } } this._updateState(); + + if(!this.interactable) { + this._resetState(); + } }, animatable: false }, @@ -437,7 +445,7 @@ var Button = cc.Class({ this._updateState(); }, - _onMouseMoveIn: function (event) { + _onMouseMoveIn: function () { if (this._pressed || !this.interactable || !this.enabledInHierarchy) return; if (!this._hovered) { diff --git a/cocos2d/core/components/CCComponent.js b/cocos2d/core/components/CCComponent.js index 6b26bb6bd5..11af567b87 100644 --- a/cocos2d/core/components/CCComponent.js +++ b/cocos2d/core/components/CCComponent.js @@ -34,7 +34,7 @@ var IsEditorOnEnableCalled = Flags.IsEditorOnEnableCalled; var IsPreloadCalled = Flags.IsPreloadCalled; var IsOnLoadStarted = Flags.IsOnLoadStarted; var IsOnLoadCalled = Flags.IsOnLoadCalled; -var IsOnStartCalled = Flags.IsOnStartCalled; +var IsStartCalled = Flags.IsStartCalled; // only use eval in editor @@ -112,7 +112,7 @@ function callOnEnable (self, enable) { function _registerEvent (self, on) { if (CC_EDITOR && !(self.constructor._executeInEditMode || cc.engine._isPlaying)) return; - if (self.start && !(self._objFlags & IsOnStartCalled)) { + if (self.start && !(self._objFlags & IsStartCalled)) { if (on) { cc.director.on(cc.Director.EVENT_BEFORE_UPDATE, _callStart, self); } @@ -150,11 +150,11 @@ var _registerUpdateEvent = function () { var _callStart = CC_EDITOR ? function () { cc.director.off(cc.Director.EVENT_BEFORE_UPDATE, _callStart, this); callStartInTryCatch(this); - this._objFlags |= IsOnStartCalled; + this._objFlags |= IsStartCalled; } : function () { cc.director.off(cc.Director.EVENT_BEFORE_UPDATE, _callStart, this); this.start(); - this._objFlags |= IsOnStartCalled; + this._objFlags |= IsStartCalled; }; var _callUpdate = CC_EDITOR ? function (event) { @@ -709,20 +709,23 @@ var Component = cc.Class({ // Remove all listeners cc.eventManager.removeListeners(this); + // + if (CC_EDITOR && !CC_TEST) { + _Scene.AssetsWatcher.stop(this); + } + // onDestroy - if (CC_EDITOR) { - if ( !CC_TEST ) { - _Scene.AssetsWatcher.stop(this); - } - if (cc.engine._isPlaying || this.constructor._executeInEditMode) { - if (this.onDestroy) { + if (this.onDestroy && (this._objFlags & IsOnLoadCalled)) { + if (CC_EDITOR) { + if (cc.engine._isPlaying || this.constructor._executeInEditMode) { callOnDestroyInTryCatch(this); } } + else { + this.onDestroy(); + } } - else if (this.onDestroy) { - this.onDestroy(); - } + // do remove component this.node._removeComponent(this); diff --git a/cocos2d/core/components/CCComponentEventHandler.js b/cocos2d/core/components/CCComponentEventHandler.js index 846c12ddd9..cbaf23cbe7 100644 --- a/cocos2d/core/components/CCComponentEventHandler.js +++ b/cocos2d/core/components/CCComponentEventHandler.js @@ -97,14 +97,14 @@ cc.Component.EventHandler = cc.Class({ * !#en Emit event with params * !#zh 触发目标组件上的指定 handler 函数,该参数是回调函数的参数值(可不填)。 * @method emit - * @param {*} params + * @param {Array} params * @example * // Call Function * var eventHandler = new cc.Component.EventHandler(); * eventHandler.target = newTarget; * eventHandler.component = "MainMenu"; * eventHandler.handler = "OnClick" - * eventHandler.emit("This is the argument to the callback function!"); + * eventHandler.emit(["param1", "param2", ....]); */ emit: function(params) { var target = this.target; diff --git a/cocos2d/core/components/CCEditBox.js b/cocos2d/core/components/CCEditBox.js index 7436496342..dcb3bcf0ad 100644 --- a/cocos2d/core/components/CCEditBox.js +++ b/cocos2d/core/components/CCEditBox.js @@ -164,7 +164,7 @@ var EditBox = cc.Class({ editor: CC_EDITOR && { menu: 'i18n:MAIN_MENU.component.ui/EditBox', - inspector: 'app://editor/page/inspector/cceditbox.html', + inspector: 'packages://inspector/inspectors/comps/cceditbox.js', help: 'i18n:COMPONENT.help_url.editbox', executeInEditMode: true, }, @@ -417,6 +417,9 @@ var EditBox = cc.Class({ _initSgNode: function() { var sgNode = this._sgNode; + if(!CC_JSB) { + sgNode.createDomElementIfNeeded(); + } this._createBackgroundSprite(); @@ -440,7 +443,6 @@ var EditBox = cc.Class({ sgNode.returnType = this.returnType; sgNode.setLineHeight(this.lineHeight); - sgNode.setDelegate(this); }, diff --git a/cocos2d/core/components/CCLabel.js b/cocos2d/core/components/CCLabel.js index 0e76f79670..bb31dbb0ce 100644 --- a/cocos2d/core/components/CCLabel.js +++ b/cocos2d/core/components/CCLabel.js @@ -156,7 +156,7 @@ var Label = cc.Class({ editor: CC_EDITOR && { menu: 'i18n:MAIN_MENU.component.renderers/Label', help: 'i18n:COMPONENT.help_url.label', - inspector: 'app://editor/page/inspector/label.html', + inspector: 'packages://inspector/inspectors/comps/label.js', }, _updateSgNodeString: function() { @@ -418,14 +418,6 @@ var Label = cc.Class({ animatable: false } - // TODO - // enableRichText: { - // default: false, - // notify: function () { - // this._sgNode.enableRichText = this.enableRichText; - // } - // } - }, statics: { @@ -453,16 +445,6 @@ var Label = cc.Class({ }, - onEnable: function() { - this._super(); - cc.director.on(cc.Director.EVENT_BEFORE_VISIT, this._updateNodeSize, this); - }, - - onDisable: function() { - this._super(); - cc.director.off(cc.Director.EVENT_BEFORE_VISIT, this._updateNodeSize, this); - }, - _createSgNode: function () { return null; }, @@ -488,9 +470,6 @@ var Label = cc.Class({ sgNode.retain(); } - // TODO - // sgNode.enableRichText = this.enableRichText; - sgNode.setHorizontalAlign( this.horizontalAlign ); sgNode.setVerticalAlign( this.verticalAlign ); sgNode.setFontSize( this._fontSize ); diff --git a/cocos2d/core/components/CCLayout.js b/cocos2d/core/components/CCLayout.js index ccc5ba74cf..0aed4a7d08 100644 --- a/cocos2d/core/components/CCLayout.js +++ b/cocos2d/core/components/CCLayout.js @@ -156,7 +156,7 @@ var Layout = cc.Class({ editor: CC_EDITOR && { menu: 'i18n:MAIN_MENU.component.ui/Layout', help: 'i18n:COMPONENT.help_url.layout', - inspector: 'app://editor/page/inspector/cclayout.html', + inspector: 'packages://inspector/inspectors/comps/cclayout.js', executeInEditMode: true, }, @@ -831,7 +831,15 @@ var Layout = cc.Class({ } }, - lateUpdate: function() { + onEnable: function () { + cc.director.on(cc.Director.EVENT_BEFORE_VISIT, this._updateLayout, this); + }, + + onDisable: function () { + cc.director.off(cc.Director.EVENT_BEFORE_VISIT, this._updateLayout, this); + }, + + _updateLayout: function() { if (this._layoutDirty && this.node.children.length > 0) { this._doLayout(); this._layoutDirty = false; diff --git a/cocos2d/core/components/CCScrollBar.js b/cocos2d/core/components/CCScrollBar.js index 2246cc185f..4f5da41e32 100644 --- a/cocos2d/core/components/CCScrollBar.js +++ b/cocos2d/core/components/CCScrollBar.js @@ -327,11 +327,16 @@ var Scrollbar = cc.Class({ } }, - reset: function() { + hide: function() { this._autoHideRemainingTime = 0; this._setOpacity(0); }, + show: function() { + this._autoHideRemainingTime = 0; + this._setOpacity(this._opacity); + }, + update: function(dt) { this._processAutoHide(dt); } diff --git a/cocos2d/core/components/CCScrollView.js b/cocos2d/core/components/CCScrollView.js index 807641e612..660e27173a 100644 --- a/cocos2d/core/components/CCScrollView.js +++ b/cocos2d/core/components/CCScrollView.js @@ -527,7 +527,6 @@ var ScrollView = cc.Class({ * @return {Vec2} - A Vec2 value indicate the current scroll offset. */ getScrollOffset: function() { - var maxScrollOffset = this.getMaxScrollOffset(); var topDelta = this._topBoundary - this._getContentTopBoundary(); var leftDeta = this._getContentLeftBoundary() - this._leftBoundary; @@ -632,6 +631,16 @@ var ScrollView = cc.Class({ } }, + /** + * !#en Stop auto scroll immediately + * !#zh 停止自动滚动, 调用此 API 可以让 Scrollview 立即停止滚动 + * @method stopAutoScroll + */ + stopAutoScroll: function() { + this._autoScrolling = false; + this._autoScrollAccumulatedTime = this._autoScrollTotalTime; + }, + /** * !#en Modify the content position. * !#zh 设置当前视图内容的坐标点。 @@ -757,8 +766,8 @@ var ScrollView = cc.Class({ if (this.content) { //refresh content size var layout = this.content.getComponent(cc.Layout); - if(layout) { - layout.lateUpdate(); + if(layout && layout.enabledInHierarchy) { + layout._updateLayout(); } var scrollViewSize = this.node.getContentSize(); @@ -769,6 +778,45 @@ var ScrollView = cc.Class({ var topRightPosition = this._convertToContentParentSpace(cc.p(scrollViewSize.width, scrollViewSize.height)); this._rightBoundary = topRightPosition.x; this._topBoundary = topRightPosition.y; + + var contentSize = this.content.getContentSize(); + + var bottomDeta = this._getContentBottomBoundary() - this._bottomBoundary; + bottomDeta = -bottomDeta; + var moveDelta = cc.p(0, 0); + var totalScrollDelta = 0; + + var leftDeta = this._getContentLeftBoundary() - this._leftBoundary; + leftDeta = -leftDeta; + + if (contentSize.height < scrollViewSize.height) { + totalScrollDelta = contentSize.height - scrollViewSize.height; + moveDelta.y = bottomDeta - totalScrollDelta; + + if (this.verticalScrollBar) { + this.verticalScrollBar.hide(); + } + } else { + if (this.verticalScrollBar) { + this.verticalScrollBar.show(); + } + } + + if (contentSize.width < scrollViewSize.width) { + totalScrollDelta = contentSize.width - scrollViewSize.width; + moveDelta.x = leftDeta; + + if (this.horizontalScrollBar) { + this.horizontalScrollBar.hide(); + } + + } else { + if (this.horizontalScrollBar) { + this.horizontalScrollBar.show(); + } + } + + this._moveContent(moveDelta); } }, @@ -891,7 +939,6 @@ var ScrollView = cc.Class({ _handlePressLogic: function() { this._autoScrolling = false; - this._calculateBoundary(); this._touchMovePreviousTimestamp = getTimeInMilliseconds(); this._touchMoveDisplacements = []; @@ -1229,6 +1276,9 @@ var ScrollView = cc.Class({ if (!CC_EDITOR) { this._registerEvent(); this.node.on('size-changed', this._calculateBoundary, this); + if(this.content) { + this.content.on('size-changed', this._calculateBoundary, this); + } } }, @@ -1238,18 +1288,24 @@ var ScrollView = cc.Class({ onDestroy: function() { this.node.off('size-changed', this._calculateBoundary, this); + if(this.content) { + this.content.off('size-changed', this._calculateBoundary, this); + } }, - onDisable: function() { + _hideScrollbar: function () { if (this.horizontalScrollBar) { - this.horizontalScrollBar.reset(); + this.horizontalScrollBar.hide(); } if (this.verticalScrollBar) { - this.verticalScrollBar.reset(); + this.verticalScrollBar.hide(); } - this._autoScrolling = false; - this._autoScrollAccumulatedTime = this._autoScrollTotalTime; + }, + + onDisable: function() { + this._hideScrollbar(); + this.stopAutoScroll(); }, update: function(dt) { diff --git a/cocos2d/core/components/CCSprite.js b/cocos2d/core/components/CCSprite.js index 9674d32ed8..3dcfef3575 100644 --- a/cocos2d/core/components/CCSprite.js +++ b/cocos2d/core/components/CCSprite.js @@ -118,7 +118,7 @@ var Sprite = cc.Class({ editor: CC_EDITOR && { menu: 'i18n:MAIN_MENU.component.renderers/Sprite', help: 'i18n:COMPONENT.help_url.sprite', - inspector: 'app://editor/page/inspector/sprite.html', + inspector: 'packages://inspector/inspectors/comps/sprite.js', }, ctor: function() { diff --git a/cocos2d/core/components/CCVideoPlayer.js b/cocos2d/core/components/CCVideoPlayer.js index f659af2e2e..178f30b419 100644 --- a/cocos2d/core/components/CCVideoPlayer.js +++ b/cocos2d/core/components/CCVideoPlayer.js @@ -57,7 +57,7 @@ var VideoPlayer = cc.Class({ editor: CC_EDITOR && { menu: 'i18n:MAIN_MENU.component.ui/VideoPlayer', - inspector: 'app://editor/page/inspector/videoplayer.html', + inspector: 'packages://inspector/inspectors/comps/videoplayer.js', help: 'i18n:COMPONENT.help_url.videoplayer', }, @@ -215,6 +215,9 @@ var VideoPlayer = cc.Class({ _initSgNode: function () { var sgNode = this._sgNode; if(sgNode) { + if(!CC_JSB) { + sgNode.createDomElementIfNeeded(); + } this._updateVideoSource(); sgNode.seekTo(this.currentTime); diff --git a/cocos2d/core/components/CCWidget.js b/cocos2d/core/components/CCWidget.js index 0b26508888..4c4c739bcf 100644 --- a/cocos2d/core/components/CCWidget.js +++ b/cocos2d/core/components/CCWidget.js @@ -49,7 +49,7 @@ var Widget = cc.Class({ editor: CC_EDITOR && { menu: 'i18n:MAIN_MENU.component.ui/Widget', help: 'i18n:COMPONENT.help_url.widget', - inspector: 'app://editor/page/inspector/widget/index.html', + inspector: 'packages://inspector/inspectors/comps/ccwidget.js', executeInEditMode: true, disallowMultiple: true, }, diff --git a/cocos2d/core/components/missing-script.js b/cocos2d/core/components/missing-script.js index 71fb1d8add..82bafac5bf 100644 --- a/cocos2d/core/components/missing-script.js +++ b/cocos2d/core/components/missing-script.js @@ -34,7 +34,7 @@ var MissingScript = cc.Class({ name: 'cc.MissingScript', extends: cc.Component, editor: { - inspector: 'app://editor/page/inspector/missing-script.html', + inspector: 'packages://inspector/inspectors/comps/missing-script.js', }, properties: { //_scriptUuid: { diff --git a/cocos2d/core/editbox/CCSGEditBox.js b/cocos2d/core/editbox/CCSGEditBox.js index 2c4792b8e4..70cb525e9b 100644 --- a/cocos2d/core/editbox/CCSGEditBox.js +++ b/cocos2d/core/editbox/CCSGEditBox.js @@ -248,6 +248,12 @@ _ccsg.EditBox = _ccsg.Node.extend({ this._renderCmd.updateVisibility(); }, + createDomElementIfNeeded: function () { + if(!this._renderCmd._edTxt) { + this._renderCmd.createNativeControl(); + } + }, + cleanup: function () { this._renderCmd._removeDomInputControl(); this.stopAllActions(); @@ -411,12 +417,12 @@ _ccsg.EditBox = _ccsg.Node.extend({ if (this._editBoxInputMode === inputMode) return; var oldText = this.getString(); + this._editBoxInputMode = inputMode; this._renderCmd.setInputMode(inputMode); this._renderCmd.transform(); this.setString(oldText); - this._editBoxInputMode = inputMode; this._renderCmd._updateLabelPosition(this.getContentSize()); }, @@ -436,7 +442,6 @@ _ccsg.EditBox = _ccsg.Node.extend({ var _p = _ccsg.EditBox.prototype; // Extended properties -_p.font; cc.defineGetterSetter(_p, 'font', null, _p._setFont); cc.defineGetterSetter(_p, 'fontName', null, _p.setFontName); cc.defineGetterSetter(_p, 'fontSize', null, _p.setFontSize); @@ -479,10 +484,10 @@ _ccsg.EditBox.KeyboardReturnType = KeyboardReturnType; proto.updateMatrix = function () { if (!this._edTxt) return; + var node = this._node, scaleX = cc.view._scaleX, scaleY = cc.view._scaleY; var dpr = cc.view._devicePixelRatio; - var t = node.getNodeToWorldTransform(); - if (!t) return; + var t = this._worldTransform; scaleX /= dpr; scaleY /= dpr; @@ -508,8 +513,9 @@ _ccsg.EditBox.KeyboardReturnType = KeyboardReturnType; }; proto.updateVisibility = function () { - var node = this._node; if (!this._edTxt) return; + + var node = this._node; var editBox = this._edTxt; if (node.visible) { editBox.style.visibility = 'visible'; @@ -570,12 +576,6 @@ _ccsg.EditBox.KeyboardReturnType = KeyboardReturnType; this.style.fontSize = thisPointer._edFontSize + 'px'; this.style.color = cc.colorToHex(editBox._textColor); - if (editBox._editBoxInputFlag === InputFlag.PASSWORD) { - thisPointer._edTxt.type = 'password'; - } else { - thisPointer._edTxt.type = 'text'; - } - if (editBox._delegate && editBox._delegate.editBoxEditingDidBegan) { editBox._delegate.editBoxEditingDidBegan(editBox); } @@ -682,16 +682,16 @@ _ccsg.EditBox.KeyboardReturnType = KeyboardReturnType; var placeholderLabelSize = this._placeholderLabel.getContentSize(); if (this._editBox._editBoxInputMode === InputMode.ANY){ - this._textLabel.setPosition(cc.p(0, editBoxSize.height)); - this._placeholderLabel.setPosition(cc.p(0, editBoxSize.height)); + this._textLabel.setPosition(0, editBoxSize.height); + this._placeholderLabel.setPosition(0, editBoxSize.height); this._placeholderLabel.setVerticalAlign(cc.VerticalTextAlignment.TOP); this._textLabel.setVerticalAlign(cc.VerticalTextAlignment.TOP); this._textLabel.enableWrapText(true); } else { this._textLabel.enableWrapText(false); - this._textLabel.setPosition(cc.p(0, editBoxSize.height)); - this._placeholderLabel.setPosition(cc.p(0, (editBoxSize.height + placeholderLabelSize.height) / 2)); + this._textLabel.setPosition(0, editBoxSize.height); + this._placeholderLabel.setPosition(0, (editBoxSize.height + placeholderLabelSize.height) / 2); this._placeholderLabel.setVerticalAlign(cc.VerticalTextAlignment.CENTER); this._textLabel.setVerticalAlign(cc.VerticalTextAlignment.CENTER); } @@ -721,6 +721,8 @@ _ccsg.EditBox.KeyboardReturnType = KeyboardReturnType; }; proto._updateLabelString = function() { + this._updateInputType(); + this._textLabel.setVisible(true); this._textLabel.setString(this._editBox._text); if (this._edTxt.type === 'password') { @@ -741,7 +743,6 @@ _ccsg.EditBox.KeyboardReturnType = KeyboardReturnType; if (this._edTxt.value === '') { this._placeholderLabel.setVisible(true); this._placeholderLabel.setString(this._editBox._placeholderText); - } else { this._updateLabelString(); @@ -787,6 +788,8 @@ _ccsg.EditBox.KeyboardReturnType = KeyboardReturnType; }; proto.setFontColor = function (color) { + if(!this._edTxt) return; + if (this._edTxt.value !== this._editBox._placeholderText) { this._edTxt.style.color = cc.colorToHex(color); } @@ -798,6 +801,7 @@ _ccsg.EditBox.KeyboardReturnType = KeyboardReturnType; }; proto.setMaxLength = function (maxLength) { + if(!this._edTxt) return; this._edTxt.maxLength = maxLength; }; @@ -810,11 +814,36 @@ _ccsg.EditBox.KeyboardReturnType = KeyboardReturnType; this._placeholderLabel.setColor(color); }; - proto.setInputFlag = function (inputFlag) { - if ((this._edTxt.value !== this._placeholderText) && (inputFlag === InputFlag.PASSWORD)) - this._edTxt.type = 'password'; - else + proto._updateInputType = function () { + if(this._editBox._keyboardReturnType === KeyboardReturnType.SEARCH) { + this._edTxt.type = 'search'; + } + + var inputMode = this._editBox._editBoxInputMode; + if(inputMode === InputMode.EMAIL_ADDR) { + this._edTxt.type = 'email'; + } else if(inputMode === InputMode.NUMERIC || + inputMode === InputMode.DECIMAL) { + this._edTxt.type = 'number'; + } else if(inputMode === InputMode.PHONE_NUMBER) { + this._edTxt.type = 'number'; + this._edTxt.pattern = '[0-9]*'; + } else if(inputMode === InputMode.URL) { + this._edTxt.type = 'url'; + } else { this._edTxt.type = 'text'; + } + + + if (this._editBox._editBoxInputFlag === InputFlag.PASSWORD) { + this._edTxt.type = 'password'; + } + }; + + proto.setInputFlag = function (inputFlag) { + if(!this._edTxt) return; + + this._updateInputType(); this._edTxt.style.textTransform = 'none'; @@ -828,26 +857,27 @@ _ccsg.EditBox.KeyboardReturnType = KeyboardReturnType; }; proto.setInputMode = function (inputMode) { + this._removeDomInputControl(); if (inputMode === InputMode.ANY) { - this._removeDomInputControl(); this._createDomTextArea(); - this._addDomInputControl(); } - else if(this._editBox._editBoxInputMode === InputMode.ANY) { - this._removeDomInputControl(); + else { this._createDomInput(); - this._addDomInputControl(); } + this._addDomInputControl(); + + this._updateInputType(); var contentSize = this._node.getContentSize(); this.updateSize(contentSize.width, contentSize.height); }; proto.setString = function (text) { + if(!this._edTxt) return; + if (text !== null) { this._edTxt.value = text; if (text === '') { - this._edTxt.type = 'text'; this._placeholderLabel.setString(this._editBox._placeholderText); this._placeholderLabel.setColor(this._editBox._placeholderColor); this._placeholderLabel.setVisible(true); @@ -857,25 +887,18 @@ _ccsg.EditBox.KeyboardReturnType = KeyboardReturnType; this._edTxt.style.color = cc.colorToHex(this._editBox._textColor); this._textLabel.setColor(this._editBox._textColor); this._placeholderLabel.setVisible(false); - if (this._editBox._editBoxInputFlag === InputFlag.PASSWORD) { - this._edTxt.type = 'password'; - } - else { - this._edTxt.type = 'text'; - } + this._updateLabelString(); } } }; proto._updateDOMFontStyle = function() { + if(!this._edTxt) return; + if (this._edTxt.value !== '') { this._edTxt.style.fontFamily = this._edFontName; this._edTxt.style.fontSize = this._edFontSize + 'px'; - if (this._editBox._editBoxInputFlag === InputFlag.PASSWORD) - this._edTxt.type = 'password'; - else - this._edTxt.type = 'text'; } this._textLabel.setFontSize(this._edFontSize); this._textLabel.setFontFileOrFamily(this._edFontName); @@ -939,7 +962,7 @@ _ccsg.EditBox.KeyboardReturnType = KeyboardReturnType; canvasRenderCmdProto.constructor = _ccsg.EditBox.CanvasRenderCmd; canvasRenderCmdProto.transform = function (parentCmd, recursive) { - _ccsg.Node.CanvasRenderCmd.prototype.transform.call(this, parentCmd, recursive); + this.originTransform(parentCmd, recursive); this.updateMatrix(); }; @@ -955,7 +978,7 @@ _ccsg.EditBox.KeyboardReturnType = KeyboardReturnType; webGLRenderCmdProto.constructor = _ccsg.EditBox.WebGLRenderCmd; webGLRenderCmdProto.transform = function (parentCmd, recursive) { - _ccsg.Node.WebGLRenderCmd.prototype.transform.call(this, parentCmd, recursive); + this.originTransform(parentCmd, recursive); this.updateMatrix(); }; diff --git a/cocos2d/core/graphics/graphics-webgl-cmd.js b/cocos2d/core/graphics/graphics-webgl-cmd.js index 69b25af3ff..a8f7f4bf0b 100644 --- a/cocos2d/core/graphics/graphics-webgl-cmd.js +++ b/cocos2d/core/graphics/graphics-webgl-cmd.js @@ -122,6 +122,9 @@ function WebGLRenderCmd (renderable) { this._indicesBuffer = null; this._indicesDirty = false; + this._matrix = new cc.math.Matrix4(); + this._matrix.identity(); + this._paths = []; this._points = []; @@ -133,7 +136,7 @@ function WebGLRenderCmd (renderable) { this._shader = new cc.GLProgram(); this._shader.initWithVertexShaderByteArray(Shader.vert, Shader.frag); this._shader.retain(); - this._shader.addAttribute(cc.ATTRIBUTE_NAME_POSITION, cc.VERTEX_ATTRIB_POSITION); + this._shader.addAttribute(cc.ATTRIBUTE_NAME_POSITION, cc.macro.VERTEX_ATTRIB_POSITION); this._shader.link(); this._shader.updateUniforms(); @@ -393,8 +396,7 @@ Js.mixin(_p, { this._indicesDirty = false; } - cc.gl.enableVertexAttribs(cc.macro.VERTEX_ATTRIB_FLAG_POSITION); - + gl.enableVertexAttribArray(cc.macro.VERTEX_ATTRIB_POSITION); gl.vertexAttribPointer(cc.macro.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, VERTS_BYTE_LENGTH, 0); var shader = this._shader; @@ -418,12 +420,19 @@ Js.mixin(_p, { }, rendering: function () { - var node = this._node; cc.gl.blendFunc(this._blendFunc.src, this._blendFunc.dst); + var wt = this._worldTransform, mat = this._matrix.mat; + mat[0] = wt.a; + mat[4] = wt.c; + mat[12] = wt.tx; + mat[1] = wt.b; + mat[5] = wt.d; + mat[13] = wt.ty; + var shader = this._shader; shader.use(); - shader._setUniformForMVPMatrixWithMat4(this._stackMatrix); + shader._setUniformForMVPMatrixWithMat4(this._matrix); this._render(); }, @@ -525,7 +534,8 @@ Js.mixin(_p, { // Calculate segment direction and length var dPos = p1.sub(p0); p0.len = dPos.mag(); - dPos.normalizeSelf(); + if (dPos.x || dPos.y) + dPos.normalizeSelf(); p0.dx = dPos.x; p0.dy = dPos.y; // Advance diff --git a/cocos2d/core/label/CCSGLabel.js b/cocos2d/core/label/CCSGLabel.js index 596a12ffb5..eb2704d396 100644 --- a/cocos2d/core/label/CCSGLabel.js +++ b/cocos2d/core/label/CCSGLabel.js @@ -477,7 +477,6 @@ _ccsg.Label = _ccsg.Node.extend({ } else if (this._labelType === _ccsg.Label.Type.TTF || this._labelType === _ccsg.Label.Type.SystemFont) { this._renderCmd._bakeLabel(); - this._renderCmd._prepareQuad(); } }, @@ -500,7 +499,7 @@ _ccsg.Label = _ccsg.Node.extend({ var locFlag = this._renderCmd._dirtyFlag; if (locFlag & _ccsg.Node._dirtyFlags.textDirty) { this._updateLabel(); - this._renderCmd._dirtyFlag &= _ccsg.Node._dirtyFlags.textDirty ^ this._renderCmd._dirtyFlag; + this._renderCmd._dirtyFlag &= ~_ccsg.Node._dirtyFlags.textDirty; } return _ccsg.Node.prototype.getContentSize.call(this); }, @@ -508,7 +507,7 @@ _ccsg.Label = _ccsg.Node.extend({ var locFlag = this._renderCmd._dirtyFlag; if (locFlag & _ccsg.Node._dirtyFlags.textDirty) { this._updateLabel(); - this._renderCmd._dirtyFlag &= _ccsg.Node._dirtyFlags.textDirty ^ this._renderCmd._dirtyFlag; + this._renderCmd._dirtyFlag &= ~_ccsg.Node._dirtyFlags.textDirty; } return _ccsg.Node.prototype._getWidth.call(this); }, @@ -516,7 +515,7 @@ _ccsg.Label = _ccsg.Node.extend({ var locFlag = this._renderCmd._dirtyFlag; if (locFlag & _ccsg.Node._dirtyFlags.textDirty) { this._updateLabel(); - this._renderCmd._dirtyFlag &= _ccsg.Node._dirtyFlags.textDirty ^ this._renderCmd._dirtyFlag; + this._renderCmd._dirtyFlag &= ~_ccsg.Node._dirtyFlags.textDirty; } return _ccsg.Node.prototype._getHeight.call(this); }, @@ -576,8 +575,6 @@ cc.BMFontHelper = { var ret = true; this._spriteBatchNode.removeAllChildren(); - - var letterClamp = false; for (var ctr = 0; ctr < this._string.length; ++ctr) { if (this._lettersInfo[ctr]._valid) { @@ -626,7 +623,7 @@ cc.BMFontHelper = { if (this._reusedRect.height > 0 && this._reusedRect.width > 0) { var fontChar = this.getChildByTag(ctr); - var locTexture = this._spriteBatchNode._renderCmd._texture || this._spriteBatchNode.textureAtlas.texture; + var locTexture = this._spriteBatchNode._texture; if (!fontChar) { fontChar = new _ccsg.Sprite(); diff --git a/cocos2d/core/label/CCSGLabelCanvasRenderCmd.js b/cocos2d/core/label/CCSGLabelCanvasRenderCmd.js index 271bd9cdbc..7abb530beb 100644 --- a/cocos2d/core/label/CCSGLabelCanvasRenderCmd.js +++ b/cocos2d/core/label/CCSGLabelCanvasRenderCmd.js @@ -25,10 +25,7 @@ ****************************************************************************/ (function () { - _ccsg.Label.TTFLabelBaker = function () { - - }; - + _ccsg.Label.TTFLabelBaker = function () {}; var proto = _ccsg.Label.TTFLabelBaker.prototype = Object.create(Object.prototype); @@ -37,19 +34,19 @@ var colorDirty = locFlag & flags.colorDirty, opacityDirty = locFlag & flags.opacityDirty; - if (colorDirty) + if (colorDirty) this._updateDisplayColor(); if (opacityDirty) this._updateDisplayOpacity(); - if(colorDirty || opacityDirty || (locFlag & flags.textDirty)){ + if (colorDirty || opacityDirty || (locFlag & flags.textDirty)) { this._notifyRegionStatus && this._notifyRegionStatus(_ccsg.Node.CanvasRenderCmd.RegionStatus.Dirty); this._rebuildLabelSkin(); } - if (this._dirtyFlag & flags.transformDirty){ + if (this._dirtyFlag & flags.transformDirty) { this.transform(this.getParentRenderCmd(), true); - this._dirtyFlag = this._dirtyFlag & _ccsg.Node._dirtyFlags.transformDirty ^ this._dirtyFlag; + this._dirtyFlag &= ~flags.transformDirty; } }; @@ -58,13 +55,13 @@ var flags = _ccsg.Node._dirtyFlags, locFlag = this._dirtyFlag; var parentNode = parentCmd ? parentCmd._node : null; - if(parentNode && parentNode._cascadeColorEnabled && (parentCmd._dirtyFlag & flags.colorDirty)) + if (parentNode && parentNode._cascadeColorEnabled && (parentCmd._dirtyFlag & flags.colorDirty)) locFlag |= flags.colorDirty; - if(parentNode && parentNode._cascadeOpacityEnabled && (parentCmd._dirtyFlag & flags.opacityDirty)) + if (parentNode && parentNode._cascadeOpacityEnabled && (parentCmd._dirtyFlag & flags.opacityDirty)) locFlag |= flags.opacityDirty; - if(parentCmd && (parentCmd._dirtyFlag & flags.transformDirty)) + if (parentCmd && (parentCmd._dirtyFlag & flags.transformDirty)) locFlag |= flags.transformDirty; var colorDirty = locFlag & flags.colorDirty, @@ -77,7 +74,7 @@ if (opacityDirty) this._syncDisplayOpacity(); - if(colorDirty || opacityDirty || (this._dirtyFlag & flags.textDirty)){ + if (colorDirty || opacityDirty || (this._dirtyFlag & flags.textDirty)) { this._rebuildLabelSkin(); } @@ -99,30 +96,6 @@ return lineHeight; }; - proto._prepareQuad = function () { - var quad = this._quad; - var white = cc.color(255, 255, 255, this._displayedOpacity); - var width = this._node._contentSize.width; - var height = this._node._contentSize.height; - quad._bl.colors = white; - quad._br.colors = white; - quad._tl.colors = white; - quad._tr.colors = white; - - quad._bl.vertices = new cc.Vertex3F(0, 0, 0); - quad._br.vertices = new cc.Vertex3F(width, 0, 0); - quad._tl.vertices = new cc.Vertex3F(0, height, 0); - quad._tr.vertices = new cc.Vertex3F(width, height, 0); - - //texture coordinate should be y-flipped - quad._bl.texCoords = new cc.Tex2F(0, 1); - quad._br.texCoords = new cc.Tex2F(1, 1); - quad._tl.texCoords = new cc.Tex2F(0, 0); - quad._tr.texCoords = new cc.Tex2F(1, 0); - - this._quadDirty = true; - }; - var label_wrapinspection = true; //Support: English French German @@ -492,12 +465,12 @@ this._labelContext.fillText(this._splitedStrings[i], startPosition.x, startPosition.y + i * lineHeight); } - this._labelTexture._textureLoaded = false; - this._labelTexture.handleLoadedTexture(); + this._texture._textureLoaded = false; + this._texture.handleLoadedTexture(); }; proto._rebuildLabelSkin = function () { - this._dirtyFlag = this._dirtyFlag & _ccsg.Node._dirtyFlags.textDirty ^ this._dirtyFlag; + this._dirtyFlag &= ~_ccsg.Node._dirtyFlags.textDirty; var node = this._node; node._updateLabel(); }; @@ -507,14 +480,12 @@ _ccsg.Label.CanvasRenderCmd = function (renderableObject) { _ccsg.Node.CanvasRenderCmd.call(this, renderableObject); this._needDraw = true; - this._labelTexture = new cc.Texture2D(); + this._texture = new cc.Texture2D(); this._labelCanvas = document.createElement('canvas'); this._labelCanvas.width = 1; this._labelCanvas.height = 1; this._labelContext = this._labelCanvas.getContext('2d'); - this._labelTexture.initWithElement(this._labelCanvas); - this._quad = new cc.V3F_C4B_T2F_Quad(); - this._quadDirty = true; + this._texture.initWithElement(this._labelCanvas); this._splitedStrings = null; }; @@ -523,6 +494,21 @@ proto.constructor = _ccsg.Label.CanvasRenderCmd; + proto.transform = function (parentCmd, recursive) { + this.originTransform(parentCmd, recursive); + + var bb = this._currentRegion, + l = bb._minX, r = bb._maxX, b = bb._minY, t = bb._maxY, + rect = cc.visibleRect, + vl = rect.left.x, vr = rect.right.x, vt = rect.top.y, vb = rect.bottom.y; + if (r < vl || l > vr || t < vb || b > vt) { + this._needDraw = false; + } + else { + this._needDraw = true; + } + }; + proto.rendering = function (ctx, scaleX, scaleY) { var node = this._node; @@ -540,7 +526,7 @@ wrapper.setCompositeOperation(_ccsg.Node.CanvasRenderCmd._getCompositeOperationByBlendFunc(node._blendFunc)); wrapper.setGlobalAlpha(alpha); - if (this._labelTexture) { + if (this._texture) { var sx, sy, sw, sh; var x, y, w, h; @@ -550,8 +536,8 @@ h = this._node._contentSize.height; - var textureWidth = this._labelTexture.getPixelWidth(); - var textureHeight = this._labelTexture.getPixelHeight(); + var textureWidth = this._texture.getPixelWidth(); + var textureHeight = this._texture.getPixelHeight(); sx = 0; sy = 0; @@ -563,9 +549,9 @@ w = w * scaleX; h = h * scaleY; - var image = this._labelTexture._htmlElementObj; - if (this._labelTexture._pattern !== '') { - wrapper.setFillStyle(context.createPattern(image, this._labelTexture._pattern)); + var image = this._texture._htmlElementObj; + if (this._texture._pattern !== '') { + wrapper.setFillStyle(context.createPattern(image, this._texture._pattern)); context.fillRect(x, y, w, h); } else { diff --git a/cocos2d/core/label/CCSGLabelWebGLRenderCmd.js b/cocos2d/core/label/CCSGLabelWebGLRenderCmd.js index 8636d8bab5..bf26a7144a 100644 --- a/cocos2d/core/label/CCSGLabelWebGLRenderCmd.js +++ b/cocos2d/core/label/CCSGLabelWebGLRenderCmd.js @@ -30,26 +30,30 @@ http://www.angelcode.com/products/bmfont/ (Free, Windows only) ****************************************************************************/ -var ccgl = cc.gl; - _ccsg.Label.WebGLRenderCmd = function(renderableObject){ _ccsg.Node.WebGLRenderCmd.call(this, renderableObject); this._needDraw = true; - this._labelTexture = new cc.Texture2D(); - this._quadWebBuffer = cc._renderContext.createBuffer(); - this._shaderProgram = cc.shaderCache.programForKey(cc.macro.SHADER_POSITION_TEXTURECOLOR); - this._quad = new cc.V3F_C4B_T2F_Quad(); - + this._texture = new cc.Texture2D(); this._labelCanvas = document.createElement("canvas"); - this._labelTexture.initWithElement(this._labelCanvas); + this._texture.initWithElement(this._labelCanvas); this._labelContext = this._labelCanvas.getContext("2d"); this._labelCanvas.width = 1; this._labelCanvas.height = 1; - this._quadDirty = true; this._splitedStrings = null; this._drawFontsize = 0; + + this._vertices = [ + {x: 0, y: 0, u: 0, v: 0}, // tl + {x: 0, y: 0, u: 0, v: 1}, // bl + {x: 0, y: 0, u: 1, v: 0}, // tr + {x: 0, y: 0, u: 1, v: 1} // br + ]; + this._color = new Uint32Array(1); + this._dirty = false; + + this._shaderProgram = cc.shaderCache.programForKey(cc.macro.SHADER_SPRITE_POSITION_TEXTURECOLORALPHATEST); }; var proto = _ccsg.Label.WebGLRenderCmd.prototype = Object.create(_ccsg.Node.WebGLRenderCmd.prototype); @@ -62,32 +66,69 @@ proto._updateDisplayOpacity = function (parentOpacity) { this._rebuildLabelSkin(); }; -proto.rendering = function (ctx) { +proto.transform = function (parentCmd, recursive) { + this.originTransform(parentCmd, recursive); + + var lx = 0, rx = this._labelCanvas.width, + by = 0, ty = this._labelCanvas.height, + wt = this._worldTransform; + + var vert = this._vertices; + vert[0].x = lx * wt.a + ty * wt.c + wt.tx; // tl + vert[0].y = lx * wt.b + ty * wt.d + wt.ty; + vert[1].x = lx * wt.a + by * wt.c + wt.tx; // bl + vert[1].y = lx * wt.b + by * wt.d + wt.ty; + vert[2].x = rx * wt.a + ty * wt.c + wt.tx; // tr + vert[2].y = rx * wt.b + ty * wt.d + wt.ty; + vert[3].x = rx * wt.a + by * wt.c + wt.tx; // br + vert[3].y = rx * wt.b + by * wt.d + wt.ty; + + var rect = cc.visibleRect, + vl = rect.left.x, vr = rect.right.x, vt = rect.top.y, vb = rect.bottom.y; + if (((vert[0].x-vl) & (vert[1].x-vl) & (vert[2].x-vl) & (vert[3].x-vl)) >> 31 || // All outside left + ((vr-vert[0].x) & (vr-vert[1].x) & (vr-vert[2].x) & (vr-vert[3].x)) >> 31 || // All outside right + ((vert[0].y-vb) & (vert[1].y-vb) & (vert[2].y-vb) & (vert[3].y-vb)) >> 31 || // All outside bottom + ((vt-vert[0].y) & (vt-vert[1].y) & (vt-vert[2].y) & (vt-vert[3].y)) >> 31) // All outside top + { + this._needDraw = false; + } + else { + this._needDraw = true; + } +}; + +proto.uploadData = function (f32buffer, ui32buffer, vertexDataOffset) { var node = this._node; + if (!node._string || (node._labelType !== _ccsg.Label.Type.TTF && + node._labelType !== _ccsg.Label.Type.SystemFont)) + return 0; - if(node.getString() && (node._labelType === _ccsg.Label.Type.TTF || - node._labelType === _ccsg.Label.Type.SystemFont)){ - var gl = ctx || cc._renderContext ; + // Fill in vertex data with quad information (4 vertices for sprite) + var opacity = this._displayedOpacity; + var r = this._displayedColor.r, + g = this._displayedColor.g, + b = this._displayedColor.b; + if (node._opacityModifyRGB) { + var a = opacity / 255; + r *= a; + g *= a; + b *= a; + } + this._color[0] = ((opacity<<24) | (b<<16) | (g<<8) | r); + var z = node._vertexZ; - this._shaderProgram.use(); - this._shaderProgram._setUniformForMVPMatrixWithMat4(this._stackMatrix); - - ccgl.blendFunc(node._blendFunc.src,node._blendFunc.dst); - ccgl.bindTexture2DN(0,this._labelTexture); - ccgl.enableVertexAttribs(cc.macro.VERTEX_ATTRIB_FLAG_POS_COLOR_TEX); - - gl.bindBuffer(gl.ARRAY_BUFFER, this._quadWebBuffer); - - if (this._quadDirty) { - gl.bufferData(gl.ARRAY_BUFFER, this._quad.arrayBuffer, gl.DYNAMIC_DRAW); - this._quadDirty = false; - } - - gl.vertexAttribPointer(0, 3, gl.FLOAT, false, 24, 0); //cc.macro.VERTEX_ATTRIB_POSITION - gl.vertexAttribPointer(1, 4, gl.UNSIGNED_BYTE, true, 24, 12); //cc.macro.VERTEX_ATTRIB_COLOR - gl.vertexAttribPointer(2, 2, gl.FLOAT, false, 24, 16); //cc.macro.VERTEX_ATTRIB_TEX_COORDS - - gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4); + var vertices = this._vertices; + var i, len = vertices.length, vertex, offset = vertexDataOffset; + for (i = 0; i < len; ++i) { + vertex = vertices[i]; + f32buffer[offset] = vertex.x; + f32buffer[offset + 1] = vertex.y; + f32buffer[offset + 2] = z; + ui32buffer[offset + 3] = this._color[0]; + f32buffer[offset + 4] = vertex.u; + f32buffer[offset + 5] = vertex.v; + offset += 6; } + return len; }; diff --git a/cocos2d/core/labelttf/CCLabelTTF.js b/cocos2d/core/labelttf/CCLabelTTF.js index 5a5299f3ec..3bfc0b82ea 100644 --- a/cocos2d/core/labelttf/CCLabelTTF.js +++ b/cocos2d/core/labelttf/CCLabelTTF.js @@ -297,7 +297,7 @@ cc.LabelTTF = _ccsg.Sprite.extend(/** @lends cc.LabelTTF# */{ if (a.r != null && a.g != null && a.b != null && a.a != null) { this._enableShadow(a, b, c); } else { - this._enableShadowNoneColor(a, b, c, d) + this._enableShadowNoneColor(a, b, c, d); } }, @@ -893,11 +893,6 @@ cc.LabelTTF.create = function (text, fontName, fontSize, dimensions, hAlignment, */ cc.LabelTTF.createWithFontDefinition = cc.LabelTTF.create; -if (cc.macro.USE_LA88_LABELS) - cc.LabelTTF._SHADER_PROGRAM = cc.macro.SHADER_POSITION_TEXTURECOLOR; -else - cc.LabelTTF._SHADER_PROGRAM = cc.macro.SHADER_POSITION_TEXTUREA8COLOR; - cc.LabelTTF.__labelHeightDiv = document.createElement("div"); cc.LabelTTF.__labelHeightDiv.style.fontFamily = "Arial"; cc.LabelTTF.__labelHeightDiv.style.position = "absolute"; @@ -922,13 +917,12 @@ document.body ? * @private */ cc.LabelTTF.__getFontHeightByDiv = function (fontName, fontSize) { - + var clientHeight, labelDiv = cc.LabelTTF.__labelHeightDiv; if(fontName instanceof cc.FontDefinition){ /** @type cc.FontDefinition */ var fontDef = fontName; - var clientHeight = cc.LabelTTF.__fontHeightCache[fontDef._getCanvasFontStr()]; + clientHeight = cc.LabelTTF.__fontHeightCache[fontDef._getCanvasFontStr()]; if (clientHeight > 0) return clientHeight; - var labelDiv = cc.LabelTTF.__labelHeightDiv; labelDiv.innerHTML = "ajghl~!"; labelDiv.style.fontFamily = fontDef.fontName; labelDiv.style.fontSize = fontDef.fontSize + "px"; @@ -938,19 +932,19 @@ cc.LabelTTF.__getFontHeightByDiv = function (fontName, fontSize) { clientHeight = labelDiv.clientHeight; cc.LabelTTF.__fontHeightCache[fontDef._getCanvasFontStr()] = clientHeight; labelDiv.innerHTML = ""; - return clientHeight; + } + else { + //Default + clientHeight = cc.LabelTTF.__fontHeightCache[fontName + "." + fontSize]; + if (clientHeight > 0) return clientHeight; + labelDiv.innerHTML = "ajghl~!"; + labelDiv.style.fontFamily = fontName; + labelDiv.style.fontSize = fontSize + "px"; + clientHeight = labelDiv.clientHeight; + cc.LabelTTF.__fontHeightCache[fontName + "." + fontSize] = clientHeight; + labelDiv.innerHTML = ""; } - //Default - var clientHeight = cc.LabelTTF.__fontHeightCache[fontName + "." + fontSize]; - if (clientHeight > 0) return clientHeight; - var labelDiv = cc.LabelTTF.__labelHeightDiv; - labelDiv.innerHTML = "ajghl~!"; - labelDiv.style.fontFamily = fontName; - labelDiv.style.fontSize = fontSize + "px"; - clientHeight = labelDiv.clientHeight; - cc.LabelTTF.__fontHeightCache[fontName + "." + fontSize] = clientHeight; - labelDiv.innerHTML = ""; return clientHeight; }; diff --git a/cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js b/cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js index 405f1103cd..603fd294ff 100644 --- a/cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js +++ b/cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js @@ -47,6 +47,7 @@ cc.LabelTTF._firsrEnglish = /^[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]/; this._isMultiLine = false; this._status = []; this._renderingIndex = 0; + this._texRect = cc.rect(); }; var proto = cc.LabelTTF.RenderCmd.prototype; @@ -174,15 +175,17 @@ cc.LabelTTF._firsrEnglish = /^[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]/; var node = this._node; var scale = cc.view.getDevicePixelRatio(); var locStrokeShadowOffsetX = node._strokeShadowOffsetX, locStrokeShadowOffsetY = node._strokeShadowOffsetY; - var locContentSizeHeight = node._contentSize.height * scale - locStrokeShadowOffsetY, locVAlignment = node._vAlignment; + var locContentSizeHeight = node._contentSize.height * scale - locStrokeShadowOffsetY, + locVAlignment = node._vAlignment, + locHAlignment = node._hAlignment; var dx = locStrokeShadowOffsetX * 0.5, dy = locContentSizeHeight + locStrokeShadowOffsetY * 0.5; var xOffset = 0, yOffset = 0, OffsetYArray = []; var locContentWidth = node._contentSize.width * scale - locStrokeShadowOffsetX; //lineHeight - var lineHeight = node.getLineHeight(); - var transformTop = (lineHeight - this._fontClientHeight) / 2; + var lineHeight = node.getLineHeight() * scale; + var transformTop = (lineHeight - this._fontClientHeight * scale) / 2; if (locHAlignment === cc.TextAlignment.RIGHT) xOffset += locContentWidth; @@ -227,7 +230,7 @@ cc.LabelTTF._firsrEnglish = /^[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]/; context.setTransform(1, 0, 0, 1, locStatus.contextTransform.x, locStatus.contextTransform.y); var xOffset = locStatus.xOffset; var yOffsetArray = locStatus.OffsetYArray; - this.drawLabels(context, xOffset, yOffsetArray) + this.drawLabels(context, xOffset, yOffsetArray); }; proto._checkWarp = function (strArr, i, maxWidth) { @@ -302,56 +305,41 @@ cc.LabelTTF._firsrEnglish = /^[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]/; }; proto.updateStatus = function () { - var flags = _ccsg.Node._dirtyFlags, locFlag = this._dirtyFlag; - var colorDirty = locFlag & flags.colorDirty, - opacityDirty = locFlag & flags.opacityDirty; + var flags = _ccsg.Node._dirtyFlags, locFlag = this._dirtyFlag, + transformDirty = locFlag & flags.transformDirty; - if (colorDirty) - this._updateDisplayColor(); - if (opacityDirty) - this._updateDisplayOpacity(); - - if(colorDirty || opacityDirty){ - this._updateColor(); - }else if(locFlag & flags.textDirty) + if (locFlag & flags.textDirty) this._updateTexture(); - if (this._dirtyFlag & flags.transformDirty){ + if (transformDirty) { + // Avoid invoke transform multiple times + this._dirtyFlag &= ~flags.transformDirty; + } + + _ccsg.Node.RenderCmd.prototype.updateStatus.call(this); + + if (transformDirty) { this.transform(this.getParentRenderCmd(), true); - this._dirtyFlag = this._dirtyFlag & _ccsg.Node._dirtyFlags.transformDirty ^ this._dirtyFlag; } }; proto._syncStatus = function (parentCmd) { - var flags = _ccsg.Node._dirtyFlags, locFlag = this._dirtyFlag; - var parentNode = parentCmd ? parentCmd._node : null; + var flags = _ccsg.Node._dirtyFlags, locFlag = this._dirtyFlag, + transformDirty = locFlag & flags.transformDirty; - if(parentNode && parentNode._cascadeColorEnabled && (parentCmd._dirtyFlag & flags.colorDirty)) - locFlag |= flags.colorDirty; - - if(parentNode && parentNode._cascadeOpacityEnabled && (parentCmd._dirtyFlag & flags.opacityDirty)) - locFlag |= flags.opacityDirty; - - if(parentCmd && (parentCmd._dirtyFlag & flags.transformDirty)) - locFlag |= flags.transformDirty; - - var colorDirty = locFlag & flags.colorDirty, - opacityDirty = locFlag & flags.opacityDirty; - - this._dirtyFlag = locFlag; - - if (colorDirty) - this._syncDisplayColor(); - if (opacityDirty) - this._syncDisplayOpacity(); - - if(colorDirty || opacityDirty){ - this._updateColor(); - }else if(locFlag & flags.textDirty) + if (locFlag & flags.textDirty) this._updateTexture(); - if (locFlag & flags.transformDirty) //update the transform + if (transformDirty) { + // Avoid invoke transform multiple times + this._dirtyFlag &= ~flags.transformDirty; + } + + _ccsg.Node.RenderCmd.prototype._syncStatus.call(this, parentCmd); + + if (transformDirty) { this.transform(parentCmd); + } }; proto.drawLabels = function (context, xOffset, yOffsetArray) { @@ -392,7 +380,7 @@ cc.LabelTTF._firsrEnglish = /^[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]/; context.fillText(line, xOffset, yOffsetArray[i]); } cc.g_NumberOfDraws++; - } + }; })(); (function(){ @@ -412,7 +400,7 @@ cc.LabelTTF._firsrEnglish = /^[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]/; proto.constructor = cc.LabelTTF.CacheRenderCmd; proto._updateTexture = function () { - this._dirtyFlag = this._dirtyFlag & _ccsg.Node._dirtyFlags.textDirty ^ this._dirtyFlag; + this._dirtyFlag &= ~_ccsg.Node._dirtyFlags.textDirty; var node = this._node; this._updateTTF(); var width = this._texRect.width, height = this._texRect.height; @@ -427,7 +415,7 @@ cc.LabelTTF._firsrEnglish = /^[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]/; if (node._string.length === 0) { locLabelCanvas.width = width; - locLabelCanvas.height = locContentSize.height || 1; + locLabelCanvas.height = height; node._texture && node._texture.handleLoadedTexture(); node.setTextureRect(this._texRect); return true; @@ -489,9 +477,8 @@ cc.LabelTTF._firsrEnglish = /^[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]/; }; proto._updateTexture = function () { - this._dirtyFlag = this._dirtyFlag & _ccsg.Node._dirtyFlags.textDirty ^ this._dirtyFlag; + this._dirtyFlag &= ~_ccsg.Node._dirtyFlags.textDirty; var node = this._node; - var scale = cc.view.getDevicePixelRatio(); this._updateTTF(); if (node._string.length === 0) { node.setTextureRect(this._texRect); @@ -547,4 +534,4 @@ cc.LabelTTF._firsrEnglish = /^[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]/; this.drawLabels(context, xOffset, yOffsetArray); wrapper.restore(); }; -})(); \ No newline at end of file +})(); diff --git a/cocos2d/core/labelttf/CCLabelTTFWebGLRenderCmd.js b/cocos2d/core/labelttf/CCLabelTTFWebGLRenderCmd.js index 1601c2b9d8..86c5a475ba 100644 --- a/cocos2d/core/labelttf/CCLabelTTFWebGLRenderCmd.js +++ b/cocos2d/core/labelttf/CCLabelTTFWebGLRenderCmd.js @@ -27,13 +27,9 @@ cc.LabelTTF.WebGLRenderCmd = function (renderable) { _ccsg.Sprite.WebGLRenderCmd.call(this, renderable); cc.LabelTTF.CacheRenderCmd.call(this); - this.setShaderProgram(cc.shaderCache.programForKey(cc.LabelTTF._SHADER_PROGRAM)); }; var proto = cc.LabelTTF.WebGLRenderCmd.prototype = Object.create(_ccsg.Sprite.WebGLRenderCmd.prototype); cc.js.mixin(proto, cc.LabelTTF.CacheRenderCmd.prototype); proto.constructor = cc.LabelTTF.WebGLRenderCmd; - proto._updateColor = function () { - this._updateTexture(); - _ccsg.Sprite.WebGLRenderCmd.prototype._updateColor.call(this); - } -})(); \ No newline at end of file + proto._updateColor = function () {}; +})(); diff --git a/cocos2d/core/layers/CCLayer.js b/cocos2d/core/layers/CCLayer.js index 28cfce1eef..9a8c05ed41 100644 --- a/cocos2d/core/layers/CCLayer.js +++ b/cocos2d/core/layers/CCLayer.js @@ -36,11 +36,10 @@ cc.Layer = _ccsg.Node.extend(/** @lends cc.Layer# */{ *

Constructor of cc.Layer, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function.

*/ ctor: function () { - var nodep = _ccsg.Node.prototype; - nodep.ctor.call(this); + _ccsg.Node.prototype.ctor.call(this); this._ignoreAnchorPointForPosition = true; - nodep.setAnchorPoint.call(this, 0.5, 0.5); - nodep.setContentSize.call(this, cc.winSize); + this.setAnchorPoint(0.5, 0.5); + this.setContentSize(cc.winSize); }, /** @@ -229,21 +228,6 @@ cc.LayerColor = cc.Layer.extend(/** @lends cc.LayerColor# */{ this._renderCmd.updateBlendFunc(locBlendFunc); }, - _setWidth: function(width){ - _ccsg.Node.prototype._setWidth.call(this, width); - this._renderCmd._updateSquareVerticesWidth(width); - }, - - _setHeight: function(height){ - _ccsg.Node.prototype._setHeight.call(this, height); - this._renderCmd._updateSquareVerticesHeight(height); - }, - - setContentSize: function(size, height){ - cc.Layer.prototype.setContentSize.call(this, size, height); - this._renderCmd._updateSquareVertices(size, height); - }, - _createRenderCmd: function(){ if (cc._renderType === cc.game.RENDER_TYPE_CANVAS) return new cc.LayerColor.CanvasRenderCmd(this); @@ -672,4 +656,4 @@ cc.LayerMultiplex = cc.Layer.extend(/** @lends cc.LayerMultiplex# */{ } this._layers.push(layer); } -}); \ No newline at end of file +}); diff --git a/cocos2d/core/layers/CCLayerCanvasRenderCmd.js b/cocos2d/core/layers/CCLayerCanvasRenderCmd.js index 5d53fef903..8151f28347 100644 --- a/cocos2d/core/layers/CCLayerCanvasRenderCmd.js +++ b/cocos2d/core/layers/CCLayerCanvasRenderCmd.js @@ -53,9 +53,32 @@ } }; + proto.updateStatus = function () { + var flags = _ccsg.Node._dirtyFlags, locFlag = this._dirtyFlag; + if (locFlag & flags.orderDirty) { + this._cacheDirty = true; + if(this._updateCache === 0) + this._updateCache = 2; + this._dirtyFlag &= ~flags.orderDirty; + } + + _ccsg.Node.RenderCmd.prototype.updateStatus.call(this); + }; + + proto._syncStatus = function (parentCmd) { + var flags = _ccsg.Node._dirtyFlags, locFlag = this._dirtyFlag; + if (locFlag & flags.orderDirty) { + this._cacheDirty = true; + if(this._updateCache === 0) + this._updateCache = 2; + this._dirtyFlag &= ~flags.orderDirty; + } + _ccsg.Node.RenderCmd.prototype._syncStatus.call(this, parentCmd); + }; + proto.transform = function (parentCmd, recursive) { var wt = this._worldTransform; - var a = wt.a, b = wt.b, c = wt.c, d = wt.d, tx = wt.tx, ty = wt.ty; + var a = wt.a, b = wt.b, c = wt.c, d = wt.d; _ccsg.Node.CanvasRenderCmd.prototype.transform.call(this, parentCmd, recursive); if(( wt.a !== a || wt.b !== b || wt.c !== c || wt.d !== d ) && this._updateCache === 0) this._updateCache = 2; @@ -64,7 +87,6 @@ proto.bake = function(){ if (!this._isBaked) { this._needDraw = true; - cc.renderer.childrenOrderDirty = true; //limit: 1. its children's blendfunc are invalid. this._isBaked = this._cacheDirty = true; if(this._updateCache === 0) @@ -83,7 +105,6 @@ proto.unbake = function(){ if (this._isBaked) { - cc.renderer.childrenOrderDirty = true; this._needDraw = false; this._isBaked = false; this._cacheDirty = true; @@ -137,7 +158,7 @@ proto.visit = function(parentCmd){ if(!this._isBaked){ - _ccsg.Node.CanvasRenderCmd.prototype.visit.call(this, parentCmd); + this.originVisit(parentCmd); return; } @@ -150,9 +171,6 @@ this._syncStatus(parentCmd); cc.renderer.pushRenderCommand(this); - this._cacheDirty = true; - if(this._updateCache === 0) - this._updateCache = 2; //the bakeSprite is drawing this._bakeSprite.visit(this); @@ -290,7 +308,7 @@ proto.visit = function(parentCmd){ if(!this._isBaked){ - _ccsg.Node.CanvasRenderCmd.prototype.visit.call(this, parentCmd); + this.originVisit(); return; } @@ -333,30 +351,6 @@ }; })(); -(function () { - cc.LayerGradient.RenderCmd = { - updateStatus: function () { - var flags = _ccsg.Node._dirtyFlags, locFlag = this._dirtyFlag; - var colorDirty = locFlag & flags.colorDirty, - opacityDirty = locFlag & flags.opacityDirty; - if(colorDirty) - this._updateDisplayColor(); - - if(opacityDirty) - this._updateDisplayOpacity(); - - if(colorDirty || opacityDirty || (locFlag & flags.gradientDirty)) - this._updateColor(); - - if(locFlag & flags.transformDirty) - //update the transform - this.transform(this.getParentRenderCmd(), true); - - this._dirtyFlag = 0; - } - }; -})(); - /** * cc.LayerGradient's rendering objects of Canvas */ @@ -370,7 +364,6 @@ this._endStopStr = null; }; var proto = cc.LayerGradient.CanvasRenderCmd.prototype = Object.create(cc.LayerColor.CanvasRenderCmd.prototype); - cc.js.mixin(proto, cc.LayerGradient.RenderCmd); proto.constructor = cc.LayerGradient.CanvasRenderCmd; proto.rendering = function (ctx, scaleX, scaleY) { @@ -403,45 +396,30 @@ cc.g_NumberOfDraws++; }; - proto._syncStatus = function (parentCmd) { + proto.updateStatus = function () { var flags = _ccsg.Node._dirtyFlags, locFlag = this._dirtyFlag; - var parentNode = parentCmd ? parentCmd._node : null; - - if(parentNode && parentNode._cascadeColorEnabled && (parentCmd._dirtyFlag & flags.colorDirty)) - locFlag |= flags.colorDirty; - - if(parentNode && parentNode._cascadeOpacityEnabled && (parentCmd._dirtyFlag & flags.opacityDirty)) - locFlag |= flags.opacityDirty; - - if(parentCmd && (parentCmd._dirtyFlag & flags.transformDirty)) - locFlag |= flags.transformDirty; - - var colorDirty = locFlag & flags.colorDirty, - opacityDirty = locFlag & flags.opacityDirty; - - this._dirtyFlag = locFlag; - - if (colorDirty) - this._syncDisplayColor(); - - if (opacityDirty) - this._syncDisplayOpacity(); - - if (locFlag & flags.transformDirty) { - //update the transform - this.transform(parentCmd); + if (locFlag & flags.gradientDirty) { + this._dirtyFlag |= flags.colorDirty; + this._dirtyFlag &= ~flags.gradientDirty; } - if (colorDirty || opacityDirty || (locFlag & flags.gradientDirty)){ - this._updateColor(); - } + _ccsg.Node.RenderCmd.prototype.updateStatus.call(this); }; - proto._updateColor = function(){ + proto._syncStatus = function (parentCmd) { + var flags = _ccsg.Node._dirtyFlags, locFlag = this._dirtyFlag; + if (locFlag & flags.gradientDirty) { + this._dirtyFlag |= flags.colorDirty; + this._dirtyFlag &= ~flags.gradientDirty; + } + + _ccsg.Node.RenderCmd.prototype._syncStatus.call(this, parentCmd); + }; + + proto._updateColor = function() { var node = this._node; var contentSize = node._contentSize; var tWidth = contentSize.width * 0.5, tHeight = contentSize.height * 0.5; - this._dirtyFlag = this._dirtyFlag & _ccsg.Node._dirtyFlags.gradientDirty ^ this._dirtyFlag; //fix the bug of gradient layer var angle = cc.pAngleSigned(cc.p(0, -1), node._alongVector); @@ -473,4 +451,4 @@ } } }; -})(); \ No newline at end of file +})(); diff --git a/cocos2d/core/layers/CCLayerWebGLRenderCmd.js b/cocos2d/core/layers/CCLayerWebGLRenderCmd.js index 94fdad15ab..3ac70da0a5 100644 --- a/cocos2d/core/layers/CCLayerWebGLRenderCmd.js +++ b/cocos2d/core/layers/CCLayerWebGLRenderCmd.js @@ -54,23 +54,28 @@ cc.Layer.WebGLRenderCmd.call(this, renderable); this._needDraw = true; + this._matrix = new cc.math.Matrix4(); + this._matrix.identity(); + // var _t = this; - _t._squareVerticesAB = new ArrayBuffer(32); + _t._squareVerticesAB = new ArrayBuffer(48); _t._squareColorsAB = new ArrayBuffer(16); var locSquareVerticesAB = _t._squareVerticesAB, locSquareColorsAB = _t._squareColorsAB; - var locVertex2FLen = cc.Vertex2F.BYTES_PER_ELEMENT, locColorLen = cc.WebGLColor.BYTES_PER_ELEMENT; - _t._squareVertices = [new cc.Vertex2F(0, 0, locSquareVerticesAB, 0), - new cc.Vertex2F(0, 0, locSquareVerticesAB, locVertex2FLen), - new cc.Vertex2F(0, 0, locSquareVerticesAB, locVertex2FLen * 2), - new cc.Vertex2F(0, 0, locSquareVerticesAB, locVertex2FLen * 3)]; - _t._squareColors = [new cc.WebGLColor(0, 0, 0, 255, locSquareColorsAB, 0), - new cc.WebGLColor(0, 0, 0, 255, locSquareColorsAB, locColorLen), - new cc.WebGLColor(0, 0, 0, 255, locSquareColorsAB, locColorLen * 2), - new cc.WebGLColor(0, 0, 0, 255, locSquareColorsAB, locColorLen * 3)]; + var locVertex3FLen = cc.Vertex3F.BYTES_PER_ELEMENT, locColorLen = cc.Color.BYTES_PER_ELEMENT; + _t._squareVertices = [new cc.Vertex3F(0, 0, 0, locSquareVerticesAB, 0), + new cc.Vertex3F(0, 0, 0, locSquareVerticesAB, locVertex3FLen), + new cc.Vertex3F(0, 0, 0, locSquareVerticesAB, locVertex3FLen * 2), + new cc.Vertex3F(0, 0, 0, locSquareVerticesAB, locVertex3FLen * 3)]; + _t._squareColors = [cc.color(0, 0, 0, 255, locSquareColorsAB, 0), + cc.color(0, 0, 0, 255, locSquareColorsAB, locColorLen), + cc.color(0, 0, 0, 255, locSquareColorsAB, locColorLen * 2), + cc.color(0, 0, 0, 255, locSquareColorsAB, locColorLen * 3)]; _t._verticesFloat32Buffer = cc._renderContext.createBuffer(); _t._colorsUint8Buffer = cc._renderContext.createBuffer(); + + this._shaderProgram = cc.shaderCache.programForKey(cc.SHADER_POSITION_COLOR); }; var proto = cc.LayerColor.WebGLRenderCmd.prototype = Object.create(cc.Layer.WebGLRenderCmd.prototype); proto.constructor = cc.LayerColor.WebGLRenderCmd; @@ -79,16 +84,25 @@ var context = ctx || cc._renderContext; var node = this._node; + var wt = this._worldTransform, mat = this._matrix.mat; + mat[0] = wt.a; + mat[4] = wt.c; + mat[12] = wt.tx; + mat[1] = wt.b; + mat[5] = wt.d; + mat[13] = wt.ty; + this._shaderProgram.use(); - this._shaderProgram._setUniformForMVPMatrixWithMat4(this._stackMatrix); - cc.gl.enableVertexAttribs(cc.macro.VERTEX_ATTRIB_FLAG_POSITION | cc.macro.VERTEX_ATTRIB_FLAG_COLOR); + this._shaderProgram._setUniformForMVPMatrixWithMat4(this._matrix); + context.enableVertexAttribArray(cc.macro.VERTEX_ATTRIB_POSITION); + context.enableVertexAttribArray(cc.macro.VERTEX_ATTRIB_COLOR); cc.gl.blendFunc(node._blendFunc.src, node._blendFunc.dst); // // Attributes // context.bindBuffer(context.ARRAY_BUFFER, this._verticesFloat32Buffer); - context.vertexAttribPointer(cc.macro.VERTEX_ATTRIB_POSITION, 2, context.FLOAT, false, 0, 0); + context.vertexAttribPointer(cc.macro.VERTEX_ATTRIB_POSITION, 3, context.FLOAT, false, 0, 0); context.bindBuffer(context.ARRAY_BUFFER, this._colorsUint8Buffer); context.vertexAttribPointer(cc.macro.VERTEX_ATTRIB_COLOR, 4, context.UNSIGNED_BYTE, true, 0, 0); @@ -96,33 +110,23 @@ context.drawArrays(context.TRIANGLE_STRIP, 0, this._squareVertices.length); }; - proto._updateSquareVertices = function(size, height){ - var locSquareVertices = this._squareVertices; - if (height === undefined) { - locSquareVertices[1].x = size.width; - locSquareVertices[2].y = size.height; - locSquareVertices[3].x = size.width; - locSquareVertices[3].y = size.height; - } else { - locSquareVertices[1].x = size; - locSquareVertices[2].y = height; - locSquareVertices[3].x = size; - locSquareVertices[3].y = height; - } - this._bindLayerVerticesBufferData(); - }; + proto.transform = function (parentCmd, recursive) { + this.originTransform(parentCmd, recursive); + + var node = this._node, + width = node._contentSize.width, + height = node._contentSize.height; - proto._updateSquareVerticesWidth = function(width){ var locSquareVertices = this._squareVertices; locSquareVertices[1].x = width; - locSquareVertices[3].x = width; - this._bindLayerVerticesBufferData(); - }; - - proto._updateSquareVerticesHeight = function(height){ - var locSquareVertices = this._squareVertices; locSquareVertices[2].y = height; + locSquareVertices[3].x = width; locSquareVertices[3].y = height; + locSquareVertices[0].z = + locSquareVertices[1].z = + locSquareVertices[2].z = + locSquareVertices[3].z = node._vertexZ; + this._bindLayerVerticesBufferData(); }; @@ -141,7 +145,7 @@ proto._bindLayerVerticesBufferData = function(){ var glContext = cc._renderContext; glContext.bindBuffer(glContext.ARRAY_BUFFER, this._verticesFloat32Buffer); - glContext.bufferData(glContext.ARRAY_BUFFER, this._squareVerticesAB, glContext.STATIC_DRAW); + glContext.bufferData(glContext.ARRAY_BUFFER, this._squareVerticesAB, glContext.DYNAMIC_DRAW); }; proto._bindLayerColorsBufferData = function(){ @@ -164,62 +168,51 @@ this._clippingRectDirty = false; }; var proto = cc.LayerGradient.WebGLRenderCmd.prototype = Object.create(cc.LayerColor.WebGLRenderCmd.prototype); - cc.js.mixin(proto, cc.LayerGradient.RenderCmd); proto.constructor = cc.LayerGradient.WebGLRenderCmd; + proto.updateStatus = function () { + var flags = _ccsg.Node._dirtyFlags, locFlag = this._dirtyFlag; + if (locFlag & flags.gradientDirty) { + this._dirtyFlag |= flags.colorDirty; + this._updateVertex(); + this._dirtyFlag &= ~flags.gradientDirty; + } + + _ccsg.Node.RenderCmd.prototype.updateStatus.call(this); + }; + proto._syncStatus = function (parentCmd) { var flags = _ccsg.Node._dirtyFlags, locFlag = this._dirtyFlag; - var parentNode = parentCmd ? parentCmd._node : null; - - if(parentNode && parentNode._cascadeColorEnabled && (parentCmd._dirtyFlag & flags.colorDirty)) - locFlag |= flags.colorDirty; - - if(parentNode && parentNode._cascadeOpacityEnabled && (parentCmd._dirtyFlag & flags.opacityDirty)) - locFlag |= flags.opacityDirty; - - if(parentCmd && (parentCmd._dirtyFlag & flags.transformDirty)) - locFlag |= flags.transformDirty; - - var colorDirty = locFlag & flags.colorDirty, - opacityDirty = locFlag & flags.opacityDirty; - - this._dirtyFlag = locFlag; - - if (colorDirty) - this._syncDisplayColor(); - - if (opacityDirty) - this._syncDisplayOpacity(); - - //if (locFlag & flags.transformDirty) { - //update the transform - this.transform(parentCmd); - //} - - if (colorDirty || opacityDirty || (locFlag & flags.gradientDirty)){ - this._updateColor(); + if (locFlag & flags.gradientDirty) { + this._dirtyFlag |= flags.colorDirty; + this._updateVertex(); + this._dirtyFlag &= ~flags.gradientDirty; } + + _ccsg.Node.RenderCmd.prototype._syncStatus.call(this, parentCmd); }; - proto._updateColor = function(){ - this._dirtyFlag = this._dirtyFlag & _ccsg.Node._dirtyFlags.gradientDirty ^ this._dirtyFlag; + proto.transform = function (parentCmd, recursive) { + this.originTransform(parentCmd, recursive); + this._updateVertex(); + }; + + proto._updateVertex = function () { var node = this._node, stops = node._colorStops; if(!stops || stops.length < 2) return; this._clippingRectDirty = true; var stopsLen = stops.length, verticesLen = stopsLen * 2, i, contentSize = node._contentSize; - this._squareVerticesAB = new ArrayBuffer(verticesLen * 8); - this._squareColorsAB = new ArrayBuffer(verticesLen * 4); - var locVertices = this._squareVertices, locColors = this._squareColors; - locVertices.length = 0; - locColors.length = 0; - - var locSquareVerticesAB = this._squareVerticesAB, locSquareColorsAB = this._squareColorsAB; - var locVertex2FLen = cc.Vertex2F.BYTES_PER_ELEMENT, locColorLen = cc.WebGLColor.BYTES_PER_ELEMENT; - for(i = 0; i < verticesLen; i++){ - locVertices.push(new cc.Vertex2F(0, 0, locSquareVerticesAB, locVertex2FLen * i)); - locColors.push(new cc.WebGLColor(0, 0, 0, 255, locSquareColorsAB, locColorLen * i)) + var locVertices = this._squareVertices; + if (locVertices.length < verticesLen) { + this._squareVerticesAB = new ArrayBuffer(verticesLen * 12); + locVertices.length = 0; + var locSquareVerticesAB = this._squareVerticesAB; + var locVertex3FLen = cc.Vertex3F.BYTES_PER_ELEMENT; + for(i = 0; i < verticesLen; i++){ + locVertices.push(new cc.Vertex3F(0, 0, 0, locSquareVerticesAB, locVertex3FLen * i)); + } } //init vertex @@ -250,12 +243,34 @@ var p0 = cc.pointApplyAffineTransform(- locAnchor.x , y - locAnchor.y, transMat); locVertices[i * 2].x = p0.x; locVertices[i * 2].y = p0.y; + locVertices[i * 2].z = node._vertexZ; var p1 = cc.pointApplyAffineTransform(contentSize.width - locAnchor.x, y - locAnchor.y, transMat); locVertices[i * 2 + 1].x = p1.x; locVertices[i * 2 + 1].y = p1.y; + locVertices[i * 2 + 1].z = node._vertexZ; } + this._bindLayerVerticesBufferData(); + }; + + proto._updateColor = function() { + var node = this._node, stops = node._colorStops; + if(!stops || stops.length < 2) + return; + //init color + var stopsLen = stops.length; + var locColors = this._squareColors, verticesLen = stopsLen * 2; + if (locColors.length < verticesLen) { + this._squareColorsAB = new ArrayBuffer(verticesLen * 4); + locColors.length = 0; + var locSquareColorsAB = this._squareColorsAB; + var locColorLen = cc.Color.BYTES_PER_ELEMENT; + for(i = 0; i < verticesLen; i++){ + locColors.push(cc.color(0, 0, 0, 255, locSquareColorsAB, locColorLen * i)); + } + } + var opacityf = this._displayedOpacity / 255.0; //, displayColor = this._displayedColor; for(i = 0; i < stopsLen; i++){ var stopColor = stops[i].color, locSquareColor0 = locColors[i * 2], locSquareColor1 = locColors[i * 2 + 1]; @@ -269,7 +284,6 @@ locSquareColor1.b = stopColor.b; locSquareColor1.a = stopColor.a * opacityf; } - this._bindLayerVerticesBufferData(); this._bindLayerColorsBufferData(); }; @@ -282,16 +296,25 @@ context.enable(context.SCISSOR_TEST); cc.view.setScissorInPoints(clippingRect.x, clippingRect.y, clippingRect.width, clippingRect.height); + var wt = this._worldTransform, mat = this._matrix.mat; + mat[0] = wt.a; + mat[4] = wt.c; + mat[12] = wt.tx; + mat[1] = wt.b; + mat[5] = wt.d; + mat[13] = wt.ty; + //draw gradient layer this._shaderProgram.use(); - this._shaderProgram._setUniformForMVPMatrixWithMat4(this._stackMatrix); - cc.gl.enableVertexAttribs(cc.macro.VERTEX_ATTRIB_FLAG_POSITION | cc.macro.VERTEX_ATTRIB_FLAG_COLOR); + this._shaderProgram._setUniformForMVPMatrixWithMat4(this._matrix); + context.enableVertexAttribArray(cc.macro.VERTEX_ATTRIB_POSITION); + context.enableVertexAttribArray(cc.macro.VERTEX_ATTRIB_COLOR); cc.gl.blendFunc(node._blendFunc.src, node._blendFunc.dst); // // Attributes // context.bindBuffer(context.ARRAY_BUFFER, this._verticesFloat32Buffer); - context.vertexAttribPointer(cc.macro.VERTEX_ATTRIB_POSITION, 2, context.FLOAT, false, 0, 0); + context.vertexAttribPointer(cc.macro.VERTEX_ATTRIB_POSITION, 3, context.FLOAT, false, 0, 0); context.bindBuffer(context.ARRAY_BUFFER, this._colorsUint8Buffer); context.vertexAttribPointer(cc.macro.VERTEX_ATTRIB_COLOR, 4, context.UNSIGNED_BYTE, true, 0, 0); context.drawArrays(context.TRIANGLE_STRIP, 0, this._squareVertices.length); @@ -308,4 +331,4 @@ } return this._clipRect; }; -})(); \ No newline at end of file +})(); diff --git a/cocos2d/core/load-pipeline/audio-downloader.js b/cocos2d/core/load-pipeline/audio-downloader.js index 2022be6aed..40fdebb9d5 100644 --- a/cocos2d/core/load-pipeline/audio-downloader.js +++ b/cocos2d/core/load-pipeline/audio-downloader.js @@ -51,7 +51,6 @@ function loadAudioFromExtList (url, typeList, audio, cb){ } function loadDomAudio (url, typeList, audio, cb) { - var num = __audioSupport.ONE_SOURCE ? 1 : typeList.length; // 加载统一使用dom diff --git a/cocos2d/core/platform/CCClass.js b/cocos2d/core/platform/CCClass.js index e9dc5416f0..8111c78d98 100644 --- a/cocos2d/core/platform/CCClass.js +++ b/cocos2d/core/platform/CCClass.js @@ -148,7 +148,7 @@ function defineProp (cls, className, propName, defaultValue, attrs) { } // set default value - Attr.attr(cls, propName, { 'default': defaultValue }); + Attr.setClassAttr(cls, propName, 'default', defaultValue); appendProp(cls, propName); @@ -228,7 +228,7 @@ function defineGetSet (cls, name, propName, val, attrs) { } if (CC_DEV) { - Attr.attr(cls, propName, {hasGetter: true}); // 方便 editor 做判断 + Attr.setClassAttr(cls, propName, 'hasGetter', true); // 方便 editor 做判断 } } @@ -243,7 +243,7 @@ function defineGetSet (cls, name, propName, val, attrs) { configurable: true, enumerable: true }); - Attr.attr(cls, propName, {hasSetter: true}); // 方便 editor 做判断 + Attr.setClassAttr(cls, propName, 'hasSetter', true); // 方便 editor 做判断 } else { if (d) { @@ -280,7 +280,9 @@ function getDefault (defaultVal) { return defaultVal; } +var DELIMETER = Attr.DELIMETER; function instantiateProps (instance, itsClass) { + var attrs = Attr.getClassAttrs(itsClass); var propList = itsClass.__props__; if (propList === null) { deferredInitializer.init(); @@ -288,9 +290,10 @@ function instantiateProps (instance, itsClass) { } for (var i = 0; i < propList.length; i++) { var prop = propList[i]; - var attrs = Attr.attr(itsClass, prop); - if (attrs && attrs.hasOwnProperty('default')) { // getter does not have default, default maybe 0 - var def = attrs.default; + var attrKey = prop + DELIMETER + 'default'; + if (attrKey in attrs) { // getter does not have default + var def = attrs[attrKey]; + // default maybe 0 if (def) { if (typeof def === 'object' && def) { if (typeof def.clone === 'function') { @@ -331,28 +334,40 @@ cc.isChildClassOf = function (subclass, superclass) { } return false; } - // fireclass - for (; subclass && subclass.$super; subclass = subclass.$super) { - if (subclass === superclass) { - return true; - } - } if (subclass === superclass) { return true; } - // js class - var dunderProto = subclass.prototype && Object.getPrototypeOf(subclass.prototype); - while (dunderProto) { - subclass = dunderProto.constructor; + for (;;) { + var proto = subclass.prototype; // binded function do not have prototype + var dunderProto = proto && Object.getPrototypeOf(proto); + subclass = dunderProto && dunderProto.constructor; + if (!subclass) { + return false; + } if (subclass === superclass) { return true; } - dunderProto = Object.getPrototypeOf(subclass.prototype); } } return false; }; +// get all super classes +function getInheritanceChain (klass) { + var chain = []; + for (;;) { + var dunderProto = Object.getPrototypeOf(klass.prototype); + klass = dunderProto && dunderProto.constructor; + if (!klass) { + break; + } + if (klass !== Object) { + chain.push(klass); + } + } + return chain; +} + function doDefine (className, baseClass, mixins, constructor, options) { var fireClass = _createCtor(constructor, baseClass, mixins, className, options); @@ -381,6 +396,12 @@ function doDefine (className, baseClass, mixins, constructor, options) { for (var p in mixin) if (mixin.hasOwnProperty(p) && INVALID_STATICS.indexOf(p) < 0) fireClass[p] = mixin[p]; + + // mixin attributes + if (CCClass._isCCClass(mixin)) { + JS.mixin(Attr.getClassAttrs(fireClass).constructor.prototype, + Attr.getClassAttrs(mixin).constructor.prototype); + } } // restore constuctor overridden by mixin fireClass.prototype.constructor = fireClass; @@ -937,12 +958,22 @@ CCClass._fastDefine = function (className, constructor, serializableFields) { for (var i = 0; i < props.length; i++) { var key = props[i]; var val = serializableFields[key]; - Attr.attr(constructor, key, { visible: false, default: val }); + Attr.setClassAttr(constructor, key, 'visible', false); + Attr.setClassAttr(constructor, key, 'default', val); } }; +CCClass.Attr = Attr; CCClass.attr = Attr.attr; +/** + * Return all super classes + * @method getInheritanceChain + * @param {Function} constructor + * @return {Function[]} + */ +CCClass.getInheritanceChain = getInheritanceChain; + var PrimitiveTypes = { // Specify that the input value must be integer in Inspector. // Also used to indicates that the type of elements in array or the type of value in dictionary is integer. diff --git a/cocos2d/core/platform/CCMacro.js b/cocos2d/core/platform/CCMacro.js index 8914c1183b..5845405d2f 100644 --- a/cocos2d/core/platform/CCMacro.js +++ b/cocos2d/core/platform/CCMacro.js @@ -1219,18 +1219,36 @@ cc.macro = { * @readonly */ SHADER_POSITION_TEXTURECOLOR: "ShaderPositionTextureColor", + /** + * @property SHADER_SPRITE_POSITION_TEXTURECOLOR + * @type {String} + * @readonly + */ + SHADER_SPRITE_POSITION_TEXTURECOLOR: "ShaderSpritePositionTextureColor", /** * @property SHADER_POSITION_TEXTURECOLORALPHATEST * @type {String} * @readonly */ SHADER_POSITION_TEXTURECOLORALPHATEST: "ShaderPositionTextureColorAlphaTest", + /** + * @property SHADER_SPRITE_POSITION_TEXTURECOLORALPHATEST + * @type {String} + * @readonly + */ + SHADER_SPRITE_POSITION_TEXTURECOLORALPHATEST: "ShaderSpritePositionTextureColorAlphaTest", /** * @property SHADER_POSITION_COLOR * @type {String} * @readonly */ SHADER_POSITION_COLOR: "ShaderPositionColor", + /** + * @property SHADER_SPRITE_POSITION_COLOR + * @type {String} + * @readonly + */ + SHADER_SPRITE_POSITION_COLOR: "ShaderSpritePositionColor", /** * @property SHADER_POSITION_TEXTURE * @type {String} @@ -1606,7 +1624,8 @@ cc.macro = { * @property {Number} ENABLE_GL_STATE_CACHE * @readonly */ - ENABLE_GL_STATE_CACHE: 1 + // Editors do not need to cache fix bug for https://github.com/cocos-creator/fireball/issues/3079 + ENABLE_GL_STATE_CACHE: CC_EDITOR ? 0 : 1 }; /** diff --git a/cocos2d/core/platform/CCObject.js b/cocos2d/core/platform/CCObject.js index 6f64e7237c..ac25c74b5f 100644 --- a/cocos2d/core/platform/CCObject.js +++ b/cocos2d/core/platform/CCObject.js @@ -19,7 +19,7 @@ var IsEditorOnEnableCalled = 1 << 12; var IsPreloadCalled = 1 << 13; var IsOnLoadCalled = 1 << 14; var IsOnLoadStarted = 1 << 15; -var IsOnStartCalled = 1 << 16; +var IsStartCalled = 1 << 16; var IsRotationLocked = 1 << 17; var IsScaleLocked = 1 << 18; @@ -30,7 +30,7 @@ var IsPositionLocked = 1 << 21; //var Hide = HideInGame | HideInEditor; // should not clone or serialize these flags var PersistentMask = ~(ToDestroy | Dirty | Destroying | DontDestroy | Activating | - IsPreloadCalled | IsOnLoadStarted | IsOnLoadCalled | IsOnStartCalled | + IsPreloadCalled | IsOnLoadStarted | IsOnLoadCalled | IsStartCalled | IsOnEnableCalled | IsEditorOnEnableCalled | IsRotationLocked | IsScaleLocked | IsAnchorLocked | IsSizeLocked | IsPositionLocked /*RegisteredInEditor*/); @@ -142,7 +142,7 @@ CCObject.Flags = { IsOnLoadCalled: IsOnLoadCalled, IsOnLoadStarted: IsOnLoadStarted, IsOnEnableCalled: IsOnEnableCalled, - IsOnStartCalled: IsOnStartCalled, + IsStartCalled: IsStartCalled, IsEditorOnEnableCalled: IsEditorOnEnableCalled, IsPositionLocked: IsPositionLocked, diff --git a/cocos2d/core/platform/CCSys.js b/cocos2d/core/platform/CCSys.js index e2ae00b442..9f7128f0e6 100644 --- a/cocos2d/core/platform/CCSys.js +++ b/cocos2d/core/platform/CCSys.js @@ -143,7 +143,7 @@ sys.LANGUAGE_POLISH = "pl"; * @property {String} LANGUAGE_UNKNOWN * @readOnly */ -sys.LANGUAGE_UNKNOWN = "unkonwn"; +sys.LANGUAGE_UNKNOWN = "unknown"; /** * @property {String} OS_IOS @@ -490,7 +490,7 @@ else { * Indicate whether system is mobile system * @property {Boolean} isMobile */ - sys.isMobile = ua.indexOf('mobile') !== -1 || ua.indexOf('android') !== -1; + sys.isMobile = /mobile|android|mqqbrowser|micromessenger|miuibrowser/.test(ua); /** * Indicate the running platform @@ -510,8 +510,20 @@ else { sys.language = currLanguage; // Get the os of system - var iOS = ( ua.match(/(iPad|iPhone|iPod)/i) ? true : false ); - var isAndroid = ua.match(/android/i) || nav.platform.match(/android/i) ? true : false; + var isAndroid = false, iOS = false, osVersion = '', osMainVersion = 0; + var uaResult = /android (\d+(?:\.\d+)+)/i.exec(ua) || /android (\d+(?:\.\d+)+)/i.exec(nav.platform); + if (uaResult) { + isAndroid = true; + osVersion = uaResult[1] || ''; + osMainVersion = parseInt(osVersion) || 0; + } + uaResult = /(iPad|iPhone|iPod).*OS ((\d+_?){2,3})/i.exec(ua); + if (uaResult) { + iOS = true; + osVersion = uaResult[2] || ''; + osMainVersion = parseInt(osVersion) || 0; + } + var osName = sys.OS_UNKNOWN; if (nav.appVersion.indexOf("Win") !== -1) osName = sys.OS_WINDOWS; else if (iOS) osName = sys.OS_IOS; @@ -525,6 +537,16 @@ else { * @property {String} os */ sys.os = osName; + /** + * Indicate the running os version + * @property {String} osVersion + */ + sys.osVersion = osVersion; + /** + * Indicate the running os main version + * @property {Number} osMainVersion + */ + sys.osMainVersion = osMainVersion; /** * Indicate the running browser type @@ -682,14 +704,13 @@ else { if (win.WebGLRenderingContext) { var tmpCanvas = document.createElement("CANVAS"); try{ - var context = cc.create3DContext(tmpCanvas, {'stencil': true, 'preserveDrawingBuffer': true }); + var context = cc.create3DContext(tmpCanvas, {'stencil': true}); if(context) { _supportWebGL = true; } if (_supportWebGL && sys.os === sys.OS_ANDROID) { var browserVer = parseFloat(sys.browserVersion); - switch (sys.browserType) { case sys.BROWSER_TYPE_MOBILE_QQ: case sys.BROWSER_TYPE_BAIDU: @@ -719,7 +740,6 @@ else { case sys.BROWSER_TYPE_UNKNOWN: case sys.BROWSER_TYPE_360: case sys.BROWSER_TYPE_MIUI: - default: _supportWebGL = false; } } diff --git a/cocos2d/core/platform/CCView.js b/cocos2d/core/platform/CCView.js index 169827badd..8507d41347 100644 --- a/cocos2d/core/platform/CCView.js +++ b/cocos2d/core/platform/CCView.js @@ -91,6 +91,8 @@ switch(__BrowserGetter.adaptationType){ break; } +var _scissorRect = cc.rect(); + /** * cc.view is the singleton object which represents the game window.
* It's main task include:
@@ -116,7 +118,7 @@ var View = cc._Class.extend({ _viewPortRect: null, // The visible rect in content's coordinate in point _visibleRect: null, - _retinaEnabled: false, + _retinaEnabled: false, _autoFullScreen: false, // The device's pixel ratio (for retina displays) _devicePixelRatio: 1, @@ -167,7 +169,7 @@ var View = cc._Class.extend({ _t._contentTranslateLeftTop = {left: 0, top: 0}; _t._viewName = "Cocos2dHTML5"; - var sys = cc.sys; + var sys = cc.sys; _t.enableRetina(sys.os === sys.OS_IOS || sys.os === sys.OS_OSX); _t.enableAutoFullScreen(sys.isMobile && sys.browserType !== sys.BROWSER_TYPE_BAIDU); cc.visibleRect && cc.visibleRect.init(_t._visibleRect); @@ -393,26 +395,26 @@ var View = cc._Class.extend({ this._isAdjustViewPort = enabled; }, - /** - * Retina support is enabled by default for Apple device but disabled for other devices,
- * it takes effect only when you called setDesignResolutionPolicy
+ /** + * Retina support is enabled by default for Apple device but disabled for other devices,
+ * it takes effect only when you called setDesignResolutionPolicy
* Only useful on web * @method enableRetina - * @param {Boolean} enabled - Enable or disable retina display - */ - enableRetina: function(enabled) { - this._retinaEnabled = !!enabled; - }, + * @param {Boolean} enabled - Enable or disable retina display + */ + enableRetina: function(enabled) { + this._retinaEnabled = !!enabled; + }, - /** - * Check whether retina display is enabled.
+ /** + * Check whether retina display is enabled.
* Only useful on web * @method isRetinaEnabled - * @return {Boolean} - */ - isRetinaEnabled: function() { - return this._retinaEnabled; - }, + * @return {Boolean} + */ + isRetinaEnabled: function() { + return this._retinaEnabled; + }, /** * If enabled, the application will try automatically to enter full screen mode on mobile devices
@@ -422,10 +424,10 @@ var View = cc._Class.extend({ * @param {Boolean} enabled - Enable or disable auto full screen on mobile devices */ enableAutoFullScreen: function(enabled) { - if (enabled && enabled !== this._autoFullScreen && cc.sys.isMobile && this._frame === document.documentElement) { + if (enabled && enabled !== this._autoFullScreen && cc.sys.isMobile && cc.game.frame === document.documentElement) { // Automatically full screen when user touches on mobile version this._autoFullScreen = true; - cc.screen.autoFullScreen(this._frame); + cc.screen.autoFullScreen(cc.game.frame); } else { this._autoFullScreen = false; @@ -774,11 +776,15 @@ var View = cc._Class.extend({ * @param {Number} h */ setScissorInPoints: function (x, y, w, h) { - var locFrameZoomFactor = this._frameZoomFactor, locScaleX = this._scaleX, locScaleY = this._scaleY; - cc._renderContext.scissor((x * locScaleX * locFrameZoomFactor + this._viewPortRect.x * locFrameZoomFactor), - (y * locScaleY * locFrameZoomFactor + this._viewPortRect.y * locFrameZoomFactor), - (w * locScaleX * locFrameZoomFactor), - (h * locScaleY * locFrameZoomFactor)); + var zoomFactor = this._frameZoomFactor, scaleX = this._scaleX, scaleY = this._scaleY; + _scissorRect.x = x; + _scissorRect.y = y; + _scissorRect.width = w; + _scissorRect.height = h; + cc._renderContext.scissor(x * scaleX * zoomFactor + this._viewPortRect.x * zoomFactor, + y * scaleY * zoomFactor + this._viewPortRect.y * zoomFactor, + w * scaleX * zoomFactor, + h * scaleY * zoomFactor); }, /** @@ -787,8 +793,7 @@ var View = cc._Class.extend({ * @return {Boolean} */ isScissorEnabled: function () { - var gl = cc._renderContext; - return gl.isEnabled(gl.SCISSOR_TEST); + return cc._renderContext.isEnabled(gl.SCISSOR_TEST); }, /** @@ -797,10 +802,7 @@ var View = cc._Class.extend({ * @return {Rect} */ getScissorRect: function () { - var gl = cc._renderContext, scaleX = this._scaleX, scaleY = this._scaleY; - var boxArr = gl.getParameter(gl.SCISSOR_BOX); - return cc.rect((boxArr[0] - this._viewPortRect.x) / scaleX, (boxArr[1] - this._viewPortRect.y) / scaleY, - boxArr[2] / scaleX, boxArr[3] / scaleY); + return cc.rect(_scissorRect); }, /** @@ -993,9 +995,9 @@ cc.ContentStrategy = cc._Class.extend(/** @lends cc.ContentStrategy# */{ }, _buildResult: function (containerW, containerH, contentW, contentH, scaleX, scaleY) { - // Makes content fit better the canvas - Math.abs(containerW - contentW) < 2 && (contentW = containerW); - Math.abs(containerH - contentH) < 2 && (contentH = containerH); + // Makes content fit better the canvas + Math.abs(containerW - contentW) < 2 && (contentW = containerW); + Math.abs(containerH - contentH) < 2 && (contentH = containerH); var viewport = cc.rect(Math.round((containerW - contentW) / 2), Math.round((containerH - contentH) / 2), @@ -1097,7 +1099,7 @@ cc.ContentStrategy = cc._Class.extend(/** @lends cc.ContentStrategy# */{ */ var EqualToWindow = EqualToFrame.extend({ preApply: function (view) { - this._super(view); + this._super(view); cc.game.frame = document.documentElement; }, @@ -1113,7 +1115,7 @@ cc.ContentStrategy = cc._Class.extend(/** @lends cc.ContentStrategy# */{ */ var ProportionalToWindow = ProportionalToFrame.extend({ preApply: function (view) { - this._super(view); + this._super(view); cc.game.frame = document.documentElement; }, @@ -1161,7 +1163,7 @@ cc.ContentStrategy = cc._Class.extend(/** @lends cc.ContentStrategy# */{ scaleX = containerW / designW, scaleY = containerH / designH, scale = 0, contentW, contentH; - scaleX < scaleY ? (scale = scaleX, contentW = containerW, contentH = designH * scale) + scaleX < scaleY ? (scale = scaleX, contentW = containerW, contentH = designH * scale) : (scale = scaleY, contentW = designW * scale, contentH = containerH); return this._buildResult(containerW, containerH, contentW, contentH, scale, scale); @@ -1235,7 +1237,7 @@ cc.ContentStrategy = cc._Class.extend(/** @lends cc.ContentStrategy# */{ * @param {ContentStrategy} contentStg The content strategy */ cc.ResolutionPolicy = cc._Class.extend(/** @lends cc.ResolutionPolicy# */{ - _containerStrategy: null, + _containerStrategy: null, _contentStrategy: null, /** diff --git a/cocos2d/core/platform/attribute.js b/cocos2d/core/platform/attribute.js index c6809670e1..cefd57fac9 100644 --- a/cocos2d/core/platform/attribute.js +++ b/cocos2d/core/platform/attribute.js @@ -26,86 +26,115 @@ var JS = require('./js'); var isPlainEmptyObj = require('./utils').isPlainEmptyObj_DEV; +function createAttrsSingle (owner, ownerCtor, superAttrs) { + var AttrsCtor; + if (CC_DEV) { + var ctorName = ownerCtor.name + '_ATTRS'; + if (owner !== ownerCtor) { + ctorName += '_INSTANCE'; + } + AttrsCtor = eval('(function ' + ctorName + '(){})'); + } + else { + AttrsCtor = function () {}; + } + if (superAttrs) { + JS.extend(AttrsCtor, superAttrs.constructor); + } + var attrs = new AttrsCtor(); + Object.defineProperty(owner, '__attrs__', { + value: attrs, + }); + return attrs; +} + +// subclass should not have __attrs__ +function createAttrs (subclass) { + var superClass; + var chains = cc.Class.getInheritanceChain(subclass); + for (var i = chains.length - 1; i >= 0; i--) { + var cls = chains[i]; + var attrs = cls.__attrs__; + if (!attrs) { + superClass = chains[i + 1]; + createAttrsSingle(cls, cls, superClass && superClass.__attrs__); + } + } + superClass = chains[0]; + createAttrsSingle(subclass, subclass, superClass && superClass.__attrs__); + return subclass.__attrs__; +} + +var DELIMETER = '$_$'; + // /** // * @class Class // */ -// * +// * // * Tag the class with any meta attributes, then return all current attributes assigned to it. // * This function holds only the attributes, not their implementations. // * // * @method attr -// * @param {Function|Object} constructor - the class or instance. If instance, the attribute will be dynamic and only available for the specified instance. -// * @param {String} propertyName - the name of property or function, used to retrieve the attributes -// * @param {Object} [attributes] - the attribute table to mark, new attributes will merged with existed attributes. Attribute whose key starts with '_' will be ignored. -// * @return {Object|Undefined} return all attributes associated with the property. if none undefined will be returned +// * @param {Function|Object} ctor - the class or instance. If instance, the attribute will be dynamic and only available for the specified instance. +// * @param {String} propName - the name of property or function, used to retrieve the attributes +// * @param {Object} [newAttrs] - the attribute table to mark, new attributes will merged with existed attributes. Attribute whose key starts with '_' will be ignored. // * @static // * @private -// * @example {@link utils/api/engine/docs/cocos2d/core/platform/attribute/attr.js} - -function attr (constructor, propertyName, attributes) { - var key = '_attr$' + propertyName; - var instance, attrs, name; - if (typeof constructor === 'function') { - // attributes in class - instance = constructor.prototype; - attrs = instance[key]; - if (typeof attributes !== 'undefined') { - // set - if (typeof attributes === 'object') { - if (!attrs) { - instance[key] = attrs = {}; - } - for (name in attributes) { - if (name[0] !== '_') { - attrs[name] = attributes[name]; - } - } - } - else { - instance[key] = attributes; - return attributes; - } - } - return attrs; +function attr (ctor, propName, newAttrs) { + var attrs, setter, key; + if (typeof ctor === 'function') { + // attributes shared between instances + attrs = ctor.__attrs__ || createAttrs(ctor); + setter = attrs.constructor.prototype; } else { // attributes in instance - instance = constructor; - if (typeof attributes !== 'undefined') { - // set - if (typeof attributes === 'object') { - if (instance.hasOwnProperty(key)) { - attrs = instance[key]; - } - if (!attrs) { - instance[key] = attrs = {}; - } - for (name in attributes) { - if (name[0] !== '_') { - attrs[name] = attributes[name]; - } - } - return JS.addon({}, attrs, instance.constructor.prototype[key]); - } - else { - instance[key] = attributes; - return attributes; + var instance = ctor; + attrs = instance.__attrs__; + if (!attrs) { + ctor = instance.constructor; + var clsAttrs = ctor.__attrs__ || createAttrs(ctor); + attrs = createAttrsSingle(instance, ctor, clsAttrs); + } + setter = attrs; + } + + if (typeof newAttrs === 'undefined') { + // get + var prefix = propName + DELIMETER; + var ret = {}; + for (key in attrs) { + if (key.startsWith(prefix)) { + ret[key.slice(prefix.length)] = attrs[key]; } } - else { - // get - attrs = instance[key]; - if (typeof attrs === 'object') { - return JS.addon({}, attrs, instance.constructor.prototype[key]); - } - else { - return attrs; + return ret; + } + else { + // set + if (typeof newAttrs === 'object') { + for (key in newAttrs) { + if (key.charCodeAt(0) !== 95 /* _ */) { + setter[propName + DELIMETER + key] = newAttrs[key]; + } } } + else if (CC_DEV) { + cc.error('attribute must be type object'); + } } } +function getClassAttrs (ctor) { + return ctor.__attrs__ || createAttrs(ctor); +} + +function setClassAttr (ctor, propName, key, value) { + var attrs = ctor.__attrs__ || createAttrs(ctor); + attrs.constructor.prototype[propName + DELIMETER + key] = value; +} + /** * @module cc */ @@ -177,7 +206,7 @@ function getTypeChecker (type, attrName) { if (CC_DEV) { return function (constructor, mainPropName) { var propInfo = '"' + JS.getClassName(constructor) + '.' + mainPropName + '"'; - var mainPropAttrs = cc.Class.attr(constructor, mainPropName) || {}; + var mainPropAttrs = attr(constructor, mainPropName); if (!mainPropAttrs.saveUrlAsAsset) { var mainPropAttrsType = mainPropAttrs.type; if (mainPropAttrsType === cc.Integer || mainPropAttrsType === cc.Float) { @@ -256,21 +285,21 @@ function ObjectType (typeCtor) { _onAfterProp: CC_DEV && function (classCtor, mainPropName) { getTypeChecker('Object', 'type')(classCtor, mainPropName); // check ValueType - var mainPropAttrs = cc.Class.attr(classCtor, mainPropName) || {}; - var def = mainPropAttrs.default; - if (typeof def === 'function') { + var defaultDef = getClassAttrs(classCtor)[mainPropName + DELIMETER + 'default']; + var defaultVal = defaultDef; + if (typeof defaultDef === 'function') { try { - def = def(); + defaultVal = defaultDef(); } catch (e) { return; } } - if (!Array.isArray(def) && cc.isChildClassOf(typeCtor, cc.ValueType)) { + if (!Array.isArray(defaultVal) && cc.isChildClassOf(typeCtor, cc.ValueType)) { var typename = JS.getClassName(typeCtor); var info = cc.js.formatStr('No need to specify the "type" of "%s.%s" because %s is a child class of ValueType.', JS.getClassName(classCtor), mainPropName, typename); - if (mainPropAttrs.default) { + if (defaultDef) { cc.log(info); } else { @@ -298,11 +327,11 @@ function RawType (typename) { cc.error('RawType is only available for Assets'); return false; } + var attrs = getClassAttrs(constructor); var found = false; for (var p = 0; p < constructor.__props__.length; p++) { var propName = constructor.__props__[p]; - var attrs = cc.Class.attr(constructor, propName); - var rawType = attrs.rawType; + var rawType = attrs[propName + DELIMETER + 'rawType']; if (rawType) { var containsUppercase = (rawType.toLowerCase() !== rawType); if (containsUppercase) { @@ -328,6 +357,9 @@ function Range (min, max) { module.exports = { attr: attr, + getClassAttrs: getClassAttrs, + setClassAttr: setClassAttr, + DELIMETER: DELIMETER, getTypeChecker: getTypeChecker, NonSerialized: NonSerialized, EditorOnly: EditorOnly, diff --git a/cocos2d/core/platform/deserialize.js b/cocos2d/core/platform/deserialize.js index 73e85a625a..76b5d66d11 100644 --- a/cocos2d/core/platform/deserialize.js +++ b/cocos2d/core/platform/deserialize.js @@ -25,6 +25,7 @@ var JS = require('./js'); var CCObject = require('./CCObject'); +var Attr = require('./attribute'); var EDITOR = CC_DEV; var ENABLE_TARGET = EDITOR; @@ -344,20 +345,21 @@ var _Deserializer = (function () { } function _deserializeFireClass(self, obj, serialized, klass, target) { + var DELIMETER = Attr.DELIMETER; var props = klass.__props__; + var attrs = Attr.getClassAttrs(klass); for (var p = 0; p < props.length; p++) { var propName = props[p]; - var attrs = cc.Class.attr(klass, propName); // assume all prop in __props__ must have attr - var rawType = attrs.rawType; + var rawType = attrs[propName + DELIMETER + 'rawType']; if (!rawType) { - if (!EDITOR && attrs.editorOnly) { + if (!EDITOR && attrs[propName + DELIMETER + 'editorOnly']) { var mayUsedInPersistRoot = (obj instanceof cc.Node && propName === '_id'); if ( !mayUsedInPersistRoot ) { continue; // skip editor only if not editor } } - if (attrs.serializable === false) { + if (attrs[propName + DELIMETER + 'serializable'] === false) { continue; // skip nonSerialized } var prop = serialized[propName]; diff --git a/cocos2d/core/platform/instantiate.js b/cocos2d/core/platform/instantiate.js index 8a42d4c68e..34218a6012 100644 --- a/cocos2d/core/platform/instantiate.js +++ b/cocos2d/core/platform/instantiate.js @@ -25,6 +25,7 @@ var CCObject = require('./CCObject'); var PersistentMask = CCObject.Flags.PersistentMask; +var Attr = require('./attribute'); var _isDomNode = require('./utils').isDomNode; /** @@ -89,7 +90,7 @@ var objsToClearTmpVar = []; // 用于重设临时变量 ///** // * Do instantiate object, the object to instantiate must be non-nil. // * 这是一个通用的 instantiate 方法,可能效率比较低。 -// * 之后可以给各种类型重载快速实例化的特殊实现,但应该在单元测试中将结果和这个方法的结果进行对比。 +// * 之后可以给各种类型重写快速实例化的特殊实现,但应该在单元测试中将结果和这个方法的结果进行对比。 // * 值得注意的是,这个方法不可重入,不支持 mixin。 // * // * @param {Object} obj - 该方法仅供内部使用,用户需负责保证参数合法。什么参数是合法的请参考 cc.instantiate 的实现。 @@ -128,11 +129,12 @@ var enumerateObject = function (obj, parent) { obj._iN$t = clone; objsToClearTmpVar.push(obj); if (cc.Class._isCCClass(klass)) { + var DELIMETER = Attr.DELIMETER; var props = klass.__props__; + var attrs = Attr.getClassAttrs(klass); for (var p = 0; p < props.length; p++) { key = props[p]; - var attrs = cc.Class.attr(klass, key); - if (attrs.serializable !== false) { + if (attrs[key + DELIMETER + 'serializable'] !== false) { value = obj[key]; type = typeof value; if (type === 'object') { diff --git a/cocos2d/core/platform/js.js b/cocos2d/core/platform/js.js index 255cea65a8..179c670c32 100644 --- a/cocos2d/core/platform/js.js +++ b/cocos2d/core/platform/js.js @@ -76,11 +76,13 @@ var js = { }, /** - * copy all properties not defined in obj from arguments[1...n] + * This method is deprecated, use cc.js.mixin please.
+ * Copy all properties not defined in obj from arguments[1...n] * @method addon * @param {Object} obj object to extend its properties * @param {Object} ...sourceObj source object to copy properties from * @return {Object} the result obj + * @deprecated */ addon: function (obj) { 'use strict'; @@ -147,6 +149,9 @@ var js = { cc.error('The class to extend must be non-nil'); return; } + if (Object.keys(cls.prototype).length > 0) { + cc.error('Class should be extended before assigning any prototype members.'); + } } for (var p in base) if (base.hasOwnProperty(p)) cls[p] = base[p]; cls.prototype = Object.create(base.prototype); diff --git a/cocos2d/core/renderer/DirtyRegion.js b/cocos2d/core/renderer/DirtyRegion.js index 8a4b302c19..b395d716d5 100644 --- a/cocos2d/core/renderer/DirtyRegion.js +++ b/cocos2d/core/renderer/DirtyRegion.js @@ -131,7 +131,7 @@ regionProto.intersects = function (target) { //update region by a rotated bounds regionProto.updateRegion = function (bounds, matrix) { - if (bounds.width == 0 || bounds.height == 0) { + if (bounds.width === 0 || bounds.height === 0) { this.setEmpty(); return; } @@ -147,7 +147,7 @@ regionProto.updateRegion = function (bounds, matrix) { var xMax = x + bounds.width; var yMax = y + bounds.height; var minX, minY, maxX, maxY; - if (a == 1.0 && b == 0.0 && c == 0.0 && d == 1.0) { + if (a === 1 && b === 0 && c === 0 && d === 1) { minX = x + tx - 1; minY = y + ty - 1; maxX = xMax + tx + 1; @@ -323,7 +323,7 @@ dirtyRegionProto.mergeDirtyList = function(dirtyList) { if (hasClipRect && (totalArea / this.clipArea) > 0.95) { this.clipRectChanged = true; } - if (mergeA != mergeB) { + if (mergeA !== mergeB) { var region = dirtyList[mergeB]; dirtyList[mergeA].union(region); regionRelease(region); diff --git a/cocos2d/core/renderer/RendererCanvas.js b/cocos2d/core/renderer/RendererCanvas.js index af9768a5ee..b79db36263 100644 --- a/cocos2d/core/renderer/RendererCanvas.js +++ b/cocos2d/core/renderer/RendererCanvas.js @@ -25,6 +25,9 @@ cc.rendererCanvas = { childrenOrderDirty: true, + assignedZ: 0, + assignedZStep: 1/10000, + _transformNodePool: [], //save nodes transform dirty _renderCmds: [], //save renderer commands @@ -151,9 +154,11 @@ cc.rendererCanvas = { for (i = 0, len = locCmds.length; i < len; i++) { var cmd = locCmds[i]; + if (!cmd._needDraw) continue; + var needRendering = false; var cmdRegion = cmd._currentRegion; - if(!cmdRegion || allNeedDraw) { + if (!cmdRegion || allNeedDraw) { needRendering = true; } else { for(var index = 0, count = dirtyList.length; index < count; ++index) { @@ -163,12 +168,12 @@ cc.rendererCanvas = { } } } - if(needRendering) { + if (needRendering) { cmd.rendering(wrapper, scaleX, scaleY); } } - if(!allNeedDraw) { + if (!allNeedDraw) { //draw debug info for dirty region if it is needed this._debugDrawDirtyRegion(wrapper); this._endDrawDirtyRegion(ctx); @@ -188,19 +193,17 @@ cc.rendererCanvas = { _renderingToCacheCanvas: function (ctx, instanceID, scaleX, scaleY) { if (!ctx) cc.log("The context of RenderTexture is invalid."); - scaleX = (typeof scaleX === 'undefined') ? 1 : scaleX; - scaleY = (typeof scaleY === 'undefined') ? 1 : scaleY; + scaleX = scaleX === undefined ? 1 : scaleX; + scaleY = scaleY === undefined ? 1 : scaleY; instanceID = instanceID || this._currentID; var locCmds = this._cacheToCanvasCmds[instanceID], i, len; ctx.computeRealOffsetY(); for (i = 0, len = locCmds.length; i < len; i++) { locCmds[i].rendering(ctx, scaleX, scaleY); } - locCmds.length = 0; - var locIDs = this._cacheInstanceIds; - delete this._cacheToCanvasCmds[instanceID]; - cc.js.array.remove(locIDs, instanceID); + this._removeCache(instanceID); + var locIDs = this._cacheInstanceIds; if (locIDs.length === 0) this._isCacheToCanvasOn = false; else @@ -220,6 +223,18 @@ cc.rendererCanvas = { this._isCacheToCanvasOn = false; }, + _removeCache: function (instanceID) { + instanceID = instanceID || this._currentID; + var cmds = this._cacheToCanvasCmds[instanceID]; + if (cmds) { + cmds.length = 0; + delete this._cacheToCanvasCmds[instanceID]; + } + + var locIDs = this._cacheInstanceIds; + cc.js.array.remove(locIDs, instanceID); + }, + resetFlag: function () { this.childrenOrderDirty = false; this._transformNodePool.length = 0; @@ -260,7 +275,7 @@ cc.rendererCanvas = { }, pushRenderCommand: function (cmd) { - if(!cmd._needDraw) + if(!cmd.rendering) return; if (this._isCacheToCanvasOn) { var currentId = this._currentID, locCmdBuffer = this._cacheToCanvasCmds; diff --git a/cocos2d/core/renderer/RendererWebGL.js b/cocos2d/core/renderer/RendererWebGL.js index f9818745d7..a380424668 100644 --- a/cocos2d/core/renderer/RendererWebGL.js +++ b/cocos2d/core/renderer/RendererWebGL.js @@ -1,15 +1,14 @@ /**************************************************************************** Copyright (c) 2013-2016 Chukong Technologies Inc. - http://www.cocos.com + http://www.cocos2d-x.org Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated engine source code (the "Software"), a limited, - worldwide, royalty-free, non-assignable, revocable and non-exclusive license - to use Cocos Creator solely to develop games on your target platforms. You shall - not use Cocos Creator software for developing other software or tools that's - used for developing games. You are not granted to publish, distribute, - sublicense, and/or sell copies of Cocos Creator. + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: The software or tools in this License Agreement are licensed, not sold. Chukong Aipu reserves all rights not expressly granted to you. @@ -23,8 +22,103 @@ THE SOFTWARE. ****************************************************************************/ +// Internal variables + +var BATCH_QUAD_COUNT = 2000; + + // Batching general informations +var _batchedInfo = { + // The batched texture, all batching element should have the same texture + texture: null, + // The batched blend source, all batching element should have the same blend source + blendSrc: null, + // The batched blend destination, all batching element should have the same blend destination + blendDst: null, + // The batched shader, all batching element should have the same shader + shader: null + }, + + _indexBuffer = null, + _vertexBuffer = null, + // Total vertex size + _maxVertexSize = 0, + // Current batching vertex size + _batchingSize = 0, + // Current batching index size + _indexSize = 0, + // Float size per vertex + _sizePerVertex = 6, + // buffer data and views + _vertexData = null, + _vertexDataSize = 0, + _vertexDataF32 = null, + _vertexDataUI32 = null, + _indexData = null, + _prevIndexSize = 0, + _pureQuad = true, + _IS_IOS = false; + + +// Inspired from @Heishe's gotta-batch-them-all branch +// https://github.com/Talisca/cocos2d-html5/commit/de731f16414eb9bcaa20480006897ca6576d362c +function updateBuffer (numQuads) { + var gl = cc._renderContext; + // Update index buffer size + if (_indexBuffer) { + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, _indexBuffer); + _indexData = new Uint16Array(numQuads * 6); + var currentQuad = 0; + for (var i = 0, len = numQuads * 6; i < len; i += 6) { + _indexData[i] = currentQuad + 0; + _indexData[i + 1] = currentQuad + 1; + _indexData[i + 2] = currentQuad + 2; + _indexData[i + 3] = currentQuad + 1; + _indexData[i + 4] = currentQuad + 2; + _indexData[i + 5] = currentQuad + 3; + currentQuad += 4; + } + gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, _indexData, gl.DYNAMIC_DRAW); + } + // Update vertex buffer size + if (_vertexBuffer) { + _vertexDataSize = numQuads * 4 * _sizePerVertex; + var byteLength = _vertexDataSize * 4; + _vertexData = new ArrayBuffer(byteLength); + _vertexDataF32 = new Float32Array(_vertexData); + _vertexDataUI32 = new Uint32Array(_vertexData); + // Init buffer data + gl.bindBuffer(gl.ARRAY_BUFFER, _vertexBuffer); + gl.bufferData(gl.ARRAY_BUFFER, _vertexDataF32, gl.DYNAMIC_DRAW); + } + _maxVertexSize = numQuads * 4; +} + +// Inspired from @Heishe's gotta-batch-them-all branch +// https://github.com/Talisca/cocos2d-html5/commit/de731f16414eb9bcaa20480006897ca6576d362c +function initQuadBuffer (numQuads) { + var gl = cc._renderContext; + if (_indexBuffer === null) { + // TODO do user need to release the memory ? + _vertexBuffer = gl.createBuffer(); + _indexBuffer = gl.createBuffer(); + } + updateBuffer(numQuads); +} + +var VertexType = cc.Enum({ + QUAD : 0, + TRIANGLE : 1 +}); + cc.rendererWebGL = { + mat4Identity: null, + childrenOrderDirty: true, + assignedZ: 0, + assignedZStep: 1/100, + + VertexType: VertexType, + _transformNodePool: [], //save nodes transform dirty _renderCmds: [], //save renderer commands @@ -34,30 +128,40 @@ cc.rendererWebGL = { _currentID: 0, _clearColor: cc.color(), //background color,default BLACK + init: function () { + var gl = cc._renderContext; + gl.disable(gl.CULL_FACE); + gl.disable(gl.DEPTH_TEST); + + this.mat4Identity = new cc.math.Matrix4(); + this.mat4Identity.identity(); + initQuadBuffer(BATCH_QUAD_COUNT); + if (cc.sys.os === cc.sys.OS_IOS) { + _IS_IOS = true; + } + }, + + getVertexSize: function () { + return _maxVertexSize; + }, + getRenderCmd: function (renderableObject) { //TODO Add renderCmd pool here return renderableObject._createRenderCmd(); }, - /** - * drawing all renderer command to context (default is cc._renderContext) - * @param {WebGLRenderingContext} [ctx=cc._renderContext] - */ - rendering: function (ctx) { - var locCmds = this._renderCmds, - i, - len; - var context = ctx || cc._renderContext; - for (i = 0, len = locCmds.length; i < len; i++) { - locCmds[i].rendering(context); - } - }, - _turnToCacheMode: function (renderTextureID) { this._isCacheToBufferOn = true; renderTextureID = renderTextureID || 0; - this._cacheToBufferCmds[renderTextureID] = []; - this._cacheInstanceIds.push(renderTextureID); + if (!this._cacheToBufferCmds[renderTextureID]) { + this._cacheToBufferCmds[renderTextureID] = []; + } + else { + this._cacheToBufferCmds[renderTextureID].length = 0; + } + if (this._cacheInstanceIds.indexOf(renderTextureID) === -1) { + this._cacheInstanceIds.push(renderTextureID); + } this._currentID = renderTextureID; }, @@ -65,21 +169,30 @@ cc.rendererWebGL = { this._isCacheToBufferOn = false; }, + _removeCache: function (instanceID) { + instanceID = instanceID || this._currentID; + var cmds = this._cacheToBufferCmds[instanceID]; + if (cmds) { + cmds.length = 0; + delete this._cacheToBufferCmds[instanceID]; + } + + var locIDs = this._cacheInstanceIds; + cc.arrayRemoveObject(locIDs, instanceID); + }, + /** * drawing all renderer command to cache canvas' context * @param {Number} [renderTextureId] */ _renderingToBuffer: function (renderTextureId) { renderTextureId = renderTextureId || this._currentID; - var locCmds = this._cacheToBufferCmds[renderTextureId], i, len; - var ctx = cc._renderContext, locIDs = this._cacheInstanceIds; - for (i = 0, len = locCmds.length; i < len; i++) { - locCmds[i].rendering(ctx); - } - locCmds.length = 0; - delete this._cacheToBufferCmds[renderTextureId]; - cc.js.array.remove(locIDs, renderTextureId); + var locCmds = this._cacheToBufferCmds[renderTextureId]; + var ctx = cc._renderContext; + this.rendering(ctx, locCmds); + this._removeCache(renderTextureId); + var locIDs = this._cacheInstanceIds; if (locIDs.length === 0) this._isCacheToBufferOn = false; else @@ -88,7 +201,9 @@ cc.rendererWebGL = { //reset renderer's flag resetFlag: function () { - this.childrenOrderDirty = false; + if (this.childrenOrderDirty) { + this.childrenOrderDirty = false; + } this._transformNodePool.length = 0; }, @@ -98,8 +213,10 @@ cc.rendererWebGL = { //sort the pool locPool.sort(this._sortNodeByLevelAsc); //transform node - for (var i = 0, len = locPool.length; i < len; i++) { - locPool[i].updateStatus(); + var i, len, cmd; + for (i = 0, len = locPool.length; i < len; i++) { + cmd = locPool[i]; + cmd.updateStatus(); } locPool.length = 0; }, @@ -118,6 +235,7 @@ cc.rendererWebGL = { }, clearRenderCommands: function () { + // Copy previous command list for late check in rendering this._renderCmds.length = 0; }, @@ -140,7 +258,7 @@ cc.rendererWebGL = { }, pushRenderCommand: function (cmd) { - if(!cmd._needDraw) + if(!cmd.rendering && !cmd.uploadData) return; if (this._isCacheToBufferOn) { var currentId = this._currentID, locCmdBuffer = this._cacheToBufferCmds; @@ -148,8 +266,186 @@ cc.rendererWebGL = { if (cmdList.indexOf(cmd) === -1) cmdList.push(cmd); } else { - if (this._renderCmds.indexOf(cmd) === -1) + if (this._renderCmds.indexOf(cmd) === -1) { this._renderCmds.push(cmd); + } } + }, + + _increaseBatchingSize: function (increment, vertexType) { + vertexType = vertexType || VertexType.QUAD; + var i, curr; + switch (vertexType) { + case VertexType.QUAD: + for (i = 0; i < increment; i += 4) { + curr = _batchingSize + i; + _indexData[_indexSize++] = curr + 0; + _indexData[_indexSize++] = curr + 1; + _indexData[_indexSize++] = curr + 2; + _indexData[_indexSize++] = curr + 1; + _indexData[_indexSize++] = curr + 2; + _indexData[_indexSize++] = curr + 3; + } + break; + case VertexType.TRIANGLE: + _pureQuad = false; + for (i = 0; i < increment; i += 3) { + curr = _batchingSize + i; + _indexData[_indexSize++] = curr + 0; + _indexData[_indexSize++] = curr + 1; + _indexData[_indexSize++] = curr + 2; + } + break; + default: + return; + } + _batchingSize += increment; + }, + + _uploadBufferData: function (cmd) { + if (_batchingSize >= _maxVertexSize) { + this._batchRendering(); + } + + // Check batching + var node = cmd._node; + var texture = cmd._texture || node._texture || node._spriteFrame._texture; + var blendSrc = cmd._node._blendFunc.src; + var blendDst = cmd._node._blendFunc.dst; + var shader = cmd._shaderProgram; + if (_batchedInfo.texture !== texture || + _batchedInfo.blendSrc !== blendSrc || + _batchedInfo.blendDst !== blendDst || + _batchedInfo.shader !== shader) { + // Draw batched elements + this._batchRendering(); + // Update _batchedInfo + _batchedInfo.texture = texture; + _batchedInfo.blendSrc = blendSrc; + _batchedInfo.blendDst = blendDst; + _batchedInfo.shader = shader; + } + + // Upload vertex data + var len = cmd.uploadData(_vertexDataF32, _vertexDataUI32, _batchingSize * _sizePerVertex); + if (len > 0) { + var i, curr, type = cmd.vertexType || VertexType.QUAD; + switch (type) { + case VertexType.QUAD: + for (i = 0; i < len; i += 4) { + curr = _batchingSize + i; + _indexData[_indexSize++] = curr + 0; + _indexData[_indexSize++] = curr + 1; + _indexData[_indexSize++] = curr + 2; + _indexData[_indexSize++] = curr + 1; + _indexData[_indexSize++] = curr + 2; + _indexData[_indexSize++] = curr + 3; + } + break; + case VertexType.TRIANGLE: + _pureQuad = false; + for (i = 0; i < len; i += 3) { + curr = _batchingSize + i; + _indexData[_indexSize++] = curr + 0; + _indexData[_indexSize++] = curr + 1; + _indexData[_indexSize++] = curr + 2; + } + break; + default: + return; + } + _batchingSize += len; + } + }, + + _batchRendering: function () { + if (_batchingSize === 0 || !_batchedInfo.texture) { + return; + } + + var gl = cc._renderContext; + var texture = _batchedInfo.texture; + var shader = _batchedInfo.shader; + var uploadAll = _batchingSize > _maxVertexSize * 0.5; + + if (shader) { + shader.use(); + shader._updateProjectionUniform(); + } + + cc.gl.blendFunc(_batchedInfo.blendSrc, _batchedInfo.blendDst); + cc.gl.bindTexture2DN(0, texture); // = cc.gl.bindTexture2D(texture); + + var _bufferchanged = !gl.bindBuffer(gl.ARRAY_BUFFER, _vertexBuffer); + // upload the vertex data to the gl buffer + if (uploadAll) { + gl.bufferData(gl.ARRAY_BUFFER, _vertexDataF32, gl.DYNAMIC_DRAW); + } + else { + var view = _vertexDataF32.subarray(0, _batchingSize * _sizePerVertex); + gl.bufferData(gl.ARRAY_BUFFER, view, gl.DYNAMIC_DRAW); + } + + if (_bufferchanged) { + gl.enableVertexAttribArray(cc.macro.VERTEX_ATTRIB_POSITION); + gl.enableVertexAttribArray(cc.macro.VERTEX_ATTRIB_COLOR); + gl.enableVertexAttribArray(cc.macro.VERTEX_ATTRIB_TEX_COORDS); + gl.vertexAttribPointer(cc.macro.VERTEX_ATTRIB_POSITION, 3, gl.FLOAT, false, 24, 0); + gl.vertexAttribPointer(cc.macro.VERTEX_ATTRIB_COLOR, 4, gl.UNSIGNED_BYTE, true, 24, 12); + gl.vertexAttribPointer(cc.macro.VERTEX_ATTRIB_TEX_COORDS, 2, gl.FLOAT, false, 24, 16); + } + + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, _indexBuffer); + if (!_prevIndexSize || !_pureQuad || _indexSize > _prevIndexSize) { + if (uploadAll) { + gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, _indexData, gl.DYNAMIC_DRAW); + } + else { + gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, _indexData.subarray(0, _indexSize), gl.DYNAMIC_DRAW); + } + } + gl.drawElements(gl.TRIANGLES, _indexSize, gl.UNSIGNED_SHORT, 0); + + cc.g_NumberOfDraws++; + + if (_pureQuad) { + _prevIndexSize = _indexSize; + } + else { + _prevIndexSize = 0; + _pureQuad = true; + } + _batchingSize = 0; + _indexSize = 0; + }, + + /** + * drawing all renderer command to context (default is cc._renderContext) + * @param {WebGLRenderingContext} [ctx=cc._renderContext] + */ + rendering: function (ctx, cmds) { + var locCmds = cmds || this._renderCmds, + i, len, cmd, + context = ctx || cc._renderContext; + + // Reset buffer for rendering + context.bindBuffer(context.ARRAY_BUFFER, null); + + for (i = 0, len = locCmds.length; i < len; ++i) { + cmd = locCmds[i]; + if (!cmd._needDraw) continue; + + if (cmd.uploadData) { + this._uploadBufferData(cmd); + } + else { + if (_batchingSize > 0) { + this._batchRendering(); + } + cmd.rendering(context); + } + } + this._batchRendering(); + _batchedInfo.texture = null; } -}; +}; \ No newline at end of file diff --git a/cocos2d/core/sprites/CCSGSprite.js b/cocos2d/core/sprites/CCSGSprite.js index cc337f8c5e..f7d6488693 100644 --- a/cocos2d/core/sprites/CCSGSprite.js +++ b/cocos2d/core/sprites/CCSGSprite.js @@ -86,8 +86,8 @@ var EventTarget = require("../cocos2d/core/event/event-target"); * @property {cc.V3F_C4B_T2F_Quad} quad - <@readonly> The quad (tex coords, vertex coords and color) information. */ _ccsg.Sprite = _ccsg.Node.extend({ - dirty:false, - atlasIndex:0, + dirty:false, + atlasIndex:0, textureAtlas:null, _batchNode:null, @@ -227,12 +227,12 @@ _ccsg.Sprite = _ccsg.Node.extend({ return cc.p(this._offsetPosition); }, - _getOffsetX: function () { - return this._offsetPosition.x; - }, - _getOffsetY: function () { - return this._offsetPosition.y; - }, + _getOffsetX: function () { + return this._offsetPosition.x; + }, + _getOffsetY: function () { + return this._offsetPosition.y; + }, /** * Returns the blend function @@ -318,25 +318,7 @@ _ccsg.Sprite = _ccsg.Node.extend({ if (this._reorderChildDirty) { var _children = this._children; - // insertion sort - var len = _children.length, i, j, tmp; - for(i=1; i= 0){ - if(tmp._localZOrder < _children[j]._localZOrder){ - _children[j+1] = _children[j]; - }else if(tmp._localZOrder === _children[j]._localZOrder && tmp.arrivalOrder < _children[j].arrivalOrder){ - _children[j+1] = _children[j]; - }else{ - break; - } - j--; - } - _children[j+1] = tmp; - } + _ccsg.Node.prototype.sortAllChildren.call(this); if (this._batchNode) { this._arrayMakeObjectsPerformSelector(_children, _ccsg.Node._stateCallbackType.sortAllChildren); @@ -554,7 +536,7 @@ _ccsg.Sprite = _ccsg.Node.extend({ return this._texture; }, - _softInit: function (fileName, rect, rotated) { + _softInit: function (fileName, rect, rotated) { if (fileName === undefined) _ccsg.Sprite.prototype.init.call(this); else if (cc.js.isString(fileName)) { @@ -585,14 +567,14 @@ _ccsg.Sprite = _ccsg.Node.extend({ this.initWithTexture(texture2d); } } - }, + }, /** * Returns the quad (tex coords, vertex coords and color) information. * @return {cc.V3F_C4B_T2F_Quad|null} Returns a cc.V3F_C4B_T2F_Quad object when render mode is WebGL, returns null when render mode is Canvas. */ getQuad:function () { - return this._renderCmd.getQuad(); + return null; }, /** @@ -642,7 +624,6 @@ _ccsg.Sprite = _ccsg.Node.extend({ _t._offsetPosition.y = 0; _t._hasChildren = false; - this._renderCmd._init(); // updated in "useSelfRender" // Atlas: TexCoords _t.setTextureRect(cc.rect(0, 0, 0, 0), false, cc.size(0, 0)); @@ -717,8 +698,6 @@ _ccsg.Sprite = _ccsg.Node.extend({ _t._offsetPosition.y = 0; _t._hasChildren = false; - this._renderCmd._init(); - var locTextureLoaded = texture.isLoaded(); _t._textureLoaded = locTextureLoaded; @@ -758,14 +737,15 @@ _ccsg.Sprite = _ccsg.Node.extend({ * @param {cc.Rect} rect a rect of texture * @param {Boolean} [rotated] Whether or not the texture is rotated * @param {cc.Size} [untrimmedSize] The original pixels size of the texture + * @param {Boolean} [needConvert] contentScaleFactor switch */ - setTextureRect: function (rect, rotated, untrimmedSize) { + setTextureRect: function (rect, rotated, untrimmedSize, needConvert) { var _t = this; _t._rectRotated = rotated || false; _t.setContentSize(untrimmedSize || rect); _t.setVertexRect(rect); - _t._renderCmd._setTextureCoords(rect); + _t._renderCmd._setTextureCoords(rect, needConvert); var relativeOffsetX = _t._unflippedOffsetPositionFromCenter.x, relativeOffsetY = _t._unflippedOffsetPositionFromCenter.y; if (_t._flippedX) @@ -775,26 +755,9 @@ _ccsg.Sprite = _ccsg.Node.extend({ var locRect = _t._rect; _t._offsetPosition.x = relativeOffsetX + (_t._contentSize.width - locRect.width) / 2; _t._offsetPosition.y = relativeOffsetY + (_t._contentSize.height - locRect.height) / 2; - - // rendering using batch node - if (_t._batchNode) { - // update dirty, don't update _recursiveDirty - _t.dirty = true; - } else { - // self rendering - // Atlas: Vertex - this._renderCmd._resetForBatchNode(); - } }, // BatchNode methods - /** - * Updates the quad according the the rotation, position, scale values. - * @function - */ - updateTransform: function(){ - this._renderCmd.updateTransform(); - }, /** * Add child to sprite (override ccsg.Node) @@ -842,20 +805,24 @@ _ccsg.Sprite = _ccsg.Node.extend({ var pNewTexture = newFrame.getTexture(); var locTextureLoaded = newFrame.textureLoaded(); if (!locTextureLoaded) { - if (pNewTexture !== _t._texture) - _t.setTexture(pNewTexture); _t._textureLoaded = false; newFrame.once("load", function (event) { var sender = event.currentTarget; _t._textureLoaded = true; + var locNewTexture = sender.getTexture(); + if (locNewTexture !== _t._texture) + _t._setTexture(locNewTexture); _t.setTextureRect(sender.getRect(), sender.isRotated(), sender.getOriginalSize()); _t.emit("load"); - _t.setColor(_t.color); + _t.setColor(_t._realColor); }, _t); - }else{ + } else { + _t._textureLoaded = true; // update texture before updating texture rect - if (pNewTexture !== _t._texture) - _t.setTexture(pNewTexture); + if (pNewTexture !== _t._texture) { + _t._setTexture(pNewTexture); + _t.setColor(_t._realColor); + } _t.setTextureRect(newFrame.getRect(), newFrame.isRotated(), newFrame.getOriginalSize()); } this._renderCmd._updateForSetSpriteFrame(pNewTexture); @@ -922,8 +889,6 @@ _ccsg.Sprite = _ccsg.Node.extend({ _t.textureAtlas = null; _t._recursiveDirty = false; _t.dirty = false; - - this._renderCmd._resetForBatchNode(); } else { // using batch _t._transformToBatch = cc.affineTransformIdentity(); diff --git a/cocos2d/core/sprites/CCSGSpriteCanvasRenderCmd.js b/cocos2d/core/sprites/CCSGSpriteCanvasRenderCmd.js index 78e918b705..18569ec20d 100644 --- a/cocos2d/core/sprites/CCSGSpriteCanvasRenderCmd.js +++ b/cocos2d/core/sprites/CCSGSpriteCanvasRenderCmd.js @@ -43,12 +43,8 @@ _ccsg.Sprite.CanvasRenderCmd = function (renderable) { var proto = _ccsg.Sprite.CanvasRenderCmd.prototype = Object.create(_ccsg.Node.CanvasRenderCmd.prototype); proto.constructor = _ccsg.Sprite.CanvasRenderCmd; -proto._init = function () {}; - proto.setDirtyRecursively = function (value) {}; -proto._resetForBatchNode = function () {}; - proto._setTexture = function (texture) { var node = this._node; if (node._texture !== texture) { @@ -189,11 +185,6 @@ proto._updateColor = function(){ } }; -proto.getQuad = function () { - //throw an error. it doesn't support this function. - return null; -}; - proto._updateForSetSpriteFrame = function (pNewTexture, textureLoaded){ this._colorized = false; this._textureCoord.renderX = this._textureCoord.x; @@ -206,39 +197,6 @@ proto._updateForSetSpriteFrame = function (pNewTexture, textureLoaded){ } }; -proto.updateTransform = function () { //TODO need delete, because Canvas needn't - var _t = this, node = this._node; - - // re-calculate matrix only if it is dirty - if (node.dirty) { - // If it is not visible, or one of its ancestors is not visible, then do nothing: - var locParent = node._parent; - if (!node._visible || ( locParent && locParent !== node._batchNode && locParent._shouldBeHidden)) { - node._shouldBeHidden = true; - } else { - node._shouldBeHidden = false; - - if (!locParent || locParent === node._batchNode) { - node._transformToBatch = _t.getNodeToParentTransform(); - } else { - //cc.assert(_t._parent instanceof _ccsg.Sprite, "Logic error in CCSprite. Parent must be a CCSprite"); - node._transformToBatch = cc.affineTransformConcat(_t.getNodeToParentTransform(), locParent._transformToBatch); - } - } - node._recursiveDirty = false; - node.dirty = false; - } - - // recursively iterate over children - if (node._hasChildren) - node._arrayMakeObjectsPerformSelector(node._children, _ccsg.Node._stateCallbackType.updateTransform); -}; - -proto._updateDisplayColor = function (parentColor) { - _ccsg.Node.CanvasRenderCmd.prototype._updateDisplayColor.call(this, parentColor); - //this._updateColor(); -}; - proto._spriteFrameLoadedCallback = function (event) { var node = this._node, spriteFrame = event.currentTarget; node.setTextureRect(spriteFrame.getRect(), spriteFrame.isRotated(), spriteFrame.getOriginalSize()); diff --git a/cocos2d/core/sprites/CCSGSpriteWebGLRenderCmd.js b/cocos2d/core/sprites/CCSGSpriteWebGLRenderCmd.js index 890135d2d3..41a5036a26 100644 --- a/cocos2d/core/sprites/CCSGSpriteWebGLRenderCmd.js +++ b/cocos2d/core/sprites/CCSGSpriteWebGLRenderCmd.js @@ -23,18 +23,23 @@ ****************************************************************************/ var macro = cc.macro; -var ccgl = cc.gl; //Sprite's WebGL render command _ccsg.Sprite.WebGLRenderCmd = function (renderable) { _ccsg.Node.WebGLRenderCmd.call(this, renderable); this._needDraw = true; - this._quad = new cc.V3F_C4B_T2F_Quad(); - this._quadWebBuffer = cc._renderContext.createBuffer(); - this._quadDirty = true; + this._vertices = [ + {x: 0, y: 0, u: 0, v: 0}, // tl + {x: 0, y: 0, u: 0, v: 0}, // bl + {x: 0, y: 0, u: 0, v: 0}, // tr + {x: 0, y: 0, u: 0, v: 0} // br + ]; + this._color = new Uint32Array(1); this._dirty = false; this._recursiveDirty = false; + + this._shaderProgram = cc.shaderCache.programForKey(macro.SHADER_SPRITE_POSITION_TEXTURECOLORALPHATEST); }; var proto = _ccsg.Sprite.WebGLRenderCmd.prototype = Object.create(_ccsg.Node.WebGLRenderCmd.prototype); @@ -86,33 +91,6 @@ proto.isFrameDisplayed = function (frame) { && cc.pointEqualToPoint(frame.getOffset(), node._unflippedOffsetPositionFromCenter)); }; -proto._init = function () { - var tempColor = {r: 255, g: 255, b: 255, a: 255}, quad = this._quad; - quad.bl.colors = tempColor; - quad.br.colors = tempColor; - quad.tl.colors = tempColor; - quad.tr.colors = tempColor; - this._quadDirty = true; -}; - -proto._resetForBatchNode = function () { - var node = this._node; - var x1 = node._offsetPosition.x; - var y1 = node._offsetPosition.y; - var x2 = x1 + node._rect.width; - var y2 = y1 + node._rect.height; - var locQuad = this._quad; - locQuad.bl.vertices = {x: x1, y: y1, z: 0}; - locQuad.br.vertices = {x: x2, y: y1, z: 0}; - locQuad.tl.vertices = {x: x1, y: y2, z: 0}; - locQuad.tr.vertices = {x: x2, y: y2, z: 0}; - this._quadDirty = true; -}; - -proto.getQuad = function () { - return this._quad; -}; - proto._updateForSetSpriteFrame = function () {}; proto._spriteFrameLoadedCallback = function (event) { @@ -141,21 +119,24 @@ proto._textureLoadedCallback = function (event) { // by default use "Self Render". // if the sprite is added to a batchnode, then it will automatically switch to "batchnode Render" node.setBatchNode(node._batchNode); - this._quadDirty = true; node.emit("load"); + + // Force refresh the render command list + cc.renderer.childrenOrderDirty = true; }; proto._setTextureCoords = function (rect) { var node = this._node; var tex = node._batchNode ? node.textureAtlas.texture : node._texture; + var uvs = this._vertices; if (!tex) return; var atlasWidth = tex.pixelWidth; var atlasHeight = tex.pixelHeight; - var left, right, top, bottom, tempSwap, locQuad = this._quad; + var left, right, top, bottom, tempSwap; if (node._rectRotated) { if (macro.FIX_ARTIFACTS_BY_STRECHING_TEXEL) { left = (2 * rect.x + 1) / (2 * atlasWidth); @@ -181,14 +162,14 @@ proto._setTextureCoords = function (rect) { right = tempSwap; } - locQuad.bl.texCoords.u = left; - locQuad.bl.texCoords.v = top; - locQuad.br.texCoords.u = left; - locQuad.br.texCoords.v = bottom; - locQuad.tl.texCoords.u = right; - locQuad.tl.texCoords.v = top; - locQuad.tr.texCoords.u = right; - locQuad.tr.texCoords.v = bottom; + uvs[0].u = right; // tl + uvs[0].v = top; // tl + uvs[1].u = left; // bl + uvs[1].v = top; // bl + uvs[2].u = right; // tr + uvs[2].v = bottom; // tr + uvs[3].u = left; // br + uvs[3].v = bottom; // br } else { if (macro.FIX_ARTIFACTS_BY_STRECHING_TEXEL) { left = (2 * rect.x + 1) / (2 * atlasWidth); @@ -214,64 +195,19 @@ proto._setTextureCoords = function (rect) { bottom = tempSwap; } - locQuad.bl.texCoords.u = left; - locQuad.bl.texCoords.v = bottom; - locQuad.br.texCoords.u = right; - locQuad.br.texCoords.v = bottom; - locQuad.tl.texCoords.u = left; - locQuad.tl.texCoords.v = top; - locQuad.tr.texCoords.u = right; - locQuad.tr.texCoords.v = top; + uvs[0].u = left; // tl + uvs[0].v = top; // tl + uvs[1].u = left; // bl + uvs[1].v = bottom; // bl + uvs[2].u = right; // tr + uvs[2].v = top; // tr + uvs[3].u = right; // br + uvs[3].v = bottom; // br } - this._quadDirty = true; -}; - -proto.transform = function(parentCmd, recursive){ - _ccsg.Node.WebGLRenderCmd.prototype.transform.call(this, parentCmd, recursive); - this._dirty = true; //use for batching }; proto._setColorDirty = function () {}; -proto._updateColor = function () { - var node = this._node, - locDisplayedColor = this._displayedColor, - r = locDisplayedColor.r, - g = locDisplayedColor.g, - b = locDisplayedColor.b, - a = locDisplayedColor.a = this._displayedOpacity; - // special opacity for premultiplied textures - if (node._opacityModifyRGB) { - locDisplayedColor.r *= a / 255.0; - locDisplayedColor.g *= a / 255.0; - locDisplayedColor.b *= a / 255.0; - } - var locQuad = this._quad; - locQuad.bl.colors = locDisplayedColor; - locQuad.br.colors = locDisplayedColor; - locQuad.tl.colors = locDisplayedColor; - locQuad.tr.colors = locDisplayedColor; - - // Roll back color - locDisplayedColor.r = r; - locDisplayedColor.g = g; - locDisplayedColor.b = b; - - // renders using Sprite Manager - if (node._batchNode) { - if (node.atlasIndex !== _ccsg.Sprite.INDEX_NOT_INITIALIZED) { - node.textureAtlas.updateQuad(locQuad, node.atlasIndex) - } else { - // no need to set it recursively - // update dirty_, don't update recursiveDirty_ - this._dirty = true; - } - } - // self render - // do nothing - this._quadDirty = true; -}; - proto._updateBlendFunc = function () { if (this._batchNode) { cc.log(cc._LogInfos.Sprite__updateBlendFunc); @@ -304,103 +240,14 @@ proto._setTexture = function (texture) { node._textureLoaded = texture ? texture._textureLoaded : false; node._texture = texture; this._updateBlendFunc(); + + if (node._textureLoaded) { + // Force refresh the render command list + cc.renderer.childrenOrderDirty = true; + } } } - if (texture) - this._shaderProgram = cc.shaderCache.programForKey(macro.SHADER_POSITION_TEXTURECOLOR); - else - this._shaderProgram = cc.shaderCache.programForKey(macro.SHADER_POSITION_COLOR); - -}; - -proto.updateTransform = function () { //called only at batching. - var _t = this, node = this._node; - - // recalculate matrix only if it is dirty - if (this._dirty) { - var locQuad = _t._quad, locParent = node._parent; - // If it is not visible, or one of its ancestors is not visible, then do nothing: - if (!node._visible || ( locParent && locParent !== node._batchNode && locParent._shouldBeHidden)) { - locQuad.br.vertices = locQuad.tl.vertices = locQuad.tr.vertices = locQuad.bl.vertices = {x: 0, y: 0, z: 0}; - node._shouldBeHidden = true; - } else { - node._shouldBeHidden = false; - if(this._dirtyFlag !== 0){ //because changing color and opacity uses dirty flag at visit, but visit doesn't call at batching. - this.updateStatus(); - this._dirtyFlag = 0; - } - - if (!locParent || locParent === node._batchNode) { - node._transformToBatch = _t.getNodeToParentTransform(); - } else { - node._transformToBatch = cc.affineTransformConcat(_t.getNodeToParentTransform(), locParent._transformToBatch); - } - - // - // calculate the Quad based on the Affine Matrix - // - var locTransformToBatch = node._transformToBatch; - var rect = node._rect; - var x1 = node._offsetPosition.x; - var y1 = node._offsetPosition.y; - - var x2 = x1 + rect.width; - var y2 = y1 + rect.height; - var x = locTransformToBatch.tx; - var y = locTransformToBatch.ty; - - var cr = locTransformToBatch.a; - var sr = locTransformToBatch.b; - var cr2 = locTransformToBatch.d; - var sr2 = -locTransformToBatch.c; - var ax = x1 * cr - y1 * sr2 + x; - var ay = x1 * sr + y1 * cr2 + y; - - var bx = x2 * cr - y1 * sr2 + x; - var by = x2 * sr + y1 * cr2 + y; - - var cx = x2 * cr - y2 * sr2 + x; - var cy = x2 * sr + y2 * cr2 + y; - - var dx = x1 * cr - y2 * sr2 + x; - var dy = x1 * sr + y2 * cr2 + y; - - var locVertexZ = node._vertexZ; - if (!macro.SPRITEBATCHNODE_RENDER_SUBPIXEL) { - ax = 0 | ax; - ay = 0 | ay; - bx = 0 | bx; - by = 0 | by; - cx = 0 | cx; - cy = 0 | cy; - dx = 0 | dx; - dy = 0 | dy; - } - locQuad.bl.vertices = {x: ax, y: ay, z: locVertexZ}; - locQuad.br.vertices = {x: bx, y: by, z: locVertexZ}; - locQuad.tl.vertices = {x: dx, y: dy, z: locVertexZ}; - locQuad.tr.vertices = {x: cx, y: cy, z: locVertexZ}; - } - node.textureAtlas.updateQuad(locQuad, node.atlasIndex); - node._recursiveDirty = false; - this._dirty = false; - } - - // recursively iterate over children - if (node._hasChildren) - node._arrayMakeObjectsPerformSelector(node._children, _ccsg.Node._stateCallbackType.updateTransform); - - /*if (macro.SPRITE_DEBUG_DRAW) { //TODO - // draw bounding box - var vertices = [ - cc.p(_t._quad.bl.vertices.x, _t._quad.bl.vertices.y), - cc.p(_t._quad.br.vertices.x, _t._quad.br.vertices.y), - cc.p(_t._quad.tr.vertices.x, _t._quad.tr.vertices.y), - cc.p(_t._quad.tl.vertices.x, _t._quad.tl.vertices.y) - ]; - cc._drawingUtil.drawPoly(vertices, 4, true); - }*/ }; proto._checkTextureBoundary = function (texture, rect, rotated) { @@ -422,79 +269,61 @@ proto._checkTextureBoundary = function (texture, rect, rotated) { } }; -proto.rendering = function (ctx) { +proto.transform = function (parentCmd, recursive) { + this.originTransform(parentCmd, recursive); + + var node = this._node, + lx = node._offsetPosition.x, rx = lx + node._rect.width, + by = node._offsetPosition.y, ty = by + node._rect.height, + wt = this._worldTransform; + + var vertices = this._vertices; + vertices[0].x = lx * wt.a + ty * wt.c + wt.tx; // tl + vertices[0].y = lx * wt.b + ty * wt.d + wt.ty; + vertices[1].x = lx * wt.a + by * wt.c + wt.tx; // bl + vertices[1].y = lx * wt.b + by * wt.d + wt.ty; + vertices[2].x = rx * wt.a + ty * wt.c + wt.tx; // tr + vertices[2].y = rx * wt.b + ty * wt.d + wt.ty; + vertices[3].x = rx * wt.a + by * wt.c + wt.tx; // br + vertices[3].y = rx * wt.b + by * wt.d + wt.ty; +}; + +proto.needDraw = function () { var node = this._node, locTexture = node._texture; - if ((locTexture &&!locTexture._textureLoaded) || this._displayedOpacity === 0) - return; + return (this._needDraw && locTexture); +}; - var gl = ctx || cc._renderContext; - //cc.assert(!_t._batchNode, "If _ccsg.Sprite is being rendered by cc.SpriteBatchNode, _ccsg.Sprite#draw SHOULD NOT be called"); +proto.uploadData = function (f32buffer, ui32buffer, vertexDataOffset) { + var node = this._node, locTexture = node._texture; + if (!(locTexture && locTexture._textureLoaded && node._rect.width && node._rect.height) || !this._displayedOpacity) + return 0; - if (locTexture) { - if (locTexture._textureLoaded) { - this._shaderProgram.use(); - this._shaderProgram._setUniformForMVPMatrixWithMat4(this._stackMatrix); - - ccgl.blendFunc(node._blendFunc.src, node._blendFunc.dst); - //optimize performance for javascript - ccgl.bindTexture2DN(0, locTexture); // = cc.gl.bindTexture2D(locTexture); - ccgl.enableVertexAttribs(macro.VERTEX_ATTRIB_FLAG_POS_COLOR_TEX); - - gl.bindBuffer(gl.ARRAY_BUFFER, this._quadWebBuffer); - if (this._quadDirty) { - gl.bufferData(gl.ARRAY_BUFFER, this._quad.arrayBuffer, gl.DYNAMIC_DRAW); - this._quadDirty = false; - } - gl.vertexAttribPointer(0, 3, gl.FLOAT, false, 24, 0); //macro.VERTEX_ATTRIB_POSITION - gl.vertexAttribPointer(1, 4, gl.UNSIGNED_BYTE, true, 24, 12); //macro.VERTEX_ATTRIB_COLOR - gl.vertexAttribPointer(2, 2, gl.FLOAT, false, 24, 16); //macro.VERTEX_ATTRIB_TEX_COORDS - gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4); - } - } else { - this._shaderProgram.use(); - this._shaderProgram._setUniformForMVPMatrixWithMat4(this._stackMatrix); - - ccgl.blendFunc(node._blendFunc.src, node._blendFunc.dst); - ccgl.bindTexture2D(null); - - ccgl.enableVertexAttribs(macro.VERTEX_ATTRIB_FLAG_POSITION | macro.VERTEX_ATTRIB_FLAG_COLOR); - - gl.bindBuffer(gl.ARRAY_BUFFER, this._quadWebBuffer); - if (this._quadDirty) { - gl.bufferData(gl.ARRAY_BUFFER, this._quad.arrayBuffer, gl.STATIC_DRAW); - this._quadDirty = false; - } - gl.vertexAttribPointer(macro.VERTEX_ATTRIB_POSITION, 3, gl.FLOAT, false, 24, 0); - gl.vertexAttribPointer(macro.VERTEX_ATTRIB_COLOR, 4, gl.UNSIGNED_BYTE, true, 24, 12); - gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4); + // Fill in vertex data with quad information (4 vertices for sprite) + var opacity = this._displayedOpacity; + var r = this._displayedColor.r, + g = this._displayedColor.g, + b = this._displayedColor.b; + if (node._opacityModifyRGB) { + var a = opacity / 255; + r *= a; + g *= a; + b *= a; } - cc.g_NumberOfDraws++; + this._color[0] = ((opacity<<24) | (b<<16) | (g<<8) | r); + var z = node._vertexZ; - if (macro.SPRITE_DEBUG_DRAW === 0 && !node._showNode) - return; + var vertices = this._vertices; + var i, len = vertices.length, vertex, offset = vertexDataOffset; + for (i = 0; i < len; ++i) { + vertex = vertices[i]; + f32buffer[offset] = vertex.x; + f32buffer[offset + 1] = vertex.y; + f32buffer[offset + 2] = z; + ui32buffer[offset + 3] = this._color[0]; + f32buffer[offset + 4] = vertex.u; + f32buffer[offset + 5] = vertex.v; + offset += 6; + } - cc.math.glMatrixMode(cc.math.KM_GL_MODELVIEW); - //cc.math.glPushMatrixWitMat4(node._stackMatrix); - cc.current_stack.stack.push(cc.current_stack.top); - cc.current_stack.top = this._stackMatrix; - - if (macro.SPRITE_DEBUG_DRAW === 1 || node._showNode) { - // draw bounding box - var locQuad = this._quad; - var verticesG1 = [ - cc.p(locQuad.tl.vertices.x, locQuad.tl.vertices.y), - cc.p(locQuad.bl.vertices.x, locQuad.bl.vertices.y), - cc.p(locQuad.br.vertices.x, locQuad.br.vertices.y), - cc.p(locQuad.tr.vertices.x, locQuad.tr.vertices.y) - ]; - cc._drawingUtil.drawPoly(verticesG1, 4, true); - } else if (macro.SPRITE_DEBUG_DRAW === 2) { - // draw texture box - var drawRectG2 = node.getTextureRect(); - var offsetPixG2 = node.getOffsetPosition(); - var verticesG2 = [cc.p(offsetPixG2.x, offsetPixG2.y), cc.p(offsetPixG2.x + drawRectG2.width, offsetPixG2.y), - cc.p(offsetPixG2.x + drawRectG2.width, offsetPixG2.y + drawRectG2.height), cc.p(offsetPixG2.x, offsetPixG2.y + drawRectG2.height)]; - cc._drawingUtil.drawPoly(verticesG2, 4, true); - } // CC_SPRITE_DEBUG_DRAW - cc.current_stack.top = cc.current_stack.stack.pop(); -}; \ No newline at end of file + return len; +}; diff --git a/cocos2d/core/sprites/CCScale9Sprite.js b/cocos2d/core/sprites/CCScale9Sprite.js index 91c8f9f03c..d81a6b97d4 100644 --- a/cocos2d/core/sprites/CCScale9Sprite.js +++ b/cocos2d/core/sprites/CCScale9Sprite.js @@ -1,8 +1,5 @@ /**************************************************************************** - Copyright (c) 2008-2010 Ricardo Quesada - Copyright (c) 2011-2012 cocos2d-x.org - Copyright (c) 2013-2014 Chukong Technologies Inc. - Copyright (c) 2012 Neofect. All rights reserved. + Copyright (c) 2016 Chukong Technologies Inc. http://www.cocos2d-x.org @@ -23,11 +20,44 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - - Created by Jung Sang-Taik on 2012-03-16 ****************************************************************************/ -EventTarget = require("../cocos2d/core/event/event-target"); +var EventTarget = require("../cocos2d/core/event/event-target"); + +var dataPool = { + _pool: {}, + _lengths: [], + put: function (data) { + var length = data.length; + if (!this._pool[length]) { + this._pool[length] = [data]; + this._lengths.push(length); + this._lengths.sort(); + } + else { + this._pool[length].push(data); + } + }, + get: function (length) { + var id; + for (var i = 0; i < this._lengths.length; i++) { + if (this._lengths[i] >= length) { + id = this._lengths[i]; + break; + } + } + if (id) { + return this._pool[id].pop(); + } + else { + return undefined; + } + } +}; + +var webgl, + vl, vb, vt, vr, + cornerId = []; /* *

@@ -51,55 +81,26 @@ EventTarget = require("../cocos2d/core/event/event-target"); * @property {Number} insetBottom - The bottom inset of the 9-slice sprite */ var simpleQuadGenerator = { - _rebuildQuads_base: function (spriteFrame, contentSize, colorOpacity, isTrimmedContentSize) { - var quads = []; + _rebuildQuads_base: function (sprite, spriteFrame, contentSize, isTrimmedContentSize) { //build vertices - var vertices = this._calculateVertices(spriteFrame, contentSize, isTrimmedContentSize); - + this._calculateVertices(sprite, spriteFrame, contentSize, isTrimmedContentSize); //build uvs - var uvs = this._calculateUVs(spriteFrame); - - //build quads - var quad; - quad = cc.pool.getFromPool(cc.V3F_C4B_T2F_Quad)|| new cc.V3F_C4B_T2F_Quad(); - - quad._bl.colors = colorOpacity; - quad._br.colors = colorOpacity; - quad._tl.colors = colorOpacity; - quad._tr.colors = colorOpacity; - - quad._bl.vertices = new cc.Vertex3F(vertices[0].x, vertices[0].y, 0); - quad._br.vertices = new cc.Vertex3F(vertices[1].x, vertices[0].y, 0); - quad._tl.vertices = new cc.Vertex3F(vertices[0].x, vertices[1].y, 0); - quad._tr.vertices = new cc.Vertex3F(vertices[1].x, vertices[1].y, 0); - - if (!spriteFrame._rotated) { - quad._bl.texCoords = new cc.Tex2F(uvs[0].x, uvs[0].y); - quad._br.texCoords = new cc.Tex2F(uvs[1].x, uvs[0].y); - quad._tl.texCoords = new cc.Tex2F(uvs[0].x, uvs[1].y); - quad._tr.texCoords = new cc.Tex2F(uvs[1].x, uvs[1].y); - } else { - quad._bl.texCoords = new cc.Tex2F(uvs[0].x, uvs[1].y); - quad._br.texCoords = new cc.Tex2F(uvs[0].x, uvs[0].y); - quad._tl.texCoords = new cc.Tex2F(uvs[1].x, uvs[1].y); - quad._tr.texCoords = new cc.Tex2F(uvs[1].x, uvs[0].y); - } - quads.push(quad); - return quads; + this._calculateUVs(sprite, spriteFrame); + sprite._vertCount = 4; }, - _calculateVertices: function (spriteFrame, contentSize, isTrimmedContentSize) { - var x0, x3; - var y0, y3; + _calculateVertices: function (sprite, spriteFrame, contentSize, isTrimmedContentSize) { + var vertices = sprite._vertices, + wt = sprite._renderCmd._worldTransform, + l, b, r, t; if (isTrimmedContentSize) { - x0 = 0; - x3 = contentSize.width; - - y0 = 0; - y3 = contentSize.height; + l = 0; + b = 0; + r = contentSize.width; + t = contentSize.height; } else { var originalSize = spriteFrame.getOriginalSize(); - var rect = spriteFrame.getRect(); + var rect = spriteFrame._rect; var offset = spriteFrame.getOffset(); var scaleX = contentSize.width / originalSize.width; var scaleY = contentSize.height / originalSize.height; @@ -108,95 +109,94 @@ var simpleQuadGenerator = { var trimmedBottom = offset.y + (originalSize.height - rect.height) / 2; var trimmedTop = offset.y - (originalSize.height - rect.height) / 2; - x0 = trimmLeft * scaleX; - x3 = contentSize.width + trimmRight * scaleX; - y0 = trimmedBottom * scaleY; - y3 = contentSize.height + trimmedTop * scaleY; + l = trimmLeft * scaleX; + b = trimmedBottom * scaleY; + r = contentSize.width + trimmRight * scaleX; + t = contentSize.height + trimmedTop * scaleY; } - var vertices = []; - vertices.push(cc.p(x0, y0)); - vertices.push(cc.p(x3, y3)); - - return vertices; - }, - - _calculateUVs: function (spriteFrame) { - var atlasWidth = spriteFrame._texture.getPixelWidth(); - var atlasHeight = spriteFrame._texture.getPixelHeight(); - - var textureRect = spriteFrame.getRect(); - - //uv computation should take spritesheet into account. - var u0, u3; - var v0, v3; - - if (spriteFrame._rotated) { - u0 = textureRect.x / atlasWidth; - u3 = (textureRect.x + textureRect.height) / atlasWidth; - - v0 = textureRect.y / atlasHeight; - v3 = (textureRect.y + textureRect.width) / atlasHeight; + if (vertices.length < 8) { + dataPool.put(vertices); + vertices = dataPool.get(8) || new Float32Array(8); + sprite._vertices = vertices; + } + // bl, br, tl, tr + if (webgl) { + vertices[0] = l * wt.a + b * wt.c + wt.tx; + vertices[1] = l * wt.b + b * wt.d + wt.ty; + vertices[2] = r * wt.a + b * wt.c + wt.tx; + vertices[3] = r * wt.b + b * wt.d + wt.ty; + vertices[4] = l * wt.a + t * wt.c + wt.tx; + vertices[5] = l * wt.b + t * wt.d + wt.ty; + vertices[6] = r * wt.a + t * wt.c + wt.tx; + vertices[7] = r * wt.b + t * wt.d + wt.ty; } else { - u0 = textureRect.x / atlasWidth; - u3 = (textureRect.x + textureRect.width) / atlasWidth; - - v0 = textureRect.y / atlasHeight; - v3 = (textureRect.y + textureRect.height) / atlasHeight; + vertices[0] = l; + vertices[1] = b; + vertices[2] = r; + vertices[3] = b; + vertices[4] = l; + vertices[5] = t; + vertices[6] = r; + vertices[7] = t; } - var uvCoordinates = []; - uvCoordinates.push(cc.p(u0, v3)); - uvCoordinates.push(cc.p(u3, v0)); + cornerId[0] = 0; + cornerId[1] = 2; + cornerId[2] = 4; + cornerId[3] = 6; + }, - return uvCoordinates; + _calculateUVs: function (sprite, spriteFrame) { + var uvs = sprite._uvs; + var atlasWidth = spriteFrame._texture.getPixelWidth(); + var atlasHeight = spriteFrame._texture.getPixelHeight(); + var textureRect = spriteFrame._rect; + + if (uvs.length < 8) { + dataPool.put(uvs); + uvs = dataPool.get(8) || new Float32Array(8); + sprite._uvs = uvs; + } + + //uv computation should take spritesheet into account. + var l, b, r, t; + + if (spriteFrame._rotated) { + l = textureRect.x / atlasWidth; + b = (textureRect.y + textureRect.width) / atlasHeight; + r = (textureRect.x + textureRect.height) / atlasWidth; + t = textureRect.y / atlasHeight; + uvs[0] = l; uvs[1] = t; + uvs[2] = l; uvs[3] = b; + uvs[4] = r; uvs[5] = t; + uvs[6] = r; uvs[7] = b; + } + else { + l = textureRect.x / atlasWidth; + b = (textureRect.y + textureRect.height) / atlasHeight; + r = (textureRect.x + textureRect.width) / atlasWidth; + t = textureRect.y / atlasHeight; + uvs[0] = l; uvs[1] = b; + uvs[2] = r; uvs[3] = b; + uvs[4] = l; uvs[5] = t; + uvs[6] = r; uvs[7] = t; + } } }; var scale9QuadGenerator = { - _rebuildQuads_base: function (spriteFrame, contentSize, colorOpacity, insetLeft, insetRight, insetTop, insetBottom) { - var quads = []; + _rebuildQuads_base: function (sprite, spriteFrame, contentSize, insetLeft, insetRight, insetTop, insetBottom) { //build vertices - var vertices = this._calculateVertices(spriteFrame, contentSize, insetLeft, insetRight, insetTop, insetBottom); - + this._calculateVertices(sprite, spriteFrame, contentSize, insetLeft, insetRight, insetTop, insetBottom); //build uvs - var uvs = this._calculateUVs(spriteFrame, insetLeft, insetRight, insetTop, insetBottom); - - //build quads - var quad; - for (var i = 0; i < 3; ++i) { - for (var j = 0; j < 3; ++j) { - quad = cc.pool.getFromPool(cc.V3F_C4B_T2F_Quad) || new cc.V3F_C4B_T2F_Quad(); - quad._bl.colors = colorOpacity; - quad._br.colors = colorOpacity; - quad._tl.colors = colorOpacity; - quad._tr.colors = colorOpacity; - - quad._bl.vertices = new cc.Vertex3F(vertices[i].x, vertices[j].y, 0); - quad._br.vertices = new cc.Vertex3F(vertices[i + 1].x, vertices[j].y, 0); - quad._tl.vertices = new cc.Vertex3F(vertices[i].x, vertices[j + 1].y, 0); - quad._tr.vertices = new cc.Vertex3F(vertices[i + 1].x, vertices[j + 1].y, 0); - - if (!spriteFrame._rotated) { - quad._bl.texCoords = new cc.Tex2F(uvs[i].x, uvs[j].y); - quad._br.texCoords = new cc.Tex2F(uvs[i + 1].x, uvs[j].y); - quad._tl.texCoords = new cc.Tex2F(uvs[i].x, uvs[j + 1].y); - quad._tr.texCoords = new cc.Tex2F(uvs[i + 1].x, uvs[j + 1].y); - } else { - quad._bl.texCoords = new cc.Tex2F(uvs[j].x, uvs[3 - i].y); - quad._br.texCoords = new cc.Tex2F(uvs[j].x, uvs[3 - (i + 1)].y); - quad._tl.texCoords = new cc.Tex2F(uvs[j + 1].x, uvs[3 - i].y); - quad._tr.texCoords = new cc.Tex2F(uvs[j + 1].x, uvs[3 - (i + 1)].y); - } - quads.push(quad); - } - } - - return quads; + this._calculateUVs(sprite, spriteFrame, insetLeft, insetRight, insetTop, insetBottom); }, - _calculateVertices: function (spriteFrame, contentSize, insetLeft, insetRight, insetTop, insetBottom) { + _calculateVertices: function (sprite, spriteFrame, contentSize, insetLeft, insetRight, insetTop, insetBottom) { + var vertices = sprite._vertices; + var wt = sprite._renderCmd._worldTransform; var leftWidth, centerWidth, rightWidth; var topHeight, centerHeight, bottomHeight; @@ -218,28 +218,50 @@ var scale9QuadGenerator = { yScale = yScale > 1 ? 1 : yScale; sizableWidth = sizableWidth < 0 ? 0 : sizableWidth; sizableHeight = sizableHeight < 0 ? 0 : sizableHeight; - var x0, x1, x2, x3; - var y0, y1, y2, y3; - x0 = 0; - x1 = leftWidth * xScale; - x2 = x1 + sizableWidth; - x3 = preferSize.width; + var x = new Array(4); + var y = new Array(4); + x[0] = 0; + x[1] = leftWidth * xScale; + x[2] = x[1] + sizableWidth; + x[3] = preferSize.width; + y[0] = 0; + y[1] = bottomHeight * yScale; + y[2] = y[1] + sizableHeight; + y[3] = preferSize.height; - y0 = 0; - y1 = bottomHeight * yScale; - y2 = y1 + sizableHeight; - y3 = preferSize.height; + if (vertices.length < 32) { + dataPool.put(vertices); + vertices = dataPool.get(32) || new Float32Array(32); + sprite._vertices = vertices; + } + var offset = 0, row, col; + if (webgl) { + for (row = 0; row < 4; row++) { + for (col = 0; col < 4; col++) { + vertices[offset] = x[col] * wt.a + y[row] * wt.c + wt.tx; + vertices[offset+1] = x[col] * wt.b + y[row] * wt.d + wt.ty; + offset += 2; + } + } + } + else { + for (row = 0; row < 4; row++) { + for (col = 0; col < 4; col++) { + vertices[offset] = x[col]; + vertices[offset+1] = y[row]; + offset += 2; + } + } + } - var vertices = []; - vertices.push(cc.p(x0, y0)); - vertices.push(cc.p(x1, y1)); - vertices.push(cc.p(x2, y2)); - vertices.push(cc.p(x3, y3)); - - return vertices; + cornerId[0] = 0; + cornerId[1] = 6; + cornerId[2] = 24; + cornerId[3] = 30; }, - _calculateUVs: function (spriteFrame, insetLeft, insetRight, insetTop, insetBottom) { + _calculateUVs: function (sprite, spriteFrame, insetLeft, insetRight, insetTop, insetBottom) { + var uvs = sprite._uvs; var rect = spriteFrame._rect; var atlasWidth = spriteFrame._texture.getPixelWidth(); var atlasHeight = spriteFrame._texture.getPixelHeight(); @@ -254,374 +276,415 @@ var scale9QuadGenerator = { topHeight = insetTop; bottomHeight = insetBottom; centerHeight = rect.height - topHeight - bottomHeight; + var textureRect = spriteFrame._rect; - var textureRect = spriteFrame.getRect(); + if (uvs.length < 32) { + dataPool.put(uvs); + uvs = dataPool.get(32) || new Float32Array(32); + sprite._uvs = uvs; + } //uv computation should take spritesheet into account. - var u0, u1, u2, u3; - var v0, v1, v2, v3; + var u = new Array(4); + var v = new Array(4); + var offset = 0, row, col; if (spriteFrame._rotated) { - u0 = textureRect.x / atlasWidth; - u1 = (bottomHeight + textureRect.x) / atlasWidth; - u2 = (bottomHeight + centerHeight + textureRect.x) / atlasWidth; - u3 = (textureRect.x + textureRect.height) / atlasWidth; + u[0] = textureRect.x / atlasWidth; + u[1] = (bottomHeight + textureRect.x) / atlasWidth; + u[2] = (bottomHeight + centerHeight + textureRect.x) / atlasWidth; + u[3] = (textureRect.x + textureRect.height) / atlasWidth; - v0 = textureRect.y / atlasHeight; - v1 = (leftWidth + textureRect.y) / atlasHeight; - v2 = (leftWidth + centerWidth + textureRect.y) / atlasHeight; - v3 = (textureRect.y + textureRect.width) / atlasHeight; + v[3] = textureRect.y / atlasHeight; + v[2] = (leftWidth + textureRect.y) / atlasHeight; + v[1] = (leftWidth + centerWidth + textureRect.y) / atlasHeight; + v[0] = (textureRect.y + textureRect.width) / atlasHeight; + + for (row = 0; row < 4; row++) { + for (col = 0; col < 4; col++) { + uvs[offset] = u[row]; + uvs[offset+1] = v[3-col]; + offset += 2; + } + } } else { - u0 = textureRect.x / atlasWidth; - u1 = (leftWidth + textureRect.x) / atlasWidth; - u2 = (leftWidth + centerWidth + textureRect.x) / atlasWidth; - u3 = (textureRect.x + textureRect.width) / atlasWidth; + u[0] = textureRect.x / atlasWidth; + u[1] = (leftWidth + textureRect.x) / atlasWidth; + u[2] = (leftWidth + centerWidth + textureRect.x) / atlasWidth; + u[3] = (textureRect.x + textureRect.width) / atlasWidth; - v0 = textureRect.y / atlasHeight; - v1 = (topHeight + textureRect.y) / atlasHeight; - v2 = (topHeight + centerHeight + textureRect.y) / atlasHeight; - v3 = (textureRect.y + textureRect.height) / atlasHeight; + v[3] = textureRect.y / atlasHeight; + v[2] = (topHeight + textureRect.y) / atlasHeight; + v[1] = (topHeight + centerHeight + textureRect.y) / atlasHeight; + v[0] = (textureRect.y + textureRect.height) / atlasHeight; + + for (row = 0; row < 4; row++) { + for (col = 0; col < 4; col++) { + uvs[offset] = u[col]; + uvs[offset+1] = v[row]; + offset += 2; + } + } } - - var uvCoordinates = []; - uvCoordinates.push(cc.p(u0, v3)); - uvCoordinates.push(cc.p(u1, v2)); - uvCoordinates.push(cc.p(u2, v1)); - uvCoordinates.push(cc.p(u3, v0)); - - return uvCoordinates; } }; var tiledQuadGenerator = { - _rebuildQuads_base: function (spriteFrame, contentSize, colorOpacity) { - var quads = []; - + _rebuildQuads_base: function (sprite, spriteFrame, contentSize) { + var vertices = sprite._vertices, + wt = sprite._renderCmd._worldTransform, + uvs = sprite._uvs; //build uvs - var uvs = this._calculateUVs(spriteFrame); - var u0 = uvs[0].x; - var v0 = uvs[0].y; - var u1 = uvs[1].x; - var v1 = uvs[1].y; - var rectWidth = spriteFrame.getRect().width; - var rectHeight = spriteFrame.getRect().height; - //build quads - var hRepeat = contentSize.width / rectWidth; - var vRepeat = contentSize.height / rectHeight; - - if(Math.ceil(hRepeat) * Math.ceil(vRepeat) > (65536 / 4)) { - cc.error("too many tiles, only 16384 tiles will be show"); - } - - for (var hindex = 0; hindex < Math.ceil(hRepeat); ++hindex) { - for (var vindex = 0; vindex < Math.ceil(vRepeat); ++vindex) { - var quad; - quad = cc.pool.getFromPool(cc.V3F_C4B_T2F_Quad) || new cc.V3F_C4B_T2F_Quad(); - - quad._bl.colors = colorOpacity; - quad._br.colors = colorOpacity; - quad._tl.colors = colorOpacity; - quad._tr.colors = colorOpacity; - - quad._bl.vertices = new cc.Vertex3F(rectWidth * hindex, rectHeight * vindex, 0); - quad._br.vertices = new cc.Vertex3F(rectWidth * Math.min(hindex + 1, hRepeat), rectHeight * vindex, 0); - quad._tl.vertices = new cc.Vertex3F(rectWidth * hindex, rectHeight * Math.min(vindex + 1, vRepeat), 0); - quad._tr.vertices = new cc.Vertex3F(rectWidth * Math.min(hindex + 1, hRepeat), rectHeight * Math.min(vindex + 1, vRepeat), 0); - - if (!spriteFrame._rotated) { - quad._bl.texCoords = new cc.Tex2F(u0, v0); - quad._br.texCoords = new cc.Tex2F(u0 + (u1 - u0) * Math.min(1, hRepeat - hindex), v0); - quad._tl.texCoords = new cc.Tex2F(u0, v0 + (v1 - v0) * Math.min(1, vRepeat - vindex)); - quad._tr.texCoords = new cc.Tex2F(u0 + (u1 - u0) * Math.min(1, hRepeat - hindex), v0 + (v1 - v0) * Math.min(1, vRepeat - vindex)); - } else { - quad._bl.texCoords = new cc.Tex2F(u0, v1); - quad._br.texCoords = new cc.Tex2F(u0, v1 + (v0 - v1) * Math.min(1, hRepeat - hindex)); - quad._tl.texCoords = new cc.Tex2F(u0 + (u1 - u0) * Math.min(1, vRepeat - vindex), v1); - quad._tr.texCoords = new cc.Tex2F(u0 + (u1 - u0) * Math.min(1, vRepeat - vindex), v1 + (v0 - v1) * Math.min(1, hRepeat - hindex)); - - } - quads.push(quad); - if(quads.length >= 65536 / 4) { - break; - } - } - } - return quads; - }, - - _calculateUVs: function (spriteFrame) { var atlasWidth = spriteFrame._texture.getPixelWidth(); var atlasHeight = spriteFrame._texture.getPixelHeight(); - - var textureRect = spriteFrame.getRect(); + var textureRect = spriteFrame._rect; //uv computation should take spritesheet into account. - var u0, u3; - var v0, v3; - + var u0, v0, u1, v1; if (spriteFrame._rotated) { u0 = textureRect.x / atlasWidth; - u3 = (textureRect.x + textureRect.height) / atlasWidth; - - v0 = textureRect.y / atlasHeight; - v3 = (textureRect.y + textureRect.width) / atlasHeight; + u1 = (textureRect.x + textureRect.height) / atlasWidth; + v0 = (textureRect.y + textureRect.width) / atlasHeight; + v1 = textureRect.y / atlasHeight; } else { u0 = textureRect.x / atlasWidth; - u3 = (textureRect.x + textureRect.width) / atlasWidth; + u1 = (textureRect.x + textureRect.width) / atlasWidth; + v0 = (textureRect.y + textureRect.height) / atlasHeight; + v1 = textureRect.y / atlasHeight; + } + + //build quads + var rectWidth = textureRect.width; + var rectHeight = textureRect.height; + var hRepeat = contentSize.width / rectWidth; + var vRepeat = contentSize.height / rectHeight; + var row = Math.ceil(vRepeat), col = Math.ceil(hRepeat); - v0 = textureRect.y / atlasHeight; - v3 = (textureRect.y + textureRect.height) / atlasHeight; + if (row * col > (65536 / 4)) { + cc.error('too many tiles, only 16384 tiles will be show'); + } + var dataLength = row * col * 4 * 2; + if (vertices.length < dataLength) { + dataPool.put(vertices); + vertices = dataPool.get(dataLength) || new Float32Array(dataLength); + sprite._vertices = vertices; + } + if (uvs.length < dataLength) { + dataPool.put(uvs); + uvs = dataPool.get(dataLength) || new Float32Array(dataLength); + sprite._uvs = uvs; } - var uvCoordinates = []; - uvCoordinates.push(cc.p(u0, v3)); - uvCoordinates.push(cc.p(u3, v0)); + var offset = 0, l, b, r, t; + sprite._vertCount = 0; + for (var vindex = 0; vindex < row; ++vindex) { + for (var hindex = 0; hindex < col; ++hindex) { + l = rectWidth * hindex; + b = rectHeight * vindex; + r = rectWidth * Math.min(hindex + 1, hRepeat); + t = rectHeight * Math.min(vindex + 1, vRepeat); + // bl.x, bl.y, br.x, br.y, tl.x, tl.y, tr.x, tr.y + if (webgl) { + vertices[offset] = l * wt.a + b * wt.c + wt.tx; + vertices[offset + 1] = l * wt.b + b * wt.d + wt.ty; + vertices[offset + 2] = r * wt.a + b * wt.c + wt.tx; + vertices[offset + 3] = r * wt.b + b * wt.d + wt.ty; + vertices[offset + 4] = l * wt.a + t * wt.c + wt.tx; + vertices[offset + 5] = l * wt.b + t * wt.d + wt.ty; + vertices[offset + 6] = r * wt.a + t * wt.c + wt.tx; + vertices[offset + 7] = r * wt.b + t * wt.d + wt.ty; + } + else { + vertices[offset] = l; + vertices[offset + 1] = b; + vertices[offset + 2] = r; + vertices[offset + 3] = b; + vertices[offset + 4] = l; + vertices[offset + 5] = t; + vertices[offset + 6] = r; + vertices[offset + 7] = t; + } - return uvCoordinates; + if (!spriteFrame._rotated) { + uvs[offset] = u0; + uvs[offset + 1] = v0; + uvs[offset + 2] = r = u0 + (u1 - u0) * Math.min(1, hRepeat - hindex); + uvs[offset + 3] = v0; + uvs[offset + 4] = u0; + uvs[offset + 5] = t = v0 + (v1 - v0) * Math.min(1, vRepeat - vindex); + uvs[offset + 6] = r; + uvs[offset + 7] = t; + } else { + uvs[offset] = u0; + uvs[offset + 1] = v1; + uvs[offset + 2] = u0; + uvs[offset + 3] = t = v1 + (v0 - v1) * Math.min(1, hRepeat - hindex); + uvs[offset + 4] = r = u0 + (u1 - u0) * Math.min(1, vRepeat - vindex); + uvs[offset + 5] = v1; + uvs[offset + 6] = r; + uvs[offset + 7] = t; + } + offset += 8; + sprite._vertCount += 4; + if (offset > dataLength) return; + } + } + + cornerId[0] = 0; + cornerId[1] = 2; + cornerId[2] = 4; + cornerId[3] = 6; } }; var fillQuadGeneratorBar = { //percentage from 0 to 1; - _rebuildQuads_base : function (spriteFrame, contentSize, colorOpacity, fillType, fillStart, fillRange) { + _rebuildQuads_base : function (sprite, spriteFrame, contentSize, fillType, fillStart, fillRange) { + var vertices = sprite._vertices, + wt = sprite._renderCmd._worldTransform, + uvs = sprite._uvs; var fillEnd; //build vertices - var vertices = this._calculateVertices(spriteFrame, contentSize); - + var l = 0, b = 0, + r = contentSize.width, t = contentSize.height; //build uvs - var uvs = this._calculateUVs(spriteFrame); + var atlasWidth = spriteFrame._texture.getPixelWidth(); + var atlasHeight = spriteFrame._texture.getPixelHeight(); + var textureRect = spriteFrame._rect; + //uv computation should take spritesheet into account. + var ul, vb, ur, vt; + if (spriteFrame._rotated) { + ul = textureRect.x / atlasWidth; + vb = (textureRect.y + textureRect.width) / atlasHeight; + ur = (textureRect.x + textureRect.height) / atlasWidth; + vt = textureRect.y / atlasHeight; + } + else { + ul = textureRect.x / atlasWidth; + vb = (textureRect.y + textureRect.height) / atlasHeight; + ur = (textureRect.x + textureRect.width) / atlasWidth; + vt = textureRect.y / atlasHeight; + } + + if (vertices.length < 8) { + dataPool.put(vertices); + vertices = dataPool.get(8) || new Float32Array(8); + sprite._vertices = vertices; + } + if (uvs.length < 8) { + dataPool.put(uvs); + uvs = dataPool.get(8) || new Float32Array(8); + sprite._uvs = uvs; + } //build quads - var quad = cc.pool.getFromPool(cc.V3F_C4B_T2F_Quad) || new cc.V3F_C4B_T2F_Quad(); - - quad._bl.colors = colorOpacity; - quad._br.colors = colorOpacity; - quad._tl.colors = colorOpacity; - quad._tr.colors = colorOpacity; - - quad._bl.vertices.x = quad._tl.vertices.x = vertices[0].x; - quad._br.vertices.x = quad._tr.vertices.x = vertices[1].x; - - quad._bl.vertices.y = quad._br.vertices.y = vertices[0].y; - quad._tl.vertices.y = quad._tr.vertices.y = vertices[1].y; - - var quadUV = [null,null,null,null]; + if (webgl) { + vertices[0] = l * wt.a + b * wt.c + wt.tx; + vertices[1] = l * wt.b + b * wt.d + wt.ty; + vertices[2] = r * wt.a + b * wt.c + wt.tx; + vertices[3] = r * wt.b + b * wt.d + wt.ty; + vertices[4] = l * wt.a + t * wt.c + wt.tx; + vertices[5] = l * wt.b + t * wt.d + wt.ty; + vertices[6] = r * wt.a + t * wt.c + wt.tx; + vertices[7] = r * wt.b + t * wt.d + wt.ty; + } + else { + vertices[0] = l; + vertices[1] = b; + vertices[2] = r; + vertices[3] = b; + vertices[4] = l; + vertices[5] = t; + vertices[6] = r; + vertices[7] = t; + } + var quadUV = new Array(8); if (!spriteFrame._rotated) { - quadUV[0] = new cc.Tex2F(uvs[0].x, uvs[0].y); - quadUV[1] = new cc.Tex2F(uvs[1].x, uvs[0].y); - quadUV[2] = new cc.Tex2F(uvs[0].x, uvs[1].y); - quadUV[3] = new cc.Tex2F(uvs[1].x, uvs[1].y); + quadUV[0] = quadUV[4] = ul; + quadUV[2] = quadUV[6] = ur; + quadUV[1] = quadUV[3] = vb; + quadUV[5] = quadUV[7] = vt; } else { - quadUV[0] = new cc.Tex2F(uvs[0].x, uvs[1].y); - quadUV[1] = new cc.Tex2F(uvs[0].x, uvs[0].y); - quadUV[2]= new cc.Tex2F(uvs[1].x, uvs[1].y); - quadUV[3]= new cc.Tex2F(uvs[1].x, uvs[0].y); + quadUV[0] = quadUV[2] = ul; + quadUV[4] = quadUV[6] = ur; + quadUV[3] = quadUV[7] = vb; + quadUV[1] = quadUV[5] = vt; } //do clamp fillStart = fillStart > 1 ? 1 : fillStart; fillStart = fillStart < 0 ? 0 : fillStart; - fillRange = fillRange < 0 ? 0 : fillRange; - fillEnd = fillStart + fillRange; - fillEnd = fillEnd > 1 ? 1 : fillEnd; + // bl : 0, 1 + // br : 2, 3 + // tl : 4, 5 + // tr : 6, 7 var progressStart, progressEnd; switch (fillType) { case cc.Scale9Sprite.FillType.HORIZONTAL: - progressStart = vertices[0].x + (vertices[1].x - vertices[0].x) * fillStart; - progressEnd = vertices[0].x + (vertices[1].x - vertices[0].x) * fillEnd; + progressStart = vertices[0] + (vertices[2] - vertices[0]) * fillStart; + progressEnd = vertices[0] + (vertices[2] - vertices[0]) * fillEnd; - quad._bl.vertices.x = progressStart; - quad._tl.vertices.x = progressStart; + vertices[0] = progressStart; + vertices[2] = progressEnd; + vertices[4] = progressStart; + vertices[6] = progressEnd; - quad._br.vertices.x = progressEnd; - quad._tr.vertices.x = progressEnd; - - quad._bl.texCoords.u = quadUV[0].u + (quadUV[1].u - quadUV[0].u) * fillStart; - quad._bl.texCoords.v = quadUV[0].v + (quadUV[1].v - quadUV[0].v) * fillStart; - - quad._tl.texCoords.u = quadUV[2].u + (quadUV[3].u - quadUV[2].u) * fillStart; - quad._tl.texCoords.v = quadUV[2].v + (quadUV[3].v - quadUV[2].v) * fillStart; - - quad._br.texCoords.u = quadUV[0].u + (quadUV[1].u - quadUV[0].u) * fillEnd; - quad._br.texCoords.v = quadUV[0].v + (quadUV[1].v - quadUV[0].v) * fillEnd; - - quad._tr.texCoords.u = quadUV[2].u + (quadUV[3].u - quadUV[2].u) * fillEnd; - quad._tr.texCoords.v = quadUV[2].v + (quadUV[3].v - quadUV[2].v) * fillEnd; + uvs[0] = quadUV[0] + (quadUV[2] - quadUV[0]) * fillStart; + uvs[1] = quadUV[1]; + uvs[2] = quadUV[0] + (quadUV[2] - quadUV[0]) * fillEnd; + uvs[3] = quadUV[3]; + uvs[4] = quadUV[4] + (quadUV[6] - quadUV[4]) * fillStart; + uvs[5] = quadUV[5]; + uvs[6] = quadUV[4] + (quadUV[6] - quadUV[4]) * fillEnd; + uvs[7] = quadUV[7]; break; case cc.Scale9Sprite.FillType.VERTICAL: - progressStart = vertices[0].y + (vertices[1].y - vertices[0].y) * fillStart; - progressEnd = vertices[0].y + (vertices[1].y - vertices[0].y) * fillEnd; + progressStart = vertices[1] + (vertices[5] - vertices[1]) * fillStart; + progressEnd = vertices[1] + (vertices[5] - vertices[1]) * fillEnd; - quad._bl.vertices.y = progressStart; - quad._br.vertices.y = progressStart; + vertices[1] = progressStart; + vertices[3] = progressStart; + vertices[5] = progressEnd; + vertices[7] = progressEnd; - quad._tl.vertices.y = progressEnd; - quad._tr.vertices.y = progressEnd; - - quad._bl.texCoords.u = quadUV[0].u + (quadUV[2].u - quadUV[0].u) * fillStart; - quad._bl.texCoords.v = quadUV[0].v + (quadUV[2].v - quadUV[0].v) * fillStart; - - quad._br.texCoords.u = quadUV[1].u + (quadUV[3].u - quadUV[1].u) * fillStart; - quad._br.texCoords.v = quadUV[1].v + (quadUV[3].v - quadUV[1].v) * fillStart; - - quad._tl.texCoords.u = quadUV[0].u + (quadUV[2].u - quadUV[0].u) * fillEnd; - quad._tl.texCoords.v = quadUV[0].v + (quadUV[2].v - quadUV[0].v) * fillEnd; - - quad._tr.texCoords.u = quadUV[1].u + (quadUV[3].u - quadUV[1].u) * fillEnd; - quad._tr.texCoords.v = quadUV[1].v + (quadUV[3].v - quadUV[1].v) * fillEnd; + uvs[0] = quadUV[0]; + uvs[1] = quadUV[1] + (quadUV[5] - quadUV[1]) * fillStart; + uvs[2] = quadUV[2]; + uvs[3] = quadUV[3] + (quadUV[7] - quadUV[3]) * fillStart; + uvs[4] = quadUV[4]; + uvs[5] = quadUV[1] + (quadUV[5] - quadUV[1]) * fillEnd; + uvs[6] = quadUV[6]; + uvs[7] = quadUV[3] + (quadUV[7] - quadUV[3]) * fillEnd; break; default: - cc.error("Unrecognized fill type in bar fill"); + cc.error('Unrecognized fill type in bar fill'); break; } + sprite._vertCount = 4; - return [quad]; - }, - - _calculateVertices : function (spriteFrame, contentSize) { - - var x0,x3; - var y0,y3; - x0 = 0; - x3 = contentSize.width; - - y0 = 0; - y3 = contentSize.height; - - return [cc.p(x0, y0), cc.p(x3, y3)]; - }, - - _calculateUVs : function (spriteFrame) { - var atlasWidth = spriteFrame._texture.getPixelWidth(); - var atlasHeight = spriteFrame._texture.getPixelHeight(); - - var textureRect = spriteFrame.getRect(); - - //uv computation should take spritesheet into account. - var u0, u3; - var v0, v3; - - if (spriteFrame._rotated) { - u0 = textureRect.x / atlasWidth; - u3 = (textureRect.x + textureRect.height) / atlasWidth; - - v0 = textureRect.y / atlasHeight; - v3 = (textureRect.y + textureRect.width) / atlasHeight; - } - else { - u0 = textureRect.x / atlasWidth; - u3 = (textureRect.x + textureRect.width) / atlasWidth; - - v0 = textureRect.y / atlasHeight; - v3 = (textureRect.y + textureRect.height) / atlasHeight; - } - - return [cc.p(u0, v3),cc.p(u3, v0)]; + cornerId[0] = 0; + cornerId[1] = 2; + cornerId[2] = 4; + cornerId[3] = 6; } }; var fillQuadGeneratorRadial = { - _rebuildQuads_base : function (spriteFrame, contentSize, colorOpacity, fillCenter, fillStart,fillRange) { + _vertPos: [cc.v2(0, 0), cc.v2(0, 0), cc.v2(0, 0), cc.v2(0, 0)], + _vertices: [cc.v2(0,0),cc.v2(0,0)], + _uvs: [cc.v2(0,0),cc.v2(0,0)], + _intersectPoint_1: [cc.v2(0, 0), cc.v2(0, 0), cc.v2(0, 0), cc.v2(0, 0)], + _intersectPoint_2: [cc.v2(0, 0), cc.v2(0, 0), cc.v2(0, 0), cc.v2(0, 0)], + outVerts: null, + outUvs: null, + rawVerts: null, + rawUvs: null, + + _rebuildQuads_base : function (sprite, spriteFrame, contentSize, fillCenter, fillStart, fillRange) { + var vertices = sprite._vertices, + uvs = sprite._uvs, + rawVerts = sprite._rawVerts, + rawUvs = sprite._rawUvs, + wt = sprite._renderCmd._worldTransform; //do round fill start [0,1), include 0, exclude 1 while (fillStart >= 1.0) fillStart -= 1.0; while (fillStart < 0.0) fillStart += 1.0; - var center = cc.v2(fillCenter); - - center.x *= contentSize.width; - center.y *= contentSize.height; + var cx = fillCenter.x * contentSize.width, + cy = fillCenter.y * contentSize.height; + var center = cc.v2( webgl ? cx * wt.a + cy * wt.c + wt.tx : cx, + webgl ? cx * wt.b + cy * wt.d + wt.ty : cy); fillStart *= Math.PI * 2; fillRange *= Math.PI * 2; var fillEnd = fillStart + fillRange; - if(!this._inited) { - this._inited = true; - this._vertPos = [cc.v2(0, 0), cc.v2(0, 0), cc.v2(0, 0), cc.v2(0, 0)]; - this._vertices = [cc.v2(0,0),cc.v2(0,0)]; - this._uvs = [cc.v2(0,0),cc.v2(0,0)]; - this._intersectPoint_1 = [cc.v2(0, 0), cc.v2(0, 0), cc.v2(0, 0), cc.v2(0, 0)]; - this._intersectPoint_2 = [cc.v2(0, 0), cc.v2(0, 0), cc.v2(0, 0), cc.v2(0, 0)]; - } + + this.outVerts = vertices; + this.outUvs = uvs; + this.rawVerts = rawVerts; + this.rawUvs = rawUvs; //build vertices - this._calculateVertices(spriteFrame, contentSize); + this._calculateVertices(wt, spriteFrame, contentSize); //build uvs this._calculateUVs(spriteFrame); - this._vertPos[0].x = this._vertPos[3].x = this._vertices[0].x; - this._vertPos[1].x = this._vertPos[2].x = this._vertices[1].x; - this._vertPos[0].y = this._vertPos[1].y = this._vertices[0].y; - this._vertPos[2].y = this._vertPos[3].y = this._vertices[1].y; + var _vertPos = this._vertPos, + _vertices = this._vertices; + + _vertPos[0].x = _vertPos[3].x = _vertices[0].x; + _vertPos[1].x = _vertPos[2].x = _vertices[1].x; + _vertPos[0].y = _vertPos[1].y = _vertices[0].y; + _vertPos[2].y = _vertPos[3].y = _vertices[1].y; //fallback //todo remove it if outside is implemented - if(center.x > this._vertices[1].x) { - center.x = this._vertices[1].x; + if(center.x > _vertices[1].x) { + center.x = _vertices[1].x; } - if(center.x < this._vertices[0].x) { - center.x = this._vertices[0].x; + if(center.x < _vertices[0].x) { + center.x = _vertices[0].x; } - if(center.y < this._vertices[0].y) { - center.y = this._vertices[0].y; + if(center.y < _vertices[0].y) { + center.y = _vertices[0].y; } - if(center.y > this._vertices[1].y) { - center.y = this._vertices[1].y; + if(center.y > _vertices[1].y) { + center.y = _vertices[1].y; } - - var rawQuad; - rawQuad = cc.pool.getFromPool(cc.V3F_C4B_T2F_Quad) || new cc.V3F_C4B_T2F_Quad(); - - rawQuad._bl.colors = colorOpacity; - rawQuad._br.colors = colorOpacity; - rawQuad._tl.colors = colorOpacity; - rawQuad._tr.colors = colorOpacity; - - rawQuad._bl.vertices.x = rawQuad._tl.vertices.x = this._vertices[0].x; - rawQuad._br.vertices.x = rawQuad._tr.vertices.x = this._vertices[1].x; - - rawQuad._bl.vertices.y = rawQuad._br.vertices.y = this._vertices[0].y; - rawQuad._tl.vertices.y = rawQuad._tr.vertices.y = this._vertices[1].y; - + + rawVerts[0] = rawVerts[4] = this._vertices[0].x; + rawVerts[2] = rawVerts[6] = this._vertices[1].x; + rawVerts[1] = rawVerts[3] = this._vertices[0].y; + rawVerts[5] = rawVerts[7] = this._vertices[1].y; if (!spriteFrame._rotated) { - rawQuad._bl.texCoords.u = rawQuad._tl.texCoords.u = this._uvs[0].x; - rawQuad._bl.texCoords.v = rawQuad._br.texCoords.v = this._uvs[0].y; - rawQuad._br.texCoords.u = rawQuad._tr.texCoords.u = this._uvs[1].x; - rawQuad._tl.texCoords.v = rawQuad._tr.texCoords.v = this._uvs[1].y; - + rawUvs[0] = rawUvs[4] = this._uvs[0].x; + rawUvs[2] = rawUvs[6] = this._uvs[1].x; + rawUvs[1] = rawUvs[3] = this._uvs[0].y; + rawUvs[5] = rawUvs[7] = this._uvs[1].y; } else { - rawQuad._bl.texCoords.u = rawQuad._br.texCoords.u = this._uvs[0].x; - rawQuad._tl.texCoords.u = rawQuad._tr.texCoords.u = this._uvs[1].x; - rawQuad._br.texCoords.v = rawQuad._tr.texCoords.v = this._uvs[0].y; - rawQuad._bl.texCoords.v = rawQuad._tl.texCoords.v = this._uvs[1].y; - + rawUvs[0] = rawUvs[2] = this._uvs[0].x; + rawUvs[4] = rawUvs[6] = this._uvs[1].x; + rawUvs[3] = rawUvs[7] = this._uvs[0].y; + rawUvs[1] = rawUvs[5] = this._uvs[1].y; } var triangles = [null, null, null, null]; - if(center.x !== this._vertices[0].x) { - triangles[0] = [3,0]; + triangles[0] = [3, 0]; } if(center.x !== this._vertices[1].x) { - triangles[2] = [1,2]; + triangles[2] = [1, 2]; } if(center.y !== this._vertices[0].y) { - triangles[1] = [0,1]; + triangles[1] = [0, 1]; } if(center.y !== this._vertices[1].y) { - triangles[3] = [2,3]; + triangles[3] = [2, 3]; } this._getInsectedPoints(this._vertices[0].x, this._vertices[1].x, this._vertices[0].y, this._vertices[1].y, center, fillStart, this._intersectPoint_1); this._getInsectedPoints(this._vertices[0].x, this._vertices[1].x, this._vertices[0].y, this._vertices[1].y, center, fillStart + fillRange, this._intersectPoint_2); - var quads = []; + var dataLength = 3 * 5 * 2; + if (vertices.length < dataLength) { + dataPool.put(vertices); + vertices = dataPool.get(dataLength) || new Float32Array(dataLength); + sprite._vertices = vertices; + } + if (uvs.length < dataLength) { + dataPool.put(uvs); + uvs = dataPool.get(dataLength) || new Float32Array(dataLength); + sprite._uvs = uvs; + } + + var offset = 0, count = 0; for(var triangleIndex = 0; triangleIndex < 4; ++triangleIndex) { var triangle = triangles[triangleIndex]; if(triangle === null) { @@ -629,12 +692,14 @@ var fillQuadGeneratorRadial = { } //all in if(fillRange >= Math.PI * 2) { - quads.push(this._generateTriangle(rawQuad, center, this._vertPos[triangle[0]], this._vertPos[triangle[1]],colorOpacity)); + this._generateTriangle(offset, center, this._vertPos[triangle[0]], this._vertPos[triangle[1]]); + offset += 6; + count += 3; continue; } //test against - var startAngle = this._getVertAngle(center,this._vertPos[triangle[0]]); - var endAngle = this._getVertAngle(center,this._vertPos[triangle[1]]); + var startAngle = this._getVertAngle(center, this._vertPos[triangle[0]]); + var endAngle = this._getVertAngle(center, this._vertPos[triangle[1]]); if(endAngle < startAngle) endAngle += Math.PI * 2; startAngle -= Math.PI * 2; endAngle -= Math.PI * 2; @@ -645,75 +710,82 @@ var fillQuadGeneratorRadial = { } else if (startAngle >= fillStart) { if(endAngle >= fillEnd) { //startAngle to fillEnd - quads.push(this._generateTriangle(rawQuad, center, this._vertPos[triangle[0]], this._intersectPoint_2[triangleIndex],colorOpacity)); + this._generateTriangle(offset, center, this._vertPos[triangle[0]], this._intersectPoint_2[triangleIndex]); } else { //startAngle to endAngle - quads.push(this._generateTriangle(rawQuad, center, this._vertPos[triangle[0]], this._vertPos[triangle[1]],colorOpacity)); + this._generateTriangle(offset, center, this._vertPos[triangle[0]], this._vertPos[triangle[1]]); } + offset += 6; + count += 3; } else { //startAngle < fillStart if(endAngle <= fillStart) { //all out } else if(endAngle <= fillEnd) { //fillStart to endAngle - quads.push(this._generateTriangle(rawQuad, center, this._intersectPoint_1[triangleIndex], this._vertPos[triangle[1]],colorOpacity)); + this._generateTriangle(offset, center, this._intersectPoint_1[triangleIndex], this._vertPos[triangle[1]]); + offset += 6; + count += 3; } else { //fillStart to fillEnd - quads.push(this._generateTriangle(rawQuad, center, this._intersectPoint_1[triangleIndex], this._intersectPoint_2[triangleIndex],colorOpacity)); + this._generateTriangle(offset, center, this._intersectPoint_1[triangleIndex], this._intersectPoint_2[triangleIndex]); + offset += 6; + count += 3; } } - //add 2 * PI startAngle += Math.PI * 2; endAngle += Math.PI * 2; } - } + sprite._vertCount = count; - var result = {}; - result.quad = quads; - result.rawQuad = rawQuad; - return result; - + cornerId[0] = 0; + cornerId[1] = 2; + cornerId[2] = 4; + cornerId[3] = 6; }, - _generateTriangle: function(rawQuad, vert0, vert1, vert2 , colorOpacity) { - var rawQuad_bl = rawQuad._bl; - var rawQuad_br = rawQuad._br; - var rawQuad_tl = rawQuad._tl; - var rawQuad_tr = rawQuad._tr; - - var v0x = rawQuad_bl.vertices.x; - var v0y = rawQuad_bl.vertices.y; - var v1x = rawQuad_tr.vertices.x; - var v1y = rawQuad_tr.vertices.y; + _generateTriangle: function(offset, vert0, vert1, vert2) { + var rawVerts = this.rawVerts; + var rawUvs = this.rawUvs; + var vertices = this.outVerts; + var v0x = rawVerts[0]; + var v0y = rawVerts[1]; + var v1x = rawVerts[6]; + var v1y = rawVerts[7]; var progressX, progressY; - var quad = cc.pool.getFromPool(cc.V3F_C4B_T2F_Quad) || new cc.V3F_C4B_T2F_Quad(); - quad._tl.vertices.x = vert0.x; - quad._tl.vertices.y = vert0.y; - - quad._bl.vertices.x = vert1.x; - quad._bl.vertices.y = vert1.y; - - quad._tr.vertices.x = vert2.x; - quad._tr.vertices.y = vert2.y; - quad._tl.colors = colorOpacity; - quad._bl.colors = colorOpacity; - quad._tr.colors = colorOpacity; + // tl: 0, 1 + // bl: 2, 3 + // tr: 4, 5 + vertices[offset] = vert0.x; + vertices[offset+1] = vert0.y; + vertices[offset+2] = vert1.x; + vertices[offset+3] = vert1.y; + vertices[offset+4] = vert2.x; + vertices[offset+5] = vert2.y; progressX = (vert0.x - v0x) / (v1x - v0x); progressY = (vert0.y - v0y) / (v1y - v0y); - this._generateUV(progressX, progressY, rawQuad_bl.texCoords,rawQuad_br.texCoords,rawQuad_tr.texCoords,rawQuad_tl.texCoords, quad._tl.texCoords); + this._generateUV(progressX, progressY, rawUvs, offset); progressX = (vert1.x - v0x) / (v1x - v0x); progressY = (vert1.y - v0y) / (v1y - v0y); - this._generateUV(progressX, progressY, rawQuad_bl.texCoords,rawQuad_br.texCoords,rawQuad_tr.texCoords,rawQuad_tl.texCoords,quad._bl.texCoords); + this._generateUV(progressX, progressY, rawUvs, offset + 2); progressX = (vert2.x - v0x) / (v1x - v0x); progressY = (vert2.y - v0y) / (v1y - v0y); - this._generateUV(progressX, progressY, rawQuad_bl.texCoords,rawQuad_br.texCoords,rawQuad_tr.texCoords,rawQuad_tl.texCoords,quad._tr.texCoords); + this._generateUV(progressX, progressY, rawUvs, offset + 4); + }, - return quad; + _generateUV : function(progressX, progressY, uvs, offset) { + var out = this.outUvs; + var px1 = uvs[0] + (uvs[2] - uvs[0]) * progressX; + var px2 = uvs[4] + (uvs[6] - uvs[4]) * progressX; + var py1 = uvs[1] + (uvs[3] - uvs[1]) * progressX; + var py2 = uvs[5] + (uvs[7] - uvs[5]) * progressX; + out[offset] = px1 + (px2 - px1) * progressY; + out[offset+1] = py1 + (py2 - py1) * progressY; }, _isAngleIn : function(angle, start, rangeAngle) { @@ -795,37 +867,31 @@ var fillQuadGeneratorRadial = { return result; }, - _generateUV : function(progressX, progressY, uvbl, uvbr, uvtr, uvtl, result) { - var px1 = uvbl.u + (uvbr.u-uvbl.u) * progressX; - var px2 = uvtl.u + (uvtr.u-uvtl.u) * progressX; - var py1 = uvbl.v + (uvbr.v-uvbl.v) * progressX; - var py2 = uvtl.v + (uvtr.v-uvtl.v) * progressX; - result.u = px1 + (px2 - px1) * progressY; - result.v = py1 + (py2 - py1) * progressY; - }, - - - _calculateVertices : function (spriteFrame, contentSize) { - - var x0,x3; - var y0,y3; + _calculateVertices : function (wt, spriteFrame, contentSize) { + var x0, x3, y0, y3; x0 = 0; - x3 = contentSize.width; - y0 = 0; + x3 = contentSize.width; y3 = contentSize.height; - this._vertices[0].x = x0; - this._vertices[0].y = y0; - this._vertices[1].x = x3; - this._vertices[1].y = y3; + if (webgl) { + this._vertices[0].x = x0 * wt.a + y0 * wt.c + wt.tx; + this._vertices[0].y = x0 * wt.b + y0 * wt.d + wt.ty; + this._vertices[1].x = x3 * wt.a + y3 * wt.c + wt.tx; + this._vertices[1].y = x3 * wt.b + y3 * wt.d + wt.ty; + } + else { + this._vertices[0].x = x0; + this._vertices[0].y = y0; + this._vertices[1].x = x3; + this._vertices[1].y = y3; + } }, _calculateUVs : function (spriteFrame) { var atlasWidth = spriteFrame._texture.getPixelWidth(); var atlasHeight = spriteFrame._texture.getPixelHeight(); - - var textureRect = spriteFrame.getRect(); + var textureRect = spriteFrame._rect; //uv computation should take spritesheet into account. var u0, u3; @@ -850,7 +916,6 @@ var fillQuadGeneratorRadial = { this._uvs[0].y = v3; this._uvs[1].x = u3; this._uvs[1].y = v0; - } }; @@ -869,10 +934,13 @@ cc.Scale9Sprite = _ccsg.Node.extend({ _renderingType: 1, //bright or not _brightState: 0, - //rendering quads - _quads: [], + //rendering quads shared by canvas and webgl + _rawVerts: null, + _rawUvs: null, + _vertices: null, + _uvs: null, + _vertCount: 0, _quadsDirty: true, - _rawQuad: null, _isTriangle: false, _isTrimmedContentSize: true, //fill type @@ -891,7 +959,12 @@ cc.Scale9Sprite = _ccsg.Node.extend({ this._blendFunc = cc.BlendFunc._alphaNonPremultiplied(); this._fillCenter = cc.v2(0,0); this.setAnchorPoint(cc.p(0.5, 0.5)); - // + // Init vertex data for simple + this._rawVerts = null; + this._rawUvs = null; + this._vertices = dataPool.get(8) || new Float32Array(8); + this._uvs = dataPool.get(8) || new Float32Array(8); + // Init sprite frame if (typeof textureOrSpriteFrame === 'string') { var frame = cc.spriteFrameCache.getSpriteFrame(textureOrSpriteFrame); if (frame) { @@ -905,6 +978,14 @@ cc.Scale9Sprite = _ccsg.Node.extend({ else if (textureOrSpriteFrame instanceof cc.Texture2D) { this.initWithTexture(textureOrSpriteFrame); } + + if (webgl === undefined) { + webgl = cc._renderType === cc.game.RENDER_TYPE_WEBGL; + vl = cc.visibleRect.left; + vr = cc.visibleRect.right; + vt = cc.visibleRect.top; + vb = cc.visibleRect.bottom; + } }, loaded: function () { @@ -959,11 +1040,13 @@ cc.Scale9Sprite = _ccsg.Node.extend({ if (spriteFrame) { this._spriteFrame = spriteFrame; this._quadsDirty = true; + this._renderCmd._needDraw = false; var self = this; var onResourceDataLoaded = function () { if (cc.sizeEqualToSize(self._contentSize, cc.size(0, 0))) { - self.setContentSize(self._spriteFrame.getRect()); + self.setContentSize(self._spriteFrame._rect); } + self._renderCmd._needDraw = true; self._renderCmd.setDirtyFlag(_ccsg.Node._dirtyFlags.contentDirty); }; if (spriteFrame.textureLoaded()) { @@ -1144,7 +1227,7 @@ cc.Scale9Sprite = _ccsg.Node.extend({ }, setDistortionTiling: function(valueOrX, y) { - if(y == undefined) { + if(y === undefined) { y = valueOrX.y; valueOrX = valueOrX.x; } @@ -1154,7 +1237,7 @@ cc.Scale9Sprite = _ccsg.Node.extend({ }, setDistortionOffset: function(valueOrX, y) { - if(y == undefined) { + if(y === undefined) { y = valueOrX.y; valueOrX = valueOrX.x; } @@ -1193,38 +1276,22 @@ cc.Scale9Sprite = _ccsg.Node.extend({ return this._fillRange; }, - _onColorOpacityDirty: function () { - var color = this.getDisplayedColor(); - color.a = this.getDisplayedOpacity(); - var index; - var quadLength = this._quads.length; - for (index = 0; index < quadLength; ++index) { - //svar quad = this._quads[index]; - this._quads[index]._bl.colors = color; - this._quads[index]._br.colors = color; - this._quads[index]._tl.colors = color; - this._quads[index]._tr.colors = color; - } - }, - _rebuildQuads: function () { - if (!this.loaded() || this._quadsDirty === false) return; - //put quads back - for(var quadIndex = 0; quadIndex < this._quads.length; ++quadIndex) { - cc.pool.putInPool(this._quads[quadIndex]); + if (!this._spriteFrame || !this._spriteFrame._textureLoaded) { + this._renderCmd._needDraw = false; + return; } - this._rawQuad && cc.pool.putInPool(this._rawQuad); - this._rawQuad = null; - this._quads = []; - var color = this.getDisplayedColor(); - color.a = this.getDisplayedOpacity(); this._isTriangle = false; + var vert; if (this._renderingType === cc.Scale9Sprite.RenderingType.SIMPLE) { - this._quads = simpleQuadGenerator._rebuildQuads_base(this._spriteFrame, this.getContentSize(), color, this._isTrimmedContentSize); + simpleQuadGenerator._rebuildQuads_base(this, this._spriteFrame, this.getContentSize(), this._isTrimmedContentSize); + vert = this._vertices; } else if (this._renderingType === cc.Scale9Sprite.RenderingType.SLICED) { - this._quads = scale9QuadGenerator._rebuildQuads_base(this._spriteFrame, this.getContentSize(), color, this._insetLeft, this._insetRight, this._insetTop, this._insetBottom); + scale9QuadGenerator._rebuildQuads_base(this, this._spriteFrame, this.getContentSize(), this._insetLeft, this._insetRight, this._insetTop, this._insetBottom); + vert = this._vertices; } else if (this._renderingType === cc.Scale9Sprite.RenderingType.TILED) { - this._quads = tiledQuadGenerator._rebuildQuads_base(this._spriteFrame, this.getContentSize(), color); + tiledQuadGenerator._rebuildQuads_base(this, this._spriteFrame, this.getContentSize()); + vert = this._vertices; } else if (this._renderingType === cc.Scale9Sprite.RenderingType.FILLED) { var fillstart = this._fillStart; var fillRange = this._fillRange; @@ -1232,7 +1299,7 @@ cc.Scale9Sprite = _ccsg.Node.extend({ fillstart += fillRange; fillRange = -fillRange; } - if(this._fillType !== cc.Scale9Sprite.FillType.RADIAL) { + if (this._fillType !== cc.Scale9Sprite.FillType.RADIAL) { fillRange = fillstart + fillRange; fillstart = fillstart > 1.0 ? 1.0 : fillstart; fillstart = fillstart < 0.0 ? 0.0 : fillstart; @@ -1240,17 +1307,51 @@ cc.Scale9Sprite = _ccsg.Node.extend({ fillRange = fillRange > 1.0 ? 1.0 : fillRange; fillRange = fillRange < 0.0 ? 0.0 : fillRange; fillRange = fillRange - fillstart; - this._quads = fillQuadGeneratorBar._rebuildQuads_base(this._spriteFrame, this.getContentSize(), color, this._fillType, fillstart,fillRange); + fillQuadGeneratorBar._rebuildQuads_base(this, this._spriteFrame, this.getContentSize(), this._fillType, fillstart, fillRange); + vert = this._vertices; } else { this._isTriangle = true; - var fillResult = fillQuadGeneratorRadial._rebuildQuads_base(this._spriteFrame, this.getContentSize(), color,this._fillCenter,fillstart,fillRange); - this._quads = fillResult.quad; - this._rawQuad = fillResult.rawQuad; + if (!this._rawVerts) { + this._rawVerts = dataPool.get(8) || new Float32Array(8); + this._rawUvs = dataPool.get(8) || new Float32Array(8); + } + fillQuadGeneratorRadial._rebuildQuads_base(this, this._spriteFrame, this.getContentSize(), this._fillCenter,fillstart, fillRange); + vert = this._rawVerts; } } else { this._quads = []; - cc.error("Can not generate quad"); + this._quadsDirty = false; + this._renderCmd._needDraw = false; + cc.error('Can not generate quad'); + return; } + + // Culling + if (webgl) { + var x0 = cornerId[0], x1 = cornerId[1], x2 = cornerId[2], x3 = cornerId[3], + y0 = cornerId[0]+1, y1 = cornerId[1]+1, y2 = cornerId[2]+1, y3 = cornerId[3]+1; + if (((vert[x0]-vl.x) & (vert[x1]-vl.x) & (vert[x2]-vl.x) & (vert[x3]-vl.x)) >> 31 || // All outside left + ((vr.x-vert[x0]) & (vr.x-vert[x1]) & (vr.x-vert[x2]) & (vr.x-vert[x3])) >> 31 || // All outside right + ((vert[y0]-vb.y) & (vert[y1]-vb.y) & (vert[y2]-vb.y) & (vert[y3]-vb.y)) >> 31 || // All outside bottom + ((vt.y-vert[y0]) & (vt.y-vert[y1]) & (vt.y-vert[y2]) & (vt.y-vert[y3])) >> 31) // All outside top + { + this._renderCmd._needDraw = false; + } + else { + this._renderCmd._needDraw = true; + } + } + else { + var bb = this._renderCmd._currentRegion, + l = bb._minX, r = bb._maxX, b = bb._minY, t = bb._maxY; + if (r < vl.x || l > vr.x || t < vb.y || b > vt.y) { + this._renderCmd._needDraw = false; + } + else { + this._renderCmd._needDraw = true; + } + } + this._quadsDirty = false; }, _createRenderCmd: function () { @@ -1265,20 +1366,10 @@ cc.Scale9Sprite = _ccsg.Node.extend({ var _p = cc.Scale9Sprite.prototype; cc.js.addon(_p, EventTarget.prototype); // Extended properties -/** @expose */ -_p.insetLeft; -cc.defineGetterSetter(_p, "insetLeft", _p.getInsetLeft, _p.setInsetLeft); -/** @expose */ -_p.insetTop; -cc.defineGetterSetter(_p, "insetTop", _p.getInsetTop, _p.setInsetTop); -/** @expose */ -_p.insetRight; -cc.defineGetterSetter(_p, "insetRight", _p.getInsetRight, _p.setInsetRight); -/** @expose */ -_p.insetBottom; -cc.defineGetterSetter(_p, "insetBottom", _p.getInsetBottom, _p.setInsetBottom); - -_p = null; +cc.defineGetterSetter(_p, 'insetLeft', _p.getInsetLeft, _p.setInsetLeft); +cc.defineGetterSetter(_p, 'insetTop', _p.getInsetTop, _p.setInsetTop); +cc.defineGetterSetter(_p, 'insetRight', _p.getInsetRight, _p.setInsetRight); +cc.defineGetterSetter(_p, 'insetBottom', _p.getInsetBottom, _p.setInsetBottom); cc.Scale9Sprite.state = {NORMAL: 0, GRAY: 1, DISTORTION: 2}; diff --git a/cocos2d/core/sprites/CCScale9SpriteCanvasRenderCmd.js b/cocos2d/core/sprites/CCScale9SpriteCanvasRenderCmd.js index 12b9ba2cb2..13108acd3a 100644 --- a/cocos2d/core/sprites/CCScale9SpriteCanvasRenderCmd.js +++ b/cocos2d/core/sprites/CCScale9SpriteCanvasRenderCmd.js @@ -1,5 +1,5 @@ /**************************************************************************** - Copyright (c) 2013-2014 Chukong Technologies Inc. + Copyright (c) 2016 Chukong Technologies Inc. http://www.cocos2d-x.org @@ -24,7 +24,12 @@ cc.Scale9Sprite.CanvasRenderCmd = function (renderable) { _ccsg.Node.CanvasRenderCmd.call(this, renderable); - this._needDraw = true; + if (this._node.loaded()) { + this._needDraw = true; + } + else { + this._needDraw = false; + } this._state = cc.Scale9Sprite.state.NORMAL; this._originalTexture = this._textureToRender = null; }; @@ -32,13 +37,13 @@ cc.Scale9Sprite.CanvasRenderCmd = function (renderable) { var proto = cc.Scale9Sprite.CanvasRenderCmd.prototype = Object.create(_ccsg.Node.CanvasRenderCmd.prototype); proto.constructor = cc.Scale9Sprite.CanvasRenderCmd; -proto._updateDisplayOpacity = function(parentOpacity){ - _ccsg.Node.WebGLRenderCmd.prototype._updateDisplayOpacity.call(this, parentOpacity); +proto.transform = function (parentCmd, recursive) { + this.originTransform(parentCmd, recursive); + this._node._rebuildQuads(); }; proto._updateDisplayColor = function(parentColor){ _ccsg.Node.WebGLRenderCmd.prototype._updateDisplayColor.call(this, parentColor); - var node = this._node; this._originalTexture = this._textureToRender = null; }; @@ -54,16 +59,16 @@ proto.rendering = function (ctx, scaleX, scaleY) { var locDisplayOpacity = this._displayedOpacity; var alpha = locDisplayOpacity/ 255; var locTexture = null; - if(node._spriteFrame) locTexture = node._spriteFrame._texture; + if (node._spriteFrame) locTexture = node._spriteFrame._texture; if (!node.loaded() || locDisplayOpacity === 0) return; - if(this._textureToRender === null || this._originalTexture !== locTexture){ + if (this._textureToRender === null || this._originalTexture !== locTexture) { this._textureToRender = this._originalTexture = locTexture; if (cc.Scale9Sprite.state.GRAY === this._state) { this._textureToRender = this._textureToRender._generateGrayTexture(); } var color = node.getDisplayedColor(); - if(locTexture && (color.r !== 255 || color.g !==255 || color.b !== 255)) + if (locTexture && (color.r !== 255 || color.g !==255 || color.b !== 255)) this._textureToRender = this._textureToRender._generateColorTexture(color.r,color.g,color.b); } @@ -72,8 +77,8 @@ proto.rendering = function (ctx, scaleX, scaleY) { wrapper.setCompositeOperation(_ccsg.Node.CanvasRenderCmd._getCompositeOperationByBlendFunc(node._blendFunc)); wrapper.setGlobalAlpha(alpha); - if(this._textureToRender) { - if(node._quadsDirty){ + if (this._textureToRender) { + if (node._quadsDirty) { node._rebuildQuads(); } var sx,sy,sw,sh; @@ -81,19 +86,22 @@ proto.rendering = function (ctx, scaleX, scaleY) { var textureWidth = this._textureToRender.getPixelWidth(); var textureHeight = this._textureToRender.getPixelHeight(); var image = this._textureToRender._htmlElementObj; + var vertices = node._vertices; + var uvs = node._uvs; + var i = 0, off = 0; - if(node._isTriangle) { - var rawQuad = node._rawQuad; - x = rawQuad._bl.vertices.x; - y = rawQuad._bl.vertices.y; - w = rawQuad._tr.vertices.x - rawQuad._bl.vertices.x; - h = rawQuad._tr.vertices.y - rawQuad._bl.vertices.y; + if (node._isTriangle) { + var rawVerts = node._rawVerts, rawUvs = node._rawUvs; + x = rawVerts[0]; + y = rawVerts[1]; + w = rawVerts[6] - x; + h = rawVerts[7] - y; y = - y - h; - sx = rawQuad._tl.texCoords.u * textureWidth; - sy = rawQuad._tl.texCoords.v * textureHeight; - sw = (rawQuad._tr.texCoords.u - rawQuad._bl.texCoords.u) * textureWidth; - sh = (rawQuad._bl.texCoords.v - rawQuad._tr.texCoords.v) * textureHeight; + sx = rawUvs[4] * textureWidth; + sy = rawUvs[5] * textureHeight; + sw = (rawUvs[6] - rawUvs[0]) * textureWidth; + sh = (rawUvs[1] - rawUvs[7]) * textureHeight; x = x * scaleX; y = y * scaleY; @@ -102,20 +110,21 @@ proto.rendering = function (ctx, scaleX, scaleY) { wrapper.save(); context.beginPath(); + var triangleCount = Math.floor(node._vertCount / 3); - var quads = node._quads; - for( var i = 0; i < quads.length; ++i) { - context.moveTo(quads[i]._tl.vertices.x * scaleX, -quads[i]._tl.vertices.y * scaleY); - context.lineTo(quads[i]._bl.vertices.x * scaleX, -quads[i]._bl.vertices.y * scaleY); - context.lineTo(quads[i]._tr.vertices.x * scaleX, -quads[i]._tr.vertices.y * scaleY); + for (i = 0, off = 0; i < triangleCount; i++) { + context.moveTo(vertices[off++] * scaleX, -vertices[off++] * scaleY); + context.lineTo(vertices[off++] * scaleX, -vertices[off++] * scaleY); + context.lineTo(vertices[off++] * scaleX, -vertices[off++] * scaleY); } context.clip(); - if (this._textureToRender._pattern !== "") { + if (this._textureToRender._pattern !== '') { wrapper.setFillStyle(context.createPattern(image, this._textureToRender._pattern)); context.fillRect(x, y, w, h); - } else { - if(sw !== 0 && sh !== 0 && w !== 0 && h !== 0) { + } + else { + if (sw > 0 && sh > 0 && w > 0 && h > 0) { context.drawImage(image, sx, sy, sw, sh, x, y, w, h); @@ -123,40 +132,69 @@ proto.rendering = function (ctx, scaleX, scaleY) { } wrapper.restore(); + cc.g_NumberOfDraws += triangleCount; + } + else if (node._renderingType === cc.Scale9Sprite.RenderingType.SLICED) { + // Sliced use a special vertices layout 16 vertices for 9 quads + for (var r = 0; r < 3; ++r) { + for (var c = 0; c < 3; ++c) { + off = r*8 + c*2; + x = vertices[off]; + y = vertices[off+1]; + w = vertices[off+10] - x; + h = vertices[off+11] - y; + y = - y - h; + x = x * scaleX; + y = y * scaleY; + w = w * scaleX; + h = h * scaleY; - } else { - var quads = node._quads; - for( var i = 0; i < quads.length; ++i) - { - x = quads[i]._bl.vertices.x; - y = quads[i]._bl.vertices.y; - w = quads[i]._tr.vertices.x - quads[i]._bl.vertices.x; - h = quads[i]._tr.vertices.y - quads[i]._bl.vertices.y; - y = - y - h; + sx = uvs[off] * textureWidth; + sy = uvs[off+11] * textureHeight; + sw = (uvs[off+10] - uvs[off]) * textureWidth; + sh = (uvs[off+1] - uvs[off+11]) * textureHeight; - sx = quads[i]._tl.texCoords.u * textureWidth; - sy = quads[i]._tl.texCoords.v * textureHeight; - sw = (quads[i]._tr.texCoords.u - quads[i]._bl.texCoords.u) * textureWidth; - sh = (quads[i]._bl.texCoords.v - quads[i]._tr.texCoords.v) * textureHeight; - - x = x * scaleX; - y = y * scaleY; - w = w * scaleX; - h = h * scaleY; - - if (this._textureToRender._pattern !== "") { - wrapper.setFillStyle(context.createPattern(image, this._textureToRender._pattern)); - context.fillRect(x, y, w, h); - } else { - if(sw !== 0 && sh !== 0 && w !== 0 && h !== 0) { + if (sw > 0 && sh > 0 && w > 0 && h > 0) { context.drawImage(image, sx, sy, sw, sh, x, y, w, h); } } } + cc.g_NumberOfDraws += 9; + } + else { + var quadCount = Math.floor(node._vertCount / 4); + for (i = 0, off = 0; i < quadCount; i++) { + x = vertices[off]; + y = vertices[off+1]; + w = vertices[off+6] - x; + h = vertices[off+7] - y; + y = - y - h; + sx = uvs[off] * textureWidth; + sy = uvs[off+7] * textureHeight; + sw = (uvs[off+6] - uvs[off]) * textureWidth; + sh = (uvs[off+1] - uvs[off+7]) * textureHeight; + + x = x * scaleX; + y = y * scaleY; + w = w * scaleX; + h = h * scaleY; + + if (this._textureToRender._pattern !== '') { + wrapper.setFillStyle(context.createPattern(image, this._textureToRender._pattern)); + context.fillRect(x, y, w, h); + } else { + if (sw > 0 && sh > 0 && w > 0 && h > 0) { + context.drawImage(image, + sx, sy, sw, sh, + x, y, w, h); + } + } + off += 8; + } + cc.g_NumberOfDraws += quadCount; } - } - cc.g_NumberOfDraws += quads.length; -} + } +}; diff --git a/cocos2d/core/sprites/CCScale9SpriteWebGLRenderCmd.js b/cocos2d/core/sprites/CCScale9SpriteWebGLRenderCmd.js index dea7127439..d34298c50c 100644 --- a/cocos2d/core/sprites/CCScale9SpriteWebGLRenderCmd.js +++ b/cocos2d/core/sprites/CCScale9SpriteWebGLRenderCmd.js @@ -1,5 +1,5 @@ /**************************************************************************** - Copyright (c) 2013-2014 Chukong Technologies Inc. + Copyright (c) 2016 Chukong Technologies Inc. http://www.cocos2d-x.org @@ -24,196 +24,210 @@ var ccgl = cc.gl; -if (_ccsg.Node.WebGLRenderCmd) { - cc.Scale9Sprite.WebGLRenderCmd = function (renderable) { - _ccsg.Node.WebGLRenderCmd.call(this, renderable); +cc.Scale9Sprite.WebGLRenderCmd = function (renderable) { + _ccsg.Node.WebGLRenderCmd.call(this, renderable); + if (this._node.loaded()) { this._needDraw = true; - this._cachedParent = null; - this._cacheDirty = false; - this._quadWebBuffer = cc._renderContext.createBuffer(); - this._quadIndexBuffer = cc._renderContext.createBuffer(); - this._indices = new Int16Array(54); - this._colorOpacityDirty = false; - }; + } + else { + this._needDraw = false; + } - var proto = cc.Scale9Sprite.WebGLRenderCmd.prototype = Object.create(_ccsg.Node.WebGLRenderCmd.prototype); - proto.constructor = cc.Scale9Sprite.WebGLRenderCmd; + this.vertexType = cc.renderer.VertexType.QUAD; + this._color = new Uint32Array(1); + this._dirty = false; + this._shaderProgram = cc.shaderCache.programForKey(cc.macro.SHADER_SPRITE_POSITION_TEXTURECOLOR); +}; - proto.rendering = function (ctx){ - var node = this._node; +var proto = cc.Scale9Sprite.WebGLRenderCmd.prototype = Object.create(_ccsg.Node.WebGLRenderCmd.prototype); +proto.constructor = cc.Scale9Sprite.WebGLRenderCmd; - var locTexture = null; - if(node._spriteFrame) locTexture = node._spriteFrame._texture; - if (!node.loaded() || this._displayedOpacity === 0) - return; - var needRebuildWebBuffer = false; - - if(node._quadsDirty){ - node._rebuildQuads(); - this._colorOpacityDirty = false; - needRebuildWebBuffer = true; +proto._uploadSliced = function (vertices, uvs, color, z, f32buffer, ui32buffer, offset) { + var off; + for (var r = 0; r < 3; ++r) { + for (var c = 0; c < 3; ++c) { + off = r*8 + c*2; + // lb + f32buffer[offset] = vertices[off]; + f32buffer[offset+1] = vertices[off+1]; + f32buffer[offset+2] = z; + ui32buffer[offset+3] = color[0]; + f32buffer[offset+4] = uvs[off]; + f32buffer[offset+5] = uvs[off+1]; + offset += 6; + // rb + f32buffer[offset] = vertices[off+2]; + f32buffer[offset + 1] = vertices[off+3]; + f32buffer[offset + 2] = z; + ui32buffer[offset + 3] = color[0]; + f32buffer[offset + 4] = uvs[off+2]; + f32buffer[offset + 5] = uvs[off+3]; + offset += 6; + // lt + f32buffer[offset] = vertices[off+8]; + f32buffer[offset + 1] = vertices[off+9]; + f32buffer[offset + 2] = z; + ui32buffer[offset + 3] = color[0]; + f32buffer[offset + 4] = uvs[off+8]; + f32buffer[offset + 5] = uvs[off+9]; + offset += 6; + // rt + f32buffer[offset] = vertices[off+10]; + f32buffer[offset + 1] = vertices[off+11]; + f32buffer[offset + 2] = z; + ui32buffer[offset + 3] = color[0]; + f32buffer[offset + 4] = uvs[off+10]; + f32buffer[offset + 5] = uvs[off+11]; + offset += 6; } - if(this._colorOpacityDirty) { - node._onColorOpacityDirty(); - this._colorOpacityDirty = false; - needRebuildWebBuffer = true; - } - var gl = ctx || cc._renderContext ; + } + return 36; +}; - if(locTexture != null) - { - this._shaderProgram.use(); - this._shaderProgram._setUniformForMVPMatrixWithMat4(this._stackMatrix); - if(this._shaderProgram === cc.Scale9Sprite.WebGLRenderCmd._distortionProgram && this._node._distortionOffset) { - this._shaderProgram.setUniformLocationWith2f( - cc.Scale9Sprite.WebGLRenderCmd._distortionOffset, - this._node._distortionOffset.x, this._node._distortionOffset.y - ); - this._shaderProgram.setUniformLocationWith2f( - cc.Scale9Sprite.WebGLRenderCmd._distortionTiling, - this._node._distortionTiling.x, this._node._distortionTiling.y - ); - } - ccgl.blendFunc(node._blendFunc.src, node._blendFunc.dst); - //optimize performance for javascript - ccgl.bindTexture2DN(0, locTexture); // = cc.gl.bindTexture2D(locTexture); - ccgl.enableVertexAttribs(cc.macro.VERTEX_ATTRIB_FLAG_POS_COLOR_TEX); +proto._uploadVertices = function (vertices, uvs, color, z, f32buffer, ui32buffer, offset) { + // src: bl, br, tl, tr + var count = this._node._vertCount; + for (var i = 0, srcOff = 0; i < count; i++, srcOff += 2) { + f32buffer[offset] = vertices[srcOff]; + f32buffer[offset + 1] = vertices[srcOff+1]; + f32buffer[offset + 2] = z; + ui32buffer[offset + 3] = color[0]; + f32buffer[offset + 4] = uvs[srcOff]; + f32buffer[offset + 5] = uvs[srcOff+1]; + offset += 6; + } + return count; +}; - gl.bindBuffer(gl.ARRAY_BUFFER, this._quadWebBuffer); - gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._quadIndexBuffer); - var quads = node._quads; - var bufferOffset = 0; - var quadsLength = quads.length; - var requiredIndicesLength = quadsLength * (node._isTriangle ? 3 : 6); - if (quadsLength === 0) return; - if (needRebuildWebBuffer) - { - //reallocate indices if indices is not enought or is too big - var indices = this._indices; - if((indices.length < requiredIndicesLength) || (indices.length > requiredIndicesLength + 128)) { - indices = this._indices = new Int16Array(requiredIndicesLength + 64); - } +proto.transform = function (parentCmd, recursive) { + this.originTransform(parentCmd, recursive); + this._node._rebuildQuads(); +}; - var indiceIndex = 0; - gl.bufferData(gl.ARRAY_BUFFER,quads[0].arrayBuffer.byteLength * quads.length, gl.DYNAMIC_DRAW); - for(var i = 0; i < quads.length; ++i) { - gl.bufferSubData(gl.ARRAY_BUFFER, bufferOffset,quads[i].arrayBuffer); - bufferOffset = bufferOffset + quads[i].arrayBuffer.byteLength; - if(node._isTriangle === true) { - indices[indiceIndex] = i * 4; - indices[indiceIndex+1] = i * 4 + 1; - indices[indiceIndex+2] = i * 4 + 2; - indiceIndex += 3; - } else { - indices[indiceIndex] = i * 4; - indices[indiceIndex+1] = i * 4 + 1; - indices[indiceIndex+2] = i * 4 + 2; - indices[indiceIndex+3] = i * 4 + 3; - indices[indiceIndex+4] = i * 4 + 2; - indices[indiceIndex+5] = i * 4 + 1; - indiceIndex += 6; - } - } - gl.bufferData(gl.ELEMENT_ARRAY_BUFFER,indices, gl.DYNAMIC_DRAW); +proto.uploadData = function (f32buffer, ui32buffer, vertexDataOffset){ + var node = this._node; + if (!node._spriteFrame || !node._spriteFrame.textureLoaded() || this._displayedOpacity === 0) { + return 0; + } - } - gl.vertexAttribPointer(0, 3, gl.FLOAT, false, 24, 0); //cc.macro.VERTEX_ATTRIB_POSITION - gl.vertexAttribPointer(1, 4, gl.UNSIGNED_BYTE, true, 24, 12); //cc.macro.VERTEX_ATTRIB_COLOR - gl.vertexAttribPointer(2, 2, gl.FLOAT, false, 24, 16); //cc.macro.VERTEX_ATTRIB_TEX_COORDS + // Rebuild vertex data + if (node._quadsDirty) { + node._rebuildQuads(); + } - gl.drawElements(gl.TRIANGLES, (node._isTriangle ? 3 : 6) * quadsLength,gl.UNSIGNED_SHORT,0); + // this._shaderProgram.use(); + if (this._shaderProgram === cc.Scale9Sprite.WebGLRenderCmd._distortionProgram && this._node._distortionOffset) { + this._shaderProgram.setUniformLocationWith2f( + cc.Scale9Sprite.WebGLRenderCmd._distortionOffset, + this._node._distortionOffset.x, this._node._distortionOffset.y + ); + this._shaderProgram.setUniformLocationWith2f( + cc.Scale9Sprite.WebGLRenderCmd._distortionTiling, + this._node._distortionTiling.x, this._node._distortionTiling.y + ); + } + // Color & z + var opacity = this._displayedOpacity; + var r = this._displayedColor.r, + g = this._displayedColor.g, + b = this._displayedColor.b; + if (node._opacityModifyRGB) { + var a = opacity / 255; + r *= a; + g *= a; + b *= a; + } + this._color[0] = ((opacity<<24) | (b<<16) | (g<<8) | r); + var z = node._vertexZ; - cc.g_NumberOfDraws += 1; + // Upload data + var vertices = node._vertices; + var uvs = node._uvs; + var types = cc.Scale9Sprite.RenderingType; + var offset = vertexDataOffset; + var len = 0; + switch (node._renderingType) { + case types.SIMPLE: + case types.TILED: + case types.FILLED: + len = this._uploadVertices(vertices, uvs, this._color, z, f32buffer, ui32buffer, offset); + break; + case types.SLICED: + len = this._uploadSliced(vertices, uvs, this._color, z, f32buffer, ui32buffer, offset); + break; + } + if (node._renderingType === types.FILLED && node._fillType === cc.Scale9Sprite.FillType.RADIAL) { + this.vertexType = cc.renderer.VertexType.TRIANGLE; + } + else { + this.vertexType = cc.renderer.VertexType.QUAD; + } + return len; +}; - } +proto.setState = function (state) { + if (state === cc.Scale9Sprite.state.NORMAL) { + this._shaderProgram = cc.shaderCache.programForKey(cc.macro.SHADER_SPRITE_POSITION_TEXTURECOLOR); + } else if (state === cc.Scale9Sprite.state.GRAY) { + this._shaderProgram = cc.Scale9Sprite.WebGLRenderCmd._getGrayShaderProgram(); + } else if (state === cc.Scale9Sprite.state.DISTORTION) { + this._shaderProgram = cc.Scale9Sprite.WebGLRenderCmd._getDistortionProgram(); + } +}; - }; - - proto._syncDisplayOpacity = function (parentOpacity) { - _ccsg.Node.WebGLRenderCmd.prototype._syncDisplayOpacity.call(this, parentOpacity); - this._colorOpacityDirty = true; - }; - - proto._updateDisplayOpacity = function(parentOpacity){ - _ccsg.Node.WebGLRenderCmd.prototype._updateDisplayOpacity.call(this, parentOpacity); - this._colorOpacityDirty = true; - }; - - proto._syncDisplayColor = function (parentColor) { - _ccsg.Node.WebGLRenderCmd.prototype._syncDisplayColor.call(this, parentColor); - this._colorOpacityDirty = true; - }; - - proto._updateDisplayColor = function(parentColor){ - _ccsg.Node.WebGLRenderCmd.prototype._updateDisplayColor.call(this, parentColor); - this._colorOpacityDirty = true; - }; - - proto.setState = function (state) { - var node = this._node; - if (state === cc.Scale9Sprite.state.NORMAL) { - node.setShaderProgram(cc.shaderCache.programForKey(cc.macro.SHADER_POSITION_TEXTURECOLOR)); - } else if (state === cc.Scale9Sprite.state.GRAY) { - node.setShaderProgram(cc.Scale9Sprite.WebGLRenderCmd._getGrayShaderProgram()); - } else if (state === cc.Scale9Sprite.state.DISTORTION) { - node.setShaderProgram(cc.Scale9Sprite.WebGLRenderCmd._getDistortionProgram()); - } - }; - - cc.Scale9Sprite.WebGLRenderCmd._grayShaderProgram = null; - cc.Scale9Sprite.WebGLRenderCmd._getGrayShaderProgram = function(){ - var grayShader = cc.Scale9Sprite.WebGLRenderCmd._grayShaderProgram; - if(grayShader) - return grayShader; - - grayShader = new cc.GLProgram(); - grayShader.initWithVertexShaderByteArray(cc.PresetShaders.POSITION_TEXTURE_COLOR_VERT, cc.Scale9Sprite.WebGLRenderCmd._grayShaderFragment); - grayShader.addAttribute(cc.macro.ATTRIBUTE_NAME_POSITION, cc.macro.VERTEX_ATTRIB_POSITION); - grayShader.addAttribute(cc.macro.ATTRIBUTE_NAME_COLOR, cc.macro.VERTEX_ATTRIB_COLOR); - grayShader.addAttribute(cc.macro.ATTRIBUTE_NAME_TEX_COORD, cc.macro.VERTEX_ATTRIB_TEX_COORDS); - grayShader.link(); - grayShader.updateUniforms(); - - cc.Scale9Sprite.WebGLRenderCmd._grayShaderProgram = grayShader; +cc.Scale9Sprite.WebGLRenderCmd._grayShaderProgram = null; +cc.Scale9Sprite.WebGLRenderCmd._getGrayShaderProgram = function(){ + var grayShader = cc.Scale9Sprite.WebGLRenderCmd._grayShaderProgram; + if (grayShader) return grayShader; - }; - cc.Scale9Sprite.WebGLRenderCmd._grayShaderFragment = - "precision lowp float;\n" - + "varying vec4 v_fragmentColor; \n" - + "varying vec2 v_texCoord; \n" - + "void main() \n" - + "{ \n" - + " vec4 c = texture2D(CC_Texture0, v_texCoord); \n" - + " gl_FragColor.xyz = vec3(0.2126*c.r + 0.7152*c.g + 0.0722*c.b); \n" - +" gl_FragColor.w = c.w ; \n" - + "}"; + grayShader = new cc.GLProgram(); + grayShader.initWithVertexShaderByteArray(cc.PresetShaders.SPRITE_POSITION_TEXTURE_COLOR_VERT, cc.Scale9Sprite.WebGLRenderCmd._grayShaderFragment); + grayShader.addAttribute(cc.macro.ATTRIBUTE_NAME_POSITION, cc.macro.VERTEX_ATTRIB_POSITION); + grayShader.addAttribute(cc.macro.ATTRIBUTE_NAME_COLOR, cc.macro.VERTEX_ATTRIB_COLOR); + grayShader.addAttribute(cc.macro.ATTRIBUTE_NAME_TEX_COORD, cc.macro.VERTEX_ATTRIB_TEX_COORDS); + grayShader.link(); + grayShader.updateUniforms(); - cc.Scale9Sprite.WebGLRenderCmd._distortionProgram = null; - cc.Scale9Sprite.WebGLRenderCmd._getDistortionProgram = function(){ - var shader = cc.Scale9Sprite.WebGLRenderCmd._distortionProgram; - if(shader) - return shader; + cc.Scale9Sprite.WebGLRenderCmd._grayShaderProgram = grayShader; + return grayShader; +}; - shader = new cc.GLProgram(); - shader.initWithVertexShaderByteArray(cc.PresetShaders.POSITION_TEXTURE_COLOR_VERT, distortionSpriteShader.fShader); - shader.addAttribute(cc.macro.ATTRIBUTE_NAME_POSITION, cc.macro.VERTEX_ATTRIB_POSITION); - shader.addAttribute(cc.macro.ATTRIBUTE_NAME_COLOR, cc.macro.VERTEX_ATTRIB_COLOR); - shader.addAttribute(cc.macro.ATTRIBUTE_NAME_TEX_COORD, cc.macro.VERTEX_ATTRIB_TEX_COORDS); - shader.link(); - shader.updateUniforms(); +cc.Scale9Sprite.WebGLRenderCmd._grayShaderFragment = + "precision lowp float;\n" + + "varying vec4 v_fragmentColor; \n" + + "varying vec2 v_texCoord; \n" + + "void main() \n" + + "{ \n" + + " vec4 c = texture2D(CC_Texture0, v_texCoord); \n" + + " gl_FragColor.xyz = vec3(0.2126*c.r + 0.7152*c.g + 0.0722*c.b); \n" + +" gl_FragColor.w = c.w ; \n" + + "}"; - cc.Scale9Sprite.WebGLRenderCmd._distortionProgram = shader; - cc.Scale9Sprite.WebGLRenderCmd._distortionOffset = shader.getUniformLocationForName('u_offset'); - cc.Scale9Sprite.WebGLRenderCmd._distortionTiling = shader.getUniformLocationForName('u_offset_tiling'); +cc.Scale9Sprite.WebGLRenderCmd._distortionProgram = null; +cc.Scale9Sprite.WebGLRenderCmd._getDistortionProgram = function(){ + var shader = cc.Scale9Sprite.WebGLRenderCmd._distortionProgram; + if(shader) return shader; - }; - var distortionSpriteShader = { - }; - distortionSpriteShader.shaderKey = 'cc.Sprite.Shader.Distortion'; - distortionSpriteShader.fShader = "precision lowp float;\n" + shader = new cc.GLProgram(); + shader.initWithVertexShaderByteArray(cc.PresetShaders.SPRITE_POSITION_TEXTURE_COLOR_VERT, distortionSpriteShader.fShader); + shader.addAttribute(cc.macro.ATTRIBUTE_NAME_POSITION, cc.macro.VERTEX_ATTRIB_POSITION); + shader.addAttribute(cc.macro.ATTRIBUTE_NAME_COLOR, cc.macro.VERTEX_ATTRIB_COLOR); + shader.addAttribute(cc.macro.ATTRIBUTE_NAME_TEX_COORD, cc.macro.VERTEX_ATTRIB_TEX_COORDS); + shader.link(); + shader.updateUniforms(); + + cc.Scale9Sprite.WebGLRenderCmd._distortionProgram = shader; + cc.Scale9Sprite.WebGLRenderCmd._distortionOffset = shader.getUniformLocationForName('u_offset'); + cc.Scale9Sprite.WebGLRenderCmd._distortionTiling = shader.getUniformLocationForName('u_offset_tiling'); + return shader; +}; + +var distortionSpriteShader = { + shaderKey: 'cc.Sprite.Shader.Distortion', + fShader: "precision lowp float;\n" + "varying vec4 v_fragmentColor; \n" + "varying vec2 v_texCoord; \n" + "uniform vec2 u_offset; \n" @@ -239,5 +253,5 @@ if (_ccsg.Node.WebGLRenderCmd) { + "uv = uv * u_offset_tiling + u_offset;\n" + "uv = fract(uv); \n" + "gl_FragColor = v_fragmentColor * texture2D(CC_Texture0, uv);\n" - + "}"; -} + + "}" +}; diff --git a/cocos2d/core/sprites/CCSpriteBatchNode.js b/cocos2d/core/sprites/CCSpriteBatchNode.js index 1201979368..847bfe231e 100644 --- a/cocos2d/core/sprites/CCSpriteBatchNode.js +++ b/cocos2d/core/sprites/CCSpriteBatchNode.js @@ -1,3 +1,4 @@ + /**************************************************************************** Copyright (c) 2008-2010 Ricardo Quesada Copyright (c) 2011-2012 cocos2d-x.org @@ -58,16 +59,14 @@ cc.SpriteBatchNode = _ccsg.Node.extend(/** @lends cc.SpriteBatchNode# */{ _blendFunc: null, // all descendants: chlidren, gran children, etc... - _descendants: null, + _texture: null, _className: "SpriteBatchNode", - ctor: function (fileImage, capacity) { + ctor: function (fileImage) { _ccsg.Node.prototype.ctor.call(this); - this._descendants = []; this._blendFunc = new cc.BlendFunc(cc.macro.BLEND_SRC, cc.macro.BLEND_DST); var texture2D; - capacity = capacity || cc.SpriteBatchNode.DEFAULT_CAPACITY; if (cc.js.isString(fileImage)) { texture2D = cc.textureCache.getTextureForKey(fileImage); if (!texture2D) @@ -75,72 +74,48 @@ cc.SpriteBatchNode = _ccsg.Node.extend(/** @lends cc.SpriteBatchNode# */{ }else if (fileImage instanceof cc.Texture2D) texture2D = fileImage; - texture2D && this.initWithTexture(texture2D, capacity); + texture2D && this.initWithTexture(texture2D); }, /** *

- * This is the opposite of "addQuadFromSprite.
- * It add the sprite to the children and descendants array, but it doesn't update add it to the texture atlas
+ * Same as addChild *

* @param {_ccsg.Sprite} child * @param {Number} z zOrder * @param {Number} aTag * @return {cc.SpriteBatchNode} + * @deprecated since v1.2 */ addSpriteWithoutQuad: function (child, z, aTag) { - cc.assert(child, cc._LogInfos.SpriteBatchNode.addSpriteWithoutQuad_2); - - if (!(child instanceof _ccsg.Sprite)) { - cc.log(cc._LogInfos.SpriteBatchNode.addSpriteWithoutQuad); - return null; - } - - // quad index is Z - child.atlasIndex = z; - - // XXX: optimize with a binary search - var i = 0, len, locDescendants = this._descendants; - if (locDescendants && locDescendants.length > 0) { - for (i = 0, len = locDescendants.length; i < len; i++) { - var obj = locDescendants[i]; - if (obj && (obj.atlasIndex >= z)) - break; - } - } - locDescendants.splice(i, 0, child); - - // IMPORTANT: Call super, and not self. Avoid adding it to the texture atlas array - _ccsg.Node.prototype.addChild.call(this, child, z, aTag); - - //#issue 1262 don't use lazy sorting, tiles are added as quads not as sprites, so sprites need to be added in order - this.reorderBatch(false); + this.addChild(child, z, aTag); return this; }, // property /** - * Return TextureAtlas of cc.SpriteBatchNode + * Return null, no texture atlas is used any more * @return {cc.TextureAtlas} + * @deprecated since v1.2 */ getTextureAtlas: function () { - return this._renderCmd.getTextureAtlas(); + return null; }, /** * TextureAtlas of cc.SpriteBatchNode setter * @param {cc.TextureAtlas} textureAtlas + * @deprecated since v1.2 */ - setTextureAtlas: function (textureAtlas) { - this._renderCmd.getTextureAtlas(textureAtlas); - }, + setTextureAtlas: function (textureAtlas) {}, /** * Return Descendants of cc.SpriteBatchNode * @return {Array} + * @deprecated since v1.2 */ getDescendants: function () { - return this._descendants; + return this._children; }, /** @@ -161,11 +136,6 @@ cc.SpriteBatchNode = _ccsg.Node.extend(/** @lends cc.SpriteBatchNode# */{ return this.initWithTexture(texture2D, capacity); }, - _setNodeDirtyForCache: function () { - if(this._renderCmd && this._renderCmd._setNodeDirtyForCache) - this._renderCmd._setNodeDirtyForCache(); - }, - /** *

* initializes a cc.SpriteBatchNode with a file image (.png, .jpeg, .pvr, etc) and a capacity of children.
@@ -185,11 +155,10 @@ cc.SpriteBatchNode = _ccsg.Node.extend(/** @lends cc.SpriteBatchNode# */{ }, /** - * Increase Atlas Capacity + * Do nothing + * @deprecated since v1.2 */ - increaseAtlasCapacity: function () { - this._renderCmd.increaseAtlasCapacity(); - }, + increaseAtlasCapacity: function () {}, /** * Removes a child given a certain index. It will also cleanup the running actions depending on the cleanup parameter. @@ -202,32 +171,13 @@ cc.SpriteBatchNode = _ccsg.Node.extend(/** @lends cc.SpriteBatchNode# */{ }, /** - * Rebuild index in order for child + * Do nothing * @param {_ccsg.Sprite} pobParent * @param {Number} index * @return {Number} + * @deprecated since v1.2 */ rebuildIndexInOrder: function (pobParent, index) { - var children = pobParent.children; - if (children && children.length > 0) { - for (var i = 0; i < children.length; i++) { - var obj = children[i]; - if (obj && (obj.zIndex < 0)) - index = this.rebuildIndexInOrder(obj, index); - } - } - // ignore self (batch node) - if (!pobParent === this) { - pobParent.atlasIndex = index; - index++; - } - if (children && children.length > 0) { - for (i = 0; i < children.length; i++) { - obj = children[i]; - if (obj && (obj.zIndex >= 0)) - index = this.rebuildIndexInOrder(obj, index); - } - } return index; }, @@ -235,12 +185,12 @@ cc.SpriteBatchNode = _ccsg.Node.extend(/** @lends cc.SpriteBatchNode# */{ * Returns highest atlas index in child * @param {_ccsg.Sprite} sprite * @return {Number} + * @deprecated since v1.2 */ highestAtlasIndexInChild: function (sprite) { var children = sprite.children; - if (!children || children.length === 0) - return sprite.atlasIndex; + return sprite.zIndex; else return this.highestAtlasIndexInChild(children[children.length - 1]); }, @@ -249,60 +199,30 @@ cc.SpriteBatchNode = _ccsg.Node.extend(/** @lends cc.SpriteBatchNode# */{ * Returns lowest atlas index in child * @param {_ccsg.Sprite} sprite * @return {Number} + * @deprecated since v1.2 */ lowestAtlasIndexInChild: function (sprite) { var children = sprite.children; if (!children || children.length === 0) - return sprite.atlasIndex; + return sprite.zIndex; else return this.lowestAtlasIndexInChild(children[children.length - 1]); }, /** - * Returns atlas index for child + * Returns index for child * @param {_ccsg.Sprite} sprite - * @param {Number} nZ * @return {Number} + * @deprecated since v1.2 */ - atlasIndexForChild: function (sprite, nZ) { - var selParent = sprite.parent; - var brothers = selParent.children; - var childIndex = brothers.indexOf(sprite); - - // ignore parent Z if parent is spriteSheet - var ignoreParent = selParent === this; - var previous = null; - if (childIndex > 0 && childIndex < cc.macro.UINT_MAX) - previous = brothers[childIndex - 1]; - - // first child of the sprite sheet - if (ignoreParent) { - if (childIndex === 0) - return 0; - return this.highestAtlasIndexInChild(previous) + 1; - } - - // parent is a _ccsg.Sprite, so, it must be taken into account - // first child of an _ccsg.Sprite ? - if (childIndex === 0) { - // less than parent and brothers - if (nZ < 0) - return selParent.atlasIndex; - else - return selParent.atlasIndex + 1; - } else { - // previous & sprite belong to the same branch - if ((previous.zIndex < 0 && nZ < 0) || (previous.zIndex >= 0 && nZ >= 0)) - return this.highestAtlasIndexInChild(previous) + 1; - - // else (previous < 0 and sprite >= 0 ) - return selParent.atlasIndex + 1; - } + atlasIndexForChild: function (sprite) { + return sprite.zIndex; }, /** * Sprites use this to start sortChildren, don't call this manually * @param {Boolean} reorder + * @deprecated since v1.2 */ reorderBatch: function (reorder) { this._reorderChildDirty = reorder; @@ -328,45 +248,6 @@ cc.SpriteBatchNode = _ccsg.Node.extend(/** @lends cc.SpriteBatchNode# */{ return new cc.BlendFunc(this._blendFunc.src,this._blendFunc.dst); }, - /** - * Reorder children (override reorderChild of ccsg.Node) - * @override - * @param {_ccsg.Sprite} child - * @param {Number} zOrder - */ - reorderChild: function (child, zOrder) { - cc.assert(child, cc._LogInfos.SpriteBatchNode.reorderChild_2); - if (this._children.indexOf(child) === -1) { - cc.log(cc._LogInfos.SpriteBatchNode.reorderChild); - return; - } - if (zOrder === child.zIndex) - return; - - //set the z-order and sort later - _ccsg.Node.prototype.reorderChild.call(this, child, zOrder); - //this.setNodeDirty(); - }, - - /** - * Removes a child from cc.SpriteBatchNode (override removeChild of ccsg.Node) - * @param {_ccsg.Sprite} child - * @param {Boolean} cleanup - */ - removeChild: function (child, cleanup) { - // explicit null handling - if (child == null) - return; - if (this._children.indexOf(child) === -1) { - cc.log(cc._LogInfos.SpriteBatchNode.removeChild); - return; - } - - // cleanup before removing - this.removeSpriteFromAtlas(child); - _ccsg.Node.prototype.removeChild.call(this, child, cleanup); - }, - /** *

* Updates a quad at a certain index into the texture atlas. The CCSprite won't be added into the children array.
@@ -383,155 +264,71 @@ cc.SpriteBatchNode = _ccsg.Node.extend(/** @lends cc.SpriteBatchNode# */{ cc.log(cc._LogInfos.SpriteBatchNode.updateQuadFromSprite); return; } - this._renderCmd.checkAtlasCapacity(); // // update the quad directly. Don't add the sprite to the scene graph // - sprite.batchNode = this; - sprite.atlasIndex = index; sprite.dirty = true; // UpdateTransform updates the textureAtlas quad - sprite.updateTransform(); + sprite._renderCmd.transform(this._renderCmd, true); }, /** *

- * Inserts a quad at a certain index into the texture atlas. The _ccsg.Sprite won't be added into the children array.
- * This method should be called only when you are dealing with very big AtlasSprite and when most of the _ccsg.Sprite won't be updated.
- * For example: a tile map (cc.TMXMap) or a label with lots of characters (cc.LabelBMFont) + * Same as addChild(sprite, index) *

* @function * @param {_ccsg.Sprite} sprite * @param {Number} index + * @deprecated since v1.2 */ insertQuadFromSprite: function (sprite, index) { - cc.assert(sprite, cc._LogInfos.SpriteBatchNode.insertQuadFromSprite_2); - if (!(sprite instanceof _ccsg.Sprite)) { - cc.log(cc._LogInfos.SpriteBatchNode.insertQuadFromSprite); - return; - } - this._renderCmd.insertQuad(sprite, index); - - // - // update the quad directly. Don't add the sprite to the scene graph - // - sprite.batchNode = this; - sprite.atlasIndex = index; - - // XXX: updateTransform will update the textureAtlas too, using updateQuad. - // XXX: so, it should be AFTER the insertQuad - sprite.dirty = true; - sprite.updateTransform(); - this._renderCmd.cutting(sprite, index); + this.addChild(sprite, index); }, /** - *

- * Initializes a cc.SpriteBatchNode with a texture2d and capacity of children.
- * The capacity will be increased in 33% in runtime if it run out of space.
- * Please pass parameters to constructor to initialize the sprite batch node, do not call this function yourself. - *

- * @function - * @param {cc.Texture2D} tex - * @param {Number} [capacity] - * @return {Boolean} - */ - initWithTexture: function (tex, capacity) { - this._children.length = 0; - this._descendants.length = 0; - - capacity = capacity || cc.SpriteBatchNode.DEFAULT_CAPACITY; - this._renderCmd.initWithTexture(tex, capacity); - return true; - }, - - /** - * Insert a child + * Same as addChild(sprite, index) * @param {_ccsg.Sprite} sprite The child sprite * @param {Number} index The insert index + * @deprecated since v1.2 */ insertChild: function (sprite, index) { - //TODO WebGL only ? - sprite.batchNode = this; - sprite.atlasIndex = index; - sprite.dirty = true; - - this._renderCmd.insertQuad(sprite, index); - this._descendants.splice(index, 0, sprite); - - // update indices - var i = index + 1, locDescendant = this._descendants; - if (locDescendant && locDescendant.length > 0) { - for (; i < locDescendant.length; i++) - locDescendant[i].atlasIndex++; - } - - // add children recursively - var locChildren = sprite.children, child, l; - if (locChildren) { - for (i = 0, l = locChildren.length || 0; i < l; i++) { - child = locChildren[i]; - if (child) { - var getIndex = this.atlasIndexForChild(child, child.zIndex); - this.insertChild(child, getIndex); - } - } - } + this.addChild(sprite, index); }, /** - * Add child at the end, faster than insert child + * Add child at the end * @function * @param {_ccsg.Sprite} sprite */ appendChild: function (sprite) { - this._reorderChildDirty = true; - sprite.batchNode = this; - sprite.dirty = true; - - this._descendants.push(sprite); - var index = this._descendants.length - 1; - - sprite.atlasIndex = index; - this._renderCmd.insertQuad(sprite, index); - - // add children recursively - var children = sprite.children; - for (var i = 0, l = children.length || 0; i < l; i++) - this.appendChild(children[i]); + this.sortAllChildren(); + var lastLocalZOrder = this._children[this._children.length-1]._localZOrder; + this.addChild(sprite. lastLocalZOrder + 1); }, /** - * Removes sprite from TextureAtlas + * Same as removeChild * @function * @param {_ccsg.Sprite} sprite + * @param {Boolean} [cleanup=true] true if all running actions and callbacks on the child node will be cleanup, false otherwise. + * @deprecated since v1.2 */ - removeSpriteFromAtlas: function (sprite) { - this._renderCmd.removeQuadAtIndex(sprite.atlasIndex); - - // Cleanup sprite. It might be reused (issue #569) - sprite.batchNode = null; - var locDescendants = this._descendants; - var index = locDescendants.indexOf(sprite); - if (index !== -1) { - locDescendants.splice(index, 1); - - // update all sprites beyond this one - var len = locDescendants.length; - for (; index < len; ++index) { - var s = locDescendants[index]; - s.atlasIndex--; - } - } - - // remove children recursively - var children = sprite.children; - if (children) { - for (var i = 0, l = children.length || 0; i < l; i++) - children[i] && this.removeSpriteFromAtlas(children[i]); - } + removeSpriteFromAtlas: function (sprite, cleanup) { + this.removeChild(sprite, cleanup); }, + + /** + * Set the texture property + * @function + * @param {cc.Texture2D} tex + * @return {Boolean} + */ + initWithTexture: function (tex) { + this.setTexture(tex); + return true; + }, + // CCTextureProtocol /** * Returns texture of the sprite batch node @@ -539,7 +336,7 @@ cc.SpriteBatchNode = _ccsg.Node.extend(/** @lends cc.SpriteBatchNode# */{ * @return {cc.Texture2D} */ getTexture: function () { - return this._renderCmd.getTexture(); + return this._texture; }, /** @@ -548,7 +345,30 @@ cc.SpriteBatchNode = _ccsg.Node.extend(/** @lends cc.SpriteBatchNode# */{ * @param {cc.Texture2D} texture */ setTexture: function(texture){ - this._renderCmd.setTexture(texture); + this._texture = texture; + + if (texture._textureLoaded) { + var children = this._children, i, len = children.length; + for (i = 0; i < len; ++i) { + children[i].setTexture(texture); + } + } + else { + texture.addEventListener("load", function(){ + var children = this._children, i, len = children.length; + for (i = 0; i < len; ++i) { + children[i].setTexture(texture); + } + }, this); + } + }, + + setShaderProgram: function (newShaderProgram) { + this._renderCmd.setShaderProgram(newShaderProgram); + var children = this._children, i, len = children.length; + for (i = 0; i < len; ++i) { + children[i].setShaderProgram(newShaderProgram); + } }, /** @@ -560,77 +380,31 @@ cc.SpriteBatchNode = _ccsg.Node.extend(/** @lends cc.SpriteBatchNode# */{ * @param {Number} [tag] */ addChild: function (child, zOrder, tag) { - cc.assert(child != null, cc._LogInfos.SpriteBatchNode.addChild_3); + cc.assert(child !== undefined, cc._LogInfos.SpriteBatchNode.addChild_3); - if(!this._renderCmd.isValidChild(child)) + if(!this._isValidChild(child)) return; - zOrder = (zOrder == null) ? child.zIndex : zOrder; - tag = (tag == null) ? child.tag : tag; + zOrder = (zOrder === undefined) ? child.zIndex : zOrder; + tag = (tag === undefined) ? child.tag : tag; _ccsg.Node.prototype.addChild.call(this, child, zOrder, tag); - this.appendChild(child); - //this.setNodeDirty(); - }, - - /** - * Removes all children from the container and do a cleanup all running actions depending on the cleanup parameter.
- * (override removeAllChildren of ccsg.Node) - * @function - * @param {Boolean} cleanup - */ - removeAllChildren: function (cleanup) { - // Invalidate atlas index. issue #569 - // useSelfRender should be performed on all descendants. issue #1216 - var locDescendants = this._descendants; - if (locDescendants && locDescendants.length > 0) { - for (var i = 0, len = locDescendants.length; i < len; i++) { - if (locDescendants[i]) - locDescendants[i].batchNode = null; - } - } - _ccsg.Node.prototype.removeAllChildren.call(this, cleanup); - this._descendants.length = 0; - this._renderCmd.removeAllQuads(); - }, - - /** - * Sort all children nodes (override draw of ccsg.Node) - */ - sortAllChildren: function () { - if (this._reorderChildDirty) { - var childrenArr = this._children; - var i, j = 0, length = childrenArr.length, tempChild; - //insertion sort - for (i = 1; i < length; i++) { - var tempItem = childrenArr[i]; - j = i - 1; - tempChild = childrenArr[j]; - - //continue moving element downwards while zOrder is smaller or when zOrder is the same but mutatedIndex is smaller - while (j >= 0 && ( tempItem._localZOrder < tempChild._localZOrder || - ( tempItem._localZOrder === tempChild._localZOrder && tempItem.arrivalOrder < tempChild.arrivalOrder ))) { - childrenArr[j + 1] = tempChild; - j = j - 1; - tempChild = childrenArr[j]; - } - childrenArr[j + 1] = tempItem; - } - - //sorted now check all children - if (childrenArr.length > 0) { - //first sort all children recursively based on zOrder - this._arrayMakeObjectsPerformSelector(childrenArr, _ccsg.Node._stateCallbackType.sortAllChildren); - this._renderCmd.updateChildrenAtlasIndex(childrenArr); - } - this._reorderChildDirty = false; + + // Apply shader + if (this._renderCmd._shaderProgram) { + child.shaderProgram = this._renderCmd._shaderProgram; } }, - _createRenderCmd: function(){ - if(cc._renderType === cc.game.RENDER_TYPE_CANVAS) - return new cc.SpriteBatchNode.CanvasRenderCmd(this); - else - return new cc.SpriteBatchNode.WebGLRenderCmd(this); + _isValidChild: function (child) { + if (!(child instanceof _ccsg.Sprite)) { + cc.log(cc._LogInfos.Sprite.addChild_4); + return false; + } + if (child.texture !== this._texture) { + cc.log(cc._LogInfos.Sprite.addChild_5); + return false; + } + return true; } }); @@ -638,16 +412,4 @@ var _p = cc.SpriteBatchNode.prototype; // Override properties cc.defineGetterSetter(_p, "texture", _p.getTexture, _p.setTexture); -cc.defineGetterSetter(_p, "textureAtlas", _p.getTextureAtlas, _p.setTextureAtlas); - -// Extended properties -/** @expose */ -_p.descendants; -cc.defineGetterSetter(_p, "descendants", _p.getDescendants); - - -/** - * @constant - * @type Number - */ -cc.SpriteBatchNode.DEFAULT_CAPACITY = 29; \ No newline at end of file +cc.defineGetterSetter(_p, "shaderProgram", _p.getShaderProgram, _p.setShaderProgram); diff --git a/cocos2d/core/sprites/CCSpriteBatchNodeCanvasRenderCmd.js b/cocos2d/core/sprites/CCSpriteBatchNodeCanvasRenderCmd.js deleted file mode 100644 index 08f1cfeb55..0000000000 --- a/cocos2d/core/sprites/CCSpriteBatchNodeCanvasRenderCmd.js +++ /dev/null @@ -1,99 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013-2014 Chukong Technologies Inc. - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -//SpriteBatchNode's canvas render command -cc.SpriteBatchNode.CanvasRenderCmd = function(renderable){ - _ccsg.Node.CanvasRenderCmd.call(this, renderable); - - this._texture = null; - this._textureToRender = null; -}; - -var proto = cc.SpriteBatchNode.CanvasRenderCmd.prototype = Object.create(_ccsg.Node.CanvasRenderCmd.prototype); -proto.constructor = cc.SpriteBatchNode.CanvasRenderCmd; - -proto.checkAtlasCapacity = function(){}; - -proto.isValidChild = function(child){ - if (!(child instanceof _ccsg.Sprite)) { - cc.log(cc._LogInfos.Sprite.addChild_4); - return false; - } - return true; -}; - -proto.initWithTexture = function(texture, capacity){ - this._textureToRender = this._texture = texture; -}; - -proto.insertQuad = function(sprite, index){}; - -proto.increaseAtlasCapacity = function(){}; - -proto.removeQuadAtIndex = function(){}; - -proto.removeAllQuads = function(){}; - -proto.getTexture = function(){ - return this._texture; -}; - -proto.setTexture = function(texture){ - this._texture = texture; - var locChildren = this._node._children; - for (var i = 0; i < locChildren.length; i++) - locChildren[i].setTexture(texture); -}; - -proto.updateChildrenAtlasIndex = function(children){ - this._node._descendants.length = 0; - //update _descendants after sortAllChildren - for (var i = 0, len = children.length; i < len; i++) - this._updateAtlasIndex(children[i]); -}; - -proto._updateAtlasIndex = function (sprite) { - var locDescendants = this._node._descendants; - var pArray = sprite.children, i, len = pArray.length; - for (i = 0; i < len; i++) { - if (pArray[i]._localZOrder < 0) { - locDescendants.push(pArray[i]); - } else { - break; - } - } - locDescendants.push(sprite); - for (; i < len; i++) { - locDescendants.push(pArray[i]); - } -}; - -proto.getTextureAtlas = function(){}; - -proto.setTextureAtlas = function(textureAtlas){}; - -proto.cutting = function(sprite, index){ - var node = this._node; - node._children.splice(index, 0, sprite); -}; \ No newline at end of file diff --git a/cocos2d/core/sprites/CCSpriteBatchNodeWebGLRenderCmd.js b/cocos2d/core/sprites/CCSpriteBatchNodeWebGLRenderCmd.js deleted file mode 100644 index a7ac4cd4e7..0000000000 --- a/cocos2d/core/sprites/CCSpriteBatchNodeWebGLRenderCmd.js +++ /dev/null @@ -1,242 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013-2014 Chukong Technologies Inc. - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -//SpriteBatchNode's WebGL render command -cc.SpriteBatchNode.WebGLRenderCmd = function(renderable){ - _ccsg.Node.WebGLRenderCmd.call(this, renderable); - this._needDraw = true; - - this._textureAtlas = null; -}; - -var proto = cc.SpriteBatchNode.WebGLRenderCmd.prototype = Object.create(_ccsg.Node.WebGLRenderCmd.prototype); -proto.constructor = cc.SpriteBatchNode.WebGLRenderCmd; - -proto.isValidChild = function(child){ - if (!(child instanceof _ccsg.Sprite)) { - cc.log(cc._LogInfos.Sprite.addChild_4); - return false; - } - if (child.texture != this.getTexture()) { - cc.log(cc._LogInfos.Sprite.addChild_5); - return false; - } - return true; -}; - -proto.rendering = function () { - var node = this._node; - if (this._textureAtlas.totalQuads === 0) - return; - - this._shaderProgram.use(); - this._shaderProgram._setUniformForMVPMatrixWithMat4(this._stackMatrix); - node._arrayMakeObjectsPerformSelector(node._children, _ccsg.Node._stateCallbackType.updateTransform); - cc.gl.blendFunc(node._blendFunc.src, node._blendFunc.dst); - - this._textureAtlas.drawQuads(); -}; - -proto.visit = function(parentCmd){ - var node = this._node; - this._propagateFlagsDown(parentCmd); - // quick return if not visible - if (!node._visible) - return; - - if (node._parent && node._parent._renderCmd) - this._curLevel = node._parent._renderCmd._curLevel + 1; - - var currentStack = cc.current_stack; - - //optimize performance for javascript - currentStack.stack.push(currentStack.top); - - if(!(this._dirtyFlag & _ccsg.Node._dirtyFlags.transformDirty)) //batchNode's transform must update in visit - this.transform(parentCmd); - this.updateStatus(parentCmd); //because batchNode doesn't visit its children. - currentStack.top = this._stackMatrix; - - node.sortAllChildren(); - - cc.renderer.pushRenderCommand(this); - - this._dirtyFlag = 0; - //optimize performance for javascript - currentStack.top = currentStack.stack.pop(); -}; - -proto.checkAtlasCapacity = function(index){ - // make needed room - var locAtlas = this._textureAtlas; - while (index >= locAtlas.capacity || locAtlas.capacity === locAtlas.totalQuads) { - this.increaseAtlasCapacity(); - } -}; - -proto.increaseAtlasCapacity = function(){ - // if we're going beyond the current TextureAtlas's capacity, - // all the previously initialized sprites will need to redo their texture coords - // this is likely computationally expensive - var locCapacity = this._textureAtlas.capacity; - var quantity = Math.floor((locCapacity + 1) * 4 / 3); - - cc.log(cc._LogInfos.SpriteBatchNode.increaseAtlasCapacity, locCapacity, quantity); - - if (!this._textureAtlas.resizeCapacity(quantity)) { - // serious problems - cc.log(cc._LogInfos.SpriteBatchNode.increaseAtlasCapacity_2); - } -}; - -proto.initWithTexture = function(texture, capacity){ - this._textureAtlas = new cc.TextureAtlas(); - this._textureAtlas.initWithTexture(texture, capacity); - this._updateBlendFunc(); - this._shaderProgram = cc.shaderCache.programForKey(cc.macro.SHADER_POSITION_TEXTURECOLOR); -}; - -proto.insertQuad = function(sprite, index){ - var locTextureAtlas = this._textureAtlas; - if (locTextureAtlas.totalQuads >= locTextureAtlas.capacity) - this.increaseAtlasCapacity(); - locTextureAtlas.insertQuad(sprite.quad, index); -}; - -proto.removeQuadAtIndex = function(index){ - this._textureAtlas.removeQuadAtIndex(index); // remove from TextureAtlas -}; - -proto.getTexture = function(){ - return this._textureAtlas.texture; -}; - -proto.setTexture = function(texture){ - this._textureAtlas.setTexture(texture); - if(texture) - this._updateBlendFunc(); -}; - -proto.removeAllQuads = function(){ - this._textureAtlas.removeAllQuads(); -}; - -proto._swap = function (oldIndex, newIndex) { - var locDescendants = this._node._descendants; - var locTextureAtlas = this._textureAtlas; - var quads = locTextureAtlas.quads; - var tempItem = locDescendants[oldIndex]; - var tempIteQuad = cc.V3F_C4B_T2F_QuadCopy(quads[oldIndex]); - - //update the index of other swapped item - locDescendants[newIndex].atlasIndex = oldIndex; - locDescendants[oldIndex] = locDescendants[newIndex]; - - locTextureAtlas.updateQuad(quads[newIndex], oldIndex); - locDescendants[newIndex] = tempItem; - locTextureAtlas.updateQuad(tempIteQuad, newIndex); -}; - -proto._updateAtlasIndex = function (sprite, curIndex) { - var count = 0; - var pArray = sprite.children; - if (pArray) - count = pArray.length; - - var oldIndex = 0; - if (count === 0) { - oldIndex = sprite.atlasIndex; - sprite.atlasIndex = curIndex; - sprite.arrivalOrder = 0; - if (oldIndex !== curIndex) - this._swap(oldIndex, curIndex); - curIndex++; - } else { - var needNewIndex = true; - if (pArray[0].zIndex >= 0) { - //all children are in front of the parent - oldIndex = sprite.atlasIndex; - sprite.atlasIndex = curIndex; - sprite.arrivalOrder = 0; - if (oldIndex !== curIndex) - this._swap(oldIndex, curIndex); - curIndex++; - needNewIndex = false; - } - for (var i = 0; i < pArray.length; i++) { - var child = pArray[i]; - if (needNewIndex && child.zIndex >= 0) { - oldIndex = sprite.atlasIndex; - sprite.atlasIndex = curIndex; - sprite.arrivalOrder = 0; - if (oldIndex !== curIndex) { - this._swap(oldIndex, curIndex); - } - curIndex++; - needNewIndex = false; - } - curIndex = this._updateAtlasIndex(child, curIndex); - } - - if (needNewIndex) { - //all children have a zOrder < 0) - oldIndex = sprite.atlasIndex; - sprite.atlasIndex = curIndex; - sprite.arrivalOrder = 0; - if (oldIndex !== curIndex) { - this._swap(oldIndex, curIndex); - } - curIndex++; - } - } - return curIndex; -}; - -proto.updateChildrenAtlasIndex = function(children){ - var index = 0; - //fast dispatch, give every child a new atlasIndex based on their relative zOrder (keep parent -> child relations intact) - // and at the same time reorder descedants and the quads to the right index - for (var i = 0; i < children.length; i++) - index = this._updateAtlasIndex(children[i], index); -}; - -proto._updateBlendFunc = function () { - if (!this._textureAtlas.texture.hasPremultipliedAlpha()) { - var blendFunc = this._node._blendFunc; - blendFunc.src = cc.macro.SRC_ALPHA; - blendFunc.dst = cc.macro.ONE_MINUS_SRC_ALPHA; - } -}; - -proto.getTextureAtlas = function(){ - return this._textureAtlas; -}; - -proto.setTextureAtlas = function(textureAtlas){ - if (textureAtlas !== this._textureAtlas) { - this._textureAtlas = textureAtlas; - } -}; - -proto.cutting = function(){}; diff --git a/cocos2d/core/sprites/CCSpriteFrame.js b/cocos2d/core/sprites/CCSpriteFrame.js index d8577737d4..50d886fbbd 100644 --- a/cocos2d/core/sprites/CCSpriteFrame.js +++ b/cocos2d/core/sprites/CCSpriteFrame.js @@ -35,17 +35,17 @@ var EventTarget = require("../event/event-target"); * You can modify the frame of a _ccsg.Sprite by doing:
* * Note: It's not recommended to use SpriteFrame constructor (new SpriteFrame) - * to create SpriteFrame instance since it's memory will be unable to manage.
- * Instead please use cc.loader.loadRes to get SpriteFrame instance from loading, - * or define a cc.SpriteFrame property in your component and drag the SpriteFrame onto it. + * because its memory usage can't be tracked in native environment,
+ * if you know what you are doing, you may need to manually retain it after creation then + * release it when you no longer need it. * * !#zh * 一个 SpriteFrame 包含:
* - 纹理:会被 Sprite 使用的 Texture2D 对象。
* - 矩形:在纹理中的矩形区域。
- * 注意:目前只建议通过以下几个方式进行创建 SpriteFrame:
- * - 可以在你的组件上定义一个 SpriteFrame 类型并通过拖动 SpriteFrame 资源进行赋值。
- * - 通过 cc.loader.loadRes 或 atlas.getSpriteFrame 来获得 spriteFrame 实例。 + * 注意:
+ * 不建议用户使用构造函数进行创建,因为其内存使用情况,不能在本地环境中进行跟踪,需要用户手动管理内存,不然会导致严重错误。
+ * 如果你知道你在做什么,你可能需要手动将其保留在创建之后,然后释放它。 * * @class SpriteFrame * @extends Asset @@ -90,12 +90,16 @@ cc.SpriteFrame = cc.Class(/** @lends cc.SpriteFrame# */{ /** * !#en * Constructor of SpriteFrame class.
- * Node: It's not recommended to use SpriteFrame constructor (new SpriteFrame),
- * Because the instance in the native environment requires the user to manually manage memory,
- * or you might cause serious errors. + * Note: It's not recommended to use SpriteFrame constructor (new SpriteFrame) + * because its memory usage can't be tracked in native environment,
+ * if you know what you are doing, you may need to manually retain it after creation then + * release it when you no longer need it. * !#zh * SpriteFrame 类的构造函数。
- * 注意:不建议用户使用构造函数进行创建,因为该实例在原生环境下需要用户手动管理内存,不然会导致严重错误。 + * 注意:
+ * 不建议用户使用构造函数进行创建,因为其内存使用情况,不能在本地环境中进行跟踪, + * 需要用户手动管理内存,不然会导致严重错误。
+ * 如果你知道你在做什么,你可能需要手动将其保留在创建之后,然后释放它。 * @method SpriteFrame * @param {String|Texture2D} [filename] * @param {Rect} [rect] @@ -104,19 +108,17 @@ cc.SpriteFrame = cc.Class(/** @lends cc.SpriteFrame# */{ * @param {Size} [originalSize] - The size of the frame in the texture */ ctor: function () { + + if (CC_DEV && (!CC_EDITOR || Editor.isRendererProcess) && !CC_TEST && !cc.game._isCloning) { + cc.warn("It's not recommended to use SpriteFrame constructor (new SpriteFrame) because its memory usage can't be tracked in native environment, if you know what you are doing, you may need to manually retain it after creation then release it when you no longer need it."); + } + var filename = arguments[0]; var rect = arguments[1]; var rotated = arguments[2]; var offset = arguments[3]; var originalSize = arguments[4]; - if (CC_DEV && (!CC_EDITOR || Editor.isRendererProcess) && !CC_TEST && !cc.game._isCloning) { - cc.warn('It\'s not recommended to use SpriteFrame constructor (new SpriteFrame) ' + - 'to create SpriteFrame instance since it\'s memory will be unable to manage. ' + - 'Instead please use cc.loader.loadRes to get SpriteFrame instance from loading, ' + - 'or define a cc.SpriteFrame property in your component and drag the SpriteFrame onto it.') - } - // the location of the sprite on rendering texture this._rect = null; diff --git a/cocos2d/core/textures/CCTexture2D.js b/cocos2d/core/textures/CCTexture2D.js index 749b70dcf9..859c5d646a 100644 --- a/cocos2d/core/textures/CCTexture2D.js +++ b/cocos2d/core/textures/CCTexture2D.js @@ -231,6 +231,7 @@ var Texture2D = cc.Class(/** @lends cc.Texture2D# */{ var locElement = self._htmlElementObj; self._contentSize.width = locElement.width; self._contentSize.height = locElement.height; + self._textureLoaded = true; //dispatch load event to listener. self.emit("load"); @@ -868,6 +869,7 @@ game.once(game.EVENT_RENDERER_INITED, function () { self._hasPremultipliedAlpha = premultiplied; self._hasMipmaps = false; + self._textureLoaded = true; //dispatch load event to listener. self.emit("load"); diff --git a/cocos2d/core/textures/CCTextureAtlas.js b/cocos2d/core/textures/CCTextureAtlas.js index 0b69da4822..4d15b04839 100644 --- a/cocos2d/core/textures/CCTextureAtlas.js +++ b/cocos2d/core/textures/CCTextureAtlas.js @@ -669,9 +669,10 @@ if (cc._renderType === game.RENDER_TYPE_WEBGL) { //vertices //gl.bindBuffer(gl.ARRAY_BUFFER, _t._buffersVBO[0]); // XXX: update is done in draw... perhaps it should be done in a timer - cc.gl.enableVertexAttribs(cc.macro.VERTEX_ATTRIB_FLAG_POS_COLOR_TEX); - gl.bindBuffer(gl.ARRAY_BUFFER, _t._quadsWebBuffer); + gl.enableVertexAttribArray(cc.macro.VERTEX_ATTRIB_POSITION); + gl.enableVertexAttribArray(cc.macro.VERTEX_ATTRIB_COLOR); + gl.enableVertexAttribArray(cc.macro.VERTEX_ATTRIB_TEX_COORDS); if (_t.dirty){ gl.bufferData(gl.ARRAY_BUFFER, _t._quadsArrayBuffer, gl.DYNAMIC_DRAW); _t.dirty = false; diff --git a/cocos2d/core/utils/base-node.js b/cocos2d/core/utils/base-node.js index c82c33fec2..43e078f206 100644 --- a/cocos2d/core/utils/base-node.js +++ b/cocos2d/core/utils/base-node.js @@ -29,29 +29,11 @@ var Misc = require('./misc'); var DirtyFlags = Misc.DirtyFlags; var IdGenerater = require('../platform/id-generater'); -// called after changing parent -function updateZOrder (node) { - var sgNode = node._sgNode; - if (CC_JSB) { - // Reset zorder to update their arrival order in JSB - var zOrder = sgNode.getLocalZOrder(); - sgNode.setLocalZOrder(zOrder + 1); - sgNode.setLocalZOrder(zOrder); - } - else { - var sgSiblings = sgNode.parent.getChildren(); - if (sgSiblings.length >= 2) { - var prevNode = sgSiblings[sgSiblings.length - 2]; - sgNode.arrivalOrder = prevNode.arrivalOrder + 1; - } - else { - sgNode.arrivalOrder = 0; - } - cc.renderer.childrenOrderDirty = true; - var parent = node._parent; - parent._sgNode._reorderChildDirty = true; - parent._reorderChildDirty = true; - parent._delaySort(); +function updateOrder (node) { + var parent = node._parent; + parent._reorderChildDirty = true; + parent._delaySort(); + if (!CC_JSB) { cc.eventManager._setDirtyForNode(node); } } @@ -107,7 +89,6 @@ var BaseNode = cc.Class(/** @lends cc.Node# */{ _globalZOrder: 0, _tag: cc.macro.NODE_TAG_INVALID, _opacityModifyRGB: false, - _reorderChildDirty: false, // API @@ -165,7 +146,7 @@ var BaseNode = cc.Class(/** @lends cc.Node# */{ if (value) { var parent = value._sgNode; parent.addChild(sgNode); - updateZOrder(this); + updateOrder(this); value._children.push(this); value.emit(CHILD_ADDED, this); } @@ -266,10 +247,8 @@ var BaseNode = cc.Class(/** @lends cc.Node# */{ this._localZOrder = value; this._sgNode.zIndex = value; - if (!CC_JSB && this._parent) { - this._parent._reorderChildDirty = true; - this._parent._delaySort(); - cc.eventManager._setDirtyForNode(this); + if(this._parent) { + updateOrder(this); } } } @@ -637,7 +616,7 @@ var BaseNode = cc.Class(/** @lends cc.Node# */{ }, //running: { - // get: + // get: //}, /** @@ -789,8 +768,6 @@ var BaseNode = cc.Class(/** @lends cc.Node# */{ sgNode.cascadeOpacity = true; } - this._dirtyFlags = DirtyFlags.ALL; - /** * Current active size provider for this node. * Size provider can equals to this._sgNode. @@ -802,6 +779,7 @@ var BaseNode = cc.Class(/** @lends cc.Node# */{ this._sizeProvider = null; this.__ignoreAnchor = false; + this._reorderChildDirty = false; // Support for ActionManager and EventManager this.__instanceId = this._id || cc.ClassManager.getNewInstanceId(); @@ -826,6 +804,7 @@ var BaseNode = cc.Class(/** @lends cc.Node# */{ var target = this.__eventTargets[i]; target && target.targetOff(this); } + cc.director.off(cc.Director.EVENT_AFTER_UPDATE, this.sortAllChildren, this); }, _destruct: Misc.destructIgnoreId, @@ -1484,7 +1463,7 @@ var BaseNode = cc.Class(/** @lends cc.Node# */{ } return false; }, - + /** * !#en Returns the world affine transform matrix. The matrix is in Pixels. * !#zh 返回节点到世界坐标系的仿射变换矩阵。矩阵单位是像素。 @@ -1503,8 +1482,8 @@ var BaseNode = cc.Class(/** @lends cc.Node# */{ var mat = this._sgNode.getNodeToWorldTransform(); if (this._isSgTransformArToMe(contentSize)) { - // _sgNode.getNodeToWorldTransform is not anchor relative (AR), in this case, - // we should translate to bottem left to consistent with it + // _sgNode.getNodeToWorldTransform is not anchor relative (AR), in this case, + // we should translate to bottem left to consistent with it // see https://github.com/cocos-creator/engine/pull/391 var tx = - this._anchorPoint.x * contentSize.width; var ty = - this._anchorPoint.y * contentSize.height; @@ -1726,7 +1705,7 @@ var BaseNode = cc.Class(/** @lends cc.Node# */{ } return mat; }, - + /** * !#en * Returns a "world" axis aligned bounding box of the node.
@@ -1752,7 +1731,7 @@ var BaseNode = cc.Class(/** @lends cc.Node# */{ var width = size.width; var height = size.height; var rect = cc.rect(- this._anchorPoint.x * width, - this._anchorPoint.y * height, width, height); - + var transAR = cc.affineTransformConcat(this.getNodeToParentTransformAR(), parentTransformAR); cc._rectApplyAffineTransformIn(rect, transAR); @@ -1907,13 +1886,15 @@ var BaseNode = cc.Class(/** @lends cc.Node# */{ } else { sibling.arrivalOrder = i; - cc.renderer.childrenOrderDirty = true; - parent._sgNode._reorderChildDirty = true; - parent._reorderChildDirty = true; - parent._delaySort(); cc.eventManager._setDirtyForNode(siblings[i]); } } + if (!CC_JSB) { + cc.renderer.childrenOrderDirty = true; + parent._sgNode._reorderChildDirty = true; + parent._reorderChildDirty = true; + parent._delaySort(); + } } }, @@ -1939,10 +1920,10 @@ var BaseNode = cc.Class(/** @lends cc.Node# */{ }, /** - * !#en Sorts the children array depends on children's zIndex and arrivalOrder, + * !#en Sorts the children array depends on children's zIndex and arrivalOrder, * normally you won't need to invoke this function. * !#zh 根据子节点的 zIndex 和 arrivalOrder 进行排序,正常情况下开发者不需要手动调用这个函数。 - * + * * @method sortAllChildren */ sortAllChildren: function () { @@ -2003,14 +1984,14 @@ var BaseNode = cc.Class(/** @lends cc.Node# */{ sgNode.setCascadeOpacityEnabled(self._cascadeOpacityEnabled); sgNode.setTag(self._tag); }, - + _updateSgNode: function () { this._updateDummySgNode(); var sgNode = this._sgNode; sgNode.setAnchorPoint(this._anchorPoint); sgNode.setVisible(this._active); sgNode.setColor(this._color); - + // update ActionManager and EventManager because sgNode maybe changed if (this._activeInHierarchy) { cc.director.getActionManager().resumeTarget(this); @@ -2110,18 +2091,6 @@ var DiffNameGetSets = { Misc.propertyDefine(BaseNode, SameNameGetSets, DiffNameGetSets); -/** - * !#en The local position in its parent's coordinate system.
- * PS: The returned value is a copy of current position, so modification of the copy will not take effect for the actual position of the node. - * !#zh 节点相对父节点的坐标。
- * 注意:返回值会是当前 position 的副本,所以对该副本所做的修改并不会影响节点的实际坐标。 - * @property position - * @type {Vec2} - * @example - * node.position = new cc.Vec2(0, 0); // OK! - * node.position.addSelf(new cc.Vec2(1, 0)); // Invalid! - */ - /** * !#en The local scale relative to the parent. * !#zh 节点相对父节点的缩放。 diff --git a/cocos2d/core/utils/misc.js b/cocos2d/core/utils/misc.js index 31612201a3..a602090703 100644 --- a/cocos2d/core/utils/misc.js +++ b/cocos2d/core/utils/misc.js @@ -69,20 +69,20 @@ misc.NextPOT = function (x) { return x + 1; }; -var DirtyFlags = misc.DirtyFlags = { - TRANSFORM: 1 << 0, - SIZE: 1 << 1, - //Visible: - //Color: - //Opacity - //Cache - //Order - //Text - //Gradient - ALL: (1 << 2) - 1 -}; - -DirtyFlags.WIDGET = DirtyFlags.TRANSFORM | DirtyFlags.SIZE; +//var DirtyFlags = misc.DirtyFlags = { +// TRANSFORM: 1 << 0, +// SIZE: 1 << 1, +// //Visible: +// //Color: +// //Opacity +// //Cache +// //Order +// //Text +// //Gradient +// ALL: (1 << 2) - 1 +//}; +// +//DirtyFlags.WIDGET = DirtyFlags.TRANSFORM | DirtyFlags.SIZE; misc.destructIgnoreId = function () { // The same as Object._destruct but dont reset _id when destroyed diff --git a/cocos2d/core/value-types/CCTypesWebGL.js b/cocos2d/core/value-types/CCTypesWebGL.js index ba4b47ef07..755c8748ef 100644 --- a/cocos2d/core/value-types/CCTypesWebGL.js +++ b/cocos2d/core/value-types/CCTypesWebGL.js @@ -49,19 +49,20 @@ cc.WebGLColor = function (r, g, b, a, arrayBuffer, offset) { this._arrayBuffer = arrayBuffer || new ArrayBuffer(cc.WebGLColor.BYTES_PER_ELEMENT); this._offset = offset || 0; - var locArrayBuffer = this._arrayBuffer, locOffset = this._offset, locElementLen = Uint8Array.BYTES_PER_ELEMENT; - this._rU8 = new Uint8Array(locArrayBuffer, locOffset, 1); - this._gU8 = new Uint8Array(locArrayBuffer, locOffset + locElementLen, 1); - this._bU8 = new Uint8Array(locArrayBuffer, locOffset + locElementLen * 2, 1); - this._aU8 = new Uint8Array(locArrayBuffer, locOffset + locElementLen * 3, 1); + var locArrayBuffer = this._arrayBuffer, locOffset = this._offset; + this._view = new Uint8Array(locArrayBuffer, locOffset, 4); - this._rU8[0] = r || 0; - this._gU8[0] = g || 0; - this._bU8[0] = b || 0; - this._aU8[0] = (a == null) ? 255 : a; + this._view[0] = r || 0; + this._view[1] = g || 0; + this._view[2] = b || 0; - if (a === undefined) + if (typeof a === 'number') { + this._view[3] = a; + } + else { + this._view[3] = 255; this.a_undefined = true; + } }; /** * @property BYTES_PER_ELEMENT @@ -71,28 +72,28 @@ cc.WebGLColor = function (r, g, b, a, arrayBuffer, offset) { cc.WebGLColor.BYTES_PER_ELEMENT = 4; var _p = cc.WebGLColor.prototype; _p._getR = function () { - return this._rU8[0]; + return this._view[0]; }; _p._setR = function (value) { - this._rU8[0] = value < 0 ? 0 : value; + this._view[0] = value < 0 ? 0 : value; }; _p._getG = function () { - return this._gU8[0]; + return this._view[1]; }; _p._setG = function (value) { - this._gU8[0] = value < 0 ? 0 : value; + this._view[1] = value < 0 ? 0 : value; }; _p._getB = function () { - return this._bU8[0]; + return this._view[2]; }; _p._setB = function (value) { - this._bU8[0] = value < 0 ? 0 : value; + this._view[2] = value < 0 ? 0 : value; }; _p._getA = function () { - return this._aU8[0]; + return this._view[3]; }; _p._setA = function (value) { - this._aU8[0] = value < 0 ? 0 : value; + this._view[3] = value < 0 ? 0 : value; }; /** @expose */ _p.r; @@ -124,10 +125,9 @@ cc.Vertex2F = function (x, y, arrayBuffer, offset) { this._arrayBuffer = arrayBuffer || new ArrayBuffer(cc.Vertex2F.BYTES_PER_ELEMENT); this._offset = offset || 0; - this._xF32 = new Float32Array(this._arrayBuffer, this._offset, 1); - this._yF32 = new Float32Array(this._arrayBuffer, this._offset + 4, 1); - this._xF32[0] = x || 0; - this._yF32[0] = y || 0; + this._view = new Float32Array(this._arrayBuffer, this._offset, 2); + this._view[0] = x || 0; + this._view[1] = y || 0; }; /** * @property BYTES_PER_ELEMENT @@ -136,24 +136,20 @@ cc.Vertex2F = function (x, y, arrayBuffer, offset) { */ cc.Vertex2F.BYTES_PER_ELEMENT = 8; -_p = cc.Vertex2F.prototype; +var _p = cc.Vertex2F.prototype; _p._getX = function () { - return this._xF32[0]; + return this._view[0]; }; _p._setX = function (xValue) { - this._xF32[0] = xValue; + this._view[0] = xValue; }; _p._getY = function () { - return this._yF32[0]; + return this._view[1]; }; _p._setY = function (yValue) { - this._yF32[0] = yValue; + this._view[1] = yValue; }; -/** @expose */ -_p.x; cc.js.getset(_p, "x", _p._getX, _p._setX); -/** @expose */ -_p.y; cc.js.getset(_p, "y", _p._getY, _p._setY); // redefine cc.Vertex3F @@ -175,12 +171,10 @@ cc.Vertex3F = function (x, y, z, arrayBuffer, offset) { this._offset = offset || 0; var locArrayBuffer = this._arrayBuffer, locOffset = this._offset; - this._xF32 = new Float32Array(locArrayBuffer, locOffset, 1); - this._xF32[0] = x || 0; - this._yF32 = new Float32Array(locArrayBuffer, locOffset + Float32Array.BYTES_PER_ELEMENT, 1); - this._yF32[0] = y || 0; - this._zF32 = new Float32Array(locArrayBuffer, locOffset + Float32Array.BYTES_PER_ELEMENT * 2, 1); - this._zF32[0] = z || 0; + this._view = new Float32Array(locArrayBuffer, locOffset, 3); + this._view[0] = x || 0; + this._view[1] = y || 0; + this._view[2] = z || 0; }; /** * @property BYTES_PER_ELEMENT @@ -191,31 +185,25 @@ cc.Vertex3F.BYTES_PER_ELEMENT = 12; _p = cc.Vertex3F.prototype; _p._getX = function () { - return this._xF32[0]; + return this._view[0]; }; _p._setX = function (xValue) { - this._xF32[0] = xValue; + this._view[0] = xValue; }; _p._getY = function () { - return this._yF32[0]; + return this._view[1]; }; _p._setY = function (yValue) { - this._yF32[0] = yValue; + this._view[1] = yValue; }; _p._getZ = function () { - return this._zF32[0]; + return this._view[2]; }; _p._setZ = function (zValue) { - this._zF32[0] = zValue; + this._view[2] = zValue; }; -/** @expose */ -_p.x; cc.js.getset(_p, "x", _p._getX, _p._setX); -/** @expose */ -_p.y; cc.js.getset(_p, "y", _p._getY, _p._setY); -/** @expose */ -_p.z; cc.js.getset(_p, "z", _p._getZ, _p._setZ); // redefine cc.Tex2F @@ -235,10 +223,9 @@ cc.Tex2F = function (u, v, arrayBuffer, offset) { this._arrayBuffer = arrayBuffer || new ArrayBuffer(cc.Tex2F.BYTES_PER_ELEMENT); this._offset = offset || 0; - this._uF32 = new Float32Array(this._arrayBuffer, this._offset, 1); - this._vF32 = new Float32Array(this._arrayBuffer, this._offset + 4, 1); - this._uF32[0] = u || 0; - this._vF32[0] = v || 0; + this._view = new Float32Array(this._arrayBuffer, this._offset, 2); + this._view[0] = u || 0; + this._view[1] = v || 0; }; /** * @property BYTES_PER_ELEMENT @@ -249,22 +236,18 @@ cc.Tex2F.BYTES_PER_ELEMENT = 8; _p = cc.Tex2F.prototype; _p._getU = function () { - return this._uF32[0]; + return this._view[0]; }; _p._setU = function (xValue) { - this._uF32[0] = xValue; + this._view[0] = xValue; }; _p._getV = function () { - return this._vF32[0]; + return this._view[1]; }; _p._setV = function (yValue) { - this._vF32[0] = yValue; + this._view[1] = yValue; }; -/** @expose */ -_p.u; cc.js.getset(_p, "u", _p._getU, _p._setU); -/** @expose */ -_p.v; cc.js.getset(_p, "v", _p._getV, _p._setV); //redefine cc.Quad2 @@ -287,11 +270,14 @@ cc.Quad2 = function (tl, tr, bl, br, arrayBuffer, offset) { this._arrayBuffer = arrayBuffer || new ArrayBuffer(cc.Quad2.BYTES_PER_ELEMENT); this._offset = offset || 0; - var locArrayBuffer = this._arrayBuffer, locElementLen = cc.Vertex2F.BYTES_PER_ELEMENT; - this._tl = tl ? new cc.Vertex2F(tl.x, tl.y, locArrayBuffer, 0) : new cc.Vertex2F(0, 0, locArrayBuffer, 0); - this._tr = tr ? new cc.Vertex2F(tr.x, tr.y, locArrayBuffer, locElementLen) : new cc.Vertex2F(0, 0, locArrayBuffer, locElementLen); - this._bl = bl ? new cc.Vertex2F(bl.x, bl.y, locArrayBuffer, locElementLen * 2) : new cc.Vertex2F(0, 0, locArrayBuffer, locElementLen * 2); - this._br = br ? new cc.Vertex2F(br.x, br.y, locArrayBuffer, locElementLen * 3) : new cc.Vertex2F(0, 0, locArrayBuffer, locElementLen * 3); + var locArrayBuffer = this._arrayBuffer, locOffset = this._offset, locElementLen = cc.Vertex2F.BYTES_PER_ELEMENT; + this._tl = tl ? new cc.Vertex2F(tl.x, tl.y, locArrayBuffer, locOffset) : new cc.Vertex2F(0, 0, locArrayBuffer, locOffset); + locOffset += locElementLen; + this._tr = tr ? new cc.Vertex2F(tr.x, tr.y, locArrayBuffer, locOffset) : new cc.Vertex2F(0, 0, locArrayBuffer, locOffset); + locOffset += locElementLen; + this._bl = bl ? new cc.Vertex2F(bl.x, bl.y, locArrayBuffer, locOffset) : new cc.Vertex2F(0, 0, locArrayBuffer, locOffset); + locOffset += locElementLen; + this._br = br ? new cc.Vertex2F(br.x, br.y, locArrayBuffer, locOffset) : new cc.Vertex2F(0, 0, locArrayBuffer, locOffset); }; /** * @property BYTES_PER_ELEMENT @@ -305,42 +291,34 @@ _p._getTL = function () { return this._tl; }; _p._setTL = function (tlValue) { - this._tl.x = tlValue.x; - this._tl.y = tlValue.y; + this._tl._view[0] = tlValue.x; + this._tl._view[1] = tlValue.y; }; _p._getTR = function () { return this._tr; }; _p._setTR = function (trValue) { - this._tr.x = trValue.x; - this._tr.y = trValue.y; + this._tr._view[0] = trValue.x; + this._tr._view[1] = trValue.y; }; _p._getBL = function() { return this._bl; }; _p._setBL = function (blValue) { - this._bl.x = blValue.x; - this._bl.y = blValue.y; + this._bl._view[0] = blValue.x; + this._bl._view[1] = blValue.y; }; _p._getBR = function () { return this._br; }; _p._setBR = function (brValue) { - this._br.x = brValue.x; - this._br.y = brValue.y; + this._br._view[0] = brValue.x; + this._br._view[1] = brValue.y; }; -/** @expose */ -_p.tl; cc.js.getset(_p, "tl", _p._getTL, _p._setTL); -/** @expose */ -_p.tr; cc.js.getset(_p, "tr", _p._getTR, _p._setTR); -/** @expose */ -_p.bl; cc.js.getset(_p, "bl", _p._getBL, _p._setBL); -/** @expose */ -_p.br; cc.js.getset(_p, "br", _p._getBR, _p._setBR); /** @@ -354,14 +332,28 @@ cc.js.getset(_p, "br", _p._getBR, _p._setBR); * @param {Vertex3F} br1 * @param {Vertex3F} tl1 * @param {Vertex3F} tr1 + * @param {Array} arrayBuffer + * @param {Number} offset * @return {Quad3} */ -cc.Quad3 = function (bl1, br1, tl1, tr1) { - this.bl = bl1 || new cc.Vertex3F(0, 0, 0); - this.br = br1 || new cc.Vertex3F(0, 0, 0); - this.tl = tl1 || new cc.Vertex3F(0, 0, 0); - this.tr = tr1 || new cc.Vertex3F(0, 0, 0); +cc.Quad3 = function (bl1, br1, tl1, tr1, arrayBuffer, offset) { + this._arrayBuffer = arrayBuffer || new ArrayBuffer(cc.Quad3.BYTES_PER_ELEMENT); + this._offset = offset || 0; + + var locArrayBuffer = this._arrayBuffer, locOffset = this._offset, locElementLen = cc.Vertex3F.BYTES_PER_ELEMENT; + this.bl = bl ? new cc.Vertex3F(bl.x, bl.y, bl.z, locArrayBuffer, locOffset) : new cc.Vertex3F(0, 0, 0, locArrayBuffer, locOffset); + locOffset += locElementLen; + this.br = br ? new cc.Vertex3F(br.x, br.y, br.z, locArrayBuffer, locOffset) : new cc.Vertex3F(0, 0, 0, locArrayBuffer, locOffset); + locOffset += locElementLen; + this.tl = tl ? new cc.Vertex3F(tl.x, tl.y, tl.z, locArrayBuffer, locOffset) : new cc.Vertex3F(0, 0, 0, locArrayBuffer, locOffset); + locOffset += locElementLen; + this.tr = tr ? new cc.Vertex3F(tr.x, tr.y, tr.z, locArrayBuffer, locOffset) : new cc.Vertex3F(0, 0, 0, locArrayBuffer, locOffset); }; +/** + * @constant + * @type {number} + */ +cc.Quad3.BYTES_PER_ELEMENT = 48; //redefine cc.V3F_C4B_T2F /** @@ -381,13 +373,17 @@ cc.V3F_C4B_T2F = function (vertices, colors, texCoords, arrayBuffer, offset) { this._arrayBuffer = arrayBuffer || new ArrayBuffer(cc.V3F_C4B_T2F.BYTES_PER_ELEMENT); this._offset = offset || 0; - var locArrayBuffer = this._arrayBuffer, locOffset = this._offset, locElementLen = cc.Vertex3F.BYTES_PER_ELEMENT; + var locArrayBuffer = this._arrayBuffer, locOffset = this._offset; this._vertices = vertices ? new cc.Vertex3F(vertices.x, vertices.y, vertices.z, locArrayBuffer, locOffset) : new cc.Vertex3F(0, 0, 0, locArrayBuffer, locOffset); - this._colors = colors ? new cc.WebGLColor(colors.r, colors.g, colors.b, colors.a, locArrayBuffer, locOffset + locElementLen) : - new cc.WebGLColor(0, 0, 0, 0, locArrayBuffer, locOffset + locElementLen); - this._texCoords = texCoords ? new cc.Tex2F(texCoords.u, texCoords.v, locArrayBuffer, locOffset + locElementLen + cc.WebGLColor.BYTES_PER_ELEMENT) : - new cc.Tex2F(0, 0, locArrayBuffer, locOffset + locElementLen + cc.WebGLColor.BYTES_PER_ELEMENT); + + locOffset += cc.Vertex3F.BYTES_PER_ELEMENT; + this._colors = colors ? new cc.WebGLColor(colors.r, colors.g, colors.b, colors.a, locArrayBuffer, locOffset) : + new cc.WebGLColor(0, 0, 0, 0, locArrayBuffer, locOffset); + + locOffset += cc.WebGLColor.BYTES_PER_ELEMENT; + this._texCoords = texCoords ? new cc.Tex2F(texCoords.u, texCoords.v, locArrayBuffer, locOffset) : + new cc.Tex2F(0, 0, locArrayBuffer, locOffset); }; /** * @method BYTES_PER_ELEMENT @@ -402,35 +398,29 @@ _p._getVertices = function () { }; _p._setVertices = function (verticesValue) { var locVertices = this._vertices; - locVertices.x = verticesValue.x; - locVertices.y = verticesValue.y; - locVertices.z = verticesValue.z; + locVertices._view[0] = verticesValue.x; + locVertices._view[1] = verticesValue.y; + locVertices._view[2] = verticesValue.z; }; _p._getColor = function () { return this._colors; }; _p._setColor = function (colorValue) { var locColors = this._colors; - locColors.r = colorValue.r; - locColors.g = colorValue.g; - locColors.b = colorValue.b; - locColors.a = colorValue.a; + locColors._view[0] = colorValue.r; + locColors._view[1] = colorValue.g; + locColors._view[2] = colorValue.b; + locColors._view[3] = colorValue.a; }; _p._getTexCoords = function () { return this._texCoords; }; _p._setTexCoords = function (texValue) { - this._texCoords.u = texValue.u; - this._texCoords.v = texValue.v; + this._texCoords._view[0] = texValue.u; + this._texCoords._view[1] = texValue.v; }; -/** @expose */ -_p.vertices; cc.js.getset(_p, "vertices", _p._getVertices, _p._setVertices); -/** @expose */ -_p.colors; cc.js.getset(_p, "colors", _p._getColor, _p._setColor); -/** @expose */ -_p.texCoords; cc.js.getset(_p, "texCoords", _p._getTexCoords, _p._setTexCoords); //redefine cc.V3F_C4B_T2F_Quad @@ -455,12 +445,15 @@ cc.V3F_C4B_T2F_Quad = function (tl, bl, tr, br, arrayBuffer, offset) { var locArrayBuffer = this._arrayBuffer, locOffset = this._offset, locElementLen = cc.V3F_C4B_T2F.BYTES_PER_ELEMENT; this._tl = tl ? new cc.V3F_C4B_T2F(tl.vertices, tl.colors, tl.texCoords, locArrayBuffer, locOffset) : new cc.V3F_C4B_T2F(null, null, null, locArrayBuffer, locOffset); - this._bl = bl ? new cc.V3F_C4B_T2F(bl.vertices, bl.colors, bl.texCoords, locArrayBuffer, locOffset + locElementLen) : - new cc.V3F_C4B_T2F(null, null, null, locArrayBuffer, locOffset + locElementLen); - this._tr = tr ? new cc.V3F_C4B_T2F(tr.vertices, tr.colors, tr.texCoords, locArrayBuffer, locOffset + locElementLen * 2) : - new cc.V3F_C4B_T2F(null, null, null, locArrayBuffer, locOffset + locElementLen * 2); - this._br = br ? new cc.V3F_C4B_T2F(br.vertices, br.colors, br.texCoords, locArrayBuffer, locOffset + locElementLen * 3) : - new cc.V3F_C4B_T2F(null, null, null, locArrayBuffer, locOffset + locElementLen * 3); + locOffset += locElementLen; + this._bl = bl ? new cc.V3F_C4B_T2F(bl.vertices, bl.colors, bl.texCoords, locArrayBuffer, locOffset) : + new cc.V3F_C4B_T2F(null, null, null, locArrayBuffer, locOffset); + locOffset += locElementLen; + this._tr = tr ? new cc.V3F_C4B_T2F(tr.vertices, tr.colors, tr.texCoords, locArrayBuffer, locOffset) : + new cc.V3F_C4B_T2F(null, null, null, locArrayBuffer, locOffset); + locOffset += locElementLen; + this._br = br ? new cc.V3F_C4B_T2F(br.vertices, br.colors, br.texCoords, locArrayBuffer, locOffset) : + new cc.V3F_C4B_T2F(null, null, null, locArrayBuffer, locOffset); }; /** * @property BYTES_PER_ELEMENT @@ -509,20 +502,10 @@ _p._getArrayBuffer = function () { return this._arrayBuffer; }; -/** @expose */ -_p.tl; cc.js.getset(_p, "tl", _p._getTL, _p._setTL); -/** @expose */ -_p.tr; cc.js.getset(_p, "tr", _p._getTR, _p._setTR); -/** @expose */ -_p.bl; cc.js.getset(_p, "bl", _p._getBL, _p._setBL); -/** @expose */ -_p.br; cc.js.getset(_p, "br", _p._getBR, _p._setBR); -/** @expose */ -_p.arrayBuffer; cc.js.get(_p, "arrayBuffer", _p._getArrayBuffer); /** @@ -600,13 +583,15 @@ cc.V2F_C4B_T2F = function (vertices, colors, texCoords, arrayBuffer, offset) { this._arrayBuffer = arrayBuffer || new ArrayBuffer(cc.V2F_C4B_T2F.BYTES_PER_ELEMENT); this._offset = offset || 0; - var locArrayBuffer = this._arrayBuffer, locOffset = this._offset, locElementLen = cc.Vertex2F.BYTES_PER_ELEMENT; + var locArrayBuffer = this._arrayBuffer, locOffset = this._offset; this._vertices = vertices ? new cc.Vertex2F(vertices.x, vertices.y, locArrayBuffer, locOffset) : new cc.Vertex2F(0, 0, locArrayBuffer, locOffset); - this._colors = colors ? new cc.WebGLColor(colors.r, colors.g, colors.b, colors.a, locArrayBuffer, locOffset + locElementLen) : - new cc.WebGLColor(0, 0, 0, 0, locArrayBuffer, locOffset + locElementLen); - this._texCoords = texCoords ? new cc.Tex2F(texCoords.u, texCoords.v, locArrayBuffer, locOffset + locElementLen + cc.WebGLColor.BYTES_PER_ELEMENT) : - new cc.Tex2F(0, 0, locArrayBuffer, locOffset + locElementLen + cc.WebGLColor.BYTES_PER_ELEMENT); + locOffset += cc.Vertex2F.BYTES_PER_ELEMENT; + this._colors = colors ? new cc.WebGLColor(colors.r, colors.g, colors.b, colors.a, locArrayBuffer, locOffset) : + new cc.WebGLColor(0, 0, 0, 0, locArrayBuffer, locOffset); + locOffset += cc.WebGLColor.BYTES_PER_ELEMENT; + this._texCoords = texCoords ? new cc.Tex2F(texCoords.u, texCoords.v, locArrayBuffer, locOffset) : + new cc.Tex2F(0, 0, locArrayBuffer, locOffset); }; /** @@ -620,35 +605,29 @@ _p._getVertices = function () { return this._vertices; }; _p._setVertices = function (verticesValue) { - this._vertices.x = verticesValue.x; - this._vertices.y = verticesValue.y; + this._vertices._view[0] = verticesValue.x; + this._vertices._view[1] = verticesValue.y; }; _p._getColor = function () { return this._colors; }; _p._setColor = function (colorValue) { var locColors = this._colors; - locColors.r = colorValue.r; - locColors.g = colorValue.g; - locColors.b = colorValue.b; - locColors.a = colorValue.a; + locColors._view[0] = colorValue.r; + locColors._view[1] = colorValue.g; + locColors._view[2] = colorValue.b; + locColors._view[3] = colorValue.a; }; _p._getTexCoords = function () { return this._texCoords; }; _p._setTexCoords = function (texValue) { - this._texCoords.u = texValue.u; - this._texCoords.v = texValue.v; + this._texCoords._view[0] = texValue.u; + this._texCoords._view[1] = texValue.v; }; -/** @expose */ -_p.vertices; cc.js.getset(_p, "vertices", _p._getVertices, _p._setVertices); -/** @expose */ -_p.colors; cc.js.getset(_p, "colors", _p._getColor, _p._setColor); -/** @expose */ -_p.texCoords; cc.js.getset(_p, "texCoords", _p._getTexCoords, _p._setTexCoords); //redefine cc.V2F_C4B_T2F_Triangle @@ -672,10 +651,12 @@ cc.V2F_C4B_T2F_Triangle = function (a, b, c, arrayBuffer, offset) { var locArrayBuffer = this._arrayBuffer, locOffset = this._offset, locElementLen = cc.V2F_C4B_T2F.BYTES_PER_ELEMENT; this._a = a ? new cc.V2F_C4B_T2F(a.vertices, a.colors, a.texCoords, locArrayBuffer, locOffset) : new cc.V2F_C4B_T2F(null, null, null, locArrayBuffer, locOffset); - this._b = b ? new cc.V2F_C4B_T2F(b.vertices, b.colors, b.texCoords, locArrayBuffer, locOffset + locElementLen) : - new cc.V2F_C4B_T2F(null, null, null, locArrayBuffer, locOffset + locElementLen); - this._c = c ? new cc.V2F_C4B_T2F(c.vertices, c.colors, c.texCoords, locArrayBuffer, locOffset + locElementLen * 2) : - new cc.V2F_C4B_T2F(null, null, null, locArrayBuffer, locOffset + locElementLen * 2); + locOffset += locElementLen; + this._b = b ? new cc.V2F_C4B_T2F(b.vertices, b.colors, b.texCoords, locArrayBuffer, locOffset) : + new cc.V2F_C4B_T2F(null, null, null, locArrayBuffer, locOffset); + locOffset += locElementLen; + this._c = c ? new cc.V2F_C4B_T2F(c.vertices, c.colors, c.texCoords, locArrayBuffer, locOffset) : + new cc.V2F_C4B_T2F(null, null, null, locArrayBuffer, locOffset); }; /** * property BYTES_PER_ELEMENT @@ -712,12 +693,6 @@ _p._setC = function (cValue) { locC.texCoords = cValue.texCoords; }; -/** @expose */ -_p.a; cc.js.getset(_p, "a", _p._getA, _p._setA); -/** @expose */ -_p.b; cc.js.getset(_p, "b", _p._getB, _p._setB); -/** @expose */ -_p.c; -cc.js.getset(_p, "c", _p._getC, _p._setC); \ No newline at end of file +cc.js.getset(_p, "c", _p._getC, _p._setC); diff --git a/cocos2d/core/videoplayer/CCSGVideoPlayer.js b/cocos2d/core/videoplayer/CCSGVideoPlayer.js index 7efcb0cfad..4dc4b8bfe2 100644 --- a/cocos2d/core/videoplayer/CCSGVideoPlayer.js +++ b/cocos2d/core/videoplayer/CCSGVideoPlayer.js @@ -35,6 +35,7 @@ _ccsg.VideoPlayer = _ccsg.Node.extend(/** @lends _ccsg.VideoPlayer# */{ _ccsg.Node.prototype.ctor.call(this); // 播放结束等事件处理的队列 this._EventList = {}; + this._renderCmd.createDom(); }, _createRenderCmd: function(){ @@ -73,6 +74,12 @@ _ccsg.VideoPlayer = _ccsg.Node.extend(/** @lends _ccsg.VideoPlayer# */{ return this._renderCmd.isPlaying(); }, + createDomElementIfNeeded: function () { + if (!this._renderCmd._video) { + this._renderCmd.createDom(); + } + }, + setKeepAspectRatioEnabled: function () { cc.log("On the web is always keep the aspect ratio"); }, @@ -254,12 +261,8 @@ _ccsg.VideoPlayer.EventType = { var proto = _ccsg.VideoPlayer.RenderCmd.prototype = Object.create(_ccsg.Node.CanvasRenderCmd.prototype); proto.constructor = _ccsg.VideoPlayer.RenderCmd; - proto.resize = function () { - - }; - proto.transform = function (parentCmd, recursive) { - _ccsg.Node.CanvasRenderCmd.prototype.transform.call(this, parentCmd, recursive); + this.originTransform(parentCmd, recursive); this.updateMatrix(); }; @@ -267,8 +270,7 @@ _ccsg.VideoPlayer.EventType = { if (!this._video) return; var node = this._node, scaleX = cc.view._scaleX, scaleY = cc.view._scaleY; var dpr = cc.view._devicePixelRatio; - var t = node.getNodeToWorldTransform(); - if (!t) return; + var t = this._worldTransform; scaleX /= dpr; scaleY /= dpr; @@ -297,9 +299,6 @@ _ccsg.VideoPlayer.EventType = { var source, video, extname; var node = this._node; - if (!this._video) { - this.createDom(); - } if (this._url == path) { return; @@ -312,6 +311,7 @@ _ccsg.VideoPlayer.EventType = { this.removeDom(); this.createDom(); + this.bindEvent(); video = this._video; @@ -418,6 +418,7 @@ _ccsg.VideoPlayer.EventType = { cc.container.removeChild(video); } this._video = null; + this._url = ""; }; proto.updateSize = function (width, height) { diff --git a/cocos2d/deprecated.js b/cocos2d/deprecated.js index 08a2953457..9cc425071f 100644 --- a/cocos2d/deprecated.js +++ b/cocos2d/deprecated.js @@ -12,15 +12,17 @@ if (CC_DEV) { /** * Inject all of the properties in source objects to target object and return the target object. * @param {object} target - * @param {object} *sources + * @param {object} source * @name cc.inject * @memberof cc * @deprecated * @returns {object} */ js.get(cc, "inject", function () { - cc.warn(INFO + " The first argument should be the destination object", 'cc.inject', 'cc.js.addon'); - return js.addon; + cc.warn(INFO + " The first argument should be the destination object", 'cc.inject', 'cc.js.mixin'); + return function (lhs, rhs) { + return js.mixin(rhs, lhs); + } }); /** diff --git a/cocos2d/labels/CCLabelAtlasCanvasRenderCmd.js b/cocos2d/labels/CCLabelAtlasCanvasRenderCmd.js index 680108c5ae..fb747ee349 100644 --- a/cocos2d/labels/CCLabelAtlasCanvasRenderCmd.js +++ b/cocos2d/labels/CCLabelAtlasCanvasRenderCmd.js @@ -104,7 +104,7 @@ } }; - proto._addChild = function(){ + proto._addChild = function(child){ child._lateChild = true; }; })(); \ No newline at end of file diff --git a/cocos2d/labels/CCLabelAtlasWebGLRenderCmd.js b/cocos2d/labels/CCLabelAtlasWebGLRenderCmd.js index d6bf60bf63..0ea80cfa2d 100644 --- a/cocos2d/labels/CCLabelAtlasWebGLRenderCmd.js +++ b/cocos2d/labels/CCLabelAtlasWebGLRenderCmd.js @@ -31,6 +31,23 @@ var proto = cc.LabelAtlas.WebGLRenderCmd.prototype = Object.create(cc.AtlasNode.WebGLRenderCmd.prototype); proto.constructor = cc.LabelAtlas.WebGLRenderCmd; + proto._updateColor = function () { + if (this._colorF32Array) { + var locDisplayedColor = this._displayedColor; + var a = this._displayedOpacity / 255, coef; + if (this._node._opacityModifyRGB) { + coef = a / 255; + } + else { + coef = 1 / 255; + } + this._colorF32Array[0] = locDisplayedColor.r * coef; + this._colorF32Array[1] = locDisplayedColor.g * coef; + this._colorF32Array[2] = locDisplayedColor.b * coef; + this._colorF32Array[3] = a; + } + }; + proto.setCascade = function(){ var node = this._node; node._cascadeOpacityEnabled = true; @@ -67,8 +84,6 @@ if (n > locTextureAtlas.getCapacity()) cc.log("cc.LabelAtlas._updateAtlasValues(): Invalid String length"); var quads = locTextureAtlas.quads; - var locDisplayedColor = this._displayedColor; - var curColor = {r: locDisplayedColor.r, g: locDisplayedColor.g, b: locDisplayedColor.b, a: node._displayedOpacity}; var locItemWidth = node._itemWidth; var locItemHeight = node._itemHeight; for (var i = 0, cr = -1; i < n; i++) { @@ -117,11 +132,10 @@ locQuadTR.vertices.x = cr * locItemWidth + locItemWidth; locQuadTR.vertices.y = node._itemHeight; locQuadTR.vertices.z = 0.0; - locQuadTL.colors = curColor; - locQuadTR.colors = curColor; - locQuadBL.colors = curColor; - locQuadBR.colors = curColor; } + + this._updateColor(); + this.updateContentSize(i, cr+1); if (n > 0) { locTextureAtlas.dirty = true; @@ -146,4 +160,4 @@ }; proto._addChild = function(){}; -})(); \ No newline at end of file +})(); diff --git a/cocos2d/labels/CCLabelBMFont.js b/cocos2d/labels/CCLabelBMFont.js index 0f75d76df5..dd574cadfe 100644 --- a/cocos2d/labels/CCLabelBMFont.js +++ b/cocos2d/labels/CCLabelBMFont.js @@ -109,8 +109,6 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{ _lineBreakWithoutSpaces: false, _imageOffset: null, - _reusedChar: null, - _textureLoaded: false, _className: "LabelBMFont", @@ -156,7 +154,6 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{ cc.EventTarget.call(this); this._imageOffset = cc.p(0, 0); - this._reusedChar = []; this._cascadeColorEnabled = true; this._cascadeOpacityEnabled = true; this.initWithString(str, fntFile, width, alignment, imageOffset); @@ -227,7 +224,6 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{ */ initWithString: function (str, fntFile, width, alignment, imageOffset) { var self = this, theString = str || ""; - var cmd = this._renderCmd; if (self._config) cc.log("cc.LabelBMFont.initWithString(): re-init is no longer supported"); @@ -265,7 +261,7 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{ if (self.initWithTexture(texture, theString.length)) { self._alignment = alignment || cc.TextAlignment.LEFT; self._imageOffset = imageOffset || cc.p(0, 0); - self._width = (width == null) ? -1 : width; + self._width = (width === undefined) ? -1 : width; self._realOpacity = 255; self._realColor = cc.color(255, 255, 255, 255); @@ -275,8 +271,6 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{ self.setAnchorPoint(0.5, 0.5); - this._renderCmd._initBatchTexture(); - self.setString(theString, true); return true; } @@ -289,7 +283,7 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{ createFontChars: function () { var self = this; var cmd = this._renderCmd; - var locTexture = cmd._texture || self.textureAtlas.texture; + var locTexture = cmd._texture || this._texture; var nextFontPositionX = 0; @@ -315,6 +309,7 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{ var nextFontPositionY = -(locCommonH - locCommonH * quantityOfLines); var prev = -1; + var fontDef; for (i = 0; i < stringLen; i++) { var key = locStr.charCodeAt(i); if (key === 0) continue; @@ -327,7 +322,7 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{ } var kerningAmount = locKerningDict[(prev << 16) | (key & 0xffff)] || 0; - var fontDef = locFontDict[key]; + fontDef = locFontDict[key]; if (!fontDef) { cc.log("cocos2d: LabelBMFont: character not found " + locStr[i]); @@ -350,18 +345,18 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{ var fontChar = self.getChildByTag(i); - if(!fontChar){ + if (!fontChar) { fontChar = new _ccsg.Sprite(); fontChar.initWithTexture(locTexture, rect, false); fontChar._newTextureWhenChangeColor = true; this.addChild(fontChar, 0, i); - }else{ - this._renderCmd._updateCharTexture(fontChar, rect, key); + } else { + cmd._updateCharTexture(fontChar, rect, key); } // Apply label properties fontChar.opacityModifyRGB = this._opacityModifyRGB; - this._renderCmd._updateCharColorAndOpacity(fontChar); + cmd._updateCharColorAndOpacity(fontChar); var yOffset = locCfg.commonHeight - fontDef.yOffset; var fontPos = cc.p(nextFontPositionX + fontDef.xOffset + fontDef.rect.width * 0.5 + kerningAmount, @@ -725,12 +720,11 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{ var texture = cc.textureCache.addImage(newConf.atlasName); var locIsLoaded = texture.isLoaded(); self._textureLoaded = locIsLoaded; - self.texture = texture; if (!locIsLoaded) { texture.once("load", function (event) { var self1 = this; self1._textureLoaded = true; - self1.texture = texture; + self1.setTexture(texture); self1.createFontChars(); self1._changeTextureColor(); self1.updateLabel(); @@ -738,6 +732,7 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{ self1.emit("load"); }, self); } else { + self.setTexture(texture); self.createFontChars(); } } @@ -752,6 +747,7 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{ }, setTexture: function(texture){ + this._texture = texture; this._renderCmd.setTexture(texture); }, @@ -851,6 +847,9 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{ /** @expose */ p.textAlign; cc.defineGetterSetter(p, "textAlign", p._getAlignment, p.setAlignment); + + // Override properties + cc.defineGetterSetter(p, "texture", p.getTexture, p.setTexture); })(); /** diff --git a/cocos2d/labels/CCLabelBMFontCanvasRenderCmd.js b/cocos2d/labels/CCLabelBMFontCanvasRenderCmd.js index 2685c046e6..81296a916e 100644 --- a/cocos2d/labels/CCLabelBMFontCanvasRenderCmd.js +++ b/cocos2d/labels/CCLabelBMFontCanvasRenderCmd.js @@ -32,17 +32,12 @@ (function(){ cc.LabelBMFont.CanvasRenderCmd = function(renderableObject){ - cc.SpriteBatchNode.CanvasRenderCmd.call(this, renderableObject); - this._needDraw = true; + _ccsg.Node.CanvasRenderCmd.call(this, renderableObject); }; - var proto = cc.LabelBMFont.CanvasRenderCmd.prototype = Object.create(cc.SpriteBatchNode.CanvasRenderCmd.prototype); + var proto = cc.LabelBMFont.CanvasRenderCmd.prototype = Object.create(_ccsg.Node.CanvasRenderCmd.prototype); proto.constructor = cc.LabelBMFont.CanvasRenderCmd; - proto.rendering = function(){ - void 0; - }; - proto._updateCharTexture = function(fontChar, rect, key){ if (key === 32) { fontChar.setTextureRect(rect, false, cc.size(0, 0)); @@ -70,27 +65,28 @@ var selChild = locChildren[i]; var cm = selChild._renderCmd; var childDColor = cm._displayedColor; - if (this._texture !== cm._texture && (childDColor.r !== locDisplayedColor.r || + if (node._texture !== cm._texture && (childDColor.r !== locDisplayedColor.r || childDColor.g !== locDisplayedColor.g || childDColor.b !== locDisplayedColor.b)) continue; selChild.texture = texture; } - this._texture = texture; + node._texture = texture; }; proto._changeTextureColor = function(){ var node = this._node; - var texture = this._textureToRender, + var texture = node._texture, contentSize = texture.getContentSize(); var oTexture = node._texture, oElement = oTexture.getHtmlElementObj(); var disColor = this._displayedColor; var textureRect = cc.rect(0, 0, oElement.width, oElement.height); - if(texture && contentSize.width > 0){ + if (texture && contentSize.width > 0) { if(!oElement) return; - this._textureToRender = oTexture._generateColorTexture(disColor.r, disColor.g, disColor.b, textureRect); + var textureToRender = oTexture._generateColorTexture(disColor.r, disColor.g, disColor.b, textureRect); + node.setTexture(textureToRender); } }; @@ -102,6 +98,4 @@ _ccsg.Node.prototype.updateDisplayedColor.call(locChild, this._displayedColor); }; - proto._initBatchTexture = function(){}; - -})(); \ No newline at end of file +})(); diff --git a/cocos2d/labels/CCLabelBMFontWebGLRenderCmd.js b/cocos2d/labels/CCLabelBMFontWebGLRenderCmd.js index 9c5f202817..d7d413e55a 100644 --- a/cocos2d/labels/CCLabelBMFontWebGLRenderCmd.js +++ b/cocos2d/labels/CCLabelBMFontWebGLRenderCmd.js @@ -32,13 +32,16 @@ (function(){ cc.LabelBMFont.WebGLRenderCmd = function(renderableObject){ - cc.SpriteBatchNode.WebGLRenderCmd.call(this, renderableObject); - this._needDraw = true; + _ccsg.Node.WebGLRenderCmd.call(this, renderableObject); }; - var proto = cc.LabelBMFont.WebGLRenderCmd.prototype = Object.create(cc.SpriteBatchNode.WebGLRenderCmd.prototype); + var proto = cc.LabelBMFont.WebGLRenderCmd.prototype = Object.create(_ccsg.Node.WebGLRenderCmd.prototype); proto.constructor = cc.LabelBMFont.WebGLRenderCmd; + proto.setTexture = function (texture) { + this._node.setOpacityModifyRGB(this._node._texture.hasPremultipliedAlpha()); + }; + proto._updateCharTexture = function(fontChar, rect, key){ // updating previous sprite fontChar.setTextureRect(rect, false); @@ -48,37 +51,5 @@ proto._changeTextureColor = function(){}; - proto._updateChildrenDisplayedOpacity = function(locChild){ - locChild.updateDisplayedOpacity(this._displayedOpacity); - }; - - proto._updateChildrenDisplayedColor = function(locChild){ - locChild.updateDisplayedColor(this._displayedColor); - }; - - proto._initBatchTexture = function(){ - var node = this._node; - var locTexture = node.textureAtlas.texture; - node._opacityModifyRGB = locTexture.hasPremultipliedAlpha(); - - var reusedChar = node._reusedChar = new _ccsg.Sprite(); - reusedChar.initWithTexture(locTexture, cc.rect(0, 0, 0, 0), false); - reusedChar.batchNode = node; - }; - - proto.rendering = function(ctx){ - cc.SpriteBatchNode.WebGLRenderCmd.prototype.rendering.call(this, ctx); - - var node = this._node; - //LabelBMFont - Debug draw - if (cc.macro.LABELBMFONT_DEBUG_DRAW) { - var size = node.getContentSize(); - var pos = cc.p(0 | ( -this._anchorPointInPoints.x), 0 | ( -this._anchorPointInPoints.y)); - var vertices = [cc.p(pos.x, pos.y), cc.p(pos.x + size.width, pos.y), cc.p(pos.x + size.width, pos.y + size.height), cc.p(pos.x, pos.y + size.height)]; - cc._drawingUtil.setDrawColor(0, 255, 0, 255); - cc._drawingUtil.drawPoly(vertices, 4, true); - } - }; - proto._updateCharColorAndOpacity = function(){}; -})(); \ No newline at end of file +})(); diff --git a/cocos2d/motion-streak/CCMotionStreakWebGLRenderCmd.js b/cocos2d/motion-streak/CCMotionStreakWebGLRenderCmd.js deleted file mode 100644 index 5a3415937c..0000000000 --- a/cocos2d/motion-streak/CCMotionStreakWebGLRenderCmd.js +++ /dev/null @@ -1,66 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013-2014 Chukong Technologies Inc. - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -cc.MotionStreak.WebGLRenderCmd = function(renderableObject){ - _ccsg.Node.WebGLRenderCmd.call(this, renderableObject); - this._needDraw = true; - this._shaderProgram = cc.shaderCache.programForKey(cc.macro.SHADER_POSITION_TEXTURECOLOR); -}; - -cc.MotionStreak.WebGLRenderCmd.prototype = Object.create(_ccsg.Node.WebGLRenderCmd.prototype); -cc.MotionStreak.WebGLRenderCmd.prototype.constructor = _ccsg.Sprite.WebGLRenderCmd; - -cc.MotionStreak.WebGLRenderCmd.prototype.rendering = function(ctx){ - var node = this._node; - if (node._nuPoints <= 1) - return; - - if (node.texture && node.texture.isLoaded()) { - ctx = ctx || cc._renderContext; - this._shaderProgram.use(); - this._shaderProgram._setUniformForMVPMatrixWithMat4(this._stackMatrix); - cc.gl.enableVertexAttribs(cc.macro.VERTEX_ATTRIB_FLAG_POS_COLOR_TEX); - cc.gl.blendFunc(node._blendFunc.src, node._blendFunc.dst); - - cc.gl.bindTexture2D(node.texture); - - //position - ctx.bindBuffer(ctx.ARRAY_BUFFER, node._verticesBuffer); - ctx.bufferData(ctx.ARRAY_BUFFER, node._vertices, ctx.DYNAMIC_DRAW); - ctx.vertexAttribPointer(cc.macro.VERTEX_ATTRIB_POSITION, 2, ctx.FLOAT, false, 0, 0); - - //texcoords - ctx.bindBuffer(ctx.ARRAY_BUFFER, node._texCoordsBuffer); - ctx.bufferData(ctx.ARRAY_BUFFER, node._texCoords, ctx.DYNAMIC_DRAW); - ctx.vertexAttribPointer(cc.macro.VERTEX_ATTRIB_TEX_COORDS, 2, ctx.FLOAT, false, 0, 0); - - //colors - ctx.bindBuffer(ctx.ARRAY_BUFFER, node._colorPointerBuffer); - ctx.bufferData(ctx.ARRAY_BUFFER, node._colorPointer, ctx.DYNAMIC_DRAW); - ctx.vertexAttribPointer(cc.macro.VERTEX_ATTRIB_COLOR, 4, ctx.UNSIGNED_BYTE, true, 0, 0); - - ctx.drawArrays(ctx.TRIANGLE_STRIP, 0, node._nuPoints * 2); - cc.g_NumberOfDraws++; - } -}; \ No newline at end of file diff --git a/cocos2d/motion-streak/CCSGMotionStreak.js b/cocos2d/motion-streak/CCSGMotionStreak.js index 713bb53ecf..e06fdc7ea4 100644 --- a/cocos2d/motion-streak/CCSGMotionStreak.js +++ b/cocos2d/motion-streak/CCSGMotionStreak.js @@ -308,9 +308,8 @@ _ccsg.MotionStreak = _ccsg.Node.extend({ * @param {cc.Texture2D} texture */ setTexture:function (texture) { - if (texture && this.texture !== texture) { + if (this.texture !== texture) this.texture = texture; - } }, /** diff --git a/cocos2d/motion-streak/CCSGMotionStreakWebGLRenderCmd.js b/cocos2d/motion-streak/CCSGMotionStreakWebGLRenderCmd.js index f6c5f6641a..fa12648aaa 100644 --- a/cocos2d/motion-streak/CCSGMotionStreakWebGLRenderCmd.js +++ b/cocos2d/motion-streak/CCSGMotionStreakWebGLRenderCmd.js @@ -25,6 +25,8 @@ _ccsg.MotionStreak.WebGLRenderCmd = function(renderableObject){ _ccsg.Node.WebGLRenderCmd.call(this, renderableObject); this._needDraw = true; + this._matrix = new cc.math.Matrix4(); + this._matrix.identity(); this._shaderProgram = cc.shaderCache.programForKey(cc.macro.SHADER_POSITION_TEXTURECOLOR); }; @@ -42,12 +44,23 @@ _ccsg.MotionStreak.WebGLRenderCmd.prototype.rendering = function(ctx){ // update the color this._updateDisplayColor(); + var wt = this._worldTransform, mat = this._matrix.mat; + mat[0] = wt.a; + mat[4] = wt.c; + mat[12] = wt.tx; + mat[1] = wt.b; + mat[5] = wt.d; + mat[13] = wt.ty; + this._shaderProgram.use(); - this._shaderProgram._setUniformForMVPMatrixWithMat4(this._stackMatrix); - cc.gl.enableVertexAttribs(cc.macro.VERTEX_ATTRIB_FLAG_POS_COLOR_TEX); + this._shaderProgram._setUniformForMVPMatrixWithMat4(this._matrix); cc.gl.blendFunc(node._blendFunc.src, node._blendFunc.dst); - cc.gl.bindTexture2D(node.texture); + cc.gl.bindTexture2DN(0, node.texture); + + ctx.enableVertexAttribArray(cc.macro.VERTEX_ATTRIB_POSITION); + ctx.enableVertexAttribArray(cc.macro.VERTEX_ATTRIB_COLOR); + ctx.enableVertexAttribArray(cc.macro.VERTEX_ATTRIB_TEX_COORDS); //position ctx.bindBuffer(ctx.ARRAY_BUFFER, node._verticesBuffer); @@ -67,4 +80,4 @@ _ccsg.MotionStreak.WebGLRenderCmd.prototype.rendering = function(ctx){ ctx.drawArrays(ctx.TRIANGLE_STRIP, 0, node._nuPoints * 2); cc.g_NumberOfDraws++; } -}; \ No newline at end of file +}; diff --git a/cocos2d/node-grid/CCNodeGrid.js b/cocos2d/node-grid/CCNodeGrid.js index 0e59aa5904..7e1f6eb95e 100644 --- a/cocos2d/node-grid/CCNodeGrid.js +++ b/cocos2d/node-grid/CCNodeGrid.js @@ -82,46 +82,6 @@ cc.NodeGrid = _ccsg.Node.extend({ this._target = target; }, - _transformForWebGL: function () { - //optimize performance for javascript - var t4x4 = this._transform4x4, topMat4 = cc.current_stack.top; - - // Convert 3x3 into 4x4 matrix - var trans = this.getNodeToParentTransform(); - var t4x4Mat = t4x4.mat; - t4x4Mat[0] = trans.a; - t4x4Mat[4] = trans.c; - t4x4Mat[12] = trans.tx; - t4x4Mat[1] = trans.b; - t4x4Mat[5] = trans.d; - t4x4Mat[13] = trans.ty; - - // Update Z vertex manually - //this._transform4x4.mat[14] = this._vertexZ; - t4x4Mat[14] = this._vertexZ; - - //optimize performance for Javascript - topMat4.multiply(t4x4) ; // = cc.math.glMultMatrix(this._transform4x4); - - // XXX: Expensive calls. Camera should be integrated into the cached affine matrix - if (this._camera !== null && !(this.grid && this.grid.isActive())) { - var app = this._renderCmd._anchorPointInPoints, - apx = app.x, apy = app.y, - translate = (apx !== 0.0 || apy !== 0.0); - if (translate) { - if(!cc.macro.SPRITEBATCHNODE_RENDER_SUBPIXEL) { - apx = 0 | apx; - apy = 0 | apy; - } - cc.kmGLTranslatef(apx, apy, 0); - this._camera.locate(); - cc.kmGLTranslatef(-apx, -apy, 0); - } else { - this._camera.locate(); - } - } - }, - _createRenderCmd: function(){ if (cc._renderType === cc.game.RENDER_TYPE_WEBGL) return new cc.NodeGrid.WebGLRenderCmd(this); @@ -147,4 +107,4 @@ cc.defineGetterSetter(_p, "target", null, _p.setTarget); */ cc.NodeGrid.create = function () { return new cc.NodeGrid(); -}; \ No newline at end of file +}; diff --git a/cocos2d/particle/CCParticleBatchNodeWebGLRenderCmd.js b/cocos2d/particle/CCParticleBatchNodeWebGLRenderCmd.js index 21b5d64b23..7f360a7fc0 100644 --- a/cocos2d/particle/CCParticleBatchNodeWebGLRenderCmd.js +++ b/cocos2d/particle/CCParticleBatchNodeWebGLRenderCmd.js @@ -28,6 +28,8 @@ cc.ParticleBatchNode.WebGLRenderCmd = function(renderable){ _ccsg.Node.WebGLRenderCmd.call(this, renderable); this._needDraw = true; + this._matrix = new cc.math.Matrix4(); + this._matrix.identity(); }; var proto = cc.ParticleBatchNode.WebGLRenderCmd.prototype = Object.create(_ccsg.Node.WebGLRenderCmd.prototype); @@ -38,8 +40,16 @@ proto.rendering = function (ctx) { if (_t.textureAtlas.totalQuads === 0) return; + var wt = this._worldTransform, mat = this._matrix.mat; + mat[0] = wt.a; + mat[4] = wt.c; + mat[12] = wt.tx; + mat[1] = wt.b; + mat[5] = wt.d; + mat[13] = wt.ty; + this._shaderProgram.use(); - this._shaderProgram._setUniformForMVPMatrixWithMat4(this._stackMatrix); + this._shaderProgram._setUniformForMVPMatrixWithMat4(this._matrix); cc.gl.blendFuncForParticle(_t._blendFunc.src, _t._blendFunc.dst); _t.textureAtlas.drawQuads(); }; @@ -60,13 +70,12 @@ proto.visit = function(parentCmd){ if (!node._visible) return; - var currentStack = cc.current_stack; - currentStack.stack.push(currentStack.top); + parentCmd = parentCmd || this.getParentRenderCmd(); + if (parentCmd) + this._curLevel = parentCmd._curLevel + 1; this._syncStatus(parentCmd); - currentStack.top = this._stackMatrix; - //this.draw(ctx); + cc.renderer.pushRenderCommand(this); this._dirtyFlag = 0; - cc.math.glPopMatrix(); -}; \ No newline at end of file +}; diff --git a/cocos2d/particle/CCParticleSystem.js b/cocos2d/particle/CCParticleSystem.js index c3c34ae941..862642e76f 100644 --- a/cocos2d/particle/CCParticleSystem.js +++ b/cocos2d/particle/CCParticleSystem.js @@ -665,7 +665,7 @@ var ParticleSystem = cc.Class({ extends: cc._RendererUnderSG, editor: CC_EDITOR && { menu: 'i18n:MAIN_MENU.component.renderers/ParticleSystem', - inspector: 'app://editor/page/inspector/particle-system/index.html', + inspector: 'packages://inspector/inspectors/comps/particle-system.js', playOnFocus: true, }, diff --git a/cocos2d/particle/CCSGParticleSystemCanvasRenderCmd.js b/cocos2d/particle/CCSGParticleSystemCanvasRenderCmd.js index b58029af27..b51f65ff5e 100644 --- a/cocos2d/particle/CCSGParticleSystemCanvasRenderCmd.js +++ b/cocos2d/particle/CCSGParticleSystemCanvasRenderCmd.js @@ -97,7 +97,7 @@ proto.updateStatus = function() { _ccsg.Node.CanvasRenderCmd.prototype.updateStatus.call(this); this._updateCurrentRegions(); this._regionFlag = _ccsg.Node.CanvasRenderCmd.RegionStatus.DirtyDouble; - this._dirtyFlag = this._dirtyFlag & _ccsg.Node._dirtyFlags.contentDirty ^ this._dirtyFlag; + this._dirtyFlag &= ~_ccsg.Node._dirtyFlags.contentDirty; }; proto.rendering = function (ctx, scaleX, scaleY) { diff --git a/cocos2d/particle/CCSGParticleSystemWebGLRenderCmd.js b/cocos2d/particle/CCSGParticleSystemWebGLRenderCmd.js index 9226f95cf6..6606d34567 100644 --- a/cocos2d/particle/CCSGParticleSystemWebGLRenderCmd.js +++ b/cocos2d/particle/CCSGParticleSystemWebGLRenderCmd.js @@ -29,6 +29,9 @@ _ccsg.ParticleSystem.WebGLRenderCmd = function(renderable){ _ccsg.Node.WebGLRenderCmd.call(this, renderable); this._needDraw = true; + this._matrix = new cc.math.Matrix4(); + this._matrix.identity(); + this._buffersVBO = [0, 0]; this._quads = []; this._indices = []; @@ -185,16 +188,26 @@ proto.rendering = function (ctx) { var gl = ctx || cc._renderContext; - this._shaderProgram.use(); - this._shaderProgram._setUniformForMVPMatrixWithMat4(this._stackMatrix); //; + var wt = this._worldTransform, mat = this._matrix.mat; + mat[0] = wt.a; + mat[4] = wt.c; + mat[12] = wt.tx; + mat[1] = wt.b; + mat[5] = wt.d; + mat[13] = wt.ty; - cc.gl.bindTexture2D(node._texture); + this._shaderProgram.use(); + this._shaderProgram._setUniformForMVPMatrixWithMat4(this._matrix); //; + + cc.gl.bindTexture2DN(0, node._texture); cc.gl.blendFuncForParticle(node._blendFunc.src, node._blendFunc.dst); // // Using VBO without VAO // - cc.gl.enableVertexAttribs(cc.macro.VERTEX_ATTRIB_FLAG_POS_COLOR_TEX); + gl.enableVertexAttribArray(cc.macro.VERTEX_ATTRIB_POSITION); + gl.enableVertexAttribArray(cc.macro.VERTEX_ATTRIB_COLOR); + gl.enableVertexAttribArray(cc.macro.VERTEX_ATTRIB_TEX_COORDS); gl.bindBuffer(gl.ARRAY_BUFFER, this._buffersVBO[0]); gl.vertexAttribPointer(cc.macro.VERTEX_ATTRIB_POSITION, 3, gl.FLOAT, false, 24, 0); // vertices @@ -358,7 +371,7 @@ proto._allocMemory = function(){ proto.postStep = function(){ var gl = cc._renderContext; gl.bindBuffer(gl.ARRAY_BUFFER, this._buffersVBO[0]); - gl.bufferData(gl.ARRAY_BUFFER, this._quadsArrayBuffer, gl.DYNAMIC_DRAW); + gl.bufferSubData(gl.ARRAY_BUFFER, 0, this._quadsArrayBuffer); }; proto._setBlendAdditive = function(){ @@ -389,4 +402,4 @@ proto._updateDeltaColor = function (selParticle, dt) { selParticle.color.b += selParticle.deltaColor.b * dt; selParticle.color.a += selParticle.deltaColor.a * dt; selParticle.isChangeColor = true; -}; \ No newline at end of file +}; diff --git a/cocos2d/physics/CCPhysicsDebugNodeWebGLRenderCmd.js b/cocos2d/physics/CCPhysicsDebugNodeWebGLRenderCmd.js index 39238bc53c..3d610138b1 100644 --- a/cocos2d/physics/CCPhysicsDebugNodeWebGLRenderCmd.js +++ b/cocos2d/physics/CCPhysicsDebugNodeWebGLRenderCmd.js @@ -29,6 +29,8 @@ cc.PhysicsDebugNode.WebGLRenderCmd = function (renderableObject) { _ccsg.Node.WebGLRenderCmd.call(this, renderableObject); this._needDraw = true; + this._matrix = new cc.math.Matrix4(); + this._matrix.identity(); }; cc.PhysicsDebugNode.WebGLRenderCmd.prototype = Object.create(_ccsg.Node.WebGLRenderCmd.prototype); @@ -42,12 +44,20 @@ node._space.eachShape(cc.DrawShape.bind(node)); node._space.eachConstraint(cc.DrawConstraint.bind(node)); + var wt = this._worldTransform, mat = this._matrix.mat; + mat[0] = wt.a; + mat[4] = wt.c; + mat[12] = wt.tx; + mat[1] = wt.b; + mat[5] = wt.d; + mat[13] = wt.ty; + //cc.DrawNode.prototype.draw.call(node); cc.gl.blendFunc(node._blendFunc.src, node._blendFunc.dst); this._shaderProgram.use(); - this._shaderProgram._setUniformForMVPMatrixWithMat4(this._stackMatrix); + this._shaderProgram._setUniformForMVPMatrixWithMat4(this._matrix); node._render(); node.clear(); }; -})(); \ No newline at end of file +})(); diff --git a/cocos2d/physics/CCPhysicsSprite.js b/cocos2d/physics/CCPhysicsSprite.js index 8b2d7c9ca1..d408324807 100644 --- a/cocos2d/physics/CCPhysicsSprite.js +++ b/cocos2d/physics/CCPhysicsSprite.js @@ -175,27 +175,20 @@ this.setNodeDirty(); }, _syncPosition:function () { - var pos = this._body.GetPosition(); - this._position.x = pos.x * this._PTMRatio; - this._position.y = pos.y * this._PTMRatio; - this._rotationRadians = this._rotation * (Math.PI / 180); + var locPosition = this._position, + pos = this._body.GetPosition(), + x = pos.x * this._PTMRatio, + y = pos.y * this._PTMRatio; + if (locPosition.x !== pos.x || locPosition.y !== pos.y) { + _ccsg.Sprite.prototype.setPosition.call(this, x, y); + } }, _syncRotation:function () { this._rotationRadians = this._body.GetAngle(); - }, - /** - * visit - */ - visit:function () { - if (this._body && this._PTMRatio) { - this._syncPosition(); - if (!this._ignoreBodyRotation) - this._syncRotation(); + var a = cc.radiansToDegrees(this._rotationRadians); + if (this._rotationX !== a) { + _ccsg.Sprite.prototype.setRotation.call(this, a); } - else { - cc.log("PhysicsSprite body or PTIMRatio was not set"); - } - this._super(); }, /** @@ -324,7 +317,6 @@ this._body.p.x = newPosOrxValue; this._body.p.y = yValue; } - //this._syncPosition(); }, /** @@ -333,7 +325,6 @@ */ setPositionX:function (xValue) { this._body.p.x = xValue; - //this._syncPosition(); }, /** @@ -342,7 +333,6 @@ */ setPositionY:function (yValue) { this._body.p.y = yValue; - //this._syncPosition(); }, _syncPosition:function () { @@ -369,12 +359,12 @@ _ccsg.Sprite.prototype.setRotation.call(this, r); } else { this._body.a = -cc.degreesToRadians(r); - //this._syncRotation(); } }, _syncRotation:function () { - if (this._rotationX !== -cc.radiansToDegrees(this._body.a)) { - _ccsg.Sprite.prototype.setRotation.call(this, -cc.radiansToDegrees(this._body.a)); + var a = -cc.radiansToDegrees(this._body.a); + if (this._rotationX !== a) { + _ccsg.Sprite.prototype.setRotation.call(this, a); } }, diff --git a/cocos2d/physics/CCPhysicsSpriteCanvasRenderCmd.js b/cocos2d/physics/CCPhysicsSpriteCanvasRenderCmd.js index 7c47b7d31f..74ba1369d2 100644 --- a/cocos2d/physics/CCPhysicsSpriteCanvasRenderCmd.js +++ b/cocos2d/physics/CCPhysicsSpriteCanvasRenderCmd.js @@ -47,47 +47,4 @@ _ccsg.Sprite.CanvasRenderCmd.prototype.rendering.call(this, ctx, scaleX, scaleY); }; - proto.getNodeToParentTransform = function(){ - var node = this._node; - - var t = this._transform;// quick reference - // base position - var locBody = node._body, locScaleX = node._scaleX, locScaleY = node._scaleY, locAnchorPIP = this._anchorPointInPoints; - t.tx = locBody.p.x; - t.ty = locBody.p.y; - - // rotation Cos and Sin - var radians = -locBody.a; - var Cos = 1, Sin = 0; - if (radians && !node._ignoreBodyRotation) { - Cos = Math.cos(radians); - Sin = Math.sin(radians); - } - - // base abcd - t.a = t.d = Cos; - t.b = -Sin; - t.c = Sin; - - // scale - if (locScaleX !== 1 || locScaleY !== 1) { - t.a *= locScaleX; - t.c *= locScaleX; - t.b *= locScaleY; - t.d *= locScaleY; - } - - // adjust anchorPoint - t.tx += Cos * -locAnchorPIP.x * locScaleX + -Sin * locAnchorPIP.y * locScaleY; - t.ty -= Sin * -locAnchorPIP.x * locScaleX + Cos * locAnchorPIP.y * locScaleY; - - // if ignore anchorPoint - if (this._ignoreAnchorPointForPosition) { - t.tx += locAnchorPIP.x; - t.ty += locAnchorPIP.y; - } - - return this._transform; - }; - -})(); \ No newline at end of file +})(); diff --git a/cocos2d/physics/CCPhysicsSpriteWebGLRenderCmd.js b/cocos2d/physics/CCPhysicsSpriteWebGLRenderCmd.js index eb6f51f798..97bb8da05c 100644 --- a/cocos2d/physics/CCPhysicsSpriteWebGLRenderCmd.js +++ b/cocos2d/physics/CCPhysicsSpriteWebGLRenderCmd.js @@ -34,7 +34,9 @@ var proto = cc.PhysicsSprite.WebGLRenderCmd.prototype = Object.create(_ccsg.Sprite.WebGLRenderCmd.prototype); proto.constructor = cc.PhysicsSprite.WebGLRenderCmd; - proto.rendering = function(ctx){ + proto.spUploadData = _ccsg.Sprite.WebGLRenderCmd.prototype.uploadData; + + proto.uploadData = function (f32buffer, ui32buffer, vertexDataOffset) { // This is a special class // Sprite can not obtain sign // So here must to calculate of each frame @@ -44,49 +46,6 @@ node._syncRotation(); this.transform(this.getParentRenderCmd(), true); - _ccsg.Sprite.WebGLRenderCmd.prototype.rendering.call(this, ctx); + return this.spUploadData(f32buffer, ui32buffer, vertexDataOffset); }; - - proto.getNodeToParentTransform = function(){ - var node = this._node; - var locBody = node._body, locAnchorPIP = this._anchorPointInPoints, locScaleX = node._scaleX, locScaleY = node._scaleY; - var x = locBody.p.x; - var y = locBody.p.y; - - if (this._ignoreAnchorPointForPosition) { - x += locAnchorPIP.x; - y += locAnchorPIP.y; - } - - // Make matrix - var radians = locBody.a, c = 1, s=0; - if (radians && !node._ignoreBodyRotation) { - c = Math.cos(radians); - s = Math.sin(radians); - } - - // Although scale is not used by physics engines, it is calculated just in case - // the sprite is animated (scaled up/down) using actions. - // For more info see: http://www.cocos2d-iphone.org/forum/topic/68990 - if (!cc._rectEqualToZero(locAnchorPIP)) { - x += c * -locAnchorPIP.x * locScaleX + -s * -locAnchorPIP.y * locScaleY; - y += s * -locAnchorPIP.x * locScaleX + c * -locAnchorPIP.y * locScaleY; - } - - // Rot, Translate Matrix - this._transform = cc.affineTransformMake(c * locScaleX, s * locScaleX, - -s * locScaleY, c * locScaleY, x, y); - - return this._transform; - }; - - proto.updateTransform = function(){ - var node = this._node; - var dirty = node.isDirty(); - if(dirty){ - var cmd = node._renderCmd; - cmd && cmd.setDirtyRecursively(true); - } - _ccsg.Sprite.WebGLRenderCmd.prototype.updateTransform.call(this); - }; -})(); \ No newline at end of file +})(); diff --git a/cocos2d/progress-timer/CCProgressTimer.js b/cocos2d/progress-timer/CCProgressTimer.js index 56e2512c02..ee49c34221 100644 --- a/cocos2d/progress-timer/CCProgressTimer.js +++ b/cocos2d/progress-timer/CCProgressTimer.js @@ -75,6 +75,21 @@ cc.ProgressTimer = _ccsg.Node.extend(/** @lends cc.ProgressTimer# */{ sprite && this.initWithSprite(sprite); }, + onEnter: function () { + this._super(); + if (cc._renderType === cc.game.RENDER_TYPE_WEBGL) { + this._renderCmd.initCmd(); + this._renderCmd._updateProgress(); + } + }, + + cleanup: function () { + if (cc._renderType === cc.game.RENDER_TYPE_WEBGL) { + this._renderCmd.releaseData(); + } + this._super(); + }, + /** * Midpoint is used to modify the progress start position. * If you're using radials type then the midpoint changes the center point @@ -214,7 +229,7 @@ cc.ProgressTimer = _ccsg.Node.extend(/** @lends cc.ProgressTimer# */{ setReverseProgress: function(reverse){ if (this._reverseDirection !== reverse){ this._reverseDirection = reverse; - this._renderCmd.releaseData(); + this._renderCmd.resetVertexData(); } }, @@ -226,11 +241,14 @@ cc.ProgressTimer = _ccsg.Node.extend(/** @lends cc.ProgressTimer# */{ setSprite: function(sprite){ if (this._sprite !== sprite) { this._sprite = sprite; - if(sprite) - this.setContentSize(sprite.width,sprite.height); - else + if(sprite) { + this.setContentSize(sprite.width, sprite.height); + sprite.ignoreAnchorPointForPosition(true); + } + else { this.setContentSize(0,0); - this._renderCmd.releaseData(); + } + this._renderCmd.resetVertexData(); } }, @@ -242,7 +260,7 @@ cc.ProgressTimer = _ccsg.Node.extend(/** @lends cc.ProgressTimer# */{ setType: function(type){ if (type !== this._type){ this._type = type; - this._renderCmd.releaseData(); + this._renderCmd.resetVertexData(); } }, @@ -254,7 +272,7 @@ cc.ProgressTimer = _ccsg.Node.extend(/** @lends cc.ProgressTimer# */{ setReverseDirection: function(reverse){ if (this._reverseDirection !== reverse){ this._reverseDirection = reverse; - this._renderCmd.releaseData(); + this._renderCmd.resetVertexData(); } }, @@ -273,7 +291,7 @@ cc.ProgressTimer = _ccsg.Node.extend(/** @lends cc.ProgressTimer# */{ this.midPoint = cc.p(0.5, 0.5); this.barChangeRate = cc.p(1, 1); this.setSprite(sprite); - this._renderCmd.initCmd(); + this._renderCmd.resetVertexData(); return true; }, diff --git a/cocos2d/progress-timer/CCProgressTimerCanvasRenderCmd.js b/cocos2d/progress-timer/CCProgressTimerCanvasRenderCmd.js index e31114bb29..01a03c7c4b 100644 --- a/cocos2d/progress-timer/CCProgressTimerCanvasRenderCmd.js +++ b/cocos2d/progress-timer/CCProgressTimerCanvasRenderCmd.js @@ -89,7 +89,8 @@ } //draw sprite - var image = locSprite._texture.getHtmlElementObj(); + var texture = locSprite._renderCmd._textureToRender || locSprite._texture; + var image = texture.getHtmlElementObj(); if (locSprite._renderCmd._colorized) { context.drawImage(image, 0, 0, locTextureCoord.width, locTextureCoord.height, @@ -105,7 +106,7 @@ proto.releaseData = function(){}; - proto.initCmd = function(){}; + proto.resetVertexData = function(){}; proto._updateProgress = function(){ var node = this._node; @@ -192,8 +193,6 @@ } }; - proto._updateColor = function(){}; - proto._syncStatus = function (parentCmd) { var node = this._node; if(!node._sprite) @@ -220,21 +219,28 @@ if (colorDirty){ spriteCmd._syncDisplayColor(); + spriteCmd._dirtyFlag &= ~flags.colorDirty; + this._dirtyFlag &= ~flags.colorDirty; } if (opacityDirty){ spriteCmd._syncDisplayOpacity(); + spriteCmd._dirtyFlag &= ~flags.opacityDirty; + this._dirtyFlag &= ~flags.opacityDirty; } if(colorDirty || opacityDirty){ spriteCmd._updateColor(); - //this._updateColor(); } if (locFlag & flags.transformDirty) { //update the transform this.transform(parentCmd); } + + if (locFlag & flags.orderDirty) { + this._dirtyFlag &= ~flags.orderDirty; + } }; proto.updateStatus = function () { @@ -250,15 +256,18 @@ if(colorDirty){ spriteCmd._updateDisplayColor(); + spriteCmd._dirtyFlag &= ~flags.colorDirty; + this._dirtyFlag &= ~flags.colorDirty; } if(opacityDirty){ spriteCmd._updateDisplayOpacity(); + spriteCmd._dirtyFlag &= ~flags.opacityDirty; + this._dirtyFlag &= ~flags.opacityDirty; } if(colorDirty || opacityDirty){ spriteCmd._updateColor(); - //this._updateColor(); } if(locFlag & flags.transformDirty){ @@ -267,4 +276,4 @@ } this._dirtyFlag = 0; }; -})(); \ No newline at end of file +})(); diff --git a/cocos2d/progress-timer/CCProgressTimerWebGLRenderCmd.js b/cocos2d/progress-timer/CCProgressTimerWebGLRenderCmd.js index d4533306b0..0350f49778 100644 --- a/cocos2d/progress-timer/CCProgressTimerWebGLRenderCmd.js +++ b/cocos2d/progress-timer/CCProgressTimerWebGLRenderCmd.js @@ -26,44 +26,64 @@ * cc.ProgressTimer's rendering objects of WebGL */ (function(){ + var MAX_VERTEX_COUNT = 8; + cc.ProgressTimer.WebGLRenderCmd = function(renderableObject){ _ccsg.Node.WebGLRenderCmd.call(this, renderableObject); this._needDraw = true; + this._progressDirty = true; - this._vertexWebGLBuffer = cc._renderContext.createBuffer(); - this._vertexDataCount = 0; - this._vertexData = null; - this._vertexArrayBuffer = null; - this._vertexDataDirty = false; + this._bl = cc.p(); + this._tr = cc.p(); + + this.initCmd(); }; var proto = cc.ProgressTimer.WebGLRenderCmd.prototype = Object.create(_ccsg.Node.WebGLRenderCmd.prototype); proto.constructor = cc.ProgressTimer.WebGLRenderCmd; + proto.transform = function (parentCmd, recursive) { + this.originTransform(parentCmd, recursive); + var sp = this._node._sprite; + sp._renderCmd.transform(this, recursive); + + var lx = sp._offsetPosition.x, rx = lx + sp._rect.width, + by = sp._offsetPosition.y, ty = by + sp._rect.height, + wt = this._worldTransform; + this._bl.x = lx * wt.a + by * wt.c + wt.tx; + this._bl.y = lx * wt.b + by * wt.d + wt.ty; + this._tr.x = rx * wt.a + ty * wt.c + wt.tx; + this._tr.y = rx * wt.b + ty * wt.d + wt.ty; + + this._updateProgressData(); + }; + proto.rendering = function (ctx) { var node = this._node; var context = ctx || cc._renderContext; - if (!this._vertexData || !node._sprite) + if (this._vertexDataCount === 0 || !node._sprite) return; this._shaderProgram.use(); - this._shaderProgram._setUniformForMVPMatrixWithMat4(this._stackMatrix); + this._shaderProgram._updateProjectionUniform(); var blendFunc = node._sprite._blendFunc; cc.gl.blendFunc(blendFunc.src, blendFunc.dst); - cc.gl.enableVertexAttribs(cc.macro.VERTEX_ATTRIB_FLAG_POS_COLOR_TEX); - cc.gl.bindTexture2D(node._sprite.texture); - context.bindBuffer(context.ARRAY_BUFFER, this._vertexWebGLBuffer); + + context.enableVertexAttribArray(cc.macro.VERTEX_ATTRIB_POSITION); + context.enableVertexAttribArray(cc.macro.VERTEX_ATTRIB_COLOR); + context.enableVertexAttribArray(cc.macro.VERTEX_ATTRIB_TEX_COORDS); + if (this._vertexDataDirty) { - context.bufferData(context.ARRAY_BUFFER, this._vertexArrayBuffer, context.DYNAMIC_DRAW); + context.bufferSubData(context.ARRAY_BUFFER, 0, this._float32View); this._vertexDataDirty = false; } - var locVertexDataLen = cc.V2F_C4B_T2F.BYTES_PER_ELEMENT; - context.vertexAttribPointer(cc.macro.VERTEX_ATTRIB_POSITION, 2, context.FLOAT, false, locVertexDataLen, 0); - context.vertexAttribPointer(cc.macro.VERTEX_ATTRIB_COLOR, 4, context.UNSIGNED_BYTE, true, locVertexDataLen, 8); - context.vertexAttribPointer(cc.macro.VERTEX_ATTRIB_TEX_COORDS, 2, context.FLOAT, false, locVertexDataLen, 12); + var locVertexDataLen = cc.V3F_C4B_T2F.BYTES_PER_ELEMENT; + context.vertexAttribPointer(cc.macro.VERTEX_ATTRIB_POSITION, 3, context.FLOAT, false, locVertexDataLen, 0); + context.vertexAttribPointer(cc.macro.VERTEX_ATTRIB_COLOR, 4, context.UNSIGNED_BYTE, true, locVertexDataLen, 12); + context.vertexAttribPointer(cc.macro.VERTEX_ATTRIB_TEX_COORDS, 2, context.FLOAT, false, locVertexDataLen, 16); if (node._type === cc.ProgressTimer.Type.RADIAL) context.drawArrays(context.TRIANGLE_FAN, 0, this._vertexDataCount); @@ -98,26 +118,34 @@ var spriteCmd = node._sprite._renderCmd; var spriteFlag = spriteCmd._dirtyFlag; - var colorDirty = spriteFlag & flags.colorDirty, - opacityDirty = spriteFlag & flags.opacityDirty; + var colorDirty = (locFlag | spriteFlag) & flags.colorDirty, + opacityDirty = (locFlag | spriteFlag) & flags.opacityDirty; if (colorDirty){ spriteCmd._syncDisplayColor(); + spriteCmd._dirtyFlag &= ~flags.colorDirty; + this._dirtyFlag &= ~flags.colorDirty; } if (opacityDirty){ spriteCmd._syncDisplayOpacity(); + spriteCmd._dirtyFlag &= ~flags.opacityDirty; + this._dirtyFlag &= ~flags.opacityDirty; } if(colorDirty || opacityDirty){ - spriteCmd._updateColor(); this._updateColor(); } - //if (locFlag & flags.transformDirty) { + if (locFlag & flags.transformDirty) { //update the transform - this.transform(parentCmd); - //} + this.transform(parentCmd); + } + + if (locFlag & flags.textureDirty) { + this._updateProgressData(); + this._dirtyFlag &= ~flags.textureDirty; + } spriteCmd._dirtyFlag = 0; }; @@ -130,21 +158,22 @@ var spriteCmd = node._sprite._renderCmd; var spriteFlag = spriteCmd._dirtyFlag; - var colorDirty = spriteFlag & flags.colorDirty, - opacityDirty = spriteFlag & flags.opacityDirty; + var colorDirty = (locFlag | spriteFlag) & flags.colorDirty, + opacityDirty = (locFlag | spriteFlag) & flags.opacityDirty; if(colorDirty){ spriteCmd._updateDisplayColor(); - this._dirtyFlag = this._dirtyFlag & flags.colorDirty ^ this._dirtyFlag; + spriteCmd._dirtyFlag &= ~flags.colorDirty; + this._dirtyFlag &= ~flags.colorDirty; } if(opacityDirty){ spriteCmd._updateDisplayOpacity(); - this._dirtyFlag = this._dirtyFlag & flags.opacityDirty ^ this._dirtyFlag; + spriteCmd._dirtyFlag &= ~flags.opacityDirty; + this._dirtyFlag &= ~flags.opacityDirty; } if(colorDirty || opacityDirty){ - spriteCmd._updateColor(); this._updateColor(); } @@ -152,27 +181,62 @@ //update the transform this.transform(this.getParentRenderCmd(), true); } + + if (locFlag & flags.orderDirty) { + this._dirtyFlag &= ~flags.orderDirty; + } + + if (locFlag & flags.textureDirty) { + this._updateProgressData(); + this._dirtyFlag &= ~flags.textureDirty; + } }; proto.releaseData = function(){ if (this._vertexData) { //release all previous information + var webglBuffer = this._vertexWebGLBuffer; + setTimeout(function () { + cc._renderContext.deleteBuffer(webglBuffer); + }, 0.1); + this._vertexWebGLBuffer = null; this._vertexData = null; + this._float32View = null; this._vertexArrayBuffer = null; this._vertexDataCount = 0; } }; - proto.initCmd = function(){ - this._vertexData = null; - this._vertexArrayBuffer = null; - this._vertexDataCount = 0; + proto.initCmd = function () { + if (!this._vertexData) { + var gl = cc._renderContext; + this._vertexWebGLBuffer = gl.createBuffer(); + + var vertexDataLen = cc.V3F_C4B_T2F.BYTES_PER_ELEMENT; + this._vertexArrayBuffer = new ArrayBuffer(MAX_VERTEX_COUNT * vertexDataLen); + this._float32View = new Float32Array(this._vertexArrayBuffer); + this._vertexData = []; + for (var i = 0; i < MAX_VERTEX_COUNT; i++) { + this._vertexData[i] = new cc.V3F_C4B_T2F(null, null, null, this._vertexArrayBuffer, i * vertexDataLen); + } - //shader program - this._shaderProgram = cc.shaderCache.programForKey(cc.macro.SHADER_POSITION_TEXTURECOLOR); + // Init buffer data + gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexWebGLBuffer); + gl.bufferData(gl.ARRAY_BUFFER, this._float32View, gl.DYNAMIC_DRAW); + + this._vertexDataCount = 0; + this._vertexDataDirty = true; + + //shader program + this._shaderProgram = cc.shaderCache.programForKey(cc.macro.SHADER_SPRITE_POSITION_TEXTURECOLOR); + } }; - proto._updateProgress = function(){ + proto.resetVertexData = function () { + this._vertexDataCount = 0; + }; + + proto._updateProgressData = function () { var node = this._node; var locType = node._type; if(locType === cc.ProgressTimer.Type.RADIAL) @@ -182,6 +246,10 @@ this._vertexDataDirty = true; }; + proto._updateProgress = function () { + this.setDirtyFlag(_ccsg.Node._dirtyFlags.textureDirty); + }; + /** *

* Update does the work of mapping the texture onto the triangles for the bar
@@ -226,74 +294,61 @@ var locVertexData; if (!this._reverseDirection) { - if (!this._vertexData) { + if (!this._vertexDataCount) { this._vertexDataCount = 4; - var vertexDataLen = cc.V2F_C4B_T2F.BYTES_PER_ELEMENT, locCount = 4; - this._vertexArrayBuffer = new ArrayBuffer(locCount * vertexDataLen); - this._vertexData = []; - for (i = 0; i < locCount; i++) - this._vertexData[i] = new cc.V2F_C4B_T2F(null, null, null, this._vertexArrayBuffer, i * vertexDataLen); } - locVertexData = this._vertexData; // TOPLEFT - locVertexData[0].texCoords = this._textureCoordFromAlphaPoint(cc.p(min.x, max.y)); - locVertexData[0].vertices = this._vertexFromAlphaPoint(cc.p(min.x, max.y)); + this._textureCoordFromAlphaPoint(locVertexData[0].texCoords, min.x, max.y); + this._vertexFromAlphaPoint(locVertexData[0].vertices, min.x, max.y); // BOTLEFT - locVertexData[1].texCoords = this._textureCoordFromAlphaPoint(cc.p(min.x, min.y)); - locVertexData[1].vertices = this._vertexFromAlphaPoint(cc.p(min.x, min.y)); + this._textureCoordFromAlphaPoint(locVertexData[1].texCoords, min.x, min.y); + this._vertexFromAlphaPoint(locVertexData[1].vertices, min.x, min.y); // TOPRIGHT - locVertexData[2].texCoords = this._textureCoordFromAlphaPoint(cc.p(max.x, max.y)); - locVertexData[2].vertices = this._vertexFromAlphaPoint(cc.p(max.x, max.y)); + this._textureCoordFromAlphaPoint(locVertexData[2].texCoords, max.x, max.y); + this._vertexFromAlphaPoint(locVertexData[2].vertices, max.x, max.y); // BOTRIGHT - locVertexData[3].texCoords = this._textureCoordFromAlphaPoint(cc.p(max.x, min.y)); - locVertexData[3].vertices = this._vertexFromAlphaPoint(cc.p(max.x, min.y)); + this._textureCoordFromAlphaPoint(locVertexData[3].texCoords, max.x, min.y); + this._vertexFromAlphaPoint(locVertexData[3].vertices, max.x, min.y); } else { - if (!this._vertexData) { + locVertexData = this._vertexData; + if (!this._vertexDataCount) { this._vertexDataCount = 8; - var rVertexDataLen = cc.V2F_C4B_T2F.BYTES_PER_ELEMENT, rLocCount = 8; - this._vertexArrayBuffer = new ArrayBuffer(rLocCount * rVertexDataLen); - var rTempData = []; - for (i = 0; i < rLocCount; i++) - rTempData[i] = new cc.V2F_C4B_T2F(null, null, null, this._vertexArrayBuffer, i * rVertexDataLen); // TOPLEFT 1 - rTempData[0].texCoords = this._textureCoordFromAlphaPoint(cc.p(0, 1)); - rTempData[0].vertices = this._vertexFromAlphaPoint(cc.p(0, 1)); + this._textureCoordFromAlphaPoint(locVertexData[0].texCoords, 0, 1); + this._vertexFromAlphaPoint(locVertexData[0].vertices, 0, 1); // BOTLEFT 1 - rTempData[1].texCoords = this._textureCoordFromAlphaPoint(cc.p(0, 0)); - rTempData[1].vertices = this._vertexFromAlphaPoint(cc.p(0, 0)); + this._textureCoordFromAlphaPoint(locVertexData[1].texCoords, 0, 0); + this._vertexFromAlphaPoint(locVertexData[1].vertices, 0, 0); // TOPRIGHT 2 - rTempData[6].texCoords = this._textureCoordFromAlphaPoint(cc.p(1, 1)); - rTempData[6].vertices = this._vertexFromAlphaPoint(cc.p(1, 1)); + this._textureCoordFromAlphaPoint(locVertexData[6].texCoords, 1, 1); + this._vertexFromAlphaPoint(locVertexData[6].vertices, 1, 1); // BOTRIGHT 2 - rTempData[7].texCoords = this._textureCoordFromAlphaPoint(cc.p(1, 0)); - rTempData[7].vertices = this._vertexFromAlphaPoint(cc.p(1, 0)); - - this._vertexData = rTempData; + this._textureCoordFromAlphaPoint(locVertexData[7].texCoords, 1, 0); + this._vertexFromAlphaPoint(locVertexData[7].vertices, 1, 0); } - locVertexData = this._vertexData; // TOPRIGHT 1 - locVertexData[2].texCoords = this._textureCoordFromAlphaPoint(cc.p(min.x, max.y)); - locVertexData[2].vertices = this._vertexFromAlphaPoint(cc.p(min.x, max.y)); + this._textureCoordFromAlphaPoint(locVertexData[2].texCoords, min.x, max.y); + this._vertexFromAlphaPoint(locVertexData[2].vertices, min.x, max.y); // BOTRIGHT 1 - locVertexData[3].texCoords = this._textureCoordFromAlphaPoint(cc.p(min.x, min.y)); - locVertexData[3].vertices = this._vertexFromAlphaPoint(cc.p(min.x, min.y)); + this._textureCoordFromAlphaPoint(locVertexData[3].texCoords, min.x, min.y); + this._vertexFromAlphaPoint(locVertexData[3].vertices, min.x, min.y); // TOPLEFT 2 - locVertexData[4].texCoords = this._textureCoordFromAlphaPoint(cc.p(max.x, max.y)); - locVertexData[4].vertices = this._vertexFromAlphaPoint(cc.p(max.x, max.y)); + this._textureCoordFromAlphaPoint(locVertexData[4].texCoords, max.x, max.y); + this._vertexFromAlphaPoint(locVertexData[4].vertices, max.x, max.y); // BOTLEFT 2 - locVertexData[5].texCoords = this._textureCoordFromAlphaPoint(cc.p(max.x, min.y)); - locVertexData[5].vertices = this._vertexFromAlphaPoint(cc.p(max.x, min.y)); + this._textureCoordFromAlphaPoint(locVertexData[5].texCoords, max.x, min.y); + this._vertexFromAlphaPoint(locVertexData[5].vertices, max.x, min.y); } this._updateColor(); }; @@ -389,47 +444,31 @@ var sameIndexCount = true; if (this._vertexDataCount !== index + 3) { sameIndexCount = false; - this._vertexData = null; - this._vertexArrayBuffer = null; - this._vertexDataCount = 0; - } - - if (!this._vertexData) { this._vertexDataCount = index + 3; - var locCount = this._vertexDataCount, vertexDataLen = cc.V2F_C4B_T2F.BYTES_PER_ELEMENT; - this._vertexArrayBuffer = new ArrayBuffer(locCount * vertexDataLen); - var locData = []; - for (i = 0; i < locCount; i++) - locData[i] = new cc.V2F_C4B_T2F(null, null, null, this._vertexArrayBuffer, i * vertexDataLen); - - this._vertexData = locData; - if(!this._vertexData){ - cc.log( "cc.ProgressTimer._updateRadial() : Not enough memory"); - return; - } } + this._updateColor(); var locVertexData = this._vertexData; if (!sameIndexCount) { // First we populate the array with the m_tMidpoint, then all // vertices/texcoords/colors of the 12 'o clock start and edges and the hitpoint - locVertexData[0].texCoords = this._textureCoordFromAlphaPoint(locMidPoint); - locVertexData[0].vertices = this._vertexFromAlphaPoint(locMidPoint); + this._textureCoordFromAlphaPoint(locVertexData[0].texCoords, locMidPoint.x, locMidPoint.y); + this._vertexFromAlphaPoint(locVertexData[0].vertices, locMidPoint.x, locMidPoint.y); - locVertexData[1].texCoords = this._textureCoordFromAlphaPoint(topMid); - locVertexData[1].vertices = this._vertexFromAlphaPoint(topMid); + this._textureCoordFromAlphaPoint(locVertexData[1].texCoords, topMid.x, topMid.y); + this._vertexFromAlphaPoint(locVertexData[1].vertices, topMid.x, topMid.y); for (i = 0; i < index; i++) { var alphaPoint = this._boundaryTexCoord(i); - locVertexData[i + 2].texCoords = this._textureCoordFromAlphaPoint(alphaPoint); - locVertexData[i + 2].vertices = this._vertexFromAlphaPoint(alphaPoint); + this._textureCoordFromAlphaPoint(locVertexData[i + 2].texCoords, alphaPoint.x, alphaPoint.y); + this._vertexFromAlphaPoint(locVertexData[i + 2].vertices, alphaPoint.x, alphaPoint.y); } } // hitpoint will go last - locVertexData[this._vertexDataCount - 1].texCoords = this._textureCoordFromAlphaPoint(hit); - locVertexData[this._vertexDataCount - 1].vertices = this._vertexFromAlphaPoint(hit); + this._textureCoordFromAlphaPoint(locVertexData[this._vertexDataCount - 1].texCoords, hit.x, hit.y); + this._vertexFromAlphaPoint(locVertexData[this._vertexDataCount - 1].vertices, hit.x, hit.y); }; proto._boundaryTexCoord = function (index) { @@ -443,44 +482,59 @@ return cc.p(0,0); }; - proto._textureCoordFromAlphaPoint = function (alpha) { + proto._textureCoordFromAlphaPoint = function (coords, ax, ay) { var locSprite = this._node._sprite; if (!locSprite) { - return {u:0, v:0}; //new cc.Tex2F(0, 0); + coords.u = 0; + coords.v = 0; + return; } - var quad = locSprite.quad; - var min = cc.p(quad.bl.texCoords.u, quad.bl.texCoords.v); - var max = cc.p(quad.tr.texCoords.u, quad.tr.texCoords.v); + var uvs = locSprite._renderCmd._vertices, + bl = uvs[1], + tr = uvs[2]; + var min = cc.p(bl.u, bl.v); + var max = cc.p(tr.u, tr.v); // Fix bug #1303 so that progress timer handles sprite frame texture rotation if (locSprite.textureRectRotated) { - var temp = alpha.x; - alpha.x = alpha.y; - alpha.y = temp; + var temp = ax; + ax = ay; + ay = temp; } - return {u: min.x * (1 - alpha.x) + max.x * alpha.x, v: min.y * (1 - alpha.y) + max.y * alpha.y}; + coords.u = min.x * (1 - ax) + max.x * ax; + coords.v = min.y * (1 - ay) + max.y * ay; }; - proto._vertexFromAlphaPoint = function (alpha) { - var locSprite = this._node._sprite; - if (!locSprite) { - return {x: 0, y: 0}; - } - var quad = locSprite.quad; - var min = cc.p(quad.bl.vertices.x, quad.bl.vertices.y); - var max = cc.p(quad.tr.vertices.x, quad.tr.vertices.y); - return {x: min.x * (1 - alpha.x) + max.x * alpha.x, y: min.y * (1 - alpha.y) + max.y * alpha.y}; + proto._vertexFromAlphaPoint = function (vertex, ax, ay) { + vertex.x = this._bl.x * (1 - ax) + this._tr.x * ax; + vertex.y = this._bl.y * (1 - ay) + this._tr.y * ay; + vertex.z = this._node._vertexZ; }; proto._updateColor = function(){ - var node = this._node; - if (!node._sprite || !this._vertexData) + var sp = this._node._sprite; + if (!this._vertexDataCount || !sp) return; - var sc = node._sprite.quad.tl.colors; + var color = this._displayedColor; + var spColor = sp._renderCmd._displayedColor; + var r = spColor.r; + var g = spColor.g; + var b = spColor.b; + var a = sp._renderCmd._displayedOpacity / 255; + if (sp._opacityModifyRGB) { + r *= a; + g *= a; + b *= a; + } + color.r = r; + color.g = g; + color.b = b; + color.a = sp._renderCmd._displayedOpacity; var locVertexData = this._vertexData; - for (var i = 0, len = this._vertexDataCount; i < len; ++i) - locVertexData[i].colors = sc; + for (var i = 0, len = this._vertexDataCount; i < len; ++i) { + locVertexData[i].colors = color; + } this._vertexDataDirty = true; }; -})(); \ No newline at end of file +})(); diff --git a/cocos2d/render-texture/CCRenderTextureWebGLRenderCmd.js b/cocos2d/render-texture/CCRenderTextureWebGLRenderCmd.js index 37a40b0298..cf8b63e542 100644 --- a/cocos2d/render-texture/CCRenderTextureWebGLRenderCmd.js +++ b/cocos2d/render-texture/CCRenderTextureWebGLRenderCmd.js @@ -49,6 +49,10 @@ proto.setVirtualViewport = function(rtBegin, fullRect, fullViewport) { this._fullViewport = fullViewport; }; +proto.needDraw = function () { + return this._needDraw && this._node.autoDraw; +}; + proto.rendering = function (ctx) { var gl = ctx || cc._renderContext; var node = this._node; @@ -384,4 +388,4 @@ proto.visit = function(parentCmd){ this._dirtyFlag = 0; cc.math.glPopMatrix(); -}; \ No newline at end of file +}; diff --git a/cocos2d/shaders/CCGLProgram.js b/cocos2d/shaders/CCGLProgram.js index d848a0e7ff..a28870300f 100644 --- a/cocos2d/shaders/CCGLProgram.js +++ b/cocos2d/shaders/CCGLProgram.js @@ -26,14 +26,8 @@ THE SOFTWARE. ****************************************************************************/ -var HashUniformEntry = function (value, location, hh) { - this.value = value; - this.location = location; - this.hh = hh || {}; -}; - -var math = cc.math; var macro = cc.macro; +var math = cc.math; /** * Class that implements a WebGL program @@ -50,28 +44,31 @@ cc.GLProgram = cc._Class.extend(/** @lends cc.GLProgram# */{ _usesTime: false, // Uniform cache - _updateUniformLocation: function (location, data, bytes) { - if (location == null) + _updateUniformLocation: function (location) { + if (!location) return false; - var updated = true; - var element = null; - for (var i = 0; i < this._hashForUniforms.length; i++) - if (this._hashForUniforms[i].location == location) - element = this._hashForUniforms[i]; + var updated; + var element = this._hashForUniforms[location]; if (!element) { - element = new HashUniformEntry(); - // key - element.location = location; - // value - element.value = data; - this._hashForUniforms.push(element); + element = [ + arguments[1], + arguments[2], + arguments[3], + arguments[4] + ]; + this._hashForUniforms[location] = element; + updated = true; } else { - if (element.value == data) - updated = false; - else - element.value = data; + updated = false; + var count = arguments.length-1; + for (var i = 0; i < count; ++i) { + if (arguments[i+1] !== element[i]) { + element[i] = arguments[i+1]; + updated = true; + } + } } return updated; @@ -119,8 +116,8 @@ cc.GLProgram = cc._Class.extend(/** @lends cc.GLProgram# */{ * @returns {cc.GLProgram} */ ctor: function (vShaderFileName, fShaderFileName, glContext) { - this._uniforms = []; - this._hashForUniforms = []; + this._uniforms = {}; + this._hashForUniforms = {}; this._glContext = glContext || cc._renderContext; vShaderFileName && fShaderFileName && this.init(vShaderFileName, fShaderFileName); @@ -173,7 +170,10 @@ cc.GLProgram = cc._Class.extend(/** @lends cc.GLProgram# */{ if (this._fragShader) locGL.attachShader(this._programObj, this._fragShader); - this._hashForUniforms.length = 0; + + for (var key in this._hashForUniforms) { + delete this._hashForUniforms[key]; + } cc.checkGLErrorDebug(); return true; @@ -287,18 +287,24 @@ cc.GLProgram = cc._Class.extend(/** @lends cc.GLProgram# */{ this.setUniformLocationWith1i(this._uniforms[macro.UNIFORM_SAMPLER], 0); }, + _addUniformLocation: function (name) { + var location = this._glContext.getUniformLocation(this._programObj, name); + this._uniforms[name] = location; + }, + /** * calls retrieves the named uniform location for this shader program. * @param {String} name * @returns {Number} */ - getUniformLocationForName:function(name){ - if(!name) + getUniformLocationForName: function (name) { + if (!name) throw new Error("cc.GLProgram.getUniformLocationForName(): uniform name should be non-null"); - if(!this._programObj) + if (!this._programObj) throw new Error("cc.GLProgram.getUniformLocationForName(): Invalid operation. Cannot get uniform location when program is not initialized"); - return this._glContext.getUniformLocation(this._programObj, name); + var location = this._uniforms[name] || this._glContext.getUniformLocation(this._programObj, name); + return location; }, /** @@ -323,9 +329,17 @@ cc.GLProgram = cc._Class.extend(/** @lends cc.GLProgram# */{ * @param {Number} i1 */ setUniformLocationWith1i: function (location, i1) { - var updated = this._updateUniformLocation(location, i1); - if (updated) - this._glContext.uniform1i(location, i1); + var gl = this._glContext; + if (typeof location === 'string') { + var updated = this._updateUniformLocation(location, i1); + if (updated) { + var locObj = this.getUniformLocationForName(location); + gl.uniform1i(locObj, i1); + } + } + else { + gl.uniform1i(location, i1); + } }, /** @@ -334,12 +348,18 @@ cc.GLProgram = cc._Class.extend(/** @lends cc.GLProgram# */{ * @param {Number} i1 * @param {Number} i2 */ - setUniformLocationWith2i:function(location, i1,i2){ - var intArray= [i1,i2]; - var updated = this._updateUniformLocation(location, intArray); - - if( updated ) - this._glContext.uniform2i(location, i1, i2); + setUniformLocationWith2i: function (location, i1, i2) { + var gl = this._glContext; + if (typeof location === 'string') { + var updated = this._updateUniformLocation(location, i1, i2); + if (updated) { + var locObj = this.getUniformLocationForName(location); + gl.uniform2i(locObj, i1, i2); + } + } + else { + gl.uniform2i(location, i1, i2); + } }, /** @@ -349,12 +369,18 @@ cc.GLProgram = cc._Class.extend(/** @lends cc.GLProgram# */{ * @param {Number} i2 * @param {Number} i3 */ - setUniformLocationWith3i:function(location, i1, i2, i3){ - var intArray = [i1,i2,i3]; - var updated = this._updateUniformLocation(location, intArray); - - if( updated ) - this._glContext.uniform3i(location, i1, i2, i3); + setUniformLocationWith3i: function (location, i1, i2, i3) { + var gl = this._glContext; + if (typeof location === 'string') { + var updated = this._updateUniformLocation(location, i1, i2, i3); + if (updated) { + var locObj = this.getUniformLocationForName(location); + gl.uniform3i(locObj, i1, i2, i3); + } + } + else { + gl.uniform3i(location, i1, i2, i3); + } }, /** @@ -365,12 +391,18 @@ cc.GLProgram = cc._Class.extend(/** @lends cc.GLProgram# */{ * @param {Number} i3 * @param {Number} i4 */ - setUniformLocationWith4i:function(location, i1, i2, i3, i4){ - var intArray = [i1,i2,i3,i4]; - var updated = this._updateUniformLocation(location, intArray); - - if( updated ) - this._glContext.uniform4i(location, i1, i2, i3, i4); + setUniformLocationWith4i: function (location, i1, i2, i3, i4) { + var gl = this._glContext; + if (typeof location === 'string') { + var updated = this._updateUniformLocation(location, i1, i2, i3, i4); + if (updated) { + var locObj = this.getUniformLocationForName(location); + gl.uniform4i(locObj, i1, i2, i3, i4); + } + } + else { + gl.uniform4i(location, i1, i2, i3, i4); + } }, /** @@ -379,11 +411,9 @@ cc.GLProgram = cc._Class.extend(/** @lends cc.GLProgram# */{ * @param {Int32Array} intArray * @param {Number} numberOfArrays */ - setUniformLocationWith2iv:function(location, intArray, numberOfArrays){ - var updated = this._updateUniformLocation(location, intArray); - - if( updated ) - this._glContext.uniform2iv(location, intArray); + setUniformLocationWith2iv: function (location, intArray) { + var locObj = typeof location === 'string' ? this.getUniformLocationForName(location) : location; + this._glContext.uniform2iv(locObj, intArray); }, /** @@ -392,24 +422,19 @@ cc.GLProgram = cc._Class.extend(/** @lends cc.GLProgram# */{ * @param {Int32Array} intArray * @param {Number} numberOfArrays */ - setUniformLocationWith3iv:function(location, intArray, numberOfArrays){ - var updated = this._updateUniformLocation(location, intArray); - - if( updated ) - this._glContext.uniform3iv(location, intArray); + setUniformLocationWith3iv:function(location, intArray){ + var locObj = typeof location === 'string' ? this.getUniformLocationForName(location) : location; + this._glContext.uniform3iv(locObj, intArray); }, /** * calls glUniform4iv only if the values are different than the previous call for this same shader program. * @param {WebGLUniformLocation} location * @param {Int32Array} intArray - * @param {Number} numberOfArrays */ - setUniformLocationWith4iv:function(location, intArray, numberOfArrays){ - var updated = this._updateUniformLocation(location, intArray); - - if( updated ) - this._glContext.uniform4iv(location, intArray); + setUniformLocationWith4iv:function(location, intArray){ + var locObj = typeof location === 'string' ? this.getUniformLocationForName(location) : location; + this._glContext.uniform4iv(locObj, intArray); }, /** @@ -418,7 +443,7 @@ cc.GLProgram = cc._Class.extend(/** @lends cc.GLProgram# */{ * @param {Number} i1 */ setUniformLocationI32: function (location, i1) { - this.setUniformLocationWith1i(arguments[0], arguments[1]); + this.setUniformLocationWith1i(location, i1); }, /** @@ -427,9 +452,17 @@ cc.GLProgram = cc._Class.extend(/** @lends cc.GLProgram# */{ * @param {Number} f1 */ setUniformLocationWith1f: function (location, f1) { - var updated = this._updateUniformLocation(location, f1); - if (updated) - this._glContext.uniform1f(location, f1); + var gl = this._glContext; + if (typeof location === 'string') { + var updated = this._updateUniformLocation(location, f1); + if (updated) { + var locObj = this.getUniformLocationForName(location); + gl.uniform1f(locObj, f1); + } + } + else { + gl.uniform1f(location, f1); + } }, /** @@ -439,10 +472,17 @@ cc.GLProgram = cc._Class.extend(/** @lends cc.GLProgram# */{ * @param {Number} f2 */ setUniformLocationWith2f: function (location, f1, f2) { - var floats = [f1, f2]; - var updated = this._updateUniformLocation(location, floats); - if (updated) - this._glContext.uniform2f(location, f1, f2); + var gl = this._glContext; + if (typeof location === 'string') { + var updated = this._updateUniformLocation(location, f1, f2); + if (updated) { + var locObj = this.getUniformLocationForName(location); + gl.uniform2f(locObj, f1, f2); + } + } + else { + gl.uniform2f(location, f1, f2); + } }, /** @@ -453,10 +493,17 @@ cc.GLProgram = cc._Class.extend(/** @lends cc.GLProgram# */{ * @param {Number} f3 */ setUniformLocationWith3f: function (location, f1, f2, f3) { - var floats = [f1, f2, f3]; - var updated = this._updateUniformLocation(location, floats); - if (updated) - this._glContext.uniform3f(location, f1, f2, f3); + var gl = this._glContext; + if (typeof location === 'string') { + var updated = this._updateUniformLocation(location, f1, f2, f3); + if (updated) { + var locObj = this.getUniformLocationForName(location); + gl.uniform3f(locObj, f1, f2, f3); + } + } + else { + gl.uniform3f(location, f1, f2, f3); + } }, /** @@ -468,58 +515,57 @@ cc.GLProgram = cc._Class.extend(/** @lends cc.GLProgram# */{ * @param {Number} f4 */ setUniformLocationWith4f: function (location, f1, f2, f3, f4) { - var floats = [f1, f2, f3, f4]; - var updated = this._updateUniformLocation(location, floats); - if (updated) - this._glContext.uniform4f(location, f1, f2, f3, f4); + var gl = this._glContext; + if (typeof location === 'string') { + var updated = this._updateUniformLocation(location, f1, f2, f3, f4); + if (updated) { + var locObj = this.getUniformLocationForName(location); + gl.uniform4f(locObj, f1, f2, f3, f4); + } + } + else { + gl.uniform4f(location, f1, f2, f3, f4); + } }, /** * calls glUniform2fv only if the values are different than the previous call for this same shader program. * @param {WebGLUniformLocation} location * @param {Float32Array} floatArray - * @param {Number} numberOfArrays */ - setUniformLocationWith2fv: function (location, floatArray, numberOfArrays) { - var updated = this._updateUniformLocation(location, floatArray); - if (updated) - this._glContext.uniform2fv(location, floatArray); + setUniformLocationWith2fv: function (location, floatArray) { + var locObj = typeof location === 'string' ? this.getUniformLocationForName(location) : location; + this._glContext.uniform2fv(locObj, floatArray); }, /** * calls glUniform3fv only if the values are different than the previous call for this same shader program. * @param {WebGLUniformLocation} location * @param {Float32Array} floatArray - * @param {Number} numberOfArrays */ - setUniformLocationWith3fv: function (location, floatArray, numberOfArrays) { - var updated = this._updateUniformLocation(location, floatArray); - if (updated) - this._glContext.uniform3fv(location, floatArray); + setUniformLocationWith3fv: function (location, floatArray) { + var locObj = typeof location === 'string' ? this.getUniformLocationForName(location) : location; + this._glContext.uniform3fv(locObj, floatArray); }, /** * calls glUniform4fv only if the values are different than the previous call for this same shader program. * @param {WebGLUniformLocation} location * @param {Float32Array} floatArray - * @param {Number} numberOfArrays */ - setUniformLocationWith4fv: function (location, floatArray, numberOfArrays) { - var updated = this._updateUniformLocation(location, floatArray); - if (updated) - this._glContext.uniform4fv(location, floatArray); + setUniformLocationWith4fv: function (location, floatArray) { + var locObj = typeof location === 'string' ? this.getUniformLocationForName(location) : location; + this._glContext.uniform4fv(locObj, floatArray); }, /** * calls glUniformMatrix4fv only if the values are different than the previous call for this same shader program. * @param {WebGLUniformLocation} location * @param {Float32Array} matrixArray - * @param {Number} numberOfMatrices */ - setUniformLocationWithMatrix4fv: function (location, matrixArray, numberOfMatrices) { - var updated = this._updateUniformLocation(location, matrixArray); - if (updated) - this._glContext.uniformMatrix4fv(location, false, matrixArray); + setUniformLocationWithMatrix4fv: function (location, matrixArray) { + var locObj = typeof location === 'string' ? this.getUniformLocationForName(location) : location; + this._glContext.uniformMatrix4fv(locObj, false, matrixArray); }, setUniformLocationF32: function () { @@ -633,6 +679,10 @@ cc.GLProgram = cc._Class.extend(/** @lends cc.GLProgram# */{ this._glContext.uniformMatrix4fv(this._uniforms[macro.UNIFORM_PMATRIX], false, math.projection_matrix_stack.top.mat); }, + _updateProjectionUniform: function(){ + this._glContext.uniformMatrix4fv(this._uniforms[macro.UNIFORM_PMATRIX], false, math.projection_matrix_stack.top.mat); + }, + /** * returns the vertexShader error log * @return {String} @@ -696,12 +746,10 @@ cc.GLProgram = cc._Class.extend(/** @lends cc.GLProgram# */{ this._programObj = null; // Purge uniform hash - for (var i = 0; i < this._hashForUniforms.length; i++) { - this._hashForUniforms[i].value = null; - this._hashForUniforms[i] = null; + for (var key in this._hashForUniforms) { + this._hashForUniforms[key].length = 0; + delete this._hashForUniforms[key]; } - - this._hashForUniforms.length = 0; }, /** diff --git a/cocos2d/shaders/CCGLStateCache.js b/cocos2d/shaders/CCGLStateCache.js index ac5873ea2e..c92b0a3623 100644 --- a/cocos2d/shaders/CCGLStateCache.js +++ b/cocos2d/shaders/CCGLStateCache.js @@ -25,12 +25,8 @@ ****************************************************************************/ var _currentProjectionMatrix = -1; -var _vertexAttribPosition = false; -var _vertexAttribColor = false; -var _vertexAttribTexCoords = false; var macro = cc.macro; - var ENABLE_GL_STATE_CACHE = macro.ENABLE_GL_STATE_CACHE; var MAX_ACTIVETEXTURE = 0, @@ -42,7 +38,6 @@ var MAX_ACTIVETEXTURE = 0, _uVAO = 0; if (ENABLE_GL_STATE_CACHE) { MAX_ACTIVETEXTURE = 16; - _currentShaderProgram = -1; _currentBoundTexture = [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1]; _blendingSource = -1; @@ -50,6 +45,64 @@ if (ENABLE_GL_STATE_CACHE) { _GLServerState = 0; if(macro.TEXTURE_ATLAS_USE_VAO) _uVAO = 0; + + var _currBuffers = {}; + + WebGLRenderingContext.prototype.glBindBuffer = WebGLRenderingContext.prototype.bindBuffer; + WebGLRenderingContext.prototype.bindBuffer = function (target, buffer) { + if (_currBuffers[target] !== buffer) { + this.glBindBuffer(target, buffer); + _currBuffers[target] = buffer; + return false; + } + else { + return true; + } + }; + + WebGLRenderingContext.prototype.glEnableVertexAttribArray = WebGLRenderingContext.prototype.enableVertexAttribArray; + WebGLRenderingContext.prototype.enableVertexAttribArray = function (index) { + if (index === macro.VERTEX_ATTRIB_FLAG_POSITION) { + if (!this._vertexAttribPosition) { + this.glEnableVertexAttribArray(index); + this._vertexAttribPosition = true; + } + } + else if (index === macro.VERTEX_ATTRIB_FLAG_COLOR) { + if (!this._vertexAttribColor) { + this.glEnableVertexAttribArray(index); + this._vertexAttribColor = true; + } + } + else if (index === macro.VERTEX_ATTRIB_FLAG_TEX_COORDS) { + if (!this._vertexAttribTexCoords) { + this.glEnableVertexAttribArray(index); + this._vertexAttribTexCoords = true; + } + } + else { + this.glEnableVertexAttribArray(index); + } + }; + + WebGLRenderingContext.prototype.glDisableVertexAttribArray = WebGLRenderingContext.prototype.disableVertexAttribArray; + WebGLRenderingContext.prototype.disableVertexAttribArray = function (index) { + if (index === macro.VERTEX_ATTRIB_FLAG_COLOR) { + if (this._vertexAttribColor) { + this.glDisableVertexAttribArray(index); + this._vertexAttribColor = false; + } + } + else if (index === macro.VERTEX_ATTRIB_FLAG_TEX_COORDS) { + if (this._vertexAttribTexCoords) { + this.glDisableVertexAttribArray(index); + this._vertexAttribTexCoords = false; + } + } + else if (index !== 0) { + this.glDisableVertexAttribArray(index); + } + }; } // GL State Cache functions @@ -64,9 +117,6 @@ cc.gl = {}; cc.gl.invalidateStateCache = function () { cc.math.glFreeAll(); _currentProjectionMatrix = -1; - _vertexAttribPosition = false; - _vertexAttribColor = false; - _vertexAttribTexCoords = false; if (ENABLE_GL_STATE_CACHE) { _currentShaderProgram = -1; for (var i = 0; i < MAX_ACTIVETEXTURE; i++) { @@ -107,21 +157,6 @@ cc.gl.deleteProgram = function (program) { gl.deleteProgram(program); }; -/* - * Uses a blending function in case it not already used.
- * If cc.macro.ENABLE_GL_STATE_CACHE is disabled, it will use glContext.blendFunc() directly. - * @function - * @param {Number} sfactor - * @param {Number} dfactor - */ -cc.gl.blendFunc = ENABLE_GL_STATE_CACHE ? function (sfactor, dfactor) { - if ((sfactor !== _blendingSource) || (dfactor !== _blendingDest)) { - _blendingSource = sfactor; - _blendingDest = dfactor; - cc.gl.setBlending(sfactor, dfactor); - } -} : cc.gl.setBlending; - /** * @function * @param {Number} sfactor @@ -139,6 +174,21 @@ cc.gl.setBlending = function (sfactor, dfactor) { } }; +/* + * Uses a blending function in case it not already used.
+ * If cc.macro.ENABLE_GL_STATE_CACHE is disabled, it will use glContext.blendFunc() directly. + * @function + * @param {Number} sfactor + * @param {Number} dfactor + */ +cc.gl.blendFunc = ENABLE_GL_STATE_CACHE ? function (sfactor, dfactor) { + if ((sfactor !== _blendingSource) || (dfactor !== _blendingDest)) { + _blendingSource = sfactor; + _blendingDest = dfactor; + cc.gl.setBlending(sfactor, dfactor); + } +} : cc.gl.setBlending; + /** * @function * @param {Number} sfactor @@ -182,52 +232,6 @@ cc.gl.setProjectionMatrixDirty = function () { _currentProjectionMatrix = -1; }; -/** - *

- * Will enable the vertex attribs that are passed as flags.
- * Possible flags:
- * cc.macro.VERTEX_ATTRIB_FLAG_POSITION
- * cc.macro.VERTEX_ATTRIB_FLAG_COLOR
- * cc.macro.VERTEX_ATTRIB_FLAG_TEX_COORDS
- *
- * These flags can be ORed. The flags that are not present, will be disabled. - *

- * @function - * @param {cc.macro.VERTEX_ATTRIB_FLAG_POSITION | cc.macro.VERTEX_ATTRIB_FLAG_COLOR | cc.macro.VERTEX_ATTRIB_FLAG_TEX_OORDS} flags - */ -cc.gl.enableVertexAttribs = function (flags) { - /* Position */ - var ctx = cc._renderContext; - var enablePosition = ( flags & macro.VERTEX_ATTRIB_FLAG_POSITION ); - if (enablePosition !== _vertexAttribPosition) { - if (enablePosition) - ctx.enableVertexAttribArray(macro.VERTEX_ATTRIB_POSITION); - else - ctx.disableVertexAttribArray(macro.VERTEX_ATTRIB_POSITION); - _vertexAttribPosition = enablePosition; - } - - /* Color */ - var enableColor = (flags & macro.VERTEX_ATTRIB_FLAG_COLOR); - if (enableColor !== _vertexAttribColor) { - if (enableColor) - ctx.enableVertexAttribArray(macro.VERTEX_ATTRIB_COLOR); - else - ctx.disableVertexAttribArray(macro.VERTEX_ATTRIB_COLOR); - _vertexAttribColor = enableColor; - } - - /* Tex Coords */ - var enableTexCoords = (flags & macro.VERTEX_ATTRIB_FLAG_TEX_COORDS); - if (enableTexCoords !== _vertexAttribTexCoords) { - if (enableTexCoords) - ctx.enableVertexAttribArray(macro.VERTEX_ATTRIB_TEX_COORDS); - else - ctx.disableVertexAttribArray(macro.VERTEX_ATTRIB_TEX_COORDS); - _vertexAttribTexCoords = enableTexCoords; - } -}; - /** * If the texture is not already bound, it binds it.
* If cc.macro.ENABLE_GL_STATE_CACHE is disabled, it will call glBindTexture() directly. diff --git a/cocos2d/shaders/CCShaderCache.js b/cocos2d/shaders/CCShaderCache.js index c004f2a359..0b533f9528 100644 --- a/cocos2d/shaders/CCShaderCache.js +++ b/cocos2d/shaders/CCShaderCache.js @@ -34,60 +34,78 @@ var macro = cc.macro; */ cc.shaderCache = /** @lends cc.shaderCache# */{ - /** - * @public - * @constant - * @type {Number} - */ - TYPE_POSITION_TEXTURECOLOR: 0, - /** - * @public - * @constant - * @type {Number} - */ - TYPE_POSITION_TEXTURECOLOR_ALPHATEST: 1, - /** - * @public - * @constant - * @type {Number} - */ - TYPE_POSITION_COLOR: 2, - /** - * @public - * @constant - * @type {Number} - */ - TYPE_POSITION_TEXTURE: 3, - /** - * @public - * @constant - * @type {Number} - */ - TYPE_POSITION_TEXTURE_UCOLOR: 4, - /** - * @public - * @constant - * @type {Number} - */ - TYPE_POSITION_TEXTURE_A8COLOR: 5, - /** - * @public - * @constant - * @type {Number} - */ - TYPE_POSITION_UCOLOR: 6, - /** - * @public - * @constant - * @type {Number} - */ - TYPE_POSITION_LENGTH_TEXTURECOLOR: 7, - /** - * @public - * @constant - * @type {Number} - */ - TYPE_MAX: 8, + /** + * @public + * @constant + * @type {Number} + */ + TYPE_POSITION_TEXTURECOLOR: 0, + /** + * @public + * @constant + * @type {Number} + */ + TYPE_POSITION_TEXTURECOLOR_ALPHATEST: 1, + /** + * @public + * @constant + * @type {Number} + */ + TYPE_POSITION_COLOR: 2, + /** + * @public + * @constant + * @type {Number} + */ + TYPE_POSITION_TEXTURE: 3, + /** + * @public + * @constant + * @type {Number} + */ + TYPE_POSITION_TEXTURE_UCOLOR: 4, + /** + * @public + * @constant + * @type {Number} + */ + TYPE_POSITION_TEXTURE_A8COLOR: 5, + /** + * @public + * @constant + * @type {Number} + */ + TYPE_POSITION_UCOLOR: 6, + /** + * @public + * @constant + * @type {Number} + */ + TYPE_POSITION_LENGTH_TEXTURECOLOR: 7, + /** + * @public + * @constant + * @type {Number} + */ + TYPE_SPRITE_POSITION_TEXTURECOLOR: 8, + /** + * @public + * @constant + * @type {Number} + */ + TYPE_SPRITE_POSITION_TEXTURECOLOR_ALPHATEST: 9, + /** + * @public + * @constant + * @type {Number} + */ + TYPE_SPRITE_POSITION_COLOR: 10, + /** + * @public + * @constant + * @type {Number} + */ + TYPE_MAX: 10, _programs: {}, @@ -101,6 +119,12 @@ cc.shaderCache = /** @lends cc.shaderCache# */{ case this.TYPE_POSITION_TEXTURECOLOR: program.initWithVertexShaderByteArray(shaders.POSITION_TEXTURE_COLOR_VERT, shaders.POSITION_TEXTURE_COLOR_FRAG); + program.addAttribute(macro.ATTRIBUTE_NAME_POSITION, macro.VERTEX_ATTRIB_POSITION); + program.addAttribute(macro.ATTRIBUTE_NAME_COLOR, macro.VERTEX_ATTRIB_COLOR); + program.addAttribute(macro.ATTRIBUTE_NAME_TEX_COORD, macro.VERTEX_ATTRIB_TEX_COORDS); + break; + case this.TYPE_SPRITE_POSITION_TEXTURECOLOR: + program.initWithVertexShaderByteArray(shaders.SPRITE_POSITION_TEXTURE_COLOR_VERT, shaders.POSITION_TEXTURE_COLOR_FRAG); program.addAttribute(macro.ATTRIBUTE_NAME_POSITION, macro.VERTEX_ATTRIB_POSITION); program.addAttribute(macro.ATTRIBUTE_NAME_COLOR, macro.VERTEX_ATTRIB_COLOR); program.addAttribute(macro.ATTRIBUTE_NAME_TEX_COORD, macro.VERTEX_ATTRIB_TEX_COORDS); @@ -108,6 +132,12 @@ cc.shaderCache = /** @lends cc.shaderCache# */{ case this.TYPE_POSITION_TEXTURECOLOR_ALPHATEST: program.initWithVertexShaderByteArray(shaders.POSITION_TEXTURE_COLOR_VERT, shaders.POSITION_TEXTURE_COLOR_ALPHATEST_FRAG); + program.addAttribute(macro.ATTRIBUTE_NAME_POSITION, macro.VERTEX_ATTRIB_POSITION); + program.addAttribute(macro.ATTRIBUTE_NAME_COLOR, macro.VERTEX_ATTRIB_COLOR); + program.addAttribute(macro.ATTRIBUTE_NAME_TEX_COORD, macro.VERTEX_ATTRIB_TEX_COORDS); + break; + case this.TYPE_SPRITE_POSITION_TEXTURECOLOR_ALPHATEST: + program.initWithVertexShaderByteArray(shaders.SPRITE_POSITION_TEXTURE_COLOR_VERT, shaders.POSITION_TEXTURE_COLOR_ALPHATEST_FRAG); program.addAttribute(macro.ATTRIBUTE_NAME_POSITION, macro.VERTEX_ATTRIB_POSITION); program.addAttribute(macro.ATTRIBUTE_NAME_COLOR, macro.VERTEX_ATTRIB_COLOR); program.addAttribute(macro.ATTRIBUTE_NAME_TEX_COORD, macro.VERTEX_ATTRIB_TEX_COORDS); @@ -115,6 +145,11 @@ cc.shaderCache = /** @lends cc.shaderCache# */{ case this.TYPE_POSITION_COLOR: program.initWithVertexShaderByteArray(shaders.POSITION_COLOR_VERT, shaders.POSITION_COLOR_FRAG); + program.addAttribute(macro.ATTRIBUTE_NAME_POSITION, macro.VERTEX_ATTRIB_POSITION); + program.addAttribute(macro.ATTRIBUTE_NAME_COLOR, macro.VERTEX_ATTRIB_COLOR); + break; + case this.TYPE_SPRITE_POSITION_COLOR: + program.initWithVertexShaderByteArray(shaders.SPRITE_POSITION_COLOR_VERT, shaders.POSITION_COLOR_FRAG); program.addAttribute(macro.ATTRIBUTE_NAME_POSITION, macro.VERTEX_ATTRIB_POSITION); program.addAttribute(macro.ATTRIBUTE_NAME_COLOR, macro.VERTEX_ATTRIB_COLOR); break; @@ -169,12 +204,24 @@ cc.shaderCache = /** @lends cc.shaderCache# */{ this._programs[macro.SHADER_POSITION_TEXTURECOLOR] = program; this._programs["ShaderPositionTextureColor"] = program; + // Position Texture Color shader with position precalculated + program = new cc.GLProgram(); + this._loadDefaultShader(program, this.TYPE_SPRITE_POSITION_TEXTURECOLOR); + this._programs[macro.SHADER_SPRITE_POSITION_TEXTURECOLOR] = program; + this._programs["ShaderSpritePositionTextureColor"] = program; + // Position Texture Color alpha test program = new cc.GLProgram(); this._loadDefaultShader(program, this.TYPE_POSITION_TEXTURECOLOR_ALPHATEST); this._programs[macro.SHADER_POSITION_TEXTURECOLORALPHATEST] = program; this._programs["ShaderPositionTextureColorAlphaTest"] = program; + // Position Texture Color alpha with position precalculated + program = new cc.GLProgram(); + this._loadDefaultShader(program, this.TYPE_SPRITE_POSITION_TEXTURECOLOR_ALPHATEST); + this._programs[macro.SHADER_SPRITE_POSITION_TEXTURECOLORALPHATEST] = program; + this._programs["ShaderSpritePositionTextureColorAlphaTest"] = program; + // // Position, Color shader // @@ -183,6 +230,14 @@ cc.shaderCache = /** @lends cc.shaderCache# */{ this._programs[macro.SHADER_POSITION_COLOR] = program; this._programs["ShaderPositionColor"] = program; + // + // Position, Color shader with position precalculated + // + program = new cc.GLProgram(); + this._loadDefaultShader(program, this.TYPE_SPRITE_POSITION_COLOR); + this._programs[macro.SHADER_SPRITE_POSITION_COLOR] = program; + this._programs["ShaderSpritePositionColor"] = program; + // // Position Texture shader // @@ -235,11 +290,21 @@ cc.shaderCache = /** @lends cc.shaderCache# */{ program.reset(); this._loadDefaultShader(program, this.TYPE_POSITION_TEXTURECOLOR); + // Sprite Position Texture Color shader + program = this.programForKey(macro.SHADER_SPRITE_POSITION_TEXTURECOLOR); + program.reset(); + this._loadDefaultShader(program, this.TYPE_SPRITE_POSITION_TEXTURECOLOR); + // Position Texture Color alpha test program = this.programForKey(macro.SHADER_POSITION_TEXTURECOLORALPHATEST); program.reset(); this._loadDefaultShader(program, this.TYPE_POSITION_TEXTURECOLOR_ALPHATEST); + // Sprite Position Texture Color alpha shader + program = this.programForKey(macro.SHADER_SPRITE_POSITION_TEXTURECOLORALPHATEST); + program.reset(); + this._loadDefaultShader(program, this.TYPE_SPRITE_POSITION_TEXTURECOLOR_ALPHATEST); + // // Position, Color shader // @@ -301,4 +366,4 @@ cc.shaderCache = /** @lends cc.shaderCache# */{ addProgram: function (program, key) { this._programs[key] = program; } -}; \ No newline at end of file +}; diff --git a/cocos2d/shaders/CCShaders.js b/cocos2d/shaders/CCShaders.js index 974f3c9c0a..af4d86c1fe 100644 --- a/cocos2d/shaders/CCShaders.js +++ b/cocos2d/shaders/CCShaders.js @@ -1,7 +1,7 @@ /**************************************************************************** Copyright (c) 2008-2010 Ricardo Quesada Copyright (c) 2011-2012 cocos2d-x.org - Copyright (c) 2013-2014 Chukong Technologies Inc. + Copyright (c) 2013-2016 Chukong Technologies Inc. http://www.cocos2d-x.org @@ -27,7 +27,7 @@ //-----------------------Shader_Position_uColor Shader Source-------------------------- /** - * Predefined constants + * Predefined propertys * @class PresetShaders * @readonly * @type {Object} @@ -84,14 +84,26 @@ cc.PresetShaders = { + "varying lowp vec4 v_fragmentColor;\n" + "void main()\n" + "{\n" - //+ " gl_Position = CC_MVPMatrix * a_position; \n" + " gl_Position = (CC_PMatrix * CC_MVMatrix) * a_position; \n" + " v_fragmentColor = a_color; \n" + "}", + /** + * @property SPRITE_POSITION_COLOR_VERT + * @type {String} + */ + SPRITE_POSITION_COLOR_VERT : "attribute vec4 a_position;\n" + + "attribute vec4 a_color;\n" + + "varying lowp vec4 v_fragmentColor;\n" + + "void main()\n" + + "{\n" + + " gl_Position = CC_PMatrix * a_position; \n" + + " v_fragmentColor = a_color; \n" + + "}", + // --------------------- Shader_PositionColorLengthTexture Shader source------------------------ /** - * @constant + * @property POSITION_COLOR_LENGTH_TEXTURE_FRAG * @type {String} */ POSITION_COLOR_LENGTH_TEXTURE_FRAG : "// #extension GL_OES_standard_derivatives : enable\n" @@ -107,7 +119,7 @@ cc.PresetShaders = { + "}", /** - * @constant + * @property POSITION_COLOR_LENGTH_TEXTURE_VERT * @type {String} */ POSITION_COLOR_LENGTH_TEXTURE_VERT : "attribute mediump vec4 a_position; \n" @@ -125,7 +137,7 @@ cc.PresetShaders = { // ----------------------Shader_PositionTexture Shader Source------------------------------------- /** - * @constant + * @property POSITION_TEXTURE_FRAG * @type {String} */ POSITION_TEXTURE_FRAG : "precision lowp float; \n" @@ -136,7 +148,7 @@ cc.PresetShaders = { + "}", /** - * @constant + * @property POSITION_TEXTURE_VERT * @type {String} */ POSITION_TEXTURE_VERT : "attribute vec4 a_position; \n" @@ -151,7 +163,7 @@ cc.PresetShaders = { // ------------------------Shader_PositionTexture_uColor Shader Source------------------------------- /** - * @constant + * @property POSITION_TEXTURE_UCOLOR_FRAG * @type {String} */ POSITION_TEXTURE_UCOLOR_FRAG : "precision lowp float; \n" @@ -163,7 +175,7 @@ cc.PresetShaders = { + "}", /** - * @constant + * @property POSITION_TEXTURE_UCOLOR_VERT * @type {String} */ POSITION_TEXTURE_UCOLOR_VERT : "attribute vec4 a_position;\n" @@ -178,7 +190,7 @@ cc.PresetShaders = { //---------------------Shader_PositionTextureA8Color Shader source------------------------------- /** - * @constant + * @property POSITION_TEXTURE_A8COLOR_FRAG * @type {String} */ POSITION_TEXTURE_A8COLOR_FRAG : "precision lowp float; \n" @@ -192,7 +204,7 @@ cc.PresetShaders = { + "}", /** - * @constant + * @property POSITION_TEXTURE_A8COLOR_VERT * @type {String} */ POSITION_TEXTURE_A8COLOR_VERT : "attribute vec4 a_position; \n" @@ -202,7 +214,6 @@ cc.PresetShaders = { + "varying mediump vec2 v_texCoord; \n" + "void main() \n" + "{ \n" - //+ " gl_Position = CC_MVPMatrix * a_position; \n" + " gl_Position = (CC_PMatrix * CC_MVMatrix) * a_position; \n" + " v_fragmentColor = a_color; \n" + " v_texCoord = a_texCoord; \n" @@ -210,7 +221,7 @@ cc.PresetShaders = { // ------------------------Shader_PositionTextureColor Shader source------------------------------------ /** - * @constant + * @property POSITION_TEXTURE_COLOR_FRAG * @type {String} */ POSITION_TEXTURE_COLOR_FRAG : "precision lowp float;\n" @@ -222,7 +233,7 @@ cc.PresetShaders = { + "}", /** - * @constant + * @property POSITION_TEXTURE_COLOR_VERT * @type {String} */ POSITION_TEXTURE_COLOR_VERT : "attribute vec4 a_position; \n" @@ -232,15 +243,30 @@ cc.PresetShaders = { + "varying mediump vec2 v_texCoord; \n" + "void main() \n" + "{ \n" - //+ " gl_Position = CC_MVPMatrix * a_position; \n" + " gl_Position = (CC_PMatrix * CC_MVMatrix) * a_position; \n" + " v_fragmentColor = a_color; \n" + " v_texCoord = a_texCoord; \n" + "}", + /** + * @property SPRITE_POSITION_TEXTURE_COLOR_VERT + * @type {String} + */ + SPRITE_POSITION_TEXTURE_COLOR_VERT : "attribute vec4 a_position; \n" + + "attribute vec2 a_texCoord; \n" + + "attribute vec4 a_color; \n" + + "varying lowp vec4 v_fragmentColor; \n" + + "varying mediump vec2 v_texCoord; \n" + + "void main() \n" + + "{ \n" + + " gl_Position = CC_PMatrix * a_position; \n" + + " v_fragmentColor = a_color; \n" + + " v_texCoord = a_texCoord; \n" + + "}", + //-----------------------Shader_PositionTextureColorAlphaTest_frag Shader Source---------------------------- /** - * @constant + * @property POSITION_TEXTURE_COLOR_ALPHATEST_FRAG * @type {String} */ POSITION_TEXTURE_COLOR_ALPHATEST_FRAG : "precision lowp float; \n" @@ -259,7 +285,7 @@ cc.PresetShaders = { //-----------------------ShaderEx_SwitchMask_frag Shader Source---------------------------- /** - * @constant + * @property EX_SWITCHMASK_FRAG * @type {String} */ EX_SWITCHMASK_FRAG : "precision lowp float; \n" @@ -275,4 +301,4 @@ cc.PresetShaders = { + " gl_FragColor = v_fragmentColor * finalColor; \n" + "}" -}; \ No newline at end of file +}; diff --git a/cocos2d/shape-nodes/CCDrawNode.js b/cocos2d/shape-nodes/CCDrawNode.js index 0973fe133c..2504ae4947 100644 --- a/cocos2d/shape-nodes/CCDrawNode.js +++ b/cocos2d/shape-nodes/CCDrawNode.js @@ -468,7 +468,7 @@ cc.game.once(cc.game.EVENT_RENDERER_INITED, function () { _ccsg.Node.prototype.ctor.call(this); this._buffer = []; this._blendFunc = new cc.BlendFunc(cc.macro.SRC_ALPHA, cc.macro.ONE_MINUS_SRC_ALPHA); - this._drawColor = new cc.WebGLColor(255,255,255,255); + this._drawColor = cc.color(255,255,255,255); this.init(); }, @@ -589,7 +589,6 @@ cc.game.once(cc.game.EVENT_RENDERER_INITED, function () { _render:function () { var gl = cc._renderContext; - cc.gl.enableVertexAttribs(cc.macro.VERTEX_ATTRIB_FLAG_POS_COLOR_TEX); gl.bindBuffer(gl.ARRAY_BUFFER, this._trianglesWebBuffer); if (this._dirty) { gl.bufferData(gl.ARRAY_BUFFER, this._trianglesArrayBuffer, gl.STREAM_DRAW); @@ -597,6 +596,10 @@ cc.game.once(cc.game.EVENT_RENDERER_INITED, function () { } var triangleSize = cc.V2F_C4B_T2F.BYTES_PER_ELEMENT; + gl.enableVertexAttribArray(cc.macro.VERTEX_ATTRIB_POSITION); + gl.enableVertexAttribArray(cc.macro.VERTEX_ATTRIB_COLOR); + gl.enableVertexAttribArray(cc.macro.VERTEX_ATTRIB_TEX_COORDS); + // vertex gl.vertexAttribPointer(cc.macro.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, triangleSize, 0); // color diff --git a/cocos2d/shape-nodes/CCDrawNodeWebGLRenderCmd.js b/cocos2d/shape-nodes/CCDrawNodeWebGLRenderCmd.js index 2125837e61..2f5b445a37 100644 --- a/cocos2d/shape-nodes/CCDrawNodeWebGLRenderCmd.js +++ b/cocos2d/shape-nodes/CCDrawNodeWebGLRenderCmd.js @@ -25,6 +25,8 @@ cc.DrawNode.WebGLRenderCmd = function (renderableObject) { _ccsg.Node.WebGLRenderCmd.call(this, renderableObject); this._needDraw = true; + this._matrix = new cc.math.Matrix4(); + this._matrix.identity(); }; cc.DrawNode.WebGLRenderCmd.prototype = Object.create(_ccsg.Node.WebGLRenderCmd.prototype); @@ -32,8 +34,18 @@ cc.DrawNode.WebGLRenderCmd.prototype.constructor = cc.DrawNode.WebGLRenderCmd; cc.DrawNode.WebGLRenderCmd.prototype.rendering = function (ctx) { var node = this._node; - cc.gl.blendFunc(node._blendFunc.src, node._blendFunc.dst); - this._shaderProgram.use(); - this._shaderProgram._setUniformForMVPMatrixWithMat4(this._stackMatrix); - node._render(); -}; \ No newline at end of file + if (node._buffer.length > 0) { + var wt = this._worldTransform, mat = this._matrix.mat; + mat[0] = wt.a; + mat[4] = wt.c; + mat[12] = wt.tx; + mat[1] = wt.b; + mat[5] = wt.d; + mat[13] = wt.ty; + + cc.gl.blendFunc(node._blendFunc.src, node._blendFunc.dst); + this._shaderProgram.use(); + this._shaderProgram._setUniformForMVPMatrixWithMat4(this._matrix); + node._render(); + } +}; diff --git a/cocos2d/text-input/CCIMEDispatcher.js b/cocos2d/text-input/CCIMEDispatcher.js index f3e098ef0d..8f1bd27644 100644 --- a/cocos2d/text-input/CCIMEDispatcher.js +++ b/cocos2d/text-input/CCIMEDispatcher.js @@ -391,8 +391,9 @@ cc.IMEDispatcher = cc._Class.extend(/** @lends cc.imeDispatcher# */{ var tipMessage = delegate.getTipMessage ? delegate.getTipMessage() : "please enter your word:"; // wechat cover the prompt funciton .So need use the Window.prototype.prompt var userInput; - if(window.Window && Window.prototype.prompt != prompt){ - userInput = Window.prototype.prompt.call(window, tipMessage, this._currentInputString); + var win = window.Window; + if(win && win.prototype.prompt && win.prototype.prompt != prompt){ + userInput = win.prototype.prompt.call(window, tipMessage, this._currentInputString); }else{ userInput = prompt(tipMessage, this._currentInputString); } diff --git a/cocos2d/tilemap/CCSGTMXLayer.js b/cocos2d/tilemap/CCSGTMXLayer.js index 64f1ca80e5..5796a36bb4 100644 --- a/cocos2d/tilemap/CCSGTMXLayer.js +++ b/cocos2d/tilemap/CCSGTMXLayer.js @@ -55,12 +55,17 @@ * @property {Number} tileWidth - Width of a tile * @property {Number} tileHeight - Height of a tile */ -_ccsg.TMXLayer = cc.SpriteBatchNode.extend(/** @lends _ccsg.TMXLayer# */{ - tiles: null, - tileset: null, - layerOrientation: null, - properties: null, - layerName: "", +_ccsg.TMXLayer = _ccsg.Node.extend(/** @lends _ccsg.TMXLayer# */{ + tiles: null, + tileset: null, + layerOrientation: null, + properties: null, + layerName: "", + + _texture: null, + _textures: null, + _texGrids: null, + _spriteTiles: null, //size of the layer in tiles _layerSize: null, @@ -93,6 +98,7 @@ _ccsg.TMXLayer = cc.SpriteBatchNode.extend(/** @lends _ccsg.TMXLayer# */{ this._layerSize = cc.size(0, 0); this._mapTileSize = cc.size(0, 0); + this._spriteTiles = {}; if(mapInfo !== undefined) this.initWithTilesetInfo(tilesetInfo, layerInfo, mapInfo); @@ -105,24 +111,112 @@ _ccsg.TMXLayer = cc.SpriteBatchNode.extend(/** @lends _ccsg.TMXLayer# */{ return new _ccsg.TMXLayer.WebGLRenderCmd(this); }, - /** - * Sets the untransformed size of the TMXLayer. - * @override - * @param {Size|Number} size The untransformed size of the TMXLayer or The untransformed size's width of the TMXLayer. - * @param {Number} [height] The untransformed size's height of the TMXLayer. - */ - setContentSize:function (size, height) { - _ccsg.Node.prototype.setContentSize.call(this, size, height); - this._renderCmd._updateCacheContext(size, height); + _fillTextureGrids: function (tileset, texId) { + var tex = this._textures[texId]; + if (!tex.isLoaded()) { + tex.once('load', function () { + this._fillTextureGrids(tileset, texId); + }, this); + return; + } + if (!tileset.imageSize.width || !tileset.imageSize.height) { + tileset.imageSize.width = tex.width; + tileset.imageSize.height = tex.height; + } + var tw = tileset._tileSize.width, + th = tileset._tileSize.height, + imageW = tex._contentSize.width, + imageH = tex._contentSize.height, + spacing = tileset.spacing, + margin = tileset.margin, + + cols = Math.floor((imageW - margin*2 + spacing) / (tw + spacing)), + rows = Math.floor((imageH - margin*2 + spacing) / (th + spacing)), + count = rows * cols, + + gid = tileset.firstGid, + maxGid = tileset.firstGid + count, + grids = this._texGrids, + grid = null, + override = grids[gid] ? true : false; + + for (; gid < maxGid; ++gid) { + // Avoid overlapping + if (override && !grids[gid]) { + override = false; + } + if (!override && grids[gid]) { + break; + } + + grid = { + texId: texId, + x: 0, y: 0, width: tw, height: th, + t: 0, l: 0, r: 0, b: 0 + }; + tileset.rectForGID(gid, grid); + grid.t = grid.y / imageH; + grid.l = grid.x / imageW; + grid.r = (grid.x + grid.width) / imageW; + grid.b = (grid.y + grid.height) / imageH; + grids[gid] = grid; + } }, /** - * Return texture of cc.SpriteBatchNode - * @function - * @return {Texture2D} + * Initializes a cc.TMXLayer with a tileset info, a layer info and a map info + * @param {cc.TMXTilesetInfo} tilesetInfo + * @param {cc.TMXLayerInfo} layerInfo + * @param {cc.TMXMapInfo} mapInfo + * @return {Boolean} */ - getTexture: function(){ - return this._renderCmd.getTexture(); + initWithTilesetInfo:function (tilesetInfo, layerInfo, mapInfo) { + var size = layerInfo._layerSize; + + // layerInfo + this.layerName = layerInfo.name; + this.tiles = layerInfo._tiles; + this.properties = layerInfo.properties; + this._layerSize = size; + this._minGID = layerInfo._minGID; + this._maxGID = layerInfo._maxGID; + this._opacity = layerInfo._opacity; + + // tilesetInfo + this.tileset = tilesetInfo; + + // mapInfo + this.layerOrientation = mapInfo.orientation; + this._mapTileSize = mapInfo.getTileSize(); + + var tilesets = mapInfo._tilesets; + if (tilesets) { + var i, len = tilesets.length, tileset, tex; + this._textures = new Array(len); + this._texGrids = []; + for (i = 0; i < len; ++i) { + tileset = tilesets[i]; + tex = cc.textureCache.addImage(tileset.sourceImage); + this._textures[i] = tex; + this._fillTextureGrids(tileset, i); + if (tileset === tilesetInfo) { + this._texture = tex; + } + } + } + + // offset (after layer orientation is set); + var offset = this._calculateLayerOffset(layerInfo.offset); + this.setPosition(offset); + + // Parse cocos2d properties + this._parseInternalProperties(); + + this.setContentSize(this._layerSize.width * this._mapTileSize.width, + this._layerSize.height * this._mapTileSize.height); + this._useAutomaticVertexZ = false; + this._vertexZvalue = 0; + return true; }, /** @@ -142,18 +236,18 @@ _ccsg.TMXLayer = cc.SpriteBatchNode.extend(/** @lends _ccsg.TMXLayer# */{ this._layerSize.height = Var.height; }, - _getLayerWidth: function () { - return this._layerSize.width; - }, - _setLayerWidth: function (width) { - this._layerSize.width = width; - }, - _getLayerHeight: function () { - return this._layerSize.height; - }, - _setLayerHeight: function (height) { - this._layerSize.height = height; - }, + _getLayerWidth: function () { + return this._layerSize.width; + }, + _setLayerWidth: function (width) { + this._layerSize.width = width; + }, + _getLayerHeight: function () { + return this._layerSize.height; + }, + _setLayerHeight: function (height) { + this._layerSize.height = height; + }, /** * Size of the map's tile (could be different from the tile's size) @@ -172,18 +266,18 @@ _ccsg.TMXLayer = cc.SpriteBatchNode.extend(/** @lends _ccsg.TMXLayer# */{ this._mapTileSize.height = Var.height; }, - _getTileWidth: function () { - return this._mapTileSize.width; - }, - _setTileWidth: function (width) { - this._mapTileSize.width = width; - }, - _getTileHeight: function () { - return this._mapTileSize.height; - }, - _setTileHeight: function (height) { - this._mapTileSize.height = height; - }, + _getTileWidth: function () { + return this._mapTileSize.width; + }, + _setTileWidth: function (width) { + this._mapTileSize.width = width; + }, + _getTileHeight: function () { + return this._mapTileSize.height; + }, + _setTileHeight: function (height) { + this._mapTileSize.height = height; + }, /** * Pointer to the map of tiles @@ -205,7 +299,7 @@ _ccsg.TMXLayer = cc.SpriteBatchNode.extend(/** @lends _ccsg.TMXLayer# */{ * Tile set information for the layer * @return {cc.TMXTilesetInfo} */ - getTileSet:function () { + getTileset:function () { return this.tileset; }, @@ -213,7 +307,7 @@ _ccsg.TMXLayer = cc.SpriteBatchNode.extend(/** @lends _ccsg.TMXLayer# */{ * Tile set information for the layer * @param {cc.TMXTilesetInfo} Var */ - setTileSet:function (Var) { + setTileset:function (Var) { this.tileset = Var; }, @@ -249,312 +343,6 @@ _ccsg.TMXLayer = cc.SpriteBatchNode.extend(/** @lends _ccsg.TMXLayer# */{ this.properties = Var; }, - /** - * Initializes a _ccsg.TMXLayer with a tileset info, a layer info and a map info - * @param {cc.TMXTilesetInfo} tilesetInfo - * @param {cc.TMXLayerInfo} layerInfo - * @param {cc.TMXMapInfo} mapInfo - * @return {Boolean} - */ - initWithTilesetInfo:function (tilesetInfo, layerInfo, mapInfo) { - // XXX: is 35% a good estimate ? - var size = layerInfo._layerSize; - var totalNumberOfTiles = parseInt(size.width * size.height); - var capacity = totalNumberOfTiles * 0.35 + 1; // 35 percent is occupied ? - var texture; - if (tilesetInfo) - texture = cc.textureCache.addImage(cc.path._normalize(tilesetInfo.sourceImage)); - - if (this.initWithTexture(texture, capacity)) { - // layerInfo - this.layerName = layerInfo.name; - this._layerSize = size; - this.tiles = layerInfo._tiles; - this._minGID = layerInfo._minGID; - this._maxGID = layerInfo._maxGID; - this._opacity = layerInfo._opacity; - this.properties = layerInfo.properties; - this._contentScaleFactor = cc.director.getContentScaleFactor(); - - // tilesetInfo - this.tileset = tilesetInfo; - - // mapInfo - this._mapTileSize = mapInfo.getTileSize(); - this.layerOrientation = mapInfo.orientation; - - // offset (after layer orientation is set); - var offset = this._calculateLayerOffset(layerInfo.offset); - this.setPosition(offset); - - this._atlasIndexArray = []; - this.setContentSize(cc.size(this._layerSize.width * this._mapTileSize.width, - this._layerSize.height * this._mapTileSize.height)); - this._useAutomaticVertexZ = false; - this._vertexZvalue = 0; - return true; - } - return false; - }, - - /** - *

Dealloc the map that contains the tile position from memory.
- * Unless you want to know at runtime the tiles positions, you can safely call this method.
- * If you are going to call layer.getTileGIDAt() then, don't release the map

- */ - releaseMap:function () { - if (this.tiles) - this.tiles = null; - - if (this._atlasIndexArray) - this._atlasIndexArray = null; - }, - - /** - *

Returns the tile (_ccsg.Sprite) at a given a tile coordinate.
- * The returned _ccsg.Sprite will be already added to the _ccsg.TMXLayer. Don't add it again.
- * The _ccsg.Sprite can be treated like any other _ccsg.Sprite: rotated, scaled, translated, opacity, color, etc.
- * You can remove either by calling:
- * - layer.removeChild(sprite, cleanup);
- * - or layer.removeTileAt(ccp(x,y));

- * @param {Vec2|Number} pos or x - * @param {Number} [y] - * @return {_ccsg.Sprite} - */ - getTileAt: function (pos, y) { - if(!pos) - throw new Error("_ccsg.TMXLayer.getTileAt(): pos should be non-null"); - if(y !== undefined) - pos = cc.p(pos, y); - if(pos.x >= this._layerSize.width || pos.y >= this._layerSize.height || pos.x < 0 || pos.y < 0) - throw new Error("_ccsg.TMXLayer.getTileAt(): invalid position"); - if(!this.tiles || !this._atlasIndexArray){ - cc.log("_ccsg.TMXLayer.getTileAt(): TMXLayer: the tiles map has been released"); - return null; - } - - var tile = null, gid = this.getTileGIDAt(pos); - - // if GID == 0, then no tile is present - if (gid === 0) - return tile; - - var z = 0 | (pos.x + pos.y * this._layerSize.width); - tile = this.getChildByTag(z); - // tile not created yet. create it - if (!tile) { - var rect = this.tileset.rectForGID(gid); - - tile = new _ccsg.Sprite(); - tile.initWithTexture(this.texture, rect); - tile.batchNode = this; - tile.setPosition(this.getPositionAt(pos)); - tile.vertexZ = this._vertexZForPos(pos); - tile.anchorX = 0; - tile.anchorY = 0; - tile.opacity = this._opacity; - - var indexForZ = this._atlasIndexForExistantZ(z); - this.addSpriteWithoutQuad(tile, indexForZ, z); - } - return tile; - }, - - /** - * Returns the tile gid at a given tile coordinate.
- * if it returns 0, it means that the tile is empty.
- * This method requires the the tile map has not been previously released (eg. don't call layer.releaseMap())
- * @param {cc.Vec2|Number} pos or x - * @param {Number} [y] - * @return {Number} - */ - getTileGIDAt:function (pos, y) { - if(pos == null) - throw new Error("_ccsg.TMXLayer.getTileGIDAt(): pos should be non-null"); - if(y !== undefined) - pos = cc.p(pos, y); - if(pos.x >= this._layerSize.width || pos.y >= this._layerSize.height || pos.x < 0 || pos.y < 0) - throw new Error("_ccsg.TMXLayer.getTileGIDAt(): invalid position"); - if(!this.tiles || !this._atlasIndexArray){ - cc.log("_ccsg.TMXLayer.getTileGIDAt(): TMXLayer: the tiles map has been released"); - return null; - } - - var idx = 0 | (pos.x + pos.y * this._layerSize.width); - // Bits on the far end of the 32-bit global tile ID are used for tile flags - var tile = this.tiles[idx]; - - return (tile & cc.TiledMap.TileFlag.FLIPPED_MASK) >>> 0; - }, - // XXX: deprecated - // tileGIDAt:getTileGIDAt, - - /** - * lipped tiles can be changed dynamically - * @param {cc.Vec2|Number} pos or x - * @param {Number} [y] - * @return {Number} - */ - getTileFlagsAt:function (pos, y) { - if(!pos) - throw new Error("_ccsg.TMXLayer.getTileFlagsAt(): pos should be non-null"); - if(y !== undefined) - pos = cc.p(pos, y); - if(pos.x >= this._layerSize.width || pos.y >= this._layerSize.height || pos.x < 0 || pos.y < 0) - throw new Error("_ccsg.TMXLayer.getTileFlagsAt(): invalid position"); - if(!this.tiles || !this._atlasIndexArray){ - cc.log("_ccsg.TMXLayer.getTileFlagsAt(): TMXLayer: the tiles map has been released"); - return null; - } - - var idx = 0 | (pos.x + pos.y * this._layerSize.width); - // Bits on the far end of the 32-bit global tile ID are used for tile flags - var tile = this.tiles[idx]; - - return (tile & cc.TiledMap.TileFlag.FLIPPED_ALL) >>> 0; - }, - // XXX: deprecated - // tileFlagAt:getTileFlagsAt, - - /** - *

Sets the tile gid (gid = tile global id) at a given tile coordinate.
- * The Tile GID can be obtained by using the method "tileGIDAt" or by using the TMX editor . Tileset Mgr +1.
- * If a tile is already placed at that position, then it will be removed.

- * @param {Number} gid - * @param {cc.Vec2|Number} posOrX position or x - * @param {Number} flagsOrY flags or y - * @param {Number} [flags] - */ - setTileGID: function(gid, posOrX, flagsOrY, flags) { - if(!posOrX) - throw new Error("_ccsg.TMXLayer.setTileGID(): pos should be non-null"); - var pos; - if (flags !== undefined) { - pos = cc.p(posOrX, flagsOrY); - } else { - pos = posOrX; - flags = flagsOrY; - } - if(pos.x >= this._layerSize.width || pos.y >= this._layerSize.height || pos.x < 0 || pos.y < 0) - throw new Error("_ccsg.TMXLayer.setTileGID(): invalid position"); - if(!this.tiles || !this._atlasIndexArray){ - cc.log("_ccsg.TMXLayer.setTileGID(): TMXLayer: the tiles map has been released"); - return; - } - if(gid !== 0 && gid < this.tileset.firstGid){ - cc.log( "_ccsg.TMXLayer.setTileGID(): invalid gid:" + gid); - return; - } - - flags = flags || 0; - this._setNodeDirtyForCache(); - var currentFlags = this.getTileFlagsAt(pos); - var currentGID = this.getTileGIDAt(pos); - - if (currentGID !== gid || currentFlags !== flags) { - var gidAndFlags = (gid | flags) >>> 0; - // setting gid=0 is equal to remove the tile - if (gid === 0) - this.removeTileAt(pos); - else if (currentGID === 0) // empty tile. create a new one - this._insertTileForGID(gidAndFlags, pos); - else { // modifying an existing tile with a non-empty tile - var z = pos.x + pos.y * this._layerSize.width; - var sprite = this.getChildByTag(z); - if (sprite) { - var rect = this.tileset.rectForGID(gid); - - sprite.setTextureRect(rect, false); - if (flags != null) - this._setupTileSprite(sprite, pos, gidAndFlags); - - this.tiles[z] = gidAndFlags; - } else - this._updateTileForGID(gidAndFlags, pos); - } - } - }, - - /** - * Removes a tile at given tile coordinate - * @param {cc.Vec2|Number} pos position or x - * @param {Number} [y] - */ - removeTileAt:function (pos, y) { - if(!pos) - throw new Error("_ccsg.TMXLayer.removeTileAt(): pos should be non-null"); - if(y !== undefined) - pos = cc.p(pos, y); - if(pos.x >= this._layerSize.width || pos.y >= this._layerSize.height || pos.x < 0 || pos.y < 0) - throw new Error("_ccsg.TMXLayer.removeTileAt(): invalid position"); - if(!this.tiles || !this._atlasIndexArray){ - cc.log("_ccsg.TMXLayer.removeTileAt(): TMXLayer: the tiles map has been released"); - return; - } - - var gid = this.getTileGIDAt(pos); - if (gid !== 0) { - if (cc._renderType === cc.game.RENDER_TYPE_CANVAS) - this._setNodeDirtyForCache(); - var z = 0 | (pos.x + pos.y * this._layerSize.width); - var atlasIndex = this._atlasIndexForExistantZ(z); - // remove tile from GID map - this.tiles[z] = 0; - - // remove tile from atlas position array - this._atlasIndexArray.splice(atlasIndex, 1); - - // remove it from sprites and/or texture atlas - var sprite = this.getChildByTag(z); - - if (sprite) - cc.SpriteBatchNode.prototype.removeChild.call(this, sprite, true); //this.removeChild(sprite, true); - else { - if(cc._renderType === cc.game.RENDER_TYPE_WEBGL) - this.textureAtlas.removeQuadAtIndex(atlasIndex); - - // update possible children - if (this._children) { - var locChildren = this._children; - for (var i = 0, len = locChildren.length; i < len; i++) { - var child = locChildren[i]; - if (child) { - var ai = child.atlasIndex; - if (ai >= atlasIndex) - child.atlasIndex = ai - 1; - } - } - } - } - } - }, - - /** - * Returns the position in pixels of a given tile coordinate - * @param {cc.Vec2|Number} pos position or x - * @param {Number} [y] - * @return {cc.Vec2} - */ - getPositionAt:function (pos, y) { - if (y !== undefined) - pos = cc.p(pos, y); - var ret = cc.p(0,0); - switch (this.layerOrientation) { - case cc.TiledMap.Orientation.ORTHO: - ret = this._positionForOrthoAt(pos); - break; - case cc.TiledMap.Orientation.ISO: - ret = this._positionForIsoAt(pos); - break; - case cc.TiledMap.Orientation.HEX: - ret = this._positionForHexAt(pos); - break; - } - return ret; - }, - // XXX: Deprecated. For backward compatibility only - // positionAt:getPositionAt, - /** * Return the value for the specific property name * @param {String} propertyName @@ -564,75 +352,6 @@ _ccsg.TMXLayer = cc.SpriteBatchNode.extend(/** @lends _ccsg.TMXLayer# */{ return this.properties[propertyName]; }, - /** - * Creates the tiles - */ - setupTiles:function () { - // Optimization: quick hack that sets the image size on the tileset - this._renderCmd.initImageSize(); - - // Parse cocos2d properties - this._parseInternalProperties(); - if (cc._renderType === cc.game.RENDER_TYPE_CANVAS) - this._setNodeDirtyForCache(); - - var locLayerHeight = this._layerSize.height, locLayerWidth = this._layerSize.width; - for (var y = 0; y < locLayerHeight; y++) { - for (var x = 0; x < locLayerWidth; x++) { - var pos = x + locLayerWidth * y; - var gid = this.tiles[pos]; - - // XXX: gid == 0 -. empty tile - if (gid !== 0) { - this._appendTileForGID(gid, cc.p(x, y)); - // Optimization: update min and max GID rendered by the layer - this._minGID = Math.min(gid, this._minGID); - this._maxGID = Math.max(gid, this._maxGID); - } - } - } - - if (!((this._maxGID >= this.tileset.firstGid) && (this._minGID >= this.tileset.firstGid))) { - cc.log("cocos2d:TMX: Only 1 tileset per layer is supported"); - } - }, - - /** - * _ccsg.TMXLayer doesn't support adding a _ccsg.Sprite manually. - * @warning addChild(child); is not supported on _ccsg.TMXLayer. Instead of setTileGID. - * @param {_ccsg.Node} child - * @param {number} zOrder - * @param {number} tag - */ - addChild:function (child, zOrder, tag) { - cc.log("addChild: is not supported on _ccsg.TMXLayer. Instead use setTileGID or tileAt."); - }, - - /** - * Remove child - * @param {_ccsg.Sprite} sprite - * @param {Boolean} cleanup - */ - removeChild:function (sprite, cleanup) { - // allows removing nil objects - if (!sprite) - return; - - if(this._children.indexOf(sprite) === -1){ - cc.log("_ccsg.TMXLayer.removeChild(): Tile does not belong to TMXLayer"); - return; - } - - if (cc._renderType === cc.game.RENDER_TYPE_CANVAS) - this._setNodeDirtyForCache(); - var atlasIndex = sprite.atlasIndex; - var zz = this._atlasIndexArray[atlasIndex]; - this.tiles[zz] = 0; - this._atlasIndexArray.splice(atlasIndex, 1); - cc.SpriteBatchNode.prototype.removeChild.call(this, sprite, cleanup); - cc.renderer.childrenOrderDirty = true; - }, - /** * Gets the layer name * @return {String} @@ -649,6 +368,273 @@ _ccsg.TMXLayer = cc.SpriteBatchNode.extend(/** @lends _ccsg.TMXLayer# */{ this.layerName = layerName; }, + /** + *

Dealloc the map that contains the tile position from memory.
+ * Unless you want to know at runtime the tiles positions, you can safely call this method.
+ * If you are going to call layer.getTileGIDAt() then, don't release the map

+ */ + releaseMap:function () { + this._spriteTiles = {}; + }, + + /** + *

Returns the tile (_ccsg.Sprite) at a given a tile coordinate.
+ * The returned _ccsg.Sprite will be already added to the _ccsg.TMXLayer. Don't add it again.
+ * The _ccsg.Sprite can be treated like any other _ccsg.Sprite: rotated, scaled, translated, opacity, color, etc.
+ * You can remove either by calling:
+ * - layer.removeChild(sprite, cleanup);
+ * - or layer.removeTileAt(ccp(x,y));

+ * @param {Vec2|Number} pos or x + * @param {Number} [y] + * @return {_ccsg.Sprite} + */ + getTileAt: function (pos, y) { + if (pos === undefined) { + throw new Error("_ccsg.TMXLayer.getTileAt(): pos should be non-null"); + } + var x = pos; + if (y === undefined) { + x = pos.x; + y = pos.y; + } + if (x >= this._layerSize.width || y >= this._layerSize.height || x < 0 || y < 0) { + throw new Error("_ccsg.TMXLayer.getTileAt(): invalid position"); + } + if (!this.tiles) { + cc.log("_ccsg.TMXLayer.getTileAt(): TMXLayer: the tiles map has been released"); + return null; + } + + var tile = null, gid = this.getTileGIDAt(x, y); + + // if GID == 0, then no tile is present + if (gid === 0) { + return tile; + } + + var z = Math.floor(pos.x) + Math.floor(pos.y) * this._layerSize.width; + tile = this._spriteTiles[z]; + // tile not created yet. create it + if (!tile) { + var rect = this._texGrids[gid]; + var tex = this._textures[rect.texId]; + + tile = new _ccsg.Sprite(tex, rect); + tile.setPosition(this.getPositionAt(x, y)); + var vertexZ = this._vertexZForPos(x, y); + tile.setVertexZ(vertexZ); + tile.setAnchorPoint(0, 0); + tile.setOpacity(this._opacity); + this.addChild(tile, vertexZ, z); + } + return tile; + }, + + /** + * Returns the tile gid at a given tile coordinate.
+ * if it returns 0, it means that the tile is empty.
+ * This method requires the the tile map has not been previously released (eg. don't call layer.releaseMap())
+ * @param {cc.Vec2|Number} pos or x + * @param {Number} [y] + * @return {Number} + */ + getTileGIDAt:function (pos, y) { + if (pos === undefined) { + throw new Error("_ccsg.TMXLayer.getTileGIDAt(): pos should be non-null"); + } + var x = pos; + if (y === undefined) { + x = pos.x; + y = pos.y; + } + if (x >= this._layerSize.width || y >= this._layerSize.height || x < 0 || y < 0) { + throw new Error("_ccsg.TMXLayer.getTileGIDAt(): invalid position"); + } + if (!this.tiles) { + cc.log("_ccsg.TMXLayer.getTileGIDAt(): TMXLayer: the tiles map has been released"); + return null; + } + + var idx = Math.floor(pos.x) + Math.floor(pos.y) * this._layerSize.width; + // Bits on the far end of the 32-bit global tile ID are used for tile flags + var tile = this.tiles[idx]; + + return (tile & cc.TiledMap.TileFlag.FLIPPED_MASK) >>> 0; + }, + // XXX: deprecated + // tileGIDAt:getTileGIDAt, + + /** + *

Sets the tile gid (gid = tile global id) at a given tile coordinate.
+ * The Tile GID can be obtained by using the method "tileGIDAt" or by using the TMX editor . Tileset Mgr +1.
+ * If a tile is already placed at that position, then it will be removed.

+ * @param {Number} gid + * @param {cc.Vec2|Number} posOrX position or x + * @param {Number} flagsOrY flags or y + * @param {Number} [flags] + */ + setTileGID: function(gid, posOrX, flagsOrY, flags) { + if (posOrX === undefined) { + throw new Error("_ccsg.TMXLayer.setTileGID(): pos should be non-null"); + } + var pos; + if (flags !== undefined) { + pos = cc.p(posOrX, flagsOrY); + } else { + pos = posOrX; + flags = flagsOrY; + } + + pos.x = Math.floor(pos.x); + pos.y = Math.floor(pos.y); + if(pos.x >= this._layerSize.width || pos.y >= this._layerSize.height || pos.x < 0 || pos.y < 0) { + throw new Error("_ccsg.TMXLayer.setTileGID(): invalid position"); + } + if (!this.tiles) { + cc.log("_ccsg.TMXLayer.setTileGID(): TMXLayer: the tiles map has been released"); + return; + } + if (gid !== 0 && gid < this.tileset.firstGid) { + cc.log( "_ccsg.TMXLayer.setTileGID(): invalid gid:" + gid); + return; + } + + flags = flags || 0; + var currentFlags = this.getTileFlagsAt(pos); + var currentGID = this.getTileGIDAt(pos); + + if (currentGID !== gid || currentFlags !== flags) { + var gidAndFlags = (gid | flags) >>> 0; + // setting gid=0 is equal to remove the tile + if (gid === 0) + this.removeTileAt(pos); + else if (currentGID === 0) // empty tile. create a new one + this._updateTileForGID(gidAndFlags, pos); + else { // modifying an existing tile with a non-empty tile + var z = pos.x + pos.y * this._layerSize.width; + var sprite = this.getChildByTag(z); + if (sprite) { + var rect = this._texGrids[gid]; + var tex = this._textures[rect.texId]; + sprite.setTexture(tex); + sprite.setTextureRect(rect, false); + if (flags != null) + this._setupTileSprite(sprite, pos, gidAndFlags); + + this.tiles[z] = gidAndFlags; + } else { + this._updateTileForGID(gidAndFlags, pos); + } + } + } + }, + + addChild: function (child, localZOrder, tag) { + _ccsg.Node.prototype.addChild.call(this, child, localZOrder, tag); + if (tag !== undefined) { + this._spriteTiles[tag] = child; + child._vertexZ = this._vertexZ + cc.renderer.assignedZStep * tag / this.tiles.length; + // child._renderCmd._needDraw = false; + } + }, + + removeChild: function (child, cleanup) { + if (this._spriteTiles[child.tag]) { + this._spriteTiles[child.tag] = null; + // child._renderCmd._needDraw = true; + } + _ccsg.Node.prototype.removeChild.call(this, child, cleanup); + }, + + /** + * Flipped tiles can be changed dynamically + * @param {cc.Point|Number} pos or x + * @param {Number} [y] + * @return {Number} + */ + getTileFlagsAt:function (pos, y) { + if(!pos) + throw new Error("_ccsg.TMXLayer.getTileFlagsAt(): pos should be non-null"); + if(y !== undefined) + pos = cc.p(pos, y); + if(pos.x >= this._layerSize.width || pos.y >= this._layerSize.height || pos.x < 0 || pos.y < 0) + throw new Error("_ccsg.TMXLayer.getTileFlagsAt(): invalid position"); + if(!this.tiles){ + cc.log("_ccsg.TMXLayer.getTileFlagsAt(): TMXLayer: the tiles map has been released"); + return null; + } + + var idx = Math.floor(pos.x) + Math.floor(pos.y) * this._layerSize.width; + // Bits on the far end of the 32-bit global tile ID are used for tile flags + var tile = this.tiles[idx]; + + return (tile & cc.TiledMap.TileFlag.FLIPPED_ALL) >>> 0; + }, + // XXX: deprecated + // tileFlagAt:getTileFlagsAt, + + /** + * Removes a tile at given tile coordinate + * @param {cc.Point|Number} pos position or x + * @param {Number} [y] + */ + removeTileAt:function (pos, y) { + if (!pos) { + throw new Error("_ccsg.TMXLayer.removeTileAt(): pos should be non-null"); + } + if (y !== undefined) { + pos = cc.p(pos, y); + } + if (pos.x >= this._layerSize.width || pos.y >= this._layerSize.height || pos.x < 0 || pos.y < 0) { + throw new Error("_ccsg.TMXLayer.removeTileAt(): invalid position"); + } + if (!this.tiles) { + cc.log("_ccsg.TMXLayer.removeTileAt(): TMXLayer: the tiles map has been released"); + return; + } + + var gid = this.getTileGIDAt(pos); + if (gid !== 0) { + var z = Math.floor(pos.x) + Math.floor(pos.y) * this._layerSize.width; + // remove tile from GID map + this.tiles[z] = 0; + + // remove it from sprites and/or texture atlas + var sprite = this._spriteTiles[z]; + if (sprite) { + this.removeChild(sprite, true); + } + } + }, + + /** + * Returns the position in pixels of a given tile coordinate + * @param {cc.Vec2|Number} pos position or x + * @param {Number} [y] + * @return {cc.Vec2} + */ + getPositionAt:function (pos, y) { + if (y !== undefined) + pos = cc.p(pos, y); + pos.x = Math.floor(pos.x); + pos.y = Math.floor(pos.y); + var ret = cc.p(0,0); + switch (this.layerOrientation) { + case cc.TiledMap.Orientation.ORTHO: + ret = this._positionForOrthoAt(pos); + break; + case cc.TiledMap.Orientation.ISO: + ret = this._positionForIsoAt(pos); + break; + case cc.TiledMap.Orientation.HEX: + ret = this._positionForHexAt(pos); + break; + } + return ret; + }, + // XXX: Deprecated. For backward compatibility only + // positionAt:getPositionAt, + _positionForIsoAt:function (pos) { return cc.p(this._mapTileSize.width / 2 * ( this._layerSize.width + pos.x - pos.y - 1), this._mapTileSize.height / 2 * (( this._layerSize.height * 2 - pos.x - pos.y) - 2)); @@ -683,74 +669,15 @@ _ccsg.TMXLayer = cc.SpriteBatchNode.extend(/** @lends _ccsg.TMXLayer# */{ return ret; }, - _appendTileForGID:function (gid, pos) { - var rect = this.tileset.rectForGID(gid); - - var z = 0 | (pos.x + pos.y * this._layerSize.width); - var tile = this._renderCmd._reusedTileWithRect(rect); - this._setupTileSprite(tile, pos, gid); - - // optimization: - // The difference between appendTileForGID and insertTileforGID is that append is faster, since - // it appends the tile at the end of the texture atlas - var indexForZ = this._atlasIndexArray.length; - - // don't add it using the "standard" way. - this.insertQuadFromSprite(tile, indexForZ); - - // append should be after addQuadFromSprite since it modifies the quantity values - this._atlasIndexArray.splice(indexForZ, 0, z); - return tile; - }, - - _insertTileForGID:function (gid, pos) { - var rect = this.tileset.rectForGID(gid); - - var z = 0 | (pos.x + pos.y * this._layerSize.width); - var tile = this._renderCmd._reusedTileWithRect(rect); - this._setupTileSprite(tile, pos, gid); - - // get atlas index - var indexForZ = this._atlasIndexForNewZ(z); - - // Optimization: add the quad without adding a child - this.insertQuadFromSprite(tile, indexForZ); - - // insert it into the local atlasindex array - this._atlasIndexArray.splice(indexForZ, 0, z); - // update possible children - if (this._children) { - var locChildren = this._children; - for (var i = 0, len = locChildren.length; i < len; i++) { - var child = locChildren[i]; - if (child) { - var ai = child.atlasIndex; - if (ai >= indexForZ) - child.atlasIndex = ai + 1; - } - } - } - this.tiles[z] = gid; - return tile; - }, - _updateTileForGID:function (gid, pos) { - var rect = this.tileset.rectForGID(gid); - var locScaleFactor = this._contentScaleFactor; - rect = cc.rect(rect.x / locScaleFactor, rect.y / locScaleFactor, - rect.width / locScaleFactor, rect.height / locScaleFactor); - var z = pos.x + pos.y * this._layerSize.width; + if (!this._texGrids[gid]) { + return; + } - var tile = this._renderCmd._reusedTileWithRect(rect); - this._setupTileSprite(tile, pos, gid); - - // get atlas index - tile.atlasIndex = this._atlasIndexForExistantZ(z); - tile.dirty = true; - tile.updateTransform(); - this.tiles[z] = gid; - - return tile; + var idx = 0 | (pos.x + pos.y * this._layerSize.width); + if (idx < this.tiles.length) { + this.tiles[idx] = gid; + } }, //The layer recognizes some special properties, like cc_vertez @@ -766,11 +693,10 @@ _ccsg.TMXLayer = cc.SpriteBatchNode.extend(/** @lends _ccsg.TMXLayer# */{ alphaFuncValue = parseFloat(alphaFuncVal); if (cc._renderType === cc.game.RENDER_TYPE_WEBGL) { //todo: need move to WebGL render cmd - this.shaderProgram = cc.shaderCache.programForKey(cc.macro.SHADER_POSITION_TEXTURECOLORALPHATEST); - var alphaValueLocation = cc._renderContext.getUniformLocation(this.shaderProgram.getProgram(), cc.macro.UNIFORM_ALPHA_TEST_VALUE_S); + this.shaderProgram = cc.shaderCache.programForKey(cc.macro.SHADER_SPRITE_POSITION_TEXTURECOLORALPHATEST); // NOTE: alpha test shader is hard-coded to use the equivalent of a glAlphaFunc(GL_GREATER) comparison this.shaderProgram.use(); - this.shaderProgram.setUniformLocationWith1f(alphaValueLocation, alphaFuncValue); + this.shaderProgram.setUniformLocationWith1f(cc.UNIFORM_ALPHA_TEST_VALUE_S, alphaFuncValue); } } else this._vertexZvalue = parseInt(vertexz, 10); @@ -778,43 +704,33 @@ _ccsg.TMXLayer = cc.SpriteBatchNode.extend(/** @lends _ccsg.TMXLayer# */{ }, _setupTileSprite:function (sprite, pos, gid) { - var z = pos.x + pos.y * this._layerSize.width; - sprite.setPosition(this.getPositionAt(pos)); - if (cc._renderType === cc.game.RENDER_TYPE_WEBGL) - sprite.vertexZ = this._vertexZForPos(pos); - else - sprite.tag = z; - - sprite.anchorX = 0; - sprite.anchorY = 0; - sprite.opacity = this._opacity; - if (cc._renderType === cc.game.RENDER_TYPE_WEBGL) { - sprite.rotation = 0.0; - } - + var posInPixel = this.getPositionAt(pos); + sprite.setPosition(posInPixel); + sprite.setVertexZ(this._vertexZForPos(pos)); + sprite.setAnchorPoint(0, 0); + sprite.setOpacity(this._opacity); sprite.setFlippedX(false); sprite.setFlippedY(false); + sprite.setRotation(0.0); // Rotation in tiled is achieved using 3 flipped states, flipping across the horizontal, vertical, and diagonal axes of the tiles. if ((gid & cc.TiledMap.TileFlag.DIAGONAL) >>> 0) { // put the anchor in the middle for ease of rotation. - sprite.anchorX = 0.5; - sprite.anchorY = 0.5; - sprite.x = this.getPositionAt(pos).x + sprite.width / 2; - sprite.y = this.getPositionAt(pos).y + sprite.height / 2; + sprite.setAnchorPoint(0.5, 0.5); + sprite.setPosition(posInPixel.x + sprite.width/2, posInPixel.y + sprite.height/2); var flag = (gid & (cc.TiledMap.TileFlag.HORIZONTAL | cc.TiledMap.TileFlag.VERTICAL) >>> 0) >>> 0; // handle the 4 diagonally flipped states. if (flag === cc.TiledMap.TileFlag.HORIZONTAL) - sprite.rotation = 90; + sprite.setRotation(90); else if (flag === cc.TiledMap.TileFlag.VERTICAL) - sprite.rotation = 270; + sprite.setRotation(270); else if (flag === (cc.TiledMap.TileFlag.VERTICAL | cc.TiledMap.TileFlag.HORIZONTAL) >>> 0) { - sprite.rotation = 90; - sprite.setFlippedX(true); + sprite.setRotation(90); + sprite.setFlippedX(true); } else { - sprite.rotation = 270; - sprite.setFlippedX(true); + sprite.setRotation(270); + sprite.setFlippedX(true); } } else { if ((gid & cc.TiledMap.TileFlag.HORIZONTAL) >>> 0) { @@ -827,17 +743,21 @@ _ccsg.TMXLayer = cc.SpriteBatchNode.extend(/** @lends _ccsg.TMXLayer# */{ } }, - _vertexZForPos:function (pos) { + _vertexZForPos:function (x, y) { + if (y === undefined) { + y = x.y; + x = x.x; + } var ret = 0; var maxVal = 0; if (this._useAutomaticVertexZ) { switch (this.layerOrientation) { case cc.TiledMap.Orientation.ISO: maxVal = this._layerSize.width + this._layerSize.height; - ret = -(maxVal - (pos.x + pos.y)); + ret = -(maxVal - (x + y)); break; case cc.TiledMap.Orientation.ORTHO: - ret = -(this._layerSize.height - pos.y); + ret = -(this._layerSize.height - y); break; case cc.TiledMap.Orientation.HEX: cc.log("TMX Hexa zOrder not supported"); @@ -846,65 +766,9 @@ _ccsg.TMXLayer = cc.SpriteBatchNode.extend(/** @lends _ccsg.TMXLayer# */{ cc.log("TMX invalid value"); break; } - } else + } else { ret = this._vertexZvalue; + } return ret; - }, - - _atlasIndexForExistantZ:function (z) { - var item; - if (this._atlasIndexArray) { - var locAtlasIndexArray = this._atlasIndexArray; - for (var i = 0, len = locAtlasIndexArray.length; i < len; i++) { - item = locAtlasIndexArray[i]; - if (item === z) - break; - } - } - if(!cc.js.isNumber(item)) - cc.log("_ccsg.TMXLayer._atlasIndexForExistantZ(): TMX atlas index not found. Shall not happen"); - return i; - }, - - _atlasIndexForNewZ:function (z) { - var locAtlasIndexArray = this._atlasIndexArray; - for (var i = 0, len = locAtlasIndexArray.length; i < len; i++) { - var val = locAtlasIndexArray[i]; - if (z < val) - break; - } - return i; } }); - -var _p = _ccsg.TMXLayer.prototype; - -/** @expose */ -cc.defineGetterSetter(_p, "texture", _p.getTexture, _p.setTexture); - -// Extended properties -/** @expose */ -_p.layerWidth; -cc.defineGetterSetter(_p, "layerWidth", _p._getLayerWidth, _p._setLayerWidth); -/** @expose */ -_p.layerHeight; -cc.defineGetterSetter(_p, "layerHeight", _p._getLayerHeight, _p._setLayerHeight); -/** @expose */ -_p.tileWidth; -cc.defineGetterSetter(_p, "tileWidth", _p._getTileWidth, _p._setTileWidth); -/** @expose */ -_p.tileHeight; -cc.defineGetterSetter(_p, "tileHeight", _p._getTileHeight, _p._setTileHeight); - - -/** - * Creates a _ccsg.TMXLayer with an tile set info, a layer info and a map info - * @deprecated since v3.0 please use new _ccsg.TMXLayer(tilesetInfo, layerInfo, mapInfo) instead. - * @param {cc.TMXTilesetInfo} tilesetInfo - * @param {cc.TMXLayerInfo} layerInfo - * @param {cc.TMXMapInfo} mapInfo - * @return {_ccsg.TMXLayer|Null} - */ -_ccsg.TMXLayer.create = function (tilesetInfo, layerInfo, mapInfo) { - return new _ccsg.TMXLayer(tilesetInfo, layerInfo, mapInfo); -}; diff --git a/cocos2d/tilemap/CCSGTMXTiledMap.js b/cocos2d/tilemap/CCSGTMXTiledMap.js index 54e03d28bc..1acf584f78 100644 --- a/cocos2d/tilemap/CCSGTMXTiledMap.js +++ b/cocos2d/tilemap/CCSGTMXTiledMap.js @@ -402,7 +402,6 @@ _ccsg.TMXTiledMap = _ccsg.Node.extend(/** @lends _ccsg.TMXTiledMap# */{ var layer = new _ccsg.TMXLayer(tileset, layerInfo, mapInfo); // tell the layerinfo to release the ownership of the tiles map. layerInfo.ownTiles = false; - layer.setupTiles(); return layer; }, diff --git a/cocos2d/tilemap/CCTMXLayerCanvasRenderCmd.js b/cocos2d/tilemap/CCTMXLayerCanvasRenderCmd.js index 27ff89195a..3e32e87d22 100644 --- a/cocos2d/tilemap/CCTMXLayerCanvasRenderCmd.js +++ b/cocos2d/tilemap/CCTMXLayerCanvasRenderCmd.js @@ -1,5 +1,5 @@ /**************************************************************************** - Copyright (c) 2013-2014 Chukong Technologies Inc. + Copyright (c) 2013-2016 Chukong Technologies Inc. http://www.cocos2d-x.org @@ -22,197 +22,244 @@ THE SOFTWARE. ****************************************************************************/ -_ccsg.TMXLayer.CanvasRenderCmd = function(renderable){ - cc.SpriteBatchNode.CanvasRenderCmd.call(this, renderable); - this._needDraw = true; - this._realWorldTransform = {a: 1, b: 0, c: 0, d: 1, tx: 0, ty: 0}; +var Orientation = null; +var TileFlag = null; +var FLIPPED_MASK = null; - var locCanvas = cc._canvas; - var tmpCanvas = document.createElement('canvas'); - tmpCanvas.width = locCanvas.width; - tmpCanvas.height = locCanvas.height; - this._cacheCanvas = tmpCanvas; - this._cacheContext = new cc.CanvasContextWrapper(this._cacheCanvas.getContext('2d')); - var tempTexture = new cc.Texture2D(); - tempTexture.initWithElement(tmpCanvas); - tempTexture.handleLoadedTexture(); - this._cacheTexture = tempTexture; - // This class uses cache, so its default cachedParent should be himself - this._cacheDirty = false; +_ccsg.TMXLayer.CanvasRenderCmd = function(renderable){ + _ccsg.Node.CanvasRenderCmd.call(this, renderable); + this._needDraw = true; + + if (!Orientation) { + Orientation = cc.TiledMap.Orientation; + TileFlag = cc.TiledMap.TileFlag; + FLIPPED_MASK = TileFlag.FLIPPED_MASK; + } }; -var proto = _ccsg.TMXLayer.CanvasRenderCmd.prototype = Object.create(cc.SpriteBatchNode.CanvasRenderCmd.prototype); +var proto = _ccsg.TMXLayer.CanvasRenderCmd.prototype = Object.create(_ccsg.Node.CanvasRenderCmd.prototype); proto.constructor = _ccsg.TMXLayer.CanvasRenderCmd; -//set the cache dirty flag for canvas -proto._setNodeDirtyForCache = function () { - this._cacheDirty = true; -}; - -proto._renderingChildToCache = function () { - if (this._cacheDirty) { - var wrapper = this._cacheContext, - context = wrapper.getContext(), locCanvas = this._cacheCanvas; - - //wrapper.save(); - context.setTransform(1, 0, 0, 1, 0, 0); - context.clearRect(0, 0, locCanvas.width, locCanvas.height); - //reset the cache context - - var locChildren = this._node._children; - for (var i = 0, len = locChildren.length; i < len; i++) { - if (locChildren[i]){ - var selCmd = locChildren[i]._renderCmd; - if(selCmd){ - selCmd.rendering(wrapper, 1, 1); - selCmd._cacheDirty = false; - } - } - } - - //wrapper.restore(); - this._cacheDirty = false; - } -}; - -proto.rendering = function (ctx, scaleX, scaleY) { - var alpha = this._displayedOpacity / 255; - if (alpha <= 0) - return; - - var node = this._node; - this._renderingChildToCache(); - var wrapper = ctx || cc._renderContext, context = wrapper.getContext(); - wrapper.setGlobalAlpha(alpha); - - var locCacheCanvas = this._cacheCanvas; - //direct draw image by canvas drawImage - if (locCacheCanvas && locCacheCanvas.width !== 0 && locCacheCanvas.height !== 0) { - wrapper.setTransform(this._realWorldTransform, scaleX, scaleY); - var locCanvasHeight = locCacheCanvas.height * scaleY; - if (node.layerOrientation === cc.TiledMap.Orientation.HEX) { - var halfTileSize = node._mapTileSize.height * 0.5 * scaleY; - context.drawImage(locCacheCanvas, 0, 0, locCacheCanvas.width, locCacheCanvas.height, - 0, -locCanvasHeight + halfTileSize, locCacheCanvas.width * scaleX, locCanvasHeight); - } else { - context.drawImage(locCacheCanvas, 0, 0, locCacheCanvas.width, locCacheCanvas.height, - 0, -locCanvasHeight, locCacheCanvas.width * scaleX, locCanvasHeight); - } - } - cc.g_NumberOfDraws++; -}; - -proto._updateCacheContext = function(size, height){ - var node = this._node, - locContentSize = node._contentSize, - locCanvas = this._cacheCanvas; - locCanvas.width = 0 | (locContentSize.width * 1.5); - locCanvas.height = 0 | (locContentSize.height * 1.5); - - //todo: need change the wrapper's height - if(node.layerOrientation === cc.TiledMap.Orientation.HEX) - this._cacheContext.setOffset(0, -node._mapTileSize.height * 0.5); //translate for hexagonal - else - this._cacheContext.setOffset(0, 0); - var locTexContentSize = this._cacheTexture._contentSize; - locTexContentSize.width = locCanvas.width; - locTexContentSize.height = locCanvas.height; -}; - -proto.getTexture = function(){ - return this._cacheTexture; -}; - -proto.visit = function(parentCmd){ - var node = this._node; - this._propagateFlagsDown(parentCmd); - //TODO: it will implement dynamic compute child cutting automation. - var i, len, locChildren = node._children; +proto.visit = function (parentCmd) { + var node = this._node, renderer = cc.renderer; // quick return if not visible - if (!node._visible || !locChildren || locChildren.length === 0) + if (!node._visible) return; parentCmd = parentCmd || this.getParentRenderCmd(); if (parentCmd) this._curLevel = parentCmd._curLevel + 1; - this._syncStatus(parentCmd); - if (this._cacheDirty) { - var wrapper = this._cacheContext, locCanvas = this._cacheCanvas, context = wrapper.getContext(), - instanceID = node.__instanceId, renderer = cc.renderer; - //begin cache - renderer._turnToCacheMode(instanceID); + if (isNaN(node._customZ)) { + node._vertexZ = renderer.assignedZ; + renderer.assignedZ += renderer.assignedZStep; + } + this._syncStatus(parentCmd); + + // Visit children + var children = node._children, child, cmd, + spTiles = node._spriteTiles, + i, len = children.length; + if (len > 0) { node.sortAllChildren(); - for (i = 0, len = locChildren.length; i < len; i++) { - if (locChildren[i]){ - var selCmd = locChildren[i]._renderCmd; - if(selCmd){ - selCmd.visit(this); - selCmd._cacheDirty = false; - } + // draw children zOrder < 0 + for (i = 0; i < len; i++) { + child = children[i]; + if (child._localZOrder < 0) { + cmd = child._renderCmd; + cmd.visit(this); + } + else { + break; } } - //wrapper.save(); - context.setTransform(1, 0, 0, 1, 0, 0); - context.clearRect(0, 0, locCanvas.width, locCanvas.height); - //set the wrapper's offset - - //draw to cache canvas - renderer._renderingToCacheCanvas(wrapper, instanceID); - //wrapper.restore(); //todo: it can be reserve. - this._cacheDirty = false + renderer.pushRenderCommand(this); + for (; i < len; i++) { + child = children[i]; + if (child._localZOrder === 0 && spTiles[child.tag]) { + if (isNaN(child._customZ)) { + child._vertexZ = renderer.assignedZ; + renderer.assignedZ += renderer.assignedZStep; + } + child._renderCmd.updateStatus(this, true); + continue; + } + child._renderCmd.visit(this); + } + } else { + renderer.pushRenderCommand(this); } - cc.renderer.pushRenderCommand(this); this._dirtyFlag = 0; }; -proto.transform = function (parentCmd, recursive) { - // transform for canvas - var t = this.getNodeToParentTransform(), - worldT = this._realWorldTransform; //get the world transform +proto.rendering = function (ctx, scaleX, scaleY) { + var node = this._node, hasRotation = (node._rotationX || node._rotationY), + layerOrientation = node.layerOrientation, + tiles = node.tiles, + alpha = node._opacity / 255; - if (parentCmd) { - var pt = parentCmd._worldTransform; - // cc.AffineTransformConcat is incorrect at get world transform - worldT.a = t.a * pt.a + t.b * pt.c; //a - worldT.b = t.a * pt.b + t.b * pt.d; //b - worldT.c = t.c * pt.a + t.d * pt.c; //c - worldT.d = t.c * pt.b + t.d * pt.d; //d - - worldT.tx = pt.a * t.tx + pt.c * t.ty + pt.tx; - worldT.ty = pt.d * t.ty + pt.ty + pt.b * t.tx; - } else { - worldT.a = t.a; - worldT.b = t.b; - worldT.c = t.c; - worldT.d = t.d; - worldT.tx = t.tx; - worldT.ty = t.ty; + if (!tiles || alpha <= 0) { + return; } - if (recursive) { - var locChildren = this._node._children; - if (!locChildren || locChildren.length === 0) - return; - var i, len; - for (i = 0, len = locChildren.length; i < len; i++) { - locChildren[i]._renderCmd.transform(this, recursive); + + var maptw = node._mapTileSize.width, + mapth = node._mapTileSize.height, + tilew = node.tileset._tileSize.width / cc.director._contentScaleFactor, + tileh = node.tileset._tileSize.height / cc.director._contentScaleFactor, + extw = tilew - maptw, + exth = tileh - mapth, + winw = cc.winSize.width, + winh = cc.winSize.height, + rows = node._layerSize.height, + cols = node._layerSize.width, + grids = node._texGrids, + spTiles = node._spriteTiles, + wt = this._worldTransform, + ox = node._position.x, + oy = node._position.y, + a = wt.a, b = wt.b, c = wt.c, d = wt.d, + mapx = ox * a + oy * c + wt.tx, + mapy = ox * b + oy * d + wt.ty; + + var wrapper = ctx || cc._renderContext, context = wrapper.getContext(); + + // Culling + var startCol = 0, startRow = 0, + maxCol = cols, maxRow = rows; + if (!hasRotation && layerOrientation === Orientation.ORTHO) { + startCol = Math.floor(-(mapx - extw * a) / (maptw * a)); + startRow = Math.floor((mapy - exth * d + mapth * rows * d - winh) / (mapth * d)); + maxCol = Math.ceil((winw - mapx + extw * a) / (maptw * a)); + maxRow = rows - Math.floor(-(mapy + exth * d) / (mapth * d)); + // Adjustment + if (startCol < 0) startCol = 0; + if (startRow < 0) startRow = 0; + if (maxCol > cols) maxCol = cols; + if (maxRow > rows) maxRow = rows; + } + + var i, row, col, colOffset = startRow * cols, z, + gid, grid, tex, cmd, + top, left, bottom, right, dw = tilew * scaleX, dh = tileh * scaleY, + w = tilew * a, h = tileh * d, gt, gl, gb, gr, + flippedX = false, flippedY = false; + + // Draw culled sprite tiles + z = colOffset + startCol; + for (i in spTiles) { + if (i < z && spTiles[i]) { + cmd = spTiles[i]._renderCmd; + if (spTiles[i]._localZOrder === 0 && !!cmd.rendering) { + cmd.rendering(ctx, scaleX, scaleY); + } + } + else if (i >= z) { + break; + } + } + + wrapper.setTransform(wt, scaleX, scaleY); + wrapper.setGlobalAlpha(alpha); + + for (row = startRow; row < maxRow; ++row) { + for (col = startCol; col < maxCol; ++col) { + z = colOffset + col; + // Skip sprite tiles + if (spTiles[z]) { + cmd = spTiles[z]._renderCmd; + if (spTiles[z]._localZOrder === 0 && !!cmd.rendering) { + cmd.rendering(ctx, scaleX, scaleY); + wrapper.setTransform(wt, scaleX, scaleY); + wrapper.setGlobalAlpha(alpha); + } + continue; + } + + gid = node.tiles[z]; + grid = grids[(gid & FLIPPED_MASK) >>> 0]; + if (!grid) { + continue; + } + tex = node._textures[grid.texId]; + if (!tex || !tex._htmlElementObj) { + continue; + } + + switch (layerOrientation) { + case Orientation.ORTHO: + left = col * maptw; + bottom = -(rows - row - 1) * mapth; + break; + case Orientation.ISO: + left = maptw / 2 * ( cols + col - row - 1); + bottom = -mapth / 2 * ( rows * 2 - col - row - 2); + break; + case Orientation.HEX: + left = col * maptw * 3 / 4; + bottom = -(rows - row - 1) * mapth + ((col % 2 === 1) ? (-mapth / 2) : 0); + break; + } + right = left + tilew; + top = bottom - tileh; + // TMX_ORIENTATION_ISO trim + if (!hasRotation && layerOrientation === Orientation.ISO) { + gb = -mapy + bottom*d; + if (gb < -winh-h) { + col += Math.floor((-winh - gb)*2/h) - 1; + continue; + } + gr = mapx + right*a; + if (gr < -w) { + col += Math.floor((-gr)*2/w) - 1; + continue; + } + gl = mapx + left*a; + gt = -mapy + top*d; + if (gl > winw || gt > 0) { + col = maxCol; + continue; + } + } + + // Rotation and Flip + if (gid > TileFlag.DIAGONAL) { + flippedX = (gid & TileFlag.HORIZONTAL) >>> 0; + flippedY = (gid & TileFlag.VERTICAL) >>> 0; + } + + if (flippedX) { + left = -right; + context.scale(-1, 1); + } + if (flippedY) { + top = -bottom; + context.scale(1, -1); + } + + context.drawImage(tex._htmlElementObj, + grid.x, grid.y, grid.width, grid.height, + left*scaleX, top*scaleY, dw, dh); + // Revert flip + if (flippedX) { + context.scale(-1, 1); + } + if (flippedY) { + context.scale(1, -1); + } + cc.g_NumberOfDraws++; + } + colOffset += cols; + } + + // Draw culled sprite tiles + for (i in spTiles) { + if (i > z && spTiles[i]) { + cmd = spTiles[i]._renderCmd; + if (spTiles[i]._localZOrder === 0 && !!cmd.rendering) { + cmd.rendering(ctx, scaleX, scaleY); + } } } }; - -proto.initImageSize = function(){ - var node = this._node; - node.tileset.imageSize = this._texture.getContentSizeInPixels(); -}; - -proto._reusedTileWithRect = function(rect){ - var node = this._node; - node._reusedTile = new _ccsg.Sprite(); - node._reusedTile.initWithTexture(this._texture, rect, false); - node._reusedTile.batchNode = node; - node._reusedTile.parent = node; - node._reusedTile._renderCmd._cachedParent = node._renderCmd; - return node._reusedTile; -}; \ No newline at end of file diff --git a/cocos2d/tilemap/CCTMXLayerWebGLRenderCmd.js b/cocos2d/tilemap/CCTMXLayerWebGLRenderCmd.js index ae1388bea7..83d1929077 100644 --- a/cocos2d/tilemap/CCTMXLayerWebGLRenderCmd.js +++ b/cocos2d/tilemap/CCTMXLayerWebGLRenderCmd.js @@ -1,5 +1,5 @@ /**************************************************************************** - Copyright (c) 2013-2014 Chukong Technologies Inc. + Copyright (c) 2013-2016 Chukong Technologies Inc. http://www.cocos2d-x.org @@ -22,44 +22,243 @@ THE SOFTWARE. ****************************************************************************/ +var Orientation = null; +var TileFlag = null; +var FLIPPED_MASK = null; + _ccsg.TMXLayer.WebGLRenderCmd = function(renderableObject){ - cc.SpriteBatchNode.WebGLRenderCmd.call(this, renderableObject); + _ccsg.Node.WebGLRenderCmd.call(this, renderableObject); this._needDraw = true; + this._vertices = [ + {x:0, y:0}, + {x:0, y:0}, + {x:0, y:0}, + {x:0, y:0} + ]; + this._color = new Uint32Array(1); + this._shaderProgram = cc.shaderCache.programForKey(cc.macro.SHADER_SPRITE_POSITION_TEXTURECOLORALPHATEST); + + var radian = Math.PI * 90 / 180; + this._sin90 = Math.sin(radian); + this._cos90 = Math.cos(radian); + radian = radian * 3; + this._sin270 = Math.sin(radian); + this._cos270 = Math.cos(radian); + + if (!Orientation) { + Orientation = cc.TiledMap.Orientation; + TileFlag = cc.TiledMap.TileFlag; + FLIPPED_MASK = TileFlag.FLIPPED_MASK; + } }; -var proto = _ccsg.TMXLayer.WebGLRenderCmd.prototype = Object.create(cc.SpriteBatchNode.WebGLRenderCmd.prototype); +var proto = _ccsg.TMXLayer.WebGLRenderCmd.prototype = Object.create(_ccsg.Node.WebGLRenderCmd.prototype); proto.constructor = _ccsg.TMXLayer.WebGLRenderCmd; -proto._updateCacheContext = function(){}; +proto.uploadData = function (f32buffer, ui32buffer, vertexDataOffset) { + var node = this._node, hasRotation = (node._rotationX || node._rotationY), + layerOrientation = node.layerOrientation, + tiles = node.tiles; -proto.initImageSize = function(){ - var node = this._node; - node.tileset.imageSize = this._textureAtlas.texture.getContentSizeInPixels(); - - // By default all the tiles are aliased - // pros: - // - easier to render - // cons: - // - difficult to scale / rotate / etc. - this._textureAtlas.texture.setAliasTexParameters(); -}; - -proto._reusedTileWithRect = function(rect){ - var node = this._node; - if (!node._reusedTile) { - node._reusedTile = new _ccsg.Sprite(); - node._reusedTile.initWithTexture(node.texture, rect, false); - node._reusedTile.batchNode = node; - } else { - // XXX HACK: Needed because if "batch node" is nil, - // then the Sprite'squad will be reset - node._reusedTile.batchNode = null; - - // Re-init the sprite - node._reusedTile.setTextureRect(rect, false); - - // restore the batch node - node._reusedTile.batchNode = node; + if (!tiles) { + return 0; } - return node._reusedTile; + + var maptw = node._mapTileSize.width, + mapth = node._mapTileSize.height, + tilew = node.tileset._tileSize.width / cc.director._contentScaleFactor, + tileh = node.tileset._tileSize.height / cc.director._contentScaleFactor, + extw = tilew - maptw, + exth = tileh - mapth, + winw = cc.winSize.width, + winh = cc.winSize.height, + rows = node._layerSize.height, + cols = node._layerSize.width, + grids = node._texGrids, + spTiles = node._spriteTiles, + wt = this._worldTransform, + a = wt.a, b = wt.b, c = wt.c, d = wt.d, tx = wt.tx, ty = wt.ty, + ox = node._position.x, + oy = node._position.y, + mapx = ox * a + oy * c + tx, + mapy = ox * b + oy * d + ty; + + var opacity = node._opacity, + cr = this._displayedColor.r, + cg = this._displayedColor.g, + cb = this._displayedColor.b; + if (node._opacityModifyRGB) { + var ca = opacity / 255; + cr *= ca; + cg *= ca; + cb *= ca; + } + this._color[0] = ((opacity<<24) | (cb<<16) | (cg<<8) | cr); + + // Culling + var startCol = 0, startRow = 0, + maxCol = cols, maxRow = rows; + if (!hasRotation && layerOrientation === Orientation.ORTHO) { + startCol = Math.floor(-(mapx - extw * a) / (maptw * a)); + startRow = Math.floor((mapy - exth * d + mapth * rows * d - winh) / (mapth * d)); + maxCol = Math.ceil((winw - mapx + extw * a) / (maptw * a)); + maxRow = rows - Math.floor(-(mapy + exth * d) / (mapth * d)); + // Adjustment + if (startCol < 0) startCol = 0; + if (startRow < 0) startRow = 0; + if (maxCol > cols) maxCol = cols; + if (maxRow > rows) maxRow = rows; + } + + var row, col, + offset = vertexDataOffset, + colOffset = startRow * cols, z, gid, grid, + i, top, left, bottom, right, + w = tilew * a, h = tileh * d, gt, gl, gb, gr, + wa = a, wb = b, wc = c, wd = d, wtx = tx, wty = ty, // world + flagged = false, flippedX = false, flippedY = false, + vertices = this._vertices; + for (row = startRow; row < maxRow; ++row) { + for (col = startCol; col < maxCol; ++col) { + // No more buffer + if (offset + 24 > f32buffer.length) { + cc.renderer._increaseBatchingSize((offset - vertexDataOffset) / 6, cc.renderer.VertexType.QUAD); + cc.renderer._batchRendering(); + vertexDataOffset = 0; + offset = 0; + } + + z = colOffset + col; + // Skip sprite tiles + if (spTiles[z]) { + continue; + } + + gid = node.tiles[z]; + grid = grids[(gid & FLIPPED_MASK) >>> 0]; + if (!grid) { + continue; + } + + // Vertices + switch (layerOrientation) { + case Orientation.ORTHO: + left = col * maptw; + bottom = (rows - row - 1) * mapth; + z = node._vertexZ + cc.renderer.assignedZStep * z / tiles.length; + break; + case Orientation.ISO: + left = maptw / 2 * ( cols + col - row - 1); + bottom = mapth / 2 * ( rows * 2 - col - row - 2); + z = node._vertexZ + cc.renderer.assignedZStep * (node.height - bottom) / node.height; + break; + case Orientation.HEX: + left = col * maptw * 3 / 4; + bottom = (rows - row - 1) * mapth + ((col % 2 === 1) ? (-mapth / 2) : 0); + z = node._vertexZ + cc.renderer.assignedZStep * (node.height - bottom) / node.height; + break; + } + right = left + tilew; + top = bottom + tileh; + // TMX_ORIENTATION_ISO trim + if (!hasRotation && layerOrientation === Orientation.ISO) { + gb = mapy + bottom*d; + if (gb > winh+h) { + col += Math.floor((gb-winh)*2/h) - 1; + continue; + } + gr = mapx + right*a; + if (gr < -w) { + col += Math.floor((-gr)*2/w) - 1; + continue; + } + gl = mapx + left*a; + gt = mapy + top*d; + if (gl > winw || gt < 0) { + col = maxCol; + continue; + } + } + // Rotation and Flip + if (gid > TileFlag.DIAGONAL) { + flagged = true; + flippedX = (gid & TileFlag.HORIZONTAL) >>> 0; + flippedY = (gid & TileFlag.VERTICAL) >>> 0; + // if ((gid & TileFlag.DIAGONAL) >>> 0) { + // var flag = (gid & (TileFlag.HORIZONTAL | TileFlag.VERTICAL) >>> 0) >>> 0; + // // handle the 4 diagonally flipped states. + // var la, lb, lc, ld; + // if (flag === TileFlag.HORIZONTAL || flag === (TileFlag.VERTICAL | TileFlag.HORIZONTAL) >>> 0) { + // lb = -(lc = this._sin90); + // la = ld = this._cos90; + // } + // else { + // lb = -(lc = this._sin270); + // la = ld = this._cos270; + // } + // left += grid.width * scalex / 2; + // bottom += grid.height * scaley / 2; + // wa = la * a + lb * c; + // wb = la * b + lb * d; + // wc = lc * a + ld * c; + // wd = lc * b + ld * d; + // wtx = a * left + c * bottom + tx; + // wty = d * bottom + ty + b * left; + // right = right - left; + // top = top - bottom; + // left = -right; + // bottom = -top; + // } + } + + vertices[0].x = left * wa + top * wc + wtx; // tl + vertices[0].y = left * wb + top * wd + wty; + vertices[1].x = left * wa + bottom * wc + wtx; // bl + vertices[1].y = left * wb + bottom * wd + wty; + vertices[2].x = right * wa + top * wc + wtx; // tr + vertices[2].y = right * wb + top * wd + wty; + vertices[3].x = right * wa + bottom * wc + wtx; // br + vertices[3].y = right * wb + bottom * wd + wty; + + for (i = 0; i < 4; ++i) { + f32buffer[offset] = vertices[i].x; + f32buffer[offset + 1] = vertices[i].y; + f32buffer[offset + 2] = z; + ui32buffer[offset + 3] = this._color[0]; + switch (i) { + case 0: // tl + f32buffer[offset + 4] = flippedX ? grid.r : grid.l; + f32buffer[offset + 5] = flippedY ? grid.b : grid.t; + break; + case 1: // bl + f32buffer[offset + 4] = flippedX ? grid.r : grid.l; + f32buffer[offset + 5] = flippedY ? grid.t : grid.b; + break; + case 2: // tr + f32buffer[offset + 4] = flippedX ? grid.l : grid.r; + f32buffer[offset + 5] = flippedY ? grid.b : grid.t; + break; + case 3: // br + f32buffer[offset + 4] = flippedX ? grid.l : grid.r; + f32buffer[offset + 5] = flippedY ? grid.t : grid.b; + break; + } + + offset += 6; + } + if (flagged) { + wa = a; + wb = b; + wc = c; + wd = d; + wtx = tx; + wty = ty; + flippedX = false; + flippedY = false; + flagged = false; + } + } + colOffset += cols; + } + return (offset - vertexDataOffset) / 6; }; diff --git a/cocos2d/tilemap/CCTMXXMLParser.js b/cocos2d/tilemap/CCTMXXMLParser.js index a8699d745a..600b9e86cd 100644 --- a/cocos2d/tilemap/CCTMXXMLParser.js +++ b/cocos2d/tilemap/CCTMXXMLParser.js @@ -146,13 +146,13 @@ cc.TMXTilesetInfo = cc._Class.extend(/** @lends cc.TMXTilesetInfo# */{ * @param {Number} gid * @return {cc.Rect} */ - rectForGID:function (gid) { - var rect = cc.rect(0, 0, 0, 0); + rectForGID:function (gid, result) { + var rect = result || cc.rect(0, 0, 0, 0); rect.width = this._tileSize.width; rect.height = this._tileSize.height; gid &= cc.TiledMap.TileFlag.FLIPPED_MASK; gid = gid - parseInt(this.firstGid, 10); - var max_x = parseInt((this.imageSize.width - this.margin + this.spacing) / (this._tileSize.width + this.spacing), 10); + var max_x = parseInt((this.imageSize.width - this.margin * 2 + this.spacing) / (this._tileSize.width + this.spacing), 10); rect.x = parseInt((gid % max_x) * (this._tileSize.width + this.spacing) + this.margin, 10); rect.y = parseInt(parseInt(gid / max_x, 10) * (this._tileSize.height + this.spacing) + this.margin, 10); return rect; @@ -628,30 +628,31 @@ cc.TMXMapInfo = cc.SAXParser.extend(/** @lends cc.TMXMapInfo# */{ cc.log("cc.TMXMapInfo.parseXMLFile(): unsupported compression method"); return null; } + var tiles; switch (compression) { case 'gzip': - layer._tiles = cc.Codec.unzipBase64AsArray(nodeValue, 4); + tiles = cc.Codec.unzipBase64AsArray(nodeValue, 4); break; case 'zlib': var inflator = new Zlib.Inflate(cc.Codec.Base64.decodeAsArray(nodeValue, 1)); - layer._tiles = uint8ArrayToUint32Array(inflator.decompress()); + tiles = uint8ArrayToUint32Array(inflator.decompress()); break; case null: case '': // Uncompressed if (encoding === "base64") - layer._tiles = cc.Codec.Base64.decodeAsArray(nodeValue, 4); + tiles = cc.Codec.Base64.decodeAsArray(nodeValue, 4); else if (encoding === "csv") { - layer._tiles = []; + tiles = []; var csvTiles = nodeValue.split(','); for (var csvIdx = 0; csvIdx < csvTiles.length; csvIdx++) - layer._tiles.push(parseInt(csvTiles[csvIdx])); + tiles.push(parseInt(csvTiles[csvIdx])); } else { //XML format var selDataTiles = data.getElementsByTagName("tile"); - layer._tiles = []; + tiles = []; for (var xmlIdx = 0; xmlIdx < selDataTiles.length; xmlIdx++) - layer._tiles.push(parseInt(selDataTiles[xmlIdx].getAttribute("gid"))); + tiles.push(parseInt(selDataTiles[xmlIdx].getAttribute("gid"))); } break; default: @@ -659,6 +660,9 @@ cc.TMXMapInfo = cc.SAXParser.extend(/** @lends cc.TMXMapInfo# */{ cc.log("cc.TMXMapInfo.parseXMLFile(): Only base64 and/or gzip/zlib maps are supported"); break; } + if (tiles) { + layer._tiles = new Uint32Array(tiles); + } // The parent element is the last layer var layerProps = selLayer.querySelectorAll("properties > property"); diff --git a/cocos2d/transitions/CCTransition.js b/cocos2d/transitions/CCTransition.js index c586437d66..992d1abb0f 100644 --- a/cocos2d/transitions/CCTransition.js +++ b/cocos2d/transitions/CCTransition.js @@ -217,8 +217,6 @@ cc.TransitionScene = _ccsg.Scene.extend(/** @lends cc.TransitionScene# */{ scale: 1.0, rotation: 0.0 }); - if(cc._renderType === cc.game.RENDER_TYPE_WEBGL) - this._inScene.getCamera().restore(); this._outScene.attr({ visible: false, @@ -227,8 +225,6 @@ cc.TransitionScene = _ccsg.Scene.extend(/** @lends cc.TransitionScene# */{ scale: 1.0, rotation: 0.0 }); - if(cc._renderType === cc.game.RENDER_TYPE_WEBGL) - this._outScene.getCamera().restore(); //[self schedule:@selector(setNewScene:) interval:0]; this.schedule(this._setNewScene, 0); @@ -903,476 +899,6 @@ cc.TransitionShrinkGrow.create = function (t, scene) { return new cc.TransitionShrinkGrow(t, scene); }; -/** - * Flips the screen horizontally.
- * The front face is the outgoing scene and the back face is the incoming scene. - * @class - * @extends cc.TransitionSceneOriented - * @param {Number} t time in seconds - * @param {_ccsg.Scene} scene - * @param {cc.TRANSITION_ORIENTATION_LEFT_OVER|cc.TRANSITION_ORIENTATION_RIGHT_OVER|cc.TRANSITION_ORIENTATION_UP_OVER|cc.TRANSITION_ORIENTATION_DOWN_OVER} o - * @example - * var trans = new cc.TransitionFlipX(t,scene,o); - */ -cc.TransitionFlipX = cc.TransitionSceneOriented.extend(/** @lends cc.TransitionFlipX# */{ - /** - * Constructor of TransitionFlipX - * @function - * @param {Number} t time in seconds - * @param {_ccsg.Scene} scene - * @param {cc.TRANSITION_ORIENTATION_LEFT_OVER|cc.TRANSITION_ORIENTATION_RIGHT_OVER|cc.TRANSITION_ORIENTATION_UP_OVER|cc.TRANSITION_ORIENTATION_DOWN_OVER} o - */ - ctor:function (t, scene, o) { - cc.TransitionSceneOriented.prototype.ctor.call(this); - if(o == null) - o = cc.TRANSITION_ORIENTATION_RIGHT_OVER; - scene && this.initWithDuration(t, scene, o); - }, - - /** - * custom on enter - */ - onEnter:function () { - cc.TransitionScene.prototype.onEnter.call(this); - - var inA, outA; - this._inScene.visible = false; - - var inDeltaZ, inAngleZ, outDeltaZ, outAngleZ; - - if (this._orientation === cc.TRANSITION_ORIENTATION_RIGHT_OVER) { - inDeltaZ = 90; - inAngleZ = 270; - outDeltaZ = 90; - outAngleZ = 0; - } else { - inDeltaZ = -90; - inAngleZ = 90; - outDeltaZ = -90; - outAngleZ = 0; - } - - inA = cc.sequence( - cc.delayTime(this._duration / 2), cc.show(), - cc.orbitCamera(this._duration / 2, 1, 0, inAngleZ, inDeltaZ, 0, 0), - cc.callFunc(this.finish, this) - ); - - outA = cc.sequence( - cc.orbitCamera(this._duration / 2, 1, 0, outAngleZ, outDeltaZ, 0, 0), - cc.hide(), cc.delayTime(this._duration / 2) - ); - - this._inScene.runAction(inA); - this._outScene.runAction(outA); - } -}); - -/** - * Flips the screen horizontally.
- * The front face is the outgoing scene and the back face is the incoming scene. - * @deprecated since v3.0,please use new cc.TransitionFlipX(t, scene,o) instead. - * @param {Number} t time in seconds - * @param {_ccsg.Scene} scene - * @param {cc.TRANSITION_ORIENTATION_LEFT_OVER|cc.TRANSITION_ORIENTATION_RIGHT_OVER|cc.TRANSITION_ORIENTATION_UP_OVER|cc.TRANSITION_ORIENTATION_DOWN_OVER} o - * @return {cc.TransitionFlipX} - */ -cc.TransitionFlipX.create = function (t, scene, o) { - return new cc.TransitionFlipX(t, scene, o); -}; - -/** - * Flips the screen vertically.
- * The front face is the outgoing scene and the back face is the incoming scene. - * @class - * @extends cc.TransitionSceneOriented - * @param {Number} t time in seconds - * @param {_ccsg.Scene} scene - * @param {cc.TRANSITION_ORIENTATION_LEFT_OVER|cc.TRANSITION_ORIENTATION_RIGHT_OVER|cc.TRANSITION_ORIENTATION_UP_OVER|cc.TRANSITION_ORIENTATION_DOWN_OVER} o - * @example - * var trans = new cc.TransitionFlipY(time,scene,0); - */ -cc.TransitionFlipY = cc.TransitionSceneOriented.extend(/** @lends cc.TransitionFlipY# */{ - - /** - * Constructor of TransitionFlipY - * @param {Number} t time in seconds - * @param {_ccsg.Scene} scene - * @param {cc.TRANSITION_ORIENTATION_LEFT_OVER|cc.TRANSITION_ORIENTATION_RIGHT_OVER|cc.TRANSITION_ORIENTATION_UP_OVER|cc.TRANSITION_ORIENTATION_DOWN_OVER} o - */ - ctor:function (t, scene, o) { - cc.TransitionSceneOriented.prototype.ctor.call(this); - if(o == null) - o = cc.TRANSITION_ORIENTATION_UP_OVER; - scene && this.initWithDuration(t, scene, o); - }, - /** - * custom on enter - */ - onEnter:function () { - cc.TransitionScene.prototype.onEnter.call(this); - - var inA, outA; - this._inScene.visible = false; - - var inDeltaZ, inAngleZ, outDeltaZ, outAngleZ; - - if (this._orientation === cc.TRANSITION_ORIENTATION_UP_OVER) { - inDeltaZ = 90; - inAngleZ = 270; - outDeltaZ = 90; - outAngleZ = 0; - } else { - inDeltaZ = -90; - inAngleZ = 90; - outDeltaZ = -90; - outAngleZ = 0; - } - - inA = cc.sequence( - cc.delayTime(this._duration / 2), cc.show(), - cc.orbitCamera(this._duration / 2, 1, 0, inAngleZ, inDeltaZ, 90, 0), - cc.callFunc(this.finish, this) - ); - outA = cc.sequence( - cc.orbitCamera(this._duration / 2, 1, 0, outAngleZ, outDeltaZ, 90, 0), - cc.hide(), cc.delayTime(this._duration / 2) - ); - - this._inScene.runAction(inA); - this._outScene.runAction(outA); - } -}); - -/** - * Flips the screen vertically.
- * The front face is the outgoing scene and the back face is the incoming scene. - * @deprecated since v3.0,please use new cc.TransitionFlipY(t, scene,o) instead. - * @param {Number} t time in seconds - * @param {_ccsg.Scene} scene - * @param {cc.TRANSITION_ORIENTATION_LEFT_OVER|cc.TRANSITION_ORIENTATION_RIGHT_OVER|cc.TRANSITION_ORIENTATION_UP_OVER|cc.TRANSITION_ORIENTATION_DOWN_OVER} o - * @return {cc.TransitionFlipY} - */ -cc.TransitionFlipY.create = function (t, scene, o) { - return new cc.TransitionFlipY(t, scene, o); -}; - -/** - * Flips the screen half horizontally and half vertically.
- * The front face is the outgoing scene and the back face is the incoming scene. - * @class - * @extends cc.TransitionSceneOriented - * @param {Number} t time in seconds - * @param {_ccsg.Scene} scene - * @param {cc.TRANSITION_ORIENTATION_LEFT_OVER|cc.TRANSITION_ORIENTATION_RIGHT_OVER|cc.TRANSITION_ORIENTATION_UP_OVER|cc.TRANSITION_ORIENTATION_DOWN_OVER} o - * @example - * var trans = cc.TransitionFlipAngular(time,scene,o); - */ -cc.TransitionFlipAngular = cc.TransitionSceneOriented.extend(/** @lends cc.TransitionFlipAngular# */{ - /** - * Constructor of TransitionFlipAngular - * @param {Number} t time in seconds - * @param {_ccsg.Scene} scene - * @param {cc.TRANSITION_ORIENTATION_LEFT_OVER|cc.TRANSITION_ORIENTATION_RIGHT_OVER|cc.TRANSITION_ORIENTATION_UP_OVER|cc.TRANSITION_ORIENTATION_DOWN_OVER} o - */ - ctor:function (t, scene, o) { - cc.TransitionSceneOriented.prototype.ctor.call(this); - if(o == null) - o = cc.TRANSITION_ORIENTATION_RIGHT_OVER; - scene && this.initWithDuration(t, scene, o); - }, - /** - * custom on enter - */ - onEnter:function () { - cc.TransitionScene.prototype.onEnter.call(this); - - var inA, outA; - this._inScene.visible = false; - - var inDeltaZ, inAngleZ, outDeltaZ, outAngleZ; - - if (this._orientation === cc.TRANSITION_ORIENTATION_RIGHT_OVER) { - inDeltaZ = 90; - inAngleZ = 270; - outDeltaZ = 90; - outAngleZ = 0; - } else { - inDeltaZ = -90; - inAngleZ = 90; - outDeltaZ = -90; - outAngleZ = 0; - } - - inA = cc.sequence( - cc.delayTime(this._duration / 2), cc.show(), - cc.orbitCamera(this._duration / 2, 1, 0, inAngleZ, inDeltaZ, -45, 0), - cc.callFunc(this.finish, this) - ); - outA = cc.sequence( - cc.orbitCamera(this._duration / 2, 1, 0, outAngleZ, outDeltaZ, 45, 0), - cc.hide(), cc.delayTime(this._duration / 2) - ); - - this._inScene.runAction(inA); - this._outScene.runAction(outA); - } -}); - -/** - * Flips the screen half horizontally and half vertically.
- * The front face is the outgoing scene and the back face is the incoming scene. - * @deprecated since v3.0,please use new new cc.TransitionFlipAngular(t, scene, o) instead - * @param {Number} t time in seconds - * @param {_ccsg.Scene} scene - * @param {cc.TRANSITION_ORIENTATION_LEFT_OVER|cc.TRANSITION_ORIENTATION_RIGHT_OVER|cc.TRANSITION_ORIENTATION_UP_OVER|cc.TRANSITION_ORIENTATION_DOWN_OVER} o - * @return {cc.TransitionFlipAngular} - */ -cc.TransitionFlipAngular.create = function (t, scene, o) { - return new cc.TransitionFlipAngular(t, scene, o); -}; - -/** - * Flips the screen horizontally doing a zoom out/in
- * The front face is the outgoing scene and the back face is the incoming scene. - * @class - * @extends cc.TransitionSceneOriented - * @param {Number} t time in seconds - * @param {_ccsg.Scene} scene - * @param {cc.TRANSITION_ORIENTATION_LEFT_OVER|cc.TRANSITION_ORIENTATION_RIGHT_OVER|cc.TRANSITION_ORIENTATION_UP_OVER|cc.TRANSITION_ORIENTATION_DOWN_OVER} o - * @example - * var trans = new cc.TransitionZoomFlipX(time,scene,o); - */ -cc.TransitionZoomFlipX = cc.TransitionSceneOriented.extend(/** @lends cc.TransitionZoomFlipX# */{ - - /** - * Constructor of TransitionZoomFlipX - * @param {Number} t time in seconds - * @param {_ccsg.Scene} scene - * @param {cc.TRANSITION_ORIENTATION_LEFT_OVER|cc.TRANSITION_ORIENTATION_RIGHT_OVER|cc.TRANSITION_ORIENTATION_UP_OVER|cc.TRANSITION_ORIENTATION_DOWN_OVER} o - */ - ctor:function (t, scene, o) { - cc.TransitionSceneOriented.prototype.ctor.call(this); - if(o == null) - o = cc.TRANSITION_ORIENTATION_RIGHT_OVER; - scene && this.initWithDuration(t, scene, o); - }, - /** - * custom on enter - */ - onEnter:function () { - cc.TransitionScene.prototype.onEnter.call(this); - - var inA, outA; - this._inScene.visible = false; - - var inDeltaZ, inAngleZ, outDeltaZ, outAngleZ; - - if (this._orientation === cc.TRANSITION_ORIENTATION_RIGHT_OVER) { - inDeltaZ = 90; - inAngleZ = 270; - outDeltaZ = 90; - outAngleZ = 0; - } else { - inDeltaZ = -90; - inAngleZ = 90; - outDeltaZ = -90; - outAngleZ = 0; - } - - inA = cc.sequence( - cc.delayTime(this._duration / 2), - cc.spawn( - cc.orbitCamera(this._duration / 2, 1, 0, inAngleZ, inDeltaZ, 0, 0), - cc.scaleTo(this._duration / 2, 1), cc.show()), - cc.callFunc(this.finish, this) - ); - outA = cc.sequence( - cc.spawn( - cc.orbitCamera(this._duration / 2, 1, 0, outAngleZ, outDeltaZ, 0, 0), - cc.scaleTo(this._duration / 2, 0.5)), - cc.hide(), - cc.delayTime(this._duration / 2) - ); - - this._inScene.scale = 0.5; - this._inScene.runAction(inA); - this._outScene.runAction(outA); - } -}); - -/** - * Flips the screen horizontally doing a zoom out/in
- * The front face is the outgoing scene and the back face is the incoming scene. - * @deprecated since v3.0,please use new new cc.TransitionZoomFlipX(t, scene, o) instead - * @param {Number} t time in seconds - * @param {_ccsg.Scene} scene - * @param {cc.TRANSITION_ORIENTATION_LEFT_OVER|cc.TRANSITION_ORIENTATION_RIGHT_OVER|cc.TRANSITION_ORIENTATION_UP_OVER|cc.TRANSITION_ORIENTATION_DOWN_OVER} o - * @return {cc.TransitionZoomFlipX} - */ -cc.TransitionZoomFlipX.create = function (t, scene, o) { - return new cc.TransitionZoomFlipX(t, scene, o); -}; - -/** - * Flips the screen vertically doing a little zooming out/in
- * The front face is the outgoing scene and the back face is the incoming scene. - * @class - * @extends cc.TransitionSceneOriented - * @param {Number} t time in seconds - * @param {_ccsg.Scene} scene - * @param {cc.TRANSITION_ORIENTATION_LEFT_OVER|cc.TRANSITION_ORIENTATION_RIGHT_OVER|cc.TRANSITION_ORIENTATION_UP_OVER|cc.TRANSITION_ORIENTATION_DOWN_OVER} o - * @example - * var trans = new cc.TransitionZoomFlipY(t,scene,o); - */ -cc.TransitionZoomFlipY = cc.TransitionSceneOriented.extend(/** @lends cc.TransitionZoomFlipY# */{ - - /** - * Constructor of TransitionZoomFlipY - * @param {Number} t time in seconds - * @param {_ccsg.Scene} scene - * @param {cc.TRANSITION_ORIENTATION_LEFT_OVER|cc.TRANSITION_ORIENTATION_RIGHT_OVER|cc.TRANSITION_ORIENTATION_UP_OVER|cc.TRANSITION_ORIENTATION_DOWN_OVER} o - */ - ctor:function (t, scene, o) { - cc.TransitionSceneOriented.prototype.ctor.call(this); - if(o == null) - o = cc.TRANSITION_ORIENTATION_UP_OVER; - scene && this.initWithDuration(t, scene, o); - }, - /** - * custom on enter - */ - onEnter:function () { - cc.TransitionScene.prototype.onEnter.call(this); - - var inA, outA; - this._inScene.visible = false; - - var inDeltaZ, inAngleZ, outDeltaZ, outAngleZ; - - if (this._orientation === cc.TRANSITION_ORIENTATION_UP_OVER) { - inDeltaZ = 90; - inAngleZ = 270; - outDeltaZ = 90; - outAngleZ = 0; - } else { - inDeltaZ = -90; - inAngleZ = 90; - outDeltaZ = -90; - outAngleZ = 0; - } - - inA = cc.sequence( - cc.delayTime(this._duration / 2), - cc.spawn( - cc.orbitCamera(this._duration / 2, 1, 0, inAngleZ, inDeltaZ, 90, 0), - cc.scaleTo(this._duration / 2, 1), cc.show()), - cc.callFunc(this.finish, this)); - - outA = cc.sequence( - cc.spawn( - cc.orbitCamera(this._duration / 2, 1, 0, outAngleZ, outDeltaZ, 90, 0), - cc.scaleTo(this._duration / 2, 0.5)), - cc.hide(), cc.delayTime(this._duration / 2)); - - this._inScene.scale = 0.5; - this._inScene.runAction(inA); - this._outScene.runAction(outA); - } -}); - -/** - * Flips the screen vertically doing a little zooming out/in
- * The front face is the outgoing scene and the back face is the incoming scene. - * @deprecated since v3.0,please use new new cc.TransitionZoomFlipY(t, scene, o) instead - * @param {Number} t time in seconds - * @param {_ccsg.Scene} scene - * @param {cc.TRANSITION_ORIENTATION_LEFT_OVER|cc.TRANSITION_ORIENTATION_RIGHT_OVER|cc.TRANSITION_ORIENTATION_UP_OVER|cc.TRANSITION_ORIENTATION_DOWN_OVER} o - * @return {cc.TransitionZoomFlipY} - */ -cc.TransitionZoomFlipY.create = function (t, scene, o) { - return new cc.TransitionZoomFlipY(t, scene, o); -}; - -/** - * Flips the screen half horizontally and half vertically doing a little zooming out/in.
- * The front face is the outgoing scene and the back face is the incoming scene. - * @class - * @extends cc.TransitionSceneOriented - * @param {Number} t time in seconds - * @param {_ccsg.Scene} scene - * @param {cc.TRANSITION_ORIENTATION_LEFT_OVER|cc.TRANSITION_ORIENTATION_RIGHT_OVER|cc.TRANSITION_ORIENTATION_UP_OVER|cc.TRANSITION_ORIENTATION_DOWN_OVER} o - * @example - * var trans = new cc.TransitionZoomFlipAngular(time,scene,o); - */ -cc.TransitionZoomFlipAngular = cc.TransitionSceneOriented.extend(/** @lends cc.TransitionZoomFlipAngular# */{ - - /** - * Constructor of TransitionZoomFlipAngular - * @param {Number} t time in seconds - * @param {_ccsg.Scene} scene - * @param {cc.TRANSITION_ORIENTATION_LEFT_OVER|cc.TRANSITION_ORIENTATION_RIGHT_OVER|cc.TRANSITION_ORIENTATION_UP_OVER|cc.TRANSITION_ORIENTATION_DOWN_OVER} o - */ - ctor:function (t, scene, o) { - cc.TransitionSceneOriented.prototype.ctor.call(this); - if(o == null) - o = cc.TRANSITION_ORIENTATION_RIGHT_OVER; - scene && this.initWithDuration(t, scene, o); - }, - /** - * custom on enter - */ - onEnter:function () { - cc.TransitionScene.prototype.onEnter.call(this); - - var inA, outA; - this._inScene.visible = false; - - var inDeltaZ, inAngleZ, outDeltaZ, outAngleZ; - if (this._orientation === cc.TRANSITION_ORIENTATION_RIGHT_OVER) { - inDeltaZ = 90; - inAngleZ = 270; - outDeltaZ = 90; - outAngleZ = 0; - } else { - inDeltaZ = -90; - inAngleZ = 90; - outDeltaZ = -90; - outAngleZ = 0; - } - - inA = cc.sequence( - cc.delayTime(this._duration / 2), - cc.spawn( - cc.orbitCamera(this._duration / 2, 1, 0, inAngleZ, inDeltaZ, -45, 0), - cc.scaleTo(this._duration / 2, 1), cc.show()), - cc.show(), - cc.callFunc(this.finish, this)); - outA = cc.sequence( - cc.spawn( - cc.orbitCamera(this._duration / 2, 1, 0, outAngleZ, outDeltaZ, 45, 0), - cc.scaleTo(this._duration / 2, 0.5)), - cc.hide(), cc.delayTime(this._duration / 2)); - - this._inScene.scale = 0.5; - this._inScene.runAction(inA); - this._outScene.runAction(outA); - } -}); - -/** - * Flips the screen half horizontally and half vertically doing a little zooming out/in.
- * The front face is the outgoing scene and the back face is the incoming scene. - * @deprecated since v3.0,please use new new cc.TransitionZoomFlipAngular(t, scene, o) instead - * @param {Number} t time in seconds - * @param {_ccsg.Scene} scene - * @param {cc.TRANSITION_ORIENTATION_LEFT_OVER|cc.TRANSITION_ORIENTATION_RIGHT_OVER|cc.TRANSITION_ORIENTATION_UP_OVER|cc.TRANSITION_ORIENTATION_DOWN_OVER} o - * @return {cc.TransitionZoomFlipAngular} - */ -cc.TransitionZoomFlipAngular.create = function (t, scene, o) { - return new cc.TransitionZoomFlipAngular(t, scene, o); -}; - /** * Fade out the outgoing scene and then fade in the incoming scene. * @class diff --git a/extensions/ccpool/CCNodePool.js b/extensions/ccpool/CCNodePool.js index 07258f7227..9c7e32d58b 100644 --- a/extensions/ccpool/CCNodePool.js +++ b/extensions/ccpool/CCNodePool.js @@ -55,7 +55,7 @@ * Constructor for creating a pool for a specific node template (usually a prefab). You can pass a component (type or name) argument for handling event for reusing and recycling node. * !#zh * 使用构造函数来创建一个节点专用的对象池,您可以传递一个组件类型或名称,用于处理节点回收和复用时的事件逻辑。 - * @param {Function|String} poolHandlerComp !#en The constructor or the class name of the component to control the unuse/reuse logic. !#zh 处理节点回收和复用事件逻辑的组件类型或名称。 + * @param {[Function|String]} poolHandlerComp !#en The constructor or the class name of the component to control the unuse/reuse logic. !#zh 处理节点回收和复用事件逻辑的组件类型或名称。 * @method NodePool * @example * properties: { @@ -119,7 +119,7 @@ cc.NodePool.prototype = { obj.removeFromParent(false); // Invoke pool handler - var handler = obj.getComponent(this.poolHandlerComp); + var handler = this.poolHandlerComp ? obj.getComponent(this.poolHandlerComp) : null; if (handler && handler.unuse) { handler.unuse(); } @@ -150,7 +150,7 @@ cc.NodePool.prototype = { this._pool.length = last; // Invoke pool handler - var handler = obj.getComponent(this.poolHandlerComp); + var handler = this.poolHandlerComp ? obj.getComponent(this.poolHandlerComp) : null; if (handler && handler.reuse) { handler.reuse.apply(handler, arguments); } diff --git a/extensions/ccui/base-classes/CCProtectedNodeCanvasRenderCmd.js b/extensions/ccui/base-classes/CCProtectedNodeCanvasRenderCmd.js index ca9831b742..b5c158786f 100644 --- a/extensions/ccui/base-classes/CCProtectedNodeCanvasRenderCmd.js +++ b/extensions/ccui/base-classes/CCProtectedNodeCanvasRenderCmd.js @@ -70,7 +70,7 @@ } } } - this._dirtyFlag = this._dirtyFlag & _ccsg.Node._dirtyFlags.colorDirty ^ this._dirtyFlag; + this._dirtyFlag &= ~_ccsg.Node._dirtyFlags.colorDirty; }, _updateDisplayOpacity: function (parentOpacity) { @@ -112,7 +112,7 @@ } } } - this._dirtyFlag = this._dirtyFlag & _ccsg.Node._dirtyFlags.opacityDirty ^ this._dirtyFlag; + this._dirtyFlag &= ~_ccsg.Node._dirtyFlags.opacityDirty; }, _changeProtectedChild: function (child) { diff --git a/extensions/ccui/uiwidgets/UIVideoPlayer.js b/extensions/ccui/uiwidgets/UIVideoPlayer.js index be21132e4b..b9463d6af6 100644 --- a/extensions/ccui/uiwidgets/UIVideoPlayer.js +++ b/extensions/ccui/uiwidgets/UIVideoPlayer.js @@ -380,7 +380,7 @@ ccui.VideoPlayer.EventType = { //update the transform this.transform(this.getParentRenderCmd(), true); this.updateMatrix(this._worldTransform, cc.view._scaleX, cc.view._scaleY); - this._dirtyFlag = this._dirtyFlag & _ccsg.Node._dirtyFlags.transformDirty ^ this._dirtyFlag; + this._dirtyFlag &= ~_ccsg.Node._dirtyFlags.transformDirty; } }; diff --git a/extensions/ccui/uiwidgets/UIWebView.js b/extensions/ccui/uiwidgets/UIWebView.js index 8ffc11d8ac..79aafb4dc7 100644 --- a/extensions/ccui/uiwidgets/UIWebView.js +++ b/extensions/ccui/uiwidgets/UIWebView.js @@ -280,7 +280,7 @@ ccui.WebView.EventType = { //update the transform this.transform(this.getParentRenderCmd(), true); this.updateMatrix(this._worldTransform, cc.view._scaleX, cc.view._scaleY); - this._dirtyFlag = this._dirtyFlag & _ccsg.Node._dirtyFlags.transformDirty ^ this._dirtyFlag; + this._dirtyFlag &= ~_ccsg.Node._dirtyFlags.transformDirty; } }; diff --git a/extensions/cocostudio/CCStudioComponent.js b/extensions/cocostudio/CCStudioComponent.js index 3c7bef88fc..46e59a3c06 100644 --- a/extensions/cocostudio/CCStudioComponent.js +++ b/extensions/cocostudio/CCStudioComponent.js @@ -30,7 +30,7 @@ var StudioComponent = cc.Class({ extends: cc.Component, editor: CC_EDITOR && { - inspector: 'unpack://engine/extensions/cocostudio/editor/studio-component.html' + inspector: 'unpack://engine/extensions/cocostudio/editor/studio-component.js' }, properties: CC_EDITOR && { diff --git a/extensions/cocostudio/editor/studio-component.js b/extensions/cocostudio/editor/studio-component.js new file mode 100644 index 0000000000..2a45c075b4 --- /dev/null +++ b/extensions/cocostudio/editor/studio-component.js @@ -0,0 +1,82 @@ +'use strict'; + +Vue.component('cc-studio-component', { + template: ` + + +
+ + + + + + + +
+ +
+ + + + + +
+ +
+ + + + + + + +
+ +
+ + + + + +
+ `, + + props: { + target: { + twoWay: true, + type: Object, + }, + }, + + methods: { + _isCheckbox() { + let type = this.target.type.value; + return type === cc.StudioComponent.ComponentType.CHECKBOX; + }, + + _isTextAtlas() { + let type = this.target.type.value; + return type === cc.StudioComponent.ComponentType.TEXT_ATLAS; + }, + + _isSliderBar() { + let type = this.target.type.value; + return type === cc.StudioComponent.ComponentType.SLIDER_BAR; + }, + + _isListView() { + let type = this.target.type.value; + return type === cc.StudioComponent.ComponentType.LIST_VIEW; + }, + + _isHList() { + let dir = this.target.listDirection.value; + return dir === cc.StudioComponent.ListDirection.HORIZONTAL; + }, + + _isVList() { + let dir = this.target.listDirection.value; + return dir === cc.StudioComponent.ListDirection.VERTICAL; + }, + } +}); diff --git a/extensions/spine/SGSkeleton.js b/extensions/spine/SGSkeleton.js index 09b2ecfaa1..386d7b4614 100644 --- a/extensions/spine/SGSkeleton.js +++ b/extensions/spine/SGSkeleton.js @@ -40,7 +40,6 @@ sp._SGSkeleton = _ccsg.Node.extend({ ctor: function(skeletonDataFile, atlasFile, scale) { _ccsg.Node.prototype.ctor.call(this); - this._blendFunc = {src: cc.macro.BLEND_SRC, dst: cc.macro.BLEND_DST}; if(arguments.length === 0) this.init(); @@ -57,9 +56,8 @@ sp._SGSkeleton = _ccsg.Node.extend({ init: function () { _ccsg.Node.prototype.init.call(this); - //this.setOpacityModifyRGB(true); - this._blendFunc.src = cc.macro.ONE; - this._blendFunc.dst = cc.macro.ONE_MINUS_SRC_ALPHA; + this._premultipliedAlpha = (cc._renderType === cc.game.RENDER_TYPE_WEBGL && cc.OPTIMIZE_BLEND_FUNC_FOR_PREMULTIPLIED_ALPHA); + this._blendFunc = {src: cc.BLEND_SRC, dst: cc.BLEND_DST}; this.scheduleUpdate(); }, @@ -259,15 +257,15 @@ sp._SGSkeleton = _ccsg.Node.extend({ * Sets the premultiplied alpha value to sp._SGSkeleton. * @param {Number} alpha */ - setOpacityModifyRGB: function (alpha) { - this._premultipliedAlpha = alpha; + setPremultipliedAlpha: function (premultiplied) { + this._premultipliedAlpha = premultiplied; }, /** * Returns whether to enable premultiplied alpha. * @returns {boolean} */ - isOpacityModifyRGB: function () { + isPremultipliedAlpha: function () { return this._premultipliedAlpha; }, @@ -281,6 +279,7 @@ sp._SGSkeleton = _ccsg.Node.extend({ this.setContentSize(skeletonData.width / cc.director.getContentScaleFactor(), skeletonData.height / cc.director.getContentScaleFactor()); this._skeleton = new spine.Skeleton(skeletonData); + this._skeleton.updateWorldTransform(); this._rootBone = this._skeleton.getRootBone(); this._ownsSkeletonData = ownsSkeletonData; diff --git a/extensions/spine/SGSkeletonCanvasRenderCmd.js b/extensions/spine/SGSkeletonCanvasRenderCmd.js index 0005c1eb81..c1bc03ab05 100644 --- a/extensions/spine/SGSkeletonCanvasRenderCmd.js +++ b/extensions/spine/SGSkeletonCanvasRenderCmd.js @@ -101,7 +101,7 @@ proto.updateStatus = function() { _ccsg.Node.CanvasRenderCmd.prototype.updateStatus.call(this); this._updateCurrentRegions(); this._regionFlag = _ccsg.Node.CanvasRenderCmd.RegionStatus.DirtyDouble; - this._dirtyFlag = this._dirtyFlag & _ccsg.Node._dirtyFlags.contentDirty ^ this._dirtyFlag; + this._dirtyFlag &= ~_ccsg.Node._dirtyFlags.contentDirty; }; proto.getLocalBB = function() { @@ -218,7 +218,7 @@ proto._updateChild = function(){ } //hack for sprite - selSprite._renderCmd._displayedOpacity = 0 | (locSkeleton.a * slot.a * 255); + selSprite._renderCmd._displayedOpacity = 0 | (this._node.getOpacity() * locSkeleton.a * slot.a); var r = 0 | (locSkeleton.r * slot.r * 255), g = 0 | (locSkeleton.g * slot.g * 255), b = 0 | (locSkeleton.b * slot.b * 255); selSprite.setColor(cc.color(r,g,b)); selSprite._renderCmd._updateColor(); diff --git a/extensions/spine/SGSkeletonWebGLRenderCmd.js b/extensions/spine/SGSkeletonWebGLRenderCmd.js index a35d775342..657806792c 100644 --- a/extensions/spine/SGSkeletonWebGLRenderCmd.js +++ b/extensions/spine/SGSkeletonWebGLRenderCmd.js @@ -28,8 +28,10 @@ var spine = sp.spine; sp._SGSkeleton.WebGLRenderCmd = function (renderableObject) { _ccsg.Node.WebGLRenderCmd.call(this, renderableObject); this._needDraw = true; - this.setShaderProgram(cc.shaderCache.programForKey(cc.macro.SHADER_POSITION_TEXTURECOLOR)); + this._matrix = new cc.math.Matrix4(); + this._matrix.identity(); this._tmpQuad = new cc.V3F_C4B_T2F_Quad(); + this.setShaderProgram(cc.shaderCache.programForKey(cc.macro.SHADER_POSITION_TEXTURECOLOR)); }; var proto = sp._SGSkeleton.WebGLRenderCmd.prototype = Object.create(_ccsg.Node.WebGLRenderCmd.prototype); @@ -44,9 +46,17 @@ proto.rendering = function (ctx) { var premultiAlpha = node._premultipliedAlpha; var blendMode = -1; + var wt = this._worldTransform, mat = this._matrix.mat; + mat[0] = wt.a; + mat[4] = wt.c; + mat[12] = wt.tx; + mat[1] = wt.b; + mat[5] = wt.d; + mat[13] = wt.ty; + this._shaderProgram.use(); - this._shaderProgram._setUniformForMVPMatrixWithMat4(this._stackMatrix); -// cc.gl.blendFunc(this._blendFunc.src, this._blendFunc.dst); + this._shaderProgram._setUniformForMVPMatrixWithMat4(this._matrix); +// cc.gl.blendFunc(locBlendFunc.src, locBlendFunc.dst); locSkeleton.r = color.r / 255; locSkeleton.g = color.g / 255; locSkeleton.b = color.b / 255; @@ -126,9 +136,9 @@ proto.rendering = function (ctx) { if (node._debugBones || node._debugSlots) { cc.math.glMatrixMode(cc.math.KM_GL_MODELVIEW); - //cc.math.glPushMatrixWitMat4(this._stackMatrix); + //cc.math.glPushMatrixWitMat4(this._matrix); cc.current_stack.stack.push(cc.current_stack.top); - cc.current_stack.top = this._stackMatrix; + cc.current_stack.top = this._matrix; var drawingUtil = cc._drawingUtil; if (node._debugSlots) { diff --git a/index.js b/index.js index 00f4dacb9f..82e68c17f4 100644 --- a/index.js +++ b/index.js @@ -30,7 +30,7 @@ eval( /* use EVAL to prevent the uglify from renaming symbols */ 'if(typeof CC_TEST=="undefined")' + - 'CC_TEST=typeof describe!="undefined"||typeof QUnit=="object";' + + 'CC_TEST=typeof tap=="object"||typeof QUnit=="object";' + 'if(typeof CC_EDITOR=="undefined")' + 'CC_EDITOR=typeof Editor=="object"&&typeof process=="object"&&"electron" in process.versions;' + 'if(typeof CC_DEV=="undefined")' + diff --git a/jsb/index.js b/jsb/index.js index 746cf71b2f..18f61b6f61 100644 --- a/jsb/index.js +++ b/jsb/index.js @@ -58,7 +58,9 @@ if (_engineNumberVersion) { cc.initEngine = function (config, cb) { require('script/jsb.js'); cc._renderType = cc.game.RENDER_TYPE_OPENGL; - cc._initDebugSetting(config[cc.game.CONFIG_KEY.debugMode]); + if (config) { + cc._initDebugSetting(config[cc.game.CONFIG_KEY.debugMode]); + } cc._engineLoaded = true; cc.log(cc.ENGINE_VERSION); if (cb) cb(); @@ -102,3 +104,7 @@ require('./jsb-enums'); require('./jsb-event'); require('./jsb-action'); require('./jsb-etc'); + +if (cc.runtime) { + require('./versions/jsb-polyfill-runtime'); +} diff --git a/jsb/jsb-director.js b/jsb/jsb-director.js index 77d379627b..691b65ef70 100644 --- a/jsb/jsb-director.js +++ b/jsb/jsb-director.js @@ -156,15 +156,17 @@ cc.js.mixin(cc.director, { if (scene instanceof cc.Scene) { this._scene = scene; sgScene = scene._sgNode; - - // Re-attach persist nodes + + // Re-attach or replace persist nodes for (id in persistNodes) { node = persistNodes[id]; var existNode = scene.getChildByUuid(id); - // Scene contains the persist node, should not reattach, should update the persist node if (existNode) { - persistNodes[id] = existNode; - existNode._persistNode = true; + // scene also contains the persist node, select the old one + var index = existNode.getSiblingIndex(); + existNode._destroyImmediate(); + node.parent = scene; + node.setSiblingIndex(index); } else { node.parent = scene; diff --git a/jsb/jsb-predefine.js b/jsb/jsb-predefine.js index ec612466af..9054b70568 100644 --- a/jsb/jsb-predefine.js +++ b/jsb/jsb-predefine.js @@ -24,9 +24,7 @@ ****************************************************************************/ // Run jsb.js before all polyfills -cc.initEngine({ - debugMode: cc.game.DEBUG_MODE_INFO -}); +cc.initEngine(); if (!cc.ClassManager) { cc.ClassManager = window.ClassManager || { @@ -56,3 +54,5 @@ require('../cocos2d/core/value-types'); require('../cocos2d/core/utils/find'); require('../cocos2d/core/event'); require('../CCDebugger'); + +cc._initDebugSetting(cc.game.DEBUG_MODE_INFO); diff --git a/jsb/versions/jsb-polyfill-runtime.js b/jsb/versions/jsb-polyfill-runtime.js new file mode 100644 index 0000000000..e5e175a68c --- /dev/null +++ b/jsb/versions/jsb-polyfill-runtime.js @@ -0,0 +1,169 @@ +/**************************************************************************** + Copyright (c) 2016 Chukong Technologies Inc. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Chukong Aipu reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +var _imageArray = []; + +function _addDownloadList (url,picName,suffix,option,cb) { + var item = { + info: { + url: url, + suffix:suffix, + picName:picName, + option: option + }, + cb: [cb] + }; + _imageArray.push(item); + return item; +} + +function _getDownloadItem (picName) { + for (var i = 0, l = _imageArray.length; i < l; i++) { + var item = _imageArray[i]; + if (item.info.picName === picName) { + return item; + } + } + return null; +} + +function _delDownloadList (picName) { + for (var i = 0, l = _imageArray.length; i < l; i++) { + var item = _imageArray[i]; + if (item.info.picName === picName) { + _imageArray.splice(i,1); + break; + } + } +} + +function loadImage (loadItem, callback) { + var url = loadItem.url; + + var cachedTex = cc.textureCache.getTextureForKey(url); + if (cachedTex) { + callback && callback(null, cachedTex); + } + else if (url.match(jsb.urlRegExp)) { + var picName; + var picSuffix = [".png", ".jpg", ".jpeg", ".gif", ".bmp"]; + var hasSuffix = false; + var suffix; + + for (var i = 0; i < picSuffix.length; i++) { + var item = picSuffix[i]; + if (url.indexOf(item) !== -1) { + hasSuffix = true; + suffix = item; + break; + } + } + var conf = loadItem.option; + if (conf) { + picName = cc.md5Encode(url + "cocos" + conf.width + "_" + conf.height); + } else { + cc.log("download default image"); + picName = cc.md5Encode(url); + } + cc.log("picName is " + picName); + var imageConfig = conf; + cachedTex = cc.textureCache._addImage(picName); + if (cachedTex instanceof cc.Texture2D) { + cc.log("loadImg find texture from cache"); + callback && callback(null, cachedTex); + } else { + var listItem = _getDownloadItem(picName); + if (listItem) { + cc.log("the same picture is downloading"); + listItem.cb.push(callback); + return; + } else { + listItem = _addDownloadList(url, picName, suffix, imageConfig, callback); + } + jsb.loadRemoteImg(JSON.stringify(listItem.info), function (configJsonText) { + var config = JSON.parse(configJsonText); + cc.log("callback from loadRemoteImg config is " + configJsonText); + var item = _getDownloadItem(config.picName); + if (!item && callback) { + callback(new Error("Load image failed: " + url), null); + return; + } + if (item.cb) { + for (var i = 0; i < item.cb.length; i++) { + cc.log("in callback list now i is " + i); + var texture = null; + var error = null; + if (config.isSuccess) { + cc.log("begin load texture picName is " + item.info.picName); + texture = cc.textureCache._addImage(item.info.picName); + if(!texture instanceof cc.Texture2D){ + texture = null; + error = new Error("add image fail: " + url); + } + } else { + error = new Error("download image fail" + url); + } + var cbItem = item.cb[i]; + if (cbItem) { + cbItem(error, texture); + } else { + cc.log("ERROR: callback is null"); + } + } + } + _delDownloadList(item); + }); + } + } + else { + cc.textureCache._addImageAsync(url, function (tex){ + if (tex instanceof cc.Texture2D) { + callback && callback(null, tex); + } + else { + callback && callback(new Error('Load image failed: ' + url)); + } + }); + } +} + +cc.loader.addLoadHandlers({ + // Images + 'png' : loadImage, + 'jpg' : loadImage, + 'bmp' : loadImage, + 'jpeg' : loadImage, + 'gif' : loadImage, + 'ico' : loadImage, + 'tiff' : loadImage, + 'webp' : loadImage, + 'image' : loadImage +}); + +cc.Follow.prototype._ctor = function (followedNode, rect) { + if(followedNode) + rect ? this.initWithTarget(followedNode, rect) + : this.initWithTarget(followedNode); +}; \ No newline at end of file diff --git a/test/qunit/lib/qunit-assert-callback.js b/test/qunit/lib/qunit-assert-callback.js index 2722e8ceae..e2374281d5 100644 --- a/test/qunit/lib/qunit-assert-callback.js +++ b/test/qunit/lib/qunit-assert-callback.js @@ -46,7 +46,7 @@ function Callback(callbackFunction_opt) { var wrapper = function () { if (!enabled) { - var message = callbackName_ + ' can be called only after enable()' + var message = callbackName_ + ' can be called only after enable()'; QUnit.push(false, message, message, msgWhenDisabled_); return; } diff --git a/test/qunit/unit/_init.js b/test/qunit/unit/_init.js index 5082668ad6..ee796dbef6 100644 --- a/test/qunit/unit/_init.js +++ b/test/qunit/unit/_init.js @@ -192,6 +192,7 @@ function _resetGame (w, h) { } cc.director.purgeDirector(); cc.loader.releaseAll(); + cc.director.runSceneImmediate(new cc.Scene()); //cc.director.pause(); } @@ -201,11 +202,15 @@ _resetGame(64, 64); var SetupEngine = { setup: function () { _resetGame(256, 512); - //// check error - //Engine._renderContext.checkMatchCurrentScene(true); }, teardown: function () { - //Engine._launchScene(new cc._Scene()); + // remove persist nodes + var persistNodeUuids = Object.keys(cc.game._persistRootNodes); + for (var i = 0; i < persistNodeUuids.length; i++) { + var uuid = persistNodeUuids[i]; + cc.game.removePersistRootNode(cc.game._persistRootNodes[uuid]); + } + cc.game.pause(); // check error cc._Test.SceneGraphUtils.checkMatchCurrentScene(); diff --git a/test/qunit/unit/test-attribute.js b/test/qunit/unit/test-attribute.js index b67e46796e..c1dedbe02b 100644 --- a/test/qunit/unit/test-attribute.js +++ b/test/qunit/unit/test-attribute.js @@ -11,59 +11,53 @@ test('base', function () { strictEqual(cc.Class.attr(MyCompBase, 'baseVal').data, 'waha', 'can get attribute'); - cc.Class.attr(MyCompBase, 'baseVal').foo = { bar: 524 }; - strictEqual(cc.Class.attr(MyCompBase, 'baseVal').foo.bar, 524, 'can assign directly'); - - var attr = cc.Class.attr(MyCompBase, 'baseVal', { + cc.Class.attr(MyCompBase, 'baseVal', { cool: 'nice' }); - ok(attr.data && attr.cool && attr.foo, 'can merge multi attribute'); + var attr = cc.Class.attr(MyCompBase, 'baseVal'); + ok(attr.data && attr.cool, 'can have multi attribute'); cc.Class.attr(MyCompBase, 'baseVal', { data: false }); + attr = cc.Class.attr(MyCompBase, 'baseVal'); strictEqual(attr.data, false, 'can change attribute'); - - // inherit - - var MyComp1 = function () { }; - cc.js.extend(MyComp1, MyCompBase); - var MyComp2 = function () { }; - cc.js.extend(MyComp2, MyCompBase); - - strictEqual(cc.Class.attr(MyComp1, 'baseVal').cool, 'nice', 'can get inherited attribute'); - cc.Class.attr(MyComp1, 'baseVal', {cool: 'good'}); - strictEqual(cc.Class.attr(MyComp1, 'baseVal').cool, 'good', 'can override inherited attribute'); - - // yes, current implement of attr is not based on real javascript prototype - strictEqual(cc.Class.attr(MyCompBase, 'baseVal').cool, 'good', 'Oh yes, sub prop of base class will be pulluted!'); - - cc.Class.attr(MyComp1, 'subVal', {}).cool = 'very nice'; - strictEqual(cc.Class.attr(MyComp1, 'subVal').cool, 'very nice', 'can have own attribute'); - - strictEqual(cc.Class.attr(MyCompBase, 'subVal'), undefined, 'main prop of base class not pulluted'); - strictEqual(cc.Class.attr(MyComp2, 'subVal'), undefined, 'sibling class not pulluted'); }); -test('not object type', function () { - var MyCompBase = function () {}; - cc.Class.attr(MyCompBase, 'subVal', false); - strictEqual(cc.Class.attr(MyCompBase, 'subVal'), false, 'attr should set to false'); - cc.Class.attr(MyCompBase, 'subVal', true); - strictEqual(cc.Class.attr(MyCompBase, 'subVal'), true, 'attr should set to true'); +test('inherit', function () { + function MyCompBase () { } + function MyComp1 () { } + cc.js.extend(MyComp1, MyCompBase); + function MyComp2 () { } + cc.js.extend(MyComp2, MyCompBase); + + cc.Class.attr(MyCompBase, 'baseVal', { + cool: 'nice' + }); + strictEqual(cc.Class.attr(MyComp1, 'baseVal').cool, 'nice', 'can get inherited attribute'); + + cc.Class.attr(MyComp1, 'baseVal', {cool: 'good'}); + strictEqual(cc.Class.attr(MyComp1, 'baseVal').cool, 'good', 'can override inherited attribute'); + strictEqual(cc.Class.attr(MyCompBase, 'baseVal').cool, 'nice', 'Sub prop of base class should not be pulluted!'); + + cc.Class.attr(MyComp1, 'subVal', { cool: 'very nice' }); + strictEqual(cc.Class.attr(MyComp1, 'subVal').cool, 'very nice', 'can have own attribute'); + + strictEqual(cc.Class.attr(MyCompBase, 'subVal').cool, undefined, 'main prop of base class not pulluted'); + strictEqual(cc.Class.attr(MyComp2, 'subVal').cool, undefined, 'sibling class not pulluted'); }); test('dynamic attribute for instance', function () { var MyCompBase = function () {}; var comp = new MyCompBase(); - cc.Class.attr(MyCompBase, 'subVal', false); - cc.Class.attr(comp, 'subVal', true); - strictEqual(cc.Class.attr(MyCompBase, 'subVal'), false, 'class attr should set to false'); - strictEqual(cc.Class.attr(comp, 'subVal'), true, 'instance attr should set to true'); + cc.Class.attr(MyCompBase, 'subVal', { value: false }); + cc.Class.attr(comp, 'subVal', { value: true }); + strictEqual(cc.Class.attr(MyCompBase, 'subVal').value, false, 'class attr should set to false'); + strictEqual(cc.Class.attr(comp, 'subVal').value, true, 'instance attr should set to true'); - cc.Class.attr(MyCompBase, 'baseVal', 123); - strictEqual(cc.Class.attr(comp, 'baseVal'), 123, 'instance attr should inherited from base'); + cc.Class.attr(MyCompBase, 'baseVal', { value: 123 }); + strictEqual(cc.Class.attr(comp, 'baseVal').value, 123, 'instance attr should inherited from base'); cc.Class.attr(MyCompBase, 'readonly', {a: false}); diff --git a/test/qunit/unit/test-class.js b/test/qunit/unit/test-class.js index 278cd28985..9966c10064 100644 --- a/test/qunit/unit/test-class.js +++ b/test/qunit/unit/test-class.js @@ -178,10 +178,9 @@ test('Inherit', function () { strictEqual(Dog.$super, Animal, 'can get super'); - strictEqual(cc.Class.attr(Animal, 'myName'), cc.Class.attr(Dog, 'myName'), - "inheritance chain shares the same property's attribute"); + strictEqual(cc.Class.attr(Animal, 'myName').tooltip, undefined, "override should not change attribute of super class"); strictEqual(cc.Class.attr(Dog, 'myName').tooltip, 'String', 'can modify attribute'); - strictEqual(cc.Class.attr(Dog, 'weight'), undefined, 'base property not added'); + strictEqual(cc.Class.attr(Dog, 'weight').default, undefined, 'base property not added'); var husky = new Husky(); var dog = new Dog(); diff --git a/test/qunit/unit/test-collider.js b/test/qunit/unit/test-collider.js index f1bd63c049..62c08d7791 100644 --- a/test/qunit/unit/test-collider.js +++ b/test/qunit/unit/test-collider.js @@ -6,8 +6,8 @@ test('collision manager', function() { manager.enabled = true; - cc.game.groupList = ['Default']; - cc.game.collisionMatrix = [[true]]; + cc.game.groupList = ['Default', 'Test']; + cc.game.collisionMatrix = [[true, false], [false, true]]; var node1 = new cc.Node(); cc.director.getScene().addChild(node1); @@ -30,6 +30,12 @@ test('collision manager', function() { strictEqual( manager._colliders.length, 4, 'collision manager should add 4 colliders'); strictEqual( manager._contacts.length, 4, 'collision manager should add 4 contacts'); + node1.group = 'Test'; + strictEqual( manager._contacts.length, 0, 'collision manager should add 0 contacts'); + + node2.group = 'Test'; + strictEqual( manager._contacts.length, 4, 'collision manager should add 0 contacts'); + box4.enabled = false; strictEqual( manager._colliders.length, 3, 'collision manager should add 3 colliders'); diff --git a/test/qunit/unit/test-load-scene.js b/test/qunit/unit/test-load-scene.js index 821dd44b9c..173305d6dd 100644 --- a/test/qunit/unit/test-load-scene.js +++ b/test/qunit/unit/test-load-scene.js @@ -71,6 +71,69 @@ test('persist node with dynamic scene', function () { ok(globalNode.parent === newScene, 'persist node should not be destoryed automatically when loading a new scene'); }); +test('persist node should replace existing node in scene', function () { + var oldNode = new cc.Node(); + oldNode.parent = cc.director.getScene(); + cc.game.addPersistRootNode(oldNode); + oldNode.setSiblingIndex(0); + + var newScene = new cc.Scene(); + newScene.addChild(new cc.Node()); + newScene.addChild(new cc.Node()); + var newNode = new cc.Node(); + newNode._id = oldNode.uuid; + newNode.parent = newScene; + newNode.setSiblingIndex(1); + + cc.director.runSceneImmediate(newScene); + + ok(oldNode.parent === newScene, 'persist node should add to new scene'); + strictEqual(oldNode.getSiblingIndex(), 1, 'persist node should restore sibling index'); + ok(newNode.parent === null, 'existing node should not in new scene'); + + cc.game.step(); // ensure sgNode sorted +}); + +test('lifecycle methods of persist node and replaced node', function () { + var oldNode = new cc.Node(); + var oldComp = oldNode.addComponent(cc.Component); + oldComp.onLoad = Callback().enable(); + oldComp.start = Callback().enable(); + oldComp.onDestroy = Callback().disable('should not call onDestroy'); + oldComp.onDisable = Callback().enable(); + oldComp.onEnable = Callback().enable(); + + oldNode.parent = cc.director.getScene(); + cc.game.addPersistRootNode(oldNode); + cc.game.step(); + oldComp.onLoad.disable('should not call onLoad again') + oldComp.start.disable('should not call start again'); + oldComp.onEnable.once(); + + var newScene = new cc.Scene(); + var newNode = new cc.Node(); + newNode._id = oldNode.uuid; + newNode.parent = newScene; + var newComp = newNode.addComponent(cc.Component); + newComp.onLoad = Callback().disable('should not call onLoad because its node is duplicated'); + newComp.start = Callback().disable('should not call start because its node is duplicated'); + newComp.onEnable = Callback().disable('should not call onEnable because its node is duplicated'); + newComp.onDisable = Callback().disable('should not call onDisable because its node is duplicated'); + newComp.onDestroy = Callback().disable('should not call onDestroy because its node is duplicated'); + newComp.update = Callback().disable('should not call update because its node is duplicated'); + + cc.director.runSceneImmediate(newScene); + + oldComp.onDisable.once('should call onDisable because parent changed'); + oldComp.onEnable.once('should call onEnable because parent changed'); + + cc.game.step(); + cc.game.step(); + + // end test + oldComp.onDestroy.enable(); +}); + (function () { if (!TestEditorExtends) { return; diff --git a/test/qunit/unit/test-object.js b/test/qunit/unit/test-object.js index 838688f5b3..41eb98719c 100644 --- a/test/qunit/unit/test-object.js +++ b/test/qunit/unit/test-object.js @@ -170,10 +170,10 @@ test('destruct', function () { CCObject.call(this); this.array = []; }; + cc.js.extend(Sub, CCObject); Sub.prototype.test_function = function () {return 342}; Sub.prototype.test_boolean = true; Sub.prototype.test_string = 'test string'; - cc.js.extend(Sub, CCObject); var inherited1 = new Sub(); inherited1.object_value = [1,2]; inherited1.function_value = {};