From 43c08b20420c95369c00e8b954fdf4966b494c4e Mon Sep 17 00:00:00 2001 From: Alexander Baranov Date: Sun, 2 Oct 2016 22:31:03 +0300 Subject: [PATCH 01/42] 'additionalTransform' correct processing --- cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js b/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js index 768998f8d2..fbb6f92330 100644 --- a/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js +++ b/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js @@ -194,6 +194,10 @@ cc.Node.RenderCmd.prototype = { } } + if (node._additionalTransformDirty) { + this._transform = t = cc.affineTransformConcat(t, node._additionalTransform); // seems like 'this._transform' can be removed + } + if (pt) { // cc.AffineTransformConcat is incorrect at get world transform wt.a = t.a * pt.a + t.b * pt.c; //a @@ -229,6 +233,10 @@ cc.Node.RenderCmd.prototype = { } } + if (node._additionalTransformDirty) { + this._transform = t = cc.affineTransformConcat(t, node._additionalTransform); + } + if (pt) { wt.a = t.a * pt.a + t.b * pt.c; wt.b = t.a * pt.b + t.b * pt.d; @@ -246,10 +254,6 @@ cc.Node.RenderCmd.prototype = { } } - if (node._additionalTransformDirty) { - this._transform = cc.affineTransformConcat(t, node._additionalTransform); - } - this._updateCurrentRegions && this._updateCurrentRegions(); this._notifyRegionStatus && this._notifyRegionStatus(cc.Node.CanvasRenderCmd.RegionStatus.DirtyDouble); From de5f52adace4bcedd3aeb10989d2ffb675c37bcb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alicia=20Boya=20Garc=C3=ADa?= Date: Wed, 9 Nov 2016 17:37:48 +0100 Subject: [PATCH 02/42] Honor device pixel ratio in CCLabelTTF.getContentSize() --- cocos2d/core/labelttf/CCLabelTTF.js | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/cocos2d/core/labelttf/CCLabelTTF.js b/cocos2d/core/labelttf/CCLabelTTF.js index 42803f2a2a..7bef98d374 100644 --- a/cocos2d/core/labelttf/CCLabelTTF.js +++ b/cocos2d/core/labelttf/CCLabelTTF.js @@ -806,7 +806,9 @@ cc.LabelTTF = cc.Sprite.extend(/** @lends cc.LabelTTF# */{ getContentSize: function () { if (this._needUpdateTexture) this._renderCmd._updateTTF(); - return cc.size(this._contentSize); + return cc.size( + this._contentSize.width / cc.view.getDevicePixelRatio(), + this._contentSize.height / cc.view.getDevicePixelRatio()); }, _getWidth: function () { From 946367a3cba63a11a0b81e50824f31efcd8a71d8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alicia=20Boya=20Garc=C3=ADa?= Date: Wed, 9 Nov 2016 17:40:05 +0100 Subject: [PATCH 03/42] Revert "Fix UIText issue and Label getContentSize value wrong in retina mode" This reverts commit 9b077f81353f82c2bdc45e4cb904e8705a4fb319. --- cocos2d/core/labelttf/CCLabelTTF.js | 6 +- .../labelttf/CCLabelTTFCanvasRenderCmd.js | 55 ++++++++++--------- extensions/ccui/uiwidgets/UIText.js | 2 +- 3 files changed, 32 insertions(+), 31 deletions(-) diff --git a/cocos2d/core/labelttf/CCLabelTTF.js b/cocos2d/core/labelttf/CCLabelTTF.js index 7bef98d374..fe4b712751 100644 --- a/cocos2d/core/labelttf/CCLabelTTF.js +++ b/cocos2d/core/labelttf/CCLabelTTF.js @@ -612,7 +612,7 @@ cc.LabelTTF = cc.Sprite.extend(/** @lends cc.LabelTTF# */{ setScale: function (scale, scaleY) { this._scaleX = scale / cc.view.getDevicePixelRatio(); this._scaleY = ((scaleY || scaleY === 0) ? scaleY : scale) / - cc.view.getDevicePixelRatio(); + cc.view.getDevicePixelRatio(); this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.transformDirty); }, @@ -814,12 +814,12 @@ cc.LabelTTF = cc.Sprite.extend(/** @lends cc.LabelTTF# */{ _getWidth: function () { if (this._needUpdateTexture) this._renderCmd._updateTTF(); - return this._contentSize.width; + return cc.Sprite.prototype._getWidth.call(this); }, _getHeight: function () { if (this._needUpdateTexture) this._renderCmd._updateTTF(); - return this._contentSize.height; + return cc.Sprite.prototype._getHeight.call(this); }, setTextureRect: function (rect, rotated, untrimmedSize) { diff --git a/cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js b/cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js index 31109f2f9b..adf6c4aee6 100644 --- a/cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js +++ b/cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js @@ -48,7 +48,6 @@ cc.LabelTTF._firsrEnglish = /^[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]/; this._status = []; this._renderingIndex = 0; - this._texRect = cc.rect(); this._canUseDirtyRegion = true; }; var proto = cc.LabelTTF.RenderCmd.prototype; @@ -104,8 +103,7 @@ cc.LabelTTF._firsrEnglish = /^[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]/; proto._updateTTF = function () { var node = this._node; - var pixelRatio = cc.view.getDevicePixelRatio(); - var locDimensionsWidth = node._dimensions.width * pixelRatio, i, strLength; + var locDimensionsWidth = node._dimensions.width, i, strLength; var locLineWidth = this._lineWidths; locLineWidth.length = 0; @@ -137,6 +135,7 @@ cc.LabelTTF._firsrEnglish = /^[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]/; locStrokeShadowOffsetY += Math.abs(locOffsetSize.y) * 2; } + var pixelRatio = cc.view.getDevicePixelRatio(); //get offset for stroke and shadow if (locDimensionsWidth === 0) { if (this._isMultiLine) @@ -167,16 +166,7 @@ cc.LabelTTF._firsrEnglish = /^[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]/; if (node._getFontStyle() !== "normal") { //add width for 'italic' and 'oblique' locSize.width = Math.ceil(locSize.width + node._fontSize * 0.3); } - if (this._strings.length === 0) { - this._texRect.width = 1; - this._texRect.height = locSize.height || 1; - } - else { - this._texRect.width = locSize.width; - this._texRect.height = locSize.height; - } - var nodeW = locSize.width / pixelRatio, nodeH = locSize.height / pixelRatio; - node.setContentSize(nodeW, nodeH); + node.setContentSize(locSize); node._strokeShadowOffsetX = locStrokeShadowOffsetX; node._strokeShadowOffsetY = locStrokeShadowOffsetY; @@ -188,14 +178,13 @@ cc.LabelTTF._firsrEnglish = /^[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]/; proto._saveStatus = function () { 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 - 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; + var locContentWidth = node._contentSize.width - locStrokeShadowOffsetX; //lineHeight var lineHeight = node.getLineHeight() * scale; @@ -322,6 +311,11 @@ cc.LabelTTF._firsrEnglish = /^[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]/; proto.updateStatus = function () { var flags = cc.Node._dirtyFlags, locFlag = this._dirtyFlag; +<<<<<<< HEAD +======= + cc.Node.RenderCmd.prototype.updateStatus.call(this); + +>>>>>>> 45cdfaa... Revert "Fix UIText issue and Label getContentSize value wrong in retina mode" if (locFlag & flags.textDirty) this._updateTexture(); @@ -335,7 +329,13 @@ cc.LabelTTF._firsrEnglish = /^[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]/; proto._syncStatus = function (parentCmd) { var flags = cc.Node._dirtyFlags, locFlag = this._dirtyFlag; +<<<<<<< HEAD +======= + + cc.Node.RenderCmd.prototype._syncStatus.call(this, parentCmd); + +>>>>>>> 45cdfaa... Revert "Fix UIText issue and Label getContentSize value wrong in retina mode" if (locFlag & flags.textDirty) this._updateTexture(); @@ -393,7 +393,6 @@ cc.LabelTTF._firsrEnglish = /^[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]/; locCanvas.width = 1; locCanvas.height = 1; this._labelContext = locCanvas.getContext("2d"); - this._texRect = cc.rect(); }; cc.LabelTTF.CacheRenderCmd.prototype = Object.create( cc.LabelTTF.RenderCmd.prototype); @@ -405,8 +404,9 @@ cc.LabelTTF._firsrEnglish = /^[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]/; proto._updateTexture = function () { this._dirtyFlag = this._dirtyFlag & cc.Node._dirtyFlags.textDirty ^ this._dirtyFlag; var node = this._node; + var locContentSize = node._contentSize; this._updateTTF(); - var width = this._texRect.width, height = this._texRect.height; + var width = locContentSize.width, height = locContentSize.height; var locContext = this._labelContext, locLabelCanvas = this._labelCanvas; @@ -417,10 +417,10 @@ cc.LabelTTF._firsrEnglish = /^[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]/; } if (node._string.length === 0) { - locLabelCanvas.width = width; - locLabelCanvas.height = height; + locLabelCanvas.width = 1; + locLabelCanvas.height = locContentSize.height || 1; node._texture && node._texture.handleLoadedTexture(); - node.setTextureRect(this._texRect); + node.setTextureRect(cc.rect(0, 0, 1, locContentSize.height)); return true; } @@ -428,13 +428,13 @@ cc.LabelTTF._firsrEnglish = /^[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]/; locContext.font = this._fontStyleStr; var flag = locLabelCanvas.width === width && locLabelCanvas.height === height; - locLabelCanvas.width = this._texRect.width; - locLabelCanvas.height = this._texRect.height; + locLabelCanvas.width = width; + locLabelCanvas.height = height; if (flag) locContext.clearRect(0, 0, width, height); this._saveStatus(); this._drawTTFInCanvas(locContext); node._texture && node._texture.handleLoadedTexture(); - node.setTextureRect(this._texRect); + node.setTextureRect(cc.rect(0, 0, width, height)); return true; }; @@ -482,14 +482,15 @@ cc.LabelTTF._firsrEnglish = /^[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]/; proto._updateTexture = function () { this._dirtyFlag = this._dirtyFlag & cc.Node._dirtyFlags.textDirty ^ this._dirtyFlag; var node = this._node; - var scale = cc.view.getDevicePixelRatio(); + var locContentSize = node._contentSize; this._updateTTF(); + var width = locContentSize.width, height = locContentSize.height; if (node._string.length === 0) { - node.setTextureRect(this._texRect); + node.setTextureRect(cc.rect(0, 0, 1, locContentSize.height)); return true; } this._saveStatus(); - node.setTextureRect(this._texRect); + node.setTextureRect(cc.rect(0, 0, width, height)); return true; }; diff --git a/extensions/ccui/uiwidgets/UIText.js b/extensions/ccui/uiwidgets/UIText.js index bfa1198a77..329ccf508e 100644 --- a/extensions/ccui/uiwidgets/UIText.js +++ b/extensions/ccui/uiwidgets/UIText.js @@ -46,7 +46,7 @@ ccui.Text = ccui.Widget.extend(/** @lends ccui.Text# */{ _fontName: "Arial", _fontSize: 16, _onSelectedScaleOffset:0.5, - _labelRenderer: null, + _labelRenderer: "", _textAreaSize: null, _textVerticalAlignment: 0, _textHorizontalAlignment: 0, From cb1f68e81a0b3c77c55f62cefd07ce676a5864f4 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Fri, 18 Nov 2016 11:15:09 +0800 Subject: [PATCH 04/42] Avoid using cc.isString, cc.isXXX --- cocos2d/core/base-nodes/CCNode.js | 7 +++---- cocos2d/core/platform/CCTypes.js | 6 +++--- cocos2d/core/sprites/CCSprite.js | 8 ++++---- cocos2d/core/sprites/CCSpriteFrame.js | 2 +- cocos2d/labels/CCLabelBMFont.js | 4 ++-- 5 files changed, 13 insertions(+), 14 deletions(-) diff --git a/cocos2d/core/base-nodes/CCNode.js b/cocos2d/core/base-nodes/CCNode.js index a5df64d76e..688b7f3160 100644 --- a/cocos2d/core/base-nodes/CCNode.js +++ b/cocos2d/core/base-nodes/CCNode.js @@ -1250,13 +1250,12 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{ addChild: function (child, localZOrder, tag) { localZOrder = localZOrder === undefined ? child._localZOrder : localZOrder; var name, setTag = false; - if(cc.isUndefined(tag)){ - tag = undefined; + if (tag === undefined) { name = child._name; - } else if(cc.isString(tag)){ + } else if (typeof tag === 'string'){ name = tag; tag = undefined; - } else if(cc.isNumber(tag)){ + } else if (typeof tag === 'number'){ setTag = true; name = ""; } diff --git a/cocos2d/core/platform/CCTypes.js b/cocos2d/core/platform/CCTypes.js index d819a242b9..c9d91a6dce 100644 --- a/cocos2d/core/platform/CCTypes.js +++ b/cocos2d/core/platform/CCTypes.js @@ -64,10 +64,10 @@ cc.Color = function (r, g, b, a) { cc.color = function (r, g, b, a) { if (r === undefined) return {r: 0, g: 0, b: 0, a: 255}; - if (cc.isString(r)) - return cc.hexToColor(r); - if (cc.isObject(r)) + if (typeof r === 'object') return {r: r.r, g: r.g, b: r.b, a: (r.a == null) ? 255 : r.a}; + if (typeof r === 'string') + return cc.hexToColor(r); return {r: r, g: g, b: b, a: (a == null ? 255 : a)}; }; diff --git a/cocos2d/core/sprites/CCSprite.js b/cocos2d/core/sprites/CCSprite.js index 5457a24714..034367bfd9 100644 --- a/cocos2d/core/sprites/CCSprite.js +++ b/cocos2d/core/sprites/CCSprite.js @@ -528,7 +528,7 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{ _softInit: function (fileName, rect, rotated) { if (fileName === undefined) cc.Sprite.prototype.init.call(this); - else if (cc.isString(fileName)) { + else if (typeof fileName === 'string') { if (fileName[0] === "#") { // Init with a sprite frame name var frameName = fileName.substr(1, fileName.length - 1); @@ -783,7 +783,7 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{ */ setSpriteFrame: function (newFrame) { var _t = this; - if(cc.isString(newFrame)){ + if(typeof newFrame === 'string'){ newFrame = cc.spriteFrameCache.getSpriteFrame(newFrame); cc.assert(newFrame, cc._LogInfos.Sprite_setSpriteFrame) } @@ -893,7 +893,7 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{ return this._renderCmd._setTexture(null); //CCSprite.cpp 327 and 338 - var isFileName = cc.isString(texture); + var isFileName = (typeof texture === 'string'); if(isFileName) texture = cc.textureCache.addImage(texture); @@ -1011,4 +1011,4 @@ delete cc._tmp.PrototypeSprite; item.source.removeEventListener('load', item.listener, item.target); } }; -})(); \ No newline at end of file +})(); diff --git a/cocos2d/core/sprites/CCSpriteFrame.js b/cocos2d/core/sprites/CCSpriteFrame.js index ccb7f9a86e..9ba272211b 100644 --- a/cocos2d/core/sprites/CCSpriteFrame.js +++ b/cocos2d/core/sprites/CCSpriteFrame.js @@ -337,7 +337,7 @@ cc.SpriteFrame = cc.Class.extend(/** @lends cc.SpriteFrame# */{ originalSize = originalSize || rect; rotated = rotated || false; - if (cc.isString(texture)){ + if (typeof texture === 'string'){ this._texture = null; this._textureFilename = texture; } else if (texture instanceof cc.Texture2D){ diff --git a/cocos2d/labels/CCLabelBMFont.js b/cocos2d/labels/CCLabelBMFont.js index 0dd628e128..97608769c1 100644 --- a/cocos2d/labels/CCLabelBMFont.js +++ b/cocos2d/labels/CCLabelBMFont.js @@ -410,9 +410,9 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{ */ setString: function (newString, needUpdateLabel) { newString = String(newString); - if (needUpdateLabel == null) + if (needUpdateLabel === undefined) needUpdateLabel = true; - if (newString == null || !cc.isString(newString)) + if (newString === undefined || typeof newString !== 'string') newString = newString + ""; this._initialString = newString; From 4eab965b80ecd997d398b90f10a962a2e06a1531 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Fri, 18 Nov 2016 11:15:38 +0800 Subject: [PATCH 05/42] Add cc.view.setDocumentPixelWidth API --- cocos2d/core/platform/CCEGLView.js | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/cocos2d/core/platform/CCEGLView.js b/cocos2d/core/platform/CCEGLView.js index 02a5122324..86b80f5444 100644 --- a/cocos2d/core/platform/CCEGLView.js +++ b/cocos2d/core/platform/CCEGLView.js @@ -311,6 +311,18 @@ cc.EGLView = cc.Class.extend(/** @lends cc.view# */{ } }, + setDocumentPixelWidth: function (width) { + // Set viewport's width + this._setViewportMeta({"width": width}, true); + + // Set body width to the exact pixel resolution + document.documentElement.style.width = width + 'px'; + document.body.style.width = "100%"; + + // Reset the resolution size and policy + this.setDesignResolutionSize(this._designResolutionSize.width, this._designResolutionSize.height, this._resolutionPolicy); + }, + _initFrameSize: function () { var locFrameSize = this._frameSize; var w = __BrowserGetter.availWidth(this._frame); @@ -756,9 +768,8 @@ cc.EGLView = cc.Class.extend(/** @lends cc.view# */{ this._setViewportMeta({"width": width}, true); // Set body width to the exact pixel resolution - document.body.style.width = width + "px"; - document.body.style.left = "0px"; - document.body.style.top = "0px"; + document.html.style.width = width + 'px'; + document.body.style.width = "100%"; // Reset the resolution size and policy this.setDesignResolutionSize(width, height, resolutionPolicy); From c715c421cfb0c19105451accad5bc1adf3b16d24 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Fri, 18 Nov 2016 11:15:52 +0800 Subject: [PATCH 06/42] Fix Editbox adaptation issue --- extensions/editbox/CCEditBox.js | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/extensions/editbox/CCEditBox.js b/extensions/editbox/CCEditBox.js index 5d3f23a25a..b8d6fb4254 100644 --- a/extensions/editbox/CCEditBox.js +++ b/extensions/editbox/CCEditBox.js @@ -674,7 +674,7 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp var LEFT_PADDING = 2; function scrollWindowUp (editBox) { - if (cc.sys.os === cc.sys.OS_IOS && cc.sys.osMainVersion === 9) { + // if (cc.sys.os === cc.sys.OS_IOS && cc.sys.osMainVersion === 9) { var worldPos = editBox.convertToWorldSpace(cc.p(0,0)); var windowHeight = cc.visibleRect.height; var windowWidth = cc.visibleRect.width; @@ -690,7 +690,7 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp window.scrollTo(0, scrollOffset); } }, TIMER_NAME); - } + // } } function capitalize (string) { @@ -925,6 +925,8 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp } else { thisPointer.__fullscreen = false; } + this.__autoResize = cc.view.__resizeWithBrowserSize; + cc.view.resizeWithBrowserSize(false); scrollWindowUp(editBox); @@ -952,6 +954,9 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp if(thisPointer.__fullscreen) { cc.view.enableAutoFullScreen(true); } + if (this.__autoResize) { + cc.view.resizeWithBrowserSize(true); + } if (editBox._delegate && editBox._delegate.editBoxEditingDidEnded) { editBox._delegate.editBoxEditingDidEnded(editBox); From 360eba7157361b498ddc0d665471c7b3fc70b1fa Mon Sep 17 00:00:00 2001 From: pandamicro Date: Fri, 18 Nov 2016 11:19:52 +0800 Subject: [PATCH 07/42] Reimplementation of DrawNode under WebGL --- cocos2d/actions/CCActionCatmullRom.js | 11 +- cocos2d/core/platform/CCConfig.js | 2 + cocos2d/core/renderer/GlobalVertexBuffer.js | 17 +- cocos2d/shape-nodes/CCDrawNode.js | 776 ++++++++++++------ .../shape-nodes/CCDrawNodeWebGLRenderCmd.js | 2 +- moduleConfig.json | 1 + 6 files changed, 534 insertions(+), 275 deletions(-) diff --git a/cocos2d/actions/CCActionCatmullRom.js b/cocos2d/actions/CCActionCatmullRom.js index 1cfa05bf8a..a17dca4ccc 100644 --- a/cocos2d/actions/CCActionCatmullRom.js +++ b/cocos2d/actions/CCActionCatmullRom.js @@ -44,9 +44,10 @@ * @param {cc.Point} p3 * @param {Number} tension * @param {Number} t + * @param {cc.Point} [out] * @return {cc.Point} */ -cc.cardinalSplineAt = function (p0, p1, p2, p3, tension, t) { +cc.cardinalSplineAt = function (p0, p1, p2, p3, tension, t, out) { var t2 = t * t; var t3 = t2 * t; @@ -62,7 +63,13 @@ cc.cardinalSplineAt = function (p0, p1, p2, p3, tension, t) { var x = (p0.x * b1 + p1.x * b2 + p2.x * b3 + p3.x * b4); var y = (p0.y * b1 + p1.y * b2 + p2.y * b3 + p3.y * b4); - return cc.p(x, y); + if (out !== undefined) { + out.x = x; + out.y = y; + } + else { + return cc.p(x, y); + } }; /** diff --git a/cocos2d/core/platform/CCConfig.js b/cocos2d/core/platform/CCConfig.js index 8ae3b6e641..bc01fbc66f 100644 --- a/cocos2d/core/platform/CCConfig.js +++ b/cocos2d/core/platform/CCConfig.js @@ -260,6 +260,8 @@ cc.LABELBMFONT_DEBUG_DRAW = 0; */ cc.LABELATLAS_DEBUG_DRAW = 0; +cc.DRAWNODE_TOTAL_VERTICES = 20000; + /** * Whether or not support retina display * @constant diff --git a/cocos2d/core/renderer/GlobalVertexBuffer.js b/cocos2d/core/renderer/GlobalVertexBuffer.js index 4bb7029805..e81c95a133 100644 --- a/cocos2d/core/renderer/GlobalVertexBuffer.js +++ b/cocos2d/core/renderer/GlobalVertexBuffer.js @@ -26,13 +26,13 @@ var GlobalVertexBuffer = (function () { var VERTICES_SIZE = 888; -var GlobalVertexBuffer = function (gl) { +var GlobalVertexBuffer = function (gl, byteLength) { // WebGL buffer this.gl = gl; this.vertexBuffer = gl.createBuffer(); this.size = VERTICES_SIZE; - this.byteLength = VERTICES_SIZE * 4 * cc.V3F_C4B_T2F_Quad.BYTES_PER_ELEMENT; + this.byteLength = byteLength || VERTICES_SIZE * 4 * cc.V3F_C4B_T2F_Quad.BYTES_PER_ELEMENT; // buffer data and views this.data = new ArrayBuffer(this.byteLength); @@ -72,14 +72,10 @@ GlobalVertexBuffer.prototype = { offset = parseInt(key); available = this._spaces[key]; if (available >= size && this.allocBuffer(offset, size)) { - return { - buffer: this, - offset: offset, - size: size - }; + return offset; } } - return null; + return -1; }, freeBuffer: function (offset, size) { @@ -121,6 +117,11 @@ GlobalVertexBuffer.prototype = { } }, + updateSubData: function (offset, dataArray) { + this.gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); + this.gl.bufferSubData(gl.ARRAY_BUFFER, offset, dataArray); + }, + destroy: function () { this.gl.deleteBuffer(this.vertexBuffer); diff --git a/cocos2d/shape-nodes/CCDrawNode.js b/cocos2d/shape-nodes/CCDrawNode.js index 48cdf4cccc..b8bcf09aa7 100644 --- a/cocos2d/shape-nodes/CCDrawNode.js +++ b/cocos2d/shape-nodes/CCDrawNode.js @@ -31,54 +31,54 @@ * Renamed and added some changes for cocos2d * */ -cc.v2fzero = function () { - return {x: 0, y: 0}; -}; +// cc.v2fzero = function () { +// return {x: 0, y: 0}; +// }; -cc.v2f = function (x, y) { - return {x: x, y: y}; -}; +// cc.v2f = function (x, y) { +// return {x: x, y: y}; +// }; -cc.v2fadd = function (v0, v1) { - return cc.v2f(v0.x + v1.x, v0.y + v1.y); -}; +// cc.v2fadd = function (v0, v1) { +// return cc.v2f(v0.x + v1.x, v0.y + v1.y); +// }; -cc.v2fsub = function (v0, v1) { - return cc.v2f(v0.x - v1.x, v0.y - v1.y); -}; +// cc.v2fsub = function (v0, v1) { +// return cc.v2f(v0.x - v1.x, v0.y - v1.y); +// }; -cc.v2fmult = function (v, s) { - return cc.v2f(v.x * s, v.y * s); -}; +// cc.v2fmult = function (v, s) { +// return cc.v2f(v.x * s, v.y * s); +// }; -cc.v2fperp = function (p0) { - return cc.v2f(-p0.y, p0.x); -}; +// cc.v2fperp = function (p0) { +// return cc.v2f(-p0.y, p0.x); +// }; -cc.v2fneg = function (p0) { - return cc.v2f(-p0.x, -p0.y); -}; +// cc.v2fneg = function (p0) { +// return cc.v2f(-p0.x, -p0.y); +// }; -cc.v2fdot = function (p0, p1) { - return p0.x * p1.x + p0.y * p1.y; -}; +// cc.v2fdot = function (p0, p1) { +// return p0.x * p1.x + p0.y * p1.y; +// }; -cc.v2fforangle = function (_a_) { - return cc.v2f(Math.cos(_a_), Math.sin(_a_)); -}; +// cc.v2fforangle = function (_a_) { +// return cc.v2f(Math.cos(_a_), Math.sin(_a_)); +// }; -cc.v2fnormalize = function (p) { - var r = cc.pNormalize(cc.p(p.x, p.y)); - return cc.v2f(r.x, r.y); -}; +// cc.v2fnormalize = function (p) { +// var r = cc.pNormalize(cc.p(p.x, p.y)); +// return cc.v2f(r.x, r.y); +// }; -cc.__v2f = function (v) { - return cc.v2f(v.x, v.y); -}; +// cc.__v2f = function (v) { +// return cc.v2f(v.x, v.y); +// }; -cc.__t = function (v) { - return {u: v.x, v: v.y}; -}; +// cc.__t = function (v) { +// return {u: v.x, v: v.y}; +// }; /** *

CCDrawNode
@@ -170,6 +170,12 @@ cc.DrawNode.TYPE_SEGMENT = 1; cc.DrawNode.TYPE_POLY = 2; cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () { + + function pMultOut (pin, floatVar, pout) { + pout.x = pin.x * floatVar; + pout.y = pin.y * floatVar; + } + if (cc._renderType === cc.game.RENDER_TYPE_CANVAS) { cc._DrawNodeElement = function (type, verts, fillColor, lineWidth, lineColor, lineCap, isClosePolygon, isFill, isStroke) { @@ -529,98 +535,185 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () { } else if (cc._renderType === cc.game.RENDER_TYPE_WEBGL) { + // 9600 vertices by default configurable in ccConfig.js + // 20 is 2 float for position, 4 int for color and 2 float for uv + var _sharedBuffer = null; + var FLOAT_PER_VERTEX = 2 + 1 + 2; + var VERTEX_BYTE = FLOAT_PER_VERTEX * 4; + var FLOAT_PER_TRIANGLE = 3 * FLOAT_PER_VERTEX; + var TRIANGLE_BYTES = FLOAT_PER_TRIANGLE * 4; + var MAX_INCREMENT = 200; + + var _vertices = [], + _from = cc.p(), + _to = cc.p(), + _color = new Uint32Array(1); + + // Used in drawSegment + var _n = cc.p(), _t = cc.p(), _nw = cc.p(), _tw = cc.p(), + _extrude = []; + cc.extend(cc.DrawNode.prototype, { - _bufferCapacity:0, + _bufferCapacity: 0, + _vertexCount: 0, + + _offset: 0, + _occupiedSize: 0, + _f32Buffer: null, + _ui32Buffer: null, - _trianglesArrayBuffer:null, - _trianglesWebBuffer:null, - _trianglesReader:null, + // _trianglesArrayBuffer:null, + // _trianglesWebBuffer:null, + // _trianglesReader:null, - _dirty:false, - _className:"DrawNodeWebGL", + _dirty: false, + _className: "DrawNodeWebGL", - ctor:function () { + manualRelease: false, + + ctor: function (capacity, manualRelease) { cc.Node.prototype.ctor.call(this); - this._buffer = []; + + if (!_sharedBuffer) { + _sharedBuffer = new GlobalVertexBuffer(cc._renderContext, cc.DRAWNODE_TOTAL_VERTICES * VERTEX_BYTE); + } + + this._renderCmd._shaderProgram = cc.shaderCache.programForKey(cc.SHADER_POSITION_LENGTHTEXTURECOLOR); this._blendFunc = new cc.BlendFunc(cc.SRC_ALPHA, cc.ONE_MINUS_SRC_ALPHA); - this._drawColor = cc.color(255,255,255,255); + this._drawColor = cc.color(255, 255, 255, 255); - this.init(); + this._bufferCapacity = capacity || 64; + this.manualRelease = manualRelease; + + this._dirty = true; + }, + + onEnter: function () { + if (this._occupiedSize < this._bufferCapacity) { + this._ensureCapacity(this._bufferCapacity); + } }, - init:function () { - if (cc.Node.prototype.init.call(this)) { - this.shaderProgram = cc.shaderCache.programForKey(cc.SHADER_POSITION_LENGTHTEXTURECOLOR); - this._ensureCapacity(64); - this._trianglesWebBuffer = cc._renderContext.createBuffer(); - this._dirty = true; + onExit: function () { + if (!this.manualRelease) { + this.release(); + } + }, + + release: function () { + if (this._occupiedSize > 0) { + this._vertexCount = 0; + _sharedBuffer.freeBuffer(this._offset, VERTEX_BYTE * this._occupiedSize); + this._occupiedSize = 0; + } + }, + + _ensureCapacity: function (count) { + var _t = this; + var prev = _t._occupiedSize; + var prevOffset = _t._offset; + if (count > prev || _t._bufferCapacity > prev) { + var request = Math.max(Math.min(prev + prev, MAX_INCREMENT), count, _t._bufferCapacity); + // free previous buffer + if (prev !== 0) { + _sharedBuffer.freeBuffer(prevOffset, VERTEX_BYTE * prev); + _t._occupiedSize = 0; + } + var offset = _t._offset = _sharedBuffer.requestBuffer(VERTEX_BYTE * request); + if (offset >= 0) { + _t._occupiedSize = _t._bufferCapacity = request; + // 5 floats per vertex + _t._f32Buffer = new Float32Array(_sharedBuffer.data, offset, FLOAT_PER_VERTEX * _t._occupiedSize); + _t._ui32Buffer = new Uint32Array(_sharedBuffer.data, offset, FLOAT_PER_VERTEX * _t._occupiedSize); + + // Copy old data + if (prev !== 0 && prevOffset !== offset) { + // offset is in byte, we need to transform to float32 index + var last = (prevOffset + prev) / 4; + for (var i = offset/4, j = prevOffset/4; j < last; i++, j++) { + _sharedBuffer.dataArray[i] = _sharedBuffer.dataArray[j]; + } + } + + return true; + } + else { + cc.warn('Failed to allocate buffer for DrawNode: buffer for ' + request + ' vertices requested'); + return false; + } + } + else { return true; } - return false; }, drawRect: function (origin, destination, fillColor, lineWidth, lineColor) { lineWidth = (lineWidth == null) ? this._lineWidth : lineWidth; - lineColor = lineColor || this.getDrawColor(); - if (lineColor.a == null) - lineColor.a = 255; - var vertices = [origin, cc.p(destination.x, origin.y), destination, cc.p(origin.x, destination.y)]; + lineColor = lineColor || this._drawColor; + _vertices.length = 0; + _vertices.push(origin.x, origin.y, destination.x, origin.y, destination.x, destination.y, origin.x, destination.y); if(fillColor == null) - this._drawSegments(vertices, lineWidth, lineColor, true); + this._drawSegments(_vertices, lineWidth, lineColor, true); else - this.drawPoly(vertices, fillColor, lineWidth, lineColor); + this.drawPoly(_vertices, fillColor, lineWidth, lineColor); + _vertices.length = 0; }, drawCircle: function (center, radius, angle, segments, drawLineToCenter, lineWidth, color) { lineWidth = lineWidth || this._lineWidth; - color = color || this.getDrawColor(); - if (color.a == null) - color.a = 255; - var coef = 2.0 * Math.PI / segments, vertices = [], i, len; + color = color || this._drawColor; + var coef = 2.0 * Math.PI / segments, i, len; + _vertices.length = 0; for (i = 0; i <= segments; i++) { var rads = i * coef; var j = radius * Math.cos(rads + angle) + center.x; var k = radius * Math.sin(rads + angle) + center.y; - vertices.push(cc.p(j, k)); + _vertices.push(j, k); } if (drawLineToCenter) - vertices.push(cc.p(center.x, center.y)); + _vertices.push(center.x, center.y); lineWidth *= 0.5; - for (i = 0, len = vertices.length; i < len - 1; i++) - this.drawSegment(vertices[i], vertices[i + 1], lineWidth, color); + for (i = 0, len = _vertices.length - 2; i < len; i += 2) { + _from.x = _vertices[i]; + _from.y = _vertices[i + 1]; + _to.x = _vertices[i + 2]; + _to.y = _vertices[i + 3]; + this.drawSegment(_from, _to, lineWidth, color); + } + _vertices.length = 0; }, drawQuadBezier: function (origin, control, destination, segments, lineWidth, color) { lineWidth = lineWidth || this._lineWidth; - color = color || this.getDrawColor(); - if (color.a == null) - color.a = 255; - var vertices = [], t = 0.0; + color = color || this._drawColor; + var t = 0.0; + _vertices.length = 0; for (var i = 0; i < segments; i++) { var x = Math.pow(1 - t, 2) * origin.x + 2.0 * (1 - t) * t * control.x + t * t * destination.x; var y = Math.pow(1 - t, 2) * origin.y + 2.0 * (1 - t) * t * control.y + t * t * destination.y; - vertices.push(cc.p(x, y)); + _vertices.push(x, y); t += 1.0 / segments; } - vertices.push(cc.p(destination.x, destination.y)); - this._drawSegments(vertices, lineWidth, color, false); + _vertices.push(destination.x, destination.y); + this._drawSegments(_vertices, lineWidth, color, false); + _vertices.length = 0; }, drawCubicBezier: function (origin, control1, control2, destination, segments, lineWidth, color) { lineWidth = lineWidth || this._lineWidth; - color = color || this.getDrawColor(); - if (color.a == null) - color.a = 255; - var vertices = [], t = 0; + color = color || this._drawColor; + var t = 0; + _vertices.length = 0; for (var i = 0; i < segments; i++) { var x = Math.pow(1 - t, 3) * origin.x + 3.0 * Math.pow(1 - t, 2) * t * control1.x + 3.0 * (1 - t) * t * t * control2.x + t * t * t * destination.x; var y = Math.pow(1 - t, 3) * origin.y + 3.0 * Math.pow(1 - t, 2) * t * control1.y + 3.0 * (1 - t) * t * t * control2.y + t * t * t * destination.y; - vertices.push(cc.p(x, y)); + _vertices.push(x, y); t += 1.0 / segments; } - vertices.push(cc.p(destination.x, destination.y)); - this._drawSegments(vertices, lineWidth, color, false); + _vertices.push(destination.x, destination.y); + this._drawSegments(_vertices, lineWidth, color, false); + _vertices.length = 0; }, drawCatmullRom: function (points, segments, lineWidth, color) { @@ -629,10 +722,9 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () { drawCardinalSpline: function (config, tension, segments, lineWidth, color) { lineWidth = lineWidth || this._lineWidth; - color = color || this.getDrawColor(); - if (color.a == null) - color.a = 255; - var vertices = [], p, lt, deltaT = 1.0 / config.length; + color = color || this._drawColor; + var p, lt, deltaT = 1.0 / config.length; + _vertices.length = 0; for (var i = 0; i < segments + 1; i++) { var dt = i / segments; @@ -647,150 +739,210 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () { } // Interpolate - var newPos = cc.cardinalSplineAt( + cc.cardinalSplineAt( cc.getControlPointAt(config, p - 1), cc.getControlPointAt(config, p - 0), cc.getControlPointAt(config, p + 1), cc.getControlPointAt(config, p + 2), - tension, lt); - vertices.push(newPos); + tension, lt, _from); + _vertices.push(_from.x, _from.y); } lineWidth *= 0.5; - for (var j = 0, len = vertices.length; j < len - 1; j++) - this.drawSegment(vertices[j], vertices[j + 1], lineWidth, color); + for (var j = 0, len = _vertices.length - 2; j < len; j += 2) { + _from.x = _vertices[j]; + _from.y = _vertices[j + 1]; + _to.x = _vertices[j + 2]; + _to.y = _vertices[j + 3]; + this.drawSegment(_from, _to, lineWidth, color); + } + _vertices.length = 0; + }, + + drawDots: function(points, radius,color) { + if(!points || points.length === 0) + return; + color = color || this._drawColor; + for(var i = 0, len = points.length; i < len; i++) { + this.drawDot(points[i], radius, color); + } }, _render:function () { var gl = cc._renderContext; + if (this._offset < 0 || this._vertexCount <= 0) { + return; + } - gl.bindBuffer(gl.ARRAY_BUFFER, this._trianglesWebBuffer); if (this._dirty) { - gl.bufferData(gl.ARRAY_BUFFER, this._trianglesArrayBuffer, gl.STREAM_DRAW); + // bindBuffer is done in updateSubData + _sharedBuffer.updateSubData(this._offset, this._f32Buffer); this._dirty = false; } - var triangleSize = cc.V2F_C4B_T2F.BYTES_PER_ELEMENT; + else { + gl.bindBuffer(gl.ARRAY_BUFFER, _sharedBuffer.vertexBuffer); + } gl.enableVertexAttribArray(cc.VERTEX_ATTRIB_POSITION); gl.enableVertexAttribArray(cc.VERTEX_ATTRIB_COLOR); gl.enableVertexAttribArray(cc.VERTEX_ATTRIB_TEX_COORDS); // vertex - gl.vertexAttribPointer(cc.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, triangleSize, 0); + gl.vertexAttribPointer(cc.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, VERTEX_BYTE, 0); // color - gl.vertexAttribPointer(cc.VERTEX_ATTRIB_COLOR, 4, gl.UNSIGNED_BYTE, true, triangleSize, 8); + gl.vertexAttribPointer(cc.VERTEX_ATTRIB_COLOR, 4, gl.UNSIGNED_BYTE, true, VERTEX_BYTE, 8); // texcood - gl.vertexAttribPointer(cc.VERTEX_ATTRIB_TEX_COORDS, 2, gl.FLOAT, false, triangleSize, 12); + gl.vertexAttribPointer(cc.VERTEX_ATTRIB_TEX_COORDS, 2, gl.FLOAT, false, VERTEX_BYTE, 12); - gl.drawArrays(gl.TRIANGLES, 0, this._buffer.length * 3); + gl.drawArrays(gl.TRIANGLES, this._offset / VERTEX_BYTE, this._vertexCount); cc.incrementGLDraws(1); //cc.checkGLErrorDebug(); }, - _ensureCapacity:function(count){ - var _t = this; - var locBuffer = _t._buffer; - if(locBuffer.length + count > _t._bufferCapacity){ - var TriangleLength = cc.V2F_C4B_T2F_Triangle.BYTES_PER_ELEMENT; - _t._bufferCapacity += Math.max(_t._bufferCapacity, count); - //re alloc - if((locBuffer == null) || (locBuffer.length === 0)){ - //init - _t._buffer = []; - _t._trianglesArrayBuffer = new ArrayBuffer(TriangleLength * _t._bufferCapacity); - _t._trianglesReader = new Uint8Array(_t._trianglesArrayBuffer); - } else { - var newTriangles = []; - var newArrayBuffer = new ArrayBuffer(TriangleLength * _t._bufferCapacity); - for(var i = 0; i < locBuffer.length;i++){ - newTriangles[i] = new cc.V2F_C4B_T2F_Triangle(locBuffer[i].a,locBuffer[i].b,locBuffer[i].c, - newArrayBuffer, i * TriangleLength); - } - _t._trianglesReader = new Uint8Array(newArrayBuffer); - _t._trianglesArrayBuffer = newArrayBuffer; - _t._buffer = newTriangles; - } - } + appendVertexData: function (x, y, color, u, v) { + var f32Buffer = this._f32Buffer; + // Float offset = byte offset / 4 + vertex count * floats by vertex + var offset = this._vertexCount * FLOAT_PER_VERTEX; + f32Buffer[offset] = x; + f32Buffer[offset + 1] = y; + _color[0] = ((color.a<<24) | (color.b<<16) | (color.g<<8) | color.r); + this._ui32Buffer[offset + 2] = _color[0]; + f32Buffer[offset + 3] = u; + f32Buffer[offset + 4] = v; + this._vertexCount++; }, drawDot:function (pos, radius, color) { - color = color || this.getDrawColor(); + color = color || this._drawColor; if (color.a == null) color.a = 255; - var c4bColor = {r: 0 | color.r, g: 0 | color.g, b: 0 | color.b, a: 0 | color.a}; - var a = {vertices: {x: pos.x - radius, y: pos.y - radius}, colors: c4bColor, texCoords: {u: -1.0, v: -1.0}}; - var b = {vertices: {x: pos.x - radius, y: pos.y + radius}, colors: c4bColor, texCoords: {u: -1.0, v: 1.0}}; - var c = {vertices: {x: pos.x + radius, y: pos.y + radius}, colors: c4bColor, texCoords: {u: 1.0, v: 1.0}}; - var d = {vertices: {x: pos.x + radius, y: pos.y - radius}, colors: c4bColor, texCoords: {u: 1.0, v: -1.0}}; + var l = pos.x - radius, + b = pos.y - radius, + r = pos.x + radius, + t = pos.y + radius; + + var vertexCount = 2 * 3; + var succeed = this._ensureCapacity(this._vertexCount + vertexCount); + if (!succeed) + return; - this._ensureCapacity(2*3); + // lb, lt, rt, lb, rt, rb + this.appendVertexData(l, b, color, -1, -1); + this.appendVertexData(l, t, color, -1, 1); + this.appendVertexData(r, t, color, 1, 1); + this.appendVertexData(l, b, color, -1, -1); + this.appendVertexData(r, t, color, 1, 1); + this.appendVertexData(r, b, color, 1, -1); - this._buffer.push(new cc.V2F_C4B_T2F_Triangle(a, b, c, this._trianglesArrayBuffer, this._buffer.length * cc.V2F_C4B_T2F_Triangle.BYTES_PER_ELEMENT)); - this._buffer.push(new cc.V2F_C4B_T2F_Triangle(a, c, d, this._trianglesArrayBuffer, this._buffer.length * cc.V2F_C4B_T2F_Triangle.BYTES_PER_ELEMENT)); this._dirty = true; }, - drawDots: function(points, radius,color) { - if(!points || points.length === 0) - return; - color = color || this.getDrawColor(); - if (color.a == null) - color.a = 255; - for(var i = 0, len = points.length; i < len; i++) - this.drawDot(points[i], radius, color); - }, - drawSegment:function (from, to, radius, color) { color = color || this.getDrawColor(); if (color.a == null) color.a = 255; radius = radius || (this._lineWidth * 0.5); - var vertexCount = 6*3; - this._ensureCapacity(vertexCount); - - var c4bColor = {r: 0 | color.r, g: 0 | color.g, b: 0 | color.b, a: 0 | color.a}; - var a = cc.__v2f(from), b = cc.__v2f(to); - var n = cc.v2fnormalize(cc.v2fperp(cc.v2fsub(b, a))), t = cc.v2fperp(n); - var nw = cc.v2fmult(n, radius), tw = cc.v2fmult(t, radius); - - var v0 = cc.v2fsub(b, cc.v2fadd(nw, tw)); - var v1 = cc.v2fadd(b, cc.v2fsub(nw, tw)); - var v2 = cc.v2fsub(b, nw); - var v3 = cc.v2fadd(b, nw); - var v4 = cc.v2fsub(a, nw); - var v5 = cc.v2fadd(a, nw); - var v6 = cc.v2fsub(a, cc.v2fsub(nw, tw)); - var v7 = cc.v2fadd(a, cc.v2fadd(nw, tw)); - - var TriangleLength = cc.V2F_C4B_T2F_Triangle.BYTES_PER_ELEMENT, triangleBuffer = this._trianglesArrayBuffer, locBuffer = this._buffer; - locBuffer.push(new cc.V2F_C4B_T2F_Triangle({vertices: v0, colors: c4bColor, texCoords: cc.__t(cc.v2fneg(cc.v2fadd(n, t)))}, - {vertices: v1, colors: c4bColor, texCoords: cc.__t(cc.v2fsub(n, t))}, {vertices: v2, colors: c4bColor, texCoords: cc.__t(cc.v2fneg(n))}, - triangleBuffer, locBuffer.length * TriangleLength)); - - locBuffer.push(new cc.V2F_C4B_T2F_Triangle({vertices: v3, colors: c4bColor, texCoords: cc.__t(n)}, - {vertices: v1, colors: c4bColor, texCoords: cc.__t(cc.v2fsub(n, t))}, {vertices: v2, colors: c4bColor, texCoords: cc.__t(cc.v2fneg(n))}, - triangleBuffer, locBuffer.length * TriangleLength)); - - locBuffer.push(new cc.V2F_C4B_T2F_Triangle({vertices: v3, colors: c4bColor, texCoords: cc.__t(n)}, - {vertices: v4, colors: c4bColor, texCoords: cc.__t(cc.v2fneg(n))}, {vertices: v2, colors: c4bColor, texCoords: cc.__t(cc.v2fneg(n))}, - triangleBuffer, locBuffer.length * TriangleLength)); - - locBuffer.push(new cc.V2F_C4B_T2F_Triangle({vertices: v3, colors: c4bColor, texCoords: cc.__t(n)}, - {vertices: v4, colors: c4bColor, texCoords: cc.__t(cc.v2fneg(n))}, {vertices: v5, colors: c4bColor, texCoords: cc.__t(n)}, - triangleBuffer, locBuffer.length * TriangleLength)); - - locBuffer.push(new cc.V2F_C4B_T2F_Triangle({vertices: v6, colors: c4bColor, texCoords: cc.__t(cc.v2fsub(t, n))}, - {vertices: v4, colors: c4bColor, texCoords: cc.__t(cc.v2fneg(n))}, {vertices: v5, colors: c4bColor, texCoords: cc.__t(n)}, - triangleBuffer, locBuffer.length * TriangleLength)); - - locBuffer.push(new cc.V2F_C4B_T2F_Triangle({vertices: v6, colors: c4bColor, texCoords: cc.__t(cc.v2fsub(t, n))}, - {vertices: v7, colors: c4bColor, texCoords: cc.__t(cc.v2fadd(n, t))}, {vertices: v5, colors: c4bColor, texCoords: cc.__t(n)}, - triangleBuffer, locBuffer.length * TriangleLength)); + var vertexCount = 6 * 3; + var succeed = this._ensureCapacity(this._vertexCount + vertexCount); + if (!succeed) + return; + + // var a = cc.__v2f(from), b = cc.__v2f(to); + var a = from, b = to; + // var n = cc.v2fnormalize(cc.v2fperp(cc.v2fsub(b, a))) + _n.x = a.y - b.y; _n.y = b.x - a.x; + cc.pNormalizeIn(_n); + // var t = cc.v2fperp(n); + _t.x = -_n.y; _t.y = _n.x; + // var nw = cc.v2fmult(n, radius), tw = cc.v2fmult(t, radius); + pMultOut(_n, radius, _nw); + pMultOut(_t, radius, _tw); + + // var v0 = cc.v2fsub(b, cc.v2fadd(nw, tw)); uv0 = cc.__t(cc.v2fneg(cc.v2fadd(n, t))) + var v0x = b.x - _nw.x - _tw.x, v0y = b.y - _nw.y - _tw.y, u0 = -(_n.x + _t.x), v0 = -(_n.y + _t.y); + // var v1 = cc.v2fadd(b, cc.v2fsub(nw, tw)); uv1 = cc.__t(cc.v2fsub(n, t)) + var v1x = b.x + _nw.x - _tw.x, v1y = b.y + _nw.y - _tw.y, u1 = _n.x - _t.x, v1 = _n.y - _t.y; + // var v2 = cc.v2fsub(b, nw); uv2 = cc.__t(cc.v2fneg(n)) + var v2x = b.x - _nw.x, v2y = b.y - _nw.y, u2 = -_n.x, v2 = -_n.y; + // var v3 = cc.v2fadd(b, nw); uv3 = cc.__t(n) + var v3x = b.x + _nw.x, v3y = b.y + _nw.y, u3 = _n.x, v3 = _n.y; + // var v4 = cc.v2fsub(a, nw); uv4 = cc.__t(cc.v2fneg(n)) + var v4x = a.x - _nw.x, v4y = a.y - _nw.y, u4 = u2, v4 = v2; + // var v5 = cc.v2fadd(a, nw); uv5 = cc.__t(n) + var v5x = a.x + _nw.x, v5y = a.y + _nw.y, u5 = _n.x, v5 = _n.y; + // var v6 = cc.v2fsub(a, cc.v2fsub(nw, tw)); uv6 = cc.__t(cc.v2fsub(t, n)) + var v6x = a.x - _nw.x + _tw.x, v6y = a.y - _nw.y + _tw.y, u6 = _t.x - _n.x, v6 = _t.y - _n.y; + // var v7 = cc.v2fadd(a, cc.v2fadd(nw, tw)); uv7 = cc.__t(cc.v2fadd(n, t)) + var v7x = a.x + _nw.x + _tw.x, v7y = a.y + _nw.y + _tw.y, u7 = _n.x + _t.x, v7 = _n.y + _t.y; + + // var TriangleLength = cc.V2F_C4B_T2F_Triangle.BYTES_PER_ELEMENT, triangleBuffer = this._trianglesArrayBuffer, locBuffer = this._buffer; + // locBuffer.push(new cc.V2F_C4B_T2F_Triangle( + // {vertices: v0, colors: c4bColor, texCoords: uv0}, + // {vertices: v1, colors: c4bColor, texCoords: uv1}, + // {vertices: v2, colors: c4bColor, texCoords: uv2}, + // triangleBuffer, locBuffer.length * TriangleLength)); + this.appendVertexData(v0x, v0y, color, u0, v0); + this.appendVertexData(v1x, v1y, color, u1, v1); + this.appendVertexData(v2x, v2y, color, u2, v2); + + // locBuffer.push(new cc.V2F_C4B_T2F_Triangle( + // {vertices: v3, colors: c4bColor, texCoords: uv3}, + // {vertices: v1, colors: c4bColor, texCoords: uv1}, + // {vertices: v2, colors: c4bColor, texCoords: uv2}, + // triangleBuffer, locBuffer.length * TriangleLength)); + this.appendVertexData(v3x, v3y, color, u3, v3); + this.appendVertexData(v1x, v1y, color, u1, v1); + this.appendVertexData(v2x, v2y, color, u2, v2); + + // locBuffer.push(new cc.V2F_C4B_T2F_Triangle( + // {vertices: v3, colors: c4bColor, texCoords: uv3}, + // {vertices: v4, colors: c4bColor, texCoords: uv4}, + // {vertices: v2, colors: c4bColor, texCoords: uv2}, + // triangleBuffer, locBuffer.length * TriangleLength)); + this.appendVertexData(v3x, v3y, color, u3, v3); + this.appendVertexData(v4x, v4y, color, u4, v4); + this.appendVertexData(v2x, v2y, color, u2, v2); + + // locBuffer.push(new cc.V2F_C4B_T2F_Triangle( + // {vertices: v3, colors: c4bColor, texCoords: uv3}, + // {vertices: v4, colors: c4bColor, texCoords: uv4}, + // {vertices: v5, colors: c4bColor, texCoords: uv5}, + // triangleBuffer, locBuffer.length * TriangleLength)); + this.appendVertexData(v3x, v3y, color, u3, v3); + this.appendVertexData(v4x, v4y, color, u4, v4); + this.appendVertexData(v5x, v5y, color, u5, v5); + + // locBuffer.push(new cc.V2F_C4B_T2F_Triangle( + // {vertices: v6, colors: c4bColor, texCoords: uv6}, + // {vertices: v4, colors: c4bColor, texCoords: uv4}, + // {vertices: v5, colors: c4bColor, texCoords: uv5}, + // triangleBuffer, locBuffer.length * TriangleLength)); + this.appendVertexData(v6x, v6y, color, u6, v6); + this.appendVertexData(v4x, v4y, color, u4, v4); + this.appendVertexData(v5x, v5y, color, u5, v5); + + // locBuffer.push(new cc.V2F_C4B_T2F_Triangle( + // {vertices: v6, colors: c4bColor, texCoords: uv6}, + // {vertices: v7, colors: c4bColor, texCoords: uv7}, + // {vertices: v5, colors: c4bColor, texCoords: uv5}, + // triangleBuffer, locBuffer.length * TriangleLength)); + this.appendVertexData(v6x, v6y, color, u6, v6); + this.appendVertexData(v7x, v7y, color, u7, v7); + this.appendVertexData(v5x, v5y, color, u5, v5); this._dirty = true; }, drawPoly:function (verts, fillColor, borderWidth, borderColor) { - if(fillColor == null){ + // Backward compatibility + if (typeof verts[0] === 'object') { + _vertices.length = 0; + for (var i = 0; i < verts.length; i++) { + _vertices.push(verts[i].x, verts[i].y); + } + verts = _vertices; + } + + if (fillColor == null) { this._drawSegments(verts, borderWidth, borderColor, true); return; } @@ -800,118 +952,214 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () { borderColor.a = 255; borderWidth = (borderWidth == null)? this._lineWidth : borderWidth; borderWidth *= 0.5; - var c4bFillColor = {r: 0 | fillColor.r, g: 0 | fillColor.g, b: 0 | fillColor.b, a: 0 | fillColor.a}; - var c4bBorderColor = {r: 0 | borderColor.r, g: 0 | borderColor.g, b: 0 | borderColor.b, a: 0 | borderColor.a}; - var extrude = [], i, v0, v1, v2, count = verts.length; - for (i = 0; i < count; i++) { - v0 = cc.__v2f(verts[(i - 1 + count) % count]); - v1 = cc.__v2f(verts[i]); - v2 = cc.__v2f(verts[(i + 1) % count]); - var n1 = cc.v2fnormalize(cc.v2fperp(cc.v2fsub(v1, v0))); - var n2 = cc.v2fnormalize(cc.v2fperp(cc.v2fsub(v2, v1))); - var offset = cc.v2fmult(cc.v2fadd(n1, n2), 1.0 / (cc.v2fdot(n1, n2) + 1.0)); - extrude[i] = {offset: offset, n: n2}; + var v0x, v0y, v1x, v1y, v2x, v2y, + factor, offx, offy, + i, count = verts.length; + _extrude.length = 0; + for (i = 0; i < count; i += 2) { + v0x = verts[(i - 2 + count) % count]; + v0y = verts[(i - 1 + count) % count]; + v1x = verts[i]; + v1y = verts[i + 1]; + v2x = verts[(i + 2) % count]; + v2y = verts[(i + 3) % count]; + // var n1 = cc.v2fnormalize(cc.v2fperp(cc.v2fsub(v1, v0))); + // var n2 = cc.v2fnormalize(cc.v2fperp(cc.v2fsub(v2, v1))); + _n.x = v0y - v1y; _n.y = v1x - v0x; + _nw.x = v1y - v2y; _nw.y = v2x - v1x; + cc.pNormalizeIn(_n); + cc.pNormalizeIn(_nw); + // var offset = cc.v2fmult(cc.v2fadd(n1, n2), 1.0 / (cc.v2fdot(n1, n2) + 1.0)); + factor = _n.x * _nw.x + _n.y * _nw.y + 1; + offx = (_n.x + _nw.x) / factor; + offy = (_n.y + _nw.y) / factor; + // extrude[i] = {offset: offset, n: n2}; + _extrude.push(offx, offy, _nw.x, _nw.y); } + // The actual input vertex count + count = count / 2; var outline = (borderWidth > 0.0), triangleCount = 3 * count - 2, vertexCount = 3 * triangleCount; - this._ensureCapacity(vertexCount); + var succeed = this._ensureCapacity(this._vertexCount + vertexCount); + if (!succeed) + return; - var triangleBytesLen = cc.V2F_C4B_T2F_Triangle.BYTES_PER_ELEMENT, trianglesBuffer = this._trianglesArrayBuffer; - var locBuffer = this._buffer; var inset = (outline == false ? 0.5 : 0.0); for (i = 0; i < count - 2; i++) { - v0 = cc.v2fsub(cc.__v2f(verts[0]), cc.v2fmult(extrude[0].offset, inset)); - v1 = cc.v2fsub(cc.__v2f(verts[i + 1]), cc.v2fmult(extrude[i + 1].offset, inset)); - v2 = cc.v2fsub(cc.__v2f(verts[i + 2]), cc.v2fmult(extrude[i + 2].offset, inset)); - locBuffer.push(new cc.V2F_C4B_T2F_Triangle({vertices: v0, colors: c4bFillColor, texCoords: cc.__t(cc.v2fzero())}, - {vertices: v1, colors: c4bFillColor, texCoords: cc.__t(cc.v2fzero())}, {vertices: v2, colors: c4bFillColor, texCoords: cc.__t(cc.v2fzero())}, - trianglesBuffer, locBuffer.length * triangleBytesLen)); + // v0 = cc.v2fsub(cc.__v2f(verts[0]), cc.v2fmult(extrude[0].offset, inset)); + v0x = verts[0] - _extrude[0] * inset; + v0y = verts[1] - _extrude[1] * inset; + // v1 = cc.v2fsub(cc.__v2f(verts[i + 1]), cc.v2fmult(extrude[i + 1].offset, inset)); + v1x = verts[i * 2 + 2] - _extrude[(i+1) * 4] * inset; + v1y = verts[i * 2 + 3] - _extrude[(i+1) * 4 + 1] * inset; + // v2 = cc.v2fsub(cc.__v2f(verts[i + 2]), cc.v2fmult(extrude[i + 2].offset, inset)); + v2x = verts[i * 2 + 4] - _extrude[(i+2) * 4] * inset; + v2y = verts[i * 2 + 5] - _extrude[(i+2) * 4 + 1] * inset; + + // locBuffer.push(new cc.V2F_C4B_T2F_Triangle( + // {vertices: v0, colors: c4bFillColor, texCoords: cc.__t(cc.v2fzero())}, + // {vertices: v1, colors: c4bFillColor, texCoords: cc.__t(cc.v2fzero())}, + // {vertices: v2, colors: c4bFillColor, texCoords: cc.__t(cc.v2fzero())}, + // trianglesBuffer, locBuffer.length * triangleBytesLen)); + this.appendVertexData(v0x, v0y, fillColor, 0, 0); + this.appendVertexData(v1x, v1y, fillColor, 0, 0); + this.appendVertexData(v2x, v2y, fillColor, 0, 0); } + var off0x, off0y, off1x, off1y, + bw = outline ? borderWidth : 0.5, + color = outline ? borderColor : fillColor, + in0x, in0y, in1x, in1y, out0x, out0y, out1x, out1y; for (i = 0; i < count; i++) { var j = (i + 1) % count; - v0 = cc.__v2f(verts[i]); - v1 = cc.__v2f(verts[j]); - - var n0 = extrude[i].n; - var offset0 = extrude[i].offset; - var offset1 = extrude[j].offset; - var inner0 = outline ? cc.v2fsub(v0, cc.v2fmult(offset0, borderWidth)) : cc.v2fsub(v0, cc.v2fmult(offset0, 0.5)); - var inner1 = outline ? cc.v2fsub(v1, cc.v2fmult(offset1, borderWidth)) : cc.v2fsub(v1, cc.v2fmult(offset1, 0.5)); - var outer0 = outline ? cc.v2fadd(v0, cc.v2fmult(offset0, borderWidth)) : cc.v2fadd(v0, cc.v2fmult(offset0, 0.5)); - var outer1 = outline ? cc.v2fadd(v1, cc.v2fmult(offset1, borderWidth)) : cc.v2fadd(v1, cc.v2fmult(offset1, 0.5)); - - if (outline) { - locBuffer.push(new cc.V2F_C4B_T2F_Triangle({vertices: inner0, colors: c4bBorderColor, texCoords: cc.__t(cc.v2fneg(n0))}, - {vertices: inner1, colors: c4bBorderColor, texCoords: cc.__t(cc.v2fneg(n0))}, {vertices: outer1, colors: c4bBorderColor, texCoords: cc.__t(n0)}, - trianglesBuffer, locBuffer.length * triangleBytesLen)); - locBuffer.push(new cc.V2F_C4B_T2F_Triangle({vertices: inner0, colors: c4bBorderColor, texCoords: cc.__t(cc.v2fneg(n0))}, - {vertices: outer0, colors: c4bBorderColor, texCoords: cc.__t(n0)}, {vertices: outer1, colors: c4bBorderColor, texCoords: cc.__t(n0)}, - trianglesBuffer, locBuffer.length * triangleBytesLen)); - } else { - locBuffer.push(new cc.V2F_C4B_T2F_Triangle({vertices: inner0, colors: c4bFillColor, texCoords: cc.__t(cc.v2fzero())}, - {vertices: inner1, colors: c4bFillColor, texCoords: cc.__t(cc.v2fzero())}, {vertices: outer1, colors: c4bFillColor, texCoords: cc.__t(n0)}, - trianglesBuffer, locBuffer.length * triangleBytesLen)); - locBuffer.push(new cc.V2F_C4B_T2F_Triangle({vertices: inner0, colors: c4bFillColor, texCoords: cc.__t(cc.v2fzero())}, - {vertices: outer0, colors: c4bFillColor, texCoords: cc.__t(n0)}, {vertices: outer1, colors: c4bFillColor, texCoords: cc.__t(n0)}, - trianglesBuffer, locBuffer.length * triangleBytesLen)); - } + v0x = verts[i * 2]; + v0y = verts[i * 2 + 1]; + v1x = verts[j * 2]; + v1y = verts[j * 2 + 1]; + + _n.x = _extrude[i * 4 + 2]; + _n.y = _extrude[i * 4 + 3]; + _nw.x = outline ? -_n.x : 0; + _nw.y = outline ? -_n.y : 0; + off0x = _extrude[i * 4]; + off0y = _extrude[i * 4 + 1]; + off1x = _extrude[j * 4]; + off1y = _extrude[j * 4 + 1]; + + // var inner0 = outline ? cc.v2fsub(v0, cc.v2fmult(offset0, borderWidth)) : cc.v2fsub(v0, cc.v2fmult(offset0, 0.5)); + in0x = v0x - off0x * bw; in0y = v0y - off0y * bw; + // var inner1 = outline ? cc.v2fsub(v1, cc.v2fmult(offset1, borderWidth)) : cc.v2fsub(v1, cc.v2fmult(offset1, 0.5)); + in1x = v1x - off1x * bw; in1y = v1y - off1y * bw; + // var outer0 = outline ? cc.v2fadd(v0, cc.v2fmult(offset0, borderWidth)) : cc.v2fadd(v0, cc.v2fmult(offset0, 0.5)); + out0x = v0x + off0x * bw; out0y = v0y + off0y * bw; + // var outer1 = outline ? cc.v2fadd(v1, cc.v2fmult(offset1, borderWidth)) : cc.v2fadd(v1, cc.v2fmult(offset1, 0.5)); + out1x = v1x + off1x * bw; out1y = v1y + off1y * bw; + + // if (outline) { + // locBuffer.push(new cc.V2F_C4B_T2F_Triangle( + // {vertices: inner0, colors: borderColor, texCoords: cc.__t(cc.v2fneg(n0))}, + // {vertices: inner1, colors: borderColor, texCoords: cc.__t(cc.v2fneg(n0))}, + // {vertices: outer1, colors: borderColor, texCoords: cc.__t(n0)}, + // trianglesBuffer, locBuffer.length * triangleBytesLen)); + // locBuffer.push(new cc.V2F_C4B_T2F_Triangle( + // {vertices: inner0, colors: borderColor, texCoords: cc.__t(cc.v2fneg(n0))}, + // {vertices: outer0, colors: borderColor, texCoords: cc.__t(n0)}, + // {vertices: outer1, colors: borderColor, texCoords: cc.__t(n0)}, + // trianglesBuffer, locBuffer.length * triangleBytesLen)); + // } else { + // locBuffer.push(new cc.V2F_C4B_T2F_Triangle( + // {vertices: inner0, colors: fillColor, texCoords: cc.__t(cc.v2fzero())}, + // {vertices: inner1, colors: fillColor, texCoords: cc.__t(cc.v2fzero())}, + // {vertices: outer1, colors: fillColor, texCoords: cc.__t(n0)}, + // trianglesBuffer, locBuffer.length * triangleBytesLen)); + // locBuffer.push(new cc.V2F_C4B_T2F_Triangle( + // {vertices: inner0, colors: fillColor, texCoords: cc.__t(cc.v2fzero())}, + // {vertices: outer0, colors: fillColor, texCoords: cc.__t(n0)}, + // {vertices: outer1, colors: fillColor, texCoords: cc.__t(n0)}, + // trianglesBuffer, locBuffer.length * triangleBytesLen)); + // } + this.appendVertexData(in0x, in0y, color, _nw.x, _nw.y); + this.appendVertexData(in1x, in1y, color, _nw.x, _nw.y); + this.appendVertexData(out1x, out1y, color, _n.x, _n.y); + + this.appendVertexData(in0x, in0y, color, _nw.x, _nw.y); + this.appendVertexData(out0x, out0y, color, _n.x, _n.y); + this.appendVertexData(out1x, out1y, color, _n.x, _n.y); } - extrude = null; + _extrude.length = 0; + _vertices.length = 0; this._dirty = true; }, _drawSegments: function(verts, borderWidth, borderColor, closePoly){ borderWidth = (borderWidth == null) ? this._lineWidth : borderWidth; + if (borderWidth <= 0) + return; + borderColor = borderColor || this._drawColor; if(borderColor.a == null) borderColor.a = 255; borderWidth *= 0.5; - if (borderWidth <= 0) - return; - var c4bBorderColor = {r: 0 | borderColor.r, g: 0 | borderColor.g, b: 0 | borderColor.b, a: 0 | borderColor.a }; - var extrude = [], i, v0, v1, v2, count = verts.length; - for (i = 0; i < count; i++) { - v0 = cc.__v2f(verts[(i - 1 + count) % count]); - v1 = cc.__v2f(verts[i]); - v2 = cc.__v2f(verts[(i + 1) % count]); - var n1 = cc.v2fnormalize(cc.v2fperp(cc.v2fsub(v1, v0))); - var n2 = cc.v2fnormalize(cc.v2fperp(cc.v2fsub(v2, v1))); - var offset = cc.v2fmult(cc.v2fadd(n1, n2), 1.0 / (cc.v2fdot(n1, n2) + 1.0)); - extrude[i] = {offset: offset, n: n2}; + var v0x, v0y, v1x, v1y, v2x, v2y, + factor, offx, offy, + i, count = verts.length; + _extrude.length = 0; + for (i = 0; i < count; i += 2) { + v0x = verts[(i - 2 + count) % count]; + v0y = verts[(i - 1 + count) % count]; + v1x = verts[i]; + v1y = verts[i + 1]; + v2x = verts[(i + 2) % count]; + v2y = verts[(i + 3) % count]; + // var n1 = cc.v2fnormalize(cc.v2fperp(cc.v2fsub(v1, v0))); + // var n2 = cc.v2fnormalize(cc.v2fperp(cc.v2fsub(v2, v1))); + _n.x = v0y - v1y; _n.y = v1x - v0x; + _nw.x = v1y - v2y; _nw.y = v2x - v1x; + cc.pNormalizeIn(_n); + cc.pNormalizeIn(_nw); + // var offset = cc.v2fmult(cc.v2fadd(n1, n2), 1.0 / (cc.v2fdot(n1, n2) + 1.0)); + factor = _n.x * _nw.x + _n.y * _nw.y + 1; + offx = (_n.x + _nw.x) / factor; + offy = (_n.y + _nw.y) / factor; + // extrude[i] = {offset: offset, n: n2}; + _extrude.push(offx, offy, _nw.x, _nw.y); } + // The actual input vertex count + count = count / 2; var triangleCount = 3 * count - 2, vertexCount = 3 * triangleCount; - this._ensureCapacity(vertexCount); + var succeed = this._ensureCapacity(this._vertexCount + vertexCount); + if (!succeed) + return; - var triangleBytesLen = cc.V2F_C4B_T2F_Triangle.BYTES_PER_ELEMENT, trianglesBuffer = this._trianglesArrayBuffer; - var locBuffer = this._buffer; - var len = closePoly ? count : count - 1; + var len = closePoly ? count : count - 1, + off0x, off0y, off1x, off1y, + in0x, in0y, in1x, in1y, out0x, out0y, out1x, out1y; for (i = 0; i < len; i++) { var j = (i + 1) % count; - v0 = cc.__v2f(verts[i]); - v1 = cc.__v2f(verts[j]); - - var n0 = extrude[i].n; - var offset0 = extrude[i].offset; - var offset1 = extrude[j].offset; - var inner0 = cc.v2fsub(v0, cc.v2fmult(offset0, borderWidth)); - var inner1 = cc.v2fsub(v1, cc.v2fmult(offset1, borderWidth)); - var outer0 = cc.v2fadd(v0, cc.v2fmult(offset0, borderWidth)); - var outer1 = cc.v2fadd(v1, cc.v2fmult(offset1, borderWidth)); - locBuffer.push(new cc.V2F_C4B_T2F_Triangle({vertices: inner0, colors: c4bBorderColor, texCoords: cc.__t(cc.v2fneg(n0))}, - {vertices: inner1, colors: c4bBorderColor, texCoords: cc.__t(cc.v2fneg(n0))}, {vertices: outer1, colors: c4bBorderColor, texCoords: cc.__t(n0)}, - trianglesBuffer, locBuffer.length * triangleBytesLen)); - locBuffer.push(new cc.V2F_C4B_T2F_Triangle({vertices: inner0, colors: c4bBorderColor, texCoords: cc.__t(cc.v2fneg(n0))}, - {vertices: outer0, colors: c4bBorderColor, texCoords: cc.__t(n0)}, {vertices: outer1, colors: c4bBorderColor, texCoords: cc.__t(n0)}, - trianglesBuffer, locBuffer.length * triangleBytesLen)); + v0x = verts[i * 2]; + v0y = verts[i * 2 + 1]; + v1x = verts[j * 2]; + v1y = verts[j * 2 + 1]; + + _n.x = _extrude[i * 4 + 2]; + _n.y = _extrude[i * 4 + 3]; + off0x = _extrude[i * 4]; + off0y = _extrude[i * 4 + 1]; + off1x = _extrude[j * 4]; + off1y = _extrude[j * 4 + 1]; + // var inner0 = cc.v2fsub(v0, cc.v2fmult(offset0, borderWidth)); + in0x = v0x - off0x * borderWidth; in0y = v0y - off0y * borderWidth; + // var inner1 = cc.v2fsub(v1, cc.v2fmult(offset1, borderWidth)); + in1x = v1x - off1x * borderWidth; in1y = v1y - off1y * borderWidth; + // var outer0 = cc.v2fadd(v0, cc.v2fmult(offset0, borderWidth)); + out0x = v0x + off0x * borderWidth; out0y = v0y + off0y * borderWidth; + // var outer1 = cc.v2fadd(v1, cc.v2fmult(offset1, borderWidth)); + out1x = v1x + off1x * borderWidth; out1y = v1y + off1y * borderWidth; + // locBuffer.push(new cc.V2F_C4B_T2F_Triangle( + // {vertices: inner0, colors: c4bBorderColor, texCoords: cc.__t(cc.v2fneg(n0))}, + // {vertices: inner1, colors: c4bBorderColor, texCoords: cc.__t(cc.v2fneg(n0))}, + // {vertices: outer1, colors: c4bBorderColor, texCoords: cc.__t(n0)}, + // trianglesBuffer, locBuffer.length * triangleBytesLen)); + this.appendVertexData(in0x, in0y, borderColor, -_n.x, -_n.y); + this.appendVertexData(in1x, in1y, borderColor, -_n.x, -_n.y); + this.appendVertexData(out1x, out1y, borderColor, _n.x, _n.y); + + // locBuffer.push(new cc.V2F_C4B_T2F_Triangle( + // {vertices: inner0, colors: c4bBorderColor, texCoords: cc.__t(cc.v2fneg(n0))}, + // {vertices: outer0, colors: c4bBorderColor, texCoords: cc.__t(n0)}, + // {vertices: outer1, colors: c4bBorderColor, texCoords: cc.__t(n0)}, + // trianglesBuffer, locBuffer.length * triangleBytesLen)); + this.appendVertexData(in0x, in0y, borderColor, -_n.x, -_n.y); + this.appendVertexData(out0x, out0y, borderColor, _n.x, _n.y); + this.appendVertexData(out1x, out1y, borderColor, _n.x, _n.y); } - extrude = null; + _extrude.length = 0; this._dirty = true; }, clear:function () { - this._buffer.length = 0; + this.release(); this._dirty = true; }, diff --git a/cocos2d/shape-nodes/CCDrawNodeWebGLRenderCmd.js b/cocos2d/shape-nodes/CCDrawNodeWebGLRenderCmd.js index 55c2457772..468e13b56a 100644 --- a/cocos2d/shape-nodes/CCDrawNodeWebGLRenderCmd.js +++ b/cocos2d/shape-nodes/CCDrawNodeWebGLRenderCmd.js @@ -35,7 +35,7 @@ cc.DrawNode.WebGLRenderCmd.prototype.rendering = function (ctx) { var node = this._node; - if (node._buffer.length > 0) { + if (node._vertexCount > 0) { var wt = this._worldTransform; this._matrix.mat[0] = wt.a; this._matrix.mat[4] = wt.c; diff --git a/moduleConfig.json b/moduleConfig.json index cc5570bc42..652575fec6 100644 --- a/moduleConfig.json +++ b/moduleConfig.json @@ -72,6 +72,7 @@ "cocos2d/core/event-manager/CCEventManager.js", "cocos2d/core/event-manager/CCEventExtension.js", + "cocos2d/core/renderer/GlobalVertexBuffer.js", "cocos2d/core/renderer/RendererCanvas.js", "cocos2d/core/renderer/RendererWebGL.js", "cocos2d/core/renderer/DirtyRegion.js", From fbe6f6ba1a38153906ac58a3b16cacde5e04728f Mon Sep 17 00:00:00 2001 From: pandamicro Date: Fri, 18 Nov 2016 11:30:33 +0800 Subject: [PATCH 08/42] Remove useless comments --- cocos2d/shape-nodes/CCDrawNode.js | 178 ++++-------------------------- 1 file changed, 21 insertions(+), 157 deletions(-) diff --git a/cocos2d/shape-nodes/CCDrawNode.js b/cocos2d/shape-nodes/CCDrawNode.js index b8bcf09aa7..e6a4dfb80e 100644 --- a/cocos2d/shape-nodes/CCDrawNode.js +++ b/cocos2d/shape-nodes/CCDrawNode.js @@ -25,61 +25,6 @@ THE SOFTWARE. ****************************************************************************/ -/** - * Code copied & pasted from SpacePatrol game https://github.com/slembcke/SpacePatrol - * - * Renamed and added some changes for cocos2d - * - */ -// cc.v2fzero = function () { -// return {x: 0, y: 0}; -// }; - -// cc.v2f = function (x, y) { -// return {x: x, y: y}; -// }; - -// cc.v2fadd = function (v0, v1) { -// return cc.v2f(v0.x + v1.x, v0.y + v1.y); -// }; - -// cc.v2fsub = function (v0, v1) { -// return cc.v2f(v0.x - v1.x, v0.y - v1.y); -// }; - -// cc.v2fmult = function (v, s) { -// return cc.v2f(v.x * s, v.y * s); -// }; - -// cc.v2fperp = function (p0) { -// return cc.v2f(-p0.y, p0.x); -// }; - -// cc.v2fneg = function (p0) { -// return cc.v2f(-p0.x, -p0.y); -// }; - -// cc.v2fdot = function (p0, p1) { -// return p0.x * p1.x + p0.y * p1.y; -// }; - -// cc.v2fforangle = function (_a_) { -// return cc.v2f(Math.cos(_a_), Math.sin(_a_)); -// }; - -// cc.v2fnormalize = function (p) { -// var r = cc.pNormalize(cc.p(p.x, p.y)); -// return cc.v2f(r.x, r.y); -// }; - -// cc.__v2f = function (v) { -// return cc.v2f(v.x, v.y); -// }; - -// cc.__t = function (v) { -// return {u: v.x, v: v.y}; -// }; - /** *

CCDrawNode
* Node that draws dots, segments and polygons.
@@ -562,10 +507,6 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () { _f32Buffer: null, _ui32Buffer: null, - // _trianglesArrayBuffer:null, - // _trianglesWebBuffer:null, - // _trianglesReader:null, - _dirty: false, _className: "DrawNodeWebGL", @@ -847,85 +788,53 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () { if (!succeed) return; - // var a = cc.__v2f(from), b = cc.__v2f(to); var a = from, b = to; - // var n = cc.v2fnormalize(cc.v2fperp(cc.v2fsub(b, a))) + // var n = normalize(perp(sub(b, a))) _n.x = a.y - b.y; _n.y = b.x - a.x; cc.pNormalizeIn(_n); - // var t = cc.v2fperp(n); + // var t = perp(n); _t.x = -_n.y; _t.y = _n.x; - // var nw = cc.v2fmult(n, radius), tw = cc.v2fmult(t, radius); + // var nw = mult(n, radius), tw = mult(t, radius); pMultOut(_n, radius, _nw); pMultOut(_t, radius, _tw); - // var v0 = cc.v2fsub(b, cc.v2fadd(nw, tw)); uv0 = cc.__t(cc.v2fneg(cc.v2fadd(n, t))) + // var v0 = sub(b, add(nw, tw)); uv0 = neg(add(n, t)) var v0x = b.x - _nw.x - _tw.x, v0y = b.y - _nw.y - _tw.y, u0 = -(_n.x + _t.x), v0 = -(_n.y + _t.y); - // var v1 = cc.v2fadd(b, cc.v2fsub(nw, tw)); uv1 = cc.__t(cc.v2fsub(n, t)) + // var v1 = add(b, sub(nw, tw)); uv1 = sub(n, t) var v1x = b.x + _nw.x - _tw.x, v1y = b.y + _nw.y - _tw.y, u1 = _n.x - _t.x, v1 = _n.y - _t.y; - // var v2 = cc.v2fsub(b, nw); uv2 = cc.__t(cc.v2fneg(n)) + // var v2 = sub(b, nw); uv2 = neg(n) var v2x = b.x - _nw.x, v2y = b.y - _nw.y, u2 = -_n.x, v2 = -_n.y; - // var v3 = cc.v2fadd(b, nw); uv3 = cc.__t(n) + // var v3 = add(b, nw); uv3 = n var v3x = b.x + _nw.x, v3y = b.y + _nw.y, u3 = _n.x, v3 = _n.y; - // var v4 = cc.v2fsub(a, nw); uv4 = cc.__t(cc.v2fneg(n)) + // var v4 = sub(a, nw); uv4 = neg(n) var v4x = a.x - _nw.x, v4y = a.y - _nw.y, u4 = u2, v4 = v2; - // var v5 = cc.v2fadd(a, nw); uv5 = cc.__t(n) + // var v5 = add(a, nw); uv5 = n var v5x = a.x + _nw.x, v5y = a.y + _nw.y, u5 = _n.x, v5 = _n.y; - // var v6 = cc.v2fsub(a, cc.v2fsub(nw, tw)); uv6 = cc.__t(cc.v2fsub(t, n)) + // var v6 = sub(a, sub(nw, tw)); uv6 = sub(t, n) var v6x = a.x - _nw.x + _tw.x, v6y = a.y - _nw.y + _tw.y, u6 = _t.x - _n.x, v6 = _t.y - _n.y; - // var v7 = cc.v2fadd(a, cc.v2fadd(nw, tw)); uv7 = cc.__t(cc.v2fadd(n, t)) + // var v7 = add(a, add(nw, tw)); uv7 = add(n, t) var v7x = a.x + _nw.x + _tw.x, v7y = a.y + _nw.y + _tw.y, u7 = _n.x + _t.x, v7 = _n.y + _t.y; - // var TriangleLength = cc.V2F_C4B_T2F_Triangle.BYTES_PER_ELEMENT, triangleBuffer = this._trianglesArrayBuffer, locBuffer = this._buffer; - // locBuffer.push(new cc.V2F_C4B_T2F_Triangle( - // {vertices: v0, colors: c4bColor, texCoords: uv0}, - // {vertices: v1, colors: c4bColor, texCoords: uv1}, - // {vertices: v2, colors: c4bColor, texCoords: uv2}, - // triangleBuffer, locBuffer.length * TriangleLength)); this.appendVertexData(v0x, v0y, color, u0, v0); this.appendVertexData(v1x, v1y, color, u1, v1); this.appendVertexData(v2x, v2y, color, u2, v2); - // locBuffer.push(new cc.V2F_C4B_T2F_Triangle( - // {vertices: v3, colors: c4bColor, texCoords: uv3}, - // {vertices: v1, colors: c4bColor, texCoords: uv1}, - // {vertices: v2, colors: c4bColor, texCoords: uv2}, - // triangleBuffer, locBuffer.length * TriangleLength)); this.appendVertexData(v3x, v3y, color, u3, v3); this.appendVertexData(v1x, v1y, color, u1, v1); this.appendVertexData(v2x, v2y, color, u2, v2); - // locBuffer.push(new cc.V2F_C4B_T2F_Triangle( - // {vertices: v3, colors: c4bColor, texCoords: uv3}, - // {vertices: v4, colors: c4bColor, texCoords: uv4}, - // {vertices: v2, colors: c4bColor, texCoords: uv2}, - // triangleBuffer, locBuffer.length * TriangleLength)); this.appendVertexData(v3x, v3y, color, u3, v3); this.appendVertexData(v4x, v4y, color, u4, v4); this.appendVertexData(v2x, v2y, color, u2, v2); - // locBuffer.push(new cc.V2F_C4B_T2F_Triangle( - // {vertices: v3, colors: c4bColor, texCoords: uv3}, - // {vertices: v4, colors: c4bColor, texCoords: uv4}, - // {vertices: v5, colors: c4bColor, texCoords: uv5}, - // triangleBuffer, locBuffer.length * TriangleLength)); this.appendVertexData(v3x, v3y, color, u3, v3); this.appendVertexData(v4x, v4y, color, u4, v4); this.appendVertexData(v5x, v5y, color, u5, v5); - // locBuffer.push(new cc.V2F_C4B_T2F_Triangle( - // {vertices: v6, colors: c4bColor, texCoords: uv6}, - // {vertices: v4, colors: c4bColor, texCoords: uv4}, - // {vertices: v5, colors: c4bColor, texCoords: uv5}, - // triangleBuffer, locBuffer.length * TriangleLength)); this.appendVertexData(v6x, v6y, color, u6, v6); this.appendVertexData(v4x, v4y, color, u4, v4); this.appendVertexData(v5x, v5y, color, u5, v5); - // locBuffer.push(new cc.V2F_C4B_T2F_Triangle( - // {vertices: v6, colors: c4bColor, texCoords: uv6}, - // {vertices: v7, colors: c4bColor, texCoords: uv7}, - // {vertices: v5, colors: c4bColor, texCoords: uv5}, - // triangleBuffer, locBuffer.length * TriangleLength)); this.appendVertexData(v6x, v6y, color, u6, v6); this.appendVertexData(v7x, v7y, color, u7, v7); this.appendVertexData(v5x, v5y, color, u5, v5); @@ -963,13 +872,13 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () { v1y = verts[i + 1]; v2x = verts[(i + 2) % count]; v2y = verts[(i + 3) % count]; - // var n1 = cc.v2fnormalize(cc.v2fperp(cc.v2fsub(v1, v0))); - // var n2 = cc.v2fnormalize(cc.v2fperp(cc.v2fsub(v2, v1))); + // var n1 = normalize(perp(sub(v1, v0))); + // var n2 = normalize(perp(sub(v2, v1))); _n.x = v0y - v1y; _n.y = v1x - v0x; _nw.x = v1y - v2y; _nw.y = v2x - v1x; cc.pNormalizeIn(_n); cc.pNormalizeIn(_nw); - // var offset = cc.v2fmult(cc.v2fadd(n1, n2), 1.0 / (cc.v2fdot(n1, n2) + 1.0)); + // var offset = mult(add(n1, n2), 1.0 / (dot(n1, n2) + 1.0)); factor = _n.x * _nw.x + _n.y * _nw.y + 1; offx = (_n.x + _nw.x) / factor; offy = (_n.y + _nw.y) / factor; @@ -985,21 +894,16 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () { var inset = (outline == false ? 0.5 : 0.0); for (i = 0; i < count - 2; i++) { - // v0 = cc.v2fsub(cc.__v2f(verts[0]), cc.v2fmult(extrude[0].offset, inset)); + // v0 = sub(verts[0], multi(extrude[0].offset, inset)); v0x = verts[0] - _extrude[0] * inset; v0y = verts[1] - _extrude[1] * inset; - // v1 = cc.v2fsub(cc.__v2f(verts[i + 1]), cc.v2fmult(extrude[i + 1].offset, inset)); + // v1 = sub(verts[i + 1], multi(extrude[i + 1].offset, inset)); v1x = verts[i * 2 + 2] - _extrude[(i+1) * 4] * inset; v1y = verts[i * 2 + 3] - _extrude[(i+1) * 4 + 1] * inset; - // v2 = cc.v2fsub(cc.__v2f(verts[i + 2]), cc.v2fmult(extrude[i + 2].offset, inset)); + // v2 = sub(verts[i + 2], multi(extrude[i + 2].offset, inset)); v2x = verts[i * 2 + 4] - _extrude[(i+2) * 4] * inset; v2y = verts[i * 2 + 5] - _extrude[(i+2) * 4 + 1] * inset; - // locBuffer.push(new cc.V2F_C4B_T2F_Triangle( - // {vertices: v0, colors: c4bFillColor, texCoords: cc.__t(cc.v2fzero())}, - // {vertices: v1, colors: c4bFillColor, texCoords: cc.__t(cc.v2fzero())}, - // {vertices: v2, colors: c4bFillColor, texCoords: cc.__t(cc.v2fzero())}, - // trianglesBuffer, locBuffer.length * triangleBytesLen)); this.appendVertexData(v0x, v0y, fillColor, 0, 0); this.appendVertexData(v1x, v1y, fillColor, 0, 0); this.appendVertexData(v2x, v2y, fillColor, 0, 0); @@ -1025,38 +929,11 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () { off1x = _extrude[j * 4]; off1y = _extrude[j * 4 + 1]; - // var inner0 = outline ? cc.v2fsub(v0, cc.v2fmult(offset0, borderWidth)) : cc.v2fsub(v0, cc.v2fmult(offset0, 0.5)); in0x = v0x - off0x * bw; in0y = v0y - off0y * bw; - // var inner1 = outline ? cc.v2fsub(v1, cc.v2fmult(offset1, borderWidth)) : cc.v2fsub(v1, cc.v2fmult(offset1, 0.5)); in1x = v1x - off1x * bw; in1y = v1y - off1y * bw; - // var outer0 = outline ? cc.v2fadd(v0, cc.v2fmult(offset0, borderWidth)) : cc.v2fadd(v0, cc.v2fmult(offset0, 0.5)); out0x = v0x + off0x * bw; out0y = v0y + off0y * bw; - // var outer1 = outline ? cc.v2fadd(v1, cc.v2fmult(offset1, borderWidth)) : cc.v2fadd(v1, cc.v2fmult(offset1, 0.5)); out1x = v1x + off1x * bw; out1y = v1y + off1y * bw; - // if (outline) { - // locBuffer.push(new cc.V2F_C4B_T2F_Triangle( - // {vertices: inner0, colors: borderColor, texCoords: cc.__t(cc.v2fneg(n0))}, - // {vertices: inner1, colors: borderColor, texCoords: cc.__t(cc.v2fneg(n0))}, - // {vertices: outer1, colors: borderColor, texCoords: cc.__t(n0)}, - // trianglesBuffer, locBuffer.length * triangleBytesLen)); - // locBuffer.push(new cc.V2F_C4B_T2F_Triangle( - // {vertices: inner0, colors: borderColor, texCoords: cc.__t(cc.v2fneg(n0))}, - // {vertices: outer0, colors: borderColor, texCoords: cc.__t(n0)}, - // {vertices: outer1, colors: borderColor, texCoords: cc.__t(n0)}, - // trianglesBuffer, locBuffer.length * triangleBytesLen)); - // } else { - // locBuffer.push(new cc.V2F_C4B_T2F_Triangle( - // {vertices: inner0, colors: fillColor, texCoords: cc.__t(cc.v2fzero())}, - // {vertices: inner1, colors: fillColor, texCoords: cc.__t(cc.v2fzero())}, - // {vertices: outer1, colors: fillColor, texCoords: cc.__t(n0)}, - // trianglesBuffer, locBuffer.length * triangleBytesLen)); - // locBuffer.push(new cc.V2F_C4B_T2F_Triangle( - // {vertices: inner0, colors: fillColor, texCoords: cc.__t(cc.v2fzero())}, - // {vertices: outer0, colors: fillColor, texCoords: cc.__t(n0)}, - // {vertices: outer1, colors: fillColor, texCoords: cc.__t(n0)}, - // trianglesBuffer, locBuffer.length * triangleBytesLen)); - // } this.appendVertexData(in0x, in0y, color, _nw.x, _nw.y); this.appendVertexData(in1x, in1y, color, _nw.x, _nw.y); this.appendVertexData(out1x, out1y, color, _n.x, _n.y); @@ -1091,13 +968,13 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () { v1y = verts[i + 1]; v2x = verts[(i + 2) % count]; v2y = verts[(i + 3) % count]; - // var n1 = cc.v2fnormalize(cc.v2fperp(cc.v2fsub(v1, v0))); - // var n2 = cc.v2fnormalize(cc.v2fperp(cc.v2fsub(v2, v1))); + // var n1 = normalize(perp(sub(v1, v0))); + // var n2 = normalize(perp(sub(v2, v1))); _n.x = v0y - v1y; _n.y = v1x - v0x; _nw.x = v1y - v2y; _nw.y = v2x - v1x; cc.pNormalizeIn(_n); cc.pNormalizeIn(_nw); - // var offset = cc.v2fmult(cc.v2fadd(n1, n2), 1.0 / (cc.v2fdot(n1, n2) + 1.0)); + // var offset = multi(add(n1, n2), 1.0 / (dot(n1, n2) + 1.0)); factor = _n.x * _nw.x + _n.y * _nw.y + 1; offx = (_n.x + _nw.x) / factor; offy = (_n.y + _nw.y) / factor; @@ -1128,28 +1005,15 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () { off0y = _extrude[i * 4 + 1]; off1x = _extrude[j * 4]; off1y = _extrude[j * 4 + 1]; - // var inner0 = cc.v2fsub(v0, cc.v2fmult(offset0, borderWidth)); in0x = v0x - off0x * borderWidth; in0y = v0y - off0y * borderWidth; - // var inner1 = cc.v2fsub(v1, cc.v2fmult(offset1, borderWidth)); in1x = v1x - off1x * borderWidth; in1y = v1y - off1y * borderWidth; - // var outer0 = cc.v2fadd(v0, cc.v2fmult(offset0, borderWidth)); out0x = v0x + off0x * borderWidth; out0y = v0y + off0y * borderWidth; - // var outer1 = cc.v2fadd(v1, cc.v2fmult(offset1, borderWidth)); out1x = v1x + off1x * borderWidth; out1y = v1y + off1y * borderWidth; - // locBuffer.push(new cc.V2F_C4B_T2F_Triangle( - // {vertices: inner0, colors: c4bBorderColor, texCoords: cc.__t(cc.v2fneg(n0))}, - // {vertices: inner1, colors: c4bBorderColor, texCoords: cc.__t(cc.v2fneg(n0))}, - // {vertices: outer1, colors: c4bBorderColor, texCoords: cc.__t(n0)}, - // trianglesBuffer, locBuffer.length * triangleBytesLen)); + this.appendVertexData(in0x, in0y, borderColor, -_n.x, -_n.y); this.appendVertexData(in1x, in1y, borderColor, -_n.x, -_n.y); this.appendVertexData(out1x, out1y, borderColor, _n.x, _n.y); - // locBuffer.push(new cc.V2F_C4B_T2F_Triangle( - // {vertices: inner0, colors: c4bBorderColor, texCoords: cc.__t(cc.v2fneg(n0))}, - // {vertices: outer0, colors: c4bBorderColor, texCoords: cc.__t(n0)}, - // {vertices: outer1, colors: c4bBorderColor, texCoords: cc.__t(n0)}, - // trianglesBuffer, locBuffer.length * triangleBytesLen)); this.appendVertexData(in0x, in0y, borderColor, -_n.x, -_n.y); this.appendVertexData(out0x, out0y, borderColor, _n.x, _n.y); this.appendVertexData(out1x, out1y, borderColor, _n.x, _n.y); From 28d62b240117b8a0afab3547686449732b27caee Mon Sep 17 00:00:00 2001 From: pandamicro Date: Fri, 18 Nov 2016 11:54:21 +0800 Subject: [PATCH 09/42] Improve Action System by reducing memory usage --- cocos2d/actions/CCActionInterval.js | 323 ++++++++++++++-------------- cocos2d/core/CCActionManager.js | 51 +++-- 2 files changed, 199 insertions(+), 175 deletions(-) diff --git a/cocos2d/actions/CCActionInterval.js b/cocos2d/actions/CCActionInterval.js index 930cb1e021..351df14bf2 100644 --- a/cocos2d/actions/CCActionInterval.js +++ b/cocos2d/actions/CCActionInterval.js @@ -53,10 +53,10 @@ cc.ActionInterval = cc.FiniteTimeAction.extend(/** @lends cc.ActionInterval# */{ _speed: 1, _speedMethod: false,//Compatible with speed class, Discard after can be deleted - /** + /** * Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function. - * @param {Number} d duration in seconds - */ + * @param {Number} d duration in seconds + */ ctor:function (d) { this._speed = 1; this._timesForRepeat = 1; @@ -65,7 +65,7 @@ cc.ActionInterval = cc.FiniteTimeAction.extend(/** @lends cc.ActionInterval# */{ this._repeatMethod = false;//Compatible with repeat class, Discard after can be deleted this._speedMethod = false;//Compatible with repeat class, Discard after can be deleted cc.FiniteTimeAction.prototype.ctor.call(this); - d !== undefined && this.initWithDuration(d); + d !== undefined && this.initWithDuration(d); }, /** @@ -343,19 +343,19 @@ cc.Sequence = cc.ActionInterval.extend(/** @lends cc.Sequence# */{ _split:null, _last:0, - /** + /** * Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function.
* Create an array of sequenceable actions. - * @param {Array|cc.FiniteTimeAction} tempArray - */ + * @param {Array|cc.FiniteTimeAction} tempArray + */ ctor:function (tempArray) { cc.ActionInterval.prototype.ctor.call(this); this._actions = []; - var paramArray = (tempArray instanceof Array) ? tempArray : arguments; - var last = paramArray.length - 1; - if ((last >= 0) && (paramArray[last] == null)) - cc.log("parameters should not be ending with null in Javascript"); + var paramArray = (tempArray instanceof Array) ? tempArray : arguments; + var last = paramArray.length - 1; + if ((last >= 0) && (paramArray[last] == null)) + cc.log("parameters should not be ending with null in Javascript"); if (last >= 0) { var prev = paramArray[0], action1; @@ -561,16 +561,16 @@ cc.Repeat = cc.ActionInterval.extend(/** @lends cc.Repeat# */{ _actionInstant:false, _innerAction:null, //CCFiniteTimeAction - /** + /** * Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function.
- * Creates a Repeat action. Times is an unsigned integer between 1 and pow(2,30). - * @param {cc.FiniteTimeAction} action - * @param {Number} times - */ + * Creates a Repeat action. Times is an unsigned integer between 1 and pow(2,30). + * @param {cc.FiniteTimeAction} action + * @param {Number} times + */ ctor: function (action, times) { cc.ActionInterval.prototype.ctor.call(this); - times !== undefined && this.initWithAction(action, times); + times !== undefined && this.initWithAction(action, times); }, /** @@ -740,16 +740,16 @@ cc.Repeat.create = cc.repeat; cc.RepeatForever = cc.ActionInterval.extend(/** @lends cc.RepeatForever# */{ _innerAction:null, //CCActionInterval - /** + /** * Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function.
- * Create a acton which repeat forever. - * @param {cc.FiniteTimeAction} action - */ + * Create a acton which repeat forever. + * @param {cc.FiniteTimeAction} action + */ ctor:function (action) { cc.ActionInterval.prototype.ctor.call(this); this._innerAction = null; - action && this.initWithAction(action); + action && this.initWithAction(action); }, /** @@ -875,23 +875,32 @@ cc.Spawn = cc.ActionInterval.extend(/** @lends cc.Spawn# */{ _one:null, _two:null, - /** + /** * Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function. - * @param {Array|cc.FiniteTimeAction} tempArray - */ + * @param {Array|cc.FiniteTimeAction} tempArray + */ ctor:function (tempArray) { cc.ActionInterval.prototype.ctor.call(this); this._one = null; this._two = null; - var paramArray = (tempArray instanceof Array) ? tempArray : arguments; - var last = paramArray.length - 1; - if ((last >= 0) && (paramArray[last] == null)) - cc.log("parameters should not be ending with null in Javascript"); + var i, paramArray, last; + if (tempArray instanceof Array) { + paramArray = tempArray; + } + else { + paramArray = new Array(arguments.length); + for (i = 0; i < arguments.length; ++i) { + paramArray[i] = arguments[i]; + } + } + last = paramArray.length - 1; + if ((last >= 0) && (paramArray[last] == null)) + cc.log("parameters should not be ending with null in Javascript"); if (last >= 0) { var prev = paramArray[0], action1; - for (var i = 1; i < last; i++) { + for (i = 1; i < last; i++) { if (paramArray[i]) { action1 = prev; prev = cc.Spawn._actionOneTwo(action1, paramArray[i]); @@ -1051,17 +1060,17 @@ cc.RotateTo = cc.ActionInterval.extend(/** @lends cc.RotateTo# */{ _startAngleY:0, _diffAngleY:0, - /** + /** * Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function.
- * Creates a RotateTo action with x and y rotation angles. - * @param {Number} duration duration in seconds - * @param {Number} deltaAngleX deltaAngleX in degrees. - * @param {Number} [deltaAngleY] deltaAngleY in degrees. - */ + * Creates a RotateTo action with x and y rotation angles. + * @param {Number} duration duration in seconds + * @param {Number} deltaAngleX deltaAngleX in degrees. + * @param {Number} [deltaAngleY] deltaAngleY in degrees. + */ ctor:function (duration, deltaAngleX, deltaAngleY) { cc.ActionInterval.prototype.ctor.call(this); - deltaAngleX !== undefined && this.initWithDuration(duration, deltaAngleX, deltaAngleY); + deltaAngleX !== undefined && this.initWithDuration(duration, deltaAngleX, deltaAngleY); }, /** @@ -1187,16 +1196,16 @@ cc.RotateBy = cc.ActionInterval.extend(/** @lends cc.RotateBy# */{ _angleY:0, _startAngleY:0, - /** + /** * Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function. - * @param {Number} duration duration in seconds - * @param {Number} deltaAngleX deltaAngleX in degrees - * @param {Number} [deltaAngleY] deltaAngleY in degrees - */ + * @param {Number} duration duration in seconds + * @param {Number} deltaAngleX deltaAngleX in degrees + * @param {Number} [deltaAngleY] deltaAngleY in degrees + */ ctor: function (duration, deltaAngleX, deltaAngleY) { cc.ActionInterval.prototype.ctor.call(this); - deltaAngleX !== undefined && this.initWithDuration(duration, deltaAngleX, deltaAngleY); + deltaAngleX !== undefined && this.initWithDuration(duration, deltaAngleX, deltaAngleY); }, /** @@ -1309,12 +1318,12 @@ cc.MoveBy = cc.ActionInterval.extend(/** @lends cc.MoveBy# */{ _startPosition:null, _previousPosition:null, - /** + /** * Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function. - * @param {Number} duration duration in seconds - * @param {cc.Point|Number} deltaPos - * @param {Number} [deltaY] - */ + * @param {Number} duration duration in seconds + * @param {cc.Point|Number} deltaPos + * @param {Number} [deltaY] + */ ctor:function (duration, deltaPos, deltaY) { cc.ActionInterval.prototype.ctor.call(this); @@ -1322,7 +1331,7 @@ cc.MoveBy = cc.ActionInterval.extend(/** @lends cc.MoveBy# */{ this._startPosition = cc.p(0, 0); this._previousPosition = cc.p(0, 0); - deltaPos !== undefined && this.initWithDuration(duration, deltaPos, deltaY); + deltaPos !== undefined && this.initWithDuration(duration, deltaPos, deltaY); }, /** @@ -1334,10 +1343,10 @@ cc.MoveBy = cc.ActionInterval.extend(/** @lends cc.MoveBy# */{ */ initWithDuration:function (duration, position, y) { if (cc.ActionInterval.prototype.initWithDuration.call(this, duration)) { - if(position.x !== undefined) { - y = position.y; - position = position.x; - } + if(position.x !== undefined) { + y = position.y; + position = position.x; + } this._positionDelta.x = position; this._positionDelta.y = y; @@ -1390,9 +1399,9 @@ cc.MoveBy = cc.ActionInterval.extend(/** @lends cc.MoveBy# */{ locStartPosition.y = locStartPosition.y + targetY - locPreviousPosition.y; x = x + locStartPosition.x; y = y + locStartPosition.y; - locPreviousPosition.x = x; - locPreviousPosition.y = y; - this.target.setPosition(x, y); + locPreviousPosition.x = x; + locPreviousPosition.y = y; + this.target.setPosition(x, y); } else { this.target.setPosition(locStartPosition.x + x, locStartPosition.y + y); } @@ -1454,17 +1463,17 @@ cc.MoveBy.create = cc.moveBy; cc.MoveTo = cc.MoveBy.extend(/** @lends cc.MoveTo# */{ _endPosition:null, - /** + /** * Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function. - * @param {Number} duration duration in seconds - * @param {cc.Point|Number} position - * @param {Number} y - */ + * @param {Number} duration duration in seconds + * @param {cc.Point|Number} position + * @param {Number} y + */ ctor:function (duration, position, y) { cc.MoveBy.prototype.ctor.call(this); this._endPosition = cc.p(0, 0); - position !== undefined && this.initWithDuration(duration, position, y); + position !== undefined && this.initWithDuration(duration, position, y); }, /** @@ -1476,10 +1485,10 @@ cc.MoveTo = cc.MoveBy.extend(/** @lends cc.MoveTo# */{ */ initWithDuration:function (duration, position, y) { if (cc.MoveBy.prototype.initWithDuration.call(this, duration, position, y)) { - if(position.x !== undefined) { - y = position.y; - position = position.x; - } + if(position.x !== undefined) { + y = position.y; + position = position.x; + } this._endPosition.x = position; this._endPosition.y = y; @@ -1557,16 +1566,16 @@ cc.SkewTo = cc.ActionInterval.extend(/** @lends cc.SkewTo# */{ _deltaX:0, _deltaY:0, - /** + /** * Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function. - * @param {Number} t time in seconds - * @param {Number} sx - * @param {Number} sy - */ + * @param {Number} t time in seconds + * @param {Number} sx + * @param {Number} sy + */ ctor: function (t, sx, sy) { cc.ActionInterval.prototype.ctor.call(this); - sy !== undefined && this.initWithDuration(t, sx, sy); + sy !== undefined && this.initWithDuration(t, sx, sy); }, /** @@ -1669,16 +1678,16 @@ cc.SkewTo.create = cc.skewTo; */ cc.SkewBy = cc.SkewTo.extend(/** @lends cc.SkewBy# */{ - /** + /** * Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function. - * @param {Number} t time in seconds - * @param {Number} sx skew in degrees for X axis - * @param {Number} sy skew in degrees for Y axis - */ - ctor: function(t, sx, sy) { - cc.SkewTo.prototype.ctor.call(this); - sy !== undefined && this.initWithDuration(t, sx, sy); - }, + * @param {Number} t time in seconds + * @param {Number} sx skew in degrees for X axis + * @param {Number} sy skew in degrees for Y axis + */ + ctor: function(t, sx, sy) { + cc.SkewTo.prototype.ctor.call(this); + sy !== undefined && this.initWithDuration(t, sx, sy); + }, /** * Initializes the action. @@ -1782,21 +1791,21 @@ cc.JumpBy = cc.ActionInterval.extend(/** @lends cc.JumpBy# */{ _jumps:0, _previousPosition:null, - /** + /** * Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function. - * @param {Number} duration - * @param {cc.Point|Number} position - * @param {Number} [y] - * @param {Number} height - * @param {Number} jumps - */ + * @param {Number} duration + * @param {cc.Point|Number} position + * @param {Number} [y] + * @param {Number} height + * @param {Number} jumps + */ ctor:function (duration, position, y, height, jumps) { cc.ActionInterval.prototype.ctor.call(this); this._startPosition = cc.p(0, 0); this._previousPosition = cc.p(0, 0); this._delta = cc.p(0, 0); - height !== undefined && this.initWithDuration(duration, position, y, height, jumps); + height !== undefined && this.initWithDuration(duration, position, y, height, jumps); }, /** * Initializes the action. @@ -1812,12 +1821,12 @@ cc.JumpBy = cc.ActionInterval.extend(/** @lends cc.JumpBy# */{ */ initWithDuration:function (duration, position, y, height, jumps) { if (cc.ActionInterval.prototype.initWithDuration.call(this, duration)) { - if (jumps === undefined) { - jumps = height; - height = y; - y = position.y; - position = position.x; - } + if (jumps === undefined) { + jumps = height; + height = y; + y = position.y; + position = position.x; + } this._delta.x = position; this._delta.y = y; this._height = height; @@ -1874,9 +1883,9 @@ cc.JumpBy = cc.ActionInterval.extend(/** @lends cc.JumpBy# */{ locStartPosition.y = locStartPosition.y + targetY - locPreviousPosition.y; x = x + locStartPosition.x; y = y + locStartPosition.y; - locPreviousPosition.x = x; - locPreviousPosition.y = y; - this.target.setPosition(x, y); + locPreviousPosition.x = x; + locPreviousPosition.y = y; + this.target.setPosition(x, y); } else { this.target.setPosition(locStartPosition.x + x, locStartPosition.y + y); } @@ -2069,18 +2078,18 @@ cc.BezierBy = cc.ActionInterval.extend(/** @lends cc.BezierBy# */{ _startPosition:null, _previousPosition:null, - /** + /** * Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function. - * @param {Number} t time in seconds - * @param {Array} c Array of points - */ + * @param {Number} t time in seconds + * @param {Array} c Array of points + */ ctor:function (t, c) { cc.ActionInterval.prototype.ctor.call(this); this._config = []; this._startPosition = cc.p(0, 0); this._previousPosition = cc.p(0, 0); - c && this.initWithDuration(t, c); + c && this.initWithDuration(t, c); }, /** @@ -2158,9 +2167,9 @@ cc.BezierBy = cc.ActionInterval.extend(/** @lends cc.BezierBy# */{ locStartPosition.y = locStartPosition.y + targetY - locPreviousPosition.y; x = x + locStartPosition.x; y = y + locStartPosition.y; - locPreviousPosition.x = x; - locPreviousPosition.y = y; - this.target.setPosition(x, y); + locPreviousPosition.x = x; + locPreviousPosition.y = y; + this.target.setPosition(x, y); } else { this.target.setPosition(locStartPosition.x + x, locStartPosition.y + y); } @@ -2224,16 +2233,16 @@ cc.BezierBy.create = cc.bezierBy; cc.BezierTo = cc.BezierBy.extend(/** @lends cc.BezierTo# */{ _toConfig:null, - /** + /** * Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function. - * @param {Number} t - * @param {Array} c array of points - * var bezierTo = new cc.BezierTo(2, bezier); - */ + * @param {Number} t + * @param {Array} c array of points + * var bezierTo = new cc.BezierTo(2, bezier); + */ ctor:function (t, c) { cc.BezierBy.prototype.ctor.call(this); this._toConfig = []; - c && this.initWithDuration(t, c); + c && this.initWithDuration(t, c); }, /** @@ -2325,15 +2334,15 @@ cc.ScaleTo = cc.ActionInterval.extend(/** @lends cc.ScaleTo# */{ _deltaX:0, _deltaY:0, - /** + /** * Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function. - * @param {Number} duration - * @param {Number} sx scale parameter in X - * @param {Number} [sy] scale parameter in Y, if Null equal to sx - */ + * @param {Number} duration + * @param {Number} sx scale parameter in X + * @param {Number} [sy] scale parameter in Y, if Null equal to sx + */ ctor:function (duration, sx, sy) { cc.ActionInterval.prototype.ctor.call(this); - sx !== undefined && this.initWithDuration(duration, sx, sy); + sx !== undefined && this.initWithDuration(duration, sx, sy); }, /** @@ -2383,7 +2392,7 @@ cc.ScaleTo = cc.ActionInterval.extend(/** @lends cc.ScaleTo# */{ dt = this._computeEaseTime(dt); if (this.target) { this.target.scaleX = this._startScaleX + this._deltaX * dt; - this.target.scaleY = this._startScaleY + this._deltaY * dt; + this.target.scaleY = this._startScaleY + this._deltaY * dt; } } }); @@ -2499,14 +2508,14 @@ cc.Blink = cc.ActionInterval.extend(/** @lends cc.Blink# */{ _times:0, _originalState:false, - /** + /** * Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function. * @param {Number} duration duration in seconds - * @param {Number} blinks blinks in times - */ + * @param {Number} blinks blinks in times + */ ctor:function (duration, blinks) { cc.ActionInterval.prototype.ctor.call(this); - blinks !== undefined && this.initWithDuration(duration, blinks); + blinks !== undefined && this.initWithDuration(duration, blinks); }, /** @@ -2612,14 +2621,14 @@ cc.FadeTo = cc.ActionInterval.extend(/** @lends cc.FadeTo# */{ _toOpacity:0, _fromOpacity:0, - /** + /** * Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function. - * @param {Number} duration - * @param {Number} opacity 0-255, 0 is transparent - */ + * @param {Number} duration + * @param {Number} opacity 0-255, 0 is transparent + */ ctor:function (duration, opacity) { cc.ActionInterval.prototype.ctor.call(this); - opacity !== undefined && this.initWithDuration(duration, opacity); + opacity !== undefined && this.initWithDuration(duration, opacity); }, /** @@ -2849,19 +2858,19 @@ cc.TintTo = cc.ActionInterval.extend(/** @lends cc.TintTo# */{ _to:null, _from:null, - /** + /** * Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function. - * @param {Number} duration - * @param {Number} red 0-255 - * @param {Number} green 0-255 - * @param {Number} blue 0-255 - */ + * @param {Number} duration + * @param {Number} red 0-255 + * @param {Number} green 0-255 + * @param {Number} blue 0-255 + */ ctor:function (duration, red, green, blue) { cc.ActionInterval.prototype.ctor.call(this); this._to = cc.color(0, 0, 0); this._from = cc.color(0, 0, 0); - blue !== undefined && this.initWithDuration(duration, red, green, blue); + blue !== undefined && this.initWithDuration(duration, red, green, blue); }, /** @@ -2969,16 +2978,16 @@ cc.TintBy = cc.ActionInterval.extend(/** @lends cc.TintBy# */{ _fromG:0, _fromB:0, - /** + /** * Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function. - * @param {Number} duration duration in seconds - * @param {Number} deltaRed - * @param {Number} deltaGreen - * @param {Number} deltaBlue - */ + * @param {Number} duration duration in seconds + * @param {Number} deltaRed + * @param {Number} deltaGreen + * @param {Number} deltaBlue + */ ctor:function (duration, deltaRed, deltaGreen, deltaBlue) { cc.ActionInterval.prototype.ctor.call(this); - deltaBlue !== undefined && this.initWithDuration(duration, deltaRed, deltaGreen, deltaBlue); + deltaBlue !== undefined && this.initWithDuration(duration, deltaRed, deltaGreen, deltaBlue); }, /** @@ -3152,15 +3161,15 @@ cc.DelayTime.create = cc.delayTime; cc.ReverseTime = cc.ActionInterval.extend(/** @lends cc.ReverseTime# */{ _other:null, - /** + /** * Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function. - * @param {cc.FiniteTimeAction} action - */ + * @param {cc.FiniteTimeAction} action + */ ctor:function (action) { cc.ActionInterval.prototype.ctor.call(this); this._other = null; - action && this.initWithAction(action); + action && this.initWithAction(action); }, /** @@ -3267,16 +3276,16 @@ cc.Animate = cc.ActionInterval.extend(/** @lends cc.Animate# */{ _splitTimes: null, _currFrameIndex:0, - /** + /** * Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function.
- * create the animate with animation. - * @param {cc.Animation} animation - */ + * create the animate with animation. + * @param {cc.Animation} animation + */ ctor:function (animation) { cc.ActionInterval.prototype.ctor.call(this); this._splitTimes = []; - animation && this.initWithAnimation(animation); + animation && this.initWithAnimation(animation); }, /** @@ -3466,15 +3475,15 @@ cc.TargetedAction = cc.ActionInterval.extend(/** @lends cc.TargetedAction# */{ _action:null, _forcedTarget:null, - /** + /** * Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function.
- * Create an action with the specified action and forced target. - * @param {cc.Node} target - * @param {cc.FiniteTimeAction} action - */ + * Create an action with the specified action and forced target. + * @param {cc.Node} target + * @param {cc.FiniteTimeAction} action + */ ctor: function (target, action) { cc.ActionInterval.prototype.ctor.call(this); - action && this.initWithTarget(target, action); + action && this.initWithTarget(target, action); }, /** diff --git a/cocos2d/core/CCActionManager.js b/cocos2d/core/CCActionManager.js index fd6e7d19b1..f3c90b46ab 100644 --- a/cocos2d/core/CCActionManager.js +++ b/cocos2d/core/CCActionManager.js @@ -37,7 +37,6 @@ cc.HashElement = cc.Class.extend(/** @lends cc.HashElement# */{ currentAction:null, //CCAction currentActionSalvaged:false, paused:false, - hh:null, //ut hash handle /** * Constructor */ @@ -48,7 +47,6 @@ cc.HashElement = cc.Class.extend(/** @lends cc.HashElement# */{ this.currentAction = null; //CCAction this.currentActionSalvaged = false; this.paused = false; - this.hh = null; //ut hash handle } }); @@ -70,6 +68,7 @@ cc.ActionManager = cc.Class.extend(/** @lends cc.ActionManager# */{ _arrayTargets:null, _currentTarget:null, _currentTargetSalvaged:false, + _elementPool: [], _searchElementByTarget:function (arr, target) { for (var k = 0; k < arr.length; k++) { @@ -86,6 +85,25 @@ cc.ActionManager = cc.Class.extend(/** @lends cc.ActionManager# */{ this._currentTargetSalvaged = false; }, + _getElement: function (target, paused) { + var element = this._elementPool.pop(); + if (!element) { + element = new cc.HashElement(); + } + element.target = target; + element.paused = !!paused; + return element; + }, + + _putElement: function (element) { + element.actions.length = 0; + element.actionIndex = 0; + element.currentAction = null; + element.currentActionSalvaged = false; + element.paused = false; + this._elementPool.push(element); + }, + /** Adds an action with a target. * If the target is already present, then the action will be added to the existing target. * If the target is not present, a new instance of this target will be created either paused or not, and the action will be added to the newly created target. @@ -104,14 +122,13 @@ cc.ActionManager = cc.Class.extend(/** @lends cc.ActionManager# */{ var element = this._hashTargets[target.__instanceId]; //if doesn't exists, create a hashelement and push in mpTargets if (!element) { - element = new cc.HashElement(); - element.paused = paused; - element.target = target; + element = this._getElement(target, paused); this._hashTargets[target.__instanceId] = element; this._arrayTargets.push(element); } - //creates a array for that eleemnt to hold the actions - this._actionAllocWithHashElement(element); + else if (!element.actions) { + element.actions = []; + } element.actions.push(action); action.startWithTarget(target); @@ -315,24 +332,22 @@ cc.ActionManager = cc.Class.extend(/** @lends cc.ActionManager# */{ _deleteHashElement:function (element) { var ret = false; if (element) { - if(this._hashTargets[element.target.__instanceId]){ + if (this._hashTargets[element.target.__instanceId]) { delete this._hashTargets[element.target.__instanceId]; - cc.arrayRemoveObject(this._arrayTargets, element); + var targets = this._arrayTargets; + for (var i = 0, l = targets.length; i < l; i++) { + if (targets[i] === element) { + targets.splice(i, 1); + break; + } + } + this._putElement(element); ret = true; } - element.actions = null; - element.target = null; } return ret; }, - _actionAllocWithHashElement:function (element) { - // 4 actions per Node by default - if (element.actions == null) { - element.actions = []; - } - }, - /** * @param {Number} dt delta time in seconds */ From 5ba285ef05dd361b156c26539b75c23a0dd0f1ea Mon Sep 17 00:00:00 2001 From: pandamicro Date: Fri, 18 Nov 2016 11:55:32 +0800 Subject: [PATCH 10/42] Improve render command syncStatus logic --- cocos2d/clipping-nodes/CCClippingNode.js | 6 ++++-- .../clipping-nodes/CCClippingNodeCanvasRenderCmd.js | 4 ++-- cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js | 12 +++--------- cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js | 2 +- cocos2d/core/layers/CCLayerCanvasRenderCmd.js | 11 ++++++----- cocos2d/core/layers/CCLayerWebGLRenderCmd.js | 4 ++-- cocos2d/parallax/CCParallaxNodeRenderCmd.js | 4 ++-- .../progress-timer/CCProgressTimerCanvasRenderCmd.js | 12 ++++++------ .../progress-timer/CCProgressTimerWebGLRenderCmd.js | 12 ++++++------ .../base-classes/UIScale9SpriteCanvasRenderCmd.js | 2 +- .../base-classes/UIScale9SpriteWebGLRenderCmd.js | 2 +- 11 files changed, 34 insertions(+), 37 deletions(-) diff --git a/cocos2d/clipping-nodes/CCClippingNode.js b/cocos2d/clipping-nodes/CCClippingNode.js index a9f301a658..64b1aba11c 100644 --- a/cocos2d/clipping-nodes/CCClippingNode.js +++ b/cocos2d/clipping-nodes/CCClippingNode.js @@ -90,7 +90,8 @@ cc.ClippingNode = cc.Node.extend(/** @lends cc.ClippingNode# */{ */ onEnter: function () { cc.Node.prototype.onEnter.call(this); - this._stencil.onEnter(); + if (this._stencil) + this._stencil.onEnter(); }, /** @@ -103,7 +104,8 @@ cc.ClippingNode = cc.Node.extend(/** @lends cc.ClippingNode# */{ */ onEnterTransitionDidFinish: function () { cc.Node.prototype.onEnterTransitionDidFinish.call(this); - this._stencil.onEnterTransitionDidFinish(); + if (this._stencil) + this._stencil.onEnterTransitionDidFinish(); }, /** diff --git a/cocos2d/clipping-nodes/CCClippingNodeCanvasRenderCmd.js b/cocos2d/clipping-nodes/CCClippingNodeCanvasRenderCmd.js index 3227b1d20c..c20d973217 100644 --- a/cocos2d/clipping-nodes/CCClippingNodeCanvasRenderCmd.js +++ b/cocos2d/clipping-nodes/CCClippingNodeCanvasRenderCmd.js @@ -178,6 +178,7 @@ this._curLevel = parentCmd._curLevel + 1; var transformRenderCmd = this; + this._syncStatus(parentCmd); // Composition mode, costy but support texture stencil this._clipElemType = !(!this._cangodhelpme() && node._stencil instanceof cc.DrawNode); if (!node._stencil || !node._stencil.visible) { @@ -186,7 +187,6 @@ return; } - this._syncStatus(parentCmd); cc.renderer.pushRenderCommand(this._rendererSaveCmd); if(this._clipElemType){ // Draw everything first using node visit function @@ -220,4 +220,4 @@ cc.ClippingNode.CanvasRenderCmd._getSharedCache = function () { return (cc.ClippingNode.CanvasRenderCmd._sharedCache) || (cc.ClippingNode.CanvasRenderCmd._sharedCache = document.createElement("canvas")); }; -})(); \ No newline at end of file +})(); diff --git a/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js b/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js index 27ed094b7b..080ff295e2 100644 --- a/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js +++ b/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js @@ -451,13 +451,6 @@ cc.Node.RenderCmd.prototype = { // In the visit logic does not restore the _dirtyFlag // Because child elements need parent's _dirtyFlag to change himself var locFlag = this._dirtyFlag, parentNode = null; - if (parentCmd) { - parentNode = parentCmd._node; - this._savedDirtyFlag = this._savedDirtyFlag || parentCmd._savedDirtyFlag || locFlag; - } - else { - this._savedDirtyFlag = this._savedDirtyFlag || locFlag; - } // There is a possibility: // The parent element changed color, child element not change @@ -474,11 +467,11 @@ cc.Node.RenderCmd.prototype = { if (parentCmd && (parentCmd._dirtyFlag & dirtyFlags.transformDirty)) locFlag |= dirtyFlags.transformDirty; + this._dirtyFlag = locFlag; + var colorDirty = locFlag & dirtyFlags.colorDirty, opacityDirty = locFlag & dirtyFlags.opacityDirty; - this._dirtyFlag = locFlag; - if (colorDirty) //update the color this._syncDisplayColor(); @@ -529,6 +522,7 @@ cc.Node.RenderCmd.prototype = { cc.Node.RenderCmd.prototype.originVisit = cc.Node.RenderCmd.prototype.visit; cc.Node.RenderCmd.prototype.originTransform = cc.Node.RenderCmd.prototype.transform; +cc.Node.RenderCmd.prototype._originSyncStatus = cc.Node.RenderCmd.prototype._syncStatus; //-----------------------Canvas --------------------------- diff --git a/cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js b/cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js index 31109f2f9b..da903bc689 100644 --- a/cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js +++ b/cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js @@ -339,7 +339,7 @@ cc.LabelTTF._firsrEnglish = /^[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]/; if (locFlag & flags.textDirty) this._updateTexture(); - cc.Node.RenderCmd.prototype._syncStatus.call(this, parentCmd); + this._originSyncStatus(parentCmd); if (cc._renderType === cc.game.RENDER_TYPE_WEBGL || locFlag & flags.transformDirty) this.transform(parentCmd); diff --git a/cocos2d/core/layers/CCLayerCanvasRenderCmd.js b/cocos2d/core/layers/CCLayerCanvasRenderCmd.js index 84ba03eb9f..b646064be3 100644 --- a/cocos2d/core/layers/CCLayerCanvasRenderCmd.js +++ b/cocos2d/core/layers/CCLayerCanvasRenderCmd.js @@ -68,13 +68,14 @@ proto._syncStatus = function (parentCmd) { var flags = cc.Node._dirtyFlags, locFlag = this._dirtyFlag; - if (locFlag & flags.orderDirty) { + // if (locFlag & flags.orderDirty) { + if (this._isBaked || locFlag & flags.orderDirty) { this._cacheDirty = true; if(this._updateCache === 0) this._updateCache = 2; - this._dirtyFlag = locFlag & flags.orderDirty ^ locFlag; + this._dirtyFlag &= ~flags.orderDirty; } - cc.Node.RenderCmd.prototype._syncStatus.call(this, parentCmd); + this._originSyncStatus(parentCmd); }; proto.transform = function (parentCmd, recursive) { @@ -414,7 +415,7 @@ this._dirtyFlag = locFlag & flags.gradientDirty ^ locFlag; } - cc.Node.RenderCmd.prototype._syncStatus.call(this, parentCmd); + this._originSyncStatus(parentCmd); }; proto._updateColor = function() { @@ -452,4 +453,4 @@ } } }; -})(); \ No newline at end of file +})(); diff --git a/cocos2d/core/layers/CCLayerWebGLRenderCmd.js b/cocos2d/core/layers/CCLayerWebGLRenderCmd.js index 8051a50abe..4b644ac349 100644 --- a/cocos2d/core/layers/CCLayerWebGLRenderCmd.js +++ b/cocos2d/core/layers/CCLayerWebGLRenderCmd.js @@ -189,7 +189,7 @@ this._dirtyFlag = locFlag & flags.gradientDirty ^ locFlag; } - cc.Node.RenderCmd.prototype._syncStatus.call(this, parentCmd); + this._originSyncStatus(parentCmd); }; proto.transform = function (parentCmd, recursive) { @@ -331,4 +331,4 @@ } return this._clipRect; }; -})(); \ No newline at end of file +})(); diff --git a/cocos2d/parallax/CCParallaxNodeRenderCmd.js b/cocos2d/parallax/CCParallaxNodeRenderCmd.js index 572c10e3e1..d8fd5d89ed 100644 --- a/cocos2d/parallax/CCParallaxNodeRenderCmd.js +++ b/cocos2d/parallax/CCParallaxNodeRenderCmd.js @@ -40,7 +40,7 @@ proto._syncStatus = function(parentCmd){ this._node._updateParallaxPosition(); - cc.Node.CanvasRenderCmd.prototype._syncStatus.call(this, parentCmd); + this._originSyncStatus(parentCmd); }; })(); @@ -63,7 +63,7 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () { proto._syncStatus = function(parentCmd){ this._node._updateParallaxPosition(); - cc.Node.WebGLRenderCmd.prototype._syncStatus.call(this, parentCmd); + this._originSyncStatus(parentCmd); }; }); diff --git a/cocos2d/progress-timer/CCProgressTimerCanvasRenderCmd.js b/cocos2d/progress-timer/CCProgressTimerCanvasRenderCmd.js index 2a9c8682a4..3dd320b543 100644 --- a/cocos2d/progress-timer/CCProgressTimerCanvasRenderCmd.js +++ b/cocos2d/progress-timer/CCProgressTimerCanvasRenderCmd.js @@ -221,14 +221,14 @@ if (colorDirty){ spriteCmd._syncDisplayColor(); - spriteCmd._dirtyFlag = spriteCmd._dirtyFlag & flags.colorDirty ^ spriteCmd._dirtyFlag; - this._dirtyFlag = this._dirtyFlag & flags.colorDirty ^ this._dirtyFlag; + spriteCmd._dirtyFlag &= ~flags.colorDirty; + this._dirtyFlag &= ~flags.colorDirty; } if (opacityDirty){ spriteCmd._syncDisplayOpacity(); - spriteCmd._dirtyFlag = spriteCmd._dirtyFlag & flags.opacityDirty ^ spriteCmd._dirtyFlag; - this._dirtyFlag = this._dirtyFlag & flags.opacityDirty ^ this._dirtyFlag; + spriteCmd._dirtyFlag &= ~flags.opacityDirty; + this._dirtyFlag &= ~flags.opacityDirty; } if(colorDirty || opacityDirty){ @@ -241,7 +241,7 @@ } if (locFlag & flags.orderDirty) { - this._dirtyFlag = this._dirtyFlag & flags.orderDirty ^ this._dirtyFlag; + this._dirtyFlag &= ~flags.orderDirty; } }; @@ -281,4 +281,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 e1be5255ae..5602a4d6fc 100644 --- a/cocos2d/progress-timer/CCProgressTimerWebGLRenderCmd.js +++ b/cocos2d/progress-timer/CCProgressTimerWebGLRenderCmd.js @@ -123,14 +123,14 @@ if (colorDirty){ spriteCmd._syncDisplayColor(); - spriteCmd._dirtyFlag = spriteCmd._dirtyFlag & flags.colorDirty ^ spriteCmd._dirtyFlag; - this._dirtyFlag = this._dirtyFlag & flags.colorDirty ^ this._dirtyFlag; + spriteCmd._dirtyFlag &= ~flags.colorDirty; + this._dirtyFlag &= ~flags.colorDirty; } if (opacityDirty){ spriteCmd._syncDisplayOpacity(); - spriteCmd._dirtyFlag = spriteCmd._dirtyFlag & flags.opacityDirty ^ spriteCmd._dirtyFlag; - this._dirtyFlag = this._dirtyFlag & flags.opacityDirty ^ this._dirtyFlag; + spriteCmd._dirtyFlag &= ~flags.opacityDirty; + this._dirtyFlag &= ~flags.opacityDirty; } if(colorDirty || opacityDirty){ @@ -144,7 +144,7 @@ if (locFlag & flags.textureDirty) { this._updateProgressData(); - this._dirtyFlag = this._dirtyFlag & flags.textureDirty ^ this._dirtyFlag; + this._dirtyFlag &= ~flags.textureDirty; } spriteCmd._dirtyFlag = 0; @@ -536,4 +536,4 @@ } this._vertexDataDirty = true; }; -})(); \ No newline at end of file +})(); diff --git a/extensions/ccui/base-classes/UIScale9SpriteCanvasRenderCmd.js b/extensions/ccui/base-classes/UIScale9SpriteCanvasRenderCmd.js index 57a27ed3c3..840332cbaf 100644 --- a/extensions/ccui/base-classes/UIScale9SpriteCanvasRenderCmd.js +++ b/extensions/ccui/base-classes/UIScale9SpriteCanvasRenderCmd.js @@ -114,7 +114,7 @@ var flags = cc.Node._dirtyFlags, locFlag = this._dirtyFlag; - cc.Node.RenderCmd.prototype._syncStatus.call(this, parentCmd); + this._originSyncStatus(parentCmd); if (locFlag & flags.cacheDirty) { this._cacheScale9Sprite(); diff --git a/extensions/ccui/base-classes/UIScale9SpriteWebGLRenderCmd.js b/extensions/ccui/base-classes/UIScale9SpriteWebGLRenderCmd.js index b8541b46d0..4f54e16998 100644 --- a/extensions/ccui/base-classes/UIScale9SpriteWebGLRenderCmd.js +++ b/extensions/ccui/base-classes/UIScale9SpriteWebGLRenderCmd.js @@ -130,7 +130,7 @@ }; proto._syncStatus = function (parentCmd){ - cc.Node.WebGLRenderCmd.prototype._syncStatus.call(this, parentCmd); + this._originSyncStatus(parentCmd); this._updateDisplayColor(this._displayedColor); this._updateDisplayOpacity(this._displayedOpacity); }; From c4f48868eb2b837142e0063b2c3b3e93b3719e8d Mon Sep 17 00:00:00 2001 From: pandamicro Date: Fri, 18 Nov 2016 11:55:50 +0800 Subject: [PATCH 11/42] Fix protected node transform issue --- cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js b/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js index 080ff295e2..2e2386ba0f 100644 --- a/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js +++ b/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js @@ -69,6 +69,16 @@ function transformChildTree (root) { child._renderCmd.transform(parentCmd); } } + var pChildren = curr._protectedChildren; + if (pChildren && pChildren.length > 0) { + parentCmd = curr._renderCmd; + for (i = 0, len = pChildren.length; i < len; ++i) { + child = pChildren[i]; + stack[index] = child; + index++; + child._renderCmd.transform(parentCmd); + } + } } } From 7d0f69a32cced901f821a1fb3012467c765f3263 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Fri, 18 Nov 2016 11:56:36 +0800 Subject: [PATCH 12/42] Improve WebGL Rendering performance --- cocos2d/core/renderer/RendererWebGL.js | 9 ++++---- .../core/sprites/CCSpriteWebGLRenderCmd.js | 23 +++++++++++-------- 2 files changed, 18 insertions(+), 14 deletions(-) diff --git a/cocos2d/core/renderer/RendererWebGL.js b/cocos2d/core/renderer/RendererWebGL.js index 918c175b71..e662f63576 100644 --- a/cocos2d/core/renderer/RendererWebGL.js +++ b/cocos2d/core/renderer/RendererWebGL.js @@ -273,9 +273,10 @@ return { } // Check batching - var texture = cmd._node._texture; - var blendSrc = cmd._node._blendFunc.src; - var blendDst = cmd._node._blendFunc.dst; + var node = cmd._node; + var texture = node._texture; + var blendSrc = node._blendFunc.src; + var blendDst = node._blendFunc.dst; var shader = cmd._shaderProgram; if (_batchedInfo.texture !== texture || _batchedInfo.blendSrc !== blendSrc || @@ -369,4 +370,4 @@ return { _batchedInfo.texture = null; } }; -})(); \ No newline at end of file +})(); diff --git a/cocos2d/core/sprites/CCSpriteWebGLRenderCmd.js b/cocos2d/core/sprites/CCSpriteWebGLRenderCmd.js index 3d02a422ce..fd5a07e6c8 100644 --- a/cocos2d/core/sprites/CCSpriteWebGLRenderCmd.js +++ b/cocos2d/core/sprites/CCSpriteWebGLRenderCmd.js @@ -272,17 +272,20 @@ 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; + wt = this._worldTransform, + wtx = wt.tx, wty = wt.ty, + lxa = lx * wt.a, lxb = lx * wt.b, rxa = rx * wt.a, rxb = rx * wt.b, + tyc = ty * wt.c, tyd = ty * wt.d, byc = by * wt.c, byd = by * wt.d; 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; + vertices[0].x = lxa + tyc + wtx; // tl + vertices[0].y = lxb + tyd + wty; + vertices[1].x = lxa + byc + wtx; // bl + vertices[1].y = lxb + byd + wty; + vertices[2].x = rxa + tyc + wtx; // tr + vertices[2].y = rxb + tyd + wty; + vertices[3].x = rxa + byc + wtx; // br + vertices[3].y = rxb + byd + wty; }; proto.needDraw = function () { @@ -324,4 +327,4 @@ return len; }; -})(); \ No newline at end of file +})(); From 5cf049dfb95c2b54e8519c2f6f484c53ebc0899f Mon Sep 17 00:00:00 2001 From: pandamicro Date: Fri, 18 Nov 2016 11:56:54 +0800 Subject: [PATCH 13/42] Fix Editbox default input mode issue --- extensions/editbox/CCEditBox.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/editbox/CCEditBox.js b/extensions/editbox/CCEditBox.js index b8d6fb4254..88b02bdf97 100644 --- a/extensions/editbox/CCEditBox.js +++ b/extensions/editbox/CCEditBox.js @@ -208,7 +208,7 @@ cc.EditBoxDelegate = cc.Class.extend({ cc.EditBox = cc.Node.extend({ _backgroundSprite: null, _delegate: null, - _editBoxInputMode: cc.EDITBOX_INPUT_MODE_SINGLELINE, + _editBoxInputMode: cc.EDITBOX_INPUT_MODE_ANY, _editBoxInputFlag: cc.EDITBOX_INPUT_FLAG_SENSITIVE, _keyboardReturnType: cc.KEYBOARD_RETURNTYPE_DEFAULT, _maxLength: 50, From e0a4b95d71e495ef1370301cd25c5558cdea848f Mon Sep 17 00:00:00 2001 From: pandamicro Date: Fri, 18 Nov 2016 11:57:05 +0800 Subject: [PATCH 14/42] Remove GL State cache --- cocos2d/shaders/CCGLStateCache.js | 54 ------------------------------- 1 file changed, 54 deletions(-) diff --git a/cocos2d/shaders/CCGLStateCache.js b/cocos2d/shaders/CCGLStateCache.js index edcf86c3b8..626c587a9c 100644 --- a/cocos2d/shaders/CCGLStateCache.js +++ b/cocos2d/shaders/CCGLStateCache.js @@ -36,60 +36,6 @@ if (cc.ENABLE_GL_STATE_CACHE) { cc._GLServerState = 0; if(cc.TEXTURE_ATLAS_USE_VAO) cc._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; - } - }; - - WebGLRenderingContext.prototype.glEnableVertexAttribArray = WebGLRenderingContext.prototype.enableVertexAttribArray; - WebGLRenderingContext.prototype.enableVertexAttribArray = function (index) { - if (index === cc.VERTEX_ATTRIB_FLAG_POSITION) { - if (!this._vertexAttribPosition) { - this.glEnableVertexAttribArray(index); - this._vertexAttribPosition = true; - } - } - else if (index === cc.VERTEX_ATTRIB_FLAG_COLOR) { - if (!this._vertexAttribColor) { - this.glEnableVertexAttribArray(index); - this._vertexAttribColor = true; - } - } - else if (index === cc.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 === cc.VERTEX_ATTRIB_FLAG_COLOR) { - if (this._vertexAttribColor) { - this.glDisableVertexAttribArray(index); - this._vertexAttribColor = false; - } - } - else if (index === cc.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 From 2ac19adbcd3ee68d349387c2dd23dc1138ace3a0 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Mon, 21 Nov 2016 22:06:00 +0800 Subject: [PATCH 15/42] Improve Scheduler memory footprint --- cocos2d/core/CCScheduler.js | 403 ++++++++++++++++++------------------ 1 file changed, 206 insertions(+), 197 deletions(-) diff --git a/cocos2d/core/CCScheduler.js b/cocos2d/core/CCScheduler.js index 4ba83d81a8..d041061edc 100644 --- a/cocos2d/core/CCScheduler.js +++ b/cocos2d/core/CCScheduler.js @@ -24,6 +24,7 @@ THE SOFTWARE. ****************************************************************************/ +(function () { /** * Minimum priority level for user scheduling. @@ -32,20 +33,20 @@ */ cc.PRIORITY_NON_SYSTEM = cc.PRIORITY_SYSTEM + 1; +var MAX_POOL_SIZE = 20; + //data structures /** * A list double-linked list used for "updates with priority" - * @Class - * @name cc.ListEntry - * @param {cc.ListEntry} prev - * @param {cc.ListEntry} next + * @param {ListEntry} prev + * @param {ListEntry} next * @param {function} callback * @param {cc.Class} target not retained (retained by hashUpdateEntry) * @param {Number} priority * @param {Boolean} paused * @param {Boolean} markedForDeletion selector will no longer be called and entry will be removed at end of the next tick */ -cc.ListEntry = function (prev, next, callback, target, priority, paused, markedForDeletion) { +var ListEntry = function (prev, next, callback, target, priority, paused, markedForDeletion) { this.prev = prev; this.next = next; this.callback = callback; @@ -55,37 +56,82 @@ cc.ListEntry = function (prev, next, callback, target, priority, paused, markedF this.markedForDeletion = markedForDeletion; }; +var _listEntries = []; +ListEntry.get = function (prev, next, callback, target, priority, paused, markedForDeletion) { + var result = _listEntries.pop(); + if (result) { + result.prev = prev; + result.next = next; + result.callback = callback; + result.target = target; + result.priority = priority; + result.paused = paused; + result.markedForDeletion = markedForDeletion; + } + else { + result = new ListEntry(prev, next, callback, target, priority, paused, markedForDeletion); + } + return result; +}; +ListEntry.put = function (entry) { + entry.prev = null; + entry.next = null; + entry.callback = null; + entry.target = null; + entry.priority = 0; + entry.paused = false; + entry.markedForDeletion = false; + if (_listEntries.length < MAX_POOL_SIZE) + _listEntries.push(entry); +}; + /** * A update entry list - * @Class - * @name cc.HashUpdateEntry * @param {Array} list Which list does it belong to ? - * @param {cc.ListEntry} entry entry in the list + * @param {ListEntry} entry entry in the list * @param {cc.Class} target hash key (retained) * @param {function} callback - * @param {Array} hh */ -cc.HashUpdateEntry = function (list, entry, target, callback, hh) { +var HashUpdateEntry = function (list, entry, target, callback) { this.list = list; this.entry = entry; this.target = target; this.callback = callback; - this.hh = hh; +}; +var _hashUpdateEntries = []; +HashUpdateEntry.get = function (list, entry, target, callback) { + var result = _hashUpdateEntries.pop(); + if (result) { + result.list = list; + result.entry = entry; + result.target = target; + result.callback = callback; + } + else { + result = new HashUpdateEntry(list, entry, target, callback); + } + return result; +}; +HashUpdateEntry.put = function (entry) { + entry.list = null; + entry.entry = null; + entry.target = null; + entry.callback = null; + if (_hashUpdateEntries.length < MAX_POOL_SIZE) + _hashUpdateEntries.push(entry); }; // /** * Hash Element used for "selectors with interval" - * @Class * @param {Array} timers * @param {cc.Class} target hash key (retained) * @param {Number} timerIndex - * @param {cc.Timer} currentTimer + * @param {CallbackTimer} currentTimer * @param {Boolean} currentTimerSalvaged * @param {Boolean} paused - * @param {Array} hh */ -cc.HashTimerEntry = cc.hashSelectorEntry = function (timers, target, timerIndex, currentTimer, currentTimerSalvaged, paused, hh) { +var HashTimerEntry = function (timers, target, timerIndex, currentTimer, currentTimerSalvaged, paused) { var _t = this; _t.timers = timers; _t.target = target; @@ -93,64 +139,76 @@ cc.HashTimerEntry = cc.hashSelectorEntry = function (timers, target, timerIndex, _t.currentTimer = currentTimer; _t.currentTimerSalvaged = currentTimerSalvaged; _t.paused = paused; - _t.hh = hh; +}; +var _hashTimerEntries = []; +HashTimerEntry.get = function (timers, target, timerIndex, currentTimer, currentTimerSalvaged, paused) { + var result = _hashTimerEntries.pop(); + if (result) { + result.timers = timers; + result.target = target; + result.timerIndex = timerIndex; + result.currentTimer = currentTimer; + result.currentTimerSalvaged = currentTimerSalvaged; + result.paused = paused; + } + else { + result = new HashTimerEntry(timers, target, timerIndex, currentTimer, currentTimerSalvaged, paused); + } + return result; +}; +HashTimerEntry.put = function (entry) { + entry.timers = null; + entry.target = null; + entry.timerIndex = 0; + entry.currentTimer = null; + entry.currentTimerSalvaged = false; + entry.paused = false; + if (_hashTimerEntries.length < MAX_POOL_SIZE) + _hashTimerEntries.push(entry); }; /** * Light weight timer - * @class * @extends cc.Class */ -cc.Timer = cc.Class.extend(/** @lends cc.Timer# */{ - _scheduler: null, - _elapsed:0.0, - _runForever:false, - _useDelay:false, - _timesExecuted:0, - _repeat:0, //0 = once, 1 is 2 x executed - _delay:0, - _interval:0.0, - - /** - * @return {Number} returns interval of timer - */ - getInterval : function(){return this._interval;}, - /** - * @param {Number} interval set interval in seconds - */ - setInterval : function(interval){this._interval = interval;}, +var CallbackTimer = function () { + this._scheduler = null; + this._elapsed = -1; + this._runForever = false; + this._useDelay = false; + this._timesExecuted = 0; + this._repeat = 0; + this._delay = 0; + this._interval = 0; + + this._target = null; + this._callback = null; + this._key = null; +}; +cc.inject({ + initWithCallback: function (scheduler, callback, target, seconds, repeat, delay, key) { + this._scheduler = scheduler; + this._target = target; + this._callback = callback; + if (key) + this._key = key; - setupTimerWithInterval: function(seconds, repeat, delay){ this._elapsed = -1; this._interval = seconds; this._delay = delay; this._useDelay = (this._delay > 0); this._repeat = repeat; this._runForever = (this._repeat === cc.REPEAT_FOREVER); + return true; }, - - trigger: function(){ - return 0; - }, - - cancel: function(){ - return 0; - }, - /** - * cc.Timer's Constructor - * Constructor of cc.Timer + * @return {Number} returns interval of timer */ - ctor:function () { - this._scheduler = null; - this._elapsed = -1; - this._runForever = false; - this._useDelay = false; - this._timesExecuted = 0; - this._repeat = 0; - this._delay = 0; - this._interval = 0; - }, + getInterval : function(){return this._interval;}, + /** + * @param {Number} interval set interval in seconds + */ + setInterval : function(interval){this._interval = interval;}, /** * triggers the timer @@ -189,62 +247,6 @@ cc.Timer = cc.Class.extend(/** @lends cc.Timer# */{ this.cancel(); } } - } -}); - -cc.TimerTargetSelector = cc.Timer.extend({ - _target: null, - _selector: null, - - ctor: function(){ - this._target = null; - this._selector = null; - }, - - initWithSelector: function(scheduler, selector, target, seconds, repeat, delay){ - this._scheduler = scheduler; - this._target = target; - this._selector = selector; - this.setupTimerWithInterval(seconds, repeat, delay); - return true; - }, - - getSelector: function(){ - return this._selector; - }, - - trigger: function(){ - //override - if (this._target && this._selector){ - this._target.call(this._selector, this._elapsed); - } - }, - - cancel: function(){ - //override - this._scheduler.unschedule(this._selector, this._target); - } - -}); - -cc.TimerTargetCallback = cc.Timer.extend({ - - _target: null, - _callback: null, - _key: null, - - ctor: function(){ - this._target = null; - this._callback = null; - }, - - initWithCallback: function(scheduler, callback, target, key, seconds, repeat, delay){ - this._scheduler = scheduler; - this._target = target; - this._callback = callback; - this._key = key; - this.setupTimerWithInterval(seconds, repeat, delay); - return true; }, getCallback: function(){ @@ -255,18 +257,37 @@ cc.TimerTargetCallback = cc.Timer.extend({ return this._key; }, - trigger: function(){ - //override - if(this._callback) + trigger: function () { + if (this._target && this._callback){ this._callback.call(this._target, this._elapsed); + } }, - cancel: function(){ + cancel: function () { //override this._scheduler.unschedule(this._callback, this._target); } +}, CallbackTimer.prototype); -}); +var _timers = []; +CallbackTimer.get = function () { + return _timers.pop() || new CallbackTimer(); +}; +CallbackTimer.put = function (timer) { + timer._scheduler = null; + timer._elapsed = -1; + timer._runForever = false; + timer._useDelay = false; + timer._timesExecuted = 0; + timer._repeat = 0; + timer._delay = 0; + timer._interval = 0; + timer._target = null; + timer._callback = null; + timer._key = null; + if (_timers.length < MAX_POOL_SIZE) + _timers.push(timer); +}; /** *

@@ -344,7 +365,7 @@ cc.Scheduler = cc.Class.extend(/** @lends cc.Scheduler# */{ } } - // most of the updates are going to be 0, that's way there + // most of the updates are going to be 0, that's why there // is an special list for updates with priority 0 if (priority === 0){ this._appendIn(this._updates0List, callback, target, paused); @@ -358,30 +379,38 @@ cc.Scheduler = cc.Class.extend(/** @lends cc.Scheduler# */{ _removeHashElement:function (element) { delete this._hashForTimers[element.target.__instanceId]; - cc.arrayRemoveObject(this._arrayForTimers, element); - element.Timer = null; - element.target = null; - element = null; + var arr = this._arrayForTimers; + for (var i = 0, l = arr.length; i < l; i++) { + if (arr[i] === element) { + arr.splice(i, 1); + break; + } + } + HashTimerEntry.put(element); }, _removeUpdateFromHash:function (entry) { - var self = this, element = self._hashForUpdates[entry.target.__instanceId]; + var self = this; + element = self._hashForUpdates[entry.target.__instanceId]; if (element) { - //list entry - cc.arrayRemoveObject(element.list, element.entry); + // Remove list entry from list + var list = element.list, listEntry = element.entry; + for (var i = 0, l = list.length; i < l; i++) { + if (list[i] === listEntry) { + list.splice(i, 1); + break; + } + } delete self._hashForUpdates[element.target.__instanceId]; - //cc.arrayRemoveObject(self._hashForUpdates, element); - element.entry = null; - - //hash entry - element.target = null; + ListEntry.put(listEntry); + HashUpdateEntry.put(element); } }, _priorityIn:function (ppList, callback, target, priority, paused) { var self = this, - listElement = new cc.ListEntry(null, null, callback, target, priority, paused, false); + listElement = ListEntry.get(null, null, callback, target, priority, paused, false); // empey list ? if (!ppList) { @@ -399,17 +428,18 @@ cc.Scheduler = cc.Class.extend(/** @lends cc.Scheduler# */{ } //update hash entry for quick access - self._hashForUpdates[target.__instanceId] = new cc.HashUpdateEntry(ppList, listElement, target, null); + self._hashForUpdates[target.__instanceId] = HashUpdateEntry.get(ppList, listElement, target, null); return ppList; }, _appendIn:function (ppList, callback, target, paused) { - var self = this, listElement = new cc.ListEntry(null, null, callback, target, 0, paused, false); + var self = this, + listElement = ListEntry.get(null, null, callback, target, 0, paused, false); ppList.push(listElement); //update hash entry for quicker access - self._hashForUpdates[target.__instanceId] = new cc.HashUpdateEntry(ppList, listElement, target, null, null); + self._hashForUpdates[target.__instanceId] = HashUpdateEntry.get(ppList, listElement, target, null, null); }, //-----------------------public method------------------------- @@ -546,30 +576,21 @@ cc.Scheduler = cc.Class.extend(/** @lends cc.Scheduler# */{ this.schedule(callback_fn, target, interval, repeat, delay, paused, target.__instanceId + ""); }, - schedule: function(callback, target, interval, repeat, delay, paused, key){ + schedule: function (callback, target, interval, repeat, delay, paused, key) { var isSelector = false; - if(typeof callback !== "function"){ - var selector = callback; + if (typeof callback !== "function") { + var tmp = callback; + callback = target; + target = tmp; isSelector = true; } - - if(isSelector === false){ - //callback, target, interval, repeat, delay, paused, key - //callback, target, interval, paused, key - if(arguments.length === 4 || arguments.length === 5){ - key = delay; - paused = repeat; - delay = 0; - repeat = cc.REPEAT_FOREVER; - } - }else{ - //selector, target, interval, repeat, delay, paused - //selector, target, interval, paused - if(arguments.length === 4){ - paused = repeat; - repeat = cc.REPEAT_FOREVER; - delay = 0; - } + //callback, target, interval, repeat, delay, paused, key + //callback, target, interval, paused, key + if(arguments.length === 4 || arguments.length === 5){ + key = delay; + paused = repeat; + repeat = cc.REPEAT_FOREVER; + delay = 0; } if (key === undefined) { key = target.__instanceId + ""; @@ -579,19 +600,19 @@ cc.Scheduler = cc.Class.extend(/** @lends cc.Scheduler# */{ var element = this._hashForTimers[target.__instanceId]; - if(!element){ + if (!element) { // Is this the 1st element ? Then set the pause level to all the callback_fns of this target - element = new cc.HashTimerEntry(null, target, 0, null, null, paused, null); + element = HashTimerEntry.get(null, target, 0, null, null, paused, null); this._arrayForTimers.push(element); this._hashForTimers[target.__instanceId] = element; - }else{ + } else { cc.assert(element.paused === paused, ""); } var timer, i; if (element.timers == null) { element.timers = []; - } else if(isSelector === false) { + } else { for (i = 0; i < element.timers.length; i++) { timer = element.timers[i]; if (callback === timer._callback) { @@ -600,27 +621,11 @@ cc.Scheduler = cc.Class.extend(/** @lends cc.Scheduler# */{ return; } } - }else{ - for (i = 0; i < element.timers.length; ++i){ - timer =element.timers[i]; - if (timer && selector === timer.getSelector()){ - cc.log("CCScheduler#scheduleSelector. Selector already scheduled. Updating interval from: %.4f to %.4f", timer.getInterval(), interval); - timer.setInterval(interval); - return; - } - } - //ccArrayEnsureExtraCapacity(element->timers, 1); } - if(isSelector === false){ - timer = new cc.TimerTargetCallback(); - timer.initWithCallback(this, callback, target, key, interval, repeat, delay); - element.timers.push(timer); - }else{ - timer = new cc.TimerTargetSelector(); - timer.initWithSelector(this, selector, target, interval, repeat, delay); - element.timers.push(timer); - } + timer = CallbackTimer.get(); + timer.initWithCallback(this, callback, target, interval, repeat, delay, key); + element.timers.push(timer); }, scheduleUpdate: function(target, priority, paused){ @@ -630,18 +635,16 @@ cc.Scheduler = cc.Class.extend(/** @lends cc.Scheduler# */{ }, _getUnscheduleMark: function(key, timer){ - //key, callback, selector + //key, callback switch (typeof key){ case "number": case "string": - return key === timer.getKey(); + return key === timer._key; case "function": return key === timer._callback; - default: - return key === timer.getSelector(); } }, - unschedule: function(key, target){ + unschedule: function (key, target) { //key, target //selector, target //callback, target - This is in order to increase compatibility @@ -660,6 +663,7 @@ cc.Scheduler = cc.Class.extend(/** @lends cc.Scheduler# */{ element.currentTimerSalvaged = true; } timers.splice(i, 1); + CallbackTimer.put(timer); //update timerIndex in case we are in tick;, looping over the actions if (element.timerIndex >= i) { element.timerIndex--; @@ -678,37 +682,40 @@ cc.Scheduler = cc.Class.extend(/** @lends cc.Scheduler# */{ } }, - unscheduleUpdate: function(target){ - if (target == null) + unscheduleUpdate: function (target) { + if (!target) return; var element = this._hashForUpdates[target.__instanceId]; - if (element){ - if (this._updateHashLocked){ + if (element) { + if (this._updateHashLocked) { element.entry.markedForDeletion = true; - }else{ + } else { this._removeUpdateFromHash(element.entry); } } }, - unscheduleAllForTarget: function(target){ + unscheduleAllForTarget: function (target) { // explicit nullptr handling - if (target == null){ + if (!target){ return; } // Custom Selectors var element = this._hashForTimers[target.__instanceId]; - if (element){ - if (element.timers.indexOf(element.currentTimer) > -1 - && (! element.currentTimerSalvaged)){ + if (element) { + var timers = element.timers; + if (timers.indexOf(element.currentTimer) > -1 && + (!element.currentTimerSalvaged)) { element.currentTimerSalvaged = true; } - // ccArrayRemoveAllObjects(element.timers); - element.timers.length = 0; + for (var i = 0, l = timers.length; i < l; i++) { + CallbackTimer.put(timers[i]); + } + timers.length = 0; if (this._currentTarget === element){ this._currentTargetSalvaged = true; @@ -788,7 +795,7 @@ cc.Scheduler = cc.Class.extend(/** @lends cc.Scheduler# */{ for (var i = 0; i < timers.length; ++i) { var timer = timers[i]; - if (callback === timer._selector){ + if (callback === timer._callback){ return true; } } @@ -1036,3 +1043,5 @@ cc.Scheduler = cc.Class.extend(/** @lends cc.Scheduler# */{ * @type Number */ cc.Scheduler.PRIORITY_SYSTEM = (-2147483647 - 1); + +})(); From 1dc258fdd340ddf1a1c4c2397bfe0d0e6a7ce642 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Mon, 21 Nov 2016 22:06:13 +0800 Subject: [PATCH 16/42] Small improvements --- cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js | 2 +- cocos2d/core/platform/CCConfig.js | 2 +- cocos2d/core/platform/CCMacro.js | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js b/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js index 2e2386ba0f..c8a066a6e3 100644 --- a/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js +++ b/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js @@ -283,7 +283,7 @@ cc.Node.RenderCmd.prototype = { } if (node._additionalTransformDirty) { - this._transform = cc.affineTransformConcat(t, node._additionalTransform); + cc.affineTransformConcatIn(t, node._additionalTransform); } if (this._updateCurrentRegions) { diff --git a/cocos2d/core/platform/CCConfig.js b/cocos2d/core/platform/CCConfig.js index bc01fbc66f..77f60e2748 100644 --- a/cocos2d/core/platform/CCConfig.js +++ b/cocos2d/core/platform/CCConfig.js @@ -267,7 +267,7 @@ cc.DRAWNODE_TOTAL_VERTICES = 20000; * @constant * @type {Number} */ -cc.IS_RETINA_DISPLAY_SUPPORTED = 1; +cc.IS_RETINA_DISPLAY_SUPPORTED = 0; /** * Default engine diff --git a/cocos2d/core/platform/CCMacro.js b/cocos2d/core/platform/CCMacro.js index a9dce0d6ed..588342eb18 100644 --- a/cocos2d/core/platform/CCMacro.js +++ b/cocos2d/core/platform/CCMacro.js @@ -245,7 +245,7 @@ cc.FLT_EPSILON = 0.0000001192092896; * @function */ cc.contentScaleFactor = cc.IS_RETINA_DISPLAY_SUPPORTED ? function () { - return cc.director.getContentScaleFactor(); + return cc.director._contentScaleFactor; } : function () { return 1; }; From 57e0c0de14aa19901eb00ea3c8843c26eb549056 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Tue, 22 Nov 2016 15:36:11 +0800 Subject: [PATCH 17/42] Improve EventManager performance --- cocos2d/core/CCDirector.js | 3 +- cocos2d/core/event-manager/CCEventManager.js | 97 ++++++++++++-------- 2 files changed, 60 insertions(+), 40 deletions(-) diff --git a/cocos2d/core/CCDirector.js b/cocos2d/core/CCDirector.js index 903f826468..1a886d59fb 100644 --- a/cocos2d/core/CCDirector.js +++ b/cocos2d/core/CCDirector.js @@ -136,7 +136,6 @@ cc.Director = cc.Class.extend(/** @lends cc.Director# */{ //action manager if(cc.ActionManager){ this._actionManager = new cc.ActionManager(); - this._scheduler.scheduleUpdate(this._actionManager, cc.Scheduler.PRIORITY_SYSTEM, false); }else{ this._actionManager = null; } @@ -229,6 +228,7 @@ cc.Director = cc.Class.extend(/** @lends cc.Director# */{ //tick before glClear: issue #533 if (!this._paused) { + this._actionManager.update(this._deltaTime); this._scheduler.update(this._deltaTime); cc.eventManager.dispatchEvent(this._eventAfterUpdate); } @@ -272,6 +272,7 @@ cc.Director = cc.Class.extend(/** @lends cc.Director# */{ this._totalFrames++; cc.eventManager.dispatchEvent(this._eventAfterDraw); + cc.eventManager.frameUpdateListeners(); this._calculateMPF(); }, diff --git a/cocos2d/core/event-manager/CCEventManager.js b/cocos2d/core/event-manager/CCEventManager.js index 6afe2e6e13..76599754c1 100644 --- a/cocos2d/core/event-manager/CCEventManager.js +++ b/cocos2d/core/event-manager/CCEventManager.js @@ -23,6 +23,8 @@ THE SOFTWARE. ****************************************************************************/ +(function () { + /** * @ignore */ @@ -73,25 +75,25 @@ cc._EventListenerVector = cc.Class.extend({ } }); -cc.__getListenerID = function (event) { - var eventType = cc.Event, getType = event.getType(); - if(getType === eventType.ACCELERATION) +function __getListenerID (event) { + var eventType = cc.Event, getType = event._type; + if (getType === eventType.ACCELERATION) return cc._EventListenerAcceleration.LISTENER_ID; - if(getType === eventType.CUSTOM) - return event.getEventName(); - if(getType === eventType.KEYBOARD) + if (getType === eventType.CUSTOM) + return event._eventName; + if (getType === eventType.KEYBOARD) return cc._EventListenerKeyboard.LISTENER_ID; - if(getType === eventType.MOUSE) + if (getType === eventType.MOUSE) return cc._EventListenerMouse.LISTENER_ID; - if(getType === eventType.FOCUS) + if (getType === eventType.FOCUS) return cc._EventListenerFocus.LISTENER_ID; - if(getType === eventType.TOUCH){ + if (getType === eventType.TOUCH) { // Touch listener is very special, it contains two kinds of listeners, EventListenerTouchOneByOne and EventListenerTouchAllAtOnce. // return UNKNOWN instead. cc.log(cc._LogInfos.__getListenerID); } return ""; -}; +} /** *

@@ -346,11 +348,7 @@ cc.eventManager = /** @lends cc.eventManager# */{ return l1._getFixedPriority() - l2._getFixedPriority(); }, - _onUpdateListeners: function (listenerID) { - var listeners = this._listenersMap[listenerID]; - if (!listeners) - return; - + _onUpdateListeners: function (listeners) { var fixedPriorityListeners = listeners.getFixedPriorityListeners(); var sceneGraphPriorityListeners = listeners.getSceneGraphPriorityListeners(); var i, selListener, idx, toRemovedListeners = this._toRemovedListeners; @@ -390,20 +388,7 @@ cc.eventManager = /** @lends cc.eventManager# */{ listeners.clearFixedListeners(); }, - _updateListeners: function (event) { - var locInDispatch = this._inDispatch; - cc.assert(locInDispatch > 0, cc._LogInfos.EventManager__updateListeners); - - if(locInDispatch > 1) - return; - - if (event.getType() === cc.Event.TOUCH) { - this._onUpdateListeners(cc._EventListenerTouchOneByOne.LISTENER_ID); - this._onUpdateListeners(cc._EventListenerTouchAllAtOnce.LISTENER_ID); - } else - this._onUpdateListeners(cc.__getListenerID(event)); - - cc.assert(locInDispatch === 1, cc._LogInfos.EventManager__updateListeners_2); + frameUpdateListeners: function () { var locListenersMap = this._listenersMap, locPriorityDirtyFlagMap = this._priorityDirtyFlagMap; for (var selKey in locListenersMap) { if (locListenersMap[selKey].empty()) { @@ -416,10 +401,41 @@ cc.eventManager = /** @lends cc.eventManager# */{ if (locToAddedListeners.length !== 0) { for (var i = 0, len = locToAddedListeners.length; i < len; i++) this._forceAddEventListener(locToAddedListeners[i]); - this._toAddedListeners.length = 0; + locToAddedListeners.length = 0; } - if(this._toRemovedListeners.length !== 0) + if (this._toRemovedListeners.length !== 0) { this._cleanToRemovedListeners(); + } + }, + + _updateTouchListeners: function (event) { + var locInDispatch = this._inDispatch; + cc.assert(locInDispatch > 0, cc._LogInfos.EventManager__updateListeners); + + if (locInDispatch > 1) + return; + + var listeners; + listeners = this._listenersMap[cc._EventListenerTouchOneByOne.LISTENER_ID]; + if (listeners) { + this._onUpdateListeners(listeners); + } + listeners = this._listenersMap[cc._EventListenerTouchAllAtOnce.LISTENER_ID]; + if (listeners) { + this._onUpdateListeners(listeners); + } + + cc.assert(locInDispatch === 1, cc._LogInfos.EventManager__updateListeners_2); + + var locToAddedListeners = this._toAddedListeners; + if (locToAddedListeners.length !== 0) { + for (var i = 0, len = locToAddedListeners.length; i < len; i++) + this._forceAddEventListener(locToAddedListeners[i]); + locToAddedListeners.length = 0; + } + if (this._toRemovedListeners.length !== 0) { + this._cleanToRemovedListeners(); + } }, //Remove all listeners in _toRemoveListeners list and cleanup @@ -486,7 +502,7 @@ cc.eventManager = /** @lends cc.eventManager# */{ // If the event was stopped, return directly. if (event.isStopped()) { - cc.eventManager._updateListeners(event); + cc.eventManager._updateTouchListeners(event); return true; } @@ -532,7 +548,7 @@ cc.eventManager = /** @lends cc.eventManager# */{ if (event.isStopped()) return; } - this._updateListeners(event); + this._updateTouchListeners(event); }, _onTouchesEventCallback: function (listener, callbackParams) { @@ -553,7 +569,7 @@ cc.eventManager = /** @lends cc.eventManager# */{ // If the event was stopped, return directly. if (event.isStopped()) { - cc.eventManager._updateListeners(event); + cc.eventManager._updateTouchListeners(event); return true; } return false; @@ -962,19 +978,20 @@ cc.eventManager = /** @lends cc.eventManager# */{ this._inDispatch++; if(!event || !event.getType) throw new Error("event is undefined"); - if (event.getType() === cc.Event.TOUCH) { + if (event._type === cc.Event.TOUCH) { this._dispatchTouchEvent(event); this._inDispatch--; return; } - var listenerID = cc.__getListenerID(event); + var listenerID = __getListenerID(event); this._sortEventListeners(listenerID); var selListeners = this._listenersMap[listenerID]; - if (selListeners != null) + if (selListeners) { this._dispatchEventToListeners(selListeners, this._onListenerCallback, event); - - this._updateListeners(event); + this._onUpdateListeners(selListeners); + } + this._inDispatch--; }, @@ -995,3 +1012,5 @@ cc.eventManager = /** @lends cc.eventManager# */{ this.dispatchEvent(ev); } }; + +})(); \ No newline at end of file From d79cf76ca608f4624a0d2ddc0c09871e76057e2f Mon Sep 17 00:00:00 2001 From: pandamicro Date: Wed, 23 Nov 2016 15:36:27 +0800 Subject: [PATCH 18/42] Fix Scale9Sprite transform issue causing transform stack corrupt --- .../base-classes/UIScale9SpriteCanvasRenderCmd.js | 6 +++--- .../base-classes/UIScale9SpriteWebGLRenderCmd.js | 4 ++-- extensions/ccui/base-classes/UIWidget.js | 13 ------------- 3 files changed, 5 insertions(+), 18 deletions(-) diff --git a/extensions/ccui/base-classes/UIScale9SpriteCanvasRenderCmd.js b/extensions/ccui/base-classes/UIScale9SpriteCanvasRenderCmd.js index 840332cbaf..2c97160033 100644 --- a/extensions/ccui/base-classes/UIScale9SpriteCanvasRenderCmd.js +++ b/extensions/ccui/base-classes/UIScale9SpriteCanvasRenderCmd.js @@ -58,9 +58,9 @@ this.originVisit(parentCmd); }; - proto.transform = function(parentCmd){ + proto.transform = function(parentCmd, recursive) { var node = this._node; - cc.Node.CanvasRenderCmd.prototype.transform.call(this, parentCmd); + this.originTransform(parentCmd, recursive); if (node._positionsAreDirty) { node._updatePositions(); node._positionsAreDirty = false; @@ -68,7 +68,7 @@ var children = node._children; for(var i=0; i * Sets whether the widget is enabled
From 956b26e70c391c3f2df5e50514128d281ec4e625 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Tue, 6 Dec 2016 12:13:22 +0800 Subject: [PATCH 19/42] Fix issues in #3407 --- cocos2d/core/labelttf/CCLabelTTF.js | 32 +++++++++++++------ .../labelttf/CCLabelTTFCanvasRenderCmd.js | 21 ++---------- extensions/ccui/uiwidgets/UIText.js | 2 +- 3 files changed, 26 insertions(+), 29 deletions(-) diff --git a/cocos2d/core/labelttf/CCLabelTTF.js b/cocos2d/core/labelttf/CCLabelTTF.js index fe4b712751..2bfb105988 100644 --- a/cocos2d/core/labelttf/CCLabelTTF.js +++ b/cocos2d/core/labelttf/CCLabelTTF.js @@ -610,9 +610,9 @@ cc.LabelTTF = cc.Sprite.extend(/** @lends cc.LabelTTF# */{ * @param {Number} [scaleY=] */ setScale: function (scale, scaleY) { - this._scaleX = scale / cc.view.getDevicePixelRatio(); - this._scaleY = ((scaleY || scaleY === 0) ? scaleY : scale) / - cc.view.getDevicePixelRatio(); + var ratio = cc.view.getDevicePixelRatio(); + this._scaleX = scale / ratio; + this._scaleY = ((scaleY || scaleY === 0) ? scaleY : scale) / ratio; this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.transformDirty); }, @@ -806,25 +806,37 @@ cc.LabelTTF = cc.Sprite.extend(/** @lends cc.LabelTTF# */{ getContentSize: function () { if (this._needUpdateTexture) this._renderCmd._updateTTF(); - return cc.size( - this._contentSize.width / cc.view.getDevicePixelRatio(), - this._contentSize.height / cc.view.getDevicePixelRatio()); + var ratio = cc.view.getDevicePixelRatio(); + return cc.size( this._contentSize.width / ratio, this._contentSize.height / ratio ); }, _getWidth: function () { if (this._needUpdateTexture) this._renderCmd._updateTTF(); - return cc.Sprite.prototype._getWidth.call(this); + return this._contentSize.width / cc.view.getDevicePixelRatio(); }, _getHeight: function () { if (this._needUpdateTexture) this._renderCmd._updateTTF(); - return cc.Sprite.prototype._getHeight.call(this); + return this._contentSize.height / cc.view.getDevicePixelRatio(); }, setTextureRect: function (rect, rotated, untrimmedSize) { - //set needConvert to false - cc.Sprite.prototype.setTextureRect.call(this, rect, rotated, untrimmedSize, false); + var _t = this; + _t._rectRotated = rotated || false; + _t.setContentSize(untrimmedSize || rect); + + _t.setVertexRect(rect); + _t._renderCmd._setTextureCoords(rect, false); + + var relativeOffsetX = _t._unflippedOffsetPositionFromCenter.x, relativeOffsetY = _t._unflippedOffsetPositionFromCenter.y; + if (_t._flippedX) + relativeOffsetX = -relativeOffsetX; + if (_t._flippedY) + relativeOffsetY = -relativeOffsetY; + var locRect = _t._rect; + _t._offsetPosition.x = relativeOffsetX + (rect.width - locRect.width) / 2; + _t._offsetPosition.y = relativeOffsetY + (rect.height - locRect.height) / 2; }, /** diff --git a/cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js b/cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js index 5949af7e97..3cbfda1e0a 100644 --- a/cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js +++ b/cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js @@ -103,7 +103,8 @@ cc.LabelTTF._firsrEnglish = /^[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]/; proto._updateTTF = function () { var node = this._node; - var locDimensionsWidth = node._dimensions.width, i, strLength; + var pixelRatio = cc.view.getDevicePixelRatio(); + var locDimensionsWidth = node._dimensions.width * pixelRatio, i, strLength; var locLineWidth = this._lineWidths; locLineWidth.length = 0; @@ -135,7 +136,6 @@ cc.LabelTTF._firsrEnglish = /^[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]/; locStrokeShadowOffsetY += Math.abs(locOffsetSize.y) * 2; } - var pixelRatio = cc.view.getDevicePixelRatio(); //get offset for stroke and shadow if (locDimensionsWidth === 0) { if (this._isMultiLine) @@ -178,6 +178,7 @@ cc.LabelTTF._firsrEnglish = /^[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]/; proto._saveStatus = function () { var node = this._node; + var scale = cc.view.getDevicePixelRatio(); var locStrokeShadowOffsetX = node._strokeShadowOffsetX, locStrokeShadowOffsetY = node._strokeShadowOffsetY; var locContentSizeHeight = node._contentSize.height - locStrokeShadowOffsetY, locVAlignment = node._vAlignment, locHAlignment = node._hAlignment; @@ -310,32 +311,16 @@ cc.LabelTTF._firsrEnglish = /^[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]/; proto.updateStatus = function () { var flags = cc.Node._dirtyFlags, locFlag = this._dirtyFlag; - -<<<<<<< HEAD -======= - cc.Node.RenderCmd.prototype.updateStatus.call(this); ->>>>>>> 45cdfaa... Revert "Fix UIText issue and Label getContentSize value wrong in retina mode" if (locFlag & flags.textDirty) this._updateTexture(); cc.Node.RenderCmd.prototype.updateStatus.call(this); - - if (this._dirtyFlag & flags.transformDirty){ - this.transform(this.getParentRenderCmd(), true); - this._dirtyFlag = this._dirtyFlag & cc.Node._dirtyFlags.transformDirty ^ this._dirtyFlag; - } }; proto._syncStatus = function (parentCmd) { var flags = cc.Node._dirtyFlags, locFlag = this._dirtyFlag; -<<<<<<< HEAD -======= - - cc.Node.RenderCmd.prototype._syncStatus.call(this, parentCmd); - ->>>>>>> 45cdfaa... Revert "Fix UIText issue and Label getContentSize value wrong in retina mode" if (locFlag & flags.textDirty) this._updateTexture(); diff --git a/extensions/ccui/uiwidgets/UIText.js b/extensions/ccui/uiwidgets/UIText.js index 329ccf508e..bfa1198a77 100644 --- a/extensions/ccui/uiwidgets/UIText.js +++ b/extensions/ccui/uiwidgets/UIText.js @@ -46,7 +46,7 @@ ccui.Text = ccui.Widget.extend(/** @lends ccui.Text# */{ _fontName: "Arial", _fontSize: 16, _onSelectedScaleOffset:0.5, - _labelRenderer: "", + _labelRenderer: null, _textAreaSize: null, _textVerticalAlignment: 0, _textHorizontalAlignment: 0, From a6dd03401e27da38bae9f8d1175711c467f6f906 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Thu, 8 Dec 2016 17:03:39 +0800 Subject: [PATCH 20/42] Code formatting --- CCBoot.js | 10 +- cocos2d/actions/CCAction.js | 142 ++--- cocos2d/actions/CCActionInterval.js | 525 +++++++++--------- cocos2d/actions/CCActionTween.js | 43 +- cocos2d/audio/CCAudio.js | 176 +++--- cocos2d/clipping-nodes/CCClippingNode.js | 9 +- .../CCClippingNodeCanvasRenderCmd.js | 45 +- .../CCClippingNodeWebGLRenderCmd.js | 22 +- cocos2d/core/CCDirector.js | 6 +- .../base-nodes/CCAtlasNodeCanvasRenderCmd.js | 16 +- .../base-nodes/CCAtlasNodeWebGLRenderCmd.js | 18 +- cocos2d/core/base-nodes/CCNode.js | 136 ++--- .../core/base-nodes/CCNodeCanvasRenderCmd.js | 2 +- .../core/base-nodes/CCNodeWebGLRenderCmd.js | 3 +- cocos2d/core/cocoa/CCAffineTransform.js | 34 +- cocos2d/core/event-manager/CCEventHelper.js | 79 +-- cocos2d/core/event-manager/CCEventManager.js | 88 +-- cocos2d/core/labelttf/CCLabelTTF.js | 14 +- .../labelttf/CCLabelTTFCanvasRenderCmd.js | 25 +- .../core/labelttf/CCLabelTTFWebGLRenderCmd.js | 7 +- cocos2d/core/layers/CCLayer.js | 54 +- cocos2d/core/layers/CCLayerCanvasRenderCmd.js | 108 ++-- cocos2d/core/layers/CCLayerWebGLRenderCmd.js | 54 +- cocos2d/core/platform/CCCommon.js | 228 ++++---- cocos2d/core/platform/CCEGLView.js | 84 +-- cocos2d/core/platform/CCInputManager.js | 120 ++-- cocos2d/core/platform/CCLoaders.js | 62 +-- cocos2d/core/platform/CCTypes.js | 48 +- cocos2d/core/renderer/RendererCanvas.js | 2 +- cocos2d/core/renderer/RendererWebGL.js | 10 +- cocos2d/core/sprites/CCSprite.js | 130 ++--- cocos2d/core/sprites/CCSpriteBatchNode.js | 26 +- .../core/sprites/CCSpriteCanvasRenderCmd.js | 27 +- cocos2d/core/sprites/CCSpriteFrame.js | 112 ++-- cocos2d/core/sprites/CCSpriteFrameCache.js | 68 +-- .../core/sprites/CCSpriteWebGLRenderCmd.js | 18 +- cocos2d/core/textures/CCTexture2D.js | 53 +- cocos2d/core/textures/CCTextureCache.js | 9 +- cocos2d/core/textures/TexturesWebGL.js | 60 +- cocos2d/core/utils/CCProfiler.js | 10 +- cocos2d/effects/CCGrid.js | 233 ++++---- cocos2d/kazmath/gl/mat4stack.js | 20 +- cocos2d/kazmath/gl/matrix.js | 2 +- cocos2d/labels/CCLabelAtlasWebGLRenderCmd.js | 35 +- cocos2d/labels/CCLabelBMFont.js | 32 +- .../labels/CCLabelBMFontCanvasRenderCmd.js | 14 +- cocos2d/labels/CCLabelBMFontWebGLRenderCmd.js | 10 +- cocos2d/menus/CCMenu.js | 8 +- cocos2d/motion-streak/CCMotionStreak.js | 106 ++-- .../CCMotionStreakWebGLRenderCmd.js | 4 +- cocos2d/node-grid/CCNodeGridWebGLRenderCmd.js | 28 +- cocos2d/parallax/CCParallaxNodeRenderCmd.js | 14 +- cocos2d/particle/CCParticleBatchNode.js | 88 +-- .../CCParticleBatchNodeCanvasRenderCmd.js | 5 +- .../CCParticleBatchNodeWebGLRenderCmd.js | 6 +- cocos2d/particle/CCParticleSystem.js | 372 ++++++------- .../CCParticleSystemCanvasRenderCmd.js | 35 +- .../CCParticleSystemWebGLRenderCmd.js | 60 +- .../CCPhysicsDebugNodeCanvasRenderCmd.js | 2 +- cocos2d/physics/CCPhysicsSprite.js | 95 ++-- .../physics/CCPhysicsSpriteCanvasRenderCmd.js | 8 +- .../physics/CCPhysicsSpriteWebGLRenderCmd.js | 6 +- .../CCProgressTimerCanvasRenderCmd.js | 46 +- .../CCProgressTimerWebGLRenderCmd.js | 38 +- cocos2d/render-texture/CCRenderTexture.js | 112 ++-- .../CCRenderTextureCanvasRenderCmd.js | 27 +- .../CCRenderTextureWebGLRenderCmd.js | 43 +- cocos2d/shaders/CCGLProgram.js | 42 +- cocos2d/shape-nodes/CCDrawNode.js | 86 +-- .../shape-nodes/CCDrawNodeCanvasRenderCmd.js | 14 +- .../shape-nodes/CCDrawNodeWebGLRenderCmd.js | 2 +- cocos2d/text-input/CCIMEDispatcher.js | 92 +-- cocos2d/text-input/CCTextFieldTTF.js | 116 ++-- cocos2d/tilemap/CCTGAlib.js | 45 +- cocos2d/tilemap/CCTMXLayerCanvasRenderCmd.js | 20 +- cocos2d/tilemap/CCTMXLayerWebGLRenderCmd.js | 50 +- cocos2d/transitions/CCTransition.js | 298 +++++----- cocos2d/transitions/CCTransitionPageTurn.js | 18 +- extensions/ccb-reader/CCBAnimationManager.js | 315 ++++++----- extensions/ccb-reader/CCBReader.js | 198 +++---- extensions/ccb-reader/CCBReaderUtil.js | 23 +- extensions/ccb-reader/CCBValue.js | 16 +- extensions/ccb-reader/CCControlLoader.js | 98 ++-- extensions/ccb-reader/CCNodeLoader.js | 72 +-- .../ccui/base-classes/CCProtectedNode.js | 92 +-- .../CCProtectedNodeCanvasRenderCmd.js | 24 +- .../CCProtectedNodeWebGLRenderCmd.js | 12 +- extensions/ccui/base-classes/UIWidget.js | 218 ++++---- extensions/ccui/layouts/UILayout.js | 186 +++---- .../ccui/layouts/UILayoutCanvasRenderCmd.js | 16 +- extensions/ccui/layouts/UILayoutManager.js | 56 +- .../ccui/layouts/UILayoutWebGLRenderCmd.js | 33 +- extensions/ccui/system/UIHelper.js | 168 +++--- extensions/ccui/uiwidgets/UILoadingBar.js | 46 +- extensions/ccui/uiwidgets/UIRichText.js | 69 ++- extensions/ccui/uiwidgets/UISlider.js | 79 ++- extensions/ccui/uiwidgets/UIText.js | 44 +- extensions/ccui/uiwidgets/UITextBMFont.js | 34 +- extensions/ccui/uiwidgets/UIVideoPlayer.js | 195 ++++--- extensions/ccui/uiwidgets/UIWebView.js | 154 ++--- .../uiwidgets/scroll-widget/UIListView.js | 263 ++++----- .../uiwidgets/scroll-widget/UIPageView.js | 174 +++--- .../scroll-widget/UIPageViewIndicator.js | 109 ++-- .../uiwidgets/scroll-widget/UIScrollView.js | 288 ++++------ .../scroll-widget/UIScrollViewBar.js | 124 ++--- .../UIScrollViewCanvasRenderCmd.js | 10 +- .../UIScrollViewWebGLRenderCmd.js | 11 +- .../cocostudio/action/CCActionManager.js | 16 +- extensions/cocostudio/action/CCActionNode.js | 26 +- extensions/cocostudio/armature/CCArmature.js | 20 +- .../armature/CCArmatureCanvasRenderCmd.js | 38 +- .../armature/CCArmatureWebGLRenderCmd.js | 26 +- extensions/cocostudio/armature/CCBone.js | 66 +-- .../armature/display/CCDisplayManager.js | 90 +-- .../armature/display/CCSkinRenderCmd.js | 22 +- extensions/cocostudio/loader/load.js | 96 ++-- .../cocostudio/loader/parsers/compatible.js | 68 +-- .../cocostudio/loader/parsers/scene-1.x.js | 128 ++--- .../loader/parsers/timelineParser-1.x.js | 162 +++--- .../loader/parsers/timelineParser-2.x.js | 412 +++++++------- .../cocostudio/loader/parsers/uiParser-1.x.js | 60 +- .../cocostudio/timeline/ActionTimeline.js | 140 +++-- extensions/cocostudio/timeline/CCBoneNode.js | 55 +- .../cocostudio/timeline/CCSkeletonNode.js | 78 +-- extensions/cocostudio/timeline/CCSkinNode.js | 10 +- extensions/cocostudio/timeline/Frame.js | 368 ++++++------ extensions/cocostudio/timeline/Timeline.js | 105 ++-- extensions/editbox/CCEditBox.js | 190 +++---- extensions/gui/scrollview/CCScrollView.js | 214 +++---- .../scrollview/CCScrollViewCanvasRenderCmd.js | 4 +- .../scrollview/CCScrollViewWebGLRenderCmd.js | 12 +- extensions/gui/scrollview/CCTableView.js | 164 +++--- extensions/spine/CCSkeletonCanvasRenderCmd.js | 46 +- extensions/spine/CCSkeletonWebGLRenderCmd.js | 14 +- 134 files changed, 5239 insertions(+), 5433 deletions(-) diff --git a/CCBoot.js b/CCBoot.js index 4c77147e6f..ec03e1080a 100644 --- a/CCBoot.js +++ b/CCBoot.js @@ -1772,7 +1772,7 @@ var _initSys = function () { * Indicate the running browser version * @memberof cc.sys * @name browserVersion - * @type {Number} + * @type {String} */ sys.browserVersion = ""; /* Determine the browser version number */ @@ -1792,7 +1792,7 @@ var _initSys = function () { * Indicate the real pixel resolution of the whole game window * @memberof cc.sys * @name windowPixelResolution - * @type {Number} + * @type {Size} */ sys.windowPixelResolution = { width: ratio * w, @@ -1811,7 +1811,7 @@ var _initSys = function () { canvas.height = 1; var context = canvas.getContext('2d'); context.fillStyle = '#000'; - context.fillRect(0,0,1,1); + context.fillRect(0, 0, 1, 1); context.globalCompositeOperation = 'multiply'; var canvas2 = _tmpCanvas2; @@ -1819,10 +1819,10 @@ var _initSys = function () { canvas2.height = 1; var context2 = canvas2.getContext('2d'); context2.fillStyle = '#fff'; - context2.fillRect(0,0,1,1); + context2.fillRect(0, 0, 1, 1); context.drawImage(canvas2, 0, 0, 1, 1); - return context.getImageData(0,0,1,1).data[0] === 0; + return context.getImageData(0, 0, 1, 1).data[0] === 0; })(); // Adjust mobile css settings diff --git a/cocos2d/actions/CCAction.js b/cocos2d/actions/CCAction.js index 8e823805b4..1fdc778d29 100644 --- a/cocos2d/actions/CCAction.js +++ b/cocos2d/actions/CCAction.js @@ -43,16 +43,16 @@ cc.ACTION_TAG_INVALID = -1; */ cc.Action = cc.Class.extend(/** @lends cc.Action# */{ //***********variables************* - originalTarget:null, - target:null, - tag:cc.ACTION_TAG_INVALID, + originalTarget: null, + target: null, + tag: cc.ACTION_TAG_INVALID, //**************Public Functions*********** /** * Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function. */ - ctor:function () { + ctor: function () { this.originalTarget = null; this.target = null; this.tag = cc.ACTION_TAG_INVALID; @@ -65,7 +65,7 @@ cc.Action = cc.Class.extend(/** @lends cc.Action# */{ * * @return {cc.Action} */ - copy:function () { + copy: function () { cc.log("copy is deprecated. Please use clone instead."); return this.clone(); }, @@ -76,7 +76,7 @@ cc.Action = cc.Class.extend(/** @lends cc.Action# */{ * * @return {cc.Action} */ - clone:function () { + clone: function () { var action = new cc.Action(); action.originalTarget = null; action.target = null; @@ -89,7 +89,7 @@ cc.Action = cc.Class.extend(/** @lends cc.Action# */{ * * @return {Boolean} */ - isDone:function () { + isDone: function () { return true; }, @@ -98,7 +98,7 @@ cc.Action = cc.Class.extend(/** @lends cc.Action# */{ * * @param {cc.Node} target */ - startWithTarget:function (target) { + startWithTarget: function (target) { this.originalTarget = target; this.target = target; }, @@ -107,7 +107,7 @@ cc.Action = cc.Class.extend(/** @lends cc.Action# */{ * called after the action has finished. It will set the 'target' to nil.
* IMPORTANT: You should never call "action stop" manually. Instead, use: "target.stopAction(action);" */ - stop:function () { + stop: function () { this.target = null; }, @@ -117,7 +117,7 @@ cc.Action = cc.Class.extend(/** @lends cc.Action# */{ * * @param {Number} dt */ - step:function (dt) { + step: function (dt) { cc.log("[Action step]. override me"); }, @@ -126,7 +126,7 @@ cc.Action = cc.Class.extend(/** @lends cc.Action# */{ * * @param {Number} dt */ - update:function (dt) { + update: function (dt) { cc.log("[Action update]. override me"); }, @@ -135,7 +135,7 @@ cc.Action = cc.Class.extend(/** @lends cc.Action# */{ * * @return {cc.Node} */ - getTarget:function () { + getTarget: function () { return this.target; }, @@ -144,7 +144,7 @@ cc.Action = cc.Class.extend(/** @lends cc.Action# */{ * * @param {cc.Node} target */ - setTarget:function (target) { + setTarget: function (target) { this.target = target; }, @@ -153,7 +153,7 @@ cc.Action = cc.Class.extend(/** @lends cc.Action# */{ * * @return {cc.Node} */ - getOriginalTarget:function () { + getOriginalTarget: function () { return this.originalTarget; }, @@ -164,7 +164,7 @@ cc.Action = cc.Class.extend(/** @lends cc.Action# */{ * The target is 'assigned', it is not 'retained'.
* @param {cc.Node} originalTarget */ - setOriginalTarget:function (originalTarget) { + setOriginalTarget: function (originalTarget) { this.originalTarget = originalTarget; }, @@ -172,7 +172,7 @@ cc.Action = cc.Class.extend(/** @lends cc.Action# */{ * get tag number. * @return {Number} */ - getTag:function () { + getTag: function () { return this.tag; }, @@ -180,7 +180,7 @@ cc.Action = cc.Class.extend(/** @lends cc.Action# */{ * set tag number. * @param {Number} tag */ - setTag:function (tag) { + setTag: function (tag) { this.tag = tag; }, @@ -189,7 +189,7 @@ cc.Action = cc.Class.extend(/** @lends cc.Action# */{ * and the ugly workaround is to use retain/release. So, these 2 methods were added to be compatible with JSB.
* This is a hack, and should be removed once JSB fixes the retain/release bug. */ - retain:function () { + retain: function () { }, /** @@ -197,7 +197,7 @@ cc.Action = cc.Class.extend(/** @lends cc.Action# */{ * and the ugly workaround is to use retain/release. So, these 2 methods were added to be compatible with JSB.
* This is a hack, and should be removed once JSB fixes the retain/release bug. */ - release:function () { + release: function () { } }); @@ -244,7 +244,7 @@ cc.FiniteTimeAction = cc.Action.extend(/** @lends cc.FiniteTimeAction# */{ /** * Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function. */ - ctor:function () { + ctor: function () { cc.Action.prototype.ctor.call(this); this._duration = 0; }, @@ -254,7 +254,7 @@ cc.FiniteTimeAction = cc.Action.extend(/** @lends cc.FiniteTimeAction# */{ * * @return {Number} */ - getDuration:function () { + getDuration: function () { return this._duration * (this._timesForRepeat || 1); }, @@ -263,7 +263,7 @@ cc.FiniteTimeAction = cc.Action.extend(/** @lends cc.FiniteTimeAction# */{ * * @param {Number} duration */ - setDuration:function (duration) { + setDuration: function (duration) { this._duration = duration; }, @@ -276,7 +276,7 @@ cc.FiniteTimeAction = cc.Action.extend(/** @lends cc.FiniteTimeAction# */{ * * @return {?cc.Action} */ - reverse:function () { + reverse: function () { cc.log("cocos2d: FiniteTimeAction#reverse: Implement me"); return null; }, @@ -287,7 +287,7 @@ cc.FiniteTimeAction = cc.Action.extend(/** @lends cc.FiniteTimeAction# */{ * * @return {cc.FiniteTimeAction} */ - clone:function () { + clone: function () { return new cc.FiniteTimeAction(); } }); @@ -304,20 +304,20 @@ cc.FiniteTimeAction = cc.Action.extend(/** @lends cc.FiniteTimeAction# */{ * @param {Number} speed */ cc.Speed = cc.Action.extend(/** @lends cc.Speed# */{ - _speed:0.0, - _innerAction:null, + _speed: 0.0, + _innerAction: null, - /** + /** * Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function. - * @param {cc.ActionInterval} action - * @param {Number} speed - */ - ctor:function (action, speed) { + * @param {cc.ActionInterval} action + * @param {Number} speed + */ + ctor: function (action, speed) { cc.Action.prototype.ctor.call(this); this._speed = 0; this._innerAction = null; - action && this.initWithAction(action, speed); + action && this.initWithAction(action, speed); }, /** @@ -326,7 +326,7 @@ cc.Speed = cc.Action.extend(/** @lends cc.Speed# */{ * * @return {Number} */ - getSpeed:function () { + getSpeed: function () { return this._speed; }, @@ -335,7 +335,7 @@ cc.Speed = cc.Action.extend(/** @lends cc.Speed# */{ * * @param {Number} speed */ - setSpeed:function (speed) { + setSpeed: function (speed) { this._speed = speed; }, @@ -346,8 +346,8 @@ cc.Speed = cc.Action.extend(/** @lends cc.Speed# */{ * @param {Number} speed * @return {Boolean} */ - initWithAction:function (action, speed) { - if(!action) + initWithAction: function (action, speed) { + if (!action) throw new Error("cc.Speed.initWithAction(): action must be non nil"); this._innerAction = action; @@ -361,7 +361,7 @@ cc.Speed = cc.Action.extend(/** @lends cc.Speed# */{ * * @returns {cc.Speed} */ - clone:function () { + clone: function () { var action = new cc.Speed(); action.initWithAction(this._innerAction.clone(), this._speed); return action; @@ -372,7 +372,7 @@ cc.Speed = cc.Action.extend(/** @lends cc.Speed# */{ * * @param {cc.Node} target */ - startWithTarget:function (target) { + startWithTarget: function (target) { cc.Action.prototype.startWithTarget.call(this, target); this._innerAction.startWithTarget(target); }, @@ -380,7 +380,7 @@ cc.Speed = cc.Action.extend(/** @lends cc.Speed# */{ /** * Stop the action. */ - stop:function () { + stop: function () { this._innerAction.stop(); cc.Action.prototype.stop.call(this); }, @@ -391,7 +391,7 @@ cc.Speed = cc.Action.extend(/** @lends cc.Speed# */{ * * @param {Number} dt */ - step:function (dt) { + step: function (dt) { this._innerAction.step(dt * this._speed); }, @@ -400,7 +400,7 @@ cc.Speed = cc.Action.extend(/** @lends cc.Speed# */{ * * @return {Boolean} */ - isDone:function () { + isDone: function () { return this._innerAction.isDone(); }, @@ -413,7 +413,7 @@ cc.Speed = cc.Action.extend(/** @lends cc.Speed# */{ * * @return {cc.Speed} */ - reverse:function () { + reverse: function () { return new cc.Speed(this._innerAction.reverse(), this._speed); }, @@ -421,7 +421,7 @@ cc.Speed = cc.Action.extend(/** @lends cc.Speed# */{ * Set inner Action. * @param {cc.ActionInterval} action */ - setInnerAction:function (action) { + setInnerAction: function (action) { if (this._innerAction !== action) { this._innerAction = action; } @@ -432,7 +432,7 @@ cc.Speed = cc.Action.extend(/** @lends cc.Speed# */{ * * @return {cc.ActionInterval} */ - getInnerAction:function () { + getInnerAction: function () { return this._innerAction; } }); @@ -492,29 +492,29 @@ cc.Speed.create = cc.speed; */ cc.Follow = cc.Action.extend(/** @lends cc.Follow# */{ // node to follow - _followedNode:null, + _followedNode: null, // whether camera should be limited to certain area - _boundarySet:false, + _boundarySet: false, // if screen size is bigger than the boundary - update not needed - _boundaryFullyCovered:false, + _boundaryFullyCovered: false, // fast access to the screen dimensions - _halfScreenSize:null, - _fullScreenSize:null, - _worldRect:null, + _halfScreenSize: null, + _fullScreenSize: null, + _worldRect: null, - leftBoundary:0.0, - rightBoundary:0.0, - topBoundary:0.0, - bottomBoundary:0.0, + leftBoundary: 0.0, + rightBoundary: 0.0, + topBoundary: 0.0, + bottomBoundary: 0.0, - /** + /** * Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function.
- * creates the action with a set boundary.
- * creates the action with no boundary set. + * creates the action with a set boundary.
+ * creates the action with no boundary set. * @param {cc.Node} followedNode * @param {cc.Rect} rect - */ - ctor:function (followedNode, rect) { + */ + ctor: function (followedNode, rect) { cc.Action.prototype.ctor.call(this); this._followedNode = null; this._boundarySet = false; @@ -529,9 +529,9 @@ cc.Follow = cc.Action.extend(/** @lends cc.Follow# */{ this.bottomBoundary = 0.0; this._worldRect = cc.rect(0, 0, 0, 0); - if(followedNode) - rect ? this.initWithTarget(followedNode, rect) - : this.initWithTarget(followedNode); + if (followedNode) + rect ? this.initWithTarget(followedNode, rect) + : this.initWithTarget(followedNode); }, /** @@ -540,7 +540,7 @@ cc.Follow = cc.Action.extend(/** @lends cc.Follow# */{ * * @return {cc.Follow} */ - clone:function () { + clone: function () { var action = new cc.Follow(); var locRect = this._worldRect; var rect = new cc.Rect(locRect.x, locRect.y, locRect.width, locRect.height); @@ -553,7 +553,7 @@ cc.Follow = cc.Action.extend(/** @lends cc.Follow# */{ * * @return {Boolean} */ - isBoundarySet:function () { + isBoundarySet: function () { return this._boundarySet; }, @@ -562,7 +562,7 @@ cc.Follow = cc.Action.extend(/** @lends cc.Follow# */{ * * @param {Boolean} value */ - setBoundarySet:function (value) { + setBoudarySet: function (value) { this._boundarySet = value; }, @@ -573,8 +573,8 @@ cc.Follow = cc.Action.extend(/** @lends cc.Follow# */{ * @param {cc.Rect} [rect=] * @return {Boolean} */ - initWithTarget:function (followedNode, rect) { - if(!followedNode) + initWithTarget: function (followedNode, rect) { + if (!followedNode) throw new Error("cc.Follow.initWithAction(): followedNode must be non nil"); var _this = this; @@ -619,7 +619,7 @@ cc.Follow = cc.Action.extend(/** @lends cc.Follow# */{ * * @param {Number} dt */ - step:function (dt) { + step: function (dt) { var tempPosX = this._followedNode.x; var tempPosY = this._followedNode.y; tempPosX = this._halfScreenSize.x - tempPosX; @@ -633,7 +633,7 @@ cc.Follow = cc.Action.extend(/** @lends cc.Follow# */{ if (this._boundaryFullyCovered) return; - this.target.setPosition(cc.clampf(tempPosX, this.leftBoundary, this.rightBoundary), cc.clampf(tempPosY, this.bottomBoundary, this.topBoundary)); + this.target.setPosition(cc.clampf(tempPosX, this.leftBoundary, this.rightBoundary), cc.clampf(tempPosY, this.bottomBoundary, this.topBoundary)); } else { this.target.setPosition(tempPosX, tempPosY); } @@ -644,14 +644,14 @@ cc.Follow = cc.Action.extend(/** @lends cc.Follow# */{ * * @return {Boolean} */ - isDone:function () { + isDone: function () { return ( !this._followedNode.running ); }, /** * Stop the action. */ - stop:function () { + stop: function () { this.target = null; cc.Action.prototype.stop.call(this); } diff --git a/cocos2d/actions/CCActionInterval.js b/cocos2d/actions/CCActionInterval.js index 351df14bf2..274dc48651 100644 --- a/cocos2d/actions/CCActionInterval.js +++ b/cocos2d/actions/CCActionInterval.js @@ -44,10 +44,10 @@ * var actionInterval = new cc.ActionInterval(3); */ cc.ActionInterval = cc.FiniteTimeAction.extend(/** @lends cc.ActionInterval# */{ - _elapsed:0, - _firstTick:false, + _elapsed: 0, + _firstTick: false, _easeList: null, - _timesForRepeat:1, + _timesForRepeat: 1, _repeatForever: false, _repeatMethod: false,//Compatible with repeat class, Discard after can be deleted _speed: 1, @@ -57,7 +57,7 @@ cc.ActionInterval = cc.FiniteTimeAction.extend(/** @lends cc.ActionInterval# */{ * Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function. * @param {Number} d duration in seconds */ - ctor:function (d) { + ctor: function (d) { this._speed = 1; this._timesForRepeat = 1; this._repeatForever = false; @@ -72,7 +72,7 @@ cc.ActionInterval = cc.FiniteTimeAction.extend(/** @lends cc.ActionInterval# */{ * How many seconds had elapsed since the actions started to run. * @return {Number} */ - getElapsed:function () { + getElapsed: function () { return this._elapsed; }, @@ -81,7 +81,7 @@ cc.ActionInterval = cc.FiniteTimeAction.extend(/** @lends cc.ActionInterval# */{ * @param {Number} d duration in seconds * @return {Boolean} */ - initWithDuration:function (d) { + initWithDuration: function (d) { this._duration = (d === 0) ? cc.FLT_EPSILON : d; // prevent division by 0 // This comparison could be in step:, but it might decrease the performance @@ -95,7 +95,7 @@ cc.ActionInterval = cc.FiniteTimeAction.extend(/** @lends cc.ActionInterval# */{ * Returns true if the action has finished. * @return {Boolean} */ - isDone:function () { + isDone: function () { return (this._elapsed >= this._duration); }, @@ -104,7 +104,7 @@ cc.ActionInterval = cc.FiniteTimeAction.extend(/** @lends cc.ActionInterval# */{ * @param {cc.Action} action * @private */ - _cloneDecoration: function(action){ + _cloneDecoration: function (action) { action._repeatForever = this._repeatForever; action._speed = this._speed; action._timesForRepeat = this._timesForRepeat; @@ -113,10 +113,10 @@ cc.ActionInterval = cc.FiniteTimeAction.extend(/** @lends cc.ActionInterval# */{ action._repeatMethod = this._repeatMethod; }, - _reverseEaseList: function(action){ - if(this._easeList){ + _reverseEaseList: function (action) { + if (this._easeList) { action._easeList = []; - for(var i=0; i 0 ? t : 0); //Compatible with repeat class, Discard after can be deleted (this._repeatMethod) - if(this._repeatMethod && this._timesForRepeat > 1 && this.isDone()){ - if(!this._repeatForever){ + if (this._repeatMethod && this._timesForRepeat > 1 && this.isDone()) { + if (!this._repeatForever) { this._timesForRepeat--; } //var diff = locInnerAction.getElapsed() - locInnerAction._duration; @@ -198,7 +198,7 @@ cc.ActionInterval = cc.FiniteTimeAction.extend(/** @lends cc.ActionInterval# */{ * Start this action with target. * @param {cc.Node} target */ - startWithTarget:function (target) { + startWithTarget: function (target) { cc.Action.prototype.startWithTarget.call(this, target); this._elapsed = 0; this._firstTick = true; @@ -210,7 +210,7 @@ cc.ActionInterval = cc.FiniteTimeAction.extend(/** @lends cc.ActionInterval# */{ * * @return {?cc.Action} */ - reverse:function () { + reverse: function () { cc.log("cc.IntervalAction: reverse not implemented."); return null; }, @@ -220,7 +220,7 @@ cc.ActionInterval = cc.FiniteTimeAction.extend(/** @lends cc.ActionInterval# */{ * @warning It should be overridden in subclass. * @param {Number} amp */ - setAmplitudeRate:function (amp) { + setAmplitudeRate: function (amp) { // Abstract class needs implementation cc.log("cc.ActionInterval.setAmplitudeRate(): it should be overridden in subclass."); }, @@ -230,7 +230,7 @@ cc.ActionInterval = cc.FiniteTimeAction.extend(/** @lends cc.ActionInterval# */{ * @warning It should be overridden in subclass. * @return {Number} 0 */ - getAmplitudeRate:function () { + getAmplitudeRate: function () { // Abstract class needs implementation cc.log("cc.ActionInterval.getAmplitudeRate(): it should be overridden in subclass."); return 0; @@ -244,8 +244,8 @@ cc.ActionInterval = cc.FiniteTimeAction.extend(/** @lends cc.ActionInterval# */{ * @param speed * @returns {cc.Action} */ - speed: function(speed){ - if(speed <= 0){ + speed: function (speed) { + if (speed <= 0) { cc.log("The speed parameter error"); return this; } @@ -259,7 +259,7 @@ cc.ActionInterval = cc.FiniteTimeAction.extend(/** @lends cc.ActionInterval# */{ * Get this action speed. * @return {Number} */ - getSpeed: function(){ + getSpeed: function () { return this._speed; }, @@ -268,7 +268,7 @@ cc.ActionInterval = cc.FiniteTimeAction.extend(/** @lends cc.ActionInterval# */{ * @param {Number} speed * @returns {cc.ActionInterval} */ - setSpeed: function(speed){ + setSpeed: function (speed) { this._speed = speed; return this; }, @@ -279,9 +279,9 @@ cc.ActionInterval = cc.FiniteTimeAction.extend(/** @lends cc.ActionInterval# */{ * @param times * @returns {cc.ActionInterval} */ - repeat: function(times){ + repeat: function (times) { times = Math.round(times); - if(isNaN(times) || times < 1){ + if (isNaN(times) || times < 1) { cc.log("The repeat parameter error"); return this; } @@ -295,7 +295,7 @@ cc.ActionInterval = cc.FiniteTimeAction.extend(/** @lends cc.ActionInterval# */{ * To repeat the an action for a limited number of times use the Repeat action.
* @returns {cc.ActionInterval} */ - repeatForever: function(){ + repeatForever: function () { this._repeatMethod = true;//Compatible with repeat class, Discard after can be deleted this._timesForRepeat = this.MAX_VALUE; this._repeatForever = true; @@ -339,16 +339,16 @@ cc.ActionInterval.create = cc.actionInterval; * var seq = new cc.Sequence(actArray); */ cc.Sequence = cc.ActionInterval.extend(/** @lends cc.Sequence# */{ - _actions:null, - _split:null, - _last:0, + _actions: null, + _split: null, + _last: 0, /** * Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function.
* Create an array of sequenceable actions. * @param {Array|cc.FiniteTimeAction} tempArray */ - ctor:function (tempArray) { + ctor: function (tempArray) { cc.ActionInterval.prototype.ctor.call(this); this._actions = []; @@ -375,8 +375,8 @@ cc.Sequence = cc.ActionInterval.extend(/** @lends cc.Sequence# */{ * @param {cc.FiniteTimeAction} actionTwo * @return {Boolean} */ - initWithTwoActions:function (actionOne, actionTwo) { - if(!actionOne || !actionTwo) + initWithTwoActions: function (actionOne, actionTwo) { + if (!actionOne || !actionTwo) throw new Error("cc.Sequence.initWithTwoActions(): arguments must all be non nil"); var d = actionOne._duration + actionTwo._duration; @@ -391,7 +391,7 @@ cc.Sequence = cc.ActionInterval.extend(/** @lends cc.Sequence# */{ * returns a new clone of the action * @returns {cc.Sequence} */ - clone:function () { + clone: function () { var action = new cc.Sequence(); this._cloneDecoration(action); action.initWithTwoActions(this._actions[0].clone(), this._actions[1].clone()); @@ -402,7 +402,7 @@ cc.Sequence = cc.ActionInterval.extend(/** @lends cc.Sequence# */{ * Start the action with target. * @param {cc.Node} target */ - startWithTarget:function (target) { + startWithTarget: function (target) { cc.ActionInterval.prototype.startWithTarget.call(this, target); this._split = this._actions[0]._duration / this._duration; this._last = -1; @@ -411,7 +411,7 @@ cc.Sequence = cc.ActionInterval.extend(/** @lends cc.Sequence# */{ /** * stop the action. */ - stop:function () { + stop: function () { // Issue #1305 if (this._last !== -1) this._actions[this._last].stop(); @@ -422,7 +422,7 @@ cc.Sequence = cc.ActionInterval.extend(/** @lends cc.Sequence# */{ * Called once per frame. Time is the number of seconds of a frame interval. * @param {Number} dt */ - update:function (dt) { + update: function (dt) { var new_t, found = 0; var locSplit = this._split, locActions = this._actions, locLast = this._last, actionFound; @@ -475,7 +475,7 @@ cc.Sequence = cc.ActionInterval.extend(/** @lends cc.Sequence# */{ * Returns a reversed action. * @return {cc.Sequence} */ - reverse:function () { + reverse: function () { var action = cc.Sequence._actionOneTwo(this._actions[1].reverse(), this._actions[0].reverse()); this._cloneDecoration(action); this._reverseEaseList(action); @@ -502,19 +502,19 @@ cc.sequence = function (/*Multiple Arguments*/tempArray) { cc.log("parameters should not be ending with null in Javascript"); var result, current, i, repeat; - while(paramArray && paramArray.length > 0){ + while (paramArray && paramArray.length > 0) { current = Array.prototype.shift.call(paramArray); repeat = current._timesForRepeat || 1; current._repeatMethod = false; current._timesForRepeat = 1; i = 0; - if(!result){ + if (!result) { result = current; i = 1; } - for(i; i @@ -578,13 +578,13 @@ cc.Repeat = cc.ActionInterval.extend(/** @lends cc.Repeat# */{ * @param {Number} times * @return {Boolean} */ - initWithAction:function (action, times) { + initWithAction: function (action, times) { var duration = action._duration * times; if (this.initWithDuration(duration)) { this._times = times; this._innerAction = action; - if (action instanceof cc.ActionInstant){ + if (action instanceof cc.ActionInstant) { this._actionInstant = true; this._times -= 1; } @@ -598,7 +598,7 @@ cc.Repeat = cc.ActionInterval.extend(/** @lends cc.Repeat# */{ * returns a new clone of the action * @returns {cc.Repeat} */ - clone:function () { + clone: function () { var action = new cc.Repeat(); this._cloneDecoration(action); action.initWithAction(this._innerAction.clone(), this._times); @@ -609,7 +609,7 @@ cc.Repeat = cc.ActionInterval.extend(/** @lends cc.Repeat# */{ * Start the action with target. * @param {cc.Node} target */ - startWithTarget:function (target) { + startWithTarget: function (target) { this._total = 0; this._nextDt = this._innerAction._duration / this._duration; cc.ActionInterval.prototype.startWithTarget.call(this, target); @@ -619,7 +619,7 @@ cc.Repeat = cc.ActionInterval.extend(/** @lends cc.Repeat# */{ /** * stop the action */ - stop:function () { + stop: function () { this._innerAction.stop(); cc.Action.prototype.stop.call(this); }, @@ -628,7 +628,7 @@ cc.Repeat = cc.ActionInterval.extend(/** @lends cc.Repeat# */{ * Called once per frame. Time is the number of seconds of a frame interval. * @param {Number} dt */ - update:function (dt) { + update: function (dt) { dt = this._computeEaseTime(dt); var locInnerAction = this._innerAction; var locDuration = this._duration; @@ -668,7 +668,7 @@ cc.Repeat = cc.ActionInterval.extend(/** @lends cc.Repeat# */{ * Return true if the action has finished. * @return {Boolean} */ - isDone:function () { + isDone: function () { return this._total === this._times; }, @@ -676,7 +676,7 @@ cc.Repeat = cc.ActionInterval.extend(/** @lends cc.Repeat# */{ * returns a reversed action. * @return {cc.Repeat} */ - reverse:function () { + reverse: function () { var action = new cc.Repeat(this._innerAction.reverse(), this._times); this._cloneDecoration(action); this._reverseEaseList(action); @@ -687,7 +687,7 @@ cc.Repeat = cc.ActionInterval.extend(/** @lends cc.Repeat# */{ * Set inner Action. * @param {cc.FiniteTimeAction} action */ - setInnerAction:function (action) { + setInnerAction: function (action) { if (this._innerAction !== action) { this._innerAction = action; } @@ -697,7 +697,7 @@ cc.Repeat = cc.ActionInterval.extend(/** @lends cc.Repeat# */{ * Get inner Action. * @return {cc.FiniteTimeAction} */ - getInnerAction:function () { + getInnerAction: function () { return this._innerAction; } }); @@ -738,14 +738,14 @@ cc.Repeat.create = cc.repeat; * var rep = new cc.RepeatForever(cc.sequence(jump2, jump1), 5); */ cc.RepeatForever = cc.ActionInterval.extend(/** @lends cc.RepeatForever# */{ - _innerAction:null, //CCActionInterval + _innerAction: null, //CCActionInterval /** * Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function.
* Create a acton which repeat forever. * @param {cc.FiniteTimeAction} action */ - ctor:function (action) { + ctor: function (action) { cc.ActionInterval.prototype.ctor.call(this); this._innerAction = null; @@ -756,8 +756,8 @@ cc.RepeatForever = cc.ActionInterval.extend(/** @lends cc.RepeatForever# */{ * @param {cc.ActionInterval} action * @return {Boolean} */ - initWithAction:function (action) { - if(!action) + initWithAction: function (action) { + if (!action) throw new Error("cc.RepeatForever.initWithAction(): action must be non null"); this._innerAction = action; @@ -768,7 +768,7 @@ cc.RepeatForever = cc.ActionInterval.extend(/** @lends cc.RepeatForever# */{ * returns a new clone of the action * @returns {cc.RepeatForever} */ - clone:function () { + clone: function () { var action = new cc.RepeatForever(); this._cloneDecoration(action); action.initWithAction(this._innerAction.clone()); @@ -779,7 +779,7 @@ cc.RepeatForever = cc.ActionInterval.extend(/** @lends cc.RepeatForever# */{ * Start the action with target. * @param {cc.Node} target */ - startWithTarget:function (target) { + startWithTarget: function (target) { cc.ActionInterval.prototype.startWithTarget.call(this, target); this._innerAction.startWithTarget(target); }, @@ -789,7 +789,7 @@ cc.RepeatForever = cc.ActionInterval.extend(/** @lends cc.RepeatForever# */{ * DON'T override unless you know what you are doing. * @param dt delta time in seconds */ - step:function (dt) { + step: function (dt) { var locInnerAction = this._innerAction; locInnerAction.step(dt); if (locInnerAction.isDone()) { @@ -806,7 +806,7 @@ cc.RepeatForever = cc.ActionInterval.extend(/** @lends cc.RepeatForever# */{ * Return true if the action has finished. * @return {Boolean} */ - isDone:function () { + isDone: function () { return false; }, @@ -814,7 +814,7 @@ cc.RepeatForever = cc.ActionInterval.extend(/** @lends cc.RepeatForever# */{ * Returns a reversed action. * @return {cc.RepeatForever} */ - reverse:function () { + reverse: function () { var action = new cc.RepeatForever(this._innerAction.reverse()); this._cloneDecoration(action); this._reverseEaseList(action); @@ -825,7 +825,7 @@ cc.RepeatForever = cc.ActionInterval.extend(/** @lends cc.RepeatForever# */{ * Set inner action. * @param {cc.ActionInterval} action */ - setInnerAction:function (action) { + setInnerAction: function (action) { if (this._innerAction !== action) { this._innerAction = action; } @@ -835,7 +835,7 @@ cc.RepeatForever = cc.ActionInterval.extend(/** @lends cc.RepeatForever# */{ * Get inner action. * @return {cc.ActionInterval} */ - getInnerAction:function () { + getInnerAction: function () { return this._innerAction; } }); @@ -872,14 +872,14 @@ cc.RepeatForever.create = cc.repeatForever; * @extends cc.ActionInterval */ cc.Spawn = cc.ActionInterval.extend(/** @lends cc.Spawn# */{ - _one:null, - _two:null, + _one: null, + _two: null, /** * Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function. * @param {Array|cc.FiniteTimeAction} tempArray */ - ctor:function (tempArray) { + ctor: function (tempArray) { cc.ActionInterval.prototype.ctor.call(this); this._one = null; this._two = null; @@ -915,8 +915,8 @@ cc.Spawn = cc.ActionInterval.extend(/** @lends cc.Spawn# */{ * @param {cc.FiniteTimeAction} action2 * @return {Boolean} */ - initWithTwoActions:function (action1, action2) { - if(!action1 || !action2) + initWithTwoActions: function (action1, action2) { + if (!action1 || !action2) throw new Error("cc.Spawn.initWithTwoActions(): arguments must all be non null"); var ret = false; @@ -943,7 +943,7 @@ cc.Spawn = cc.ActionInterval.extend(/** @lends cc.Spawn# */{ * returns a new clone of the action * @returns {cc.Spawn} */ - clone:function () { + clone: function () { var action = new cc.Spawn(); this._cloneDecoration(action); action.initWithTwoActions(this._one.clone(), this._two.clone()); @@ -954,7 +954,7 @@ cc.Spawn = cc.ActionInterval.extend(/** @lends cc.Spawn# */{ * Start the action with target. * @param {cc.Node} target */ - startWithTarget:function (target) { + startWithTarget: function (target) { cc.ActionInterval.prototype.startWithTarget.call(this, target); this._one.startWithTarget(target); this._two.startWithTarget(target); @@ -963,7 +963,7 @@ cc.Spawn = cc.ActionInterval.extend(/** @lends cc.Spawn# */{ /** * Stop the action */ - stop:function () { + stop: function () { this._one.stop(); this._two.stop(); cc.Action.prototype.stop.call(this); @@ -973,7 +973,7 @@ cc.Spawn = cc.ActionInterval.extend(/** @lends cc.Spawn# */{ * Called once per frame. Time is the number of seconds of a frame interval. * @param {Number} dt */ - update:function (dt) { + update: function (dt) { dt = this._computeEaseTime(dt); if (this._one) this._one.update(dt); @@ -985,7 +985,7 @@ cc.Spawn = cc.ActionInterval.extend(/** @lends cc.Spawn# */{ * Returns a reversed action. * @return {cc.Spawn} */ - reverse:function () { + reverse: function () { var action = cc.Spawn._actionOneTwo(this._one.reverse(), this._two.reverse()); this._cloneDecoration(action); this._reverseEaseList(action); @@ -1052,13 +1052,13 @@ cc.Spawn._actionOneTwo = function (action1, action2) { * var rotateTo = new cc.RotateTo(2, 61.0); */ cc.RotateTo = cc.ActionInterval.extend(/** @lends cc.RotateTo# */{ - _dstAngleX:0, - _startAngleX:0, - _diffAngleX:0, + _dstAngleX: 0, + _startAngleX: 0, + _diffAngleX: 0, - _dstAngleY:0, - _startAngleY:0, - _diffAngleY:0, + _dstAngleY: 0, + _startAngleY: 0, + _diffAngleY: 0, /** * Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function.
@@ -1067,7 +1067,7 @@ cc.RotateTo = cc.ActionInterval.extend(/** @lends cc.RotateTo# */{ * @param {Number} deltaAngleX deltaAngleX in degrees. * @param {Number} [deltaAngleY] deltaAngleY in degrees. */ - ctor:function (duration, deltaAngleX, deltaAngleY) { + ctor: function (duration, deltaAngleX, deltaAngleY) { cc.ActionInterval.prototype.ctor.call(this); deltaAngleX !== undefined && this.initWithDuration(duration, deltaAngleX, deltaAngleY); @@ -1080,7 +1080,7 @@ cc.RotateTo = cc.ActionInterval.extend(/** @lends cc.RotateTo# */{ * @param {Number} deltaAngleY * @return {Boolean} */ - initWithDuration:function (duration, deltaAngleX, deltaAngleY) { + initWithDuration: function (duration, deltaAngleX, deltaAngleY) { if (cc.ActionInterval.prototype.initWithDuration.call(this, duration)) { this._dstAngleX = deltaAngleX || 0; this._dstAngleY = deltaAngleY || this._dstAngleX; @@ -1093,7 +1093,7 @@ cc.RotateTo = cc.ActionInterval.extend(/** @lends cc.RotateTo# */{ * returns a new clone of the action * @returns {cc.RotateTo} */ - clone:function () { + clone: function () { var action = new cc.RotateTo(); this._cloneDecoration(action); action.initWithDuration(this._duration, this._dstAngleX, this._dstAngleY); @@ -1104,7 +1104,7 @@ cc.RotateTo = cc.ActionInterval.extend(/** @lends cc.RotateTo# */{ * Start the action with target. * @param {cc.Node} target */ - startWithTarget:function (target) { + startWithTarget: function (target) { cc.ActionInterval.prototype.startWithTarget.call(this, target); // Calculate X @@ -1132,7 +1132,7 @@ cc.RotateTo = cc.ActionInterval.extend(/** @lends cc.RotateTo# */{ * Will be overridden. * @returns {cc.Action} */ - reverse:function () { + reverse: function () { cc.log("cc.RotateTo.reverse(): it should be overridden in subclass."); }, @@ -1140,7 +1140,7 @@ cc.RotateTo = cc.ActionInterval.extend(/** @lends cc.RotateTo# */{ * Called once per frame. Time is the number of seconds of a frame interval. * @param {Number} dt */ - update:function (dt) { + update: function (dt) { dt = this._computeEaseTime(dt); if (this.target) { this.target.rotationX = this._startAngleX + this._diffAngleX * dt; @@ -1191,10 +1191,10 @@ cc.RotateTo.create = cc.rotateTo; * var actionBy = new cc.RotateBy(2, 360); */ cc.RotateBy = cc.ActionInterval.extend(/** @lends cc.RotateBy# */{ - _angleX:0, - _startAngleX:0, - _angleY:0, - _startAngleY:0, + _angleX: 0, + _startAngleX: 0, + _angleY: 0, + _startAngleY: 0, /** * Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function. @@ -1215,7 +1215,7 @@ cc.RotateBy = cc.ActionInterval.extend(/** @lends cc.RotateBy# */{ * @param {Number} [deltaAngleY=] deltaAngleY in degrees * @return {Boolean} */ - initWithDuration:function (duration, deltaAngleX, deltaAngleY) { + initWithDuration: function (duration, deltaAngleX, deltaAngleY) { if (cc.ActionInterval.prototype.initWithDuration.call(this, duration)) { this._angleX = deltaAngleX || 0; this._angleY = deltaAngleY || this._angleX; @@ -1228,7 +1228,7 @@ cc.RotateBy = cc.ActionInterval.extend(/** @lends cc.RotateBy# */{ * returns a new clone of the action * @returns {cc.RotateBy} */ - clone:function () { + clone: function () { var action = new cc.RotateBy(); this._cloneDecoration(action); action.initWithDuration(this._duration, this._angleX, this._angleY); @@ -1239,7 +1239,7 @@ cc.RotateBy = cc.ActionInterval.extend(/** @lends cc.RotateBy# */{ * Start the action with target. * @param {cc.Node} target */ - startWithTarget:function (target) { + startWithTarget: function (target) { cc.ActionInterval.prototype.startWithTarget.call(this, target); this._startAngleX = target.rotationX; this._startAngleY = target.rotationY; @@ -1249,7 +1249,7 @@ cc.RotateBy = cc.ActionInterval.extend(/** @lends cc.RotateBy# */{ * Called once per frame. Time is the number of seconds of a frame interval. * @param {Number} dt */ - update:function (dt) { + update: function (dt) { dt = this._computeEaseTime(dt); if (this.target) { this.target.rotationX = this._startAngleX + this._angleX * dt; @@ -1261,7 +1261,7 @@ cc.RotateBy = cc.ActionInterval.extend(/** @lends cc.RotateBy# */{ * Returns a reversed action. * @return {cc.RotateBy} */ - reverse:function () { + reverse: function () { var action = new cc.RotateBy(this._duration, -this._angleX, -this._angleY); this._cloneDecoration(action); this._reverseEaseList(action); @@ -1314,9 +1314,9 @@ cc.RotateBy.create = cc.rotateBy; * var actionTo = cc.moveBy(2, cc.p(windowSize.width - 40, windowSize.height - 40)); */ cc.MoveBy = cc.ActionInterval.extend(/** @lends cc.MoveBy# */{ - _positionDelta:null, - _startPosition:null, - _previousPosition:null, + _positionDelta: null, + _startPosition: null, + _previousPosition: null, /** * Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function. @@ -1324,7 +1324,7 @@ cc.MoveBy = cc.ActionInterval.extend(/** @lends cc.MoveBy# */{ * @param {cc.Point|Number} deltaPos * @param {Number} [deltaY] */ - ctor:function (duration, deltaPos, deltaY) { + ctor: function (duration, deltaPos, deltaY) { cc.ActionInterval.prototype.ctor.call(this); this._positionDelta = cc.p(0, 0); @@ -1341,9 +1341,9 @@ cc.MoveBy = cc.ActionInterval.extend(/** @lends cc.MoveBy# */{ * @param {Number} [y] * @return {Boolean} */ - initWithDuration:function (duration, position, y) { + initWithDuration: function (duration, position, y) { if (cc.ActionInterval.prototype.initWithDuration.call(this, duration)) { - if(position.x !== undefined) { + if (position.x !== undefined) { y = position.y; position = position.x; } @@ -1359,7 +1359,7 @@ cc.MoveBy = cc.ActionInterval.extend(/** @lends cc.MoveBy# */{ * returns a new clone of the action * @returns {cc.MoveBy} */ - clone:function () { + clone: function () { var action = new cc.MoveBy(); this._cloneDecoration(action); action.initWithDuration(this._duration, this._positionDelta); @@ -1370,7 +1370,7 @@ cc.MoveBy = cc.ActionInterval.extend(/** @lends cc.MoveBy# */{ * Start the action with target. * @param {cc.Node} target */ - startWithTarget:function (target) { + startWithTarget: function (target) { cc.ActionInterval.prototype.startWithTarget.call(this, target); var locPosX = target.getPositionX(); var locPosY = target.getPositionY(); @@ -1384,7 +1384,7 @@ cc.MoveBy = cc.ActionInterval.extend(/** @lends cc.MoveBy# */{ * Called once per frame. Time is the number of seconds of a frame interval. * @param {Number} dt */ - update:function (dt) { + update: function (dt) { dt = this._computeEaseTime(dt); if (this.target) { var x = this._positionDelta.x * dt; @@ -1412,7 +1412,7 @@ cc.MoveBy = cc.ActionInterval.extend(/** @lends cc.MoveBy# */{ * MoveTo reverse is not implemented * @return {cc.MoveBy} */ - reverse:function () { + reverse: function () { var action = new cc.MoveBy(this._duration, cc.p(-this._positionDelta.x, -this._positionDelta.y)); this._cloneDecoration(action); this._reverseEaseList(action); @@ -1461,7 +1461,7 @@ cc.MoveBy.create = cc.moveBy; * var actionBy = new cc.MoveTo(2, cc.p(80, 80)); */ cc.MoveTo = cc.MoveBy.extend(/** @lends cc.MoveTo# */{ - _endPosition:null, + _endPosition: null, /** * Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function. @@ -1469,7 +1469,7 @@ cc.MoveTo = cc.MoveBy.extend(/** @lends cc.MoveTo# */{ * @param {cc.Point|Number} position * @param {Number} y */ - ctor:function (duration, position, y) { + ctor: function (duration, position, y) { cc.MoveBy.prototype.ctor.call(this); this._endPosition = cc.p(0, 0); @@ -1483,9 +1483,9 @@ cc.MoveTo = cc.MoveBy.extend(/** @lends cc.MoveTo# */{ * @param {Number} y * @return {Boolean} */ - initWithDuration:function (duration, position, y) { + initWithDuration: function (duration, position, y) { if (cc.MoveBy.prototype.initWithDuration.call(this, duration, position, y)) { - if(position.x !== undefined) { + if (position.x !== undefined) { y = position.y; position = position.x; } @@ -1501,7 +1501,7 @@ cc.MoveTo = cc.MoveBy.extend(/** @lends cc.MoveTo# */{ * returns a new clone of the action * @returns {cc.MoveTo} */ - clone:function () { + clone: function () { var action = new cc.MoveTo(); this._cloneDecoration(action); action.initWithDuration(this._duration, this._endPosition); @@ -1512,7 +1512,7 @@ cc.MoveTo = cc.MoveBy.extend(/** @lends cc.MoveTo# */{ * Start the action with target. * @param {cc.Node} target */ - startWithTarget:function (target) { + startWithTarget: function (target) { cc.MoveBy.prototype.startWithTarget.call(this, target); this._positionDelta.x = this._endPosition.x - target.getPositionX(); this._positionDelta.y = this._endPosition.y - target.getPositionY(); @@ -1557,14 +1557,14 @@ cc.MoveTo.create = cc.moveTo; * var actionTo = new cc.SkewTo(2, 37.2, -37.2); */ cc.SkewTo = cc.ActionInterval.extend(/** @lends cc.SkewTo# */{ - _skewX:0, - _skewY:0, - _startSkewX:0, - _startSkewY:0, - _endSkewX:0, - _endSkewY:0, - _deltaX:0, - _deltaY:0, + _skewX: 0, + _skewY: 0, + _startSkewX: 0, + _startSkewY: 0, + _endSkewX: 0, + _endSkewY: 0, + _deltaX: 0, + _deltaY: 0, /** * Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function. @@ -1585,7 +1585,7 @@ cc.SkewTo = cc.ActionInterval.extend(/** @lends cc.SkewTo# */{ * @param {Number} sy * @return {Boolean} */ - initWithDuration:function (t, sx, sy) { + initWithDuration: function (t, sx, sy) { var ret = false; if (cc.ActionInterval.prototype.initWithDuration.call(this, t)) { this._endSkewX = sx; @@ -1599,7 +1599,7 @@ cc.SkewTo = cc.ActionInterval.extend(/** @lends cc.SkewTo# */{ * returns a new clone of the action * @returns {cc.SkewTo} */ - clone:function () { + clone: function () { var action = new cc.SkewTo(); this._cloneDecoration(action); action.initWithDuration(this._duration, this._endSkewX, this._endSkewY); @@ -1610,7 +1610,7 @@ cc.SkewTo = cc.ActionInterval.extend(/** @lends cc.SkewTo# */{ * Start the action with target. * @param {cc.Node} target */ - startWithTarget:function (target) { + startWithTarget: function (target) { cc.ActionInterval.prototype.startWithTarget.call(this, target); this._startSkewX = target.skewX % 180; @@ -1632,7 +1632,7 @@ cc.SkewTo = cc.ActionInterval.extend(/** @lends cc.SkewTo# */{ * Called once per frame. Time is the number of seconds of a frame interval. * @param {Number} dt */ - update:function (dt) { + update: function (dt) { dt = this._computeEaseTime(dt); this.target.skewX = this._startSkewX + this._deltaX * dt; this.target.skewY = this._startSkewY + this._deltaY * dt; @@ -1684,7 +1684,7 @@ cc.SkewBy = cc.SkewTo.extend(/** @lends cc.SkewBy# */{ * @param {Number} sx skew in degrees for X axis * @param {Number} sy skew in degrees for Y axis */ - ctor: function(t, sx, sy) { + ctor: function (t, sx, sy) { cc.SkewTo.prototype.ctor.call(this); sy !== undefined && this.initWithDuration(t, sx, sy); }, @@ -1696,7 +1696,7 @@ cc.SkewBy = cc.SkewTo.extend(/** @lends cc.SkewBy# */{ * @param {Number} deltaSkewY skew in degrees for Y axis * @return {Boolean} */ - initWithDuration:function (t, deltaSkewX, deltaSkewY) { + initWithDuration: function (t, deltaSkewX, deltaSkewY) { var ret = false; if (cc.SkewTo.prototype.initWithDuration.call(this, t, deltaSkewX, deltaSkewY)) { this._skewX = deltaSkewX; @@ -1710,7 +1710,7 @@ cc.SkewBy = cc.SkewTo.extend(/** @lends cc.SkewBy# */{ * returns a new clone of the action * @returns {cc.SkewBy} */ - clone:function () { + clone: function () { var action = new cc.SkewBy(); this._cloneDecoration(action); action.initWithDuration(this._duration, this._skewX, this._skewY); @@ -1721,7 +1721,7 @@ cc.SkewBy = cc.SkewTo.extend(/** @lends cc.SkewBy# */{ * Start the action width target. * @param {cc.Node} target */ - startWithTarget:function (target) { + startWithTarget: function (target) { cc.SkewTo.prototype.startWithTarget.call(this, target); this._deltaX = this._skewX; this._deltaY = this._skewY; @@ -1733,7 +1733,7 @@ cc.SkewBy = cc.SkewTo.extend(/** @lends cc.SkewBy# */{ * Returns a reversed action. * @return {cc.SkewBy} */ - reverse:function () { + reverse: function () { var action = new cc.SkewBy(this._duration, -this._skewX, -this._skewY); this._cloneDecoration(action); this._reverseEaseList(action); @@ -1785,11 +1785,11 @@ cc.SkewBy.create = cc.skewBy; * var actionBy = new cc.JumpBy(2, 300, 0, 50, 4); */ cc.JumpBy = cc.ActionInterval.extend(/** @lends cc.JumpBy# */{ - _startPosition:null, - _delta:null, - _height:0, - _jumps:0, - _previousPosition:null, + _startPosition: null, + _delta: null, + _height: 0, + _jumps: 0, + _previousPosition: null, /** * Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function. @@ -1799,7 +1799,7 @@ cc.JumpBy = cc.ActionInterval.extend(/** @lends cc.JumpBy# */{ * @param {Number} height * @param {Number} jumps */ - ctor:function (duration, position, y, height, jumps) { + ctor: function (duration, position, y, height, jumps) { cc.ActionInterval.prototype.ctor.call(this); this._startPosition = cc.p(0, 0); this._previousPosition = cc.p(0, 0); @@ -1819,7 +1819,7 @@ cc.JumpBy = cc.ActionInterval.extend(/** @lends cc.JumpBy# */{ * actionBy.initWithDuration(2, cc.p(300, 0), 50, 4); * actionBy.initWithDuration(2, 300, 0, 50, 4); */ - initWithDuration:function (duration, position, y, height, jumps) { + initWithDuration: function (duration, position, y, height, jumps) { if (cc.ActionInterval.prototype.initWithDuration.call(this, duration)) { if (jumps === undefined) { jumps = height; @@ -1840,7 +1840,7 @@ cc.JumpBy = cc.ActionInterval.extend(/** @lends cc.JumpBy# */{ * returns a new clone of the action * @returns {cc.JumpBy} */ - clone:function () { + clone: function () { var action = new cc.JumpBy(); this._cloneDecoration(action); action.initWithDuration(this._duration, this._delta, this._height, this._jumps); @@ -1851,7 +1851,7 @@ cc.JumpBy = cc.ActionInterval.extend(/** @lends cc.JumpBy# */{ * Start the action with target. * @param {cc.Node} target */ - startWithTarget:function (target) { + startWithTarget: function (target) { cc.ActionInterval.prototype.startWithTarget.call(this, target); var locPosX = target.getPositionX(); var locPosY = target.getPositionY(); @@ -1865,7 +1865,7 @@ cc.JumpBy = cc.ActionInterval.extend(/** @lends cc.JumpBy# */{ * Called once per frame. Time is the number of seconds of a frame interval. * @param {Number} dt */ - update:function (dt) { + update: function (dt) { dt = this._computeEaseTime(dt); if (this.target) { var frac = dt * this._jumps % 1.0; @@ -1896,7 +1896,7 @@ cc.JumpBy = cc.ActionInterval.extend(/** @lends cc.JumpBy# */{ * Returns a reversed action. * @return {cc.JumpBy} */ - reverse:function () { + reverse: function () { var action = new cc.JumpBy(this._duration, cc.p(-this._delta.x, -this._delta.y), this._height, this._jumps); this._cloneDecoration(action); this._reverseEaseList(action); @@ -1952,7 +1952,7 @@ cc.JumpBy.create = cc.jumpBy; * var actionTo = new cc.JumpTo(2, 300, 0, 50, 4); */ cc.JumpTo = cc.JumpBy.extend(/** @lends cc.JumpTo# */{ - _endPosition:null, + _endPosition: null, /** * Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function. @@ -1962,7 +1962,7 @@ cc.JumpTo = cc.JumpBy.extend(/** @lends cc.JumpTo# */{ * @param {Number} height * @param {Number} jumps */ - ctor:function (duration, position, y, height, jumps) { + ctor: function (duration, position, y, height, jumps) { cc.JumpBy.prototype.ctor.call(this); this._endPosition = cc.p(0, 0); @@ -1980,7 +1980,7 @@ cc.JumpTo = cc.JumpBy.extend(/** @lends cc.JumpTo# */{ * actionTo.initWithDuration(2, cc.p(300, 0), 50, 4); * actionTo.initWithDuration(2, 300, 0, 50, 4); */ - initWithDuration:function (duration, position, y, height, jumps) { + initWithDuration: function (duration, position, y, height, jumps) { if (cc.JumpBy.prototype.initWithDuration.call(this, duration, position, y, height, jumps)) { if (jumps === undefined) { y = position.y; @@ -1996,7 +1996,7 @@ cc.JumpTo = cc.JumpBy.extend(/** @lends cc.JumpTo# */{ * Start the action with target. * @param {cc.Node} target */ - startWithTarget:function (target) { + startWithTarget: function (target) { cc.JumpBy.prototype.startWithTarget.call(this, target); this._delta.x = this._endPosition.x - this._startPosition.x; this._delta.y = this._endPosition.y - this._startPosition.y; @@ -2006,7 +2006,7 @@ cc.JumpTo = cc.JumpBy.extend(/** @lends cc.JumpTo# */{ * returns a new clone of the action * @returns {cc.JumpTo} */ - clone:function () { + clone: function () { var action = new cc.JumpTo(); this._cloneDecoration(action); action.initWithDuration(this._duration, this._endPosition, this._height, this._jumps); @@ -2058,9 +2058,9 @@ cc.JumpTo.create = cc.jumpTo; */ cc.bezierAt = function (a, b, c, d, t) { return (Math.pow(1 - t, 3) * a + - 3 * t * (Math.pow(1 - t, 2)) * b + - 3 * Math.pow(t, 2) * (1 - t) * c + - Math.pow(t, 3) * d ); + 3 * t * (Math.pow(1 - t, 2)) * b + + 3 * Math.pow(t, 2) * (1 - t) * c + + Math.pow(t, 3) * d ); }; /** An action that moves the target with a cubic Bezier curve by a certain distance. @@ -2074,16 +2074,16 @@ cc.bezierAt = function (a, b, c, d, t) { * var bezierForward = new cc.BezierBy(3, bezier); */ cc.BezierBy = cc.ActionInterval.extend(/** @lends cc.BezierBy# */{ - _config:null, - _startPosition:null, - _previousPosition:null, + _config: null, + _startPosition: null, + _previousPosition: null, /** * Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function. * @param {Number} t time in seconds * @param {Array} c Array of points */ - ctor:function (t, c) { + ctor: function (t, c) { cc.ActionInterval.prototype.ctor.call(this); this._config = []; this._startPosition = cc.p(0, 0); @@ -2098,7 +2098,7 @@ cc.BezierBy = cc.ActionInterval.extend(/** @lends cc.BezierBy# */{ * @param {Array} c Array of points * @return {Boolean} */ - initWithDuration:function (t, c) { + initWithDuration: function (t, c) { if (cc.ActionInterval.prototype.initWithDuration.call(this, t)) { this._config = c; return true; @@ -2110,7 +2110,7 @@ cc.BezierBy = cc.ActionInterval.extend(/** @lends cc.BezierBy# */{ * returns a new clone of the action * @returns {cc.BezierBy} */ - clone:function () { + clone: function () { var action = new cc.BezierBy(); this._cloneDecoration(action); var newConfigs = []; @@ -2126,7 +2126,7 @@ cc.BezierBy = cc.ActionInterval.extend(/** @lends cc.BezierBy# */{ * Start the action with target. * @param {cc.Node} target */ - startWithTarget:function (target) { + startWithTarget: function (target) { cc.ActionInterval.prototype.startWithTarget.call(this, target); var locPosX = target.getPositionX(); var locPosY = target.getPositionY(); @@ -2140,7 +2140,7 @@ cc.BezierBy = cc.ActionInterval.extend(/** @lends cc.BezierBy# */{ * Called once per frame. Time is the number of seconds of a frame interval. * @param {Number} dt */ - update:function (dt) { + update: function (dt) { dt = this._computeEaseTime(dt); if (this.target) { var locConfig = this._config; @@ -2180,12 +2180,12 @@ cc.BezierBy = cc.ActionInterval.extend(/** @lends cc.BezierBy# */{ * Returns a reversed action. * @return {cc.BezierBy} */ - reverse:function () { + reverse: function () { var locConfig = this._config; var r = [ cc.pAdd(locConfig[1], cc.pNeg(locConfig[2])), cc.pAdd(locConfig[0], cc.pNeg(locConfig[2])), - cc.pNeg(locConfig[2]) ]; + cc.pNeg(locConfig[2])]; var action = new cc.BezierBy(this._duration, r); this._cloneDecoration(action); this._reverseEaseList(action); @@ -2231,7 +2231,7 @@ cc.BezierBy.create = cc.bezierBy; * var bezierTo = new cc.BezierTo(2, bezier); */ cc.BezierTo = cc.BezierBy.extend(/** @lends cc.BezierTo# */{ - _toConfig:null, + _toConfig: null, /** * Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function. @@ -2239,7 +2239,7 @@ cc.BezierTo = cc.BezierBy.extend(/** @lends cc.BezierTo# */{ * @param {Array} c array of points * var bezierTo = new cc.BezierTo(2, bezier); */ - ctor:function (t, c) { + ctor: function (t, c) { cc.BezierBy.prototype.ctor.call(this); this._toConfig = []; c && this.initWithDuration(t, c); @@ -2251,7 +2251,7 @@ cc.BezierTo = cc.BezierBy.extend(/** @lends cc.BezierTo# */{ * @param {Array} c Array of points * @return {Boolean} */ - initWithDuration:function (t, c) { + initWithDuration: function (t, c) { if (cc.ActionInterval.prototype.initWithDuration.call(this, t)) { this._toConfig = c; return true; @@ -2263,7 +2263,7 @@ cc.BezierTo = cc.BezierBy.extend(/** @lends cc.BezierTo# */{ * returns a new clone of the action * @returns {cc.BezierTo} */ - clone:function () { + clone: function () { var action = new cc.BezierTo(); this._cloneDecoration(action); action.initWithDuration(this._duration, this._toConfig); @@ -2274,7 +2274,7 @@ cc.BezierTo = cc.BezierBy.extend(/** @lends cc.BezierTo# */{ * Start the action with target. * @param {cc.Node} target */ - startWithTarget:function (target) { + startWithTarget: function (target) { cc.BezierBy.prototype.startWithTarget.call(this, target); var locStartPos = this._startPosition; var locToConfig = this._toConfig; @@ -2325,14 +2325,14 @@ cc.BezierTo.create = cc.bezierTo; * var actionTo = new cc.ScaleTo(2, 0.5, 2); */ cc.ScaleTo = cc.ActionInterval.extend(/** @lends cc.ScaleTo# */{ - _scaleX:1, - _scaleY:1, - _startScaleX:1, - _startScaleY:1, - _endScaleX:0, - _endScaleY:0, - _deltaX:0, - _deltaY:0, + _scaleX: 1, + _scaleY: 1, + _startScaleX: 1, + _startScaleY: 1, + _endScaleX: 0, + _endScaleY: 0, + _deltaX: 0, + _deltaY: 0, /** * Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function. @@ -2340,7 +2340,7 @@ cc.ScaleTo = cc.ActionInterval.extend(/** @lends cc.ScaleTo# */{ * @param {Number} sx scale parameter in X * @param {Number} [sy] scale parameter in Y, if Null equal to sx */ - ctor:function (duration, sx, sy) { + ctor: function (duration, sx, sy) { cc.ActionInterval.prototype.ctor.call(this); sx !== undefined && this.initWithDuration(duration, sx, sy); }, @@ -2352,7 +2352,7 @@ cc.ScaleTo = cc.ActionInterval.extend(/** @lends cc.ScaleTo# */{ * @param {Number} [sy=] * @return {Boolean} */ - initWithDuration:function (duration, sx, sy) { //function overload here + initWithDuration: function (duration, sx, sy) { //function overload here if (cc.ActionInterval.prototype.initWithDuration.call(this, duration)) { this._endScaleX = sx; this._endScaleY = (sy != null) ? sy : sx; @@ -2365,7 +2365,7 @@ cc.ScaleTo = cc.ActionInterval.extend(/** @lends cc.ScaleTo# */{ * returns a new clone of the action * @returns {cc.ScaleTo} */ - clone:function () { + clone: function () { var action = new cc.ScaleTo(); this._cloneDecoration(action); action.initWithDuration(this._duration, this._endScaleX, this._endScaleY); @@ -2376,7 +2376,7 @@ cc.ScaleTo = cc.ActionInterval.extend(/** @lends cc.ScaleTo# */{ * Start the action with target. * @param {cc.Node} target */ - startWithTarget:function (target) { + startWithTarget: function (target) { cc.ActionInterval.prototype.startWithTarget.call(this, target); this._startScaleX = target.scaleX; this._startScaleY = target.scaleY; @@ -2388,7 +2388,7 @@ cc.ScaleTo = cc.ActionInterval.extend(/** @lends cc.ScaleTo# */{ * Called once per frame. Time is the number of seconds of a frame interval. * @param {Number} dt */ - update:function (dt) { + update: function (dt) { dt = this._computeEaseTime(dt); if (this.target) { this.target.scaleX = this._startScaleX + this._deltaX * dt; @@ -2437,7 +2437,7 @@ cc.ScaleBy = cc.ScaleTo.extend(/** @lends cc.ScaleBy# */{ * Start the action with target. * @param {cc.Node} target */ - startWithTarget:function (target) { + startWithTarget: function (target) { cc.ScaleTo.prototype.startWithTarget.call(this, target); this._deltaX = this._startScaleX * this._endScaleX - this._startScaleX; this._deltaY = this._startScaleY * this._endScaleY - this._startScaleY; @@ -2447,7 +2447,7 @@ cc.ScaleBy = cc.ScaleTo.extend(/** @lends cc.ScaleBy# */{ * Returns a reversed action. * @return {cc.ScaleBy} */ - reverse:function () { + reverse: function () { var action = new cc.ScaleBy(this._duration, 1 / this._endScaleX, 1 / this._endScaleY); this._cloneDecoration(action); this._reverseEaseList(action); @@ -2458,7 +2458,7 @@ cc.ScaleBy = cc.ScaleTo.extend(/** @lends cc.ScaleBy# */{ * returns a new clone of the action * @returns {cc.ScaleBy} */ - clone:function () { + clone: function () { var action = new cc.ScaleBy(); this._cloneDecoration(action); action.initWithDuration(this._duration, this._endScaleX, this._endScaleY); @@ -2505,15 +2505,15 @@ cc.ScaleBy.create = cc.scaleBy; * var action = new cc.Blink(2, 10); */ cc.Blink = cc.ActionInterval.extend(/** @lends cc.Blink# */{ - _times:0, - _originalState:false, + _times: 0, + _originalState: false, /** * Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function. * @param {Number} duration duration in seconds * @param {Number} blinks blinks in times */ - ctor:function (duration, blinks) { + ctor: function (duration, blinks) { cc.ActionInterval.prototype.ctor.call(this); blinks !== undefined && this.initWithDuration(duration, blinks); }, @@ -2524,7 +2524,7 @@ cc.Blink = cc.ActionInterval.extend(/** @lends cc.Blink# */{ * @param {Number} blinks blinks in times * @return {Boolean} */ - initWithDuration:function (duration, blinks) { + initWithDuration: function (duration, blinks) { if (cc.ActionInterval.prototype.initWithDuration.call(this, duration)) { this._times = blinks; return true; @@ -2536,7 +2536,7 @@ cc.Blink = cc.ActionInterval.extend(/** @lends cc.Blink# */{ * returns a new clone of the action * @returns {cc.Blink} */ - clone:function () { + clone: function () { var action = new cc.Blink(); this._cloneDecoration(action); action.initWithDuration(this._duration, this._times); @@ -2547,7 +2547,7 @@ cc.Blink = cc.ActionInterval.extend(/** @lends cc.Blink# */{ * Called once per frame. Time is the number of seconds of a frame interval. * @param {Number} dt time in seconds */ - update:function (dt) { + update: function (dt) { dt = this._computeEaseTime(dt); if (this.target && !this.isDone()) { var slice = 1.0 / this._times; @@ -2560,7 +2560,7 @@ cc.Blink = cc.ActionInterval.extend(/** @lends cc.Blink# */{ * Start the action with target. * @param {cc.Node} target */ - startWithTarget:function (target) { + startWithTarget: function (target) { cc.ActionInterval.prototype.startWithTarget.call(this, target); this._originalState = target.visible; }, @@ -2568,7 +2568,7 @@ cc.Blink = cc.ActionInterval.extend(/** @lends cc.Blink# */{ /** * stop the action */ - stop:function () { + stop: function () { this.target.visible = this._originalState; cc.ActionInterval.prototype.stop.call(this); }, @@ -2577,7 +2577,7 @@ cc.Blink = cc.ActionInterval.extend(/** @lends cc.Blink# */{ * Returns a reversed action. * @return {cc.Blink} */ - reverse:function () { + reverse: function () { var action = new cc.Blink(this._duration, this._times); this._cloneDecoration(action); this._reverseEaseList(action); @@ -2618,15 +2618,15 @@ cc.Blink.create = cc.blink; * var action = new cc.FadeTo(1.0, 0); */ cc.FadeTo = cc.ActionInterval.extend(/** @lends cc.FadeTo# */{ - _toOpacity:0, - _fromOpacity:0, + _toOpacity: 0, + _fromOpacity: 0, /** * Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function. * @param {Number} duration * @param {Number} opacity 0-255, 0 is transparent */ - ctor:function (duration, opacity) { + ctor: function (duration, opacity) { cc.ActionInterval.prototype.ctor.call(this); opacity !== undefined && this.initWithDuration(duration, opacity); }, @@ -2637,7 +2637,7 @@ cc.FadeTo = cc.ActionInterval.extend(/** @lends cc.FadeTo# */{ * @param {Number} opacity * @return {Boolean} */ - initWithDuration:function (duration, opacity) { + initWithDuration: function (duration, opacity) { if (cc.ActionInterval.prototype.initWithDuration.call(this, duration)) { this._toOpacity = opacity; return true; @@ -2649,7 +2649,7 @@ cc.FadeTo = cc.ActionInterval.extend(/** @lends cc.FadeTo# */{ * returns a new clone of the action * @returns {cc.FadeTo} */ - clone:function () { + clone: function () { var action = new cc.FadeTo(); this._cloneDecoration(action); action.initWithDuration(this._duration, this._toOpacity); @@ -2660,7 +2660,7 @@ cc.FadeTo = cc.ActionInterval.extend(/** @lends cc.FadeTo# */{ * Called once per frame. Time is the number of seconds of a frame interval. * @param {Number} time time in seconds */ - update:function (time) { + update: function (time) { time = this._computeEaseTime(time); var fromOpacity = this._fromOpacity !== undefined ? this._fromOpacity : 255; this.target.opacity = fromOpacity + (this._toOpacity - fromOpacity) * time; @@ -2670,7 +2670,7 @@ cc.FadeTo = cc.ActionInterval.extend(/** @lends cc.FadeTo# */{ * Start this action with target. * @param {cc.Node} target */ - startWithTarget:function (target) { + startWithTarget: function (target) { cc.ActionInterval.prototype.startWithTarget.call(this, target); this._fromOpacity = target.opacity; } @@ -2713,7 +2713,7 @@ cc.FadeIn = cc.FadeTo.extend(/** @lends cc.FadeIn# */{ * Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function. * @param {Number} duration duration in seconds */ - ctor:function (duration) { + ctor: function (duration) { cc.FadeTo.prototype.ctor.call(this); if (duration == null) duration = 0; @@ -2724,7 +2724,7 @@ cc.FadeIn = cc.FadeTo.extend(/** @lends cc.FadeIn# */{ * Returns a reversed action. * @return {cc.FadeOut} */ - reverse:function () { + reverse: function () { var action = new cc.FadeOut(); action.initWithDuration(this._duration, 0); this._cloneDecoration(action); @@ -2736,7 +2736,7 @@ cc.FadeIn = cc.FadeTo.extend(/** @lends cc.FadeIn# */{ * returns a new clone of the action * @returns {cc.FadeIn} */ - clone:function () { + clone: function () { var action = new cc.FadeIn(); this._cloneDecoration(action); action.initWithDuration(this._duration, this._toOpacity); @@ -2747,8 +2747,8 @@ cc.FadeIn = cc.FadeTo.extend(/** @lends cc.FadeIn# */{ * Start the action with target. * @param {cc.Node} target */ - startWithTarget:function (target) { - if(this._reverseAction) + startWithTarget: function (target) { + if (this._reverseAction) this._toOpacity = this._reverseAction._fromOpacity; cc.FadeTo.prototype.startWithTarget.call(this, target); } @@ -2789,7 +2789,7 @@ cc.FadeOut = cc.FadeTo.extend(/** @lends cc.FadeOut# */{ * Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function. * @param {Number} duration duration in seconds */ - ctor:function (duration) { + ctor: function (duration) { cc.FadeTo.prototype.ctor.call(this); if (duration == null) duration = 0; @@ -2800,7 +2800,7 @@ cc.FadeOut = cc.FadeTo.extend(/** @lends cc.FadeOut# */{ * Returns a reversed action. * @return {cc.FadeIn} */ - reverse:function () { + reverse: function () { var action = new cc.FadeIn(); action._reverseAction = this; action.initWithDuration(this._duration, 255); @@ -2813,7 +2813,7 @@ cc.FadeOut = cc.FadeTo.extend(/** @lends cc.FadeOut# */{ * returns a new clone of the action * @returns {cc.FadeOut} */ - clone:function () { + clone: function () { var action = new cc.FadeOut(); this._cloneDecoration(action); action.initWithDuration(this._duration, this._toOpacity); @@ -2855,8 +2855,8 @@ cc.FadeOut.create = cc.fadeOut; * var action = new cc.TintTo(2, 255, 0, 255); */ cc.TintTo = cc.ActionInterval.extend(/** @lends cc.TintTo# */{ - _to:null, - _from:null, + _to: null, + _from: null, /** * Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function. @@ -2865,7 +2865,7 @@ cc.TintTo = cc.ActionInterval.extend(/** @lends cc.TintTo# */{ * @param {Number} green 0-255 * @param {Number} blue 0-255 */ - ctor:function (duration, red, green, blue) { + ctor: function (duration, red, green, blue) { cc.ActionInterval.prototype.ctor.call(this); this._to = cc.color(0, 0, 0); this._from = cc.color(0, 0, 0); @@ -2881,7 +2881,7 @@ cc.TintTo = cc.ActionInterval.extend(/** @lends cc.TintTo# */{ * @param {Number} blue 0-255 * @return {Boolean} */ - initWithDuration:function (duration, red, green, blue) { + initWithDuration: function (duration, red, green, blue) { if (cc.ActionInterval.prototype.initWithDuration.call(this, duration)) { this._to = cc.color(red, green, blue); return true; @@ -2893,7 +2893,7 @@ cc.TintTo = cc.ActionInterval.extend(/** @lends cc.TintTo# */{ * returns a new clone of the action * @returns {cc.TintTo} */ - clone:function () { + clone: function () { var action = new cc.TintTo(); this._cloneDecoration(action); var locTo = this._to; @@ -2905,7 +2905,7 @@ cc.TintTo = cc.ActionInterval.extend(/** @lends cc.TintTo# */{ * Start the action with target. * @param {cc.Node} target */ - startWithTarget:function (target) { + startWithTarget: function (target) { cc.ActionInterval.prototype.startWithTarget.call(this, target); this._from = this.target.color; @@ -2915,7 +2915,7 @@ cc.TintTo = cc.ActionInterval.extend(/** @lends cc.TintTo# */{ * Called once per frame. Time is the number of seconds of a frame interval. * @param {Number} dt time in seconds */ - update:function (dt) { + update: function (dt) { dt = this._computeEaseTime(dt); var locFrom = this._from, locTo = this._to; if (locFrom) { @@ -2970,13 +2970,13 @@ cc.TintTo.create = cc.tintTo; * var action = new cc.TintBy(2, -127, -255, -127); */ cc.TintBy = cc.ActionInterval.extend(/** @lends cc.TintBy# */{ - _deltaR:0, - _deltaG:0, - _deltaB:0, + _deltaR: 0, + _deltaG: 0, + _deltaB: 0, - _fromR:0, - _fromG:0, - _fromB:0, + _fromR: 0, + _fromG: 0, + _fromB: 0, /** * Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function. @@ -2985,7 +2985,7 @@ cc.TintBy = cc.ActionInterval.extend(/** @lends cc.TintBy# */{ * @param {Number} deltaGreen * @param {Number} deltaBlue */ - ctor:function (duration, deltaRed, deltaGreen, deltaBlue) { + ctor: function (duration, deltaRed, deltaGreen, deltaBlue) { cc.ActionInterval.prototype.ctor.call(this); deltaBlue !== undefined && this.initWithDuration(duration, deltaRed, deltaGreen, deltaBlue); }, @@ -2998,7 +2998,7 @@ cc.TintBy = cc.ActionInterval.extend(/** @lends cc.TintBy# */{ * @param {Number} deltaBlue 0-255 * @return {Boolean} */ - initWithDuration:function (duration, deltaRed, deltaGreen, deltaBlue) { + initWithDuration: function (duration, deltaRed, deltaGreen, deltaBlue) { if (cc.ActionInterval.prototype.initWithDuration.call(this, duration)) { this._deltaR = deltaRed; this._deltaG = deltaGreen; @@ -3012,7 +3012,7 @@ cc.TintBy = cc.ActionInterval.extend(/** @lends cc.TintBy# */{ * returns a new clone of the action * @returns {cc.TintBy} */ - clone:function () { + clone: function () { var action = new cc.TintBy(); this._cloneDecoration(action); action.initWithDuration(this._duration, this._deltaR, this._deltaG, this._deltaB); @@ -3023,7 +3023,7 @@ cc.TintBy = cc.ActionInterval.extend(/** @lends cc.TintBy# */{ * Start the action with target. * @param {cc.Node} target */ - startWithTarget:function (target) { + startWithTarget: function (target) { cc.ActionInterval.prototype.startWithTarget.call(this, target); var color = target.color; @@ -3037,12 +3037,12 @@ cc.TintBy = cc.ActionInterval.extend(/** @lends cc.TintBy# */{ * Called once per frame. Time is the number of seconds of a frame interval. * @param {Number} dt time in seconds */ - update:function (dt) { + update: function (dt) { dt = this._computeEaseTime(dt); this.target.color = cc.color(this._fromR + this._deltaR * dt, - this._fromG + this._deltaG * dt, - this._fromB + this._deltaB * dt); + this._fromG + this._deltaG * dt, + this._fromB + this._deltaB * dt); }, @@ -3050,7 +3050,7 @@ cc.TintBy = cc.ActionInterval.extend(/** @lends cc.TintBy# */{ * Returns a reversed action. * @return {cc.TintBy} */ - reverse:function () { + reverse: function () { var action = new cc.TintBy(this._duration, -this._deltaR, -this._deltaG, -this._deltaB); this._cloneDecoration(action); this._reverseEaseList(action); @@ -3098,13 +3098,14 @@ cc.DelayTime = cc.ActionInterval.extend(/** @lends cc.DelayTime# */{ * Will be overwrite. * @param {Number} dt time in seconds */ - update:function (dt) {}, + update: function (dt) { + }, /** * Returns a reversed action. * @return {cc.DelayTime} */ - reverse:function () { + reverse: function () { var action = new cc.DelayTime(this._duration); this._cloneDecoration(action); this._reverseEaseList(action); @@ -3115,7 +3116,7 @@ cc.DelayTime = cc.ActionInterval.extend(/** @lends cc.DelayTime# */{ * returns a new clone of the action * @returns {cc.DelayTime} */ - clone:function () { + clone: function () { var action = new cc.DelayTime(); this._cloneDecoration(action); action.initWithDuration(this._duration); @@ -3159,13 +3160,13 @@ cc.DelayTime.create = cc.delayTime; * var reverse = new cc.ReverseTime(this); */ cc.ReverseTime = cc.ActionInterval.extend(/** @lends cc.ReverseTime# */{ - _other:null, + _other: null, /** * Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function. * @param {cc.FiniteTimeAction} action */ - ctor:function (action) { + ctor: function (action) { cc.ActionInterval.prototype.ctor.call(this); this._other = null; @@ -3176,10 +3177,10 @@ cc.ReverseTime = cc.ActionInterval.extend(/** @lends cc.ReverseTime# */{ * @param {cc.FiniteTimeAction} action * @return {Boolean} */ - initWithAction:function (action) { - if(!action) + initWithAction: function (action) { + if (!action) throw new Error("cc.ReverseTime.initWithAction(): action must be non null"); - if(action === this._other) + if (action === this._other) throw new Error("cc.ReverseTime.initWithAction(): the action was already passed in."); if (cc.ActionInterval.prototype.initWithDuration.call(this, action._duration)) { @@ -3194,7 +3195,7 @@ cc.ReverseTime = cc.ActionInterval.extend(/** @lends cc.ReverseTime# */{ * returns a new clone of the action * @returns {cc.ReverseTime} */ - clone:function () { + clone: function () { var action = new cc.ReverseTime(); this._cloneDecoration(action); action.initWithAction(this._other.clone()); @@ -3205,7 +3206,7 @@ cc.ReverseTime = cc.ActionInterval.extend(/** @lends cc.ReverseTime# */{ * Start the action with target. * @param {cc.Node} target */ - startWithTarget:function (target) { + startWithTarget: function (target) { cc.ActionInterval.prototype.startWithTarget.call(this, target); this._other.startWithTarget(target); }, @@ -3214,7 +3215,7 @@ cc.ReverseTime = cc.ActionInterval.extend(/** @lends cc.ReverseTime# */{ * Called once per frame. Time is the number of seconds of a frame interval. * @param {Number} dt time in seconds */ - update:function (dt) { + update: function (dt) { dt = this._computeEaseTime(dt); if (this._other) this._other.update(1 - dt); @@ -3224,14 +3225,14 @@ cc.ReverseTime = cc.ActionInterval.extend(/** @lends cc.ReverseTime# */{ * Returns a reversed action. * @return {cc.ActionInterval} */ - reverse:function () { + reverse: function () { return this._other.clone(); }, /** * Stop the action */ - stop:function () { + stop: function () { this._other.stop(); cc.Action.prototype.stop.call(this); } @@ -3269,19 +3270,19 @@ cc.ReverseTime.create = cc.reverseTime; * var anim = new cc.Animate(dance_grey); */ cc.Animate = cc.ActionInterval.extend(/** @lends cc.Animate# */{ - _animation:null, - _nextFrame:0, - _origFrame:null, - _executedLoops:0, + _animation: null, + _nextFrame: 0, + _origFrame: null, + _executedLoops: 0, _splitTimes: null, - _currFrameIndex:0, + _currFrameIndex: 0, /** * Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function.
* create the animate with animation. * @param {cc.Animation} animation */ - ctor:function (animation) { + ctor: function (animation) { cc.ActionInterval.prototype.ctor.call(this); this._splitTimes = []; @@ -3291,14 +3292,14 @@ cc.Animate = cc.ActionInterval.extend(/** @lends cc.Animate# */{ /** * @return {cc.Animation} */ - getAnimation:function () { + getAnimation: function () { return this._animation; }, /** * @param {cc.Animation} animation */ - setAnimation:function (animation) { + setAnimation: function (animation) { this._animation = animation; }, @@ -3314,8 +3315,8 @@ cc.Animate = cc.ActionInterval.extend(/** @lends cc.Animate# */{ * @param {cc.Animation} animation * @return {Boolean} */ - initWithAnimation:function (animation) { - if(!animation) + initWithAnimation: function (animation) { + if (!animation) throw new Error("cc.Animate.initWithAnimation(): animation must be non-NULL"); var singleDuration = animation.getDuration(); if (this.initWithDuration(singleDuration * animation.getLoops())) { @@ -3348,7 +3349,7 @@ cc.Animate = cc.ActionInterval.extend(/** @lends cc.Animate# */{ * returns a new clone of the action * @returns {cc.Animate} */ - clone:function () { + clone: function () { var action = new cc.Animate(); this._cloneDecoration(action); action.initWithAnimation(this._animation.clone()); @@ -3359,7 +3360,7 @@ cc.Animate = cc.ActionInterval.extend(/** @lends cc.Animate# */{ * Start the action with target. * @param {cc.Sprite} target */ - startWithTarget:function (target) { + startWithTarget: function (target) { cc.ActionInterval.prototype.startWithTarget.call(this, target); if (this._animation.getRestoreOriginalFrame()) this._origFrame = target.displayFrame(); @@ -3371,7 +3372,7 @@ cc.Animate = cc.ActionInterval.extend(/** @lends cc.Animate# */{ * Called once per frame. Time is the number of seconds of a frame interval. * @param {Number} dt */ - update:function (dt) { + update: function (dt) { dt = this._computeEaseTime(dt); // if t==1, ignore. Animation should finish with t==1 if (dt < 1.0) { @@ -3406,7 +3407,7 @@ cc.Animate = cc.ActionInterval.extend(/** @lends cc.Animate# */{ * Returns a reversed action. * @return {cc.Animate} */ - reverse:function () { + reverse: function () { var locAnimation = this._animation; var oldArray = locAnimation.getFrames(); var newArray = []; @@ -3431,7 +3432,7 @@ cc.Animate = cc.ActionInterval.extend(/** @lends cc.Animate# */{ /** * stop the action */ - stop:function () { + stop: function () { if (this._animation.getRestoreOriginalFrame() && this.target) this.target.setSpriteFrame(this._origFrame); cc.Action.prototype.stop.call(this); @@ -3472,8 +3473,8 @@ cc.Animate.create = cc.animate; * @param {cc.FiniteTimeAction} action */ cc.TargetedAction = cc.ActionInterval.extend(/** @lends cc.TargetedAction# */{ - _action:null, - _forcedTarget:null, + _action: null, + _forcedTarget: null, /** * Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function.
@@ -3492,7 +3493,7 @@ cc.TargetedAction = cc.ActionInterval.extend(/** @lends cc.TargetedAction# */{ * @param {cc.FiniteTimeAction} action * @return {Boolean} */ - initWithTarget:function (target, action) { + initWithTarget: function (target, action) { if (this.initWithDuration(action._duration)) { this._forcedTarget = target; this._action = action; @@ -3505,7 +3506,7 @@ cc.TargetedAction = cc.ActionInterval.extend(/** @lends cc.TargetedAction# */{ * returns a new clone of the action * @returns {cc.TargetedAction} */ - clone:function () { + clone: function () { var action = new cc.TargetedAction(); this._cloneDecoration(action); action.initWithTarget(this._forcedTarget, this._action.clone()); @@ -3516,7 +3517,7 @@ cc.TargetedAction = cc.ActionInterval.extend(/** @lends cc.TargetedAction# */{ * Start the action with target. * @param {cc.Node} target */ - startWithTarget:function (target) { + startWithTarget: function (target) { cc.ActionInterval.prototype.startWithTarget.call(this, target); this._action.startWithTarget(this._forcedTarget); }, @@ -3524,7 +3525,7 @@ cc.TargetedAction = cc.ActionInterval.extend(/** @lends cc.TargetedAction# */{ /** * stop the action */ - stop:function () { + stop: function () { this._action.stop(); }, @@ -3532,7 +3533,7 @@ cc.TargetedAction = cc.ActionInterval.extend(/** @lends cc.TargetedAction# */{ * Called once per frame. Time is the number of seconds of a frame interval. * @param {Number} dt */ - update:function (dt) { + update: function (dt) { dt = this._computeEaseTime(dt); this._action.update(dt); }, @@ -3541,7 +3542,7 @@ cc.TargetedAction = cc.ActionInterval.extend(/** @lends cc.TargetedAction# */{ * return the target that the action will be forced to run with * @return {cc.Node} */ - getForcedTarget:function () { + getForcedTarget: function () { return this._forcedTarget; }, @@ -3549,7 +3550,7 @@ cc.TargetedAction = cc.ActionInterval.extend(/** @lends cc.TargetedAction# */{ * set the target that the action will be forced to run with * @param {cc.Node} forcedTarget */ - setForcedTarget:function (forcedTarget) { + setForcedTarget: function (forcedTarget) { if (this._forcedTarget !== forcedTarget) this._forcedTarget = forcedTarget; } diff --git a/cocos2d/actions/CCActionTween.js b/cocos2d/actions/CCActionTween.js index fa3e394f1f..daa6c368d1 100644 --- a/cocos2d/actions/CCActionTween.js +++ b/cocos2d/actions/CCActionTween.js @@ -36,7 +36,8 @@ cc.ActionTweenDelegate = cc.Class.extend(/** @lends cc.ActionTweenDelegate */{ * @param value * @param key */ - updateTweenAction:function(value, key){} + updateTweenAction: function (value, key) { + } }); /** @@ -60,24 +61,24 @@ cc.ActionTweenDelegate = cc.Class.extend(/** @lends cc.ActionTweenDelegate */{ * @param {Number} to */ cc.ActionTween = cc.ActionInterval.extend(/** @lends cc.ActionTween */{ - key:"", - from:0, - to:0, - delta:0, + key: "", + from: 0, + to: 0, + delta: 0, - /** + /** * Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function.
- * Creates an initializes the action with the property name (key), and the from and to parameters. - * @param {Number} duration - * @param {String} key - * @param {Number} from - * @param {Number} to - */ - ctor:function(duration, key, from, to){ + * Creates an initializes the action with the property name (key), and the from and to parameters. + * @param {Number} duration + * @param {String} key + * @param {Number} from + * @param {Number} to + */ + ctor: function (duration, key, from, to) { cc.ActionInterval.prototype.ctor.call(this); this.key = ""; - to !== undefined && this.initWithDuration(duration, key, from, to); + to !== undefined && this.initWithDuration(duration, key, from, to); }, /** @@ -88,7 +89,7 @@ cc.ActionTween = cc.ActionInterval.extend(/** @lends cc.ActionTween */{ * @param {Number} to * @return {Boolean} */ - initWithDuration:function (duration, key, from, to) { + initWithDuration: function (duration, key, from, to) { if (cc.ActionInterval.prototype.initWithDuration.call(this, duration)) { this.key = key; this.to = to; @@ -102,8 +103,8 @@ cc.ActionTween = cc.ActionInterval.extend(/** @lends cc.ActionTween */{ * Start this tween with target. * @param {cc.ActionTweenDelegate} target */ - startWithTarget:function (target) { - if(!target || !target.updateTweenAction) + startWithTarget: function (target) { + if (!target || !target.updateTweenAction) throw new Error("cc.ActionTween.startWithTarget(): target must be non-null, and target must implement updateTweenAction function"); cc.ActionInterval.prototype.startWithTarget.call(this, target); this.delta = this.to - this.from; @@ -114,7 +115,7 @@ cc.ActionTween = cc.ActionInterval.extend(/** @lends cc.ActionTween */{ * * @param {Number} dt */ - update:function (dt) { + update: function (dt) { this.target.updateTweenAction(this.to - this.delta * (1 - dt), this.key); }, @@ -122,7 +123,7 @@ cc.ActionTween = cc.ActionInterval.extend(/** @lends cc.ActionTween */{ * returns a reversed action. * @return {cc.ActionTween} */ - reverse:function () { + reverse: function () { return new cc.ActionTween(this.duration, this.key, this.to, this.from); }, @@ -132,7 +133,7 @@ cc.ActionTween = cc.ActionInterval.extend(/** @lends cc.ActionTween */{ * * @return {cc.ActionTween} */ - clone:function(){ + clone: function () { var action = new cc.ActionTween(); action.initWithDuration(this._duration, this.key, this.from, this.to); return action; @@ -163,4 +164,4 @@ cc.actionTween = function (duration, key, from, to) { * @param {Number} to * @return {cc.ActionTween} */ -cc.ActionTween.create = cc.actionTween; \ No newline at end of file +cc.ActionTween.create = cc.actionTween; diff --git a/cocos2d/audio/CCAudio.js b/cocos2d/audio/CCAudio.js index 4561f09ddc..f4e9cec4f6 100644 --- a/cocos2d/audio/CCAudio.js +++ b/cocos2d/audio/CCAudio.js @@ -37,7 +37,7 @@ * * May be modifications for a few browser version */ -(function(){ +(function () { var DEBUG = false; @@ -48,7 +48,7 @@ // check Web Audio's context var supportWebAudio = !!(window.AudioContext || window.webkitAudioContext || window.mozAudioContext); - var support = {ONLY_ONE: false, WEB_AUDIO: supportWebAudio, DELAY_CREATE_CTX: false, ONE_SOURCE: false }; + var support = {ONLY_ONE: false, WEB_AUDIO: supportWebAudio, DELAY_CREATE_CTX: false, ONE_SOURCE: false}; if (sys.browserType === sys.BROWSER_TYPE_FIREFOX) { support.DELAY_CREATE_CTX = true; @@ -67,8 +67,8 @@ window.__audioSupport = support; - if(DEBUG){ - setTimeout(function(){ + if (DEBUG) { + setTimeout(function () { cc.log("browse type: " + sys.browserType); cc.log("browse version: " + version); cc.log("MULTI_CHANNEL: " + window.__audioSupport.MULTI_CHANNEL); @@ -87,7 +87,7 @@ cc.Audio = cc.Class.extend({ _element: null, _AUDIO_TYPE: "AUDIO", - ctor: function(url){ + ctor: function (url) { this.src = url; }, @@ -133,9 +133,10 @@ cc.Audio = cc.Class.extend({ stop: function () { if (!this._element) return; this._element.pause(); - try{ + try { this._element.currentTime = 0; - } catch (err) {} + } catch (err) { + } }, pause: function () { @@ -163,7 +164,7 @@ cc.Audio = cc.Class.extend({ if (this._AUDIO_TYPE === "AUDIO") { var elem = document.createElement("audio"); var sources = elem.getElementsByTagName('source'); - for (var i=0; i durationTime return this.context.currentTime - this._startTime > this.buffer.duration; }, - set paused (bool) {}, + set paused(bool) { + }, - get loop () { return this._loop; }, - set loop (bool) { return this._loop = bool; }, + get loop() { + return this._loop; + }, + set loop(bool) { + return this._loop = bool; + }, - get volume () { return this._volume['gain'].value; }, - set volume (num) { return this._volume['gain'].value = num; }, + get volume() { + return this._volume['gain'].value; + }, + set volume(num) { + return this._volume['gain'].value = num; + }, - get currentTime () { return this.playedLength; }, - set currentTime (num) { return this.playedLength = num; }, + get currentTime() { + return this.playedLength; + }, + set currentTime(num) { + return this.playedLength = num; + }, play: function (offset) { @@ -300,15 +314,15 @@ cc.Audio.WebAudio.prototype = { } }; -(function(polyfill){ +(function (polyfill) { var SWA = polyfill.WEB_AUDIO, SWB = polyfill.ONLY_ONE; var support = []; - (function(){ + (function () { var audio = document.createElement("audio"); - if(audio.canPlayType) { + if (audio.canPlayType) { var ogg = audio.canPlayType('audio/ogg; codecs="vorbis"'); if (ogg && ogg !== "") support.push(".ogg"); var mp3 = audio.canPlayType("audio/mpeg"); @@ -321,17 +335,17 @@ cc.Audio.WebAudio.prototype = { if (m4a && m4a !== "") support.push(".m4a"); } })(); - try{ - if(SWA){ + try { + if (SWA) { var context = new (window.AudioContext || window.webkitAudioContext || window.mozAudioContext)(); cc.Audio._context = context; - if(polyfill.DELAY_CREATE_CTX) - setTimeout(function(){ + if (polyfill.DELAY_CREATE_CTX) + setTimeout(function () { context = new (window.AudioContext || window.webkitAudioContext || window.mozAudioContext)(); cc.Audio._context = context; }, 0); } - }catch(error){ + } catch (error) { SWA = false; cc.log("browser don't support web audio"); } @@ -351,26 +365,26 @@ cc.Audio.WebAudio.prototype = { // Our asynchronous callback request.onload = function () { - context["decodeAudioData"](request.response, function(buffer){ + context["decodeAudioData"](request.response, function (buffer) { //success cb(null, buffer); //audio.setBuffer(buffer); - }, function(){ + }, function () { //error cb('decode error - ' + url); }); }; - request.onerror = function(){ + request.onerror = function () { cb('request error - ' + url); }; request.send(); }, - load: function(realUrl, url, res, cb){ + load: function (realUrl, url, res, cb) { - if(support.length === 0) + if (support.length === 0) return cb("can not support audio!"); var audio = cc.loader.getRes(url); @@ -379,14 +393,14 @@ cc.Audio.WebAudio.prototype = { var i; - if(cc.loader.audioPath) + if (cc.loader.audioPath) realUrl = cc.path.join(cc.loader.audioPath, realUrl); var extname = cc.path.extname(realUrl); var typeList = [extname]; - for(i=0; itrue if the background music is playing, otherwise false */ - willPlayMusic: function(){return false;}, + willPlayMusic: function () { + return false; + }, /** * Play music. @@ -549,9 +565,9 @@ cc.Audio.WebAudio.prototype = { * //example * cc.audioEngine.rewindMusic(); */ - rewindMusic: function(){ + rewindMusic: function () { var audio = this._currMusic; - if (audio){ + if (audio) { audio.stop(); audio.play(); } @@ -564,7 +580,7 @@ cc.Audio.WebAudio.prototype = { * //example * var volume = cc.audioEngine.getMusicVolume(); */ - getMusicVolume: function(){ + getMusicVolume: function () { return this._musicVolume; }, @@ -575,7 +591,7 @@ cc.Audio.WebAudio.prototype = { * //example * cc.audioEngine.setMusicVolume(0.5); */ - setMusicVolume: function(volume){ + setMusicVolume: function (volume) { volume = volume - 0; if (isNaN(volume)) volume = 1; if (volume > 1) volume = 1; @@ -600,7 +616,7 @@ cc.Audio.WebAudio.prototype = { * cc.log("music is not playing"); * } */ - isMusicPlaying: function(){ + isMusicPlaying: function () { var audio = this._currMusic; if (audio) { return audio.getPlaying(); @@ -621,7 +637,7 @@ cc.Audio.WebAudio.prototype = { * //example * var soundId = cc.audioEngine.playEffect(path); */ - playEffect: function(url, loop){ + playEffect: function (url, loop) { if (SWB && this._currMusic && this._currMusic.getPlaying()) { cc.log('Browser is only allowed to play one audio'); @@ -703,18 +719,18 @@ cc.Audio.WebAudio.prototype = { * //example * cc.audioEngine.setEffectsVolume(0.5); */ - setEffectsVolume: function(volume){ + setEffectsVolume: function (volume) { volume = volume - 0; - if(isNaN(volume)) volume = 1; - if(volume > 1) volume = 1; - if(volume < 0) volume = 0; + if (isNaN(volume)) volume = 1; + if (volume > 1) volume = 1; + if (volume < 0) volume = 0; this._effectVolume = volume; var audioPool = this._audioPool; - for(var p in audioPool){ + for (var p in audioPool) { var audioList = audioPool[p]; - if(Array.isArray(audioList)) - for(var i=0; i diff --git a/cocos2d/clipping-nodes/CCClippingNodeCanvasRenderCmd.js b/cocos2d/clipping-nodes/CCClippingNodeCanvasRenderCmd.js index c20d973217..c9208a8c9f 100644 --- a/cocos2d/clipping-nodes/CCClippingNodeCanvasRenderCmd.js +++ b/cocos2d/clipping-nodes/CCClippingNodeCanvasRenderCmd.js @@ -23,8 +23,8 @@ ****************************************************************************/ //-------------------------- ClippingNode's canvas render cmd -------------------------------- -(function(){ - cc.ClippingNode.CanvasRenderCmd = function(renderable){ +(function () { + cc.ClippingNode.CanvasRenderCmd = function (renderable) { cc.Node.CanvasRenderCmd.call(this, renderable); this._needDraw = false; @@ -38,10 +38,11 @@ var proto = cc.ClippingNode.CanvasRenderCmd.prototype = Object.create(cc.Node.CanvasRenderCmd.prototype); proto.constructor = cc.ClippingNode.CanvasRenderCmd; - proto.initStencilBits = function(){}; + proto.initStencilBits = function () { + }; - proto.setStencil = function(stencil){ - if(stencil == null) + proto.setStencil = function (stencil) { + if (stencil == null) return; this._node._stencil = stencil; @@ -49,8 +50,8 @@ // For shape stencil, rewrite the draw of stencil ,only init the clip path and draw nothing. //else if (stencil instanceof cc.DrawNode) { - if(stencil._buffer){ - for(var i=0; i 0; j--) - context.lineTo(vertices[j].x , -vertices[j].y ); + context.lineTo(vertices[j].x, -vertices[j].y); } } context.clip(); @@ -154,10 +155,10 @@ } }; - proto.transform = function(parentCmd, recursive){ - cc.Node.CanvasRenderCmd.prototype.transform.call(this, parentCmd, recursive); + proto.transform = function (parentCmd, recursive) { + this.originTransform(parentCmd, recursive); var node = this._node; - if(node._stencil && node._stencil._renderCmd) + if (node._stencil && node._stencil._renderCmd) node._stencil._renderCmd.transform(this, recursive); }; diff --git a/cocos2d/clipping-nodes/CCClippingNodeWebGLRenderCmd.js b/cocos2d/clipping-nodes/CCClippingNodeWebGLRenderCmd.js index c84ee963d3..986cbcb887 100644 --- a/cocos2d/clipping-nodes/CCClippingNodeWebGLRenderCmd.js +++ b/cocos2d/clipping-nodes/CCClippingNodeWebGLRenderCmd.js @@ -23,8 +23,8 @@ ****************************************************************************/ // ------------------------------- ClippingNode's WebGL render cmd ------------------------------ -(function(){ - cc.ClippingNode.WebGLRenderCmd = function(renderable){ +(function () { + cc.ClippingNode.WebGLRenderCmd = function (renderable) { cc.Node.WebGLRenderCmd.call(this, renderable); this._needDraw = false; @@ -43,7 +43,7 @@ cc.ClippingNode.WebGLRenderCmd._visit_once = null; cc.ClippingNode.WebGLRenderCmd._layer = -1; - proto.initStencilBits = function(){ + proto.initStencilBits = function () { // get (only once) the number of bits of the stencil buffer cc.ClippingNode.WebGLRenderCmd._init_once = true; if (cc.ClippingNode.WebGLRenderCmd._init_once) { @@ -54,10 +54,10 @@ } }; - proto.transform = function(parentCmd, recursive){ + proto.transform = function (parentCmd, recursive) { var node = this._node; this.originTransform(parentCmd, recursive); - if(node._stencil) { + if (node._stencil) { node._stencil._renderCmd.transform(this, recursive); } }; @@ -126,16 +126,16 @@ currentStack.top = currentStack.stack.pop(); }; - proto.setStencil = function(stencil){ + proto.setStencil = function (stencil) { var node = this._node; - if(node._stencil) + if (node._stencil) node._stencil._parent = null; node._stencil = stencil; - if(node._stencil) + if (node._stencil) node._stencil._parent = node; }; - proto._onBeforeVisit = function(ctx){ + proto._onBeforeVisit = function (ctx) { var gl = ctx || cc._renderContext, node = this._node; cc.ClippingNode.WebGLRenderCmd._layer++; @@ -171,14 +171,14 @@ } }; - proto._onAfterDrawStencil = function(ctx){ + proto._onAfterDrawStencil = function (ctx) { var gl = ctx || cc._renderContext; gl.depthMask(true); 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){ + proto._onAfterVisit = function (ctx) { var gl = ctx || cc._renderContext; cc.ClippingNode.WebGLRenderCmd._layer--; diff --git a/cocos2d/core/CCDirector.js b/cocos2d/core/CCDirector.js index 1a886d59fb..3cfcfc77fe 100644 --- a/cocos2d/core/CCDirector.js +++ b/cocos2d/core/CCDirector.js @@ -43,7 +43,7 @@ cc.g_NumberOfDraws = 0; * - setting the OpenGL pixel format (default on is RGB565)
* - setting the OpenGL pixel format (default on is RGB565)
* - setting the OpenGL buffer depth (default one is 0-bit)
- - setting the color for clear screen (default one is BLACK)
+ * - setting the color for clear screen (default one is BLACK)
* - setting the projection (default one is 3D)
* - setting the orientation (default one is Portrait)
*
@@ -134,9 +134,9 @@ cc.Director = cc.Class.extend(/** @lends cc.Director# */{ //scheduler this._scheduler = new cc.Scheduler(); //action manager - if(cc.ActionManager){ + if (cc.ActionManager) { this._actionManager = new cc.ActionManager(); - }else{ + } else { this._actionManager = null; } diff --git a/cocos2d/core/base-nodes/CCAtlasNodeCanvasRenderCmd.js b/cocos2d/core/base-nodes/CCAtlasNodeCanvasRenderCmd.js index 3d0162aed3..290cd2a0c3 100644 --- a/cocos2d/core/base-nodes/CCAtlasNodeCanvasRenderCmd.js +++ b/cocos2d/core/base-nodes/CCAtlasNodeCanvasRenderCmd.js @@ -25,8 +25,8 @@ /** * cc.AtlasNode's rendering objects of Canvas */ -(function(){ - cc.AtlasNode.CanvasRenderCmd = function(renderableObject){ +(function () { + cc.AtlasNode.CanvasRenderCmd = function (renderableObject) { cc.Node.CanvasRenderCmd.call(this, renderableObject); this._needDraw = false; this._colorUnmodified = cc.color.WHITE; @@ -36,7 +36,7 @@ var proto = cc.AtlasNode.CanvasRenderCmd.prototype = Object.create(cc.Node.CanvasRenderCmd.prototype); proto.constructor = cc.AtlasNode.CanvasRenderCmd; - proto.initWithTexture = function(texture, tileWidth, tileHeight, itemsToRender){ + proto.initWithTexture = function (texture, tileWidth, tileHeight, itemsToRender) { var node = this._node; node._itemWidth = tileWidth; node._itemHeight = tileHeight; @@ -54,7 +54,7 @@ return true; }; - proto.setColor = function(color3){ + proto.setColor = function (color3) { var node = this._node; var locRealColor = node._realColor; if ((locRealColor.r === color3.r) && (locRealColor.g === color3.g) && (locRealColor.b === color3.b)) @@ -63,24 +63,24 @@ this._changeTextureColor(); }; - proto._changeTextureColor = function(){ + proto._changeTextureColor = function () { var node = this._node; var texture = node._texture, color = this._colorUnmodified, element = texture.getHtmlElementObj(); var textureRect = cc.rect(0, 0, element.width, element.height); - if(texture === this._textureToRender) + if (texture === this._textureToRender) this._textureToRender = texture._generateColorTexture(color.r, color.g, color.b, textureRect); else texture._generateColorTexture(color.r, color.g, color.b, textureRect, this._textureToRender.getHtmlElementObj()); }; - proto.setOpacity = function(opacity){ + proto.setOpacity = function (opacity) { var node = this._node; cc.Node.prototype.setOpacity.call(node, opacity); }; - proto._calculateMaxItems = function(){ + proto._calculateMaxItems = function () { var node = this._node; var selTexture = node._texture; var size = selTexture.getContentSize(); diff --git a/cocos2d/core/base-nodes/CCAtlasNodeWebGLRenderCmd.js b/cocos2d/core/base-nodes/CCAtlasNodeWebGLRenderCmd.js index 70f7aa0724..16f27ae09d 100644 --- a/cocos2d/core/base-nodes/CCAtlasNodeWebGLRenderCmd.js +++ b/cocos2d/core/base-nodes/CCAtlasNodeWebGLRenderCmd.js @@ -25,8 +25,8 @@ /** * cc.AtlasNode's rendering objects of WebGL */ -(function(){ - cc.AtlasNode.WebGLRenderCmd = function(renderableObject){ +(function () { + cc.AtlasNode.WebGLRenderCmd = function (renderableObject) { cc.Node.WebGLRenderCmd.call(this, renderableObject); this._needDraw = true; this._textureAtlas = null; @@ -78,7 +78,7 @@ } }; - proto.initWithTexture = function(texture, tileWidth, tileHeight, itemsToRender){ + proto.initWithTexture = function (texture, tileWidth, tileHeight, itemsToRender) { var node = this._node; node._itemWidth = tileWidth; node._itemHeight = tileHeight; @@ -106,7 +106,7 @@ return true; }; - proto.setColor = function(color3){ + proto.setColor = function (color3) { var temp = cc.color(color3.r, color3.g, color3.b), node = this._node; this._colorUnmodified = color3; var locDisplayedOpacity = this._displayedOpacity; @@ -118,7 +118,7 @@ cc.Node.prototype.setColor.call(node, temp); }; - proto.setOpacity = function(opacity){ + proto.setOpacity = function (opacity) { var node = this._node; cc.Node.prototype.setOpacity.call(node, opacity); // special opacity for premultiplied textures @@ -137,17 +137,17 @@ } }; - proto.getTexture = function(){ + proto.getTexture = function () { return this._textureAtlas.texture; }; - proto.setTexture = function(texture){ + proto.setTexture = function (texture) { this._textureAtlas.texture = texture; this._updateBlendFunc(); this._updateOpacityModifyRGB(); }; - proto._calculateMaxItems = function(){ + proto._calculateMaxItems = function () { var node = this._node; var selTexture = this._textureAtlas.texture; var size = selTexture.getContentSize(); @@ -157,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/CCNode.js b/cocos2d/core/base-nodes/CCNode.js index 2d1757bf43..c8f587ca27 100644 --- a/cocos2d/core/base-nodes/CCNode.js +++ b/cocos2d/core/base-nodes/CCNode.js @@ -727,7 +727,7 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{ * @return {Number} */ getPositionY: function () { - return this._position.y; + return this._position.y; }, /** @@ -782,7 +782,7 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{ * @param {Boolean} visible Pass true to make the node visible, false to hide the node. */ setVisible: function (visible) { - if(this._visible !== visible){ + if (this._visible !== visible) { this._visible = visible; //if(visible) this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.transformDirty); @@ -1019,8 +1019,8 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{ * @function * @param {String} name */ - setName: function(name){ - this._name = name; + setName: function (name) { + this._name = name; }, /** @@ -1028,7 +1028,7 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{ * @function * @returns {string} A string that identifies the node. */ - getName: function(){ + getName: function () { return this._name; }, @@ -1166,7 +1166,7 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{ * @deprecated since v3.0, please use getBoundingBox instead * @return {cc.Rect} */ - boundingBox: function(){ + boundingBox: function () { cc.log(cc._LogInfos.Node_boundingBox); return this.getBoundingBox(); }, @@ -1223,16 +1223,16 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{ * @param {String} name A name to find the child node. * @return {cc.Node} a CCNode object whose name equals to the input parameter */ - getChildByName: function(name){ - if(!name){ + getChildByName: function (name) { + if (!name) { cc.log("Invalid name"); return null; } var locChildren = this._children; - for(var i = 0, len = locChildren.length; i < len; i++){ - if(locChildren[i]._name === name) - return locChildren[i]; + for (var i = 0, len = locChildren.length; i < len; i++) { + if (locChildren[i]._name === name) + return locChildren[i]; } return null; }, @@ -1252,10 +1252,10 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{ var name, setTag = false; if (tag === undefined) { name = child._name; - } else if (typeof tag === 'string'){ + } else if (typeof tag === 'string') { name = tag; tag = undefined; - } else if (typeof tag === 'number'){ + } else if (typeof tag === 'number') { setTag = true; name = ""; } @@ -1266,12 +1266,12 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{ this._addChildHelper(child, localZOrder, tag, name, setTag); }, - _addChildHelper: function(child, localZOrder, tag, name, setTag){ - if(!this._children) + _addChildHelper: function (child, localZOrder, tag, name, setTag) { + if (!this._children) this._children = []; this._insertChild(child, localZOrder); - if(setTag) + if (setTag) child.setTag(tag); else child.setName(name); @@ -1279,7 +1279,7 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{ child.setParent(this); child.setOrderOfArrival(cc.s_globalOrderOfArrival++); - if( this._running ){ + if (this._running) { child.onEnter(); // prevent onEnterTransitionDidFinish to be called twice when a node is added in onEnter if (this._isTransitionFinished) @@ -1429,7 +1429,7 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{ child._setLocalZOrder(z); }, - setNodeDirty: function(){ + setNodeDirty: function () { this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.transformDirty); }, @@ -1462,22 +1462,22 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{ // 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{ + while (j >= 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; + _children[j + 1] = tmp; } //don't need to check children recursively, that's done in visit of each child @@ -1680,49 +1680,49 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{ */ schedule: function (callback, interval, repeat, delay, key) { var len = arguments.length; - if(typeof callback === "function"){ + if (typeof callback === "function") { //callback, interval, repeat, delay, key - if(len === 1){ + if (len === 1) { //callback interval = 0; repeat = cc.REPEAT_FOREVER; delay = 0; key = this.__instanceId; - }else if(len === 2){ - if(typeof interval === "number"){ + } else if (len === 2) { + if (typeof interval === "number") { //callback, interval repeat = cc.REPEAT_FOREVER; delay = 0; key = this.__instanceId; - }else{ + } else { //callback, key key = interval; interval = 0; repeat = cc.REPEAT_FOREVER; delay = 0; } - }else if(len === 3){ - if(typeof repeat === "string"){ + } else if (len === 3) { + if (typeof repeat === "string") { //callback, interval, key key = repeat; repeat = cc.REPEAT_FOREVER; - }else{ + } else { //callback, interval, repeat key = this.__instanceId; } delay = 0; - }else if(len === 4){ + } else if (len === 4) { key = this.__instanceId; } - }else{ + } else { //selector //selector, interval //selector, interval, repeat, delay - if(len === 1){ + if (len === 1) { interval = 0; repeat = cc.REPEAT_FOREVER; delay = 0; - }else if(len === 2){ + } else if (len === 2) { repeat = cc.REPEAT_FOREVER; delay = 0; } @@ -1749,7 +1749,7 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{ scheduleOnce: function (callback, delay, key) { //selector, delay //callback, delay, key - if(key === undefined) + if (key === undefined) key = this.__instanceId; this.schedule(callback, 0, 0, delay, key); }, @@ -1885,7 +1885,7 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{ * @return {cc.AffineTransform} */ getParentToNodeTransform: function () { - return this._renderCmd.getParentToNodeTransform(); + return this._renderCmd.getParentToNodeTransform(); }, /** @@ -1912,7 +1912,7 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{ * @function * @deprecated since v3.0, please use getNodeToWorldTransform instead */ - nodeToWorldTransform: function(){ + nodeToWorldTransform: function () { return this.getNodeToWorldTransform(); }, @@ -1950,7 +1950,7 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{ * @return {cc.Point} */ convertToWorldSpace: function (nodePoint) { - nodePoint = nodePoint || cc.p(0,0); + nodePoint = nodePoint || cc.p(0, 0); return cc.pointApplyAffineTransform(nodePoint, this.getNodeToWorldTransform()); }, @@ -1973,7 +1973,7 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{ * @return {cc.Point} */ convertToWorldSpaceAR: function (nodePoint) { - nodePoint = nodePoint || cc.p(0,0); + nodePoint = nodePoint || cc.p(0, 0); var pt = cc.pAdd(nodePoint, this._renderCmd.getAnchorPointInPoints()); return this.convertToWorldSpace(pt); }, @@ -2121,7 +2121,7 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{ * @param {cc.Node.RenderCmd} parentCmd parent's render command * @param {boolean} recursive whether call its children's transform */ - transform: function(parentCmd, recursive){ + transform: function (parentCmd, recursive) { this._renderCmd.transform(parentCmd, recursive); }, @@ -2132,7 +2132,7 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{ * @return {cc.AffineTransform} * @deprecated since v3.0, please use getNodeToParentTransform instead */ - nodeToParentTransform: function(){ + nodeToParentTransform: function () { return this.getNodeToParentTransform(); }, @@ -2142,20 +2142,20 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{ * @function * @return {cc.AffineTransform} The affine transform object */ - getNodeToParentTransform: function(ancestor){ + getNodeToParentTransform: function (ancestor) { var t = this._renderCmd.getNodeToParentTransform(); - if(ancestor){ + if (ancestor) { var T = {a: t.a, b: t.b, c: t.c, d: t.d, tx: t.tx, ty: t.ty}; - for(var p = this._parent; p != null && p != ancestor ; p = p.getParent()){ + for (var p = this._parent; p != null && p != ancestor; p = p.getParent()) { cc.affineTransformConcatIn(T, p.getNodeToParentTransform()); } return T; - }else{ + } else { return t; } }, - getNodeToParentAffineTransform: function(ancestor){ + getNodeToParentAffineTransform: function (ancestor) { return this.getNodeToParentTransform(ancestor); }, @@ -2429,8 +2429,8 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{ this._renderCmd = cc.renderer.getRenderCmd(this); }, - _createRenderCmd: function(){ - if(cc._renderType === cc.game.RENDER_TYPE_CANVAS) + _createRenderCmd: function () { + if (cc._renderType === cc.game.RENDER_TYPE_CANVAS) return new cc.Node.CanvasRenderCmd(this); else return new cc.Node.WebGLRenderCmd(this); @@ -2462,7 +2462,7 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{ * And returns a boolean result. Your callback can return `true` to terminate the enumeration. * */ - enumerateChildren: function(name, callback){ + enumerateChildren: function (name, callback) { cc.assert(name && name.length != 0, "Invalid name"); cc.assert(callback != null, "Invalid callback function"); @@ -2472,39 +2472,39 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{ // Starts with '//'? var searchRecursively = false; - if(length > 2 && name[0] === "/" && name[1] === "/"){ + if (length > 2 && name[0] === "/" && name[1] === "/") { searchRecursively = true; subStrStartPos = 2; subStrlength -= 2; } var searchFromParent = false; - if(length > 3 && name[length-3] === "/" && name[length-2] === "." && name[length-1] === "."){ + if (length > 3 && name[length - 3] === "/" && name[length - 2] === "." && name[length - 1] === ".") { searchFromParent = true; subStrlength -= 3; } var newName = name.substr(subStrStartPos, subStrlength); - if(searchFromParent) + if (searchFromParent) newName = "[[:alnum:]]+/" + newName; - if(searchRecursively) + if (searchRecursively) this.doEnumerateRecursive(this, newName, callback); else this.doEnumerate(newName, callback); }, - doEnumerateRecursive: function(node, name, callback){ + doEnumerateRecursive: function (node, name, callback) { var ret = false; - if(node.doEnumerate(name,callback)){ + if (node.doEnumerate(name, callback)) { ret = true; - }else{ + } else { var child, children = node.getChildren(), length = children.length; // search its children - for (var i=0; i * 0, 1, 0 ]

* @function - * + * * @return {cc.AffineTransform} */ cc.affineTransformMakeIdentity = function () { @@ -117,7 +117,7 @@ cc.affineTransformMakeIdentity = function () { * [ 1, 0, 0,
* 0, 1, 0 ]

* @function - * + * * @return {cc.AffineTransform} * @deprecated since v3.0, please use cc.affineTransformMakeIdentity() instead * @see cc.affineTransformMakeIdentity @@ -129,7 +129,7 @@ cc.affineTransformIdentity = function () { /** * Apply the affine transformation on a rect. * @function - * + * * @param {cc.Rect} rect * @param {cc.AffineTransform} anAffineTransform * @return {cc.Rect} @@ -153,7 +153,7 @@ cc.rectApplyAffineTransform = function (rect, anAffineTransform) { return cc.rect(minX, minY, (maxX - minX), (maxY - minY)); }; -cc._rectApplyAffineTransformIn = function(rect, anAffineTransform){ +cc._rectApplyAffineTransformIn = function (rect, anAffineTransform) { var top = cc.rectGetMinY(rect); var left = cc.rectGetMinX(rect); var right = cc.rectGetMaxX(rect); @@ -179,7 +179,7 @@ cc._rectApplyAffineTransformIn = function(rect, anAffineTransform){ /** * Create a new affine transformation with a base transformation matrix and a translation based on it. * @function - * + * * @param {cc.AffineTransform} t The base affine transform object * @param {Number} tx The translation on x axis * @param {Number} ty The translation on y axis @@ -219,12 +219,14 @@ cc.affineTransformRotate = function (aTransform, anAngle) { var fSin = Math.sin(anAngle); var fCos = Math.cos(anAngle); - return {a: aTransform.a * fCos + aTransform.c * fSin, + return { + a: aTransform.a * fCos + aTransform.c * fSin, b: aTransform.b * fCos + aTransform.d * fSin, c: aTransform.c * fCos - aTransform.a * fSin, d: aTransform.d * fCos - aTransform.b * fSin, tx: aTransform.tx, - ty: aTransform.ty}; + ty: aTransform.ty + }; }; /** @@ -236,12 +238,14 @@ cc.affineTransformRotate = function (aTransform, anAngle) { * @return {cc.AffineTransform} The result of concatenation */ cc.affineTransformConcat = function (t1, t2) { - return {a: t1.a * t2.a + t1.b * t2.c, //a + return { + a: t1.a * t2.a + t1.b * t2.c, //a b: t1.a * t2.b + t1.b * t2.d, //b c: t1.c * t2.a + t1.d * t2.c, //c d: t1.c * t2.b + t1.d * t2.d, //d tx: t1.tx * t2.a + t1.ty * t2.c + t2.tx, //tx - ty: t1.tx * t2.b + t1.ty * t2.d + t2.ty}; //ty + ty: t1.tx * t2.b + t1.ty * t2.d + t2.ty + }; //ty }; /** @@ -283,6 +287,8 @@ cc.affineTransformEqualToTransform = function (t1, t2) { */ cc.affineTransformInvert = function (t) { var determinant = 1 / (t.a * t.d - t.b * t.c); - return {a: determinant * t.d, b: -determinant * t.b, c: -determinant * t.c, d: determinant * t.a, - tx: determinant * (t.c * t.ty - t.d * t.tx), ty: determinant * (t.b * t.tx - t.a * t.ty)}; + return { + a: determinant * t.d, b: -determinant * t.b, c: -determinant * t.c, d: determinant * t.a, + tx: determinant * (t.c * t.ty - t.d * t.tx), ty: determinant * (t.b * t.tx - t.a * t.ty) + }; }; diff --git a/cocos2d/core/event-manager/CCEventHelper.js b/cocos2d/core/event-manager/CCEventHelper.js index bd4198f23a..b005e71c59 100644 --- a/cocos2d/core/event-manager/CCEventHelper.js +++ b/cocos2d/core/event-manager/CCEventHelper.js @@ -24,111 +24,112 @@ ****************************************************************************/ // The event helper -cc.EventHelper = function(){}; +cc.EventHelper = function () { +}; cc.EventHelper.prototype = { constructor: cc.EventHelper, - apply: function ( object ) { + apply: function (object) { object.addEventListener = cc.EventHelper.prototype.addEventListener; object.hasEventListener = cc.EventHelper.prototype.hasEventListener; object.removeEventListener = cc.EventHelper.prototype.removeEventListener; object.dispatchEvent = cc.EventHelper.prototype.dispatchEvent; }, - addEventListener: function ( type, listener, target ) { + addEventListener: function (type, listener, target) { //check 'type' status, if the status is ready, dispatch event next frame - if(type === "load" && this._textureLoaded){ //only load event checked. - setTimeout(function(){ + if (type === "load" && this._textureLoaded) { //only load event checked. + setTimeout(function () { listener.call(target); }, 0); return; } - if ( this._listeners === undefined ) + if (this._listeners === undefined) this._listeners = {}; var listeners = this._listeners; - if ( listeners[ type ] === undefined ) - listeners[ type ] = []; + if (listeners[type] === undefined) + listeners[type] = []; - if ( !this.hasEventListener(type, listener, target)) - listeners[ type ].push( {callback:listener, eventTarget: target} ); + if (!this.hasEventListener(type, listener, target)) + listeners[type].push({callback: listener, eventTarget: target}); }, - hasEventListener: function ( type, listener, target ) { - if ( this._listeners === undefined ) + hasEventListener: function (type, listener, target) { + if (this._listeners === undefined) return false; var listeners = this._listeners; - if ( listeners[ type ] !== undefined ) { - for(var i = 0, len = listeners.length; i < len ; i++){ + if (listeners[type] !== undefined) { + for (var i = 0, len = listeners.length; i < len; i++) { var selListener = listeners[i]; - if(selListener.callback === listener && selListener.eventTarget === target) + if (selListener.callback === listener && selListener.eventTarget === target) return true; } } return false; }, - removeEventListener: function( type, listener, target){ - if ( this._listeners === undefined ) + removeEventListener: function (type, listener, target) { + if (this._listeners === undefined) return; var listeners = this._listeners; - var listenerArray = listeners[ type ]; + var listenerArray = listeners[type]; - if ( listenerArray !== undefined ) { - for(var i = 0; i < listenerArray.length ; ){ + if (listenerArray !== undefined) { + for (var i = 0; i < listenerArray.length;) { var selListener = listenerArray[i]; - if(selListener.eventTarget === target && selListener.callback === listener) - listenerArray.splice( i, 1 ); + if (selListener.eventTarget === target && selListener.callback === listener) + listenerArray.splice(i, 1); else i++ } } }, - removeEventTarget: function( type, listener, target){ - if ( this._listeners === undefined ) + removeEventTarget: function (type, listener, target) { + if (this._listeners === undefined) return; var listeners = this._listeners; - var listenerArray = listeners[ type ]; + var listenerArray = listeners[type]; - if ( listenerArray !== undefined ) { - for(var i = 0; i < listenerArray.length ; ){ + if (listenerArray !== undefined) { + for (var i = 0; i < listenerArray.length;) { var selListener = listenerArray[i]; - if(selListener.eventTarget === target) - listenerArray.splice( i, 1 ); + if (selListener.eventTarget === target) + listenerArray.splice(i, 1); else i++ } } }, - dispatchEvent: function ( event, clearAfterDispatch ) { - if ( this._listeners === undefined ) + dispatchEvent: function (event, clearAfterDispatch) { + if (this._listeners === undefined) return; - if(clearAfterDispatch == null) + if (clearAfterDispatch == null) clearAfterDispatch = true; var listeners = this._listeners; - var listenerArray = listeners[ event]; + var listenerArray = listeners[event]; - if ( listenerArray !== undefined ) { + if (listenerArray !== undefined) { var array = []; var length = listenerArray.length; - for ( var i = 0; i < length; i ++ ) { - array[ i ] = listenerArray[ i ]; + for (var i = 0; i < length; i++) { + array[i] = listenerArray[i]; } - for ( i = 0; i < length; i ++ ) { - array[ i ].callback.call( array[i].eventTarget, this ); + for (i = 0; i < length; i++) { + array[i].callback.call(array[i].eventTarget, this); } - if(clearAfterDispatch) + if (clearAfterDispatch) listenerArray.length = 0; } } diff --git a/cocos2d/core/event-manager/CCEventManager.js b/cocos2d/core/event-manager/CCEventManager.js index 76599754c1..890ba5bf7c 100644 --- a/cocos2d/core/event-manager/CCEventManager.js +++ b/cocos2d/core/event-manager/CCEventManager.js @@ -107,9 +107,9 @@ function __getListenerID (event) { */ cc.eventManager = /** @lends cc.eventManager# */{ //Priority dirty flag - DIRTY_NONE:0, - DIRTY_FIXED_PRIORITY:1 <<0, - DIRTY_SCENE_GRAPH_PRIORITY : 1<< 1, + DIRTY_NONE: 0, + DIRTY_FIXED_PRIORITY: 1 << 0, + DIRTY_SCENE_GRAPH_PRIORITY: 1 << 1, DIRTY_ALL: 3, _listenersMap: {}, @@ -124,7 +124,7 @@ cc.eventManager = /** @lends cc.eventManager# */{ _isEnabled: false, _nodePriorityIndex: 0, - _internalCustomListenerIDs:[cc.game.EVENT_HIDE, cc.game.EVENT_SHOW], + _internalCustomListenerIDs: [cc.game.EVENT_HIDE, cc.game.EVENT_SHOW], _setDirtyForNode: function (node) { // Mark the node dirty only when there is an event listener associated with it. @@ -143,12 +143,12 @@ cc.eventManager = /** @lends cc.eventManager# */{ pauseTarget: function (node, recursive) { var listeners = this._nodeListenersMap[node.__instanceId], i, len; if (listeners) { - for ( i = 0, len = listeners.length; i < len; i++) + for (i = 0, len = listeners.length; i < len; i++) listeners[i]._setPaused(true); } if (recursive === true) { var locChildren = node.getChildren(); - for ( i = 0, len = locChildren.length; i< len; i++) + for (i = 0, len = locChildren.length; i < len; i++) this.pauseTarget(locChildren[i], true); } }, @@ -160,14 +160,14 @@ cc.eventManager = /** @lends cc.eventManager# */{ */ resumeTarget: function (node, recursive) { var listeners = this._nodeListenersMap[node.__instanceId], i, len; - if (listeners){ - for ( i = 0, len = listeners.length; i < len; i++) + if (listeners) { + for (i = 0, len = listeners.length; i < len; i++) listeners[i]._setPaused(false); } this._setDirtyForNode(node); if (recursive === true) { var locChildren = node.getChildren(); - for ( i = 0, len = locChildren.length; i< len; i++) + for (i = 0, len = locChildren.length; i< len; i++) this.resumeTarget(locChildren[i], true); } }, @@ -231,7 +231,7 @@ cc.eventManager = /** @lends cc.eventManager# */{ for (var i = 0; i < listenerVector.length;) { selListener = listenerVector[i]; selListener._setRegistered(false); - if (selListener._getSceneGraphPriority() != null){ + if (selListener._getSceneGraphPriority() != null) { this._dissociateNodeAndEventListener(selListener._getSceneGraphPriority(), selListener); selListener._setSceneGraphPriority(null); // NULL out the node pointer so we don't have any dangling pointers to destroyed nodes. } @@ -273,7 +273,7 @@ cc.eventManager = /** @lends cc.eventManager# */{ }, _sortEventListeners: function (listenerID) { - var dirtyFlag = this.DIRTY_NONE, locFlagMap = this._priorityDirtyFlagMap; + var dirtyFlag = this.DIRTY_NONE, locFlagMap = this._priorityDirtyFlagMap; if (locFlagMap[listenerID]) dirtyFlag = locFlagMap[listenerID]; @@ -284,9 +284,9 @@ cc.eventManager = /** @lends cc.eventManager# */{ if (dirtyFlag & this.DIRTY_FIXED_PRIORITY) this._sortListenersOfFixedPriority(listenerID); - if (dirtyFlag & this.DIRTY_SCENE_GRAPH_PRIORITY){ + if (dirtyFlag & this.DIRTY_SCENE_GRAPH_PRIORITY) { var rootNode = cc.director.getRunningScene(); - if(rootNode) + if (rootNode) this._sortListenersOfSceneGraphPriority(listenerID, rootNode); else locFlagMap[listenerID] = this.DIRTY_SCENE_GRAPH_PRIORITY; @@ -300,7 +300,7 @@ cc.eventManager = /** @lends cc.eventManager# */{ return; var sceneGraphListener = listeners.getSceneGraphPriorityListeners(); - if(!sceneGraphListener || sceneGraphListener.length === 0) + if (!sceneGraphListener || sceneGraphListener.length === 0) return; // Reset priority index @@ -313,12 +313,12 @@ cc.eventManager = /** @lends cc.eventManager# */{ listeners.getSceneGraphPriorityListeners().sort(this._sortEventListenersOfSceneGraphPriorityDes); }, - _sortEventListenersOfSceneGraphPriorityDes : function(l1, l2){ + _sortEventListenersOfSceneGraphPriorityDes: function (l1, l2) { var locNodePriorityMap = cc.eventManager._nodePriorityMap, node1 = l1._getSceneGraphPriority(), node2 = l2._getSceneGraphPriority(); - if( !l2 || !node2 || !locNodePriorityMap[node2.__instanceId] ) + if (!l2 || !node2 || !locNodePriorityMap[node2.__instanceId]) return -1; - else if( !l1 || !node1 || !locNodePriorityMap[node1.__instanceId] ) + else if (!l1 || !node1 || !locNodePriorityMap[node1.__instanceId]) return 1; return locNodePriorityMap[l2._getSceneGraphPriority().__instanceId] - locNodePriorityMap[l1._getSceneGraphPriority().__instanceId]; }, @@ -329,7 +329,7 @@ cc.eventManager = /** @lends cc.eventManager# */{ return; var fixedListeners = listeners.getFixedPriorityListeners(); - if(!fixedListeners || fixedListeners.length === 0) + if (!fixedListeners || fixedListeners.length === 0) return; // After sort: priority < 0, > 0 fixedListeners.sort(this._sortListenersOfFixedPriorityAsc); @@ -439,24 +439,24 @@ cc.eventManager = /** @lends cc.eventManager# */{ }, //Remove all listeners in _toRemoveListeners list and cleanup - _cleanToRemovedListeners: function(){ + _cleanToRemovedListeners: function () { var toRemovedListeners = this._toRemovedListeners; - for(var i = 0; i< toRemovedListeners.length; i++){ + for (var i = 0; i < toRemovedListeners.length; i++) { var selListener = toRemovedListeners[i]; var listeners = this._listenersMap[selListener._getListenerID()]; - if(!listeners) + if (!listeners) continue; var idx, fixedPriorityListeners = listeners.getFixedPriorityListeners(), sceneGraphPriorityListeners = listeners.getSceneGraphPriorityListeners(); - if(sceneGraphPriorityListeners){ + if (sceneGraphPriorityListeners) { idx = sceneGraphPriorityListeners.indexOf(selListener); if (idx !== -1) { sceneGraphPriorityListeners.splice(idx, 1); } } - if(fixedPriorityListeners){ + if (fixedPriorityListeners) { idx = fixedPriorityListeners.indexOf(selListener); if (idx !== -1) { fixedPriorityListeners.splice(idx, 1); @@ -466,7 +466,7 @@ cc.eventManager = /** @lends cc.eventManager# */{ toRemovedListeners.length = 0; }, - _onTouchEventCallback: function(listener, argsObj){ + _onTouchEventCallback: function (listener, argsObj) { // Skip if the listener was removed. if (!listener._isRegistered) return false; @@ -485,14 +485,14 @@ cc.eventManager = /** @lends cc.eventManager# */{ } else if (listener._claimedTouches.length > 0 && ((removedIdx = listener._claimedTouches.indexOf(selTouch)) !== -1)) { isClaimed = true; - if(getCode === eventCode.MOVED && listener.onTouchMoved){ + if (getCode === eventCode.MOVED && listener.onTouchMoved) { listener.onTouchMoved(selTouch, event); - } else if(getCode === eventCode.ENDED){ + } else if (getCode === eventCode.ENDED) { if (listener.onTouchEnded) listener.onTouchEnded(selTouch, event); if (listener._registered) listener._claimedTouches.splice(removedIdx, 1); - } else if(getCode === eventCode.CANCELLED){ + } else if (getCode === eventCode.CANCELLED) { if (listener.onTouchCancelled) listener.onTouchCancelled(selTouch, event); if (listener._registered) @@ -558,13 +558,13 @@ cc.eventManager = /** @lends cc.eventManager# */{ var eventCode = cc.EventTouch.EventCode, event = callbackParams.event, touches = callbackParams.touches, getCode = event.getEventCode(); event._setCurrentTarget(listener._node); - if(getCode === eventCode.BEGAN && listener.onTouchesBegan) + if (getCode === eventCode.BEGAN && listener.onTouchesBegan) listener.onTouchesBegan(touches, event); - else if(getCode === eventCode.MOVED && listener.onTouchesMoved) + else if (getCode === eventCode.MOVED && listener.onTouchesMoved) listener.onTouchesMoved(touches, event); - else if(getCode === eventCode.ENDED && listener.onTouchesEnded) + else if (getCode === eventCode.ENDED && listener.onTouchesEnded) listener.onTouchesEnded(touches, event); - else if(getCode === eventCode.CANCELLED && listener.onTouchesCancelled) + else if (getCode === eventCode.CANCELLED && listener.onTouchesCancelled) listener.onTouchesCancelled(touches, event); // If the event was stopped, return directly. @@ -691,7 +691,7 @@ cc.eventManager = /** @lends cc.eventManager# */{ } }, - _sortNumberAsc : function (a, b) { + _sortNumberAsc: function (a, b) { return a - b; }, @@ -711,11 +711,11 @@ cc.eventManager = /** @lends cc.eventManager# */{ */ addListener: function (listener, nodeOrPriority) { cc.assert(listener && nodeOrPriority, cc._LogInfos.eventManager_addListener_2); - if(!(listener instanceof cc.EventListener)){ + if (!(listener instanceof cc.EventListener)) { cc.assert(!cc.isNumber(nodeOrPriority), cc._LogInfos.eventManager_addListener_3); listener = cc.EventListener.create(listener); } else { - if(listener._isRegistered()){ + if (listener._isRegistered()) { cc.log(cc._LogInfos.eventManager_addListener_4); return; } @@ -802,7 +802,7 @@ cc.eventManager = /** @lends cc.eventManager# */{ } }, - _removeListenerInCallback: function(listeners, callback){ + _removeListenerInCallback: function (listeners, callback) { if (listeners == null) return false; @@ -810,7 +810,7 @@ cc.eventManager = /** @lends cc.eventManager# */{ var selListener = listeners[i]; if (selListener._onCustomEvent === callback || selListener._onEvent === callback) { selListener._setRegistered(false); - if (selListener._getSceneGraphPriority() != null){ + if (selListener._getSceneGraphPriority() != null) { this._dissociateNodeAndEventListener(selListener._getSceneGraphPriority(), selListener); selListener._setSceneGraphPriority(null); // NULL out the node pointer so we don't have any dangling pointers to destroyed nodes. } @@ -823,7 +823,7 @@ cc.eventManager = /** @lends cc.eventManager# */{ return false; }, - _removeListenerInVector : function(listeners, listener){ + _removeListenerInVector: function (listeners, listener) { if (listeners == null) return false; @@ -831,7 +831,7 @@ cc.eventManager = /** @lends cc.eventManager# */{ var selListener = listeners[i]; if (selListener === listener) { selListener._setRegistered(false); - if (selListener._getSceneGraphPriority() != null){ + if (selListener._getSceneGraphPriority() != null) { this._dissociateNodeAndEventListener(selListener._getSceneGraphPriority(), selListener); selListener._setSceneGraphPriority(null); // NULL out the node pointer so we don't have any dangling pointers to destroyed nodes. } @@ -916,8 +916,8 @@ cc.eventManager = /** @lends cc.eventManager# */{ */ removeAllListeners: function () { var locListeners = this._listenersMap, locInternalCustomEventIDs = this._internalCustomListenerIDs; - for (var selKey in locListeners){ - if(locInternalCustomEventIDs.indexOf(selKey) === -1) + for (var selKey in locListeners) { + if (locInternalCustomEventIDs.indexOf(selKey) === -1) this._removeListenersForListenerID(selKey); } }, @@ -938,7 +938,7 @@ cc.eventManager = /** @lends cc.eventManager# */{ if (fixedPriorityListeners) { var found = fixedPriorityListeners.indexOf(listener); if (found !== -1) { - if(listener._getSceneGraphPriority() != null) + if (listener._getSceneGraphPriority() != null) cc.log(cc._LogInfos.eventManager_setPriority); if (listener._getFixedPriority() !== fixedPriority) { listener._setFixedPriority(fixedPriority); @@ -976,7 +976,7 @@ cc.eventManager = /** @lends cc.eventManager# */{ this._updateDirtyFlagForSceneGraph(); this._inDispatch++; - if(!event || !event.getType) + if (!event || !event.getType) throw new Error("event is undefined"); if (event._type === cc.Event.TOUCH) { this._dispatchTouchEvent(event); @@ -995,7 +995,7 @@ cc.eventManager = /** @lends cc.eventManager# */{ this._inDispatch--; }, - _onListenerCallback: function(listener, event){ + _onListenerCallback: function (listener, event) { event._setCurrentTarget(listener._getSceneGraphPriority()); listener._onEvent(event); return event.isStopped(); @@ -1013,4 +1013,4 @@ cc.eventManager = /** @lends cc.eventManager# */{ } }; -})(); \ No newline at end of file +})(); diff --git a/cocos2d/core/labelttf/CCLabelTTF.js b/cocos2d/core/labelttf/CCLabelTTF.js index 2bfb105988..2342fc555c 100644 --- a/cocos2d/core/labelttf/CCLabelTTF.js +++ b/cocos2d/core/labelttf/CCLabelTTF.js @@ -512,8 +512,8 @@ cc.LabelTTF = cc.Sprite.extend(/** @lends cc.LabelTTF# */{ this._fontName = textDefinition.fontName; this._fontSize = textDefinition.fontSize || 12; - if(textDefinition.lineHeight) - this._lineHeight = textDefinition.lineHeight + if (textDefinition.lineHeight) + this._lineHeight = textDefinition.lineHeight; else this._lineHeight = this._fontSize; @@ -537,7 +537,7 @@ cc.LabelTTF = cc.Sprite.extend(/** @lends cc.LabelTTF# */{ if (mustUpdateTexture) this._renderCmd._updateTexture(); var flags = cc.Node._dirtyFlags; - this._renderCmd.setDirtyFlag(flags.colorDirty|flags.opacityDirty|flags.textDirty); + this._renderCmd.setDirtyFlag(flags.colorDirty | flags.opacityDirty | flags.textDirty); }, _prepareTextDefinition: function (adjustForResolution) { @@ -857,7 +857,7 @@ cc.LabelTTF = cc.Sprite.extend(/** @lends cc.LabelTTF# */{ }, //For web only - _setFontStyle: function(fontStyle){ + _setFontStyle: function (fontStyle) { if (this._fontStyle !== fontStyle) { this._fontStyle = fontStyle; this._renderCmd._setFontStyle(this._fontName, this._fontSize, this._fontStyle, this._fontWeight); @@ -865,11 +865,11 @@ cc.LabelTTF = cc.Sprite.extend(/** @lends cc.LabelTTF# */{ } }, - _getFontStyle: function(){ + _getFontStyle: function () { return this._fontStyle; }, - _setFontWeight: function(fontWeight){ + _setFontWeight: function (fontWeight) { if (this._fontWeight !== fontWeight) { this._fontWeight = fontWeight; this._renderCmd._setFontStyle(this._fontName, this._fontSize, this._fontStyle, this._fontWeight); @@ -877,7 +877,7 @@ cc.LabelTTF = cc.Sprite.extend(/** @lends cc.LabelTTF# */{ } }, - _getFontWeight: function(){ + _getFontWeight: function () { return this._fontWeight; } }); diff --git a/cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js b/cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js index 3cbfda1e0a..c4b7a33b93 100644 --- a/cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js +++ b/cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js @@ -32,7 +32,7 @@ cc.LabelTTF._lastWordRex = /([a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]+|\S)$ cc.LabelTTF._lastEnglish = /[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]+$/; cc.LabelTTF._firsrEnglish = /^[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]/; -(function() { +(function () { cc.LabelTTF.RenderCmd = function () { this._fontClientHeight = 18; this._fontStyleStr = ""; @@ -54,10 +54,10 @@ cc.LabelTTF._firsrEnglish = /^[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]/; proto.constructor = cc.LabelTTF.RenderCmd; proto._setFontStyle = function (fontNameOrFontDef, fontSize, fontStyle, fontWeight) { - if(fontNameOrFontDef instanceof cc.FontDefinition){ + if (fontNameOrFontDef instanceof cc.FontDefinition) { this._fontStyleStr = fontNameOrFontDef._getCanvasFontStr(); this._fontClientHeight = cc.LabelTTF.__getFontHeightByDiv(fontNameOrFontDef); - }else { + } else { var deviceFontSize = fontSize * cc.view.getDevicePixelRatio(); this._fontStyleStr = fontStyle + " " + fontWeight + " " + deviceFontSize + "px '" + fontNameOrFontDef + "'"; this._fontClientHeight = cc.LabelTTF.__getFontHeightByDiv(fontNameOrFontDef, fontSize); @@ -72,7 +72,7 @@ cc.LabelTTF._firsrEnglish = /^[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]/; return this._fontClientHeight; }; - proto._updateColor = function(){ + proto._updateColor = function () { this._setColorsString(); this._updateTexture(); }; @@ -220,9 +220,9 @@ cc.LabelTTF._firsrEnglish = /^[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]/; OffsetYArray.push(yOffset); } var tmpStatus = { - contextTransform:cc.p(dx,dy), - xOffset:xOffset, - OffsetYArray:OffsetYArray + contextTransform: cc.p(dx, dy), + xOffset: xOffset, + OffsetYArray: OffsetYArray }; this._status.push(tmpStatus); }; @@ -456,7 +456,8 @@ cc.LabelTTF._firsrEnglish = /^[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]/; var proto = cc.LabelTTF.CanvasRenderCmd.prototype; proto.constructor = cc.LabelTTF.CanvasRenderCmd; - proto._measureConfig = function () {}; + proto._measureConfig = function () { + }; proto._measure = function (text) { var context = cc._renderContext.getContext(); @@ -479,7 +480,7 @@ cc.LabelTTF._firsrEnglish = /^[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]/; return true; }; - proto.rendering = function(ctx) { + proto.rendering = function (ctx) { var scaleX = cc.view.getScaleX(), scaleY = cc.view.getScaleY(); var wrapper = ctx || cc._renderContext, context = wrapper.getContext(); @@ -487,11 +488,11 @@ cc.LabelTTF._firsrEnglish = /^[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]/; return; var node = this._node; wrapper.computeRealOffsetY(); - if(this._status.length <= 0) + if (this._status.length <= 0) return; - var locIndex = (this._renderingIndex >= this._status.length)? this._renderingIndex-this._status.length:this._renderingIndex; + var locIndex = (this._renderingIndex >= this._status.length) ? this._renderingIndex - this._status.length : this._renderingIndex; var status = this._status[locIndex]; - this._renderingIndex = locIndex+1; + this._renderingIndex = locIndex + 1; var locHeight = node._rect.height, locX = node._offsetPosition.x, diff --git a/cocos2d/core/labelttf/CCLabelTTFWebGLRenderCmd.js b/cocos2d/core/labelttf/CCLabelTTFWebGLRenderCmd.js index 6b7e25f8b6..fee7c6fa8f 100644 --- a/cocos2d/core/labelttf/CCLabelTTFWebGLRenderCmd.js +++ b/cocos2d/core/labelttf/CCLabelTTFWebGLRenderCmd.js @@ -23,7 +23,7 @@ ****************************************************************************/ // ----------------------------------- LabelTTF WebGL render cmd ---------------------------- -(function() { +(function () { cc.LabelTTF.WebGLRenderCmd = function (renderable) { cc.Sprite.WebGLRenderCmd.call(this, renderable); cc.LabelTTF.CacheRenderCmd.call(this); @@ -32,5 +32,6 @@ cc.inject(cc.LabelTTF.CacheRenderCmd.prototype, proto); proto.constructor = cc.LabelTTF.WebGLRenderCmd; - proto._updateColor = function () {}; -})(); \ No newline at end of file + proto._updateColor = function () { + }; +})(); diff --git a/cocos2d/core/layers/CCLayer.js b/cocos2d/core/layers/CCLayer.js index fc085fa19f..12030caa7a 100644 --- a/cocos2d/core/layers/CCLayer.js +++ b/cocos2d/core/layers/CCLayer.js @@ -45,7 +45,7 @@ cc.Layer = cc.Node.extend(/** @lends cc.Layer# */{ /** * Initialization of the layer, please do not call this function by yourself, you should pass the parameters to constructor to initialize a layer */ - init: function(){ + init: function () { var _t = this; _t._ignoreAnchorPointForPosition = true; _t.setAnchorPoint(0.5, 0.5); @@ -61,7 +61,7 @@ cc.Layer = cc.Node.extend(/** @lends cc.Layer# */{ * @function * @see cc.Layer#unbake */ - bake: function(){ + bake: function () { this._renderCmd.bake(); }, @@ -71,7 +71,7 @@ cc.Layer = cc.Node.extend(/** @lends cc.Layer# */{ * @function * @see cc.Layer#bake */ - unbake: function(){ + unbake: function () { this._renderCmd.unbake(); }, @@ -81,16 +81,16 @@ cc.Layer = cc.Node.extend(/** @lends cc.Layer# */{ * @returns {boolean} * @see cc.Layer#bake and cc.Layer#unbake */ - isBaked: function(){ + isBaked: function () { return this._renderCmd._isBaked; }, - addChild: function(child, localZOrder, tag){ + addChild: function (child, localZOrder, tag) { cc.Node.prototype.addChild.call(this, child, localZOrder, tag); this._renderCmd._bakeForAddChild(child); }, - _createRenderCmd: function(){ + _createRenderCmd: function () { if (cc._renderType === cc.game.RENDER_TYPE_CANVAS) return new cc.Layer.CanvasRenderCmd(this); else @@ -188,7 +188,7 @@ cc.LayerColor = cc.Layer.extend(/** @lends cc.LayerColor# */{ * @param {Number} [width=] * @param {Number} [height=] */ - ctor: function(color, width, height){ + ctor: function (color, width, height) { cc.Layer.prototype.ctor.call(this); this._blendFunc = cc.BlendFunc._alphaNonPremultiplied(); cc.LayerColor.prototype.init.call(this, color, width, height); @@ -212,7 +212,7 @@ cc.LayerColor = cc.Layer.extend(/** @lends cc.LayerColor# */{ locRealColor.g = color.g; locRealColor.b = color.b; this._realOpacity = color.a; - this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.colorDirty|cc.Node._dirtyFlags.opacityDirty); + this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.colorDirty | cc.Node._dirtyFlags.opacityDirty); cc.LayerColor.prototype.setContentSize.call(this, width, height); return true; @@ -235,7 +235,7 @@ cc.LayerColor = cc.Layer.extend(/** @lends cc.LayerColor# */{ this._renderCmd.updateBlendFunc(locBlendFunc); }, - _createRenderCmd: function(){ + _createRenderCmd: function () { if (cc._renderType === cc.game.RENDER_TYPE_CANVAS) return new cc.LayerColor.CanvasRenderCmd(this); else @@ -257,7 +257,7 @@ cc.LayerColor.create = function (color, width, height) { }; //LayerColor - Getter Setter -(function(){ +(function () { var proto = cc.LayerColor.prototype; cc.defineGetterSetter(proto, "width", proto._getWidth, proto._setWidth); cc.defineGetterSetter(proto, "height", proto._getHeight, proto._setHeight); @@ -328,12 +328,12 @@ cc.LayerGradient = cc.LayerColor.extend(/** @lends cc.LayerGradient# */{ this._startOpacity = 255; this._endOpacity = 255; - if(stops && stops instanceof Array){ + if (stops && stops instanceof Array) { this._colorStops = stops; - stops.splice(0, 0, {p:0, color: start || cc.color.BLACK}); - stops.push({p:1, color: end || cc.color.BLACK}); + stops.splice(0, 0, {p: 0, color: start || cc.color.BLACK}); + stops.push({p: 1, color: end || cc.color.BLACK}); } else - this._colorStops = [{p:0, color: start || cc.color.BLACK}, {p:1, color: end || cc.color.BLACK}]; + this._colorStops = [{p: 0, color: start || cc.color.BLACK}, {p: 1, color: end || cc.color.BLACK}]; cc.LayerGradient.prototype.init.call(this, start, end, v, stops); }, @@ -365,7 +365,7 @@ cc.LayerGradient = cc.LayerColor.extend(/** @lends cc.LayerGradient# */{ _t._compressedInterpolation = true; cc.LayerColor.prototype.init.call(_t, cc.color(start.r, start.g, start.b, 255)); - this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.colorDirty|cc.Node._dirtyFlags.opacityDirty|cc.Node._dirtyFlags.gradientDirty); + this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.colorDirty | cc.Node._dirtyFlags.opacityDirty | cc.Node._dirtyFlags.gradientDirty); return true; }, @@ -408,7 +408,7 @@ cc.LayerGradient = cc.LayerColor.extend(/** @lends cc.LayerGradient# */{ this.color = color; //update the color stops var stops = this._colorStops; - if(stops && stops.length > 0){ + if (stops && stops.length > 0) { var selColor = stops[0].color; selColor.r = color.r; selColor.g = color.g; @@ -431,8 +431,8 @@ cc.LayerGradient = cc.LayerColor.extend(/** @lends cc.LayerGradient# */{ locColor.b = color.b; //update the color stops var stops = this._colorStops; - if(stops && stops.length > 0){ - var selColor = stops[stops.length -1].color; + if (stops && stops.length > 0) { + var selColor = stops[stops.length - 1].color; selColor.r = color.r; selColor.g = color.g; selColor.b = color.b; @@ -456,7 +456,7 @@ cc.LayerGradient = cc.LayerColor.extend(/** @lends cc.LayerGradient# */{ this._startOpacity = o; //update the color stops var stops = this._colorStops; - if(stops && stops.length > 0) + if (stops && stops.length > 0) stops[0].color.a = o; this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.opacityDirty); }, @@ -476,8 +476,8 @@ cc.LayerGradient = cc.LayerColor.extend(/** @lends cc.LayerGradient# */{ setEndOpacity: function (o) { this._endOpacity = o; var stops = this._colorStops; - if(stops && stops.length > 0) - stops[stops.length -1].color.a = o; + if (stops && stops.length > 0) + stops[stops.length - 1].color.a = o; this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.opacityDirty); }, @@ -531,7 +531,7 @@ cc.LayerGradient = cc.LayerColor.extend(/** @lends cc.LayerGradient# */{ * [{p: 0, color: cc.color.RED},{p: 1, color: cc.color.RED},...] * @returns {Array} */ - getColorStops: function(){ + getColorStops: function () { return this._colorStops; }, /** @@ -548,13 +548,13 @@ cc.LayerGradient = cc.LayerColor.extend(/** @lends cc.LayerGradient# */{ * //where p = A value between 0.0 and 1.0 that represents the position between start and end in a gradient * */ - setColorStops: function(colorStops){ + setColorStops: function (colorStops) { this._colorStops = colorStops; //todo need update the start color and end color - this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.colorDirty|cc.Node._dirtyFlags.opacityDirty|cc.Node._dirtyFlags.gradientDirty); + this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.colorDirty | cc.Node._dirtyFlags.opacityDirty | cc.Node._dirtyFlags.gradientDirty); }, - _createRenderCmd: function(){ + _createRenderCmd: function () { if (cc._renderType === cc.game.RENDER_TYPE_CANVAS) return new cc.LayerGradient.CanvasRenderCmd(this); else @@ -576,7 +576,7 @@ cc.LayerGradient.create = function (start, end, v, stops) { return new cc.LayerGradient(start, end, v, stops); }; //LayerGradient - Getter Setter -(function(){ +(function () { var proto = cc.LayerGradient.prototype; // Extended properties /** @expose */ @@ -699,4 +699,4 @@ cc.LayerMultiplex = cc.Layer.extend(/** @lends cc.LayerMultiplex# */{ */ cc.LayerMultiplex.create = function (/*Multiple Arguments*/) { return new cc.LayerMultiplex(Array.prototype.slice.call(arguments)); -}; \ No newline at end of file +}; diff --git a/cocos2d/core/layers/CCLayerCanvasRenderCmd.js b/cocos2d/core/layers/CCLayerCanvasRenderCmd.js index b646064be3..9b379ae4f9 100644 --- a/cocos2d/core/layers/CCLayerCanvasRenderCmd.js +++ b/cocos2d/core/layers/CCLayerCanvasRenderCmd.js @@ -31,7 +31,7 @@ /** * cc.Layer's rendering objects of Canvas */ -(function(){ +(function () { //Layer's canvas render command cc.Layer.CanvasRenderCmd = function(renderable){ cc.Node.CanvasRenderCmd.call(this, renderable); @@ -44,8 +44,8 @@ var proto = cc.Layer.CanvasRenderCmd.prototype = Object.create(cc.Node.CanvasRenderCmd.prototype); proto.constructor = cc.Layer.CanvasRenderCmd; - proto._setCacheDirty = function(child){ - if(child && this._updateCache === 0) + proto._setCacheDirty = function (child) { + if (child && this._updateCache === 0) this._updateCache = 2; if (this._cacheDirty === false) { this._cacheDirty = true; @@ -58,7 +58,7 @@ var flags = cc.Node._dirtyFlags, locFlag = this._dirtyFlag; if (locFlag & flags.orderDirty) { this._cacheDirty = true; - if(this._updateCache === 0) + if (this._updateCache === 0) this._updateCache = 2; this._dirtyFlag = locFlag & flags.orderDirty ^ locFlag; } @@ -71,7 +71,7 @@ // if (locFlag & flags.orderDirty) { if (this._isBaked || locFlag & flags.orderDirty) { this._cacheDirty = true; - if(this._updateCache === 0) + if (this._updateCache === 0) this._updateCache = 2; this._dirtyFlag &= ~flags.orderDirty; } @@ -81,52 +81,52 @@ 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; - cc.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.originTransform(parentCmd, recursive); + if (( wt.a !== a || wt.b !== b || wt.c !== c || wt.d !== d ) && this._updateCache === 0) this._updateCache = 2; }; - proto.bake = function(){ + 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) + if (this._updateCache === 0) this._updateCache = 2; var children = this._node._children; - for(var i = 0, len = children.length; i < len; i++) + for (var i = 0, len = children.length; i < len; i++) children[i]._renderCmd._setCachedParent(this); if (!this._bakeSprite) { this._bakeSprite = new cc.BakeSprite(); - this._bakeSprite.setAnchorPoint(0,0); + this._bakeSprite.setAnchorPoint(0, 0); } } }; - proto.unbake = function(){ + proto.unbake = function () { if (this._isBaked) { cc.renderer.childrenOrderDirty = true; this._needDraw = false; this._isBaked = false; this._cacheDirty = true; - if(this._updateCache === 0) + if (this._updateCache === 0) this._updateCache = 2; var children = this._node._children; - for(var i = 0, len = children.length; i < len; i++) + for (var i = 0, len = children.length; i < len; i++) children[i]._renderCmd._setCachedParent(null); } }; - proto.isBaked = function(){ + proto.isBaked = function () { return this._isBaked; }; - proto.rendering = function(){ - if(this._cacheDirty){ + proto.rendering = function () { + if (this._cacheDirty) { var node = this._node; var children = node._children, locBakeSprite = this._bakeSprite; @@ -134,17 +134,17 @@ this.transform(this.getParentRenderCmd(), true); var boundingBox = this._getBoundingBoxForBake(); - boundingBox.width = 0|(boundingBox.width+0.5); - boundingBox.height = 0|(boundingBox.height+0.5); + boundingBox.width = 0 | (boundingBox.width + 0.5); + boundingBox.height = 0 | (boundingBox.height + 0.5); var bakeContext = locBakeSprite.getCacheContext(); var ctx = bakeContext.getContext(); locBakeSprite.setPosition(boundingBox.x, boundingBox.y); - if(this._updateCache > 0){ + if (this._updateCache > 0) { locBakeSprite.resetCanvasSize(boundingBox.width, boundingBox.height); - bakeContext.setOffset(0 - boundingBox.x, ctx.canvas.height - boundingBox.height + boundingBox.y ); + bakeContext.setOffset(0 - boundingBox.x, ctx.canvas.height - boundingBox.height + boundingBox.y); //visit for canvas node.sortAllChildren(); cc.renderer._turnToCacheMode(this.__instanceId); @@ -180,12 +180,12 @@ this._dirtyFlag = 0; }; - proto._bakeForAddChild = function(child){ - if(child._parent === this._node && this._isBaked) + proto._bakeForAddChild = function (child) { + if (child._parent === this._node && this._isBaked) child._renderCmd._setCachedParent(this); }; - proto._getBoundingBoxForBake = function(){ + proto._getBoundingBoxForBake = function () { var rect = null, node = this._node; //query child's BoundingBox @@ -197,11 +197,11 @@ for (var i = 0, len = locChildren.length; i < len; i++) { var child = locChildren[i]; if (child && child._visible) { - if(rect){ + if (rect) { var childRect = child._getBoundingBoxToCurrentNode(trans); if (childRect) rect = cc.rectUnion(rect, childRect); - }else{ + } else { rect = child._getBoundingBoxToCurrentNode(trans); } } @@ -213,7 +213,7 @@ /** * cc.LayerColor's rendering objects of Canvas */ -(function(){ +(function () { //LayerColor's canvas render command cc.LayerColor.CanvasRenderCmd = function(renderable){ cc.Layer.CanvasRenderCmd.call(this, renderable); @@ -224,7 +224,7 @@ var proto = cc.LayerColor.CanvasRenderCmd.prototype = Object.create(cc.Layer.CanvasRenderCmd.prototype); proto.constructor = cc.LayerColor.CanvasRenderCmd; - proto.unbake = function(){ + proto.unbake = function () { cc.Layer.CanvasRenderCmd.prototype.unbake.call(this); this._needDraw = true; }; @@ -246,41 +246,41 @@ + (0 | curColor.b) + ", 1)"); //TODO: need cache the color string wrapper.setTransform(this._worldTransform, scaleX, scaleY); - context.fillRect(0, 0, locWidth , -locHeight ); + context.fillRect(0, 0, locWidth, -locHeight); cc.g_NumberOfDraws++; }; - proto.updateBlendFunc = function(blendFunc){ + proto.updateBlendFunc = function (blendFunc) { this._blendFuncStr = cc.Node.CanvasRenderCmd._getCompositeOperationByBlendFunc(blendFunc); }; proto._updateSquareVertices = proto._updateSquareVerticesWidth = - proto._updateSquareVerticesHeight = function(){}; + proto._updateSquareVerticesHeight = function () {}; - proto._bakeRendering = function(){ - if(this._cacheDirty){ + proto._bakeRendering = function () { + if (this._cacheDirty) { var node = this._node; var locBakeSprite = this._bakeSprite, children = node._children; - var len = children.length, i; + var i, len = children.length; //compute the bounding box of the bake layer. this.transform(this.getParentRenderCmd(), true); //compute the bounding box of the bake layer. var boundingBox = this._getBoundingBoxForBake(); - boundingBox.width = 0|(boundingBox.width+0.5); - boundingBox.height = 0|(boundingBox.height+0.5); + boundingBox.width = 0 | (boundingBox.width + 0.5); + boundingBox.height = 0 | (boundingBox.height + 0.5); var bakeContext = locBakeSprite.getCacheContext(); var ctx = bakeContext.getContext(); locBakeSprite.setPosition(boundingBox.x, boundingBox.y); - if(this._updateCache > 0) { + if (this._updateCache > 0) { ctx.fillStyle = bakeContext._currentFillStyle; locBakeSprite.resetCanvasSize(boundingBox.width, boundingBox.height); - bakeContext.setOffset(0 - boundingBox.x, ctx.canvas.height - boundingBox.height + boundingBox.y ); + bakeContext.setOffset(0 - boundingBox.x, ctx.canvas.height - boundingBox.height + boundingBox.y); var child; cc.renderer._turnToCacheMode(this.__instanceId); @@ -330,7 +330,7 @@ this._dirtyFlag = 0; }; - proto._getBoundingBoxForBake = function(){ + proto._getBoundingBoxForBake = function () { var node = this._node; //default size var rect = cc.rect(0, 0, node._contentSize.width, node._contentSize.height); @@ -356,8 +356,8 @@ /** * cc.LayerGradient's rendering objects of Canvas */ -(function(){ - cc.LayerGradient.CanvasRenderCmd = function(renderable){ +(function () { + cc.LayerGradient.CanvasRenderCmd = function (renderable) { cc.LayerColor.CanvasRenderCmd.call(this, renderable); this._needDraw = true; this._startPoint = cc.p(0, 0); @@ -381,12 +381,12 @@ wrapper.setGlobalAlpha(opacity); var gradient = context.createLinearGradient(this._startPoint.x, this._startPoint.y, this._endPoint.x, this._endPoint.y); - if(node._colorStops){ //Should always fall here now - for(var i=0; i < node._colorStops.length; i++) { - var stop = node._colorStops[i]; - gradient.addColorStop(stop.p, this._colorStopsStr[i]); - } - }else{ + if (node._colorStops) { //Should always fall here now + for (var i = 0; i < node._colorStops.length; i++) { + var stop = node._colorStops[i]; + gradient.addColorStop(stop.p, this._colorStopsStr[i]); + } + } else { gradient.addColorStop(0, this._startStopStr); gradient.addColorStop(1, this._endStopStr); } @@ -394,7 +394,7 @@ wrapper.setFillStyle(gradient); wrapper.setTransform(this._worldTransform, scaleX, scaleY); - context.fillRect(0, 0, locWidth , -locHeight ); + context.fillRect(0, 0, locWidth, -locHeight); cc.g_NumberOfDraws++; }; @@ -418,15 +418,15 @@ this._originSyncStatus(parentCmd); }; - proto._updateColor = function() { + proto._updateColor = function () { var node = this._node; var contentSize = node._contentSize; var tWidth = contentSize.width * 0.5, tHeight = contentSize.height * 0.5; //fix the bug of gradient layer var angle = cc.pAngleSigned(cc.p(0, -1), node._alongVector); - var p1 = cc.pRotateByAngle(cc.p(0, -1), cc.p(0,0), angle); - var factor = Math.min(Math.abs(1 / p1.x), Math.abs(1/ p1.y)); + var p1 = cc.pRotateByAngle(cc.p(0, -1), cc.p(0, 0), angle); + var factor = Math.min(Math.abs(1 / p1.x), Math.abs(1 / p1.y)); this._startPoint.x = tWidth * (-p1.x * factor) + tWidth; this._startPoint.y = tHeight * (p1.y * factor) - tHeight; @@ -434,18 +434,18 @@ this._endPoint.y = tHeight * (-p1.y * factor) - tHeight; var locStartColor = this._displayedColor, locEndColor = node._endColor; - var startOpacity = node._startOpacity/255, endOpacity = node._endOpacity/255; + var startOpacity = node._startOpacity / 255, endOpacity = node._endOpacity / 255; this._startStopStr = "rgba(" + Math.round(locStartColor.r) + "," + Math.round(locStartColor.g) + "," + Math.round(locStartColor.b) + "," + startOpacity.toFixed(4) + ")"; this._endStopStr = "rgba(" + Math.round(locEndColor.r) + "," + Math.round(locEndColor.g) + "," + Math.round(locEndColor.b) + "," + endOpacity.toFixed(4) + ")"; - if( node._colorStops){ + if (node._colorStops) { this._startOpacity = 0; this._endOpacity = 0; this._colorStopsStr = []; - for(var i =0; i < node._colorStops.length; i++){ + for (var i = 0; i < node._colorStops.length; i++) { var stopColor = node._colorStops[i].color; var stopOpacity = stopColor.a == null ? 1 : stopColor.a / 255; this._colorStopsStr.push("rgba(" + Math.round(stopColor.r) + "," + Math.round(stopColor.g) + "," diff --git a/cocos2d/core/layers/CCLayerWebGLRenderCmd.js b/cocos2d/core/layers/CCLayerWebGLRenderCmd.js index 4b644ac349..a80ed27b5a 100644 --- a/cocos2d/core/layers/CCLayerWebGLRenderCmd.js +++ b/cocos2d/core/layers/CCLayerWebGLRenderCmd.js @@ -39,11 +39,14 @@ var proto = cc.Layer.WebGLRenderCmd.prototype = Object.create(cc.Node.WebGLRenderCmd.prototype); proto.constructor = cc.Layer.WebGLRenderCmd; - proto.bake = function(){}; + proto.bake = function () { + }; - proto.unbake = function(){}; + proto.unbake = function () { + }; - proto._bakeForAddChild = function(){}; + proto._bakeForAddChild = function () { + }; })(); /** @@ -130,7 +133,7 @@ this._bindLayerVerticesBufferData(); }; - proto._updateColor = function(){ + proto._updateColor = function () { var locDisplayedColor = this._displayedColor, locDisplayedOpacity = this._displayedOpacity, locSquareColors = this._squareColors; for (var i = 0; i < 4; i++) { @@ -142,26 +145,27 @@ this._bindLayerColorsBufferData(); }; - proto._bindLayerVerticesBufferData = function(){ + proto._bindLayerVerticesBufferData = function () { var glContext = cc._renderContext; glContext.bindBuffer(glContext.ARRAY_BUFFER, this._verticesFloat32Buffer); glContext.bufferData(glContext.ARRAY_BUFFER, this._squareVerticesAB, glContext.DYNAMIC_DRAW); }; - proto._bindLayerColorsBufferData = function(){ + proto._bindLayerColorsBufferData = function () { var glContext = cc._renderContext; glContext.bindBuffer(glContext.ARRAY_BUFFER, this._colorsUint8Buffer); glContext.bufferData(glContext.ARRAY_BUFFER, this._squareColorsAB, glContext.STATIC_DRAW); }; - proto.updateBlendFunc = function(blendFunc){}; + proto.updateBlendFunc = function (blendFunc) { + }; })(); /** * cc.LayerGradient's rendering objects of WebGL */ -(function(){ - cc.LayerGradient.WebGLRenderCmd = function(renderable){ +(function () { + cc.LayerGradient.WebGLRenderCmd = function (renderable) { cc.LayerColor.WebGLRenderCmd.call(this, renderable); this._needDraw = true; this._clipRect = new cc.Rect(); @@ -199,35 +203,35 @@ proto._updateVertex = function () { var node = this._node, stops = node._colorStops; - if(!stops || stops.length < 2) + if (!stops || stops.length < 2) return; this._clippingRectDirty = true; - var stopsLen = stops.length, verticesLen = stopsLen * 2, i, contentSize = node._contentSize; + var i, stopsLen = stops.length, verticesLen = stopsLen * 2, contentSize = node._contentSize; 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++){ + for (i = 0; i < verticesLen; i++) { locVertices.push(new cc.Vertex3F(0, 0, 0, locSquareVerticesAB, locVertex3FLen * i)); } } //init vertex - var angle = Math.PI + cc.pAngleSigned(cc.p(0, -1), node._alongVector), locAnchor = cc.p(contentSize.width/2, contentSize.height /2); + var angle = Math.PI + cc.pAngleSigned(cc.p(0, -1), node._alongVector), locAnchor = cc.p(contentSize.width / 2, contentSize.height / 2); var degrees = Math.round(cc.radiansToDegrees(angle)); var transMat = cc.affineTransformMake(1, 0, 0, 1, locAnchor.x, locAnchor.y); transMat = cc.affineTransformRotate(transMat, angle); var a, b; - if(degrees < 90) { + if (degrees < 90) { a = cc.p(-locAnchor.x, locAnchor.y); b = cc.p(locAnchor.x, locAnchor.y); - } else if(degrees < 180) { + } else if (degrees < 180) { a = cc.p(locAnchor.x, locAnchor.y); b = cc.p(locAnchor.x, -locAnchor.y); - } else if(degrees < 270) { + } else if (degrees < 270) { a = cc.p(locAnchor.x, -locAnchor.y); b = cc.p(-locAnchor.x, -locAnchor.y); } else { @@ -236,11 +240,11 @@ } var sin = Math.sin(angle), cos = Math.cos(angle); - var tx = Math.abs((a.x * cos - a.y * sin)/locAnchor.x), ty = Math.abs((b.x * sin + b.y * cos)/locAnchor.y); + var tx = Math.abs((a.x * cos - a.y * sin) / locAnchor.x), ty = Math.abs((b.x * sin + b.y * cos) / locAnchor.y); transMat = cc.affineTransformScale(transMat, tx, ty); for (i = 0; i < stopsLen; i++) { - var stop = stops[i], y = stop.p * contentSize.height ; - var p0 = cc.pointApplyAffineTransform(- locAnchor.x , y - locAnchor.y, transMat); + var stop = stops[i], y = stop.p * contentSize.height; + 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; @@ -253,13 +257,13 @@ this._bindLayerVerticesBufferData(); }; - proto._updateColor = function() { + proto._updateColor = function () { var node = this._node, stops = node._colorStops; - if(!stops || stops.length < 2) + if (!stops || stops.length < 2) return; //init color - var stopsLen = stops.length; + var i, stopsLen = stops.length; var locColors = this._squareColors, verticesLen = stopsLen * 2; if (locColors.length < verticesLen) { this._squareColorsAB = new ArrayBuffer(verticesLen * 4); @@ -272,7 +276,7 @@ } var opacityf = this._displayedOpacity / 255.0; //, displayColor = this._displayedColor; - for(i = 0; i < stopsLen; i++){ + for (i = 0; i < stopsLen; i++) { var stopColor = stops[i].color, locSquareColor0 = locColors[i * 2], locSquareColor1 = locColors[i * 2 + 1]; locSquareColor0.r = stopColor.r; locSquareColor0.g = stopColor.g; @@ -322,8 +326,8 @@ context.disable(context.SCISSOR_TEST); }; - proto._getClippingRect = function(){ - if(this._clippingRectDirty){ + proto._getClippingRect = function () { + if (this._clippingRectDirty) { var node = this._node; var rect = cc.rect(0, 0, node._contentSize.width, node._contentSize.height); var trans = node.getNodeToWorldTransform(); diff --git a/cocos2d/core/platform/CCCommon.js b/cocos2d/core/platform/CCCommon.js index 0b2287a9b0..5855777eb8 100644 --- a/cocos2d/core/platform/CCCommon.js +++ b/cocos2d/core/platform/CCCommon.js @@ -42,7 +42,7 @@ cc.associateWithNative = function (jsObj, superclass) { * @constant * @type {Object} * @example - cc.eventManager.addListener({ + cc.eventManager.addListener({ event: cc.EventListener.KEYBOARD, onKeyPressed: function(keyCode, event){ if (cc.KEY["a"] == keyCode) { @@ -52,129 +52,129 @@ cc.associateWithNative = function (jsObj, superclass) { }, this); */ cc.KEY = { - none:0, + none: 0, // android - back:6, - menu:18, + back: 6, + menu: 18, - backspace:8, - tab:9, + backspace: 8, + tab: 9, - enter:13, + enter: 13, - shift:16, //should use shiftkey instead - ctrl:17, //should use ctrlkey - alt:18, //should use altkey - pause:19, - capslock:20, + shift: 16, //should use shiftkey instead + ctrl: 17, //should use ctrlkey + alt: 18, //should use altkey + pause: 19, + capslock: 20, - escape:27, - space:32, - pageup:33, - pagedown:34, - end:35, - home:36, - left:37, - up:38, - right:39, - down:40, - select:41, + escape: 27, + space: 32, + pageup: 33, + pagedown: 34, + end: 35, + home: 36, + left: 37, + up: 38, + right: 39, + down: 40, + select: 41, - insert:45, - Delete:46, - 0:48, - 1:49, - 2:50, - 3:51, - 4:52, - 5:53, - 6:54, - 7:55, - 8:56, - 9:57, - a:65, - b:66, - c:67, - d:68, - e:69, - f:70, - g:71, - h:72, - i:73, - j:74, - k:75, - l:76, - m:77, - n:78, - o:79, - p:80, - q:81, - r:82, - s:83, - t:84, - u:85, - v:86, - w:87, - x:88, - y:89, - z:90, + insert: 45, + Delete: 46, + 0: 48, + 1: 49, + 2: 50, + 3: 51, + 4: 52, + 5: 53, + 6: 54, + 7: 55, + 8: 56, + 9: 57, + a: 65, + b: 66, + c: 67, + d: 68, + e: 69, + f: 70, + g: 71, + h: 72, + i: 73, + j: 74, + k: 75, + l: 76, + m: 77, + n: 78, + o: 79, + p: 80, + q: 81, + r: 82, + s: 83, + t: 84, + u: 85, + v: 86, + w: 87, + x: 88, + y: 89, + z: 90, - num0:96, - num1:97, - num2:98, - num3:99, - num4:100, - num5:101, - num6:102, - num7:103, - num8:104, - num9:105, - '*':106, - '+':107, - '-':109, - 'numdel':110, - '/':111, - f1:112, //f1-f12 don't work on ie - f2:113, - f3:114, - f4:115, - f5:116, - f6:117, - f7:118, - f8:119, - f9:120, - f10:121, - f11:122, - f12:123, + num0: 96, + num1: 97, + num2: 98, + num3: 99, + num4: 100, + num5: 101, + num6: 102, + num7: 103, + num8: 104, + num9: 105, + '*': 106, + '+': 107, + '-': 109, + 'numdel': 110, + '/': 111, + f1: 112, //f1-f12 don't work on ie + f2: 113, + f3: 114, + f4: 115, + f5: 116, + f6: 117, + f7: 118, + f8: 119, + f9: 120, + f10: 121, + f11: 122, + f12: 123, - numlock:144, - scrolllock:145, + numlock: 144, + scrolllock: 145, - ';':186, - semicolon:186, - equal:187, - '=':187, - ',':188, - comma:188, - dash:189, - '.':190, - period:190, - forwardslash:191, - grave:192, - '[':219, - openbracket:219, - backslash:220, - ']':221, - closebracket:221, - quote:222, + ';': 186, + semicolon: 186, + equal: 187, + '=': 187, + ',': 188, + comma: 188, + dash: 189, + '.': 190, + period: 190, + forwardslash: 191, + grave: 192, + '[': 219, + openbracket: 219, + backslash: 220, + ']': 221, + closebracket: 221, + quote: 222, // gamepad control - dpadLeft:1000, - dpadRight:1001, - dpadUp:1003, - dpadDown:1004, - dpadCenter:1005 + dpadLeft: 1000, + dpadRight: 1001, + dpadUp: 1003, + dpadDown: 1004, + dpadCenter: 1005 }; /** @@ -226,7 +226,7 @@ cc.FMT_UNKNOWN = 5; * @returns {Number} */ cc.getImageFormatByData = function (imgData) { - // if it is a png file buffer. + // if it is a png file buffer. if (imgData.length > 8 && imgData[0] === 0x89 && imgData[1] === 0x50 && imgData[2] === 0x4E @@ -238,7 +238,7 @@ cc.getImageFormatByData = function (imgData) { return cc.FMT_PNG; } - // if it is a tiff file buffer. + // if it is a tiff file buffer. if (imgData.length > 2 && ((imgData[0] === 0x49 && imgData[1] === 0x49) || (imgData[0] === 0x4d && imgData[1] === 0x4d) || (imgData[0] === 0xff && imgData[1] === 0xd8))) { diff --git a/cocos2d/core/platform/CCEGLView.js b/cocos2d/core/platform/CCEGLView.js index 86b80f5444..e84433f4d7 100644 --- a/cocos2d/core/platform/CCEGLView.js +++ b/cocos2d/core/platform/CCEGLView.js @@ -36,17 +36,17 @@ cc.DENSITYDPI_MEDIUM = "medium-dpi"; cc.DENSITYDPI_LOW = "low-dpi"; var __BrowserGetter = { - init: function(){ + init: function () { this.html = document.getElementsByTagName("html")[0]; }, - availWidth: function(frame){ - if(!frame || frame === this.html) + availWidth: function (frame) { + if (!frame || frame === this.html) return window.innerWidth; else return frame.clientWidth; }, - availHeight: function(frame){ - if(!frame || frame === this.html) + availHeight: function (frame) { + if (!frame || frame === this.html) return window.innerHeight; else return frame.clientHeight; @@ -57,39 +57,39 @@ var __BrowserGetter = { adaptationType: cc.sys.browserType }; -if(window.navigator.userAgent.indexOf("OS 8_1_") > -1) //this mistake like MIUI, so use of MIUI treatment method +if (window.navigator.userAgent.indexOf("OS 8_1_") > -1) //this mistake like MIUI, so use of MIUI treatment method __BrowserGetter.adaptationType = cc.sys.BROWSER_TYPE_MIUI; -if(cc.sys.os === cc.sys.OS_IOS) // All browsers are WebView +if (cc.sys.os === cc.sys.OS_IOS) // All browsers are WebView __BrowserGetter.adaptationType = cc.sys.BROWSER_TYPE_SAFARI; -switch(__BrowserGetter.adaptationType){ +switch (__BrowserGetter.adaptationType) { case cc.sys.BROWSER_TYPE_SAFARI: __BrowserGetter.meta["minimal-ui"] = "true"; - __BrowserGetter.availWidth = function(frame){ + __BrowserGetter.availWidth = function (frame) { return frame.clientWidth; }; - __BrowserGetter.availHeight = function(frame){ + __BrowserGetter.availHeight = function (frame) { return frame.clientHeight; }; break; case cc.sys.BROWSER_TYPE_CHROME: - __BrowserGetter.__defineGetter__("target-densitydpi", function(){ + __BrowserGetter.__defineGetter__("target-densitydpi", function () { return cc.view._targetDensityDPI; }); case cc.sys.BROWSER_TYPE_SOUGOU: case cc.sys.BROWSER_TYPE_UC: - __BrowserGetter.availWidth = function(frame){ + __BrowserGetter.availWidth = function (frame) { return frame.clientWidth; }; - __BrowserGetter.availHeight = function(frame){ + __BrowserGetter.availHeight = function (frame) { return frame.clientHeight; }; break; case cc.sys.BROWSER_TYPE_MIUI: - __BrowserGetter.init = function(view){ - if(view.__resizeWithBrowserSize) return; - var resize = function(){ + __BrowserGetter.init = function (view) { + if (view.__resizeWithBrowserSize) return; + var resize = function () { view.setDesignResolutionSize( view._designResolutionSize.width, view._designResolutionSize.height, @@ -244,7 +244,7 @@ cc.EGLView = cc.Class.extend(/** @lends cc.view# */{ *

* @param {String} densityDPI */ - setTargetDensityDPI: function(densityDPI){ + setTargetDensityDPI: function (densityDPI) { this._targetDensityDPI = densityDPI; this._adjustViewportMeta(); }, @@ -253,7 +253,7 @@ cc.EGLView = cc.Class.extend(/** @lends cc.view# */{ * Returns the current target-densitydpi value of cc.view. * @returns {String} */ - getTargetDensityDPI: function(){ + getTargetDensityDPI: function () { return this._targetDensityDPI; }, @@ -295,9 +295,9 @@ cc.EGLView = cc.Class.extend(/** @lends cc.view# */{ /** * Sets the orientation of the game, it can be landscape, portrait or auto. - * When set it to landscape or portrait, and screen w/h ratio doesn't fit, + * When set it to landscape or portrait, and screen w/h ratio doesn't fit, * cc.view will automatically rotate the game canvas using CSS. - * Note that this function doesn't have any effect in native, + * Note that this function doesn't have any effect in native, * in native, you need to set the application orientation in native project settings * @param {Number} orientation - Possible values: cc.ORIENTATION_LANDSCAPE | cc.ORIENTATION_PORTRAIT | cc.ORIENTATION_AUTO */ @@ -330,7 +330,7 @@ cc.EGLView = cc.Class.extend(/** @lends cc.view# */{ var isLandscape = w >= h; if (!this._orientationChanging || !cc.sys.isMobile || - (isLandscape && this._orientation & cc.ORIENTATION_LANDSCAPE) || + (isLandscape && this._orientation & cc.ORIENTATION_LANDSCAPE) || (!isLandscape && this._orientation & cc.ORIENTATION_PORTRAIT)) { locFrameSize.width = w; locFrameSize.height = h; @@ -362,7 +362,7 @@ cc.EGLView = cc.Class.extend(/** @lends cc.view# */{ _setViewportMeta: function (metas, overwrite) { var vp = document.getElementById("cocosMetaElement"); - if(vp && overwrite){ + if (vp && overwrite) { document.head.removeChild(vp); } @@ -381,11 +381,11 @@ cc.EGLView = cc.Class.extend(/** @lends cc.view# */{ content += "," + key + "=" + metas[key]; } else if (overwrite) { - pattern = new RegExp(key+"\s*=\s*[^,]+"); + pattern = new RegExp(key + "\s*=\s*[^,]+"); content.replace(pattern, key + "=" + metas[key]); } } - if(/^,/.test(content)) + if (/^,/.test(content)) content = content.substr(1); vp.content = content; @@ -443,7 +443,7 @@ cc.EGLView = cc.Class.extend(/** @lends cc.view# */{ * Only useful on web * @param {Boolean} enabled Enable or disable retina display */ - enableRetina: function(enabled) { + enableRetina: function (enabled) { this._retinaEnabled = !!enabled; }, @@ -452,7 +452,7 @@ cc.EGLView = cc.Class.extend(/** @lends cc.view# */{ * Only useful on web * @return {Boolean} */ - isRetinaEnabled: function() { + isRetinaEnabled: function () { return this._retinaEnabled; }, @@ -462,7 +462,7 @@ cc.EGLView = cc.Class.extend(/** @lends cc.view# */{ * Only useful on web * @param {Boolean} enabled Enable or disable auto full screen on mobile devices */ - enableAutoFullScreen: function(enabled) { + enableAutoFullScreen: function (enabled) { if (enabled && enabled !== this._autoFullScreen && cc.sys.isMobile && this._frame === document.documentElement) { // Automatically full screen when user touches on mobile version this._autoFullScreen = true; @@ -478,7 +478,7 @@ cc.EGLView = cc.Class.extend(/** @lends cc.view# */{ * Only useful on web * @return {Boolean} Auto full screen enabled or not */ - isAutoFullScreenEnabled: function() { + isAutoFullScreenEnabled: function () { return this._autoFullScreen; }, @@ -584,7 +584,7 @@ cc.EGLView = cc.Class.extend(/** @lends cc.view# */{ * @return {cc.Size} */ getVisibleSize: function () { - return cc.size(this._visibleRect.width,this._visibleRect.height); + return cc.size(this._visibleRect.width, this._visibleRect.height); }, /** @@ -601,7 +601,7 @@ cc.EGLView = cc.Class.extend(/** @lends cc.view# */{ * @return {cc.Point} */ getVisibleOrigin: function () { - return cc.p(this._visibleRect.x,this._visibleRect.y); + return cc.p(this._visibleRect.x, this._visibleRect.y); }, /** @@ -643,15 +643,15 @@ cc.EGLView = cc.Class.extend(/** @lends cc.view# */{ // Ensure compatibility with JSB else { var _locPolicy = cc.ResolutionPolicy; - if(resolutionPolicy === _locPolicy.EXACT_FIT) + if (resolutionPolicy === _locPolicy.EXACT_FIT) _t._resolutionPolicy = _t._rpExactFit; - if(resolutionPolicy === _locPolicy.SHOW_ALL) + if (resolutionPolicy === _locPolicy.SHOW_ALL) _t._resolutionPolicy = _t._rpShowAll; - if(resolutionPolicy === _locPolicy.NO_BORDER) + if (resolutionPolicy === _locPolicy.NO_BORDER) _t._resolutionPolicy = _t._rpNoBorder; - if(resolutionPolicy === _locPolicy.FIXED_HEIGHT) + if (resolutionPolicy === _locPolicy.FIXED_HEIGHT) _t._resolutionPolicy = _t._rpFixedHeight; - if(resolutionPolicy === _locPolicy.FIXED_WIDTH) + if (resolutionPolicy === _locPolicy.FIXED_WIDTH) _t._resolutionPolicy = _t._rpFixedWidth; } }, @@ -671,7 +671,7 @@ cc.EGLView = cc.Class.extend(/** @lends cc.view# */{ */ setDesignResolutionSize: function (width, height, resolutionPolicy) { // Defensive code - if( !(width > 0 || height > 0) ){ + if (!(width > 0 || height > 0)) { cc.log(cc._LogInfos.EGLView_setDesignResolutionSize); return; } @@ -685,7 +685,7 @@ cc.EGLView = cc.Class.extend(/** @lends cc.view# */{ policy.preApply(this); // Reinit frame size - if(cc.sys.isMobile) + if (cc.sys.isMobile) this._adjustViewportMeta(); // Permit to re-detect the orientation of device. @@ -697,12 +697,12 @@ cc.EGLView = cc.Class.extend(/** @lends cc.view# */{ var result = policy.apply(this, this._designResolutionSize); - if(result.scale && result.scale.length === 2){ + if (result.scale && result.scale.length === 2) { this._scaleX = result.scale[0]; this._scaleY = result.scale[1]; } - if(result.viewport){ + if (result.viewport) { var vp = this._viewPortRect, vb = this._visibleRect, rv = result.viewport; @@ -871,7 +871,7 @@ cc.EGLView = cc.Class.extend(/** @lends cc.view# */{ * Returns device pixel ratio for retina display. * @return {Number} */ - getDevicePixelRatio: function() { + getDevicePixelRatio: function () { return this._devicePixelRatio; }, @@ -903,7 +903,7 @@ cc.EGLView = cc.Class.extend(/** @lends cc.view# */{ _convertTouchesWithScale: function (touches) { var viewport = this._viewPortRect, scaleX = this._scaleX, scaleY = this._scaleY, selTouch, selPoint, selPrePoint; - for( var i = 0; i < touches.length; i++){ + for (var i = 0; i < touches.length; i++) { selTouch = touches[i]; selPoint = selTouch._point; selPrePoint = selTouch._prevPoint; @@ -1021,7 +1021,7 @@ cc.ContentStrategy = cc.Class.extend(/** @lends cc.ContentStrategy# */{ contentW, contentH); // Translate the content - if (cc._renderType === cc.game.RENDER_TYPE_CANVAS){ + if (cc._renderType === cc.game.RENDER_TYPE_CANVAS) { //TODO: modify something for setTransform //cc._renderContext.translate(viewport.x, viewport.y + contentH); } diff --git a/cocos2d/core/platform/CCInputManager.js b/cocos2d/core/platform/CCInputManager.js index 11230c464a..382b1f86ed 100644 --- a/cocos2d/core/platform/CCInputManager.js +++ b/cocos2d/core/platform/CCInputManager.js @@ -62,20 +62,20 @@ cc.inputManager = /** @lends cc.inputManager# */{ _isRegisterEvent: false, - _preTouchPoint: cc.p(0,0), - _prevMousePoint: cc.p(0,0), + _preTouchPoint: cc.p(0, 0), + _prevMousePoint: cc.p(0, 0), _preTouchPool: [], _preTouchPoolPointer: 0, _touches: [], - _touchesIntegerDict:{}, + _touchesIntegerDict: {}, _indexBitsUsed: 0, _maxTouches: 5, _accelEnabled: false, - _accelInterval: 1/30, + _accelInterval: 1 / 30, _accelMinus: 1, _accelCurTime: 0, _acceleration: null, @@ -121,15 +121,15 @@ cc.inputManager = /** @lends cc.inputManager# */{ * @param {Array} touches */ handleTouchesBegin: function (touches) { - var selTouch, index, curTouch, touchID, + var selTouch, index, curTouch, touchID, handleTouches = [], locTouchIntDict = this._touchesIntegerDict, now = cc.sys.now(); - for(var i = 0, len = touches.length; i< len; i ++){ + for (var i = 0, len = touches.length; i < len; i++) { selTouch = touches[i]; touchID = selTouch.getID(); index = locTouchIntDict[touchID]; - if(index == null){ + if (index == null) { var unusedIndex = this._getUnUsedIndex(); if (unusedIndex === -1) { cc.log(cc._LogInfos.inputManager_handleTouchesBegin, unusedIndex); @@ -143,7 +143,7 @@ cc.inputManager = /** @lends cc.inputManager# */{ handleTouches.push(curTouch); } } - if(handleTouches.length > 0){ + if (handleTouches.length > 0) { this._glView._convertTouchesWithScale(handleTouches); var touchEvent = new cc.EventTouch(handleTouches); touchEvent._eventCode = cc.EventTouch.EventCode.BEGAN; @@ -155,27 +155,27 @@ cc.inputManager = /** @lends cc.inputManager# */{ * @function * @param {Array} touches */ - handleTouchesMove: function(touches){ - var selTouch, index, touchID, + handleTouchesMove: function (touches) { + var selTouch, index, touchID, handleTouches = [], locTouches = this._touches, now = cc.sys.now(); - for(var i = 0, len = touches.length; i< len; i ++){ + for (var i = 0, len = touches.length; i < len; i++) { selTouch = touches[i]; touchID = selTouch.getID(); index = this._touchesIntegerDict[touchID]; - if(index == null){ + if (index == null) { //cc.log("if the index doesn't exist, it is an error"); continue; } - if(locTouches[index]){ + if (locTouches[index]) { locTouches[index]._setPoint(selTouch._point); locTouches[index]._setPrevPoint(selTouch._prevPoint); locTouches[index]._lastModified = now; handleTouches.push(locTouches[index]); } } - if(handleTouches.length > 0){ + if (handleTouches.length > 0) { this._glView._convertTouchesWithScale(handleTouches); var touchEvent = new cc.EventTouch(handleTouches); touchEvent._eventCode = cc.EventTouch.EventCode.MOVED; @@ -187,9 +187,9 @@ cc.inputManager = /** @lends cc.inputManager# */{ * @function * @param {Array} touches */ - handleTouchesEnd: function(touches){ + handleTouchesEnd: function (touches) { var handleTouches = this.getSetOfTouchesEndOrCancel(touches); - if(handleTouches.length > 0) { + if (handleTouches.length > 0) { this._glView._convertTouchesWithScale(handleTouches); var touchEvent = new cc.EventTouch(handleTouches); touchEvent._eventCode = cc.EventTouch.EventCode.ENDED; @@ -201,9 +201,9 @@ cc.inputManager = /** @lends cc.inputManager# */{ * @function * @param {Array} touches */ - handleTouchesCancel: function(touches){ + handleTouchesCancel: function (touches) { var handleTouches = this.getSetOfTouchesEndOrCancel(touches); - if(handleTouches.length > 0) { + if (handleTouches.length > 0) { this._glView._convertTouchesWithScale(handleTouches); var touchEvent = new cc.EventTouch(handleTouches); touchEvent._eventCode = cc.EventTouch.EventCode.CANCELLED; @@ -216,17 +216,17 @@ cc.inputManager = /** @lends cc.inputManager# */{ * @param {Array} touches * @returns {Array} */ - getSetOfTouchesEndOrCancel: function(touches) { + getSetOfTouchesEndOrCancel: function (touches) { var selTouch, index, touchID, handleTouches = [], locTouches = this._touches, locTouchesIntDict = this._touchesIntegerDict; - for(var i = 0, len = touches.length; i< len; i ++){ + for (var i = 0, len = touches.length; i < len; i++) { selTouch = touches[i]; touchID = selTouch.getID(); index = locTouchesIntDict[touchID]; - if(index == null){ + if (index == null) { continue; //cc.log("if the index doesn't exist, it is an error"); } - if(locTouches[index]){ + if (locTouches[index]) { locTouches[index]._setPoint(selTouch._point); locTouches[index]._setPrevPoint(selTouch._prevPoint); handleTouches.push(locTouches[index]); @@ -269,7 +269,7 @@ cc.inputManager = /** @lends cc.inputManager# */{ * @param {cc.Touch} touch * @return {cc.Touch} */ - getPreTouch: function(touch){ + getPreTouch: function (touch) { var preTouch = null; var locPreTouchPool = this._preTouchPool; var id = touch.getID(); @@ -288,7 +288,7 @@ cc.inputManager = /** @lends cc.inputManager# */{ * @function * @param {cc.Touch} touch */ - setPreTouch: function(touch){ + setPreTouch: function (touch) { var find = false; var locPreTouchPool = this._preTouchPool; var id = touch.getID(); @@ -316,10 +316,10 @@ cc.inputManager = /** @lends cc.inputManager# */{ * @param {cc.Point} pos * @return {cc.Touch} */ - getTouchByXY: function(tx, ty, pos){ + getTouchByXY: function (tx, ty, pos) { var locPreTouch = this._preTouchPoint; var location = this._glView.convertToLocationInView(tx, ty, pos); - var touch = new cc.Touch(location.x, location.y); + var touch = new cc.Touch(location.x, location.y); touch._setPrevPoint(locPreTouch.x, locPreTouch.y); locPreTouch.x = location.x; locPreTouch.y = location.y; @@ -333,7 +333,7 @@ cc.inputManager = /** @lends cc.inputManager# */{ * @param {Number} eventType * @returns {cc.EventMouse} */ - getMouseEvent: function(location, pos, eventType){ + getMouseEvent: function (location, pos, eventType) { var locPreMouse = this._prevMousePoint; this._glView._convertMouseToLocationInView(location, pos); var mouseEvent = new cc.EventMouse(eventType); @@ -350,7 +350,7 @@ cc.inputManager = /** @lends cc.inputManager# */{ * @param {cc.Point} pos * @return {cc.Point} */ - getPointByEvent: function(event, pos){ + getPointByEvent: function (event, pos) { if (event.pageX != null) //not available in <= IE8 return {x: event.pageX, y: event.pageY}; @@ -365,7 +365,7 @@ cc.inputManager = /** @lends cc.inputManager# */{ * @param {cc.Point} pos * @returns {Array} */ - getTouchesByEvent: function(event, pos){ + getTouchesByEvent: function (event, pos) { var touchArr = [], locView = this._glView; var touch_event, touch, preLocation; var locPreTouch = this._preTouchPoint; @@ -401,8 +401,8 @@ cc.inputManager = /** @lends cc.inputManager# */{ * @function * @param {HTMLElement} element */ - registerSystemEvent: function(element){ - if(this._isRegisterEvent) return; + registerSystemEvent: function (element) { + if (this._isRegisterEvent) return; var locView = this._glView = cc.view; var selfPointer = this; @@ -416,7 +416,7 @@ cc.inputManager = /** @lends cc.inputManager# */{ // miui // WECHAT var prohibition = false; - if( cc.sys.isMobile) + if (cc.sys.isMobile) prohibition = true; //register touch event @@ -426,19 +426,19 @@ cc.inputManager = /** @lends cc.inputManager# */{ }, false); window.addEventListener('mouseup', function (event) { - if(prohibition) return; + if (prohibition) return; var savePressed = selfPointer._mousePressed; selfPointer._mousePressed = false; - if(!savePressed) + if (!savePressed) return; var pos = selfPointer.getHTMLElementPosition(element); var location = selfPointer.getPointByEvent(event, pos); - if (!cc.rectContainsPoint(new cc.Rect(pos.left, pos.top, pos.width, pos.height), location)){ + if (!cc.rectContainsPoint(new cc.Rect(pos.left, pos.top, pos.width, pos.height), location)) { selfPointer.handleTouchesEnd([selfPointer.getTouchByXY(location.x, location.y, pos)]); - var mouseEvent = selfPointer.getMouseEvent(location,pos,cc.EventMouse.UP); + var mouseEvent = selfPointer.getMouseEvent(location, pos, cc.EventMouse.UP); mouseEvent.setButton(event.button); cc.eventManager.dispatchEvent(mouseEvent); } @@ -446,7 +446,7 @@ cc.inputManager = /** @lends cc.inputManager# */{ //register canvas mouse event element.addEventListener("mousedown", function (event) { - if(prohibition) return; + if (prohibition) return; selfPointer._mousePressed = true; var pos = selfPointer.getHTMLElementPosition(element); @@ -454,7 +454,7 @@ cc.inputManager = /** @lends cc.inputManager# */{ selfPointer.handleTouchesBegin([selfPointer.getTouchByXY(location.x, location.y, pos)]); - var mouseEvent = selfPointer.getMouseEvent(location,pos,cc.EventMouse.DOWN); + var mouseEvent = selfPointer.getMouseEvent(location, pos, cc.EventMouse.DOWN); mouseEvent.setButton(event.button); cc.eventManager.dispatchEvent(mouseEvent); @@ -464,7 +464,7 @@ cc.inputManager = /** @lends cc.inputManager# */{ }, false); element.addEventListener("mouseup", function (event) { - if(prohibition) return; + if (prohibition) return; selfPointer._mousePressed = false; var pos = selfPointer.getHTMLElementPosition(element); @@ -472,7 +472,7 @@ cc.inputManager = /** @lends cc.inputManager# */{ selfPointer.handleTouchesEnd([selfPointer.getTouchByXY(location.x, location.y, pos)]); - var mouseEvent = selfPointer.getMouseEvent(location,pos,cc.EventMouse.UP); + var mouseEvent = selfPointer.getMouseEvent(location, pos, cc.EventMouse.UP); mouseEvent.setButton(event.button); cc.eventManager.dispatchEvent(mouseEvent); @@ -481,15 +481,15 @@ cc.inputManager = /** @lends cc.inputManager# */{ }, false); element.addEventListener("mousemove", function (event) { - if(prohibition) return; + if (prohibition) return; var pos = selfPointer.getHTMLElementPosition(element); var location = selfPointer.getPointByEvent(event, pos); selfPointer.handleTouchesMove([selfPointer.getTouchByXY(location.x, location.y, pos)]); - var mouseEvent = selfPointer.getMouseEvent(location,pos,cc.EventMouse.MOVE); - if(selfPointer._mousePressed) + var mouseEvent = selfPointer.getMouseEvent(location, pos, cc.EventMouse.MOVE); + if (selfPointer._mousePressed) mouseEvent.setButton(event.button); else mouseEvent.setButton(null); @@ -503,7 +503,7 @@ cc.inputManager = /** @lends cc.inputManager# */{ var pos = selfPointer.getHTMLElementPosition(element); var location = selfPointer.getPointByEvent(event, pos); - var mouseEvent = selfPointer.getMouseEvent(location,pos,cc.EventMouse.SCROLL); + var mouseEvent = selfPointer.getMouseEvent(location, pos, cc.EventMouse.SCROLL); mouseEvent.setButton(event.button); mouseEvent.setScrollData(0, event.wheelDelta); cc.eventManager.dispatchEvent(mouseEvent); @@ -513,11 +513,11 @@ cc.inputManager = /** @lends cc.inputManager# */{ }, false); /* firefox fix */ - element.addEventListener("DOMMouseScroll", function(event) { + element.addEventListener("DOMMouseScroll", function (event) { var pos = selfPointer.getHTMLElementPosition(element); var location = selfPointer.getPointByEvent(event, pos); - var mouseEvent = selfPointer.getMouseEvent(location,pos,cc.EventMouse.SCROLL); + var mouseEvent = selfPointer.getMouseEvent(location, pos, cc.EventMouse.SCROLL); mouseEvent.setButton(event.button); mouseEvent.setScrollData(0, event.detail * -120); cc.eventManager.dispatchEvent(mouseEvent); @@ -527,17 +527,17 @@ cc.inputManager = /** @lends cc.inputManager# */{ }, false); } - if(window.navigator.msPointerEnabled){ + if (window.navigator.msPointerEnabled) { var _pointerEventsMap = { - "MSPointerDown" : selfPointer.handleTouchesBegin, - "MSPointerMove" : selfPointer.handleTouchesMove, - "MSPointerUp" : selfPointer.handleTouchesEnd, - "MSPointerCancel" : selfPointer.handleTouchesCancel + "MSPointerDown": selfPointer.handleTouchesBegin, + "MSPointerMove": selfPointer.handleTouchesMove, + "MSPointerUp": selfPointer.handleTouchesEnd, + "MSPointerCancel": selfPointer.handleTouchesCancel }; - for(var eventName in _pointerEventsMap){ - (function(_pointerEvent, _touchEvent){ - element.addEventListener(_pointerEvent, function (event){ + for (var eventName in _pointerEventsMap) { + (function (_pointerEvent, _touchEvent) { + element.addEventListener(_pointerEvent, function (event) { var pos = selfPointer.getHTMLElementPosition(element); pos.left -= document.documentElement.scrollLeft; pos.top -= document.documentElement.scrollTop; @@ -549,7 +549,7 @@ cc.inputManager = /** @lends cc.inputManager# */{ } } - if(supportTouches) { + if (supportTouches) { //register canvas touch event element.addEventListener("touchstart", function (event) { if (!event.changedTouches) return; @@ -606,16 +606,18 @@ cc.inputManager = /** @lends cc.inputManager# */{ this._isRegisterEvent = true; }, - _registerKeyboardEvent: function(){}, + _registerKeyboardEvent: function () { + }, - _registerAccelerometerEvent: function(){}, + _registerAccelerometerEvent: function () { + }, /** * @function * @param {Number} dt */ - update:function(dt){ - if(this._accelCurTime > this._accelInterval){ + update: function (dt) { + if (this._accelCurTime > this._accelInterval) { this._accelCurTime -= this._accelInterval; cc.eventManager.dispatchEvent(new cc.EventAcceleration(this._acceleration)); } diff --git a/cocos2d/core/platform/CCLoaders.js b/cocos2d/core/platform/CCLoaders.js index 9d1f44041d..69c8e9430f 100644 --- a/cocos2d/core/platform/CCLoaders.js +++ b/cocos2d/core/platform/CCLoaders.js @@ -24,35 +24,35 @@ ****************************************************************************/ cc._txtLoader = { - load : function(realUrl, url, res, cb){ + load: function (realUrl, url, res, cb) { cc.loader.loadTxt(realUrl, cb); } }; cc.loader.register(["txt", "xml", "vsh", "fsh", "atlas"], cc._txtLoader); cc._jsonLoader = { - load : function(realUrl, url, res, cb){ + load: function (realUrl, url, res, cb) { cc.loader.loadJson(realUrl, cb); } }; cc.loader.register(["json", "ExportJson"], cc._jsonLoader); cc._jsLoader = { - load : function(realUrl, url, res, cb){ + load: function (realUrl, url, res, cb) { cc.loader.loadJs(realUrl, cb); } }; cc.loader.register(["js"], cc._jsLoader); cc._imgLoader = { - load : function(realUrl, url, res, cb){ + load: function (realUrl, url, res, cb) { var callback; if (cc.loader.isLoading(realUrl)) { callback = cb; } else { - callback = function(err, img){ - if(err) + callback = function (err, img) { + if (err) return cb(err); cc.loader.cache[url] = img; cc.textureCache.handleLoadedTexture(url); @@ -62,18 +62,18 @@ cc._imgLoader = { cc.loader.loadImg(realUrl, callback); } }; -cc.loader.register(["png", "jpg", "bmp","jpeg","gif", "ico", "tiff", "webp"], cc._imgLoader); +cc.loader.register(["png", "jpg", "bmp", "jpeg", "gif", "ico", "tiff", "webp"], cc._imgLoader); cc._serverImgLoader = { - load : function(realUrl, url, res, cb){ + load: function (realUrl, url, res, cb) { cc._imgLoader.load(res.src, url, res, cb); } }; cc.loader.register(["serverImg"], cc._serverImgLoader); cc._plistLoader = { - load : function(realUrl, url, res, cb){ - cc.loader.loadTxt(realUrl, function(err, txt){ - if(err) + load: function (realUrl, url, res, cb) { + cc.loader.loadTxt(realUrl, function (err, txt) { + if (err) return cb(err); cb(null, cc.plistParser.parse(txt)); }); @@ -82,31 +82,31 @@ cc._plistLoader = { cc.loader.register(["plist"], cc._plistLoader); cc._fontLoader = { - TYPE : { - ".eot" : "embedded-opentype", - ".ttf" : "truetype", - ".ttc" : "truetype", - ".woff" : "woff", - ".svg" : "svg" + TYPE: { + ".eot": "embedded-opentype", + ".ttf": "truetype", + ".ttc": "truetype", + ".woff": "woff", + ".svg": "svg" }, - _loadFont : function(name, srcs, type){ + _loadFont: function (name, srcs, type) { var doc = document, path = cc.path, TYPE = this.TYPE, fontStyle = document.createElement("style"); fontStyle.type = "text/css"; doc.body.appendChild(fontStyle); var fontStr = ""; - if(isNaN(name - 0)) + if (isNaN(name - 0)) fontStr += "@font-face { font-family:" + name + "; src:"; else fontStr += "@font-face { font-family:'" + name + "'; src:"; - if(srcs instanceof Array){ - for(var i = 0, li = srcs.length; i < li; i++){ + if (srcs instanceof Array) { + for (var i = 0, li = srcs.length; i < li; i++) { var src = srcs[i]; type = path.extname(src).toLowerCase(); fontStr += "url('" + srcs[i] + "') format('" + TYPE[type] + "')"; fontStr += (i === li - 1) ? ";" : ","; } - }else{ + } else { type = type.toLowerCase(); fontStr += "url('" + srcs + "') format('" + TYPE[type] + "');"; } @@ -114,7 +114,7 @@ cc._fontLoader = { //
.
var preloadDiv = document.createElement("div"); - var _divStyle = preloadDiv.style; + var _divStyle = preloadDiv.style; _divStyle.fontFamily = name; preloadDiv.innerHTML = "."; _divStyle.position = "absolute"; @@ -122,23 +122,23 @@ cc._fontLoader = { _divStyle.top = "-100px"; doc.body.appendChild(preloadDiv); }, - load : function(realUrl, url, res, cb){ + load: function (realUrl, url, res, cb) { var self = this; var type = res.type, name = res.name, srcs = res.srcs; - if(cc.isString(res)){ + if (cc.isString(res)) { type = cc.path.extname(res); name = cc.path.basename(res, type); self._loadFont(name, res, type); - }else{ + } else { self._loadFont(name, srcs); } - if(document.fonts){ - document.fonts.load("1em " + name).then(function(){ + if (document.fonts) { + document.fonts.load("1em " + name).then(function () { cb(null, true); - }, function(err){ + }, function (err) { cb(err); }); - }else{ + } else { cb(null, true); } } @@ -146,7 +146,7 @@ cc._fontLoader = { cc.loader.register(["font", "eot", "ttf", "woff", "svg", "ttc"], cc._fontLoader); cc._binaryLoader = { - load : function(realUrl, url, res, cb){ + load: function (realUrl, url, res, cb) { cc.loader.loadBinary(realUrl, cb); } }; diff --git a/cocos2d/core/platform/CCTypes.js b/cocos2d/core/platform/CCTypes.js index c9d91a6dce..2e54cfe2d4 100644 --- a/cocos2d/core/platform/CCTypes.js +++ b/cocos2d/core/platform/CCTypes.js @@ -63,12 +63,12 @@ cc.Color = function (r, g, b, a) { */ cc.color = function (r, g, b, a) { if (r === undefined) - return {r: 0, g: 0, b: 0, a: 255}; + return new cc.Color(0, 0, 0, 255); if (typeof r === 'object') - return {r: r.r, g: r.g, b: r.b, a: (r.a == null) ? 255 : r.a}; + return new cc.Color(r.r, r.g, r.b, (r.a == null) ? 255 : r.a); if (typeof r === 'string') return cc.hexToColor(r); - return {r: r, g: g, b: b, a: (a == null ? 255 : a)}; + return new cc.Color(r, g, b, (a == null ? 255 : a)); }; /** @@ -280,7 +280,7 @@ _p._setTR = function (trValue) { this._tr._view[0] = trValue.x; this._tr._view[1] = trValue.y; }; -_p._getBL = function() { +_p._getBL = function () { return this._bl; }; _p._setBL = function (blValue) { @@ -508,23 +508,31 @@ cc.V3F_C4B_T2F_QuadZero = function () { */ cc.V3F_C4B_T2F_QuadCopy = function (sourceQuad) { if (!sourceQuad) - return cc.V3F_C4B_T2F_QuadZero(); + return cc.V3F_C4B_T2F_QuadZero(); //return new cc.V3F_C4B_T2F_Quad(sourceQuad,tl,sourceQuad,bl,sourceQuad.tr,sourceQuad.br,null,0); var srcTL = sourceQuad.tl, srcBL = sourceQuad.bl, srcTR = sourceQuad.tr, srcBR = sourceQuad.br; return { - tl: {vertices: {x: srcTL.vertices.x, y: srcTL.vertices.y, z: srcTL.vertices.z}, + tl: { + vertices: {x: srcTL.vertices.x, y: srcTL.vertices.y, z: srcTL.vertices.z}, colors: {r: srcTL.colors.r, g: srcTL.colors.g, b: srcTL.colors.b, a: srcTL.colors.a}, - texCoords: {u: srcTL.texCoords.u, v: srcTL.texCoords.v}}, - bl: {vertices: {x: srcBL.vertices.x, y: srcBL.vertices.y, z: srcBL.vertices.z}, + texCoords: {u: srcTL.texCoords.u, v: srcTL.texCoords.v} + }, + bl: { + vertices: {x: srcBL.vertices.x, y: srcBL.vertices.y, z: srcBL.vertices.z}, colors: {r: srcBL.colors.r, g: srcBL.colors.g, b: srcBL.colors.b, a: srcBL.colors.a}, - texCoords: {u: srcBL.texCoords.u, v: srcBL.texCoords.v}}, - tr: {vertices: {x: srcTR.vertices.x, y: srcTR.vertices.y, z: srcTR.vertices.z}, + texCoords: {u: srcBL.texCoords.u, v: srcBL.texCoords.v} + }, + tr: { + vertices: {x: srcTR.vertices.x, y: srcTR.vertices.y, z: srcTR.vertices.z}, colors: {r: srcTR.colors.r, g: srcTR.colors.g, b: srcTR.colors.b, a: srcTR.colors.a}, - texCoords: {u: srcTR.texCoords.u, v: srcTR.texCoords.v}}, - br: {vertices: {x: srcBR.vertices.x, y: srcBR.vertices.y, z: srcBR.vertices.z}, + texCoords: {u: srcTR.texCoords.u, v: srcTR.texCoords.v} + }, + br: { + vertices: {x: srcBR.vertices.x, y: srcBR.vertices.y, z: srcBR.vertices.z}, colors: {r: srcBR.colors.r, g: srcBR.colors.g, b: srcBR.colors.b, a: srcBR.colors.a}, - texCoords: {u: srcBR.texCoords.u, v: srcBR.texCoords.v}} + texCoords: {u: srcBR.texCoords.u, v: srcBR.texCoords.v} + } }; }; @@ -927,18 +935,18 @@ cc.FontDefinition = function (properties) { _t.shadowOpacity = 1.0; //properties mapping: - if(properties && properties instanceof Object){ - for(var key in properties){ - _t[key] = properties[key]; - } + if (properties && properties instanceof Object) { + for (var key in properties) { + _t[key] = properties[key]; + } } }; /** * Web ONLY * */ -cc.FontDefinition.prototype._getCanvasFontStr = function(){ - var lineHeight = !this.lineHeight.charAt ? this.lineHeight+"px" : this.lineHeight; - return this.fontStyle + " " + this.fontWeight + " " + this.fontSize + "px/"+lineHeight+" '" + this.fontName + "'"; +cc.FontDefinition.prototype._getCanvasFontStr = function () { + var lineHeight = !this.lineHeight.charAt ? this.lineHeight + "px" : this.lineHeight; + return this.fontStyle + " " + this.fontWeight + " " + this.fontSize + "px/" + lineHeight + " '" + this.fontName + "'"; }; cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () { diff --git a/cocos2d/core/renderer/RendererCanvas.js b/cocos2d/core/renderer/RendererCanvas.js index 1fb7c09f6f..65d2a8835c 100644 --- a/cocos2d/core/renderer/RendererCanvas.js +++ b/cocos2d/core/renderer/RendererCanvas.js @@ -213,7 +213,7 @@ cc.rendererCanvas = { scaleX = cc.isUndefined(scaleX) ? 1 : scaleX; scaleY = cc.isUndefined(scaleY) ? 1 : scaleY; instanceID = instanceID || this._currentID; - var locCmds = this._cacheToCanvasCmds[instanceID], i, len; + var i, locCmds = this._cacheToCanvasCmds[instanceID], len; ctx.computeRealOffsetY(); for (i = 0, len = locCmds.length; i < len; i++) { locCmds[i].rendering(ctx, scaleX, scaleY); diff --git a/cocos2d/core/renderer/RendererWebGL.js b/cocos2d/core/renderer/RendererWebGL.js index e662f63576..60debaf811 100644 --- a/cocos2d/core/renderer/RendererWebGL.js +++ b/cocos2d/core/renderer/RendererWebGL.js @@ -108,7 +108,7 @@ return { childrenOrderDirty: true, assignedZ: 0, - assignedZStep: 1/100, + assignedZStep: 1 / 100, _transformNodePool: [], //save nodes transform dirty _renderCmds: [], //save renderer commands @@ -236,20 +236,20 @@ return { gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); }, - setDepthTest: function (enable){ + setDepthTest: function (enable) { var gl = cc._renderContext; - if(enable){ + if (enable) { gl.clearDepth(1.0); gl.enable(gl.DEPTH_TEST); gl.depthFunc(gl.LEQUAL); } - else{ + else { gl.disable(gl.DEPTH_TEST); } }, pushRenderCommand: function (cmd) { - if(!cmd.needDraw()) + if (!cmd.needDraw()) return; if (this._isCacheToBufferOn) { var currentId = this._currentID, locCmdBuffer = this._cacheToBufferCmds; diff --git a/cocos2d/core/sprites/CCSprite.js b/cocos2d/core/sprites/CCSprite.js index 034367bfd9..5e9600a925 100644 --- a/cocos2d/core/sprites/CCSprite.js +++ b/cocos2d/core/sprites/CCSprite.js @@ -84,41 +84,41 @@ * @property {cc.V3F_C4B_T2F_Quad} quad - <@readonly> The quad (tex coords, vertex coords and color) information. */ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{ - dirty:false, - atlasIndex:0, - textureAtlas:null, + dirty: false, + atlasIndex: 0, + textureAtlas: null, - _batchNode:null, - _recursiveDirty:null, //Whether all of the sprite's children needs to be updated - _hasChildren:null, //Whether the sprite contains children - _shouldBeHidden:false, //should not be drawn because one of the ancestors is not visible - _transformToBatch:null, + _batchNode: null, + _recursiveDirty: null, //Whether all of the sprite's children needs to be updated + _hasChildren: null, //Whether the sprite contains children + _shouldBeHidden: false, //should not be drawn because one of the ancestors is not visible + _transformToBatch: null, // // Data used when the sprite is self-rendered // - _blendFunc:null, //It's required for CCTextureProtocol inheritance - _texture:null, //cc.Texture2D object that is used to render the sprite + _blendFunc: null, //It's required for CCTextureProtocol inheritance + _texture: null, //cc.Texture2D object that is used to render the sprite // // Shared data // // texture - _rect:null, //Rectangle of cc.Texture2D - _rectRotated:false, //Whether the texture is rotated + _rect: null, //Rectangle of cc.Texture2D + _rectRotated: false, //Whether the texture is rotated // Offset Position (used by Zwoptex) - _offsetPosition:null, // absolute - _unflippedOffsetPositionFromCenter:null, + _offsetPosition: null, // absolute + _unflippedOffsetPositionFromCenter: null, - _opacityModifyRGB:false, + _opacityModifyRGB: false, // image is flipped - _flippedX:false, //Whether the sprite is flipped horizontally or not. - _flippedY:false, //Whether the sprite is flipped vertically or not. + _flippedX: false, //Whether the sprite is flipped horizontally or not. + _flippedY: false, //Whether the sprite is flipped vertically or not. - _textureLoaded:false, - _className:"Sprite", + _textureLoaded: false, + _className: "Sprite", ctor: function (fileName, rect, rotated) { var self = this; @@ -140,7 +140,7 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{ * Returns whether the texture have been loaded * @returns {boolean} */ - textureLoaded:function(){ + textureLoaded: function () { return this._textureLoaded; }, @@ -150,7 +150,7 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{ * @param {Object} target * @deprecated since 3.1, please use addEventListener instead */ - addLoadedEventListener:function(callback, target){ + addLoadedEventListener: function (callback, target) { this.addEventListener("load", callback, target); }, @@ -158,7 +158,7 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{ * Returns whether or not the Sprite needs to be updated in the Atlas * @return {Boolean} True if the sprite needs to be updated in the Atlas, false otherwise. */ - isDirty:function () { + isDirty: function () { return this.dirty; }, @@ -166,7 +166,7 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{ * Makes the sprite to be updated in the Atlas. * @param {Boolean} bDirty */ - setDirty:function (bDirty) { + setDirty: function (bDirty) { this.dirty = bDirty; }, @@ -174,7 +174,7 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{ * Returns whether or not the texture rectangle is rotated. * @return {Boolean} */ - isTextureRectRotated:function () { + isTextureRectRotated: function () { return this._rectRotated; }, @@ -182,7 +182,7 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{ * Returns the index used on the TextureAtlas. * @return {Number} */ - getAtlasIndex:function () { + getAtlasIndex: function () { return this.atlasIndex; }, @@ -191,7 +191,7 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{ * @warning Don't modify this value unless you know what you are doing * @param {Number} atlasIndex */ - setAtlasIndex:function (atlasIndex) { + setAtlasIndex: function (atlasIndex) { this.atlasIndex = atlasIndex; }, @@ -199,7 +199,7 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{ * Returns the rect of the cc.Sprite in points * @return {cc.Rect} */ - getTextureRect:function () { + getTextureRect: function () { return cc.rect(this._rect); }, @@ -207,7 +207,7 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{ * Returns the weak reference of the cc.TextureAtlas when the sprite is rendered using via cc.SpriteBatchNode * @return {cc.TextureAtlas} */ - getTextureAtlas:function () { + getTextureAtlas: function () { return this.textureAtlas; }, @@ -215,7 +215,7 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{ * Sets the weak reference of the cc.TextureAtlas when the sprite is rendered using via cc.SpriteBatchNode * @param {cc.TextureAtlas} textureAtlas */ - setTextureAtlas:function (textureAtlas) { + setTextureAtlas: function (textureAtlas) { this.textureAtlas = textureAtlas; }, @@ -223,7 +223,7 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{ * Returns the offset position of the sprite. Calculated automatically by editors like Zwoptex. * @return {cc.Point} */ - getOffsetPosition:function () { + getOffsetPosition: function () { return cc.p(this._offsetPosition); }, @@ -238,7 +238,7 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{ * Returns the blend function * @return {cc.BlendFunc} */ - getBlendFunc:function () { + getBlendFunc: function () { return this._blendFunc; }, @@ -248,7 +248,7 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{ * @param {cc.SpriteFrame} spriteFrame A CCSpriteFrame object. It should includes a valid texture and a rect * @return {Boolean} true if the sprite is initialized properly, false otherwise. */ - initWithSpriteFrame:function (spriteFrame) { + initWithSpriteFrame: function (spriteFrame) { cc.assert(spriteFrame, cc._LogInfos.Sprite_initWithSpriteFrame); return this.setSpriteFrame(spriteFrame); }, @@ -264,7 +264,7 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{ * var sprite = new cc.Sprite(); * sprite.initWithSpriteFrameName("grossini_dance_01.png"); */ - initWithSpriteFrameName:function (spriteFrameName) { + initWithSpriteFrameName: function (spriteFrameName) { cc.assert(spriteFrameName, cc._LogInfos.Sprite_initWithSpriteFrameName); var frame = cc.spriteFrameCache.getSpriteFrame(spriteFrameName); cc.assert(frame, spriteFrameName + cc._LogInfos.Sprite_initWithSpriteFrameName1); @@ -275,7 +275,7 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{ * Tell the sprite to use batch node render. * @param {cc.SpriteBatchNode} batchNode */ - useBatchNode:function (batchNode) { + useBatchNode: function (batchNode) { this.textureAtlas = batchNode.getTextureAtlas(); // weak ref this._batchNode = batchNode; }, @@ -290,7 +290,7 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{ *

* @param {cc.Rect} rect */ - setVertexRect:function (rect) { + setVertexRect: function (rect) { var locRect = this._rect; locRect.x = rect.x; locRect.y = rect.y; @@ -303,7 +303,7 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{ * Sort all children of this sprite node. * @override */ - sortAllChildren:function () { + sortAllChildren: function () { if (this._reorderChildDirty) { var _children = this._children; @@ -325,9 +325,9 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{ * @param {Number} zOrder * @override */ - reorderChild:function (child, zOrder) { + reorderChild: function (child, zOrder) { cc.assert(child, cc._LogInfos.Sprite_reorderChild_2); - if(this._children.indexOf(child) === -1){ + if (this._children.indexOf(child) === -1) { cc.log(cc._LogInfos.Sprite_reorderChild); return; } @@ -348,7 +348,7 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{ * @param cleanup whether or not cleanup all running actions * @override */ - removeChild:function (child, cleanup) { + removeChild: function (child, cleanup) { if (this._batchNode) this._batchNode.removeSpriteFromAtlas(child); cc.Node.prototype.removeChild.call(this, child, cleanup); @@ -369,7 +369,7 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{ * @param cleanup whether or not cleanup all running actions * @override */ - removeAllChildren:function (cleanup) { + removeAllChildren: function (cleanup) { var locChildren = this._children, locBatchNode = this._batchNode; if (locBatchNode && locChildren != null) { for (var i = 0, len = locChildren.length; i < len; i++) @@ -389,8 +389,8 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{ * @param {Boolean} relative * @override */ - ignoreAnchorPointForPosition:function (relative) { - if(this._batchNode){ + ignoreAnchorPointForPosition: function (relative) { + if (this._batchNode) { cc.log(cc._LogInfos.Sprite_ignoreAnchorPointForPosition); return; } @@ -401,7 +401,7 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{ * Sets whether the sprite should be flipped horizontally or not. * @param {Boolean} flippedX true if the sprite should be flipped horizontally, false otherwise. */ - setFlippedX:function (flippedX) { + setFlippedX: function (flippedX) { if (this._flippedX !== flippedX) { this._flippedX = flippedX; this.setTextureRect(this._rect, this._rectRotated, this._contentSize); @@ -413,7 +413,7 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{ * Sets whether the sprite should be flipped vertically or not. * @param {Boolean} flippedY true if the sprite should be flipped vertically, false otherwise. */ - setFlippedY:function (flippedY) { + setFlippedY: function (flippedY) { if (this._flippedY !== flippedY) { this._flippedY = flippedY; this.setTextureRect(this._rect, this._rectRotated, this._contentSize); @@ -431,7 +431,7 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{ * sprite.setScaleX(sprite.getScaleX() * -1);

* @return {Boolean} true if the sprite is flipped horizontally, false otherwise. */ - isFlippedX:function () { + isFlippedX: function () { return this._flippedX; }, @@ -445,7 +445,7 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{ * sprite.setScaleY(sprite.getScaleY() * -1);

* @return {Boolean} true if the sprite is flipped vertically, false otherwise. */ - isFlippedY:function () { + isFlippedY: function () { return this._flippedY; }, @@ -468,7 +468,7 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{ * Returns whether opacity modify color or not. * @return {Boolean} */ - isOpacityModifyRGB:function () { + isOpacityModifyRGB: function () { return this._opacityModifyRGB; }, @@ -480,16 +480,16 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{ * @param {String} animationName * @param {Number} frameIndex */ - setDisplayFrameWithAnimationName:function (animationName, frameIndex) { + setDisplayFrameWithAnimationName: function (animationName, frameIndex) { cc.assert(animationName, cc._LogInfos.Sprite_setDisplayFrameWithAnimationName_3); var cache = cc.animationCache.getAnimation(animationName); - if(!cache){ + if (!cache) { cc.log(cc._LogInfos.Sprite_setDisplayFrameWithAnimationName); return; } var animFrame = cache.getFrames()[frameIndex]; - if(!animFrame){ + if (!animFrame) { cc.log(cc._LogInfos.Sprite_setDisplayFrameWithAnimationName_2); return; } @@ -500,11 +500,11 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{ * Returns the batch node object if this sprite is rendered by cc.SpriteBatchNode * @returns {cc.SpriteBatchNode|null} The cc.SpriteBatchNode object if this sprite is rendered by cc.SpriteBatchNode, null if the sprite isn't used batch node. */ - getBatchNode:function () { + getBatchNode: function () { return this._batchNode; }, - _setReorderChildDirtyRecursively:function () { + _setReorderChildDirtyRecursively: function () { //only set parents flag the first time if (!this._reorderChildDirty) { this._reorderChildDirty = true; @@ -521,7 +521,7 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{ * Returns the texture of the sprite node * @returns {cc.Texture2D} */ - getTexture:function () { + getTexture: function () { return this._texture; }, @@ -562,7 +562,7 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{ * 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 () { + getQuad: function () { return null; }, @@ -632,7 +632,7 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{ * @param {cc.Rect} rect The rectangle assigned the content area from texture. * @return {Boolean} true if the sprite is initialized properly, false otherwise. */ - initWithFile:function (filename, rect) { + initWithFile: function (filename, rect) { cc.assert(filename, cc._LogInfos.Sprite_initWithFile); var tex = cc.textureCache.getTextureForKey(filename); @@ -768,7 +768,7 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{ if (tag == null) tag = child.tag; - if(this._renderCmd._setBatchNodeForAddChild(child)){ + if (this._renderCmd._setBatchNodeForAddChild(child)) { //cc.Node already sets isReorderChildDirty_ so this needs to be after batchNode check cc.Node.prototype.addChild.call(this, child, localZOrder, tag); this._hasChildren = true; @@ -783,7 +783,7 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{ */ setSpriteFrame: function (newFrame) { var _t = this; - if(typeof newFrame === 'string'){ + if (typeof newFrame === 'string') { newFrame = cc.spriteFrameCache.getSpriteFrame(newFrame); cc.assert(newFrame, cc._LogInfos.Sprite_setSpriteFrame) } @@ -819,7 +819,7 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{ * @param {cc.SpriteFrame|String} newFrame * @deprecated */ - setDisplayFrame: function(newFrame){ + setDisplayFrame: function (newFrame) { cc.log(cc._LogInfos.Sprite_setDisplayFrame); this.setSpriteFrame(newFrame); }, @@ -830,7 +830,7 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{ * @param {cc.SpriteFrame} frame * @return {Boolean} */ - isFrameDisplayed: function(frame){ + isFrameDisplayed: function (frame) { return this._renderCmd.isFrameDisplayed(frame); }, @@ -865,7 +865,7 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{ * batch.addChild(sprite); * layer.addChild(batch); */ - setBatchNode:function (spriteBatchNode) { + setBatchNode: function (spriteBatchNode) { var _t = this; _t._batchNode = spriteBatchNode; // weak reference @@ -889,13 +889,13 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{ * @param {cc.Texture2D|String} texture */ setTexture: function (texture) { - if(!texture) + if (!texture) return this._renderCmd._setTexture(null); //CCSprite.cpp 327 and 338 var isFileName = (typeof texture === 'string'); - if(isFileName) + if (isFileName) texture = cc.textureCache.addImage(texture); this._loader.clear(); @@ -915,7 +915,7 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{ this._textureLoaded = true; }, - _changeRectWithTexture: function(texture){ + _changeRectWithTexture: function (texture) { var contentSize = texture._contentSize; var rect = cc.rect( 0, 0, @@ -924,8 +924,8 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{ this.setTextureRect(rect); }, - _createRenderCmd: function(){ - if(cc._renderType === cc.game.RENDER_TYPE_CANVAS) + _createRenderCmd: function () { + if (cc._renderType === cc.game.RENDER_TYPE_CANVAS) return new cc.Sprite.CanvasRenderCmd(this); else return new cc.Sprite.WebGLRenderCmd(this); diff --git a/cocos2d/core/sprites/CCSpriteBatchNode.js b/cocos2d/core/sprites/CCSpriteBatchNode.js index d8044af074..3abd61fb4c 100644 --- a/cocos2d/core/sprites/CCSpriteBatchNode.js +++ b/cocos2d/core/sprites/CCSpriteBatchNode.js @@ -69,7 +69,7 @@ cc.SpriteBatchNode = cc.Node.extend(/** @lends cc.SpriteBatchNode# */{ texture2D = cc.textureCache.getTextureForKey(fileImage); if (!texture2D) texture2D = cc.textureCache.addImage(fileImage); - }else if (fileImage instanceof cc.Texture2D) + } else if (fileImage instanceof cc.Texture2D) texture2D = fileImage; texture2D && this.initWithTexture(texture2D); @@ -105,7 +105,8 @@ cc.SpriteBatchNode = cc.Node.extend(/** @lends cc.SpriteBatchNode# */{ * @param {cc.TextureAtlas} textureAtlas * @deprecated since v3.12 */ - setTextureAtlas: function (textureAtlas) {}, + setTextureAtlas: function (textureAtlas) { + }, /** * Return Descendants of cc.SpriteBatchNode @@ -156,7 +157,8 @@ cc.SpriteBatchNode = cc.Node.extend(/** @lends cc.SpriteBatchNode# */{ * Do nothing * @deprecated since v3.12 */ - increaseAtlasCapacity: function () {}, + increaseAtlasCapacity: function () { + }, /** * Removes a child given a certain index. It will also cleanup the running actions depending on the cleanup parameter. @@ -243,7 +245,7 @@ cc.SpriteBatchNode = cc.Node.extend(/** @lends cc.SpriteBatchNode# */{ * @return {cc.BlendFunc} */ getBlendFunc: function () { - return new cc.BlendFunc(this._blendFunc.src,this._blendFunc.dst); + return new cc.BlendFunc(this._blendFunc.src, this._blendFunc.dst); }, /** @@ -301,8 +303,8 @@ cc.SpriteBatchNode = cc.Node.extend(/** @lends cc.SpriteBatchNode# */{ */ appendChild: function (sprite) { this.sortAllChildren(); - var lastLocalZOrder = this._children[this._children.length-1]._localZOrder; - this.addChild(sprite. lastLocalZOrder + 1); + var lastLocalZOrder = this._children[this._children.length - 1]._localZOrder; + this.addChild(sprite.lastLocalZOrder + 1); }, /** @@ -342,18 +344,18 @@ cc.SpriteBatchNode = cc.Node.extend(/** @lends cc.SpriteBatchNode# */{ * @function * @param {cc.Texture2D} texture */ - setTexture: function(texture){ + setTexture: function (texture) { this._texture = texture; if (texture._textureLoaded) { - var children = this._children, i, len = children.length; + var i, children = this._children, 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; + texture.addEventListener("load", function () { + var i, children = this._children, len = children.length; for (i = 0; i < len; ++i) { children[i].setTexture(texture); } @@ -363,7 +365,7 @@ cc.SpriteBatchNode = cc.Node.extend(/** @lends cc.SpriteBatchNode# */{ setShaderProgram: function (newShaderProgram) { this._renderCmd.setShaderProgram(newShaderProgram); - var children = this._children, i, len = children.length; + var i, children = this._children, len = children.length; for (i = 0; i < len; ++i) { children[i].setShaderProgram(newShaderProgram); } @@ -380,7 +382,7 @@ cc.SpriteBatchNode = cc.Node.extend(/** @lends cc.SpriteBatchNode# */{ addChild: function (child, zOrder, tag) { cc.assert(child !== undefined, cc._LogInfos.CCSpriteBatchNode_addChild_3); - if(!this._isValidChild(child)) + if (!this._isValidChild(child)) return; zOrder = (zOrder === undefined) ? child.zIndex : zOrder; diff --git a/cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js b/cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js index ba289bfcf1..29472fb4b6 100644 --- a/cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js +++ b/cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js @@ -22,7 +22,7 @@ THE SOFTWARE. ****************************************************************************/ -(function() { +(function () { cc.Sprite.CanvasRenderCmd = function (renderable) { cc.Node.CanvasRenderCmd.call(this, renderable); this._needDraw = true; @@ -44,14 +44,15 @@ var proto = cc.Sprite.CanvasRenderCmd.prototype = Object.create(cc.Node.CanvasRenderCmd.prototype); proto.constructor = cc.Sprite.CanvasRenderCmd; - proto.setDirtyRecursively = function (value) {}; + proto.setDirtyRecursively = function (value) { + }; proto._setTexture = function (texture) { var node = this._node; if (node._texture !== texture) { if (texture) { node._textureLoaded = texture._textureLoaded; - }else{ + } else { node._textureLoaded = false; } node._texture = texture; @@ -107,7 +108,7 @@ var locTextureCoord = this._textureCoord, alpha = (this._displayedOpacity / 255); var texture = this._textureToRender || node._texture; - if ((texture && (locTextureCoord.width === 0 || locTextureCoord.height === 0|| !texture._textureLoaded)) || alpha === 0) + if ((texture && (locTextureCoord.width === 0 || locTextureCoord.height === 0 || !texture._textureLoaded)) || alpha === 0) return; var wrapper = ctx || cc._renderContext, context = wrapper.getContext(); @@ -118,7 +119,7 @@ wrapper.setCompositeOperation(this._blendFuncStr); wrapper.setGlobalAlpha(alpha); - if(node._flippedX || node._flippedY) + if (node._flippedX || node._flippedY) wrapper.save(); if (node._flippedX) { locX = -locX - locWidth; @@ -133,7 +134,7 @@ if (this._colorized) { sx = 0; sy = 0; - }else{ + } else { sx = locTextureCoord.renderX; sy = locTextureCoord.renderY; } @@ -163,22 +164,22 @@ context.fillRect(x, y, contentSize.width * scaleX, contentSize.height * scaleY); } } - if(node._flippedX || node._flippedY) + if (node._flippedX || node._flippedY) wrapper.restore(); cc.g_NumberOfDraws++; }; - proto._updateColor = function(){ + proto._updateColor = function () { var node = this._node; var texture = node._texture, rect = this._textureCoord; var dColor = this._displayedColor; - if(texture){ - if(dColor.r !== 255 || dColor.g !== 255 || dColor.b !== 255){ + if (texture) { + if (dColor.r !== 255 || dColor.g !== 255 || dColor.b !== 255) { this._textureToRender = texture._generateColorTexture(dColor.r, dColor.g, dColor.b, rect); this._colorized = true; - }else if(texture){ + } else if (texture) { this._textureToRender = texture; this._colorized = false; } @@ -232,14 +233,14 @@ if (!rect) return texture; - counterclockwise = counterclockwise == null? true: counterclockwise; // texture package is counterclockwise, spine is clockwise + counterclockwise = counterclockwise == null ? true : counterclockwise; // texture package is counterclockwise, spine is clockwise var nCanvas = document.createElement("canvas"); nCanvas.width = rect.width; nCanvas.height = rect.height; var ctx = nCanvas.getContext("2d"); ctx.translate(nCanvas.width / 2, nCanvas.height / 2); - if(counterclockwise) + if (counterclockwise) ctx.rotate(-1.5707963267948966); else ctx.rotate(1.5707963267948966); diff --git a/cocos2d/core/sprites/CCSpriteFrame.js b/cocos2d/core/sprites/CCSpriteFrame.js index 9ba272211b..4879225a53 100644 --- a/cocos2d/core/sprites/CCSpriteFrame.js +++ b/cocos2d/core/sprites/CCSpriteFrame.js @@ -52,18 +52,18 @@ * var frame2 = new cc.SpriteFrame(texture, cc.rect(0,0,90,128),false,0,cc.size(90,128)); */ cc.SpriteFrame = cc.Class.extend(/** @lends cc.SpriteFrame# */{ - _offset:null, - _originalSize:null, - _rectInPixels:null, - _rotated:false, - _rect:null, - _offsetInPixels:null, - _originalSizeInPixels:null, - _texture:null, - _textureFilename:"", - _textureLoaded:false, - - ctor:function (filename, rect, rotated, offset, originalSize) { + _offset: null, + _originalSize: null, + _rectInPixels: null, + _rotated: false, + _rect: null, + _offsetInPixels: null, + _originalSizeInPixels: null, + _texture: null, + _textureFilename: "", + _textureLoaded: false, + + ctor: function (filename, rect, rotated, offset, originalSize) { this._offset = cc.p(0, 0); this._offsetInPixels = cc.p(0, 0); this._originalSize = cc.size(0, 0); @@ -73,11 +73,11 @@ cc.SpriteFrame = cc.Class.extend(/** @lends cc.SpriteFrame# */{ this._texture = null; this._textureLoaded = false; - if(filename !== undefined && rect !== undefined ){ - if(rotated === undefined || offset === undefined || originalSize === undefined) + if (filename !== undefined && rect !== undefined) { + if (rotated === undefined || offset === undefined || originalSize === undefined) this.initWithTexture(filename, rect); else - this.initWithTexture(filename, rect, rotated, offset, originalSize) + this.initWithTexture(filename, rect, rotated, offset, originalSize); } }, @@ -85,7 +85,7 @@ cc.SpriteFrame = cc.Class.extend(/** @lends cc.SpriteFrame# */{ * Returns whether the texture have been loaded * @returns {boolean} */ - textureLoaded:function(){ + textureLoaded: function () { return this._textureLoaded; }, @@ -95,7 +95,7 @@ cc.SpriteFrame = cc.Class.extend(/** @lends cc.SpriteFrame# */{ * @param {Object} target * @deprecated since 3.1, please use addEventListener instead */ - addLoadedEventListener:function(callback, target){ + addLoadedEventListener: function (callback, target) { this.addEventListener("load", callback, target); }, @@ -103,7 +103,7 @@ cc.SpriteFrame = cc.Class.extend(/** @lends cc.SpriteFrame# */{ * Gets the rect of the frame in the texture * @return {cc.Rect} */ - getRectInPixels:function () { + getRectInPixels: function () { var locRectInPixels = this._rectInPixels; return cc.rect(locRectInPixels.x, locRectInPixels.y, locRectInPixels.width, locRectInPixels.height); }, @@ -112,9 +112,9 @@ cc.SpriteFrame = cc.Class.extend(/** @lends cc.SpriteFrame# */{ * Sets the rect of the frame in the texture * @param {cc.Rect} rectInPixels */ - setRectInPixels:function (rectInPixels) { - if (!this._rectInPixels){ - this._rectInPixels = cc.rect(0,0,0,0); + setRectInPixels: function (rectInPixels) { + if (!this._rectInPixels) { + this._rectInPixels = cc.rect(0, 0, 0, 0); } this._rectInPixels.x = rectInPixels.x; this._rectInPixels.y = rectInPixels.y; @@ -127,7 +127,7 @@ cc.SpriteFrame = cc.Class.extend(/** @lends cc.SpriteFrame# */{ * Returns whether the sprite frame is rotated in the texture. * @return {Boolean} */ - isRotated:function () { + isRotated: function () { return this._rotated; }, @@ -135,7 +135,7 @@ cc.SpriteFrame = cc.Class.extend(/** @lends cc.SpriteFrame# */{ * Set whether the sprite frame is rotated in the texture. * @param {Boolean} bRotated */ - setRotated:function (bRotated) { + setRotated: function (bRotated) { this._rotated = bRotated; }, @@ -143,7 +143,7 @@ cc.SpriteFrame = cc.Class.extend(/** @lends cc.SpriteFrame# */{ * Returns the rect of the sprite frame in the texture * @return {cc.Rect} */ - getRect:function () { + getRect: function () { var locRect = this._rect; return cc.rect(locRect.x, locRect.y, locRect.width, locRect.height); }, @@ -152,9 +152,9 @@ cc.SpriteFrame = cc.Class.extend(/** @lends cc.SpriteFrame# */{ * Sets the rect of the sprite frame in the texture * @param {cc.Rect} rect */ - setRect:function (rect) { - if (!this._rect){ - this._rect = cc.rect(0,0,0,0); + setRect: function (rect) { + if (!this._rect) { + this._rect = cc.rect(0, 0, 0, 0); } this._rect.x = rect.x; this._rect.y = rect.y; @@ -167,7 +167,7 @@ cc.SpriteFrame = cc.Class.extend(/** @lends cc.SpriteFrame# */{ * Returns the offset of the sprite frame in the texture in pixel * @return {cc.Point} */ - getOffsetInPixels:function () { + getOffsetInPixels: function () { return cc.p(this._offsetInPixels); }, @@ -175,7 +175,7 @@ cc.SpriteFrame = cc.Class.extend(/** @lends cc.SpriteFrame# */{ * Sets the offset of the sprite frame in the texture in pixel * @param {cc.Point} offsetInPixels */ - setOffsetInPixels:function (offsetInPixels) { + setOffsetInPixels: function (offsetInPixels) { this._offsetInPixels.x = offsetInPixels.x; this._offsetInPixels.y = offsetInPixels.y; cc._pointPixelsToPointsOut(this._offsetInPixels, this._offset); @@ -185,7 +185,7 @@ cc.SpriteFrame = cc.Class.extend(/** @lends cc.SpriteFrame# */{ * Returns the original size of the trimmed image * @return {cc.Size} */ - getOriginalSizeInPixels:function () { + getOriginalSizeInPixels: function () { return cc.size(this._originalSizeInPixels); }, @@ -193,7 +193,7 @@ cc.SpriteFrame = cc.Class.extend(/** @lends cc.SpriteFrame# */{ * Sets the original size of the trimmed image * @param {cc.Size} sizeInPixels */ - setOriginalSizeInPixels:function (sizeInPixels) { + setOriginalSizeInPixels: function (sizeInPixels) { this._originalSizeInPixels.width = sizeInPixels.width; this._originalSizeInPixels.height = sizeInPixels.height; }, @@ -202,7 +202,7 @@ cc.SpriteFrame = cc.Class.extend(/** @lends cc.SpriteFrame# */{ * Returns the original size of the trimmed image * @return {cc.Size} */ - getOriginalSize:function () { + getOriginalSize: function () { return cc.size(this._originalSize); }, @@ -210,7 +210,7 @@ cc.SpriteFrame = cc.Class.extend(/** @lends cc.SpriteFrame# */{ * Sets the original size of the trimmed image * @param {cc.Size} sizeInPixels */ - setOriginalSize:function (sizeInPixels) { + setOriginalSize: function (sizeInPixels) { this._originalSize.width = sizeInPixels.width; this._originalSize.height = sizeInPixels.height; }, @@ -219,7 +219,7 @@ cc.SpriteFrame = cc.Class.extend(/** @lends cc.SpriteFrame# */{ * Returns the texture of the frame * @return {cc.Texture2D} */ - getTexture:function () { + getTexture: function () { if (this._texture) return this._texture; if (this._textureFilename !== "") { @@ -235,15 +235,15 @@ cc.SpriteFrame = cc.Class.extend(/** @lends cc.SpriteFrame# */{ * Sets the texture of the frame, the texture is retained automatically * @param {cc.Texture2D} texture */ - setTexture:function (texture) { + setTexture: function (texture) { if (this._texture !== texture) { var locLoaded = texture.isLoaded(); this._textureLoaded = locLoaded; this._texture = texture; - if(!locLoaded){ - texture.addEventListener("load", function(sender){ + if (!locLoaded) { + texture.addEventListener("load", function (sender) { this._textureLoaded = true; - if(this._rotated && cc._renderType === cc.game.RENDER_TYPE_CANVAS){ + if (this._rotated && cc._renderType === cc.game.RENDER_TYPE_CANVAS) { var tempElement = sender.getHtmlElementObj(); tempElement = cc.Sprite.CanvasRenderCmd._cutRotateImageToCanvas(tempElement, this.getRect()); var tempTexture = new cc.Texture2D(); @@ -255,15 +255,15 @@ cc.SpriteFrame = cc.Class.extend(/** @lends cc.SpriteFrame# */{ this.setRect(cc.rect(0, 0, rect.width, rect.height)); } var locRect = this._rect; - if(locRect.width === 0 && locRect.height === 0){ + if (locRect.width === 0 && locRect.height === 0) { var w = sender.width, h = sender.height; this._rect.width = w; this._rect.height = h; this._rectInPixels = cc.rectPointsToPixels(this._rect); this._originalSizeInPixels.width = this._rectInPixels.width; this._originalSizeInPixels.height = this._rectInPixels.height; - this._originalSize.width = w; - this._originalSize.height = h; + this._originalSize.width = w; + this._originalSize.height = h; } //dispatch 'load' event of cc.SpriteFrame this.dispatchEvent("load"); @@ -276,7 +276,7 @@ cc.SpriteFrame = cc.Class.extend(/** @lends cc.SpriteFrame# */{ * Returns the offset of the frame in the texture * @return {cc.Point} */ - getOffset:function () { + getOffset: function () { return cc.p(this._offset); }, @@ -284,7 +284,7 @@ cc.SpriteFrame = cc.Class.extend(/** @lends cc.SpriteFrame# */{ * Sets the offset of the frame in the texture * @param {cc.Point} offsets */ - setOffset:function (offsets) { + setOffset: function (offsets) { this._offset.x = offsets.x; this._offset.y = offsets.y; }, @@ -293,7 +293,7 @@ cc.SpriteFrame = cc.Class.extend(/** @lends cc.SpriteFrame# */{ * Clone the sprite frame * @returns {SpriteFrame} */ - clone: function(){ + clone: function () { var frame = new cc.SpriteFrame(); frame.initWithTexture(this._textureFilename, this._rectInPixels, this._rotated, this._offsetInPixels, this._originalSizeInPixels); frame.setTexture(this._texture); @@ -304,7 +304,7 @@ cc.SpriteFrame = cc.Class.extend(/** @lends cc.SpriteFrame# */{ * Copy the sprite frame * @return {cc.SpriteFrame} */ - copyWithZone:function () { + copyWithZone: function () { var copy = new cc.SpriteFrame(); copy.initWithTexture(this._textureFilename, this._rectInPixels, this._rotated, this._offsetInPixels, this._originalSizeInPixels); copy.setTexture(this._texture); @@ -315,7 +315,7 @@ cc.SpriteFrame = cc.Class.extend(/** @lends cc.SpriteFrame# */{ * Copy the sprite frame * @returns {cc.SpriteFrame} */ - copy:function () { + copy: function () { return this.copyWithZone(); }, @@ -329,18 +329,18 @@ cc.SpriteFrame = cc.Class.extend(/** @lends cc.SpriteFrame# */{ * @param {cc.Size} [originalSize=rect.size] * @return {Boolean} */ - initWithTexture:function (texture, rect, rotated, offset, originalSize) { - if(arguments.length === 2) + initWithTexture: function (texture, rect, rotated, offset, originalSize) { + if (arguments.length === 2) rect = cc.rectPointsToPixels(rect); offset = offset || cc.p(0, 0); originalSize = originalSize || rect; rotated = rotated || false; - if (typeof texture === 'string'){ + if (typeof texture === 'string') { this._texture = null; this._textureFilename = texture; - } else if (texture instanceof cc.Texture2D){ + } else if (texture instanceof cc.Texture2D) { this.setTexture(texture); } @@ -349,19 +349,19 @@ cc.SpriteFrame = cc.Class.extend(/** @lends cc.SpriteFrame# */{ this._rectInPixels = rect; this._rect = cc.rectPixelsToPoints(rect); - if(texture && texture.url && texture.isLoaded()) { + if (texture && texture.url && texture.isLoaded()) { var _x, _y; - if(rotated){ + if (rotated) { _x = rect.x + rect.height; _y = rect.y + rect.width; - }else{ + } else { _x = rect.x + rect.width; _y = rect.y + rect.height; } - if(_x > texture.getPixelsWide()){ + if (_x > texture.getPixelsWide()) { cc.error(cc._LogInfos.RectWidth, texture.url); } - if(_y > texture.getPixelsHigh()){ + if (_y > texture.getPixelsHigh()) { cc.error(cc._LogInfos.RectHeight, texture.url); } } @@ -394,7 +394,7 @@ cc.EventHelper.prototype.apply(cc.SpriteFrame.prototype); * @return {cc.SpriteFrame} */ cc.SpriteFrame.create = function (filename, rect, rotated, offset, originalSize) { - return new cc.SpriteFrame(filename,rect,rotated,offset,originalSize); + return new cc.SpriteFrame(filename, rect, rotated, offset, originalSize); }; /** diff --git a/cocos2d/core/sprites/CCSpriteFrameCache.js b/cocos2d/core/sprites/CCSpriteFrameCache.js index d6955477c1..52c2ba375c 100644 --- a/cocos2d/core/sprites/CCSpriteFrameCache.js +++ b/cocos2d/core/sprites/CCSpriteFrameCache.js @@ -36,38 +36,38 @@ * @name cc.spriteFrameCache */ cc.spriteFrameCache = /** @lends cc.spriteFrameCache# */{ - _CCNS_REG1 : /^\s*\{\s*([\-]?\d+[.]?\d*)\s*,\s*([\-]?\d+[.]?\d*)\s*\}\s*$/, - _CCNS_REG2 : /^\s*\{\s*\{\s*([\-]?\d+[.]?\d*)\s*,\s*([\-]?\d+[.]?\d*)\s*\}\s*,\s*\{\s*([\-]?\d+[.]?\d*)\s*,\s*([\-]?\d+[.]?\d*)\s*\}\s*\}\s*$/, + _CCNS_REG1: /^\s*\{\s*([\-]?\d+[.]?\d*)\s*,\s*([\-]?\d+[.]?\d*)\s*\}\s*$/, + _CCNS_REG2: /^\s*\{\s*\{\s*([\-]?\d+[.]?\d*)\s*,\s*([\-]?\d+[.]?\d*)\s*\}\s*,\s*\{\s*([\-]?\d+[.]?\d*)\s*,\s*([\-]?\d+[.]?\d*)\s*\}\s*\}\s*$/, _spriteFrames: {}, _spriteFramesAliases: {}, - _frameConfigCache : {}, + _frameConfigCache: {}, - _rectFromString : function (content) { + _rectFromString: function (content) { var result = this._CCNS_REG2.exec(content); - if(!result) return cc.rect(0, 0, 0, 0); + if (!result) return cc.rect(0, 0, 0, 0); return cc.rect(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3]), parseFloat(result[4])); }, - _pointFromString : function (content) { + _pointFromString: function (content) { var result = this._CCNS_REG1.exec(content); - if(!result) return cc.p(0,0); + if (!result) return cc.p(0, 0); return cc.p(parseFloat(result[1]), parseFloat(result[2])); }, - _sizeFromString : function (content) { + _sizeFromString: function (content) { var result = this._CCNS_REG1.exec(content); - if(!result) return cc.size(0, 0); + if (!result) return cc.size(0, 0); return cc.size(parseFloat(result[1]), parseFloat(result[2])); }, - _getFrameConfig : function(url){ + _getFrameConfig: function (url) { var dict = cc.loader.getRes(url); cc.assert(dict, cc._LogInfos.spriteFrameCache__getFrameConfig_2, url); cc.loader.release(url);//release it in loader - if(dict._inited){ + if (dict._inited) { this._frameConfigCache[url] = dict; return dict; } @@ -75,24 +75,24 @@ cc.spriteFrameCache = /** @lends cc.spriteFrameCache# */{ return this._frameConfigCache[url]; }, - _getFrameConfigByJsonObject: function(url, jsonObject) { + _getFrameConfigByJsonObject: function (url, jsonObject) { cc.assert(jsonObject, cc._LogInfos.spriteFrameCache__getFrameConfig_2, url); this._frameConfigCache[url] = this._parseFrameConfig(jsonObject); return this._frameConfigCache[url]; }, - _parseFrameConfig: function(dict) { + _parseFrameConfig: function (dict) { var tempFrames = dict["frames"], tempMeta = dict["metadata"] || dict["meta"]; var frames = {}, meta = {}; var format = 0; - if(tempMeta){//init meta + if (tempMeta) {//init meta var tmpFormat = tempMeta["format"]; format = (tmpFormat.length <= 1) ? parseInt(tmpFormat) : tmpFormat; meta.image = tempMeta["textureFileName"] || tempMeta["textureFileName"] || tempMeta["image"]; } for (var key in tempFrames) { var frameDict = tempFrames[key]; - if(!frameDict) continue; + if (!frameDict) continue; var tempFrame = {}; if (format == 0) { @@ -140,9 +140,9 @@ cc.spriteFrameCache = /** @lends cc.spriteFrameCache# */{ }, // Adds multiple Sprite Frames from a json object. it uses for local web view app. - _addSpriteFramesByObject: function(url, jsonObject, texture) { + _addSpriteFramesByObject: function (url, jsonObject, texture) { cc.assert(url, cc._LogInfos.spriteFrameCache_addSpriteFrames_2); - if(!jsonObject || !jsonObject["frames"]) + if (!jsonObject || !jsonObject["frames"]) return; var frameConfig = this._frameConfigCache[url] || this._getFrameConfigByJsonObject(url, jsonObject); @@ -150,16 +150,16 @@ cc.spriteFrameCache = /** @lends cc.spriteFrameCache# */{ this._createSpriteFrames(url, frameConfig, texture); }, - _createSpriteFrames: function(url, frameConfig, texture) { + _createSpriteFrames: function (url, frameConfig, texture) { var frames = frameConfig.frames, meta = frameConfig.meta; - if(!texture){ + if (!texture) { var texturePath = cc.path.changeBasename(url, meta.image || ".png"); texture = cc.textureCache.addImage(texturePath); - }else if(texture instanceof cc.Texture2D){ + } else if (texture instanceof cc.Texture2D) { //do nothing - }else if(cc.isString(texture)){//string + } else if (cc.isString(texture)) {//string texture = cc.textureCache.addImage(texture); - }else{ + } else { cc.assert(0, cc._LogInfos.spriteFrameCache_addSpriteFrames_3); } @@ -171,8 +171,8 @@ cc.spriteFrameCache = /** @lends cc.spriteFrameCache# */{ if (!spriteFrame) { spriteFrame = new cc.SpriteFrame(texture, frame.rect, frame.rotated, frame.offset, frame.size); var aliases = frame.aliases; - if(aliases){//set aliases - for(var i = 0, li = aliases.length; i < li; i++){ + if (aliases) {//set aliases + for (var i = 0, li = aliases.length; i < li; i++) { var alias = aliases[i]; if (spAliases[alias]) cc.log(cc._LogInfos.spriteFrameCache_addSpriteFrames, alias); @@ -218,7 +218,7 @@ cc.spriteFrameCache = /** @lends cc.spriteFrameCache# */{ //Is it a SpriteFrame plist? var dict = this._frameConfigCache[url] || cc.loader.getRes(url); - if(!dict || !dict["frames"]) + if (!dict || !dict["frames"]) return; var frameConfig = this._frameConfigCache[url] || this._getFrameConfig(url); @@ -294,13 +294,13 @@ cc.spriteFrameCache = /** @lends cc.spriteFrameCache# */{ removeSpriteFramesFromFile: function (url) { var self = this, spriteFrames = self._spriteFrames, aliases = self._spriteFramesAliases, cfg = self._frameConfigCache[url]; - if(!cfg) return; + if (!cfg) return; var frames = cfg.frames; for (var key in frames) { if (spriteFrames[key]) { delete(spriteFrames[key]); for (var alias in aliases) {//remove alias - if(aliases[alias] === key) delete aliases[alias]; + if (aliases[alias] === key) delete aliases[alias]; } } } @@ -320,7 +320,7 @@ cc.spriteFrameCache = /** @lends cc.spriteFrameCache# */{ if (frame && (frame.getTexture() === texture)) { delete(spriteFrames[key]); for (var alias in aliases) {//remove alias - if(aliases[alias] === key) delete aliases[alias]; + if (aliases[alias] === key) delete aliases[alias]; } } } @@ -345,15 +345,15 @@ cc.spriteFrameCache = /** @lends cc.spriteFrameCache# */{ var key = self._spriteFramesAliases[name]; if (key) { frame = self._spriteFrames[key.toString()]; - if(!frame) delete self._spriteFramesAliases[name]; + if (!frame) delete self._spriteFramesAliases[name]; } } return frame; }, - _clear: function () { - this._spriteFrames = {}; - this._spriteFramesAliases = {}; - this._frameConfigCache = {}; - } + _clear: function () { + this._spriteFrames = {}; + this._spriteFramesAliases = {}; + this._frameConfigCache = {}; + } }; diff --git a/cocos2d/core/sprites/CCSpriteWebGLRenderCmd.js b/cocos2d/core/sprites/CCSpriteWebGLRenderCmd.js index fd5a07e6c8..735db8e214 100644 --- a/cocos2d/core/sprites/CCSpriteWebGLRenderCmd.js +++ b/cocos2d/core/sprites/CCSpriteWebGLRenderCmd.js @@ -23,7 +23,7 @@ ****************************************************************************/ //Sprite's WebGL render command -(function() { +(function () { cc.Sprite.WebGLRenderCmd = function (renderable) { cc.Node.WebGLRenderCmd.call(this, renderable); @@ -45,9 +45,10 @@ var proto = cc.Sprite.WebGLRenderCmd.prototype = Object.create(cc.Node.WebGLRenderCmd.prototype); proto.constructor = cc.Sprite.WebGLRenderCmd; - proto.updateBlendFunc = function (blendFunc) {}; + proto.updateBlendFunc = function (blendFunc) { + }; - proto.setDirtyFlag = function(dirtyFlag){ + proto.setDirtyFlag = function (dirtyFlag) { cc.Node.WebGLRenderCmd.prototype.setDirtyFlag.call(this, dirtyFlag); this._dirty = true; }; @@ -201,7 +202,8 @@ } }; - proto._setColorDirty = function () {}; + proto._setColorDirty = function () { + }; proto._updateBlendFunc = function () { if (this._batchNode) { @@ -229,12 +231,12 @@ var node = this._node; // If batchnode, then texture id should be the same if (node._batchNode) { - if(node._batchNode.texture !== texture){ + if (node._batchNode.texture !== texture) { cc.log(cc._LogInfos.Sprite_setTexture); return; } } else { - if(node._texture !== texture){ + if (node._texture !== texture) { node._textureLoaded = texture ? texture._textureLoaded : false; node._texture = texture; this._updateBlendFunc(); @@ -272,7 +274,7 @@ 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, + wt = this._worldTransform, wtx = wt.tx, wty = wt.ty, lxa = lx * wt.a, lxb = lx * wt.b, rxa = rx * wt.a, rxb = rx * wt.b, tyc = ty * wt.c, tyd = ty * wt.d, byc = by * wt.c, byd = by * wt.d; @@ -309,7 +311,7 @@ g *= a; b *= a; } - this._color[0] = ((opacity<<24) | (b<<16) | (g<<8) | r); + this._color[0] = ((opacity << 24) | (b << 16) | (g << 8) | r); var z = node._vertexZ; var vertices = this._vertices; diff --git a/cocos2d/core/textures/CCTexture2D.js b/cocos2d/core/textures/CCTexture2D.js index b772532ae1..3d1e3c66af 100644 --- a/cocos2d/core/textures/CCTexture2D.js +++ b/cocos2d/core/textures/CCTexture2D.js @@ -322,20 +322,20 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () { }, setTexParameters: function (texParams, magFilter, wrapS, wrapT) { - if(magFilter !== undefined) + if (magFilter !== undefined) texParams = {minFilter: texParams, magFilter: magFilter, wrapS: wrapS, wrapT: wrapT}; - if(texParams.wrapS === cc.REPEAT && texParams.wrapT === cc.REPEAT){ + if (texParams.wrapS === cc.REPEAT && texParams.wrapT === cc.REPEAT) { this._pattern = "repeat"; return; } - if(texParams.wrapS === cc.REPEAT ){ + if (texParams.wrapS === cc.REPEAT) { this._pattern = "repeat-x"; return; } - if(texParams.wrapT === cc.REPEAT){ + if (texParams.wrapT === cc.REPEAT) { this._pattern = "repeat-y"; return; } @@ -383,8 +383,9 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () { this.removeEventTarget("load", target); }, - _generateColorTexture: function(){/*overide*/}, - _generateTextureCacheForColor: function(){ + _generateColorTexture: function () {/*overide*/ + }, + _generateTextureCacheForColor: function () { if (this.channelCache) return this.channelCache; @@ -403,23 +404,23 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () { _grayElementObj: null, _backupElement: null, _isGray: false, - _switchToGray: function(toGray){ - if(!this._textureLoaded || this._isGray === toGray) + _switchToGray: function (toGray) { + if (!this._textureLoaded || this._isGray === toGray) return; this._isGray = toGray; - if(this._isGray){ + if (this._isGray) { this._backupElement = this._htmlElementObj; - if(!this._grayElementObj) + if (!this._grayElementObj) this._grayElementObj = cc.Texture2D._generateGrayTexture(this._htmlElementObj); this._htmlElementObj = this._grayElementObj; } else { - if(this._backupElement !== null) + if (this._backupElement !== null) this._htmlElementObj = this._backupElement; } } }; - var renderToCache = function(image, cache){ + var renderToCache = function (image, cache) { var w = image.width; var h = image.height; @@ -443,7 +444,7 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () { var to = ctx.getImageData(0, 0, w, h); var data = to.data; for (var i = 0; i < pixels.length; i += 4) { - data[i ] = (rgbI === 0) ? pixels[i ] : 0; + data[i] = (rgbI === 0) ? pixels[i] : 0; data[i + 1] = (rgbI === 1) ? pixels[i + 1] : 0; data[i + 2] = (rgbI === 2) ? pixels[i + 2] : 0; data[i + 3] = pixels[i + 3]; @@ -454,17 +455,17 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () { }; //change color function - if(cc.sys._supportCanvasNewBlendModes){ + if (cc.sys._supportCanvasNewBlendModes) { //multiply mode //Primary afferent, Draw a new texture based on rect - proto._generateColorTexture = function(r, g, b, rect, canvas){ + proto._generateColorTexture = function (r, g, b, rect, canvas) { var onlyCanvas = false; - if(canvas) + if (canvas) onlyCanvas = true; else canvas = document.createElement("canvas"); var textureImage = this._htmlElementObj; - if(!rect) + if (!rect) rect = cc.rect(0, 0, textureImage.width, textureImage.height); canvas.width = rect.width; @@ -472,7 +473,7 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () { var context = canvas.getContext("2d"); context.globalCompositeOperation = "source-over"; - context.fillStyle = "rgb(" + (r|0) + "," + (g|0) + "," + (b|0) + ")"; + context.fillStyle = "rgb(" + (r | 0) + "," + (g | 0) + "," + (b | 0) + ")"; context.fillRect(0, 0, rect.width, rect.height); context.globalCompositeOperation = "multiply"; context.drawImage( @@ -486,28 +487,28 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () { rect.x, rect.y, rect.width, rect.height, 0, 0, rect.width, rect.height ); - if(onlyCanvas) + if (onlyCanvas) return canvas; var newTexture = new cc.Texture2D(); newTexture.initWithElement(canvas); newTexture.handleLoadedTexture(); return newTexture; }; - }else{ + } else { //Four color map overlay - proto._generateColorTexture = function(r, g, b, rect, canvas){ + proto._generateColorTexture = function (r, g, b, rect, canvas) { var onlyCanvas = false; - if(canvas) + if (canvas) onlyCanvas = true; else canvas = document.createElement("canvas"); var textureImage = this._htmlElementObj; - if(!rect) + if (!rect) rect = cc.rect(0, 0, textureImage.width, textureImage.height); var x, y, w, h; x = rect.x; y = rect.y; w = rect.width; h = rect.height; - if(!w || !h) + if (!w || !h) return; canvas.width = w; @@ -545,7 +546,7 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () { 0, 0, w, h ); } - if(onlyCanvas) + if (onlyCanvas) return canvas; var newTexture = new cc.Texture2D(); @@ -578,7 +579,7 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () { */ cc.Texture2D = cc.Class.extend(/** @lends cc.Texture2D# */proto); - cc.Texture2D._generateGrayTexture = function(texture, rect, renderCanvas){ + cc.Texture2D._generateGrayTexture = function (texture, rect, renderCanvas) { if (texture === null) return null; renderCanvas = renderCanvas || document.createElement("canvas"); diff --git a/cocos2d/core/textures/CCTextureCache.js b/cocos2d/core/textures/CCTextureCache.js index dcef25dc39..19cac4b9fa 100644 --- a/cocos2d/core/textures/CCTextureCache.js +++ b/cocos2d/core/textures/CCTextureCache.js @@ -108,7 +108,7 @@ cc.textureCache = /** @lends cc.textureCache# */{ * //example * var key = cc.textureCache.getTextureForKey("hello.png"); */ - getTextureForKey: function(textureKeyName){ + getTextureForKey: function (textureKeyName) { return this._textures[textureKeyName] || this._textures[cc.loader._getAliase(textureKeyName)]; }, @@ -343,13 +343,12 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () { //remove judge var tex = locTexs[url] || locTexs[cc.loader._getAliase(url)]; if (tex) { - if(tex.isLoaded()) { + if (tex.isLoaded()) { cb && cb.call(target, tex); return tex; } - else - { - tex.addEventListener("load", function(){ + else { + tex.addEventListener("load", function () { cb && cb.call(target, tex); }, target); return tex; diff --git a/cocos2d/core/textures/TexturesWebGL.js b/cocos2d/core/textures/TexturesWebGL.js index cf6a2555de..bcec5bfb53 100644 --- a/cocos2d/core/textures/TexturesWebGL.js +++ b/cocos2d/core/textures/TexturesWebGL.js @@ -324,10 +324,10 @@ cc._tmp.WebGLTexture2D = function () { drawAtPoint: function (point) { var self = this; var coordinates = [ - 0.0, self.maxT, - self.maxS, self.maxT, - 0.0, 0.0, - self.maxS, 0.0 ], + 0.0, self.maxT, + self.maxS, self.maxT, + 0.0, 0.0, + self.maxS, 0.0], gl = cc._renderContext; var width = self._pixelsWide * self.maxS, @@ -337,7 +337,7 @@ cc._tmp.WebGLTexture2D = function () { point.x, point.y, 0.0, width + point.x, point.y, 0.0, point.x, height + point.y, 0.0, - width + point.x, height + point.y, 0.0 ]; + width + point.x, height + point.y, 0.0]; self._shaderProgram.use(); self._shaderProgram.setUniformsForBuiltins(); @@ -364,10 +364,10 @@ cc._tmp.WebGLTexture2D = function () { 0.0, 0.0, self.maxS, 0.0]; - var vertices = [ rect.x, rect.y, /*0.0,*/ + var vertices = [rect.x, rect.y, /*0.0,*/ rect.x + rect.width, rect.y, /*0.0,*/ rect.x, rect.y + rect.height, /*0.0,*/ - rect.x + rect.width, rect.y + rect.height /*0.0*/ ]; + rect.x + rect.width, rect.y + rect.height /*0.0*/]; self._shaderProgram.use(); self._shaderProgram.setUniformsForBuiltins(); @@ -451,9 +451,9 @@ cc._tmp.WebGLTexture2D = function () { handleLoadedTexture: function (premultiplied) { var self = this; premultiplied = - (premultiplied !== undefined) - ? premultiplied - : self._hasPremultipliedAlpha; + (premultiplied !== undefined) + ? premultiplied + : self._hasPremultipliedAlpha; // Not sure about this ! Some texture need to be updated even after loaded if (!cc.game._rendererInitialized) return; @@ -471,7 +471,7 @@ cc._tmp.WebGLTexture2D = function () { cc.glBindTexture2D(self); gl.pixelStorei(gl.UNPACK_ALIGNMENT, 4); - if(premultiplied) + if (premultiplied) gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1); // Specify OpenGL texture image @@ -484,7 +484,7 @@ cc._tmp.WebGLTexture2D = function () { self.shaderProgram = cc.shaderCache.programForKey(cc.SHADER_POSITION_TEXTURE); cc.glBindTexture2D(null); - if(premultiplied) + if (premultiplied) gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0); var pixelsWide = self._htmlElementObj.width; @@ -575,7 +575,7 @@ cc._tmp.WebGLTexture2D = function () { var _t = this; var gl = cc._renderContext; - if(magFilter !== undefined) + if (magFilter !== undefined) texParams = {minFilter: texParams, magFilter: magFilter, wrapS: wrapS, wrapT: wrapT}; cc.assert((_t._pixelsWide === cc.NextPOT(_t._pixelsWide) && _t._pixelsHigh === cc.NextPOT(_t._pixelsHigh)) || @@ -664,7 +664,6 @@ cc._tmp.WebGLTexture2D = function () { var imageSize = cc.size(uiImage.getWidth(), uiImage.getHeight()); var pixelFormat = tex2d.defaultPixelFormat; var bpp = uiImage.getBitsPerComponent(); - var i; // compute pixel format if (!hasAlpha) { @@ -677,7 +676,7 @@ cc._tmp.WebGLTexture2D = function () { } // Repack the pixel data into the right format - var length = width * height; + var i, length = width * height; if (pixelFormat === tex2d.PIXEL_FORMAT_RGB565) { if (hasAlpha) { @@ -688,8 +687,8 @@ cc._tmp.WebGLTexture2D = function () { for (i = 0; i < length; ++i) { tempData[i] = ((((inPixel32[i] >> 0) & 0xFF) >> 3) << 11) | // R - ((((inPixel32[i] >> 8) & 0xFF) >> 2) << 5) | // G - ((((inPixel32[i] >> 16) & 0xFF) >> 3) << 0); // B + ((((inPixel32[i] >> 8) & 0xFF) >> 2) << 5) | // G + ((((inPixel32[i] >> 16) & 0xFF) >> 3) << 0); // B } } else { // Convert "RRRRRRRRRGGGGGGGGBBBBBBBB" to "RRRRRGGGGGGBBBBB" @@ -699,8 +698,8 @@ cc._tmp.WebGLTexture2D = function () { for (i = 0; i < length; ++i) { tempData[i] = (((inPixel8[i] & 0xFF) >> 3) << 11) | // R - (((inPixel8[i] & 0xFF) >> 2) << 5) | // G - (((inPixel8[i] & 0xFF) >> 3) << 0); // B + (((inPixel8[i] & 0xFF) >> 2) << 5) | // G + (((inPixel8[i] & 0xFF) >> 3) << 0); // B } } } else if (pixelFormat === tex2d.PIXEL_FORMAT_RGBA4444) { @@ -711,9 +710,9 @@ cc._tmp.WebGLTexture2D = function () { for (i = 0; i < length; ++i) { tempData[i] = ((((inPixel32[i] >> 0) & 0xFF) >> 4) << 12) | // R - ((((inPixel32[i] >> 8) & 0xFF) >> 4) << 8) | // G - ((((inPixel32[i] >> 16) & 0xFF) >> 4) << 4) | // B - ((((inPixel32[i] >> 24) & 0xFF) >> 4) << 0); // A + ((((inPixel32[i] >> 8) & 0xFF) >> 4) << 8) | // G + ((((inPixel32[i] >> 16) & 0xFF) >> 4) << 4) | // B + ((((inPixel32[i] >> 24) & 0xFF) >> 4) << 0); // A } } else if (pixelFormat === tex2d.PIXEL_FORMAT_RGB5A1) { // Convert "RRRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA" to "RRRRRGGGGGBBBBBA" @@ -723,9 +722,9 @@ cc._tmp.WebGLTexture2D = function () { for (i = 0; i < length; ++i) { tempData[i] = ((((inPixel32[i] >> 0) & 0xFF) >> 3) << 11) | // R - ((((inPixel32[i] >> 8) & 0xFF) >> 3) << 6) | // G - ((((inPixel32[i] >> 16) & 0xFF) >> 3) << 1) | // B - ((((inPixel32[i] >> 24) & 0xFF) >> 7) << 0); // A + ((((inPixel32[i] >> 8) & 0xFF) >> 3) << 6) | // G + ((((inPixel32[i] >> 16) & 0xFF) >> 3) << 1) | // B + ((((inPixel32[i] >> 24) & 0xFF) >> 7) << 0); // A } } else if (pixelFormat === tex2d.PIXEL_FORMAT_A8) { // Convert "RRRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA" to "AAAAAAAA" @@ -827,7 +826,7 @@ cc._tmp.WebGLTextureAtlas = function () { // XXX: update is done in draw... perhaps it should be done in a timer gl.bindBuffer(gl.ARRAY_BUFFER, _t._quadsWebBuffer); - if (_t.dirty){ + if (_t.dirty) { gl.bufferData(gl.ARRAY_BUFFER, _t._quadsArrayBuffer, gl.DYNAMIC_DRAW); _t.dirty = false; } @@ -899,14 +898,13 @@ cc._tmp.WebGLTextureCache = function () { } var tex = locTexs[url] || locTexs[cc.loader._getAliase(url)]; if (tex) { - if(tex.isLoaded()) { + if (tex.isLoaded()) { cb && cb.call(target, tex); return tex; } - else - { - tex.addEventListener("load", function(){ - cb && cb.call(target, tex); + else { + tex.addEventListener("load", function () { + cb && cb.call(target, tex); }, target); return tex; } diff --git a/cocos2d/core/utils/CCProfiler.js b/cocos2d/core/utils/CCProfiler.js index 704f8697eb..923f1acff8 100644 --- a/cocos2d/core/utils/CCProfiler.js +++ b/cocos2d/core/utils/CCProfiler.js @@ -2,9 +2,9 @@ cc.profiler = (function () { var _showFPS = false; var _inited = false; var _frames = 0, _frameRate = 0, _lastSPF = 0, _accumDt = 0; - var _afterVisitListener = null, - _FPSLabel = document.createElement('div'), - _SPFLabel = document.createElement('div'), + var _afterVisitListener = null, + _FPSLabel = document.createElement('div'), + _SPFLabel = document.createElement('div'), _drawsLabel = document.createElement('div'), _fps = document.createElement('div'); @@ -47,7 +47,7 @@ cc.profiler = (function () { if (_analyseCount >= _levelDetCycle) { average = _totalFPS / _levelDetCycle; - for (i = lastId; i >0; i--) { + for (i = lastId; i > 0; i--) { ratio = _fpsCount[i] / _levelDetCycle; // Determined level if (ratio >= LEVEL_DET_FACTOR && average >= LEVELS[i]) { @@ -147,4 +147,4 @@ cc.profiler = (function () { }; return profiler; -})(); \ No newline at end of file +})(); diff --git a/cocos2d/effects/CCGrid.js b/cocos2d/effects/CCGrid.js index 8c5cd08a22..f6459a2269 100644 --- a/cocos2d/effects/CCGrid.js +++ b/cocos2d/effects/CCGrid.js @@ -31,18 +31,18 @@ * @extends cc.Class */ cc.GridBase = cc.Class.extend(/** @lends cc.GridBase# */{ - _active:false, - _reuseGrid:0, - _gridSize:null, - _gridRect:null, - _texture:null, - _step:null, - _grabber:null, - _isTextureFlipped:false, - _shaderProgram:null, - _directorProjection:0, - - _dirty:false, + _active: false, + _reuseGrid: 0, + _gridSize: null, + _gridRect: null, + _texture: null, + _step: null, + _grabber: null, + _isTextureFlipped: false, + _shaderProgram: null, + _directorProjection: 0, + + _dirty: false, /** * create one cc.GridBase Object @@ -52,21 +52,21 @@ cc.GridBase = cc.Class.extend(/** @lends cc.GridBase# */{ * @param {Boolean} [flipped=] * @param {cc.Rect} rect */ - ctor:function (gridSize, texture, flipped, rect) { + ctor: function (gridSize, texture, flipped, rect) { cc.sys._checkWebGLRenderMode(); - this._active=false; - this._reuseGrid=0; - this._gridSize=null; - this._gridRect=new cc.rect(); - this._texture=null; + this._active = false; + this._reuseGrid = 0; + this._gridSize = null; + this._gridRect = new cc.rect(); + this._texture = null; this._step = cc.p(0, 0); - this._grabber=null; - this._isTextureFlipped=false; - this._shaderProgram=null; - this._directorProjection=0; - this._dirty=false; + this._grabber = null; + this._isTextureFlipped = false; + this._shaderProgram = null; + this._directorProjection = 0; + this._dirty = false; - if(gridSize !== undefined) + if (gridSize !== undefined) this.initWithSize(gridSize, texture, flipped, rect); }, @@ -74,7 +74,7 @@ cc.GridBase = cc.Class.extend(/** @lends cc.GridBase# */{ * whether or not the grid is active * @return {Boolean} */ - isActive:function () { + isActive: function () { return this._active; }, @@ -82,7 +82,7 @@ cc.GridBase = cc.Class.extend(/** @lends cc.GridBase# */{ * whether or not the grid is active * @param {Number} active */ - setActive:function (active) { + setActive: function (active) { this._active = active; if (!active) { var director = cc.director; @@ -95,14 +95,14 @@ cc.GridBase = cc.Class.extend(/** @lends cc.GridBase# */{ * get number of times that the grid will be reused * @return {Number} */ - getReuseGrid:function () { + getReuseGrid: function () { return this._reuseGrid; }, /** * set number of times that the grid will be reused * @param reuseGrid */ - setReuseGrid:function (reuseGrid) { + setReuseGrid: function (reuseGrid) { this._reuseGrid = reuseGrid; }, @@ -110,7 +110,7 @@ cc.GridBase = cc.Class.extend(/** @lends cc.GridBase# */{ * get size of the grid * @return {cc.Size} */ - getGridSize:function () { + getGridSize: function () { return cc.size(this._gridSize.width, this._gridSize.height); }, @@ -118,7 +118,7 @@ cc.GridBase = cc.Class.extend(/** @lends cc.GridBase# */{ * set size of the grid * @param {cc.Size} gridSize */ - setGridSize:function (gridSize) { + setGridSize: function (gridSize) { this._gridSize.width = parseInt(gridSize.width); this._gridSize.height = parseInt(gridSize.height); }, @@ -127,7 +127,7 @@ cc.GridBase = cc.Class.extend(/** @lends cc.GridBase# */{ * set rect of the grid * @param {cc.Rect} rect */ - setGridRect:function (rect) { + setGridRect: function (rect) { this._gridRect = rect; }, @@ -135,7 +135,7 @@ cc.GridBase = cc.Class.extend(/** @lends cc.GridBase# */{ * get rect of the grid * @return {cc.Rect} rect */ - getGridRect:function () { + getGridRect: function () { return this._gridRect; }, @@ -143,7 +143,7 @@ cc.GridBase = cc.Class.extend(/** @lends cc.GridBase# */{ * get pixels between the grids * @return {cc.Point} */ - getStep:function () { + getStep: function () { return cc.p(this._step.x, this._step.y); }, @@ -151,7 +151,7 @@ cc.GridBase = cc.Class.extend(/** @lends cc.GridBase# */{ * set pixels between the grids * @param {cc.Point} step */ - setStep:function (step) { + setStep: function (step) { this._step.x = step.x; this._step.y = step.y; }, @@ -160,7 +160,7 @@ cc.GridBase = cc.Class.extend(/** @lends cc.GridBase# */{ * get whether or not the texture is flipped * @return {Boolean} */ - isTextureFlipped:function () { + isTextureFlipped: function () { return this._isTextureFlipped; }, @@ -168,7 +168,7 @@ cc.GridBase = cc.Class.extend(/** @lends cc.GridBase# */{ * set whether or not the texture is flipped * @param {Boolean} flipped */ - setTextureFlipped:function (flipped) { + setTextureFlipped: function (flipped) { if (this._isTextureFlipped !== flipped) { this._isTextureFlipped = flipped; this.calculateVertexPoints(); @@ -183,7 +183,7 @@ cc.GridBase = cc.Class.extend(/** @lends cc.GridBase# */{ * @param {cc.Rect} [rect=] * @returns {boolean} */ - initWithSize:function (gridSize, texture, flipped, rect) { + initWithSize: function (gridSize, texture, flipped, rect) { if (!texture) { var director = cc.director; var winSize = director.getWinSizeInPixels(); @@ -213,10 +213,9 @@ cc.GridBase = cc.Class.extend(/** @lends cc.GridBase# */{ this._gridSize = gridSize; this._texture = texture; this._isTextureFlipped = flipped; - if(rect === undefined || cc._rectEqualToZero(rect)) - { + if (rect === undefined || cc._rectEqualToZero(rect)) { var size = this._texture.getContentSize(); - rect = new cc.rect(0,0,size.width,size.height); + rect = new cc.rect(0, 0, size.width, size.height); } this._gridRect = rect; @@ -233,17 +232,17 @@ cc.GridBase = cc.Class.extend(/** @lends cc.GridBase# */{ return true; }, - beforeDraw:function () { + beforeDraw: function () { // save projection this._directorProjection = cc.director.getProjection(); //this.set2DProjection(); //TODO why? var size = cc.director.getWinSizeInPixels(); - gl.viewport(0, 0, size.width , size.height); + gl.viewport(0, 0, size.width, size.height); this._grabber.beforeRender(this._texture); }, - afterDraw:function (target) { + afterDraw: function (target) { this._grabber.afterRender(this._texture); // restore projection @@ -262,23 +261,23 @@ cc.GridBase = cc.Class.extend(/** @lends cc.GridBase# */{ afterBlit: function () { }, - blit:function () { + blit: function () { cc.log("cc.GridBase.blit(): Shall be overridden in subclass."); }, - reuse:function () { + reuse: function () { cc.log("cc.GridBase.reuse(): Shall be overridden in subclass."); }, - calculateVertexPoints:function () { + calculateVertexPoints: function () { cc.log("cc.GridBase.calculateVertexPoints(): Shall be overridden in subclass."); }, - set2DProjection:function () { + set2DProjection: function () { var winSize = cc.director.getWinSizeInPixels(); var gl = cc._renderContext; - gl.viewport(0, 0, winSize.width , winSize.height); + gl.viewport(0, 0, winSize.width, winSize.height); cc.kmGLMatrixMode(cc.KM_GL_PROJECTION); cc.kmGLLoadIdentity(); @@ -310,14 +309,14 @@ cc.GridBase.create = function (gridSize, texture, flipped, rect) { * @extends cc.GridBase */ cc.Grid3D = cc.GridBase.extend(/** @lends cc.Grid3D# */{ - _texCoordinates:null, - _vertices:null, - _originalVertices:null, - _indices:null, + _texCoordinates: null, + _vertices: null, + _originalVertices: null, + _indices: null, - _texCoordinateBuffer:null, - _verticesBuffer:null, - _indicesBuffer:null, + _texCoordinateBuffer: null, + _verticesBuffer: null, + _indicesBuffer: null, _needDepthTestForBlit: false, _oldDepthTestValue: false, @@ -331,21 +330,21 @@ cc.Grid3D = cc.GridBase.extend(/** @lends cc.Grid3D# */{ * @param {Boolean} [flipped=] * @param {cc.Rect} [rect=] */ - ctor:function (gridSize, texture, flipped, rect) { + ctor: function (gridSize, texture, flipped, rect) { cc.GridBase.prototype.ctor.call(this); - this._texCoordinates=null; - this._vertices=null; - this._originalVertices=null; - this._indices=null; + this._texCoordinates = null; + this._vertices = null; + this._originalVertices = null; + this._indices = null; - this._texCoordinateBuffer=null; - this._verticesBuffer=null; - this._indicesBuffer=null; + this._texCoordinateBuffer = null; + this._verticesBuffer = null; + this._indicesBuffer = null; this._matrix = new cc.math.Matrix4(); this._matrix.identity(); - if(gridSize !== undefined) + if (gridSize !== undefined) this.initWithSize(gridSize, texture, flipped, rect); }, @@ -355,8 +354,8 @@ cc.Grid3D = cc.GridBase.extend(/** @lends cc.Grid3D# */{ * @param {cc.Point} pos * @return {cc.Vertex3F} */ - vertex:function (pos) { - return this.getVertex(pos); + vertex: function (pos) { + return this.getVertex(pos); }, /** @@ -364,8 +363,8 @@ cc.Grid3D = cc.GridBase.extend(/** @lends cc.Grid3D# */{ * @param {cc.Point} pos * @return {cc.Vertex3F} */ - getVertex: function(pos){ - if(pos.x !== (0| pos.x) || pos.y !== (0| pos.y)) + getVertex: function (pos) { + if (pos.x !== (0 | pos.x) || pos.y !== (0 | pos.y)) cc.log("cc.Grid3D.vertex() : Numbers must be integers"); var index = 0 | ((pos.x * (this._gridSize.height + 1) + pos.y) * 3); var locVertices = this._vertices; @@ -378,7 +377,7 @@ cc.Grid3D = cc.GridBase.extend(/** @lends cc.Grid3D# */{ * @param {cc.Point} pos * @return {cc.Vertex3F} */ - originalVertex:function (pos) { + originalVertex: function (pos) { return this.getOriginalVertex(pos); }, @@ -387,8 +386,8 @@ cc.Grid3D = cc.GridBase.extend(/** @lends cc.Grid3D# */{ * @param {cc.Point} pos * @return {cc.Vertex3F} */ - getOriginalVertex: function(pos) { - if(pos.x !== (0| pos.x) || pos.y !== (0| pos.y)) + getOriginalVertex: function (pos) { + if (pos.x !== (0 | pos.x) || pos.y !== (0 | pos.y)) cc.log("cc.Grid3D.originalVertex() : Numbers must be integers"); var index = 0 | ((pos.x * (this._gridSize.height + 1) + pos.y) * 3); var locOriginalVertices = this._originalVertices; @@ -400,8 +399,8 @@ cc.Grid3D = cc.GridBase.extend(/** @lends cc.Grid3D# */{ * @param {cc.Point} pos * @param {cc.Vertex3F} vertex */ - setVertex:function (pos, vertex) { - if(pos.x !== (0| pos.x) || pos.y !== (0| pos.y)) + setVertex: function (pos, vertex) { + if (pos.x !== (0 | pos.x) || pos.y !== (0 | pos.y)) cc.log("cc.Grid3D.setVertex() : Numbers must be integers"); var index = 0 | ((pos.x * (this._gridSize.height + 1) + pos.y) * 3); var vertArray = this._vertices; @@ -433,7 +432,7 @@ cc.Grid3D = cc.GridBase.extend(/** @lends cc.Grid3D# */{ } }, - blit:function (target) { + blit: function (target) { var n = this._gridSize.width * this._gridSize.height; var wt = target._renderCmd._worldTransform; @@ -476,16 +475,16 @@ cc.Grid3D = cc.GridBase.extend(/** @lends cc.Grid3D# */{ cc.incrementGLDraws(1); }, - reuse:function () { + reuse: function () { if (this._reuseGrid > 0) { var locOriginalVertices = this._originalVertices, locVertices = this._vertices; - for (var i = 0, len = this._vertices.length; i < len; i++) + for (var i = 0, len = this._vertices.length; i < len; i++) locOriginalVertices[i] = locVertices[i]; --this._reuseGrid; } }, - calculateVertexPoints:function () { + calculateVertexPoints: function () { var gl = cc._renderContext; var width = this._texture.pixelsWidth; @@ -498,13 +497,13 @@ cc.Grid3D = cc.GridBase.extend(/** @lends cc.Grid3D# */{ this._texCoordinates = new Float32Array(numOfPoints * 2); this._indices = new Uint16Array(locGridSize.width * locGridSize.height * 6); - if(this._verticesBuffer) + if (this._verticesBuffer) gl.deleteBuffer(this._verticesBuffer); this._verticesBuffer = gl.createBuffer(); - if(this._texCoordinateBuffer) + if (this._texCoordinateBuffer) gl.deleteBuffer(this._texCoordinateBuffer); this._texCoordinateBuffer = gl.createBuffer(); - if(this._indicesBuffer) + if (this._indicesBuffer) gl.deleteBuffer(this._indicesBuffer); this._indicesBuffer = gl.createBuffer(); @@ -531,10 +530,10 @@ cc.Grid3D = cc.GridBase.extend(/** @lends cc.Grid3D# */{ locIndices[idx * 6 + 5] = d; var l1 = [a * 3, b * 3, c * 3, d * 3]; - var e = {x:x1, y:y1, z:0}; //new cc.Vertex3F(x1, y1, 0); - var f = {x:x2, y:y1, z:0}; //new cc.Vertex3F(x2, y1, 0); - var g = {x:x2, y:y2, z:0}; // new cc.Vertex3F(x2, y2, 0); - var h = {x:x1, y:y2, z:0}; //new cc.Vertex3F(x1, y2, 0); + var e = {x: x1, y: y1, z: 0}; //new cc.Vertex3F(x1, y1, 0); + var f = {x: x2, y: y1, z: 0}; //new cc.Vertex3F(x2, y1, 0); + var g = {x: x2, y: y2, z: 0}; // new cc.Vertex3F(x2, y2, 0); + var h = {x: x1, y: y2, z: 0}; //new cc.Vertex3F(x1, y2, 0); var l2 = [e, f, g, h]; var tex1 = [a * 2, b * 2, c * 2, d * 2]; @@ -562,11 +561,11 @@ cc.Grid3D = cc.GridBase.extend(/** @lends cc.Grid3D# */{ this._dirty = true; }, - setNeedDepthTestForBlit: function(needDepthTest){ + setNeedDepthTestForBlit: function (needDepthTest) { this._needDepthTestForBlit = needDepthTest; }, - getNeedDepthTestForBlit: function(){ + getNeedDepthTestForBlit: function () { return this._needDepthTestForBlit; } }); @@ -590,14 +589,14 @@ cc.Grid3D.create = function (gridSize, texture, flipped) { * @extends cc.GridBase */ cc.TiledGrid3D = cc.GridBase.extend(/** @lends cc.TiledGrid3D# */{ - _texCoordinates:null, - _vertices:null, - _originalVertices:null, - _indices:null, + _texCoordinates: null, + _vertices: null, + _originalVertices: null, + _indices: null, - _texCoordinateBuffer:null, - _verticesBuffer:null, - _indicesBuffer:null, + _texCoordinateBuffer: null, + _verticesBuffer: null, + _indicesBuffer: null, /** * create one TiledGrid3D object @@ -606,21 +605,21 @@ cc.TiledGrid3D = cc.GridBase.extend(/** @lends cc.TiledGrid3D# */{ * @param {cc.Texture2D} [texture=] * @param {Boolean} [flipped=] */ - ctor:function (gridSize, texture, flipped, rect) { + ctor: function (gridSize, texture, flipped, rect) { cc.GridBase.prototype.ctor.call(this); - this._texCoordinates=null; - this._vertices=null; - this._originalVertices=null; - this._indices=null; + this._texCoordinates = null; + this._vertices = null; + this._originalVertices = null; + this._indices = null; - this._texCoordinateBuffer=null; - this._verticesBuffer=null; - this._indicesBuffer=null; + this._texCoordinateBuffer = null; + this._verticesBuffer = null; + this._indicesBuffer = null; this._matrix = new cc.math.Matrix4(); this._matrix.identity(); - if(gridSize !== undefined) + if (gridSize !== undefined) this.initWithSize(gridSize, texture, flipped, rect); }, @@ -630,7 +629,7 @@ cc.TiledGrid3D = cc.GridBase.extend(/** @lends cc.TiledGrid3D# */{ * @param {cc.Point} pos * @return {cc.Quad3} */ - tile:function (pos) { + tile: function (pos) { return this.getTile(pos); }, @@ -639,15 +638,15 @@ cc.TiledGrid3D = cc.GridBase.extend(/** @lends cc.TiledGrid3D# */{ * @param {cc.Point} pos * @return {cc.Quad3} */ - getTile: function(pos){ - if(pos.x !== (0| pos.x) || pos.y !== (0| pos.y)) + getTile: function (pos) { + if (pos.x !== (0 | pos.x) || pos.y !== (0 | pos.y)) cc.log("cc.TiledGrid3D.tile() : Numbers must be integers"); var idx = (this._gridSize.height * pos.x + pos.y) * 4 * 3; var locVertices = this._vertices; return new cc.Quad3(new cc.Vertex3F(locVertices[idx], locVertices[idx + 1], locVertices[idx + 2]), new cc.Vertex3F(locVertices[idx + 3], locVertices[idx + 4], locVertices[idx + 5]), - new cc.Vertex3F(locVertices[idx + 6 ], locVertices[idx + 7], locVertices[idx + 8]), + new cc.Vertex3F(locVertices[idx + 6], locVertices[idx + 7], locVertices[idx + 8]), new cc.Vertex3F(locVertices[idx + 9], locVertices[idx + 10], locVertices[idx + 11])); }, @@ -656,15 +655,15 @@ cc.TiledGrid3D = cc.GridBase.extend(/** @lends cc.TiledGrid3D# */{ * @param {cc.Point} pos * @return {cc.Quad3} */ - getOriginalTile:function (pos) { - if(pos.x !== (0| pos.x) || pos.y !== (0| pos.y)) + getOriginalTile: function (pos) { + if (pos.x !== (0 | pos.x) || pos.y !== (0 | pos.y)) cc.log("cc.TiledGrid3D.originalTile() : Numbers must be integers"); var idx = (this._gridSize.height * pos.x + pos.y) * 4 * 3; var locOriginalVertices = this._originalVertices; return new cc.Quad3(new cc.Vertex3F(locOriginalVertices[idx], locOriginalVertices[idx + 1], locOriginalVertices[idx + 2]), new cc.Vertex3F(locOriginalVertices[idx + 3], locOriginalVertices[idx + 4], locOriginalVertices[idx + 5]), - new cc.Vertex3F(locOriginalVertices[idx + 6 ], locOriginalVertices[idx + 7], locOriginalVertices[idx + 8]), + new cc.Vertex3F(locOriginalVertices[idx + 6], locOriginalVertices[idx + 7], locOriginalVertices[idx + 8]), new cc.Vertex3F(locOriginalVertices[idx + 9], locOriginalVertices[idx + 10], locOriginalVertices[idx + 11])); }, @@ -674,7 +673,7 @@ cc.TiledGrid3D = cc.GridBase.extend(/** @lends cc.TiledGrid3D# */{ * @param {cc.Point} pos * @return {cc.Quad3} */ - originalTile: function(pos) { + originalTile: function (pos) { return this.getOriginalTile(pos); }, @@ -683,8 +682,8 @@ cc.TiledGrid3D = cc.GridBase.extend(/** @lends cc.TiledGrid3D# */{ * @param {cc.Point} pos * @param {cc.Quad3} coords */ - setTile:function (pos, coords) { - if(pos.x !== (0| pos.x) || pos.y !== (0| pos.y)) + setTile: function (pos, coords) { + if (pos.x !== (0 | pos.x) || pos.y !== (0 | pos.y)) cc.log("cc.TiledGrid3D.setTile() : Numbers must be integers"); var idx = (this._gridSize.height * pos.x + pos.y) * 12; @@ -747,7 +746,7 @@ cc.TiledGrid3D = cc.GridBase.extend(/** @lends cc.TiledGrid3D# */{ cc.incrementGLDraws(1); }, - reuse:function () { + reuse: function () { if (this._reuseGrid > 0) { var locVertices = this._vertices, locOriginalVertices = this._originalVertices; for (var i = 0; i < locVertices.length; i++) @@ -756,7 +755,7 @@ cc.TiledGrid3D = cc.GridBase.extend(/** @lends cc.TiledGrid3D# */{ } }, - calculateVertexPoints:function () { + calculateVertexPoints: function () { var width = this._texture.pixelsWidth; var height = this._texture.pixelsHeight; var imageH = this._texture.getContentSizeInPixels().height; @@ -768,13 +767,13 @@ cc.TiledGrid3D = cc.GridBase.extend(/** @lends cc.TiledGrid3D# */{ this._indices = new Uint16Array(numQuads * 6); var gl = cc._renderContext; - if(this._verticesBuffer) + if (this._verticesBuffer) gl.deleteBuffer(this._verticesBuffer); this._verticesBuffer = gl.createBuffer(); - if(this._texCoordinateBuffer) + if (this._texCoordinateBuffer) gl.deleteBuffer(this._texCoordinateBuffer); this._texCoordinateBuffer = gl.createBuffer(); - if(this._indicesBuffer) + if (this._indicesBuffer) gl.deleteBuffer(this._indicesBuffer); this._indicesBuffer = gl.createBuffer(); diff --git a/cocos2d/kazmath/gl/mat4stack.js b/cocos2d/kazmath/gl/mat4stack.js index ecd3aceba3..962f3d6ece 100644 --- a/cocos2d/kazmath/gl/mat4stack.js +++ b/cocos2d/kazmath/gl/mat4stack.js @@ -26,14 +26,14 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -(function(cc){ +(function (cc) { /** * The stack of cc.math.Matrix4 * @param {cc.math.Matrix4} [top] * @param {Array} [stack] * @constructor */ - cc.math.Matrix4Stack = function(top, stack) { + cc.math.Matrix4Stack = function (top, stack) { this.top = top; this.stack = stack || []; //this._matrixPool = []; // use pool in next version @@ -41,39 +41,39 @@ cc.km_mat4_stack = cc.math.Matrix4Stack; var proto = cc.math.Matrix4Stack.prototype; - proto.initialize = function() { //cc.km_mat4_stack_initialize + proto.initialize = function () { //cc.km_mat4_stack_initialize this.stack.length = 0; this.top = null; }; //for compatibility - cc.km_mat4_stack_push = function(stack, item){ + cc.km_mat4_stack_push = function (stack, item) { stack.stack.push(stack.top); stack.top = new cc.math.Matrix4(item); }; - cc.km_mat4_stack_pop = function(stack, pOut){ + cc.km_mat4_stack_pop = function (stack, pOut) { stack.top = stack.stack.pop(); }; - cc.km_mat4_stack_release = function(stack){ + cc.km_mat4_stack_release = function (stack) { stack.stack = null; stack.top = null; }; - proto.push = function(item) { + proto.push = function (item) { item = item || this.top; this.stack.push(this.top); this.top = new cc.math.Matrix4(item); //this.top = this._getFromPool(item); }; - proto.pop = function() { + proto.pop = function () { //this._putInPool(this.top); this.top = this.stack.pop(); }; - proto.release = function(){ + proto.release = function () { this.stack = null; this.top = null; this._matrixPool = null; @@ -88,7 +88,7 @@ return ret; }; - proto._putInPool = function(matrix){ + proto._putInPool = function (matrix) { this._matrixPool.push(matrix); }; })(cc); diff --git a/cocos2d/kazmath/gl/matrix.js b/cocos2d/kazmath/gl/matrix.js index ae2605db06..38f111f583 100644 --- a/cocos2d/kazmath/gl/matrix.js +++ b/cocos2d/kazmath/gl/matrix.js @@ -26,7 +26,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -(function(cc) { +(function (cc) { cc.KM_GL_MODELVIEW = 0x1700; cc.KM_GL_PROJECTION = 0x1701; cc.KM_GL_TEXTURE = 0x1702; diff --git a/cocos2d/labels/CCLabelAtlasWebGLRenderCmd.js b/cocos2d/labels/CCLabelAtlasWebGLRenderCmd.js index 9a7484d1ba..5edf6c501b 100644 --- a/cocos2d/labels/CCLabelAtlasWebGLRenderCmd.js +++ b/cocos2d/labels/CCLabelAtlasWebGLRenderCmd.js @@ -22,8 +22,8 @@ THE SOFTWARE. ****************************************************************************/ -(function(){ - cc.LabelAtlas.WebGLRenderCmd = function(renderable){ +(function () { + cc.LabelAtlas.WebGLRenderCmd = function (renderable) { cc.AtlasNode.WebGLRenderCmd.call(this, renderable); this._needDraw = true; }; @@ -50,13 +50,13 @@ } }; - proto.setCascade = function(){ + proto.setCascade = function () { var node = this._node; node._cascadeOpacityEnabled = true; node._cascadeColorEnabled = true; }; - proto.rendering = function(ctx){ + proto.rendering = function (ctx) { cc.AtlasNode.WebGLRenderCmd.prototype.rendering.call(this, ctx); if (cc.LABELATLAS_DEBUG_DRAW) { var node = this._node; @@ -64,15 +64,15 @@ var locRect = node.getBoundingBoxToWorld(); var posX = locRect.x, posY = locRect.y; - s.width = locRect.width; - s.height = locRect.height; - var vertices = [cc.p(posX, posY), cc.p(posX+ s.width, posY), - cc.p(s.width+posX, s.height+posY), cc.p(posX, posY+s.height)]; + s.width = locRect.width; + s.height = locRect.height; + var vertices = [cc.p(posX, posY), cc.p(posX + s.width, posY), + cc.p(s.width + posX, s.height + posY), cc.p(posX, posY + s.height)]; cc._drawingUtil.drawPoly(vertices, 4, true); } }; - proto.updateAtlasValues = function(){ + proto.updateAtlasValues = function () { var node = this._node; var locString = node._string; var n = locString.length; @@ -96,9 +96,9 @@ var a = locString.charCodeAt(i) - node._mapStartChar.charCodeAt(0); var row = a % node._itemsPerRow; var col = 0 | (a / node._itemsPerRow); - if(row < 0 || col < 0) + if (row < 0 || col < 0) continue; - if(row*locItemWidth + locItemWidth > textureWide || col*locItemHeight + locItemHeight > textureHigh) + if (row * locItemWidth + locItemWidth > textureWide || col * locItemHeight + locItemHeight > textureHigh) continue; cr++; @@ -142,7 +142,7 @@ this._updateColor(); - this.updateContentSize(i, cr+1); + this.updateContentSize(i, cr + 1); if (n > 0) { locTextureAtlas.dirty = true; var totalQuads = locTextureAtlas.totalQuads; @@ -151,19 +151,20 @@ } }; - proto.updateContentSize = function(i, cr){ + proto.updateContentSize = function (i, cr) { var node = this._node, contentSize = node._contentSize; - if(i !== cr && i*node._itemWidth === contentSize.width && node._itemHeight === contentSize.height){ + if (i !== cr && i * node._itemWidth === contentSize.width && node._itemHeight === contentSize.height) { node.setContentSize(cr * node._itemWidth, node._itemHeight); } }; - proto.setString = function(label){ + proto.setString = function (label) { var len = label.length; if (len > this._textureAtlas.totalQuads) this._textureAtlas.resizeCapacity(len); }; - proto._addChild = function(){}; -})(); \ No newline at end of file + proto._addChild = function () { + }; +})(); diff --git a/cocos2d/labels/CCLabelBMFont.js b/cocos2d/labels/CCLabelBMFont.js index 97608769c1..d583bfef24 100644 --- a/cocos2d/labels/CCLabelBMFont.js +++ b/cocos2d/labels/CCLabelBMFont.js @@ -106,8 +106,8 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{ _textureLoaded: false, _className: "LabelBMFont", - _createRenderCmd: function(){ - if(cc._renderType === cc.game.RENDER_TYPE_WEBGL) + _createRenderCmd: function () { + if (cc._renderType === cc.game.RENDER_TYPE_WEBGL) return new cc.LabelBMFont.WebGLRenderCmd(this); else return new cc.LabelBMFont.CanvasRenderCmd(this); @@ -366,7 +366,7 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{ //If the last character processed has an xAdvance which is less that the width of the characters image, then we need // to adjust the width of the string to take this into account, or the character will overlap the end of the bounding box - if(fontDef && fontDef.xAdvance < fontDef.rect.width) + if (fontDef && fontDef.xAdvance < fontDef.rect.width) tmpSize.width = longestLine - fontDef.xAdvance + fontDef.rect.width; else tmpSize.width = longestLine; @@ -434,9 +434,8 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{ }, // calc the text all with in a line - _getCharsWidth:function (startIndex, endIndex) { - if (endIndex <= 0) - { + _getCharsWidth: function (startIndex, endIndex) { + if (endIndex <= 0) { return 0; } var curTextFirstSprite = this.getChildByTag(startIndex); @@ -444,12 +443,11 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{ return this._getLetterPosXLeft(curTextLastSprite) - this._getLetterPosXLeft(curTextFirstSprite); }, - _checkWarp:function (strArr, i, maxWidth, initStringWrapNum) { + _checkWarp: function (strArr, i, maxWidth, initStringWrapNum) { var self = this; var text = strArr[i]; var curLength = 0; - for (var strArrIndex = 0; strArrIndex < i; strArrIndex++) - { + for (var strArrIndex = 0; strArrIndex < i; strArrIndex++) { curLength += strArr[strArrIndex].length; } @@ -554,8 +552,7 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{ if (oldArrLength < stringArr.length) { newWrapNum++; } - if (i > 0) - { + if (i > 0) { wrapString += "\n"; } wrapString += stringArr[i]; @@ -739,7 +736,7 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{ return this._fntFile; }, - setTexture: function(texture){ + setTexture: function (texture) { this._texture = texture; this._renderCmd.setTexture(texture); }, @@ -766,7 +763,8 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{ this.updateLabel(); }, - _atlasNameFromFntFile: function (fntFile) {}, + _atlasNameFromFntFile: function (fntFile) { + }, _kerningAmountForFirst: function (first, second) { var ret = 0; @@ -788,14 +786,14 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{ }, //Checking whether the character is a whitespace - _isspace_unicode: function(ch){ + _isspace_unicode: function (ch) { ch = ch.charCodeAt(0); return ((ch >= 9 && ch <= 13) || ch === 32 || ch === 133 || ch === 160 || ch === 5760 || (ch >= 8192 && ch <= 8202) || ch === 8232 || ch === 8233 || ch === 8239 || ch === 8287 || ch === 12288) }, - _utf8_trim_ws: function(str){ + _utf8_trim_ws: function (str) { var len = str.length; if (len <= 0) @@ -819,7 +817,7 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{ //Trims str st str=[0, index) after the operation. //Return value: the trimmed string. - _utf8_trim_from: function(str, index){ + _utf8_trim_from: function (str, index) { var len = str.length; if (index >= len || index < 0) return; @@ -827,7 +825,7 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{ } }); -(function(){ +(function () { var p = cc.LabelBMFont.prototype; cc.EventHelper.prototype.apply(p); diff --git a/cocos2d/labels/CCLabelBMFontCanvasRenderCmd.js b/cocos2d/labels/CCLabelBMFontCanvasRenderCmd.js index 1f34cd6cb4..e824bc1941 100644 --- a/cocos2d/labels/CCLabelBMFontCanvasRenderCmd.js +++ b/cocos2d/labels/CCLabelBMFontCanvasRenderCmd.js @@ -38,7 +38,7 @@ var proto = cc.LabelBMFont.CanvasRenderCmd.prototype = Object.create(cc.Node.CanvasRenderCmd.prototype); proto.constructor = cc.LabelBMFont.CanvasRenderCmd; - proto._updateCharTexture = function(fontChar, rect, key){ + proto._updateCharTexture = function (fontChar, rect, key) { if (key === 32) { fontChar.setTextureRect(rect, false, cc.size(0, 0)); } else { @@ -49,7 +49,7 @@ } }; - proto._updateCharColorAndOpacity = function(fontChar){ + proto._updateCharColorAndOpacity = function (fontChar) { // Color MUST be set before opacity, since opacity might change color if OpacityModifyRGB is on fontChar._displayedColor = this._displayedColor; fontChar._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.colorDirty); @@ -73,7 +73,7 @@ node._texture = texture; }; - proto._changeTextureColor = function(){ + proto._changeTextureColor = function () { var node = this._node; var texture = node._texture, contentSize = texture.getContentSize(); @@ -83,19 +83,19 @@ var disColor = this._displayedColor; var textureRect = cc.rect(0, 0, oElement.width, oElement.height); if (texture && contentSize.width > 0) { - if(!oElement) + if (!oElement) return; var textureToRender = oTexture._generateColorTexture(disColor.r, disColor.g, disColor.b, textureRect); node.setTexture(textureToRender); } }; - proto._updateChildrenDisplayedOpacity = function(locChild){ + proto._updateChildrenDisplayedOpacity = function (locChild) { cc.Node.prototype.updateDisplayedOpacity.call(locChild, this._displayedOpacity); }; - proto._updateChildrenDisplayedColor = function(locChild){ + proto._updateChildrenDisplayedColor = function (locChild) { cc.Node.prototype.updateDisplayedColor.call(locChild, this._displayedColor); }; -})(); \ No newline at end of file +})(); diff --git a/cocos2d/labels/CCLabelBMFontWebGLRenderCmd.js b/cocos2d/labels/CCLabelBMFontWebGLRenderCmd.js index 68d5c374a7..e255e60e4d 100644 --- a/cocos2d/labels/CCLabelBMFontWebGLRenderCmd.js +++ b/cocos2d/labels/CCLabelBMFontWebGLRenderCmd.js @@ -42,14 +42,16 @@ this._node.setOpacityModifyRGB(this._node._texture.hasPremultipliedAlpha()); }; - proto._updateCharTexture = function(fontChar, rect, key){ + proto._updateCharTexture = function (fontChar, rect, key) { // updating previous sprite fontChar.setTextureRect(rect, false); // restore to default in case they were modified fontChar.visible = true; }; - proto._changeTextureColor = function(){}; + proto._changeTextureColor = function () { + }; - proto._updateCharColorAndOpacity = function(){}; -})(); \ No newline at end of file + proto._updateCharColorAndOpacity = function () { + }; +})(); diff --git a/cocos2d/menus/CCMenu.js b/cocos2d/menus/CCMenu.js index 6cf5703760..6df7b838eb 100644 --- a/cocos2d/menus/CCMenu.js +++ b/cocos2d/menus/CCMenu.js @@ -281,8 +281,8 @@ cc.Menu = cc.Layer.extend(/** @lends cc.Menu# */{ if ((arguments.length > 0) && (arguments[arguments.length - 1] == null)) cc.log("parameters should not be ending with null in Javascript"); - var rows = []; - for (var i = 0; i < arguments.length; i++) { + var i, rows = []; + for (i = 0; i < arguments.length; i++) { rows.push(arguments[i]); } var height = -5; @@ -363,7 +363,7 @@ cc.Menu = cc.Layer.extend(/** @lends cc.Menu# */{ alignItemsInRows: function (/*Multiple arguments*/) { if ((arguments.length > 0) && (arguments[arguments.length - 1] == null)) cc.log("parameters should not be ending with null in Javascript"); - var columns = [], i; + var i, columns = []; for (i = 0; i < arguments.length; i++) { columns.push(arguments[i]); } @@ -558,7 +558,7 @@ cc.Menu = cc.Layer.extend(/** @lends cc.Menu# */{ }, /** * only use for jsbinding - * @returns {boolean} + * @returns {boolean} */ isOpacityModifyRGB: function () { return false; diff --git a/cocos2d/motion-streak/CCMotionStreak.js b/cocos2d/motion-streak/CCMotionStreak.js index 1553aa4c2a..158393454a 100644 --- a/cocos2d/motion-streak/CCMotionStreak.js +++ b/cocos2d/motion-streak/CCMotionStreak.js @@ -44,33 +44,33 @@ * new cc.MotionStreak(2, 3, 32, cc.color.GREEN, s_streak); */ cc.MotionStreak = cc.Node.extend(/** @lends cc.MotionStreak# */{ - texture:null, - fastMode:false, - startingPositionInitialized:false, + texture: null, + fastMode: false, + startingPositionInitialized: false, - _blendFunc:null, + _blendFunc: null, - _stroke:0, - _fadeDelta:0, - _minSeg:0, + _stroke: 0, + _fadeDelta: 0, + _minSeg: 0, - _maxPoints:0, - _nuPoints:0, - _previousNuPoints:0, + _maxPoints: 0, + _nuPoints: 0, + _previousNuPoints: 0, /* Pointers */ - _pointVertexes:null, - _pointState:null, + _pointVertexes: null, + _pointState: null, // webgl - _vertices:null, - _colorPointer:null, - _texCoords:null, + _vertices: null, + _colorPointer: null, + _texCoords: null, - _verticesBuffer:null, - _colorPointerBuffer:null, - _texCoordsBuffer:null, - _className:"MotionStreak", + _verticesBuffer: null, + _colorPointerBuffer: null, + _texCoordsBuffer: null, + _className: "MotionStreak", /** * creates and initializes a motion streak with fade in seconds, minimum segments, stroke's width, color, texture filename or texture
@@ -112,7 +112,7 @@ cc.MotionStreak = cc.Node.extend(/** @lends cc.MotionStreak# */{ this._colorPointerBuffer = null; this._texCoordsBuffer = null; - if(texture !== undefined) + if (texture !== undefined) this.initWithFade(fade, minSeg, stroke, color, texture); }, @@ -120,7 +120,7 @@ cc.MotionStreak = cc.Node.extend(/** @lends cc.MotionStreak# */{ * Gets the texture. * @return {cc.Texture2D} */ - getTexture:function () { + getTexture: function () { return this.texture; }, @@ -128,7 +128,7 @@ cc.MotionStreak = cc.Node.extend(/** @lends cc.MotionStreak# */{ * Set the texture. * @param {cc.Texture2D} texture */ - setTexture:function (texture) { + setTexture: function (texture) { if (this.texture !== texture) this.texture = texture; }, @@ -137,7 +137,7 @@ cc.MotionStreak = cc.Node.extend(/** @lends cc.MotionStreak# */{ * Gets the blend func. * @return {cc.BlendFunc} */ - getBlendFunc:function () { + getBlendFunc: function () { return this._blendFunc; }, @@ -146,7 +146,7 @@ cc.MotionStreak = cc.Node.extend(/** @lends cc.MotionStreak# */{ * @param {Number} src * @param {Number} dst */ - setBlendFunc:function (src, dst) { + setBlendFunc: function (src, dst) { if (dst === undefined) { this._blendFunc = src; } else { @@ -160,7 +160,7 @@ cc.MotionStreak = cc.Node.extend(/** @lends cc.MotionStreak# */{ * @warning cc.MotionStreak.getOpacity has not been supported. * @returns {number} */ - getOpacity:function () { + getOpacity: function () { cc.log("cc.MotionStreak.getOpacity has not been supported."); return 0; }, @@ -170,7 +170,7 @@ cc.MotionStreak = cc.Node.extend(/** @lends cc.MotionStreak# */{ * @warning cc.MotionStreak.setOpacity has not been supported. * @param opacity */ - setOpacity:function (opacity) { + setOpacity: function (opacity) { cc.log("cc.MotionStreak.setOpacity has not been supported."); }, @@ -179,14 +179,14 @@ cc.MotionStreak = cc.Node.extend(/** @lends cc.MotionStreak# */{ * @warning cc.MotionStreak.setOpacityModifyRGB has not been supported. * @param value */ - setOpacityModifyRGB:function (value) { + setOpacityModifyRGB: function (value) { }, /** * Checking OpacityModifyRGB. * @returns {boolean} */ - isOpacityModifyRGB:function () { + isOpacityModifyRGB: function () { return false; }, @@ -194,7 +194,7 @@ cc.MotionStreak = cc.Node.extend(/** @lends cc.MotionStreak# */{ * Checking fast mode. * @returns {boolean} */ - isFastMode:function () { + isFastMode: function () { return this.fastMode; }, @@ -202,7 +202,7 @@ cc.MotionStreak = cc.Node.extend(/** @lends cc.MotionStreak# */{ * set fast mode * @param {Boolean} fastMode */ - setFastMode:function (fastMode) { + setFastMode: function (fastMode) { this.fastMode = fastMode; }, @@ -210,7 +210,7 @@ cc.MotionStreak = cc.Node.extend(/** @lends cc.MotionStreak# */{ * Checking starting position initialized. * @returns {boolean} */ - isStartingPositionInitialized:function () { + isStartingPositionInitialized: function () { return this.startingPositionInitialized; }, @@ -218,7 +218,7 @@ cc.MotionStreak = cc.Node.extend(/** @lends cc.MotionStreak# */{ * Set Starting Position Initialized. * @param {Boolean} startingPositionInitialized */ - setStartingPositionInitialized:function (startingPositionInitialized) { + setStartingPositionInitialized: function (startingPositionInitialized) { this.startingPositionInitialized = startingPositionInitialized; }, @@ -226,7 +226,7 @@ cc.MotionStreak = cc.Node.extend(/** @lends cc.MotionStreak# */{ * Get stroke. * @returns {Number} stroke */ - getStroke:function () { + getStroke: function () { return this._stroke; }, @@ -234,7 +234,7 @@ cc.MotionStreak = cc.Node.extend(/** @lends cc.MotionStreak# */{ * Set stroke. * @param {Number} stroke */ - setStroke:function (stroke) { + setStroke: function (stroke) { this._stroke = stroke; }, @@ -247,14 +247,14 @@ cc.MotionStreak = cc.Node.extend(/** @lends cc.MotionStreak# */{ * @param {string|cc.Texture2D} texture texture filename or texture * @return {Boolean} */ - initWithFade:function (fade, minSeg, stroke, color, texture) { - if(!texture) + initWithFade: function (fade, minSeg, stroke, color, texture) { + if (!texture) throw new Error("cc.MotionStreak.initWithFade(): Invalid filename or texture"); if (cc.isString(texture)) texture = cc.textureCache.addImage(texture); - cc.Node.prototype.setPosition.call(this, cc.p(0,0)); + cc.Node.prototype.setPosition.call(this, cc.p(0, 0)); this.anchorX = 0; this.anchorY = 0; this.ignoreAnchor = true; @@ -304,7 +304,7 @@ cc.MotionStreak = cc.Node.extend(/** @lends cc.MotionStreak# */{ * color used for the tint * @param {cc.Color} color */ - tintWithColor:function (color) { + tintWithColor: function (color) { this.color = color; // Fast assignation @@ -319,7 +319,7 @@ cc.MotionStreak = cc.Node.extend(/** @lends cc.MotionStreak# */{ /** * Remove all living segments of the ribbon */ - reset:function () { + reset: function () { this._nuPoints = 0; }, @@ -329,9 +329,9 @@ cc.MotionStreak = cc.Node.extend(/** @lends cc.MotionStreak# */{ * @param {cc.Point|Number} position * @param {Number} [yValue=undefined] If not exists, the first parameter must be cc.Point. */ - setPosition:function (position, yValue) { + setPosition: function (position, yValue) { this.startingPositionInitialized = true; - if(yValue === undefined){ + if (yValue === undefined) { this._positionR.x = position.x; this._positionR.y = position.y; } else { @@ -344,7 +344,7 @@ cc.MotionStreak = cc.Node.extend(/** @lends cc.MotionStreak# */{ * Gets the position.x * @return {Number} */ - getPositionX:function () { + getPositionX: function () { return this._positionR.x; }, @@ -352,9 +352,9 @@ cc.MotionStreak = cc.Node.extend(/** @lends cc.MotionStreak# */{ * Set the position.x * @param {Number} x */ - setPositionX:function (x) { + setPositionX: function (x) { this._positionR.x = x; - if(!this.startingPositionInitialized) + if (!this.startingPositionInitialized) this.startingPositionInitialized = true; }, @@ -362,17 +362,17 @@ cc.MotionStreak = cc.Node.extend(/** @lends cc.MotionStreak# */{ * Gets the position.y * @return {Number} */ - getPositionY:function () { - return this._positionR.y; + getPositionY: function () { + return this._positionR.y; }, /** * Set the position.y * @param {Number} y */ - setPositionY:function (y) { + setPositionY: function (y) { this._positionR.y = y; - if(!this.startingPositionInitialized) + if (!this.startingPositionInitialized) this.startingPositionInitialized = true; }, @@ -383,7 +383,7 @@ cc.MotionStreak = cc.Node.extend(/** @lends cc.MotionStreak# */{ * Only one "update" method could be scheduled per node.

* @param {Number} delta */ - update:function (delta) { + update: function (delta) { if (!this.startingPositionInitialized) return; @@ -392,7 +392,7 @@ cc.MotionStreak = cc.Node.extend(/** @lends cc.MotionStreak# */{ delta *= this._fadeDelta; - var newIdx, newIdx2, i, i2; + var i, newIdx, newIdx2, i2; var mov = 0; // Update current points @@ -447,7 +447,7 @@ cc.MotionStreak = cc.Node.extend(/** @lends cc.MotionStreak# */{ appendNewPoint = false; else if (locNuPoints > 0) { var a1 = cc.pDistanceSQ(cc.p(locPointVertexes[(locNuPoints - 1) * 2], locPointVertexes[(locNuPoints - 1) * 2 + 1]), - this._positionR) < this._minSeg; + this._positionR) < this._minSeg; var a2 = (locNuPoints === 1) ? false : (cc.pDistanceSQ( cc.p(locPointVertexes[(locNuPoints - 2) * 2], locPointVertexes[(locNuPoints - 2) * 2 + 1]), this._positionR) < (this._minSeg * 2.0)); if (a1 || a2) @@ -506,8 +506,8 @@ cc.MotionStreak = cc.Node.extend(/** @lends cc.MotionStreak# */{ this._nuPoints = locNuPoints; }, - _createRenderCmd: function(){ - if(cc._renderType === cc.game.RENDER_TYPE_WEBGL) + _createRenderCmd: function () { + if (cc._renderType === cc.game.RENDER_TYPE_WEBGL) return new cc.MotionStreak.WebGLRenderCmd(this); else return null; //MotionStreak doesn't support Canvas mode diff --git a/cocos2d/motion-streak/CCMotionStreakWebGLRenderCmd.js b/cocos2d/motion-streak/CCMotionStreakWebGLRenderCmd.js index 69f4f12f5f..50ddcffd69 100644 --- a/cocos2d/motion-streak/CCMotionStreakWebGLRenderCmd.js +++ b/cocos2d/motion-streak/CCMotionStreakWebGLRenderCmd.js @@ -33,7 +33,7 @@ cc.MotionStreak.WebGLRenderCmd = function(renderableObject){ cc.MotionStreak.WebGLRenderCmd.prototype = Object.create(cc.Node.WebGLRenderCmd.prototype); cc.MotionStreak.WebGLRenderCmd.prototype.constructor = cc.Sprite.WebGLRenderCmd; -cc.MotionStreak.WebGLRenderCmd.prototype.rendering = function(ctx){ +cc.MotionStreak.WebGLRenderCmd.prototype.rendering = function (ctx) { var node = this._node; if (node._nuPoints <= 1) return; @@ -77,4 +77,4 @@ cc.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/CCNodeGridWebGLRenderCmd.js b/cocos2d/node-grid/CCNodeGridWebGLRenderCmd.js index 8c45377dfe..bf51ee5e56 100644 --- a/cocos2d/node-grid/CCNodeGridWebGLRenderCmd.js +++ b/cocos2d/node-grid/CCNodeGridWebGLRenderCmd.js @@ -33,15 +33,15 @@ var proto = cc.NodeGrid.WebGLRenderCmd.prototype = Object.create(cc.Node.WebGLRenderCmd.prototype); proto.constructor = cc.NodeGrid.WebGLRenderCmd; - proto.visit = function(parentCmd) { + proto.visit = function (parentCmd) { var node = this._node; // 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; + if (parentCmd) + this._curLevel = parentCmd._curLevel + 1; var currentStack = cc.current_stack; currentStack.stack.push(currentStack.top); @@ -49,16 +49,16 @@ currentStack.top = this._stackMatrix; /*var beforeProjectionType = cc.director.PROJECTION_DEFAULT; - if (locGrid && locGrid._active) { - //var backMatrix = new cc.kmMat4(); - //cc.kmMat4Assign(backMatrix, this._stackMatrix); + if (locGrid && locGrid._active) { + //var backMatrix = new cc.kmMat4(); + //cc.kmMat4Assign(backMatrix, this._stackMatrix); - beforeProjectionType = cc.director.getProjection(); - //locGrid.set2DProjection(); + beforeProjectionType = cc.director.getProjection(); + //locGrid.set2DProjection(); - //reset this._stackMatrix to current_stack.top - //cc.kmMat4Assign(currentStack.top, backMatrix); - }*/ + //reset this._stackMatrix to current_stack.top + //cc.kmMat4Assign(currentStack.top, backMatrix); + }*/ cc.renderer.pushRenderCommand(this._gridBeginCommand); if (node._target) @@ -76,7 +76,7 @@ } //if (locGrid && locGrid._active) { - //cc.director.setProjection(beforeProjectionType); + //cc.director.setProjection(beforeProjectionType); //} cc.renderer.pushRenderCommand(this._gridEndCommand); @@ -84,13 +84,13 @@ currentStack.top = currentStack.stack.pop(); }; - proto.onGridBeginDraw = function(){ + proto.onGridBeginDraw = function () { var locGrid = this._node.grid; if (locGrid && locGrid._active) locGrid.beforeDraw(); }; - proto.onGridEndDraw = function(){ + proto.onGridEndDraw = function () { var locGrid = this._node.grid; if (locGrid && locGrid._active) locGrid.afterDraw(this._node); diff --git a/cocos2d/parallax/CCParallaxNodeRenderCmd.js b/cocos2d/parallax/CCParallaxNodeRenderCmd.js index d8fd5d89ed..53f3ccf6c7 100644 --- a/cocos2d/parallax/CCParallaxNodeRenderCmd.js +++ b/cocos2d/parallax/CCParallaxNodeRenderCmd.js @@ -33,35 +33,35 @@ var proto = cc.ParallaxNode.CanvasRenderCmd.prototype = Object.create(cc.Node.CanvasRenderCmd.prototype); proto.constructor = cc.ParallaxNode.CanvasRenderCmd; - proto.updateStatus = function(){ + proto.updateStatus = function () { this._node._updateParallaxPosition(); cc.Node.CanvasRenderCmd.prototype.updateStatus.call(this); }; - proto._syncStatus = function(parentCmd){ + proto._syncStatus = function (parentCmd) { this._node._updateParallaxPosition(); this._originSyncStatus(parentCmd); }; })(); cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () { - if(cc._renderType !== cc.game.RENDER_TYPE_WEBGL) + if (cc._renderType !== cc.game.RENDER_TYPE_WEBGL) return; - cc.ParallaxNode.WebGLRenderCmd = function(renderable){ - cc.Node.WebGLRenderCmd.call(this, renderable); + cc.ParallaxNode.WebGLRenderCmd = function (renderable) { + this._rootCtor(renderable); this._needDraw = false; }; var proto = cc.ParallaxNode.WebGLRenderCmd.prototype = Object.create(cc.Node.WebGLRenderCmd.prototype); proto.constructor = cc.ParallaxNode.WebGLRenderCmd; - proto.updateStatus = function(){ + proto.updateStatus = function () { this._node._updateParallaxPosition(); cc.Node.WebGLRenderCmd.prototype.updateStatus.call(this); }; - proto._syncStatus = function(parentCmd){ + proto._syncStatus = function (parentCmd) { this._node._updateParallaxPosition(); this._originSyncStatus(parentCmd); }; diff --git a/cocos2d/particle/CCParticleBatchNode.js b/cocos2d/particle/CCParticleBatchNode.js index 1a2200f93e..b92d6d5a09 100644 --- a/cocos2d/particle/CCParticleBatchNode.js +++ b/cocos2d/particle/CCParticleBatchNode.js @@ -71,10 +71,10 @@ cc.PARTICLE_DEFAULT_CAPACITY = 500; * var particleBatchNode = new cc.ParticleBatchNode(texture, 30); */ cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{ - textureAtlas:null, + textureAtlas: null, //the blend function used for drawing the quads - _blendFunc:null, - _className:"ParticleBatchNode", + _blendFunc: null, + _className: "ParticleBatchNode", /** * initializes the particle system with the name of a file on disk (for a list of supported formats look at the cc.Texture2D class), a capacity of particles @@ -91,9 +91,9 @@ cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{ * var texture = cc.TextureCache.getInstance().addImage("res/grossini_dance.png"); * var particleBatchNode = new cc.ParticleBatchNode(texture, 30); */ - ctor:function (fileImage, capacity) { + ctor: function (fileImage, capacity) { cc.Node.prototype.ctor.call(this); - this._blendFunc = {src:cc.BLEND_SRC, dst:cc.BLEND_DST}; + this._blendFunc = {src: cc.BLEND_SRC, dst: cc.BLEND_DST}; if (cc.isString(fileImage)) { this.init(fileImage, capacity); } else if (fileImage instanceof cc.Texture2D) { @@ -101,8 +101,8 @@ cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{ } }, - _createRenderCmd: function(){ - if(cc._renderType === cc.game.RENDER_TYPE_CANVAS) + _createRenderCmd: function () { + if (cc._renderType === cc.game.RENDER_TYPE_CANVAS) return new cc.ParticleBatchNode.CanvasRenderCmd(this); else return new cc.ParticleBatchNode.WebGLRenderCmd(this); @@ -114,7 +114,7 @@ cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{ * @param {Number} capacity * @return {Boolean} */ - initWithTexture:function (texture, capacity) { + initWithTexture: function (texture, capacity) { this.textureAtlas = new cc.TextureAtlas(); this.textureAtlas.initWithTexture(texture, capacity); @@ -131,7 +131,7 @@ cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{ * @param {Number} capacity * @return {Boolean} */ - initWithFile:function (fileImage, capacity) { + initWithFile: function (fileImage, capacity) { var tex = cc.textureCache.addImage(fileImage); return this.initWithTexture(tex, capacity); }, @@ -142,7 +142,7 @@ cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{ * @param {Number} capacity * @return {Boolean} */ - init:function (fileImage, capacity) { + init: function (fileImage, capacity) { var tex = cc.textureCache.addImage(fileImage); return this.initWithTexture(tex, capacity); }, @@ -153,23 +153,23 @@ cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{ * @param {Number} zOrder * @param {Number} tag */ - addChild:function (child, zOrder, tag) { - if(!child) + addChild: function (child, zOrder, tag) { + if (!child) throw new Error("cc.ParticleBatchNode.addChild() : child should be non-null"); - if(!(child instanceof cc.ParticleSystem)) + if (!(child instanceof cc.ParticleSystem)) throw new Error("cc.ParticleBatchNode.addChild() : only supports cc.ParticleSystem as children"); zOrder = (zOrder == null) ? child.zIndex : zOrder; tag = (tag == null) ? child.tag : tag; - if(child.getTexture() !== this.textureAtlas.texture) + if (child.getTexture() !== this.textureAtlas.texture) throw new Error("cc.ParticleSystem.addChild() : the child is not using the same texture id"); // If this is the 1st children, then copy blending function var childBlendFunc = child.getBlendFunc(); if (this._children.length === 0) this.setBlendFunc(childBlendFunc); - else{ - if((childBlendFunc.src !== this._blendFunc.src) || (childBlendFunc.dst !== this._blendFunc.dst)){ + else { + if ((childBlendFunc.src !== this._blendFunc.src) || (childBlendFunc.dst !== this._blendFunc.dst)) { cc.log("cc.ParticleSystem.addChild() : Can't add a ParticleSystem that uses a different blending function"); return; } @@ -198,7 +198,7 @@ cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{ * @param {cc.ParticleSystem} pSystem * @param {Number} index */ - insertChild:function (pSystem, index) { + insertChild: function (pSystem, index) { var totalParticles = pSystem.getTotalParticles(); var locTextureAtlas = this.textureAtlas; var totalQuads = locTextureAtlas.totalQuads; @@ -222,14 +222,14 @@ cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{ * @param {cc.ParticleSystem} child * @param {Boolean} cleanup */ - removeChild:function (child, cleanup) { + removeChild: function (child, cleanup) { // explicit nil handling if (child == null) return; - if(!(child instanceof cc.ParticleSystem)) + if (!(child instanceof cc.ParticleSystem)) throw new Error("cc.ParticleBatchNode.removeChild(): only supports cc.ParticleSystem as children"); - if(this._children.indexOf(child) === -1){ + if (this._children.indexOf(child) === -1) { cc.log("cc.ParticleBatchNode.removeChild(): doesn't contain the sprite. Can't remove it"); return; } @@ -254,12 +254,12 @@ cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{ * @param {cc.ParticleSystem} child * @param {Number} zOrder */ - reorderChild:function (child, zOrder) { - if(!child) + reorderChild: function (child, zOrder) { + if (!child) throw new Error("cc.ParticleBatchNode.reorderChild(): child should be non-null"); - if(!(child instanceof cc.ParticleSystem)) + if (!(child instanceof cc.ParticleSystem)) throw new Error("cc.ParticleBatchNode.reorderChild(): only supports cc.QuadParticleSystems as children"); - if(this._children.indexOf(child) === -1){ + if (this._children.indexOf(child) === -1) { cc.log("cc.ParticleBatchNode.reorderChild(): Child doesn't belong to batch"); return; } @@ -306,14 +306,14 @@ cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{ * @param {Number} index * @param {Boolean} doCleanup */ - removeChildAtIndex:function (index, doCleanup) { + removeChildAtIndex: function (index, doCleanup) { this.removeChild(this._children[i], doCleanup); }, /** * @param {Boolean} [doCleanup=true] */ - removeAllChildren:function (doCleanup) { + removeAllChildren: function (doCleanup) { var locChildren = this._children; for (var i = 0; i < locChildren.length; i++) { locChildren[i].setBatchNode(null); @@ -326,7 +326,7 @@ cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{ * disables a particle by inserting a 0'd quad into the texture atlas * @param {Number} particleIndex */ - disableParticle:function (particleIndex) { + disableParticle: function (particleIndex) { var quad = this.textureAtlas.quads[particleIndex]; quad.br.vertices.x = quad.br.vertices.y = quad.tr.vertices.x = quad.tr.vertices.y = quad.tl.vertices.x = quad.tl.vertices.y = quad.bl.vertices.x = quad.bl.vertices.y = 0.0; @@ -337,7 +337,7 @@ cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{ * returns the used texture * @return {cc.Texture2D} */ - getTexture:function () { + getTexture: function () { return this.textureAtlas.texture; }, @@ -345,7 +345,7 @@ cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{ * sets a new texture. it will be retained * @param {cc.Texture2D} texture */ - setTexture:function (texture) { + setTexture: function (texture) { this.textureAtlas.texture = texture; // If the new texture has No premultiplied alpha, AND the blendFunc hasn't been changed, then update it @@ -361,11 +361,11 @@ cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{ * @param {Number|Object} src * @param {Number} dst */ - setBlendFunc:function (src, dst) { - if (dst === undefined){ + setBlendFunc: function (src, dst) { + if (dst === undefined) { this._blendFunc.src = src.src; this._blendFunc.dst = src.dst; - } else{ + } else { this._blendFunc.src = src; this._blendFunc.src = dst; } @@ -375,11 +375,11 @@ cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{ * returns the blending function used for the texture * @return {cc.BlendFunc} */ - getBlendFunc:function () { + getBlendFunc: function () { return new cc.BlendFunc(this._blendFunc.src, this._blendFunc.dst); }, - _updateAllAtlasIndexes:function () { + _updateAllAtlasIndexes: function () { var index = 0; var locChildren = this._children; for (var i = 0; i < locChildren.length; i++) { @@ -389,7 +389,7 @@ cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{ } }, - _increaseAtlasCapacityTo:function (quantity) { + _increaseAtlasCapacityTo: function (quantity) { cc.log("cocos2d: cc.ParticleBatchNode: resizing TextureAtlas capacity from [" + this.textureAtlas.getCapacity() + "] to [" + quantity + "]."); @@ -399,7 +399,7 @@ cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{ } }, - _searchNewPositionInChildrenForZ:function (z) { + _searchNewPositionInChildrenForZ: function (z) { var locChildren = this._children; var count = locChildren.length; for (var i = 0; i < count; i++) { @@ -409,7 +409,7 @@ cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{ return count; }, - _getCurrentIndex:function (child, z) { + _getCurrentIndex: function (child, z) { var foundCurrentIdx = false; var foundNewIdx = false; @@ -441,7 +441,7 @@ cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{ if (!foundNewIdx) newIndex = count; newIndex += minusOne; - return {newIndex:newIndex, oldIndex:oldIndex}; + return {newIndex: newIndex, oldIndex: oldIndex}; }, // @@ -457,10 +457,10 @@ cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{ // @return {Number} // @private // - _addChildHelper:function (child, z, aTag) { - if(!child) + _addChildHelper: function (child, z, aTag) { + if (!child) throw new Error("cc.ParticleBatchNode._addChildHelper(): child should be non-null"); - if(child.parent){ + if (child.parent) { cc.log("cc.ParticleBatchNode._addChildHelper(): child already added. It can't be added again"); return null; } @@ -483,7 +483,7 @@ cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{ return pos; }, - _updateBlendFunc:function () { + _updateBlendFunc: function () { if (!this.textureAtlas.texture.hasPremultipliedAlpha()) { this._blendFunc.src = cc.SRC_ALPHA; this._blendFunc.dst = cc.ONE_MINUS_SRC_ALPHA; @@ -494,7 +494,7 @@ cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{ * return the texture atlas used for drawing the quads * @return {cc.TextureAtlas} */ - getTextureAtlas:function () { + getTextureAtlas: function () { return this.textureAtlas; }, @@ -502,7 +502,7 @@ cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{ * set the texture atlas used for drawing the quads * @param {cc.TextureAtlas} textureAtlas */ - setTextureAtlas:function (textureAtlas) { + setTextureAtlas: function (textureAtlas) { this.textureAtlas = textureAtlas; } }); diff --git a/cocos2d/particle/CCParticleBatchNodeCanvasRenderCmd.js b/cocos2d/particle/CCParticleBatchNodeCanvasRenderCmd.js index 36da185ecb..341e16ad9e 100644 --- a/cocos2d/particle/CCParticleBatchNodeCanvasRenderCmd.js +++ b/cocos2d/particle/CCParticleBatchNodeCanvasRenderCmd.js @@ -22,7 +22,7 @@ THE SOFTWARE. ****************************************************************************/ -(function(){ +(function () { /** * cc.ParticleBatchNode's rendering objects of Canvas */ @@ -34,5 +34,6 @@ var proto = cc.ParticleBatchNode.CanvasRenderCmd.prototype = Object.create(cc.Node.CanvasRenderCmd.prototype); proto.constructor = cc.ParticleBatchNode.CanvasRenderCmd; - proto._initWithTexture = function(){}; + proto._initWithTexture = function () { + }; })(); diff --git a/cocos2d/particle/CCParticleBatchNodeWebGLRenderCmd.js b/cocos2d/particle/CCParticleBatchNodeWebGLRenderCmd.js index 44cea2f052..df376ce113 100644 --- a/cocos2d/particle/CCParticleBatchNodeWebGLRenderCmd.js +++ b/cocos2d/particle/CCParticleBatchNodeWebGLRenderCmd.js @@ -22,7 +22,7 @@ THE SOFTWARE. ****************************************************************************/ -(function(){ +(function () { /** * cc.ParticleBatchNode's rendering objects of WebGL */ @@ -55,7 +55,7 @@ _t.textureAtlas.drawQuads(); }; - proto._initWithTexture = function(){ + proto._initWithTexture = function () { this._shaderProgram = cc.shaderCache.programForKey(cc.SHADER_POSITION_TEXTURECOLOR); }; @@ -80,4 +80,4 @@ this._dirtyFlag = 0; }; -})(); \ No newline at end of file +})(); diff --git a/cocos2d/particle/CCParticleSystem.js b/cocos2d/particle/CCParticleSystem.js index 6239d7adaa..2e8d079d1a 100644 --- a/cocos2d/particle/CCParticleSystem.js +++ b/cocos2d/particle/CCParticleSystem.js @@ -64,10 +64,10 @@ * @param {cc.Particle.ModeA} [modeB=] */ cc.Particle = function (pos, startPos, color, deltaColor, size, deltaSize, rotation, deltaRotation, timeToLive, atlasIndex, modeA, modeB) { - this.pos = pos ? pos : cc.p(0,0); - this.startPos = startPos ? startPos : cc.p(0,0); - this.color = color ? color : {r:0, g: 0, b:0, a:255}; - this.deltaColor = deltaColor ? deltaColor : {r:0, g: 0, b:0, a:255} ; + this.pos = pos ? pos : cc.p(0, 0); + this.startPos = startPos ? startPos : cc.p(0, 0); + this.color = color ? color : {r: 0, g: 0, b: 0, a: 255}; + this.deltaColor = deltaColor ? deltaColor : {r: 0, g: 0, b: 0, a: 255}; this.size = size || 0; this.deltaSize = deltaSize || 0; this.rotation = rotation || 0; @@ -89,7 +89,7 @@ cc.Particle = function (pos, startPos, color, deltaColor, size, deltaSize, rotat * @param {Number} tangentialAccel */ cc.Particle.ModeA = function (dir, radialAccel, tangentialAccel) { - this.dir = dir ? dir : cc.p(0,0); + this.dir = dir ? dir : cc.p(0, 0); this.radialAccel = radialAccel || 0; this.tangentialAccel = tangentialAccel || 0; }; @@ -111,8 +111,8 @@ cc.Particle.ModeB = function (angle, degreesPerSecond, radius, deltaRadius) { }; /** - * Array of Point instances used to optimize particle updates - */ + * Array of Point instances used to optimize particle updates + */ cc.Particle.TemporaryPoints = [ cc.p(), cc.p(), @@ -211,7 +211,7 @@ cc.Particle.TemporaryPoints = [ * emitter.startSpin = 0; */ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ - _className:"ParticleSystem", + _className: "ParticleSystem", //***********variables************* _plistFile: "", //! time elapsed since the start of the system (in seconds) @@ -285,12 +285,12 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * Constructor of cc.ParticleSystem * @param {String|Number} plistFile */ - ctor:function (plistFile) { + ctor: function (plistFile) { cc.Node.prototype.ctor.call(this); this.emitterMode = cc.ParticleSystem.MODE_GRAVITY; this.modeA = new cc.ParticleSystem.ModeA(); this.modeB = new cc.ParticleSystem.ModeB(); - this._blendFunc = {src:cc.BLEND_SRC, dst:cc.BLEND_DST}; + this._blendFunc = {src: cc.BLEND_SRC, dst: cc.BLEND_DST}; this._particles = []; this._sourcePosition = cc.p(0, 0); @@ -348,8 +348,8 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ } }, - _createRenderCmd: function(){ - if(cc._renderType === cc.game.RENDER_TYPE_CANVAS) + _createRenderCmd: function () { + if (cc._renderType === cc.game.RENDER_TYPE_CANVAS) return new cc.ParticleSystem.CanvasRenderCmd(this); else return new cc.ParticleSystem.WebGLRenderCmd(this); @@ -360,8 +360,8 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * It's very expensive to change color on Canvas mode, so if set it to true, particle system will ignore the changing color operation. * @param {boolean} ignore */ - ignoreColor: function(ignore){ - this._dontTint = ignore; + ignoreColor: function (ignore) { + this._dontTint = ignore; }, /** @@ -370,7 +370,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ *

* @param {cc.Rect} pointRect */ - initTexCoordsWithRect:function (pointRect) { + initTexCoordsWithRect: function (pointRect) { this._renderCmd.initTexCoordsWithRect(pointRect); }, @@ -378,7 +378,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * return weak reference to the cc.SpriteBatchNode that renders the cc.Sprite * @return {cc.ParticleBatchNode} */ - getBatchNode:function () { + getBatchNode: function () { return this._batchNode; }, @@ -386,7 +386,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * set weak reference to the cc.SpriteBatchNode that renders the cc.Sprite * @param {cc.ParticleBatchNode} batchNode */ - setBatchNode:function (batchNode) { + setBatchNode: function (batchNode) { this._renderCmd.setBatchNode(batchNode); }, @@ -394,7 +394,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * return index of system in batch node array * @return {Number} */ - getAtlasIndex:function () { + getAtlasIndex: function () { return this.atlasIndex; }, @@ -402,7 +402,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * set index of system in batch node array * @param {Number} atlasIndex */ - setAtlasIndex:function (atlasIndex) { + setAtlasIndex: function (atlasIndex) { this.atlasIndex = atlasIndex; }, @@ -410,7 +410,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * Return DrawMode of ParticleSystem (Canvas Mode only) * @return {Number} */ - getDrawMode:function () { + getDrawMode: function () { return this._renderCmd.getDrawMode(); }, @@ -418,7 +418,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * DrawMode of ParticleSystem setter (Canvas Mode only) * @param {Number} drawMode */ - setDrawMode:function (drawMode) { + setDrawMode: function (drawMode) { this._renderCmd.setDrawMode(drawMode); }, @@ -426,7 +426,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * Return ShapeType of ParticleSystem (Canvas Mode only) * @return {Number} */ - getShapeType:function () { + getShapeType: function () { return this._renderCmd.getShapeType(); }, @@ -434,7 +434,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * ShapeType of ParticleSystem setter (Canvas Mode only) * @param {Number} shapeType */ - setShapeType:function (shapeType) { + setShapeType: function (shapeType) { this._renderCmd.setShapeType(shapeType); }, @@ -442,7 +442,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * Return ParticleSystem is active * @return {Boolean} */ - isActive:function () { + isActive: function () { return this._isActive; }, @@ -450,7 +450,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * Quantity of particles that are being simulated at the moment * @return {Number} */ - getParticleCount:function () { + getParticleCount: function () { return this.particleCount; }, @@ -458,7 +458,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * Quantity of particles setter * @param {Number} particleCount */ - setParticleCount:function (particleCount) { + setParticleCount: function (particleCount) { this.particleCount = particleCount; }, @@ -466,7 +466,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * How many seconds the emitter wil run. -1 means 'forever' * @return {Number} */ - getDuration:function () { + getDuration: function () { return this.duration; }, @@ -474,7 +474,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * set run seconds of the emitter * @param {Number} duration */ - setDuration:function (duration) { + setDuration: function (duration) { this.duration = duration; }, @@ -482,7 +482,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * Return sourcePosition of the emitter * @return {cc.Point | Object} */ - getSourcePosition:function () { + getSourcePosition: function () { return {x: this._sourcePosition.x, y: this._sourcePosition.y}; }, @@ -498,7 +498,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * Return Position variance of the emitter * @return {cc.Point | Object} */ - getPosVar:function () { + getPosVar: function () { return {x: this._posVar.x, y: this._posVar.y}; }, @@ -506,7 +506,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * Position variance of the emitter setter * @param {cc.Point} posVar */ - setPosVar:function (posVar) { + setPosVar: function (posVar) { this._posVar = posVar; }, @@ -514,7 +514,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * Return life of each particle * @return {Number} */ - getLife:function () { + getLife: function () { return this.life; }, @@ -522,7 +522,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * life of each particle setter * @param {Number} life */ - setLife:function (life) { + setLife: function (life) { this.life = life; }, @@ -530,7 +530,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * Return life variance of each particle * @return {Number} */ - getLifeVar:function () { + getLifeVar: function () { return this.lifeVar; }, @@ -538,7 +538,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * life variance of each particle setter * @param {Number} lifeVar */ - setLifeVar:function (lifeVar) { + setLifeVar: function (lifeVar) { this.lifeVar = lifeVar; }, @@ -546,7 +546,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * Return angle of each particle * @return {Number} */ - getAngle:function () { + getAngle: function () { return this.angle; }, @@ -554,7 +554,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * angle of each particle setter * @param {Number} angle */ - setAngle:function (angle) { + setAngle: function (angle) { this.angle = angle; }, @@ -562,7 +562,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * Return angle variance of each particle * @return {Number} */ - getAngleVar:function () { + getAngleVar: function () { return this.angleVar; }, @@ -570,7 +570,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * angle variance of each particle setter * @param angleVar */ - setAngleVar:function (angleVar) { + setAngleVar: function (angleVar) { this.angleVar = angleVar; }, @@ -579,8 +579,8 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * Return Gravity of emitter * @return {cc.Point} */ - getGravity:function () { - if(this.emitterMode !== cc.ParticleSystem.MODE_GRAVITY) + getGravity: function () { + if (this.emitterMode !== cc.ParticleSystem.MODE_GRAVITY) cc.log("cc.ParticleBatchNode.getGravity() : Particle Mode should be Gravity"); var locGravity = this.modeA.gravity; return cc.p(locGravity.x, locGravity.y); @@ -590,8 +590,8 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * Gravity of emitter setter * @param {cc.Point} gravity */ - setGravity:function (gravity) { - if(this.emitterMode !== cc.ParticleSystem.MODE_GRAVITY) + setGravity: function (gravity) { + if (this.emitterMode !== cc.ParticleSystem.MODE_GRAVITY) cc.log("cc.ParticleBatchNode.setGravity() : Particle Mode should be Gravity"); this.modeA.gravity = gravity; }, @@ -600,8 +600,8 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * Return Speed of each particle * @return {Number} */ - getSpeed:function () { - if(this.emitterMode !== cc.ParticleSystem.MODE_GRAVITY) + getSpeed: function () { + if (this.emitterMode !== cc.ParticleSystem.MODE_GRAVITY) cc.log("cc.ParticleBatchNode.getSpeed() : Particle Mode should be Gravity"); return this.modeA.speed; }, @@ -610,8 +610,8 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * Speed of each particle setter * @param {Number} speed */ - setSpeed:function (speed) { - if(this.emitterMode !== cc.ParticleSystem.MODE_GRAVITY) + setSpeed: function (speed) { + if (this.emitterMode !== cc.ParticleSystem.MODE_GRAVITY) cc.log("cc.ParticleBatchNode.setSpeed() : Particle Mode should be Gravity"); this.modeA.speed = speed; }, @@ -620,8 +620,8 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * return speed variance of each particle. Only available in 'Gravity' mode. * @return {Number} */ - getSpeedVar:function () { - if(this.emitterMode !== cc.ParticleSystem.MODE_GRAVITY) + getSpeedVar: function () { + if (this.emitterMode !== cc.ParticleSystem.MODE_GRAVITY) cc.log("cc.ParticleBatchNode.getSpeedVar() : Particle Mode should be Gravity"); return this.modeA.speedVar; }, @@ -630,8 +630,8 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * speed variance of each particle setter. Only available in 'Gravity' mode. * @param {Number} speedVar */ - setSpeedVar:function (speedVar) { - if(this.emitterMode !== cc.ParticleSystem.MODE_GRAVITY) + setSpeedVar: function (speedVar) { + if (this.emitterMode !== cc.ParticleSystem.MODE_GRAVITY) cc.log("cc.ParticleBatchNode.setSpeedVar() : Particle Mode should be Gravity"); this.modeA.speedVar = speedVar; }, @@ -640,8 +640,8 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * Return tangential acceleration of each particle. Only available in 'Gravity' mode. * @return {Number} */ - getTangentialAccel:function () { - if(this.emitterMode !== cc.ParticleSystem.MODE_GRAVITY) + getTangentialAccel: function () { + if (this.emitterMode !== cc.ParticleSystem.MODE_GRAVITY) cc.log("cc.ParticleBatchNode.getTangentialAccel() : Particle Mode should be Gravity"); return this.modeA.tangentialAccel; }, @@ -650,8 +650,8 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * Tangential acceleration of each particle setter. Only available in 'Gravity' mode. * @param {Number} tangentialAccel */ - setTangentialAccel:function (tangentialAccel) { - if(this.emitterMode !== cc.ParticleSystem.MODE_GRAVITY) + setTangentialAccel: function (tangentialAccel) { + if (this.emitterMode !== cc.ParticleSystem.MODE_GRAVITY) cc.log("cc.ParticleBatchNode.setTangentialAccel() : Particle Mode should be Gravity"); this.modeA.tangentialAccel = tangentialAccel; }, @@ -660,8 +660,8 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * Return tangential acceleration variance of each particle. Only available in 'Gravity' mode. * @return {Number} */ - getTangentialAccelVar:function () { - if(this.emitterMode !== cc.ParticleSystem.MODE_GRAVITY) + getTangentialAccelVar: function () { + if (this.emitterMode !== cc.ParticleSystem.MODE_GRAVITY) cc.log("cc.ParticleBatchNode.getTangentialAccelVar() : Particle Mode should be Gravity"); return this.modeA.tangentialAccelVar; }, @@ -670,8 +670,8 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * tangential acceleration variance of each particle setter. Only available in 'Gravity' mode. * @param {Number} tangentialAccelVar */ - setTangentialAccelVar:function (tangentialAccelVar) { - if(this.emitterMode !== cc.ParticleSystem.MODE_GRAVITY) + setTangentialAccelVar: function (tangentialAccelVar) { + if (this.emitterMode !== cc.ParticleSystem.MODE_GRAVITY) cc.log("cc.ParticleBatchNode.setTangentialAccelVar() : Particle Mode should be Gravity"); this.modeA.tangentialAccelVar = tangentialAccelVar; }, @@ -680,8 +680,8 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * Return radial acceleration of each particle. Only available in 'Gravity' mode. * @return {Number} */ - getRadialAccel:function () { - if(this.emitterMode !== cc.ParticleSystem.MODE_GRAVITY) + getRadialAccel: function () { + if (this.emitterMode !== cc.ParticleSystem.MODE_GRAVITY) cc.log("cc.ParticleBatchNode.getRadialAccel() : Particle Mode should be Gravity"); return this.modeA.radialAccel; }, @@ -690,8 +690,8 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * radial acceleration of each particle setter. Only available in 'Gravity' mode. * @param {Number} radialAccel */ - setRadialAccel:function (radialAccel) { - if(this.emitterMode !== cc.ParticleSystem.MODE_GRAVITY) + setRadialAccel: function (radialAccel) { + if (this.emitterMode !== cc.ParticleSystem.MODE_GRAVITY) cc.log("cc.ParticleBatchNode.setRadialAccel() : Particle Mode should be Gravity"); this.modeA.radialAccel = radialAccel; }, @@ -700,8 +700,8 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * Return radial acceleration variance of each particle. Only available in 'Gravity' mode. * @return {Number} */ - getRadialAccelVar:function () { - if(this.emitterMode !== cc.ParticleSystem.MODE_GRAVITY) + getRadialAccelVar: function () { + if (this.emitterMode !== cc.ParticleSystem.MODE_GRAVITY) cc.log("cc.ParticleBatchNode.getRadialAccelVar() : Particle Mode should be Gravity"); return this.modeA.radialAccelVar; }, @@ -710,8 +710,8 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * radial acceleration variance of each particle setter. Only available in 'Gravity' mode. * @param {Number} radialAccelVar */ - setRadialAccelVar:function (radialAccelVar) { - if(this.emitterMode !== cc.ParticleSystem.MODE_GRAVITY) + setRadialAccelVar: function (radialAccelVar) { + if (this.emitterMode !== cc.ParticleSystem.MODE_GRAVITY) cc.log("cc.ParticleBatchNode.setRadialAccelVar() : Particle Mode should be Gravity"); this.modeA.radialAccelVar = radialAccelVar; }, @@ -720,8 +720,8 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * get the rotation of each particle to its direction Only available in 'Gravity' mode. * @returns {boolean} */ - getRotationIsDir: function(){ - if(this.emitterMode !== cc.ParticleSystem.MODE_GRAVITY) + getRotationIsDir: function () { + if (this.emitterMode !== cc.ParticleSystem.MODE_GRAVITY) cc.log("cc.ParticleBatchNode.getRotationIsDir() : Particle Mode should be Gravity"); return this.modeA.rotationIsDir; }, @@ -730,8 +730,8 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * set the rotation of each particle to its direction Only available in 'Gravity' mode. * @param {boolean} t */ - setRotationIsDir: function(t){ - if(this.emitterMode !== cc.ParticleSystem.MODE_GRAVITY) + setRotationIsDir: function (t) { + if (this.emitterMode !== cc.ParticleSystem.MODE_GRAVITY) cc.log("cc.ParticleBatchNode.setRotationIsDir() : Particle Mode should be Gravity"); this.modeA.rotationIsDir = t; }, @@ -741,8 +741,8 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * Return starting radius of the particles. Only available in 'Radius' mode. * @return {Number} */ - getStartRadius:function () { - if(this.emitterMode !== cc.ParticleSystem.MODE_RADIUS) + getStartRadius: function () { + if (this.emitterMode !== cc.ParticleSystem.MODE_RADIUS) cc.log("cc.ParticleBatchNode.getStartRadius() : Particle Mode should be Radius"); return this.modeB.startRadius; }, @@ -751,8 +751,8 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * starting radius of the particles setter. Only available in 'Radius' mode. * @param {Number} startRadius */ - setStartRadius:function (startRadius) { - if(this.emitterMode !== cc.ParticleSystem.MODE_RADIUS) + setStartRadius: function (startRadius) { + if (this.emitterMode !== cc.ParticleSystem.MODE_RADIUS) cc.log("cc.ParticleBatchNode.setStartRadius() : Particle Mode should be Radius"); this.modeB.startRadius = startRadius; }, @@ -761,8 +761,8 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * Return starting radius variance of the particles. Only available in 'Radius' mode. * @return {Number} */ - getStartRadiusVar:function () { - if(this.emitterMode !== cc.ParticleSystem.MODE_RADIUS) + getStartRadiusVar: function () { + if (this.emitterMode !== cc.ParticleSystem.MODE_RADIUS) cc.log("cc.ParticleBatchNode.getStartRadiusVar() : Particle Mode should be Radius"); return this.modeB.startRadiusVar; }, @@ -771,8 +771,8 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * starting radius variance of the particles setter. Only available in 'Radius' mode. * @param {Number} startRadiusVar */ - setStartRadiusVar:function (startRadiusVar) { - if(this.emitterMode !== cc.ParticleSystem.MODE_RADIUS) + setStartRadiusVar: function (startRadiusVar) { + if (this.emitterMode !== cc.ParticleSystem.MODE_RADIUS) cc.log("cc.ParticleBatchNode.setStartRadiusVar() : Particle Mode should be Radius"); this.modeB.startRadiusVar = startRadiusVar; }, @@ -781,8 +781,8 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * Return ending radius of the particles. Only available in 'Radius' mode. * @return {Number} */ - getEndRadius:function () { - if(this.emitterMode !== cc.ParticleSystem.MODE_RADIUS) + getEndRadius: function () { + if (this.emitterMode !== cc.ParticleSystem.MODE_RADIUS) cc.log("cc.ParticleBatchNode.getEndRadius() : Particle Mode should be Radius"); return this.modeB.endRadius; }, @@ -791,8 +791,8 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * ending radius of the particles setter. Only available in 'Radius' mode. * @param {Number} endRadius */ - setEndRadius:function (endRadius) { - if(this.emitterMode !== cc.ParticleSystem.MODE_RADIUS) + setEndRadius: function (endRadius) { + if (this.emitterMode !== cc.ParticleSystem.MODE_RADIUS) cc.log("cc.ParticleBatchNode.setEndRadius() : Particle Mode should be Radius"); this.modeB.endRadius = endRadius; }, @@ -801,8 +801,8 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * Return ending radius variance of the particles. Only available in 'Radius' mode. * @return {Number} */ - getEndRadiusVar:function () { - if(this.emitterMode !== cc.ParticleSystem.MODE_RADIUS) + getEndRadiusVar: function () { + if (this.emitterMode !== cc.ParticleSystem.MODE_RADIUS) cc.log("cc.ParticleBatchNode.getEndRadiusVar() : Particle Mode should be Radius"); return this.modeB.endRadiusVar; }, @@ -811,8 +811,8 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * ending radius variance of the particles setter. Only available in 'Radius' mode. * @param endRadiusVar */ - setEndRadiusVar:function (endRadiusVar) { - if(this.emitterMode !== cc.ParticleSystem.MODE_RADIUS) + setEndRadiusVar: function (endRadiusVar) { + if (this.emitterMode !== cc.ParticleSystem.MODE_RADIUS) cc.log("cc.ParticleBatchNode.setEndRadiusVar() : Particle Mode should be Radius"); this.modeB.endRadiusVar = endRadiusVar; }, @@ -821,8 +821,8 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * get Number of degress to rotate a particle around the source pos per second. Only available in 'Radius' mode. * @return {Number} */ - getRotatePerSecond:function () { - if(this.emitterMode !== cc.ParticleSystem.MODE_RADIUS) + getRotatePerSecond: function () { + if (this.emitterMode !== cc.ParticleSystem.MODE_RADIUS) cc.log("cc.ParticleBatchNode.getRotatePerSecond() : Particle Mode should be Radius"); return this.modeB.rotatePerSecond; }, @@ -831,8 +831,8 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * set Number of degress to rotate a particle around the source pos per second. Only available in 'Radius' mode. * @param {Number} degrees */ - setRotatePerSecond:function (degrees) { - if(this.emitterMode !== cc.ParticleSystem.MODE_RADIUS) + setRotatePerSecond: function (degrees) { + if (this.emitterMode !== cc.ParticleSystem.MODE_RADIUS) cc.log("cc.ParticleBatchNode.setRotatePerSecond() : Particle Mode should be Radius"); this.modeB.rotatePerSecond = degrees; }, @@ -841,8 +841,8 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * Return Variance in degrees for rotatePerSecond. Only available in 'Radius' mode. * @return {Number} */ - getRotatePerSecondVar:function () { - if(this.emitterMode !== cc.ParticleSystem.MODE_RADIUS) + getRotatePerSecondVar: function () { + if (this.emitterMode !== cc.ParticleSystem.MODE_RADIUS) cc.log("cc.ParticleBatchNode.getRotatePerSecondVar() : Particle Mode should be Radius"); return this.modeB.rotatePerSecondVar; }, @@ -851,30 +851,30 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * Variance in degrees for rotatePerSecond setter. Only available in 'Radius' mode. * @param degrees */ - setRotatePerSecondVar:function (degrees) { - if(this.emitterMode !== cc.ParticleSystem.MODE_RADIUS) + setRotatePerSecondVar: function (degrees) { + if (this.emitterMode !== cc.ParticleSystem.MODE_RADIUS) cc.log("cc.ParticleBatchNode.setRotatePerSecondVar() : Particle Mode should be Radius"); this.modeB.rotatePerSecondVar = degrees; }, ////////////////////////////////////////////////////////////////////////// //don't use a transform matrix, this is faster - setScale:function (scale, scaleY) { + setScale: function (scale, scaleY) { this._transformSystemDirty = true; cc.Node.prototype.setScale.call(this, scale, scaleY); }, - setRotation:function (newRotation) { + setRotation: function (newRotation) { this._transformSystemDirty = true; cc.Node.prototype.setRotation.call(this, newRotation); }, - setScaleX:function (newScaleX) { + setScaleX: function (newScaleX) { this._transformSystemDirty = true; cc.Node.prototype.setScaleX.call(this, newScaleX); }, - setScaleY:function (newScaleY) { + setScaleY: function (newScaleY) { this._transformSystemDirty = true; cc.Node.prototype.setScaleY.call(this, newScaleY); }, @@ -883,7 +883,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * get start size in pixels of each particle * @return {Number} */ - getStartSize:function () { + getStartSize: function () { return this.startSize; }, @@ -891,7 +891,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * set start size in pixels of each particle * @param {Number} startSize */ - setStartSize:function (startSize) { + setStartSize: function (startSize) { this.startSize = startSize; }, @@ -899,7 +899,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * get size variance in pixels of each particle * @return {Number} */ - getStartSizeVar:function () { + getStartSizeVar: function () { return this.startSizeVar; }, @@ -907,7 +907,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * set size variance in pixels of each particle * @param {Number} startSizeVar */ - setStartSizeVar:function (startSizeVar) { + setStartSizeVar: function (startSizeVar) { this.startSizeVar = startSizeVar; }, @@ -915,7 +915,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * get end size in pixels of each particle * @return {Number} */ - getEndSize:function () { + getEndSize: function () { return this.endSize; }, @@ -923,7 +923,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * set end size in pixels of each particle * @param endSize */ - setEndSize:function (endSize) { + setEndSize: function (endSize) { this.endSize = endSize; }, @@ -931,7 +931,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * get end size variance in pixels of each particle * @return {Number} */ - getEndSizeVar:function () { + getEndSizeVar: function () { return this.endSizeVar; }, @@ -939,7 +939,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * set end size variance in pixels of each particle * @param {Number} endSizeVar */ - setEndSizeVar:function (endSizeVar) { + setEndSizeVar: function (endSizeVar) { this.endSizeVar = endSizeVar; }, @@ -947,7 +947,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * set start color of each particle * @return {cc.Color} */ - getStartColor:function () { + getStartColor: function () { return cc.color(this._startColor.r, this._startColor.g, this._startColor.b, this._startColor.a); }, @@ -955,7 +955,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * get start color of each particle * @param {cc.Color} startColor */ - setStartColor:function (startColor) { + setStartColor: function (startColor) { this._startColor = cc.color(startColor); }, @@ -963,7 +963,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * get start color variance of each particle * @return {cc.Color} */ - getStartColorVar:function () { + getStartColorVar: function () { return cc.color(this._startColorVar.r, this._startColorVar.g, this._startColorVar.b, this._startColorVar.a); }, @@ -971,7 +971,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * set start color variance of each particle * @param {cc.Color} startColorVar */ - setStartColorVar:function (startColorVar) { + setStartColorVar: function (startColorVar) { this._startColorVar = cc.color(startColorVar); }, @@ -979,7 +979,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * get end color and end color variation of each particle * @return {cc.Color} */ - getEndColor:function () { + getEndColor: function () { return cc.color(this._endColor.r, this._endColor.g, this._endColor.b, this._endColor.a); }, @@ -987,7 +987,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * set end color and end color variation of each particle * @param {cc.Color} endColor */ - setEndColor:function (endColor) { + setEndColor: function (endColor) { this._endColor = cc.color(endColor); }, @@ -995,7 +995,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * get end color variance of each particle * @return {cc.Color} */ - getEndColorVar:function () { + getEndColorVar: function () { return cc.color(this._endColorVar.r, this._endColorVar.g, this._endColorVar.b, this._endColorVar.a); }, @@ -1003,7 +1003,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * set end color variance of each particle * @param {cc.Color} endColorVar */ - setEndColorVar:function (endColorVar) { + setEndColorVar: function (endColorVar) { this._endColorVar = cc.color(endColorVar); }, @@ -1011,7 +1011,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * get initial angle of each particle * @return {Number} */ - getStartSpin:function () { + getStartSpin: function () { return this.startSpin; }, @@ -1019,7 +1019,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * set initial angle of each particle * @param {Number} startSpin */ - setStartSpin:function (startSpin) { + setStartSpin: function (startSpin) { this.startSpin = startSpin; }, @@ -1027,7 +1027,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * get initial angle variance of each particle * @return {Number} */ - getStartSpinVar:function () { + getStartSpinVar: function () { return this.startSpinVar; }, @@ -1035,7 +1035,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * set initial angle variance of each particle * @param {Number} startSpinVar */ - setStartSpinVar:function (startSpinVar) { + setStartSpinVar: function (startSpinVar) { this.startSpinVar = startSpinVar; }, @@ -1043,7 +1043,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * get end angle of each particle * @return {Number} */ - getEndSpin:function () { + getEndSpin: function () { return this.endSpin; }, @@ -1051,7 +1051,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * set end angle of each particle * @param {Number} endSpin */ - setEndSpin:function (endSpin) { + setEndSpin: function (endSpin) { this.endSpin = endSpin; }, @@ -1059,7 +1059,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * get end angle variance of each particle * @return {Number} */ - getEndSpinVar:function () { + getEndSpinVar: function () { return this.endSpinVar; }, @@ -1067,7 +1067,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * set end angle variance of each particle * @param {Number} endSpinVar */ - setEndSpinVar:function (endSpinVar) { + setEndSpinVar: function (endSpinVar) { this.endSpinVar = endSpinVar; }, @@ -1075,7 +1075,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * get emission rate of the particles * @return {Number} */ - getEmissionRate:function () { + getEmissionRate: function () { return this.emissionRate; }, @@ -1083,7 +1083,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * set emission rate of the particles * @param {Number} emissionRate */ - setEmissionRate:function (emissionRate) { + setEmissionRate: function (emissionRate) { this.emissionRate = emissionRate; }, @@ -1091,7 +1091,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * get maximum particles of the system * @return {Number} */ - getTotalParticles:function () { + getTotalParticles: function () { return this._totalParticles; }, @@ -1099,7 +1099,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * set maximum particles of the system * @param {Number} tp totalParticles */ - setTotalParticles:function (tp) { + setTotalParticles: function (tp) { this._renderCmd.setTotalParticles(tp); }, @@ -1107,7 +1107,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * get Texture of Particle System * @return {cc.Texture2D} */ - getTexture:function () { + getTexture: function () { return this._texture; }, @@ -1115,15 +1115,15 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * set Texture of Particle System * @param {cc.Texture2D } texture */ - setTexture:function (texture) { - if(!texture) + setTexture: function (texture) { + if (!texture) return; - if(texture.isLoaded()){ + if (texture.isLoaded()) { this.setTextureWithRect(texture, cc.rect(0, 0, texture.width, texture.height)); } else { this._textureLoaded = false; - texture.addEventListener("load", function(sender){ + texture.addEventListener("load", function (sender) { this._textureLoaded = true; this.setTextureWithRect(sender, cc.rect(0, 0, sender.width, sender.height)); }, this); @@ -1135,7 +1135,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * get BlendFunc of Particle System * @return {cc.BlendFunc} */ - getBlendFunc:function () { + getBlendFunc: function () { return this._blendFunc; }, @@ -1144,7 +1144,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * @param {Number} src * @param {Number} dst */ - setBlendFunc:function (src, dst) { + setBlendFunc: function (src, dst) { if (dst === undefined) { if (this._blendFunc !== src) { this._blendFunc = src; @@ -1152,7 +1152,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ } } else { if (this._blendFunc.src !== src || this._blendFunc.dst !== dst) { - this._blendFunc = {src:src, dst:dst}; + this._blendFunc = {src: src, dst: dst}; this._updateBlendFunc(); } } @@ -1162,7 +1162,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * does the alpha value modify color getter * @return {Boolean} */ - isOpacityModifyRGB:function () { + isOpacityModifyRGB: function () { return this._opacityModifyRGB; }, @@ -1170,7 +1170,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * does the alpha value modify color setter * @param newValue */ - setOpacityModifyRGB:function (newValue) { + setOpacityModifyRGB: function (newValue) { this._opacityModifyRGB = newValue; }, @@ -1183,7 +1183,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * source blend function = GL_SRC_ALPHA; * dest blend function = GL_ONE; */ - isBlendAdditive:function () { + isBlendAdditive: function () { return (( this._blendFunc.src === cc.SRC_ALPHA && this._blendFunc.dst === cc.ONE) || (this._blendFunc.src === cc.ONE && this._blendFunc.dst === cc.ONE)); }, @@ -1193,7 +1193,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ *

* @param {Boolean} isBlendAdditive */ - setBlendAdditive:function (isBlendAdditive) { + setBlendAdditive: function (isBlendAdditive) { var locBlendFunc = this._blendFunc; if (isBlendAdditive) { locBlendFunc.src = cc.SRC_ALPHA; @@ -1207,7 +1207,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * get particles movement type: Free or Grouped * @return {Number} */ - getPositionType:function () { + getPositionType: function () { return this.positionType; }, @@ -1215,7 +1215,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * set particles movement type: Free or Grouped * @param {Number} positionType */ - setPositionType:function (positionType) { + setPositionType: function (positionType) { this.positionType = positionType; }, @@ -1225,7 +1225,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ *

* @return {Boolean} */ - isAutoRemoveOnFinish:function () { + isAutoRemoveOnFinish: function () { return this.autoRemoveOnFinish; }, @@ -1235,7 +1235,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ *

* @param {Boolean} isAutoRemoveOnFinish */ - setAutoRemoveOnFinish:function (isAutoRemoveOnFinish) { + setAutoRemoveOnFinish: function (isAutoRemoveOnFinish) { this.autoRemoveOnFinish = isAutoRemoveOnFinish; }, @@ -1243,7 +1243,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * return kind of emitter modes * @return {Number} */ - getEmitterMode:function () { + getEmitterMode: function () { return this.emitterMode; }, @@ -1254,14 +1254,14 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ *

* @param {Number} emitterMode */ - setEmitterMode:function (emitterMode) { + setEmitterMode: function (emitterMode) { this.emitterMode = emitterMode; }, /** * initializes a cc.ParticleSystem */ - init:function () { + init: function () { return this.initWithTotalParticles(150); }, @@ -1274,10 +1274,10 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * @param {String} plistFile * @return {boolean} */ - initWithFile:function (plistFile) { + initWithFile: function (plistFile) { this._plistFile = plistFile; var dict = cc.loader.getRes(plistFile); - if(!dict){ + if (!dict) { cc.log("cc.ParticleSystem.initWithFile(): Particles: file not found"); return false; } @@ -1290,7 +1290,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * return bounding box of particle system in world space * @return {cc.Rect} */ - getBoundingBoxToWorld:function () { + getBoundingBoxToWorld: function () { return cc.rect(0, 0, cc._canvas.width, cc._canvas.height); }, @@ -1300,7 +1300,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * @param {String} dirname * @return {Boolean} */ - initWithDictionary:function (dictionary, dirname) { + initWithDictionary: function (dictionary, dirname) { var ret = false; var buffer = null; var image = null; @@ -1353,7 +1353,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ // position this.setPosition(parseFloat(locValueForKey("sourcePositionx", dictionary)), - parseFloat(locValueForKey("sourcePositiony", dictionary))); + parseFloat(locValueForKey("sourcePositiony", dictionary))); this._posVar.x = parseFloat(locValueForKey("sourcePositionVariancex", dictionary)); this._posVar.y = parseFloat(locValueForKey("sourcePositionVariancey", dictionary)); @@ -1449,24 +1449,24 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ var imageFormat = cc.getImageFormatByData(buffer); - if(imageFormat !== cc.FMT_TIFF && imageFormat !== cc.FMT_PNG){ + if (imageFormat !== cc.FMT_TIFF && imageFormat !== cc.FMT_PNG) { cc.log("cc.ParticleSystem: unknown image format with Data"); return false; } var canvasObj = document.createElement("canvas"); - if(imageFormat === cc.FMT_PNG){ + if (imageFormat === cc.FMT_PNG) { var myPngObj = new cc.PNGReader(buffer); myPngObj.render(canvasObj); } else { var myTIFFObj = cc.tiffReader; - myTIFFObj.parseTIFF(buffer,canvasObj); + myTIFFObj.parseTIFF(buffer, canvasObj); } cc.textureCache.cacheImage(imgPath, canvasObj); var addTexture = cc.textureCache.getTextureForKey(imgPath); - if(!addTexture) + if (!addTexture) cc.log("cc.ParticleSystem.initWithDictionary() : error loading the texture"); this.setTexture(addTexture); } @@ -1482,12 +1482,12 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * @param {Number} numberOfParticles * @return {Boolean} */ - initWithTotalParticles:function (numberOfParticles) { + initWithTotalParticles: function (numberOfParticles) { this._totalParticles = numberOfParticles; var i, locParticles = this._particles; locParticles.length = 0; - for(i = 0; i< numberOfParticles; i++){ + for (i = 0; i < numberOfParticles; i++) { locParticles[i] = new cc.Particle(); } @@ -1533,7 +1533,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * @function * @see scheduleUpdate(); */ - destroyParticleSystem:function () { + destroyParticleSystem: function () { this.unscheduleUpdate(); }, @@ -1555,7 +1555,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * Initializes a particle * @param {cc.Particle} particle */ - initParticle:function (particle) { + initParticle: function (particle) { var locRandomMinus11 = cc.randomMinus1To1; // timeToLive // no negative life. prevent division by 0 @@ -1612,7 +1612,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ // position if (this.positionType === cc.ParticleSystem.TYPE_FREE) particle.startPos = this.convertToWorldSpace(this._pointZeroForParticle); - else if (this.positionType === cc.ParticleSystem.TYPE_RELATIVE){ + else if (this.positionType === cc.ParticleSystem.TYPE_RELATIVE) { particle.startPos.x = this._position.x; particle.startPos.y = this._position.y; } @@ -1637,7 +1637,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ locParticleModeA.tangentialAccel = locModeA.tangentialAccel + locModeA.tangentialAccelVar * locRandomMinus11(); // rotation is dir - if(locModeA.rotationIsDir) + if (locModeA.rotationIsDir) particle.rotation = -cc.radiansToDegrees(cc.pToAngle(locParticleModeA.dir)); } else { // Mode Radius: B @@ -1658,7 +1658,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ /** * stop emitting particles. Running particles will continue to run until they die */ - stopSystem:function () { + stopSystem: function () { this._isActive = false; this._elapsed = this.duration; this._emitCounter = 0; @@ -1667,19 +1667,19 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ /** * Kill all living particles. */ - resetSystem:function () { + resetSystem: function () { this._isActive = true; this._elapsed = 0; var locParticles = this._particles; for (this._particleIdx = 0; this._particleIdx < this.particleCount; ++this._particleIdx) - locParticles[this._particleIdx].timeToLive = 0 ; + locParticles[this._particleIdx].timeToLive = 0; }, /** * whether or not the system is full * @return {Boolean} */ - isFull:function () { + isFull: function () { return (this.particleCount >= this._totalParticles); }, @@ -1688,14 +1688,14 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * @param {cc.Particle} particle * @param {cc.Point} newPosition */ - updateQuadWithParticle:function (particle, newPosition) { + updateQuadWithParticle: function (particle, newPosition) { this._renderCmd.updateQuadWithParticle(particle, newPosition); }, /** * should be overridden by subclasses */ - postStep:function () { + postStep: function () { this._renderCmd.postStep(); }, @@ -1832,10 +1832,10 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ } else { // life < 0 var currentIndex = selParticle.atlasIndex; - if(this._particleIdx !== this.particleCount -1){ - var deadParticle = locParticles[this._particleIdx]; - locParticles[this._particleIdx] = locParticles[this.particleCount -1]; - locParticles[this.particleCount -1] = deadParticle; + if (this._particleIdx !== this.particleCount - 1) { + var deadParticle = locParticles[this._particleIdx]; + locParticles[this._particleIdx] = locParticles[this.particleCount - 1]; + locParticles[this.particleCount - 1] = deadParticle; } if (this._batchNode) { //disable the switched particle @@ -1862,7 +1862,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ /** * update emitter's status (dt = 0) */ - updateWithNoTime:function () { + updateWithNoTime: function () { this.update(0); }, @@ -1873,7 +1873,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ // @return {String} "" if not found; return the string if found. // @private // - _valueForKey:function (key, dict) { + _valueForKey: function (key, dict) { if (dict) { var pString = dict[key]; return pString != null ? pString : ""; @@ -1881,8 +1881,8 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ return ""; }, - _updateBlendFunc:function () { - if(this._batchNode){ + _updateBlendFunc: function () { + if (this._batchNode) { cc.log("Can't change blending functions when the particle is being batched"); return; } @@ -1908,7 +1908,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * * @return {cc.ParticleSystem} */ - clone:function () { + clone: function () { var retParticle = new cc.ParticleSystem(); // self, not super @@ -1922,7 +1922,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ // blend function var blend = this.getBlendFunc(); - retParticle.setBlendFunc(blend.src,blend.dst); + retParticle.setBlendFunc(blend.src, blend.dst); // color retParticle.setStartColor(this.getStartColor()); @@ -1941,15 +1941,15 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ // position retParticle.setPosition(cc.p(this.x, this.y)); - retParticle.setPosVar(cc.p(this.getPosVar().x,this.getPosVar().y)); + retParticle.setPosVar(cc.p(this.getPosVar().x, this.getPosVar().y)); retParticle.setPositionType(this.getPositionType()); // Spinning - retParticle.setStartSpin(this.getStartSpin()||0); - retParticle.setStartSpinVar(this.getStartSpinVar()||0); - retParticle.setEndSpin(this.getEndSpin()||0); - retParticle.setEndSpinVar(this.getEndSpinVar()||0); + retParticle.setStartSpin(this.getStartSpin() || 0); + retParticle.setStartSpinVar(this.getStartSpinVar() || 0); + retParticle.setEndSpin(this.getEndSpin() || 0); + retParticle.setEndSpinVar(this.getEndSpinVar() || 0); retParticle.setEmitterMode(this.getEmitterMode()); @@ -1957,7 +1957,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ if (this.getEmitterMode() === cc.ParticleSystem.MODE_GRAVITY) { // gravity var gra = this.getGravity(); - retParticle.setGravity(cc.p(gra.x,gra.y)); + retParticle.setGravity(cc.p(gra.x, gra.y)); // speed retParticle.setSpeed(this.getSpeed()); @@ -1995,7 +1995,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ retParticle.setOpacityModifyRGB(this.isOpacityModifyRGB()); // texture var texture = this.getTexture(); - if(texture){ + if (texture) { var size = texture.getContentSize(); retParticle.setTextureWithRect(texture, cc.rect(0, 0, size.width, size.height)); } @@ -2042,7 +2042,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * listen the event that coming to foreground on Android (An empty function for native) * @param {cc.Class} obj */ - listenBackToForeground:function (obj) { + listenBackToForeground: function (obj) { //do nothing } }); @@ -2174,7 +2174,7 @@ cc.ParticleSystem.createWithTotalParticles = cc.ParticleSystem.create; */ cc.ParticleSystem.ModeA = function (gravity, speed, speedVar, tangentialAccel, tangentialAccelVar, radialAccel, radialAccelVar, rotationIsDir) { /** Gravity value. Only available in 'Gravity' mode. */ - this.gravity = gravity ? gravity : cc.p(0,0); + this.gravity = gravity ? gravity : cc.p(0, 0); /** speed of each particle. Only available in 'Gravity' mode. */ this.speed = speed || 0; /** speed variance of each particle. Only available in 'Gravity' mode. */ diff --git a/cocos2d/particle/CCParticleSystemCanvasRenderCmd.js b/cocos2d/particle/CCParticleSystemCanvasRenderCmd.js index de78252346..4ff3fc4d87 100644 --- a/cocos2d/particle/CCParticleSystemCanvasRenderCmd.js +++ b/cocos2d/particle/CCParticleSystemCanvasRenderCmd.js @@ -39,23 +39,23 @@ var proto = cc.ParticleSystem.CanvasRenderCmd.prototype = Object.create(cc.Node.CanvasRenderCmd.prototype); proto.constructor = cc.ParticleSystem.CanvasRenderCmd; - proto.getDrawMode = function(){ + proto.getDrawMode = function () { return this._drawMode; }; - proto.setDrawMode = function(drawMode){ + proto.setDrawMode = function (drawMode) { this._drawMode = drawMode; }; - proto.getShapeType = function(){ + proto.getShapeType = function () { return this._shapeType; }; - proto.setShapeType = function(shapeType){ + proto.setShapeType = function (shapeType) { this._shapeType = shapeType; }; - proto.setBatchNode = function(batchNode){ + proto.setBatchNode = function (batchNode) { if (this._batchNode !== batchNode) { this._node._batchNode = batchNode; } @@ -65,7 +65,7 @@ //do nothing }; - proto.updateParticlePosition = function(particle, position){ + proto.updateParticlePosition = function (particle, position) { cc.pIn(particle.drawPos, position); }; @@ -143,7 +143,7 @@ cc.g_NumberOfDraws++; }; - proto._changeTextureColor = function(texture, color, rect){ + proto._changeTextureColor = function (texture, color, rect) { var tintCache = this._tintCache; var textureContentSize = texture.getContentSize(); tintCache.width = textureContentSize.width; @@ -151,16 +151,16 @@ return texture._generateColorTexture(color.r, color.g, color.b, rect, tintCache); }; - proto.initTexCoordsWithRect = function(pointRect){ + proto.initTexCoordsWithRect = function (pointRect) { this._pointRect = pointRect; }; - proto.setTotalParticles = function(tp){ + proto.setTotalParticles = function (tp) { //cc.assert(tp <= this._allocatedParticles, "Particle: resizing particle array only supported for quads"); this._node._totalParticles = (tp < 200) ? tp : 200; }; - proto.addParticle = function(){ + proto.addParticle = function () { var node = this._node, particles = node._particles, particle; @@ -173,21 +173,24 @@ return particle; }; - proto._setupVBO = function(){}; - proto._allocMemory = function(){ + proto._setupVBO = function () { + }; + proto._allocMemory = function () { return true; }; - proto.postStep = function(){}; + proto.postStep = function () { + }; - proto._setBlendAdditive = function(){ + proto._setBlendAdditive = function () { var locBlendFunc = this._node._blendFunc; locBlendFunc.src = cc.BLEND_SRC; locBlendFunc.dst = cc.BLEND_DST; }; - proto._initWithTotalParticles = function(totalParticles){}; - proto._updateDeltaColor = function(selParticle, dt){ + proto._initWithTotalParticles = function (totalParticles) { + }; + proto._updateDeltaColor = function (selParticle, dt) { if (!this._node._dontTint) { selParticle.color.r += selParticle.deltaColor.r * dt; selParticle.color.g += selParticle.deltaColor.g * dt; diff --git a/cocos2d/particle/CCParticleSystemWebGLRenderCmd.js b/cocos2d/particle/CCParticleSystemWebGLRenderCmd.js index 8e684256d3..55cc7fa128 100644 --- a/cocos2d/particle/CCParticleSystemWebGLRenderCmd.js +++ b/cocos2d/particle/CCParticleSystemWebGLRenderCmd.js @@ -22,7 +22,7 @@ THE SOFTWARE. ****************************************************************************/ -(function(){ +(function () { /** * ParticleSystem's WebGL render command */ @@ -41,12 +41,16 @@ var proto = cc.ParticleSystem.WebGLRenderCmd.prototype = Object.create(cc.Node.WebGLRenderCmd.prototype); proto.constructor = cc.ParticleSystem.WebGLRenderCmd; - proto.getDrawMode = function(){}; - proto.setDrawMode = function(drawMode){}; - proto.getShapeType = function(){}; - proto.setShapeType = function(shapeType){}; + proto.getDrawMode = function () { + }; + proto.setDrawMode = function (drawMode) { + }; + proto.getShapeType = function () { + }; + proto.setShapeType = function (shapeType) { + }; - proto.setBatchNode = function(batchNode){ + proto.setBatchNode = function (batchNode) { var node = this._node; if (node._batchNode !== batchNode) { var oldBatch = node._batchNode; @@ -91,11 +95,11 @@ } }; - proto.isDifferentTexture = function(texture1, texture2){ - return (texture1 === texture2); + proto.isDifferentTexture = function (texture1, texture2) { + return (texture1 === texture2); }; - proto.updateParticlePosition = function(particle, position){ + proto.updateParticlePosition = function (particle, position) { // IMPORTANT: newPos may not be used as a reference here! (as it is just the temporary tpa point) // the implementation of updateQuadWithParticle must use // the x and y values directly @@ -113,9 +117,9 @@ var r, g, b, a; if (node._opacityModifyRGB) { - r = 0 | (particle.color.r * particle.color.a/255); - g = 0 | (particle.color.g * particle.color.a/255); - b = 0 | (particle.color.b * particle.color.a/255); + r = 0 | (particle.color.r * particle.color.a / 255); + g = 0 | (particle.color.g * particle.color.a / 255); + b = 0 | (particle.color.b * particle.color.a / 255); } else { r = 0 | (particle.color.r ); g = 0 | (particle.color.g ); @@ -219,16 +223,16 @@ gl.drawElements(gl.TRIANGLES, node._particleIdx * 6, gl.UNSIGNED_SHORT, 0); }; - proto.initTexCoordsWithRect = function(pointRect){ + proto.initTexCoordsWithRect = function (pointRect) { var node = this._node; var texture = node.texture; var scaleFactor = cc.contentScaleFactor(); // convert to pixels coords var rect = cc.rect( - pointRect.x * scaleFactor, - pointRect.y * scaleFactor, - pointRect.width * scaleFactor, - pointRect.height * scaleFactor); + pointRect.x * scaleFactor, + pointRect.y * scaleFactor, + pointRect.width * scaleFactor, + pointRect.height * scaleFactor); var wide = pointRect.width; var high = pointRect.height; @@ -288,7 +292,7 @@ } }; - proto.setTotalParticles = function(tp){ + proto.setTotalParticles = function (tp) { var node = this._node; // If we are setting the total numer of particles to a number higher // than what is allocated, we need to allocate new arrays @@ -321,7 +325,7 @@ this._setupVBO(); //set the texture coord - if(node._texture){ + if (node._texture) { this.initTexCoordsWithRect(cc.rect(0, 0, node._texture.width, node._texture.height)); } } else @@ -329,13 +333,13 @@ node.resetSystem(); }; - proto.addParticle = function(){ + proto.addParticle = function () { var node = this._node, particles = node._particles; return particles[node.particleCount]; }; - proto._setupVBO = function(){ + proto._setupVBO = function () { var node = this; var gl = cc._renderContext; @@ -351,10 +355,10 @@ //cc.checkGLErrorDebug(); }; - proto._allocMemory = function(){ - var node = this._node; + proto._allocMemory = function () { + var node = this._node; //cc.assert((!this._quads && !this._indices), "Memory already allocated"); - if(node._batchNode){ + if (node._batchNode) { cc.log("cc.ParticleSystem._allocMemory(): Memory should not be allocated when not using batchNode"); return false; } @@ -376,13 +380,13 @@ return true; }; - proto.postStep = function(){ + proto.postStep = function () { var gl = cc._renderContext; gl.bindBuffer(gl.ARRAY_BUFFER, this._buffersVBO[0]); gl.bufferSubData(gl.ARRAY_BUFFER, 0, this._quadsArrayBuffer); }; - proto._setBlendAdditive = function(){ + proto._setBlendAdditive = function () { var locBlendFunc = this._node._blendFunc; if (this._texture && !this._texture.hasPremultipliedAlpha()) { locBlendFunc.src = cc.SRC_ALPHA; @@ -393,7 +397,7 @@ } }; - proto._initWithTotalParticles = function(totalParticles){ + proto._initWithTotalParticles = function (totalParticles) { // allocating data space if (!this._allocMemory()) return false; @@ -411,4 +415,4 @@ selParticle.color.a += selParticle.deltaColor.a * dt; selParticle.isChangeColor = true; }; -})(); \ No newline at end of file +})(); diff --git a/cocos2d/physics/CCPhysicsDebugNodeCanvasRenderCmd.js b/cocos2d/physics/CCPhysicsDebugNodeCanvasRenderCmd.js index be1f6f14ba..b3b417fed1 100644 --- a/cocos2d/physics/CCPhysicsDebugNodeCanvasRenderCmd.js +++ b/cocos2d/physics/CCPhysicsDebugNodeCanvasRenderCmd.js @@ -35,7 +35,7 @@ var proto = cc.PhysicsDebugNode.CanvasRenderCmd.prototype = Object.create(cc.Node.CanvasRenderCmd.prototype); proto.constructor = cc.PhysicsDebugNode.CanvasRenderCmd; - proto.rendering = function(ctx, scaleX, scaleY){ + proto.rendering = function (ctx, scaleX, scaleY) { var node = this._node; if (!node._space) return; diff --git a/cocos2d/physics/CCPhysicsSprite.js b/cocos2d/physics/CCPhysicsSprite.js index 80df018400..dde3546318 100644 --- a/cocos2d/physics/CCPhysicsSprite.js +++ b/cocos2d/physics/CCPhysicsSprite.js @@ -37,10 +37,10 @@ */ (function () { var box2dAPI = { - _ignoreBodyRotation:false, - _body:null, - _PTMRatio:32, - _rotation:1, + _ignoreBodyRotation: false, + _body: null, + _PTMRatio: 32, + _rotation: 1, /** * Create a PhysicsSprite with filename and rect * Constructor of cc.PhysicsSprite for Box2d @@ -66,12 +66,12 @@ * var physicsSprite2 = new cc.PhysicsSprite(texture, cc.rect(0,0,480,320)); * */ - ctor:function(fileName, rect){ + ctor: function (fileName, rect) { cc.Sprite.prototype.ctor.call(this); if (fileName === undefined) { cc.PhysicsSprite.prototype.init.call(this); - }else if (cc.isString(fileName)) { + } else if (cc.isString(fileName)) { if (fileName[0] === "#") { //init with a sprite frame name var frameName = fileName.substr(1, fileName.length - 1); @@ -81,7 +81,7 @@ //init with filename and rect this.init(fileName, rect); } - }else if (cc.isObject(fileName)) { + } else if (cc.isObject(fileName)) { if (fileName instanceof cc.Texture2D) { //init with texture and rect this.initWithTexture(fileName, rect); @@ -103,7 +103,7 @@ * set body * @param {Box2D.Dynamics.b2Body} body */ - setBody:function (body) { + setBody: function (body) { this._body = body; }, @@ -111,7 +111,7 @@ * get body * @return {Box2D.Dynamics.b2Body} */ - getBody:function () { + getBody: function () { return this._body; }, @@ -119,7 +119,7 @@ * set PTM ratio * @param {Number} r */ - setPTMRatio:function (r) { + setPTMRatio: function (r) { this._PTMRatio = r; }, @@ -127,7 +127,7 @@ * get PTM ration * @return {Number} */ - getPTMRatio:function () { + getPTMRatio: function () { return this._PTMRatio; }, @@ -135,9 +135,9 @@ * get position * @return {cc.Point} */ - getPosition:function () { + getPosition: function () { var pos = this._body.GetPosition(); - var locPTMRatio =this._PTMRatio; + var locPTMRatio = this._PTMRatio; return cc.p(pos.x * locPTMRatio, pos.y * locPTMRatio); }, @@ -145,9 +145,9 @@ * set position * @param {cc.Point} p */ - setPosition:function (p) { + setPosition: function (p) { var angle = this._body.GetAngle(); - var locPTMRatio =this._PTMRatio; + var locPTMRatio = this._PTMRatio; this._body.setTransform(Box2D.b2Vec2(p.x / locPTMRatio, p.y / locPTMRatio), angle); this.setNodeDirty(); }, @@ -156,7 +156,7 @@ * get rotation * @return {Number} */ - getRotation:function () { + getRotation: function () { return (this._ignoreBodyRotation ? cc.radiansToDegrees(this._rotationRadians) : cc.radiansToDegrees(this._body.GetAngle())); }, @@ -164,7 +164,7 @@ * set rotation * @param {Number} r */ - setRotation:function (r) { + setRotation: function (r) { if (this._ignoreBodyRotation) { this._rotation = r; } else { @@ -175,7 +175,7 @@ this.setNodeDirty(); }, - _syncPosition:function () { + _syncPosition: function () { var locPosition = this._position, pos = this._body.GetPosition(), x = pos.x * this._PTMRatio, @@ -184,7 +184,7 @@ cc.Sprite.prototype.setPosition.call(this, x, y); } }, - _syncRotation:function () { + _syncRotation: function () { this._rotationRadians = this._body.GetAngle(); var a = cc.radiansToDegrees(this._rotationRadians); if (this._rotationX !== a) { @@ -196,15 +196,15 @@ * set whether to ingore body's rotation * @param {Boolean} b */ - setIgnoreBodyRotation: function(b) { + setIgnoreBodyRotation: function (b) { this._ignoreBodyRotation = b; } }; var chipmunkAPI = { - _ignoreBodyRotation:false, - _body:null, //physics body - _rotation:1, + _ignoreBodyRotation: false, + _body: null, //physics body + _rotation: 1, /** * Create a PhysicsSprite with filename and rect @@ -231,12 +231,12 @@ * var physicsSprite2 = new cc.PhysicsSprite(texture, cc.rect(0,0,480,320)); * */ - ctor:function(fileName, rect){ + ctor: function (fileName, rect) { cc.Sprite.prototype.ctor.call(this); if (fileName === undefined) { cc.PhysicsSprite.prototype.init.call(this); - }else if (cc.isString(fileName)) { + } else if (cc.isString(fileName)) { if (fileName[0] === "#") { //init with a sprite frame name var frameName = fileName.substr(1, fileName.length - 1); @@ -246,7 +246,7 @@ //init with filename and rect this.init(fileName, rect); } - }else if (cc.isObject(fileName)) { + } else if (cc.isObject(fileName)) { if (fileName instanceof cc.Texture2D) { //init with texture and rect this.initWithTexture(fileName, rect); @@ -259,7 +259,7 @@ cc.renderer.pushRenderCommand(this._renderCmd); }, - visit: function(){ + visit: function () { cc.renderer.pushRenderCommand(this._renderCmd); cc.Sprite.prototype.visit.call(this); }, @@ -268,7 +268,7 @@ * set body * @param {cp.Body} body */ - setBody:function (body) { + setBody: function (body) { this._body = body; }, @@ -276,7 +276,7 @@ * get body * @returns {cp.Body} */ - getBody:function () { + getBody: function () { return this._body; }, @@ -284,16 +284,16 @@ * get position * @return {cc.Point} */ - getPosition:function () { + getPosition: function () { var locBody = this._body; - return {x:locBody.p.x, y:locBody.p.y}; + return {x: locBody.p.x, y: locBody.p.y}; }, /** * get position x * @return {Number} */ - getPositionX:function () { + getPositionX: function () { return this._body.p.x; }, @@ -301,7 +301,7 @@ * get position y * @return {Number} */ - getPositionY:function () { + getPositionY: function () { return this._body.p.y; }, @@ -310,7 +310,7 @@ * @param {cc.Point|Number}newPosOrxValue * @param {Number}yValue */ - setPosition:function (newPosOrxValue, yValue) { + setPosition: function (newPosOrxValue, yValue) { if (yValue === undefined) { this._body.p.x = newPosOrxValue.x; this._body.p.y = newPosOrxValue.y; @@ -324,7 +324,7 @@ * set position x * @param {Number} xValue */ - setPositionX:function (xValue) { + setPositionX: function (xValue) { this._body.p.x = xValue; }, @@ -332,11 +332,11 @@ * set position y * @param {Number} yValue */ - setPositionY:function (yValue) { + setPositionY: function (yValue) { this._body.p.y = yValue; }, - _syncPosition:function () { + _syncPosition: function () { var locPosition = this._position, locBody = this._body; if (locPosition.x !== locBody.p.x || locPosition.y !== locBody.p.y) { cc.Sprite.prototype.setPosition.call(this, locBody.p.x, locBody.p.y); @@ -347,7 +347,7 @@ * get rotation * @return {Number} */ - getRotation:function () { + getRotation: function () { return this._ignoreBodyRotation ? this._rotationX : -cc.radiansToDegrees(this._body.a); }, @@ -355,14 +355,14 @@ * set rotation * @param {Number} r */ - setRotation:function (r) { + setRotation: function (r) { if (this._ignoreBodyRotation) { cc.Sprite.prototype.setRotation.call(this, r); } else { this._body.a = -cc.degreesToRadians(r); } }, - _syncRotation:function () { + _syncRotation: function () { var a = -cc.radiansToDegrees(this._body.a); if (this._rotationX !== a) { cc.Sprite.prototype.setRotation.call(this, a); @@ -373,7 +373,7 @@ * get the affine transform matrix of node to parent coordinate frame * @return {cc.AffineTransform} */ - getNodeToParentTransform:function () { + getNodeToParentTransform: function () { return this._renderCmd.getNodeToParentTransform(); }, @@ -381,21 +381,22 @@ * whether dirty * @return {Boolean} */ - isDirty:function(){ - return !this._body.isSleeping(); + isDirty: function () { + return !this._body.isSleeping(); + }, + setDirty: function () { }, - setDirty: function(){ }, /** * set whether to ignore rotation of body * @param {Boolean} b */ - setIgnoreBodyRotation: function(b) { + setIgnoreBodyRotation: function (b) { this._ignoreBodyRotation = b; }, - _createRenderCmd: function(){ - if(cc._renderType === cc.game.RENDER_TYPE_CANVAS) + _createRenderCmd: function () { + if (cc._renderType === cc.game.RENDER_TYPE_CANVAS) return new cc.PhysicsSprite.CanvasRenderCmd(this); else return new cc.PhysicsSprite.WebGLRenderCmd(this); diff --git a/cocos2d/physics/CCPhysicsSpriteCanvasRenderCmd.js b/cocos2d/physics/CCPhysicsSpriteCanvasRenderCmd.js index 705749d259..846f0f27cf 100644 --- a/cocos2d/physics/CCPhysicsSpriteCanvasRenderCmd.js +++ b/cocos2d/physics/CCPhysicsSpriteCanvasRenderCmd.js @@ -34,17 +34,17 @@ var proto = cc.PhysicsSprite.CanvasRenderCmd.prototype = Object.create(cc.Sprite.CanvasRenderCmd.prototype); proto.constructor = cc.PhysicsSprite.CanvasRenderCmd; - proto.rendering = function(ctx, scaleX, scaleY){ + proto.rendering = function (ctx, scaleX, scaleY) { // This is a special class // Sprite can not obtain sign // So here must to calculate of each frame - var node = this._node; + var node = this._node; node._syncPosition(); - if(!node._ignoreBodyRotation) + if (!node._ignoreBodyRotation) node._syncRotation(); this.transform(this.getParentRenderCmd()); cc.Sprite.CanvasRenderCmd.prototype.rendering.call(this, ctx, scaleX, scaleY); }; -})(); \ No newline at end of file +})(); diff --git a/cocos2d/physics/CCPhysicsSpriteWebGLRenderCmd.js b/cocos2d/physics/CCPhysicsSpriteWebGLRenderCmd.js index d2e6b25c25..1c943ae99e 100644 --- a/cocos2d/physics/CCPhysicsSpriteWebGLRenderCmd.js +++ b/cocos2d/physics/CCPhysicsSpriteWebGLRenderCmd.js @@ -40,12 +40,12 @@ // This is a special class // Sprite can not obtain sign // So here must to calculate of each frame - var node = this._node; + var node = this._node; node._syncPosition(); - if(!node._ignoreBodyRotation) + if (!node._ignoreBodyRotation) node._syncRotation(); this.transform(this.getParentRenderCmd(), true); return this.spUploadData(f32buffer, ui32buffer, vertexDataOffset); }; -})(); \ No newline at end of file +})(); diff --git a/cocos2d/progress-timer/CCProgressTimerCanvasRenderCmd.js b/cocos2d/progress-timer/CCProgressTimerCanvasRenderCmd.js index 3dd320b543..17276c23f5 100644 --- a/cocos2d/progress-timer/CCProgressTimerCanvasRenderCmd.js +++ b/cocos2d/progress-timer/CCProgressTimerCanvasRenderCmd.js @@ -44,7 +44,7 @@ proto.constructor = cc.ProgressTimer.CanvasRenderCmd; proto.rendering = function (ctx, scaleX, scaleY) { - var wrapper = ctx || cc._renderContext,context = wrapper.getContext(), node = this._node, locSprite = node._sprite; + var wrapper = ctx || cc._renderContext, context = wrapper.getContext(), node = this._node, locSprite = node._sprite; var locTextureCoord = locSprite._renderCmd._textureCoord, alpha = locSprite._renderCmd._displayedOpacity / 255; if (locTextureCoord.width === 0 || locTextureCoord.height === 0) @@ -76,14 +76,14 @@ if (node._type === cc.ProgressTimer.TYPE_BAR) { var locBarRect = this._barRect; context.beginPath(); - context.rect(locBarRect.x , locBarRect.y , locBarRect.width , locBarRect.height ); + context.rect(locBarRect.x, locBarRect.y, locBarRect.width, locBarRect.height); context.clip(); context.closePath(); } else if (node._type === cc.ProgressTimer.TYPE_RADIAL) { - var locOriginX = this._origin.x ; - var locOriginY = this._origin.y ; + var locOriginX = this._origin.x; + var locOriginY = this._origin.y; context.beginPath(); - context.arc(locOriginX, locOriginY, this._radius , this._PI180 * this._startAngle, this._PI180 * this._endAngle, this._counterClockWise); + context.arc(locOriginX, locOriginY, this._radius, this._PI180 * this._startAngle, this._PI180 * this._endAngle, this._counterClockWise); context.lineTo(locOriginX, locOriginY); context.clip(); context.closePath(); @@ -95,21 +95,23 @@ if (locSprite._renderCmd._colorized) { context.drawImage(image, 0, 0, locTextureCoord.width, locTextureCoord.height, - locX , locY , locWidth , locHeight ); + locX, locY, locWidth, locHeight); } else { context.drawImage(image, locTextureCoord.renderX, locTextureCoord.renderY, locTextureCoord.width, locTextureCoord.height, - locX , locY , locWidth , locHeight ); + locX, locY, locWidth, locHeight); } wrapper.restore(); cc.g_NumberOfDraws++; }; - proto.releaseData = function(){}; + proto.releaseData = function () { + }; - proto.resetVertexData = function(){}; + proto.resetVertexData = function () { + }; - proto._updateProgress = function(){ + proto._updateProgress = function () { this.setDirtyFlag(cc.Node._dirtyFlags.contentDirty); var node = this._node; var locSprite = node._sprite; @@ -197,18 +199,18 @@ proto._syncStatus = function (parentCmd) { var node = this._node; - if(!node._sprite) + if (!node._sprite) return; var flags = cc.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; this._dirtyFlag = locFlag; @@ -219,19 +221,19 @@ var colorDirty = spriteFlag & flags.colorDirty, opacityDirty = spriteFlag & flags.opacityDirty; - if (colorDirty){ + if (colorDirty) { spriteCmd._syncDisplayColor(); spriteCmd._dirtyFlag &= ~flags.colorDirty; this._dirtyFlag &= ~flags.colorDirty; } - if (opacityDirty){ + if (opacityDirty) { spriteCmd._syncDisplayOpacity(); spriteCmd._dirtyFlag &= ~flags.opacityDirty; this._dirtyFlag &= ~flags.opacityDirty; } - if(colorDirty || opacityDirty){ + if (colorDirty || opacityDirty) { spriteCmd._updateColor(); } @@ -247,7 +249,7 @@ proto.updateStatus = function () { var node = this._node; - if(!node._sprite) + if (!node._sprite) return; var flags = cc.Node._dirtyFlags, locFlag = this._dirtyFlag; var spriteCmd = node._sprite._renderCmd; @@ -256,23 +258,23 @@ var colorDirty = spriteFlag & flags.colorDirty, opacityDirty = spriteFlag & flags.opacityDirty; - if(colorDirty){ + if (colorDirty) { spriteCmd._updateDisplayColor(); spriteCmd._dirtyFlag = spriteCmd._dirtyFlag & flags.colorDirty ^ spriteCmd._dirtyFlag; this._dirtyFlag = this._dirtyFlag & flags.colorDirty ^ this._dirtyFlag; } - if(opacityDirty){ + if (opacityDirty) { spriteCmd._updateDisplayOpacity(); spriteCmd._dirtyFlag = spriteCmd._dirtyFlag & flags.opacityDirty ^ spriteCmd._dirtyFlag; this._dirtyFlag = this._dirtyFlag & flags.opacityDirty ^ this._dirtyFlag; } - if(colorDirty || opacityDirty){ + if (colorDirty || opacityDirty) { spriteCmd._updateColor(); } - if(locFlag & flags.transformDirty){ + if (locFlag & flags.transformDirty) { //update the transform this.transform(this.getParentRenderCmd(), true); } diff --git a/cocos2d/progress-timer/CCProgressTimerWebGLRenderCmd.js b/cocos2d/progress-timer/CCProgressTimerWebGLRenderCmd.js index 5602a4d6fc..c0f5911f7d 100644 --- a/cocos2d/progress-timer/CCProgressTimerWebGLRenderCmd.js +++ b/cocos2d/progress-timer/CCProgressTimerWebGLRenderCmd.js @@ -102,16 +102,16 @@ proto._syncStatus = function (parentCmd) { var node = this._node; - if(!node._sprite) + if (!node._sprite) return; var flags = cc.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; this._dirtyFlag = locFlag; @@ -121,19 +121,19 @@ var colorDirty = (locFlag | spriteFlag) & flags.colorDirty, opacityDirty = (locFlag | spriteFlag) & flags.opacityDirty; - if (colorDirty){ + if (colorDirty) { spriteCmd._syncDisplayColor(); spriteCmd._dirtyFlag &= ~flags.colorDirty; this._dirtyFlag &= ~flags.colorDirty; } - if (opacityDirty){ + if (opacityDirty) { spriteCmd._syncDisplayOpacity(); spriteCmd._dirtyFlag &= ~flags.opacityDirty; this._dirtyFlag &= ~flags.opacityDirty; } - if(colorDirty || opacityDirty){ + if (colorDirty || opacityDirty) { this._updateColor(); } @@ -152,7 +152,7 @@ proto.updateStatus = function () { var node = this._node; - if(!node._sprite) + if (!node._sprite) return; var flags = cc.Node._dirtyFlags, locFlag = this._dirtyFlag; var spriteCmd = node._sprite._renderCmd; @@ -161,23 +161,23 @@ var colorDirty = (locFlag | spriteFlag) & flags.colorDirty, opacityDirty = (locFlag | spriteFlag) & flags.opacityDirty; - if(colorDirty){ + if (colorDirty) { spriteCmd._updateDisplayColor(); spriteCmd._dirtyFlag = spriteCmd._dirtyFlag & flags.colorDirty ^ spriteCmd._dirtyFlag; this._dirtyFlag = this._dirtyFlag & flags.colorDirty ^ this._dirtyFlag; } - if(opacityDirty){ + if (opacityDirty) { spriteCmd._updateDisplayOpacity(); spriteCmd._dirtyFlag = spriteCmd._dirtyFlag & flags.opacityDirty ^ spriteCmd._dirtyFlag; this._dirtyFlag = this._dirtyFlag & flags.opacityDirty ^ this._dirtyFlag; } - if(colorDirty || opacityDirty){ + if (colorDirty || opacityDirty) { this._updateColor(); } - if(locFlag & flags.transformDirty){ + if (locFlag & flags.transformDirty) { //update the transform this.transform(this.getParentRenderCmd(), true); } @@ -192,7 +192,7 @@ } }; - proto.releaseData = function(){ + proto.releaseData = function () { if (this._vertexData) { //release all previous information var webglBuffer = this._vertexWebGLBuffer; @@ -238,9 +238,9 @@ proto._updateProgressData = function () { var node = this._node; var locType = node._type; - if(locType === cc.ProgressTimer.TYPE_RADIAL) + if (locType === cc.ProgressTimer.TYPE_RADIAL) this._updateRadial(); - else if(locType === cc.ProgressTimer.TYPE_BAR) + else if (locType === cc.ProgressTimer.TYPE_BAR) this._updateBar(); this._vertexDataDirty = true; }; @@ -260,7 +260,7 @@ *

* @private */ - proto._updateBar = function(){ + proto._updateBar = function () { var node = this._node; if (!node._sprite) return; @@ -268,7 +268,7 @@ var i, alpha = node._percentage / 100.0; var locBarChangeRate = node._barChangeRate; var alphaOffset = cc.pMult(cc.p((1.0 - locBarChangeRate.x) + alpha * locBarChangeRate.x, - (1.0 - locBarChangeRate.y) + alpha * locBarChangeRate.y), 0.5); + (1.0 - locBarChangeRate.y) + alpha * locBarChangeRate.y), 0.5); var min = cc.pSub(node._midPoint, alphaOffset), max = cc.pAdd(node._midPoint, alphaOffset); if (min.x < 0) { @@ -478,7 +478,7 @@ else return cc.p((locProTextCoords >> ((index << 1) + 1)) & 1, (locProTextCoords >> (index << 1)) & 1); } - return cc.p(0,0); + return cc.p(0, 0); }; proto._textureCoordFromAlphaPoint = function (coords, ax, ay) { @@ -510,7 +510,7 @@ vertex.z = this._node._vertexZ; }; - proto._updateColor = function(){ + proto._updateColor = function () { var sp = this._node._sprite; if (!this._vertexDataCount || !sp) return; diff --git a/cocos2d/render-texture/CCRenderTexture.js b/cocos2d/render-texture/CCRenderTexture.js index d0e6950e51..594142f914 100644 --- a/cocos2d/render-texture/CCRenderTexture.js +++ b/cocos2d/render-texture/CCRenderTexture.js @@ -77,26 +77,26 @@ cc.NextPOT = function (x) { * @property {cc.Color} clearColorVal - Clear color value, valid only when "autoDraw" is true. */ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{ - sprite:null, + sprite: null, - // - //

Code for "auto" update
- // Valid flags: GL_COLOR_BUFFER_BIT, GL_DEPTH_BUFFER_BIT, GL_STENCIL_BUFFER_BIT.
- // They can be OR'ed. Valid when "autoDraw is YES.

- // @public - // - clearFlags:0, + // + //

Code for "auto" update
+ // Valid flags: GL_COLOR_BUFFER_BIT, GL_DEPTH_BUFFER_BIT, GL_STENCIL_BUFFER_BIT.
+ // They can be OR'ed. Valid when "autoDraw is YES.

+ // @public + // + clearFlags: 0, - clearDepthVal:0, - autoDraw:false, + clearDepthVal: 0, + autoDraw: false, - _texture:null, - _pixelFormat:0, + _texture: null, + _pixelFormat: 0, - clearStencilVal:0, - _clearColor:null, + clearStencilVal: 0, + _clearColor: null, - _className:"RenderTexture", + _className: "RenderTexture", /** * creates a RenderTexture object with width and height in Points and a pixel format, only RGB and RGBA formats are valid @@ -110,23 +110,23 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{ * var rt = new cc.RenderTexture(width, height, format, depthStencilFormat) * @function */ - ctor: function(width, height, format, depthStencilFormat){ + ctor: function (width, height, format, depthStencilFormat) { cc.Node.prototype.ctor.call(this); this._cascadeColorEnabled = true; this._cascadeOpacityEnabled = true; this._pixelFormat = cc.Texture2D.PIXEL_FORMAT_RGBA8888; - this._clearColor = new cc.Color(0,0,0,255); + this._clearColor = new cc.Color(0, 0, 0, 255); - if(width !== undefined && height !== undefined) { + if (width !== undefined && height !== undefined) { format = format || cc.Texture2D.PIXEL_FORMAT_RGBA8888; depthStencilFormat = depthStencilFormat || 0; this.initWithWidthAndHeight(width, height, format, depthStencilFormat); } - this.setAnchorPoint(0,0); + this.setAnchorPoint(0, 0); }, - _createRenderCmd: function(){ - if(cc._renderType === cc.game.RENDER_TYPE_CANVAS) + _createRenderCmd: function () { + if (cc._renderType === cc.game.RENDER_TYPE_CANVAS) return new cc.RenderTexture.CanvasRenderCmd(this); else return new cc.RenderTexture.WebGLRenderCmd(this); @@ -136,7 +136,7 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{ * Clear RenderTexture. * @function */ - cleanup: function(){ + cleanup: function () { cc.Node.prototype.onExit.call(this); this._renderCmd.cleanup(); }, @@ -145,7 +145,7 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{ * Gets the sprite * @return {cc.Sprite} */ - getSprite:function () { + getSprite: function () { return this.sprite; }, @@ -153,7 +153,7 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{ * Set the sprite * @param {cc.Sprite} sprite */ - setSprite:function (sprite) { + setSprite: function (sprite) { this.sprite = sprite; }, @@ -163,8 +163,8 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{ * @param {cc.Rect} fullRect * @param {cc.Rect} fullViewport */ - setVirtualViewport: function(rtBegin, fullRect, fullViewport){ - this._renderCmd.setVirtualViewport(rtBegin, fullRect, fullViewport); + setVirtualViewport: function (rtBegin, fullRect, fullViewport) { + this._renderCmd.setVirtualViewport(rtBegin, fullRect, fullViewport); }, /** @@ -176,7 +176,7 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{ * @param {Number} [depthStencilFormat] * @return {Boolean} */ - initWithWidthAndHeight: function(width, height, format, depthStencilFormat){ + initWithWidthAndHeight: function (width, height, format, depthStencilFormat) { return this._renderCmd.initWithWidthAndHeight(width, height, format, depthStencilFormat); }, @@ -184,7 +184,7 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{ * starts grabbing * @function */ - begin: function(){ + begin: function () { cc.renderer._turnToCacheMode(this.__instanceId); this._renderCmd.begin(); }, @@ -198,16 +198,16 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{ * @param {Number} [depthValue=] * @param {Number} [stencilValue=] */ - beginWithClear:function (r, g, b, a, depthValue, stencilValue) { + beginWithClear: function (r, g, b, a, depthValue, stencilValue) { //todo: only for WebGL? var gl = cc._renderContext; depthValue = depthValue || gl.COLOR_BUFFER_BIT; stencilValue = stencilValue || (gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); - this._beginWithClear(r , g , b , a , depthValue, stencilValue, (gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT | gl.STENCIL_BUFFER_BIT)); + this._beginWithClear(r, g, b, a, depthValue, stencilValue, (gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT | gl.STENCIL_BUFFER_BIT)); }, - _beginWithClear: function(r, g, b, a, depthValue, stencilValue, flags){ + _beginWithClear: function (r, g, b, a, depthValue, stencilValue, flags) { this.begin(); this._renderCmd._beginWithClear(r, g, b, a, depthValue, stencilValue, flags); }, @@ -216,7 +216,7 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{ * ends grabbing * @function */ - end: function(){ + end: function () { this._renderCmd.end(); }, @@ -227,7 +227,7 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{ * @param {Number} b blue 0-1 * @param {Number} a alpha 0-1 */ - clear:function (r, g, b, a) { + clear: function (r, g, b, a) { this.beginWithClear(r, g, b, a); this.end(); }, @@ -240,7 +240,7 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{ * @param {number} width * @param {number} height */ - clearRect: function(x, y, width, height){ + clearRect: function (x, y, width, height) { this._renderCmd.clearRect(x, y, width, height); }, @@ -249,7 +249,7 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{ * @function * @param {Number} depthValue */ - clearDepth: function(depthValue){ + clearDepth: function (depthValue) { this._renderCmd.clearDepth(depthValue); }, @@ -258,7 +258,7 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{ * @function * @param {Number} stencilValue */ - clearStencil: function(stencilValue) { + clearStencil: function (stencilValue) { this._renderCmd.clearStencil(stencilValue); }, @@ -266,7 +266,7 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{ * Valid flags: GL_COLOR_BUFFER_BIT, GL_DEPTH_BUFFER_BIT, GL_STENCIL_BUFFER_BIT. They can be OR'ed. Valid when "autoDraw is YES. * @return {Number} */ - getClearFlags:function () { + getClearFlags: function () { return this.clearFlags; }, @@ -274,7 +274,7 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{ * Set the clearFlags * @param {Number} clearFlags */ - setClearFlags:function (clearFlags) { + setClearFlags: function (clearFlags) { this.clearFlags = clearFlags; }, @@ -283,16 +283,16 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{ * @function * @return {cc.Color} */ - getClearColor:function () { + getClearColor: function () { return this._clearColor; }, - /** - * Set the clear color value. Valid only when "autoDraw" is true. - * @function - * @param {cc.Color} clearColor The clear color - */ - setClearColor: function(clearColor){ + /** + * Set the clear color value. Valid only when "autoDraw" is true. + * @function + * @param {cc.Color} clearColor The clear color + */ + setClearColor: function (clearColor) { var locClearColor = this._clearColor; locClearColor.r = clearColor.r; locClearColor.g = clearColor.g; @@ -305,7 +305,7 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{ * Value for clearDepth. Valid only when autoDraw is true. * @return {Number} */ - getClearDepth:function () { + getClearDepth: function () { return this.clearDepthVal; }, @@ -313,7 +313,7 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{ * Set value for clearDepth. Valid only when autoDraw is true. * @param {Number} clearDepth */ - setClearDepth:function (clearDepth) { + setClearDepth: function (clearDepth) { this.clearDepthVal = clearDepth; }, @@ -321,7 +321,7 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{ * Value for clear Stencil. Valid only when autoDraw is true * @return {Number} */ - getClearStencil:function () { + getClearStencil: function () { return this.clearStencilVal; }, @@ -329,7 +329,7 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{ * Set value for clear Stencil. Valid only when autoDraw is true * @return {Number} */ - setClearStencil:function (clearStencil) { + setClearStencil: function (clearStencil) { this.clearStencilVal = clearStencil; }, @@ -338,7 +338,7 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{ * Will be enabled in the future. * @return {Boolean} */ - isAutoDraw:function () { + isAutoDraw: function () { return this.autoDraw; }, @@ -347,7 +347,7 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{ * Will be enabled in the future. * @return {Boolean} */ - setAutoDraw:function (autoDraw) { + setAutoDraw: function (autoDraw) { this.autoDraw = autoDraw; }, @@ -359,7 +359,7 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{ * @param {Number} filePath * @param {Number} format */ - saveToFile:function (filePath, format) { + saveToFile: function (filePath, format) { cc.log("saveToFile isn't supported on Cocos2d-Html5"); }, @@ -367,7 +367,7 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{ * creates a new CCImage from with the texture's data. Caller is responsible for releasing it by calling delete. * @return {*} */ - newCCImage:function(flipImage){ + newCCImage: function (flipImage) { cc.log("saveToFile isn't supported on cocos2d-html5"); return null; }, @@ -376,13 +376,15 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{ * Listen "come to background" message, and save render texture. It only has effect on Android. * @param {cc.Class} obj */ - listenToBackground:function (obj) { }, + listenToBackground: function (obj) { + }, /** * Listen "come to foreground" message and restore the frame buffer object. It only has effect on Android. * @param {cc.Class} obj */ - listenToForeground:function (obj) { } + listenToForeground: function (obj) { + } }); var _p = cc.RenderTexture.prototype; diff --git a/cocos2d/render-texture/CCRenderTextureCanvasRenderCmd.js b/cocos2d/render-texture/CCRenderTextureCanvasRenderCmd.js index c79b36f34d..3d20f4002b 100644 --- a/cocos2d/render-texture/CCRenderTextureCanvasRenderCmd.js +++ b/cocos2d/render-texture/CCRenderTextureCanvasRenderCmd.js @@ -35,20 +35,22 @@ var proto = cc.RenderTexture.CanvasRenderCmd.prototype = Object.create(cc.Node.CanvasRenderCmd.prototype); proto.constructor = cc.RenderTexture.CanvasRenderCmd; - proto.cleanup = function(){ + proto.cleanup = function () { this._cacheContext = null; this._cacheCanvas = null; }; - proto.clearStencil = function (stencilValue) { }; + proto.clearStencil = function (stencilValue) { + }; - proto.setVirtualViewport = function(rtBegin, fullRect, fullViewport) {}; + proto.setVirtualViewport = function (rtBegin, fullRect, fullViewport) { + }; - proto.updateClearColor = function(clearColor){ + proto.updateClearColor = function (clearColor) { this._clearColorStr = "rgba(" + (0 | clearColor.r) + "," + (0 | clearColor.g) + "," + (0 | clearColor.b) + "," + clearColor.a / 255 + ")"; }; - proto.initWithWidthAndHeight = function(width, height, format, depthStencilFormat){ + proto.initWithWidthAndHeight = function (width, height, format, depthStencilFormat) { var node = this._node; var locCacheCanvas = this._cacheCanvas, locScaleFactor = cc.contentScaleFactor(); locCacheCanvas.width = 0 | (width * locScaleFactor); @@ -67,9 +69,10 @@ return true; }; - proto.begin = function(){}; + proto.begin = function () { + }; - proto._beginWithClear = function(r, g, b, a, depthValue, stencilValue, flags){ + proto._beginWithClear = function (r, g, b, a, depthValue, stencilValue, flags) { r = r || 0; g = g || 0; b = b || 0; @@ -77,13 +80,13 @@ var context = this._cacheContext.getContext(); var locCanvas = this._cacheCanvas; - context.setTransform(1,0,0,1,0,0); + context.setTransform(1, 0, 0, 1, 0, 0); this._cacheContext.setFillStyle("rgba(" + (0 | r) + "," + (0 | g) + "," + (0 | b) + "," + a / 255 + ")"); context.clearRect(0, 0, locCanvas.width, locCanvas.height); context.fillRect(0, 0, locCanvas.width, locCanvas.height); }; - proto.end = function(){ + proto.end = function () { var node = this._node; var scale = cc.contentScaleFactor(); @@ -92,11 +95,11 @@ spriteRenderCmd._notifyRegionStatus && spriteRenderCmd._notifyRegionStatus(cc.Node.CanvasRenderCmd.RegionStatus.Dirty); }; - proto.clearRect = function(x, y, width, height){ + proto.clearRect = function (x, y, width, height) { this._cacheContext.clearRect(x, y, width, -height); }; - proto.clearDepth = function(depthValue){ + proto.clearDepth = function (depthValue) { cc.log("clearDepth isn't supported on Cocos2d-Html5"); }; @@ -106,4 +109,4 @@ node.sprite.visit(this); this._dirtyFlag = 0; }; -})(); \ No newline at end of file +})(); diff --git a/cocos2d/render-texture/CCRenderTextureWebGLRenderCmd.js b/cocos2d/render-texture/CCRenderTextureWebGLRenderCmd.js index dd25b8bf73..84c2407e88 100644 --- a/cocos2d/render-texture/CCRenderTextureWebGLRenderCmd.js +++ b/cocos2d/render-texture/CCRenderTextureWebGLRenderCmd.js @@ -40,7 +40,7 @@ var proto = cc.RenderTexture.WebGLRenderCmd.prototype = Object.create(cc.Node.WebGLRenderCmd.prototype); proto.constructor = cc.RenderTexture.WebGLRenderCmd; - proto.setVirtualViewport = function(rtBegin, fullRect, fullViewport) { + proto.setVirtualViewport = function (rtBegin, fullRect, fullViewport) { this._rtTextureRect.x = rtBegin.x; this._rtTextureRect.y = rtBegin.y; @@ -99,7 +99,7 @@ var locChildren = node._children; for (var i = 0; i < locChildren.length; i++) { var getChild = locChildren[i]; - if (getChild !== node.sprite){ + if (getChild !== node.sprite) { getChild._renderCmd.visit(node.sprite._renderCmd); //TODO it's very Strange } } @@ -107,7 +107,7 @@ } }; - proto.clearStencil = function(stencilValue) { + proto.clearStencil = function (stencilValue) { var gl = cc._renderContext; // save old stencil value var stencilClearValue = gl.getParameter(gl.STENCIL_CLEAR_VALUE); @@ -119,7 +119,7 @@ gl.clearStencil(stencilClearValue); }; - proto.cleanup = function(){ + proto.cleanup = function () { var node = this._node; //node.sprite = null; this._textureCopy = null; @@ -130,16 +130,17 @@ gl.deleteRenderbuffer(this._depthRenderBuffer); }; - proto.updateClearColor = function(clearColor){ }; + proto.updateClearColor = function (clearColor) { + }; - proto.initWithWidthAndHeight = function(width, height, format, depthStencilFormat){ + proto.initWithWidthAndHeight = function (width, height, format, depthStencilFormat) { var node = this._node; - if(format === cc.Texture2D.PIXEL_FORMAT_A8) - cc.log( "cc.RenderTexture._initWithWidthAndHeightForWebGL() : only RGB and RGBA formats are valid for a render texture;"); + if (format === cc.Texture2D.PIXEL_FORMAT_A8) + cc.log("cc.RenderTexture._initWithWidthAndHeightForWebGL() : only RGB and RGBA formats are valid for a render texture;"); var gl = cc._renderContext, locScaleFactor = cc.contentScaleFactor(); - this._fullRect = new cc.Rect(0,0, width, height); - this._fullViewport = new cc.Rect(0,0, width, height); + this._fullRect = new cc.Rect(0, 0, width, height); + this._fullViewport = new cc.Rect(0, 0, width, height); width = 0 | (width * locScaleFactor); height = 0 | (height * locScaleFactor); @@ -147,7 +148,7 @@ this._oldFBO = gl.getParameter(gl.FRAMEBUFFER_BINDING); // textures must be power of two squared - var powW , powH; + var powW, powH; if (cc.configuration.supportsNPOT()) { powW = width; @@ -194,16 +195,16 @@ this._depthRenderBuffer = gl.createRenderbuffer(); gl.bindRenderbuffer(gl.RENDERBUFFER, this._depthRenderBuffer); gl.renderbufferStorage(gl.RENDERBUFFER, depthStencilFormat, powW, powH); - if(depthStencilFormat === gl.DEPTH_STENCIL) + if (depthStencilFormat === gl.DEPTH_STENCIL) gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, this._depthRenderBuffer); - else if(depthStencilFormat === gl.STENCIL_INDEX || depthStencilFormat === gl.STENCIL_INDEX8) + else if (depthStencilFormat === gl.STENCIL_INDEX || depthStencilFormat === gl.STENCIL_INDEX8) gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.STENCIL_ATTACHMENT, gl.RENDERBUFFER, this._depthRenderBuffer); - else if(depthStencilFormat === gl.DEPTH_COMPONENT16) + else if (depthStencilFormat === gl.DEPTH_COMPONENT16) gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, this._depthRenderBuffer); } // check if it worked (probably worth doing :) ) - if(gl.checkFramebufferStatus(gl.FRAMEBUFFER) !== gl.FRAMEBUFFER_COMPLETE) + if (gl.checkFramebufferStatus(gl.FRAMEBUFFER) !== gl.FRAMEBUFFER_COMPLETE) cc.log("Could not attach texture to the framebuffer"); locTexture.setAliasTexParameters(); @@ -223,7 +224,7 @@ return true; }; - proto.begin = function(){ + proto.begin = function () { var node = this._node; // Save the current matrix cc.kmGLMatrixMode(cc.KM_GL_PROJECTION); @@ -274,7 +275,7 @@ } }; - proto._beginWithClear = function(r, g, b, a, depthValue, stencilValue, flags){ + proto._beginWithClear = function (r, g, b, a, depthValue, stencilValue, flags) { r = r / 255; g = g / 255; b = b / 255; @@ -315,7 +316,7 @@ gl.clearStencil(stencilClearValue); }; - proto.end = function(){ + proto.end = function () { var node = this._node; cc.renderer._renderingToBuffer(node.__instanceId); @@ -343,11 +344,11 @@ director.setProjection(director.getProjection());*/ }; - proto.clearRect = function(x, y, width, height){ + proto.clearRect = function (x, y, width, height) { //TODO need to implement }; - proto.clearDepth = function(depthValue){ + proto.clearDepth = function (depthValue) { var node = this._node; node.begin(); @@ -363,7 +364,7 @@ node.end(); }; - proto.visit = function(parentCmd){ + proto.visit = function (parentCmd) { var node = this._node; if (!node._visible) return; diff --git a/cocos2d/shaders/CCGLProgram.js b/cocos2d/shaders/CCGLProgram.js index 829584886f..af365ff69c 100644 --- a/cocos2d/shaders/CCGLProgram.js +++ b/cocos2d/shaders/CCGLProgram.js @@ -59,10 +59,10 @@ cc.GLProgram = cc.Class.extend(/** @lends cc.GLProgram# */{ updated = true; } else { updated = false; - var count = arguments.length-1; + var count = arguments.length - 1; for (var i = 0; i < count; ++i) { - if (arguments[i+1] !== element[i]) { - element[i] = arguments[i+1]; + if (arguments[i + 1] !== element[i]) { + element[i] = arguments[i + 1]; updated = true; } } @@ -106,18 +106,18 @@ cc.GLProgram = cc.Class.extend(/** @lends cc.GLProgram# */{ return ( status === true ); }, - /** - * Create a cc.GLProgram object - * @param {String} vShaderFileName - * @param {String} fShaderFileName - * @returns {cc.GLProgram} - */ + /** + * Create a cc.GLProgram object + * @param {String} vShaderFileName + * @param {String} fShaderFileName + * @returns {cc.GLProgram} + */ ctor: function (vShaderFileName, fShaderFileName, glContext) { this._uniforms = {}; this._hashForUniforms = {}; this._glContext = glContext || cc._renderContext; - vShaderFileName && fShaderFileName && this.init(vShaderFileName, fShaderFileName); + vShaderFileName && fShaderFileName && this.init(vShaderFileName, fShaderFileName); }, /** @@ -194,9 +194,9 @@ cc.GLProgram = cc.Class.extend(/** @lends cc.GLProgram# */{ */ initWithVertexShaderFilename: function (vShaderFilename, fShaderFileName) { var vertexSource = cc.loader.getRes(vShaderFilename); - if(!vertexSource) throw new Error("Please load the resource firset : " + vShaderFilename); + if (!vertexSource) throw new Error("Please load the resource firset : " + vShaderFilename); var fragmentSource = cc.loader.getRes(fShaderFileName); - if(!fragmentSource) throw new Error("Please load the resource firset : " + fShaderFileName); + if (!fragmentSource) throw new Error("Please load the resource firset : " + fShaderFileName); return this.initWithVertexShaderByteArray(vertexSource, fragmentSource); }, @@ -224,7 +224,7 @@ cc.GLProgram = cc.Class.extend(/** @lends cc.GLProgram# */{ * @return {Boolean} */ link: function () { - if(!this._programObj) { + if (!this._programObj) { cc.log("cc.GLProgram.link(): Cannot link invalid program"); return false; } @@ -418,7 +418,7 @@ cc.GLProgram = cc.Class.extend(/** @lends cc.GLProgram# */{ * @param {WebGLUniformLocation|String} location * @param {Int32Array} intArray */ - setUniformLocationWith3iv:function(location, intArray){ + setUniformLocationWith3iv: function (location, intArray) { var locObj = typeof location === 'string' ? this.getUniformLocationForName(location) : location; this._glContext.uniform3iv(locObj, intArray); }, @@ -428,7 +428,7 @@ cc.GLProgram = cc.Class.extend(/** @lends cc.GLProgram# */{ * @param {WebGLUniformLocation|String} location * @param {Int32Array} intArray */ - setUniformLocationWith4iv:function(location, intArray){ + setUniformLocationWith4iv: function (location, intArray) { var locObj = typeof location === 'string' ? this.getUniformLocationForName(location) : location; this._glContext.uniform4iv(locObj, intArray); }, @@ -627,7 +627,7 @@ cc.GLProgram = cc.Class.extend(/** @lends cc.GLProgram# */{ }, _setUniformsForBuiltinsForRenderer: function (node) { - if(!node || !node._renderCmd) + if (!node || !node._renderCmd) return; var matrixP = new cc.math.Matrix4(); @@ -664,7 +664,7 @@ cc.GLProgram = cc.Class.extend(/** @lends cc.GLProgram# */{ */ setUniformForModelViewProjectionMatrix: function () { this._glContext.uniformMatrix4fv(this._uniforms[cc.UNIFORM_MVPMATRIX_S], false, - cc.getMat4MultiplyValue(cc.projection_matrix_stack.top, cc.modelview_matrix_stack.top)); + cc.getMat4MultiplyValue(cc.projection_matrix_stack.top, cc.modelview_matrix_stack.top)); }, setUniformForModelViewProjectionMatrixWithMat4: function (swapMat4) { @@ -677,8 +677,8 @@ cc.GLProgram = cc.Class.extend(/** @lends cc.GLProgram# */{ this._glContext.uniformMatrix4fv(this._uniforms[cc.UNIFORM_PMATRIX_S], false, cc.projection_matrix_stack.top.mat); }, - _setUniformForMVPMatrixWithMat4: function(modelViewMatrix){ - if(!modelViewMatrix) + _setUniformForMVPMatrixWithMat4: function (modelViewMatrix) { + if (!modelViewMatrix) throw new Error("modelView matrix is undefined."); this._glContext.uniformMatrix4fv(this._uniforms[cc.UNIFORM_MVMATRIX_S], false, modelViewMatrix.mat); this._glContext.uniformMatrix4fv(this._uniforms[cc.UNIFORM_PMATRIX_S], false, cc.projection_matrix_stack.top.mat); @@ -789,8 +789,8 @@ cc.GLProgram.create = function (vShaderFileName, fShaderFileName) { cc.GLProgram._highpSupported = null; -cc.GLProgram._isHighpSupported = function(){ - if(cc.GLProgram._highpSupported == null){ +cc.GLProgram._isHighpSupported = function () { + if (cc.GLProgram._highpSupported == null) { var ctx = cc._renderContext; var highp = ctx.getShaderPrecisionFormat(ctx.FRAGMENT_SHADER, ctx.HIGH_FLOAT); cc.GLProgram._highpSupported = highp.precision !== 0; diff --git a/cocos2d/shape-nodes/CCDrawNode.js b/cocos2d/shape-nodes/CCDrawNode.js index e6a4dfb80e..732bd8cda8 100644 --- a/cocos2d/shape-nodes/CCDrawNode.js +++ b/cocos2d/shape-nodes/CCDrawNode.js @@ -36,8 +36,8 @@ cc.DrawNode = cc.Node.extend(/** @lends cc.DrawNode# */{ //TODO need refactor - _buffer:null, - _blendFunc:null, + _buffer: null, + _blendFunc: null, _lineWidth: 1, _drawColor: null, @@ -97,7 +97,7 @@ cc.DrawNode = cc.Node.extend(/** @lends cc.DrawNode# */{ * @returns {cc.Color} */ getDrawColor: function () { - return cc.color(this._drawColor.r, this._drawColor.g, this._drawColor.b, this._drawColor.a); + return cc.color(this._drawColor.r, this._drawColor.g, this._drawColor.b, this._drawColor.a); } }); @@ -116,7 +116,7 @@ cc.DrawNode.TYPE_POLY = 2; cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () { - function pMultOut (pin, floatVar, pout) { + function pMultOut(pin, floatVar, pout) { pout.x = pin.x * floatVar; pout.y = pin.y * floatVar; } @@ -137,7 +137,7 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () { }; cc.extend(cc.DrawNode.prototype, /** @lends cc.DrawNode# */{ - _className:"DrawNodeCanvas", + _className: "DrawNodeCanvas", /** *

The cc.DrawNodeCanvas's constructor.
@@ -155,9 +155,9 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () { this._localBB = new cc.Rect(); }, - setLocalBB: function(rectorX, y, width, height) { + setLocalBB: function (rectorX, y, width, height) { var localBB = this._localBB; - if(y === undefined) { + if (y === undefined) { localBB.x = rectorX.x; localBB.y = rectorX.y; localBB.width = rectorX.width; @@ -180,7 +180,7 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () { drawRect: function (origin, destination, fillColor, lineWidth, lineColor) { lineWidth = (lineWidth == null) ? this._lineWidth : lineWidth; lineColor = lineColor || this.getDrawColor(); - if(lineColor.a == null) + if (lineColor.a == null) lineColor.a = 255; var vertices = [ @@ -198,7 +198,7 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () { element.lineCap = "butt"; element.fillColor = fillColor; if (fillColor) { - if(fillColor.a == null) + if (fillColor.a == null) fillColor.a = 255; element.isFill = true; } @@ -336,7 +336,7 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () { drawCardinalSpline: function (config, tension, segments, lineWidth, color) { lineWidth = lineWidth || this._lineWidth; color = color || this.getDrawColor(); - if(color.a == null) + if (color.a == null) color.a = 255; var vertices = [], p, lt, deltaT = 1.0 / config.length; @@ -394,14 +394,14 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () { * @param {Number} radius * @param {cc.Color} [color] */ - drawDots: function(points, radius, color){ - if(!points || points.length == 0) + drawDots: function (points, radius, color) { + if (!points || points.length == 0) return; color = color || this.getDrawColor(); if (color.a == null) color.a = 255; - for(var i = 0, len = points.length; i < len; i++) - this.drawDot(points[i], radius, color); + for (var i = 0, len = points.length; i < len; i++) + this.drawDot(points[i], radius, color); }, /** @@ -460,7 +460,7 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () { */ drawPoly: function (verts, fillColor, lineWidth, lineColor) { var vertsCopy = []; - for (var i=0; i < verts.length; i++) { + for (var i = 0; i < verts.length; i++) { vertsCopy.push(cc.p(verts[i].x, verts[i].y)); } return this.drawPoly_(vertsCopy, fillColor, lineWidth, lineColor); @@ -473,7 +473,7 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () { this._buffer.length = 0; }, - _createRenderCmd: function(){ + _createRenderCmd: function () { return new cc.DrawNode.CanvasRenderCmd(this); } }); @@ -559,7 +559,7 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () { if (prev !== 0) { _sharedBuffer.freeBuffer(prevOffset, VERTEX_BYTE * prev); _t._occupiedSize = 0; - } + } var offset = _t._offset = _sharedBuffer.requestBuffer(VERTEX_BYTE * request); if (offset >= 0) { _t._occupiedSize = _t._bufferCapacity = request; @@ -571,7 +571,7 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () { if (prev !== 0 && prevOffset !== offset) { // offset is in byte, we need to transform to float32 index var last = (prevOffset + prev) / 4; - for (var i = offset/4, j = prevOffset/4; j < last; i++, j++) { + for (var i = offset / 4, j = prevOffset / 4; j < last; i++, j++) { _sharedBuffer.dataArray[i] = _sharedBuffer.dataArray[j]; } } @@ -593,7 +593,7 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () { lineColor = lineColor || this._drawColor; _vertices.length = 0; _vertices.push(origin.x, origin.y, destination.x, origin.y, destination.x, destination.y, origin.x, destination.y); - if(fillColor == null) + if (fillColor == null) this._drawSegments(_vertices, lineWidth, lineColor, true); else this.drawPoly(_vertices, fillColor, lineWidth, lineColor); @@ -700,16 +700,16 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () { _vertices.length = 0; }, - drawDots: function(points, radius,color) { - if(!points || points.length === 0) + drawDots: function (points, radius, color) { + if (!points || points.length === 0) return; color = color || this._drawColor; - for(var i = 0, len = points.length; i < len; i++) { + for (var i = 0, len = points.length; i < len; i++) { this.drawDot(points[i], radius, color); } }, - _render:function () { + _render: function () { var gl = cc._renderContext; if (this._offset < 0 || this._vertexCount <= 0) { return; @@ -746,14 +746,14 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () { var offset = this._vertexCount * FLOAT_PER_VERTEX; f32Buffer[offset] = x; f32Buffer[offset + 1] = y; - _color[0] = ((color.a<<24) | (color.b<<16) | (color.g<<8) | color.r); + _color[0] = ((color.a << 24) | (color.b << 16) | (color.g << 8) | color.r); this._ui32Buffer[offset + 2] = _color[0]; f32Buffer[offset + 3] = u; f32Buffer[offset + 4] = v; this._vertexCount++; }, - drawDot:function (pos, radius, color) { + drawDot: function (pos, radius, color) { color = color || this._drawColor; if (color.a == null) color.a = 255; @@ -764,7 +764,7 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () { var vertexCount = 2 * 3; var succeed = this._ensureCapacity(this._vertexCount + vertexCount); - if (!succeed) + if (!succeed) return; // lb, lt, rt, lb, rt, rb @@ -778,14 +778,14 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () { this._dirty = true; }, - drawSegment:function (from, to, radius, color) { + drawSegment: function (from, to, radius, color) { color = color || this.getDrawColor(); if (color.a == null) color.a = 255; radius = radius || (this._lineWidth * 0.5); var vertexCount = 6 * 3; var succeed = this._ensureCapacity(this._vertexCount + vertexCount); - if (!succeed) + if (!succeed) return; var a = from, b = to; @@ -841,7 +841,7 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () { this._dirty = true; }, - drawPoly:function (verts, fillColor, borderWidth, borderColor) { + drawPoly: function (verts, fillColor, borderWidth, borderColor) { // Backward compatibility if (typeof verts[0] === 'object') { _vertices.length = 0; @@ -859,9 +859,9 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () { fillColor.a = 255; if (borderColor.a == null) borderColor.a = 255; - borderWidth = (borderWidth == null)? this._lineWidth : borderWidth; + borderWidth = (borderWidth == null) ? this._lineWidth : borderWidth; borderWidth *= 0.5; - var v0x, v0y, v1x, v1y, v2x, v2y, + var v0x, v0y, v1x, v1y, v2x, v2y, factor, offx, offy, i, count = verts.length; _extrude.length = 0; @@ -889,7 +889,7 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () { count = count / 2; var outline = (borderWidth > 0.0), triangleCount = 3 * count - 2, vertexCount = 3 * triangleCount; var succeed = this._ensureCapacity(this._vertexCount + vertexCount); - if (!succeed) + if (!succeed) return; var inset = (outline == false ? 0.5 : 0.0); @@ -898,18 +898,18 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () { v0x = verts[0] - _extrude[0] * inset; v0y = verts[1] - _extrude[1] * inset; // v1 = sub(verts[i + 1], multi(extrude[i + 1].offset, inset)); - v1x = verts[i * 2 + 2] - _extrude[(i+1) * 4] * inset; - v1y = verts[i * 2 + 3] - _extrude[(i+1) * 4 + 1] * inset; + v1x = verts[i * 2 + 2] - _extrude[(i + 1) * 4] * inset; + v1y = verts[i * 2 + 3] - _extrude[(i + 1) * 4 + 1] * inset; // v2 = sub(verts[i + 2], multi(extrude[i + 2].offset, inset)); - v2x = verts[i * 2 + 4] - _extrude[(i+2) * 4] * inset; - v2y = verts[i * 2 + 5] - _extrude[(i+2) * 4 + 1] * inset; + v2x = verts[i * 2 + 4] - _extrude[(i + 2) * 4] * inset; + v2y = verts[i * 2 + 5] - _extrude[(i + 2) * 4 + 1] * inset; this.appendVertexData(v0x, v0y, fillColor, 0, 0); this.appendVertexData(v1x, v1y, fillColor, 0, 0); this.appendVertexData(v2x, v2y, fillColor, 0, 0); } - var off0x, off0y, off1x, off1y, + var off0x, off0y, off1x, off1y, bw = outline ? borderWidth : 0.5, color = outline ? borderColor : fillColor, in0x, in0y, in1x, in1y, out0x, out0y, out1x, out1y; @@ -947,17 +947,17 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () { this._dirty = true; }, - _drawSegments: function(verts, borderWidth, borderColor, closePoly){ + _drawSegments: function (verts, borderWidth, borderColor, closePoly) { borderWidth = (borderWidth == null) ? this._lineWidth : borderWidth; if (borderWidth <= 0) return; borderColor = borderColor || this._drawColor; - if(borderColor.a == null) + if (borderColor.a == null) borderColor.a = 255; borderWidth *= 0.5; - var v0x, v0y, v1x, v1y, v2x, v2y, + var v0x, v0y, v1x, v1y, v2x, v2y, factor, offx, offy, i, count = verts.length; _extrude.length = 0; @@ -986,11 +986,11 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () { count = count / 2; var triangleCount = 3 * count - 2, vertexCount = 3 * triangleCount; var succeed = this._ensureCapacity(this._vertexCount + vertexCount); - if (!succeed) + if (!succeed) return; var len = closePoly ? count : count - 1, - off0x, off0y, off1x, off1y, + off0x, off0y, off1x, off1y, in0x, in0y, in1x, in1y, out0x, out0y, out1x, out1y; for (i = 0; i < len; i++) { var j = (i + 1) % count; @@ -1022,7 +1022,7 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () { this._dirty = true; }, - clear:function () { + clear: function () { this.release(); this._dirty = true; }, diff --git a/cocos2d/shape-nodes/CCDrawNodeCanvasRenderCmd.js b/cocos2d/shape-nodes/CCDrawNodeCanvasRenderCmd.js index 19d04e2937..a19ded7bf3 100644 --- a/cocos2d/shape-nodes/CCDrawNodeCanvasRenderCmd.js +++ b/cocos2d/shape-nodes/CCDrawNodeCanvasRenderCmd.js @@ -22,7 +22,7 @@ THE SOFTWARE. ****************************************************************************/ -(function(){ +(function () { cc.DrawNode.CanvasRenderCmd = function(renderableObject){ cc.Node.CanvasRenderCmd.call(this, renderableObject); @@ -41,7 +41,7 @@ return node._localBB; }; - cc.extend( cc.DrawNode.CanvasRenderCmd.prototype, { + cc.extend(cc.DrawNode.CanvasRenderCmd.prototype, { rendering: function (ctx, scaleX, scaleY) { var wrapper = ctx || cc._renderContext, context = wrapper.getContext(), node = this._node; var alpha = node._displayedOpacity / 255; @@ -79,7 +79,7 @@ wrapper.setFillStyle("rgba(" + (0 | locColor.r) + "," + (0 | locColor.g) + "," + (0 | locColor.b) + "," + locColor.a / 255 + ")"); ctx.beginPath(); - ctx.arc(locPos.x , -locPos.y , locRadius , 0, Math.PI * 2, false); + ctx.arc(locPos.x, -locPos.y, locRadius, 0, Math.PI * 2, false); ctx.closePath(); ctx.fill(); }, @@ -95,8 +95,8 @@ ctx.lineWidth = locLineWidth * scaleX; ctx.beginPath(); ctx.lineCap = locLineCap; - ctx.moveTo(locFrom.x , -locFrom.y ); - ctx.lineTo(locTo.x , -locTo.y ); + ctx.moveTo(locFrom.x, -locFrom.y); + ctx.lineTo(locTo.x, -locTo.y); ctx.stroke(); }, @@ -122,9 +122,9 @@ + (0 | locLineColor.b) + "," + locLineColor.a / 255 + ")"); ctx.beginPath(); - ctx.moveTo(firstPoint.x , -firstPoint.y ); + ctx.moveTo(firstPoint.x, -firstPoint.y); for (var i = 1, len = locVertices.length; i < len; i++) - ctx.lineTo(locVertices[i].x , -locVertices[i].y ); + ctx.lineTo(locVertices[i].x, -locVertices[i].y); if (locIsClosePolygon) ctx.closePath(); diff --git a/cocos2d/shape-nodes/CCDrawNodeWebGLRenderCmd.js b/cocos2d/shape-nodes/CCDrawNodeWebGLRenderCmd.js index 468e13b56a..6c86d28833 100644 --- a/cocos2d/shape-nodes/CCDrawNodeWebGLRenderCmd.js +++ b/cocos2d/shape-nodes/CCDrawNodeWebGLRenderCmd.js @@ -50,4 +50,4 @@ node._render(); } }; -})(); \ No newline at end of file +})(); diff --git a/cocos2d/text-input/CCIMEDispatcher.js b/cocos2d/text-input/CCIMEDispatcher.js index 6e65e92c51..e22f6da1f1 100644 --- a/cocos2d/text-input/CCIMEDispatcher.js +++ b/cocos2d/text-input/CCIMEDispatcher.js @@ -45,27 +45,27 @@ cc.IMEDelegate = cc.Class.extend(/** @lends cc.IMEDelegate# */{ /** * Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function. */ - ctor:function () { + ctor: function () { cc.imeDispatcher.addDelegate(this); }, /** * Remove delegate */ - removeDelegate:function () { + removeDelegate: function () { cc.imeDispatcher.removeDelegate(this); }, /** * Remove delegate * @return {Boolean} */ - attachWithIME:function () { + attachWithIME: function () { return cc.imeDispatcher.attachDelegateWithIME(this); }, /** * Detach with IME * @return {Boolean} */ - detachWithIME:function () { + detachWithIME: function () { return cc.imeDispatcher.detachDelegateWithIME(this); }, @@ -74,60 +74,60 @@ cc.IMEDelegate = cc.Class.extend(/** @lends cc.IMEDelegate# */{ * Called by CCIMEDispatcher. * @return {Boolean} */ - canAttachWithIME:function () { + canAttachWithIME: function () { return false; }, /** * When the delegate detach with IME, this method call by CCIMEDispatcher. */ - didAttachWithIME:function () { + didAttachWithIME: function () { }, /** * Decide the delegate instance can stop receive ime message or not. * @return {Boolean} */ - canDetachWithIME:function () { + canDetachWithIME: function () { return false; }, /** * When the delegate detach with IME, this method call by CCIMEDispatcher. */ - didDetachWithIME:function () { + didDetachWithIME: function () { }, /** * Called by CCIMEDispatcher when some text input from IME. */ - insertText:function (text, len) { + insertText: function (text, len) { }, /** * Called by CCIMEDispatcher when user clicked the backward key. */ - deleteBackward:function () { + deleteBackward: function () { }, /** * Called by CCIMEDispatcher for get text which delegate already has. * @return {String} */ - getContentText:function () { + getContentText: function () { return ""; }, ////////////////////////////////////////////////////////////////////////// // keyboard show/hide notification ////////////////////////////////////////////////////////////////////////// - keyboardWillShow:function (info) { + keyboardWillShow: function (info) { }, - keyboardDidShow:function (info) { + keyboardDidShow: function (info) { }, - keyboardWillHide:function (info) { + keyboardWillHide: function (info) { }, - keyboardDidHide:function (info) { + keyboardDidHide: function (info) { } }); @@ -137,19 +137,19 @@ cc.IMEDelegate = cc.Class.extend(/** @lends cc.IMEDelegate# */{ * @name cc.imeDispatcher */ cc.IMEDispatcher = cc.Class.extend(/** @lends cc.imeDispatcher# */{ - _domInputControl:null, - impl:null, - _currentInputString:"", - _lastClickPosition:null, + _domInputControl: null, + impl: null, + _currentInputString: "", + _lastClickPosition: null, /** * Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function. */ - ctor:function () { + ctor: function () { this.impl = new cc.IMEDispatcher.Impl(); this._lastClickPosition = cc.p(0, 0); }, - init:function () { + init: function () { if (cc.sys.isMobile) return; this._domInputControl = cc.$("#imeDispatcherInput"); @@ -202,7 +202,7 @@ cc.IMEDispatcher = cc.Class.extend(/** @lends cc.imeDispatcher# */{ }, false); }, - _processDomInputString:function (text) { + _processDomInputString: function (text) { var i, startPos; var len = this._currentInputString.length < text.length ? this._currentInputString.length : text.length; for (startPos = 0; startPos < len; startPos++) { @@ -225,7 +225,7 @@ cc.IMEDispatcher = cc.Class.extend(/** @lends cc.imeDispatcher# */{ * @param {String} text * @param {Number} len */ - dispatchInsertText:function (text, len) { + dispatchInsertText: function (text, len) { if (!this.impl || !text || len <= 0) return; @@ -239,7 +239,7 @@ cc.IMEDispatcher = cc.Class.extend(/** @lends cc.imeDispatcher# */{ /** * Dispatch the delete backward operation */ - dispatchDeleteBackward:function () { + dispatchDeleteBackward: function () { if (!this.impl) { return; } @@ -255,7 +255,7 @@ cc.IMEDispatcher = cc.Class.extend(/** @lends cc.imeDispatcher# */{ * Get the content text, which current CCIMEDelegate which attached with IME has. * @return {String} */ - getContentText:function () { + getContentText: function () { if (this.impl && this.impl._delegateWithIme) { var pszContentText = this.impl._delegateWithIme.getContentText(); return (pszContentText) ? pszContentText : ""; @@ -267,7 +267,7 @@ cc.IMEDispatcher = cc.Class.extend(/** @lends cc.imeDispatcher# */{ * Dispatch keyboard notification * @param {cc.IMEKeyboardNotificationInfo} info */ - dispatchKeyboardWillShow:function (info) { + dispatchKeyboardWillShow: function (info) { if (this.impl) { for (var i = 0; i < this.impl._delegateList.length; i++) { var delegate = this.impl._delegateList[i]; @@ -282,7 +282,7 @@ cc.IMEDispatcher = cc.Class.extend(/** @lends cc.imeDispatcher# */{ * Dispatch keyboard notification * @param {cc.IMEKeyboardNotificationInfo} info */ - dispatchKeyboardDidShow:function (info) { + dispatchKeyboardDidShow: function (info) { if (this.impl) { for (var i = 0; i < this.impl._delegateList.length; i++) { var delegate = this.impl._delegateList[i]; @@ -296,7 +296,7 @@ cc.IMEDispatcher = cc.Class.extend(/** @lends cc.imeDispatcher# */{ * Dispatch keyboard notification * @param {cc.IMEKeyboardNotificationInfo} info */ - dispatchKeyboardWillHide:function (info) { + dispatchKeyboardWillHide: function (info) { if (this.impl) { for (var i = 0; i < this.impl._delegateList.length; i++) { var delegate = this.impl._delegateList[i]; @@ -311,7 +311,7 @@ cc.IMEDispatcher = cc.Class.extend(/** @lends cc.imeDispatcher# */{ * Dispatch keyboard notification * @param {cc.IMEKeyboardNotificationInfo} info */ - dispatchKeyboardDidHide:function (info) { + dispatchKeyboardDidHide: function (info) { if (this.impl) { for (var i = 0; i < this.impl._delegateList.length; i++) { var delegate = this.impl._delegateList[i]; @@ -329,7 +329,7 @@ cc.IMEDispatcher = cc.Class.extend(/** @lends cc.imeDispatcher# */{ * //example * cc.imeDispatcher.addDelegate(this); */ - addDelegate:function (delegate) { + addDelegate: function (delegate) { if (!delegate || !this.impl) return; @@ -348,7 +348,7 @@ cc.IMEDispatcher = cc.Class.extend(/** @lends cc.imeDispatcher# */{ * //example * var ret = cc.imeDispatcher.attachDelegateWithIME(this); */ - attachDelegateWithIME:function (delegate) { + attachDelegateWithIME: function (delegate) { if (!this.impl || !delegate) return false; @@ -381,8 +381,8 @@ cc.IMEDispatcher = cc.Class.extend(/** @lends cc.imeDispatcher# */{ return true; }, - _focusDomInput:function (delegate) { - if(cc.sys.isMobile){ + _focusDomInput: function (delegate) { + if (cc.sys.isMobile) { this.impl._delegateWithIme = delegate; delegate.didAttachWithIME(); //prompt @@ -392,15 +392,15 @@ cc.IMEDispatcher = cc.Class.extend(/** @lends cc.imeDispatcher# */{ // wechat cover the prompt function .So need use the Window.prototype.prompt var userInput; var win = window.Window; - if(win && win.prototype.prompt && win.prototype.prompt != prompt){ + if (win && win.prototype.prompt && win.prototype.prompt != prompt) { userInput = win.prototype.prompt.call(window, tipMessage, this._currentInputString); - }else{ + } else { userInput = prompt(tipMessage, this._currentInputString); } - if(userInput != null) + if (userInput != null) this._processDomInputString(userInput); this.dispatchInsertText("\n", 1); - }else{ + } else { this.impl._delegateWithIme = delegate; this._currentInputString = delegate.string || ""; delegate.didAttachWithIME(); @@ -410,7 +410,7 @@ cc.IMEDispatcher = cc.Class.extend(/** @lends cc.imeDispatcher# */{ } }, - _domInputControlTranslate:function () { + _domInputControlTranslate: function () { if (/msie/i.test(navigator.userAgent)) { this._domInputControl.style.left = this._lastClickPosition.x + "px"; this._domInputControl.style.top = this._lastClickPosition.y + "px"; @@ -427,7 +427,7 @@ cc.IMEDispatcher = cc.Class.extend(/** @lends cc.imeDispatcher# */{ * //example * var ret = cc.imeDispatcher.detachDelegateWithIME(this); */ - detachDelegateWithIME:function (delegate) { + detachDelegateWithIME: function (delegate) { if (!this.impl || !delegate) return false; @@ -451,7 +451,7 @@ cc.IMEDispatcher = cc.Class.extend(/** @lends cc.imeDispatcher# */{ * //example * cc.imeDispatcher.removeDelegate(this); */ - removeDelegate:function (delegate) { + removeDelegate: function (delegate) { if (!this.impl || !delegate) return; @@ -476,7 +476,7 @@ cc.IMEDispatcher = cc.Class.extend(/** @lends cc.imeDispatcher# */{ * cc.imeDispatcher.processKeycode(e.keyCode); * }); */ - processKeycode:function (keyCode) { + processKeycode: function (keyCode) { if (keyCode < 32) { if (keyCode === cc.KEY.backspace) { this.dispatchDeleteBackward(); @@ -503,12 +503,12 @@ cc.IMEDispatcher = cc.Class.extend(/** @lends cc.imeDispatcher# */{ * @name cc.IMEDispatcher.Impl */ cc.IMEDispatcher.Impl = cc.Class.extend(/** @lends cc.IMEDispatcher.Impl# */{ - _delegateWithIme:null, - _delegateList:null, + _delegateWithIme: null, + _delegateList: null, /** * Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function. */ - ctor:function () { + ctor: function () { this._delegateList = []; }, /** @@ -516,7 +516,7 @@ cc.IMEDispatcher.Impl = cc.Class.extend(/** @lends cc.IMEDispatcher.Impl# */{ * @param {cc.IMEDelegate} delegate * @return {Number|Null} */ - findDelegate:function (delegate) { + findDelegate: function (delegate) { for (var i = 0; i < this._delegateList.length; i++) { if (this._delegateList[i] === delegate) return i; @@ -532,4 +532,4 @@ document.body ? cc.imeDispatcher.init() : window.addEventListener('load', function () { cc.imeDispatcher.init(); - }, false); \ No newline at end of file + }, false); diff --git a/cocos2d/text-input/CCTextFieldTTF.js b/cocos2d/text-input/CCTextFieldTTF.js index 716a85fbd9..c582afb199 100644 --- a/cocos2d/text-input/CCTextFieldTTF.js +++ b/cocos2d/text-input/CCTextFieldTTF.js @@ -35,7 +35,7 @@ cc.TextFieldDelegate = cc.Class.extend(/** @lends cc.TextFieldDelegate# */{ * @param {cc.TextFieldTTF} sender * @return {Boolean} */ - onTextFieldAttachWithIME:function (sender) { + onTextFieldAttachWithIME: function (sender) { return false; }, @@ -44,7 +44,7 @@ cc.TextFieldDelegate = cc.Class.extend(/** @lends cc.TextFieldDelegate# */{ * @param {cc.TextFieldTTF} sender * @return {Boolean} */ - onTextFieldDetachWithIME:function (sender) { + onTextFieldDetachWithIME: function (sender) { return false; }, @@ -55,7 +55,7 @@ cc.TextFieldDelegate = cc.Class.extend(/** @lends cc.TextFieldDelegate# */{ * @param {Number} len * @return {Boolean} */ - onTextFieldInsertText:function (sender, text, len) { + onTextFieldInsertText: function (sender, text, len) { return false }, @@ -66,7 +66,7 @@ cc.TextFieldDelegate = cc.Class.extend(/** @lends cc.TextFieldDelegate# */{ * @param {Number} len * @return {Boolean} */ - onTextFieldDeleteBackward:function (sender, delText, len) { + onTextFieldDeleteBackward: function (sender, delText, len) { return false; }, @@ -75,7 +75,7 @@ cc.TextFieldDelegate = cc.Class.extend(/** @lends cc.TextFieldDelegate# */{ * @param {cc.TextFieldTTF} sender * @return {Boolean} */ - onDraw:function (sender) { + onDraw: function (sender) { return false; } }); @@ -104,15 +104,15 @@ cc.TextFieldDelegate = cc.Class.extend(/** @lends cc.TextFieldDelegate# */{ * var textField = new cc.TextFieldTTF("", "Arial", 32); */ cc.TextFieldTTF = cc.LabelTTF.extend(/** @lends cc.TextFieldTTF# */{ - delegate:null, - colorSpaceHolder:null, + delegate: null, + colorSpaceHolder: null, _colorText: null, - _lens:null, - _inputText:"", - _placeHolder:"", - _charCount:0, - _className:"TextFieldTTF", + _lens: null, + _inputText: "", + _placeHolder: "", + _charCount: 0, + _className: "TextFieldTTF", /** * Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function.
@@ -123,28 +123,28 @@ cc.TextFieldTTF = cc.LabelTTF.extend(/** @lends cc.TextFieldTTF# */{ * @param {String} fontName * @param {Number} fontSize */ - ctor:function (placeholder, dimensions, alignment, fontName, fontSize) { + ctor: function (placeholder, dimensions, alignment, fontName, fontSize) { this.colorSpaceHolder = cc.color(127, 127, 127); - this._colorText = cc.color(255,255,255, 255); + this._colorText = cc.color(255, 255, 255, 255); cc.LabelTTF.prototype.ctor.call(this); - if(fontSize !== undefined){ + if (fontSize !== undefined) { this.initWithPlaceHolder("", dimensions, alignment, fontName, fontSize); - if(placeholder) + if (placeholder) this.setPlaceHolder(placeholder); - }else if(fontName === undefined && alignment !== undefined){ + } else if (fontName === undefined && alignment !== undefined) { this.initWithString("", arguments[1], arguments[2]); - if(placeholder) + if (placeholder) this.setPlaceHolder(placeholder); } }, - onEnter: function(){ + onEnter: function () { cc.LabelTTF.prototype.onEnter.call(this); cc.imeDispatcher.addDelegate(this); }, - onExit: function(){ + onExit: function () { cc.LabelTTF.prototype.onExit.call(this); cc.imeDispatcher.removeDelegate(this); }, @@ -153,7 +153,7 @@ cc.TextFieldTTF = cc.LabelTTF.extend(/** @lends cc.TextFieldTTF# */{ * Gets the delegate. * @return {cc.Node} */ - getDelegate:function () { + getDelegate: function () { return this.delegate; }, @@ -161,7 +161,7 @@ cc.TextFieldTTF = cc.LabelTTF.extend(/** @lends cc.TextFieldTTF# */{ * Set the delegate. * @param {cc.Node} value */ - setDelegate:function (value) { + setDelegate: function (value) { this.delegate = value; }, @@ -169,7 +169,7 @@ cc.TextFieldTTF = cc.LabelTTF.extend(/** @lends cc.TextFieldTTF# */{ * Gets the char count. * @return {Number} */ - getCharCount:function () { + getCharCount: function () { return this._charCount; }, @@ -177,7 +177,7 @@ cc.TextFieldTTF = cc.LabelTTF.extend(/** @lends cc.TextFieldTTF# */{ * Returns the color of space holder. * @return {cc.Color} */ - getColorSpaceHolder:function () { + getColorSpaceHolder: function () { return cc.color(this.colorSpaceHolder); }, @@ -185,12 +185,12 @@ cc.TextFieldTTF = cc.LabelTTF.extend(/** @lends cc.TextFieldTTF# */{ * Sets the color of space holder. * @param {cc.Color} value */ - setColorSpaceHolder:function (value) { + setColorSpaceHolder: function (value) { this.colorSpaceHolder.r = value.r; this.colorSpaceHolder.g = value.g; this.colorSpaceHolder.b = value.b; this.colorSpaceHolder.a = cc.isUndefined(value.a) ? 255 : value.a; - if(!this._inputText.length) + if (!this._inputText.length) this.setColor(this.colorSpaceHolder); }, @@ -198,12 +198,12 @@ cc.TextFieldTTF = cc.LabelTTF.extend(/** @lends cc.TextFieldTTF# */{ * Sets the color of cc.TextFieldTTF's text. * @param {cc.Color} textColor */ - setTextColor:function(textColor){ + setTextColor: function (textColor) { this._colorText.r = textColor.r; this._colorText.g = textColor.g; this._colorText.b = textColor.b; this._colorText.a = cc.isUndefined(textColor.a) ? 255 : textColor.a; - if(this._inputText.length) + if (this._inputText.length) this.setColor(this._colorText); }, @@ -223,12 +223,12 @@ cc.TextFieldTTF = cc.LabelTTF.extend(/** @lends cc.TextFieldTTF# */{ * // When three parameters * textField.initWithPlaceHolder("", "Arial", 32); */ - initWithPlaceHolder:function (placeholder, dimensions, alignment, fontName, fontSize) { + initWithPlaceHolder: function (placeholder, dimensions, alignment, fontName, fontSize) { switch (arguments.length) { case 5: if (placeholder) this.setPlaceHolder(placeholder); - return this.initWithString(this._placeHolder,fontName, fontSize, dimensions, alignment); + return this.initWithString(this._placeHolder, fontName, fontSize, dimensions, alignment); break; case 3: if (placeholder) @@ -245,19 +245,19 @@ cc.TextFieldTTF = cc.LabelTTF.extend(/** @lends cc.TextFieldTTF# */{ * Input text property * @param {String} text */ - setString:function (text) { + setString: function (text) { text = String(text); this._inputText = text || ""; // if there is no input text, display placeholder instead - if (!this._inputText.length){ + if (!this._inputText.length) { cc.LabelTTF.prototype.setString.call(this, this._placeHolder); this.setColor(this.colorSpaceHolder); } else { - cc.LabelTTF.prototype.setString.call(this,this._inputText); + cc.LabelTTF.prototype.setString.call(this, this._inputText); this.setColor(this._colorText); } - if(cc._renderType === cc.game.RENDER_TYPE_CANVAS) + if (cc._renderType === cc.game.RENDER_TYPE_CANVAS) this._renderCmd._updateTexture(); this._charCount = this._inputText.length; }, @@ -266,7 +266,7 @@ cc.TextFieldTTF = cc.LabelTTF.extend(/** @lends cc.TextFieldTTF# */{ * Gets the string * @return {String} */ - getString:function () { + getString: function () { return this._inputText; }, @@ -275,10 +275,10 @@ cc.TextFieldTTF = cc.LabelTTF.extend(/** @lends cc.TextFieldTTF# */{ * display this string if string equal "". * @param {String} text */ - setPlaceHolder:function (text) { + setPlaceHolder: function (text) { this._placeHolder = text || ""; if (!this._inputText.length) { - cc.LabelTTF.prototype.setString.call(this,this._placeHolder); + cc.LabelTTF.prototype.setString.call(this, this._placeHolder); this.setColor(this.colorSpaceHolder); } }, @@ -288,7 +288,7 @@ cc.TextFieldTTF = cc.LabelTTF.extend(/** @lends cc.TextFieldTTF# */{ * default display string. * @return {String} */ - getPlaceHolder:function () { + getPlaceHolder: function () { return this._placeHolder; }, @@ -296,7 +296,7 @@ cc.TextFieldTTF = cc.LabelTTF.extend(/** @lends cc.TextFieldTTF# */{ * Render function using the canvas 2d context or WebGL context, internal usage only, please do not call this function. * @param {CanvasRenderingContext2D | WebGLRenderingContext} ctx The render context */ - draw:function (ctx) { + draw: function (ctx) { //console.log("size",this._contentSize); var context = ctx || cc._renderContext; if (this.delegate && this.delegate.onDraw(this)) @@ -305,14 +305,6 @@ cc.TextFieldTTF = cc.LabelTTF.extend(/** @lends cc.TextFieldTTF# */{ cc.LabelTTF.prototype.draw.call(this, context); }, - /** - * Recursive method that visit its children and draw them. - * @param {CanvasRenderingContext2D|WebGLRenderingContext} ctx - */ - visit: function(ctx){ - this._super(ctx); - }, - ////////////////////////////////////////////////////////////////////////// // CCIMEDelegate interface ////////////////////////////////////////////////////////////////////////// @@ -320,7 +312,7 @@ cc.TextFieldTTF = cc.LabelTTF.extend(/** @lends cc.TextFieldTTF# */{ * Open keyboard and receive input text. * @return {Boolean} */ - attachWithIME:function () { + attachWithIME: function () { return cc.imeDispatcher.attachDelegateWithIME(this); }, @@ -328,7 +320,7 @@ cc.TextFieldTTF = cc.LabelTTF.extend(/** @lends cc.TextFieldTTF# */{ * End text input and close keyboard. * @return {Boolean} */ - detachWithIME:function () { + detachWithIME: function () { return cc.imeDispatcher.detachDelegateWithIME(this); }, @@ -336,34 +328,34 @@ cc.TextFieldTTF = cc.LabelTTF.extend(/** @lends cc.TextFieldTTF# */{ * Return whether to allow attach with IME. * @return {Boolean} */ - canAttachWithIME:function () { + canAttachWithIME: function () { return (this.delegate) ? (!this.delegate.onTextFieldAttachWithIME(this)) : true; }, /** * When the delegate detach with IME, this method call by CCIMEDispatcher. */ - didAttachWithIME:function () { + didAttachWithIME: function () { }, /** * Return whether to allow detach with IME. * @return {Boolean} */ - canDetachWithIME:function () { + canDetachWithIME: function () { return (this.delegate) ? (!this.delegate.onTextFieldDetachWithIME(this)) : true; }, /** * When the delegate detach with IME, this method call by CCIMEDispatcher. */ - didDetachWithIME:function () { + didDetachWithIME: function () { }, /** * Delete backward */ - deleteBackward:function () { + deleteBackward: function () { var strLen = this._inputText.length; if (strLen === 0) return; @@ -380,7 +372,7 @@ cc.TextFieldTTF = cc.LabelTTF.extend(/** @lends cc.TextFieldTTF# */{ if (strLen <= deleteLen) { this._inputText = ""; this._charCount = 0; - cc.LabelTTF.prototype.setString.call(this,this._placeHolder); + cc.LabelTTF.prototype.setString.call(this, this._placeHolder); this.setColor(this.colorSpaceHolder); return; } @@ -392,7 +384,7 @@ cc.TextFieldTTF = cc.LabelTTF.extend(/** @lends cc.TextFieldTTF# */{ /** * Remove delegate */ - removeDelegate:function () { + removeDelegate: function () { cc.imeDispatcher.removeDelegate(this); }, @@ -421,7 +413,7 @@ cc.TextFieldTTF = cc.LabelTTF.extend(/** @lends cc.TextFieldTTF# */{ * @param {String} text * @param {Number} len */ - insertText:function (text, len) { + insertText: function (text, len) { var sInsert = text; // insert \n means input end @@ -456,20 +448,20 @@ cc.TextFieldTTF = cc.LabelTTF.extend(/** @lends cc.TextFieldTTF# */{ * Gets the input text. * @return {String} */ - getContentText:function () { + getContentText: function () { return this._inputText; }, ////////////////////////////////////////////////////////////////////////// // keyboard show/hide notification ////////////////////////////////////////////////////////////////////////// - keyboardWillShow:function (info) { + keyboardWillShow: function (info) { }, - keyboardDidShow:function (info) { + keyboardDidShow: function (info) { }, - keyboardWillHide:function (info) { + keyboardWillHide: function (info) { }, - keyboardDidHide:function (info) { + keyboardDidHide: function (info) { } }); diff --git a/cocos2d/tilemap/CCTGAlib.js b/cocos2d/tilemap/CCTGAlib.js index 60a8672ca4..76bd69bcf7 100644 --- a/cocos2d/tilemap/CCTGAlib.js +++ b/cocos2d/tilemap/CCTGAlib.js @@ -200,7 +200,7 @@ cc.tgaDestroy = function (psInfo) { * @returns {boolean} */ cc.tgaLoadRLEImageData = function (buffer, bufSize, psInfo) { - var mode, total, i, index = 0 , skip = 0, flag = 0; + var mode, total, i, index = 0, skip = 0, flag = 0; var aux = [], runlength = 0; var step = 18; // . size_t step = (sizeof(unsigned char) + sizeof(signed short)) * 6; @@ -293,8 +293,8 @@ cc.__setDataToArray = function (sourceData, destArray, startIndex) { * @param binaryData */ cc.BinaryStreamReader = cc.Class.extend({ - _binaryData:null, - _offset:0, + _binaryData: null, + _offset: 0, /** *

The cc.BinaryStreamReader's constructor.
@@ -302,7 +302,7 @@ cc.BinaryStreamReader = cc.Class.extend({ * Override it to extend its behavior, remember to call "this._super()" in the extended "ctor" function.

* @param binaryData */ - ctor:function (binaryData) { + ctor: function (binaryData) { this._binaryData = binaryData; }, @@ -310,7 +310,7 @@ cc.BinaryStreamReader = cc.Class.extend({ * Set the binaryData. * @param binaryData */ - setBinaryData:function (binaryData) { + setBinaryData: function (binaryData) { this._binaryData = binaryData; this._offset = 0; }, @@ -319,16 +319,16 @@ cc.BinaryStreamReader = cc.Class.extend({ * Gets the binaryData. * @returns {Object} */ - getBinaryData:function () { + getBinaryData: function () { return this._binaryData; }, - _checkSize:function (neededBits) { + _checkSize: function (neededBits) { if (!(this._offset + Math.ceil(neededBits / 8) < this._data.length)) throw new Error("Index out of bound"); }, - _decodeFloat:function (precisionBits, exponentBits) { + _decodeFloat: function (precisionBits, exponentBits) { var length = precisionBits + exponentBits + 1; var size = length >> 3; this._checkSize(length); @@ -357,11 +357,11 @@ cc.BinaryStreamReader = cc.Class.extend({ : Math.pow(2, exponent - bias) * (1 + significand) : 0); }, - _readByte:function (i, size) { + _readByte: function (i, size) { return this._data[this._offset + size - i - 1]; }, - _decodeInt:function (bits, signed) { + _decodeInt: function (bits, signed) { var x = this._readBits(0, bits, bits / 8), max = Math.pow(2, bits); var result = signed && x >= max / 2 ? x - max : x; @@ -369,12 +369,13 @@ cc.BinaryStreamReader = cc.Class.extend({ return result; }, - _shl:function (a, b) { - for (++b; --b; a = ((a %= 0x7fffffff + 1) & 0x40000000) === 0x40000000 ? a * 2 : (a - 0x40000000) * 2 + 0x7fffffff + 1){}; + _shl: function (a, b) { + for (++b; --b; a = ((a %= 0x7fffffff + 1) & 0x40000000) === 0x40000000 ? a * 2 : (a - 0x40000000) * 2 + 0x7fffffff + 1) { + } return a; }, - _readBits:function (start, length, size) { + _readBits: function (start, length, size) { var offsetLeft = (start + length) % 8; var offsetRight = start % 8; var curByte = size - (start >> 3) - 1; @@ -392,33 +393,33 @@ cc.BinaryStreamReader = cc.Class.extend({ return sum; }, - readInteger:function () { + readInteger: function () { return this._decodeInt(32, true); }, - readUnsignedInteger:function () { + readUnsignedInteger: function () { return this._decodeInt(32, false); }, - readSingle:function () { + readSingle: function () { return this._decodeFloat(23, 8); }, - readShort:function () { + readShort: function () { return this._decodeInt(16, true); }, - readUnsignedShort:function () { + readUnsignedShort: function () { return this._decodeInt(16, false); }, - readByte:function () { + readByte: function () { var readByte = this._data[this._offset]; this._offset += 1; return readByte; }, - readData:function (start, end) { + readData: function (start, end) { if (this._binaryData instanceof Array) { return this._binaryData.slice(start, end); } else { @@ -427,11 +428,11 @@ cc.BinaryStreamReader = cc.Class.extend({ } }, - setOffset:function (offset) { + setOffset: function (offset) { this._offset = offset; }, - getOffset:function () { + getOffset: function () { return this._offset; } }); diff --git a/cocos2d/tilemap/CCTMXLayerCanvasRenderCmd.js b/cocos2d/tilemap/CCTMXLayerCanvasRenderCmd.js index d28a3cde6b..cddb01fd28 100644 --- a/cocos2d/tilemap/CCTMXLayerCanvasRenderCmd.js +++ b/cocos2d/tilemap/CCTMXLayerCanvasRenderCmd.js @@ -132,10 +132,10 @@ if (maxRow > rows) maxRow = rows; } - var i, row, col, colOffset = startRow * cols, z, + var i, row, col, colOffset = startRow * cols, z, gid, grid, tex, cmd, mask = cc.TMX_TILE_FLIPPED_MASK, - top, left, bottom, right, dw = tilew, dh = tileh , + top, left, bottom, right, dw = tilew, dh = tileh, w = tilew * a, h = tileh * d, gt, gl, gb, gr, flippedX = false, flippedY = false; @@ -198,18 +198,18 @@ top = bottom - tileh; // TMX_ORIENTATION_ISO trim if (!hasRotation && layerOrientation === cc.TMX_ORIENTATION_ISO) { - gb = -mapy + bottom*d; - if (gb < -winh-h) { - col += Math.floor((-winh - gb)*2/h) - 1; + gb = -mapy + bottom * d; + if (gb < -winh - h) { + col += Math.floor((-winh - gb) * 2 / h) - 1; continue; } - gr = mapx + right*a; + gr = mapx + right * a; if (gr < -w) { - col += Math.floor((-gr)*2/w) - 1; + col += Math.floor((-gr) * 2 / w) - 1; continue; } - gl = mapx + left*a; - gt = -mapy + top*d; + gl = mapx + left * a; + gt = -mapy + top * d; if (gl > winw || gt > 0) { col = maxCol; continue; @@ -256,4 +256,4 @@ } } }; -})(); \ No newline at end of file +})(); diff --git a/cocos2d/tilemap/CCTMXLayerWebGLRenderCmd.js b/cocos2d/tilemap/CCTMXLayerWebGLRenderCmd.js index 36103af82b..6b68bc0d96 100644 --- a/cocos2d/tilemap/CCTMXLayerWebGLRenderCmd.js +++ b/cocos2d/tilemap/CCTMXLayerWebGLRenderCmd.js @@ -27,10 +27,10 @@ cc.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} + {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.SHADER_SPRITE_POSITION_TEXTURECOLORALPHATEST); @@ -86,7 +86,7 @@ cg *= ca; cb *= ca; } - this._color[0] = ((opacity<<24) | (cb<<16) | (cg<<8) | cr); + this._color[0] = ((opacity << 24) | (cb << 16) | (cg << 8) | cr); // Culling var startCol = 0, startRow = 0, @@ -107,7 +107,7 @@ offset = vertexDataOffset, colOffset = startRow * cols, z, gid, grid, mask = cc.TMX_TILE_FLIPPED_MASK, - i, top, left, bottom, right, + 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, @@ -156,18 +156,18 @@ top = bottom + tileh; // TMX_ORIENTATION_ISO trim if (!hasRotation && layerOrientation === cc.TMX_ORIENTATION_ISO) { - gb = mapy + bottom*d; - if (gb > winh+h) { - col += Math.floor((gb-winh)*2/h) - 1; + gb = mapy + bottom * d; + if (gb > winh + h) { + col += Math.floor((gb - winh) * 2 / h) - 1; continue; } - gr = mapx + right*a; + gr = mapx + right * a; if (gr < -w) { - col += Math.floor((-gr)*2/w) - 1; + col += Math.floor((-gr) * 2 / w) - 1; continue; } - gl = mapx + left*a; - gt = mapy + top*d; + gl = mapx + left * a; + gt = mapy + top * d; if (gl > winw || gt < 0) { col = maxCol; continue; @@ -221,21 +221,21 @@ 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; + 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; + 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; + 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; + f32buffer[offset + 4] = flippedX ? grid.l : grid.r; + f32buffer[offset + 5] = flippedY ? grid.t : grid.b; + break; } offset += 6; diff --git a/cocos2d/transitions/CCTransition.js b/cocos2d/transitions/CCTransition.js index 6796074555..8673ab9164 100644 --- a/cocos2d/transitions/CCTransition.js +++ b/cocos2d/transitions/CCTransition.js @@ -64,12 +64,12 @@ cc.TRANSITION_ORIENTATION_DOWN_OVER = 1; * var trans = new TransitionScene(time,scene); */ cc.TransitionScene = cc.Scene.extend(/** @lends cc.TransitionScene# */{ - _inScene:null, - _outScene:null, - _duration:null, - _isInSceneOnTop:false, - _isSendCleanupToScene:false, - _className:"TransitionScene", + _inScene: null, + _outScene: null, + _duration: null, + _isInSceneOnTop: false, + _isSendCleanupToScene: false, + _className: "TransitionScene", /** * creates a base transition with duration and incoming scene @@ -77,14 +77,14 @@ cc.TransitionScene = cc.Scene.extend(/** @lends cc.TransitionScene# */{ * @param {Number} t time in seconds * @param {cc.Scene} scene the scene to transit with */ - ctor:function (t, scene) { + ctor: function (t, scene) { cc.Scene.prototype.ctor.call(this); - if(t !== undefined && scene !== undefined) + if (t !== undefined && scene !== undefined) this.initWithDuration(t, scene); }, //private - _setNewScene:function (dt) { + _setNewScene: function (dt) { this.unschedule(this._setNewScene); // Before replacing, save the "send cleanup to scene" var director = cc.director; @@ -99,14 +99,14 @@ cc.TransitionScene = cc.Scene.extend(/** @lends cc.TransitionScene# */{ }, //protected - _sceneOrder:function () { + _sceneOrder: function () { this._isInSceneOnTop = true; }, /** * stuff gets drawn here */ - visit:function () { + visit: function () { if (this._isInSceneOnTop) { this._outScene.visit(); this._inScene.visit(); @@ -125,7 +125,7 @@ cc.TransitionScene = cc.Scene.extend(/** @lends cc.TransitionScene# */{ * If you override onEnter, you must call its parent's onEnter function with this._super(). *

*/ - onEnter:function () { + onEnter: function () { cc.Node.prototype.onEnter.call(this); // disable events while transitions @@ -146,7 +146,7 @@ cc.TransitionScene = cc.Scene.extend(/** @lends cc.TransitionScene# */{ * If you override onExit, you shall call its parent's onExit with this._super(). *

*/ - onExit:function () { + onExit: function () { cc.Node.prototype.onExit.call(this); // enable events while transitions @@ -162,7 +162,7 @@ cc.TransitionScene = cc.Scene.extend(/** @lends cc.TransitionScene# */{ /** * custom cleanup */ - cleanup:function () { + cleanup: function () { cc.Node.prototype.cleanup.call(this); if (this._isSendCleanupToScene) @@ -175,17 +175,17 @@ cc.TransitionScene = cc.Scene.extend(/** @lends cc.TransitionScene# */{ * @param {cc.Scene} scene a scene to transit to * @return {Boolean} return false if error */ - initWithDuration:function (t, scene) { - if(!scene) + initWithDuration: function (t, scene) { + if (!scene) throw new Error("cc.TransitionScene.initWithDuration(): Argument scene must be non-nil"); if (this.init()) { this._duration = t; this.attr({ - x: 0, - y: 0, - anchorX: 0, - anchorY: 0 + x: 0, + y: 0, + anchorX: 0, + anchorY: 0 }); // retain this._inScene = scene; @@ -195,7 +195,7 @@ cc.TransitionScene = cc.Scene.extend(/** @lends cc.TransitionScene# */{ this._outScene.init(); } - if(this._inScene === this._outScene) + if (this._inScene === this._outScene) throw new Error("cc.TransitionScene.initWithDuration(): Incoming scene must be different from the outgoing scene"); this._sceneOrder(); @@ -208,22 +208,22 @@ cc.TransitionScene = cc.Scene.extend(/** @lends cc.TransitionScene# */{ /** * called after the transition finishes */ - finish:function () { + finish: function () { // clean up this._inScene.attr({ - visible: true, - x: 0, - y: 0, - scale: 1.0, - rotation: 0.0 + visible: true, + x: 0, + y: 0, + scale: 1.0, + rotation: 0.0 }); this._outScene.attr({ - visible: false, - x: 0, - y: 0, - scale: 1.0, - rotation: 0.0 + visible: false, + x: 0, + y: 0, + scale: 1.0, + rotation: 0.0 }); //[self schedule:@selector(setNewScene:) interval:0]; @@ -233,7 +233,7 @@ cc.TransitionScene = cc.Scene.extend(/** @lends cc.TransitionScene# */{ /** * set hide the out scene and show in scene */ - hideOutShowIn:function () { + hideOutShowIn: function () { this._inScene.visible = true; this._outScene.visible = false; } @@ -262,7 +262,7 @@ cc.TransitionScene.create = function (t, scene) { * var trans = new cc.TransitionSceneOriented(time,scene,orientation); */ cc.TransitionSceneOriented = cc.TransitionScene.extend(/** @lends cc.TransitionSceneOriented# */{ - _orientation:0, + _orientation: 0, /** * Constructor of TransitionSceneOriented @@ -270,7 +270,7 @@ cc.TransitionSceneOriented = cc.TransitionScene.extend(/** @lends cc.TransitionS * @param {cc.Scene} scene * @param {cc.TRANSITION_ORIENTATION_LEFT_OVER|cc.TRANSITION_ORIENTATION_RIGHT_OVER|cc.TRANSITION_ORIENTATION_UP_OVER|cc.TRANSITION_ORIENTATION_DOWN_OVER} orientation */ - ctor:function (t, scene, orientation) { + ctor: function (t, scene, orientation) { cc.TransitionScene.prototype.ctor.call(this); orientation != undefined && this.initWithDuration(t, scene, orientation); }, @@ -281,7 +281,7 @@ cc.TransitionSceneOriented = cc.TransitionScene.extend(/** @lends cc.TransitionS * @param {cc.TRANSITION_ORIENTATION_LEFT_OVER|cc.TRANSITION_ORIENTATION_RIGHT_OVER|cc.TRANSITION_ORIENTATION_UP_OVER|cc.TRANSITION_ORIENTATION_DOWN_OVER} orientation * @return {Boolean} */ - initWithDuration:function (t, scene, orientation) { + initWithDuration: function (t, scene, orientation) { if (cc.TransitionScene.prototype.initWithDuration.call(this, t, scene)) { this._orientation = orientation; } @@ -318,7 +318,7 @@ cc.TransitionRotoZoom = cc.TransitionScene.extend(/** @lends cc.TransitionRotoZo * @param {Number} t time in seconds * @param {cc.Scene} scene */ - ctor:function (t, scene) { + ctor: function (t, scene) { cc.TransitionScene.prototype.ctor.call(this); scene && this.initWithDuration(t, scene); }, @@ -326,19 +326,19 @@ cc.TransitionRotoZoom = cc.TransitionScene.extend(/** @lends cc.TransitionRotoZo * Custom On Enter callback * @override */ - onEnter:function () { + onEnter: function () { cc.TransitionScene.prototype.onEnter.call(this); - this._inScene.attr({ - scale: 0.001, - anchorX: 0.5, - anchorY: 0.5 - }); - this._outScene.attr({ - scale: 1.0, - anchorX: 0.5, - anchorY: 0.5 - }); + this._inScene.attr({ + scale: 0.001, + anchorX: 0.5, + anchorY: 0.5 + }); + this._outScene.attr({ + scale: 1.0, + anchorX: 0.5, + anchorY: 0.5 + }); var rotoZoom = cc.sequence( cc.spawn(cc.scaleBy(this._duration / 2, 0.001), @@ -378,26 +378,26 @@ cc.TransitionJumpZoom = cc.TransitionScene.extend(/** @lends cc.TransitionJumpZo * @param {Number} t time in seconds * @param {cc.Scene} scene */ - ctor:function (t, scene) { + ctor: function (t, scene) { cc.TransitionScene.prototype.ctor.call(this); scene && this.initWithDuration(t, scene); }, /** * Custom on enter */ - onEnter:function () { + onEnter: function () { cc.TransitionScene.prototype.onEnter.call(this); var winSize = cc.director.getWinSize(); - this._inScene.attr({ - scale: 0.5, - x: winSize.width, - y: 0, - anchorX: 0.5, - anchorY: 0.5 - }); + this._inScene.attr({ + scale: 0.5, + x: winSize.width, + y: 0, + anchorX: 0.5, + anchorY: 0.5 + }); this._outScene.anchorX = 0.5; - this._outScene.anchorY = 0.5; + this._outScene.anchorY = 0.5; var jump = cc.jumpBy(this._duration / 4, cc.p(-winSize.width, 0), winSize.width / 4, 2); var scaleIn = cc.scaleTo(this._duration / 4, 1.0); @@ -438,14 +438,14 @@ cc.TransitionMoveInL = cc.TransitionScene.extend(/** @lends cc.TransitionMoveInL * @param {Number} t time in seconds * @param {cc.Scene} scene */ - ctor:function (t, scene) { + ctor: function (t, scene) { cc.TransitionScene.prototype.ctor.call(this); scene && this.initWithDuration(t, scene); }, /** * Custom on enter */ - onEnter:function () { + onEnter: function () { cc.TransitionScene.prototype.onEnter.call(this); this.initScenes(); @@ -458,14 +458,14 @@ cc.TransitionMoveInL = cc.TransitionScene.extend(/** @lends cc.TransitionMoveInL /** * initializes the scenes */ - initScenes:function () { + initScenes: function () { this._inScene.setPosition(-cc.director.getWinSize().width, 0); }, /** * returns the action that will be performed */ - action:function () { + action: function () { return cc.moveTo(this._duration, cc.p(0, 0)); }, @@ -474,7 +474,7 @@ cc.TransitionMoveInL = cc.TransitionScene.extend(/** @lends cc.TransitionMoveInL * @param {cc.ActionInterval} action * @return {cc.EaseOut} */ - easeActionWithAction:function (action) { + easeActionWithAction: function (action) { return new cc.EaseOut(action, 2.0); } }); @@ -505,14 +505,14 @@ cc.TransitionMoveInR = cc.TransitionMoveInL.extend(/** @lends cc.TransitionMoveI * @param {Number} t time in seconds * @param {cc.Scene} scene */ - ctor:function (t, scene) { + ctor: function (t, scene) { cc.TransitionMoveInL.prototype.ctor.call(this); scene && this.initWithDuration(t, scene); }, /** * Init function */ - initScenes:function () { + initScenes: function () { this._inScene.setPosition(cc.director.getWinSize().width, 0); } }); @@ -543,14 +543,14 @@ cc.TransitionMoveInT = cc.TransitionMoveInL.extend(/** @lends cc.TransitionMoveI * @param {Number} t time in seconds * @param {cc.Scene} scene */ - ctor:function (t, scene) { + ctor: function (t, scene) { cc.TransitionMoveInL.prototype.ctor.call(this); scene && this.initWithDuration(t, scene); }, /** * init function */ - initScenes:function () { + initScenes: function () { this._inScene.setPosition(0, cc.director.getWinSize().height); } }); @@ -581,7 +581,7 @@ cc.TransitionMoveInB = cc.TransitionMoveInL.extend(/** @lends cc.TransitionMoveI * @param {Number} t time in seconds * @param {cc.Scene} scene */ - ctor:function (t, scene) { + ctor: function (t, scene) { cc.TransitionMoveInL.prototype.ctor.call(this); scene && this.initWithDuration(t, scene); }, @@ -589,7 +589,7 @@ cc.TransitionMoveInB = cc.TransitionMoveInL.extend(/** @lends cc.TransitionMoveI /** * init function */ - initScenes:function () { + initScenes: function () { this._inScene.setPosition(0, -cc.director.getWinSize().height); } }); @@ -630,18 +630,18 @@ cc.TransitionSlideInL = cc.TransitionScene.extend(/** @lends cc.TransitionSlideI * @param {Number} t time in seconds * @param {cc.Scene} scene */ - ctor:function (t, scene) { + ctor: function (t, scene) { cc.TransitionScene.prototype.ctor.call(this); scene && this.initWithDuration(t, scene); }, - _sceneOrder:function () { + _sceneOrder: function () { this._isInSceneOnTop = false; }, /** * custom on enter */ - onEnter:function () { + onEnter: function () { cc.TransitionScene.prototype.onEnter.call(this); this.initScenes(); @@ -657,14 +657,14 @@ cc.TransitionSlideInL = cc.TransitionScene.extend(/** @lends cc.TransitionSlideI /** * initializes the scenes */ - initScenes:function () { + initScenes: function () { this._inScene.setPosition(-cc.director.getWinSize().width + cc.ADJUST_FACTOR, 0); }, /** * returns the action that will be performed by the incoming and outgoing scene * @return {cc.MoveBy} */ - action:function () { + action: function () { return cc.moveBy(this._duration, cc.p(cc.director.getWinSize().width - cc.ADJUST_FACTOR, 0)); }, @@ -672,7 +672,7 @@ cc.TransitionSlideInL = cc.TransitionScene.extend(/** @lends cc.TransitionSlideI * @param {cc.ActionInterval} action * @return {*} */ - easeActionWithAction:function (action) { + easeActionWithAction: function (action) { return new cc.EaseInOut(action, 2.0); } }); @@ -703,24 +703,24 @@ cc.TransitionSlideInR = cc.TransitionSlideInL.extend(/** @lends cc.TransitionSli * @param {Number} t time in seconds * @param {cc.Scene} scene */ - ctor:function (t, scene) { + ctor: function (t, scene) { cc.TransitionSlideInL.prototype.ctor.call(this); scene && this.initWithDuration(t, scene); }, - _sceneOrder:function () { + _sceneOrder: function () { this._isInSceneOnTop = true; }, /** * initializes the scenes */ - initScenes:function () { + initScenes: function () { this._inScene.setPosition(cc.director.getWinSize().width - cc.ADJUST_FACTOR, 0); }, /** * returns the action that will be performed by the incoming and outgoing scene * @return {cc.MoveBy} */ - action:function () { + action: function () { return cc.moveBy(this._duration, cc.p(-(cc.director.getWinSize().width - cc.ADJUST_FACTOR), 0)); } }); @@ -751,18 +751,18 @@ cc.TransitionSlideInB = cc.TransitionSlideInL.extend(/** @lends cc.TransitionSli * @param {Number} t time in seconds * @param {cc.Scene} scene */ - ctor:function (t, scene) { + ctor: function (t, scene) { cc.TransitionSlideInL.prototype.ctor.call(this); scene && this.initWithDuration(t, scene); }, - _sceneOrder:function () { + _sceneOrder: function () { this._isInSceneOnTop = false; }, /** * initializes the scenes */ - initScenes:function () { + initScenes: function () { this._inScene.setPosition(0, -(cc.director.getWinSize().height - cc.ADJUST_FACTOR)); }, @@ -770,7 +770,7 @@ cc.TransitionSlideInB = cc.TransitionSlideInL.extend(/** @lends cc.TransitionSli * returns the action that will be performed by the incoming and outgoing scene * @return {cc.MoveBy} */ - action:function () { + action: function () { return cc.moveBy(this._duration, cc.p(0, cc.director.getWinSize().height - cc.ADJUST_FACTOR)); } }); @@ -801,18 +801,18 @@ cc.TransitionSlideInT = cc.TransitionSlideInL.extend(/** @lends cc.TransitionSli * @param {Number} t time in seconds * @param {cc.Scene} scene */ - ctor:function (t, scene) { + ctor: function (t, scene) { cc.TransitionSlideInL.prototype.ctor.call(this); scene && this.initWithDuration(t, scene); }, - _sceneOrder:function () { + _sceneOrder: function () { this._isInSceneOnTop = true; }, /** * initializes the scenes */ - initScenes:function () { + initScenes: function () { this._inScene.setPosition(0, cc.director.getWinSize().height - cc.ADJUST_FACTOR); }, @@ -820,7 +820,7 @@ cc.TransitionSlideInT = cc.TransitionSlideInL.extend(/** @lends cc.TransitionSli * returns the action that will be performed by the incoming and outgoing scene * @return {cc.MoveBy} */ - action:function () { + action: function () { return cc.moveBy(this._duration, cc.p(0, -(cc.director.getWinSize().height - cc.ADJUST_FACTOR))); } }); @@ -851,26 +851,26 @@ cc.TransitionShrinkGrow = cc.TransitionScene.extend(/** @lends cc.TransitionShri * @param {Number} t time in seconds * @param {cc.Scene} scene */ - ctor:function (t, scene) { + ctor: function (t, scene) { cc.TransitionScene.prototype.ctor.call(this); scene && this.initWithDuration(t, scene); }, /** * Custom on enter */ - onEnter:function () { + onEnter: function () { cc.TransitionScene.prototype.onEnter.call(this); - this._inScene.attr({ - scale: 0.001, - anchorX: 2 / 3.0, - anchorY: 0.5 - }); - this._outScene.attr({ - scale: 1.0, - anchorX: 1 / 3.0, - anchorY: 0.5 - }); + this._inScene.attr({ + scale: 0.001, + anchorX: 2 / 3.0, + anchorY: 0.5 + }); + this._outScene.attr({ + scale: 1.0, + anchorX: 1 / 3.0, + anchorY: 0.5 + }); var scaleOut = cc.scaleTo(this._duration, 0.01); var scaleIn = cc.scaleTo(this._duration, 1.0); @@ -883,7 +883,7 @@ cc.TransitionShrinkGrow = cc.TransitionScene.extend(/** @lends cc.TransitionShri * @param action * @return {cc.EaseOut} */ - easeActionWithAction:function (action) { + easeActionWithAction: function (action) { return new cc.EaseOut(action, 2.0); } }); @@ -910,7 +910,7 @@ cc.TransitionShrinkGrow.create = function (t, scene) { * var trans = new cc.TransitionFade(time,scene,color) */ cc.TransitionFade = cc.TransitionScene.extend(/** @lends cc.TransitionFade# */{ - _color:null, + _color: null, /** * Constructor of TransitionFade @@ -918,7 +918,7 @@ cc.TransitionFade = cc.TransitionScene.extend(/** @lends cc.TransitionFade# */{ * @param {cc.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, color) { + ctor: function (t, scene, color) { cc.TransitionScene.prototype.ctor.call(this); this._color = cc.color(); scene && this.initWithDuration(t, scene, color); @@ -927,7 +927,7 @@ cc.TransitionFade = cc.TransitionScene.extend(/** @lends cc.TransitionFade# */{ /** * custom on enter */ - onEnter:function () { + onEnter: function () { cc.TransitionScene.prototype.onEnter.call(this); var l = new cc.LayerColor(this._color); @@ -948,7 +948,7 @@ cc.TransitionFade = cc.TransitionScene.extend(/** @lends cc.TransitionFade# */{ /** * custom on exit */ - onExit:function () { + onExit: function () { cc.TransitionScene.prototype.onExit.call(this); this.removeChildByTag(cc.SCENE_FADE, false); }, @@ -960,7 +960,7 @@ cc.TransitionFade = cc.TransitionScene.extend(/** @lends cc.TransitionFade# */{ * @param {cc.Color} color * @return {Boolean} */ - initWithDuration:function (t, scene, color) { + initWithDuration: function (t, scene, color) { color = color || cc.color.BLACK; if (cc.TransitionScene.prototype.initWithDuration.call(this, t, scene)) { this._color.r = color.r; @@ -1000,14 +1000,14 @@ cc.TransitionCrossFade = cc.TransitionScene.extend(/** @lends cc.TransitionCross * @param {Number} t time in seconds * @param {cc.Scene} scene */ - ctor:function (t, scene) { + ctor: function (t, scene) { cc.TransitionScene.prototype.ctor.call(this); scene && this.initWithDuration(t, scene); }, /** * custom on enter */ - onEnter:function () { + onEnter: function () { cc.TransitionScene.prototype.onEnter.call(this); // create a transparent color layer @@ -1020,12 +1020,12 @@ cc.TransitionCrossFade = cc.TransitionScene.extend(/** @lends cc.TransitionCross var inTexture = new cc.RenderTexture(winSize.width, winSize.height); inTexture.sprite.anchorX = 0.5; - inTexture.sprite.anchorY = 0.5; + inTexture.sprite.anchorY = 0.5; inTexture.attr({ - x: winSize.width / 2, - y: winSize.height / 2, - anchorX: 0.5, - anchorY: 0.5 + x: winSize.width / 2, + y: winSize.height / 2, + anchorX: 0.5, + anchorY: 0.5 }); // render inScene to its texturebuffer @@ -1036,8 +1036,8 @@ cc.TransitionCrossFade = cc.TransitionScene.extend(/** @lends cc.TransitionCross // create the second render texture for outScene var outTexture = new cc.RenderTexture(winSize.width, winSize.height); outTexture.setPosition(winSize.width / 2, winSize.height / 2); - outTexture.sprite.anchorX = outTexture.anchorX = 0.5; - outTexture.sprite.anchorY = outTexture.anchorY = 0.5; + outTexture.sprite.anchorX = outTexture.anchorX = 0.5; + outTexture.sprite.anchorY = outTexture.anchorY = 0.5; // render outScene to its texturebuffer outTexture.begin(); @@ -1071,24 +1071,10 @@ cc.TransitionCrossFade = cc.TransitionScene.extend(/** @lends cc.TransitionCross /** * custom on exit */ - onExit:function () { + onExit: function () { this.removeChildByTag(cc.SCENE_FADE, false); cc.TransitionScene.prototype.onExit.call(this); }, - - /** - * stuff gets drawn here - */ - visit:function () { - cc.Node.prototype.visit.call(this); - }, - - /** - * overide draw - */ - draw:function () { - // override draw since both scenes (textures) are rendered in 1 scene - } }); /** @@ -1118,20 +1104,20 @@ cc.TransitionTurnOffTiles = cc.TransitionScene.extend(/** @lends cc.TransitionTu * @param {Number} t time in seconds * @param {cc.Scene} scene */ - ctor:function (t, scene) { + ctor: function (t, scene) { cc.TransitionScene.prototype.ctor.call(this); this._gridProxy = new cc.NodeGrid(); scene && this.initWithDuration(t, scene); }, - _sceneOrder:function () { + _sceneOrder: function () { this._isInSceneOnTop = false; }, /** * custom on enter */ - onEnter:function () { + onEnter: function () { cc.TransitionScene.prototype.onEnter.call(this); this._gridProxy.setTarget(this._outScene); this._gridProxy.onEnter(); @@ -1145,7 +1131,7 @@ cc.TransitionTurnOffTiles = cc.TransitionScene.extend(/** @lends cc.TransitionTu this._gridProxy.runAction(cc.sequence(action, cc.callFunc(this.finish, this), cc.stopGrid())); }, - visit: function(){ + visit: function () { this._inScene.visit(); this._gridProxy.visit(); }, @@ -1154,7 +1140,7 @@ cc.TransitionTurnOffTiles = cc.TransitionScene.extend(/** @lends cc.TransitionTu * @param {cc.ActionInterval} action * @return {cc.ActionInterval} */ - easeActionWithAction:function (action) { + easeActionWithAction: function (action) { return action; } }); @@ -1182,7 +1168,7 @@ cc.TransitionTurnOffTiles.create = function (t, scene) { cc.TransitionSplitCols = cc.TransitionScene.extend(/** @lends cc.TransitionSplitCols# */{ _gridProxy: null, - _switchTargetToInscene: function(){ + _switchTargetToInscene: function () { this._gridProxy.setTarget(this._inScene); }, @@ -1191,7 +1177,7 @@ cc.TransitionSplitCols = cc.TransitionScene.extend(/** @lends cc.TransitionSplit * @param {Number} t time in seconds * @param {cc.Scene} scene */ - ctor:function (t, scene) { + ctor: function (t, scene) { cc.TransitionScene.prototype.ctor.call(this); this._gridProxy = new cc.NodeGrid(); scene && this.initWithDuration(t, scene); @@ -1199,7 +1185,7 @@ cc.TransitionSplitCols = cc.TransitionScene.extend(/** @lends cc.TransitionSplit /** * custom on enter */ - onEnter:function () { + onEnter: function () { cc.TransitionScene.prototype.onEnter.call(this); //this._inScene.visible = false; this._gridProxy.setTarget(this._outScene); @@ -1214,13 +1200,13 @@ cc.TransitionSplitCols = cc.TransitionScene.extend(/** @lends cc.TransitionSplit ); }, - onExit: function(){ + onExit: function () { this._gridProxy.setTarget(null); this._gridProxy.onExit(); cc.TransitionScene.prototype.onExit.call(this); }, - visit: function(){ + visit: function () { this._gridProxy.visit(); }, @@ -1228,14 +1214,14 @@ cc.TransitionSplitCols = cc.TransitionScene.extend(/** @lends cc.TransitionSplit * @param {cc.ActionInterval} action * @return {cc.EaseInOut} */ - easeActionWithAction:function (action) { + easeActionWithAction: function (action) { return new cc.EaseInOut(action, 3.0); }, /** * @return {*} */ - action:function () { + action: function () { return cc.splitCols(this._duration / 2.0, 3); } }); @@ -1267,14 +1253,14 @@ cc.TransitionSplitRows = cc.TransitionSplitCols.extend(/** @lends cc.TransitionS * @param {Number} t time in seconds * @param {cc.Scene} scene */ - ctor:function (t, scene) { + ctor: function (t, scene) { cc.TransitionSplitCols.prototype.ctor.call(this); scene && this.initWithDuration(t, scene); }, /** * @return {*} */ - action:function () { + action: function () { return cc.splitRows(this._duration / 2.0, 3); } }); @@ -1306,19 +1292,19 @@ cc.TransitionFadeTR = cc.TransitionScene.extend(/** @lends cc.TransitionFadeTR# * @param {Number} t time in seconds * @param {cc.Scene} scene */ - ctor:function (t, scene) { + ctor: function (t, scene) { cc.TransitionScene.prototype.ctor.call(this); this._gridProxy = new cc.NodeGrid(); scene && this.initWithDuration(t, scene); }, - _sceneOrder:function () { + _sceneOrder: function () { this._isInSceneOnTop = false; }, /** * Custom on enter */ - onEnter:function () { + onEnter: function () { cc.TransitionScene.prototype.onEnter.call(this); this._gridProxy.setTarget(this._outScene); @@ -1335,7 +1321,7 @@ cc.TransitionFadeTR = cc.TransitionScene.extend(/** @lends cc.TransitionFadeTR# ); }, - visit: function(){ + visit: function () { this._inScene.visit(); this._gridProxy.visit(); }, @@ -1344,7 +1330,7 @@ cc.TransitionFadeTR = cc.TransitionScene.extend(/** @lends cc.TransitionFadeTR# * @param {cc.ActionInterval} action * @return {cc.ActionInterval} */ - easeActionWithAction:function (action) { + easeActionWithAction: function (action) { return action; }, @@ -1352,7 +1338,7 @@ cc.TransitionFadeTR = cc.TransitionScene.extend(/** @lends cc.TransitionFadeTR# * @param {cc.Size} size * @return {*} */ - actionWithSize:function (size) { + actionWithSize: function (size) { return cc.fadeOutTRTiles(this._duration, size); } }); @@ -1383,7 +1369,7 @@ cc.TransitionFadeBL = cc.TransitionFadeTR.extend(/** @lends cc.TransitionFadeBL# * @param {Number} t time in seconds * @param {cc.Scene} scene */ - ctor:function (t, scene) { + ctor: function (t, scene) { cc.TransitionFadeTR.prototype.ctor.call(this); scene && this.initWithDuration(t, scene); }, @@ -1392,7 +1378,7 @@ cc.TransitionFadeBL = cc.TransitionFadeTR.extend(/** @lends cc.TransitionFadeBL# * @param {cc.Size} size * @return {*} */ - actionWithSize:function (size) { + actionWithSize: function (size) { return cc.fadeOutBLTiles(this._duration, size); } }); @@ -1425,7 +1411,7 @@ cc.TransitionFadeUp = cc.TransitionFadeTR.extend(/** @lends cc.TransitionFadeUp# * @param {Number} t time in seconds * @param {cc.Scene} scene */ - ctor:function (t, scene) { + ctor: function (t, scene) { cc.TransitionFadeTR.prototype.ctor.call(this); scene && this.initWithDuration(t, scene); }, @@ -1434,7 +1420,7 @@ cc.TransitionFadeUp = cc.TransitionFadeTR.extend(/** @lends cc.TransitionFadeUp# * @param {cc.Size} size * @return {cc.FadeOutUpTiles} */ - actionWithSize:function (size) { + actionWithSize: function (size) { return new cc.FadeOutUpTiles(this._duration, size); } }); @@ -1466,7 +1452,7 @@ cc.TransitionFadeDown = cc.TransitionFadeTR.extend(/** @lends cc.TransitionFadeD * @param {Number} t time in seconds * @param {cc.Scene} scene */ - ctor:function (t, scene) { + ctor: function (t, scene) { cc.TransitionFadeTR.prototype.ctor.call(this); scene && this.initWithDuration(t, scene); }, @@ -1475,8 +1461,8 @@ cc.TransitionFadeDown = cc.TransitionFadeTR.extend(/** @lends cc.TransitionFadeD * @param {cc.Size} size * @return {*} */ - actionWithSize:function (size) { - return cc.fadeOutDownTiles( this._duration, size); + actionWithSize: function (size) { + return cc.fadeOutDownTiles(this._duration, size); } }); diff --git a/cocos2d/transitions/CCTransitionPageTurn.js b/cocos2d/transitions/CCTransitionPageTurn.js index 6b71fd848b..5a689945ec 100644 --- a/cocos2d/transitions/CCTransitionPageTurn.js +++ b/cocos2d/transitions/CCTransitionPageTurn.js @@ -47,7 +47,7 @@ cc.TransitionPageTurn = cc.TransitionScene.extend(/** @lends cc.TransitionPageTu * @param {cc.Scene} scene * @param {Boolean} backwards */ - ctor:function (t, scene, backwards) { + ctor: function (t, scene, backwards) { cc.TransitionScene.prototype.ctor.call(this); this._gridProxy = new cc.NodeGrid(); this.initWithDuration(t, scene, backwards); @@ -56,9 +56,9 @@ cc.TransitionPageTurn = cc.TransitionScene.extend(/** @lends cc.TransitionPageTu /** * @type Boolean */ - _back:true, + _back: true, _gridProxy: null, - _className:"TransitionPageTurn", + _className: "TransitionPageTurn", /** * Creates a base transition with duration and incoming scene.
@@ -69,7 +69,7 @@ cc.TransitionPageTurn = cc.TransitionScene.extend(/** @lends cc.TransitionPageTu * @param {Boolean} backwards * @return {Boolean} */ - initWithDuration:function (t, scene, backwards) { + initWithDuration: function (t, scene, backwards) { // XXX: needed before [super init] this._back = backwards; @@ -83,7 +83,7 @@ cc.TransitionPageTurn = cc.TransitionScene.extend(/** @lends cc.TransitionPageTu * @param {cc.Size} vector * @return {cc.ReverseTime|cc.TransitionScene} */ - actionWithSize:function (vector) { + actionWithSize: function (vector) { if (this._back) return cc.reverseTime(cc.pageTurn3D(this._duration, vector)); // Get hold of the PageTurn3DAction else @@ -93,7 +93,7 @@ cc.TransitionPageTurn = cc.TransitionScene.extend(/** @lends cc.TransitionPageTu /** * custom on enter */ - onEnter:function () { + onEnter: function () { cc.TransitionScene.prototype.onEnter.call(this); var winSize = cc.director.getWinSize(); var x, y; @@ -123,16 +123,16 @@ cc.TransitionPageTurn = cc.TransitionScene.extend(/** @lends cc.TransitionPageTu } }, - visit: function(){ + visit: function () { //cc.TransitionScene.prototype.visit.call(this); - if(this._back) + if (this._back) this._outScene.visit(); else this._inScene.visit(); this._gridProxy.visit(); }, - _sceneOrder:function () { + _sceneOrder: function () { this._isInSceneOnTop = this._back; } }); diff --git a/extensions/ccb-reader/CCBAnimationManager.js b/extensions/ccb-reader/CCBAnimationManager.js index b341ea4bbd..faedbfb6c4 100644 --- a/extensions/ccb-reader/CCBAnimationManager.js +++ b/extensions/ccb-reader/CCBAnimationManager.js @@ -25,42 +25,43 @@ ****************************************************************************/ cc.BuilderAnimationManagerDelegate = cc.Class.extend({ - completedAnimationSequenceNamed:function (name) {} + completedAnimationSequenceNamed: function (name) { + } }); cc.BuilderAnimationManager = cc.Class.extend({ - _sequences:null, - _nodeSequences:null, - _baseValues:null, - _autoPlaySequenceId:0, - - _rootNode:null, - _owner:null, - _rootContainerSize:null, - - _delegate:null, - _runningSequence:null, - - _documentOutletNames:null, - _documentOutletNodes:null, - _documentCallbackNames:null, - _documentCallbackNodes:null, - _documentCallbackControlEvents:null, - _documentControllerName:"", - _lastCompletedSequenceName:"", - _keyframeCallbacks:null, - _keyframeCallFuncs:null, - - _animationCompleteCallbackFunc:null, - _target:null, - _jsControlled:false, - - ctor:function () { + _sequences: null, + _nodeSequences: null, + _baseValues: null, + _autoPlaySequenceId: 0, + + _rootNode: null, + _owner: null, + _rootContainerSize: null, + + _delegate: null, + _runningSequence: null, + + _documentOutletNames: null, + _documentOutletNodes: null, + _documentCallbackNames: null, + _documentCallbackNodes: null, + _documentCallbackControlEvents: null, + _documentControllerName: "", + _lastCompletedSequenceName: "", + _keyframeCallbacks: null, + _keyframeCallFuncs: null, + + _animationCompleteCallbackFunc: null, + _target: null, + _jsControlled: false, + + ctor: function () { this._rootContainerSize = cc.size(0, 0); this.init(); }, - init:function () { + init: function () { this._sequences = []; this._nodeSequences = new cc._Dictionary(); this._baseValues = new cc._Dictionary(); @@ -77,122 +78,122 @@ cc.BuilderAnimationManager = cc.Class.extend({ return true; }, - getSequences:function () { + getSequences: function () { return this._sequences; }, - setSequences:function(seqs){ + setSequences: function (seqs) { this._sequences = seqs; }, - getAutoPlaySequenceId:function () { + getAutoPlaySequenceId: function () { return this._autoPlaySequenceId; }, - setAutoPlaySequenceId:function (autoPlaySequenceId) { + setAutoPlaySequenceId: function (autoPlaySequenceId) { this._autoPlaySequenceId = autoPlaySequenceId; }, - getRootNode:function () { + getRootNode: function () { return this._rootNode; }, - setRootNode:function (rootNode) { + setRootNode: function (rootNode) { this._rootNode = rootNode; }, - getOwner:function () { + getOwner: function () { return this._owner; }, - setOwner:function (owner) { + setOwner: function (owner) { this._owner = owner; }, - addDocumentCallbackNode:function(node){ + addDocumentCallbackNode: function (node) { this._documentCallbackNodes.push(node); }, - addDocumentCallbackName:function(name){ + addDocumentCallbackName: function (name) { this._documentCallbackNames.push(name); }, - addDocumentCallbackControlEvents:function(controlEvents){ + addDocumentCallbackControlEvents: function (controlEvents) { this._documentCallbackControlEvents.push(controlEvents); }, - addDocumentOutletNode:function(node){ + addDocumentOutletNode: function (node) { this._documentOutletNodes.push(node); }, - addDocumentOutletName:function(name){ + addDocumentOutletName: function (name) { this._documentOutletNames.push(name); }, - setDocumentControllerName:function(name){ + setDocumentControllerName: function (name) { this._documentControllerName = name; }, - getDocumentControllerName:function(){ + getDocumentControllerName: function () { return this._documentControllerName; }, - getDocumentCallbackNames:function(){ + getDocumentCallbackNames: function () { return this._documentCallbackNames; }, - getDocumentCallbackNodes:function(){ + getDocumentCallbackNodes: function () { return this._documentCallbackNodes; }, - getDocumentCallbackControlEvents:function(){ + getDocumentCallbackControlEvents: function () { return this._documentCallbackControlEvents; }, - getDocumentOutletNames:function(){ + getDocumentOutletNames: function () { return this._documentOutletNames; }, - getDocumentOutletNodes:function(){ + getDocumentOutletNodes: function () { return this._documentOutletNodes; }, - getLastCompletedSequenceName:function(){ + getLastCompletedSequenceName: function () { return this._lastCompletedSequenceName; }, - getKeyframeCallbacks:function(){ + getKeyframeCallbacks: function () { return this._keyframeCallbacks; }, - getRootContainerSize:function () { + getRootContainerSize: function () { return this._rootContainerSize; }, - setRootContainerSize:function (rootContainerSize) { + setRootContainerSize: function (rootContainerSize) { this._rootContainerSize = cc.size(rootContainerSize.width, rootContainerSize.height); }, - getDelegate:function () { + getDelegate: function () { return this._delegate; }, - setDelegate:function (delegate) { + setDelegate: function (delegate) { this._delegate = delegate; }, - getRunningSequenceName:function () { - if(this._runningSequence) + getRunningSequenceName: function () { + if (this._runningSequence) return this._runningSequence.getName(); return null; }, - getContainerSize:function (node) { + getContainerSize: function (node) { if (node) return node.getContentSize(); else return this._rootContainerSize; }, - addNode:function (node, seq) { + addNode: function (node, seq) { this._nodeSequences.setObject(seq, node); }, - setBaseValue:function (value, node, propName) { + setBaseValue: function (value, node, propName) { var props = this._baseValues.objectForKey(node); if (!props) { props = new cc._Dictionary(); @@ -201,11 +202,11 @@ cc.BuilderAnimationManager = cc.Class.extend({ props.setObject(value, propName); }, - moveAnimationsFromNode:function(fromNode,toNode){ + moveAnimationsFromNode: function (fromNode, toNode) { // Move base values var locBaseValues = this._baseValues; var baseValue = locBaseValues.objectForKey(fromNode); - if(baseValue !== null) { + if (baseValue !== null) { locBaseValues.setObject(baseValue, toNode); locBaseValues.removeObjectForKey(fromNode); } @@ -213,13 +214,13 @@ cc.BuilderAnimationManager = cc.Class.extend({ // Move seqs var locNodeSequences = this._nodeSequences; var seqs = locNodeSequences.objectForKey(fromNode); - if(seqs != null) { + if (seqs != null) { locNodeSequences.setObject(seqs, toNode); locNodeSequences.removeObjectForKey(fromNode); } }, - getActionForCallbackChannel:function(channel) { + getActionForCallbackChannel: function (channel) { var lastKeyframeTime = 0; var actions = []; @@ -230,7 +231,7 @@ cc.BuilderAnimationManager = cc.Class.extend({ var keyframe = keyframes[i]; var timeSinceLastKeyframe = keyframe.getTime() - lastKeyframeTime; lastKeyframeTime = keyframe.getTime(); - if(timeSinceLastKeyframe > 0) { + if (timeSinceLastKeyframe > 0) { actions.push(cc.delayTime(timeSinceLastKeyframe)); } @@ -238,41 +239,41 @@ cc.BuilderAnimationManager = cc.Class.extend({ var selectorName = keyVal[0]; var selectorTarget = keyVal[1]; - if(this._jsControlled) { + if (this._jsControlled) { var callbackName = selectorTarget + ":" + selectorName; //add number to the stream var callback = this._keyframeCallFuncs[callbackName]; - if(callback != null) + if (callback != null) actions.push(callback); } else { var target; - if(selectorTarget === CCB_TARGETTYPE_DOCUMENTROOT) + if (selectorTarget === CCB_TARGETTYPE_DOCUMENTROOT) target = this._rootNode; else if (selectorTarget === CCB_TARGETTYPE_OWNER) target = this._owner; - if(target != null) { - if(selectorName.length > 0) { + if (target != null) { + if (selectorName.length > 0) { var selCallFunc = 0; - if(target.onResolveCCBCCCallFuncSelector != null) + if (target.onResolveCCBCCCallFuncSelector != null) selCallFunc = target.onResolveCCBCCCallFuncSelector(target, selectorName); - if(selCallFunc === 0) + if (selCallFunc === 0) cc.log("Skipping selector '" + selectorName + "' since no CCBSelectorResolver is present."); else - actions.push(cc.callFunc(selCallFunc,target)); + actions.push(cc.callFunc(selCallFunc, target)); } else { cc.log("Unexpected empty selector."); } } } } - if(actions.length < 1) + if (actions.length < 1) return null; return cc.sequence(actions); }, - getActionForSoundChannel:function(channel) { + getActionForSoundChannel: function (channel) { var lastKeyframeTime = 0; var actions = []; @@ -283,7 +284,7 @@ cc.BuilderAnimationManager = cc.Class.extend({ var keyframe = keyframes[i]; var timeSinceLastKeyframe = keyframe.getTime() - lastKeyframeTime; lastKeyframeTime = keyframe.getTime(); - if(timeSinceLastKeyframe > 0) { + if (timeSinceLastKeyframe > 0) { actions.push(cc.delayTime(timeSinceLastKeyframe)); } @@ -293,29 +294,29 @@ cc.BuilderAnimationManager = cc.Class.extend({ actions.push(cc.BuilderSoundEffect.create(soundFile, pitch, pan, gain)); } - if(actions.length < 1) + if (actions.length < 1) return null; return cc.sequence(actions); }, - runAnimationsForSequenceNamed:function(name){ + runAnimationsForSequenceNamed: function (name) { this.runAnimationsForSequenceIdTweenDuration(this._getSequenceId(name), 0); }, - runAnimationsForSequenceNamedTweenDuration:function(name, tweenDuration){ - this.runAnimationsForSequenceIdTweenDuration(this._getSequenceId(name), tweenDuration); + runAnimationsForSequenceNamedTweenDuration: function (name, tweenDuration) { + this.runAnimationsForSequenceIdTweenDuration(this._getSequenceId(name), tweenDuration); }, - runAnimationsForSequenceIdTweenDuration:function(nSeqId, tweenDuration){ - if(nSeqId === -1) + runAnimationsForSequenceIdTweenDuration: function (nSeqId, tweenDuration) { + if (nSeqId === -1) throw new Error("cc.BuilderAnimationManager.runAnimationsForSequenceIdTweenDuration(): Sequence id should not be -1"); tweenDuration = tweenDuration || 0; this._rootNode.stopAllActions(); var allKeys = this._nodeSequences.allKeys(); - for(var i = 0,len = allKeys.length ; i< len;i++){ + for (var i = 0, len = allKeys.length; i < len; i++) { var node = allKeys[i]; node.stopAllActions(); @@ -323,27 +324,27 @@ cc.BuilderAnimationManager = cc.Class.extend({ var seqNodeProps = seqs.objectForKey(nSeqId); var j; var seqNodePropNames = []; - if(seqNodeProps){ + if (seqNodeProps) { var propKeys = seqNodeProps.allKeys(); - for(j = 0; j < propKeys.length; j++){ + for (j = 0; j < propKeys.length; j++) { var propName = propKeys[j]; var seqProp = seqNodeProps.objectForKey(propName); seqNodePropNames.push(propName); - this._setFirstFrame(node, seqProp,tweenDuration); - this._runAction(node,seqProp,tweenDuration); + this._setFirstFrame(node, seqProp, tweenDuration); + this._runAction(node, seqProp, tweenDuration); } } var nodeBaseValues = this._baseValues.objectForKey(node); - if(nodeBaseValues){ + if (nodeBaseValues) { var baseKeys = nodeBaseValues.allKeys(); - for(j = 0; j < baseKeys.length;j++){ - var selBaseKey = baseKeys[j]; - if(seqNodePropNames.indexOf(selBaseKey) === -1){ + for (j = 0; j < baseKeys.length; j++) { + var selBaseKey = baseKeys[j]; + if (seqNodePropNames.indexOf(selBaseKey) === -1) { var value = nodeBaseValues.objectForKey(selBaseKey); - if(value != null) - this._setAnimatedProperty(selBaseKey,node, value, tweenDuration); + if (value != null) + this._setAnimatedProperty(selBaseKey, node, value, tweenDuration); } } } @@ -352,7 +353,7 @@ cc.BuilderAnimationManager = cc.Class.extend({ // Make callback at end of sequence var seq = this._getSequence(nSeqId); var completeAction = cc.sequence(cc.delayTime(seq.getDuration() + tweenDuration), - cc.callFunc(this._sequenceCompleted,this)); + cc.callFunc(this._sequenceCompleted, this)); this._rootNode.runAction(completeAction); // Playback callbacks and sounds @@ -376,10 +377,10 @@ cc.BuilderAnimationManager = cc.Class.extend({ this._runningSequence = this._getSequence(nSeqId); }, - runAnimations:function (name, tweenDuration) { + runAnimations: function (name, tweenDuration) { tweenDuration = tweenDuration || 0; var nSeqId; - if(cc.isString(name)) + if (cc.isString(name)) nSeqId = this._getSequenceId(name); else nSeqId = name; @@ -387,29 +388,29 @@ cc.BuilderAnimationManager = cc.Class.extend({ this.runAnimationsForSequenceIdTweenDuration(nSeqId, tweenDuration); }, - setAnimationCompletedCallback:function(target,callbackFunc){ + setAnimationCompletedCallback: function (target, callbackFunc) { this._target = target; this._animationCompleteCallbackFunc = callbackFunc; }, - setCompletedAnimationCallback:function(target,callbackFunc){ - this.setAnimationCompletedCallback(target,callbackFunc); + setCompletedAnimationCallback: function (target, callbackFunc) { + this.setAnimationCompletedCallback(target, callbackFunc); }, - setCallFunc:function(callFunc, callbackNamed) { + setCallFunc: function (callFunc, callbackNamed) { this._keyframeCallFuncs[callbackNamed] = callFunc; }, - debug:function () { + debug: function () { }, - _getBaseValue:function (node, propName) { + _getBaseValue: function (node, propName) { var props = this._baseValues.objectForKey(node); if (props) return props.objectForKey(propName); return null; }, - _getSequenceId:function (sequenceName) { + _getSequenceId: function (sequenceName) { var element = null; var locSequences = this._sequences; for (var i = 0, len = locSequences.length; i < len; i++) { @@ -420,7 +421,7 @@ cc.BuilderAnimationManager = cc.Class.extend({ return -1; }, - _getSequence:function (sequenceId) { + _getSequence: function (sequenceId) { var element = null; var locSequences = this._sequences; for (var i = 0, len = locSequences.length; i < len; i++) { @@ -431,9 +432,9 @@ cc.BuilderAnimationManager = cc.Class.extend({ return null; }, - _getAction:function (keyframe0, keyframe1, propName, node) { + _getAction: function (keyframe0, keyframe1, propName, node) { var duration = keyframe1.getTime() - (keyframe0 ? keyframe0.getTime() : 0); - var getArr,type,getValueArr, x, y; + var getArr, type, getValueArr, x, y; if (propName === "rotation") { return cc.BuilderRotateTo.create(duration, keyframe1.getValue()); @@ -455,8 +456,8 @@ cc.BuilderAnimationManager = cc.Class.extend({ } } else if (propName === "displayFrame") { return cc.sequence(cc.delayTime(duration), cc.BuilderSetSpriteFrame.create(keyframe1.getValue())); - } else if(propName === "position"){ - getArr = this._getBaseValue(node,propName); + } else if (propName === "position") { + getArr = this._getBaseValue(node, propName); type = getArr[2]; //get relative position @@ -466,11 +467,11 @@ cc.BuilderAnimationManager = cc.Class.extend({ var containerSize = this.getContainerSize(node.getParent()); - var absPos = cc._getAbsolutePosition(x,y, type,containerSize,propName); + var absPos = cc._getAbsolutePosition(x, y, type, containerSize, propName); - return cc.moveTo(duration,absPos); - } else if( propName === "scale"){ - getArr = this._getBaseValue(node,propName); + return cc.moveTo(duration, absPos); + } else if (propName === "scale") { + getArr = this._getBaseValue(node, propName); type = getArr[2]; //get relative position @@ -478,28 +479,28 @@ cc.BuilderAnimationManager = cc.Class.extend({ x = getValueArr[0]; y = getValueArr[1]; - if(type === CCB_SCALETYPE_MULTIPLY_RESOLUTION){ + if (type === CCB_SCALETYPE_MULTIPLY_RESOLUTION) { //TODO need to test var resolutionScale = cc.BuilderReader.getResolutionScale(); x *= resolutionScale; y *= resolutionScale; } - return cc.scaleTo(duration,x,y); - } else if( propName === "skew") { + return cc.scaleTo(duration, x, y); + } else if (propName === "skew") { //get relative position getValueArr = keyframe1.getValue(); x = getValueArr[0]; y = getValueArr[1]; - return cc.skewTo(duration,x,y); + return cc.skewTo(duration, x, y); } else { cc.log("BuilderReader: Failed to create animation for property: " + propName); } return null; }, - _setAnimatedProperty:function (propName, node, value, tweenDuration) { - if(tweenDuration > 0){ + _setAnimatedProperty: function (propName, node, value, tweenDuration) { + if (tweenDuration > 0) { // Create a fake keyframe to generate the action from var kf1 = new cc.BuilderKeyframe(); kf1.setValue(value); @@ -511,64 +512,62 @@ cc.BuilderAnimationManager = cc.Class.extend({ node.runAction(tweenAction); } else { // Just set the value - var getArr, nType, x,y; - if(propName === "position"){ - getArr = this._getBaseValue(node,propName); + var getArr, nType, x, y; + if (propName === "position") { + getArr = this._getBaseValue(node, propName); nType = getArr[2]; x = value[0]; y = value[1]; - node.setPosition(cc._getAbsolutePosition(x,y,nType, this.getContainerSize(node.getParent()),propName)); - }else if(propName === "scale"){ - getArr = this._getBaseValue(node,propName); + node.setPosition(cc._getAbsolutePosition(x, y, nType, this.getContainerSize(node.getParent()), propName)); + } else if (propName === "scale") { + getArr = this._getBaseValue(node, propName); nType = getArr[2]; x = value[0]; y = value[1]; - cc.setRelativeScale(node,x,y,nType,propName); - } else if( propName === "skew") { + cc.setRelativeScale(node, x, y, nType, propName); + } else if (propName === "skew") { x = value[0]; y = value[1]; node.setSkewX(x); node.setSkewY(y); - }else { + } else { // [node setValue:value forKey:name]; // TODO only handle rotation, opacity, displayFrame, color - if(propName === "rotation"){ + if (propName === "rotation") { node.setRotation(value); - } else if(propName === "rotationX") - { + } else if(propName === "rotationX") { node.setRotationSkewX(value); - }else if(propName === "rotationY") - { + } else if(propName === "rotationY") { node.setRotationSkewY(value); - }else if(propName === "opacity"){ + } else if(propName === "opacity") { node.setOpacity(value); - } else if(propName === "displayFrame"){ + } else if(propName === "displayFrame") { node.setSpriteFrame(value); - } else if(propName === "color"){ + } else if(propName === "color") { var ccColor3B = value.getColor(); if(ccColor3B.r !== 255 || ccColor3B.g !== 255 || ccColor3B.b !== 255){ node.setColor(ccColor3B); } - } else if( propName === "visible"){ + } else if (propName === "visible") { value = value || false; node.setVisible(value); } else { - cc.log("unsupported property name is "+ propName); + cc.log("unsupported property name is " + propName); } } } }, - _setFirstFrame:function (node, seqProp, tweenDuration) { + _setFirstFrame: function (node, seqProp, tweenDuration) { var keyframes = seqProp.getKeyframes(); if (keyframes.length === 0) { // Use base value (no animation) var baseValue = this._getBaseValue(node, seqProp.getName()); - if(!baseValue) + if (!baseValue) cc.log("cc.BuilderAnimationManager._setFirstFrame(): No baseValue found for property"); this._setAnimatedProperty(seqProp.getName(), node, baseValue, tweenDuration); } else { @@ -578,8 +577,8 @@ cc.BuilderAnimationManager = cc.Class.extend({ } }, - _getEaseAction:function (action, easingType, easingOpt) { - if (easingType === CCB_KEYFRAME_EASING_LINEAR || easingType === CCB_KEYFRAME_EASING_INSTANT ) { + _getEaseAction: function (action, easingType, easingOpt) { + if (easingType === CCB_KEYFRAME_EASING_LINEAR || easingType === CCB_KEYFRAME_EASING_INSTANT) { return action; } else if (easingType === CCB_KEYFRAME_EASING_CUBIC_IN) { return action.easing(cc.easeIn(easingOpt)); @@ -611,7 +610,7 @@ cc.BuilderAnimationManager = cc.Class.extend({ } }, - _runAction:function (node, seqProp, tweenDuration) { + _runAction: function (node, seqProp, tweenDuration) { var keyframes = seqProp.getKeyframes(); var numKeyframes = keyframes.length; @@ -628,7 +627,7 @@ cc.BuilderAnimationManager = cc.Class.extend({ for (var i = 0; i < numKeyframes - 1; ++i) { var kf0 = keyframes[i]; - var kf1 = keyframes[(i+1)]; + var kf1 = keyframes[(i + 1)]; var action = this._getAction(kf0, kf1, seqProp.getName(), node); if (action) { @@ -642,12 +641,12 @@ cc.BuilderAnimationManager = cc.Class.extend({ } }, - _sequenceCompleted:function () { + _sequenceCompleted: function () { var locRunningSequence = this._runningSequence; var locRunningName = locRunningSequence.getName(); - if(this._lastCompletedSequenceName != locRunningSequence.getName()){ + if (this._lastCompletedSequenceName != locRunningSequence.getName()) { this._lastCompletedSequenceName = locRunningSequence.getName(); } @@ -660,7 +659,7 @@ cc.BuilderAnimationManager = cc.Class.extend({ if (this._delegate) this._delegate.completedAnimationSequenceNamed(locRunningName); - if(this._target && this._animationCompleteCallbackFunc){ + if (this._target && this._animationCompleteCallbackFunc) { this._animationCompleteCallbackFunc.call(this._target); } } @@ -668,13 +667,13 @@ cc.BuilderAnimationManager = cc.Class.extend({ cc.BuilderSetSpriteFrame = cc.ActionInstant.extend({ - _spriteFrame:null, + _spriteFrame: null, - initWithSpriteFrame:function (spriteFrame) { + initWithSpriteFrame: function (spriteFrame) { this._spriteFrame = spriteFrame; return true; }, - update:function (time) { + update: function (time) { this.target.setSpriteFrame(this._spriteFrame); } }); @@ -692,11 +691,11 @@ cc.BuilderSetSpriteFrame.create = function (spriteFrame) { // cc.BuilderRotateTo // cc.BuilderRotateTo = cc.ActionInterval.extend({ - _startAngle:0, - _dstAngle:0, - _diffAngle:0, + _startAngle: 0, + _dstAngle: 0, + _diffAngle: 0, - initWithDuration:function (duration, angle) { + initWithDuration: function (duration, angle) { if (cc.ActionInterval.prototype.initWithDuration.call(this, duration)) { this._dstAngle = angle; return true; @@ -704,11 +703,11 @@ cc.BuilderRotateTo = cc.ActionInterval.extend({ return false; } }, - update:function (time) { + update: function (time) { this.target.setRotation(this._startAngle + (this._diffAngle * time)); }, - startWithTarget:function (node) { + startWithTarget: function (node) { cc.ActionInterval.prototype.startWithTarget.call(this, node); this._startAngle = this.target.getRotation(); this._diffAngle = this._dstAngle - this._startAngle; @@ -750,18 +749,18 @@ cc.BuilderRotateYTo.create = function (duration, angle) { // cc.BuilderSoundEffect // cc.BuilderSoundEffect = cc.ActionInstant.extend({ - init:function(file) { + init: function (file) { this._file = file; return true; }, - update:function(dt) { + update: function (dt) { cc.audioEngine.playEffect(this._file); } }); cc.BuilderSoundEffect.create = function (file, pitch, pan, gain) { var ret = new cc.BuilderSoundEffect(); if (ret && ret.init(file)) { - return ret; + return ret; } return null; }; diff --git a/extensions/ccb-reader/CCBReader.js b/extensions/ccb-reader/CCBReader.js index d613575d0d..5703adf558 100644 --- a/extensions/ccb-reader/CCBReader.js +++ b/extensions/ccb-reader/CCBReader.js @@ -121,39 +121,39 @@ cc.BuilderFile.create = function () { * Parse CCBI file which is generated by CocosBuilder */ cc.BuilderReader = cc.Class.extend({ - _jsControlled:false, - _data:null, - _ccbRootPath:"", + _jsControlled: false, + _data: null, + _ccbRootPath: "", - _bytes:0, - _currentByte:0, - _currentBit:0, + _bytes: 0, + _currentByte: 0, + _currentBit: 0, - _stringCache:null, - _loadedSpriteSheets:null, + _stringCache: null, + _loadedSpriteSheets: null, - _owner:null, - _animationManager:null, - _animationManagers:null, - _animatedProps:null, + _owner: null, + _animationManager: null, + _animationManagers: null, + _animatedProps: null, - _ccNodeLoaderLibrary:null, - _ccNodeLoaderListener:null, - _ccbMemberVariableAssigner:null, - _ccbSelectorResolver:null, + _ccNodeLoaderLibrary: null, + _ccNodeLoaderListener: null, + _ccbMemberVariableAssigner: null, + _ccbSelectorResolver: null, - _ownerOutletNames:null, - _ownerOutletNodes:null, - _nodesWithAnimationManagers:null, - _animationManagerForNodes:null, + _ownerOutletNames: null, + _ownerOutletNodes: null, + _nodesWithAnimationManagers: null, + _animationManagerForNodes: null, - _ownerCallbackNames:null, - _ownerCallbackNodes:null, - _ownerCallbackEvents:null, + _ownerCallbackNames: null, + _ownerCallbackNodes: null, + _ownerCallbackEvents: null, - _readNodeGraphFromData:false, + _readNodeGraphFromData: false, - ctor:function (ccNodeLoaderLibrary, ccbMemberVariableAssigner, ccbSelectorResolver, ccNodeLoaderListener) { + ctor: function (ccNodeLoaderLibrary, ccbMemberVariableAssigner, ccbSelectorResolver, ccNodeLoaderListener) { this._stringCache = []; this._loadedSpriteSheets = []; this._currentBit = -1; @@ -186,15 +186,15 @@ cc.BuilderReader = cc.Class.extend({ } }, - getCCBRootPath:function () { + getCCBRootPath: function () { return this._ccbRootPath; }, - setCCBRootPath:function (rootPath) { + setCCBRootPath: function (rootPath) { this._ccbRootPath = rootPath; }, - initWithData:function (data, owner) { + initWithData: function (data, owner) { //setup action manager this._animationManager = new cc.BuilderAnimationManager(); @@ -213,7 +213,7 @@ cc.BuilderReader = cc.Class.extend({ return true; }, - _loadBinarySync : function(url){ + _loadBinarySync: function (url) { var self = this; var req = this.getXMLHttpRequest(); var errInfo = "load " + url + " failed!"; @@ -247,7 +247,7 @@ cc.BuilderReader = cc.Class.extend({ return arrayInfo; }, - readNodeGraphFromFile:function (ccbFileName, owner, parentSize, animationManager) { + readNodeGraphFromFile: function (ccbFileName, owner, parentSize, animationManager) { if (parentSize == null) { parentSize = cc.director.getWinSize(); } else if (parentSize instanceof cc.BuilderAnimationManager) { @@ -256,7 +256,7 @@ cc.BuilderReader = cc.Class.extend({ } var data = cc.loader.getRes(ccbFileName); - if(!data){ + if (!data) { var realUrl = cc.loader.getUrl(ccbFileName); data = cc.loader.loadBinarySync(realUrl); cc.loader.cache[ccbFileName] = data; @@ -265,7 +265,7 @@ cc.BuilderReader = cc.Class.extend({ return this.readNodeGraphFromData(data, owner, parentSize, animationManager); }, - readNodeGraphFromData:function (data, owner, parentSize) { + readNodeGraphFromData: function (data, owner, parentSize) { this.initWithData(data, owner); var locAnimationManager = this._animationManager; locAnimationManager.setRootContainerSize(parentSize); @@ -303,42 +303,42 @@ cc.BuilderReader = cc.Class.extend({ return nodeGraph; }, - createSceneWithNodeGraphFromFile:function (ccbFileName, owner, parentSize, animationManager) { + createSceneWithNodeGraphFromFile: function (ccbFileName, owner, parentSize, animationManager) { var node = this.readNodeGraphFromFile(ccbFileName, owner, parentSize, animationManager); var scene = new cc.Scene(); scene.addChild(node); return scene; }, - getCCBMemberVariableAssigner:function () { + getCCBMemberVariableAssigner: function () { return this._ccbMemberVariableAssigner; }, - getCCBSelectorResolver:function () { + getCCBSelectorResolver: function () { return this._ccbSelectorResolver; }, - getAnimationManager:function () { + getAnimationManager: function () { return this._animationManager; }, - setAnimationManager:function (animationManager) { + setAnimationManager: function (animationManager) { this._animationManager = animationManager; }, - getAnimatedProperties:function () { + getAnimatedProperties: function () { return this._animatedProps; }, - getLoadedSpriteSheet:function () { + getLoadedSpriteSheet: function () { return this._loadedSpriteSheets; }, - getOwner:function () { + getOwner: function () { return this._owner; }, - readInt:function (signed) { + readInt: function (signed) { var numBits = 0; while (!this._getBit()) { numBits++; @@ -369,17 +369,17 @@ cc.BuilderReader = cc.Class.extend({ return num; }, - readByte:function () { + readByte: function () { var byteValue = this._data[this._currentByte]; this._currentByte++; return byteValue; }, - readBool:function () { + readBool: function () { return (0 !== this.readByte()); }, - readFloat:function () { + readFloat: function () { var type = this.readByte(); switch (type) { @@ -403,7 +403,7 @@ cc.BuilderReader = cc.Class.extend({ } }, - _decodeFloat:function (precisionBits, exponentBits) { + _decodeFloat: function (precisionBits, exponentBits) { var length = precisionBits + exponentBits + 1; var size = length >> 3; this._checkSize(length); @@ -433,7 +433,7 @@ cc.BuilderReader = cc.Class.extend({ : Math.pow(2, exponent - bias) * (1 + significand) : 0); }, - _readBitsOnly:function (start, length, size) { + _readBitsOnly: function (start, length, size) { var offsetLeft = (start + length) % 8; var offsetRight = start % 8; var curByte = size - (start >> 3) - 1; @@ -453,90 +453,90 @@ cc.BuilderReader = cc.Class.extend({ return sum; }, - _readByteOnly:function (i, size) { + _readByteOnly: function (i, size) { return this._data[this._currentByte + size - i - 1]; }, - _shl:function (a, b) { + _shl: function (a, b) { for (++b; --b; a = ((a %= 0x7fffffff + 1) & 0x40000000) === 0x40000000 ? a * 2 : (a - 0x40000000) * 2 + 0x7fffffff + 1); return a; }, - _checkSize:function (neededBits) { + _checkSize: function (neededBits) { if (!(this._currentByte + Math.ceil(neededBits / 8) < this._data.length)) { throw new Error("Index out of bound"); } }, - readCachedString:function () { + readCachedString: function () { return this._stringCache[this.readInt(false)]; }, - isJSControlled:function () { + isJSControlled: function () { return this._jsControlled; }, - getOwnerCallbackNames:function () { + getOwnerCallbackNames: function () { return this._ownerCallbackNames; }, - getOwnerCallbackNodes:function () { + getOwnerCallbackNodes: function () { return this._ownerCallbackNodes; }, - getOwnerCallbackControlEvents:function(){ + getOwnerCallbackControlEvents: function () { return this._ownerCallbackEvents; }, - getOwnerOutletNames:function () { + getOwnerOutletNames: function () { return this._ownerOutletNames; }, - getOwnerOutletNodes:function () { + getOwnerOutletNodes: function () { return this._ownerOutletNodes; }, - getNodesWithAnimationManagers:function () { + getNodesWithAnimationManagers: function () { return this._nodesWithAnimationManagers; }, - getAnimationManagersForNodes:function () { + getAnimationManagersForNodes: function () { return this._animationManagerForNodes; }, - getAnimationManagers:function () { + getAnimationManagers: function () { return this._animationManagers; }, - setAnimationManagers:function (animationManagers) { + setAnimationManagers: function (animationManagers) { this._animationManagers = animationManagers; }, - addOwnerCallbackName:function (name) { - this._ownerCallbackNames.push(name) + addOwnerCallbackName: function (name) { + this._ownerCallbackNames.push(name); }, - addOwnerCallbackNode:function (node) { + addOwnerCallbackNode: function (node) { this._ownerCallbackNodes.push(node); }, - addOwnerCallbackControlEvents:function(event){ + addOwnerCallbackControlEvents: function (event) { this._ownerCallbackEvents.push(event); }, - addDocumentCallbackName:function (name) { + addDocumentCallbackName: function (name) { this._animationManager.addDocumentCallbackName(name); }, - addDocumentCallbackNode:function (node) { + addDocumentCallbackNode: function (node) { this._animationManager.addDocumentCallbackNode(node); }, - addDocumentCallbackControlEvents:function(controlEvents){ + addDocumentCallbackControlEvents: function (controlEvents) { this._animationManager.addDocumentCallbackControlEvents(controlEvents); }, - readFileWithCleanUp:function (cleanUp) { + readFileWithCleanUp: function (cleanUp) { if (!this._readHeader()) return null; if (!this._readStringCache()) @@ -552,18 +552,18 @@ cc.BuilderReader = cc.Class.extend({ return node; }, - addOwnerOutletName: function(name){ - this._ownerOutletNames.push(name); + addOwnerOutletName: function (name) { + this._ownerOutletNames.push(name); }, - addOwnerOutletNode: function(node){ - if(node == null) + addOwnerOutletNode: function (node) { + if (node == null) return; this._ownerOutletNodes.push(node); }, - _cleanUpNodeGraph:function (node) { + _cleanUpNodeGraph: function (node) { node.userObject = null; var getChildren = node.getChildren(); for (var i = 0, len = getChildren.length; i < len; i++) { @@ -571,7 +571,7 @@ cc.BuilderReader = cc.Class.extend({ } }, - _readCallbackKeyframesForSeq:function(seq) { + _readCallbackKeyframesForSeq: function (seq) { var numKeyframes = this.readInt(false); if (!numKeyframes) @@ -584,14 +584,14 @@ cc.BuilderReader = cc.Class.extend({ var callbackName = this.readCachedString(); var callbackType = this.readInt(false); - var value = [ callbackName, callbackType]; + var value = [callbackName, callbackType]; var keyframe = new cc.BuilderKeyframe(); keyframe.setTime(time); keyframe.setValue(value); - if(locJsControlled) - locAnimationManager.getKeyframeCallbacks().push(callbackType+":"+callbackName); + if (locJsControlled) + locAnimationManager.getKeyframeCallbacks().push(callbackType + ":" + callbackName); locKeyframes.push(keyframe); } @@ -602,7 +602,7 @@ cc.BuilderReader = cc.Class.extend({ return true; }, - _readSoundKeyframesForSeq:function(seq) { + _readSoundKeyframesForSeq: function (seq) { var numKeyframes = this.readInt(false); if (!numKeyframes) @@ -617,7 +617,7 @@ cc.BuilderReader = cc.Class.extend({ var pan = this.readFloat(); var gain = this.readFloat(); - var value = [soundFile, pitch, pan, gain]; + var value = [soundFile, pitch, pan, gain]; var keyframe = new cc.BuilderKeyframe(); keyframe.setTime(time); keyframe.setValue(value); @@ -629,7 +629,7 @@ cc.BuilderReader = cc.Class.extend({ seq.setSoundChannel(channel); return true; }, - _readSequences:function () { + _readSequences: function () { var sequences = this._animationManager.getSequences(); var numSeqs = this.readInt(false); for (var i = 0; i < numSeqs; i++) { @@ -650,7 +650,7 @@ cc.BuilderReader = cc.Class.extend({ return true; }, - readKeyframe:function (type) { + readKeyframe: function (type) { var keyframe = new cc.BuilderKeyframe(); keyframe.setTime(this.readFloat()); var easingType = this.readInt(false); @@ -707,7 +707,7 @@ cc.BuilderReader = cc.Class.extend({ return keyframe; }, - _readHeader:function () { + _readHeader: function () { /* If no bytes loaded, don't crash about it. */ if (!this._data) return false; @@ -733,7 +733,7 @@ cc.BuilderReader = cc.Class.extend({ return true; }, - _readStringFromBytes:function (startIndex, strLen, reverse) { + _readStringFromBytes: function (startIndex, strLen, reverse) { reverse = reverse || false; var strValue = ""; var i, locData = this._data, locCurrentByte = this._currentByte; @@ -747,14 +747,14 @@ cc.BuilderReader = cc.Class.extend({ return strValue; }, - _readStringCache:function () { + _readStringCache: function () { var numStrings = this.readInt(false); for (var i = 0; i < numStrings; i++) this._readStringCacheEntry(); return true; }, - _readStringCacheEntry:function () { + _readStringCacheEntry: function () { var b0 = this.readByte(); var b1 = this.readByte(); @@ -772,7 +772,7 @@ cc.BuilderReader = cc.Class.extend({ this._stringCache.push(str); }, - _readNodeGraph:function (parent) { + _readNodeGraph: function (parent) { /* Read class name. */ var className = this.readCachedString(); @@ -887,16 +887,16 @@ cc.BuilderReader = cc.Class.extend({ // Assign custom properties. if (ccNodeLoader.getCustomProperties().length > 0) { var customAssigned = false; - if(!locJsControlled) { + if (!locJsControlled) { target = node; - if(target != null && target.onAssignCCBCustomProperty != null) { + if (target != null && target.onAssignCCBCustomProperty != null) { var customProperties = ccNodeLoader.getCustomProperties(); var customPropKeys = customProperties.allKeys(); - for(i = 0;i < customPropKeys.length;i++){ + for (i = 0; i < customPropKeys.length; i++) { var customPropValue = customProperties.objectForKey(customPropKeys[i]); customAssigned = target.onAssignCCBCustomProperty(target, customPropKeys[i], customPropValue); locMemberAssigner = this._ccbMemberVariableAssigner; - if(!customAssigned && (locMemberAssigner != null) && (locMemberAssigner.onAssignCCBCustomProperty != null)) + if (!customAssigned && (locMemberAssigner != null) && (locMemberAssigner.onAssignCCBCustomProperty != null)) customAssigned = locMemberAssigner.onAssignCCBCustomProperty(target, customPropKeys[i], customPropValue); } } @@ -951,7 +951,7 @@ cc.BuilderReader = cc.Class.extend({ }); cc.BuilderReader._ccbResolutionScale = 1; -cc.BuilderReader.setResolutionScale = function(scale){ +cc.BuilderReader.setResolutionScale = function (scale) { cc.BuilderReader._ccbResolutionScale = scale; }; @@ -970,14 +970,14 @@ cc.BuilderReader.loadAsScene = function (ccbFilePath, owner, parentSize, ccbRoot }; cc.BuilderReader._controllerClassCache = {}; -cc.BuilderReader.registerController = function(controllerName, controller){ +cc.BuilderReader.registerController = function (controllerName, controller) { cc.BuilderReader._controllerClassCache[controllerName] = cc.Class.extend(controller); }; cc.BuilderReader.load = function (ccbFilePath, owner, parentSize, ccbRootPath) { ccbRootPath = ccbRootPath || cc.BuilderReader.getResourcePath(); var reader = new cc.BuilderReader(cc.NodeLoaderLibrary.newDefaultCCNodeLoaderLibrary()); reader.setCCBRootPath(ccbRootPath); - if((ccbFilePath.length < 5)||(ccbFilePath.toLowerCase().lastIndexOf(".ccbi") !== ccbFilePath.length - 5)) + if ((ccbFilePath.length < 5) || (ccbFilePath.toLowerCase().lastIndexOf(".ccbi") !== ccbFilePath.length - 5)) ccbFilePath = ccbFilePath + ".ccbi"; var node = reader.readNodeGraphFromFile(ccbFilePath, owner, parentSize); @@ -993,7 +993,7 @@ cc.BuilderReader.load = function (ccbFilePath, owner, parentSize, ccbRootPath) { callbackName = ownerCallbackNames[i]; callbackNode = ownerCallbackNodes[i]; callbackControlEvents = ownerCallbackControlEvents[i]; - if(callbackNode instanceof cc.ControlButton) + if (callbackNode instanceof cc.ControlButton) callbackNode.addTargetWithActionForControlEvents(owner, owner[callbackName], callbackControlEvents); //register all type of events else callbackNode.setCallback(owner[callbackName], owner); @@ -1011,7 +1011,7 @@ cc.BuilderReader.load = function (ccbFilePath, owner, parentSize, ccbRootPath) { var nodesWithAnimationManagers = reader.getNodesWithAnimationManagers(); var animationManagersForNodes = reader.getAnimationManagersForNodes(); - if(!nodesWithAnimationManagers || !animationManagersForNodes) + if (!nodesWithAnimationManagers || !animationManagersForNodes) return node; var controllerClassCache = cc.BuilderReader._controllerClassCache; @@ -1028,7 +1028,7 @@ cc.BuilderReader.load = function (ccbFilePath, owner, parentSize, ccbRootPath) { // Create a controller var controllerClass = controllerClassCache[controllerName]; - if(!controllerClass) throw new Error("Can not find controller : " + controllerName); + if (!controllerClass) throw new Error("Can not find controller : " + controllerName); var controller = new controllerClass(); controller.controllerName = controllerName; @@ -1043,7 +1043,7 @@ cc.BuilderReader.load = function (ccbFilePath, owner, parentSize, ccbRootPath) { callbackName = documentCallbackNames[j]; callbackNode = documentCallbackNodes[j]; callbackControlEvents = documentCallbackControlEvents[j]; - if(callbackNode instanceof cc.ControlButton) + if (callbackNode instanceof cc.ControlButton) callbackNode.addTargetWithActionForControlEvents(controller, controller[callbackName], callbackControlEvents); //register all type of events else callbackNode.setCallback(controller[callbackName], controller); @@ -1069,7 +1069,7 @@ cc.BuilderReader.load = function (ccbFilePath, owner, parentSize, ccbRootPath) { var callbackType = callbackSplit[0]; var kfCallbackName = callbackSplit[1]; - if (callbackType == 1){ // Document callback + if (callbackType == 1) { // Document callback animationManager.setCallFunc(cc.callFunc(controller[kfCallbackName], controller), keyframeCallbacks[j]); } else if (callbackType == 2 && owner) {// Owner callback animationManager.setCallFunc(cc.callFunc(owner[kfCallbackName], owner), keyframeCallbacks[j]); @@ -1123,4 +1123,4 @@ cc.BuilderReader.concat = function (stringA, stringB) { return stringA + stringB; }; -cc.loader.register(["ccbi"], cc._binaryLoader); \ No newline at end of file +cc.loader.register(["ccbi"], cc._binaryLoader); diff --git a/extensions/ccb-reader/CCBReaderUtil.js b/extensions/ccb-reader/CCBReaderUtil.js index d3ebcfa821..0de9c4fa30 100644 --- a/extensions/ccb-reader/CCBReaderUtil.js +++ b/extensions/ccb-reader/CCBReaderUtil.js @@ -25,17 +25,22 @@ ****************************************************************************/ cc.NodeLoaderListener = cc.Class.extend({ - onNodeLoaded:function(node,nodeLoader){} + onNodeLoaded: function (node, nodeLoader) { + } }); cc.BuilderSelectorResolver = cc.Class.extend({ - onResolveCCBCCMenuItemSelector:function(target, selectorName){}, - onResolveCCBCCCallFuncSelector:function(target, selectorName){}, - onResolveCCBCCControlSelector:function(target,selectorName){} + onResolveCCBCCMenuItemSelector: function (target, selectorName) { + }, + onResolveCCBCCCallFuncSelector: function (target, selectorName) { + }, + onResolveCCBCCControlSelector: function (target, selectorName) { + } }); cc.BuilderScriptOwnerProtocol = cc.Class.extend({ - createNew:function(){} + createNew: function () { + } }); cc.BuilderMemberVariableAssigner = cc.Class.extend({ @@ -47,7 +52,9 @@ cc.BuilderMemberVariableAssigner = cc.Class.extend({ * @param {cc.Node} node The member variable. * @return {Boolean} Whether the assignment was successful. */ - onAssignCCBMemberVariable:function(target,memberVariableName, node){ return false;}, + onAssignCCBMemberVariable: function (target, memberVariableName, node) { + return false; + }, /** * The callback function of assigning custom properties. @@ -57,5 +64,7 @@ cc.BuilderMemberVariableAssigner = cc.Class.extend({ * @param {*} value The value of the property. * @return {Boolean} Whether the assignment was successful. */ - onAssignCCBCustomProperty:function(target, memberVariableName, value){ return false; } + onAssignCCBCustomProperty: function (target, memberVariableName, value) { + return false; + } }); diff --git a/extensions/ccb-reader/CCBValue.js b/extensions/ccb-reader/CCBValue.js index 781c25d861..3b8c8f8011 100644 --- a/extensions/ccb-reader/CCBValue.js +++ b/extensions/ccb-reader/CCBValue.js @@ -56,21 +56,21 @@ cc.Color3BWapper.create = function (color) { }; cc.BuilderValue = cc.Class.extend({ - _value:null, - _type:0, + _value: null, + _type: 0, - getIntValue:function () { + getIntValue: function () { }, - getFloatValue:function () { + getFloatValue: function () { }, - getBoolValue:function () { + getBoolValue: function () { }, - getByteValue:function () { + getByteValue: function () { }, - getPointer:function () { + getPointer: function () { }, - getValue:function(){ + getValue: function () { return this._value; } }); diff --git a/extensions/ccb-reader/CCControlLoader.js b/extensions/ccb-reader/CCControlLoader.js index 901f8509dd..832a005bda 100644 --- a/extensions/ccb-reader/CCControlLoader.js +++ b/extensions/ccb-reader/CCControlLoader.js @@ -30,7 +30,7 @@ cc.BuilderFileLoader = cc.NodeLoader.extend({ _createCCNode:function (parent, ccbReader) { return cc.BuilderFile.create(); }, - onHandlePropTypeCCBFile:function (node, parent, propertyName, ccbFileNode, ccbReader) { + onHandlePropTypeCCBFile: function (node, parent, propertyName, ccbFileNode, ccbReader) { if (propertyName === PROPERTY_CCBFILE) { node.setCCBFileNode(ccbFileNode); } else { @@ -48,16 +48,16 @@ var PROPERTY_SELECTED = "selected"; var PROPERTY_CCCONTROL = "ccControl"; cc.ControlLoader = cc.NodeLoader.extend({ - _createCCNode:function (parent, ccbReander) { + _createCCNode: function (parent, ccbReander) { }, - onHandlePropTypeBlockCCControl:function (node, parent, propertyName, blockCCControlData, ccbReader) { + onHandlePropTypeBlockCCControl: function (node, parent, propertyName, blockCCControlData, ccbReader) { if (propertyName === PROPERTY_CCCONTROL) { node.addTargetWithActionForControlEvents(blockCCControlData.target, blockCCControlData.selCCControlHandler, blockCCControlData.controlEvents); } else { cc.NodeLoader.prototype.onHandlePropTypeBlockCCControl.call(this, node, parent, propertyName, blockCCControlData, ccbReader); } }, - onHandlePropTypeCheck:function (node, parent, propertyName, check, ccbReader) { + onHandlePropTypeCheck: function (node, parent, propertyName, check, ccbReader) { if (propertyName === PROPERTY_ENABLED) { node.setEnabled(check); } else if (propertyName === PROPERTY_SELECTED) { @@ -88,18 +88,18 @@ var PROPERTY_BACKGROUNDSPRITEFRAME_HIGHLIGHTED = "backgroundSpriteFrame|2"; var PROPERTY_BACKGROUNDSPRITEFRAME_DISABLED = "backgroundSpriteFrame|3"; cc.ControlButtonLoader = cc.ControlLoader.extend({ - _createCCNode:function (parent, ccbReader) { + _createCCNode: function (parent, ccbReader) { return new cc.ControlButton(); }, - onHandlePropTypeCheck:function (node, parent, propertyName, check, ccbReader) { + onHandlePropTypeCheck: function (node, parent, propertyName, check, ccbReader) { if (propertyName === PROPERTY_ZOOMONTOUCHDOWN) { node.setZoomOnTouchDown(check); } else { cc.ControlLoader.prototype.onHandlePropTypeCheck.call(this, node, parent, propertyName, check, ccbReader); } }, - onHandlePropTypeString:function (node, parent, propertyName, stringValue, ccbReader) { + onHandlePropTypeString: function (node, parent, propertyName, stringValue, ccbReader) { if (propertyName === PROPERTY_TITLE_NORMAL) { node.setTitleForState(stringValue, cc.CONTROL_STATE_NORMAL); } else if (propertyName === PROPERTY_TITLE_HIGHLIGHTED) { @@ -110,7 +110,7 @@ cc.ControlButtonLoader = cc.ControlLoader.extend({ cc.ControlLoader.prototype.onHandlePropTypeString.call(this, node, parent, propertyName, stringValue, ccbReader); } }, - onHandlePropTypeFontTTF:function (node, parent, propertyName, fontTTF, ccbReader) { + onHandlePropTypeFontTTF: function (node, parent, propertyName, fontTTF, ccbReader) { if (propertyName === PROPERTY_TITLETTF_NORMAL) { node.setTitleTTFForState(fontTTF, cc.CONTROL_STATE_NORMAL); } else if (propertyName === PROPERTY_TITLETTF_HIGHLIGHTED) { @@ -121,7 +121,7 @@ cc.ControlButtonLoader = cc.ControlLoader.extend({ cc.ControlLoader.prototype.onHandlePropTypeFontTTF.call(this, node, parent, propertyName, fontTTF, ccbReader); } }, - onHandlePropTypeFloatScale:function (node, parent, propertyName, floatScale, ccbReader) { + onHandlePropTypeFloatScale: function (node, parent, propertyName, floatScale, ccbReader) { if (propertyName === PROPERTY_TITLETTFSIZE_NORMAL) { node.setTitleTTFSizeForState(floatScale, cc.CONTROL_STATE_NORMAL); } else if (propertyName === PROPERTY_TITLETTFSIZE_HIGHLIGHTED) { @@ -132,21 +132,21 @@ cc.ControlButtonLoader = cc.ControlLoader.extend({ cc.ControlLoader.prototype.onHandlePropTypeFloatScale.call(this, node, parent, propertyName, floatScale, ccbReader); } }, - onHandlePropTypePoint:function (node, parent, propertyName, point, ccbReader) { + onHandlePropTypePoint: function (node, parent, propertyName, point, ccbReader) { if (propertyName === PROPERTY_LABELANCHORPOINT) { node.setLabelAnchorPoint(point); } else { cc.ControlLoader.prototype.onHandlePropTypePoint.call(this, node, parent, propertyName, point, ccbReader); } }, - onHandlePropTypeSize:function (node, parent, propertyName, size, ccbReader) { + onHandlePropTypeSize: function (node, parent, propertyName, size, ccbReader) { if (propertyName === PROPERTY_PREFEREDSIZE) { node.setPreferredSize(size); } else { cc.ControlLoader.prototype.onHandlePropTypeSize.call(this, node, parent, propertyName, size, ccbReader); } }, - onHandlePropTypeSpriteFrame:function (node, parent, propertyName, spriteFrame, ccbReader) { + onHandlePropTypeSpriteFrame: function (node, parent, propertyName, spriteFrame, ccbReader) { if (propertyName === PROPERTY_BACKGROUNDSPRITEFRAME_NORMAL) { if (spriteFrame != null) { node.setBackgroundSpriteFrameForState(spriteFrame, cc.CONTROL_STATE_NORMAL); @@ -163,7 +163,7 @@ cc.ControlButtonLoader = cc.ControlLoader.extend({ cc.ControlLoader.prototype.onHandlePropTypeSpriteFrame.call(this, node, parent, propertyName, spriteFrame, ccbReader); } }, - onHandlePropTypeColor3:function (node, parent, propertyName, ccColor3B, ccbReader) { + onHandlePropTypeColor3: function (node, parent, propertyName, ccColor3B, ccbReader) { if (propertyName === PROPERTY_TITLECOLOR_NORMAL) { node.setTitleColorForState(ccColor3B, cc.CONTROL_STATE_NORMAL); } else if (propertyName === PROPERTY_TITLECOLOR_HIGHLIGHTED) { @@ -187,19 +187,19 @@ var PROPERTY_BOUNCES = "bounces"; var PROPERTY_SCALE = "scale"; cc.ScrollViewLoader = cc.NodeLoader.extend({ - _createCCNode:function (parent, ccbReader) { + _createCCNode: function (parent, ccbReader) { return new cc.ScrollView(); }, - onHandlePropTypeSize:function(node,parent,propertyName,size,ccbReader){ - if(propertyName === PROPERTY_CONTENTSIZE){ + onHandlePropTypeSize: function (node, parent, propertyName, size, ccbReader) { + if (propertyName === PROPERTY_CONTENTSIZE) { node.setViewSize(size); - }else{ - cc.NodeLoader.prototype.onHandlePropTypeSize.call(this, node,parent,propertyName,size,ccbReader); + } else { + cc.NodeLoader.prototype.onHandlePropTypeSize.call(this, node, parent, propertyName, size, ccbReader); } }, - onHandlePropTypeCCBFile:function (node, parent, propertyName, ccbFileNode, ccbReader) { + onHandlePropTypeCCBFile: function (node, parent, propertyName, ccbFileNode, ccbReader) { if (propertyName === PROPERTY_CONTAINER) { node.setContainer(ccbFileNode); node.updateInset(); @@ -207,7 +207,7 @@ cc.ScrollViewLoader = cc.NodeLoader.extend({ cc.NodeLoader.prototype.onHandlePropTypeCCBFile.call(this, node, parent, propertyName, ccbFileNode, ccbReader); } }, - onHandlePropTypeCheck:function (node, parent, propertyName, check, ccbReader) { + onHandlePropTypeCheck: function (node, parent, propertyName, check, ccbReader) { if (propertyName === PROPERTY_CLIPSTOBOUNDS) { node.setClippingToBounds(check); } else if (propertyName === PROPERTY_BOUNCES) { @@ -216,14 +216,14 @@ cc.ScrollViewLoader = cc.NodeLoader.extend({ cc.NodeLoader.prototype.onHandlePropTypeCheck.call(this, node, parent, propertyName, check, ccbReader); } }, - onHandlePropTypeFloat:function (node, parent, propertyName, floatValue, ccbReader) { + onHandlePropTypeFloat: function (node, parent, propertyName, floatValue, ccbReader) { if (propertyName === PROPERTY_SCALE) { node.setScale(floatValue); } else { cc.NodeLoader.prototype.onHandlePropTypeFloat.call(this, node, parent, propertyName, floatValue, ccbReader); } }, - onHandlePropTypeIntegerLabeled:function (node, parent, propertyName, integerLabeled, ccbReader) { + onHandlePropTypeIntegerLabeled: function (node, parent, propertyName, integerLabeled, ccbReader) { if (propertyName === PROPERTY_DIRECTION) { node.setDirection(integerLabeled); } else { @@ -242,12 +242,12 @@ var PROPERTY_COLOR = "color"; var PROPERTY_OPACITY = "opacity"; var PROPERTY_BLENDFUNC = "blendFunc"; var PROPERTY_INSETLEFT = "insetLeft"; -var PROPERTY_INSETTOP = "insetTop" ; +var PROPERTY_INSETTOP = "insetTop"; var PROPERTY_INSETRIGHT = "insetRight"; var PROPERTY_INSETBOTTOM = "insetBottom"; cc.Scale9SpriteLoader = cc.NodeLoader.extend({ - _createCCNode:function(parent,ccbReader){ + _createCCNode: function (parent, ccbReader) { var sprite = new cc.Scale9Sprite(); sprite.setAnchorPoint(0, 0); @@ -255,63 +255,63 @@ cc.Scale9SpriteLoader = cc.NodeLoader.extend({ return sprite; }, - onHandlePropTypeColor3:function(node, parent, propertyName, ccColor3B,ccbReader){ - if(propertyName === PROPERTY_COLOR) { - if(ccColor3B.r !== 255 || ccColor3B.g !== 255 || ccColor3B.b !== 255){ + onHandlePropTypeColor3: function (node, parent, propertyName, ccColor3B, ccbReader) { + if (propertyName === PROPERTY_COLOR) { + if (ccColor3B.r !== 255 || ccColor3B.g !== 255 || ccColor3B.b !== 255) { node.setColor(ccColor3B); } } else { - cc.NodeLoader.prototype.onHandlePropTypeColor3.call(this, node, parent, propertyName, ccColor3B,ccbReader); + cc.NodeLoader.prototype.onHandlePropTypeColor3.call(this, node, parent, propertyName, ccColor3B, ccbReader); } }, - onHandlePropTypeByte:function(node, parent, propertyName, byteValue,ccbReader){ - if(propertyName === PROPERTY_OPACITY) { + onHandlePropTypeByte: function (node, parent, propertyName, byteValue, ccbReader) { + if (propertyName === PROPERTY_OPACITY) { node.setOpacity(byteValue); } else { - cc.NodeLoader.prototype.onHandlePropTypeByte.call(this, node, parent, propertyName, byteValue,ccbReader); + cc.NodeLoader.prototype.onHandlePropTypeByte.call(this, node, parent, propertyName, byteValue, ccbReader); } }, - onHandlePropTypeBlendFunc:function(node, parent, propertyName, ccBlendFunc,ccbReader){ - if(propertyName === PROPERTY_BLENDFUNC) { + onHandlePropTypeBlendFunc: function (node, parent, propertyName, ccBlendFunc, ccbReader) { + if (propertyName === PROPERTY_BLENDFUNC) { // TODO Not exported by CocosBuilder yet! // node.setBlendFunc(ccBlendFunc); } else { - cc.NodeLoader.prototype.onHandlePropTypeBlendFunc.call(this, node, parent, propertyName, ccBlendFunc,ccbReader); + cc.NodeLoader.prototype.onHandlePropTypeBlendFunc.call(this, node, parent, propertyName, ccBlendFunc, ccbReader); } }, - onHandlePropTypeSpriteFrame:function(node, parent, propertyName, spriteFrame,ccbReader){ - if(propertyName === PROPERTY_SPRITEFRAME) { + onHandlePropTypeSpriteFrame: function (node, parent, propertyName, spriteFrame, ccbReader) { + if (propertyName === PROPERTY_SPRITEFRAME) { node.setSpriteFrame(spriteFrame); } else { - cc.NodeLoader.prototype.onHandlePropTypeSpriteFrame.call(this, node, parent, propertyName, spriteFrame,ccbReader); + cc.NodeLoader.prototype.onHandlePropTypeSpriteFrame.call(this, node, parent, propertyName, spriteFrame, ccbReader); } }, - onHandlePropTypeSize:function(node, parent, propertyName, size,ccbReader){ - if(propertyName === PROPERTY_CONTENTSIZE) { + onHandlePropTypeSize: function (node, parent, propertyName, size, ccbReader) { + if (propertyName === PROPERTY_CONTENTSIZE) { //node.setContentSize(size); - } else if(propertyName === PROPERTY_PREFEREDSIZE) { + } else if (propertyName === PROPERTY_PREFEREDSIZE) { node.setPreferredSize(size); } else { - cc.NodeLoader.prototype.onHandlePropTypeSize.call(this, node, parent, propertyName, size,ccbReader); + cc.NodeLoader.prototype.onHandlePropTypeSize.call(this, node, parent, propertyName, size, ccbReader); } }, - onHandlePropTypeFloat:function(node, parent, propertyName, floatValue,ccbReader){ - if(propertyName === PROPERTY_INSETLEFT) { + onHandlePropTypeFloat: function (node, parent, propertyName, floatValue, ccbReader) { + if (propertyName === PROPERTY_INSETLEFT) { node.setInsetLeft(floatValue); - } else if(propertyName === PROPERTY_INSETTOP) { + } else if (propertyName === PROPERTY_INSETTOP) { node.setInsetTop(floatValue); - } else if(propertyName === PROPERTY_INSETRIGHT) { + } else if (propertyName === PROPERTY_INSETRIGHT) { node.setInsetRight(floatValue); - } else if(propertyName === PROPERTY_INSETBOTTOM) { + } else if (propertyName === PROPERTY_INSETBOTTOM) { node.setInsetBottom(floatValue); } else { - cc.NodeLoader.prototype.onHandlePropTypeFloat.call(this, node, parent, propertyName, floatValue,ccbReader); + cc.NodeLoader.prototype.onHandlePropTypeFloat.call(this, node, parent, propertyName, floatValue, ccbReader); } } }); -cc.Scale9SpriteLoader.loader = function(){ - return new cc.Scale9SpriteLoader(); +cc.Scale9SpriteLoader.loader = function () { + return new cc.Scale9SpriteLoader(); }; diff --git a/extensions/ccb-reader/CCNodeLoader.js b/extensions/ccb-reader/CCNodeLoader.js index 67b575f41a..536886e098 100644 --- a/extensions/ccb-reader/CCNodeLoader.js +++ b/extensions/ccb-reader/CCNodeLoader.js @@ -54,9 +54,9 @@ function BlockCCControlData(selCCControlHandler, target, controlEvents) { } cc.NodeLoader = cc.Class.extend({ - _customProperties:null, + _customProperties: null, - ctor:function(){ + ctor: function () { this._customProperties = new cc._Dictionary(); }, @@ -327,15 +327,15 @@ cc.NodeLoader = cc.Class.extend({ } }, - getCustomProperties:function(){ + getCustomProperties: function () { return this._customProperties; }, - _createCCNode:function (parent, ccbReader) { + _createCCNode: function (parent, ccbReader) { return new cc.Node(); }, - parsePropTypePosition:function (node, parent, ccbReader, propertyName) { + parsePropTypePosition: function (node, parent, ccbReader, propertyName) { var x = ccbReader.readFloat(); var y = ccbReader.readFloat(); @@ -650,7 +650,7 @@ cc.NodeLoader = cc.Class.extend({ cc.log("Unexpected NULL target for selector."); } } else { - if(selectorTarget === CCB_TARGETTYPE_DOCUMENTROOT){ + if (selectorTarget === CCB_TARGETTYPE_DOCUMENTROOT) { ccbReader.addDocumentCallbackNode(node); ccbReader.addDocumentCallbackName(selectorName); ccbReader.addDocumentCallbackControlEvents(0); @@ -664,7 +664,7 @@ cc.NodeLoader = cc.Class.extend({ return null; }, - parsePropTypeBlockCCControl:function (node, parent, ccbReader) { + parsePropTypeBlockCCControl: function (node, parent, ccbReader) { var selectorName = ccbReader.readCachedString(); var selectorTarget = ccbReader.readInt(false); var controlEvents = ccbReader.readInt(false); @@ -704,7 +704,7 @@ cc.NodeLoader = cc.Class.extend({ cc.log("Unexpected NULL target for selector."); } } else { - if(selectorTarget === CCB_TARGETTYPE_DOCUMENTROOT){ + if (selectorTarget === CCB_TARGETTYPE_DOCUMENTROOT) { ccbReader.addDocumentCallbackNode(node); ccbReader.addDocumentCallbackName(selectorName); ccbReader.addDocumentCallbackControlEvents(controlEvents); @@ -728,7 +728,7 @@ cc.NodeLoader = cc.Class.extend({ var myCCBReader = new cc.BuilderReader(ccbReader); var bytes = cc.loader.getRes(ccbFileName); - if(!bytes){ + if (!bytes) { var realUrl = cc.loader.getUrl(ccbFileName); bytes = cc.loader.loadBinarySync(realUrl); cc.loader.cache[ccbFileName] = bytes; @@ -754,7 +754,7 @@ cc.NodeLoader = cc.Class.extend({ return [x,y]; }, - onHandlePropTypePosition:function (node, parent, propertyName, position, ccbReader) { + onHandlePropTypePosition: function (node, parent, propertyName, position, ccbReader) { if (propertyName === PROPERTY_POSITION) { node.setPosition(position); } else { @@ -762,7 +762,7 @@ cc.NodeLoader = cc.Class.extend({ } }, - onHandlePropTypePoint:function (node, parent, propertyName, position, ccbReader) { + onHandlePropTypePoint: function (node, parent, propertyName, position, ccbReader) { if (propertyName === PROPERTY_ANCHORPOINT) { node.setAnchorPoint(position); } else { @@ -770,11 +770,11 @@ cc.NodeLoader = cc.Class.extend({ } }, - onHandlePropTypePointLock:function (node, parent, propertyName, pointLock, ccbReader) { + onHandlePropTypePointLock: function (node, parent, propertyName, pointLock, ccbReader) { ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName); }, - onHandlePropTypeSize:function (node, parent, propertyName, sizeValue, ccbReader) { + onHandlePropTypeSize: function (node, parent, propertyName, sizeValue, ccbReader) { if (propertyName === PROPERTY_CONTENTSIZE) { node.setContentSize(sizeValue); } else { @@ -782,7 +782,7 @@ cc.NodeLoader = cc.Class.extend({ } }, - onHandlePropTypeScaleLock:function (node, parent, propertyName, scaleLock, ccbReader) { + onHandlePropTypeScaleLock: function (node, parent, propertyName, scaleLock, ccbReader) { if (propertyName === PROPERTY_SCALE) { node.setScaleX(scaleLock[0]); node.setScaleY(scaleLock[1]); @@ -804,13 +804,13 @@ cc.NodeLoader = cc.Class.extend({ node[nameY](xy[1]); } }, - onHandlePropTypeFloat:function (node, parent, propertyName, floatValue, ccbReader) { + onHandlePropTypeFloat: function (node, parent, propertyName, floatValue, ccbReader) { //ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName); // It may be a custom property, add it to custom property dictionary. this._customProperties.setObject(floatValue, propertyName); }, - onHandlePropTypeDegrees:function (node, parent, propertyName, degrees, ccbReader) { + onHandlePropTypeDegrees: function (node, parent, propertyName, degrees, ccbReader) { if (propertyName === PROPERTY_ROTATION) { node.setRotation(degrees); } else { @@ -818,11 +818,11 @@ cc.NodeLoader = cc.Class.extend({ } }, - onHandlePropTypeFloatScale:function (node, parent, propertyName, floatScale, ccbReader) { + onHandlePropTypeFloatScale: function (node, parent, propertyName, floatScale, ccbReader) { ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName); }, - onHandlePropTypeInteger:function (node, parent, propertyName, integer, ccbReader) { + onHandlePropTypeInteger: function (node, parent, propertyName, integer, ccbReader) { if (propertyName === PROPERTY_TAG) { node.setTag(integer); } else { @@ -830,15 +830,15 @@ cc.NodeLoader = cc.Class.extend({ } }, - onHandlePropTypeIntegerLabeled:function (node, parent, propertyName, integerLabeled, ccbReader) { + onHandlePropTypeIntegerLabeled: function (node, parent, propertyName, integerLabeled, ccbReader) { ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName); }, - onHandlePropTypeFloatVar:function (node, parent, propertyName, floatVar, ccbReader) { + onHandlePropTypeFloatVar: function (node, parent, propertyName, floatVar, ccbReader) { ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName); }, - onHandlePropTypeCheck:function (node, parent, propertyName, check, ccbReader) { + onHandlePropTypeCheck: function (node, parent, propertyName, check, ccbReader) { if (propertyName === PROPERTY_VISIBLE) { node.setVisible(check); } else if (propertyName === PROPERTY_IGNOREANCHORPOINTFORPOSITION) { @@ -848,53 +848,53 @@ cc.NodeLoader = cc.Class.extend({ } }, - onHandlePropTypeSpriteFrame:function (node, parent, propertyName, spriteFrame, ccbReader) { + onHandlePropTypeSpriteFrame: function (node, parent, propertyName, spriteFrame, ccbReader) { ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName); }, - onHandlePropTypeAnimation:function (node, parent, propertyName, ccAnimation, ccbReader) { + onHandlePropTypeAnimation: function (node, parent, propertyName, ccAnimation, ccbReader) { ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName); }, - onHandlePropTypeTexture:function (node, parent, propertyName, ccTexture2D, ccbReader) { + onHandlePropTypeTexture: function (node, parent, propertyName, ccTexture2D, ccbReader) { ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName); }, - onHandlePropTypeByte:function (node, parent, propertyName, byteValue, ccbReader) { + onHandlePropTypeByte: function (node, parent, propertyName, byteValue, ccbReader) { ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName); }, - onHandlePropTypeColor3:function (node, parent, propertyName, ccColor3B, ccbReader) { + onHandlePropTypeColor3: function (node, parent, propertyName, ccColor3B, ccbReader) { ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName); }, - onHandlePropTypeColor4FVar:function (node, parent, propertyName, ccColor4FVar, ccbReader) { + onHandlePropTypeColor4FVar: function (node, parent, propertyName, ccColor4FVar, ccbReader) { ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName); }, - onHandlePropTypeFlip:function (node, parent, propertyName, flip, ccbReader) { + onHandlePropTypeFlip: function (node, parent, propertyName, flip, ccbReader) { ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName); }, - onHandlePropTypeBlendFunc:function (node, parent, propertyName, ccBlendFunc, ccbReader) { + onHandlePropTypeBlendFunc: function (node, parent, propertyName, ccBlendFunc, ccbReader) { ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName); }, - onHandlePropTypeFntFile:function (node, parent, propertyName, fntFile, ccbReader) { + onHandlePropTypeFntFile: function (node, parent, propertyName, fntFile, ccbReader) { ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName); }, - onHandlePropTypeString:function (node, parent, propertyName, strValue, ccbReader) { + onHandlePropTypeString: function (node, parent, propertyName, strValue, ccbReader) { //ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName); // It may be a custom property, add it to custom property dictionary. this._customProperties.setObject(strValue, propertyName); }, - onHandlePropTypeText:function (node, parent, propertyName, textValue, ccbReader) { + onHandlePropTypeText: function (node, parent, propertyName, textValue, ccbReader) { ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName); }, - onHandlePropTypeFontTTF:function (node, parent, propertyName, fontTTF, ccbReader) { + onHandlePropTypeFontTTF: function (node, parent, propertyName, fontTTF, ccbReader) { ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName); }, - onHandlePropTypeBlock:function (node, parent, propertyName, blockData, ccbReader) { + onHandlePropTypeBlock: function (node, parent, propertyName, blockData, ccbReader) { ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName); }, - onHandlePropTypeBlockCCControl:function (node, parent, propertyName, blockCCControlData, ccbReader) { + onHandlePropTypeBlockCCControl: function (node, parent, propertyName, blockCCControlData, ccbReader) { ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName); }, - onHandlePropTypeCCBFile:function (node, parent, propertyName, ccbFileNode, ccbReader) { + onHandlePropTypeCCBFile: function (node, parent, propertyName, ccbFileNode, ccbReader) { ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName); } }); diff --git a/extensions/ccui/base-classes/CCProtectedNode.js b/extensions/ccui/base-classes/CCProtectedNode.js index 8407e7e633..c77c2b5456 100644 --- a/extensions/ccui/base-classes/CCProtectedNode.js +++ b/extensions/ccui/base-classes/CCProtectedNode.js @@ -31,7 +31,7 @@ cc.ProtectedNode = cc.Node.extend(/** @lends cc.ProtectedNode# */{ _protectedChildren: null, _reorderProtectedChildDirty: false, - _insertProtectedChild: function(child, z){ + _insertProtectedChild: function (child, z) { this._reorderProtectedChildDirty = true; this._protectedChildren.push(child); child._setLocalZOrder(z); @@ -41,7 +41,7 @@ cc.ProtectedNode = cc.Node.extend(/** @lends cc.ProtectedNode# */{ * Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function. * @function */ - ctor: function(){ + ctor: function () { cc.Node.prototype.ctor.call(this); this._protectedChildren = []; }, @@ -55,25 +55,25 @@ cc.ProtectedNode = cc.Node.extend(/** @lends cc.ProtectedNode# */{ * @param {Number} [localZOrder] Z order for drawing priority. Please refer to `setLocalZOrder(int)` * @param {Number} [tag] An integer to identify the node easily. Please refer to `setTag(int)` */ - addProtectedChild: function(child, localZOrder, tag){ - cc.assert(child != null, "child must be non-nil"); - cc.assert(!child.parent, "child already added. It can't be added again"); + addProtectedChild: function (child, localZOrder, tag) { + cc.assert(child != null, "child must be non-nil"); + cc.assert(!child.parent, "child already added. It can't be added again"); localZOrder = localZOrder || child.getLocalZOrder(); - if(tag) + if (tag) child.setTag(tag); this._insertProtectedChild(child, localZOrder); child.setParent(this); child.setOrderOfArrival(cc.s_globalOrderOfArrival); - if(this._running){ + if (this._running) { child.onEnter(); // prevent onEnterTransitionDidFinish to be called twice when a node is added in onEnter - if(this._isTransitionFinished) + if (this._isTransitionFinished) child.onEnterTransitionDidFinish(); } - if(this._cascadeColorEnabled) + if (this._cascadeColorEnabled) this._renderCmd.setCascadeColorEnabledDirty(); if (this._cascadeOpacityEnabled) this._renderCmd.setCascadeOpacityEnabledDirty(); @@ -84,11 +84,11 @@ cc.ProtectedNode = cc.Node.extend(/** @lends cc.ProtectedNode# */{ * @param {Number} tag An identifier to find the child node. * @return {cc.Node} a Node object whose tag equals to the input parameter */ - getProtectedChildByTag: function(tag){ + getProtectedChildByTag: function (tag) { cc.assert(tag !== cc.NODE_TAG_INVALID, "Invalid tag"); var locChildren = this._protectedChildren; - for(var i = 0, len = locChildren.length; i < len; i++) - if(locChildren.getTag() === tag) + for (var i = 0, len = locChildren.length; i < len; i++) + if (locChildren.getTag() === tag) return locChildren[i]; return null; }, @@ -98,18 +98,18 @@ cc.ProtectedNode = cc.Node.extend(/** @lends cc.ProtectedNode# */{ * @param {cc.Node} child The child node which will be removed. * @param {Boolean} [cleanup=true] true if all running actions and callbacks on the child node will be cleanup, false otherwise. */ - removeProtectedChild: function(child, cleanup){ - if(cleanup == null) + removeProtectedChild: function (child, cleanup) { + if (cleanup == null) cleanup = true; - var locChildren = this._protectedChildren; - if(locChildren.length === 0) + var locChildren = this._protectedChildren; + if (locChildren.length === 0) return; var idx = locChildren.indexOf(child); - if(idx > -1){ - if(this._running){ - child.onExitTransitionDidStart(); - child.onExit(); - } + if (idx > -1) { + if (this._running) { + child.onExitTransitionDidStart(); + child.onExit(); + } // If you don't do cleanup, the child's actions will not get removed and the // its scheduledSelectors_ dict will not get released! @@ -128,10 +128,10 @@ cc.ProtectedNode = cc.Node.extend(/** @lends cc.ProtectedNode# */{ * @param {Number} tag * @param {Boolean} [cleanup=true] */ - removeProtectedChildByTag: function(tag, cleanup){ - cc.assert( tag !== cc.NODE_TAG_INVALID, "Invalid tag"); + removeProtectedChildByTag: function (tag, cleanup) { + cc.assert(tag !== cc.NODE_TAG_INVALID, "Invalid tag"); - if(cleanup == null) + if (cleanup == null) cleanup = true; var child = this.getProtectedChildByTag(tag); @@ -146,7 +146,7 @@ cc.ProtectedNode = cc.Node.extend(/** @lends cc.ProtectedNode# */{ * Removes all children from the container with a cleanup. * @see cc.ProtectedNode#removeAllProtectedChildrenWithCleanup */ - removeAllProtectedChildren: function(){ + removeAllProtectedChildren: function () { this.removeAllProtectedChildrenWithCleanup(true); }, @@ -154,17 +154,17 @@ cc.ProtectedNode = cc.Node.extend(/** @lends cc.ProtectedNode# */{ * Removes all children from the container, and do a cleanup to all running actions depending on the cleanup parameter. * @param {Boolean} [cleanup=true] true if all running actions on all children nodes should be cleanup, false otherwise. */ - removeAllProtectedChildrenWithCleanup: function(cleanup){ - if(cleanup == null) + removeAllProtectedChildrenWithCleanup: function (cleanup) { + if (cleanup == null) cleanup = true; var locChildren = this._protectedChildren; // not using detachChild improves speed here - for (var i = 0, len = locChildren.length; i< len; i++) { + for (var i = 0, len = locChildren.length; i < len; i++) { var child = locChildren[i]; // IMPORTANT: // -1st do onExit // -2nd cleanup - if(this._running){ + if (this._running) { child.onExitTransitionDidStart(); child.onExit(); } @@ -182,8 +182,8 @@ cc.ProtectedNode = cc.Node.extend(/** @lends cc.ProtectedNode# */{ * @param {cc.Node} child An already added child node. It MUST be already added. * @param {Number} localZOrder Z order for drawing priority. Please refer to setLocalZOrder(int) */ - reorderProtectedChild: function(child, localZOrder){ - cc.assert( child != null, "Child must be non-nil"); + reorderProtectedChild: function (child, localZOrder) { + cc.assert(child != null, "Child must be non-nil"); this._reorderProtectedChildDirty = true; child.setOrderOfArrival(cc.s_globalOrderOfArrival++); child._setLocalZOrder(localZOrder); @@ -196,27 +196,27 @@ cc.ProtectedNode = cc.Node.extend(/** @lends cc.ProtectedNode# */{ * @note Don't call this manually unless a child added needs to be removed in the same frame *

*/ - sortAllProtectedChildren: function(){ + sortAllProtectedChildren: function () { if (this._reorderProtectedChildDirty) { var _children = this._protectedChildren; // 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 + while (j >= 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; + _children[j + 1] = tmp; } //don't need to check children recursively, that's done in visit of each child @@ -224,7 +224,7 @@ cc.ProtectedNode = cc.Node.extend(/** @lends cc.ProtectedNode# */{ } }, - _changePosition: function(){}, + _changePosition: function () {}, /** * Stops itself and its children and protected children's all running actions and schedulers @@ -287,8 +287,8 @@ cc.ProtectedNode = cc.Node.extend(/** @lends cc.ProtectedNode# */{ locChildren[i].onExitTransitionDidStart(); }, - _createRenderCmd: function(){ - if(cc._renderType === cc.game.RENDER_TYPE_CANVAS) + _createRenderCmd: function () { + if (cc._renderType === cc.game.RENDER_TYPE_CANVAS) return new cc.ProtectedNode.CanvasRenderCmd(this); else return new cc.ProtectedNode.WebGLRenderCmd(this); @@ -300,6 +300,6 @@ cc.ProtectedNode = cc.Node.extend(/** @lends cc.ProtectedNode# */{ * @deprecated since v3.0, please use new cc.ProtectedNode() instead. * @return cc.ProtectedNode */ -cc.ProtectedNode.create = function(){ +cc.ProtectedNode.create = function () { return new cc.ProtectedNode(); -}; \ No newline at end of file +}; diff --git a/extensions/ccui/base-classes/CCProtectedNodeCanvasRenderCmd.js b/extensions/ccui/base-classes/CCProtectedNodeCanvasRenderCmd.js index 1e36802e0d..7e9cae0b4b 100644 --- a/extensions/ccui/base-classes/CCProtectedNodeCanvasRenderCmd.js +++ b/extensions/ccui/base-classes/CCProtectedNodeCanvasRenderCmd.js @@ -22,7 +22,7 @@ THE SOFTWARE. ****************************************************************************/ -(function(){ +(function () { cc.ProtectedNode.RenderCmd = { _updateDisplayColor: function (parentColor) { var node = this._node; @@ -55,16 +55,16 @@ selChildren = node._children; for (i = 0, len = selChildren.length; i < len; i++) { item = selChildren[i]; - if (item && item._renderCmd){ + if (item && item._renderCmd) { item._renderCmd._updateDisplayColor(locDispColor); item._renderCmd._updateColor(); } } } selChildren = node._protectedChildren; - for(i = 0, len = selChildren.length;i < len; i++){ + for (i = 0, len = selChildren.length; i < len; i++) { item = selChildren[i]; - if(item && item._renderCmd){ + if (item && item._renderCmd) { item._renderCmd._updateDisplayColor(locDispColor); item._renderCmd._updateColor(); } @@ -97,16 +97,16 @@ selChildren = node._children; for (i = 0, len = selChildren.length; i < len; i++) { item = selChildren[i]; - if (item && item._renderCmd){ + if (item && item._renderCmd) { item._renderCmd._updateDisplayOpacity(this._displayedOpacity); item._renderCmd._updateColor(); } } } selChildren = node._protectedChildren; - for(i = 0, len = selChildren.length;i < len; i++){ + for (i = 0, len = selChildren.length; i < len; i++) { item = selChildren[i]; - if(item && item._renderCmd){ + if (item && item._renderCmd) { item._renderCmd._updateDisplayOpacity(this._displayedOpacity); item._renderCmd._updateColor(); } @@ -199,17 +199,17 @@ this._cacheDirty = false; }; - proto.transform = function(parentCmd, recursive){ + proto.transform = function (parentCmd, recursive) { var node = this._node; - if(node._changePosition) + if (node._changePosition) node._changePosition(); this.originTransform(parentCmd, recursive); var i, len, locChildren = node._protectedChildren; - if(recursive && locChildren && locChildren.length !== 0){ - for(i = 0, len = locChildren.length; i< len; i++){ + if (recursive && locChildren && locChildren.length !== 0) { + for (i = 0, len = locChildren.length; i < len; i++) { locChildren[i]._renderCmd.transform(this, recursive); } } @@ -217,4 +217,4 @@ proto.pNodeVisit = proto.visit; proto.pNodeTransform = proto.transform; -})(); \ No newline at end of file +})(); diff --git a/extensions/ccui/base-classes/CCProtectedNodeWebGLRenderCmd.js b/extensions/ccui/base-classes/CCProtectedNodeWebGLRenderCmd.js index 6640c7cf9b..0dd4843c7f 100644 --- a/extensions/ccui/base-classes/CCProtectedNodeWebGLRenderCmd.js +++ b/extensions/ccui/base-classes/CCProtectedNodeWebGLRenderCmd.js @@ -22,8 +22,8 @@ THE SOFTWARE. ****************************************************************************/ -(function(){ - if(!cc.Node.WebGLRenderCmd) +(function () { + if (!cc.Node.WebGLRenderCmd) return; cc.ProtectedNode.WebGLRenderCmd = function (renderable) { cc.Node.WebGLRenderCmd.call(this, renderable); @@ -87,13 +87,13 @@ this._dirtyFlag = 0; }; - proto.transform = function(parentCmd, recursive){ + proto.transform = function (parentCmd, recursive) { this.originTransform(parentCmd, recursive); var i, len, locChildren = this._node._protectedChildren; - if(recursive && locChildren && locChildren.length !== 0){ - for(i = 0, len = locChildren.length; i< len; i++){ + if (recursive && locChildren && locChildren.length !== 0) { + for (i = 0, len = locChildren.length; i < len; i++) { locChildren[i]._renderCmd.transform(this, recursive); } } @@ -101,4 +101,4 @@ proto.pNodeVisit = proto.visit; proto.pNodeTransform = proto.transform; -})(); \ No newline at end of file +})(); diff --git a/extensions/ccui/base-classes/UIWidget.js b/extensions/ccui/base-classes/UIWidget.js index 9b8a2310f9..92d9b360b4 100644 --- a/extensions/ccui/base-classes/UIWidget.js +++ b/extensions/ccui/base-classes/UIWidget.js @@ -29,7 +29,7 @@ ccui._FocusNavigationController = cc.Class.extend({ _enableFocusNavigation: false, _keyboardEventPriority: 1, - enableFocusNavigation: function(flag){ + enableFocusNavigation: function (flag) { if (this._enableFocusNavigation === flag) return; @@ -40,16 +40,16 @@ ccui._FocusNavigationController = cc.Class.extend({ this._removeKeyboardEventListener(); }, - _setFirstFocsuedWidget: function(widget){ + _setFirstFocsuedWidget: function (widget) { this._firstFocusedWidget = widget; }, - _onKeyPressed: function(keyCode, event){ + _onKeyPressed: function (keyCode, event) { if (this._enableFocusNavigation && this._firstFocusedWidget) { if (keyCode === cc.KEY.dpadDown) { this._firstFocusedWidget = this._firstFocusedWidget.findNextFocusedWidget(ccui.Widget.DOWN, this._firstFocusedWidget); } - if (keyCode === cc.KEY.dpadUp){ + if (keyCode === cc.KEY.dpadUp) { this._firstFocusedWidget = this._firstFocusedWidget.findNextFocusedWidget(ccui.Widget.UP, this._firstFocusedWidget); } if (keyCode === cc.KEY.dpadLeft) { @@ -61,7 +61,7 @@ ccui._FocusNavigationController = cc.Class.extend({ } }, - _addKeyboardEventListener: function(){ + _addKeyboardEventListener: function () { if (!this._keyboardListener) { this._keyboardListener = cc.EventListener.create({ event: cc.EventListener.KEYBOARD, @@ -71,7 +71,7 @@ ccui._FocusNavigationController = cc.Class.extend({ } }, - _removeKeyboardEventListener: function(){ + _removeKeyboardEventListener: function () { if (this._keyboardListener) { cc.eventManager.removeEventListener(this._keyboardListener); this._keyboardListener = null; @@ -123,7 +123,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ _actionTag: 0, _customSize: null, _layoutParameterDictionary: null, - _layoutParameterType:0, + _layoutParameterType: 0, _focused: false, _focusEnabled: true, @@ -182,19 +182,16 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ * @returns {boolean} */ init: function () { - if (cc.ProtectedNode.prototype.init.call(this)) { - this._layoutParameterDictionary = {}; - this._initRenderer(); - this.setBright(true); + this._layoutParameterDictionary = {}; + this._initRenderer(); + this.setBright(true); - this.onFocusChanged = this.onFocusChange; - this.onNextFocusedWidget = null; - this.setAnchorPoint(cc.p(0.5, 0.5)); + this.onFocusChanged = this.onFocusChange; + this.onNextFocusedWidget = null; + this.setAnchorPoint(cc.p(0.5, 0.5)); - this.ignoreContentAdaptWithSize(true); - return true; - } - return false; + this.ignoreContentAdaptWithSize(true); + return true; }, /** @@ -214,7 +211,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ * Calls unscheduleUpdate and its parent's onExit * @override */ - onExit: function(){ + onExit: function () { this.unscheduleUpdate(); cc.ProtectedNode.prototype.onExit.call(this); }, @@ -239,7 +236,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ return null; }, - _updateContentSizeWithTextureSize: function(size){ + _updateContentSizeWithTextureSize: function (size) { if(this._unifySize){ this.setContentSize(size); return; @@ -247,7 +244,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ this.setContentSize(this._ignoreSize ? size : this._customSize); }, - _isAncestorsEnabled: function(){ + _isAncestorsEnabled: function () { var parentWidget = this._getAncensterWidget(this); if (parentWidget == null) return true; @@ -262,7 +259,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ * @since v3.2 * @param {Boolean} isPropagate */ - setPropagateTouchEvents: function(isPropagate){ + setPropagateTouchEvents: function (isPropagate) { this._propagateTouchEvents = isPropagate; }, @@ -271,7 +268,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ * @since v3.2 * @returns {boolean} */ - isPropagateTouchEvents: function(){ + isPropagateTouchEvents: function () { return this._propagateTouchEvents; }, @@ -280,7 +277,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ * @since v3.2 * @param {Boolean} swallow */ - setSwallowTouches: function(swallow){ + setSwallowTouches: function (swallow) { if (this._touchListener) this._touchListener.setSwallowTouches(swallow); }, @@ -290,15 +287,15 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ * @since v3.2 * @returns {boolean} */ - isSwallowTouches: function(){ - if (this._touchListener){ + isSwallowTouches: function () { + if (this._touchListener) { //return true; //todo need test return this._touchListener.isSwallowTouches(); } return false; }, - _getAncensterWidget: function(node){ + _getAncensterWidget: function (node) { if (null == node) return null; @@ -312,7 +309,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ return this._getAncensterWidget(parent.getParent()); }, - _isAncestorsVisible: function(node){ + _isAncestorsVisible: function (node) { if (null == node) return true; @@ -339,7 +336,8 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ /** * initializes renderer of widget. */ - _initRenderer: function () {}, + _initRenderer: function () { + }, /** * Sets _customSize of ccui.Widget, if ignoreSize is true, the content size is its renderer's contentSize, otherwise the content size is parameter. @@ -357,7 +355,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ this._customSize.height = locHeight; if(this._unifySize){ //unify size logic - } else if (this._ignoreSize){ + } else if (this._ignoreSize) { this._contentSize = this.getVirtualRendererSize(); } if (!this._usingLayoutComponent && this._running) { @@ -374,7 +372,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ this._customSize.width = w; if(this._unifySize){ //unify size logic - } else if (this._ignoreSize){ + } else if (this._ignoreSize) { this._contentSize = this.getVirtualRendererSize(); } @@ -390,7 +388,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ this._customSize.height = h; if(this._unifySize){ //unify size logic - } else if (this._ignoreSize){ + } else if (this._ignoreSize) { this._contentSize = this.getVirtualRendererSize(); } @@ -469,9 +467,9 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ * @param {cc.Size} [parentSize] parent size */ updateSizeAndPosition: function (parentSize) { - if(!parentSize){ + if (!parentSize) { var widgetParent = this.getWidgetParent(); - if(widgetParent) + if (widgetParent) parentSize = widgetParent.getLayoutSize(); else parentSize = this._parent.getContentSize(); @@ -479,7 +477,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ switch (this._sizeType) { case ccui.Widget.SIZE_ABSOLUTE: - if(this._ignoreSize) + if (this._ignoreSize) this.setContentSize(this.getVirtualRendererSize()); else this.setContentSize(this._customSize); @@ -487,8 +485,8 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ this._sizePercent.y = (parentSize.height > 0) ? this._customSize.height / parentSize.height : 0; break; case ccui.Widget.SIZE_PERCENT: - var cSize = cc.size(parentSize.width * this._sizePercent.x , parentSize.height * this._sizePercent.y); - if(this._ignoreSize) + var cSize = cc.size(parentSize.width * this._sizePercent.x, parentSize.height * this._sizePercent.y); + if (this._ignoreSize) this.setContentSize(this.getVirtualRendererSize()); else this.setContentSize(cSize); @@ -515,9 +513,9 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ default: break; } - if(this._parent instanceof ccui.ImageView){ + if (this._parent instanceof ccui.ImageView) { var renderer = this._parent._imageRenderer; - if(renderer && !renderer._textureLoaded) + if (renderer && !renderer._textureLoaded) return; } this.setPosition(absPos); @@ -553,11 +551,11 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ return; } - if(this._ignoreSize === ignore) + if (this._ignoreSize === ignore) return; this._ignoreSize = ignore; - this.setContentSize( ignore ? this.getVirtualRendererSize() : this._customSize ); + this.setContentSize(ignore ? this.getVirtualRendererSize() : this._customSize); //this._onSizeChanged(); }, @@ -581,7 +579,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ * Gets layout size of ccui.Widget. * @returns {cc.Size} */ - getLayoutSize: function(){ + getLayoutSize: function () { return cc.size(this._contentSize); }, @@ -622,7 +620,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ /** * Gets the content size of widget. Content size is widget's texture size. */ - getVirtualRendererSize:function(){ + getVirtualRendererSize: function () { return cc.size(this._contentSize); }, @@ -650,7 +648,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ this._touchEnabled = enable; //TODO need consider remove and re-add. if (this._touchEnabled) { - if(!this._touchListener) + if (!this._touchListener) this._touchListener = cc.EventListener.create({ event: cc.EventListener.TOUCH_ONE_BY_ONE, swallowTouches: true, @@ -676,7 +674,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ * Determines if the widget is highlighted * @returns {boolean} true if the widget is highlighted, false if the widget is not highlighted . */ - isHighlighted: function(){ + isHighlighted: function () { return this._highlight; }, @@ -684,7 +682,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ * Sets whether the widget is highlighted. The default value is false, a widget is default to not highlighted * @param highlight true if the widget is highlighted, false if the widget is not highlighted. */ - setHighlighted:function(highlight){ + setHighlighted: function (highlight) { if (highlight === this._highlight) return; this._highlight = highlight; @@ -713,9 +711,9 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ setFocused: function (focus) { this._focused = focus; //make sure there is only one focusedWidget - if (focus){ + if (focus) { ccui.Widget._focusedWidget = this; - if(ccui.Widget._focusNavigationController) + if (ccui.Widget._focusNavigationController) ccui.Widget._focusNavigationController._setFirstFocsuedWidget(this); } }, @@ -724,7 +722,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ * returns whether the widget could accept focus. * @returns {boolean} true represent the widget could accept focus, false represent the widget couldn't accept focus */ - isFocusEnabled: function(){ + isFocusEnabled: function () { return this._focusEnabled; }, @@ -732,7 +730,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ * sets whether the widget could accept focus. * @param {Boolean} enable true represent the widget could accept focus, false represent the widget couldn't accept focus */ - setFocusEnabled: function(enable){ + setFocusEnabled: function (enable) { this._focusEnabled = enable; }, @@ -745,12 +743,12 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ * @param current the current focused widget * @return the next focused widget in a layout */ - findNextFocusedWidget: function( direction, current){ - if (null === this.onNextFocusedWidget || null == this.onNextFocusedWidget(direction) ) { + findNextFocusedWidget: function (direction, current) { + if (null === this.onNextFocusedWidget || null == this.onNextFocusedWidget(direction)) { var isLayout = current instanceof ccui.Layout; if (this.isFocused() || isLayout) { var layout = this.getParent(); - if (null === layout || !(layout instanceof ccui.Layout)){ + if (null === layout || !(layout instanceof ccui.Layout)) { //the outer layout's default behaviour is : loop focus if (isLayout) return current.findNextFocusedWidget(direction, current); @@ -769,7 +767,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ /** * when a widget calls this method, it will get focus immediately. */ - requestFocus: function(){ + requestFocus: function () { if (this === ccui.Widget._focusedWidget) return; this.dispatchFocusEvent(ccui.Widget._focusedWidget, this); @@ -778,7 +776,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ /** * no matter what widget object you call this method on , it will return you the exact one focused widget */ - getCurrentFocusedWidget: function(){ + getCurrentFocusedWidget: function () { return ccui.Widget._focusedWidget; }, @@ -801,10 +799,10 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ * @param {ccui.Widget} sender * @param {cc.Touch} touch */ - interceptTouchEvent: function(eventType, sender, touch){ + interceptTouchEvent: function (eventType, sender, touch) { var widgetParent = this.getWidgetParent(); if (widgetParent) - widgetParent.interceptTouchEvent(eventType,sender,touch); + widgetParent.interceptTouchEvent(eventType, sender, touch); }, /** @@ -812,7 +810,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ * @param {ccui.Widget} widgetLostFocus * @param {ccui.Widget} widgetGetFocus */ - onFocusChange: function(widgetLostFocus, widgetGetFocus){ + onFocusChange: function (widgetLostFocus, widgetGetFocus) { //only change focus when there is indeed a get&lose happens if (widgetLostFocus) widgetLostFocus.setFocused(false); @@ -825,12 +823,12 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ * @param {ccui.Widget} widgetLostFocus * @param {ccui.Widget} widgetGetFocus */ - dispatchFocusEvent: function(widgetLostFocus, widgetGetFocus){ + dispatchFocusEvent: function (widgetLostFocus, widgetGetFocus) { //if the widgetLoseFocus doesn't get focus, it will use the previous focused widget instead if (widgetLostFocus && !widgetLostFocus.isFocused()) widgetLostFocus = ccui.Widget._focusedWidget; - if (widgetGetFocus !== widgetLostFocus){ + if (widgetGetFocus !== widgetLostFocus) { if (widgetGetFocus && widgetGetFocus.onFocusChanged) widgetGetFocus.onFocusChanged(widgetLostFocus, widgetGetFocus); if (widgetLostFocus && widgetGetFocus.onFocusChanged) @@ -874,13 +872,16 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ } }, - _onPressStateChangedToNormal: function () {}, + _onPressStateChangedToNormal: function () { + }, - _onPressStateChangedToPressed: function () {}, + _onPressStateChangedToPressed: function () { + }, - _onPressStateChangedToDisabled: function () {}, + _onPressStateChangedToDisabled: function () { + }, - _updateChildrenDisplayedRGBA: function(){ + _updateChildrenDisplayedRGBA: function () { this.setColor(this.getColor()); this.setOpacity(this.getOpacity()); }, @@ -888,7 +889,8 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ /** * A call back function when widget lost of focus. */ - didNotSelectSelf: function () {}, + didNotSelectSelf: function () { + }, /** *

@@ -907,11 +909,11 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ */ onTouchBegan: function (touch, event) { this._hit = false; - if (this.isVisible() && this.isEnabled() && this._isAncestorsEnabled() && this._isAncestorsVisible(this) ){ + if (this.isVisible() && this.isEnabled() && this._isAncestorsEnabled() && this._isAncestorsVisible(this)) { var touchPoint = touch.getLocation(); this._touchBeganPosition.x = touchPoint.x; this._touchBeganPosition.y = touchPoint.y; - if(this.hitTest(this._touchBeganPosition) && this.isClippingParentContainsPoint(this._touchBeganPosition)) + if (this.hitTest(this._touchBeganPosition) && this.isClippingParentContainsPoint(this._touchBeganPosition)) this._hit = true; } if (!this._hit) { @@ -930,9 +932,9 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ return true; }, - propagateTouchEvent: function(event, sender, touch){ + propagateTouchEvent: function (event, sender, touch) { var widgetParent = this.getWidgetParent(); - if (widgetParent){ + if (widgetParent) { widgetParent.interceptTouchEvent(event, sender, touch); } }, @@ -1044,7 +1046,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ * @param {Object} target */ addTouchEventListener: function (selector, target) { - if(target === undefined) + if (target === undefined) this._touchEventCallback = selector; else { this._touchEventSelector = selector; @@ -1052,7 +1054,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ } }, - addClickEventListener: function(callback){ + addClickEventListener: function (callback) { this._clickEventListener = callback; }, @@ -1062,7 +1064,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ * @returns {boolean} true if the point is in widget's space, false otherwise. */ hitTest: function (pt) { - var bb = cc.rect(0,0, this._contentSize.width, this._contentSize.height); + var bb = cc.rect(0, 0, this._contentSize.width, this._contentSize.height); return cc.rectContainsPoint(bb, this.convertToNodeSpace(pt)); }, @@ -1071,7 +1073,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ * @param {cc.Point} pt location point * @returns {Boolean} */ - isClippingParentContainsPoint: function(pt){ + isClippingParentContainsPoint: function (pt) { this._affectByClipping = false; var parent = this.getParent(); var clippingParent = null; @@ -1310,7 +1312,8 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ return this._flippedY; }, - _adaptRenderers: function(){}, + _adaptRenderers: function () { + }, /** * Determines if the widget is bright @@ -1364,15 +1367,15 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ * Gets the position of touch began event. * @returns {cc.Point} */ - getTouchBeganPosition: function(){ - return cc.p(this._touchBeganPosition); + getTouchBeganPosition: function () { + return cc.p(this._touchBeganPosition); }, /** * Gets the position of touch moved event * @returns {cc.Point} */ - getTouchMovePosition: function(){ + getTouchMovePosition: function () { return cc.p(this._touchMovePosition); }, @@ -1380,7 +1383,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ * Gets the position of touch end event * @returns {cc.Point} */ - getTouchEndPosition:function(){ + getTouchEndPosition: function () { return cc.p(this._touchEndPosition); }, @@ -1397,7 +1400,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ * @param {ccui.LayoutParameter} parameter */ setLayoutParameter: function (parameter) { - if(!parameter) + if (!parameter) return; this._layoutParameterDictionary[parameter.getLayoutType()] = parameter; this._layoutParameterType = parameter.getLayoutType(); @@ -1445,7 +1448,8 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ } }, - _copySpecialProperties: function (model) {}, + _copySpecialProperties: function (model) { + }, _copyProperties: function (widget) { this.setEnabled(widget.isEnabled()); @@ -1514,7 +1518,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ * @deprecated since v3.0, please use getLeftBoundary instead. * @returns {number} */ - getLeftInParent: function(){ + getLeftInParent: function () { cc.log("getLeftInParent is deprecated. Please use getLeftBoundary instead."); return this.getLeftBoundary(); }, @@ -1524,7 +1528,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ * @deprecated since v3.0, please use getBottomBoundary instead. * @returns {number} */ - getBottomInParent: function(){ + getBottomInParent: function () { cc.log("getBottomInParent is deprecated. Please use getBottomBoundary instead."); return this.getBottomBoundary(); }, @@ -1534,7 +1538,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ * @deprecated since v3.0, please use getRightBoundary instead. * @returns {number} */ - getRightInParent: function(){ + getRightInParent: function () { cc.log("getRightInParent is deprecated. Please use getRightBoundary instead."); return this.getRightBoundary(); }, @@ -1544,7 +1548,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ * @deprecated since v3.0, please use getTopBoundary instead. * @returns {number} */ - getTopInParent: function(){ + getTopInParent: function () { cc.log("getTopInParent is deprecated. Please use getTopBoundary instead."); return this.getTopBoundary(); }, @@ -1687,14 +1691,14 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ this._nodes.length = 0; }, - _findLayout: function(){ + _findLayout: function () { cc.renderer.childrenOrderDirty = true; var layout = this._parent; - while(layout){ - if(layout._doLayout){ + while (layout) { + if (layout._doLayout) { layout._doLayoutDirty = true; break; - }else + } else layout = layout._parent; } }, @@ -1722,42 +1726,42 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ * @since v3.3 * @param {function} callback */ - addCCSEventListener: function(callback){ + addCCSEventListener: function (callback) { this._ccEventCallback = callback; }, //override the scale functions. - setScaleX: function(scaleX){ + setScaleX: function (scaleX) { if (this._flippedX) scaleX = scaleX * -1; cc.Node.prototype.setScaleX.call(this, scaleX); }, - setScaleY: function(scaleY){ + setScaleY: function (scaleY) { if (this._flippedY) scaleY = scaleY * -1; cc.Node.prototype.setScaleY.call(this, scaleY); }, - setScale: function(scaleX, scaleY){ - if(scaleY === undefined) + setScale: function (scaleX, scaleY) { + if (scaleY === undefined) scaleY = scaleX; this.setScaleX(scaleX); this.setScaleY(scaleY); }, - getScaleX: function(){ + getScaleX: function () { var originalScale = cc.Node.prototype.getScaleX.call(this); if (this._flippedX) originalScale = originalScale * -1.0; return originalScale; }, - getScaleY: function(){ + getScaleY: function () { var originalScale = cc.Node.prototype.getScaleY.call(this); if (this._flippedY) originalScale = originalScale * -1.0; return originalScale; }, - getScale: function(){ - if(this.getScaleX() !== this.getScaleY()) + getScale: function () { + if (this.getScaleX() !== this.getScaleY()) cc.log("Widget#scale. ScaleX != ScaleY. Don't know which one to return"); return this.getScaleX(); }, @@ -1767,7 +1771,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ * @since v3.3 * @param {String} callbackName */ - setCallbackName: function(callbackName){ + setCallbackName: function (callbackName) { this._callbackName = callbackName; }, @@ -1776,7 +1780,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ * @since v3.3 * @returns {String|Null} */ - getCallbackName: function(){ + getCallbackName: function () { return this._callbackName; }, @@ -1785,7 +1789,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ * @since v3.3 * @param {String} callbackType */ - setCallbackType: function(callbackType){ + setCallbackType: function (callbackType) { this._callbackType = callbackType; }, @@ -1794,7 +1798,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ * @since v3.3 * @returns {String|null} */ - getCallbackType: function(){ + getCallbackType: function () { return this._callbackType; }, @@ -1816,8 +1820,8 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ }, - _createRenderCmd: function(){ - if(cc._renderType === cc.game.RENDER_TYPE_WEBGL) + _createRenderCmd: function () { + if (cc._renderType === cc.game.RENDER_TYPE_WEBGL) return new ccui.Widget.WebGLRenderCmd(this); else return new ccui.Widget.CanvasRenderCmd(this); @@ -1892,8 +1896,8 @@ ccui.Widget._focusNavigationController = null; * @note it doesn't implemented on Web * @param {Boolean} enable set true to enable dpad focus navigation, otherwise disable dpad focus navigation */ -ccui.Widget.enableDpadNavigation = function(enable){ - if (enable){ +ccui.Widget.enableDpadNavigation = function (enable) { + if (enable) { if (null == ccui.Widget._focusNavigationController) { ccui.Widget._focusNavigationController = new ccui._FocusNavigationController(); if (ccui.Widget._focusedWidget) { @@ -1902,7 +1906,7 @@ ccui.Widget.enableDpadNavigation = function(enable){ } ccui.Widget._focusNavigationController.enableFocusNavigation(true); } else { - if(ccui.Widget._focusNavigationController){ + if (ccui.Widget._focusNavigationController) { ccui.Widget._focusNavigationController.enableFocusNavigation(false); ccui.Widget._focusNavigationController = null; } @@ -1914,7 +1918,7 @@ ccui.Widget.enableDpadNavigation = function(enable){ * @function * @returns {null|ccui.Widget} */ -ccui.Widget.getCurrentFocusedWidget = function(){ +ccui.Widget.getCurrentFocusedWidget = function () { return ccui.Widget._focusedWidget; }; diff --git a/extensions/ccui/layouts/UILayout.js b/extensions/ccui/layouts/UILayout.js index ff4d82bf5c..48788ac2d5 100644 --- a/extensions/ccui/layouts/UILayout.js +++ b/extensions/ccui/layouts/UILayout.js @@ -63,11 +63,11 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{ _finalPositionX: 0, _finalPositionY: 0, - _backGroundImageOpacity:0, + _backGroundImageOpacity: 0, _loopFocus: false, //whether enable loop focus or not __passFocusToChild: true, //on default, it will pass the focus to the next nearest widget - _isFocusPassing:false, //when finding the next focused widget, use this variable to pass focus between layout & widget + _isFocusPassing: false, //when finding the next focused widget, use this variable to pass focus between layout & widget _isInterceptTouch: false, /** @@ -89,7 +89,7 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{ this.ignoreContentAdaptWithSize(false); this.setContentSize(cc.size(0, 0)); this.setAnchorPoint(0, 0); - this.onPassFocusToChild = this._findNearestChildWidgetIndex.bind(this); + this.onPassFocusToChild = this._findNearestChildWidgetIndex.bind(this); this._backGroundImageCapInsets = cc.rect(0, 0, 0, 0); @@ -107,7 +107,7 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{ * Calls its parent's onEnter, and calls its clippingStencil's onEnter if clippingStencil isn't null. * @override */ - onEnter: function(){ + onEnter: function () { ccui.Widget.prototype.onEnter.call(this); if (this._clippingStencil) this._clippingStencil.onEnter(); @@ -119,7 +119,7 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{ * Calls its parent's onExit, and calls its clippingStencil's onExit if clippingStencil isn't null. * @override */ - onExit: function(){ + onExit: function () { ccui.Widget.prototype.onExit.call(this); if (this._clippingStencil) this._clippingStencil.onExit(); @@ -129,7 +129,7 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{ * If a layout is loop focused which means that the focus movement will be inside the layout * @param {Boolean} loop pass true to let the focus movement loop inside the layout */ - setLoopFocus: function(loop){ + setLoopFocus: function (loop) { this._loopFocus = loop; }, @@ -137,7 +137,7 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{ * Gets whether enable focus loop * @returns {boolean} If focus loop is enabled, then it will return true, otherwise it returns false. The default value is false. */ - isLoopFocus: function(){ + isLoopFocus: function () { return this._loopFocus; }, @@ -145,7 +145,7 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{ * Specifies whether the layout pass its focus to its child * @param pass To specify whether the layout pass its focus to its child */ - setPassFocusToChild: function(pass){ + setPassFocusToChild: function (pass) { this.__passFocusToChild = pass; }, @@ -153,7 +153,7 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{ * Returns whether the layout will pass the focus to its children or not. The default value is true * @returns {boolean} To query whether the layout will pass the focus to its children or not. The default value is true */ - isPassFocusToChild: function(){ + isPassFocusToChild: function () { return this.__passFocusToChild; }, @@ -164,7 +164,7 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{ * @param {ccui.Widget} current the current focused widget * @returns {ccui.Widget} return the index of widget in the layout */ - findNextFocusedWidget: function(direction, current){ + findNextFocusedWidget: function (direction, current) { if (this._isFocusPassing || this.isFocused()) { var parent = this.getParent(); this._isFocusPassing = false; @@ -181,31 +181,31 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{ return this; parent._isFocusPassing = true; return parent.findNextFocusedWidget(direction, this); - } else if(current.isFocused() || current instanceof ccui.Layout) { + } else if (current.isFocused() || current instanceof ccui.Layout) { if (this._layoutType === ccui.Layout.LINEAR_HORIZONTAL) { - switch (direction){ + switch (direction) { case ccui.Widget.LEFT: return this._getPreviousFocusedWidget(direction, current); - break; + break; case ccui.Widget.RIGHT: return this._getNextFocusedWidget(direction, current); - break; + break; case ccui.Widget.DOWN: case ccui.Widget.UP: - if (this._isLastWidgetInContainer(this, direction)){ + if (this._isLastWidgetInContainer(this, direction)) { if (this._isWidgetAncestorSupportLoopFocus(current, direction)) return ccui.Widget.prototype.findNextFocusedWidget.call(this, direction, this); return current; } else { return ccui.Widget.prototype.findNextFocusedWidget.call(this, direction, this); } - break; + break; default: cc.assert(0, "Invalid Focus Direction"); return current; } } else if (this._layoutType === ccui.Layout.LINEAR_VERTICAL) { - switch (direction){ + switch (direction) { case ccui.Widget.LEFT: case ccui.Widget.RIGHT: if (this._isLastWidgetInContainer(this, direction)) { @@ -215,7 +215,7 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{ } else return ccui.Widget.prototype.findNextFocusedWidget.call(this, direction, this); - break; + break; case ccui.Widget.DOWN: return this._getNextFocusedWidget(direction, current); break; @@ -282,7 +282,7 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{ * and sets the layout dirty flag to true. * @param {Boolean} cleanup true if all running actions on all children nodes should be cleanup, false otherwise. */ - removeAllChildrenWithCleanup: function(cleanup){ + removeAllChildrenWithCleanup: function (cleanup) { ccui.Widget.prototype.removeAllChildrenWithCleanup.call(this, cleanup); this._doLayoutDirty = true; }, @@ -337,7 +337,7 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{ switch (this._clippingType) { case ccui.Layout.CLIPPING_SCISSOR: case ccui.Layout.CLIPPING_STENCIL: - if (able){ + if (able) { this._clippingStencil = new cc.DrawNode(); this._renderCmd.rebindStencilRendering(this._clippingStencil); if (this._running) @@ -415,8 +415,8 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{ var right = Math.min(worldPos.x + scissorWidth, parentClippingRect.x + parentClippingRect.width); var top = Math.min(worldPos.y + scissorHeight, parentClippingRect.y + parentClippingRect.height); - this._clippingRect.width = Math.max(0.0, right - this._clippingRect.x); - this._clippingRect.height = Math.max(0.0, top - this._clippingRect.y); + this._clippingRect.width = Math.max(0.0, right - this._clippingRect.x); + this._clippingRect.height = Math.max(0.0, top - this._clippingRect.y); } else { this._clippingRect.x = worldPos.x; this._clippingRect.y = worldPos.y; @@ -477,7 +477,7 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{ if (!fileName) return; texType = texType || ccui.Widget.LOCAL_TEXTURE; - if (this._backGroundImage === null){ + if (this._backGroundImage === null) { this._addBackGroundImage(); this.setBackGroundImageScale9Enabled(this._backGroundScale9Enabled); } @@ -507,7 +507,7 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{ * @param {cc.Rect} capInsets capinsets of background image. */ setBackGroundImageCapInsets: function (capInsets) { - if(!capInsets) + if (!capInsets) return; var locInsets = this._backGroundImageCapInsets; locInsets.x = capInsets.x; @@ -780,7 +780,7 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{ }, _updateBackGroundImageColor: function () { - if(this._backGroundImage) + if (this._backGroundImage) this._backGroundImage.setColor(this._backGroundImageColor); }, @@ -802,7 +802,7 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{ var locChild = null; for (var i = 0; i < layoutChildrenArray.length; i++) { locChild = layoutChildrenArray[i]; - if(locChild instanceof ccui.Widget) + if (locChild instanceof ccui.Widget) this._supplyTheLayoutParameterLackToChild(locChild); } this._doLayoutDirty = true; @@ -835,20 +835,20 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{ this._doLayoutDirty = false; }, - _getLayoutContentSize: function(){ + _getLayoutContentSize: function () { return this.getContentSize(); }, - _getLayoutElements: function(){ + _getLayoutElements: function () { return this.getChildren(); }, - _updateBackGroundImageOpacity: function(){ + _updateBackGroundImageOpacity: function () { if (this._backGroundImage) this._backGroundImage.setOpacity(this._backGroundImageOpacity); }, - _updateBackGroundImageRGBA: function(){ + _updateBackGroundImageRGBA: function () { if (this._backGroundImage) { this._backGroundImage.setColor(this._backGroundImageColor); this._backGroundImage.setOpacity(this._backGroundImageOpacity); @@ -860,13 +860,13 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{ * @returns {cc.Size} * @private */ - _getLayoutAccumulatedSize: function(){ + _getLayoutAccumulatedSize: function () { var children = this.getChildren(); - var layoutSize = cc.size(0, 0); + var layoutSize = cc.size(0, 0); var widgetCount = 0, locSize; - for(var i = 0, len = children.length; i < len; i++) { + for (var i = 0, len = children.length; i < len; i++) { var layout = children[i]; - if (null !== layout && layout instanceof ccui.Layout){ + if (null !== layout && layout instanceof ccui.Layout) { locSize = layout._getLayoutAccumulatedSize(); layoutSize.width += locSize.width; layoutSize.height += locSize.height; @@ -875,8 +875,8 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{ widgetCount++; var m = layout.getLayoutParameter().getMargin(); locSize = layout.getContentSize(); - layoutSize.width += locSize.width + (m.right + m.left) * 0.5; - layoutSize.height += locSize.height + (m.top + m.bottom) * 0.5; + layoutSize.width += locSize.width + (m.right + m.left) * 0.5; + layoutSize.height += locSize.height + (m.top + m.bottom) * 0.5; } } } @@ -884,10 +884,10 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{ //substract extra size var type = this.getLayoutType(); if (type === ccui.Layout.LINEAR_HORIZONTAL) - layoutSize.height = layoutSize.height - layoutSize.height/widgetCount * (widgetCount-1); + layoutSize.height = layoutSize.height - layoutSize.height / widgetCount * (widgetCount - 1); if (type === ccui.Layout.LINEAR_VERTICAL) - layoutSize.width = layoutSize.width - layoutSize.width/widgetCount * (widgetCount-1); + layoutSize.width = layoutSize.width - layoutSize.width / widgetCount * (widgetCount - 1); return layoutSize; }, @@ -899,7 +899,7 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{ * @returns {Number} * @private */ - _findNearestChildWidgetIndex: function(direction, baseWidget){ + _findNearestChildWidgetIndex: function (direction, baseWidget) { if (baseWidget == null || baseWidget === this) return this._findFirstFocusEnabledWidgetIndex(); @@ -912,9 +912,9 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{ while (index < count) { var w = locChildren[index]; if (w && w instanceof ccui.Widget && w.isFocusEnabled()) { - var length = (w instanceof ccui.Layout)? w._calculateNearestDistance(baseWidget) + var length = (w instanceof ccui.Layout) ? w._calculateNearestDistance(baseWidget) : cc.pLength(cc.pSub(this._getWorldCenterPoint(w), widgetPosition)); - if (length < distance){ + if (length < distance) { found = index; distance = length; } @@ -935,7 +935,7 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{ * @returns {Number} The index of child widget in the container * @private */ - _findFarthestChildWidgetIndex: function(direction, baseWidget){ + _findFarthestChildWidgetIndex: function (direction, baseWidget) { if (baseWidget == null || baseWidget === this) return this._findFirstFocusEnabledWidgetIndex(); @@ -944,20 +944,20 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{ var distance = -cc.FLT_MAX, found = 0; if (direction === ccui.Widget.LEFT || direction === ccui.Widget.RIGHT || direction === ccui.Widget.DOWN || direction === ccui.Widget.UP) { - var widgetPosition = this._getWorldCenterPoint(baseWidget); - while (index < count) { + var widgetPosition = this._getWorldCenterPoint(baseWidget); + while (index < count) { var w = locChildren[index]; if (w && w instanceof ccui.Widget && w.isFocusEnabled()) { - var length = (w instanceof ccui.Layout)?w._calculateFarthestDistance(baseWidget) + var length = (w instanceof ccui.Layout) ? w._calculateFarthestDistance(baseWidget) : cc.pLength(cc.pSub(this._getWorldCenterPoint(w), widgetPosition)); - if (length > distance){ + if (length > distance) { found = index; distance = length; } } index++; } - return found; + return found; } cc.log("invalid focus direction!!!"); return 0; @@ -969,9 +969,9 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{ * @returns {Number} return the nearest distance between the baseWidget and the layout's children * @private */ - _calculateNearestDistance: function(baseWidget){ + _calculateNearestDistance: function (baseWidget) { var distance = cc.FLT_MAX; - var widgetPosition = this._getWorldCenterPoint(baseWidget); + var widgetPosition = this._getWorldCenterPoint(baseWidget); var locChildren = this._children; for (var i = 0, len = locChildren.length; i < len; i++) { @@ -996,9 +996,9 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{ * @returns {number} * @private */ - _calculateFarthestDistance:function(baseWidget){ + _calculateFarthestDistance: function (baseWidget) { var distance = -cc.FLT_MAX; - var widgetPosition = this._getWorldCenterPoint(baseWidget); + var widgetPosition = this._getWorldCenterPoint(baseWidget); var locChildren = this._children; for (var i = 0, len = locChildren.length; i < len; i++) { @@ -1026,7 +1026,7 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{ * @param baseWidget * @private */ - _findProperSearchingFunctor: function(direction, baseWidget){ + _findProperSearchingFunctor: function (direction, baseWidget) { if (baseWidget === undefined) return; @@ -1038,13 +1038,13 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{ } else if (direction === ccui.Widget.RIGHT) { this.onPassFocusToChild = (previousWidgetPosition.x > widgetPosition.x) ? this._findFarthestChildWidgetIndex : this._findNearestChildWidgetIndex; - }else if(direction === ccui.Widget.DOWN) { + } else if (direction === ccui.Widget.DOWN) { this.onPassFocusToChild = (previousWidgetPosition.y > widgetPosition.y) ? this._findNearestChildWidgetIndex : this._findFarthestChildWidgetIndex; - }else if(direction === ccui.Widget.UP) { + } else if (direction === ccui.Widget.UP) { this.onPassFocusToChild = (previousWidgetPosition.y < widgetPosition.y) ? this._findNearestChildWidgetIndex : this._findFarthestChildWidgetIndex; - }else + } else cc.log("invalid direction!"); }, @@ -1053,15 +1053,15 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{ * @returns {ccui.Widget} * @private */ - _findFirstNonLayoutWidget:function(){ + _findFirstNonLayoutWidget: function () { var locChildren = this._children; - for(var i = 0, len = locChildren.length; i < len; i++) { + for (var i = 0, len = locChildren.length; i < len; i++) { var child = locChildren[i]; - if (child instanceof ccui.Layout){ + if (child instanceof ccui.Layout) { var widget = child._findFirstNonLayoutWidget(); - if(widget) + if (widget) return widget; - } else{ + } else { if (child instanceof ccui.Widget) return child; } @@ -1074,7 +1074,7 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{ * @returns {number} * @private */ - _findFirstFocusEnabledWidgetIndex: function(){ + _findFirstFocusEnabledWidgetIndex: function () { var index = 0, locChildren = this.getChildren(); var count = locChildren.length; while (index < count) { @@ -1092,9 +1092,9 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{ * @returns {*} * @private */ - _findFocusEnabledChildWidgetByIndex: function(index){ + _findFocusEnabledChildWidgetByIndex: function (index) { var widget = this._getChildWidgetByIndex(index); - if (widget){ + if (widget) { if (widget.isFocusEnabled()) return widget; index = index + 1; @@ -1109,10 +1109,10 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{ * @returns {cc.Point} * @private */ - _getWorldCenterPoint: function(widget){ + _getWorldCenterPoint: function (widget) { //FIXEDME: we don't need to calculate the content size of layout anymore - var widgetSize = widget instanceof ccui.Layout ? widget._getLayoutAccumulatedSize() : widget.getContentSize(); - return widget.convertToWorldSpace(cc.p(widgetSize.width /2, widgetSize.height /2)); + var widgetSize = widget instanceof ccui.Layout ? widget._getLayoutAccumulatedSize() : widget.getContentSize(); + return widget.convertToWorldSpace(cc.p(widgetSize.width / 2, widgetSize.height / 2)); }, /** @@ -1122,9 +1122,9 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{ * @returns {ccui.Widget} the next focused widget * @private */ - _getNextFocusedWidget: function(direction, current){ + _getNextFocusedWidget: function (direction, current) { var nextWidget = null, locChildren = this._children; - var previousWidgetPos = locChildren.indexOf(current); + var previousWidgetPos = locChildren.indexOf(current); previousWidgetPos = previousWidgetPos + 1; if (previousWidgetPos < locChildren.length) { nextWidget = this._getChildWidgetByIndex(previousWidgetPos); @@ -1159,8 +1159,8 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{ return this._getNextFocusedWidget(direction, nextWidget); } else return (current instanceof ccui.Layout) ? current : ccui.Widget._focusedWidget; - } else{ - if (this._isLastWidgetInContainer(current, direction)){ + } else { + if (this._isLastWidgetInContainer(current, direction)) { if (this._isWidgetAncestorSupportLoopFocus(this, direction)) return ccui.Widget.prototype.findNextFocusedWidget.call(this, direction, this); return (current instanceof ccui.Layout) ? current : ccui.Widget._focusedWidget; @@ -1177,14 +1177,14 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{ * @returns {ccui.Widget} the next focused widget * @private */ - _getPreviousFocusedWidget: function(direction, current){ + _getPreviousFocusedWidget: function (direction, current) { var nextWidget = null, locChildren = this._children; var previousWidgetPos = locChildren.indexOf(current); previousWidgetPos = previousWidgetPos - 1; - if (previousWidgetPos >= 0){ + if (previousWidgetPos >= 0) { nextWidget = this._getChildWidgetByIndex(previousWidgetPos); if (nextWidget.isFocusEnabled()) { - if (nextWidget instanceof ccui.Layout){ + if (nextWidget instanceof ccui.Layout) { nextWidget._isFocusPassing = true; return nextWidget.findNextFocusedWidget(direction, nextWidget); } @@ -1192,13 +1192,13 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{ return nextWidget; } else return this._getPreviousFocusedWidget(direction, nextWidget); //handling the disabled widget, there is no actual focus lose or get, so we don't need any envet - }else { - if (this._loopFocus){ + } else { + if (this._loopFocus) { if (this._checkFocusEnabledChild()) { - previousWidgetPos = locChildren.length -1; + previousWidgetPos = locChildren.length - 1; nextWidget = this._getChildWidgetByIndex(previousWidgetPos); - if (nextWidget.isFocusEnabled()){ - if (nextWidget instanceof ccui.Layout){ + if (nextWidget.isFocusEnabled()) { + if (nextWidget instanceof ccui.Layout) { nextWidget._isFocusPassing = true; return nextWidget.findNextFocusedWidget(direction, nextWidget); } else { @@ -1255,7 +1255,7 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{ * @returns {Boolean} * @private */ - _isLastWidgetInContainer:function(widget, direction){ + _isLastWidgetInContainer: function (widget, direction) { var parent = widget.getParent(); if (parent == null || !(parent instanceof ccui.Layout)) return true; @@ -1280,8 +1280,8 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{ if (direction === ccui.Widget.UP) return this._isLastWidgetInContainer(parent, direction); - } else if(parent.getLayoutType() === ccui.Layout.LINEAR_VERTICAL){ - if (direction === ccui.Widget.UP){ + } else if (parent.getLayoutType() === ccui.Layout.LINEAR_VERTICAL) { + if (direction === ccui.Widget.UP) { if (index === 0) return this._isLastWidgetInContainer(parent, direction); else @@ -1311,7 +1311,7 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{ * @returns {Boolean} * @private */ - _isWidgetAncestorSupportLoopFocus: function(widget, direction){ + _isWidgetAncestorSupportLoopFocus: function (widget, direction) { var parent = widget.getParent(); if (parent == null || !(parent instanceof ccui.Layout)) return false; @@ -1323,12 +1323,12 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{ else return this._isWidgetAncestorSupportLoopFocus(parent, direction); } - if (layoutType === ccui.Layout.LINEAR_VERTICAL){ + if (layoutType === ccui.Layout.LINEAR_VERTICAL) { if (direction === ccui.Widget.DOWN || direction === ccui.Widget.UP) return true; else return this._isWidgetAncestorSupportLoopFocus(parent, direction); - } else{ + } else { cc.assert(0, "invalid layout type"); return false; } @@ -1343,7 +1343,7 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{ * @returns {ccui.Widget} * @private */ - _passFocusToChild: function(direction, current){ + _passFocusToChild: function (direction, current) { if (this._checkFocusEnabledChild()) { var previousWidget = ccui.Widget.getCurrentFocusedWidget(); this._findProperSearchingFunctor(direction, previousWidget); @@ -1357,7 +1357,7 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{ this.dispatchFocusEvent(current, widget); return widget; } - }else + } else return this; }, @@ -1366,9 +1366,9 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{ * @returns {boolean} * @private */ - _checkFocusEnabledChild: function(){ + _checkFocusEnabledChild: function () { var locChildren = this._children; - for(var i = 0, len = locChildren.length; i < len; i++){ + for (var i = 0, len = locChildren.length; i < len; i++) { var widget = locChildren[i]; if (widget && widget instanceof ccui.Widget && widget.isFocusEnabled()) return true; @@ -1393,7 +1393,7 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{ }, _copySpecialProperties: function (layout) { - if(!(layout instanceof ccui.Layout)) + if (!(layout instanceof ccui.Layout)) return; this.setBackGroundImageScale9Enabled(layout._backGroundScale9Enabled); this.setBackGroundImage(layout._backGroundImageFileName, layout._bgImageTexType); @@ -1414,13 +1414,13 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{ /** * force refresh widget layout */ - forceDoLayout: function(){ + forceDoLayout: function () { this.requestDoLayout(); this._doLayout(); }, - _createRenderCmd: function(){ - if(cc._renderType === cc.game.RENDER_TYPE_WEBGL) + _createRenderCmd: function () { + if (cc._renderType === cc.game.RENDER_TYPE_WEBGL) return new ccui.Layout.WebGLRenderCmd(this); else return new ccui.Layout.CanvasRenderCmd(this); @@ -1524,4 +1524,4 @@ ccui.Layout.BACKGROUND_IMAGE_ZORDER = -1; * @type {number} * @constant */ -ccui.Layout.BACKGROUND_RENDERER_ZORDER = -2; \ No newline at end of file +ccui.Layout.BACKGROUND_RENDERER_ZORDER = -2; diff --git a/extensions/ccui/layouts/UILayoutCanvasRenderCmd.js b/extensions/ccui/layouts/UILayoutCanvasRenderCmd.js index aa78743222..84ff54d167 100644 --- a/extensions/ccui/layouts/UILayoutCanvasRenderCmd.js +++ b/extensions/ccui/layouts/UILayoutCanvasRenderCmd.js @@ -70,7 +70,7 @@ proto.layoutVisit = proto.visit; - proto._onRenderSaveCmd = function(ctx, scaleX, scaleY){ + proto._onRenderSaveCmd = function (ctx, scaleX, scaleY) { var wrapper = ctx || cc._renderContext, context = wrapper.getContext(); wrapper.save(); wrapper.save(); @@ -81,31 +81,31 @@ var element = buffer[i], vertices = element.verts; var firstPoint = vertices[0]; context.beginPath(); - context.moveTo(firstPoint.x, -firstPoint.y ); + context.moveTo(firstPoint.x, -firstPoint.y); for (var j = 1, len = vertices.length; j < len; j++) - context.lineTo(vertices[j].x , -vertices[j].y ); + context.lineTo(vertices[j].x, -vertices[j].y); context.closePath(); } }; - proto._onRenderClipCmd = function(ctx){ + proto._onRenderClipCmd = function (ctx) { var wrapper = ctx || cc._renderContext, context = wrapper.getContext(); wrapper.restore(); context.clip(); }; - proto._onRenderRestoreCmd = function(ctx){ + proto._onRenderRestoreCmd = function (ctx) { var wrapper = ctx || cc._renderContext, context = wrapper.getContext(); wrapper.restore(); }; - proto.rebindStencilRendering = function(stencil){ + proto.rebindStencilRendering = function (stencil) { stencil._renderCmd.rendering = this.__stencilDraw; stencil._renderCmd._canUseDirtyRegion = true; }; - proto.__stencilDraw = function(ctx,scaleX, scaleY){ //Only for Canvas + proto.__stencilDraw = function (ctx, scaleX, scaleY) { //Only for Canvas //do nothing, rendering in layout }; @@ -152,4 +152,4 @@ ccui.Layout.CanvasRenderCmd._getSharedCache = function () { return (cc.ClippingNode._sharedCache) || (cc.ClippingNode._sharedCache = document.createElement("canvas")); }; -})(); \ No newline at end of file +})(); diff --git a/extensions/ccui/layouts/UILayoutManager.js b/extensions/ccui/layouts/UILayoutManager.js index d69a36618c..7c71a9496e 100644 --- a/extensions/ccui/layouts/UILayoutManager.js +++ b/extensions/ccui/layouts/UILayoutManager.js @@ -45,7 +45,7 @@ ccui.getLayoutManager = function (type) { * @name ccui.linearVerticalLayoutManager */ ccui.linearVerticalLayoutManager = /** @lends ccui.linearVerticalLayoutManager# */{ - _doLayout: function(layout){ + _doLayout: function (layout) { var layoutSize = layout._getLayoutContentSize(); var container = layout._getLayoutElements(); var topBoundary = layoutSize.height; @@ -55,13 +55,13 @@ ccui.linearVerticalLayoutManager = /** @lends ccui.linearVerticalLayoutManager# if (child) { var layoutParameter = child.getLayoutParameter(); - if (layoutParameter){ + if (layoutParameter) { var childGravity = layoutParameter.getGravity(); var ap = child.getAnchorPoint(); var cs = child.getContentSize(); var finalPosX = ap.x * cs.width; var finalPosY = topBoundary - ((1.0 - ap.y) * cs.height); - switch (childGravity){ + switch (childGravity) { case ccui.LinearLayoutParameter.NONE: case ccui.LinearLayoutParameter.LEFT: break; @@ -91,21 +91,21 @@ ccui.linearVerticalLayoutManager = /** @lends ccui.linearVerticalLayoutManager# * @name ccui.linearHorizontalLayoutManager */ ccui.linearHorizontalLayoutManager = /** @lends ccui.linearHorizontalLayoutManager# */{ - _doLayout: function(layout){ + _doLayout: function (layout) { var layoutSize = layout._getLayoutContentSize(); var container = layout._getLayoutElements(); var leftBoundary = 0.0; - for (var i = 0, len = container.length; i < len; i++) { + for (var i = 0, len = container.length; i < len; i++) { var child = container[i]; if (child) { var layoutParameter = child.getLayoutParameter(); - if (layoutParameter){ + if (layoutParameter) { var childGravity = layoutParameter.getGravity(); var ap = child.getAnchorPoint(); var cs = child.getContentSize(); var finalPosX = leftBoundary + (ap.x * cs.width); var finalPosY = layoutSize.height - (1.0 - ap.y) * cs.height; - switch (childGravity){ + switch (childGravity) { case ccui.LinearLayoutParameter.NONE: case ccui.LinearLayoutParameter.TOP: break; @@ -138,16 +138,16 @@ ccui.relativeLayoutManager = /** @lends ccui.relativeLayoutManager# */{ _unlayoutChildCount: 0, _widgetChildren: [], _widget: null, - _finalPositionX:0, - _finalPositionY:0, - _relativeWidgetLP:null, + _finalPositionX: 0, + _finalPositionY: 0, + _relativeWidgetLP: null, - _doLayout: function(layout){ + _doLayout: function (layout) { this._widgetChildren = this._getAllWidgets(layout); var locChildren = this._widgetChildren; while (this._unlayoutChildCount > 0) { - for (var i = 0, len = locChildren.length; i < len; i++) { + for (var i = 0, len = locChildren.length; i < len; i++) { this._widget = locChildren[i]; var layoutParameter = this._widget.getLayoutParameter(); @@ -170,11 +170,11 @@ ccui.relativeLayoutManager = /** @lends ccui.relativeLayoutManager# */{ this._widgetChildren.length = 0; }, - _getAllWidgets: function(layout){ + _getAllWidgets: function (layout) { var container = layout._getLayoutElements(); var locWidgetChildren = this._widgetChildren; locWidgetChildren.length = 0; - for (var i = 0, len = container.length; i < len; i++){ + for (var i = 0, len = container.length; i < len; i++) { var child = container[i]; if (child && child instanceof ccui.Widget) { var layoutParameter = child.getLayoutParameter(); @@ -186,14 +186,14 @@ ccui.relativeLayoutManager = /** @lends ccui.relativeLayoutManager# */{ return locWidgetChildren; }, - _getRelativeWidget: function(widget){ + _getRelativeWidget: function (widget) { var relativeWidget = null; var layoutParameter = widget.getLayoutParameter(); var relativeName = layoutParameter.getRelativeToWidgetName(); if (relativeName && relativeName.length !== 0) { - var locChildren = this._widgetChildren; - for(var i = 0, len = locChildren.length; i < len; i++){ + var locChildren = this._widgetChildren; + for (var i = 0, len = locChildren.length; i < len; i++) { var child = locChildren[i]; if (child){ var rlayoutParameter = child.getLayoutParameter(); @@ -208,7 +208,7 @@ ccui.relativeLayoutManager = /** @lends ccui.relativeLayoutManager# */{ return relativeWidget; }, - _calculateFinalPositionWithRelativeWidget: function(layout){ + _calculateFinalPositionWithRelativeWidget: function (layout) { var locWidget = this._widget; var ap = locWidget.getAnchorPoint(); var cs = locWidget.getContentSize(); @@ -261,7 +261,7 @@ ccui.relativeLayoutManager = /** @lends ccui.relativeLayoutManager# */{ break; case ccui.RelativeLayoutParameter.LOCATION_ABOVE_LEFTALIGN: - if (relativeWidget){ + if (relativeWidget) { if (this._relativeWidgetLP && !this._relativeWidgetLP._put) return false; this._finalPositionY = relativeWidget.getTopBoundary() + ap.y * cs.height; @@ -269,7 +269,7 @@ ccui.relativeLayoutManager = /** @lends ccui.relativeLayoutManager# */{ } break; case ccui.RelativeLayoutParameter.LOCATION_ABOVE_CENTER: - if (relativeWidget){ + if (relativeWidget) { if (this._relativeWidgetLP && !this._relativeWidgetLP._put) return false; var rbs = relativeWidget.getContentSize(); @@ -286,7 +286,7 @@ ccui.relativeLayoutManager = /** @lends ccui.relativeLayoutManager# */{ } break; case ccui.RelativeLayoutParameter.LOCATION_LEFT_OF_TOPALIGN: - if (relativeWidget){ + if (relativeWidget) { if (this._relativeWidgetLP && !this._relativeWidgetLP._put) return false; this._finalPositionY = relativeWidget.getTopBoundary() - (1.0 - ap.y) * cs.height; @@ -311,7 +311,7 @@ ccui.relativeLayoutManager = /** @lends ccui.relativeLayoutManager# */{ } break; case ccui.RelativeLayoutParameter.LOCATION_RIGHT_OF_TOPALIGN: - if (relativeWidget){ + if (relativeWidget) { if (this._relativeWidgetLP && !this._relativeWidgetLP._put) return false; this._finalPositionY = relativeWidget.getTopBoundary() - (1.0 - ap.y) * cs.height; @@ -319,7 +319,7 @@ ccui.relativeLayoutManager = /** @lends ccui.relativeLayoutManager# */{ } break; case ccui.RelativeLayoutParameter.LOCATION_RIGHT_OF_CENTER: - if (relativeWidget){ + if (relativeWidget) { if (this._relativeWidgetLP && !this._relativeWidgetLP._put) return false; var rbs = relativeWidget.getContentSize(); @@ -329,7 +329,7 @@ ccui.relativeLayoutManager = /** @lends ccui.relativeLayoutManager# */{ } break; case ccui.RelativeLayoutParameter.LOCATION_RIGHT_OF_BOTTOMALIGN: - if (relativeWidget){ + if (relativeWidget) { if (this._relativeWidgetLP && !this._relativeWidgetLP._put) return false; this._finalPositionY = relativeWidget.getBottomBoundary() + ap.y * cs.height; @@ -337,10 +337,10 @@ ccui.relativeLayoutManager = /** @lends ccui.relativeLayoutManager# */{ } break; case ccui.RelativeLayoutParameter.LOCATION_BELOW_LEFTALIGN: - if (relativeWidget){ + if (relativeWidget) { if (this._relativeWidgetLP && !this._relativeWidgetLP._put) return false; - this._finalPositionY = relativeWidget.getBottomBoundary() - (1.0 - ap.y) * cs.height; + this._finalPositionY = relativeWidget.getBottomBoundary() - (1.0 - ap.y) * cs.height; this._finalPositionX = relativeWidget.getLeftBoundary() + ap.x * cs.width; } break; @@ -367,7 +367,7 @@ ccui.relativeLayoutManager = /** @lends ccui.relativeLayoutManager# */{ return true; }, - _calculateFinalPositionWithRelativeAlign: function(){ + _calculateFinalPositionWithRelativeAlign: function () { var layoutParameter = this._widget.getLayoutParameter(); var mg = layoutParameter.getMargin(); @@ -454,4 +454,4 @@ ccui.relativeLayoutManager = /** @lends ccui.relativeLayoutManager# */{ break; } } -}; \ No newline at end of file +}; diff --git a/extensions/ccui/layouts/UILayoutWebGLRenderCmd.js b/extensions/ccui/layouts/UILayoutWebGLRenderCmd.js index 9fd8544f8c..05a1f7f0c1 100644 --- a/extensions/ccui/layouts/UILayoutWebGLRenderCmd.js +++ b/extensions/ccui/layouts/UILayoutWebGLRenderCmd.js @@ -23,8 +23,8 @@ THE SOFTWARE. ****************************************************************************/ -(function(){ - if(!ccui.ProtectedNode.WebGLRenderCmd) +(function () { + if (!ccui.ProtectedNode.WebGLRenderCmd) return; ccui.Layout.WebGLRenderCmd = function(renderable){ ccui.ProtectedNode.WebGLRenderCmd.call(this, renderable); @@ -75,7 +75,7 @@ proto.layoutVisit = proto.visit; - proto._onBeforeVisitStencil = function(ctx){ + proto._onBeforeVisitStencil = function (ctx) { var gl = ctx || cc._renderContext; ccui.Layout.WebGLRenderCmd._layer++; @@ -101,20 +101,19 @@ }; - proto._onAfterDrawStencil = function(ctx){ + proto._onAfterDrawStencil = function (ctx) { var gl = ctx || cc._renderContext; gl.depthMask(true); gl.stencilFunc(gl.EQUAL, this._mask_layer_le, this._mask_layer_le); gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP); }; - proto._onAfterVisitStencil = function(ctx){ + proto._onAfterVisitStencil = function (ctx) { var gl = ctx || cc._renderContext; ccui.Layout.WebGLRenderCmd._layer--; - if (this._currentStencilEnabled) - { + if (this._currentStencilEnabled) { var mask_layer = 0x1 << ccui.Layout.WebGLRenderCmd._layer; var mask_layer_l = mask_layer - 1; var mask_layer_le = mask_layer | mask_layer_l; @@ -122,13 +121,12 @@ gl.stencilMask(mask_layer); gl.stencilFunc(gl.EQUAL, mask_layer_le, mask_layer_le); } - else - { + else { gl.disable(gl.STENCIL_TEST); } }; - proto._onBeforeVisitScissor = function(ctx){ + proto._onBeforeVisitScissor = function (ctx) { this._node._clippingRectDirty = true; var clippingRect = this._node._getClippingRect(); var gl = ctx || cc._renderContext; @@ -146,11 +144,11 @@ } }; - proto._onAfterVisitScissor = function(ctx){ + proto._onAfterVisitScissor = function (ctx) { var gl = ctx || cc._renderContext; if (this._scissorOldState) { if (!cc.rectEqualToRect(this._clippingOldRect, this._node._clippingRect)) { - cc.view.setScissorInPoints( this._clippingOldRect.x, + cc.view.setScissorInPoints(this._clippingOldRect.x, this._clippingOldRect.y, this._clippingOldRect.width, this._clippingOldRect.height); @@ -160,13 +158,14 @@ gl.disable(gl.SCISSOR_TEST); } }; - - proto.rebindStencilRendering = function(stencil){}; - proto.transform = function(parentCmd, recursive){ + proto.rebindStencilRendering = function (stencil) { + }; + + proto.transform = function (parentCmd, recursive) { var node = this._node; this.pNodeTransform(parentCmd, recursive); - if(node._clippingStencil) + if (node._clippingStencil) node._clippingStencil._renderCmd.transform(this, recursive); }; @@ -235,7 +234,7 @@ currentStack.top = currentStack.stack.pop(); }; - proto.scissorClippingVisit = function(parentCmd){ + proto.scissorClippingVisit = function (parentCmd) { cc.renderer.pushRenderCommand(this._beforeVisitCmdScissor); this.pNodeVisit(parentCmd); cc.renderer.pushRenderCommand(this._afterVisitCmdScissor); diff --git a/extensions/ccui/system/UIHelper.js b/extensions/ccui/system/UIHelper.js index ec4ba83de5..327bf8dca6 100644 --- a/extensions/ccui/system/UIHelper.js +++ b/extensions/ccui/system/UIHelper.js @@ -32,71 +32,71 @@ * @name ccui.helper */ ccui.helper = { - /** - * Finds a widget whose tag equals to param tag from root widget. - * @param {ccui.Widget} root - * @param {number} tag - * @returns {ccui.Widget} - */ - seekWidgetByTag: function (root, tag) { - if (!root) - return null; - if (root.getTag() === tag) - return root; - - var arrayRootChildren = root.getChildren(); - var length = arrayRootChildren.length; - for (var i = 0; i < length; i++) { - var child = arrayRootChildren[i]; - var res = ccui.helper.seekWidgetByTag(child, tag); - if (res !== null) - return res; - } - return null; - }, - - /** - * Finds a widget whose name equals to param name from root widget. - * @param {ccui.Widget} root - * @param {String} name - * @returns {ccui.Widget} - */ - seekWidgetByName: function (root, name) { - if (!root) - return null; - if (root.getName() === name) - return root; - var arrayRootChildren = root.getChildren(); - var length = arrayRootChildren.length; - for (var i = 0; i < length; i++) { - var child = arrayRootChildren[i]; - var res = ccui.helper.seekWidgetByName(child, name); - if (res !== null) - return res; - } - return null; - }, - - /** - * Finds a widget whose name equals to param name from root widget. - * RelativeLayout will call this method to find the widget witch is needed. - * @param {ccui.Widget} root - * @param {String} name - * @returns {ccui.Widget} - */ - seekWidgetByRelativeName: function (root, name) { - if (!root) - return null; - var arrayRootChildren = root.getChildren(); - var length = arrayRootChildren.length; - for (var i = 0; i < length; i++) { - var child = arrayRootChildren[i]; - var layoutParameter = child.getLayoutParameter(ccui.LayoutParameter.RELATIVE); - if (layoutParameter && layoutParameter.getRelativeName() === name) - return child; - } - return null; - }, + /** + * Finds a widget whose tag equals to param tag from root widget. + * @param {ccui.Widget} root + * @param {number} tag + * @returns {ccui.Widget} + */ + seekWidgetByTag: function (root, tag) { + if (!root) + return null; + if (root.getTag() === tag) + return root; + + var arrayRootChildren = root.getChildren(); + var length = arrayRootChildren.length; + for (var i = 0; i < length; i++) { + var child = arrayRootChildren[i]; + var res = ccui.helper.seekWidgetByTag(child, tag); + if (res !== null) + return res; + } + return null; + }, + + /** + * Finds a widget whose name equals to param name from root widget. + * @param {ccui.Widget} root + * @param {String} name + * @returns {ccui.Widget} + */ + seekWidgetByName: function (root, name) { + if (!root) + return null; + if (root.getName() === name) + return root; + var arrayRootChildren = root.getChildren(); + var length = arrayRootChildren.length; + for (var i = 0; i < length; i++) { + var child = arrayRootChildren[i]; + var res = ccui.helper.seekWidgetByName(child, name); + if (res !== null) + return res; + } + return null; + }, + + /** + * Finds a widget whose name equals to param name from root widget. + * RelativeLayout will call this method to find the widget witch is needed. + * @param {ccui.Widget} root + * @param {String} name + * @returns {ccui.Widget} + */ + seekWidgetByRelativeName: function (root, name) { + if (!root) + return null; + var arrayRootChildren = root.getChildren(); + var length = arrayRootChildren.length; + for (var i = 0; i < length; i++) { + var child = arrayRootChildren[i]; + var layoutParameter = child.getLayoutParameter(ccui.LayoutParameter.RELATIVE); + if (layoutParameter && layoutParameter.getRelativeName() === name) + return child; + } + return null; + }, /** * Finds a widget whose action tag equals to param name from root widget. @@ -104,28 +104,28 @@ ccui.helper = { * @param {Number} tag * @returns {ccui.Widget} */ - seekActionWidgetByActionTag: function (root, tag) { - if (!root) - return null; - if (root.getActionTag() === tag) - return root; - var arrayRootChildren = root.getChildren(); - for (var i = 0; i < arrayRootChildren.length; i++) { - var child = arrayRootChildren[i]; - var res = ccui.helper.seekActionWidgetByActionTag(child, tag); - if (res !== null) - return res; - } - return null; - } , + seekActionWidgetByActionTag: function (root, tag) { + if (!root) + return null; + if (root.getActionTag() === tag) + return root; + var arrayRootChildren = root.getChildren(); + for (var i = 0; i < arrayRootChildren.length; i++) { + var child = arrayRootChildren[i]; + var res = ccui.helper.seekActionWidgetByActionTag(child, tag); + if (res !== null) + return res; + } + return null; + }, _activeLayout: true, /** * Refresh object and it's children layout state * @param {cc.Node} rootNode */ - doLayout: function(rootNode){ - if(!this._activeLayout) + doLayout: function (rootNode) { + if (!this._activeLayout) return; var children = rootNode.getChildren(), node; for(var i = 0, len = children.length;i < len; i++) { @@ -137,7 +137,7 @@ ccui.helper = { } }, - changeLayoutSystemActiveState: function(active){ + changeLayoutSystemActiveState: function (active) { this._activeLayout = active; }, @@ -162,10 +162,10 @@ ccui.helper = { return cc.rect(x, y, width, height); }, - _createSpriteFromBase64: function(base64String, key) { + _createSpriteFromBase64: function (base64String, key) { var texture2D = cc.textureCache.getTextureForKey(key); - if(!texture2D) { + if (!texture2D) { var image = new Image(); image.src = base64String; cc.textureCache.cacheImage(key, image); diff --git a/extensions/ccui/uiwidgets/UILoadingBar.js b/extensions/ccui/uiwidgets/UILoadingBar.js index 9113121c6d..1fdba04c17 100644 --- a/extensions/ccui/uiwidgets/UILoadingBar.js +++ b/extensions/ccui/uiwidgets/UILoadingBar.js @@ -61,9 +61,9 @@ ccui.LoadingBar = ccui.Widget.extend(/** @lends ccui.LoadingBar# */{ this._capInsets = cc.rect(0, 0, 0, 0); ccui.Widget.prototype.ctor.call(this); - if(textureName !== undefined) + if (textureName !== undefined) this.loadTexture(textureName); - if(percentage !== undefined) + if (percentage !== undefined) this.setPercent(percentage); }, @@ -86,16 +86,16 @@ ccui.LoadingBar = ccui.Widget.extend(/** @lends ccui.LoadingBar# */{ switch (this._direction) { case ccui.LoadingBar.TYPE_LEFT: this._barRenderer.setAnchorPoint(0, 0.5); - this._barRenderer.setPosition(0, this._contentSize.height*0.5); - if (!this._scale9Enabled) - this._barRenderer.setFlippedX(false); + this._barRenderer.setPosition(0, this._contentSize.height * 0.5); + if (!this._scale9Enabled) + this._barRenderer.setFlippedX(false); break; case ccui.LoadingBar.TYPE_RIGHT: this._barRenderer.setAnchorPoint(1, 0.5); - this._barRenderer.setPosition(this._totalLength,this._contentSize.height*0.5); - if (!this._scale9Enabled) - this._barRenderer.setFlippedX(true); + this._barRenderer.setPosition(this._totalLength, this._contentSize.height * 0.5); + if (!this._scale9Enabled) + this._barRenderer.setFlippedX(true); break; } @@ -124,8 +124,8 @@ ccui.LoadingBar = ccui.Widget.extend(/** @lends ccui.LoadingBar# */{ var barRenderer = this._barRenderer; var self = this; - if(!barRenderer._textureLoaded){ - barRenderer.addEventListener("load", function(){ + if (!barRenderer._textureLoaded) { + barRenderer.addEventListener("load", function () { self.loadTexture(self._textureFile, self._renderBarTexType); self._setPercent(self._percent); }); @@ -148,12 +148,12 @@ ccui.LoadingBar = ccui.Widget.extend(/** @lends ccui.LoadingBar# */{ switch (this._direction) { case ccui.LoadingBar.TYPE_LEFT: - barRenderer.setAnchorPoint(0,0.5); + barRenderer.setAnchorPoint(0, 0.5); if (!this._scale9Enabled) barRenderer.setFlippedX(false); break; case ccui.LoadingBar.TYPE_RIGHT: - barRenderer.setAnchorPoint(1,0.5); + barRenderer.setAnchorPoint(1, 0.5); if (!this._scale9Enabled) barRenderer.setFlippedX(true); break; @@ -207,7 +207,7 @@ ccui.LoadingBar = ccui.Widget.extend(/** @lends ccui.LoadingBar# */{ * @param {cc.Rect} capInsets */ setCapInsets: function (capInsets) { - if(!capInsets) + if (!capInsets) return; var locInsets = this._capInsets; locInsets.x = capInsets.x; @@ -232,9 +232,9 @@ ccui.LoadingBar = ccui.Widget.extend(/** @lends ccui.LoadingBar# */{ * @param {number} percent percent value from 1 to 100. */ setPercent: function (percent) { - if(percent > 100) + if (percent > 100) percent = 100; - if(percent < 0) + if (percent < 0) percent = 0; if (percent === this._percent) return; @@ -242,7 +242,7 @@ ccui.LoadingBar = ccui.Widget.extend(/** @lends ccui.LoadingBar# */{ this._setPercent(percent); }, - _setPercent: function(){ + _setPercent: function () { var res, rect, spriteRenderer, spriteTextureRect; if (this._totalLength <= 0) @@ -274,7 +274,7 @@ ccui.LoadingBar = ccui.Widget.extend(/** @lends ccui.LoadingBar# */{ * @param {Number|cc.Size} contentSize * @param {Number} [height] */ - setContentSize: function(contentSize, height){ + setContentSize: function (contentSize, height) { ccui.Widget.prototype.setContentSize.call(this, contentSize, height); this._totalLength = (height === undefined) ? contentSize.width : contentSize; }, @@ -292,8 +292,8 @@ ccui.LoadingBar = ccui.Widget.extend(/** @lends ccui.LoadingBar# */{ this._barRendererAdaptDirty = true; }, - _adaptRenderers: function(){ - if (this._barRendererAdaptDirty){ + _adaptRenderers: function () { + if (this._barRendererAdaptDirty) { this._barRendererScaleChangedWithSize(); this._barRendererAdaptDirty = false; } @@ -315,7 +315,7 @@ ccui.LoadingBar = ccui.Widget.extend(/** @lends ccui.LoadingBar# */{ * Returns the texture size of renderer. * @returns {cc.Size|*} */ - getVirtualRendererSize:function(){ + getVirtualRendererSize: function () { return cc.size(this._barRendererTextureSize); }, @@ -340,7 +340,7 @@ ccui.LoadingBar = ccui.Widget.extend(/** @lends ccui.LoadingBar# */{ } } else { this._totalLength = locContentSize.width; - if (this._scale9Enabled){ + if (this._scale9Enabled) { this._setScale9Scale(); locBarRender.setScale(1.0); } else { @@ -385,7 +385,7 @@ ccui.LoadingBar = ccui.Widget.extend(/** @lends ccui.LoadingBar# */{ }, _copySpecialProperties: function (loadingBar) { - if(loadingBar instanceof ccui.LoadingBar){ + if (loadingBar instanceof ccui.LoadingBar) { this._prevIgnoreSize = loadingBar._prevIgnoreSize; this.setScale9Enabled(loadingBar._scale9Enabled); this.loadTexture(loadingBar._textureFile, loadingBar._renderBarTexType); @@ -440,4 +440,4 @@ ccui.LoadingBar.TYPE_RIGHT = 1; * @constant * @type {number} */ -ccui.LoadingBar.RENDERER_ZORDER = -1; \ No newline at end of file +ccui.LoadingBar.RENDERER_ZORDER = -1; diff --git a/extensions/ccui/uiwidgets/UIRichText.js b/extensions/ccui/uiwidgets/UIRichText.js index 1247d00f7d..c0572561f4 100644 --- a/extensions/ccui/uiwidgets/UIRichText.js +++ b/extensions/ccui/uiwidgets/UIRichText.js @@ -32,7 +32,7 @@ ccui.RichElement = ccui.Class.extend(/** @lends ccui.RichElement# */{ _type: 0, _tag: 0, _color: null, - _opacity:0, + _opacity: 0, /** * Constructor of ccui.RichElement */ @@ -46,7 +46,7 @@ ccui.RichElement = ccui.Class.extend(/** @lends ccui.RichElement# */{ this._color.b = color.b; } this._opacity = opacity || 0; - if(opacity === undefined) { + if (opacity === undefined) { this._color.a = color.a; } else { @@ -256,7 +256,7 @@ ccui.RichText = ccui.Widget.extend(/** @lends ccui.RichText# */{ removeElement: function (element) { if (cc.isNumber(element)) this._richElements.splice(element, 1); - else + else cc.arrayRemoveObject(this._richElements, element); this._formatTextDirty = true; }, @@ -276,7 +276,7 @@ ccui.RichText = ccui.Widget.extend(/** @lends ccui.RichText# */{ var elementRenderer = null; switch (element._type) { case ccui.RichElement.TEXT: - if( element._fontDefinition) + if (element._fontDefinition) elementRenderer = new cc.LabelTTF(element._text, element._fontDefinition); else //todo: There may be ambiguous elementRenderer = new cc.LabelTTF(element._text, element._fontName, element._fontSize); @@ -300,7 +300,7 @@ ccui.RichText = ccui.Widget.extend(/** @lends ccui.RichText# */{ element = locRichElements[i]; switch (element._type) { case ccui.RichElement.TEXT: - if( element._fontDefinition) + if (element._fontDefinition) this._handleTextRenderer(element._text, element._fontDefinition, element._fontDefinition.fontSize, element._fontDefinition.fillStyle); else this._handleTextRenderer(element._text, element._fontName, element._fontSize, element._color); @@ -329,10 +329,10 @@ ccui.RichText = ccui.Widget.extend(/** @lends ccui.RichText# */{ * @private */ _handleTextRenderer: function (text, fontNameOrFontDef, fontSize, color) { - if(text === "") + if (text === "") return; - if(text === "\n"){ //Force Line Breaking + if (text === "\n") { //Force Line Breaking this._addNewLine(); return; } @@ -349,21 +349,20 @@ ccui.RichText = ccui.Widget.extend(/** @lends ccui.RichText# */{ var cutWords = curText.substr(leftLength, curText.length - 1); var validLeftLength = leftLength > 0; - if(this._lineBreakOnSpace){ + if (this._lineBreakOnSpace) { var lastSpaceIndex = leftWords.lastIndexOf(' '); - leftLength = lastSpaceIndex === -1 ? leftLength : lastSpaceIndex+1 ; + leftLength = lastSpaceIndex === -1 ? leftLength : lastSpaceIndex + 1; cutWords = curText.substr(leftLength, curText.length - 1); validLeftLength = leftLength > 0 && cutWords !== " "; } if (validLeftLength) { var leftRenderer = null; - if( fontNameOrFontDef instanceof cc.FontDefinition) - { + if (fontNameOrFontDef instanceof cc.FontDefinition) { leftRenderer = new cc.LabelTTF(leftWords.substr(0, leftLength), fontNameOrFontDef); leftRenderer.setOpacity(fontNameOrFontDef.fillStyle.a); //TODO: Verify that might not be needed... - }else{ - leftRenderer = new cc.LabelTTF(leftWords.substr(0, leftLength), fontNameOrFontDef, fontSize); + } else { + leftRenderer = new cc.LabelTTF(leftWords.substr(0, leftLength), fontNameOrFontDef, fontSize); leftRenderer.setColor(color); leftRenderer.setOpacity(color.a); } @@ -373,9 +372,9 @@ ccui.RichText = ccui.Widget.extend(/** @lends ccui.RichText# */{ this._addNewLine(); this._handleTextRenderer(cutWords, fontNameOrFontDef, fontSize, color); } else { - if( fontNameOrFontDef instanceof cc.FontDefinition) { + if (fontNameOrFontDef instanceof cc.FontDefinition) { textRenderer.setOpacity(fontNameOrFontDef.fillStyle.a); //TODO: Verify that might not be needed... - }else { + } else { textRenderer.setColor(color); textRenderer.setOpacity(color.a); } @@ -432,7 +431,7 @@ ccui.RichText = ccui.Widget.extend(/** @lends ccui.RichText# */{ } //Text flow horizontal alignment: - if(this._textHorizontalAlignment !== cc.TEXT_ALIGNMENT_LEFT) { + if (this._textHorizontalAlignment !== cc.TEXT_ALIGNMENT_LEFT) { offsetX = 0; if (this._textHorizontalAlignment === cc.TEXT_ALIGNMENT_RIGHT) offsetX = this._contentSize.width - nextPosX; @@ -473,7 +472,7 @@ ccui.RichText = ccui.Widget.extend(/** @lends ccui.RichText# */{ nextPosX += l.getContentSize().width; } //Text flow alignment(s) - if( this._textHorizontalAlignment !== cc.TEXT_ALIGNMENT_LEFT || this._textVerticalAlignment !== cc.VERTICAL_TEXT_ALIGNMENT_TOP) { + if (this._textHorizontalAlignment !== cc.TEXT_ALIGNMENT_LEFT || this._textVerticalAlignment !== cc.VERTICAL_TEXT_ALIGNMENT_TOP) { offsetX = 0; if (this._textHorizontalAlignment === cc.TEXT_ALIGNMENT_RIGHT) offsetX = this._contentSize.width - nextPosX; @@ -498,12 +497,12 @@ ccui.RichText = ccui.Widget.extend(/** @lends ccui.RichText# */{ } var length = locElementRenders.length; - for (i = 0; i= ballRect.x && nsp.x <= (ballRect.x + ballRect.width) && nsp.y >= ballRect.y && @@ -507,7 +506,7 @@ ccui.Slider = ccui.Widget.extend(/** @lends ccui.Slider# */{ * @returns {number} */ _getPercentWithBallPos: function (px) { - return ((px/this._barLength)*100); + return ((px / this._barLength) * 100); }, /** @@ -525,13 +524,13 @@ ccui.Slider = ccui.Widget.extend(/** @lends ccui.Slider# */{ * @param {Function} selector * @param {Object} [target=] */ - addEventListener: function(selector, target){ + addEventListener: function (selector, target) { this._sliderEventSelector = selector; //when target is undefined, _sliderEventSelector = _eventCallback this._sliderEventListener = target; }, _percentChangedEvent: function () { - if(this._sliderEventSelector){ + if (this._sliderEventSelector) { if (this._sliderEventListener) this._sliderEventSelector.call(this._sliderEventListener, this, ccui.Slider.EVENT_PERCENT_CHANGED); else @@ -555,14 +554,12 @@ ccui.Slider = ccui.Widget.extend(/** @lends ccui.Slider# */{ this._progressBarRendererDirty = true; }, - _adaptRenderers: function(){ - if (this._barRendererAdaptDirty) - { + _adaptRenderers: function () { + if (this._barRendererAdaptDirty) { this._barRendererScaleChangedWithSize(); this._barRendererAdaptDirty = false; } - if (this._progressBarRendererDirty) - { + if (this._progressBarRendererDirty) { this._progressBarRendererScaleChangedWithSize(); this._progressBarRendererDirty = false; } @@ -572,7 +569,7 @@ ccui.Slider = ccui.Widget.extend(/** @lends ccui.Slider# */{ * Returns the content size of bar renderer. * @returns {cc.Size} */ - getVirtualRendererSize: function(){ + getVirtualRendererSize: function () { return this._barRenderer.getContentSize(); }, @@ -585,13 +582,13 @@ ccui.Slider = ccui.Widget.extend(/** @lends ccui.Slider# */{ }, _barRendererScaleChangedWithSize: function () { - if (this._unifySize){ + if (this._unifySize) { this._barLength = this._contentSize.width; this._barRenderer.setPreferredSize(this._contentSize); - }else if(this._ignoreSize) { + } else if (this._ignoreSize) { this._barRenderer.setScale(1.0); this._barLength = this._contentSize.width; - }else { + } else { this._barLength = this._contentSize.width; if (this._scale9Enabled) { this._barRenderer.setPreferredSize(this._contentSize); @@ -600,7 +597,7 @@ ccui.Slider = ccui.Widget.extend(/** @lends ccui.Slider# */{ var btextureSize = this._barTextureSize; if (btextureSize.width <= 0.0 || btextureSize.height <= 0.0) { this._barRenderer.setScale(1.0); - }else{ + } else { var bscaleX = this._contentSize.width / btextureSize.width; var bscaleY = this._contentSize.height / btextureSize.height; this._barRenderer.setScaleX(bscaleX); @@ -613,9 +610,9 @@ ccui.Slider = ccui.Widget.extend(/** @lends ccui.Slider# */{ }, _progressBarRendererScaleChangedWithSize: function () { - if(this._unifySize){ + if (this._unifySize) { this._progressBarRenderer.setPreferredSize(this._contentSize); - }else if(this._ignoreSize) { + } else if (this._ignoreSize) { if (!this._scale9Enabled) { var ptextureSize = this._progressBarTextureSize; var pscaleX = this._contentSize.width / ptextureSize.width; @@ -654,9 +651,9 @@ ccui.Slider = ccui.Widget.extend(/** @lends ccui.Slider# */{ }, _onPressStateChangedToPressed: function () { - if (!this._slidBallPressedTextureFile){ + if (!this._slidBallPressedTextureFile) { this._slidBallNormalRenderer.setScale(this._sliderBallNormalTextureScaleX + this._zoomScale, this._sliderBallNormalTextureScaleY + this._zoomScale); - }else{ + } else { this._slidBallNormalRenderer.setVisible(false); this._slidBallPressedRenderer.setVisible(true); this._slidBallDisabledRenderer.setVisible(false); @@ -664,7 +661,7 @@ ccui.Slider = ccui.Widget.extend(/** @lends ccui.Slider# */{ }, _onPressStateChangedToDisabled: function () { - if (this._slidBallDisabledTextureFile){ + if (this._slidBallDisabledTextureFile) { this._slidBallNormalRenderer.setVisible(false); this._slidBallDisabledRenderer.setVisible(true); } @@ -672,27 +669,27 @@ ccui.Slider = ccui.Widget.extend(/** @lends ccui.Slider# */{ this._slidBallPressedRenderer.setVisible(false); }, - setZoomScale: function(scale){ + setZoomScale: function (scale) { this._zoomScale = scale; }, - getZoomScale: function(){ + getZoomScale: function () { return this._zoomScale; }, - getSlidBallNormalRenderer : function () { + getSlidBallNormalRenderer: function () { return this._slidBallNormalRenderer; }, - getSlidBallPressedRenderer : function () { + getSlidBallPressedRenderer: function () { return this._slidBallPressedRenderer; }, - getSlidBallDisabledRenderer : function () { + getSlidBallDisabledRenderer: function () { return this._slidBallDisabledRenderer; }, - getSlidBallRenderer : function () { + getSlidBallRenderer: function () { return this._slidBallRenderer; }, @@ -770,4 +767,4 @@ ccui.Slider.PROGRESSBAR_RENDERER_ZORDER = -2; * @constant * @type {number} */ -ccui.Slider.BALL_RENDERER_ZORDER = -1; \ No newline at end of file +ccui.Slider.BALL_RENDERER_ZORDER = -1; diff --git a/extensions/ccui/uiwidgets/UIText.js b/extensions/ccui/uiwidgets/UIText.js index bfa1198a77..c6270a082c 100644 --- a/extensions/ccui/uiwidgets/UIText.js +++ b/extensions/ccui/uiwidgets/UIText.js @@ -45,7 +45,7 @@ ccui.Text = ccui.Widget.extend(/** @lends ccui.Text# */{ _normalScaleValueY: 1, _fontName: "Arial", _fontSize: 16, - _onSelectedScaleOffset:0.5, + _onSelectedScaleOffset: 0.5, _labelRenderer: null, _textAreaSize: null, _textVerticalAlignment: 0, @@ -98,8 +98,8 @@ ccui.Text = ccui.Widget.extend(/** @lends ccui.Text# */{ * @param {String} text */ setString: function (text) { - if(text === this._labelRenderer.getString()) - return; + if(text === this._labelRenderer.getString()) return; + this._labelRenderer.setString(text); this._updateContentSizeWithTextureSize(this._labelRenderer.getContentSize()); this._labelRendererAdaptDirty = true; @@ -186,8 +186,8 @@ ccui.Text = ccui.Widget.extend(/** @lends ccui.Text# */{ * Returns the type of ccui.Text. * @returns {null} */ - getType: function(){ - return this._type; + getType: function () { + return this._type; }, /** @@ -196,7 +196,7 @@ ccui.Text = ccui.Widget.extend(/** @lends ccui.Text# */{ */ setTextAreaSize: function (size) { this._labelRenderer.setDimensions(size); - if (!this._ignoreSize){ + if (!this._ignoreSize) { this._customSize = size; } this._updateContentSizeWithTextureSize(this._labelRenderer.getContentSize()); @@ -207,7 +207,7 @@ ccui.Text = ccui.Widget.extend(/** @lends ccui.Text# */{ * Returns renderer's dimension. * @returns {cc.Size} */ - getTextAreaSize: function(){ + getTextAreaSize: function () { return this._labelRenderer.getDimensions(); }, @@ -285,7 +285,7 @@ ccui.Text = ccui.Widget.extend(/** @lends ccui.Text# */{ this._labelRendererAdaptDirty = true; }, - _adaptRenderers: function(){ + _adaptRenderers: function () { if (this._labelRendererAdaptDirty) { this._labelScaleChangedWithSize(); this._labelRendererAdaptDirty = false; @@ -297,7 +297,7 @@ ccui.Text = ccui.Widget.extend(/** @lends ccui.Text# */{ * @override * @returns {cc.Size} */ - getVirtualRendererSize: function(){ + getVirtualRendererSize: function () { return this._labelRenderer.getContentSize(); }, @@ -310,7 +310,7 @@ ccui.Text = ccui.Widget.extend(/** @lends ccui.Text# */{ }, //@since v3.3 - getAutoRenderSize: function(){ + getAutoRenderSize: function () { var virtualSize = this._labelRenderer.getContentSize(); if (!this._ignoreSize) { this._labelRenderer.setDimensions(0, 0); @@ -323,7 +323,7 @@ ccui.Text = ccui.Widget.extend(/** @lends ccui.Text# */{ _labelScaleChangedWithSize: function () { var locContentSize = this._contentSize; if (this._ignoreSize) { - this._labelRenderer.setDimensions(0,0); + this._labelRenderer.setDimensions(0, 0); this._labelRenderer.setScale(1.0); this._normalScaleValueX = this._normalScaleValueY = 1; } else { @@ -357,7 +357,7 @@ ccui.Text = ccui.Widget.extend(/** @lends ccui.Text# */{ * @param {cc.Size} offset * @param {Number} blurRadius */ - enableShadow: function(shadowColor, offset, blurRadius){ + enableShadow: function (shadowColor, offset, blurRadius) { this._labelRenderer.enableShadow(shadowColor, offset, blurRadius); }, @@ -366,7 +366,7 @@ ccui.Text = ccui.Widget.extend(/** @lends ccui.Text# */{ * @param {cc.Color} outlineColor * @param {cc.Size} outlineSize */ - enableOutline: function(outlineColor, outlineSize){ + enableOutline: function (outlineColor, outlineSize) { this._labelRenderer.enableStroke(outlineColor, outlineSize); }, @@ -374,7 +374,7 @@ ccui.Text = ccui.Widget.extend(/** @lends ccui.Text# */{ * Enables glow color * @param glowColor */ - enableGlow: function(glowColor){ + enableGlow: function (glowColor) { if (this._type === ccui.Text.Type.TTF) this._labelRenderer.enableGlow(glowColor); }, @@ -382,8 +382,8 @@ ccui.Text = ccui.Widget.extend(/** @lends ccui.Text# */{ /** * Disables renderer's effect. */ - disableEffect: function(){ - if(this._labelRenderer.disableEffect) + disableEffect: function () { + if (this._labelRenderer.disableEffect) this._labelRenderer.disableEffect(); }, @@ -392,7 +392,7 @@ ccui.Text = ccui.Widget.extend(/** @lends ccui.Text# */{ }, _copySpecialProperties: function (uiLabel) { - if(uiLabel instanceof ccui.Text){ + if (uiLabel instanceof ccui.Text) { this.setFontName(uiLabel._fontName); this.setFontSize(uiLabel.getFontSize()); this.setString(uiLabel.getString()); @@ -422,20 +422,20 @@ ccui.Text = ccui.Widget.extend(/** @lends ccui.Text# */{ return this._textAreaSize.height; }, - _changePosition: function(){ + _changePosition: function () { this._adaptRenderers(); }, - setColor: function(color){ + setColor: function (color) { cc.ProtectedNode.prototype.setColor.call(this, color); this._labelRenderer.setColor(color); }, - setTextColor: function(color){ + setTextColor: function (color) { this._labelRenderer.setFontFillColor(color); }, - getTextColor: function(){ + getTextColor: function () { return this._labelRenderer._getFillStyle(); } }); @@ -495,4 +495,4 @@ ccui.Text.RENDERER_ZORDER = -1; ccui.Text.Type = { SYSTEM: 0, TTF: 1 -}; \ No newline at end of file +}; diff --git a/extensions/ccui/uiwidgets/UITextBMFont.js b/extensions/ccui/uiwidgets/UITextBMFont.js index 1430d4aafd..8d61344569 100644 --- a/extensions/ccui/uiwidgets/UITextBMFont.js +++ b/extensions/ccui/uiwidgets/UITextBMFont.js @@ -77,18 +77,18 @@ ccui.LabelBMFont = ccui.TextBMFont = ccui.Widget.extend(/** @lends ccui.TextBMFo var _self = this; var locRenderer = _self._labelBMFontRenderer; - if(!locRenderer._textureLoaded){ - locRenderer.addEventListener("load", function(){ - _self.setFntFile(_self._fntFileName); - var parent = _self.parent; - while (parent) { - if (parent.requestDoLayout) { - parent.requestDoLayout(); - break; - } - parent = parent.parent; - } - }); + if (!locRenderer._textureLoaded) { + locRenderer.addEventListener("load", function () { + _self.setFntFile(_self._fntFileName); + var parent = _self.parent; + while (parent) { + if (parent.requestDoLayout) { + parent.requestDoLayout(); + break; + } + parent = parent.parent; + } + }); } }, @@ -107,7 +107,7 @@ ccui.LabelBMFont = ccui.TextBMFont = ccui.Widget.extend(/** @lends ccui.TextBMFo * @param {String} value */ setString: function (value) { - if(value === this._labelBMFontRenderer.getString()) + if (value === this._labelBMFontRenderer.getString()) return; this._stringValue = value; this._labelBMFontRenderer.setString(value); @@ -129,7 +129,7 @@ ccui.LabelBMFont = ccui.TextBMFont = ccui.Widget.extend(/** @lends ccui.TextBMFo * Returns the length of TextBMFont's string. * @returns {Number} */ - getStringLength: function(){ + getStringLength: function () { return this._labelBMFontRenderer.getStringLength(); }, @@ -138,8 +138,8 @@ ccui.LabelBMFont = ccui.TextBMFont = ccui.Widget.extend(/** @lends ccui.TextBMFo this._labelBMFontRendererAdaptDirty = true; }, - _adaptRenderers: function(){ - if (this._labelBMFontRendererAdaptDirty){ + _adaptRenderers: function () { + if (this._labelBMFontRendererAdaptDirty) { this._labelBMFontScaleChangedWithSize(); this._labelBMFontRendererAdaptDirty = false; } @@ -150,7 +150,7 @@ ccui.LabelBMFont = ccui.TextBMFont = ccui.Widget.extend(/** @lends ccui.TextBMFo * @override * @returns {cc.Size} */ - getVirtualRendererSize: function(){ + getVirtualRendererSize: function () { return this._labelBMFontRenderer.getContentSize(); }, diff --git a/extensions/ccui/uiwidgets/UIVideoPlayer.js b/extensions/ccui/uiwidgets/UIVideoPlayer.js index afff6fd2a7..664415c258 100644 --- a/extensions/ccui/uiwidgets/UIVideoPlayer.js +++ b/extensions/ccui/uiwidgets/UIVideoPlayer.js @@ -38,14 +38,14 @@ ccui.VideoPlayer = ccui.Widget.extend(/** @lends ccui.VideoPlayer# */{ _playing: false, _stopped: true, - ctor: function(path){ + ctor: function (path) { ccui.Widget.prototype.ctor.call(this); this._EventList = {}; - if(path) + if (path) this.setURL(path); }, - _createRenderCmd: function(){ + _createRenderCmd: function () { return new ccui.VideoPlayer.RenderCmd(this); }, @@ -55,7 +55,7 @@ ccui.VideoPlayer = ccui.Widget.extend(/** @lends ccui.VideoPlayer# */{ * All supported video formats will be added to the video * @param {String} address */ - setURL: function(address){ + setURL: function (address) { this._renderCmd.updateURL(address); }, @@ -63,28 +63,28 @@ ccui.VideoPlayer = ccui.Widget.extend(/** @lends ccui.VideoPlayer# */{ * Get the video path * @returns {String} */ - getURL: function() { + getURL: function () { return this._renderCmd._url; }, /** * Play the video */ - play: function(){ + play: function () { var self = this, video = this._renderCmd._video; - if(video){ + if (video) { this._played = true; video.pause(); - if(this._stopped !== false || this._playing !== false || this._played !== true) + if (this._stopped !== false || this._playing !== false || this._played !== true) video.currentTime = 0; - if(ccui.VideoPlayer._polyfill.autoplayAfterOperation){ - setTimeout(function(){ + if (ccui.VideoPlayer._polyfill.autoplayAfterOperation) { + setTimeout(function () { video.play(); self._playing = true; self._stopped = false; }, 20); - }else{ + } else { video.play(); this._playing = true; this._stopped = false; @@ -95,9 +95,9 @@ ccui.VideoPlayer = ccui.Widget.extend(/** @lends ccui.VideoPlayer# */{ /** * Pause the video */ - pause: function(){ + pause: function () { var video = this._renderCmd._video; - if(video && this._playing === true && this._stopped === false){ + if (video && this._playing === true && this._stopped === false) { video.pause(); this._playing = false; } @@ -106,8 +106,8 @@ ccui.VideoPlayer = ccui.Widget.extend(/** @lends ccui.VideoPlayer# */{ /** * Resume the video */ - resume: function(){ - if(this._stopped === false && this._playing === false && this._played === true){ + resume: function () { + if (this._stopped === false && this._playing === false && this._played === true) { this.play(); } }, @@ -115,17 +115,17 @@ ccui.VideoPlayer = ccui.Widget.extend(/** @lends ccui.VideoPlayer# */{ /** * Stop the video */ - stop: function(){ + stop: function () { var self = this, video = this._renderCmd._video; - if(video){ + if (video) { video.pause(); video.currentTime = 0; this._playing = false; this._stopped = true; } - setTimeout(function(){ + setTimeout(function () { self._dispatchEvent(ccui.VideoPlayer.EventType.STOPPED); }, 0); }, @@ -133,12 +133,12 @@ ccui.VideoPlayer = ccui.Widget.extend(/** @lends ccui.VideoPlayer# */{ * Jump to the specified point in time * @param {Number} sec */ - seekTo: function(sec){ + seekTo: function (sec) { var video = this._renderCmd._video; - if(video){ + if (video) { video.currentTime = sec; - if(ccui.VideoPlayer._polyfill.autoplayAfterOperation && this.isPlaying()){ - setTimeout(function(){ + if (ccui.VideoPlayer._polyfill.autoplayAfterOperation && this.isPlaying()) { + setTimeout(function () { video.play(); }, 20); } @@ -149,9 +149,9 @@ ccui.VideoPlayer = ccui.Widget.extend(/** @lends ccui.VideoPlayer# */{ * Whether the video is playing * @returns {boolean} */ - isPlaying: function(){ - if(ccui.VideoPlayer._polyfill.autoplayAfterOperation && this._playing){ - setTimeout(function(){ + isPlaying: function () { + if (ccui.VideoPlayer._polyfill.autoplayAfterOperation && this._playing) { + setTimeout(function () { video.play(); }, 20); } @@ -161,10 +161,10 @@ ccui.VideoPlayer = ccui.Widget.extend(/** @lends ccui.VideoPlayer# */{ /** * Whether to keep the aspect ratio */ - setKeepAspectRatioEnabled: function(enable){ + setKeepAspectRatioEnabled: function (enable) { cc.log("On the web is always keep the aspect ratio"); }, - isKeepAspectRatioEnabled: function(){ + isKeepAspectRatioEnabled: function () { return false; }, @@ -173,10 +173,10 @@ ccui.VideoPlayer = ccui.Widget.extend(/** @lends ccui.VideoPlayer# */{ * May appear inconsistent in different browsers * @param {boolean} enable */ - setFullScreenEnabled: function(enable){ + setFullScreenEnabled: function (enable) { var video = this._renderCmd._video; - if(video){ - if(enable) + if (video) { + if (enable) cc.screen.requestFullScreen(video); else cc.screen.exitFullScreen(video); @@ -186,7 +186,7 @@ ccui.VideoPlayer = ccui.Widget.extend(/** @lends ccui.VideoPlayer# */{ /** * Determine whether already full screen */ - isFullScreenEnabled: function(){ + isFullScreenEnabled: function () { cc.log("Can't know status"); }, @@ -195,7 +195,7 @@ ccui.VideoPlayer = ccui.Widget.extend(/** @lends ccui.VideoPlayer# */{ * @param {ccui.VideoPlayer.EventType} event * @param {Function} callback */ - setEventListener: function(event, callback){ + setEventListener: function (event, callback) { this._EventList[event] = callback; }, @@ -203,11 +203,11 @@ ccui.VideoPlayer = ccui.Widget.extend(/** @lends ccui.VideoPlayer# */{ * Delete events * @param {ccui.VideoPlayer.EventType} event */ - removeEventListener: function(event){ + removeEventListener: function (event) { this._EventList[event] = null; }, - _dispatchEvent: function(event) { + _dispatchEvent: function (event) { var callback = this._EventList[event]; if (callback) callback.call(this, this, this._renderCmd._video.src); @@ -216,43 +216,40 @@ ccui.VideoPlayer = ccui.Widget.extend(/** @lends ccui.VideoPlayer# */{ /** * Trigger playing events */ - onPlayEvent: function(){ + onPlayEvent: function () { var list = this._EventList[ccui.VideoPlayer.EventType.PLAYING]; - if(list) - for(var i=0; i -1) + if (index > -1) this._items.splice(index, 1); this._onItemListChanged(); @@ -269,7 +265,7 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{ /** * Removes all children from ccui.ListView. */ - removeAllChildren: function(){ + removeAllChildren: function () { this.removeAllChildrenWithCleanup(true); }, @@ -277,7 +273,7 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{ * Removes all children from ccui.ListView and do a cleanup all running actions depending on the cleanup parameter. * @param {Boolean} cleanup */ - removeAllChildrenWithCleanup: function(cleanup){ + removeAllChildrenWithCleanup: function (cleanup) { ccui.ScrollView.prototype.removeAllChildrenWithCleanup.call(this, cleanup); this._items = []; @@ -320,7 +316,7 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{ /** * Removes all items from ccui.ListView. */ - removeAllItems: function(){ + removeAllItems: function () { this.removeAllChildren(); }, @@ -349,7 +345,7 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{ * @returns {Number} the index of item. */ getIndex: function (item) { - if(item == null) + if (item == null) return -1; return this._items.indexOf(item); }, @@ -369,8 +365,7 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{ * Set magnetic type of ListView. * @param {ccui.ListView.MAGNETIC_NONE|ccui.ListView.MAGNETIC_CENTER,ccui.ListView.MAGNETIC_BOTH_END|ccui.ListView.MAGNETIC_LEFT|ccui.ListView.MAGNETIC_RIGHT|ccui.ListView.MAGNETIC_TOP|ccui.ListView.MAGNETIC_BOTTOM} magneticType */ - setMagneticType: function(magneticType) - { + setMagneticType: function (magneticType) { this._magneticType = magneticType; this._onItemListChanged(); this._startMagneticScroll(); @@ -380,8 +375,7 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{ * Get magnetic type of ListView. * @returns {number} */ - getMagneticType: function() - { + getMagneticType: function () { return this._magneticType; }, @@ -389,8 +383,7 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{ * Set magnetic allowed out of boundary. * @param {boolean} magneticAllowedOutOfBoundary */ - setMagneticAllowedOutOfBoundary: function(magneticAllowedOutOfBoundary) - { + setMagneticAllowedOutOfBoundary: function (magneticAllowedOutOfBoundary) { this._magneticAllowedOutOfBoundary = magneticAllowedOutOfBoundary; }, @@ -398,8 +391,7 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{ * Query whether the magnetic out of boundary is allowed. * @returns {boolean} */ - getMagneticAllowedOutOfBoundary: function() - { + getMagneticAllowedOutOfBoundary: function () { return this._magneticAllowedOutOfBoundary; }, @@ -418,7 +410,7 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{ * Returns the margin between each item. * @returns {Number} */ - getItemsMargin:function(){ + getItemsMargin: function () { return this._itemsMargin; }, @@ -443,21 +435,17 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{ ccui.ScrollView.prototype.setDirection.call(this, dir); }, - _getHowMuchOutOfBoundary: function(addition) - { - if(addition === undefined) + _getHowMuchOutOfBoundary: function (addition) { + if (addition === undefined) addition = cc.p(0, 0); - if(!this._magneticAllowedOutOfBoundary || this._items.length === 0) - { + if (!this._magneticAllowedOutOfBoundary || this._items.length === 0) { return ccui.ScrollView.prototype._getHowMuchOutOfBoundary.call(this, addition); } - else if(this._magneticType === ccui.ListView.MAGNETIC_NONE || this._magneticType === ccui.ListView.MAGNETIC_BOTH_END) - { + else if (this._magneticType === ccui.ListView.MAGNETIC_NONE || this._magneticType === ccui.ListView.MAGNETIC_BOTH_END) { return ccui.ScrollView.prototype._getHowMuchOutOfBoundary.call(this, addition); } - else if(addition.x === 0 && addition.y === 0 && !this._outOfBoundaryAmountDirty) - { + else if (addition.x === 0 && addition.y === 0 && !this._outOfBoundaryAmountDirty) { return this._outOfBoundaryAmount; } @@ -472,8 +460,7 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{ var firstItemAdjustment = cc.p(0, 0); var lastItemAdjustment = cc.p(0, 0); - switch (this._magneticType) - { + switch (this._magneticType) { case ccui.ListView.MAGNETIC_CENTER: firstItemAdjustment.x = (contentSize.width - this._items[0].width) / 2; firstItemAdjustment.y = (contentSize.height - this._items[0].height) / 2; @@ -503,55 +490,44 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{ // Calculate the actual amount var outOfBoundaryAmount = cc.p(0, 0); - if(this._innerContainer.getLeftBoundary() + addition.x > leftBoundary) - { + if (this._innerContainer.getLeftBoundary() + addition.x > leftBoundary) { outOfBoundaryAmount.x = leftBoundary - (this._innerContainer.getLeftBoundary() + addition.x); } - else if(this._innerContainer.getRightBoundary() + addition.x < rightBoundary) - { + else if (this._innerContainer.getRightBoundary() + addition.x < rightBoundary) { outOfBoundaryAmount.x = rightBoundary - (this._innerContainer.getRightBoundary() + addition.x); } - if(this._innerContainer.getTopBoundary() + addition.y < topBoundary) - { + if (this._innerContainer.getTopBoundary() + addition.y < topBoundary) { outOfBoundaryAmount.y = topBoundary - (this._innerContainer.getTopBoundary() + addition.y); } - else if(this._innerContainer.getBottomBoundary() + addition.y > bottomBoundary) - { + else if (this._innerContainer.getBottomBoundary() + addition.y > bottomBoundary) { outOfBoundaryAmount.y = bottomBoundary - (this._innerContainer.getBottomBoundary() + addition.y); } - if(addition.x === 0 && addition.y === 0) - { + if (addition.x === 0 && addition.y === 0) { this._outOfBoundaryAmount = outOfBoundaryAmount; this._outOfBoundaryAmountDirty = false; } return outOfBoundaryAmount; }, - _calculateItemPositionWithAnchor: function(item, itemAnchorPoint) - { + _calculateItemPositionWithAnchor: function (item, itemAnchorPoint) { var origin = cc.p(item.getLeftBoundary(), item.getBottomBoundary()); var size = item.getContentSize(); - return cc.p(origin. x + size.width * itemAnchorPoint.x, origin.y + size.height * itemAnchorPoint.y); + return cc.p(origin.x + size.width * itemAnchorPoint.x, origin.y + size.height * itemAnchorPoint.y); }, - _findClosestItem: function(targetPosition, items, itemAnchorPoint, firstIndex, distanceFromFirst, lastIndex, distanceFromLast) - { + _findClosestItem: function (targetPosition, items, itemAnchorPoint, firstIndex, distanceFromFirst, lastIndex, distanceFromLast) { cc.assert(firstIndex >= 0 && lastIndex < items.length && firstIndex <= lastIndex, ""); - if (firstIndex === lastIndex) - { + if (firstIndex === lastIndex) { return items[firstIndex]; } - if (lastIndex - firstIndex === 1) - { - if (distanceFromFirst <= distanceFromLast) - { + if (lastIndex - firstIndex === 1) { + if (distanceFromFirst <= distanceFromLast) { return items[firstIndex]; } - else - { + else { return items[lastIndex]; } } @@ -561,13 +537,11 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{ var itemPosition = this._calculateItemPositionWithAnchor(items[midIndex], itemAnchorPoint); var distanceFromMid = cc.pLength(cc.pSub(targetPosition, itemPosition)); - if (distanceFromFirst <= distanceFromLast) - { + if (distanceFromFirst <= distanceFromLast) { // Left half return this._findClosestItem(targetPosition, items, itemAnchorPoint, firstIndex, distanceFromFirst, midIndex, distanceFromMid); } - else - { + else { // Right half return this._findClosestItem(targetPosition, items, itemAnchorPoint, midIndex, distanceFromMid, lastIndex, distanceFromLast); } @@ -580,10 +554,8 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{ * @param {cc.Point} itemAnchorPoint Specifies an anchor point of each item for position to calculate distance. * @returns {?ccui.Widget} A item instance if list view is not empty. Otherwise, returns null. */ - getClosestItemToPosition: function(targetPosition, itemAnchorPoint) - { - if (this._items.length === 0) - { + getClosestItemToPosition: function (targetPosition, itemAnchorPoint) { + if (this._items.length === 0) { return null; } @@ -608,8 +580,7 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{ * @returns {?ccui.Widget} A item instance if list view is not empty. Otherwise, returns null. */ - getClosestItemToPositionInCurrentView: function(positionRatioInView, itemAnchorPoint) - { + getClosestItemToPositionInCurrentView: function (positionRatioInView, itemAnchorPoint) { // Calculate the target position var contentSize = this.getContentSize(); var targetPosition = cc.pMult(this._innerContainer.getPosition(), -1); @@ -623,8 +594,7 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{ * Query the center item * @returns {?ccui.Widget} A item instance. */ - getCenterItemInCurrentView: function() - { + getCenterItemInCurrentView: function () { return this.getClosestItemToPositionInCurrentView(cc.p(0.5, 0.5), cc.p(0.5, 0.5)); }, @@ -632,10 +602,8 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{ * Query the leftmost item in horizontal list * @returns {?ccui.Widget} A item instance. */ - getLeftmostItemInCurrentView: function() - { - if(this._direction === ccui.ScrollView.DIR_HORIZONTAL) - { + getLeftmostItemInCurrentView: function () { + if (this._direction === ccui.ScrollView.DIR_HORIZONTAL) { return this.getClosestItemToPositionInCurrentView(cc.p(0, 0.5), cc.p(0.5, 0.5)); } @@ -646,10 +614,8 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{ * Query the rightmost item in horizontal list * @returns {?ccui.Widget} A item instance. */ - getRightmostItemInCurrentView: function() - { - if(this._direction === ccui.ScrollView.DIR_HORIZONTAL) - { + getRightmostItemInCurrentView: function () { + if (this._direction === ccui.ScrollView.DIR_HORIZONTAL) { return this.getClosestItemToPositionInCurrentView(cc.p(1, 0.5), cc.p(0.5, 0.5)); } @@ -660,10 +626,8 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{ * Query the topmost item in horizontal list * @returns {?ccui.Widget} A item instance. */ - getTopmostItemInCurrentView: function() - { - if(this._direction === ccui.ScrollView.DIR_VERTICAL) - { + getTopmostItemInCurrentView: function () { + if (this._direction === ccui.ScrollView.DIR_VERTICAL) { return this.getClosestItemToPositionInCurrentView(cc.p(0.5, 1), cc.p(0.5, 0.5)); } @@ -674,18 +638,15 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{ * Query the topmost item in horizontal list * @returns {?ccui.Widget} A item instance. */ - getBottommostItemInCurrentView: function() - { - if(this._direction === ccui.ScrollView.DIR_VERTICAL) - { + getBottommostItemInCurrentView: function () { + if (this._direction === ccui.ScrollView.DIR_VERTICAL) { return this.getClosestItemToPositionInCurrentView(cc.p(0.5, 0), cc.p(0.5, 0.5)); } return null; }, - _calculateItemDestination: function(positionRatioInView, item, itemAnchorPoint) - { + _calculateItemDestination: function (positionRatioInView, item, itemAnchorPoint) { var contentSize = this.getContentSize(); var positionInView = cc.p(0, 0); positionInView.x += contentSize.width * positionRatioInView.x; @@ -695,68 +656,57 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{ return cc.pMult(cc.pSub(itemPosition, positionInView), -1); }, - jumpToBottom: function() - { + jumpToBottom: function () { this.doLayout(); ccui.ScrollView.prototype.jumpToBottom.call(this); }, - jumpToTop: function() - { + jumpToTop: function () { this.doLayout(); ccui.ScrollView.prototype.jumpToTop.call(this); }, - jumpToLeft: function() - { + jumpToLeft: function () { this.doLayout(); ccui.ScrollView.prototype.jumpToLeft.call(this); }, - jumpToRight: function() - { + jumpToRight: function () { this.doLayout(); ccui.ScrollView.prototype.jumpToRight.call(this); }, - jumpToTopLeft: function() - { + jumpToTopLeft: function () { this.doLayout(); ccui.ScrollView.prototype.jumpToTopLeft.call(this); }, - jumpToTopRight: function() - { + jumpToTopRight: function () { this.doLayout(); ccui.ScrollView.prototype.jumpToTopRight.call(this); }, - jumpToBottomLeft: function() - { + jumpToBottomLeft: function () { this.doLayout(); ccui.ScrollView.prototype.jumpToBottomLeft.call(this); }, - jumpToBottomRight: function() - { + jumpToBottomRight: function () { this.doLayout(); ccui.ScrollView.prototype.jumpToBottomRight.call(this); }, - jumpToPercentVertical: function(percent) - { + jumpToPercentVertical: function (percent) { this.doLayout(); ccui.ScrollView.prototype.jumpToPercentVertical.call(this, percent); }, - jumpToPercentHorizontal: function(percent) - { + jumpToPercentHorizontal: function (percent) { this.doLayout(); ccui.ScrollView.prototype.jumpToPercentHorizontal.call(this, percent); }, - jumpToPercentBothDirection: function(percent) - { + jumpToPercentBothDirection: function (percent) { this.doLayout(); ccui.ScrollView.prototype.jumpToPercentBothDirection.call(this, percent); }, @@ -767,19 +717,17 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{ * @param {cc.Point} positionRatioInView Specifies the position with ratio in list view's content size. * @param {cc.Point} itemAnchorPoint Specifies an anchor point of each item for position to calculate distance. */ - jumpToItem: function(itemIndex, positionRatioInView, itemAnchorPoint) - { + jumpToItem: function (itemIndex, positionRatioInView, itemAnchorPoint) { var item = this.getItem(itemIndex); - if(!item) + if (!item) return; this.doLayout(); var destination = this._calculateItemDestination(positionRatioInView, item, itemAnchorPoint); - if(!this.bounceEnabled) - { + if (!this.bounceEnabled) { var delta = cc.pSub(destination, this._innerContainer.getPosition()); var outOfBoundary = this._getHowMuchOutOfBoundary(delta); destination.x += outOfBoundary.x; @@ -796,14 +744,13 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{ * @param {cc.Point} itemAnchorPoint Specifies an anchor point of each item for position to calculate distance. * @param {number} [timeInSec = 1.0] Scroll time */ - scrollToItem: function(itemIndex, positionRatioInView, itemAnchorPoint, timeInSec) - { - if(timeInSec === undefined) + scrollToItem: function (itemIndex, positionRatioInView, itemAnchorPoint, timeInSec) { + if (timeInSec === undefined) timeInSec = 1; var item = this.getItem(itemIndex); - if(!item) + if (!item) return; var destination = this._calculateItemDestination(positionRatioInView, item, itemAnchorPoint); @@ -829,16 +776,15 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{ /** * provides a public _doLayout function for Editor. it calls _doLayout. */ - doLayout: function(){ + doLayout: function () { this._doLayout(); }, - requestDoLayout: function() - { + requestDoLayout: function () { this._refreshViewDirty = true; }, - _doLayout: function(){ + _doLayout: function () { //ccui.Layout.prototype._doLayout.call(this); if (this._refreshViewDirty) { var locItems = this._items; @@ -868,19 +814,19 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{ * Adds callback function called ListView event triggered * @param {Function} selector */ - addEventListener: function(selector){ + addEventListener: function (selector) { this._ccListViewEventCallback = selector; }, _selectedItemEvent: function (event) { var eventEnum = (event === ccui.Widget.TOUCH_BEGAN) ? ccui.ListView.ON_SELECTED_ITEM_START : ccui.ListView.ON_SELECTED_ITEM_END; - if(this._listViewEventSelector){ + if (this._listViewEventSelector) { if (this._listViewEventListener) this._listViewEventSelector.call(this._listViewEventListener, this, eventEnum); else this._listViewEventSelector(this, eventEnum); } - if(this._ccListViewEventCallback) + if (this._ccListViewEventCallback) this._ccListViewEventCallback(this, eventEnum); }, @@ -943,7 +889,7 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{ }, _copySpecialProperties: function (listView) { - if(listView instanceof ccui.ListView){ + if (listView instanceof ccui.ListView) { ccui.ScrollView.prototype._copySpecialProperties.call(this, listView); this.setItemModel(listView._model); this.setItemsMargin(listView._itemsMargin); @@ -954,27 +900,21 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{ } }, - _startAttenuatingAutoScroll: function(deltaMove, initialVelocity) - { + _startAttenuatingAutoScroll: function (deltaMove, initialVelocity) { var adjustedDeltaMove = deltaMove; - if(this._items.length !== 0 && this._magneticType !== ccui.ListView.MAGNETIC_NONE) - { + if (this._items.length !== 0 && this._magneticType !== ccui.ListView.MAGNETIC_NONE) { adjustedDeltaMove = this._flattenVectorByDirection(adjustedDeltaMove); var howMuchOutOfBoundary = this._getHowMuchOutOfBoundary(adjustedDeltaMove); // If the destination is out of boundary, do nothing here. Because it will be handled by bouncing back. - if(howMuchOutOfBoundary.x === 0 && howMuchOutOfBoundary.y === 0 ) - { + if (howMuchOutOfBoundary.x === 0 && howMuchOutOfBoundary.y === 0) { var magType = this._magneticType; - if(magType === ccui.ListView.MAGNETIC_BOTH_END) - { - if(this._direction === ccui.ScrollView.DIR_HORIZONTAL) - { + if (magType === ccui.ListView.MAGNETIC_BOTH_END) { + if (this._direction === ccui.ScrollView.DIR_HORIZONTAL) { magType = (adjustedDeltaMove.x > 0 ? ccui.ListView.MAGNETIC_LEFT : ccui.ListView.MAGNETIC_RIGHT); } - else if(this._direction === ccui.ScrollView.DIR_VERTICAL) - { + else if (this._direction === ccui.ScrollView.DIR_VERTICAL) { magType = (adjustedDeltaMove.y > 0 ? ccui.ListView.MAGNETIC_BOTTOM : ccui.ListView.MAGNETIC_TOP); } } @@ -990,34 +930,37 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{ adjustedDeltaMove = cc.pSub(magneticPosition, itemPosition); } } - ccui.ScrollView.prototype._startAttenuatingAutoScroll.call(this,adjustedDeltaMove, initialVelocity); - }, - - _getAnchorPointByMagneticType: function(magneticType) - { - switch(magneticType) - { - case ccui.ListView.MAGNETIC_NONE: return cc.p(0, 0); - case ccui.ListView.MAGNETIC_BOTH_END: return cc.p(0, 1); - case ccui.ListView.MAGNETIC_CENTER: return cc.p(0.5, 0.5); - case ccui.ListView.MAGNETIC_LEFT: return cc.p(0, 0.5); - case ccui.ListView.MAGNETIC_RIGHT: return cc.p(1, 0.5); - case ccui.ListView.MAGNETIC_TOP: return cc.p(0.5, 1); - case ccui.ListView.MAGNETIC_BOTTOM: return cc.p(0.5, 0); + ccui.ScrollView.prototype._startAttenuatingAutoScroll.call(this, adjustedDeltaMove, initialVelocity); + }, + + _getAnchorPointByMagneticType: function (magneticType) { + switch (magneticType) { + case ccui.ListView.MAGNETIC_NONE: + return cc.p(0, 0); + case ccui.ListView.MAGNETIC_BOTH_END: + return cc.p(0, 1); + case ccui.ListView.MAGNETIC_CENTER: + return cc.p(0.5, 0.5); + case ccui.ListView.MAGNETIC_LEFT: + return cc.p(0, 0.5); + case ccui.ListView.MAGNETIC_RIGHT: + return cc.p(1, 0.5); + case ccui.ListView.MAGNETIC_TOP: + return cc.p(0.5, 1); + case ccui.ListView.MAGNETIC_BOTTOM: + return cc.p(0.5, 0); } return cc.p(0, 0); }, - _startMagneticScroll: function() - { - if(this._items.length === 0 || this._magneticType === ccui.ListView.MAGNETIC_NONE) - { + _startMagneticScroll: function () { + if (this._items.length === 0 || this._magneticType === ccui.ListView.MAGNETIC_NONE) { return; } // Find the closest item - var magneticAnchorPoint =this._getAnchorPointByMagneticType(this._magneticType); + var magneticAnchorPoint = this._getAnchorPointByMagneticType(this._magneticType); var magneticPosition = cc.pMult(this._innerContainer.getPosition(), -1); magneticPosition.x += this.width * magneticAnchorPoint.x; magneticPosition.y += this.height * magneticAnchorPoint.y; diff --git a/extensions/ccui/uiwidgets/scroll-widget/UIPageView.js b/extensions/ccui/uiwidgets/scroll-widget/UIPageView.js index 6c48c6e743..e37853778a 100644 --- a/extensions/ccui/uiwidgets/scroll-widget/UIPageView.js +++ b/extensions/ccui/uiwidgets/scroll-widget/UIPageView.js @@ -38,7 +38,7 @@ ccui.PageView = ccui.ListView.extend(/** @lends ccui.PageView# */{ _childFocusCancelOffset: 0, _pageViewEventListener: null, _pageViewEventSelector: null, - _className:"PageView", + _className: "PageView", _indicator: null, _indicatorPositionAsAnchorPoint: null, @@ -77,8 +77,7 @@ ccui.PageView = ccui.ListView.extend(/** @lends ccui.PageView# */{ * Insert a page into the end of PageView. * @param {ccui.Widget} page Page to be inserted. */ - addPage: function(page) - { + addPage: function (page) { this.pushBackCustomItem(page); }, @@ -87,8 +86,7 @@ ccui.PageView = ccui.ListView.extend(/** @lends ccui.PageView# */{ * @param {ccui.Widget} page Page to be inserted. * @param {number} idx A given index. */ - insertPage: function(page, idx) - { + insertPage: function (page, idx) { this.insertCustomItem(page, idx); }, @@ -111,7 +109,7 @@ ccui.PageView = ccui.ListView.extend(/** @lends ccui.PageView# */{ /** * Removes all pages from PageView */ - removeAllPages: function(){ + removeAllPages: function () { this.removeAllItems(); }, @@ -132,14 +130,13 @@ ccui.PageView = ccui.ListView.extend(/** @lends ccui.PageView# */{ }, - _doLayout: function(){ + _doLayout: function () { if (!this._refreshViewDirty) return; ccui.ListView.prototype._doLayout.call(this); - if(this._indicator) - { + if (this._indicator) { var index = this.getIndex(this.getCenterItemInCurrentView()); this._indicator.indicate(index); } @@ -151,20 +148,16 @@ ccui.PageView = ccui.ListView.extend(/** @lends ccui.PageView# */{ * Changes scroll direction of ccui.PageView. * @param {ccui.ScrollView.DIR_NONE | ccui.ScrollView.DIR_VERTICAL | ccui.ScrollView.DIR_HORIZONTAL | ccui.ScrollView.DIR_BOTH} direction */ - setDirection: function(direction) - { + setDirection: function (direction) { ccui.ListView.prototype.setDirection.call(this, direction); - if(direction === ccui.ScrollView.DIR_HORIZONTAL) - { + if (direction === ccui.ScrollView.DIR_HORIZONTAL) { this._indicatorPositionAsAnchorPoint = cc.p(0.5, 0.1); } - else if(direction === ccui.ScrollView.DIR_VERTICAL) - { + else if (direction === ccui.ScrollView.DIR_VERTICAL) { this._indicatorPositionAsAnchorPoint = cc.p(0.1, 0.5); } - if(this._indicator) - { + if (this._indicator) { this._indicator.setDirection(direction); this._refreshIndicatorPosition(); } @@ -176,7 +169,7 @@ ccui.PageView = ccui.ListView.extend(/** @lends ccui.PageView# */{ * @param threshold * @deprecated Since v3.9, this method has no effect. */ - setCustomScrollThreshold: function(threshold){ + setCustomScrollThreshold: function (threshold) { }, @@ -185,7 +178,7 @@ ccui.PageView = ccui.ListView.extend(/** @lends ccui.PageView# */{ * @since v3.2 * @deprecated Since v3.9, this method always returns 0. */ - getCustomScrollThreshold: function(){ + getCustomScrollThreshold: function () { return 0; }, @@ -194,52 +187,44 @@ ccui.PageView = ccui.ListView.extend(/** @lends ccui.PageView# */{ * @since v3.2 * @deprecated Since v3.9, this method has no effect. */ - setUsingCustomScrollThreshold: function(flag){ + setUsingCustomScrollThreshold: function (flag) { }, /** * Queries whether we are using user defined scroll page threshold or not * @deprecated Since v3.9, this method always returns false. */ - isUsingCustomScrollThreshold: function(){ + isUsingCustomScrollThreshold: function () { return false; }, - _moveInnerContainer: function(deltaMove, canStartBounceBack) - { + _moveInnerContainer: function (deltaMove, canStartBounceBack) { ccui.ListView.prototype._moveInnerContainer.call(this, deltaMove, canStartBounceBack); this._curPageIdx = this.getIndex(this.getCenterItemInCurrentView()); - if(this._indicator) - { + if (this._indicator) { this._indicator.indicate(this._curPageIdx); } }, - _onItemListChanged: function() - { + _onItemListChanged: function () { ccui.ListView.prototype._onItemListChanged.call(this); - if(this._indicator) - { + if (this._indicator) { this._indicator.reset(this._items.length); } }, - _onSizeChanged: function() - { + _onSizeChanged: function () { ccui.ListView.prototype._onSizeChanged.call(this); this._refreshIndicatorPosition(); }, - _remedyLayoutParameter: function (item) - { + _remedyLayoutParameter: function (item) { item.setContentSize(this.getContentSize()); ccui.ListView.prototype._remedyLayoutParameter.call(this, item); }, - - _refreshIndicatorPosition: function() - { - if(this._indicator) - { + + _refreshIndicatorPosition: function () { + if (this._indicator) { var contentSize = this.getContentSize(); var posX = contentSize.width * this._indicatorPositionAsAnchorPoint.x; var posY = contentSize.height * this._indicatorPositionAsAnchorPoint.y; @@ -257,12 +242,10 @@ ccui.PageView = ccui.ListView.extend(/** @lends ccui.PageView# */{ var touchMoveVelocity = this._flattenVectorByDirection(this._calculateTouchMoveVelocity()); var INERTIA_THRESHOLD = 500; - if(cc.pLength(touchMoveVelocity) < INERTIA_THRESHOLD) - { + if (cc.pLength(touchMoveVelocity) < INERTIA_THRESHOLD) { this._startMagneticScroll(); } - else - { + else { // Handle paging by inertia force. var currentPage = this.getItem(this._curPageIdx); var destination = this._calculateItemDestination(cc.p(0.5, 0.5), currentPage, cc.p(0.5, 0.5)); @@ -271,18 +254,14 @@ ccui.PageView = ccui.ListView.extend(/** @lends ccui.PageView# */{ // If the direction of displacement to current page and the direction of touch are same, just start magnetic scroll to the current page. // Otherwise, move to the next page of touch direction. - if(touchMoveVelocity.x * deltaToCurrentPage.x > 0 || touchMoveVelocity.y * deltaToCurrentPage.y > 0) - { + if (touchMoveVelocity.x * deltaToCurrentPage.x > 0 || touchMoveVelocity.y * deltaToCurrentPage.y > 0) { this._startMagneticScroll(); } - else - { - if(touchMoveVelocity.x < 0 || touchMoveVelocity.y > 0) - { + else { + if (touchMoveVelocity.x < 0 || touchMoveVelocity.y > 0) { ++this._curPageIdx; } - else - { + else { --this._curPageIdx; } this._curPageIdx = Math.min(this._curPageIdx, this._items.length); @@ -293,19 +272,18 @@ ccui.PageView = ccui.ListView.extend(/** @lends ccui.PageView# */{ }, - _getAutoScrollStopEpsilon: function() - { + _getAutoScrollStopEpsilon: function () { return 0.001; }, _pageTurningEvent: function () { - if(this._pageViewEventSelector){ + if (this._pageViewEventSelector) { if (this._pageViewEventListener) this._pageViewEventSelector.call(this._pageViewEventListener, this, ccui.PageView.EVENT_TURNING); else this._pageViewEventSelector(this, ccui.PageView.EVENT_TURNING); } - if(this._ccEventCallback) + if (this._ccEventCallback) this._ccEventCallback(this, ccui.PageView.EVENT_TURNING); }, @@ -320,9 +298,9 @@ ccui.PageView = ccui.ListView.extend(/** @lends ccui.PageView# */{ this._pageViewEventListener = target; }, - addEventListener: function(selector){ - this._ccEventCallback = function(ref, eventType) { - if(eventType == ccui.ScrollView.EVENT_AUTOSCROLL_ENDED) + addEventListener: function (selector) { + this._ccEventCallback = function (ref, eventType) { + if (eventType == ccui.ScrollView.EVENT_AUTOSCROLL_ENDED) selector(this, eventType) }; }, @@ -332,8 +310,7 @@ ccui.PageView = ccui.ListView.extend(/** @lends ccui.PageView# */{ * This is the different between scrollToPage. * @param {number} index A given index in PageView. Index start from 0 to pageCount -1. */ - setCurrentPageIndex: function(index) - { + setCurrentPageIndex: function (index) { this.jumpToItem(index, cc.p(0.5, 0.5), cc.p(0.5, 0.5)); }, @@ -343,8 +320,7 @@ ccui.PageView = ccui.ListView.extend(/** @lends ccui.PageView# */{ * @param {number} index A given index in PageView. Index start from 0 to pageCount -1. * @deprecated since v3.9, this is deprecated. Use `setCurrentPageIndex()` instead. */ - setCurPageIndex: function(index) - { + setCurPageIndex: function (index) { this.setCurrentPageIndex(index); }, @@ -370,7 +346,7 @@ ccui.PageView = ccui.ListView.extend(/** @lends ccui.PageView# */{ * Returns all pages of PageView * @returns {Array} */ - getPages:function(){ + getPages: function () { return this.getItems(); }, @@ -379,7 +355,7 @@ ccui.PageView = ccui.ListView.extend(/** @lends ccui.PageView# */{ * @param {Number} index * @returns {ccui.Layout} */ - getPage: function(index){ + getPage: function (index) { return this.getItem(index); }, @@ -416,20 +392,16 @@ ccui.PageView = ccui.ListView.extend(/** @lends ccui.PageView# */{ * Toggle page indicator enabled. * @param {boolean} enabled True if enable page indicator, false otherwise. */ - setIndicatorEnabled: function(enabled) - { - if(enabled == (this._indicator !== null)) - { + setIndicatorEnabled: function (enabled) { + if (enabled == (this._indicator !== null)) { return; } - if(!enabled) - { + if (!enabled) { this.removeProtectedChild(this._indicator); this._indicator = null; } - else - { + else { this._indicator = new ccui.PageViewIndicator(); this._indicator.setDirection(this.getDirection()); this.addProtectedChild(this._indicator, 10000); @@ -442,8 +414,7 @@ ccui.PageView = ccui.ListView.extend(/** @lends ccui.PageView# */{ * Query page indicator state. * @returns {boolean} True if page indicator is enabled, false otherwise. */ - getIndicatorEnabled: function() - { + getIndicatorEnabled: function () { return this._indicator !== null; }, @@ -451,8 +422,7 @@ ccui.PageView = ccui.ListView.extend(/** @lends ccui.PageView# */{ * Set the page indicator's position using anchor point. * @param {cc.Point} positionAsAnchorPoint The position as anchor point. */ - setIndicatorPositionAsAnchorPoint: function(positionAsAnchorPoint) - { + setIndicatorPositionAsAnchorPoint: function (positionAsAnchorPoint) { this._indicatorPositionAsAnchorPoint = positionAsAnchorPoint; this._refreshIndicatorPosition(); }, @@ -461,8 +431,7 @@ ccui.PageView = ccui.ListView.extend(/** @lends ccui.PageView# */{ * Get the page indicator's position as anchor point. * @returns {cc.Point} */ - getIndicatorPositionAsAnchorPoint: function() - { + getIndicatorPositionAsAnchorPoint: function () { return this._indicatorPositionAsAnchorPoint; }, @@ -470,10 +439,8 @@ ccui.PageView = ccui.ListView.extend(/** @lends ccui.PageView# */{ * Set the page indicator's position in page view. * @param {cc.Point} position The position in page view */ - setIndicatorPosition: function(position) - { - if(this._indicator) - { + setIndicatorPosition: function (position) { + if (this._indicator) { var contentSize = this.getContentSize(); this._indicatorPositionAsAnchorPoint.x = position.x / contentSize.width; this._indicatorPositionAsAnchorPoint.y = position.y / contentSize.height; @@ -485,8 +452,7 @@ ccui.PageView = ccui.ListView.extend(/** @lends ccui.PageView# */{ * Get the page indicator's position. * @returns {cc.Point} */ - getIndicatorPosition: function() - { + getIndicatorPosition: function () { cc.assert(this._indicator !== null, ""); return this._indicator.getPosition(); }, @@ -495,10 +461,8 @@ ccui.PageView = ccui.ListView.extend(/** @lends ccui.PageView# */{ * Set space between page indicator's index nodes. * @param {number} spaceBetweenIndexNodes Space between nodes in pixel. */ - setIndicatorSpaceBetweenIndexNodes: function(spaceBetweenIndexNodes) - { - if(this._indicator) - { + setIndicatorSpaceBetweenIndexNodes: function (spaceBetweenIndexNodes) { + if (this._indicator) { this._indicator.setSpaceBetweenIndexNodes(spaceBetweenIndexNodes); } }, @@ -507,8 +471,7 @@ ccui.PageView = ccui.ListView.extend(/** @lends ccui.PageView# */{ * Get the space between page indicator's index nodes. * @returns {number} */ - getIndicatorSpaceBetweenIndexNodes: function() - { + getIndicatorSpaceBetweenIndexNodes: function () { cc.assert(this._indicator !== null, ""); return this._indicator.getSpaceBetweenIndexNodes(); }, @@ -517,10 +480,8 @@ ccui.PageView = ccui.ListView.extend(/** @lends ccui.PageView# */{ * Set color of page indicator's selected index. * @param {cc.Color} color Color for indicator */ - setIndicatorSelectedIndexColor: function(color) - { - if(this._indicator) - { + setIndicatorSelectedIndexColor: function (color) { + if (this._indicator) { this._indicator.setSelectedIndexColor(color); } }, @@ -529,8 +490,7 @@ ccui.PageView = ccui.ListView.extend(/** @lends ccui.PageView# */{ * Get the color of page indicator's selected index. * @returns {cc.Color} */ - getIndicatorSelectedIndexColor: function() - { + getIndicatorSelectedIndexColor: function () { cc.assert(this._indicator !== null, ""); return this._indicator.getSelectedIndexColor(); }, @@ -539,10 +499,8 @@ ccui.PageView = ccui.ListView.extend(/** @lends ccui.PageView# */{ * Set color of page indicator's index nodes. * @param {cc.Color} color Color for indicator */ - setIndicatorIndexNodesColor: function(color) - { - if(this._indicator) - { + setIndicatorIndexNodesColor: function (color) { + if (this._indicator) { this._indicator.setIndexNodesColor(color); } }, @@ -551,8 +509,7 @@ ccui.PageView = ccui.ListView.extend(/** @lends ccui.PageView# */{ * Get the color of page indicator's index nodes. * @returns {cc.Color} */ - getIndicatorIndexNodesColor: function() - { + getIndicatorIndexNodesColor: function () { cc.assert(this._indicator !== null, ""); return this._indicator.getIndexNodesColor(); }, @@ -561,10 +518,8 @@ ccui.PageView = ccui.ListView.extend(/** @lends ccui.PageView# */{ * Set scale of page indicator's index nodes. * @param {Number} scale Scale for indicator */ - setIndicatorIndexNodesScale: function(indexNodesScale) - { - if(this._indicator) - { + setIndicatorIndexNodesScale: function (indexNodesScale) { + if (this._indicator) { this._indicator.setIndexNodesScale(indexNodesScale); this._indicator.indicate(this._curPageIdx); } @@ -574,8 +529,7 @@ ccui.PageView = ccui.ListView.extend(/** @lends ccui.PageView# */{ * Get the scale of page indicator's index nodes. * @returns {Number} */ - getIndicatorIndexNodesScale: function() - { + getIndicatorIndexNodesScale: function () { cc.assert(this._indicator !== null, ""); return this._indicator.getIndexNodesScale(); }, @@ -585,10 +539,8 @@ ccui.PageView = ccui.ListView.extend(/** @lends ccui.PageView# */{ * @param {String} texName * @param {ccui.Widget.LOCAL_TEXTURE | ccui.Widget.PLIST_TEXTURE} [texType = ccui.Widget.LOCAL_TEXTURE] */ - setIndicatorIndexNodesTexture: function(texName, texType) - { - if(this._indicator) - { + setIndicatorIndexNodesTexture: function (texName, texType) { + if (this._indicator) { this._indicator.setIndexNodesTexture(texName, texType); this._indicator.indicate(this._curPageIdx); } diff --git a/extensions/ccui/uiwidgets/scroll-widget/UIPageViewIndicator.js b/extensions/ccui/uiwidgets/scroll-widget/UIPageViewIndicator.js index 4ffb42b51d..8044ba2269 100644 --- a/extensions/ccui/uiwidgets/scroll-widget/UIPageViewIndicator.js +++ b/extensions/ccui/uiwidgets/scroll-widget/UIPageViewIndicator.js @@ -67,8 +67,7 @@ ccui.PageViewIndicator = ccui.ProtectedNode.extend(/** @lends ccui.PageViewIndic * Sets direction of indicator * @param {ccui.ScrollView.DIR_NONE | ccui.ScrollView.DIR_VERTICAL | ccui.ScrollView.DIR_HORIZONTAL | ccui.ScrollView.DIR_BOTH} direction */ - setDirection: function(direction) - { + setDirection: function (direction) { this._direction = direction; this._rearrange(); }, @@ -77,14 +76,11 @@ ccui.PageViewIndicator = ccui.ProtectedNode.extend(/** @lends ccui.PageViewIndic * resets indicator with new page count. * @param {number} numberOfTotalPages */ - reset: function(numberOfTotalPages) - { - while(this._indexNodes.length < numberOfTotalPages) - { + reset: function (numberOfTotalPages) { + while (this._indexNodes.length < numberOfTotalPages) { this._increaseNumberOfPages(); } - while(this._indexNodes.length > numberOfTotalPages) - { + while (this._indexNodes.length > numberOfTotalPages) { this._decreaseNumberOfPages(); } this._rearrange(); @@ -95,19 +91,15 @@ ccui.PageViewIndicator = ccui.ProtectedNode.extend(/** @lends ccui.PageViewIndic * Indicates node by index * @param {number} index */ - indicate: function(index) - { - if (index < 0 || index >= this._indexNodes.length) - { + indicate: function (index) { + if (index < 0 || index >= this._indexNodes.length) { return; } this._currentIndexNode.setPosition(this._indexNodes[index].getPosition()); }, - _rearrange: function() - { - if(this._indexNodes.length === 0) - { + _rearrange: function () { + if (this._indexNodes.length === 0) { return; } @@ -121,15 +113,12 @@ ccui.PageViewIndicator = ccui.ProtectedNode.extend(/** @lends ccui.PageViewIndic var totalSizeValue = sizeValue * numberOfItems + this._spaceBetweenIndexNodes * (numberOfItems - 1); var posValue = -(totalSizeValue / 2) + (sizeValue / 2); - for(var i = 0; i < this._indexNodes.length; ++i) - { + for (var i = 0; i < this._indexNodes.length; ++i) { var position; - if(horizontal) - { + if (horizontal) { position = cc.p(posValue, indexNodeSize.height / 2.0); } - else - { + else { position = cc.p(indexNodeSize.width / 2.0, -posValue); } this._indexNodes[i].setPosition(position); @@ -141,10 +130,8 @@ ccui.PageViewIndicator = ccui.ProtectedNode.extend(/** @lends ccui.PageViewIndic * Sets space between index nodes. * @param {number} spaceBetweenIndexNodes */ - setSpaceBetweenIndexNodes: function(spaceBetweenIndexNodes) - { - if(this._spaceBetweenIndexNodes === spaceBetweenIndexNodes) - { + setSpaceBetweenIndexNodes: function (spaceBetweenIndexNodes) { + if (this._spaceBetweenIndexNodes === spaceBetweenIndexNodes) { return; } this._spaceBetweenIndexNodes = spaceBetweenIndexNodes; @@ -155,8 +142,7 @@ ccui.PageViewIndicator = ccui.ProtectedNode.extend(/** @lends ccui.PageViewIndic * Gets space between index nodes. * @returns {number} */ - getSpaceBetweenIndexNodes: function() - { + getSpaceBetweenIndexNodes: function () { return this._spaceBetweenIndexNodes; }, @@ -164,8 +150,7 @@ ccui.PageViewIndicator = ccui.ProtectedNode.extend(/** @lends ccui.PageViewIndic * Sets color of selected index node * @param {cc.Color} color */ - setSelectedIndexColor: function(color) - { + setSelectedIndexColor: function (color) { this._currentIndexNode.setColor(color); }, @@ -173,8 +158,7 @@ ccui.PageViewIndicator = ccui.ProtectedNode.extend(/** @lends ccui.PageViewIndic * Gets color of selected index node * @returns {cc.Color} */ - getSelectedIndexColor: function() - { + getSelectedIndexColor: function () { return this._currentIndexNode.getColor(); }, @@ -182,12 +166,10 @@ ccui.PageViewIndicator = ccui.ProtectedNode.extend(/** @lends ccui.PageViewIndic * Sets color of index nodes * @param {cc.Color} indexNodesColor */ - setIndexNodesColor: function(indexNodesColor) - { + setIndexNodesColor: function (indexNodesColor) { this._indexNodesColor = indexNodesColor; - for(var i = 0 ; i < this._indexNodes.length; ++i) - { + for (var i = 0; i < this._indexNodes.length; ++i) { this._indexNodes[i].setColor(indexNodesColor); } }, @@ -196,8 +178,7 @@ ccui.PageViewIndicator = ccui.ProtectedNode.extend(/** @lends ccui.PageViewIndic * Gets color of index nodes * @returns {cc.Color} */ - getIndexNodesColor: function() - { + getIndexNodesColor: function () { var locRealColor = this._indexNodesColor; return cc.color(locRealColor.r, locRealColor.g, locRealColor.b, locRealColor.a); }, @@ -206,19 +187,16 @@ ccui.PageViewIndicator = ccui.ProtectedNode.extend(/** @lends ccui.PageViewIndic * Sets scale of index nodes * @param {Number} indexNodesScale */ - setIndexNodesScale: function(indexNodesScale) - { - if(this._indexNodesScale === indexNodesScale) - { + setIndexNodesScale: function (indexNodesScale) { + if (this._indexNodesScale === indexNodesScale) { return; } this._indexNodesScale = indexNodesScale; this._currentIndexNode.setScale(indexNodesScale); - for(var i = 0 ; i < this._indexNodes.length; ++i) - { - this._indexNodes[i].setScale(this,_indexNodesScale); + for (var i = 0; i < this._indexNodes.length; ++i) { + this._indexNodes[i].setScale(this, _indexNodesScale); } this._rearrange(); @@ -228,8 +206,7 @@ ccui.PageViewIndicator = ccui.ProtectedNode.extend(/** @lends ccui.PageViewIndic * Gets scale of index nodes * @returns {Number} */ - getIndexNodesScale: function() - { + getIndexNodesScale: function () { return this._indexNodesScale; }, @@ -238,28 +215,24 @@ ccui.PageViewIndicator = ccui.ProtectedNode.extend(/** @lends ccui.PageViewIndic * @param {String} texName * @param {ccui.Widget.LOCAL_TEXTURE | ccui.Widget.PLIST_TEXTURE} [texType = ccui.Widget.LOCAL_TEXTURE] */ - setIndexNodesTexture: function(texName, texType) - { - if(texType === undefined) + setIndexNodesTexture: function (texName, texType) { + if (texType === undefined) texType = ccui.Widget.LOCAL_TEXTURE; this._useDefaultTexture = false; this._indexNodesTextureFile = texName; this._indexNodesTexType = texType; - switch (texType) - { + switch (texType) { case ccui.Widget.LOCAL_TEXTURE: this._currentIndexNode.setTexture(texName); - for(var i = 0 ; i < this._indexNodes.length; ++i) - { + for (var i = 0; i < this._indexNodes.length; ++i) { this._indexNodes[i].setTexture(texName); } break; case ccui.Widget.PLIST_TEXTURE: this._currentIndexNode.setSpriteFrame(texName); - for(var i = 0 ; i < this._indexNodes.length; ++i) - { + for (var i = 0; i < this._indexNodes.length; ++i) { this._indexNodes[i].setSpriteFrame(texName); } break; @@ -270,19 +243,15 @@ ccui.PageViewIndicator = ccui.ProtectedNode.extend(/** @lends ccui.PageViewIndic this._rearrange(); }, - _increaseNumberOfPages: function() - { + _increaseNumberOfPages: function () { var indexNode; - if(this._useDefaultTexture) - { + if (this._useDefaultTexture) { indexNode = ccui.helper._createSpriteFromBase64(ccui.PageViewIndicator.CIRCLE_IMAGE, ccui.PageViewIndicator.CIRCLE_IMAGE_KEY); } - else - { + else { indexNode = new cc.Sprite(); - switch (this._indexNodesTexType) - { + switch (this._indexNodesTexType) { case ccui.Widget.LOCAL_TEXTURE: indexNode.initWithFile(this._indexNodesTextureFile); break; @@ -301,10 +270,8 @@ ccui.PageViewIndicator = ccui.ProtectedNode.extend(/** @lends ccui.PageViewIndic this._indexNodes.push(indexNode); }, - _decreaseNumberOfPages: function() - { - if(this._indexNodes.length === 0) - { + _decreaseNumberOfPages: function () { + if (this._indexNodes.length === 0) { return; } this.removeProtectedChild(this._indexNodes[0]); @@ -314,10 +281,8 @@ ccui.PageViewIndicator = ccui.ProtectedNode.extend(/** @lends ccui.PageViewIndic /** * Removes all index nodes. */ - clear: function() - { - for(var i = 0; i < this._indexNodes.length; ++i) - { + clear: function () { + for (var i = 0; i < this._indexNodes.length; ++i) { this.removeProtectedChild(this._indexNodes[i]); } this._indexNodes.length = 0; diff --git a/extensions/ccui/uiwidgets/scroll-widget/UIScrollView.js b/extensions/ccui/uiwidgets/scroll-widget/UIScrollView.js index 0a71cdf1a3..21030376b7 100644 --- a/extensions/ccui/uiwidgets/scroll-widget/UIScrollView.js +++ b/extensions/ccui/uiwidgets/scroll-widget/UIScrollView.js @@ -47,12 +47,12 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{ _touchMoveDisplacements: null, _touchMoveTimeDeltas: null, _touchMovePreviousTimestamp: 0, - _touchTotalTimeThreshold : 0.5, + _touchTotalTimeThreshold: 0.5, _autoScrolling: false, _autoScrollTargetDelta: null, _autoScrollAttenuate: true, - _autoScrollStartPosition : null, + _autoScrollStartPosition: null, _autoScrollTotalTime: 0, _autoScrollAccumulatedTime: 0, _autoScrollCurrentlyOutOfBoundary: false, @@ -144,7 +144,7 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{ * @param {ccui.Widget} current the current focused widget * @returns {ccui.Widget} */ - findNextFocusedWidget: function(direction, current){ + findNextFocusedWidget: function (direction, current) { if (this.getLayoutType() === ccui.Layout.LINEAR_VERTICAL || this.getLayoutType() === ccui.Layout.LINEAR_HORIZONTAL) { return this._innerContainer.findNextFocusedWidget(direction, current); @@ -156,7 +156,7 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{ ccui.Layout.prototype._initRenderer.call(this); this._innerContainer = new ccui.Layout(); - this._innerContainer.setColor(cc.color(255,255,255)); + this._innerContainer.setColor(cc.color(255, 255, 255)); this._innerContainer.setOpacity(255); this._innerContainer.setCascadeColorEnabled(true); this._innerContainer.setCascadeOpacityEnabled(true); @@ -164,8 +164,8 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{ this.addProtectedChild(this._innerContainer, 1, 1); }, - _createRenderCmd: function(){ - if(cc._renderType === cc.game.RENDER_TYPE_WEBGL) + _createRenderCmd: function () { + if (cc._renderType === cc.game.RENDER_TYPE_WEBGL) return new ccui.ScrollView.WebGLRenderCmd(this); else return new ccui.ScrollView.CanvasRenderCmd(this); @@ -193,7 +193,7 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{ * @param {cc.Size} size inner container size. */ setInnerContainerSize: function (size) { - var innerContainer = this._innerContainer, + var innerContainer = this._innerContainer, locSize = this._contentSize, innerSizeWidth = locSize.width, innerSizeHeight = locSize.height; @@ -283,23 +283,18 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{ * * @param {cc.Point} position Inner container position. */ - setInnerContainerPosition: function(position) - { - if(position.x === this._innerContainer.getPositionX() && position.y === this._innerContainer.getPositionY()) - { + setInnerContainerPosition: function (position) { + if (position.x === this._innerContainer.getPositionX() && position.y === this._innerContainer.getPositionY()) { return; } this._innerContainer.setPosition(position); this._outOfBoundaryAmountDirty = true; // Process bouncing events - if(this.bounceEnabled) - { - for(var _direction = ccui.ScrollView.MOVEDIR_TOP; _direction < ccui.ScrollView.MOVEDIR_RIGHT; ++_direction) - { - if(this._isOutOfBoundary(_direction)) - { - this._processScrollEvent(_direction, true); + if (this.bounceEnabled) { + for (var _direction = ccui.ScrollView.MOVEDIR_TOP; _direction < ccui.ScrollView.MOVEDIR_RIGHT; ++_direction) { + if (this._isOutOfBoundary(_direction)) { + this._processScrollEvent(_direction, true); } } } @@ -312,8 +307,7 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{ * * @return The inner container position. */ - getInnerContainerPosition: function() - { + getInnerContainerPosition: function () { return this._innerContainer.getPosition(); }, @@ -334,7 +328,7 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{ }, _isInContainer: function (widget) { - if(!this._clippingEnabled) + if (!this._clippingEnabled) return true; var wPos = widget._position, wSize = widget._contentSize, @@ -359,9 +353,9 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{ updateChildren: function () { var child, i, l; var childrenArray = this._innerContainer._children; - for(i = 0, l = childrenArray.length; i < l; i++) { + for (i = 0, l = childrenArray.length; i < l; i++) { child = childrenArray[i]; - if(child._inViewRect === true && this._isInContainer(child) === false) + if (child._inViewRect === true && this._isInContainer(child) === false) child._inViewRect = false; else if (child._inViewRect === false && this._isInContainer(child) === true) child._inViewRect = true; @@ -375,9 +369,9 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{ * @returns {boolean} */ addChild: function (widget, zOrder, tag) { - if(!widget) + if (!widget) return false; - if(this._isInContainer(widget) === false) + if (this._isInContainer(widget) === false) widget._inViewRect = false; zOrder = zOrder || widget.getLocalZOrder(); tag = tag || widget.getTag(); @@ -395,7 +389,7 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{ * Removes all children. * @param {Boolean} cleanup */ - removeAllChildrenWithCleanup: function(cleanup){ + removeAllChildrenWithCleanup: function (cleanup) { this._innerContainer.removeAllChildrenWithCleanup(cleanup); }, @@ -444,59 +438,48 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{ return this._innerContainer.getChildByName(name); }, - _flattenVectorByDirection: function(vector) - { - var result = cc.p(0 ,0); + _flattenVectorByDirection: function (vector) { + var result = cc.p(0, 0); result.x = (this._direction === ccui.ScrollView.DIR_VERTICAL ? 0 : vector.x); result.y = (this._direction === ccui.ScrollView.DIR_HORIZONTAL ? 0 : vector.y); return result; }, - _getHowMuchOutOfBoundary: function(addition) - { - if(addition === undefined) + _getHowMuchOutOfBoundary: function (addition) { + if (addition === undefined) addition = cc.p(0, 0); - if(addition.x === 0 && addition.y === 0 && !this._outOfBoundaryAmountDirty) - { + if (addition.x === 0 && addition.y === 0 && !this._outOfBoundaryAmountDirty) { return this._outOfBoundaryAmount; } var outOfBoundaryAmount = cc.p(0, 0); - if(this._innerContainer.getLeftBoundary() + addition.x > this._leftBoundary) - { + if (this._innerContainer.getLeftBoundary() + addition.x > this._leftBoundary) { outOfBoundaryAmount.x = this._leftBoundary - (this._innerContainer.getLeftBoundary() + addition.x); } - else if(this._innerContainer.getRightBoundary() + addition.x < this._rightBoundary) - { + else if (this._innerContainer.getRightBoundary() + addition.x < this._rightBoundary) { outOfBoundaryAmount.x = this._rightBoundary - (this._innerContainer.getRightBoundary() + addition.x); } - if(this._innerContainer.getTopBoundary() + addition.y < this._topBoundary) - { + if (this._innerContainer.getTopBoundary() + addition.y < this._topBoundary) { outOfBoundaryAmount.y = this._topBoundary - (this._innerContainer.getTopBoundary() + addition.y); } - else if(this._innerContainer.getBottomBoundary() + addition.y > this._bottomBoundary) - { + else if (this._innerContainer.getBottomBoundary() + addition.y > this._bottomBoundary) { outOfBoundaryAmount.y = this._bottomBoundary - (this._innerContainer.getBottomBoundary() + addition.y); } - if(addition.x === 0 && addition.y === 0 ) - { + if (addition.x === 0 && addition.y === 0) { this._outOfBoundaryAmount = outOfBoundaryAmount; this._outOfBoundaryAmountDirty = false; } return outOfBoundaryAmount; }, - _isOutOfBoundary: function(dir) - { + _isOutOfBoundary: function (dir) { var outOfBoundary = this._getHowMuchOutOfBoundary(); - if(dir !== undefined) - { - switch (dir) - { + if (dir !== undefined) { + switch (dir) { case ccui.ScrollView.MOVEDIR_TOP: return outOfBoundary.y > 0; case ccui.ScrollView.MOVEDIR_BOTTOM: @@ -507,8 +490,7 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{ return outOfBoundary.x > 0; } } - else - { + else { return !this._fltEqualZero(outOfBoundary); } @@ -516,17 +498,15 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{ }, - _moveInnerContainer: function(deltaMove, canStartBounceBack) - { + _moveInnerContainer: function (deltaMove, canStartBounceBack) { var adjustedMove = this._flattenVectorByDirection(deltaMove); this.setInnerContainerPosition(cc.pAdd(this.getInnerContainerPosition(), adjustedMove)); - var outOfBoundary =this._getHowMuchOutOfBoundary(); + var outOfBoundary = this._getHowMuchOutOfBoundary(); this._updateScrollBar(outOfBoundary); - if(this.bounceEnabled && canStartBounceBack) - { + if (this.bounceEnabled && canStartBounceBack) { this._startBounceBackIfNeeded(); } }, @@ -543,22 +523,18 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{ } }, - _calculateTouchMoveVelocity: function() - { + _calculateTouchMoveVelocity: function () { var totalTime = 0; - for(var i = 0; i < this._touchMoveTimeDeltas.length; ++i) - { + for (var i = 0; i < this._touchMoveTimeDeltas.length; ++i) { totalTime += this._touchMoveTimeDeltas[i]; } - if(totalTime == 0 || totalTime >= this._touchTotalTimeThreshold) - { + if (totalTime == 0 || totalTime >= this._touchTotalTimeThreshold) { return cc.p(0, 0); } - var totalMovement = cc.p(0 ,0); + var totalMovement = cc.p(0, 0); - for(var i = 0; i < this._touchMoveDisplacements.length; ++i) - { + for (var i = 0; i < this._touchMoveDisplacements.length; ++i) { totalMovement.x += this._touchMoveDisplacements[i].x; totalMovement.y += this._touchMoveDisplacements[i].y; } @@ -570,8 +546,7 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{ * Set the touch total time threshold * @param {Number} touchTotalTimeThreshold */ - setTouchTotalTimeThreshold: function(touchTotalTimeThreshold) - { + setTouchTotalTimeThreshold: function (touchTotalTimeThreshold) { this._touchTotalTimeThreshold = touchTotalTimeThreshold; }, @@ -580,27 +555,22 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{ * Get the touch total time threshold * @returns {Number} */ - getTouchTotalTimeThreshold: function() - { + getTouchTotalTimeThreshold: function () { return this._touchTotalTimeThreshold; }, - _startInertiaScroll: function(touchMoveVelocity) - { + _startInertiaScroll: function (touchMoveVelocity) { var MOVEMENT_FACTOR = 0.7; var inertiaTotalMovement = cc.pMult(touchMoveVelocity, MOVEMENT_FACTOR); this._startAttenuatingAutoScroll(inertiaTotalMovement, touchMoveVelocity); }, - _startBounceBackIfNeeded: function() - { - if (!this.bounceEnabled) - { + _startBounceBackIfNeeded: function () { + if (!this.bounceEnabled) { return false; } var bounceBackAmount = this._getHowMuchOutOfBoundary(); - if(this._fltEqualZero(bounceBackAmount)) - { + if (this._fltEqualZero(bounceBackAmount)) { return false; } @@ -609,25 +579,21 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{ return true; }, - _startAutoScrollToDestination: function(destination, timeInSec, attenuated) - { - this._startAutoScroll(cc.pSub(destination , this._innerContainer.getPosition()), timeInSec, attenuated); + _startAutoScrollToDestination: function (destination, timeInSec, attenuated) { + this._startAutoScroll(cc.pSub(destination, this._innerContainer.getPosition()), timeInSec, attenuated); }, - _calculateAutoScrollTimeByInitialSpeed: function(initialSpeed) - { + _calculateAutoScrollTimeByInitialSpeed: function (initialSpeed) { // Calculate the time from the initial speed according to quintic polynomial. return Math.sqrt(Math.sqrt(initialSpeed / 5)); }, - _startAttenuatingAutoScroll: function(deltaMove, initialVelocity) - { - var time = this._calculateAutoScrollTimeByInitialSpeed(cc.pLength(initialVelocity)); + _startAttenuatingAutoScroll: function (deltaMove, initialVelocity) { + var time = this._calculateAutoScrollTimeByInitialSpeed(cc.pLength(initialVelocity)); this._startAutoScroll(deltaMove, time, true); }, - _startAutoScroll: function(deltaMove, timeInSec, attenuated) - { + _startAutoScroll: function (deltaMove, timeInSec, attenuated) { var adjustedDeltaMove = this._flattenVectorByDirection(deltaMove); this._autoScrolling = true; @@ -637,16 +603,14 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{ this._autoScrollTotalTime = timeInSec; this._autoScrollAccumulatedTime = 0; this._autoScrollBraking = false; - this._autoScrollBrakingStartPosition = cc.p(0,0 ); + this._autoScrollBrakingStartPosition = cc.p(0, 0); // If the destination is also out of boundary of same side, start brake from beggining. var currentOutOfBoundary = this._getHowMuchOutOfBoundary(); - if(!this._fltEqualZero(currentOutOfBoundary)) - { + if (!this._fltEqualZero(currentOutOfBoundary)) { this._autoScrollCurrentlyOutOfBoundary = true; var afterOutOfBoundary = this._getHowMuchOutOfBoundary(adjustedDeltaMove); - if(currentOutOfBoundary.x * afterOutOfBoundary.x > 0 || currentOutOfBoundary.y * afterOutOfBoundary.y > 0) - { + if (currentOutOfBoundary.x * afterOutOfBoundary.x > 0 || currentOutOfBoundary.y * afterOutOfBoundary.y > 0) { this._autoScrollBraking = true; } } @@ -655,51 +619,42 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{ /** * Immediately stops inner container scroll initiated by any of the "scrollTo*" member functions */ - stopAutoScroll: function() - { + stopAutoScroll: function () { this._autoScrolling = false; this._autoScrollAttenuate = true; this._autoScrollTotalTime = 0; this._autoScrollAccumulatedTime = 0; }, - _isNecessaryAutoScrollBrake: function() - { - if(this._autoScrollBraking) - { + _isNecessaryAutoScrollBrake: function () { + if (this._autoScrollBraking) { return true; } - if(this._isOutOfBoundary()) - { + if (this._isOutOfBoundary()) { // It just went out of boundary. - if(!this._autoScrollCurrentlyOutOfBoundary) - { + if (!this._autoScrollCurrentlyOutOfBoundary) { this._autoScrollCurrentlyOutOfBoundary = true; this._autoScrollBraking = true; this._autoScrollBrakingStartPosition = this.getInnerContainerPosition(); return true; } } - else - { + else { this._autoScrollCurrentlyOutOfBoundary = false; } return false; }, - _getAutoScrollStopEpsilon: function() - { + _getAutoScrollStopEpsilon: function () { return 0.0001; }, - _fltEqualZero: function(point) - { - return (Math.abs(point.x) <= 0.0001 && Math.abs(point.y) <= 0.0001); + _fltEqualZero: function (point) { + return (Math.abs(point.x) <= 0.0001 && Math.abs(point.y) <= 0.0001); }, - _processAutoScrolling: function(deltaTime) - { + _processAutoScrolling: function (deltaTime) { var OUT_OF_BOUNDARY_BREAKING_FACTOR = 0.05; // Make auto scroll shorter if it needs to deaccelerate. var brakingFactor = (this._isNecessaryAutoScrollBrake() ? OUT_OF_BOUNDARY_BREAKING_FACTOR : 1); @@ -709,28 +664,24 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{ // Calculate the progress percentage var percentage = Math.min(1, this._autoScrollAccumulatedTime / this._autoScrollTotalTime); - if(this._autoScrollAttenuate) - { + if (this._autoScrollAttenuate) { percentage -= 1; percentage = percentage * percentage * percentage * percentage * percentage + 1; } // Calculate the new position - var newPosition = cc.pAdd(this._autoScrollStartPosition, cc.pMult(this._autoScrollTargetDelta,percentage)); + var newPosition = cc.pAdd(this._autoScrollStartPosition, cc.pMult(this._autoScrollTargetDelta, percentage)); var reachedEnd = Math.abs(percentage - 1) <= this._getAutoScrollStopEpsilon(); - if(this.bounceEnabled) - { + if (this.bounceEnabled) { // The new position is adjusted if out of boundary newPosition = cc.pAdd(this._autoScrollBrakingStartPosition, cc.pMult(cc.pSub(newPosition, this._autoScrollBrakingStartPosition), brakingFactor)); } - else - { + else { // Don't let go out of boundary var moveDelta = cc.pSub(newPosition, this.getInnerContainerPosition()); var outOfBoundary = this._getHowMuchOutOfBoundary(moveDelta); - if(!this._fltEqualZero(outOfBoundary)) - { + if (!this._fltEqualZero(outOfBoundary)) { newPosition.x += outOfBoundary.x; newPosition.y += outOfBoundary.y; @@ -739,8 +690,7 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{ } // Finish auto scroll if it ended - if(reachedEnd) - { + if (reachedEnd) { this._autoScrolling = false; this._dispatchEvent(ccui.ScrollView.EVENT_AUTOSCROLL_ENDED); } @@ -748,10 +698,8 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{ this._moveInnerContainer(cc.pSub(newPosition, this.getInnerContainerPosition()), reachedEnd); }, - _jumpToDestination: function (desOrX, y) - { - if(desOrX.x === undefined) - { + _jumpToDestination: function (desOrX, y) { + if (desOrX.x === undefined) { desOrX = cc.p(desOrX, y); } @@ -759,19 +707,16 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{ this._moveInnerContainer(cc.pSub(desOrX, this.getInnerContainerPosition()), true); }, - _scrollChildren: function(deltaMove) - { + _scrollChildren: function (deltaMove) { var realMove = deltaMove; - if(this.bounceEnabled) - { + if (this.bounceEnabled) { // If the position of the inner container is out of the boundary, the offsets should be divided by two. var outOfBoundary = this._getHowMuchOutOfBoundary(); realMove.x *= (outOfBoundary.x == 0 ? 1 : 0.5); realMove.y *= (outOfBoundary.y == 0 ? 1 : 0.5); } - if(!this.bounceEnabled) - { + if (!this.bounceEnabled) { var outOfBoundary = this._getHowMuchOutOfBoundary(realMove); realMove.x += outOfBoundary.x; realMove.y += outOfBoundary.y; @@ -785,16 +730,14 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{ if (realMove.y > 0.0) // up { var icBottomPos = this._innerContainer.getBottomBoundary(); - if (icBottomPos + realMove.y >= this._bottomBoundary) - { + if (icBottomPos + realMove.y >= this._bottomBoundary) { scrolledToBottom = true; } } else if (realMove.y < 0.0) // down { var icTopPos = this._innerContainer.getTopBoundary(); - if (icTopPos + realMove.y <= this._topBoundary) - { + if (icTopPos + realMove.y <= this._topBoundary) { scrolledToTop = true; } } @@ -802,39 +745,32 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{ if (realMove.x < 0.0) // left { var icRightPos = this._innerContainer.getRightBoundary(); - if (icRightPos + realMove.x <= this._rightBoundary) - { + if (icRightPos + realMove.x <= this._rightBoundary) { scrolledToRight = true; } } else if (realMove.x > 0.0) // right { var icLeftPos = this._innerContainer.getLeftBoundary(); - if (icLeftPos + realMove.x >= this._leftBoundary) - { + if (icLeftPos + realMove.x >= this._leftBoundary) { scrolledToLeft = true; } } this._moveInnerContainer(realMove, false); - if(realMove.x != 0 || realMove.y != 0) - { + if (realMove.x != 0 || realMove.y != 0) { this._processScrollingEvent(); } - if(scrolledToBottom) - { + if (scrolledToBottom) { this._processScrollEvent(ccui.ScrollView.MOVEDIR_BOTTOM, false); } - if(scrolledToTop) - { + if (scrolledToTop) { this._processScrollEvent(ccui.ScrollView.MOVEDIR_TOP, false); } - if(scrolledToLeft) - { + if (scrolledToLeft) { this._processScrollEvent(ccui.ScrollView.MOVEDIR_LEFT, false); } - if(scrolledToRight) - { + if (scrolledToRight) { this._processScrollEvent(ccui.ScrollView.MOVEDIR_RIGHT, false); } }, @@ -902,7 +838,7 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{ } var inSize = this._innerContainer.getContentSize(); this._startAutoScrollToDestination(cc.p(this._contentSize.width - inSize.width, - this._contentSize.height - inSize.height), time, attenuated); + this._contentSize.height - inSize.height), time, attenuated); }, /** @@ -1075,13 +1011,11 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{ this._jumpToDestination(-(percent.x * w / 100), minY + percent.y * h / 100); }, - _gatherTouchMove: function(delta) - { + _gatherTouchMove: function (delta) { var NUMBER_OF_GATHERED_TOUCHES_FOR_MOVE_SPEED = 5; - while(this._touchMoveDisplacements.length >= NUMBER_OF_GATHERED_TOUCHES_FOR_MOVE_SPEED) - { - this._touchMoveDisplacements.splice(0,1); - this._touchMoveTimeDeltas.splice(0,1) + while (this._touchMoveDisplacements.length >= NUMBER_OF_GATHERED_TOUCHES_FOR_MOVE_SPEED) { + this._touchMoveDisplacements.splice(0, 1); + this._touchMoveTimeDeltas.splice(0, 1) } this._touchMoveDisplacements.push(delta); @@ -1131,11 +1065,9 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{ this._bePressed = false; var bounceBackStarted = this._startBounceBackIfNeeded(); - if(!bounceBackStarted && this.inertiaScrollEnabled) - { + if (!bounceBackStarted && this.inertiaScrollEnabled) { var touchMoveVelocity = this._calculateTouchMoveVelocity(); - if(touchMoveVelocity.x !== 0 || touchMoveVelocity.y !== 0) - { + if (touchMoveVelocity.x !== 0 || touchMoveVelocity.y !== 0) { this._startInertiaScroll(touchMoveVelocity); } } @@ -1158,7 +1090,7 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{ */ onTouchBegan: function (touch, event) { var pass = ccui.Layout.prototype.onTouchBegan.call(this, touch, event); - if(!this._isInterceptTouch){ + if (!this._isInterceptTouch) { if (this._hit) this._handlePressLogic(touch); } @@ -1172,7 +1104,7 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{ */ onTouchMoved: function (touch, event) { ccui.Layout.prototype.onTouchMoved.call(this, touch, event); - if(!this._isInterceptTouch) + if (!this._isInterceptTouch) this._handleMoveLogic(touch); }, @@ -1183,7 +1115,7 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{ */ onTouchEnded: function (touch, event) { ccui.Layout.prototype.onTouchEnded.call(this, touch, event); - if(!this._isInterceptTouch) + if (!this._isInterceptTouch) this._handleReleaseLogic(touch); this._isInterceptTouch = false; }, @@ -1222,7 +1154,7 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{ return; } - if(this._direction === ccui.ScrollView.DIR_NONE) + if (this._direction === ccui.ScrollView.DIR_NONE) return; var touchPoint = touch.getLocation(); @@ -1253,12 +1185,10 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{ } }, - _processScrollEvent: function(_directionEvent, bounce) - { + _processScrollEvent: function (_directionEvent, bounce) { var event = 0; - switch(_directionEvent) - { + switch (_directionEvent) { case ccui.ScrollView.MOVEDIR_TOP: event = (bounce ? ccui.ScrollView.EVENT_BOUNCE_TOP : ccui.ScrollView.EVENT_SCROLL_TO_TOP); break; @@ -1276,20 +1206,18 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{ this._dispatchEvent(event); }, - _processScrollingEvent: function() - { - this._dispatchEvent( ccui.ScrollView.EVENT_SCROLLING); + _processScrollingEvent: function () { + this._dispatchEvent(ccui.ScrollView.EVENT_SCROLLING); }, - _dispatchEvent: function(event) - { - if(this._scrollViewEventSelector){ + _dispatchEvent: function (event) { + if (this._scrollViewEventSelector) { if (this._scrollViewEventListener) this._scrollViewEventSelector.call(this._scrollViewEventListener, this, event); else this._scrollViewEventSelector(this, event); } - if(this._ccEventCallback) + if (this._ccEventCallback) this._ccEventCallback(this, event); }, @@ -1308,7 +1236,7 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{ * Adds callback function called ScrollView event triggered * @param {Function} selector */ - addEventListener: function(selector){ + addEventListener: function (selector) { this._ccEventCallback = selector; }, @@ -1670,7 +1598,7 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{ return "ScrollView"; }, - _createCloneInstance: function(){ + _createCloneInstance: function () { return new ccui.ScrollView(); }, @@ -1679,7 +1607,7 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{ }, _copySpecialProperties: function (scrollView) { - if(scrollView instanceof ccui.ScrollView) { + if (scrollView instanceof ccui.ScrollView) { ccui.Layout.prototype._copySpecialProperties.call(this, scrollView); this.setInnerContainerSize(scrollView.getInnerContainerSize()); this.setInnerContainerPosition(scrollView.getInnerContainerPosition()); diff --git a/extensions/ccui/uiwidgets/scroll-widget/UIScrollViewBar.js b/extensions/ccui/uiwidgets/scroll-widget/UIScrollViewBar.js index ab425afcc6..4e9c1840a7 100644 --- a/extensions/ccui/uiwidgets/scroll-widget/UIScrollViewBar.js +++ b/extensions/ccui/uiwidgets/scroll-widget/UIScrollViewBar.js @@ -41,16 +41,16 @@ ccui.ScrollViewBar = ccui.ProtectedNode.extend(/** @lends ccui.ScrollViewBar# */ _lowerHalfCircle: null, _body: null, - _opacity : 255, + _opacity: 255, - _marginFromBoundary : 0, + _marginFromBoundary: 0, _marginForLength: 0, _touching: false, _autoHideEnabled: true, - autoHideTime : 0, - _autoHideRemainingTime : 0, + autoHideTime: 0, + _autoHideRemainingTime: 0, _className: "ScrollViewBar", /** @@ -62,7 +62,7 @@ ccui.ScrollViewBar = ccui.ProtectedNode.extend(/** @lends ccui.ScrollViewBar# */ ctor: function (parent, direction) { cc.ProtectedNode.prototype.ctor.call(this); this._direction = direction; - this._parentScroll = parent; + this._parentScroll = parent; this._marginFromBoundary = ccui.ScrollViewBar.DEFAULT_MARGIN; this._marginForLength = ccui.ScrollViewBar.DEFAULT_MARGIN; @@ -91,7 +91,7 @@ ccui.ScrollViewBar = ccui.ProtectedNode.extend(/** @lends ccui.ScrollViewBar# */ this.addProtectedChild(this._upperHalfCircle); this.addProtectedChild(this._lowerHalfCircle); - this._body = ccui.helper._createSpriteFromBase64(ccui.ScrollViewBar.BODY_IMAGE_1_PIXEL_HEIGHT, ccui.ScrollViewBar.BODY_IMAGE_1_PIXEL_HEIGHT_KEY); + this._body = ccui.helper._createSpriteFromBase64(ccui.ScrollViewBar.BODY_IMAGE_1_PIXEL_HEIGHT, ccui.ScrollViewBar.BODY_IMAGE_1_PIXEL_HEIGHT_KEY); this._body.setAnchorPoint(cc.p(0.5, 0)); this.addProtectedChild(this._body); @@ -100,8 +100,7 @@ ccui.ScrollViewBar = ccui.ProtectedNode.extend(/** @lends ccui.ScrollViewBar# */ cc.ProtectedNode.prototype.setOpacity.call(this, 0); this._autoHideRemainingTime = 0; - if(this._direction === ccui.ScrollView.DIR_HORIZONTAL) - { + if (this._direction === ccui.ScrollView.DIR_HORIZONTAL) { this.setRotation(90); } }, @@ -110,22 +109,18 @@ ccui.ScrollViewBar = ccui.ProtectedNode.extend(/** @lends ccui.ScrollViewBar# */ * Set the scroll bar position from the left-bottom corner (horizontal) or right-top corner (vertical). * @param {cc.Point} positionFromCorner The position from the left-bottom corner (horizontal) or right-top corner (vertical). */ - setPositionFromCorner: function(positionFromCorner) - { - if(this._direction === ccui.ScrollView.DIR_VERTICAL) - { + setPositionFromCorner: function (positionFromCorner) { + if (this._direction === ccui.ScrollView.DIR_VERTICAL) { this._marginForLength = positionFromCorner.y; this._marginFromBoundary = positionFromCorner.x; } - else - { + else { this._marginForLength = positionFromCorner.x; this._marginFromBoundary = positionFromCorner.y; } }, - onEnter: function() - { + onEnter: function () { cc.ProtectedNode.prototype.onEnter.call(this); this.scheduleUpdate(); }, @@ -134,14 +129,11 @@ ccui.ScrollViewBar = ccui.ProtectedNode.extend(/** @lends ccui.ScrollViewBar# */ * Get the scroll bar position from the left-bottom corner (horizontal) or right-top corner (vertical). * @returns {cc.Point} */ - getPositionFromCorner: function() - { - if(this._direction === ccui.ScrollView.DIR_VERTICAL) - { + getPositionFromCorner: function () { + if (this._direction === ccui.ScrollView.DIR_VERTICAL) { return cc.p(this._marginFromBoundary, this._marginForLength); } - else - { + else { return cc.p(this._marginForLength, this._marginFromBoundary); } }, @@ -149,8 +141,7 @@ ccui.ScrollViewBar = ccui.ProtectedNode.extend(/** @lends ccui.ScrollViewBar# */ * Set the scroll bar's width * @param {number} width The scroll bar's width */ - setWidth: function(width) - { + setWidth: function (width) { var scale = width / this._body.width; this._body.setScaleX(scale); this._upperHalfCircle.setScale(scale); @@ -161,8 +152,7 @@ ccui.ScrollViewBar = ccui.ProtectedNode.extend(/** @lends ccui.ScrollViewBar# */ * Get the scroll bar's width * @returns {number} the scroll bar's width */ - getWidth: function() - { + getWidth: function () { return this._body.getBoundingBox().width; }, @@ -170,11 +160,10 @@ ccui.ScrollViewBar = ccui.ProtectedNode.extend(/** @lends ccui.ScrollViewBar# */ * Set scroll bar auto hide state * @param {boolean} autoHideEnabled scroll bar auto hide state */ - setAutoHideEnabled: function(autoHideEnabled) - { + setAutoHideEnabled: function (autoHideEnabled) { this._autoHideEnabled = autoHideEnabled; - if(!this._autoHideEnabled && !this._touching && this._autoHideRemainingTime <= 0) + if (!this._autoHideEnabled && !this._touching && this._autoHideRemainingTime <= 0) cc.ProtectedNode.prototype.setOpacity.call(this, this.opacity); else cc.ProtectedNode.prototype.setOpacity.call(this, 0); @@ -183,8 +172,7 @@ ccui.ScrollViewBar = ccui.ProtectedNode.extend(/** @lends ccui.ScrollViewBar# */ * Query scroll bar auto hide state * @returns {boolean} True if scroll bar auto hide is enabled, false otherwise. */ - isAutoHideEnabled: function() - { + isAutoHideEnabled: function () { return this._autoHideEnabled; }, @@ -192,8 +180,7 @@ ccui.ScrollViewBar = ccui.ProtectedNode.extend(/** @lends ccui.ScrollViewBar# */ * Set scroll bar opacity * @param {number} opacity scroll bar opacity */ - setOpacity: function(opacity) - { + setOpacity: function (opacity) { this._opacity = opacity; }, @@ -201,51 +188,42 @@ ccui.ScrollViewBar = ccui.ProtectedNode.extend(/** @lends ccui.ScrollViewBar# */ * Get scroll bar opacity * @returns {number} */ - getOpacity: function() - { + getOpacity: function () { return this._opacity; }, - _updateLength: function(length) - { + _updateLength: function (length) { var ratio = length / this._body.getTextureRect().height; this._body.setScaleY(ratio); this._upperHalfCircle.setPositionY(this._body.getPositionY() + length); }, - _processAutoHide: function(dt) - { - if(!this._autoHideEnabled || this._autoHideRemainingTime <= 0) - { + _processAutoHide: function (dt) { + if (!this._autoHideEnabled || this._autoHideRemainingTime <= 0) { return; } - else if(this._touching) - { + else if (this._touching) { // If it is touching, don't auto hide. return; } this._autoHideRemainingTime -= dt; - if(this._autoHideRemainingTime <= this.autoHideTime) - { - this. _autoHideRemainingTime = Math.max(0, this._autoHideRemainingTime); + if (this._autoHideRemainingTime <= this.autoHideTime) { + this._autoHideRemainingTime = Math.max(0, this._autoHideRemainingTime); cc.ProtectedNode.prototype.setOpacity.call(this, this._opacity * (this._autoHideRemainingTime / this.autoHideTime)); } }, - update: function(dt) - { + update: function (dt) { this._processAutoHide(dt); }, /** * This is called by parent ScrollView when a touch is began. Don't call this directly. */ - onTouchBegan: function() - { - if(!this._autoHideEnabled) - { + onTouchBegan: function () { + if (!this._autoHideEnabled) { return; } this._touching = true; @@ -254,16 +232,13 @@ ccui.ScrollViewBar = ccui.ProtectedNode.extend(/** @lends ccui.ScrollViewBar# */ /** * This is called by parent ScrollView when a touch is ended. Don't call this directly. */ - onTouchEnded: function() - { - if(!this._autoHideEnabled) - { + onTouchEnded: function () { + if (!this._autoHideEnabled) { return; } this._touching = false; - if(this._autoHideRemainingTime <= 0) - { + if (this._autoHideRemainingTime <= 0) { // If the remaining time is 0, it means that it didn't moved after touch started so scroll bar is not showing. return; } @@ -275,10 +250,8 @@ ccui.ScrollViewBar = ccui.ProtectedNode.extend(/** @lends ccui.ScrollViewBar# */ * * @param {cc.Point} outOfBoundary amount how much the inner container of ScrollView is out of boundary */ - onScrolled: function(outOfBoundary) - { - if(this._autoHideEnabled) - { + onScrolled: function (outOfBoundary) { + if (this._autoHideEnabled) { this._autoHideRemainingTime = this.autoHideTime; cc.ProtectedNode.prototype.setOpacity.call(this, this.opacity); } @@ -290,15 +263,13 @@ ccui.ScrollViewBar = ccui.ProtectedNode.extend(/** @lends ccui.ScrollViewBar# */ var outOfBoundaryValue = 0; var innerContainerPosition = 0; - if(this._direction === ccui.ScrollView.DIR_VERTICAL) - { + if (this._direction === ccui.ScrollView.DIR_VERTICAL) { innerContainerMeasure = innerContainer.height; scrollViewMeasure = this._parentScroll.height; outOfBoundaryValue = outOfBoundary.y; innerContainerPosition = -innerContainer.getPositionY(); } - else if(this._direction === ccui.ScrollView.DIR_HORIZONTAL) - { + else if (this._direction === ccui.ScrollView.DIR_HORIZONTAL) { innerContainerMeasure = innerContainer.width; scrollViewMeasure = this._parentScroll.width; outOfBoundaryValue = outOfBoundary.x; @@ -311,11 +282,9 @@ ccui.ScrollViewBar = ccui.ProtectedNode.extend(/** @lends ccui.ScrollViewBar# */ this.setPosition(position); }, - _calculateLength: function(innerContainerMeasure, scrollViewMeasure, outOfBoundaryValue) - { + _calculateLength: function (innerContainerMeasure, scrollViewMeasure, outOfBoundaryValue) { var denominatorValue = innerContainerMeasure; - if(outOfBoundaryValue !== 0) - { + if (outOfBoundaryValue !== 0) { // If it is out of boundary, the length of scroll bar gets shorter quickly. var GETTING_SHORTER_FACTOR = 20; denominatorValue += (outOfBoundaryValue > 0 ? outOfBoundaryValue : -outOfBoundaryValue) * GETTING_SHORTER_FACTOR; @@ -325,18 +294,15 @@ ccui.ScrollViewBar = ccui.ProtectedNode.extend(/** @lends ccui.ScrollViewBar# */ return Math.abs(scrollViewMeasure - 2 * this._marginForLength) * lengthRatio; }, - _calculatePosition: function(innerContainerMeasure, scrollViewMeasure, innerContainerPosition, outOfBoundaryValue, length) - { + _calculatePosition: function (innerContainerMeasure, scrollViewMeasure, innerContainerPosition, outOfBoundaryValue, length) { var denominatorValue = innerContainerMeasure - scrollViewMeasure; - if(outOfBoundaryValue !== 0) - { + if (outOfBoundaryValue !== 0) { denominatorValue += Math.abs(outOfBoundaryValue); } var positionRatio = 0; - if(denominatorValue !== 0) - { + if (denominatorValue !== 0) { positionRatio = innerContainerPosition / denominatorValue; positionRatio = Math.max(positionRatio, 0); positionRatio = Math.min(positionRatio, 1); @@ -344,12 +310,10 @@ ccui.ScrollViewBar = ccui.ProtectedNode.extend(/** @lends ccui.ScrollViewBar# */ var position = (scrollViewMeasure - length - 2 * this._marginForLength) * positionRatio + this._marginForLength; - if(this._direction === ccui.ScrollView.DIR_VERTICAL) - { + if (this._direction === ccui.ScrollView.DIR_VERTICAL) { return cc.p(this._parentScroll.width - this._marginFromBoundary, position); } - else - { + else { return cc.p(position, this._marginFromBoundary); } } diff --git a/extensions/ccui/uiwidgets/scroll-widget/UIScrollViewCanvasRenderCmd.js b/extensions/ccui/uiwidgets/scroll-widget/UIScrollViewCanvasRenderCmd.js index a96de5790a..d724d98e62 100644 --- a/extensions/ccui/uiwidgets/scroll-widget/UIScrollViewCanvasRenderCmd.js +++ b/extensions/ccui/uiwidgets/scroll-widget/UIScrollViewCanvasRenderCmd.js @@ -1,5 +1,5 @@ -(function(){ - if(!ccui.ProtectedNode.CanvasRenderCmd) +(function () { + if (!ccui.ProtectedNode.CanvasRenderCmd) return; ccui.ScrollView.CanvasRenderCmd = function(renderable){ ccui.Layout.CanvasRenderCmd.call(this, renderable); @@ -27,7 +27,7 @@ proto.rendering = function (ctx) { var currentID = this._node.__instanceId; - var locCmds = cc.renderer._cacheToCanvasCmds[currentID], i, len, + var i, locCmds = cc.renderer._cacheToCanvasCmds[currentID], len, scaleX = cc.view.getScaleX(), scaleY = cc.view.getScaleY(); var context = ctx || cc._renderContext; @@ -37,9 +37,9 @@ for (i = 0, len = locCmds.length; i < len; i++) { var checkNode = locCmds[i]._node; - if(checkNode instanceof ccui.ScrollView) + if (checkNode instanceof ccui.ScrollView) continue; - if(checkNode && checkNode._parent && checkNode._parent._inViewRect === false) + if (checkNode && checkNode._parent && checkNode._parent._inViewRect === false) continue; locCmds[i].rendering(context, scaleX, scaleY); } diff --git a/extensions/ccui/uiwidgets/scroll-widget/UIScrollViewWebGLRenderCmd.js b/extensions/ccui/uiwidgets/scroll-widget/UIScrollViewWebGLRenderCmd.js index 413d23aff0..5f22e798ba 100644 --- a/extensions/ccui/uiwidgets/scroll-widget/UIScrollViewWebGLRenderCmd.js +++ b/extensions/ccui/uiwidgets/scroll-widget/UIScrollViewWebGLRenderCmd.js @@ -1,6 +1,5 @@ - -(function(){ - if(!ccui.ProtectedNode.WebGLRenderCmd) +(function () { + if (!ccui.ProtectedNode.WebGLRenderCmd) return; ccui.ScrollView.WebGLRenderCmd = function(renderable){ ccui.Layout.WebGLRenderCmd.call(this, renderable); @@ -28,7 +27,7 @@ cc.renderer._turnToNormalMode(); }; - proto.rendering = function(ctx){ + proto.rendering = function (ctx) { var currentID = this._node.__instanceId, locCmds = cc.renderer._cacheToBufferCmds[currentID], i, len, checkNode, cmd, @@ -45,9 +44,9 @@ for (i = 0, len = locCmds.length; i < len; i++) { cmd = locCmds[i]; checkNode = cmd._node; - if(checkNode instanceof ccui.ScrollView) + if (checkNode instanceof ccui.ScrollView) continue; - if(checkNode && checkNode._parent && checkNode._parent._inViewRect === false) + if (checkNode && checkNode._parent && checkNode._parent._inViewRect === false) continue; if (cmd.uploadData) { diff --git a/extensions/cocostudio/action/CCActionManager.js b/extensions/cocostudio/action/CCActionManager.js index 434fb83327..0a5dc68b9f 100644 --- a/extensions/cocostudio/action/CCActionManager.js +++ b/extensions/cocostudio/action/CCActionManager.js @@ -84,8 +84,8 @@ ccs.actionManager = /** @lends ccs.actionManager# */{ if (action) action.play(fun); }, - - /** + + /** * Stop an Action with a name. * @param {String} jsonName * @param {String} actionName @@ -103,10 +103,10 @@ ccs.actionManager = /** @lends ccs.actionManager# */{ this._actionDic = {}; }, - /** - * Clear data: Release all actions. - */ - clear: function() { - this._actionDic = {}; - } + /** + * Clear data: Release all actions. + */ + clear: function () { + this._actionDic = {}; + } }; diff --git a/extensions/cocostudio/action/CCActionNode.js b/extensions/cocostudio/action/CCActionNode.js index 199c7d110f..d029830088 100644 --- a/extensions/cocostudio/action/CCActionNode.js +++ b/extensions/cocostudio/action/CCActionNode.js @@ -72,12 +72,12 @@ ccs.ActionNode = ccs.Class.extend(/** @lends ccs.ActionNode# */{ var actionFrameDic = actionFrameList[i]; var frameIndex = actionFrameDic["frameid"]; var frameTweenType = actionFrameDic["tweenType"]; - if(frameTweenType == null) + if (frameTweenType == null) frameTweenType = 0; var frameTweenParameterNum = actionFrameDic["tweenParameter"]; var frameTweenParameter = []; - for (var j = 0; j < frameTweenParameterNum; j++){ + for (var j = 0; j < frameTweenParameterNum; j++) { var value = actionFrameDic["tweenParameter"][j]; frameTweenParameter.push(value); } @@ -86,7 +86,7 @@ ccs.ActionNode = ccs.Class.extend(/** @lends ccs.ActionNode# */{ if (actionFrameDic["positionx"] !== undefined) { var positionX = actionFrameDic["positionx"]; var positionY = actionFrameDic["positiony"]; - if(positionOffset && node.parent){ + if (positionOffset && node.parent) { var AnchorPointIn = node.parent.getAnchorPointInPoints(); positionX += AnchorPointIn.x; positionY += AnchorPointIn.y; @@ -249,7 +249,7 @@ ccs.ActionNode = ccs.Class.extend(/** @lends ccs.ActionNode# */{ * @param {ccs.ActionFrame} frame */ deleteFrame: function (frame) { - if (frame == null) + if (frame === undefined) return; var frameType = frame.frameType; var array = this._frameArray[frameType]; @@ -265,7 +265,7 @@ ccs.ActionNode = ccs.Class.extend(/** @lends ccs.ActionNode# */{ }, _refreshActionProperty: function () { - if (this._object === null) + if (!this._object) return null; var locSpawnArray = []; for (var i = 0; i < this._frameArrayNum; i++) { @@ -284,10 +284,10 @@ ccs.ActionNode = ccs.Class.extend(/** @lends ccs.ActionNode# */{ else { locAction = locFrame.getAction(0); } - if(locAction) + if (locAction) locSequenceArray.push(locAction); } - if(locSequenceArray){ + if (locSequenceArray) { var locSequence = cc.sequence(locSequenceArray); if (locSequence !== null) locSpawnArray.push(locSequence); @@ -304,9 +304,9 @@ ccs.ActionNode = ccs.Class.extend(/** @lends ccs.ActionNode# */{ * @param {cc.CallFunc} fun */ playAction: function (fun) { - if (this._object === null || this._actionSpawn === null) + if (!this._object || !this._actionSpawn) return; - if(fun) + if (fun) this._action = cc.sequence(this._actionSpawn, fun); else this._action = cc.sequence(this._actionSpawn); @@ -325,7 +325,7 @@ ccs.ActionNode = ccs.Class.extend(/** @lends ccs.ActionNode# */{ stopAction: function () { var node = this.getActionNode(); if (node !== null && this._action !== null) { - if(!this._action.isDone()) + if (!this._action.isDone()) node.stopAction(this._action); } }, @@ -356,7 +356,7 @@ ccs.ActionNode = ccs.Class.extend(/** @lends ccs.ActionNode# */{ */ getLastFrameIndex: function () { var locFrameindex = -1; - var locIsFindFrame = false ,locFrameArray = this._frameArray; + var locIsFindFrame = false, locFrameArray = this._frameArray; for (var i = 0, len = this._frameArrayNum; i < len; i++) { var locArray = locFrameArray[i]; if (locArray.length <= 0) @@ -381,7 +381,7 @@ ccs.ActionNode = ccs.Class.extend(/** @lends ccs.ActionNode# */{ var locUnitTime = this.getUnitTime(); for (var i = 0; i < this._frameArrayNum; i++) { var locArray = this._frameArray[i]; - if (locArray === null) + if (!locArray) continue; for (var j = 0; j < locArray.length; j++) { @@ -423,7 +423,7 @@ ccs.ActionNode = ccs.Class.extend(/** @lends ccs.ActionNode# */{ * @returns {Boolean} that if the action is done once time */ isActionDoneOnce: function () { - if (this._action === null) + if (!this._action) return true; return this._action.isDone(); } diff --git a/extensions/cocostudio/armature/CCArmature.js b/extensions/cocostudio/armature/CCArmature.js index 2f03c1710e..6cd69a89d5 100644 --- a/extensions/cocostudio/armature/CCArmature.js +++ b/extensions/cocostudio/armature/CCArmature.js @@ -151,7 +151,7 @@ ccs.Armature = ccs.Node.extend(/** @lends ccs.Armature# */{ }, addChild: function (child, localZOrder, tag) { - if(child instanceof ccui.Widget){ + if (child instanceof ccui.Widget) { cc.log("Armature doesn't support to add Widget as its child, it will be fix soon."); return; } @@ -194,7 +194,7 @@ ccs.Armature = ccs.Node.extend(/** @lends ccs.Armature# */{ addBone: function (bone, parentName) { cc.assert(bone, "Argument must be non-nil"); var locBoneDic = this._boneDic; - if(bone.getName()) + if (bone.getName()) cc.assert(!locBoneDic[bone.getName()], "bone already added. It can't be added again"); if (parentName) { @@ -282,7 +282,7 @@ ccs.Armature = ccs.Node.extend(/** @lends ccs.Armature# */{ this.setAnchorPoint(locOffsetPoint.x / rect.width, locOffsetPoint.y / rect.height); }, - getOffsetPoints: function(){ + getOffsetPoints: function () { return {x: this._offsetPoint.x, y: this._offsetPoint.y}; }, @@ -345,21 +345,21 @@ ccs.Armature = ccs.Node.extend(/** @lends ccs.Armature# */{ * This boundingBox will calculate all bones' boundingBox every time * @returns {cc.Rect} */ - getBoundingBox: function(){ + getBoundingBox: function () { var minX, minY, maxX, maxY = 0; var first = true; var boundingBox = cc.rect(0, 0, 0, 0), locChildren = this._children; var len = locChildren.length; - for (var i=0; i= ccs.CONST_VERSION_COMBINED){ + if (this._dataVersion >= ccs.CONST_VERSION_COMBINED) { ccs.TransformHelp.nodeConcat(locTweenData, this._boneData); locTweenData.scaleX -= 1; locTweenData.scaleY -= 1; @@ -182,7 +182,7 @@ ccs.Bone = ccs.Node.extend(/** @lends ccs.Bone# */{ locWorldInfo.skewX = locTweenData.skewX + this._skewX + cc.degreesToRadians(this._rotationX); locWorldInfo.skewY = locTweenData.skewY + this._skewY - cc.degreesToRadians(this._rotationY); - if(this._parentBone) + if (this._parentBone) this._applyParentTransform(this._parentBone); else { if (this._armatureParentBone) @@ -195,7 +195,7 @@ ccs.Bone = ccs.Node.extend(/** @lends ccs.Bone# */{ } ccs.displayFactory.updateDisplay(this, delta, this._boneTransformDirty || this._armature.getArmatureTransformDirty()); - for(var i=0; i 0 && this._children.getIndex(bone) !== -1 ) { - if(recursion) { + if (this._children.length > 0 && this._children.getIndex(bone) !== -1) { + if (recursion) { var ccbones = bone._children; - for(var i=0; i= 0) && (index < locDisplayList.length) ) + if ((index >= 0) && (index < locDisplayList.length)) decoDisplay = locDisplayList[index]; - else{ + else { decoDisplay = new ccs.DecorativeDisplay(); locDisplayList.push(decoDisplay); } - if(display instanceof ccs.DisplayData){ + if (display instanceof ccs.DisplayData) { ccs.displayFactory.addDisplay(this._bone, decoDisplay, display); //! if changed display index is current display index, then change current display to the new display - if(index === this._displayIndex) { + if (index === this._displayIndex) { this._displayIndex = -1; this.changeDisplayWithIndex(index, false); } @@ -117,14 +117,14 @@ ccs.DisplayManager = ccs.Class.extend(/** @lends ccs.DisplayManager */{ if (!find) display.setSkinData(new ccs.BaseData()); } - } else if (display instanceof cc.ParticleSystem){ + } else if (display instanceof cc.ParticleSystem) { displayData = new ccs.ParticleDisplayData(); display.removeFromParent(); display.cleanup(); var armature = this._bone.getArmature(); if (armature) display.setParent(armature); - } else if(display instanceof ccs.Armature) { + } else if (display instanceof ccs.Armature) { displayData = new ccs.ArmatureDisplayData(); displayData.displayName = display.getName(); display.setParentBone(this._bone); @@ -134,15 +134,15 @@ ccs.DisplayManager = ccs.Class.extend(/** @lends ccs.DisplayManager */{ decoDisplay.setDisplayData(displayData); //! if changed display index is current display index, then change current display to the new display - if(index === this._displayIndex) { + if (index === this._displayIndex) { this._displayIndex = -1; this.changeDisplayWithIndex(index, false); } }, - _addDisplayOther:function(decoDisplay,display){ + _addDisplayOther: function (decoDisplay, display) { var displayData = null; - if (display instanceof ccs.Skin){ + if (display instanceof ccs.Skin) { var skin = display; skin.setBone(this._bone); displayData = new ccs.SpriteDisplayData(); @@ -151,7 +151,7 @@ ccs.DisplayManager = ccs.Class.extend(/** @lends ccs.DisplayManager */{ var spriteDisplayData = decoDisplay.getDisplayData(); if (spriteDisplayData instanceof ccs.SpriteDisplayData) skin.setSkinData(spriteDisplayData.skinData); - else{ + else { var find = false; for (var i = this._decoDisplayList.length - 2; i >= 0; i--) { var dd = this._decoDisplayList[i]; @@ -170,16 +170,16 @@ ccs.DisplayManager = ccs.Class.extend(/** @lends ccs.DisplayManager */{ } } - else if (display instanceof cc.ParticleSystem){ + else if (display instanceof cc.ParticleSystem) { displayData = new ccs.ParticleDisplayData(); displayData.displayName = display._plistFile; } - else if (display instanceof ccs.Armature){ + else if (display instanceof ccs.Armature) { displayData = new ccs.ArmatureDisplayData(); displayData.displayName = display.getName(); display.setParentBone(this._bone); } - else { + else { displayData = new ccs.DisplayData(); } decoDisplay.setDisplay(display); @@ -190,7 +190,7 @@ ccs.DisplayManager = ccs.Class.extend(/** @lends ccs.DisplayManager */{ * Removes display node from list. * @param {Number} index */ - removeDisplay:function (index) { + removeDisplay: function (index) { this._decoDisplayList.splice(index, 1); if (index === this._displayIndex) { this.setCurrentDecorativeDisplay(null); @@ -202,7 +202,7 @@ ccs.DisplayManager = ccs.Class.extend(/** @lends ccs.DisplayManager */{ * Returns the display node list. * @returns {Array} */ - getDecorativeDisplayList:function(){ + getDecorativeDisplayList: function () { return this._decoDisplayList; }, @@ -215,7 +215,7 @@ ccs.DisplayManager = ccs.Class.extend(/** @lends ccs.DisplayManager */{ * @param {Number} index The index of the display you want to change * @param {Boolean} force If true, then force change display to specified display, or current display will set to display index edit in the flash every key frame. */ - changeDisplayWithIndex:function (index, force) { + changeDisplayWithIndex: function (index, force) { if (index >= this._decoDisplayList.length) { cc.log("the index value is out of range"); return; @@ -230,7 +230,7 @@ ccs.DisplayManager = ccs.Class.extend(/** @lends ccs.DisplayManager */{ //! If displayIndex < 0, it means you want to hide you display if (index < 0) { - if(this._displayRenderNode) { + if (this._displayRenderNode) { this._displayRenderNode.removeFromParent(true); this.setCurrentDecorativeDisplay(null); } @@ -258,7 +258,7 @@ ccs.DisplayManager = ccs.Class.extend(/** @lends ccs.DisplayManager */{ * Sets current decorative display. * @param {ccs.DecorativeDisplay} decoDisplay */ - setCurrentDecorativeDisplay:function (decoDisplay) { + setCurrentDecorativeDisplay: function (decoDisplay) { var locCurrentDecoDisplay = this._currentDecoDisplay; if (ccs.ENABLE_PHYSICS_CHIPMUNK_DETECT || ccs.ENABLE_PHYSICS_SAVE_CALCULATED_VERTEX) { if (locCurrentDecoDisplay && locCurrentDecoDisplay.getColliderDetector()) @@ -299,7 +299,7 @@ ccs.DisplayManager = ccs.Class.extend(/** @lends ccs.DisplayManager */{ this._displayRenderNode.setVisible(this._visible); this._displayType = this._currentDecoDisplay.getDisplayData().displayType; - }else + } else this._displayType = ccs.DISPLAY_TYPE_MAX; @@ -310,7 +310,7 @@ ccs.DisplayManager = ccs.Class.extend(/** @lends ccs.DisplayManager */{ * Returns the current display render node. * @returns {cc.Node} */ - getDisplayRenderNode:function () { + getDisplayRenderNode: function () { return this._displayRenderNode; }, @@ -318,7 +318,7 @@ ccs.DisplayManager = ccs.Class.extend(/** @lends ccs.DisplayManager */{ * Returns the type of display render node. * @returns {Number} */ - getDisplayRenderNodeType:function(){ + getDisplayRenderNodeType: function () { return this._displayType; }, @@ -326,7 +326,7 @@ ccs.DisplayManager = ccs.Class.extend(/** @lends ccs.DisplayManager */{ * Returns the index of display render node. * @returns {Number} */ - getCurrentDisplayIndex:function () { + getCurrentDisplayIndex: function () { return this._displayIndex; }, @@ -334,7 +334,7 @@ ccs.DisplayManager = ccs.Class.extend(/** @lends ccs.DisplayManager */{ * Returns the current decorative display * @returns {ccs.DecorativeDisplay} */ - getCurrentDecorativeDisplay:function () { + getCurrentDecorativeDisplay: function () { return this._currentDecoDisplay; }, @@ -343,7 +343,7 @@ ccs.DisplayManager = ccs.Class.extend(/** @lends ccs.DisplayManager */{ * @param index * @returns {ccs.DecorativeDisplay} */ - getDecorativeDisplayByIndex:function (index) { + getDecorativeDisplayByIndex: function (index) { return this._decoDisplayList[index]; }, @@ -355,7 +355,7 @@ ccs.DisplayManager = ccs.Class.extend(/** @lends ccs.DisplayManager */{ *

* @param {ccs.BoneData} boneData */ - initDisplayList:function (boneData) { + initDisplayList: function (boneData) { this._decoDisplayList.length = 0; if (!boneData) return; @@ -382,7 +382,7 @@ ccs.DisplayManager = ccs.Class.extend(/** @lends ccs.DisplayManager */{ if (y !== undefined) point = cc.p(point, y); - if(this._currentDecoDisplay.getDisplayData().displayType === ccs.DISPLAY_TYPE_SPRITE){ + if (this._currentDecoDisplay.getDisplayData().displayType === ccs.DISPLAY_TYPE_SPRITE) { /* * First we first check if the point is in the sprite content rect. If false, then we continue to check * the contour point. If this step is also false, then we can say the bone not contain this point. @@ -402,7 +402,7 @@ ccs.DisplayManager = ccs.Class.extend(/** @lends ccs.DisplayManager */{ *

* @param {boolean} visible */ - setVisible:function (visible) { + setVisible: function (visible) { if (!this._displayRenderNode) return; this._visible = visible; @@ -413,39 +413,39 @@ ccs.DisplayManager = ccs.Class.extend(/** @lends ccs.DisplayManager */{ * Determines if the display is visible * @returns {boolean} true if the node is visible, false if the node is hidden. */ - isVisible:function () { + isVisible: function () { return this._visible; }, - getContentSize:function () { + getContentSize: function () { if (!this._displayRenderNode) return cc.size(0, 0); return this._displayRenderNode.getContentSize(); }, - getBoundingBox:function () { + getBoundingBox: function () { if (!this._displayRenderNode) return cc.rect(0, 0, 0, 0); return this._displayRenderNode.getBoundingBox(); }, - getAnchorPoint:function () { + getAnchorPoint: function () { if (!this._displayRenderNode) - return cc.p(0, 0); + return cc.p(0, 0); return this._displayRenderNode.getAnchorPoint(); }, - getAnchorPointInPoints:function () { + getAnchorPointInPoints: function () { if (!this._displayRenderNode) - return cc.p(0, 0); + return cc.p(0, 0); return this._displayRenderNode.getAnchorPointInPoints(); }, - getForceChangeDisplay:function () { + getForceChangeDisplay: function () { return this._forceChangeDisplay; }, - release:function () { + release: function () { this._decoDisplayList = null; if (this._displayRenderNode) { this._displayRenderNode.removeFromParent(true); @@ -462,4 +462,4 @@ ccs.DisplayManager = ccs.Class.extend(/** @lends ccs.DisplayManager */{ */ ccs.DisplayManager.create = function (bone) { return new ccs.DisplayManager(bone); -}; \ No newline at end of file +}; diff --git a/extensions/cocostudio/armature/display/CCSkinRenderCmd.js b/extensions/cocostudio/armature/display/CCSkinRenderCmd.js index a57b625494..c37bc9d960 100644 --- a/extensions/cocostudio/armature/display/CCSkinRenderCmd.js +++ b/extensions/cocostudio/armature/display/CCSkinRenderCmd.js @@ -23,7 +23,7 @@ THE SOFTWARE. ****************************************************************************/ -(function(){ +(function () { ccs.Skin.RenderCmd = { _realWorldTM: null, transform: function (parentCmd, recursive) { @@ -40,10 +40,10 @@ } 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.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; @@ -63,16 +63,16 @@ } } else { - wt.a = t.a; - wt.b = t.b; - wt.c = t.c; - wt.d = t.d; + wt.a = t.a; + wt.b = t.b; + wt.c = t.c; + wt.d = t.d; wt.tx = t.tx; wt.ty = t.ty; } var rwtm = this._realWorldTM; - if(rwtm) { - rwtm.a = t.a; rwtm.b = t.b; rwtm.c = t.c; rwtm.d = t.d; rwtm.tx= t.tx; rwtm.ty = t.ty; + if (rwtm) { + rwtm.a = t.a; rwtm.b = t.b; rwtm.c = t.c; rwtm.d = t.d; rwtm.tx = t.tx; rwtm.ty = t.ty; cc.affineTransformConcatIn(rwtm, this._node.bone.getArmature()._renderCmd._worldTransform); } }, diff --git a/extensions/cocostudio/loader/load.js b/extensions/cocostudio/loader/load.js index 46ac7eab01..bf75cce354 100644 --- a/extensions/cocostudio/loader/load.js +++ b/extensions/cocostudio/loader/load.js @@ -22,7 +22,7 @@ THE SOFTWARE. ****************************************************************************/ -ccs._load = (function(){ +ccs._load = (function () { /** * load file @@ -31,43 +31,43 @@ ccs._load = (function(){ * @param {String} [path=] - Resource search path * @returns {*} */ - var load = function(file, type, path){ + var load = function (file, type, path) { var json = cc.loader.getRes(file); - if(!json) + if (!json) return cc.log("%s does not exist", file); var ext = extname(file).toLocaleLowerCase(); - if(ext !== "json" && ext !== "exportjson") + if (ext !== "json" && ext !== "exportjson") return cc.log("%s load error, must be json file", file); var parse; - if(!type){ - if(json["widgetTree"]) + if (!type) { + if (json["widgetTree"]) parse = parser["ccui"]; - else if(json["nodeTree"]) + else if (json["nodeTree"]) parse = parser["timeline"]; - else if(json["Content"] && json["Content"]["Content"]) + else if (json["Content"] && json["Content"]["Content"]) parse = parser["timeline"]; - else if(json["gameobjects"]) + else if (json["gameobjects"]) parse = parser["scene"]; - }else{ + } else { parse = parser[type]; } - if(!parse){ + if (!parse) { cc.log("Can't find the parser : %s", file); return new cc.Node(); } var version = json["version"] || json["Version"]; - if(!version && json["armature_data"]){ + if (!version && json["armature_data"]) { cc.warn("%s is armature. please use:", file); cc.warn(" ccs.armatureDataManager.addArmatureFileInfoAsync(%s);", file); cc.warn(" var armature = new ccs.Armature('name');"); return new cc.Node(); } var currentParser = getParser(parse, version); - if(!currentParser){ + if (!currentParser) { cc.log("Can't find the parser : %s", file); return new cc.Node(); } @@ -82,24 +82,24 @@ ccs._load = (function(){ "scene": {} }; - load.registerParser = function(name, version, target){ - if(!name || !version || !target) + load.registerParser = function (name, version, target) { + if (!name || !version || !target) return cc.log("register parser error"); - if(!parser[name]) + if (!parser[name]) parser[name] = {}; parser[name][version] = target; }; - load.getParser = function(name, version){ - if(name && version) + load.getParser = function (name, version) { + if (name && version) return parser[name] ? parser[name][version] : undefined; - if(name) + if (name) return parser[name]; return parser; }; //Gets the file extension - var extname = function(fileName){ + var extname = function (fileName) { var arr = fileName.match(extnameReg); return ( arr && arr[1] ) ? arr[1] : null; }; @@ -107,10 +107,10 @@ ccs._load = (function(){ var parserReg = /([^\.](\.\*)?)*$/; - var getParser = function(parser, version){ - if(parser[version]) + var getParser = function (parser, version) { + if (parser[version]) return parser[version]; - else if(version === "*") + else if (version === "*") return null; else return getParser(parser, version.replace(parserReg, "*")); @@ -122,25 +122,25 @@ ccs._load = (function(){ ccs._parser = cc.Class.extend({ - ctor: function(){ + ctor: function () { this.parsers = {}; }, _dirnameReg: /\S*\//, - _dirname: function(path){ + _dirname: function (path) { var arr = path.match(this._dirnameReg); return (arr && arr[0]) ? arr[0] : ""; }, - getClass: function(json){ + getClass: function (json) { return json["classname"]; }, - getNodeJson: function(json){ + getNodeJson: function (json) { return json["widgetTree"]; }, - parse: function(file, json, resourcePath){ + parse: function (file, json, resourcePath) { resourcePath = resourcePath || this._dirname(file); this.pretreatment(json, resourcePath); var node = this.parseNode(this.getNodeJson(json), resourcePath, file); @@ -148,14 +148,16 @@ ccs._parser = cc.Class.extend({ return node; }, - pretreatment: function(json, resourcePath, file){}, + pretreatment: function (json, resourcePath, file) { + }, - deferred: function(json, resourcePath, node, file){}, + deferred: function (json, resourcePath, node, file) { + }, - parseNode: function(json, resourcePath){ + parseNode: function (json, resourcePath) { var parser = this.parsers[this.getClass(json)]; var widget = null; - if(parser) + if (parser) widget = parser.call(this, json, resourcePath); else cc.log("Can't find the parser : %s", this.getClass(json)); @@ -163,7 +165,7 @@ ccs._parser = cc.Class.extend({ return widget; }, - registerParser: function(widget, parse){ + registerParser: function (widget, parse) { this.parsers[widget] = parse; } }); @@ -180,7 +182,7 @@ ccs._parser = cc.Class.extend({ * @param {String} [path=] Resource path * @returns {{node: cc.Node, action: cc.Action}} */ -ccs.load = function(file, path){ +ccs.load = function (file, path) { var object = { node: null, action: null @@ -188,7 +190,7 @@ ccs.load = function(file, path){ object.node = ccs._load(file, null, path); object.action = ccs._load(file, "action", path); - if(object.action && object.action.tag === -1 && object.node) + if (object.action && object.action.tag === -1 && object.node) object.action.tag = object.node.tag; return object; }; @@ -208,10 +210,10 @@ ccs.load.preload = true; * @param {String} [path=] Resource path * @returns {{node: cc.Node, action: cc.Action}} */ -ccs.loadWithVisibleSize = function(file, path){ +ccs.loadWithVisibleSize = function (file, path) { var object = ccs.load(file, path); var size = cc.director.getVisibleSize(); - if(object.node && size){ + if (object.node && size) { object.node.setContentSize(size.width, size.height); ccui.helper.doLayout(object.node); } @@ -229,7 +231,7 @@ ccs.actionTimelineCache = { * @param file * @returns {*} */ - createAction: function(file){ + createAction: function (file) { return ccs._load(file, "action"); } }; @@ -242,37 +244,37 @@ ccs.csLoader = { * @param file * @returns {*} */ - createNode: function(file){ + createNode: function (file) { return ccs._load(file); } }; cc.loader.register(["json"], { - load : function(realUrl, url, res, cb){ - cc.loader.loadJson(realUrl, function(error, data){ + load: function (realUrl, url, res, cb) { + cc.loader.loadJson(realUrl, function (error, data) { var path = cc.path; - if(data && data["Content"] && data["Content"]["Content"]["UsedResources"]){ + if (data && data["Content"] && data["Content"]["Content"]["UsedResources"]) { var UsedResources = data["Content"]["Content"]["UsedResources"], dirname = path.dirname(url), list = [], tmpUrl, normalUrl; - for(var i=0; i= 1700){ + if (!version || versionNum >= 1700) { cc.warn("Not supported file types, Please try use the ccs.load"); return null; } @@ -63,16 +63,16 @@ * @param callback * @deprecated This function will be deprecated sooner or later please use parser.registerParser */ - registerTypeAndCallBack: function(classType, ins, object, callback){ + registerTypeAndCallBack: function (classType, ins, object, callback) { var parser = ccs._load.getParser("ccui")["*"]; var func = callback.bind(object); - parser.registerParser(classType, function(options, resourcePath){ + parser.registerParser(classType, function (options, resourcePath) { var widget = new ins(); var uiOptions = options["options"]; object.setPropsFromJsonDictionary && object.setPropsFromJsonDictionary(widget, uiOptions); this.generalAttributes(widget, uiOptions); var customProperty = uiOptions["customProperty"]; - if(customProperty) + if (customProperty) customProperty = JSON.parse(customProperty); else customProperty = {}; @@ -90,13 +90,13 @@ * @param {String} version version string. * @returns {Number} */ - getVersionInteger: function(version){ - if(!version || typeof version !== "string") return 0; + getVersionInteger: function (version) { + if (!version || typeof version !== "string") return 0; var arr = version.split("."); if (arr.length !== 4) return 0; var num = 0; - arr.forEach(function(n, i){ + arr.forEach(function (n, i) { num += n * Math.pow(10, 3 - i); }); return num; @@ -127,12 +127,12 @@ * Returns the file path * @returns {string} */ - getFilePath: function(){ + getFilePath: function () { return this._filePath; }, //@deprecated This function will be deprecated sooner or later - setFilePath: function(path){ + setFilePath: function (path) { this._filePath = path; }, @@ -141,7 +141,7 @@ * Returns the parsed object map. (analytic function) * @returns {Object} */ - getParseObjectMap: function(){ + getParseObjectMap: function () { return ccs._load.getParser("ccui")["*"]["parsers"]; }, @@ -150,31 +150,32 @@ * Returns the parsed callback map. (analytic function) * @returns {*} */ - getParseCallBackMap: function(){ + getParseCallBackMap: function () { return ccs._load.getParser("ccui")["*"]["parsers"]; }, //@deprecated This function will be deprecated sooner or later - clear: function(){} + clear: function () { + } }; var parser = ccs._load.getParser("ccui")["*"]; - ccs.imageViewReader = {setPropsFromJsonDictionary: parser.ImageViewAttributes}; - ccs.buttonReader = {setPropsFromJsonDictionary: parser.ButtonAttributes}; - ccs.checkBoxReader = {setPropsFromJsonDictionary: parser.CheckBoxAttributes}; + ccs.imageViewReader = {setPropsFromJsonDictionary: parser.ImageViewAttributes}; + ccs.buttonReader = {setPropsFromJsonDictionary: parser.ButtonAttributes}; + ccs.checkBoxReader = {setPropsFromJsonDictionary: parser.CheckBoxAttributes}; ccs.labelAtlasReader = {setPropsFromJsonDictionary: parser.TextAtlasAttributes}; - ccs.labelBMFontReader= {setPropsFromJsonDictionary: parser.TextBMFontAttributes}; - ccs.labelReader = {setPropsFromJsonDictionary: parser.TextAttributes}; - ccs.layoutReader = {setPropsFromJsonDictionary: parser.LayoutAttributes}; - ccs.listViewReader = {setPropsFromJsonDictionary: parser.ListViewAttributes}; + ccs.labelBMFontReader = {setPropsFromJsonDictionary: parser.TextBMFontAttributes}; + ccs.labelReader = {setPropsFromJsonDictionary: parser.TextAttributes}; + ccs.layoutReader = {setPropsFromJsonDictionary: parser.LayoutAttributes}; + ccs.listViewReader = {setPropsFromJsonDictionary: parser.ListViewAttributes}; ccs.loadingBarReader = {setPropsFromJsonDictionary: parser.LoadingBarAttributes}; - ccs.pageViewReader = {setPropsFromJsonDictionary: parser.PageViewAttributes}; + ccs.pageViewReader = {setPropsFromJsonDictionary: parser.PageViewAttributes}; ccs.scrollViewReader = {setPropsFromJsonDictionary: parser.ScrollViewAttributes}; - ccs.sliderReader = {setPropsFromJsonDictionary: parser.SliderAttributes}; - ccs.textFieldReader = {setPropsFromJsonDictionary: parser.TextFieldAttributes}; + ccs.sliderReader = {setPropsFromJsonDictionary: parser.SliderAttributes}; + ccs.textFieldReader = {setPropsFromJsonDictionary: parser.TextFieldAttributes}; })(); -(function(){ +(function () { ccs.sceneReader = { _node: null, @@ -185,7 +186,7 @@ * @param file * @returns {*} */ - createNodeWithSceneFile: function(file){ + createNodeWithSceneFile: function (file) { var node = ccs._load(file, "scene"); this._node = node; return node; @@ -196,7 +197,7 @@ * @param {Number} tag * @returns {cc.Node|null} */ - getNodeByTag: function(tag){ + getNodeByTag: function (tag) { if (this._node == null) return null; if (this._node.getTag() === tag) @@ -228,7 +229,7 @@ * Returns the version of ccs.SceneReader. * @returns {string} */ - version: function(){ + version: function () { return "*"; }, @@ -237,15 +238,16 @@ * Sets the listener to reader. * Cannot use */ - setTarget: function(){}, + setTarget: function () { + }, //@deprecated This function will be deprecated sooner or later /** * Clear all triggers and stops all sounds. */ - clear: function(){ + clear: function () { ccs.triggerManager.removeAll(); cc.audioEngine.end(); } }; -})(); \ No newline at end of file +})(); diff --git a/extensions/cocostudio/loader/parsers/scene-1.x.js b/extensions/cocostudio/loader/parsers/scene-1.x.js index 04569cb17f..8982f26bfc 100644 --- a/extensions/cocostudio/loader/parsers/scene-1.x.js +++ b/extensions/cocostudio/loader/parsers/scene-1.x.js @@ -22,18 +22,18 @@ THE SOFTWARE. ****************************************************************************/ -(function(load, baseParser){ +(function (load, baseParser) { var Parser = baseParser.extend({ - getNodeJson: function(json){ + getNodeJson: function (json) { return json; }, - parseNode: function(json, resourcePath){ + parseNode: function (json, resourcePath) { var parser = this.parsers[this.getClass(json)]; var node = null; - if(parser) + if (parser) node = parser.call(this, json, resourcePath); else cc.log("Can't find the parser : %s", this.getClass(json)); @@ -41,32 +41,32 @@ return node; }, - deferred: function(json, resourcePath, node, file){ - ccs.triggerManager.parse(json["Triggers"]||[]); - if(ccs.sceneReader) + deferred: function (json, resourcePath, node, file) { + ccs.triggerManager.parse(json["Triggers"] || []); + if (ccs.sceneReader) ccs.sceneReader._node = node; }, - setPropertyFromJsonDict: function(node, json){ - var x = (cc.isUndefined(json["x"]))?0:json["x"]; - var y = (cc.isUndefined(json["y"]))?0:json["y"]; + setPropertyFromJsonDict: function (node, json) { + var x = (cc.isUndefined(json["x"])) ? 0 : json["x"]; + var y = (cc.isUndefined(json["y"])) ? 0 : json["y"]; node.setPosition(x, y); - var bVisible = Boolean((cc.isUndefined(json["visible"]))?1:json["visible"]); + var bVisible = Boolean((cc.isUndefined(json["visible"])) ? 1 : json["visible"]); node.setVisible(bVisible); - var nTag = (cc.isUndefined(json["objecttag"]))?-1:json["objecttag"]; + var nTag = (cc.isUndefined(json["objecttag"])) ? -1 : json["objecttag"]; node.setTag(nTag); - var nZorder = (cc.isUndefined(json["zorder"]))?0:json["zorder"]; + var nZorder = (cc.isUndefined(json["zorder"])) ? 0 : json["zorder"]; node.setLocalZOrder(nZorder); - var fScaleX = (cc.isUndefined(json["scalex"]))?1:json["scalex"]; - var fScaleY = (cc.isUndefined(json["scaley"]))?1:json["scaley"]; + var fScaleX = (cc.isUndefined(json["scalex"])) ? 1 : json["scalex"]; + var fScaleY = (cc.isUndefined(json["scaley"])) ? 1 : json["scaley"]; node.setScaleX(fScaleX); node.setScaleY(fScaleY); - var fRotationZ = (cc.isUndefined(json["rotation"]))?0:json["rotation"]; + var fRotationZ = (cc.isUndefined(json["rotation"])) ? 0 : json["rotation"]; node.setRotation(fRotationZ); var sName = json["name"] || ""; @@ -77,24 +77,24 @@ var parser = new Parser(); - parser.parseChild = function(node, objects, resourcePath){ + parser.parseChild = function (node, objects, resourcePath) { for (var i = 0; i < objects.length; i++) { var child, options = objects[i]; - if(options) + if (options) child = this.parseNode(options, resourcePath); - if(child) + if (child) node.addChild(child); } }; var componentsParser = { - "CCSprite": function(node, component, resourcePath){ + "CCSprite": function (node, component, resourcePath) { var child = new cc.Sprite(); - loadTexture(component["fileData"], resourcePath, function(path, type){ - if(type === 0) + loadTexture(component["fileData"], resourcePath, function (path, type) { + if (type === 0) child.setTexture(path); - else if(type === 1){ + else if (type === 1) { var spriteFrame = cc.spriteFrameCache.getSpriteFrame(path); child.setSpriteFrame(spriteFrame); } @@ -103,20 +103,20 @@ node.addComponent(render); return render; }, - "CCTMXTiledMap": function(node, component, resourcePath){ + "CCTMXTiledMap": function (node, component, resourcePath) { var child = null; - loadTexture(component["fileData"], resourcePath, function(path, type){ - if(type === 0) + loadTexture(component["fileData"], resourcePath, function (path, type) { + if (type === 0) child = new cc.TMXTiledMap(path); }); var render = new ccs.ComRender(child, "CCTMXTiledMap"); node.addComponent(render); return render; }, - "CCParticleSystemQuad": function(node, component, resourcePath){ + "CCParticleSystemQuad": function (node, component, resourcePath) { var child = null; - loadTexture(component["fileData"], resourcePath, function(path, type){ - if(type === 0) + loadTexture(component["fileData"], resourcePath, function (path, type) { + if (type === 0) child = new cc.ParticleSystem(path); else cc.log("unknown resourcetype on CCParticleSystemQuad!"); @@ -126,10 +126,10 @@ node.addComponent(render); return render; }, - "CCArmature": function(node, component, resourcePath){ + "CCArmature": function (node, component, resourcePath) { var child = null; - loadTexture(component["fileData"], resourcePath, function(path, type){ - if(type === 0){ + loadTexture(component["fileData"], resourcePath, function (path, type) { + if (type === 0) { var jsonDict = cc.loader.getRes(path); if (!jsonDict) cc.log("Please load the resource [%s] first!", path); var armature_data = jsonDict["armature_data"]; @@ -139,7 +139,7 @@ child = new ccs.Armature(name); } }); - if(child){ + if (child) { var render = new ccs.ComRender(child, "CCArmature"); node.addComponent(render); var actionName = component["selectedactionname"]; @@ -150,101 +150,103 @@ } }, - "CCComAudio": function(node, component, resourcePath){ + "CCComAudio": function (node, component, resourcePath) { var audio = null; - loadTexture(component["fileData"], resourcePath, function(path, type){ - if(type === 0){ + loadTexture(component["fileData"], resourcePath, function (path, type) { + if (type === 0) { audio = new ccs.ComAudio(); audio.preloadEffect(path); var name = component["name"]; - if(name) + if (name) audio.setName(name); node.addComponent(audio); } }); }, - "CCComAttribute": function(node, component, resourcePath){ + "CCComAttribute": function (node, component, resourcePath) { var attribute = null; - loadTexture(component["fileData"], resourcePath, function(path, type){ - if(type === 0){ + loadTexture(component["fileData"], resourcePath, function (path, type) { + if (type === 0) { attribute = new ccs.ComAttribute(); if (path !== "") attribute.parse(path); node.addComponent(attribute); - }else + } else cc.log("unknown resourcetype on CCComAttribute!"); }); return attribute; }, - "CCBackgroundAudio": function(node, component, resourcePath){ + "CCBackgroundAudio": function (node, component, resourcePath) { var audio = null; - loadTexture(component["fileData"], resourcePath, function(path, type){ - if(type === 0){ + loadTexture(component["fileData"], resourcePath, function (path, type) { + if (type === 0) { audio = new ccs.ComAudio(); audio.preloadBackgroundMusic(path); - audio.setFile(path);var bLoop = Boolean(component["loop"] || 0); + audio.setFile(path); + var bLoop = Boolean(component["loop"] || 0); audio.setLoop(bLoop); var name = component["name"]; - if(name) + if (name) audio.setName(name); node.addComponent(audio); audio.playBackgroundMusic(path, bLoop); } }); }, - "GUIComponent": function(node, component, resourcePath){ + "GUIComponent": function (node, component, resourcePath) { var widget = null; - loadTexture(component["fileData"], resourcePath, function(path, type){ + loadTexture(component["fileData"], resourcePath, function (path, type) { widget = ccs._load(path, "ccui"); }); var render = new ccs.ComRender(widget, "GUIComponent"); node.addComponent(render); return render; }, - "CCScene": function(){} + "CCScene": function () { + } }; var loadedPlist = {}; - var loadTexture = function(json, resourcePath, cb){ - if(json != null){ + var loadTexture = function (json, resourcePath, cb) { + if (json != null) { var path = json["path"]; var type = json["resourceType"]; var plist = json["plist"]; - if(!path) + if (!path) return; - if(plist){ - if(cc.loader.getRes(resourcePath + plist)){ + if (plist) { + if (cc.loader.getRes(resourcePath + plist)) { loadedPlist[resourcePath + plist] = true; cc.spriteFrameCache.addSpriteFrames(resourcePath + plist); - }else{ - if(!loadedPlist[resourcePath + plist]) + } else { + if (!loadedPlist[resourcePath + plist]) cc.log("%s need to be preloaded", resourcePath + plist); } } - if(type !== 0) + if (type !== 0) cb(path, type); else cb(resourcePath + path, type); } }; - parser.parseComponents = function(node, json, resourcePath){ - if(!node || !json) + parser.parseComponents = function (node, json, resourcePath) { + if (!node || !json) return; - json.forEach(function(component){ + json.forEach(function (component) { var parser = componentsParser[component["classname"]]; var render = null; - if(parser) + if (parser) render = parser(node, component, resourcePath); else cc.log("Can't find the component parser : %s", component["classname"]); var name = component["name"]; - if(render && name){ + if (render && name) { render.setName(name); } }); }; - parser.registerParser("CCNode", function(options, resourcePath){ + parser.registerParser("CCNode", function (options, resourcePath) { var node = new cc.Node(); this.setPropertyFromJsonDict(node, options); this.parseChild.call(this, node, options["gameobjects"], resourcePath); diff --git a/extensions/cocostudio/loader/parsers/timelineParser-1.x.js b/extensions/cocostudio/loader/parsers/timelineParser-1.x.js index 61a04a2fbf..1e9d907805 100644 --- a/extensions/cocostudio/loader/parsers/timelineParser-1.x.js +++ b/extensions/cocostudio/loader/parsers/timelineParser-1.x.js @@ -22,22 +22,22 @@ THE SOFTWARE. ****************************************************************************/ -(function(load, baseParser){ +(function (load, baseParser) { var loadedPlist = {}; var Parser = baseParser.extend({ - getNodeJson: function(json){ + getNodeJson: function (json) { return json["nodeTree"]; }, - addSpriteFrame: function(plists, pngs, resourcePath){ - if(!plists || !pngs || plists.length !== pngs.length) + addSpriteFrame: function (plists, pngs, resourcePath) { + if (!plists || !pngs || plists.length !== pngs.length) return; for (var i = 0; i < plists.length; i++) { var plist = resourcePath + plists[i]; - if(!cc.loader.getRes(plist) && !loadedPlist[plist]) + if (!cc.loader.getRes(plist) && !loadedPlist[plist]) cc.log("%s need to be preloaded", plist); else loadedPlist[plist] = true; @@ -48,67 +48,65 @@ } }, - pretreatment: function(json, resourcePath, file){ + pretreatment: function (json, resourcePath, file) { this.addSpriteFrame(json["textures"], json["texturesPng"], resourcePath); } }); var parser = new Parser(); - parser.generalAttributes = function(node, options){ - var width = options["width"] !=null ? options["width"] : 0; - var height = options["height"] !=null ? options["height"] : 0; - var x = options["x"] !=null ? options["x"] : 0; - var y = options["y"] !=null ? options["y"] : 0; - var scalex = options["scaleX"] !=null ? options["scaleX"] : 1; - var scaley = options["scaleY"] !=null ? options["scaleY"] : 1; - var rotation = options["rotation"] !=null ? options["rotation"] : 0; - var rotationSkewX = options["rotationSkewX"]!=null ? options["rotationSkewX"] : 0; - var rotationSkewY = options["rotationSkewY"]!=null ? options["rotationSkewY"] : 0; - var skewx = options["skewX"] !=null ? options["skewX"] : 0; - var skewy = options["skewY"] !=null ? options["skewY"] : 0; - var anchorx = options["anchorPointX"] !=null ? options["anchorPointX"] : 0.5; - var anchory = options["anchorPointY"] !=null ? options["anchorPointY"] : 0.5; - var alpha = options["opacity"] !=null ? options["opacity"] : 255; - var red = options["colorR"] !=null ? options["colorR"] : 255; - var green = options["colorG"] !=null ? options["colorG"] : 255; - var blue = options["colorB"] !=null ? options["colorB"] : 255; - var zorder = options["colorR"] !=null ? options["colorR"] : 0; - var tag = options["tag"] !=null ? options["tag"] : 0; - var actionTag = options["actionTag"] !=null ? options["actionTag"] : 0; - var visible = options["visible"] !=null ? options["visible"] : true; + parser.generalAttributes = function (node, options) { + var width = options["width"] != null ? options["width"] : 0; + var height = options["height"] != null ? options["height"] : 0; + var x = options["x"] != null ? options["x"] : 0; + var y = options["y"] != null ? options["y"] : 0; + var scalex = options["scaleX"] != null ? options["scaleX"] : 1; + var scaley = options["scaleY"] != null ? options["scaleY"] : 1; + var rotation = options["rotation"] != null ? options["rotation"] : 0; + var rotationSkewX = options["rotationSkewX"] != null ? options["rotationSkewX"] : 0; + var rotationSkewY = options["rotationSkewY"] != null ? options["rotationSkewY"] : 0; + var skewx = options["skewX"] != null ? options["skewX"] : 0; + var skewy = options["skewY"] != null ? options["skewY"] : 0; + var anchorx = options["anchorPointX"] != null ? options["anchorPointX"] : 0.5; + var anchory = options["anchorPointY"] != null ? options["anchorPointY"] : 0.5; + var alpha = options["opacity"] != null ? options["opacity"] : 255; + var red = options["colorR"] != null ? options["colorR"] : 255; + var green = options["colorG"] != null ? options["colorG"] : 255; + var blue = options["colorB"] != null ? options["colorB"] : 255; + var zorder = options["colorR"] != null ? options["colorR"] : 0; + var tag = options["tag"] != null ? options["tag"] : 0; + var actionTag = options["actionTag"] != null ? options["actionTag"] : 0; + var visible = options["visible"] != null ? options["visible"] : true; - if(x != 0 || y != 0) + if (x != 0 || y != 0) node.setPosition(cc.p(x, y)); - if(scalex != 1) + if (scalex != 1) node.setScaleX(scalex); - if(scaley != 1) + if (scaley != 1) node.setScaleY(scaley); if (rotation != 0) node.setRotation(rotation); - if(rotationSkewX != 0) + if (rotationSkewX != 0) node.setRotationX(rotationSkewX); - if(rotationSkewY != 0) + if (rotationSkewY != 0) node.setRotationY(rotationSkewY); - if(skewx != 0) + if (skewx != 0) node.setSkewX(skewx); - if(skewy != 0) + if (skewy != 0) node.setSkewY(skewy); - if(anchorx != 0.5 || anchory != 0.5) + if (anchorx != 0.5 || anchory != 0.5) node.setAnchorPoint(cc.p(anchorx, anchory)); - if(width != 0 || height != 0) + if (width != 0 || height != 0) node.setContentSize(cc.size(width, height)); - if(zorder != 0) + if (zorder != 0) node.setLocalZOrder(zorder); - if(visible != true) + if (visible != true) node.setVisible(visible); - if(alpha != 255) - { + if (alpha != 255) { node.setOpacity(alpha); } - if(red != 255 || green != 255 || blue != 255) - { + if (red != 255 || green != 255 || blue != 255) { node.setColor(cc.color(red, green, blue)); } @@ -117,32 +115,32 @@ node.setUserObject(new ccs.ActionTimelineData(actionTag)); }; - parser.parseComponent = function(node, options){ - if(!options) return; - for (var i = 0; i < options.length; ++i){ + parser.parseComponent = function (node, options) { + if (!options) return; + for (var i = 0; i < options.length; ++i) { var dic = options[i]; var component = this.loadComponent(dic); - if (component){ + if (component) { node.addComponent(component); } } }; - parser.parseChild = function(parse, widget, options, resourcePath){ + parser.parseChild = function (parse, widget, options, resourcePath) { var children = options["children"]; for (var i = 0; i < children.length; i++) { var child = this.parseNode(children[i], resourcePath); - if(child){ - if(widget instanceof ccui.PageView){ - if(child instanceof ccui.Layout) + if (child) { + if (widget instanceof ccui.PageView) { + if (child instanceof ccui.Layout) widget.addPage(child); } else { - if(widget instanceof ccui.ListView){ - if(child instanceof ccui.Widget) + if (widget instanceof ccui.ListView) { + if (child instanceof ccui.Widget) widget.pushBackCustomItem(child); } else { - if(!(widget instanceof ccui.Layout) && child instanceof ccui.Widget) { - if(child.getPositionType() === ccui.Widget.POSITION_PERCENT) { + if (!(widget instanceof ccui.Layout) && child instanceof ccui.Widget) { + if (child.getPositionType() === ccui.Widget.POSITION_PERCENT) { var position = child.getPositionPercent(); var anchor = widget.getAnchorPoint(); child.setPositionPercent(cc.p(position.x + anchor.x, position.y + anchor.y)); @@ -158,53 +156,53 @@ } }; - parser.initNode = function(options){ + parser.initNode = function (options) { var node = new cc.Node(); this.generalAttributes(node, options); return node; }; - parser.initSubGraph = function(options){ + parser.initSubGraph = function (options) { var filePath = options["fileName"]; var node; - if (filePath && "" !== filePath){ + if (filePath && "" !== filePath) { node = this.createNode(filePath); - }else{ + } else { node = new ccs.Node(); } this.generalAttributes(node, options); return node; }; - parser.initSprite = function(options, resourcePath){ + parser.initSprite = function (options, resourcePath) { var path = options["fileName"]; var sprite; - if(path != null){ + if (path != null) { var spriteFrame = cc.spriteFrameCache.getSpriteFrame(path); - if(!spriteFrame){ + if (!spriteFrame) { path = resourcePath + path; sprite = new ccs.Sprite(path); - }else{ + } else { sprite = ccs.Sprite.createWithSpriteFrame(spriteFrame); } - if(!sprite){ + if (!sprite) { sprite = new cc.Sprite(); cc.log("filePath is empty. Create a sprite with no texture"); } - }else{ + } else { sprite = new ccs.Sprite(); } this.generalAttributes(sprite, options); var flipX = options["flipX"]; var flipY = options["flipY"]; - if(flipX != false) + if (flipX != false) sprite.setFlippedX(flipX); - if(flipY != false) + if (flipY != false) sprite.setFlippedY(flipY); return sprite; }; - parser.initParticle = function(options, resourcePath){ + parser.initParticle = function (options, resourcePath) { var filePath = options["plistFile"]; var num = options["tmxFile"]; var particle = new cc.ParticleSystemQuad(filePath); @@ -212,41 +210,41 @@ this.generalAttributes(particle, options); return particle; }; - parser.initTMXTiledMap = function(options, resourcePath){ + parser.initTMXTiledMap = function (options, resourcePath) { var tmxFile = options["tmxFile"]; var tmxString = options["tmxString"]; //todo check path and resourcePath var path = options["resourcePath"]; var tmx = null; - if (tmxFile && "" !== tmxFile){ + if (tmxFile && "" !== tmxFile) { tmx = new cc.TMXTiledMap(tmxFile); - }else if (tmxString && "" !== tmxString && path && "" !== path){ + } else if (tmxString && "" !== tmxString && path && "" !== path) { tmx = new cc.TMXTiledMap(tmxString, path); } return tmx; }; var uiParser = load.getParser("ccui")["*"]; - parser.initWidget = function(options, resourcePath){ + parser.initWidget = function (options, resourcePath) { var type = options["classname"]; var parser = uiParser.parsers[type]; - if(!parser) + if (!parser) return cc.log("%s parser is not found", type); var node = parser.call(uiParser, options, resourcePath); - if(node){ + if (node) { var rotationSkewX = options["rotationSkewX"]; var rotationSkewY = options["rotationSkewY"]; - var skewx = options["skewX"]; - var skewy = options["skewY"]; - if(rotationSkewX != 0) + var skewx = options["skewX"]; + var skewy = options["skewY"]; + if (rotationSkewX != 0) node.setRotationX(rotationSkewX); - if(rotationSkewY != 0) + if (rotationSkewY != 0) node.setRotationY(rotationSkewY); - if(skewx != 0) + if (skewx != 0) node.setSkewX(skewx); - if(skewy != 0) + if (skewy != 0) node.setSkewY(skewy); var actionTag = options["actionTag"]; @@ -278,8 +276,8 @@ {name: "TextField", handle: parser.initWidget} ]; - register.forEach(function(item){ - parser.registerParser(item.name, function(options, parse, resourcePath){ + register.forEach(function (item) { + parser.registerParser(item.name, function (options, parse, resourcePath) { var node = item.handle.call(this, options["options"]); this.parseComponent(node, options["components"]); this.parseChild(parse, node, options, resourcePath); diff --git a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js index f8da6b0210..e79ab9b791 100644 --- a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js +++ b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js @@ -22,15 +22,15 @@ THE SOFTWARE. ****************************************************************************/ -(function(load, baseParser){ +(function (load, baseParser) { var DEBUG = false; var Parser = baseParser.extend({ - parse: function(file, json, path){ + parse: function (file, json, path) { var resourcePath; - if(path !== undefined) + if (path !== undefined) resourcePath = path; else resourcePath = this._dirname(file); @@ -40,15 +40,15 @@ return node; }, - getNodeJson: function(json){ + getNodeJson: function (json) { var content = json["Content"]; - if(content["ObjectData"]) + if (content["ObjectData"]) return content["ObjectData"]; return content["Content"]["ObjectData"]; }, - getClass: function(json){ + getClass: function (json) { return json["ctype"]; } @@ -56,8 +56,8 @@ var parser = new Parser(); - var getParam = function(value, dValue){ - if(value === undefined) + var getParam = function (value, dValue) { + if (value === undefined) return dValue; else return value; @@ -67,19 +67,19 @@ // NODE // ////////// - parser.generalAttributes = function(node, json){ - if(json["Name"] != null) + parser.generalAttributes = function (node, json) { + if (json["Name"] != null) node.setName(json["Name"]); var position = json["Position"]; - if(position != null && (position["X"] != null || position["Y"] != null)) - node.setPosition(cc.p(position["X"]||0, position["Y"]||0)); + if (position != null && (position["X"] != null || position["Y"] != null)) + node.setPosition(cc.p(position["X"] || 0, position["Y"] || 0)); var scale = json["Scale"]; - if(scale != null){ - if(scale["ScaleX"] != null) + if (scale != null) { + if (scale["ScaleX"] != null) node.setScaleX(scale["ScaleX"]); - if(scale["ScaleY"] != null) + if (scale["ScaleY"] != null) node.setScaleY(scale["ScaleY"]); } @@ -93,12 +93,12 @@ var anchor = json["AnchorPoint"]; - if(anchor != null){ - if(anchor["ScaleX"] == null) + if (anchor != null) { + if (anchor["ScaleX"] == null) anchor["ScaleX"] = 0; - if(anchor["ScaleY"] == null) + if (anchor["ScaleY"] == null) anchor["ScaleY"] = 0; - if(anchor["ScaleX"] != 0.5 || anchor["ScaleY"] != 0.5) + if (anchor["ScaleX"] != 0.5 || anchor["ScaleY"] != 0.5) node.setAnchorPoint(cc.p(anchor["ScaleX"], anchor["ScaleY"])); } @@ -109,7 +109,7 @@ node.setVisible(visible); var size = json["Size"]; - if(size) + if (size) setContentSize(node, size); if (json["Alpha"] != null) @@ -120,7 +120,7 @@ var actionTag = json["ActionTag"] || 0; var extensionData = new ccs.ComExtensionData(); var customProperty = json["UserData"]; - if(customProperty !== undefined) + if (customProperty !== undefined) extensionData.setCustomProperty(customProperty); extensionData.setActionTag(actionTag); if (node.getComponent("ComExtensionData")) @@ -133,21 +133,21 @@ setLayoutComponent(node, json); }; - parser.parseChild = function(node, children, resourcePath){ - if(!node || !children) return; + parser.parseChild = function (node, children, resourcePath) { + if (!node || !children) return; for (var i = 0; i < children.length; i++) { var child = this.parseNode(children[i], resourcePath); - if(child){ - if(node instanceof ccui.PageView){ - if(child instanceof ccui.Layout) + if (child) { + if (node instanceof ccui.PageView) { + if (child instanceof ccui.Layout) node.addPage(child); } else { - if(node instanceof ccui.ListView){ - if(child instanceof ccui.Widget) + if (node instanceof ccui.ListView) { + if (child instanceof ccui.Widget) node.pushBackCustomItem(child); } else { - if(!(node instanceof ccui.Layout) && child instanceof ccui.Widget) { - if(child.getPositionType() === ccui.Widget.POSITION_PERCENT) { + if (!(node instanceof ccui.Layout) && child instanceof ccui.Widget) { + if (child.getPositionType() === ccui.Widget.POSITION_PERCENT) { var position = child.getPositionPercent(); var anchor = node.getAnchorPoint(); child.setPositionPercent(cc.p(position.x + anchor.x, position.y + anchor.y)); @@ -165,12 +165,12 @@ * @param json * @returns {cc.Node} */ - parser.initSingleNode = function(json){ + parser.initSingleNode = function (json) { var node = new cc.Node(); this.generalAttributes(node, json); var color = json["CColor"]; - if(color != null) + if (color != null) node.setColor(getColor(color)); return node; @@ -182,21 +182,21 @@ * @param resourcePath * @returns {cc.Sprite} */ - parser.initSprite = function(json, resourcePath){ - var node = new cc.Sprite(); + parser.initSprite = function (json, resourcePath) { + var node = new cc.Sprite(); - loadTexture(json["FileData"], resourcePath, function(path, type){ - if(type === 0) + loadTexture(json["FileData"], resourcePath, function (path, type) { + if (type === 0) node.setTexture(path); - else if(type === 1){ + else if (type === 1) { var spriteFrame = cc.spriteFrameCache.getSpriteFrame(path); - if(spriteFrame) + if (spriteFrame) node.setSpriteFrame(spriteFrame); } }); var blendData = json["BlendFunc"]; - if(json["BlendFunc"]) { + if (json["BlendFunc"]) { var blendFunc = cc.BlendFunc.ALPHA_PREMULTIPLIED; if (blendData["Src"] !== undefined) blendFunc.src = blendData["Src"]; @@ -205,14 +205,14 @@ node.setBlendFunc(blendFunc); } - if(json["FlipX"]) + if (json["FlipX"]) node.setFlippedX(true); - if(json["FlipY"]) + if (json["FlipY"]) node.setFlippedY(true); this.generalAttributes(node, json); var color = json["CColor"]; - if(color != null) + if (color != null) node.setColor(getColor(color)); return node; @@ -224,11 +224,11 @@ * @param resourcePath * @returns {*} */ - parser.initParticle = function(json, resourcePath){ + parser.initParticle = function (json, resourcePath) { var node, self = this; - loadTexture(json["FileData"], resourcePath, function(path, type){ - if(!cc.loader.getRes(path)) + loadTexture(json["FileData"], resourcePath, function (path, type) { + if (!cc.loader.getRes(path)) cc.log("%s need to be preloaded", path); node = new cc.ParticleSystem(path); self.generalAttributes(node, json); @@ -236,11 +236,11 @@ !cc.sys.isNative && node.setDrawMode(cc.ParticleSystem.TEXTURE_MODE); var blendData = json["BlendFunc"]; - if(json["BlendFunc"]){ + if (json["BlendFunc"]) { var blendFunc = cc.BlendFunc.ALPHA_PREMULTIPLIED; - if(blendData["Src"] !== undefined) + if (blendData["Src"] !== undefined) blendFunc.src = blendData["Src"]; - if(blendData["Dst"] !== undefined) + if (blendData["Dst"] !== undefined) blendFunc.dst = blendData["Dst"]; node.setBlendFunc(blendFunc); } @@ -270,7 +270,7 @@ widget.setActionTag(actionTag); var extensionData = new ccs.ComExtensionData(); var customProperty = json["UserData"]; - if(customProperty !== undefined) + if (customProperty !== undefined) extensionData.setCustomProperty(customProperty); extensionData.setActionTag(actionTag); if (widget.getComponent("ComExtensionData")) @@ -347,26 +347,26 @@ bindCallback(widget, json); }; - var bindCallback = function(widget, json){ + var bindCallback = function (widget, json) { var callBackType = json["CallBackType"]; var callBackName = json["CallBackName"]; - var callBack = function(e){ - if(typeof widget[callBackName] === "function") + var callBack = function (e) { + if (typeof widget[callBackName] === "function") widget[callBackName](e); }; - if(callBackType === "Click"){ + if (callBackType === "Click") { widget.addClickEventListener(callBack); - }else if(callBackType === "Touch"){ + } else if (callBackType === "Touch") { widget.addTouchEventListener(callBack); - }else if(callBackType === "Event"){ + } else if (callBackType === "Event") { widget.addCCSEventListener(callBack); } }; - var setLayoutComponent = function(widget, json){ + var setLayoutComponent = function (widget, json) { var layoutComponent = ccui.LayoutComponent.bindLayoutComponent(widget); - if(!layoutComponent) + if (!layoutComponent) return; var positionXPercentEnabled = json["PositionPercentXEnable"] || json["PositionPercentXEnabled"] || false; @@ -378,8 +378,8 @@ positionXPercent = PrePosition["X"] || 0; positionYPercent = PrePosition["Y"] || 0; } - var sizeXPercentEnable = json["PercentWidthEnable"] || json["PercentWidthEnabled"] || false; - var sizeYPercentEnable = json["PercentHeightEnable"]|| json["PercentHeightEnabled"] || false; + var sizeXPercentEnable = json["PercentWidthEnable"] || json["PercentWidthEnabled"] || false; + var sizeYPercentEnable = json["PercentHeightEnable"] || json["PercentHeightEnabled"] || false; var sizeXPercent = 0, sizeYPercent = 0, PreSize = json["PreSize"]; @@ -441,18 +441,18 @@ layoutComponent.setRightMargin(rightMargin); }; - var setLayoutBackground = function(layout, single, first, end){ - if( layout.getBackGroundColorType() === 2 ){ + var setLayoutBackground = function (layout, single, first, end) { + if (layout.getBackGroundColorType() === 2) { first = first || {}; end = end || {}; layout.setBackGroundColor(getColor(first), getColor(end)); - }else{ + } else { single = single || {}; layout.setBackGroundColor(getColor(single)); } }; - var setLayoutBackgroundVector = function(widget, vector){ + var setLayoutBackgroundVector = function (widget, vector) { var x = vector["ScaleX"] || 0; var y = vector["ScaleY"] || 0; widget.setBackGroundColorVector(cc.p(x, y)); @@ -464,34 +464,34 @@ * @param resourcePath * @returns {ccui.Layout} */ - parser.initPanel = function(json, resourcePath){ + parser.initPanel = function (json, resourcePath) { var widget = new ccui.Layout(); this.widgetAttributes(widget, json); var clipEnabled = json["ClipAble"] || false; - if(clipEnabled != null) + if (clipEnabled != null) widget.setClippingEnabled(clipEnabled); var colorType = getParam(json["ComboBoxIndex"], 0); widget.setBackGroundColorType(colorType); var bgColorOpacity = getParam(json["BackColorAlpha"], 255); - if(bgColorOpacity != null) + if (bgColorOpacity != null) widget.setBackGroundColorOpacity(bgColorOpacity); var backGroundScale9Enabled = json["Scale9Enable"]; - if(backGroundScale9Enabled != null) + if (backGroundScale9Enabled != null) widget.setBackGroundImageScale9Enabled(backGroundScale9Enabled); var opacity = getParam(json["Alpha"], 255); widget.setOpacity(opacity); - loadTexture(json["FileData"], resourcePath, function(path, type){ + loadTexture(json["FileData"], resourcePath, function (path, type) { widget.setBackGroundImage(path, type); }); - if(backGroundScale9Enabled){ + if (backGroundScale9Enabled) { var scale9OriginX = json["Scale9OriginX"] || 0; var scale9OriginY = json["Scale9OriginY"] || 0; @@ -503,8 +503,8 @@ )); setContentSize(widget, json["Size"]); - }else{ - if (!widget.isIgnoreContentAdaptWithSize()){ + } else { + if (!widget.isIgnoreContentAdaptWithSize()) { setContentSize(widget, json["Size"]); } @@ -521,37 +521,39 @@ * @param json * @param resourcePath */ - parser.initText = function(json, resourcePath){ + parser.initText = function (json, resourcePath) { var widget = new ccui.Text(); var touchScaleEnabled = json["TouchScaleChangeAble"]; - if(touchScaleEnabled != null) + if (touchScaleEnabled != null) widget.setTouchScaleChangeEnabled(touchScaleEnabled); var text = json["LabelText"]; - if(text != null) + if (text != null) widget.setString(text); var fontSize = json["FontSize"]; - if(fontSize != null) + if (fontSize != null) widget.setFontSize(fontSize); var fontName = json["FontName"]; - if(fontName != null) + if (fontName != null) widget.setFontName(fontName); var areaWidth = json["AreaWidth"]; var areaHeight = json["areaHeight"]; - if(areaWidth && areaHeight) + if (areaWidth && areaHeight) widget.setTextAreaSize(cc.size(areaWidth, areaHeight)); var h_alignment = json["HorizontalAlignmentType"] || "HT_Left"; - switch(h_alignment){ + switch (h_alignment) { case "HT_Right": - h_alignment = 2; break; + h_alignment = 2; + break; case "HT_Center": - h_alignment = 1; break; + h_alignment = 1; + break; case "HT_Left": default: h_alignment = 0; @@ -559,11 +561,13 @@ widget.setTextHorizontalAlignment(h_alignment); var v_alignment = json["VerticalAlignmentType"] || "VT_Top"; - switch(v_alignment){ + switch (v_alignment) { case "VT_Bottom": - v_alignment = 2; break; + v_alignment = 2; + break; case "VT_Center": - v_alignment = 1; break; + v_alignment = 1; + break; case "VT_Top": default: v_alignment = 0; @@ -571,10 +575,10 @@ widget.setTextVerticalAlignment(v_alignment); var fontResource = json["FontResource"]; - if(fontResource != null){ + if (fontResource != null) { var path = fontResource["Path"]; //resoutceType = fontResource["Type"]; - if(path != null){ + if (path != null) { if (cc.sys.isNative) { fontName = cc.path.join(cc.loader.resPath, resourcePath, path); } else { @@ -585,10 +589,10 @@ } } - if(json["OutlineEnabled"] && json["OutlineColor"] && widget.enableOutline) + if (json["OutlineEnabled"] && json["OutlineColor"] && widget.enableOutline) widget.enableOutline(getColor(json["OutlineColor"]), getParam(json["OutlineSize"], 1)); - if(json["ShadowEnabled"] && json["ShadowColor"] && widget.enableShadow) + if (json["ShadowEnabled"] && json["ShadowColor"] && widget.enableShadow) widget.enableShadow( getColor(json["ShadowColor"]), cc.size(getParam(json["ShadowOffsetX"], 2), getParam(json["ShadowOffsetY"], -2)), @@ -596,7 +600,7 @@ ); var isCustomSize = json["IsCustomSize"]; - if(isCustomSize != null) + if (isCustomSize != null) widget.ignoreContentAdaptWithSize(!isCustomSize); widget.setUnifySizeEnabled(false); @@ -615,39 +619,39 @@ * @param json * @param resourcePath */ - parser.initButton = function(json, resourcePath){ + parser.initButton = function (json, resourcePath) { var widget = new ccui.Button(); - loadTexture(json["NormalFileData"], resourcePath, function(path, type){ + loadTexture(json["NormalFileData"], resourcePath, function (path, type) { widget.loadTextureNormal(path, type); }); - loadTexture(json["PressedFileData"], resourcePath, function(path, type){ + loadTexture(json["PressedFileData"], resourcePath, function (path, type) { widget.loadTexturePressed(path, type); }); - loadTexture(json["DisabledFileData"], resourcePath, function(path, type){ + loadTexture(json["DisabledFileData"], resourcePath, function (path, type) { widget.loadTextureDisabled(path, type); }); var scale9Enabled = getParam(json["Scale9Enable"], false); - if(scale9Enabled) { + if (scale9Enabled) { widget.setScale9Enabled(scale9Enabled); } var text = json["ButtonText"]; - if(text != null) + if (text != null) widget.setTitleText(text); var fontSize = json["FontSize"]; - if(fontSize != null) + if (fontSize != null) widget.setTitleFontSize(fontSize); var fontName = json["FontName"]; - if(fontName != null) + if (fontName != null) widget.setTitleFontName(fontName); var textColor = json["TextColor"]; - if(textColor != null) + if (textColor != null) widget.setTitleColor(getColor(textColor)); var displaystate = getParam(json["DisplayState"], true); @@ -655,10 +659,10 @@ widget.setEnabled(displaystate); var fontResource = json["FontResource"]; - if(fontResource != null){ + if (fontResource != null) { var path = fontResource["Path"]; //resoutceType = fontResource["Type"]; - if(path != null){ + if (path != null) { if (cc.sys.isNative) { fontName = cc.path.join(cc.loader.resPath, resourcePath, path); } else { @@ -670,26 +674,26 @@ } var label = widget.getTitleRenderer(); - if(label && json["ShadowEnabled"] && json["ShadowColor"] && label.enableShadow){ + if (label && json["ShadowEnabled"] && json["ShadowColor"] && label.enableShadow) { label.enableShadow( getColor(json["ShadowColor"]), cc.size(getParam(json["ShadowOffsetX"], 2), getParam(json["ShadowOffsetY"], -2)), json["ShadowBlurRadius"] || 0 ); } - if(label && json["OutlineEnabled"] && json["OutlineColor"] && label.enableStroke) + if (label && json["OutlineEnabled"] && json["OutlineColor"] && label.enableStroke) label.enableStroke(getColor(json["OutlineColor"]), getParam(json["OutlineSize"], 1)); this.widgetAttributes(widget, json); - if(scale9Enabled) { + if (scale9Enabled) { widget.setUnifySizeEnabled(false); widget.ignoreContentAdaptWithSize(false); var capInsets = cc.rect( - json["Scale9OriginX"] || 0, - json["Scale9OriginY"] || 0, - json["Scale9Width"] || 0, - json["Scale9Height"] || 0 + json["Scale9OriginX"] || 0, + json["Scale9OriginY"] || 0, + json["Scale9Width"] || 0, + json["Scale9Height"] || 0 ); widget.setCapInsets(capInsets); @@ -706,7 +710,7 @@ * @param json * @param resourcePath */ - parser.initCheckBox = function(json, resourcePath){ + parser.initCheckBox = function (json, resourcePath) { var widget = new ccui.CheckBox(); @@ -720,8 +724,8 @@ {name: "NodeDisableFileData", handle: widget.loadTextureFrontCrossDisabled} ]; - dataList.forEach(function(item){ - loadTexture(json[item.name], resourcePath, function(path, type){ + dataList.forEach(function (item) { + loadTexture(json[item.name], resourcePath, function (path, type) { item.handle.call(widget, path, type); }); }); @@ -741,12 +745,12 @@ * @param json * @param resourcePath */ - parser.initScrollView = function(json, resourcePath){ + parser.initScrollView = function (json, resourcePath) { var widget = new ccui.ScrollView(); this.widgetAttributes(widget, json); - loadTexture(json["FileData"], resourcePath, function(path, type){ + loadTexture(json["FileData"], resourcePath, function (path, type) { widget.setBackGroundImage(path, type); }); @@ -757,11 +761,11 @@ widget.setBackGroundColorType(colorType); var bgColorOpacity = json["BackColorAlpha"]; - if(bgColorOpacity != null) + if (bgColorOpacity != null) widget.setBackGroundColorOpacity(bgColorOpacity); var backGroundScale9Enabled = json["Scale9Enable"]; - if(backGroundScale9Enabled){ + if (backGroundScale9Enabled) { widget.setBackGroundImageScale9Enabled(true); @@ -773,7 +777,7 @@ scale9OriginX, scale9OriginY, scale9Width, scale9Height )); setContentSize(widget, json["Size"]); - }else if(!widget.isIgnoreContentAdaptWithSize()){ + } else if (!widget.isIgnoreContentAdaptWithSize()) { setContentSize(widget, json["Size"]); } @@ -788,9 +792,9 @@ widget.setInnerContainerSize(innerSize); var direction = 0; - if(json["ScrollDirectionType"] === "Vertical") direction = 1; - if(json["ScrollDirectionType"] === "Horizontal") direction = 2; - if(json["ScrollDirectionType"] === "Vertical_Horizontal") direction = 3; + if (json["ScrollDirectionType"] === "Vertical") direction = 1; + if (json["ScrollDirectionType"] === "Horizontal") direction = 2; + if (json["ScrollDirectionType"] === "Vertical_Horizontal") direction = 3; widget.setDirection(direction); var bounceEnabled = getParam(json["IsBounceEnabled"], false); @@ -804,19 +808,19 @@ * @param json * @param resourcePath */ - parser.initImageView = function(json, resourcePath){ + parser.initImageView = function (json, resourcePath) { var widget = new ccui.ImageView(); - loadTexture(json["FileData"], resourcePath, function(path, type){ + loadTexture(json["FileData"], resourcePath, function (path, type) { widget.loadTexture(path, type); }); - loadTexture(json["ImageFileData"], resourcePath, function(path, type){ + loadTexture(json["ImageFileData"], resourcePath, function (path, type) { widget.loadTexture(path, type); }); var scale9Enabled = json["Scale9Enable"]; - if(scale9Enabled){ + if (scale9Enabled) { widget.setScale9Enabled(true); widget.setUnifySizeEnabled(false); widget.ignoreContentAdaptWithSize(false); @@ -826,7 +830,7 @@ var scale9Width = json["Scale9Width"] || 0; var scale9Height = json["Scale9Height"] || 0; widget.setCapInsets(cc.rect( - scale9OriginX , + scale9OriginX, scale9OriginY, scale9Width, scale9Height @@ -845,13 +849,13 @@ * @param resourcePath * @returns {ccui.LoadingBar} */ - parser.initLoadingBar = function(json, resourcePath){ + parser.initLoadingBar = function (json, resourcePath) { var widget = new ccui.LoadingBar(); this.widgetAttributes(widget, json); - loadTexture(json["ImageFileData"], resourcePath, function(path, type){ + loadTexture(json["ImageFileData"], resourcePath, function (path, type) { widget.loadTexture(path, type); }); @@ -859,7 +863,7 @@ widget.setDirection(direction); var percent = getParam(json["ProgressInfo"], 80); - if(percent != null) + if (percent != null) widget.setPercent(percent); return widget; @@ -871,7 +875,7 @@ * @param json * @param resourcePath */ - parser.initSlider = function(json, resourcePath){ + parser.initSlider = function (json, resourcePath) { var widget = new ccui.Slider(); var loader = cc.loader; @@ -885,9 +889,9 @@ {name: "BallDisabledData", handle: widget.loadSlidBallTextureDisabled}, {name: "ProgressBarData", handle: widget.loadProgressBarTexture} ]; - textureList.forEach(function(item){ - loadTexture(json[item.name], resourcePath, function(path, type){ - if(type === 0 && !loader.getRes(path)) + textureList.forEach(function (item) { + loadTexture(json[item.name], resourcePath, function (path, type) { + if (type === 0 && !loader.getRes(path)) cc.log("%s need to be preloaded", path); item.handle.call(widget, path, type); }); @@ -908,13 +912,13 @@ * @param json * @param resourcePath */ - parser.initPageView = function(json, resourcePath){ + parser.initPageView = function (json, resourcePath) { var widget = new ccui.PageView(); this.widgetAttributes(widget, json); - loadTexture(json["FileData"], resourcePath, function(path, type){ + loadTexture(json["FileData"], resourcePath, function (path, type) { widget.setBackGroundImage(path, type); }); @@ -922,7 +926,7 @@ widget.setClippingEnabled(clipEnabled); var backGroundScale9Enabled = json["Scale9Enable"]; - if(backGroundScale9Enabled){ + if (backGroundScale9Enabled) { widget.setBackGroundImageScale9Enabled(true); var scale9OriginX = json["Scale9OriginX"] || 0; @@ -944,7 +948,7 @@ setLayoutBackgroundVector(widget, json["ColorVector"]); var bgColorOpacity = json["BackColorAlpha"]; - if(bgColorOpacity != null) + if (bgColorOpacity != null) widget.setBackGroundColorOpacity(bgColorOpacity); setContentSize(widget, json["Size"]); @@ -959,13 +963,13 @@ * @param resourcePath * @returns {ccui.ListView} */ - parser.initListView = function(json, resourcePath){ + parser.initListView = function (json, resourcePath) { var widget = new ccui.ListView(); this.widgetAttributes(widget, json); - loadTexture(json["FileData"], resourcePath, function(path, type){ + loadTexture(json["FileData"], resourcePath, function (path, type) { widget.setBackGroundImage(path, type); }); @@ -977,7 +981,7 @@ var bgColorOpacity = getParam(json["BackColorAlpha"], 255); var backGroundScale9Enabled = json["Scale9Enable"]; - if(backGroundScale9Enabled){ + if (backGroundScale9Enabled) { widget.setBackGroundImageScale9Enabled(true); var scale9OriginX = json["Scale9OriginX"] || 0; @@ -995,15 +999,15 @@ var directionType = getParam(json["DirectionType"], ccui.ListView.DIR_HORIZONTAL); var verticalType = getParam(json["VerticalType"], "Align_Left"); var horizontalType = getParam(json["HorizontalType"], "Align_Top"); - if(!directionType){ + if (!directionType) { widget.setDirection(ccui.ScrollView.DIR_HORIZONTAL); - if(verticalType === "Align_Bottom") + if (verticalType === "Align_Bottom") widget.setGravity(ccui.ListView.GRAVITY_BOTTOM); - else if(verticalType === "Align_VerticalCenter") + else if (verticalType === "Align_VerticalCenter") widget.setGravity(ccui.ListView.GRAVITY_CENTER_VERTICAL); else widget.setGravity(ccui.ListView.GRAVITY_TOP); - }else if(directionType === "Vertical"){ + } else if (directionType === "Vertical") { widget.setDirection(ccui.ScrollView.DIR_VERTICAL); if (horizontalType === "") widget.setGravity(ccui.ListView.GRAVITY_LEFT); @@ -1022,13 +1026,13 @@ var innerSize = json["InnerNodeSize"]; //Width - if(innerSize != null) - widget.setInnerContainerSize(cc.size(innerSize["Widget"]||0, innerSize["Height"]||0)); + if (innerSize != null) + widget.setInnerContainerSize(cc.size(innerSize["Widget"] || 0, innerSize["Height"] || 0)); setLayoutBackground(widget, json["SingleColor"], json["FirstColor"], json["EndColor"]); setLayoutBackgroundVector(widget, json["ColorVector"]); - if(bgColorOpacity != null) + if (bgColorOpacity != null) widget.setBackGroundColorOpacity(bgColorOpacity); setContentSize(widget, json["Size"]); @@ -1042,7 +1046,7 @@ * @param resourcePath * @returns {ccui.TextAtlas} */ - parser.initTextAtlas = function(json, resourcePath){ + parser.initTextAtlas = function (json, resourcePath) { var widget = new ccui.TextAtlas(); @@ -1052,10 +1056,10 @@ var startCharMap = json["StartChar"]; - loadTexture(json["LabelAtlasFileImage_CNB"], resourcePath, function(path, type){ - if(!cc.loader.getRes(path)) + loadTexture(json["LabelAtlasFileImage_CNB"], resourcePath, function (path, type) { + if (!cc.loader.getRes(path)) cc.log("%s need to be preloaded", path); - if(type === 0){ + if (type === 0) { widget.setProperty(stringValue, path, itemWidth, itemHeight, startCharMap); } }); @@ -1073,7 +1077,7 @@ * @param resourcePath * @returns {ccui.TextBMFont} */ - parser.initTextBMFont = function(json, resourcePath){ + parser.initTextBMFont = function (json, resourcePath) { var widget = new ccui.TextBMFont(); this.widgetAttributes(widget, json); @@ -1081,8 +1085,8 @@ var text = json["LabelText"]; widget.setString(text); - loadTexture(json["LabelBMFontFile_CNB"], resourcePath, function(path, type){ - if(!cc.loader.getRes(path)) + loadTexture(json["LabelBMFontFile_CNB"], resourcePath, function (path, type) { + if (!cc.loader.getRes(path)) cc.log("%s need to be pre loaded", path); widget.setFntFile(path); }); @@ -1096,30 +1100,30 @@ * @param resourcePath * @returns {ccui.TextField} */ - parser.initTextField = function(json, resourcePath){ + parser.initTextField = function (json, resourcePath) { var widget = new ccui.TextField(); var passwordEnabled = json["PasswordEnable"]; - if(passwordEnabled){ + if (passwordEnabled) { widget.setPasswordEnabled(true); var passwordStyleText = json["PasswordStyleText"] || "*"; widget.setPasswordStyleText(passwordStyleText); } var placeHolder = json["PlaceHolderText"]; - if(placeHolder != null) + if (placeHolder != null) widget.setPlaceHolder(placeHolder); var fontSize = json["FontSize"]; - if(fontSize != null) + if (fontSize != null) widget.setFontSize(fontSize); var fontName = json["FontName"]; - if(fontName != null) + if (fontName != null) widget.setFontName(fontName); var maxLengthEnabled = json["MaxLengthEnable"]; - if(maxLengthEnabled){ + if (maxLengthEnabled) { widget.setMaxLengthEnabled(true); var maxLength = json["MaxLengthText"] || 0; widget.setMaxLength(maxLength); @@ -1129,14 +1133,14 @@ this.widgetAttributes(widget, json); var text = json["LabelText"]; - if(text != null) + if (text != null) widget.setString(text); var fontResource = json["FontResource"]; - if(fontResource != null){ + if (fontResource != null) { var path = fontResource["Path"]; //resoutceType = fontResource["Type"]; - if(path != null){ + if (path != null) { if (cc.sys.isNative) { fontName = cc.path.join(cc.loader.resPath, resourcePath, path); } else { @@ -1151,10 +1155,10 @@ widget.ignoreContentAdaptWithSize(false); var color = json["CColor"]; - if(color != null) + if (color != null) widget.setTextColor(getColor(color)); - if (!widget.isIgnoreContentAdaptWithSize()){ + if (!widget.isIgnoreContentAdaptWithSize()) { setContentSize(widget, json["Size"]); if (cc.sys.isNative) widget.getVirtualRenderer().setLineBreakWithoutSpace(true); @@ -1170,14 +1174,14 @@ * @param json * @param resourcePath */ - parser.initSimpleAudio = function(json, resourcePath){ + parser.initSimpleAudio = function (json, resourcePath) { var node = new ccs.ComAudio(); var loop = json["Loop"] || false; //var volume = json["Volume"] || 0; //cc.audioEngine.setMusicVolume(volume); node.setLoop(loop); - loadTexture(json["FileData"], resourcePath, function(path, type){ + loadTexture(json["FileData"], resourcePath, function (path, type) { node.setFile(path); }); @@ -1189,12 +1193,12 @@ * @param resourcePath * @returns {*} */ - parser.initGameMap = function(json, resourcePath){ + parser.initGameMap = function (json, resourcePath) { var node = null; - loadTexture(json["FileData"], resourcePath, function(path, type){ - if(type === 0) + loadTexture(json["FileData"], resourcePath, function (path, type) { + if (type === 0) node = new cc.TMXTiledMap(path); parser.generalAttributes(node, json); @@ -1209,17 +1213,17 @@ * @param resourcePath * @returns {*} */ - parser.initProjectNode = function(json, resourcePath){ + parser.initProjectNode = function (json, resourcePath) { var projectFile = json["FileData"]; - if(projectFile != null && projectFile["Path"]){ + if (projectFile != null && projectFile["Path"]) { var file = resourcePath + projectFile["Path"]; - if(cc.loader.getRes(file)){ + if (cc.loader.getRes(file)) { var obj = ccs.load(file, resourcePath); parser.generalAttributes(obj.node, json); - if(obj.action && obj.node){ + if (obj.action && obj.node) { obj.action.tag = obj.node.tag; var InnerActionSpeed = json["InnerActionSpeed"]; - if(InnerActionSpeed !== undefined) + if (InnerActionSpeed !== undefined) obj.action.setTimeSpeed(InnerActionSpeed); obj.node.runAction(obj.action); obj.action.gotoFrameAndPause(0); @@ -1230,10 +1234,10 @@ } }; - var getFileName = function(name){ - if(!name) return ""; + var getFileName = function (name) { + if (!name) return ""; var arr = name.match(/([^\/]+)\.[^\/]+$/); - if(arr && arr[1]) + if (arr && arr[1]) return arr[1]; else return ""; @@ -1244,7 +1248,7 @@ * @param json * @param resourcePath */ - parser.initArmature = function(json, resourcePath){ + parser.initArmature = function (json, resourcePath) { var node = new ccs.Armature(); @@ -1254,24 +1258,24 @@ var currentAnimationName = json["CurrentAnimationName"]; - loadTexture(json["FileData"], resourcePath, function(path, type){ + loadTexture(json["FileData"], resourcePath, function (path, type) { var plists, pngs; var armJson = cc.loader.getRes(path); - if(!armJson) + if (!armJson) cc.log("%s need to be preloaded", path); - else{ + else { plists = armJson["config_file_path"]; pngs = armJson["config_png_path"]; - plists.forEach(function(plist, index){ - if(pngs[index]) + plists.forEach(function (plist, index) { + if (pngs[index]) cc.spriteFrameCache.addSpriteFrames(plist, pngs[index]); }); } ccs.armatureDataManager.addArmatureFileInfo(path); node.init(getFileName(path)); - if(isAutoPlay) + if (isAutoPlay) node.getAnimation().play(currentAnimationName, -1, isLoop); - else{ + else { node.getAnimation().play(currentAnimationName); node.getAnimation().gotoAndPause(0); } @@ -1286,65 +1290,65 @@ return node; }; - parser.initBoneNode = function(json, resourcePath){ + parser.initBoneNode = function (json, resourcePath) { var node = new ccs.BoneNode(); var length = json["Length"]; - if(length !== undefined) + if (length !== undefined) node.setDebugDrawLength(length); var blendFunc = json["BlendFunc"]; - if(blendFunc && blendFunc["Src"] !== undefined && blendFunc["Dst"] !== undefined) + if (blendFunc && blendFunc["Src"] !== undefined && blendFunc["Dst"] !== undefined) node.setBlendFunc(new cc.BlendFunc(blendFunc["Src"], blendFunc["Dst"])); parser.generalAttributes(node, json); var color = json["CColor"]; - if(color && (color["R"] !== undefined || color["G"] !== undefined || color["B"] !== undefined)) + if (color && (color["R"] !== undefined || color["G"] !== undefined || color["B"] !== undefined)) node.setColor(getColor(color)); return node; }; - parser.initSkeletonNode = function(json){ + parser.initSkeletonNode = function (json) { var node = new ccs.SkeletonNode(); parser.generalAttributes(node, json); var color = json["CColor"]; - if(color && (color["R"] !== undefined || color["G"] !== undefined || color["B"] !== undefined)) + if (color && (color["R"] !== undefined || color["G"] !== undefined || color["B"] !== undefined)) node.setColor(getColor(color)); return node; }; var loadedPlist = {}; - var loadTexture = function(json, resourcePath, cb){ - if(json != null){ + var loadTexture = function (json, resourcePath, cb) { + if (json != null) { var path = json["Path"]; var type; - if(json["Type"] === "Default" || json["Type"] === "Normal") + if (json["Type"] === "Default" || json["Type"] === "Normal") type = 0; else type = 1; var plist = json["Plist"]; - if(plist){ - if(cc.loader.getRes(resourcePath + plist)){ + if (plist) { + if (cc.loader.getRes(resourcePath + plist)) { loadedPlist[resourcePath + plist] = true; cc.spriteFrameCache.addSpriteFrames(resourcePath + plist); - }else{ - if(!loadedPlist[resourcePath + plist] && !cc.spriteFrameCache.getSpriteFrame(path)) + } else { + if (!loadedPlist[resourcePath + plist] && !cc.spriteFrameCache.getSpriteFrame(path)) cc.log("%s need to be preloaded", resourcePath + plist); } } - if(type !== 0){ - if(cc.spriteFrameCache.getSpriteFrame(path)) + if (type !== 0) { + if (cc.spriteFrameCache.getSpriteFrame(path)) cb(path, type); else cc.log("failed to get spriteFrame: %s", path); - }else + } else cb(resourcePath + path, type); } }; - var getColor = function(json){ - if(!json) return; + var getColor = function (json) { + if (!json) return; var r = json["R"] != null ? json["R"] : 255; var g = json["G"] != null ? json["G"] : 255; var b = json["B"] != null ? json["B"] : 255; @@ -1352,10 +1356,10 @@ return cc.color(r, g, b, a); }; - var setContentSize = function(node, size){ + var setContentSize = function (node, size) { var x = size["X"] || 0; var y = size["Y"] || 0; - if(size) + if (size) node.setContentSize(cc.size(x, y)); }; @@ -1388,8 +1392,8 @@ {name: "SkeletonNodeObjectData", handle: parser.initSkeletonNode} ]; - register.forEach(function(item){ - parser.registerParser(item.name, function(options, resourcePath){ + register.forEach(function (item) { + parser.registerParser(item.name, function (options, resourcePath) { var node = item.handle.call(this, options, resourcePath); this.parseChild(node, options["Children"], resourcePath); DEBUG && node && (node.__parserName = item.name); diff --git a/extensions/cocostudio/loader/parsers/uiParser-1.x.js b/extensions/cocostudio/loader/parsers/uiParser-1.x.js index 8c345d4128..1e54d745aa 100644 --- a/extensions/cocostudio/loader/parsers/uiParser-1.x.js +++ b/extensions/cocostudio/loader/parsers/uiParser-1.x.js @@ -201,9 +201,9 @@ } }; - var getPath = function(res, type, path, cb){ - if(path){ - if(type === 0) + var getPath = function (res, type, path, cb) { + if (path) { + if (type === 0) cb(res + path, type); else cb(path, type); @@ -213,14 +213,14 @@ /** * Panel parser (UILayout) */ - parser.LayoutAttributes = function(widget, options, resourcePath){ + parser.LayoutAttributes = function (widget, options, resourcePath) { var w = 0, h = 0; var adaptScreen = options["adaptScreen"]; - if (adaptScreen){ + if (adaptScreen) { var screenSize = cc.director.getWinSize(); w = screenSize.width; h = screenSize.height; - }else{ + } else { w = options["width"]; h = options["height"]; } @@ -555,7 +555,7 @@ /** * Slider parser (UISlider) */ - parser.SliderAttributes = function(widget, options, resourcePath){ + parser.SliderAttributes = function (widget, options, resourcePath) { var slider = widget; @@ -568,15 +568,15 @@ var imageFileType = imageFileNameDic["resourceType"]; var imageFileName = imageFileNameDic["path"]; - if(bt != null){ - if(barTextureScale9Enable){ - getPath(resourcePath, imageFileType, imageFileName, function(path, type){ + if (bt != null) { + if (barTextureScale9Enable) { + getPath(resourcePath, imageFileType, imageFileName, function (path, type) { slider.loadBarTexture(path, type); }); slider.setSize(cc.size(barLength, slider.getContentSize().height)); } - }else{ - getPath(resourcePath, imageFileType, imageFileName, function(path, type){ + } else { + getPath(resourcePath, imageFileType, imageFileName, function (path, type) { slider.loadBarTexture(path, type); }); } @@ -591,9 +591,9 @@ resourcePath, pressedDic["resourceType"] || normalDic["resourceType"], pressedDic["path"] || normalDic["path"], - function(path, type){ + function (path, type) { slider.loadSlidBallTexturePressed(path, type); - }); + }); var disabledDic = options["ballDisabledData"]; getPath(resourcePath, disabledDic["resourceType"], disabledDic["path"], function(path, type){ @@ -608,59 +608,59 @@ /** * TextField parser (UITextField) */ - parser.TextFieldAttributes = function(widget, options, resourcePath){ + parser.TextFieldAttributes = function (widget, options, resourcePath){ var ph = options["placeHolder"]; - if(ph) + if (ph) widget.setPlaceHolder(ph); widget.setString(options["text"]||""); var fs = options["fontSize"]; - if(fs) + if (fs) widget.setFontSize(fs); var fn = options["fontName"]; - if (fn != null){ - if(cc.sys.isNative){ - if(regTTF.test(fn)){ + if (fn != null) { + if (cc.sys.isNative) { + if (regTTF.test(fn)) { widget.setFontName(cc.path.join(cc.loader.resPath, resourcePath, fn)); - }else{ + } else { widget.setFontName(fn); } - }else{ + } else { widget.setFontName(fn.replace(regTTF, '')); } } var tsw = options["touchSizeWidth"]; var tsh = options["touchSizeHeight"]; - if(tsw!=null && tsh!=null) + if (tsw!=null && tsh!=null) widget.setTouchSize(tsw, tsh); var dw = options["width"]; var dh = options["height"]; - if(dw > 0 || dh > 0){ + if (dw > 0 || dh > 0) { //textField.setSize(cc.size(dw, dh)); } var maxLengthEnable = options["maxLengthEnable"]; widget.setMaxLengthEnabled(maxLengthEnable); - if(maxLengthEnable){ + if (maxLengthEnable) { var maxLength = options["maxLength"]; widget.setMaxLength(maxLength); } var passwordEnable = options["passwordEnable"]; widget.setPasswordEnabled(passwordEnable); - if(passwordEnable) + if (passwordEnable) widget.setPasswordStyleText(options["passwordStyleText"]); var aw = options["areaWidth"]; var ah = options["areaHeight"]; - if(aw && ah){ + if (aw && ah) { var size = cc.size(aw, ah); widget.setTextAreaSize(size); } var ha = options["hAlignment"]; - if(ha) + if (ha) widget.setTextHorizontalAlignment(ha); var va = options["vAlignment"]; - if(va) + if (va) widget.setTextVerticalAlignment(va); var r = options["colorR"]; @@ -702,4 +702,4 @@ load.registerParser("ccui", "*", parser); -})(ccs._load, ccs._parser); \ No newline at end of file +})(ccs._load, ccs._parser); diff --git a/extensions/cocostudio/timeline/ActionTimeline.js b/extensions/cocostudio/timeline/ActionTimeline.js index cdf57b58dc..fd899ae120 100644 --- a/extensions/cocostudio/timeline/ActionTimeline.js +++ b/extensions/cocostudio/timeline/ActionTimeline.js @@ -34,11 +34,11 @@ ccs.ActionTimelineData = ccs.Class.extend({ _actionTag: 0, - ctor: function(actionTag){ + ctor: function (actionTag) { this._init(actionTag); }, - _init: function(actionTag){ + _init: function (actionTag) { this._actionTag = actionTag; return true; }, @@ -47,20 +47,20 @@ ccs.ActionTimelineData = ccs.Class.extend({ * Set the action tag. * @param {number} actionTag */ - setActionTag: function(actionTag){ + setActionTag: function (actionTag) { this._actionTag = actionTag; }, /** * Gets the action tag. */ - getActionTag: function(){ + getActionTag: function () { return this._actionTag; } }); -ccs.AnimationInfo = function(name, start, end){ +ccs.AnimationInfo = function (name, start, end) { this.name = name; this.startIndex = start; this.endIndex = end; @@ -110,7 +110,7 @@ ccs.ComExtensionData.create = function(){ * @param actionTag * @returns {ccs.ActionTimelineData} */ -ccs.ActionTimelineData.create = function(actionTag){ +ccs.ActionTimelineData.create = function (actionTag) { return new ccs.ActionTimelineData(actionTag); }; @@ -130,7 +130,7 @@ ccs.ActionTimeline = cc.Action.extend({ _duration: 0, _time: null, _timeSpeed: 1, - _frameInternal: 1/60, + _frameInternal: 1 / 60, _playing: false, _currentFrame: 0, _startFrame: 0, @@ -140,7 +140,7 @@ ccs.ActionTimeline = cc.Action.extend({ _animationInfos: null, _lastFrameListener: null, - ctor: function(){ + ctor: function () { cc.Action.prototype.ctor.call(this); this._timelineMap = {}; this._timelineList = []; @@ -148,29 +148,28 @@ ccs.ActionTimeline = cc.Action.extend({ this.init(); }, - _gotoFrame: function(frameIndex){ + _gotoFrame: function (frameIndex) { var size = this._timelineList.length; - for(var i = 0; i < size; i++) - { + for (var i = 0; i < size; i++) { this._timelineList[i]._gotoFrame(frameIndex); } }, - _stepToFrame: function(frameIndex){ + _stepToFrame: function (frameIndex) { var size = this._timelineList.length; - for(var i = 0; i < size; i++){ + for (var i = 0; i < size; i++) { this._timelineList[i]._stepToFrame(frameIndex); } }, //emit frame event, call it when enter a frame - _emitFrameEvent: function(frame){ - if(this._frameEventListener){ + _emitFrameEvent: function (frame) { + if (this._frameEventListener) { this._frameEventListener(frame); } }, - init: function(){ + init: function () { return true; }, @@ -181,23 +180,23 @@ ccs.ActionTimeline = cc.Action.extend({ * @param [currentFrameIndex=] set current frame index. * @param [loop=] Whether or not the animation need loop. */ - gotoFrameAndPlay: function(startIndex, endIndex, currentFrameIndex, loop){ + gotoFrameAndPlay: function (startIndex, endIndex, currentFrameIndex, loop) { //Consolidation parameters var i = 0, argLen = arguments.length; var num = [], bool; - for(i; i= this._startFrame && frameIndex <= this._endFrame){ + setCurrentFrame: function (frameIndex) { + if (frameIndex >= this._startFrame && frameIndex <= this._endFrame) { this._currentFrame = frameIndex; this._time = this._currentFrame * this._frameInternal; - }else{ + } else { cc.log("frame index is not between start frame and end frame"); } @@ -309,7 +308,7 @@ ccs.ActionTimeline = cc.Action.extend({ * Get current frame. * @returns {number} */ - getCurrentFrame: function(){ + getCurrentFrame: function () { return this._currentFrame; }, @@ -317,7 +316,7 @@ ccs.ActionTimeline = cc.Action.extend({ * add Timeline to ActionTimeline * @param {ccs.Timeline} timeline */ - addTimeline: function(timeline){ + addTimeline: function (timeline) { var tag = timeline.getActionTag(); if (!this._timelineMap[tag]) { this._timelineMap[tag] = []; @@ -335,13 +334,13 @@ ccs.ActionTimeline = cc.Action.extend({ * remove Timeline to ActionTimeline * @param {ccs.Timeline} timeline */ - removeTimeline: function(timeline){ + removeTimeline: function (timeline) { var tag = timeline.getActionTag(); if (this._timelineMap[tag]) { - if(this._timelineMap[tag].some(function(item){ - if(item === timeline) - return true; - })) { + if (this._timelineMap[tag].some(function (item) { + if (item === timeline) + return true; + })) { cc.arrayRemoveObject(this._timelineMap[tag], timeline); cc.arrayRemoveObject(this._timelineList, timeline); timeline.setActionTimeline(null); @@ -353,7 +352,7 @@ ccs.ActionTimeline = cc.Action.extend({ * Gets the timeline list * @returns {array | null} */ - getTimelines: function(){ + getTimelines: function () { return this._timelineList; }, @@ -361,14 +360,14 @@ ccs.ActionTimeline = cc.Action.extend({ * Set the Frame event * @param {function} listener */ - setFrameEventCallFunc: function(listener){ + setFrameEventCallFunc: function (listener) { this._frameEventListener = listener; }, /** * remove event */ - clearFrameEventCallFunc: function(){ + clearFrameEventCallFunc: function () { this._frameEventListener = null; }, @@ -376,15 +375,14 @@ ccs.ActionTimeline = cc.Action.extend({ * Clone this timeline * @returns {ccs.ActionTimeline} */ - clone: function(){ + clone: function () { var newAction = new ccs.ActionTimeline(); newAction.setDuration(this._duration); newAction.setTimeSpeed(this._timeSpeed); - for (var a in this._timelineMap){ + for (var a in this._timelineMap) { var timelines = this._timelineMap[a]; - for(var b in timelines) - { + for (var b in timelines) { var timeline = timelines[b]; var newTimeline = timeline.clone(); newAction.addTimeline(newTimeline); @@ -399,7 +397,7 @@ ccs.ActionTimeline = cc.Action.extend({ * Reverse is not defined; * @returns {null} */ - reverse: function(){ + reverse: function () { return null; }, @@ -407,42 +405,40 @@ ccs.ActionTimeline = cc.Action.extend({ * Stepping of this time line. * @param {number} delta */ - step: function(delta){ - if (!this._playing || this._timelineMap.length === 0 || this._duration === 0) - { + step: function (delta) { + if (!this._playing || this._timelineMap.length === 0 || this._duration === 0) { return; } this._time += delta * this._timeSpeed; var endoffset = this._time - this._endFrame * this._frameInternal; - if(endoffset < this._frameInternal){ + if (endoffset < this._frameInternal) { this._currentFrame = Math.floor(this._time / this._frameInternal); this._stepToFrame(this._currentFrame); - if(endoffset >= 0 && this._lastFrameListener) + if (endoffset >= 0 && this._lastFrameListener) this._lastFrameListener(); - }else{ + } else { this._playing = this._loop; - if(!this._playing){ + if (!this._playing) { this._time = this._endFrame * this._frameInternal; - if (this._currentFrame != this._endFrame){ + if (this._currentFrame != this._endFrame) { this._currentFrame = this._endFrame; this._stepToFrame(this._currentFrame); - if(this._lastFrameListener) + if (this._lastFrameListener) this._lastFrameListener(); } - }else + } else this.gotoFrameAndPlay(this._startFrame, this._endFrame, this._loop); } }, - _foreachNodeDescendant: function(parent, callback){ + _foreachNodeDescendant: function (parent, callback) { callback(parent); var children = parent.getChildren(); - for (var i=0; i 0){ + while (boneStack.length > 0) { var top = boneStack.pop(); var topCmd = top._renderCmd; topCmd._syncStatus(topCmd.getParentRenderCmd()); @@ -205,7 +205,7 @@ ccs.SkeletonNode = (function(){ var topChildren = top.getChildBones(); - for (var childbone, i=0; i= this._frames[0].getFrameIndex()) + do { + if (frameIndex < this._frames[0].getFrameIndex()) { + if (this._currentKeyFrameIndex >= this._frames[0].getFrameIndex()) needEnterFrame = true; this._fromIndex = 0; @@ -211,7 +209,7 @@ ccs.Timeline = ccs.Class.extend({ this._currentKeyFrameIndex = 0; this._betweenDuration = this._frames[0].getFrameIndex(); break; - }else if(frameIndex >= this._frames[length - 1].getFrameIndex()){ + } else if (frameIndex >= this._frames[length - 1].getFrameIndex()) { this._fromIndex = length - 1; this._toIndex = 0; @@ -225,14 +223,13 @@ ccs.Timeline = ccs.Class.extend({ var low = 0, high = length - 1, mid = 0; - while(low <= high){ - mid = Math.ceil(( low + high )/2); - if(frameIndex >= this._frames[mid].getFrameIndex() && frameIndex < this._frames[mid + 1].getFrameIndex()) - { + while (low <= high) { + mid = Math.ceil(( low + high ) / 2); + if (frameIndex >= this._frames[mid].getFrameIndex() && frameIndex < this._frames[mid + 1].getFrameIndex()) { target = mid; break; } - if(this._frames[mid].getFrameIndex()>frameIndex) + if (this._frames[mid].getFrameIndex() > frameIndex) high = mid - 1; else low = mid + 1; @@ -240,37 +237,36 @@ ccs.Timeline = ccs.Class.extend({ this._fromIndex = target; - if(length > 1) + if (length > 1) this._toIndex = (target + 1) | 0; else this._toIndex = (target) | 0; from = this._frames[this._fromIndex]; - to = this._frames[this._toIndex]; + to = this._frames[this._toIndex]; from = this._frames[target]; - to = this._frames[target+1]; + to = this._frames[target + 1]; - if(target === 0 && this._currentKeyFrameIndex < from.getFrameIndex()) + if (target === 0 && this._currentKeyFrameIndex < from.getFrameIndex()) needEnterFrame = true; this._currentKeyFrameIndex = from.getFrameIndex(); this._betweenDuration = to.getFrameIndex() - from.getFrameIndex(); } while (0); - if(needEnterFrame || this._currentKeyFrame != from) { + if (needEnterFrame || this._currentKeyFrame != from) { this._currentKeyFrame = from; this._currentKeyFrame.onEnter(to); } }, - _updateCurrentKeyFrame: function(frameIndex){ - if(frameIndex > 60) + _updateCurrentKeyFrame: function (frameIndex) { + if (frameIndex > 60) var a = 0; //! If play to current frame's front or back, then find current frame again - if (frameIndex < this._currentKeyFrameIndex || frameIndex >= this._currentKeyFrameIndex + this._betweenDuration) - { + if (frameIndex < this._currentKeyFrameIndex || frameIndex >= this._currentKeyFrameIndex + this._betweenDuration) { var from = null; var to = null; @@ -278,29 +274,26 @@ ccs.Timeline = ccs.Class.extend({ { var length = this._frames.length; - if (frameIndex < this._frames[0].getFrameIndex()) - { + if (frameIndex < this._frames[0].getFrameIndex()) { from = to = this._frames[0]; this._currentKeyFrameIndex = 0; this._betweenDuration = this._frames[0].getFrameIndex(); break; } - else if(frameIndex >= this._frames[length - 1].getFrameIndex()) - { + else if (frameIndex >= this._frames[length - 1].getFrameIndex()) { var lastFrameIndex = this._frames[length - 1].getFrameIndex(); - if(this._currentKeyFrameIndex >= lastFrameIndex) + if (this._currentKeyFrameIndex >= lastFrameIndex) return; frameIndex = lastFrameIndex; } - do{ + do { this._fromIndex = this._toIndex; from = this._frames[this._fromIndex]; - this._currentKeyFrameIndex = from.getFrameIndex(); + this._currentKeyFrameIndex = from.getFrameIndex(); this._toIndex = this._fromIndex + 1; - if (this._toIndex >= length) - { + if (this._toIndex >= length) { this._toIndex = 0; } @@ -308,11 +301,11 @@ ccs.Timeline = ccs.Class.extend({ if (frameIndex === from.getFrameIndex()) break; - if(frameIndex > from.getFrameIndex() && frameIndex < to.getFrameIndex()) + if (frameIndex > from.getFrameIndex() && frameIndex < to.getFrameIndex()) break; - if(from.isEnterWhenPassed()) + if (from.isEnterWhenPassed()) from.onEnter(to); - }while (true); + } while (true); this._betweenDuration = to.getFrameIndex() - from.getFrameIndex(); @@ -331,6 +324,6 @@ ccs.Timeline = ccs.Class.extend({ * @deprecated v3.0, please use new ccs.Timeline() instead. * @returns {ccs.Timeline} */ -ccs.Timeline.create = function(){ +ccs.Timeline.create = function () { return new ccs.Timeline(); -}; \ No newline at end of file +}; diff --git a/extensions/editbox/CCEditBox.js b/extensions/editbox/CCEditBox.js index 88b02bdf97..9cef1b321d 100644 --- a/extensions/editbox/CCEditBox.js +++ b/extensions/editbox/CCEditBox.js @@ -267,39 +267,39 @@ cc.EditBox = cc.Node.extend({ this._updateEditBoxSize(width, height); }, - setVisible: function ( visible ) { + setVisible: function (visible) { cc.Node.prototype.setVisible.call(this, visible); this._renderCmd.updateVisibility(); }, createDomElementIfNeeded: function () { - if(!this._renderCmd._edTxt) { + if (!this._renderCmd._edTxt) { this._renderCmd.createNativeControl(); } }, - setTabIndex: function(index) { - if(this._renderCmd._edTxt) { + setTabIndex: function (index) { + if (this._renderCmd._edTxt) { this._renderCmd._edTxt.tabIndex = index; } }, - getTabIndex: function() { - if(this._renderCmd._edTxt) { + getTabIndex: function () { + if (this._renderCmd._edTxt) { return this._renderCmd._edTxt.tabIndex; } cc.warn('The dom control is not created!'); return -1; }, - setFocus: function() { - if(this._renderCmd._edTxt) { + setFocus: function () { + if (this._renderCmd._edTxt) { this._renderCmd._edTxt.focus(); } }, - isFocused: function() { - if(this._renderCmd._edTxt) { + isFocused: function () { + if (this._renderCmd._edTxt) { return document.activeElement === this._renderCmd._edTxt; } cc.warn('The dom control is not created!'); @@ -307,7 +307,7 @@ cc.EditBox = cc.Node.extend({ }, stayOnTop: function (flag) { - if(this._alwaysOnTop === flag) return; + if (this._alwaysOnTop === flag) return; this._alwaysOnTop = flag; this._renderCmd.stayOnTop(this._alwaysOnTop); @@ -321,9 +321,9 @@ cc.EditBox = cc.Node.extend({ _onTouchBegan: function (touch) { var touchPoint = touch.getLocation(); - var bb = cc.rect(0,0, this._contentSize.width, this._contentSize.height); + var bb = cc.rect(0, 0, this._contentSize.width, this._contentSize.height); var hitted = cc.rectContainsPoint(bb, this.convertToNodeSpace(touchPoint)); - if(hitted) { + if (hitted) { return true; } else { @@ -337,12 +337,12 @@ cc.EditBox = cc.Node.extend({ }, _updateBackgroundSpriteSize: function (width, height) { - if(this._backgroundSprite) { + if (this._backgroundSprite) { this._backgroundSprite.setContentSize(width, height); } }, - _updateEditBoxSize: function(size, height) { + _updateEditBoxSize: function (size, height) { var newWidth = (typeof size.width === 'number') ? size.width : size; var newHeight = (typeof size.height === 'number') ? size.height : height; @@ -367,7 +367,7 @@ cc.EditBox = cc.Node.extend({ this._renderCmd._setFont(fontStyle); }, - getBackgroundSprite: function() { + getBackgroundSprite: function () { return this._backgroundSprite; }, @@ -415,7 +415,7 @@ cc.EditBox = cc.Node.extend({ */ setMaxLength: function (maxLength) { if (!isNaN(maxLength)) { - if(maxLength < 0) { + if (maxLength < 0) { //we can't set Number.MAX_VALUE to input's maxLength property //so we use a magic number here, it should works at most use cases. maxLength = 65535; @@ -515,13 +515,13 @@ cc.EditBox = cc.Node.extend({ * @param {cc.Color | cc.Scale9Sprite} normal9SpriteBg */ initWithSizeAndBackgroundSprite: function (size, normal9SpriteBg) { - if(this._backgroundSprite) { + if (this._backgroundSprite) { this._backgroundSprite.removeFromParent(); } this._backgroundSprite = normal9SpriteBg; this.setContentSize(size); - if(this._backgroundSprite && !this._backgroundSprite.parent) { + if (this._backgroundSprite && !this._backgroundSprite.parent) { this._backgroundSprite.setAnchorPoint(cc.p(0, 0)); this.addChild(this._backgroundSprite); @@ -662,7 +662,7 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp if (cc.sys.OS_ANDROID === cc.sys.os && (cc.sys.browserType === cc.sys.BROWSER_TYPE_SOUGOU - || cc.sys.browserType === cc.sys.BROWSER_TYPE_360)) { + || cc.sys.browserType === cc.sys.BROWSER_TYPE_360)) { editbox._polyfill.zoomInvalid = true; } })(cc.EditBox); @@ -673,31 +673,33 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp var TIMER_NAME = 400; var LEFT_PADDING = 2; - function scrollWindowUp (editBox) { + function scrollWindowUp(editBox) { // if (cc.sys.os === cc.sys.OS_IOS && cc.sys.osMainVersion === 9) { - var worldPos = editBox.convertToWorldSpace(cc.p(0,0)); - var windowHeight = cc.visibleRect.height; - var windowWidth = cc.visibleRect.width; - var factor = 0.5; - if(windowWidth > windowHeight) { - factor = 0.7; + var worldPos = editBox.convertToWorldSpace(cc.p(0, 0)); + var windowHeight = cc.visibleRect.height; + var windowWidth = cc.visibleRect.width; + var factor = 0.5; + if (windowWidth > windowHeight) { + factor = 0.7; + } + setTimeout(function () { + if (window.scrollY < SCROLLY && worldPos.y < windowHeight * factor) { + var scrollOffset = windowHeight * factor - worldPos.y - window.scrollY; + if (scrollOffset < 35) scrollOffset = 35; + if (scrollOffset > 320) scrollOffset = 320; + window.scrollTo(0, scrollOffset); } - setTimeout(function() { - if(window.scrollY < SCROLLY && worldPos.y < windowHeight * factor) { - var scrollOffset = windowHeight * factor - worldPos.y - window.scrollY; - if (scrollOffset < 35) scrollOffset = 35; - if (scrollOffset > 320) scrollOffset = 320; - window.scrollTo(0, scrollOffset); - } - }, TIMER_NAME); + }, TIMER_NAME); // } } - function capitalize (string) { - return string.replace(/(?:^|\s)\S/g, function(a) { return a.toUpperCase(); }); + function capitalize(string) { + return string.replace(/(?:^|\s)\S/g, function (a) { + return a.toUpperCase(); + }); } - function capitalizeFirstLetter (string) { + function capitalizeFirstLetter(string) { return string.charAt(0).toUpperCase() + string.slice(1); } @@ -718,7 +720,7 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp var container = cc.game.container; var a = t.a * scaleX, b = t.b, c = t.c, d = t.d * scaleY; - var offsetX = container && container.style.paddingLeft && parseInt(container.style.paddingLeft); + var offsetX = container && container.style.paddingLeft && parseInt(container.style.paddingLeft); var offsetY = container && container.style.paddingBottom && parseInt(container.style.paddingBottom); var tx = t.tx * scaleX + offsetX, ty = t.ty * scaleY + offsetY; @@ -746,18 +748,18 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp } else { editBox.style.visibility = 'hidden'; var hasChild = false; - if('contains' in cc.game.container) { + if ('contains' in cc.game.container) { hasChild = cc.game.container.contains(editBox); - }else { + } else { hasChild = cc.game.container.compareDocumentPosition(editBox) % 16; } - if(hasChild) + if (hasChild) cc.game.container.removeChild(editBox); } }; proto.stayOnTop = function (flag) { - if(flag) { + if (flag) { this._removeLabels(); this._edTxt.style.display = ''; } else { @@ -812,7 +814,7 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp if (e.keyCode === cc.KEY.enter) { e.stopPropagation(); e.preventDefault(); - if(this.value === '') { + if (this.value === '') { this.style.fontSize = editBox._placeholderFontSize + 'px'; this.style.color = cc.colorToHex(editBox._placeholderColor); } @@ -833,7 +835,7 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp this.style.color = cc.colorToHex(editBox._textColor); thisPointer._hiddenLabels(); - if(cc.view.isAutoFullScreenEnabled()) { + if (cc.view.isAutoFullScreenEnabled()) { thisPointer.__fullscreen = true; cc.view.enableAutoFullScreen(false); cc.screen.exitFullScreen(); @@ -853,7 +855,7 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp var editBox = thisPointer._editBox; editBox._text = this.value; thisPointer._updateEditBoxContentStyle(); - if(thisPointer.__fullscreen) { + if (thisPointer.__fullscreen) { cc.view.enableAutoFullScreen(true); } if (this.__autoResize) { @@ -904,7 +906,7 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp var editBox = thisPointer._editBox; if (editBox._delegate && editBox._delegate.editBoxTextChanged) { - if(editBox._text.toLowerCase() !== this.value.toLowerCase()) { + if (editBox._text.toLowerCase() !== this.value.toLowerCase()) { editBox._text = this.value; thisPointer._updateEditBoxContentStyle(); editBox._delegate.editBoxTextChanged(editBox, editBox._text); @@ -918,7 +920,7 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp this.style.fontSize = thisPointer._edFontSize + 'px'; this.style.color = cc.colorToHex(editBox._textColor); - if(cc.view.isAutoFullScreenEnabled()) { + if (cc.view.isAutoFullScreenEnabled()) { thisPointer.__fullscreen = true; cc.view.enableAutoFullScreen(false); cc.screen.exitFullScreen(); @@ -951,7 +953,7 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp editBox._text = this.value; thisPointer._updateEditBoxContentStyle(); window.scrollY = 0; - if(thisPointer.__fullscreen) { + if (thisPointer.__fullscreen) { cc.view.enableAutoFullScreen(true); } if (this.__autoResize) { @@ -975,14 +977,14 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp proto._createLabels = function () { var editBoxSize = this._editBox.getContentSize(); - if(!this._textLabel) { + if (!this._textLabel) { this._textLabel = new cc.LabelTTF(); this._textLabel.setVisible(false); this._textLabel.setAnchorPoint(cc.p(0, 1)); this._editBox.addChild(this._textLabel, 100); } - if(!this._placeholderLabel) { + if (!this._placeholderLabel) { this._placeholderLabel = new cc.LabelTTF(); this._placeholderLabel.setAnchorPoint(cc.p(0, 1)); this._placeholderLabel.setColor(cc.color.GRAY); @@ -993,14 +995,14 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp }; proto._removeLabels = function () { - if(!this._textLabel) return; + if (!this._textLabel) return; this._editBox.removeChild(this._textLabel); this._textLabel = null; }; proto._updateLabelPosition = function (editBoxSize) { - if(!this._textLabel || !this._placeholderLabel) return; + if (!this._textLabel || !this._placeholderLabel) return; var labelContentSize = cc.size(editBoxSize.width - LEFT_PADDING, editBoxSize.height); this._textLabel.setContentSize(labelContentSize); @@ -1008,7 +1010,7 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp this._placeholderLabel.setLineHeight(editBoxSize.height); var placeholderLabelSize = this._placeholderLabel.getContentSize(); - if (this._editBox._editBoxInputMode === cc.EDITBOX_INPUT_MODE_ANY){ + if (this._editBox._editBoxInputMode === cc.EDITBOX_INPUT_MODE_ANY) { this._textLabel.setPosition(LEFT_PADDING, editBoxSize.height); this._placeholderLabel.setPosition(LEFT_PADDING, editBoxSize.height); this._placeholderLabel.setVerticalAlignment(cc.VERTICAL_TEXT_ALIGNMENT_TOP); @@ -1026,22 +1028,22 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp }; proto.setLineHeight = function (lineHeight) { - if(this._textLabel) { + if (this._textLabel) { this._textLabel.setLineHeight(lineHeight); } }; proto._hiddenLabels = function () { - if(this._textLabel) { + if (this._textLabel) { this._textLabel.setVisible(false); } - if(this._placeholderLabel) { + if (this._placeholderLabel) { this._placeholderLabel.setVisible(false); } }; - proto._updateEditBoxContentStyle = function() { + proto._updateEditBoxContentStyle = function () { var inputFlag = this._editBox._editBoxInputFlag; if (inputFlag === cc.EDITBOX_INPUT_FLAG_INITIAL_CAPS_ALL_CHARACTERS) { this._editBox._text = this._editBox._text.toUpperCase(); @@ -1054,10 +1056,10 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp } }; - proto._updateLabelString = function() { + proto._updateLabelString = function () { this._updateInputType(); - if(this._textLabel) { + if (this._textLabel) { this._textLabel.setVisible(true); this._textLabel.setString(this._editBox._text); } @@ -1068,12 +1070,12 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp for (var i = 0; i < len; ++i) { passwordString += '\u25CF'; } - if(this._textLabel) { + if (this._textLabel) { this._textLabel.setString(passwordString); } } else { this._updateEditBoxContentStyle(); - if(this._textLabel) { + if (this._textLabel) { this._textLabel.setString(this._editBox._text); } } @@ -1082,7 +1084,7 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp proto._showLabels = function () { this._hiddenLabels(); if (this._edTxt.value === '') { - if(this._placeholderLabel) { + if (this._placeholderLabel) { this._placeholderLabel.setVisible(true); this._placeholderLabel.setString(this._editBox._placeholderText); } @@ -1092,8 +1094,8 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp } }; - proto.show = function() { - if(!this._editBox._alwaysOnTop) { + proto.show = function () { + if (!this._editBox._alwaysOnTop) { if (this._edTxt.style.display === 'none') { this._edTxt.style.display = ''; this._edTxt.focus(); @@ -1102,8 +1104,8 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp this._hiddenLabels(); }; - proto.hidden = function() { - if(!this._editBox._alwaysOnTop) { + proto.hidden = function () { + if (!this._editBox._alwaysOnTop) { this._edTxt.style.display = 'none'; } this._showLabels(); @@ -1135,12 +1137,12 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp }; proto.setFontColor = function (color) { - if(!this._edTxt) return; + if (!this._edTxt) return; if (this._edTxt.value !== this._editBox._placeholderText) { this._edTxt.style.color = cc.colorToHex(color); } - if(this._textLabel) { + if (this._textLabel) { this._textLabel.setColor(color); } }; @@ -1150,7 +1152,7 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp }; proto.setMaxLength = function (maxLength) { - if(!this._edTxt) return; + if (!this._edTxt) return; this._edTxt.maxLength = maxLength; }; @@ -1164,20 +1166,20 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp }; proto._updateInputType = function () { - if(this._editBox._keyboardReturnType === cc.KEYBOARD_RETURNTYPE_SEARCH) { + if (this._editBox._keyboardReturnType === cc.KEYBOARD_RETURNTYPE_SEARCH) { this._edTxt.type = 'search'; } var inputMode = this._editBox._editBoxInputMode; - if(inputMode === cc.EDITBOX_INPUT_MODE_EMAILADDR) { + if (inputMode === cc.EDITBOX_INPUT_MODE_EMAILADDR) { this._edTxt.type = 'email'; - } else if(inputMode === cc.EDITBOX_INPUT_MODE_DECIMAL || - inputMode === cc.EDITBOX_INPUT_MODE_NUMERIC) { + } else if (inputMode === cc.EDITBOX_INPUT_MODE_DECIMAL || + inputMode === cc.EDITBOX_INPUT_MODE_NUMERIC) { this._edTxt.type = 'number'; - } else if(inputMode === cc.EDITBOX_INPUT_MODE_PHONENUMBER) { + } else if (inputMode === cc.EDITBOX_INPUT_MODE_PHONENUMBER) { this._edTxt.type = 'number'; this._edTxt.pattern = '[0-9]*'; - } else if(inputMode === cc.EDITBOX_INPUT_MODE_URL) { + } else if (inputMode === cc.EDITBOX_INPUT_MODE_URL) { this._edTxt.type = 'url'; } else { this._edTxt.type = 'text'; @@ -1190,7 +1192,7 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp }; proto.setInputFlag = function (inputFlag) { - if(!this._edTxt) return; + if (!this._edTxt) return; this._updateInputType(); @@ -1221,28 +1223,28 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp }; proto.setString = function (text) { - if(!this._edTxt) return; + if (!this._edTxt) return; if (text !== null) { this._edTxt.value = text; if (text === '') { - if(this._placeholderLabel) { + if (this._placeholderLabel) { this._placeholderLabel.setString(this._editBox._placeholderText); this._placeholderLabel.setColor(this._editBox._placeholderColor); this._placeholderLabel.setVisible(true); } - if(this._textLabel) { + if (this._textLabel) { this._textLabel.setVisible(false); } } else { this._edTxt.style.color = cc.colorToHex(this._editBox._textColor); - if(this._textLabel) { + if (this._textLabel) { this._textLabel.setColor(this._editBox._textColor); } - if(this._placeholderLabel) { + if (this._placeholderLabel) { this._placeholderLabel.setVisible(false); } @@ -1251,21 +1253,21 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp } }; - proto._updateDOMFontStyle = function() { - if(!this._edTxt) return; + 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._textLabel) { + if (this._textLabel) { this._textLabel.setFontSize(this._edFontSize); this._textLabel.setFontName(this._edFontName); } }; - proto.updateSize = function(newWidth, newHeight) { + proto.updateSize = function (newWidth, newHeight) { var editboxDomNode = this._edTxt; if (!editboxDomNode) return; @@ -1275,7 +1277,7 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp this._updateLabelPosition(cc.size(newWidth, newHeight)); }; - proto.createNativeControl = function() { + proto.createNativeControl = function () { this._createDomTextArea(); this._addDomInputControl(); }; @@ -1286,14 +1288,14 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp proto._removeDomInputControl = function () { var editBox = this._edTxt; - if(editBox){ + if (editBox) { var hasChild = false; - if('contains' in cc.game.container) { + if ('contains' in cc.game.container) { hasChild = cc.game.container.contains(editBox); - }else { + } else { hasChild = cc.game.container.compareDocumentPosition(editBox) % 16; } - if(hasChild) + if (hasChild) cc.game.container.removeChild(editBox); } this._edTxt = null; @@ -1317,7 +1319,7 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp var canvasRenderCmdProto = cc.EditBox.CanvasRenderCmd.prototype = Object.create(cc.Node.CanvasRenderCmd.prototype); - function _getPropertyDescriptor (obj, name) { + function _getPropertyDescriptor(obj, name) { var pd = Object.getOwnPropertyDescriptor(obj, name); if (pd) { return pd; @@ -1345,8 +1347,8 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp cc.error('cc.js.mixin: arguments must be type object:', source); continue; } - for ( var name in source) { - _copyprop( name, source, obj); + for (var name in source) { + _copyprop(name, source, obj); } } } diff --git a/extensions/gui/scrollview/CCScrollView.js b/extensions/gui/scrollview/CCScrollView.js index f28592f67b..3834839a8e 100644 --- a/extensions/gui/scrollview/CCScrollView.js +++ b/extensions/gui/scrollview/CCScrollView.js @@ -40,19 +40,19 @@ var SCROLL_DEACCEL_RATE = 0.95; var SCROLL_DEACCEL_DIST = 1.0; var BOUNCE_DURATION = 0.15; var INSET_RATIO = 0.2; -var MOVE_INCH = 7.0/160.0; +var MOVE_INCH = 7.0 / 160.0; var BOUNCE_BACK_FACTOR = 0.35; -cc.convertDistanceFromPointToInch = function(pointDis){ +cc.convertDistanceFromPointToInch = function (pointDis) { var eglViewer = cc.view; - var factor = (eglViewer.getScaleX() + eglViewer.getScaleY())/2; + var factor = (eglViewer.getScaleX() + eglViewer.getScaleY()) / 2; return (pointDis * factor) / 160; // CCDevice::getDPI() default value }; cc.ScrollViewDelegate = cc.Class.extend({ - scrollViewDidScroll:function (view) { + scrollViewDidScroll: function (view) { }, - scrollViewDidZoom:function (view) { + scrollViewDidZoom: function (view) { } }); @@ -72,35 +72,35 @@ cc.ScrollViewDelegate = cc.Class.extend({ * @property {Boolean} clippingToBounds - Indicate whether the scroll view clips its children */ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{ - _zoomScale:0, - _minZoomScale:0, - _maxZoomScale:0, - _delegate:null, - _direction:cc.SCROLLVIEW_DIRECTION_BOTH, - _dragging:false, - _contentOffset:null, - _container:null, - _touchMoved:false, - _maxInset:null, - _minInset:null, - _bounceable:false, - _clippingToBounds:false, - _scrollDistance:null, - _touchPoint:null, - _touchLength:0, - _touches:null, - _viewSize:null, - _minScale:0, - _maxScale:0, + _zoomScale: 0, + _minZoomScale: 0, + _maxZoomScale: 0, + _delegate: null, + _direction: cc.SCROLLVIEW_DIRECTION_BOTH, + _dragging: false, + _contentOffset: null, + _container: null, + _touchMoved: false, + _maxInset: null, + _minInset: null, + _bounceable: false, + _clippingToBounds: false, + _scrollDistance: null, + _touchPoint: null, + _touchLength: 0, + _touches: null, + _viewSize: null, + _minScale: 0, + _maxScale: 0, //scissor rect for parent, just for restoring GL_SCISSOR_BOX - _parentScissorRect:null, - _scissorRestored:false, + _parentScissorRect: null, + _scissorRestored: false, // cache object - _tmpViewRect:null, + _tmpViewRect: null, _touchListener: null, - _className:"ScrollView", + _className: "ScrollView", /** * @contructor @@ -108,26 +108,26 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{ * @param container * @returns {ScrollView} */ - ctor:function (size, container) { + ctor: function (size, container) { cc.Layer.prototype.ctor.call(this); - this._contentOffset = cc.p(0,0); + this._contentOffset = cc.p(0, 0); this._maxInset = cc.p(0, 0); this._minInset = cc.p(0, 0); this._scrollDistance = cc.p(0, 0); this._touchPoint = cc.p(0, 0); this._touches = []; this._viewSize = cc.size(0, 0); - this._parentScissorRect = new cc.Rect(0,0,0,0); - this._tmpViewRect = new cc.Rect(0,0,0,0); + this._parentScissorRect = new cc.Rect(0, 0, 0, 0); + this._tmpViewRect = new cc.Rect(0, 0, 0, 0); - if(container != undefined) + if (container != undefined) this.initWithViewSize(size, container); else this.initWithViewSize(cc.size(200, 200), null); }, - init:function () { + init: function () { return this.initWithViewSize(cc.size(200, 200), null); }, @@ -137,8 +137,8 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{ * @param {cc.Node} container * @return {Boolean} */ - initWithViewSize:function (size, container) { - var pZero = cc.p(0,0); + initWithViewSize: function (size, container) { + var pZero = cc.p(0, 0); if (cc.Layer.prototype.init.call(this)) { if (!container && !this._container) { container = new cc.Layer(); @@ -192,7 +192,7 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{ }, - getContentOffset:function () { + getContentOffset: function () { var locPos = this._container.getPosition(); return cc.p(locPos.x, locPos.y); }, @@ -204,7 +204,7 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{ * @param {cc.Point} offset new offset * @param {Number} dt animation duration */ - setContentOffsetInDuration:function (offset, dt) { + setContentOffsetInDuration: function (offset, dt) { var scroll = cc.moveTo(dt, offset); var expire = cc.callFunc(this._stoppedAnimatedScroll, this); this._container.runAction(cc.sequence(scroll, expire)); @@ -246,7 +246,7 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{ } }, - getZoomScale:function () { + getZoomScale: function () { return this._container.getScale(); }, @@ -256,7 +256,7 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{ * @param {Number} s a new scale value * @param {Number} dt animation duration */ - setZoomScaleInDuration:function (s, dt) { + setZoomScaleInDuration: function (s, dt) { if (dt > 0) { var locScale = this._container.getScale(); if (locScale !== s) { @@ -272,7 +272,7 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{ * Returns the current container's minimum offset. You may want this while you animate scrolling by yourself * @return {cc.Point} Returns the current container's minimum offset. */ - minContainerOffset:function () { + minContainerOffset: function () { var locContainer = this._container; var locContentSize = locContainer.getContentSize(), locViewSize = this._viewSize; return cc.p(locViewSize.width - locContentSize.width * locContainer.getScaleX(), @@ -283,7 +283,7 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{ * Returns the current container's maximum offset. You may want this while you animate scrolling by yourself * @return {cc.Point} Returns the current container's maximum offset. */ - maxContainerOffset:function () { + maxContainerOffset: function () { return cc.p(0.0, 0.0); }, @@ -292,7 +292,7 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{ * @param {cc.Node} node * @return {Boolean} YES if it is in visible bounds */ - isNodeVisible:function (node) { + isNodeVisible: function (node) { var offset = this.getContentOffset(); var size = this.getViewSize(); var scale = this.getZoomScale(); @@ -305,7 +305,7 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{ /** * Provided to make scroll view compatible with SWLayer's pause method */ - pause:function (sender) { + pause: function (sender) { this._container.pause(); var selChildren = this._container.getChildren(); for (var i = 0; i < selChildren.length; i++) { @@ -317,7 +317,7 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{ /** * Provided to make scroll view compatible with SWLayer's resume method */ - resume:function (sender) { + resume: function (sender) { var selChildren = this._container.getChildren(); for (var i = 0, len = selChildren.length; i < len; i++) { selChildren[i].resume(); @@ -326,16 +326,16 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{ this._super(); }, - isDragging:function () { + isDragging: function () { return this._dragging; }, - isTouchMoved:function () { + isTouchMoved: function () { return this._touchMoved; }, - isBounceable:function () { + isBounceable: function () { return this._bounceable; }, - setBounceable:function (bounceable) { + setBounceable: function (bounceable) { this._bounceable = bounceable; }, @@ -346,20 +346,20 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{ * Hence, this scroll view will use a separate size property. *

*/ - getViewSize:function () { + getViewSize: function () { return this._viewSize; }, - setViewSize:function (size) { + setViewSize: function (size) { this._viewSize = size; - cc.Node.prototype.setContentSize.call(this,size); + cc.Node.prototype.setContentSize.call(this, size); }, - getContainer:function () { + getContainer: function () { return this._container; }, - setContainer:function (container) { + setContainer: function (container) { // Make sure that 'm_pContainer' has a non-NULL value since there are // lots of logic that use 'm_pContainer'. if (!container) @@ -378,23 +378,23 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{ /** * direction allowed to scroll. CCScrollViewDirectionBoth by default. */ - getDirection:function () { + getDirection: function () { return this._direction; }, - setDirection:function (direction) { + setDirection: function (direction) { this._direction = direction; }, - getDelegate:function () { + getDelegate: function () { return this._delegate; }, - setDelegate:function (delegate) { + setDelegate: function (delegate) { this._delegate = delegate; }, /** override functions */ // optional - onTouchBegan:function (touch, event) { + onTouchBegan: function (touch, event) { for (var c = this; c != null; c = c.parent) { if (!c.isVisible()) return false; @@ -430,7 +430,7 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{ return true; }, - onTouchMoved:function (touch, event) { + onTouchMoved: function (touch, event) { if (!this.isVisible()) return; @@ -447,17 +447,17 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{ var moveDistance = cc.pSub(newPoint, this._touchPoint); var dis = 0.0, locDirection = this._direction, pos; - if (locDirection === cc.SCROLLVIEW_DIRECTION_VERTICAL){ + if (locDirection === cc.SCROLLVIEW_DIRECTION_VERTICAL) { dis = moveDistance.y; pos = this._container.getPositionY(); if (!(this.minContainerOffset().y <= pos && pos <= this.maxContainerOffset().y)) moveDistance.y *= BOUNCE_BACK_FACTOR; - } else if (locDirection === cc.SCROLLVIEW_DIRECTION_HORIZONTAL){ + } else if (locDirection === cc.SCROLLVIEW_DIRECTION_HORIZONTAL) { dis = moveDistance.x; pos = this._container.getPositionX(); if (!(this.minContainerOffset().x <= pos && pos <= this.maxContainerOffset().x)) moveDistance.x *= BOUNCE_BACK_FACTOR; - }else { + } else { dis = Math.sqrt(moveDistance.x * moveDistance.x + moveDistance.y * moveDistance.y); pos = this._container.getPositionY(); @@ -470,12 +470,12 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{ moveDistance.x *= BOUNCE_BACK_FACTOR; } - if (!this._touchMoved && Math.abs(cc.convertDistanceFromPointToInch(dis)) < MOVE_INCH ){ + if (!this._touchMoved && Math.abs(cc.convertDistanceFromPointToInch(dis)) < MOVE_INCH) { //CCLOG("Invalid movement, distance = [%f, %f], disInch = %f", moveDistance.x, moveDistance.y); return; } - if (!this._touchMoved){ + if (!this._touchMoved) { moveDistance.x = 0; moveDistance.y = 0; } @@ -509,7 +509,7 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{ } }, - onTouchEnded:function (touch, event) { + onTouchEnded: function (touch, event) { if (!this.isVisible()) return; @@ -521,7 +521,7 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{ this._touchMoved = false; }, - onTouchCancelled:function (touch, event) { + onTouchCancelled: function (touch, event) { if (!this.isVisible()) return; @@ -532,33 +532,33 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{ setContentSize: function (size, height) { if (this.getContainer() !== null) { - if(height === undefined) + if (height === undefined) this.getContainer().setContentSize(size); else this.getContainer().setContentSize(size, height); this.updateInset(); } }, - _setWidth: function (value) { - var container = this.getContainer(); - if (container !== null) { - container._setWidth(value); - this.updateInset(); - } - }, - _setHeight: function (value) { - var container = this.getContainer(); - if (container !== null) { - container._setHeight(value); - this.updateInset(); - } - }, - - getContentSize:function () { + _setWidth: function (value) { + var container = this.getContainer(); + if (container !== null) { + container._setWidth(value); + this.updateInset(); + } + }, + _setHeight: function (value) { + var container = this.getContainer(); + if (container !== null) { + container._setHeight(value); + this.updateInset(); + } + }, + + getContentSize: function () { return this._container.getContentSize(); }, - updateInset:function () { + updateInset: function () { if (this.getContainer() !== null) { var locViewSize = this._viewSize; var tempOffset = this.maxContainerOffset(); @@ -573,15 +573,15 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{ /** * Determines whether it clips its children or not. */ - isClippingToBounds:function () { + isClippingToBounds: function () { return this._clippingToBounds; }, - setClippingToBounds:function (clippingToBounds) { + setClippingToBounds: function (clippingToBounds) { this._clippingToBounds = clippingToBounds; }, - addChild:function (child, zOrder, tag) { + addChild: function (child, zOrder, tag) { if (!child) throw new Error("child must not nil!"); @@ -597,12 +597,12 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{ } }, - isTouchEnabled: function(){ + isTouchEnabled: function () { return this._touchListener !== null; }, - setTouchEnabled:function (e) { - if(this._touchListener) + setTouchEnabled: function (e) { + if (this._touchListener) cc.eventManager.removeListener(this._touchListener); this._touchListener = null; if (!e) { @@ -613,13 +613,13 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{ var listener = cc.EventListener.create({ event: cc.EventListener.TOUCH_ONE_BY_ONE }); - if(this.onTouchBegan) + if (this.onTouchBegan) listener.onTouchBegan = this.onTouchBegan.bind(this); - if(this.onTouchMoved) + if (this.onTouchMoved) listener.onTouchMoved = this.onTouchMoved.bind(this); - if(this.onTouchEnded) + if (this.onTouchEnded) listener.onTouchEnded = this.onTouchEnded.bind(this); - if(this.onTouchCancelled) + if (this.onTouchCancelled) listener.onTouchCancelled = this.onTouchCancelled.bind(this); this._touchListener = listener; cc.eventManager.addListener(listener, this); @@ -632,7 +632,7 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{ * @param size view size * @return initialized scroll view object */ - _initWithViewSize:function (size) { + _initWithViewSize: function (size) { return null; }, @@ -641,7 +641,7 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{ * * @param animated If YES, relocation is animated */ - _relocateContainer:function (animated) { + _relocateContainer: function (animated) { var min = this.minContainerOffset(); var max = this.maxContainerOffset(); var locDirection = this._direction; @@ -669,7 +669,7 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{ * * @param {Number} dt delta */ - _deaccelerateScrolling:function (dt) { + _deaccelerateScrolling: function (dt) { if (this._dragging) { this.unschedule(this._deaccelerateScrolling); return; @@ -678,7 +678,7 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{ var maxInset, minInset; var oldPosition = this._container.getPosition(); var locScrollDistance = this._scrollDistance; - this._container.setPosition(oldPosition.x + locScrollDistance.x , oldPosition.y + locScrollDistance.y); + this._container.setPosition(oldPosition.x + locScrollDistance.x, oldPosition.y + locScrollDistance.y); if (this._bounceable) { maxInset = this._maxInset; minInset = this._minInset; @@ -709,7 +709,7 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{ /** * This method makes sure auto scrolling causes delegate to invoke its method */ - _performedAnimatedScroll:function (dt) { + _performedAnimatedScroll: function (dt) { if (this._dragging) { this.unschedule(this._performedAnimatedScroll); return; @@ -721,7 +721,7 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{ /** * Expire animated scroll delegate calls */ - _stoppedAnimatedScroll:function (node) { + _stoppedAnimatedScroll: function (node) { this.unschedule(this._performedAnimatedScroll); // After the animation stopped, "scrollViewDidScroll" should be invoked, this could fix the bug of lack of tableview cells. if (this._delegate && this._delegate.scrollViewDidScroll) { @@ -732,11 +732,11 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{ /** * Zoom handling */ - _handleZoom:function () { + _handleZoom: function () { }, - _getViewRect:function(){ - var screenPos = this.convertToWorldSpace(cc.p(0,0)); + _getViewRect: function () { + var screenPos = this.convertToWorldSpace(cc.p(0, 0)); var locViewSize = this._viewSize; var scaleX = this.getScaleX(); @@ -767,7 +767,7 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{ return locViewRect; }, - _createRenderCmd: function(){ + _createRenderCmd: function () { if (cc._renderType === cc.game.RENDER_TYPE_CANVAS) { return new cc.ScrollView.CanvasRenderCmd(this); } else { @@ -815,4 +815,4 @@ _p = null; */ cc.ScrollView.create = function (size, container) { return new cc.ScrollView(size, container); -}; \ No newline at end of file +}; diff --git a/extensions/gui/scrollview/CCScrollViewCanvasRenderCmd.js b/extensions/gui/scrollview/CCScrollViewCanvasRenderCmd.js index 7b5e89c715..81b8121ec9 100644 --- a/extensions/gui/scrollview/CCScrollViewCanvasRenderCmd.js +++ b/extensions/gui/scrollview/CCScrollViewCanvasRenderCmd.js @@ -36,7 +36,7 @@ var proto = cc.ScrollView.CanvasRenderCmd.prototype = Object.create(cc.Layer.CanvasRenderCmd.prototype); proto.constructor = cc.ScrollView.CanvasRenderCmd; - proto._startCmd = function(ctx, scaleX, scaleY){ + proto._startCmd = function (ctx, scaleX, scaleY) { var node = this._node; var wrapper = ctx || cc._renderContext, context = wrapper.getContext(); wrapper.save(); @@ -57,7 +57,7 @@ } }; - proto._endCmd = function(wrapper){ + proto._endCmd = function (wrapper) { wrapper = wrapper || cc._renderContext; wrapper.restore(); }; diff --git a/extensions/gui/scrollview/CCScrollViewWebGLRenderCmd.js b/extensions/gui/scrollview/CCScrollViewWebGLRenderCmd.js index d435aac834..1623f6a0a1 100644 --- a/extensions/gui/scrollview/CCScrollViewWebGLRenderCmd.js +++ b/extensions/gui/scrollview/CCScrollViewWebGLRenderCmd.js @@ -34,11 +34,11 @@ var proto = cc.ScrollView.WebGLRenderCmd.prototype = Object.create(cc.Layer.WebGLRenderCmd.prototype); proto.constructor = cc.ScrollView.WebGLRenderCmd; - proto._startCmd = function(){ + proto._startCmd = function () { var node = this._node; var EGLViewer = cc.view; var frame = node._getViewRect(); - if(EGLViewer.isScissorEnabled()){ + if (EGLViewer.isScissorEnabled()) { node._scissorRestored = true; node._parentScissorRect = EGLViewer.getScissorRect(); //set the intersection of m_tParentScissorRect and frame as the new scissor rect @@ -50,7 +50,7 @@ var yy = Math.min(frame.y + frame.height, locPSRect.y + locPSRect.height); EGLViewer.setScissorInPoints(x, y, xx - x, yy - y); } - }else{ + } else { var ctx = cc._renderContext; ctx.enable(ctx.SCISSOR_TEST); //clip @@ -58,12 +58,12 @@ } }; - proto._endCmd = function(){ + proto._endCmd = function () { var node = this._node; if (node._scissorRestored) { //restore the parent's scissor rect var rect = node._parentScissorRect; cc.view.setScissorInPoints(rect.x, rect.y, rect.width, rect.height); - }else{ + } else { var ctx = cc._renderContext; ctx.disable(ctx.SCISSOR_TEST); } @@ -103,4 +103,4 @@ this._dirtyFlag = 0; }; -})(); \ No newline at end of file +})(); diff --git a/extensions/gui/scrollview/CCTableView.js b/extensions/gui/scrollview/CCTableView.js index b7b8ef044f..a197ada84a 100644 --- a/extensions/gui/scrollview/CCTableView.js +++ b/extensions/gui/scrollview/CCTableView.js @@ -48,30 +48,30 @@ cc.TABLEVIEW_FILL_BOTTOMUP = 1; * @property {Number} objectId - The index used internally by SWTableView and its subclasses */ cc.TableViewCell = cc.Node.extend(/** @lends cc.TableViewCell# */{ - _idx:0, - _className:"TableViewCell", + _idx: 0, + _className: "TableViewCell", /** * The index used internally by SWTableView and its subclasses */ - getIdx:function () { + getIdx: function () { return this._idx; }, - setIdx:function (idx) { + setIdx: function (idx) { this._idx = idx; }, /** * Cleans up any resources linked to this cell and resets idx property. */ - reset:function () { + reset: function () { this._idx = cc.INVALID_INDEX; }, - setObjectID:function (idx) { + setObjectID: function (idx) { this._idx = idx; }, - getObjectID:function () { + getObjectID: function () { return this._idx; } }); @@ -94,7 +94,7 @@ cc.TableViewDelegate = cc.ScrollViewDelegate.extend(/** @lends cc.TableViewDeleg * @param {cc.TableView} table table contains the given cell * @param {cc.TableViewCell} cell cell that is touched */ - tableCellTouched:function (table, cell) { + tableCellTouched: function (table, cell) { }, /** @@ -103,7 +103,7 @@ cc.TableViewDelegate = cc.ScrollViewDelegate.extend(/** @lends cc.TableViewDeleg * @param {cc.TableView} table table contains the given cell * @param {cc.TableViewCell} cell cell that is pressed */ - tableCellHighlight:function(table, cell){ + tableCellHighlight: function (table, cell) { }, /** @@ -112,7 +112,7 @@ cc.TableViewDelegate = cc.ScrollViewDelegate.extend(/** @lends cc.TableViewDeleg * @param {cc.TableView} table table contains the given cell * @param {cc.TableViewCell} cell cell that is pressed */ - tableCellUnhighlight:function(table, cell){ + tableCellUnhighlight: function (table, cell) { }, @@ -125,7 +125,7 @@ cc.TableViewDelegate = cc.ScrollViewDelegate.extend(/** @lends cc.TableViewDeleg * @param table table contains the given cell * @param cell cell that is pressed */ - tableCellWillRecycle:function(table, cell){ + tableCellWillRecycle: function (table, cell) { } }); @@ -140,7 +140,7 @@ cc.TableViewDataSource = cc.Class.extend(/** @lends cc.TableViewDataSource# */{ * @param {Number} idx the index of a cell to get a size * @return {cc.Size} size of a cell at given index */ - tableCellSizeForIndex:function(table, idx){ + tableCellSizeForIndex: function (table, idx) { return this.cellSizeForTable(table); }, /** @@ -149,8 +149,8 @@ cc.TableViewDataSource = cc.Class.extend(/** @lends cc.TableViewDataSource# */{ * @param {cc.TableView} table table to hold the instances of Class * @return {cc.Size} cell size */ - cellSizeForTable:function (table) { - return cc.size(0,0); + cellSizeForTable: function (table) { + return cc.size(0, 0); }, /** @@ -159,7 +159,7 @@ cc.TableViewDataSource = cc.Class.extend(/** @lends cc.TableViewDataSource# */{ * @param idx index to search for a cell * @return {cc.TableView} cell found at idx */ - tableCellAtIndex:function (table, idx) { + tableCellAtIndex: function (table, idx) { return null; }, @@ -168,7 +168,7 @@ cc.TableViewDataSource = cc.Class.extend(/** @lends cc.TableViewDataSource# */{ * @param {cc.TableView} table table to hold the instances of Class * @return {Number} number of cells */ - numberOfCellsInTableView:function (table) { + numberOfCellsInTableView: function (table) { return 0; } }); @@ -186,14 +186,14 @@ cc.TableViewDataSource = cc.Class.extend(/** @lends cc.TableViewDataSource# */{ * */ cc.TableView = cc.ScrollView.extend(/** @lends cc.TableView# */{ - _vOrdering:null, - _indices:null, - _cellsFreed:null, - _dataSource:null, - _tableViewDelegate:null, - _oldDirection:null, - _cellsPositions:null, //vector with all cell positions - _touchedCell:null, + _vOrdering: null, + _indices: null, + _cellsFreed: null, + _dataSource: null, + _tableViewDelegate: null, + _oldDirection: null, + _cellsPositions: null, //vector with all cell positions + _touchedCell: null, /** * The @@ -201,7 +201,7 @@ cc.TableView = cc.ScrollView.extend(/** @lends cc.TableView# */{ * @param size * @param container */ - ctor:function (dataSource, size, container) { + ctor: function (dataSource, size, container) { cc.ScrollView.prototype.ctor.call(this); this._oldDirection = cc.SCROLLVIEW_DIRECTION_NONE; this._cellsPositions = []; @@ -212,7 +212,7 @@ cc.TableView = cc.ScrollView.extend(/** @lends cc.TableView# */{ this._updateContentSize(); }, - __indexFromOffset:function (offset) { + __indexFromOffset: function (offset) { var low = 0; var high = this._dataSource.numberOfCellsInTableView(this) - 1; var search; @@ -226,16 +226,16 @@ cc.TableView = cc.ScrollView.extend(/** @lends cc.TableView# */{ } var locCellsPositions = this._cellsPositions; - while (high >= low){ - var index = 0|(low + (high - low) / 2); + while (high >= low) { + var index = 0 | (low + (high - low) / 2); var cellStart = locCellsPositions[index]; var cellEnd = locCellsPositions[index + 1]; - if (search >= cellStart && search <= cellEnd){ + if (search >= cellStart && search <= cellEnd) { return index; - } else if (search < cellStart){ + } else if (search < cellStart) { high = index - 1; - }else { + } else { low = index + 1; } } @@ -245,7 +245,7 @@ cc.TableView = cc.ScrollView.extend(/** @lends cc.TableView# */{ return -1; }, - _indexFromOffset:function (offset) { + _indexFromOffset: function (offset) { var locOffset = {x: offset.x, y: offset.y}; var locDataSource = this._dataSource; var maxIdx = locDataSource.numberOfCellsInTableView(this) - 1; @@ -262,7 +262,7 @@ cc.TableView = cc.ScrollView.extend(/** @lends cc.TableView# */{ return index; }, - __offsetFromIndex:function (index) { + __offsetFromIndex: function (index) { var offset; switch (this.getDirection()) { case cc.SCROLLVIEW_DIRECTION_HORIZONTAL: @@ -276,7 +276,7 @@ cc.TableView = cc.ScrollView.extend(/** @lends cc.TableView# */{ return offset; }, - _offsetFromIndex:function (index) { + _offsetFromIndex: function (index) { var offset = this.__offsetFromIndex(index); var cellSize = this._dataSource.tableCellSizeForIndex(this, index); @@ -286,14 +286,14 @@ cc.TableView = cc.ScrollView.extend(/** @lends cc.TableView# */{ return offset; }, - _updateCellPositions:function(){ + _updateCellPositions: function () { var cellsCount = this._dataSource.numberOfCellsInTableView(this); var locCellsPositions = this._cellsPositions; - if (cellsCount > 0){ + if (cellsCount > 0) { var currentPos = 0; var cellSize, locDataSource = this._dataSource; - for (var i=0; i < cellsCount; i++) { + for (var i = 0; i < cellsCount; i++) { locCellsPositions[i] = currentPos; cellSize = locDataSource.tableCellSizeForIndex(this, i); switch (this.getDirection()) { @@ -309,12 +309,12 @@ cc.TableView = cc.ScrollView.extend(/** @lends cc.TableView# */{ } }, - _updateContentSize:function () { + _updateContentSize: function () { var size = cc.size(0, 0); var cellsCount = this._dataSource.numberOfCellsInTableView(this); - if(cellsCount > 0){ + if (cellsCount > 0) { var maxPosition = this._cellsPositions[cellsCount]; switch (this.getDirection()) { case cc.SCROLLVIEW_DIRECTION_HORIZONTAL: @@ -338,8 +338,8 @@ cc.TableView = cc.ScrollView.extend(/** @lends cc.TableView# */{ } }, - _moveCellOutOfSight:function (cell) { - if(this._tableViewDelegate && this._tableViewDelegate.tableCellWillRecycle) + _moveCellOutOfSight: function (cell) { + if (this._tableViewDelegate && this._tableViewDelegate.tableCellWillRecycle) this._tableViewDelegate.tableCellWillRecycle(this, cell); this._cellsFreed.addObject(cell); @@ -352,50 +352,52 @@ cc.TableView = cc.ScrollView.extend(/** @lends cc.TableView# */{ } }, - _setIndexForCell:function (index, cell) { + _setIndexForCell: function (index, cell) { cell.setAnchorPoint(0, 0); cell.setPosition(this._offsetFromIndex(index)); cell.setIdx(index); }, - _addCellIfNecessary:function (cell) { + _addCellIfNecessary: function (cell) { if (cell.getParent() !== this.getContainer()) { this.getContainer().addChild(cell); } this._cellsUsed.insertSortedObject(cell); var locIndices = this._indices, addIdx = cell.getIdx(); - if(locIndices.indexOf(addIdx) === -1){ + if (locIndices.indexOf(addIdx) === -1) { locIndices.push(addIdx); //sort - locIndices.sort(function(a,b){return a-b;}); + locIndices.sort(function (a, b) { + return a - b; + }); } }, /** * data source */ - getDataSource:function () { + getDataSource: function () { return this._dataSource; }, - setDataSource:function (source) { + setDataSource: function (source) { this._dataSource = source; }, /** * delegate */ - getDelegate:function () { + getDelegate: function () { return this._tableViewDelegate; }, - setDelegate:function (delegate) { + setDelegate: function (delegate) { this._tableViewDelegate = delegate; }, /** * determines how cell is ordered and filled in the view. */ - setVerticalFillOrder:function (fillOrder) { + setVerticalFillOrder: function (fillOrder) { if (this._vOrdering !== fillOrder) { this._vOrdering = fillOrder; if (this._cellsUsed.count() > 0) { @@ -403,11 +405,11 @@ cc.TableView = cc.ScrollView.extend(/** @lends cc.TableView# */{ } } }, - getVerticalFillOrder:function () { + getVerticalFillOrder: function () { return this._vOrdering; }, - initWithViewSize:function (size, container) { + initWithViewSize: function (size, container) { if (cc.ScrollView.prototype.initWithViewSize.call(this, size, container)) { this._cellsUsed = new cc.ArrayForObjectSorting(); this._cellsFreed = new cc.ArrayForObjectSorting(); @@ -427,7 +429,7 @@ cc.TableView = cc.ScrollView.extend(/** @lends cc.TableView# */{ * * @param idx index to find a cell */ - updateCellAtIndex:function (idx) { + updateCellAtIndex: function (idx) { if (idx === cc.INVALID_INDEX || idx > this._dataSource.numberOfCellsInTableView(this) - 1) return; @@ -445,7 +447,7 @@ cc.TableView = cc.ScrollView.extend(/** @lends cc.TableView# */{ * * @param idx location to insert */ - insertCellAtIndex:function (idx) { + insertCellAtIndex: function (idx) { if (idx === cc.INVALID_INDEX || idx > this._dataSource.numberOfCellsInTableView(this) - 1) return; @@ -473,7 +475,7 @@ cc.TableView = cc.ScrollView.extend(/** @lends cc.TableView# */{ * * @param idx index to find a cell */ - removeCellAtIndex:function (idx) { + removeCellAtIndex: function (idx) { if (idx === cc.INVALID_INDEX || idx > this._dataSource.numberOfCellsInTableView(this) - 1) return; @@ -498,13 +500,13 @@ cc.TableView = cc.ScrollView.extend(/** @lends cc.TableView# */{ /** * reloads data from data source. the view will be refreshed. */ - reloadData:function () { + reloadData: function () { this._oldDirection = cc.SCROLLVIEW_DIRECTION_NONE; var locCellsUsed = this._cellsUsed, locCellsFreed = this._cellsFreed, locContainer = this.getContainer(); for (var i = 0, len = locCellsUsed.count(); i < len; i++) { var cell = locCellsUsed.objectAtIndex(i); - if(this._tableViewDelegate && this._tableViewDelegate.tableCellWillRecycle) + if (this._tableViewDelegate && this._tableViewDelegate.tableCellWillRecycle) this._tableViewDelegate.tableCellWillRecycle(this, cell); locCellsFreed.addObject(cell); @@ -529,7 +531,7 @@ cc.TableView = cc.ScrollView.extend(/** @lends cc.TableView# */{ * * @return {TableViewCell} free cell */ - dequeueCell:function () { + dequeueCell: function () { if (this._cellsFreed.count() === 0) { return null; } else { @@ -545,14 +547,14 @@ cc.TableView = cc.ScrollView.extend(/** @lends cc.TableView# */{ * @param idx index * @return {cc.TableViewCell} a cell at a given index */ - cellAtIndex:function (idx) { + cellAtIndex: function (idx) { var i = this._indices.indexOf(idx); if (i === -1) return null; return this._cellsUsed.objectWithObjectID(idx); }, - scrollViewDidScroll:function (view) { + scrollViewDidScroll: function (view) { var locDataSource = this._dataSource; var countOfItems = locDataSource.numberOfCellsInTableView(this); if (0 === countOfItems) @@ -561,24 +563,24 @@ cc.TableView = cc.ScrollView.extend(/** @lends cc.TableView# */{ if (this._tableViewDelegate !== null && this._tableViewDelegate.scrollViewDidScroll) this._tableViewDelegate.scrollViewDidScroll(this); - var idx = 0, locViewSize = this._viewSize, locContainer = this.getContainer(); + var idx = 0, locViewSize = this._viewSize, locContainer = this.getContainer(); var offset = this.getContentOffset(); offset.x *= -1; offset.y *= -1; - var maxIdx = Math.max(countOfItems-1, 0); + var maxIdx = Math.max(countOfItems - 1, 0); if (this._vOrdering === cc.TABLEVIEW_FILL_TOPDOWN) - offset.y = offset.y + locViewSize.height/locContainer.getScaleY(); + offset.y = offset.y + locViewSize.height / locContainer.getScaleY(); var startIdx = this._indexFromOffset(offset); if (startIdx === cc.INVALID_INDEX) startIdx = countOfItems - 1; if (this._vOrdering === cc.TABLEVIEW_FILL_TOPDOWN) - offset.y -= locViewSize.height/locContainer.getScaleY(); + offset.y -= locViewSize.height / locContainer.getScaleY(); else - offset.y += locViewSize.height/locContainer.getScaleY(); - offset.x += locViewSize.width/locContainer.getScaleX(); + offset.y += locViewSize.height / locContainer.getScaleY(); + offset.x += locViewSize.width / locContainer.getScaleX(); var endIdx = this._indexFromOffset(offset); if (endIdx === cc.INVALID_INDEX) @@ -619,24 +621,24 @@ cc.TableView = cc.ScrollView.extend(/** @lends cc.TableView# */{ } }, - scrollViewDidZoom:function (view) { + scrollViewDidZoom: function (view) { }, - onTouchEnded:function (touch, event) { + onTouchEnded: function (touch, event) { if (!this.isVisible()) return; - if (this._touchedCell){ + if (this._touchedCell) { var bb = this.getBoundingBox(); var tmpOrigin = cc.p(bb.x, bb.y); tmpOrigin = this._parent.convertToWorldSpace(tmpOrigin); bb.x = tmpOrigin.x; bb.y = tmpOrigin.y; var locTableViewDelegate = this._tableViewDelegate; - if (cc.rectContainsPoint(bb, touch.getLocation()) && locTableViewDelegate !== null){ - if(locTableViewDelegate.tableCellUnhighlight) + if (cc.rectContainsPoint(bb, touch.getLocation()) && locTableViewDelegate !== null) { + if (locTableViewDelegate.tableCellUnhighlight) locTableViewDelegate.tableCellUnhighlight(this, this._touchedCell); - if(locTableViewDelegate.tableCellTouched) + if (locTableViewDelegate.tableCellTouched) locTableViewDelegate.tableCellTouched(this, this._touchedCell); } this._touchedCell = null; @@ -644,7 +646,7 @@ cc.TableView = cc.ScrollView.extend(/** @lends cc.TableView# */{ cc.ScrollView.prototype.onTouchEnded.call(this, touch, event); }, - onTouchBegan:function(touch, event){ + onTouchBegan: function (touch, event) { for (var c = this; c != null; c = c.parent) { if (!c.isVisible()) return false; @@ -652,7 +654,7 @@ cc.TableView = cc.ScrollView.extend(/** @lends cc.TableView# */{ var touchResult = cc.ScrollView.prototype.onTouchBegan.call(this, touch, event); - if(this._touches.length === 1) { + if (this._touches.length === 1) { var index, point; point = this.getContainer().convertTouchToNodeSpace(touch); @@ -661,12 +663,12 @@ cc.TableView = cc.ScrollView.extend(/** @lends cc.TableView# */{ if (index === cc.INVALID_INDEX) this._touchedCell = null; else - this._touchedCell = this.cellAtIndex(index); + this._touchedCell = this.cellAtIndex(index); if (this._touchedCell && this._tableViewDelegate !== null && this._tableViewDelegate.tableCellHighlight) this._tableViewDelegate.tableCellHighlight(this, this._touchedCell); - } else if(this._touchedCell) { - if(this._tableViewDelegate !== null && this._tableViewDelegate.tableCellUnhighlight) + } else if (this._touchedCell) { + if (this._tableViewDelegate !== null && this._tableViewDelegate.tableCellUnhighlight) this._tableViewDelegate.tableCellUnhighlight(this, this._touchedCell); this._touchedCell = null; } @@ -674,21 +676,21 @@ cc.TableView = cc.ScrollView.extend(/** @lends cc.TableView# */{ return touchResult; }, - onTouchMoved: function(touch, event){ + onTouchMoved: function (touch, event) { cc.ScrollView.prototype.onTouchMoved.call(this, touch, event); if (this._touchedCell && this.isTouchMoved()) { - if(this._tableViewDelegate !== null && this._tableViewDelegate.tableCellUnhighlight) + if (this._tableViewDelegate !== null && this._tableViewDelegate.tableCellUnhighlight) this._tableViewDelegate.tableCellUnhighlight(this, this._touchedCell); this._touchedCell = null; } }, - onTouchCancelled: function(touch, event){ + onTouchCancelled: function (touch, event) { cc.ScrollView.prototype.onTouchCancelled.call(this, touch, event); if (this._touchedCell) { - if(this._tableViewDelegate !== null && this._tableViewDelegate.tableCellUnhighlight) + if (this._tableViewDelegate !== null && this._tableViewDelegate.tableCellUnhighlight) this._tableViewDelegate.tableCellUnhighlight(this, this._touchedCell); this._touchedCell = null; } diff --git a/extensions/spine/CCSkeletonCanvasRenderCmd.js b/extensions/spine/CCSkeletonCanvasRenderCmd.js index 589ab62c53..d5f1c2c207 100644 --- a/extensions/spine/CCSkeletonCanvasRenderCmd.js +++ b/extensions/spine/CCSkeletonCanvasRenderCmd.js @@ -36,10 +36,10 @@ wrapper = wrapper || cc._renderContext; var locSkeleton = node._skeleton, drawOrder = locSkeleton.drawOrder; - for(i = 0, n = drawOrder.length; i < n; i++){ + for (i = 0, n = drawOrder.length; i < n; i++) { slot = drawOrder[i]; slotNode = slot._slotNode; - if(slotNode._visible && slotNode._renderCmd && slot.currentSprite){ + if (slotNode._visible && slotNode._renderCmd && slot.currentSprite) { slotNode._renderCmd.transform(this, true); slot.currentSprite._renderCmd.rendering(wrapper, scaleX, scaleY); slotNode._renderCmd._dirtyFlag = slot.currentSprite._renderCmd._dirtyFlag = 0; @@ -96,8 +96,8 @@ } }; - proto._updateRegionAttachmentSlot = function(attachment, slot, points) { - if(!points) + proto._updateRegionAttachmentSlot = function (attachment, slot, points) { + if (!points) return; var vertices = {}, VERTEX = sp.VERTEX_INDEX, bone = slot.bone; @@ -109,7 +109,7 @@ points.push(cc.p(vertices[VERTEX.X2], vertices[VERTEX.Y2])); }; - proto._createChildFormSkeletonData = function(){ + proto._createChildFormSkeletonData = function () { var node = this._node; var locSkeleton = node._skeleton, spriteName, sprite; for (var i = 0, n = locSkeleton.slots.length; i < n; i++) { @@ -117,13 +117,13 @@ var slotNode = new cc.Node(); slot._slotNode = slotNode; - if(attachment instanceof spine.RegionAttachment){ + if (attachment instanceof spine.RegionAttachment) { spriteName = attachment.rendererObject.name; sprite = this._createSprite(slot, attachment); slot.currentSprite = sprite; slot.currentSpriteName = spriteName; slotNode.addChild(sprite); - } else if(attachment instanceof spine.MeshAttachment){ + } else if (attachment instanceof spine.MeshAttachment) { //todo for mesh } } @@ -140,7 +140,7 @@ rendererObject.height / rendererObject.originalHeight * attachment.scaleY); }; - proto._createSprite = function(slot, attachment){ + proto._createSprite = function (slot, attachment) { var rendererObject = attachment.rendererObject; var texture = rendererObject.page._texture; var sprite = new cc.Sprite(); @@ -156,30 +156,30 @@ return sprite; }; - proto._updateChild = function(){ + proto._updateChild = function () { var locSkeleton = this._node._skeleton, slots = locSkeleton.slots; var i, n, selSprite; var slot, attachment, slotNode; - for(i = 0, n = slots.length; i < n; i++){ + for (i = 0, n = slots.length; i < n; i++) { slot = slots[i]; attachment = slot.attachment; slotNode = slot._slotNode; - if(!attachment){ + if (!attachment) { slotNode.setVisible(false); continue; } var type = attachment.type; - if (type === spine.AttachmentType.region){ - if(attachment.rendererObject){ - if(!slot.currentSpriteName || slot.currentSpriteName !== attachment.name){ - var spriteName = attachment.rendererObject.name; - if(slot.currentSprite !== undefined) + if (type === spine.AttachmentType.region) { + if (attachment.rendererObject) { + if (!slot.currentSpriteName || slot.currentSpriteName !== attachment.name) { + var spriteName = attachment.rendererObject.name; + if (slot.currentSprite !== undefined) slot.currentSprite.setVisible(false); - slot.sprites = slot.sprites ||{}; - if(slot.sprites[spriteName] !== undefined) + slot.sprites = slot.sprites || {}; + if (slot.sprites[spriteName] !== undefined) slot.sprites[spriteName].setVisible(true); - else{ + else { var sprite = this._createSprite(slot, attachment); slotNode.addChild(sprite); } @@ -196,10 +196,10 @@ selSprite = slot.currentSprite; selSprite._flippedX = bone.worldFlipX; selSprite._flippedY = bone.worldFlipY; - if(selSprite._flippedY || selSprite._flippedX){ + if (selSprite._flippedY || selSprite._flippedX) { slotNode.setRotation(bone.worldRotation); selSprite.setRotation(attachment.rotation); - }else{ + } else { slotNode.setRotation(-bone.worldRotation); selSprite.setRotation(-attachment.rotation); } @@ -207,7 +207,7 @@ //hack for sprite 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.setColor(cc.color(r, g, b)); selSprite._renderCmd._updateColor(); } else if (type === spine.AttachmentType.skinnedmesh) { //todo for mesh @@ -218,4 +218,4 @@ slotNode.setVisible(true); } }; -})(); \ No newline at end of file +})(); diff --git a/extensions/spine/CCSkeletonWebGLRenderCmd.js b/extensions/spine/CCSkeletonWebGLRenderCmd.js index 77f4d76573..f659221929 100644 --- a/extensions/spine/CCSkeletonWebGLRenderCmd.js +++ b/extensions/spine/CCSkeletonWebGLRenderCmd.js @@ -22,7 +22,7 @@ THE SOFTWARE. ****************************************************************************/ -(function(){ +(function () { sp.Skeleton.WebGLRenderCmd = function (renderableObject) { cc.Node.WebGLRenderCmd.call(this, renderableObject); this._needDraw = true; @@ -71,7 +71,7 @@ continue; attachment = slot.attachment; - switch(slot.attachment.type) { + switch (slot.attachment.type) { case sp.ATTACHMENT_TYPE.REGION: this._updateRegionAttachmentQuad(attachment, slot, tmpQuad, premultiAlpha); break; @@ -184,11 +184,13 @@ } }; - proto._createChildFormSkeletonData = function(){}; + proto._createChildFormSkeletonData = function () { + }; - proto._updateChild = function(){}; + proto._updateChild = function () { + }; - proto._updateRegionAttachmentQuad = function(self, slot, quad, premultipliedAlpha) { + proto._updateRegionAttachmentQuad = function (self, slot, quad, premultipliedAlpha) { var vertices = {}; self.computeVertices(slot.bone.skeleton.x, slot.bone.skeleton.y, slot.bone, vertices); var a = slot.bone.skeleton.a * slot.a * attachment.a * 255; @@ -222,7 +224,7 @@ quad.br.texCoords.v = self.uvs[VERTEX.Y4]; }; - proto._updateMeshAttachmentQuad = function(self, slot, quad, premultipliedAlpha) { + proto._updateMeshAttachmentQuad = function (self, slot, quad, premultipliedAlpha) { var vertices = {}; self.computeWorldVertices(slot.bone.x, slot.bone.y, slot, vertices); var r = slot.bone.skeleton.r * slot.r * 255; From 35d19b771bec82999289f587f43875673c4417e3 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Thu, 8 Dec 2016 17:13:05 +0800 Subject: [PATCH 21/42] A set of small improvements --- CCBoot.js | 78 +++---------------- cocos2d/audio/CCAudio.js | 8 +- cocos2d/core/CCDirector.js | 9 --- cocos2d/core/CCScheduler.js | 4 +- .../core/base-nodes/CCNodeCanvasRenderCmd.js | 17 ++-- cocos2d/core/cocoa/CCAffineTransform.js | 11 +++ cocos2d/core/platform/CCCommon.js | 39 +--------- cocos2d/core/platform/CCEGLView.js | 13 ++-- cocos2d/core/renderer/RendererWebGL.js | 2 +- cocos2d/core/sprites/CCSprite.js | 10 --- cocos2d/core/sprites/CCSpriteFrameCache.js | 1 + cocos2d/core/textures/CCTexture2D.js | 14 ++-- cocos2d/core/utils/CCProfiler.js | 5 +- cocos2d/menus/CCMenu.js | 15 ++-- extensions/cocostudio/armature/CCArmature.js | 1 - 15 files changed, 65 insertions(+), 162 deletions(-) diff --git a/CCBoot.js b/CCBoot.js index ec03e1080a..260854524a 100644 --- a/CCBoot.js +++ b/CCBoot.js @@ -594,37 +594,7 @@ cc.loader = (function () { _langPathCache = {}, //cache for lang path _aliases = {}, //aliases for res url _queue = {}, // Callback queue for resources already loading - _urlRegExp = new RegExp( - "^" + - // protocol identifier - "(?:(?:https?|ftp)://)" + - // user:pass authentication - "(?:\\S+(?::\\S*)?@)?" + - "(?:" + - // IP address dotted notation octets - // excludes loopback network 0.0.0.0 - // excludes reserved space >= 224.0.0.0 - // excludes network & broacast addresses - // (first & last IP address of each class) - "(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])" + - "(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}" + - "(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))" + - "|" + - // host name - "(?:(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)" + - // domain name - "(?:\\.(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)*" + - // TLD identifier - "(?:\\.(?:[a-z\\u00a1-\\uffff]{2,}))" + - "|" + - "(?:localhost)" + - ")" + - // port number - "(?::\\d{2,5})?" + - // resource path - "(?:/\\S*)?" + - "$", "i" - ); + _urlRegExp = new RegExp("^(?:https?|ftp)://\\S*$", "i"); return /** @lends cc.Loader# */{ /** @@ -650,7 +620,9 @@ cc.loader = (function () { * @returns {XMLHttpRequest} */ getXMLHttpRequest: function () { - return window.XMLHttpRequest ? new window.XMLHttpRequest() : new ActiveXObject("MSXML2.XMLHTTP"); + var xhr = window.XMLHttpRequest ? new window.XMLHttpRequest() : new ActiveXObject("MSXML2.XMLHTTP"); + xhr.timeout = 10000; + return xhr; }, //@MODE_BEGIN DEV @@ -1863,13 +1835,13 @@ var _initSys = function () { if (win.WebGLRenderingContext) { var tmpCanvas = document.createElement("CANVAS"); try{ - var context = cc.create3DContext(tmpCanvas, {'stencil': true}); + var context = cc.create3DContext(tmpCanvas); if (context && context.getShaderPrecisionFormat) { _supportWebGL = true; } - if (_supportWebGL && sys.os === sys.OS_IOS) { - // Not activating WebGL in iOS UIWebView because it may crash when entering background + if (_supportWebGL && sys.os === sys.OS_IOS && sys.osMainVersion === 9) { + // Not activating WebGL in iOS 9 UIWebView because it may crash when entering background if (!window.indexedDB) { _supportWebGL = false; } @@ -2691,8 +2663,8 @@ cc.game = /** @lends cc.game# */{ this._renderContext = cc._renderContext = cc.webglContext = cc.create3DContext(localCanvas, { 'stencil': true, - 'antialias': !cc.sys.isMobile, - 'alpha': false + 'alpha': false, + 'preserveDrawingBuffer': false }); } // WebGL context created successfully @@ -2809,35 +2781,3 @@ Function.prototype.bind = Function.prototype.bind || function (oThis) { return fBound; }; - -cc._urlRegExp = new RegExp( - "^" + - // protocol identifier - "(?:(?:https?|ftp)://)" + - // user:pass authentication - "(?:\\S+(?::\\S*)?@)?" + - "(?:" + - // IP address dotted notation octets - // excludes loopback network 0.0.0.0 - // excludes reserved space >= 224.0.0.0 - // excludes network & broacast addresses - // (first & last IP address of each class) - "(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])" + - "(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}" + - "(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))" + - "|" + - // host name - "(?:(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)" + - // domain name - "(?:\\.(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)*" + - // TLD identifier - "(?:\\.(?:[a-z\\u00a1-\\uffff]{2,}))" + - "|" + - "(?:localhost)" + - ")" + - // port number - "(?::\\d{2,5})?" + - // resource path - "(?:/\\S*)?" + - "$", "i" -); diff --git a/cocos2d/audio/CCAudio.js b/cocos2d/audio/CCAudio.js index f4e9cec4f6..b48b63d411 100644 --- a/cocos2d/audio/CCAudio.js +++ b/cocos2d/audio/CCAudio.js @@ -834,6 +834,7 @@ cc.Audio.WebAudio.prototype = { } list.length = 0; } + ap.length = 0; }, /** @@ -850,7 +851,12 @@ cc.Audio.WebAudio.prototype = { cc.loader.release(url); var pool = this._audioPool[url]; - if(pool) pool.length = 0; + if (pool) { + for (var i = 0; i < pool.length; i++) { + pool[i].stop(); + } + pool.length = 0; + } delete this._audioPool[url]; }, diff --git a/cocos2d/core/CCDirector.js b/cocos2d/core/CCDirector.js index 3cfcfc77fe..9f6a6ce1a0 100644 --- a/cocos2d/core/CCDirector.js +++ b/cocos2d/core/CCDirector.js @@ -239,9 +239,6 @@ cc.Director = cc.Class.extend(/** @lends cc.Director# */{ this.setNextScene(); } - if (this._beforeVisitScene) - this._beforeVisitScene(); - // draw the scene if (this._runningScene) { if (renderer.childrenOrderDirty) { @@ -265,9 +262,6 @@ cc.Director = cc.Class.extend(/** @lends cc.Director# */{ cc.eventManager.dispatchEvent(this._eventAfterVisit); cc.g_NumberOfDraws = 0; - if (this._afterVisitScene) - this._afterVisitScene(); - renderer.rendering(cc._renderContext); this._totalFrames++; @@ -277,9 +271,6 @@ cc.Director = cc.Class.extend(/** @lends cc.Director# */{ this._calculateMPF(); }, - _beforeVisitScene: null, - _afterVisitScene: null, - /** * End the life of director in the next frame */ diff --git a/cocos2d/core/CCScheduler.js b/cocos2d/core/CCScheduler.js index 2dbd12b71a..0c75dc15af 100644 --- a/cocos2d/core/CCScheduler.js +++ b/cocos2d/core/CCScheduler.js @@ -237,7 +237,7 @@ cc.inject({ } } - if (!this._runForever && this._timesExecuted > this._repeat) + if (this._callback && !this._runForever && this._timesExecuted > this._repeat) this.cancel(); } } @@ -596,7 +596,7 @@ cc.Scheduler = cc.Class.extend(/** @lends cc.Scheduler# */{ if (!element) { // Is this the 1st element ? Then set the pause level to all the callback_fns of this target - element = HashTimerEntry.get(null, target, 0, null, null, paused, null); + element = HashTimerEntry.get(null, target, 0, null, null, paused); this._arrayForTimers.push(element); this._hashForTimers[target.__instanceId] = element; } else { diff --git a/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js b/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js index 199cdd76be..56ed8c3aa7 100644 --- a/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js +++ b/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js @@ -27,15 +27,14 @@ cc.CustomRenderCmd = function (target, func) { this._needDraw = true; this._target = target; this._callback = func; - - this.rendering = function (ctx, scaleX, scaleY) { - if (!this._callback) - return; - this._callback.call(this._target, ctx, scaleX, scaleY); - }; - this.needDraw = function () { - return this._needDraw; - }; +}; +cc.CustomRenderCmd.prototype.rendering = function (ctx, scaleX, scaleY) { + if (!this._callback) + return; + this._callback.call(this._target, ctx, scaleX, scaleY); +}; +cc.CustomRenderCmd.prototype.needDraw = function () { + return this._needDraw; }; var dirtyFlags = cc.Node._dirtyFlags = { diff --git a/cocos2d/core/cocoa/CCAffineTransform.js b/cocos2d/core/cocoa/CCAffineTransform.js index e05a6c537b..8ff0957dfb 100644 --- a/cocos2d/core/cocoa/CCAffineTransform.js +++ b/cocos2d/core/cocoa/CCAffineTransform.js @@ -292,3 +292,14 @@ cc.affineTransformInvert = function (t) { tx: determinant * (t.c * t.ty - t.d * t.tx), ty: determinant * (t.b * t.tx - t.a * t.ty) }; }; + +cc.affineTransformInvertOut = function (t, out) { + var a = t.a, b = t.b, c = t.c, d = t.d; + var determinant = 1 / (a * d - b * c); + out.a = determinant * d; + out.b = -determinant * b; + out.c = -determinant * c; + out.d = determinant * a; + out.tx = determinant * (c * t.ty - d * t.tx); + out.ty = determinant * (b * t.tx - a * t.ty); +}; diff --git a/cocos2d/core/platform/CCCommon.js b/cocos2d/core/platform/CCCommon.js index 5855777eb8..296193ea75 100644 --- a/cocos2d/core/platform/CCCommon.js +++ b/cocos2d/core/platform/CCCommon.js @@ -244,7 +244,7 @@ cc.getImageFormatByData = function (imgData) { || (imgData[0] === 0xff && imgData[1] === 0xd8))) { return cc.FMT_TIFF; } - return cc.FMT_UNKNOWN; + return cc.FMT_UNKNOWN; }; /** @@ -265,39 +265,4 @@ cc.inherits = function (childCtor, parentCtor) { // for( var i in parentCtor ) { // childCtor[ i ] = parentCtor[ i ]; // } -}; - -/** - * @deprecated since v3.0, please use cc.Class.extend and _super - * @cc.Class.extend - */ -cc.base = function(me, opt_methodName, var_args) { - var caller = arguments.callee.caller; - if (caller.superClass_) { - // This is a constructor. Call the superclass constructor. - ret = caller.superClass_.constructor.apply( me, Array.prototype.slice.call(arguments, 1)); - return ret; - } - - var args = Array.prototype.slice.call(arguments, 2); - var foundCaller = false; - for (var ctor = me.constructor; ctor; ctor = ctor.superClass_ && ctor.superClass_.constructor) { - if (ctor.prototype[opt_methodName] === caller) { - foundCaller = true; - } else if (foundCaller) { - return ctor.prototype[opt_methodName].apply(me, args); - } - } - - // If we did not find the caller in the prototype chain, - // then one of two things happened: - // 1) The caller is an instance method. - // 2) This method was not called by the right caller. - if (me[opt_methodName] === caller) { - return me.constructor.prototype[opt_methodName].apply(me, args); - } else { - throw Error( - 'cc.base called from a method of one name ' + - 'to a method of a different name'); - } -}; +}; \ No newline at end of file diff --git a/cocos2d/core/platform/CCEGLView.js b/cocos2d/core/platform/CCEGLView.js index e84433f4d7..c6e900c4a1 100644 --- a/cocos2d/core/platform/CCEGLView.js +++ b/cocos2d/core/platform/CCEGLView.js @@ -678,11 +678,9 @@ cc.EGLView = cc.Class.extend(/** @lends cc.view# */{ this.setResolutionPolicy(resolutionPolicy); var policy = this._resolutionPolicy; - if (!policy){ - cc.log(cc._LogInfos.EGLView_setDesignResolutionSize_2); - return; + if (policy) { + policy.preApply(this); } - policy.preApply(this); // Reinit frame size if (cc.sys.isMobile) @@ -692,6 +690,11 @@ cc.EGLView = cc.Class.extend(/** @lends cc.view# */{ this._orientationChanging = true; this._initFrameSize(); + if (!policy) { + cc.log(cc._LogInfos.EGLView_setDesignResolutionSize_2); + return; + } + this._originalDesignResolutionSize.width = this._designResolutionSize.width = width; this._originalDesignResolutionSize.height = this._designResolutionSize.height = height; @@ -768,7 +771,7 @@ cc.EGLView = cc.Class.extend(/** @lends cc.view# */{ this._setViewportMeta({"width": width}, true); // Set body width to the exact pixel resolution - document.html.style.width = width + 'px'; + document.documentElement.style.width = width + 'px'; document.body.style.width = "100%"; // Reset the resolution size and policy diff --git a/cocos2d/core/renderer/RendererWebGL.js b/cocos2d/core/renderer/RendererWebGL.js index 60debaf811..327180c654 100644 --- a/cocos2d/core/renderer/RendererWebGL.js +++ b/cocos2d/core/renderer/RendererWebGL.js @@ -126,7 +126,7 @@ return { this.mat4Identity = new cc.math.Matrix4(); this.mat4Identity.identity(); - initQuadBuffer(2000); + initQuadBuffer(500); if (cc.sys.os === cc.sys.OS_IOS) { _IS_IOS = true; } diff --git a/cocos2d/core/sprites/CCSprite.js b/cocos2d/core/sprites/CCSprite.js index 5e9600a925..9314462c67 100644 --- a/cocos2d/core/sprites/CCSprite.js +++ b/cocos2d/core/sprites/CCSprite.js @@ -354,16 +354,6 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{ cc.Node.prototype.removeChild.call(this, child, cleanup); }, - /** - * Sets whether the sprite is visible or not. - * @param {Boolean} visible - * @override - */ - setVisible:function (visible) { - cc.Node.prototype.setVisible.call(this, visible); - this._renderCmd.setDirtyRecursively(true); - }, - /** * Removes all children from the container. * @param cleanup whether or not cleanup all running actions diff --git a/cocos2d/core/sprites/CCSpriteFrameCache.js b/cocos2d/core/sprites/CCSpriteFrameCache.js index 52c2ba375c..d8df34823b 100644 --- a/cocos2d/core/sprites/CCSpriteFrameCache.js +++ b/cocos2d/core/sprites/CCSpriteFrameCache.js @@ -190,6 +190,7 @@ cc.spriteFrameCache = /** @lends cc.spriteFrameCache# */{ tempTexture.initWithElement(tempElement); tempTexture.handleLoadedTexture(); spriteFrame.setTexture(tempTexture); + spriteFrame.setRotated(false); var rect = spriteFrame._rect; spriteFrame.setRect(cc.rect(0, 0, rect.width, rect.height)); diff --git a/cocos2d/core/textures/CCTexture2D.js b/cocos2d/core/textures/CCTexture2D.js index 3d1e3c66af..d3067fcf29 100644 --- a/cocos2d/core/textures/CCTexture2D.js +++ b/cocos2d/core/textures/CCTexture2D.js @@ -112,6 +112,8 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () { this._textureLoaded = false; this._htmlElementObj = null; this._pattern = ""; + this._pixelsWide = 0; + this._pixelsHigh = 0; }, /** @@ -119,7 +121,7 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () { * @return {Number} */ getPixelsWide: function () { - return this._contentSize.width; + return this._pixelsWide; }, /** @@ -127,7 +129,7 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () { * @return {Number} */ getPixelsHigh: function () { - return this._contentSize.height; + return this._pixelsHigh; }, /** @@ -162,8 +164,8 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () { if (!element) return; this._htmlElementObj = element; - this._contentSize.width = element.width; - this._contentSize.height = element.height; + this._pixelsWide = this._contentSize.width = element.width; + this._pixelsHigh = this._contentSize.height = element.height; this._textureLoaded = true; }, @@ -196,8 +198,8 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () { } var locElement = self._htmlElementObj; - self._contentSize.width = locElement.width; - self._contentSize.height = locElement.height; + self._pixelsWide = self._contentSize.width = locElement.width; + self._pixelsHigh = self._contentSize.height = locElement.height; //dispatch load event to listener. self.dispatchEvent("load"); diff --git a/cocos2d/core/utils/CCProfiler.js b/cocos2d/core/utils/CCProfiler.js index 923f1acff8..5d314f629d 100644 --- a/cocos2d/core/utils/CCProfiler.js +++ b/cocos2d/core/utils/CCProfiler.js @@ -21,7 +21,7 @@ cc.profiler = (function () { _fps.style.bottom = cc.DIRECTOR_STATS_POSITION.y + '0px'; _fps.style.left = cc.DIRECTOR_STATS_POSITION.x + 'px'; _fps.style.width = '45px'; - _fps.style.height = '60px'; + _fps.style.height = '80px'; var labels = [_drawsLabel, _SPFLabel, _FPSLabel]; for (var i = 0; i < 3; ++i) { @@ -85,8 +85,9 @@ cc.profiler = (function () { } if (_showFPS) { + var mode = cc._renderType === cc.game.RENDER_TYPE_CANVAS ? "\n canvas" : "\n webgl"; _SPFLabel.innerText = _lastSPF.toFixed(3); - _FPSLabel.innerText = _frameRate.toFixed(1); + _FPSLabel.innerText = _frameRate.toFixed(1).toString() + mode; _drawsLabel.innerText = (0 | cc.g_NumberOfDraws).toString(); } } diff --git a/cocos2d/menus/CCMenu.js b/cocos2d/menus/CCMenu.js index 6df7b838eb..e3edd737ee 100644 --- a/cocos2d/menus/CCMenu.js +++ b/cocos2d/menus/CCMenu.js @@ -84,19 +84,14 @@ cc.Menu = cc.Layer.extend(/** @lends cc.Menu# */{ onTouchCancelled: this._onTouchCancelled }); - if ((arguments.length > 0) && (arguments[arguments.length - 1] == null)) - cc.log("parameters should not be ending with null in Javascript"); - var argc = arguments.length, items; - if (argc === 0) { + if (menuItems instanceof Array) { + items = menuItems; + } + else if (argc === 0) { items = []; - } else if (argc === 1) { - if (menuItems instanceof Array) { - items = menuItems; - } - else items = [menuItems]; } - else if (argc > 1) { + else if (argc > 0) { items = []; for (var i = 0; i < argc; i++) { if (arguments[i]) diff --git a/extensions/cocostudio/armature/CCArmature.js b/extensions/cocostudio/armature/CCArmature.js index 6cd69a89d5..020c83f2b5 100644 --- a/extensions/cocostudio/armature/CCArmature.js +++ b/extensions/cocostudio/armature/CCArmature.js @@ -79,7 +79,6 @@ ccs.Armature = ccs.Node.extend(/** @lends ccs.Armature# */{ * @return {Boolean} */ init: function (name, parentBone) { - cc.Node.prototype.init.call(this); if (parentBone) this._parentBone = parentBone; this.removeAllChildren(); From 56710d469bbc33d3ad0966564a315e2f468df58c Mon Sep 17 00:00:00 2001 From: pandamicro Date: Thu, 8 Dec 2016 18:01:32 +0800 Subject: [PATCH 22/42] Async loading project.json file, avoid chrome warning --- CCBoot.js | 73 +++++++++++++++++++++++++++++-------------------------- 1 file changed, 39 insertions(+), 34 deletions(-) diff --git a/CCBoot.js b/CCBoot.js index 260854524a..8a2e56080c 100644 --- a/CCBoot.js +++ b/CCBoot.js @@ -2262,6 +2262,7 @@ cc.game = /** @lends cc.game# */{ // states _paused: true,//whether the game is paused + _configLoaded: false,//whether config loaded _prepareCalled: false,//whether the prepare function has been called _prepared: false,//whether the engine has prepared _rendererInitialized: false, @@ -2397,7 +2398,13 @@ cc.game = /** @lends cc.game# */{ config = self.config, CONFIG_KEY = self.CONFIG_KEY; - this._loadConfig(); + // Config loaded + if (!this._configLoaded) { + this._loadConfig(function () { + self.prepare(cb); + }); + return; + } // Already prepared if (this._prepared) { @@ -2553,46 +2560,42 @@ cc.game = /** @lends cc.game# */{ }, // @Game loading section - _loadConfig: function () { + _loadConfig: function (cb) { // Load config - // Already loaded - if (this.config) { - this._initConfig(this.config); - return; - } - // Load from document.ccConfig - if (document["ccConfig"]) { - this._initConfig(document["ccConfig"]); + var config = this.config || document["ccConfig"]; + // Already loaded or Load from document.ccConfig + if (config) { + this._initConfig(config); + cb && cb(); } // Load from project.json else { - var data = {}; - try { - var cocos_script = document.getElementsByTagName('script'); - for(var i = 0; i < cocos_script.length; i++){ - var _t = cocos_script[i].getAttribute('cocos'); - if(_t === '' || _t) { - break; - } - } - var _src, txt, _resPath; - if(i < cocos_script.length){ - _src = cocos_script[i].src; - if(_src){ - _resPath = /(.*)\//.exec(_src)[0]; - cc.loader.resPath = _resPath; - _src = cc.path.join(_resPath, 'project.json'); - } - txt = cc.loader._loadTxtSync(_src); + var cocos_script = document.getElementsByTagName('script'); + for (var i = 0; i < cocos_script.length; i++) { + var _t = cocos_script[i].getAttribute('cocos'); + if (_t === '' || _t) { + break; } - if(!txt){ - txt = cc.loader._loadTxtSync("project.json"); + } + var self = this; + var loaded = function (err, txt) { + var data = JSON.parse(txt); + self._initConfig(data); + cb && cb(); + }; + var _src, txt, _resPath; + if (i < cocos_script.length) { + _src = cocos_script[i].src; + if (_src) { + _resPath = /(.*)\//.exec(_src)[0]; + cc.loader.resPath = _resPath; + _src = cc.path.join(_resPath, 'project.json'); } - data = JSON.parse(txt); - } catch (e) { - cc.log("Failed to read or parse project.json"); + cc.loader.loadTxt(_src, loaded); + } + if (!txt) { + cc.loader.loadTxt("project.json", loaded); } - this._initConfig(data); } }, @@ -2605,6 +2608,7 @@ cc.game = /** @lends cc.game# */{ config[CONFIG_KEY.engineDir] = config[CONFIG_KEY.engineDir] || "frameworks/cocos2d-html5"; if (config[CONFIG_KEY.debugMode] == null) config[CONFIG_KEY.debugMode] = 0; + config[CONFIG_KEY.exposeClassName] = !!config[CONFIG_KEY.exposeClassName]; config[CONFIG_KEY.frameRate] = config[CONFIG_KEY.frameRate] || 60; if (config[CONFIG_KEY.renderMode] == null) config[CONFIG_KEY.renderMode] = 0; @@ -2615,6 +2619,7 @@ cc.game = /** @lends cc.game# */{ if (modules && modules.indexOf("core") < 0) modules.splice(0, 0, "core"); modules && (config[CONFIG_KEY.modules] = modules); this.config = config; + this._configLoaded = true; }, _initRenderer: function (width, height) { From c2bce43dcfbbf6e5d82331a23ac2f3c5fee35a8c Mon Sep 17 00:00:00 2001 From: pandamicro Date: Thu, 8 Dec 2016 18:14:55 +0800 Subject: [PATCH 23/42] Improve Class construction performance --- CCBoot.js | 18 +- cocos2d/core/platform/CCClass.js | 295 ++++++++++++++++--------------- 2 files changed, 167 insertions(+), 146 deletions(-) diff --git a/CCBoot.js b/CCBoot.js index 8a2e56080c..00ba24bee4 100644 --- a/CCBoot.js +++ b/CCBoot.js @@ -2238,14 +2238,15 @@ cc.game = /** @lends cc.game# */{ * @constant * @type {Object} * - * @prop {String} engineDir - In debug mode, if you use the whole engine to develop your game, you should specify its relative path with "engineDir". - * @prop {String} modules - Defines which modules you will need in your game, it's useful only on web - * @prop {String} debugMode - Debug mode, see DEBUG_MODE_XXX constant definitions. - * @prop {String} showFPS - Left bottom corner fps information will show when "showFPS" equals true, otherwise it will be hide. - * @prop {String} frameRate - Sets the wanted frame rate for your game, but the real fps depends on your game implementation and the running environment. - * @prop {String} id - Sets the id of your canvas element on the web page, it's useful only on web. - * @prop {String} renderMode - Sets the renderer type, only useful on web, 0: Automatic, 1: Canvas, 2: WebGL - * @prop {String} jsList - Sets the list of js files in your game. + * @prop {String} engineDir - In debug mode, if you use the whole engine to develop your game, you should specify its relative path with "engineDir". + * @prop {String} modules - Defines which modules you will need in your game, it's useful only on web + * @prop {String} debugMode - Debug mode, see DEBUG_MODE_XXX constant definitions. + * @prop {String} exposeClassName - Expose class name to chrome debug tools + * @prop {String} showFPS - Left bottom corner fps information will show when "showFPS" equals true, otherwise it will be hide. + * @prop {String} frameRate - Sets the wanted frame rate for your game, but the real fps depends on your game implementation and the running environment. + * @prop {String} id - Sets the id of your canvas element on the web page, it's useful only on web. + * @prop {String} renderMode - Sets the renderer type, only useful on web, 0: Automatic, 1: Canvas, 2: WebGL + * @prop {String} jsList - Sets the list of js files in your game. */ CONFIG_KEY: { width: "width", @@ -2253,6 +2254,7 @@ cc.game = /** @lends cc.game# */{ engineDir: "engineDir", modules: "modules", debugMode: "debugMode", + exposeClassName: "exposeClassName", showFPS: "showFPS", frameRate: "frameRate", id: "id", diff --git a/cocos2d/core/platform/CCClass.js b/cocos2d/core/platform/CCClass.js index e5d5ca1b81..1916135594 100644 --- a/cocos2d/core/platform/CCClass.js +++ b/cocos2d/core/platform/CCClass.js @@ -26,6 +26,116 @@ var cc = cc || {}; +/** + * Common getter setter configuration function + * @function + * @param {Object} proto A class prototype or an object to config
+ * @param {String} prop Property name + * @param {function} getter Getter function for the property + * @param {function} setter Setter function for the property + * @param {String} getterName Name of getter function for the property + * @param {String} setterName Name of setter function for the property + */ +cc.defineGetterSetter = function (proto, prop, getter, setter, getterName, setterName) { + if (proto.__defineGetter__) { + getter && proto.__defineGetter__(prop, getter); + setter && proto.__defineSetter__(prop, setter); + } else if (Object.defineProperty) { + var desc = {enumerable: false, configurable: true}; + getter && (desc.get = getter); + setter && (desc.set = setter); + Object.defineProperty(proto, prop, desc); + } else { + throw new Error("browser does not support getters"); + } + + if (!getterName && !setterName) { + // Lookup getter/setter function + var hasGetter = (getter != null), hasSetter = (setter != undefined), props = Object.getOwnPropertyNames(proto); + for (var i = 0; i < props.length; i++) { + var name = props[i]; + + if ((proto.__lookupGetter__ ? proto.__lookupGetter__(name) + : Object.getOwnPropertyDescriptor(proto, name)) + || typeof proto[name] !== "function") + continue; + + var func = proto[name]; + if (hasGetter && func === getter) { + getterName = name; + if (!hasSetter || setterName) break; + } + if (hasSetter && func === setter) { + setterName = name; + if (!hasGetter || getterName) break; + } + } + } + + // Found getter/setter + var ctor = proto.constructor; + if (getterName) { + if (!ctor.__getters__) { + ctor.__getters__ = {}; + } + ctor.__getters__[getterName] = prop; + } + if (setterName) { + if (!ctor.__setters__) { + ctor.__setters__ = {}; + } + ctor.__setters__[setterName] = prop; + } +}; + +/** + * Create a new object and copy all properties in an exist object to the new object + * @function + * @param {object|Array} obj The source object + * @return {Array|object} The created object + */ +cc.clone = function (obj) { + // Cloning is better if the new object is having the same prototype chain + // as the copied obj (or otherwise, the cloned object is certainly going to + // have a different hidden class). Play with C1/C2 of the + // PerformanceVirtualMachineTests suite to see how this makes an impact + // under extreme conditions. + // + // Object.create(Object.getPrototypeOf(obj)) doesn't work well because the + // prototype lacks a link to the constructor (Carakan, V8) so the new + // object wouldn't have the hidden class that's associated with the + // constructor (also, for whatever reasons, utilizing + // Object.create(Object.getPrototypeOf(obj)) + Object.defineProperty is even + // slower than the original in V8). Therefore, we call the constructor, but + // there is a big caveat - it is possible that the this.init() in the + // constructor would throw with no argument. It is also possible that a + // derived class forgets to set "constructor" on the prototype. We ignore + // these possibities for and the ultimate solution is a standardized + // Object.clone(). + var newObj = (obj.constructor) ? new obj.constructor : {}; + + // Assuming that the constuctor above initialized all properies on obj, the + // following keyed assignments won't turn newObj into dictionary mode + // because they're not *appending new properties* but *assigning existing + // ones* (note that appending indexed properties is another story). See + // CCClass.js for a link to the devils when the assumption fails. + for (var key in obj) { + var copy = obj[key]; + // Beware that typeof null == "object" ! + if (((typeof copy) === "object") && copy && !(copy instanceof cc.Node) && !(copy instanceof HTMLElement)) { + newObj[key] = cc.clone(copy); + } else { + newObj[key] = copy; + } + } + return newObj; +}; + +cc.inject = function (srcPrototype, destPrototype) { + for (var key in srcPrototype) + destPrototype[key] = srcPrototype[key]; +}; + /** * @namespace * @name ClassManager @@ -71,43 +181,63 @@ var ClassManager = { // don't run the init constructor) var prototype = Object.create(_super); - var classId = ClassManager.getNewID(); - ClassManager[classId] = _super; // Copy the properties over onto the new prototype. We make function // properties non-eumerable as this makes typeof === 'function' check // unnecessary in the for...in loop used 1) for generating Class() // 2) for cc.clone and perhaps more. It is also required to make // these function properties cacheable in Carakan. - var desc = { writable: true, enumerable: false, configurable: true }; - - prototype.__instanceId = null; - - // The dummy Class constructor - function Class() { - this.__instanceId = ClassManager.getNewInstanceId(); - // All construction is actually done in the init method - if (this.ctor) - this.ctor.apply(this, arguments); - } + var desc = {writable: true, enumerable: false, configurable: true}; + + // The dummy Class constructor + var Class; + if (cc.game.config[cc.game.CONFIG_KEY.exposeClassName]) { + var constructor = "(function " + (props._className || "Class") + " (arg0, arg1, arg2, arg3, arg4, arg5) {\n"; + constructor += " this.__instanceId = ClassManager.getNewInstanceId();\n"; + constructor += " if (this.ctor) {\n"; + constructor += " switch (arguments.length) {\n"; + constructor += " case 0: this.ctor(); break;\n"; + constructor += " case 1: this.ctor(arg0); break;\n"; + constructor += " case 3: this.ctor(arg0, arg1, arg2); break;\n"; + constructor += " case 4: this.ctor(arg0, arg1, arg2, arg3); break;\n"; + constructor += " case 5: this.ctor(arg0, arg1, arg2, arg3, arg4); break;\n"; + constructor += " default: this.ctor.apply(this, arguments);\n"; + constructor += " }\n"; + constructor += " }\n"; + constructor += "})"; + Class = eval(constructor); + } + else { + Class = function (arg0, arg1, arg2, arg3, arg4) { + this.__instanceId = ClassManager.getNewInstanceId(); + if (this.ctor) { + switch (arguments.length) { + case 0: this.ctor(); break; + case 1: this.ctor(arg0); break; + case 2: this.ctor(arg0, arg1); break; + case 3: this.ctor(arg0, arg1, arg2); break; + case 4: this.ctor(arg0, arg1, arg2, arg3); break; + case 5: this.ctor(arg0, arg1, arg2, arg3, arg4); break; + default: this.ctor.apply(this, arguments); + } + } + }; + } - Class.id = classId; - // desc = { writable: true, enumerable: false, configurable: true, - // value: XXX }; Again, we make this non-enumerable. - desc.value = classId; - Object.defineProperty(prototype, '__pid', desc); + desc.value = ClassManager.getNewID(); + Object.defineProperty(prototype, '__pid', desc); - // Populate our constructed prototype object - Class.prototype = prototype; + // Populate our constructed prototype object + Class.prototype = prototype; - // Enforce the constructor to be what we expect - desc.value = Class; - Object.defineProperty(Class.prototype, 'constructor', desc); + // Enforce the constructor to be what we expect + desc.value = Class; + Object.defineProperty(prototype, 'constructor', desc); - // Copy getter/setter - this.__getters__ && (Class.__getters__ = cc.clone(this.__getters__)); - this.__setters__ && (Class.__setters__ = cc.clone(this.__setters__)); + // Copy getter/setter + this.__getters__ && (Class.__getters__ = cc.clone(this.__getters__)); + this.__setters__ && (Class.__setters__ = cc.clone(this.__setters__)); - for(var idx = 0, li = arguments.length; idx < li; ++idx) { + for (var idx = 0, li = arguments.length; idx < li; ++idx) { var prop = arguments[idx]; for (var name in prop) { var isFunc = (typeof prop[name] === "function"); @@ -179,114 +309,3 @@ var ClassManager = { }; })(); -/** - * Common getter setter configuration function - * @function - * @param {Object} proto A class prototype or an object to config
- * @param {String} prop Property name - * @param {function} getter Getter function for the property - * @param {function} setter Setter function for the property - * @param {String} getterName Name of getter function for the property - * @param {String} setterName Name of setter function for the property - */ -cc.defineGetterSetter = function (proto, prop, getter, setter, getterName, setterName){ - if (proto.__defineGetter__) { - getter && proto.__defineGetter__(prop, getter); - setter && proto.__defineSetter__(prop, setter); - } else if (Object.defineProperty) { - var desc = { enumerable: false, configurable: true }; - getter && (desc.get = getter); - setter && (desc.set = setter); - Object.defineProperty(proto, prop, desc); - } else { - throw new Error("browser does not support getters"); - } - - if(!getterName && !setterName) { - // Lookup getter/setter function - var hasGetter = (getter != null), hasSetter = (setter != undefined), props = Object.getOwnPropertyNames(proto); - for (var i = 0; i < props.length; i++) { - var name = props[i]; - - if( (proto.__lookupGetter__ ? proto.__lookupGetter__(name) - : Object.getOwnPropertyDescriptor(proto, name)) - || typeof proto[name] !== "function" ) - continue; - - var func = proto[name]; - if (hasGetter && func === getter) { - getterName = name; - if(!hasSetter || setterName) break; - } - if (hasSetter && func === setter) { - setterName = name; - if(!hasGetter || getterName) break; - } - } - } - - // Found getter/setter - var ctor = proto.constructor; - if (getterName) { - if (!ctor.__getters__) { - ctor.__getters__ = {}; - } - ctor.__getters__[getterName] = prop; - } - if (setterName) { - if (!ctor.__setters__) { - ctor.__setters__ = {}; - } - ctor.__setters__[setterName] = prop; - } -}; - -/** - * Create a new object and copy all properties in an exist object to the new object - * @function - * @param {object|Array} obj The source object - * @return {Array|object} The created object - */ -cc.clone = function (obj) { - // Cloning is better if the new object is having the same prototype chain - // as the copied obj (or otherwise, the cloned object is certainly going to - // have a different hidden class). Play with C1/C2 of the - // PerformanceVirtualMachineTests suite to see how this makes an impact - // under extreme conditions. - // - // Object.create(Object.getPrototypeOf(obj)) doesn't work well because the - // prototype lacks a link to the constructor (Carakan, V8) so the new - // object wouldn't have the hidden class that's associated with the - // constructor (also, for whatever reasons, utilizing - // Object.create(Object.getPrototypeOf(obj)) + Object.defineProperty is even - // slower than the original in V8). Therefore, we call the constructor, but - // there is a big caveat - it is possible that the this.init() in the - // constructor would throw with no argument. It is also possible that a - // derived class forgets to set "constructor" on the prototype. We ignore - // these possibities for and the ultimate solution is a standardized - // Object.clone(). - var newObj = (obj.constructor) ? new obj.constructor : {}; - - // Assuming that the constuctor above initialized all properies on obj, the - // following keyed assignments won't turn newObj into dictionary mode - // because they're not *appending new properties* but *assigning existing - // ones* (note that appending indexed properties is another story). See - // CCClass.js for a link to the devils when the assumption fails. - for (var key in obj) { - var copy = obj[key]; - // Beware that typeof null == "object" ! - if (((typeof copy) === "object") && copy && - !(copy instanceof cc.Node) && !(copy instanceof HTMLElement)) { - newObj[key] = cc.clone(copy); - } else { - newObj[key] = copy; - } - } - return newObj; -}; - -cc.inject = function(srcPrototype, destPrototype){ - for(var key in srcPrototype) - destPrototype[key] = srcPrototype[key]; -}; - From bb0c1716254dce87ab0fe7060f84c5571eb96415 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Thu, 8 Dec 2016 18:21:46 +0800 Subject: [PATCH 24/42] Reduce cc.Color memory footprint --- cocos2d/core/layers/CCLayerWebGLRenderCmd.js | 16 +- cocos2d/core/platform/CCTypes.js | 252 ++++++++++++++++-- .../core/platform/CCTypesPropertyDefine.js | 165 ------------ cocos2d/core/platform/CCTypesWebGL.js | 130 --------- moduleConfig.json | 8 +- 5 files changed, 247 insertions(+), 324 deletions(-) delete mode 100644 cocos2d/core/platform/CCTypesPropertyDefine.js delete mode 100644 cocos2d/core/platform/CCTypesWebGL.js diff --git a/cocos2d/core/layers/CCLayerWebGLRenderCmd.js b/cocos2d/core/layers/CCLayerWebGLRenderCmd.js index a80ed27b5a..adfa4ea287 100644 --- a/cocos2d/core/layers/CCLayerWebGLRenderCmd.js +++ b/cocos2d/core/layers/CCLayerWebGLRenderCmd.js @@ -66,15 +66,15 @@ _t._squareColorsAB = new ArrayBuffer(16); var locSquareVerticesAB = _t._squareVerticesAB, locSquareColorsAB = _t._squareColorsAB; - var locVertex3FLen = cc.Vertex3F.BYTES_PER_ELEMENT, locColorLen = cc.Color.BYTES_PER_ELEMENT; + var locVertex3FLen = cc.Vertex3F.BYTES_PER_ELEMENT, locColorLen = cc._WebGLColor.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._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)]; _t._verticesFloat32Buffer = cc._renderContext.createBuffer(); _t._colorsUint8Buffer = cc._renderContext.createBuffer(); @@ -269,9 +269,9 @@ 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 locColorLen = cc._WebGLColor.BYTES_PER_ELEMENT; + for (i = 0; i < verticesLen; i++) { + locColors.push(new cc._WebGLColor(0, 0, 0, 255, locSquareColorsAB, locColorLen * i)); } } diff --git a/cocos2d/core/platform/CCTypes.js b/cocos2d/core/platform/CCTypes.js index 2e54cfe2d4..84bc1ab3fb 100644 --- a/cocos2d/core/platform/CCTypes.js +++ b/cocos2d/core/platform/CCTypes.js @@ -34,12 +34,55 @@ * @see cc.color */ cc.Color = function (r, g, b, a) { - this.r = r || 0; - this.g = g || 0; - this.b = b || 0; - this.a = (a == null) ? 255 : a; + r = r || 0; + g = g || 0; + b = b || 0; + a = a || 0; + this._val = ((r << 24) >>> 0) + (g << 16) + (b << 8) + a; }; +var _p = cc.Color.prototype; +_p._getR = function () { + return (this._val & 0xff000000) >>> 24; +}; +_p._setR = function (value) { + this._val = (this._val & 0x00ffffff) | ((value << 24) >>> 0); +}; +_p._getG = function () { + return (this._val & 0x00ff0000) >> 16; +}; +_p._setG = function (value) { + this._val = (this._val & 0xff00ffff) | (value << 16); +}; +_p._getB = function () { + return (this._val & 0x0000ff00) >> 8; +}; +_p._setB = function (value) { + this._val = (this._val & 0xffff00ff) | (value << 8); +}; + +_p._getA = function () { + return this._val & 0x000000ff; +}; + +_p.setA = function (value) { + this._val = (this._val & 0xffffff00) | value; +}; + + +/** @expose */ +_p.r; +cc.defineGetterSetter(_p, "r", _p._getR, _p._setR); +/** @expose */ +_p.g; +cc.defineGetterSetter(_p, "g", _p._getG, _p._setG); +/** @expose */ +_p.b; +cc.defineGetterSetter(_p, "b", _p._getB, _p._setB); +/** @expose */ +_p.a; +cc.defineGetterSetter(_p, "a", _p._getA, _p._setA); + /** * Generate a color object based on multiple forms of parameters * @example @@ -354,10 +397,10 @@ cc.V3F_C4B_T2F = function (vertices, colors, texCoords, arrayBuffer, offset) { new cc.Vertex3F(0, 0, 0, locArrayBuffer, locOffset); locOffset += cc.Vertex3F.BYTES_PER_ELEMENT; - this._colors = colors ? new cc.Color(colors.r, colors.g, colors.b, colors.a, locArrayBuffer, locOffset) : - new cc.Color(0, 0, 0, 0, locArrayBuffer, locOffset); + 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.Color.BYTES_PER_ELEMENT; + 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); }; @@ -570,9 +613,9 @@ cc.V2F_C4B_T2F = function (vertices, colors, texCoords, arrayBuffer, offset) { this._vertices = vertices ? new cc.Vertex2F(vertices.x, vertices.y, locArrayBuffer, locOffset) : new cc.Vertex2F(0, 0, locArrayBuffer, locOffset); locOffset += cc.Vertex2F.BYTES_PER_ELEMENT; - this._colors = colors ? cc.color(colors.r, colors.g, colors.b, colors.a, locArrayBuffer, locOffset) : - cc.color(0, 0, 0, 0, locArrayBuffer, locOffset); - locOffset += cc.Color.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); }; @@ -753,7 +796,7 @@ cc.hexToColor = function (hex) { var r = c >> 16; var g = (c >> 8) % 256; var b = c % 256; - return cc.color(r, g, b); + return new cc.Color(r, g, b); }; /** @@ -950,9 +993,188 @@ cc.FontDefinition.prototype._getCanvasFontStr = function () { }; cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () { - if (cc._renderType === cc.game.RENDER_TYPE_CANVAS) { - cc.assert(cc.isFunction(cc._tmp.PrototypeColor), cc._LogInfos.MissingFile, "CCTypesPropertyDefine.js"); - cc._tmp.PrototypeColor(); - delete cc._tmp.PrototypeColor; + if (cc._renderType === cc.game.RENDER_TYPE_WEBGL) { + //redefine Color + 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; + this._view = new Uint8Array(locArrayBuffer, locOffset, 4); + + this._view[0] = r || 0; + this._view[1] = g || 0; + this._view[2] = b || 0; + this._view[3] = (a == null) ? 255 : a; + + if (a === undefined) + this.a_undefined = true; + }; + cc._WebGLColor.BYTES_PER_ELEMENT = 4; + _p = cc._WebGLColor.prototype; + _p._getR = function () { + return this._view[0]; + }; + _p._setR = function (value) { + this._view[0] = value < 0 ? 0 : value; + }; + _p._getG = function () { + return this._view[1]; + }; + _p._setG = function (value) { + this._view[1] = value < 0 ? 0 : value; + }; + _p._getB = function () { + return this._view[2]; + }; + _p._setB = function (value) { + this._view[2] = value < 0 ? 0 : value; + }; + _p._getA = function () { + return this._view[3]; + }; + _p._setA = function (value) { + this._view[3] = value < 0 ? 0 : value; + }; + cc.defineGetterSetter(_p, "r", _p._getR, _p._setR); + cc.defineGetterSetter(_p, "g", _p._getG, _p._setG); + cc.defineGetterSetter(_p, "b", _p._getB, _p._setB); + cc.defineGetterSetter(_p, "a", _p._getA, _p._setA); } }); + +_p = cc.color; +/** + * White color (255, 255, 255, 255) + * @returns {cc.Color} + * @private + */ +_p._getWhite = function () { + return cc.color(255, 255, 255); +}; + +/** + * Yellow color (255, 255, 0, 255) + * @returns {cc.Color} + * @private + */ +_p._getYellow = function () { + return cc.color(255, 255, 0); +}; + +/** + * Blue color (0, 0, 255, 255) + * @type {cc.Color} + * @private + */ +_p._getBlue = function () { + return cc.color(0, 0, 255); +}; + +/** + * Green Color (0, 255, 0, 255) + * @type {cc.Color} + * @private + */ +_p._getGreen = function () { + return cc.color(0, 255, 0); +}; + +/** + * Red Color (255, 0, 0, 255) + * @type {cc.Color} + * @private + */ +_p._getRed = function () { + return cc.color(255, 0, 0); +}; + +/** + * Magenta Color (255, 0, 255, 255) + * @type {cc.Color} + * @private + */ +_p._getMagenta = function () { + return cc.color(255, 0, 255); +}; + +/** + * Black Color (0, 0, 0, 255) + * @type {cc.Color} + * @private + */ +_p._getBlack = function () { + return cc.color(0, 0, 0); +}; + +/** + * Orange Color (255, 127, 0, 255) + * @type {_p} + * @private + */ +_p._getOrange = function () { + return cc.color(255, 127, 0); +}; + +/** + * Gray Color (166, 166, 166, 255) + * @type {_p} + * @private + */ +_p._getGray = function () { + return cc.color(166, 166, 166); +}; + +/** @expose */ +_p.WHITE; +cc.defineGetterSetter(_p, "WHITE", _p._getWhite); +/** @expose */ +_p.YELLOW; +cc.defineGetterSetter(_p, "YELLOW", _p._getYellow); +/** @expose */ +_p.BLUE; +cc.defineGetterSetter(_p, "BLUE", _p._getBlue); +/** @expose */ +_p.GREEN; +cc.defineGetterSetter(_p, "GREEN", _p._getGreen); +/** @expose */ +_p.RED; +cc.defineGetterSetter(_p, "RED", _p._getRed); +/** @expose */ +_p.MAGENTA; +cc.defineGetterSetter(_p, "MAGENTA", _p._getMagenta); +/** @expose */ +_p.BLACK; +cc.defineGetterSetter(_p, "BLACK", _p._getBlack); +/** @expose */ +_p.ORANGE; +cc.defineGetterSetter(_p, "ORANGE", _p._getOrange); +/** @expose */ +_p.GRAY; +cc.defineGetterSetter(_p, "GRAY", _p._getGray); + +cc.BlendFunc._disable = function(){ + return new cc.BlendFunc(cc.ONE, cc.ZERO); +}; +cc.BlendFunc._alphaPremultiplied = function(){ + return new cc.BlendFunc(cc.ONE, cc.ONE_MINUS_SRC_ALPHA); +}; +cc.BlendFunc._alphaNonPremultiplied = function(){ + return new cc.BlendFunc(cc.SRC_ALPHA, cc.ONE_MINUS_SRC_ALPHA); +}; +cc.BlendFunc._additive = function(){ + return new cc.BlendFunc(cc.SRC_ALPHA, cc.ONE); +}; + +/** @expose */ +cc.BlendFunc.DISABLE; +cc.defineGetterSetter(cc.BlendFunc, "DISABLE", cc.BlendFunc._disable); +/** @expose */ +cc.BlendFunc.ALPHA_PREMULTIPLIED; +cc.defineGetterSetter(cc.BlendFunc, "ALPHA_PREMULTIPLIED", cc.BlendFunc._alphaPremultiplied); +/** @expose */ +cc.BlendFunc.ALPHA_NON_PREMULTIPLIED; +cc.defineGetterSetter(cc.BlendFunc, "ALPHA_NON_PREMULTIPLIED", cc.BlendFunc._alphaNonPremultiplied); +/** @expose */ +cc.BlendFunc.ADDITIVE; +cc.defineGetterSetter(cc.BlendFunc, "ADDITIVE", cc.BlendFunc._additive); diff --git a/cocos2d/core/platform/CCTypesPropertyDefine.js b/cocos2d/core/platform/CCTypesPropertyDefine.js deleted file mode 100644 index f0be5ac1de..0000000000 --- a/cocos2d/core/platform/CCTypesPropertyDefine.js +++ /dev/null @@ -1,165 +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. - ****************************************************************************/ - -cc._tmp.PrototypeColor = function () { - var _p = cc.color; - /** - * White color (255, 255, 255, 255) - * @returns {cc.Color} - * @private - */ - _p._getWhite = function () { - return _p(255, 255, 255); - }; - - /** - * Yellow color (255, 255, 0, 255) - * @returns {cc.Color} - * @private - */ - _p._getYellow = function () { - return _p(255, 255, 0); - }; - - /** - * Blue color (0, 0, 255, 255) - * @type {cc.Color} - * @private - */ - _p._getBlue = function () { - return _p(0, 0, 255); - }; - - /** - * Green Color (0, 255, 0, 255) - * @type {cc.Color} - * @private - */ - _p._getGreen = function () { - return _p(0, 255, 0); - }; - - /** - * Red Color (255, 0, 0, 255) - * @type {cc.Color} - * @private - */ - _p._getRed = function () { - return _p(255, 0, 0); - }; - - /** - * Magenta Color (255, 0, 255, 255) - * @type {cc.Color} - * @private - */ - _p._getMagenta = function () { - return _p(255, 0, 255); - }; - - /** - * Black Color (0, 0, 0, 255) - * @type {cc.Color} - * @private - */ - _p._getBlack = function () { - return _p(0, 0, 0); - }; - - /** - * Orange Color (255, 127, 0, 255) - * @type {_p} - * @private - */ - _p._getOrange = function () { - return _p(255, 127, 0); - }; - - /** - * Gray Color (166, 166, 166, 255) - * @type {_p} - * @private - */ - _p._getGray = function () { - return _p(166, 166, 166); - }; - - /** @expose */ - _p.WHITE; - cc.defineGetterSetter(_p, "WHITE", _p._getWhite); - /** @expose */ - _p.YELLOW; - cc.defineGetterSetter(_p, "YELLOW", _p._getYellow); - /** @expose */ - _p.BLUE; - cc.defineGetterSetter(_p, "BLUE", _p._getBlue); - /** @expose */ - _p.GREEN; - cc.defineGetterSetter(_p, "GREEN", _p._getGreen); - /** @expose */ - _p.RED; - cc.defineGetterSetter(_p, "RED", _p._getRed); - /** @expose */ - _p.MAGENTA; - cc.defineGetterSetter(_p, "MAGENTA", _p._getMagenta); - /** @expose */ - _p.BLACK; - cc.defineGetterSetter(_p, "BLACK", _p._getBlack); - /** @expose */ - _p.ORANGE; - cc.defineGetterSetter(_p, "ORANGE", _p._getOrange); - /** @expose */ - _p.GRAY; - cc.defineGetterSetter(_p, "GRAY", _p._getGray); - - cc.BlendFunc._disable = function(){ - return new cc.BlendFunc(cc.ONE, cc.ZERO); - }; - cc.BlendFunc._alphaPremultiplied = function(){ - return new cc.BlendFunc(cc.ONE, cc.ONE_MINUS_SRC_ALPHA); - }; - cc.BlendFunc._alphaNonPremultiplied = function(){ - return new cc.BlendFunc(cc.SRC_ALPHA, cc.ONE_MINUS_SRC_ALPHA); - }; - cc.BlendFunc._additive = function(){ - return new cc.BlendFunc(cc.SRC_ALPHA, cc.ONE); - }; - - /** @expose */ - cc.BlendFunc.DISABLE; - cc.defineGetterSetter(cc.BlendFunc, "DISABLE", cc.BlendFunc._disable); - /** @expose */ - cc.BlendFunc.ALPHA_PREMULTIPLIED; - cc.defineGetterSetter(cc.BlendFunc, "ALPHA_PREMULTIPLIED", cc.BlendFunc._alphaPremultiplied); - /** @expose */ - cc.BlendFunc.ALPHA_NON_PREMULTIPLIED; - cc.defineGetterSetter(cc.BlendFunc, "ALPHA_NON_PREMULTIPLIED", cc.BlendFunc._alphaNonPremultiplied); - /** @expose */ - cc.BlendFunc.ADDITIVE; - cc.defineGetterSetter(cc.BlendFunc, "ADDITIVE", cc.BlendFunc._additive); -}; - - diff --git a/cocos2d/core/platform/CCTypesWebGL.js b/cocos2d/core/platform/CCTypesWebGL.js deleted file mode 100644 index bbee8dd1ff..0000000000 --- a/cocos2d/core/platform/CCTypesWebGL.js +++ /dev/null @@ -1,130 +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. - ****************************************************************************/ - -var cc = cc || {}; -cc._tmp = cc._tmp || {}; - -cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () { - if (cc._renderType !== cc.game.RENDER_TYPE_WEBGL) { - return; - } - - //redefine some types with ArrayBuffer for WebGL - /** - * @class cc.Color - * @param {Number} r - * @param {Number}g - * @param {Number} b - * @param {Number} a - * @param {Array} arrayBuffer - * @param {Number} offset - * @returns {cc.Color} - */ - cc.color = function (r, g, b, a, arrayBuffer, offset) { - if (r === undefined) - return new cc.Color(0, 0, 0, 255, arrayBuffer, offset); - if (cc.isString(r)) { - var color = cc.hexToColor(r); - return new cc.Color(color.r, color.g, color.b, color.a); - } - if (cc.isObject(r)) - return new cc.Color(r.r, r.g, r.b, r.a, r.arrayBuffer, r.offset); - return new cc.Color(r, g, b, a, arrayBuffer, offset); - }; - //redefine cc.Color - /** - * @class cc.Color - * @param {Number} r - * @param {Number}g - * @param {Number} b - * @param {Number} a - * @param {Array} arrayBuffer - * @param {Number} offset - * @constructor - */ - cc.Color = function (r, g, b, a, arrayBuffer, offset) { - this._arrayBuffer = arrayBuffer || new ArrayBuffer(cc.Color.BYTES_PER_ELEMENT); - this._offset = offset || 0; - - var locArrayBuffer = this._arrayBuffer, locOffset = this._offset; - this._view = new Uint8Array(locArrayBuffer, locOffset, 4); - - this._view[0] = r || 0; - this._view[1] = g || 0; - this._view[2] = b || 0; - this._view[3] = (a == null) ? 255 : a; - - if (a === undefined) - this.a_undefined = true; - }; - /** - * @constant - * @type {number} - */ - cc.Color.BYTES_PER_ELEMENT = 4; - var _p = cc.Color.prototype; - _p._getR = function () { - return this._view[0]; - }; - _p._setR = function (value) { - this._view[0] = value < 0 ? 0 : value; - }; - _p._getG = function () { - return this._view[1]; - }; - _p._setG = function (value) { - this._view[1] = value < 0 ? 0 : value; - }; - _p._getB = function () { - return this._view[2]; - }; - _p._setB = function (value) { - this._view[2] = value < 0 ? 0 : value; - }; - _p._getA = function () { - return this._view[3]; - }; - _p._setA = function (value) { - this._view[3] = value < 0 ? 0 : value; - }; - /** @expose */ - _p.r; - cc.defineGetterSetter(_p, "r", _p._getR, _p._setR); - /** @expose */ - _p.g; - cc.defineGetterSetter(_p, "g", _p._getG, _p._setG); - /** @expose */ - _p.b; - cc.defineGetterSetter(_p, "b", _p._getB, _p._setB); - /** @expose */ - _p.a; - cc.defineGetterSetter(_p, "a", _p._getA, _p._setA); - - cc.assert(cc.isFunction(cc._tmp.PrototypeColor), cc._LogInfos.MissingFile, "CCTypesPropertyDefine.js"); - cc._tmp.PrototypeColor(); - delete cc._tmp.PrototypeColor; - -}); diff --git a/moduleConfig.json b/moduleConfig.json index 652575fec6..b36d7c4121 100644 --- a/moduleConfig.json +++ b/moduleConfig.json @@ -34,9 +34,7 @@ "core", "cocos2d/compression/ZipUtils.js", - "cocos2d/compression/base64.js", - "cocos2d/compression/gzip.js", - "cocos2d/compression/zlib.min.js" + "cocos2d/compression/base64.js" ], "core" : [ "cocos2d/core/event-manager/CCEventHelper.js", @@ -51,8 +49,6 @@ "cocos2d/core/platform/CCConfig.js", "cocos2d/core/platform/miniFramework.js", "cocos2d/core/platform/CCMacro.js", - "cocos2d/core/platform/CCTypesWebGL.js", - "cocos2d/core/platform/CCTypesPropertyDefine.js", "cocos2d/core/platform/CCTypes.js", "cocos2d/core/platform/CCEGLView.js", "cocos2d/core/platform/CCScreen.js", @@ -491,4 +487,4 @@ "external" : ["box2d", "chipmunk", "socketio", "pluginx", "gaf"] }, "bootFile" : "CCBoot.js" -} \ No newline at end of file +} From 0ce51b138f5850927b3171cb70ab71a30980e0f1 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Thu, 8 Dec 2016 18:21:57 +0800 Subject: [PATCH 25/42] Fix scissor clipping issue --- cocos2d/core/platform/CCEGLView.js | 42 ++++++++++++++++++++++-------- 1 file changed, 31 insertions(+), 11 deletions(-) diff --git a/cocos2d/core/platform/CCEGLView.js b/cocos2d/core/platform/CCEGLView.js index c6e900c4a1..6588d420e2 100644 --- a/cocos2d/core/platform/CCEGLView.js +++ b/cocos2d/core/platform/CCEGLView.js @@ -102,7 +102,7 @@ switch (__BrowserGetter.adaptationType) { break; } -var _scissorRect = cc.rect(); +var _scissorRect = null; /** * cc.view is the singleton object which represents the game window.
@@ -801,15 +801,24 @@ cc.EGLView = cc.Class.extend(/** @lends cc.view# */{ * @param {Number} h */ setScissorInPoints: function (x, y, w, h) { - 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); + var locFrameZoomFactor = this._frameZoomFactor, locScaleX = this._scaleX, locScaleY = this._scaleY; + var sx = Math.ceil(x * locScaleX * locFrameZoomFactor + this._viewPortRect.x * locFrameZoomFactor); + var sy = Math.ceil(y * locScaleY * locFrameZoomFactor + this._viewPortRect.y * locFrameZoomFactor); + var sw = Math.ceil(w * locScaleX * locFrameZoomFactor); + var sh = Math.ceil(h * locScaleY * locFrameZoomFactor); + + if (!_scissorRect) { + var boxArr = gl.getParameter(gl.SCISSOR_BOX); + _scissorRect = cc.rect(boxArr[0], boxArr[1], boxArr[2], boxArr[3]); + } + + if (_scissorRect.x != sx || _scissorRect.y != sy || _scissorRect.width != sw || _scissorRect.height != sh) { + _scissorRect.x = sx; + _scissorRect.y = sy; + _scissorRect.width = sw; + _scissorRect.height = sh; + cc._renderContext.scissor(sx, sy, sw, sh); + } }, /** @@ -825,7 +834,18 @@ cc.EGLView = cc.Class.extend(/** @lends cc.view# */{ * @return {cc.Rect} */ getScissorRect: function () { - return cc.rect(_scissorRect); + if (!_scissorRect) { + var boxArr = gl.getParameter(gl.SCISSOR_BOX); + _scissorRect = cc.rect(boxArr[0], boxArr[1], boxArr[2], boxArr[3]); + } + var scaleX = this._scaleX; + var scaleY = this._scaleY; + return cc.rect( + (_scissorRect.x - this._viewPortRect.x) / scaleX, + (_scissorRect.y - this._viewPortRect.y) / scaleY, + _scissorRect.width / scaleX, + _scissorRect.height / scaleY + ); }, /** From 41b102637fb5a930bc37a6e88c4d779120d0ab3e Mon Sep 17 00:00:00 2001 From: pandamicro Date: Thu, 8 Dec 2016 18:22:27 +0800 Subject: [PATCH 26/42] Improve updateProjectionUniform performance --- cocos2d/kazmath/gl/mat4stack.js | 1 + cocos2d/kazmath/gl/matrix.js | 1 + cocos2d/shaders/CCGLProgram.js | 9 +++++++-- 3 files changed, 9 insertions(+), 2 deletions(-) diff --git a/cocos2d/kazmath/gl/mat4stack.js b/cocos2d/kazmath/gl/mat4stack.js index 962f3d6ece..cd339423e2 100644 --- a/cocos2d/kazmath/gl/mat4stack.js +++ b/cocos2d/kazmath/gl/mat4stack.js @@ -36,6 +36,7 @@ cc.math.Matrix4Stack = function (top, stack) { this.top = top; this.stack = stack || []; + this.lastUpdated = 0; //this._matrixPool = []; // use pool in next version }; cc.km_mat4_stack = cc.math.Matrix4Stack; diff --git a/cocos2d/kazmath/gl/matrix.js b/cocos2d/kazmath/gl/matrix.js index 38f111f583..13c9798125 100644 --- a/cocos2d/kazmath/gl/matrix.js +++ b/cocos2d/kazmath/gl/matrix.js @@ -106,6 +106,7 @@ throw new Error("Invalid matrix mode specified"); //TODO: Proper error handling break; } + cc.current_stack.lastUpdated = cc.director.getTotalFrames(); }; cc.kmGLLoadIdentity = function () { diff --git a/cocos2d/shaders/CCGLProgram.js b/cocos2d/shaders/CCGLProgram.js index af365ff69c..d9e59b109d 100644 --- a/cocos2d/shaders/CCGLProgram.js +++ b/cocos2d/shaders/CCGLProgram.js @@ -39,6 +39,7 @@ cc.GLProgram = cc.Class.extend(/** @lends cc.GLProgram# */{ _uniforms: null, _hashForUniforms: null, _usesTime: false, + _projectionUpdated: -1, // Uniform cache _updateUniformLocation: function (location) { @@ -684,8 +685,12 @@ cc.GLProgram = cc.Class.extend(/** @lends cc.GLProgram# */{ this._glContext.uniformMatrix4fv(this._uniforms[cc.UNIFORM_PMATRIX_S], false, cc.projection_matrix_stack.top.mat); }, - _updateProjectionUniform: function(){ - this._glContext.uniformMatrix4fv(this._uniforms[cc.UNIFORM_PMATRIX_S], false, cc.projection_matrix_stack.top.mat); + _updateProjectionUniform: function () { + var stack = cc.projection_matrix_stack; + if (stack.lastUpdated !== this._projectionUpdated) { + this._glContext.uniformMatrix4fv(this._uniforms[cc.UNIFORM_PMATRIX_S], false, stack.top.mat); + this._projectionUpdated = stack.lastUpdated; + } }, /** From 7f9e68a3155ba6adc7e9ca939a2e2a7adf2dc093 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Thu, 8 Dec 2016 18:26:14 +0800 Subject: [PATCH 27/42] Improve RenderCmd construction performance --- .../core/base-nodes/CCNodeCanvasRenderCmd.js | 5 ++++- .../core/base-nodes/CCNodeWebGLRenderCmd.js | 5 ++++- .../labelttf/CCLabelTTFCanvasRenderCmd.js | 20 ++++++++++--------- .../core/labelttf/CCLabelTTFWebGLRenderCmd.js | 4 ++-- cocos2d/core/layers/CCLayerCanvasRenderCmd.js | 9 +++++---- cocos2d/core/layers/CCLayerWebGLRenderCmd.js | 14 +++++++------ .../core/sprites/CCSpriteCanvasRenderCmd.js | 3 ++- .../core/sprites/CCSpriteWebGLRenderCmd.js | 3 ++- .../labels/CCLabelBMFontCanvasRenderCmd.js | 6 +++--- cocos2d/labels/CCLabelBMFontWebGLRenderCmd.js | 6 +++--- .../CCMotionStreakWebGLRenderCmd.js | 4 ++-- cocos2d/node-grid/CCNodeGridWebGLRenderCmd.js | 6 +++--- cocos2d/parallax/CCParallaxNodeRenderCmd.js | 6 +++--- .../CCParticleBatchNodeCanvasRenderCmd.js | 4 ++-- .../CCParticleBatchNodeWebGLRenderCmd.js | 4 ++-- .../CCParticleSystemCanvasRenderCmd.js | 6 +++--- .../CCParticleSystemWebGLRenderCmd.js | 4 ++-- .../CCPhysicsDebugNodeCanvasRenderCmd.js | 6 +++--- .../CCPhysicsDebugNodeWebGLRenderCmd.js | 6 +++--- .../physics/CCPhysicsSpriteCanvasRenderCmd.js | 6 +++--- .../physics/CCPhysicsSpriteWebGLRenderCmd.js | 6 +++--- .../CCProgressTimerCanvasRenderCmd.js | 6 +++--- .../CCProgressTimerWebGLRenderCmd.js | 6 +++--- .../CCRenderTextureCanvasRenderCmd.js | 6 +++--- .../CCRenderTextureWebGLRenderCmd.js | 6 +++--- .../shape-nodes/CCDrawNodeCanvasRenderCmd.js | 4 ++-- .../shape-nodes/CCDrawNodeWebGLRenderCmd.js | 4 ++-- cocos2d/tilemap/CCTMXLayerCanvasRenderCmd.js | 6 +++--- cocos2d/tilemap/CCTMXLayerWebGLRenderCmd.js | 6 +++--- .../CCProtectedNodeCanvasRenderCmd.js | 3 ++- .../CCProtectedNodeWebGLRenderCmd.js | 3 ++- .../ccui/base-classes/UIWidgetRenderCmd.js | 4 ++-- .../ccui/layouts/UILayoutCanvasRenderCmd.js | 7 ++++--- .../ccui/layouts/UILayoutWebGLRenderCmd.js | 5 +++-- .../UIScrollViewCanvasRenderCmd.js | 4 ++-- .../UIScrollViewWebGLRenderCmd.js | 4 ++-- .../armature/CCArmatureCanvasRenderCmd.js | 6 +++--- .../armature/CCArmatureWebGLRenderCmd.js | 4 ++-- extensions/cocostudio/armature/CCBone.js | 10 +++++----- .../armature/display/CCSkinRenderCmd.js | 8 ++++---- extensions/cocostudio/timeline/CCBoneNode.js | 4 ++-- extensions/editbox/CCEditBox.js | 4 ++-- .../scrollview/CCScrollViewCanvasRenderCmd.js | 6 +++--- .../scrollview/CCScrollViewWebGLRenderCmd.js | 6 +++--- extensions/spine/CCSkeletonCanvasRenderCmd.js | 6 +++--- extensions/spine/CCSkeletonWebGLRenderCmd.js | 2 +- 46 files changed, 140 insertions(+), 123 deletions(-) diff --git a/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js b/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js index 56ed8c3aa7..23151853d7 100644 --- a/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js +++ b/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js @@ -542,7 +542,9 @@ cc.Node.RenderCmd.prototype._originSyncStatus = cc.Node.RenderCmd.prototype._syn (function () { //The cc.Node's render command for Canvas cc.Node.CanvasRenderCmd = function (renderable) { - cc.Node.RenderCmd.call(this, renderable); + this._node = renderable; + this._anchorPointInPoints = {x: 0, y: 0}; + this._displayedColor = cc.color(255, 255, 255, 255); this._cachedParent = null; this._cacheDirty = false; this._currentRegion = new cc.Region(); @@ -559,6 +561,7 @@ cc.Node.RenderCmd.prototype._originSyncStatus = cc.Node.RenderCmd.prototype._syn var proto = cc.Node.CanvasRenderCmd.prototype = Object.create(cc.Node.RenderCmd.prototype); proto.constructor = cc.Node.CanvasRenderCmd; + proto._rootCtor = cc.Node.CanvasRenderCmd; proto._notifyRegionStatus = function (status) { if (this._needDraw && this._regionFlag < status) { diff --git a/cocos2d/core/base-nodes/CCNodeWebGLRenderCmd.js b/cocos2d/core/base-nodes/CCNodeWebGLRenderCmd.js index 0d57439e6a..aa6f3cba61 100644 --- a/cocos2d/core/base-nodes/CCNodeWebGLRenderCmd.js +++ b/cocos2d/core/base-nodes/CCNodeWebGLRenderCmd.js @@ -24,12 +24,15 @@ // ------------------------------ The cc.Node's render command for WebGL ---------------------------------- (function() { cc.Node.WebGLRenderCmd = function (renderable) { - cc.Node.RenderCmd.call(this, renderable); + this._node = renderable; + this._anchorPointInPoints = {x: 0, y: 0}; + this._displayedColor = cc.color(255, 255, 255, 255); this._shaderProgram = null; }; var proto = cc.Node.WebGLRenderCmd.prototype = Object.create(cc.Node.RenderCmd.prototype); proto.constructor = cc.Node.WebGLRenderCmd; + proto._rootCtor = cc.Node.WebGLRenderCmd; proto._updateColor = function () { }; diff --git a/cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js b/cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js index c4b7a33b93..88ba1933a9 100644 --- a/cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js +++ b/cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js @@ -52,6 +52,7 @@ cc.LabelTTF._firsrEnglish = /^[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]/; }; var proto = cc.LabelTTF.RenderCmd.prototype; proto.constructor = cc.LabelTTF.RenderCmd; + proto._labelCmdCtor = cc.LabelTTF.RenderCmd; proto._setFontStyle = function (fontNameOrFontDef, fontSize, fontStyle, fontWeight) { if (fontNameOrFontDef instanceof cc.FontDefinition) { @@ -371,9 +372,9 @@ cc.LabelTTF._firsrEnglish = /^[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]/; }; })(); -(function(){ - cc.LabelTTF.CacheRenderCmd = function (renderable) { - cc.LabelTTF.RenderCmd.call(this,renderable); +(function () { + cc.LabelTTF.CacheRenderCmd = function () { + this._labelCmdCtor(); var locCanvas = this._labelCanvas = document.createElement("canvas"); locCanvas.width = 1; locCanvas.height = 1; @@ -385,6 +386,7 @@ cc.LabelTTF._firsrEnglish = /^[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]/; var proto = cc.LabelTTF.CacheRenderCmd.prototype; proto.constructor = cc.LabelTTF.CacheRenderCmd; + proto._cacheCmdCtor = cc.LabelTTF.CacheRenderCmd; proto._updateTexture = function () { this._dirtyFlag = this._dirtyFlag & cc.Node._dirtyFlags.textDirty ^ this._dirtyFlag; @@ -433,10 +435,10 @@ cc.LabelTTF._firsrEnglish = /^[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]/; })(); -(function(){ +(function () { cc.LabelTTF.CacheCanvasRenderCmd = function (renderable) { - cc.Sprite.CanvasRenderCmd.call(this, renderable); - cc.LabelTTF.CacheRenderCmd.call(this); + this._spriteCmdCtor(renderable); + this._cacheCmdCtor(); }; var proto = cc.LabelTTF.CacheCanvasRenderCmd.prototype = Object.create(cc.Sprite.CanvasRenderCmd.prototype); @@ -444,10 +446,10 @@ cc.LabelTTF._firsrEnglish = /^[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]/; proto.constructor = cc.LabelTTF.CacheCanvasRenderCmd; })(); -(function(){ +(function () { cc.LabelTTF.CanvasRenderCmd = function (renderable) { - cc.Sprite.CanvasRenderCmd.call(this, renderable); - cc.LabelTTF.RenderCmd.call(this); + this._spriteCmdCtor(renderable); + this._labelCmdCtor(); }; cc.LabelTTF.CanvasRenderCmd.prototype = Object.create(cc.Sprite.CanvasRenderCmd.prototype); diff --git a/cocos2d/core/labelttf/CCLabelTTFWebGLRenderCmd.js b/cocos2d/core/labelttf/CCLabelTTFWebGLRenderCmd.js index fee7c6fa8f..e1e8411e58 100644 --- a/cocos2d/core/labelttf/CCLabelTTFWebGLRenderCmd.js +++ b/cocos2d/core/labelttf/CCLabelTTFWebGLRenderCmd.js @@ -25,8 +25,8 @@ // ----------------------------------- LabelTTF WebGL render cmd ---------------------------- (function () { cc.LabelTTF.WebGLRenderCmd = function (renderable) { - cc.Sprite.WebGLRenderCmd.call(this, renderable); - cc.LabelTTF.CacheRenderCmd.call(this); + this._spriteCmdCtor(renderable); + this._cacheCmdCtor(); }; var proto = cc.LabelTTF.WebGLRenderCmd.prototype = Object.create(cc.Sprite.WebGLRenderCmd.prototype); diff --git a/cocos2d/core/layers/CCLayerCanvasRenderCmd.js b/cocos2d/core/layers/CCLayerCanvasRenderCmd.js index 9b379ae4f9..021957242b 100644 --- a/cocos2d/core/layers/CCLayerCanvasRenderCmd.js +++ b/cocos2d/core/layers/CCLayerCanvasRenderCmd.js @@ -33,8 +33,8 @@ */ (function () { //Layer's canvas render command - cc.Layer.CanvasRenderCmd = function(renderable){ - cc.Node.CanvasRenderCmd.call(this, renderable); + cc.Layer.CanvasRenderCmd = function (renderable) { + this._rootCtor(renderable); this._isBaked = false; this._bakeSprite = null; this._canUseDirtyRegion = true; @@ -43,6 +43,7 @@ var proto = cc.Layer.CanvasRenderCmd.prototype = Object.create(cc.Node.CanvasRenderCmd.prototype); proto.constructor = cc.Layer.CanvasRenderCmd; + proto._layerCmdCtor = cc.Layer.CanvasRenderCmd; proto._setCacheDirty = function (child) { if (child && this._updateCache === 0) @@ -215,8 +216,8 @@ */ (function () { //LayerColor's canvas render command - cc.LayerColor.CanvasRenderCmd = function(renderable){ - cc.Layer.CanvasRenderCmd.call(this, renderable); + cc.LayerColor.CanvasRenderCmd = function (renderable) { + this._layerCmdCtor(renderable); this._needDraw = true; this._blendFuncStr = "source-over"; this._bakeRenderCmd = new cc.CustomRenderCmd(this, this._bakeRendering); diff --git a/cocos2d/core/layers/CCLayerWebGLRenderCmd.js b/cocos2d/core/layers/CCLayerWebGLRenderCmd.js index adfa4ea287..309921e184 100644 --- a/cocos2d/core/layers/CCLayerWebGLRenderCmd.js +++ b/cocos2d/core/layers/CCLayerWebGLRenderCmd.js @@ -31,13 +31,15 @@ /** * cc.Layer's rendering objects of WebGL */ -(function(){ - cc.Layer.WebGLRenderCmd = function(renderable){ - cc.Node.WebGLRenderCmd.call(this, renderable); +(function () { + cc.Layer.WebGLRenderCmd = function (renderable) { + this._rootCtor(renderable); + this._isBaked = false; }; var proto = cc.Layer.WebGLRenderCmd.prototype = Object.create(cc.Node.WebGLRenderCmd.prototype); proto.constructor = cc.Layer.WebGLRenderCmd; + proto._layerCmdCtor = cc.Layer.WebGLRenderCmd; proto.bake = function () { }; @@ -52,9 +54,9 @@ /** * cc.LayerColor's rendering objects of WebGL */ -(function(){ - cc.LayerColor.WebGLRenderCmd = function(renderable){ - cc.Layer.WebGLRenderCmd.call(this, renderable); +(function () { + cc.LayerColor.WebGLRenderCmd = function (renderable) { + this._layerCmdCtor(renderable); this._needDraw = true; this._matrix = new cc.math.Matrix4(); diff --git a/cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js b/cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js index 29472fb4b6..eaa8bbfecb 100644 --- a/cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js +++ b/cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js @@ -24,7 +24,7 @@ (function () { cc.Sprite.CanvasRenderCmd = function (renderable) { - cc.Node.CanvasRenderCmd.call(this, renderable); + this._rootCtor(renderable); this._needDraw = true; this._textureCoord = { renderX: 0, //the x of texture coordinate for render, when texture tinted, its value doesn't equal x. @@ -43,6 +43,7 @@ var proto = cc.Sprite.CanvasRenderCmd.prototype = Object.create(cc.Node.CanvasRenderCmd.prototype); proto.constructor = cc.Sprite.CanvasRenderCmd; + proto._spriteCmdCtor = cc.Sprite.CanvasRenderCmd; proto.setDirtyRecursively = function (value) { }; diff --git a/cocos2d/core/sprites/CCSpriteWebGLRenderCmd.js b/cocos2d/core/sprites/CCSpriteWebGLRenderCmd.js index 735db8e214..f10773b1d7 100644 --- a/cocos2d/core/sprites/CCSpriteWebGLRenderCmd.js +++ b/cocos2d/core/sprites/CCSpriteWebGLRenderCmd.js @@ -26,7 +26,7 @@ (function () { cc.Sprite.WebGLRenderCmd = function (renderable) { - cc.Node.WebGLRenderCmd.call(this, renderable); + this._rootCtor(renderable); this._needDraw = true; this._vertices = [ @@ -44,6 +44,7 @@ var proto = cc.Sprite.WebGLRenderCmd.prototype = Object.create(cc.Node.WebGLRenderCmd.prototype); proto.constructor = cc.Sprite.WebGLRenderCmd; + proto._spriteCmdCtor = cc.Sprite.WebGLRenderCmd; proto.updateBlendFunc = function (blendFunc) { }; diff --git a/cocos2d/labels/CCLabelBMFontCanvasRenderCmd.js b/cocos2d/labels/CCLabelBMFontCanvasRenderCmd.js index e824bc1941..5861daa30a 100644 --- a/cocos2d/labels/CCLabelBMFontCanvasRenderCmd.js +++ b/cocos2d/labels/CCLabelBMFontCanvasRenderCmd.js @@ -30,9 +30,9 @@ http://www.angelcode.com/products/bmfont/ (Free, Windows only) ****************************************************************************/ -(function(){ - cc.LabelBMFont.CanvasRenderCmd = function(renderableObject){ - cc.Node.CanvasRenderCmd.call(this, renderableObject); +(function () { + cc.LabelBMFont.CanvasRenderCmd = function (renderableObject) { + this._rootCtor(renderableObject); }; var proto = cc.LabelBMFont.CanvasRenderCmd.prototype = Object.create(cc.Node.CanvasRenderCmd.prototype); diff --git a/cocos2d/labels/CCLabelBMFontWebGLRenderCmd.js b/cocos2d/labels/CCLabelBMFontWebGLRenderCmd.js index e255e60e4d..7e468e37d7 100644 --- a/cocos2d/labels/CCLabelBMFontWebGLRenderCmd.js +++ b/cocos2d/labels/CCLabelBMFontWebGLRenderCmd.js @@ -30,9 +30,9 @@ http://www.angelcode.com/products/bmfont/ (Free, Windows only) ****************************************************************************/ -(function(){ - cc.LabelBMFont.WebGLRenderCmd = function(renderableObject){ - cc.Node.WebGLRenderCmd.call(this, renderableObject); +(function () { + cc.LabelBMFont.WebGLRenderCmd = function (renderableObject) { + this._rootCtor(renderableObject); }; var proto = cc.LabelBMFont.WebGLRenderCmd.prototype = Object.create(cc.Node.WebGLRenderCmd.prototype); diff --git a/cocos2d/motion-streak/CCMotionStreakWebGLRenderCmd.js b/cocos2d/motion-streak/CCMotionStreakWebGLRenderCmd.js index 50ddcffd69..e2d74f574a 100644 --- a/cocos2d/motion-streak/CCMotionStreakWebGLRenderCmd.js +++ b/cocos2d/motion-streak/CCMotionStreakWebGLRenderCmd.js @@ -22,8 +22,8 @@ THE SOFTWARE. ****************************************************************************/ -cc.MotionStreak.WebGLRenderCmd = function(renderableObject){ - cc.Node.WebGLRenderCmd.call(this, renderableObject); +cc.MotionStreak.WebGLRenderCmd = function (renderableObject) { + this._rootCtor(renderableObject); this._needDraw = true; this._matrix = new cc.math.Matrix4(); this._matrix.identity(); diff --git a/cocos2d/node-grid/CCNodeGridWebGLRenderCmd.js b/cocos2d/node-grid/CCNodeGridWebGLRenderCmd.js index bf51ee5e56..9288a0fd69 100644 --- a/cocos2d/node-grid/CCNodeGridWebGLRenderCmd.js +++ b/cocos2d/node-grid/CCNodeGridWebGLRenderCmd.js @@ -22,9 +22,9 @@ THE SOFTWARE. ****************************************************************************/ -(function(){ - cc.NodeGrid.WebGLRenderCmd = function(renderable){ - cc.Node.WebGLRenderCmd.call(this, renderable); +(function () { + cc.NodeGrid.WebGLRenderCmd = function (renderable) { + this._rootCtor(renderable); this._needDraw = false; this._gridBeginCommand = new cc.CustomRenderCmd(this, this.onGridBeginDraw); this._gridEndCommand = new cc.CustomRenderCmd(this, this.onGridEndDraw); diff --git a/cocos2d/parallax/CCParallaxNodeRenderCmd.js b/cocos2d/parallax/CCParallaxNodeRenderCmd.js index 53f3ccf6c7..960a1881a9 100644 --- a/cocos2d/parallax/CCParallaxNodeRenderCmd.js +++ b/cocos2d/parallax/CCParallaxNodeRenderCmd.js @@ -24,9 +24,9 @@ //TODO find a way to simple these code. -(function(){ - cc.ParallaxNode.CanvasRenderCmd = function(renderable){ - cc.Node.CanvasRenderCmd.call(this, renderable); +(function () { + cc.ParallaxNode.CanvasRenderCmd = function (renderable) { + this._rootCtor(renderable); this._needDraw = false; }; diff --git a/cocos2d/particle/CCParticleBatchNodeCanvasRenderCmd.js b/cocos2d/particle/CCParticleBatchNodeCanvasRenderCmd.js index 341e16ad9e..6e0990d140 100644 --- a/cocos2d/particle/CCParticleBatchNodeCanvasRenderCmd.js +++ b/cocos2d/particle/CCParticleBatchNodeCanvasRenderCmd.js @@ -26,8 +26,8 @@ /** * cc.ParticleBatchNode's rendering objects of Canvas */ - cc.ParticleBatchNode.CanvasRenderCmd = function(renderable){ - cc.Node.CanvasRenderCmd.call(this, renderable); + cc.ParticleBatchNode.CanvasRenderCmd = function (renderable) { + this._rootCtor(renderable); this._needDraw = false; }; diff --git a/cocos2d/particle/CCParticleBatchNodeWebGLRenderCmd.js b/cocos2d/particle/CCParticleBatchNodeWebGLRenderCmd.js index df376ce113..82e7f290f6 100644 --- a/cocos2d/particle/CCParticleBatchNodeWebGLRenderCmd.js +++ b/cocos2d/particle/CCParticleBatchNodeWebGLRenderCmd.js @@ -26,8 +26,8 @@ /** * cc.ParticleBatchNode's rendering objects of WebGL */ - cc.ParticleBatchNode.WebGLRenderCmd = function(renderable){ - cc.Node.WebGLRenderCmd.call(this, renderable); + cc.ParticleBatchNode.WebGLRenderCmd = function (renderable) { + this._rootCtor(renderable); this._needDraw = true; this._matrix = new cc.math.Matrix4(); this._matrix.identity(); diff --git a/cocos2d/particle/CCParticleSystemCanvasRenderCmd.js b/cocos2d/particle/CCParticleSystemCanvasRenderCmd.js index 4ff3fc4d87..5165b69728 100644 --- a/cocos2d/particle/CCParticleSystemCanvasRenderCmd.js +++ b/cocos2d/particle/CCParticleSystemCanvasRenderCmd.js @@ -25,9 +25,9 @@ /** * ParticleSystem's canvas render command */ -(function(){ - cc.ParticleSystem.CanvasRenderCmd = function(renderable){ - cc.Node.CanvasRenderCmd.call(this, renderable); +(function () { + cc.ParticleSystem.CanvasRenderCmd = function (renderable) { + this._rootCtor(renderable); this._needDraw = true; this._drawMode = cc.ParticleSystem.TEXTURE_MODE; diff --git a/cocos2d/particle/CCParticleSystemWebGLRenderCmd.js b/cocos2d/particle/CCParticleSystemWebGLRenderCmd.js index 55cc7fa128..52a85c542b 100644 --- a/cocos2d/particle/CCParticleSystemWebGLRenderCmd.js +++ b/cocos2d/particle/CCParticleSystemWebGLRenderCmd.js @@ -26,8 +26,8 @@ /** * ParticleSystem's WebGL render command */ - cc.ParticleSystem.WebGLRenderCmd = function(renderable){ - cc.Node.WebGLRenderCmd.call(this, renderable); + cc.ParticleSystem.WebGLRenderCmd = function (renderable) { + this._rootCtor(renderable); this._needDraw = true; this._matrix = new cc.math.Matrix4(); diff --git a/cocos2d/physics/CCPhysicsDebugNodeCanvasRenderCmd.js b/cocos2d/physics/CCPhysicsDebugNodeCanvasRenderCmd.js index b3b417fed1..1adf9a3f49 100644 --- a/cocos2d/physics/CCPhysicsDebugNodeCanvasRenderCmd.js +++ b/cocos2d/physics/CCPhysicsDebugNodeCanvasRenderCmd.js @@ -25,9 +25,9 @@ /** * cc.PhysicsDebugNode's rendering objects of Canvas */ -(function(){ - cc.PhysicsDebugNode.CanvasRenderCmd = function(renderableObject){ - cc.Node.CanvasRenderCmd.call(this, renderableObject); +(function () { + cc.PhysicsDebugNode.CanvasRenderCmd = function (renderableObject) { + this._rootCtor(renderableObject); this._buffer = renderableObject._buffer; this._needDraw = true; }; diff --git a/cocos2d/physics/CCPhysicsDebugNodeWebGLRenderCmd.js b/cocos2d/physics/CCPhysicsDebugNodeWebGLRenderCmd.js index e2f16f8560..1c2a9fb69a 100644 --- a/cocos2d/physics/CCPhysicsDebugNodeWebGLRenderCmd.js +++ b/cocos2d/physics/CCPhysicsDebugNodeWebGLRenderCmd.js @@ -25,9 +25,9 @@ /** * cc.PhysicsDebugNode's rendering objects of WebGL */ -(function(){ +(function () { cc.PhysicsDebugNode.WebGLRenderCmd = function (renderableObject) { - cc.Node.WebGLRenderCmd.call(this, renderableObject); + this._rootCtor(renderableObject); this._needDraw = true; this._matrix = new cc.math.Matrix4(); this._matrix.identity(); @@ -60,4 +60,4 @@ node.clear(); }; -})(); \ No newline at end of file +})(); diff --git a/cocos2d/physics/CCPhysicsSpriteCanvasRenderCmd.js b/cocos2d/physics/CCPhysicsSpriteCanvasRenderCmd.js index 846f0f27cf..09279e65ea 100644 --- a/cocos2d/physics/CCPhysicsSpriteCanvasRenderCmd.js +++ b/cocos2d/physics/CCPhysicsSpriteCanvasRenderCmd.js @@ -25,9 +25,9 @@ /** * cc.PhysicsSprite's rendering objects of Canvas */ -(function(){ - cc.PhysicsSprite.CanvasRenderCmd = function(renderableObject){ - cc.Sprite.CanvasRenderCmd.call(this, renderableObject); +(function () { + cc.PhysicsSprite.CanvasRenderCmd = function (renderableObject) { + this._spriteCmdCtor(renderableObject); this._needDraw = true; }; diff --git a/cocos2d/physics/CCPhysicsSpriteWebGLRenderCmd.js b/cocos2d/physics/CCPhysicsSpriteWebGLRenderCmd.js index 1c943ae99e..25fc120601 100644 --- a/cocos2d/physics/CCPhysicsSpriteWebGLRenderCmd.js +++ b/cocos2d/physics/CCPhysicsSpriteWebGLRenderCmd.js @@ -25,9 +25,9 @@ /** * cc.PhysicsSprite's rendering objects of WebGL */ -(function(){ - cc.PhysicsSprite.WebGLRenderCmd = function(renderableObject){ - cc.Sprite.WebGLRenderCmd.call(this, renderableObject); +(function () { + cc.PhysicsSprite.WebGLRenderCmd = function (renderableObject) { + this._spriteCmdCtor(renderableObject); this._needDraw = true; }; diff --git a/cocos2d/progress-timer/CCProgressTimerCanvasRenderCmd.js b/cocos2d/progress-timer/CCProgressTimerCanvasRenderCmd.js index 17276c23f5..4dc2a71b74 100644 --- a/cocos2d/progress-timer/CCProgressTimerCanvasRenderCmd.js +++ b/cocos2d/progress-timer/CCProgressTimerCanvasRenderCmd.js @@ -25,9 +25,9 @@ /** * cc.ProgressTimer's rendering objects of Canvas */ -(function(){ - cc.ProgressTimer.CanvasRenderCmd = function(renderableObject){ - cc.Node.CanvasRenderCmd.call(this, renderableObject); +(function () { + cc.ProgressTimer.CanvasRenderCmd = function (renderableObject) { + this._rootCtor(renderableObject); this._needDraw = true; this._PI180 = Math.PI / 180; diff --git a/cocos2d/progress-timer/CCProgressTimerWebGLRenderCmd.js b/cocos2d/progress-timer/CCProgressTimerWebGLRenderCmd.js index c0f5911f7d..8ee5a7da1a 100644 --- a/cocos2d/progress-timer/CCProgressTimerWebGLRenderCmd.js +++ b/cocos2d/progress-timer/CCProgressTimerWebGLRenderCmd.js @@ -25,11 +25,11 @@ /** * cc.ProgressTimer's rendering objects of WebGL */ -(function(){ +(function () { var MAX_VERTEX_COUNT = 8; - cc.ProgressTimer.WebGLRenderCmd = function(renderableObject){ - cc.Node.WebGLRenderCmd.call(this, renderableObject); + cc.ProgressTimer.WebGLRenderCmd = function (renderableObject) { + this._rootCtor(renderableObject); this._needDraw = true; this._progressDirty = true; diff --git a/cocos2d/render-texture/CCRenderTextureCanvasRenderCmd.js b/cocos2d/render-texture/CCRenderTextureCanvasRenderCmd.js index 3d20f4002b..d15cb963fa 100644 --- a/cocos2d/render-texture/CCRenderTextureCanvasRenderCmd.js +++ b/cocos2d/render-texture/CCRenderTextureCanvasRenderCmd.js @@ -22,9 +22,9 @@ THE SOFTWARE. ****************************************************************************/ -(function(){ - cc.RenderTexture.CanvasRenderCmd = function(renderableObject){ - cc.Node.CanvasRenderCmd.call(this, renderableObject); +(function () { + cc.RenderTexture.CanvasRenderCmd = function (renderableObject) { + this._rootCtor(renderableObject); this._needDraw = true; this._clearColorStr = "rgba(255,255,255,1)"; diff --git a/cocos2d/render-texture/CCRenderTextureWebGLRenderCmd.js b/cocos2d/render-texture/CCRenderTextureWebGLRenderCmd.js index 84c2407e88..2f6994219b 100644 --- a/cocos2d/render-texture/CCRenderTextureWebGLRenderCmd.js +++ b/cocos2d/render-texture/CCRenderTextureWebGLRenderCmd.js @@ -22,9 +22,9 @@ THE SOFTWARE. ****************************************************************************/ -(function(){ - cc.RenderTexture.WebGLRenderCmd = function(renderableObject){ - cc.Node.WebGLRenderCmd.call(this, renderableObject); +(function () { + cc.RenderTexture.WebGLRenderCmd = function (renderableObject) { + this._rootCtor(renderableObject); this._needDraw = true; this._fBO = null; diff --git a/cocos2d/shape-nodes/CCDrawNodeCanvasRenderCmd.js b/cocos2d/shape-nodes/CCDrawNodeCanvasRenderCmd.js index a19ded7bf3..771f852748 100644 --- a/cocos2d/shape-nodes/CCDrawNodeCanvasRenderCmd.js +++ b/cocos2d/shape-nodes/CCDrawNodeCanvasRenderCmd.js @@ -24,8 +24,8 @@ (function () { - cc.DrawNode.CanvasRenderCmd = function(renderableObject){ - cc.Node.CanvasRenderCmd.call(this, renderableObject); + cc.DrawNode.CanvasRenderCmd = function (renderableObject) { + this._rootCtor(renderableObject); this._needDraw = true; this._buffer = null; this._drawColor = null; diff --git a/cocos2d/shape-nodes/CCDrawNodeWebGLRenderCmd.js b/cocos2d/shape-nodes/CCDrawNodeWebGLRenderCmd.js index 6c86d28833..ef9d443c98 100644 --- a/cocos2d/shape-nodes/CCDrawNodeWebGLRenderCmd.js +++ b/cocos2d/shape-nodes/CCDrawNodeWebGLRenderCmd.js @@ -22,9 +22,9 @@ THE SOFTWARE. ****************************************************************************/ -(function(){ +(function () { cc.DrawNode.WebGLRenderCmd = function (renderableObject) { - cc.Node.WebGLRenderCmd.call(this, renderableObject); + this._rootCtor(renderableObject); this._needDraw = true; this._matrix = new cc.math.Matrix4(); this._matrix.identity(); diff --git a/cocos2d/tilemap/CCTMXLayerCanvasRenderCmd.js b/cocos2d/tilemap/CCTMXLayerCanvasRenderCmd.js index cddb01fd28..f354284de2 100644 --- a/cocos2d/tilemap/CCTMXLayerCanvasRenderCmd.js +++ b/cocos2d/tilemap/CCTMXLayerCanvasRenderCmd.js @@ -22,9 +22,9 @@ THE SOFTWARE. ****************************************************************************/ -(function(){ - cc.TMXLayer.CanvasRenderCmd = function(renderable){ - cc.Node.CanvasRenderCmd.call(this, renderable); +(function () { + cc.TMXLayer.CanvasRenderCmd = function (renderable) { + this._rootCtor(renderable); this._needDraw = true; }; diff --git a/cocos2d/tilemap/CCTMXLayerWebGLRenderCmd.js b/cocos2d/tilemap/CCTMXLayerWebGLRenderCmd.js index 6b68bc0d96..d0e90bebc9 100644 --- a/cocos2d/tilemap/CCTMXLayerWebGLRenderCmd.js +++ b/cocos2d/tilemap/CCTMXLayerWebGLRenderCmd.js @@ -22,9 +22,9 @@ THE SOFTWARE. ****************************************************************************/ -(function(){ - cc.TMXLayer.WebGLRenderCmd = function(renderableObject){ - cc.Node.WebGLRenderCmd.call(this, renderableObject); +(function () { + cc.TMXLayer.WebGLRenderCmd = function (renderableObject) { + this._rootCtor(renderableObject); this._needDraw = true; this._vertices = [ {x: 0, y: 0}, diff --git a/extensions/ccui/base-classes/CCProtectedNodeCanvasRenderCmd.js b/extensions/ccui/base-classes/CCProtectedNodeCanvasRenderCmd.js index 7e9cae0b4b..db7594d0d0 100644 --- a/extensions/ccui/base-classes/CCProtectedNodeCanvasRenderCmd.js +++ b/extensions/ccui/base-classes/CCProtectedNodeCanvasRenderCmd.js @@ -139,7 +139,7 @@ }; cc.ProtectedNode.CanvasRenderCmd = function (renderable) { - cc.Node.CanvasRenderCmd.call(this, renderable); + this._rootCtor(renderable); this._cachedParent = null; this._cacheDirty = false; }; @@ -147,6 +147,7 @@ var proto = cc.ProtectedNode.CanvasRenderCmd.prototype = Object.create(cc.Node.CanvasRenderCmd.prototype); cc.inject(cc.ProtectedNode.RenderCmd, proto); proto.constructor = cc.ProtectedNode.CanvasRenderCmd; + proto._pNodeCmdCtor = cc.ProtectedNode.CanvasRenderCmd; proto.visit = function(parentCmd){ var node = this._node; diff --git a/extensions/ccui/base-classes/CCProtectedNodeWebGLRenderCmd.js b/extensions/ccui/base-classes/CCProtectedNodeWebGLRenderCmd.js index 0dd4843c7f..5306e98ba7 100644 --- a/extensions/ccui/base-classes/CCProtectedNodeWebGLRenderCmd.js +++ b/extensions/ccui/base-classes/CCProtectedNodeWebGLRenderCmd.js @@ -26,12 +26,13 @@ if (!cc.Node.WebGLRenderCmd) return; cc.ProtectedNode.WebGLRenderCmd = function (renderable) { - cc.Node.WebGLRenderCmd.call(this, renderable); + this._rootCtor(renderable); }; var proto = cc.ProtectedNode.WebGLRenderCmd.prototype = Object.create(cc.Node.WebGLRenderCmd.prototype); cc.inject(cc.ProtectedNode.RenderCmd, proto); proto.constructor = cc.ProtectedNode.WebGLRenderCmd; + proto._pNodeCmdCtor = cc.ProtectedNode.WebGLRenderCmd; proto.visit = function(parentCmd){ var node = this._node; diff --git a/extensions/ccui/base-classes/UIWidgetRenderCmd.js b/extensions/ccui/base-classes/UIWidgetRenderCmd.js index 9119c327dd..14b69c6e01 100644 --- a/extensions/ccui/base-classes/UIWidgetRenderCmd.js +++ b/extensions/ccui/base-classes/UIWidgetRenderCmd.js @@ -25,7 +25,7 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () { if (cc._renderType === cc.game.RENDER_TYPE_CANVAS) { ccui.Widget.CanvasRenderCmd = function (renderable) { - cc.ProtectedNode.CanvasRenderCmd.call(this, renderable); + this._pNodeCmdCtor(renderable); this._needDraw = false; }; @@ -62,7 +62,7 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () { proto.widgetTransform = proto.transform; } else { ccui.Widget.WebGLRenderCmd = function (renderable) { - cc.ProtectedNode.WebGLRenderCmd.call(this, renderable); + this._pNodeCmdCtor(renderable); this._needDraw = false; }; diff --git a/extensions/ccui/layouts/UILayoutCanvasRenderCmd.js b/extensions/ccui/layouts/UILayoutCanvasRenderCmd.js index 84ff54d167..bbde61bc21 100644 --- a/extensions/ccui/layouts/UILayoutCanvasRenderCmd.js +++ b/extensions/ccui/layouts/UILayoutCanvasRenderCmd.js @@ -23,9 +23,9 @@ THE SOFTWARE. ****************************************************************************/ -(function(){ - ccui.Layout.CanvasRenderCmd = function(renderable){ - ccui.ProtectedNode.CanvasRenderCmd.call(this, renderable); +(function () { + ccui.Layout.CanvasRenderCmd = function (renderable) { + this._pNodeCmdCtor(renderable); this._needDraw = false; this._rendererSaveCmd = new cc.CustomRenderCmd(this, this._onRenderSaveCmd); @@ -38,6 +38,7 @@ var proto = ccui.Layout.CanvasRenderCmd.prototype = Object.create(ccui.ProtectedNode.CanvasRenderCmd.prototype); proto.constructor = ccui.Layout.CanvasRenderCmd; + proto._layoutCmdCtor = ccui.Layout.CanvasRenderCmd; cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () { if (ccui.Widget.CanvasRenderCmd) { diff --git a/extensions/ccui/layouts/UILayoutWebGLRenderCmd.js b/extensions/ccui/layouts/UILayoutWebGLRenderCmd.js index 05a1f7f0c1..9c9ef2dfab 100644 --- a/extensions/ccui/layouts/UILayoutWebGLRenderCmd.js +++ b/extensions/ccui/layouts/UILayoutWebGLRenderCmd.js @@ -26,8 +26,8 @@ (function () { if (!ccui.ProtectedNode.WebGLRenderCmd) return; - ccui.Layout.WebGLRenderCmd = function(renderable){ - ccui.ProtectedNode.WebGLRenderCmd.call(this, renderable); + ccui.Layout.WebGLRenderCmd = function (renderable) { + this._pNodeCmdCtor(renderable); this._needDraw = false; this._currentStencilEnabled = 0; @@ -45,6 +45,7 @@ var proto = ccui.Layout.WebGLRenderCmd.prototype = Object.create(ccui.ProtectedNode.WebGLRenderCmd.prototype); proto.constructor = ccui.Layout.WebGLRenderCmd; + proto._layoutCmdCtor = ccui.Layout.CanvasRenderCmd; proto.visit = function(parentCmd){ var node = this._node; diff --git a/extensions/ccui/uiwidgets/scroll-widget/UIScrollViewCanvasRenderCmd.js b/extensions/ccui/uiwidgets/scroll-widget/UIScrollViewCanvasRenderCmd.js index d724d98e62..4ddc6e18b0 100644 --- a/extensions/ccui/uiwidgets/scroll-widget/UIScrollViewCanvasRenderCmd.js +++ b/extensions/ccui/uiwidgets/scroll-widget/UIScrollViewCanvasRenderCmd.js @@ -1,8 +1,8 @@ (function () { if (!ccui.ProtectedNode.CanvasRenderCmd) return; - ccui.ScrollView.CanvasRenderCmd = function(renderable){ - ccui.Layout.CanvasRenderCmd.call(this, renderable); + ccui.ScrollView.CanvasRenderCmd = function (renderable) { + this._layoutCmdCtor(renderable); //this._needDraw = true; this._dirty = false; }; diff --git a/extensions/ccui/uiwidgets/scroll-widget/UIScrollViewWebGLRenderCmd.js b/extensions/ccui/uiwidgets/scroll-widget/UIScrollViewWebGLRenderCmd.js index 5f22e798ba..abf3fc9278 100644 --- a/extensions/ccui/uiwidgets/scroll-widget/UIScrollViewWebGLRenderCmd.js +++ b/extensions/ccui/uiwidgets/scroll-widget/UIScrollViewWebGLRenderCmd.js @@ -1,8 +1,8 @@ (function () { if (!ccui.ProtectedNode.WebGLRenderCmd) return; - ccui.ScrollView.WebGLRenderCmd = function(renderable){ - ccui.Layout.WebGLRenderCmd.call(this, renderable); + ccui.ScrollView.WebGLRenderCmd = function (renderable) { + this._layoutCmdCtor(renderable); this._needDraw = true; this._dirty = false; }; diff --git a/extensions/cocostudio/armature/CCArmatureCanvasRenderCmd.js b/extensions/cocostudio/armature/CCArmatureCanvasRenderCmd.js index 17ffba9e3c..db6954e66a 100644 --- a/extensions/cocostudio/armature/CCArmatureCanvasRenderCmd.js +++ b/extensions/cocostudio/armature/CCArmatureCanvasRenderCmd.js @@ -41,9 +41,9 @@ }; })(); -(function(){ - ccs.Armature.CanvasRenderCmd = function(renderableObject){ - cc.Node.CanvasRenderCmd.call(this, renderableObject); +(function () { + ccs.Armature.CanvasRenderCmd = function (renderableObject) { + this._rootCtor(renderableObject); this._needDraw = true; this._realAnchorPointInPoints = new cc.Point(0,0); diff --git a/extensions/cocostudio/armature/CCArmatureWebGLRenderCmd.js b/extensions/cocostudio/armature/CCArmatureWebGLRenderCmd.js index 09b130b951..ba678dbdf9 100644 --- a/extensions/cocostudio/armature/CCArmatureWebGLRenderCmd.js +++ b/extensions/cocostudio/armature/CCArmatureWebGLRenderCmd.js @@ -24,8 +24,8 @@ (function () { - ccs.Armature.WebGLRenderCmd = function(renderableObject){ - cc.Node.WebGLRenderCmd.call(this, renderableObject); + ccs.Armature.WebGLRenderCmd = function (renderableObject) { + this._rootCtor(renderableObject); this._needDraw = true; this._parentCmd = null; diff --git a/extensions/cocostudio/armature/CCBone.js b/extensions/cocostudio/armature/CCBone.js index 842ede37b5..31ce5ae142 100644 --- a/extensions/cocostudio/armature/CCBone.js +++ b/extensions/cocostudio/armature/CCBone.js @@ -717,9 +717,9 @@ ccs.Bone.RenderCmd = { } }; -(function(){ - ccs.Bone.CanvasRenderCmd = function(renderable){ - cc.Node.CanvasRenderCmd.call(this, renderable); +(function () { + ccs.Bone.CanvasRenderCmd = function (renderable) { + this._rootCtor(renderable); this._needDraw = false; }; @@ -731,8 +731,8 @@ ccs.Bone.RenderCmd = { (function () { if (!cc.Node.WebGLRenderCmd) return; - ccs.Bone.WebGLRenderCmd = function(renderable){ - cc.Node.WebGLRenderCmd.call(this, renderable); + ccs.Bone.WebGLRenderCmd = function (renderable) { + this._rootCtor(renderable); this._needDraw = false; }; diff --git a/extensions/cocostudio/armature/display/CCSkinRenderCmd.js b/extensions/cocostudio/armature/display/CCSkinRenderCmd.js index c37bc9d960..44c02a907a 100644 --- a/extensions/cocostudio/armature/display/CCSkinRenderCmd.js +++ b/extensions/cocostudio/armature/display/CCSkinRenderCmd.js @@ -90,8 +90,8 @@ } }; - ccs.Skin.CanvasRenderCmd = function(renderable){ - cc.Sprite.CanvasRenderCmd.call(this, renderable); + ccs.Skin.CanvasRenderCmd = function (renderable) { + this._spriteCmdCtor(renderable); this._realWorldTM = {a: 1, b: 0, c: 0, d: 1, tx: 0, ty: 0}; }; @@ -111,8 +111,8 @@ this._currentRegion.updateRegion(this.getLocalBB(), this._realWorldTM); }; - ccs.Skin.WebGLRenderCmd = function(renderable){ - cc.Sprite.WebGLRenderCmd.call(this, renderable); + ccs.Skin.WebGLRenderCmd = function (renderable) { + this._spriteCmdCtor(renderable); }; proto = ccs.Skin.WebGLRenderCmd.prototype = Object.create(cc.Sprite.WebGLRenderCmd.prototype); diff --git a/extensions/cocostudio/timeline/CCBoneNode.js b/extensions/cocostudio/timeline/CCBoneNode.js index ae9f40af30..7a4d82ab41 100644 --- a/extensions/cocostudio/timeline/CCBoneNode.js +++ b/extensions/cocostudio/timeline/CCBoneNode.js @@ -522,7 +522,7 @@ ccs.BoneNode = (function () { var BoneNodeCanvasCmd = (function () { var BoneNodeCanvasCmd = function (node) { - Node.CanvasRenderCmd.call(this, node); + this._rootCtor(node); this._debug = false; this._color = cc.color.WHITE; this._drawNode = new cc.DrawNode(); @@ -555,7 +555,7 @@ ccs.BoneNode = (function () { var BoneNodeWebGLCmd = (function () { var BoneNodeWebGLCmd = function (node) { - Node.WebGLRenderCmd.call(this, node); + this._rootCtor(node); this._debug = false; this._color = cc.color.WHITE; this._drawNode = new cc.DrawNode(); diff --git a/extensions/editbox/CCEditBox.js b/extensions/editbox/CCEditBox.js index 9cef1b321d..758f04934f 100644 --- a/extensions/editbox/CCEditBox.js +++ b/extensions/editbox/CCEditBox.js @@ -1313,7 +1313,7 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp //define the canvas render command cc.EditBox.CanvasRenderCmd = function (node) { - cc.Node.CanvasRenderCmd.call(this, node); + this._rootCtor(node); this.initializeRenderCmd(node); }; @@ -1366,7 +1366,7 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp //define the webgl render command cc.EditBox.WebGLRenderCmd = function (node) { - cc.Node.WebGLRenderCmd.call(this, node); + this._rootCtor(node); this.initializeRenderCmd(node); }; diff --git a/extensions/gui/scrollview/CCScrollViewCanvasRenderCmd.js b/extensions/gui/scrollview/CCScrollViewCanvasRenderCmd.js index 81b8121ec9..c323eedbd0 100644 --- a/extensions/gui/scrollview/CCScrollViewCanvasRenderCmd.js +++ b/extensions/gui/scrollview/CCScrollViewCanvasRenderCmd.js @@ -22,9 +22,9 @@ THE SOFTWARE. ****************************************************************************/ -(function() { - cc.ScrollView.CanvasRenderCmd = function(renderable){ - cc.Layer.CanvasRenderCmd.call(this, renderable); +(function () { + cc.ScrollView.CanvasRenderCmd = function (renderable) { + this._layerCmdCtor(renderable); this._needDraw = false; this.startCmd = new cc.CustomRenderCmd(this, this._startCmd); diff --git a/extensions/gui/scrollview/CCScrollViewWebGLRenderCmd.js b/extensions/gui/scrollview/CCScrollViewWebGLRenderCmd.js index 1623f6a0a1..78d3affdbc 100644 --- a/extensions/gui/scrollview/CCScrollViewWebGLRenderCmd.js +++ b/extensions/gui/scrollview/CCScrollViewWebGLRenderCmd.js @@ -22,9 +22,9 @@ THE SOFTWARE. ****************************************************************************/ -(function() { - cc.ScrollView.WebGLRenderCmd = function(renderable){ - cc.Layer.WebGLRenderCmd.call(this, renderable); +(function () { + cc.ScrollView.WebGLRenderCmd = function (renderable) { + this._layerCmdCtor(renderable); this._needDraw = false; this.startCmd = new cc.CustomRenderCmd(this, this._startCmd); diff --git a/extensions/spine/CCSkeletonCanvasRenderCmd.js b/extensions/spine/CCSkeletonCanvasRenderCmd.js index d5f1c2c207..073c8ab045 100644 --- a/extensions/spine/CCSkeletonCanvasRenderCmd.js +++ b/extensions/spine/CCSkeletonCanvasRenderCmd.js @@ -22,9 +22,9 @@ THE SOFTWARE. ****************************************************************************/ -(function(){ - sp.Skeleton.CanvasRenderCmd = function(renderableObject){ - cc.Node.CanvasRenderCmd.call(this, renderableObject); +(function () { + sp.Skeleton.CanvasRenderCmd = function (renderableObject) { + this._rootCtor(renderableObject); this._needDraw = true; }; diff --git a/extensions/spine/CCSkeletonWebGLRenderCmd.js b/extensions/spine/CCSkeletonWebGLRenderCmd.js index f659221929..f287f719b6 100644 --- a/extensions/spine/CCSkeletonWebGLRenderCmd.js +++ b/extensions/spine/CCSkeletonWebGLRenderCmd.js @@ -24,7 +24,7 @@ (function () { sp.Skeleton.WebGLRenderCmd = function (renderableObject) { - cc.Node.WebGLRenderCmd.call(this, renderableObject); + this._rootCtor(renderableObject); this._needDraw = true; this._matrix = new cc.math.Matrix4(); this._matrix.identity(); From 926c9e4c953f78a06ae4f3e524ff9e9fd1d7fc41 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Thu, 8 Dec 2016 18:27:48 +0800 Subject: [PATCH 28/42] Improve construction performance in general --- .../CCClippingNodeCanvasRenderCmd.js | 2 +- .../CCClippingNodeWebGLRenderCmd.js | 2 +- .../base-nodes/CCAtlasNodeCanvasRenderCmd.js | 2 +- .../base-nodes/CCAtlasNodeWebGLRenderCmd.js | 2 +- cocos2d/core/base-nodes/CCNode.js | 36 ++++------------ .../core/base-nodes/CCNodeCanvasRenderCmd.js | 43 +++++++++++-------- cocos2d/core/layers/CCLayerCanvasRenderCmd.js | 3 ++ cocos2d/core/textures/CCTexture2D.js | 2 +- cocos2d/particle/CCParticleSystem.js | 37 ++++++++++------ .../CCParticleSystemCanvasRenderCmd.js | 5 ++- .../CCParticleSystemWebGLRenderCmd.js | 7 ++- extensions/ccpool/CCPool.js | 4 +- .../ccui/base-classes/UIWidgetRenderCmd.js | 5 +++ .../ccui/layouts/UILayoutCanvasRenderCmd.js | 15 ++++--- extensions/ccui/layouts/UILayoutManager.js | 2 +- .../ccui/layouts/UILayoutWebGLRenderCmd.js | 20 ++++++--- .../armature/CCArmatureCanvasRenderCmd.js | 2 +- 17 files changed, 105 insertions(+), 84 deletions(-) diff --git a/cocos2d/clipping-nodes/CCClippingNodeCanvasRenderCmd.js b/cocos2d/clipping-nodes/CCClippingNodeCanvasRenderCmd.js index c9208a8c9f..588075a538 100644 --- a/cocos2d/clipping-nodes/CCClippingNodeCanvasRenderCmd.js +++ b/cocos2d/clipping-nodes/CCClippingNodeCanvasRenderCmd.js @@ -25,7 +25,7 @@ //-------------------------- ClippingNode's canvas render cmd -------------------------------- (function () { cc.ClippingNode.CanvasRenderCmd = function (renderable) { - cc.Node.CanvasRenderCmd.call(this, renderable); + this._rootCtor(renderable); this._needDraw = false; this._godhelpme = false; diff --git a/cocos2d/clipping-nodes/CCClippingNodeWebGLRenderCmd.js b/cocos2d/clipping-nodes/CCClippingNodeWebGLRenderCmd.js index 986cbcb887..623f8c30dd 100644 --- a/cocos2d/clipping-nodes/CCClippingNodeWebGLRenderCmd.js +++ b/cocos2d/clipping-nodes/CCClippingNodeWebGLRenderCmd.js @@ -25,7 +25,7 @@ // ------------------------------- ClippingNode's WebGL render cmd ------------------------------ (function () { cc.ClippingNode.WebGLRenderCmd = function (renderable) { - cc.Node.WebGLRenderCmd.call(this, renderable); + this._rootCtor(renderable); this._needDraw = false; this._beforeVisitCmd = new cc.CustomRenderCmd(this, this._onBeforeVisit); diff --git a/cocos2d/core/base-nodes/CCAtlasNodeCanvasRenderCmd.js b/cocos2d/core/base-nodes/CCAtlasNodeCanvasRenderCmd.js index 290cd2a0c3..4fb324f4a9 100644 --- a/cocos2d/core/base-nodes/CCAtlasNodeCanvasRenderCmd.js +++ b/cocos2d/core/base-nodes/CCAtlasNodeCanvasRenderCmd.js @@ -27,7 +27,7 @@ */ (function () { cc.AtlasNode.CanvasRenderCmd = function (renderableObject) { - cc.Node.CanvasRenderCmd.call(this, renderableObject); + this._rootCtor(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 16f27ae09d..8fce00f8da 100644 --- a/cocos2d/core/base-nodes/CCAtlasNodeWebGLRenderCmd.js +++ b/cocos2d/core/base-nodes/CCAtlasNodeWebGLRenderCmd.js @@ -27,7 +27,7 @@ */ (function () { cc.AtlasNode.WebGLRenderCmd = function (renderableObject) { - cc.Node.WebGLRenderCmd.call(this, renderableObject); + this._rootCtor(renderableObject); this._needDraw = true; this._textureAtlas = null; this._colorUnmodified = cc.color.WHITE; diff --git a/cocos2d/core/base-nodes/CCNode.js b/cocos2d/core/base-nodes/CCNode.js index c8f587ca27..2cfbd4dd07 100644 --- a/cocos2d/core/base-nodes/CCNode.js +++ b/cocos2d/core/base-nodes/CCNode.js @@ -163,12 +163,10 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{ //since 2.0 api _reorderChildDirty: false, - _shaderProgram: null, arrivalOrder: 0, _actionManager: null, _scheduler: null, - _eventDispatcher: null, _additionalTransformDirty: false, _additionalTransform: null, @@ -190,32 +188,23 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{ * Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function. * @function */ - ctor: function(){ - this._initNode(); - this._initRendererCmd(); - }, - - _initNode: function () { + ctor: function () { var _t = this; _t._anchorPoint = cc.p(0, 0); _t._contentSize = cc.size(0, 0); _t._position = cc.p(0, 0); - _t._normalizedPosition = cc.p(0,0); + _t._normalizedPosition = cc.p(0, 0); _t._children = []; var director = cc.director; - _t._actionManager = director.getActionManager(); - _t._scheduler = director.getScheduler(); _t._additionalTransform = cc.affineTransformMakeIdentity(); if (cc.ComponentContainer) { _t._componentContainer = new cc.ComponentContainer(_t); } - - this._realOpacity = 255; this._realColor = cc.color(255, 255, 255, 255); - this._cascadeColorEnabled = false; - this._cascadeOpacityEnabled = false; + + this._renderCmd = this._createRenderCmd(); }, /** @@ -224,7 +213,6 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{ * @returns {boolean} Whether the initialization was successful. */ init: function () { - //this._initNode(); //this has been called in ctor. return true; }, @@ -649,12 +637,12 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{ setPosition: function (newPosOrxValue, yValue) { var locPosition = this._position; if (yValue === undefined) { - if(locPosition.x === newPosOrxValue.x && locPosition.y === newPosOrxValue.y) + if (locPosition.x === newPosOrxValue.x && locPosition.y === newPosOrxValue.y) return; locPosition.x = newPosOrxValue.x; locPosition.y = newPosOrxValue.y; } else { - if(locPosition.x === newPosOrxValue && locPosition.y === yValue) + if (locPosition.x === newPosOrxValue && locPosition.y === yValue) return; locPosition.x = newPosOrxValue; locPosition.y = yValue; @@ -1114,9 +1102,7 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{ * @return {cc.ActionManager} A CCActionManager object. */ getActionManager: function () { - if (!this._actionManager) - this._actionManager = cc.director.getActionManager(); - return this._actionManager; + return this._actionManager || cc.director.getActionManager(); }, /** @@ -1140,9 +1126,7 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{ * @return {cc.Scheduler} A CCScheduler object. */ getScheduler: function () { - if (!this._scheduler) - this._scheduler = cc.director.getScheduler(); - return this._scheduler; + return this._scheduler || cc.director.getScheduler(); }, /** @@ -2425,10 +2409,6 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{ return false; }, - _initRendererCmd: function(){ - this._renderCmd = cc.renderer.getRenderCmd(this); - }, - _createRenderCmd: function () { if (cc._renderType === cc.game.RENDER_TYPE_CANVAS) return new cc.Node.CanvasRenderCmd(this); diff --git a/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js b/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js index 23151853d7..cd4db111e0 100644 --- a/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js +++ b/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js @@ -83,28 +83,26 @@ function transformChildTree(root) { //-------------------------Base ------------------------- cc.Node.RenderCmd = function (renderable) { - this._dirtyFlag = 1; //need update the transform at first. - this._savedDirtyFlag = true; - this._node = renderable; - this._needDraw = false; - this._anchorPointInPoints = new cc.Point(0, 0); - - this._transform = {a: 1, b: 0, c: 0, d: 1, tx: 0, ty: 0}; - this._worldTransform = {a: 1, b: 0, c: 0, d: 1, tx: 0, ty: 0}; - this._inverse = {a: 1, b: 0, c: 0, d: 1, tx: 0, ty: 0}; - - this._displayedOpacity = 255; + this._anchorPointInPoints = {x: 0, y: 0}; this._displayedColor = cc.color(255, 255, 255, 255); - this._cascadeColorEnabledDirty = false; - this._cascadeOpacityEnabledDirty = false; - - this._curLevel = -1; }; cc.Node.RenderCmd.prototype = { constructor: cc.Node.RenderCmd, + _needDraw: false, + _dirtyFlag: 1, + _curLevel: -1, + + _displayedOpacity: 255, + _cascadeColorEnabledDirty: false, + _cascadeOpacityEnabledDirty: false, + + _transform: null, + _worldTransform: null, + _inverse: null, + needDraw: function () { return this._needDraw; }, @@ -133,8 +131,12 @@ cc.Node.RenderCmd.prototype = { }, getParentToNodeTransform: function () { - if (this._dirtyFlag & cc.Node._dirtyFlags.transformDirty) - this._inverse = cc.affineTransformInvert(this.getNodeToParentTransform()); + if (!this._inverse) { + this._inverse = {a: 1, b: 0, c: 0, d: 1, tx: 0, ty: 0}; + } + if (this._dirtyFlag & cc.Node._dirtyFlags.transformDirty) { + cc.affineTransformInvertOut(this.getNodeToParentTransform(), this._inverse); + } return this._inverse; }, @@ -161,6 +163,11 @@ cc.Node.RenderCmd.prototype = { }, transform: function (parentCmd, recursive) { + if (!this._transform) { + this._transform = {a: 1, b: 0, c: 0, d: 1, tx: 0, ty: 0}; + this._worldTransform = {a: 1, b: 0, c: 0, d: 1, tx: 0, ty: 0}; + } + var node = this._node, pt = parentCmd ? parentCmd._worldTransform : null, t = this._transform, @@ -302,7 +309,7 @@ cc.Node.RenderCmd.prototype = { }, getNodeToParentTransform: function () { - if (this._dirtyFlag & cc.Node._dirtyFlags.transformDirty) { + if (!this._transform || this._dirtyFlag & cc.Node._dirtyFlags.transformDirty) { this.transform(); } return this._transform; diff --git a/cocos2d/core/layers/CCLayerCanvasRenderCmd.js b/cocos2d/core/layers/CCLayerCanvasRenderCmd.js index 021957242b..a6f7fd4cff 100644 --- a/cocos2d/core/layers/CCLayerCanvasRenderCmd.js +++ b/cocos2d/core/layers/CCLayerCanvasRenderCmd.js @@ -80,6 +80,9 @@ }; proto.transform = function (parentCmd, recursive) { + if (!this._worldTransform) { + this._worldTransform = {a: 1, b: 0, c: 0, d: 1, tx: 0, ty: 0}; + } var wt = this._worldTransform; var a = wt.a, b = wt.b, c = wt.c, d = wt.d, tx = wt.tx, ty = wt.ty; this.originTransform(parentCmd, recursive); diff --git a/cocos2d/core/textures/CCTexture2D.js b/cocos2d/core/textures/CCTexture2D.js index d3067fcf29..41b1726168 100644 --- a/cocos2d/core/textures/CCTexture2D.js +++ b/cocos2d/core/textures/CCTexture2D.js @@ -98,7 +98,7 @@ cc.PVRHaveAlphaPremultiplied_ = false; cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () { - if(cc._renderType === cc.game.RENDER_TYPE_CANVAS) { + if (cc._renderType === cc.game.RENDER_TYPE_CANVAS) { var proto = { _contentSize: null, diff --git a/cocos2d/particle/CCParticleSystem.js b/cocos2d/particle/CCParticleSystem.js index 2e8d079d1a..01e2759c33 100644 --- a/cocos2d/particle/CCParticleSystem.js +++ b/cocos2d/particle/CCParticleSystem.js @@ -490,8 +490,9 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * sourcePosition of the emitter setter * @param sourcePosition */ - setSourcePosition:function (sourcePosition) { - this._sourcePosition = sourcePosition; + setSourcePosition: function (sourcePosition) { + this._sourcePosition.x = sourcePosition.x; + this._sourcePosition.y = sourcePosition.y; }, /** @@ -507,7 +508,8 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * @param {cc.Point} posVar */ setPosVar: function (posVar) { - this._posVar = posVar; + this._posVar.x = posVar.x; + this._posVar.y = posVar.y; }, /** @@ -956,7 +958,10 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * @param {cc.Color} startColor */ setStartColor: function (startColor) { - this._startColor = cc.color(startColor); + this._startColor.r = startColor.r; + this._startColor.g = startColor.g; + this._startColor.b = startColor.b; + this._startColor.a = startColor.a; }, /** @@ -972,7 +977,10 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * @param {cc.Color} startColorVar */ setStartColorVar: function (startColorVar) { - this._startColorVar = cc.color(startColorVar); + this._startColorVar.r = startColorVar.r; + this._startColorVar.g = startColorVar.g; + this._startColorVar.b = startColorVar.b; + this._startColorVar.a = startColorVar.a; }, /** @@ -988,7 +996,10 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * @param {cc.Color} endColor */ setEndColor: function (endColor) { - this._endColor = cc.color(endColor); + this._endColor.r = endColor.r; + this._endColor.g = endColor.g; + this._endColor.b = endColor.b; + this._endColor.a = endColor.a; }, /** @@ -1004,7 +1015,10 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ * @param {cc.Color} endColorVar */ setEndColorVar: function (endColorVar) { - this._endColorVar = cc.color(endColorVar); + this._endColorVar.r = endColorVar.r; + this._endColorVar.g = endColorVar.g; + this._endColorVar.b = endColorVar.b; + this._endColorVar.a = endColorVar.a; }, /** @@ -1391,13 +1405,8 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ locModeA.tangentialAccelVar = (pszTmp) ? parseFloat(pszTmp) : 0; // rotation is dir - var locRotationIsDir = locValueForKey("rotationIsDir", dictionary); - if (locRotationIsDir !== null) { - locRotationIsDir = locRotationIsDir.toString().toLowerCase(); - locModeA.rotationIsDir = (locRotationIsDir === "true" || locRotationIsDir === "1"); - } - else - locModeA.rotationIsDir = false; + var locRotationIsDir = locValueForKey("rotationIsDir", dictionary).toLowerCase(); + locModeA.rotationIsDir = (locRotationIsDir != null && (locRotationIsDir === "true" || locRotationIsDir === "1")); } else if (this.emitterMode === cc.ParticleSystem.MODE_RADIUS) { // or Mode B: radius movement var locModeB = this.modeB; diff --git a/cocos2d/particle/CCParticleSystemCanvasRenderCmd.js b/cocos2d/particle/CCParticleSystemCanvasRenderCmd.js index 5165b69728..781baf7004 100644 --- a/cocos2d/particle/CCParticleSystemCanvasRenderCmd.js +++ b/cocos2d/particle/CCParticleSystemCanvasRenderCmd.js @@ -34,7 +34,7 @@ this._shapeType = cc.ParticleSystem.BALL_SHAPE; this._pointRect = cc.rect(0, 0, 0, 0); - this._tintCache = document.createElement("canvas"); + this._tintCache = null; }; var proto = cc.ParticleSystem.CanvasRenderCmd.prototype = Object.create(cc.Node.CanvasRenderCmd.prototype); proto.constructor = cc.ParticleSystem.CanvasRenderCmd; @@ -144,6 +144,9 @@ }; proto._changeTextureColor = function (texture, color, rect) { + if (!this._tintCache) { + this._tintCache = document.createElement("canvas"); + } var tintCache = this._tintCache; var textureContentSize = texture.getContentSize(); tintCache.width = textureContentSize.width; diff --git a/cocos2d/particle/CCParticleSystemWebGLRenderCmd.js b/cocos2d/particle/CCParticleSystemWebGLRenderCmd.js index 52a85c542b..892f8a2d21 100644 --- a/cocos2d/particle/CCParticleSystemWebGLRenderCmd.js +++ b/cocos2d/particle/CCParticleSystemWebGLRenderCmd.js @@ -30,8 +30,7 @@ this._rootCtor(renderable); this._needDraw = true; - this._matrix = new cc.math.Matrix4(); - this._matrix.identity(); + this._matrix = null; this._buffersVBO = [0, 0]; this._quads = []; @@ -193,6 +192,10 @@ var gl = ctx || cc._renderContext; + if (!this._matrix) { + this._matrix = new cc.math.Matrix4(); + this._matrix.identity(); + } var wt = this._worldTransform; this._matrix.mat[0] = wt.a; this._matrix.mat[4] = wt.c; diff --git a/extensions/ccpool/CCPool.js b/extensions/ccpool/CCPool.js index 489ae1d9c6..2159c091c8 100644 --- a/extensions/ccpool/CCPool.js +++ b/extensions/ccpool/CCPool.js @@ -62,7 +62,7 @@ cc.pool = /** @lends cc.pool# */{ putInPool: function (obj) { var pid = obj.constructor.prototype['__pid']; if (!pid) { - var desc = { writable: true, enumerable: false, configurable: true }; + var desc = {writable: true, enumerable: false, configurable: true}; desc.value = ClassManager.getNewID(); Object.defineProperty(obj.constructor.prototype, '__pid', desc); } @@ -143,4 +143,4 @@ cc.pool = /** @lends cc.pool# */{ } this._pool = {}; } -}; \ No newline at end of file +}; diff --git a/extensions/ccui/base-classes/UIWidgetRenderCmd.js b/extensions/ccui/base-classes/UIWidgetRenderCmd.js index 14b69c6e01..bc3d7236d1 100644 --- a/extensions/ccui/base-classes/UIWidgetRenderCmd.js +++ b/extensions/ccui/base-classes/UIWidgetRenderCmd.js @@ -41,6 +41,11 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () { }; proto.transform = function (parentCmd, recursive) { + if (!this._transform) { + this._transform = {a: 1, b: 0, c: 0, d: 1, tx: 0, ty: 0}; + this._worldTransform = {a: 1, b: 0, c: 0, d: 1, tx: 0, ty: 0}; + } + var node = this._node; if (node._visible && node._running) { node._adaptRenderers(); diff --git a/extensions/ccui/layouts/UILayoutCanvasRenderCmd.js b/extensions/ccui/layouts/UILayoutCanvasRenderCmd.js index bbde61bc21..70ff689777 100644 --- a/extensions/ccui/layouts/UILayoutCanvasRenderCmd.js +++ b/extensions/ccui/layouts/UILayoutCanvasRenderCmd.js @@ -28,12 +28,9 @@ this._pNodeCmdCtor(renderable); this._needDraw = false; - this._rendererSaveCmd = new cc.CustomRenderCmd(this, this._onRenderSaveCmd); - this._rendererClipCmd = new cc.CustomRenderCmd(this, this._onRenderClipCmd); - this._rendererRestoreCmd = new cc.CustomRenderCmd(this, this._onRenderRestoreCmd); - this._rendererSaveCmd._canUseDirtyRegion = true; - this._rendererClipCmd._canUseDirtyRegion = true; - this._rendererRestoreCmd._canUseDirtyRegion = true; + this._rendererSaveCmd = null; + this._rendererClipCmd = null; + this._rendererRestoreCmd = null; }; var proto = ccui.Layout.CanvasRenderCmd.prototype = Object.create(ccui.ProtectedNode.CanvasRenderCmd.prototype); @@ -115,7 +112,11 @@ if (!node._clippingStencil || !node._clippingStencil.isVisible()) return; - this._syncStatus(parentCmd); + if (!this._rendererSaveCmd) { + this._rendererSaveCmd = new cc.CustomRenderCmd(this, this._onRenderSaveCmd); + this._rendererClipCmd = new cc.CustomRenderCmd(this, this._onRenderClipCmd); + this._rendererRestoreCmd = new cc.CustomRenderCmd(this, this._onRenderRestoreCmd); + } cc.renderer.pushRenderCommand(this._rendererSaveCmd); node._clippingStencil.visit(this); diff --git a/extensions/ccui/layouts/UILayoutManager.js b/extensions/ccui/layouts/UILayoutManager.js index 7c71a9496e..9f89d13e75 100644 --- a/extensions/ccui/layouts/UILayoutManager.js +++ b/extensions/ccui/layouts/UILayoutManager.js @@ -197,7 +197,7 @@ ccui.relativeLayoutManager = /** @lends ccui.relativeLayoutManager# */{ var child = locChildren[i]; if (child){ var rlayoutParameter = child.getLayoutParameter(); - if (rlayoutParameter && rlayoutParameter.getRelativeName() === relativeName) { + if (rlayoutParameter && rlayoutParameter.getRelativeName() === relativeName) { relativeWidget = child; this._relativeWidgetLP = rlayoutParameter; break; diff --git a/extensions/ccui/layouts/UILayoutWebGLRenderCmd.js b/extensions/ccui/layouts/UILayoutWebGLRenderCmd.js index 9c9ef2dfab..4a05a9d5f1 100644 --- a/extensions/ccui/layouts/UILayoutWebGLRenderCmd.js +++ b/extensions/ccui/layouts/UILayoutWebGLRenderCmd.js @@ -36,11 +36,11 @@ this._mask_layer_le = 0; - this._beforeVisitCmdStencil = new cc.CustomRenderCmd(this, this._onBeforeVisitStencil); - this._afterDrawStencilCmd = new cc.CustomRenderCmd(this, this._onAfterDrawStencil); - this._afterVisitCmdStencil = new cc.CustomRenderCmd(this, this._onAfterVisitStencil); - this._beforeVisitCmdScissor = new cc.CustomRenderCmd(this, this._onBeforeVisitScissor); - this._afterVisitCmdScissor = new cc.CustomRenderCmd(this, this._onAfterVisitScissor); + this._beforeVisitCmdStencil = null; + this._afterDrawStencilCmd = null; + this._afterVisitCmdStencil = null; + this._beforeVisitCmdScissor = null; + this._afterVisitCmdScissor = null; }; var proto = ccui.Layout.WebGLRenderCmd.prototype = Object.create(ccui.ProtectedNode.WebGLRenderCmd.prototype); @@ -188,6 +188,12 @@ return; } + if (!this._beforeVisitCmdStencil) { + this._beforeVisitCmdStencil = new cc.CustomRenderCmd(this, this._onBeforeVisitStencil); + this._afterDrawStencilCmd = new cc.CustomRenderCmd(this, this._onAfterDrawStencil); + this._afterVisitCmdStencil = new cc.CustomRenderCmd(this, this._onAfterVisitStencil); + } + cc.renderer.pushRenderCommand(this._beforeVisitCmdStencil); //optimize performance for javascript @@ -236,6 +242,10 @@ }; proto.scissorClippingVisit = function (parentCmd) { + if (!this._beforeVisitCmdScissor) { + this._beforeVisitCmdScissor = new cc.CustomRenderCmd(this, this._onBeforeVisitScissor); + this._afterVisitCmdScissor = new cc.CustomRenderCmd(this, this._onAfterVisitScissor); + } cc.renderer.pushRenderCommand(this._beforeVisitCmdScissor); this.pNodeVisit(parentCmd); cc.renderer.pushRenderCommand(this._afterVisitCmdScissor); diff --git a/extensions/cocostudio/armature/CCArmatureCanvasRenderCmd.js b/extensions/cocostudio/armature/CCArmatureCanvasRenderCmd.js index db6954e66a..97617db4f5 100644 --- a/extensions/cocostudio/armature/CCArmatureCanvasRenderCmd.js +++ b/extensions/cocostudio/armature/CCArmatureCanvasRenderCmd.js @@ -46,7 +46,7 @@ this._rootCtor(renderableObject); this._needDraw = true; - this._realAnchorPointInPoints = new cc.Point(0,0); + this._realAnchorPointInPoints = new cc.Point(0, 0); this._canUseDirtyRegion = true; this._startRenderCmd = new cc.CustomRenderCmd(this, this._startCmdCallback); this._RestoreRenderCmd = new cc.CustomRenderCmd(this, this._RestoreCmdCallback); From 59d4645c7f14cccdeaab4d68cb462b7b0a90e434 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Thu, 8 Dec 2016 22:47:17 +0800 Subject: [PATCH 29/42] Improve label adaptation performance --- cocos2d/core/labelttf/CCLabelTTF.js | 4 +- .../labelttf/CCLabelTTFCanvasRenderCmd.js | 49 +++++++++++++------ cocos2d/labels/CCLabelBMFont.js | 31 +++++++----- 3 files changed, 57 insertions(+), 27 deletions(-) diff --git a/cocos2d/core/labelttf/CCLabelTTF.js b/cocos2d/core/labelttf/CCLabelTTF.js index 2342fc555c..6d367baee8 100644 --- a/cocos2d/core/labelttf/CCLabelTTF.js +++ b/cocos2d/core/labelttf/CCLabelTTF.js @@ -133,7 +133,9 @@ cc.LabelTTF = cc.Sprite.extend(/** @lends cc.LabelTTF# */{ this._renderCmd._setFontStyle(this._fontName, fontSize, this._fontStyle, this._fontWeight); this.string = strInfo; this._renderCmd._setColorsString(); - this._renderCmd._updateTexture(); + if (this._string) { + this._renderCmd._updateTexture(); + } this._setUpdateTextureDirty(); // Needed for high dpi text. diff --git a/cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js b/cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js index 88ba1933a9..d12ea0896a 100644 --- a/cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js +++ b/cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js @@ -111,6 +111,7 @@ cc.LabelTTF._firsrEnglish = /^[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]/; this._isMultiLine = false; this._measureConfig(); + var textWidthCache = {}; if (locDimensionsWidth !== 0) { // Content processing this._strings = node._string.split('\n'); @@ -121,7 +122,13 @@ cc.LabelTTF._firsrEnglish = /^[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]/; } else { this._strings = node._string.split('\n'); for (i = 0, strLength = this._strings.length; i < strLength; i++) { - locLineWidth.push(this._measure(this._strings[i])); + if(this._strings[i]) { + var measuredWidth = this._measure(this._strings[i]); + locLineWidth.push(measuredWidth); + textWidthCache[this._strings[i]] = measuredWidth; + } else { + locLineWidth.push(0); + } } } @@ -139,14 +146,18 @@ cc.LabelTTF._firsrEnglish = /^[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]/; //get offset for stroke and shadow if (locDimensionsWidth === 0) { - if (this._isMultiLine) - locSize = cc.size( - Math.ceil(Math.max.apply(Math, locLineWidth) + locStrokeShadowOffsetX), - Math.ceil((this._fontClientHeight * pixelRatio * this._strings.length) + locStrokeShadowOffsetY)); - else - locSize = cc.size( - Math.ceil(this._measure(node._string) + locStrokeShadowOffsetX), - Math.ceil(this._fontClientHeight * pixelRatio + locStrokeShadowOffsetY)); + if (this._isMultiLine) { + locSize = cc.size(Math.ceil(Math.max.apply(Math, locLineWidth) + locStrokeShadowOffsetX), + Math.ceil((this._fontClientHeight * pixelRatio * this._strings.length) + locStrokeShadowOffsetY)); + } + else { + var measuredWidth = textWidthCache[node._string]; + if(!measuredWidth && node._string) { + measuredWidth = this._measure(node._string); + } + locSize = cc.size(Math.ceil((measuredWidth ? measuredWidth : 0) + locStrokeShadowOffsetX), + Math.ceil(this._fontClientHeight * pixelRatio + locStrokeShadowOffsetY)); + } } else { if (node._dimensions.height === 0) { if (this._isMultiLine) @@ -381,7 +392,7 @@ cc.LabelTTF._firsrEnglish = /^[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]/; this._labelContext = locCanvas.getContext("2d"); }; - cc.LabelTTF.CacheRenderCmd.prototype = Object.create( cc.LabelTTF.RenderCmd.prototype); + cc.LabelTTF.CacheRenderCmd.prototype = Object.create(cc.LabelTTF.RenderCmd.prototype); cc.inject(cc.LabelTTF.RenderCmd.prototype, cc.LabelTTF.CacheRenderCmd.prototype); var proto = cc.LabelTTF.CacheRenderCmd.prototype; @@ -397,7 +408,7 @@ cc.LabelTTF._firsrEnglish = /^[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]/; var locContext = this._labelContext, locLabelCanvas = this._labelCanvas; - if(!node._texture){ + if (!node._texture) { var labelTexture = new cc.Texture2D(); labelTexture.initWithElement(this._labelCanvas); node.setTexture(labelTexture); @@ -430,7 +441,11 @@ cc.LabelTTF._firsrEnglish = /^[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]/; }; proto._measure = function (text) { - return this._labelContext.measureText(text).width; + if (text) { + return this._labelContext.measureText(text).width; + } else { + return 0; + } }; })(); @@ -462,9 +477,13 @@ cc.LabelTTF._firsrEnglish = /^[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]/; }; proto._measure = function (text) { - var context = cc._renderContext.getContext(); - context.font = this._fontStyleStr; - return context.measureText(text).width; + if(text) { + var context = cc._renderContext.getContext(); + context.font = this._fontStyleStr; + return context.measureText(text).width; + } else { + return 0; + } }; proto._updateTexture = function () { diff --git a/cocos2d/labels/CCLabelBMFont.js b/cocos2d/labels/CCLabelBMFont.js index d583bfef24..7c261a14b7 100644 --- a/cocos2d/labels/CCLabelBMFont.js +++ b/cocos2d/labels/CCLabelBMFont.js @@ -128,7 +128,9 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{ } } if (this._textureLoaded) { - this.createFontChars(); + if(this._string && this._string.length > 0) { + this.createFontChars(); + } if (needUpdateLabel) this.updateLabel(); } @@ -273,6 +275,9 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{ * updates the font chars based on the string to render */ createFontChars: function () { + var locStr = this._string; + var stringLen = locStr ? locStr.length : 0; + var self = this; var cmd = this._renderCmd; var locTexture = cmd._texture || this._texture; @@ -285,11 +290,6 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{ var quantityOfLines = 1; - var locStr = self._string; - var stringLen = locStr ? locStr.length : 0; - - if (stringLen === 0) - return; var i, locCfg = self._config, locKerningDict = locCfg.kerningDict, locCommonH = locCfg.commonHeight, locFontDict = locCfg.fontDefDictionary; @@ -383,13 +383,17 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{ var self = this; var locChildren = self._children; if (locChildren) { - for (var i = 0, li = locChildren.length; i < li; i++) { + var length = locChildren.length; + for (var i = 0, li = length; i < li; i++) { var node = locChildren[i]; if (node) node.visible = false; } } - if (self._config) - self.createFontChars(); + if (self._config) { + if(self._string && self._string.length > 0) { + self.createFontChars(); + } + } if (!fromUpdate) self.updateLabel(); @@ -715,7 +719,10 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{ var self1 = this; self1._textureLoaded = true; self1.setTexture(sender); - self1.createFontChars(); + if(self1._string && self1._string.length > 0) { + self1.createFontChars(); + } + self1._changeTextureColor(); self1.updateLabel(); @@ -723,7 +730,9 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{ }, self); } else { self.setTexture(texture); - self.createFontChars(); + if(self._string && self._string.length > 0) { + self.createFontChars(); + } } } }, From c1c76b0003242d0df65b2b5d32ca12504f75b20a Mon Sep 17 00:00:00 2001 From: pandamicro Date: Thu, 8 Dec 2016 22:50:11 +0800 Subject: [PATCH 30/42] Reimplement UIScale9Sprite using creator approach --- cocos2d/core/renderer/RendererWebGL.js | 5 +- .../ccui/base-classes/UIScale9Sprite.js | 1504 +++++++---------- .../UIScale9SpriteCanvasRenderCmd.js | 240 ++- .../UIScale9SpriteWebGLRenderCmd.js | 250 ++- 4 files changed, 817 insertions(+), 1182 deletions(-) diff --git a/cocos2d/core/renderer/RendererWebGL.js b/cocos2d/core/renderer/RendererWebGL.js index 327180c654..593a4434ef 100644 --- a/cocos2d/core/renderer/RendererWebGL.js +++ b/cocos2d/core/renderer/RendererWebGL.js @@ -274,7 +274,10 @@ return { // Check batching var node = cmd._node; - var texture = node._texture; + var texture = node._texture || (node._spriteFrame ? node._spriteFrame._texture : null); + if (!texture) { + return; + } var blendSrc = node._blendFunc.src; var blendDst = node._blendFunc.dst; var shader = cmd._shaderProgram; diff --git a/extensions/ccui/base-classes/UIScale9Sprite.js b/extensions/ccui/base-classes/UIScale9Sprite.js index dcb9215268..f7fcbb08af 100644 --- a/extensions/ccui/base-classes/UIScale9Sprite.js +++ b/extensions/ccui/base-classes/UIScale9Sprite.js @@ -3,6 +3,7 @@ Copyright (c) 2011-2012 cocos2d-x.org Copyright (c) 2013-2014 Chukong Technologies Inc. Copyright (c) 2012 Neofect. All rights reserved. + Copyright (c) 2016 zilongshanren. All rights reserved. http://www.cocos2d-x.org @@ -26,6 +27,293 @@ Created by Jung Sang-Taik on 2012-03-16 ****************************************************************************/ +(function () { + +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 FIX_ARTIFACTS_BY_STRECHING_TEXEL = cc.FIX_ARTIFACTS_BY_STRECHING_TEXEL, cornerId = [], webgl; + + +var simpleQuadGenerator = { + _rebuildQuads_base: function (sprite, spriteFrame, contentSize, isTrimmedContentSize) { + //build vertices + var vertices = sprite._vertices, + wt = sprite._renderCmd._worldTransform, + l, b, r, t; + if (isTrimmedContentSize) { + l = 0; + b = 0; + r = contentSize.width; + t = contentSize.height; + } else { + var originalSize = spriteFrame._originalSize; + var rect = spriteFrame._rect; + var offset = spriteFrame._offset; + var scaleX = contentSize.width / originalSize.width; + var scaleY = contentSize.height / originalSize.height; + var trimmLeft = offset.x + (originalSize.width - rect.width) / 2; + var trimmRight = offset.x - (originalSize.width - rect.width) / 2; + var trimmedBottom = offset.y + (originalSize.height - rect.height) / 2; + var trimmedTop = offset.y - (originalSize.height - rect.height) / 2; + + l = trimmLeft * scaleX; + b = trimmedBottom * scaleY; + r = contentSize.width + trimmRight * scaleX; + t = contentSize.height + trimmedTop * scaleY; + } + + 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 { + vertices[0] = l; + vertices[1] = b; + vertices[2] = r; + vertices[3] = b; + vertices[4] = l; + vertices[5] = t; + vertices[6] = r; + vertices[7] = t; + } + + cornerId[0] = 0; + cornerId[1] = 2; + cornerId[2] = 4; + cornerId[3] = 6; + + //build uvs + if (sprite._uvsDirty) { + this._calculateUVs(sprite, spriteFrame); + } + + sprite._vertCount = 4; + }, + + _calculateUVs: function (sprite, spriteFrame) { + var uvs = sprite._uvs; + var atlasWidth = spriteFrame._texture._pixelsWide; + var atlasHeight = spriteFrame._texture._pixelsHigh; + 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; + var texelCorrect = FIX_ARTIFACTS_BY_STRECHING_TEXEL ? 0.5 : 0; + + if (spriteFrame._rotated) { + l = (textureRect.x + texelCorrect) / atlasWidth; + b = (textureRect.y + textureRect.width - texelCorrect) / atlasHeight; + r = (textureRect.x + textureRect.height - texelCorrect) / atlasWidth; + t = (textureRect.y + texelCorrect) / 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 + texelCorrect) / atlasWidth; + b = (textureRect.y + textureRect.height - texelCorrect) / atlasHeight; + r = (textureRect.x + textureRect.width - texelCorrect) / atlasWidth; + t = (textureRect.y + texelCorrect) / 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 = { + x: new Array(4), + y: new Array(4), + _rebuildQuads_base: function (sprite, spriteFrame, contentSize, insetLeft, insetRight, insetTop, insetBottom) { + //build vertices + var vertices = sprite._vertices; + var wt = sprite._renderCmd._worldTransform; + var leftWidth, centerWidth, rightWidth; + var topHeight, centerHeight, bottomHeight; + var rect = spriteFrame._rect; + + leftWidth = insetLeft; + rightWidth = insetRight; + centerWidth = rect.width - leftWidth - rightWidth; + topHeight = insetTop; + bottomHeight = insetBottom; + centerHeight = rect.height - topHeight - bottomHeight; + + var preferSize = contentSize; + var sizableWidth = preferSize.width - leftWidth - rightWidth; + var sizableHeight = preferSize.height - topHeight - bottomHeight; + var xScale = preferSize.width / (leftWidth + rightWidth); + var yScale = preferSize.height / (topHeight + bottomHeight); + xScale = xScale > 1 ? 1 : xScale; + yScale = yScale > 1 ? 1 : yScale; + sizableWidth = sizableWidth < 0 ? 0 : sizableWidth; + sizableHeight = sizableHeight < 0 ? 0 : sizableHeight; + var x = this.x; + var y = this.y; + 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; + + 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; + } + } + } + + cornerId[0] = 0; + cornerId[1] = 6; + cornerId[2] = 24; + cornerId[3] = 30; + + //build uvs + if (sprite._uvsDirty) { + this._calculateUVs(sprite, 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._pixelsWide; + var atlasHeight = spriteFrame._texture._pixelsHigh; + + //caculate texture coordinate + var leftWidth, centerWidth, rightWidth; + var topHeight, centerHeight, bottomHeight; + var textureRect = spriteFrame._rect; + + leftWidth = insetLeft; + rightWidth = insetRight; + centerWidth = rect.width - leftWidth - rightWidth; + topHeight = insetTop; + bottomHeight = insetBottom; + centerHeight = rect.height - topHeight - bottomHeight; + + 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 u = this.x; + var v = this.y; + var texelCorrect = FIX_ARTIFACTS_BY_STRECHING_TEXEL ? 0.5 : 0; + var offset = 0, row, col; + + if (spriteFrame._rotated) { + u[0] = (textureRect.x + texelCorrect) / atlasWidth; + u[1] = (bottomHeight + textureRect.x) / atlasWidth; + u[2] = (bottomHeight + centerHeight + textureRect.x) / atlasWidth; + u[3] = (textureRect.x + textureRect.height - texelCorrect) / atlasWidth; + + v[3] = (textureRect.y + texelCorrect) / atlasHeight; + v[2] = (leftWidth + textureRect.y) / atlasHeight; + v[1] = (leftWidth + centerWidth + textureRect.y) / atlasHeight; + v[0] = (textureRect.y + textureRect.width - texelCorrect) / 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 { + u[0] = (textureRect.x + texelCorrect) / atlasWidth; + u[1] = (leftWidth + textureRect.x) / atlasWidth; + u[2] = (leftWidth + centerWidth + textureRect.x) / atlasWidth; + u[3] = (textureRect.x + textureRect.width - texelCorrect) / atlasWidth; + + v[3] = (textureRect.y + texelCorrect) / atlasHeight; + v[2] = (topHeight + textureRect.y) / atlasHeight; + v[1] = (topHeight + centerHeight + textureRect.y) / atlasHeight; + v[0] = (textureRect.y + textureRect.height - texelCorrect) / atlasHeight; + + for (row = 0; row < 4; row++) { + for (col = 0; col < 4; col++) { + uvs[offset] = u[col]; + uvs[offset+1] = v[row]; + offset += 2; + } + } + } + } +}; /** *

@@ -35,7 +323,6 @@ * to specific areas of a sprite. With 9-slice scaling (3x3 grid),
* you can ensure that the sprite does not become distorted when
* scaled.
- * @note: it will refactor in v3.1
* @see http://yannickloriot.com/library/ios/cccontrolextension/Classes/CCScale9Sprite.html
*

* @class @@ -50,161 +337,39 @@ */ ccui.Scale9Sprite = cc.Scale9Sprite = cc.Node.extend(/** @lends ccui.Scale9Sprite# */{ - _spriteRect: null, - _capInsetsInternal: null, - _positionsAreDirty: false, - + //resource data, could be async loaded. + _spriteFrame: null, _scale9Image: null, - _topLeft: null, - _top: null, - _topRight: null, - _left: null, - _centre: null, - _right: null, - _bottomLeft: null, - _bottom: null, - _bottomRight: null, - - _scale9Enabled: true, - _brightState: 0, - _renderers: null, - _opacityModifyRGB: false, - - _originalSize: null, - _preferredSize: null, - _opacity: 0, - _color: null, - _capInsets: null, + //scale 9 data _insetLeft: 0, - _insetTop: 0, _insetRight: 0, + _insetTop: 0, _insetBottom: 0, - - _spriteFrameRotated: false, - _textureLoaded:false, - _className:"Scale9Sprite", + //blend function + _blendFunc: null, + //sliced or simple + _renderingType: 1, + //bright or not + _brightState: 0, + _opacityModifyRGB: false, + //rendering quads shared by canvas and webgl + _rawVerts: null, + _rawUvs: null, + _vertices: null, + _uvs: null, + _vertCount: 0, + _quadsDirty: true, + _uvsDirty: true, + _isTriangle: false, + _isTrimmedContentSize: false, //v3.3 _flippedX: false, _flippedY: false, /** - * return texture is loaded - * @returns {boolean} - */ - textureLoaded:function(){ - return this._textureLoaded; - }, - - /** - * add texture loaded event listener - * @param {Function} callback - * @param {Object} target - * @deprecated since 3.1, please use addEventListener instead - */ - addLoadedEventListener:function(callback, target){ - this.addEventListener("load", callback, target); - }, - - _updateCapInset: function () { - var insets, locInsetLeft = this._insetLeft, locInsetTop = this._insetTop, locInsetRight = this._insetRight; - var locSpriteRect = this._spriteRect, locInsetBottom = this._insetBottom; - if (locInsetLeft === 0 && locInsetTop === 0 && locInsetRight === 0 && locInsetBottom === 0) { - insets = cc.rect(0, 0, 0, 0); - } else { - insets = this._spriteFrameRotated ? cc.rect(locInsetBottom, locInsetLeft, - locSpriteRect.width - locInsetRight - locInsetLeft, - locSpriteRect.height - locInsetTop - locInsetBottom) : - cc.rect(locInsetLeft, locInsetTop, - locSpriteRect.width - locInsetLeft - locInsetRight, - locSpriteRect.height - locInsetTop - locInsetBottom); - } - this.setCapInsets(insets); - }, - - _updatePositions: function () { - // Check that instances are non-NULL - if (!((this._topLeft) && (this._topRight) && (this._bottomRight) && - (this._bottomLeft) && (this._centre))) { - // if any of the above sprites are NULL, return - return; - } - - var size = this._contentSize; - var locTopLeft = this._topLeft, locTopRight = this._topRight, locBottomRight = this._bottomRight, locBottomLeft = this._bottomLeft; - var locLeft = this._left, locRight = this._right, locTop = this._top, locBottom = this._bottom; - var locCenter = this._centre, locCenterContentSize = this._centre.getContentSize(); - var locTopLeftContentSize = locTopLeft.getContentSize(); - var locBottomLeftContentSize = locBottomLeft.getContentSize(); - - var sizableWidth = size.width - locTopLeftContentSize.width - locTopRight.getContentSize().width; - var sizableHeight = size.height - locTopLeftContentSize.height - locBottomRight.getContentSize().height; - - var horizontalScale = sizableWidth / locCenterContentSize.width; - var verticalScale = sizableHeight / locCenterContentSize.height; - - var rescaledWidth = locCenterContentSize.width * horizontalScale; - var rescaledHeight = locCenterContentSize.height * verticalScale; - - var leftWidth = locBottomLeftContentSize.width; - var bottomHeight = locBottomLeftContentSize.height; - var centerOffset = cc.p(this._offset.x * horizontalScale, this._offset.y*verticalScale); - - if (cc._renderType === cc.game.RENDER_TYPE_WEBGL) { - //browser is in canvas mode, need to manually control rounding to prevent overlapping pixels - var roundedRescaledWidth = Math.round(rescaledWidth); - if (rescaledWidth !== roundedRescaledWidth) { - rescaledWidth = roundedRescaledWidth; - horizontalScale = rescaledWidth / locCenterContentSize.width; - } - var roundedRescaledHeight = Math.round(rescaledHeight); - if (rescaledHeight !== roundedRescaledHeight) { - rescaledHeight = roundedRescaledHeight; - verticalScale = rescaledHeight / locCenterContentSize.height; - } - } - - locCenter.setScaleX(horizontalScale); - locCenter.setScaleY(verticalScale); - - locBottomLeft.setAnchorPoint(1, 1); - locBottomLeft.setPosition(leftWidth,bottomHeight); - - locBottomRight.setAnchorPoint(0, 1); - locBottomRight.setPosition(leftWidth+rescaledWidth,bottomHeight); - - - locTopLeft.setAnchorPoint(1, 0); - locTopLeft.setPosition(leftWidth, bottomHeight+rescaledHeight); - - locTopRight.setAnchorPoint(0, 0); - locTopRight.setPosition(leftWidth+rescaledWidth, bottomHeight+rescaledHeight); - - locLeft.setAnchorPoint(1, 0.5); - locLeft.setPosition(leftWidth, bottomHeight+rescaledHeight/2 + centerOffset.y); - locLeft.setScaleY(verticalScale); - - locRight.setAnchorPoint(0, 0.5); - locRight.setPosition(leftWidth+rescaledWidth,bottomHeight+rescaledHeight/2 + centerOffset.y); - locRight.setScaleY(verticalScale); - - locTop.setAnchorPoint(0.5, 0); - locTop.setPosition(leftWidth+rescaledWidth/2 + centerOffset.x,bottomHeight+rescaledHeight); - locTop.setScaleX(horizontalScale); - - locBottom.setAnchorPoint(0.5, 1); - locBottom.setPosition(leftWidth+rescaledWidth/2 + centerOffset.x,bottomHeight); - locBottom.setScaleX(horizontalScale); - - locCenter.setAnchorPoint(0.5, 0.5); - locCenter.setPosition(leftWidth+rescaledWidth/2 + centerOffset.x, bottomHeight+rescaledHeight/2 + centerOffset.y); - locCenter.setScaleX(horizontalScale); - locCenter.setScaleY(verticalScale); - }, - - /** - * Constructor function. override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function. + * Constructor function. * @function * @param {string|cc.SpriteFrame} file file name of texture or a SpriteFrame * @param {cc.Rect} rectOrCapInsets @@ -213,14 +378,18 @@ ccui.Scale9Sprite = cc.Scale9Sprite = cc.Node.extend(/** @lends ccui.Scale9Sprit */ ctor: function (file, rectOrCapInsets, capInsets) { cc.Node.prototype.ctor.call(this); + + //for async texture load this._loader = new cc.Sprite.LoadManager(); - this._spriteRect = cc.rect(0, 0, 0, 0); - this._capInsetsInternal = cc.rect(0, 0, 0, 0); - this._originalSize = cc.size(0, 0); - this._preferredSize = cc.size(0, 0); - this._capInsets = cc.rect(0, 0, 0, 0); - this._renderers = []; + this._renderCmd.setState(this._brightState); + this._blendFunc = cc.BlendFunc._alphaPremultiplied(); + 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); if (file !== undefined) { if (file instanceof cc.SpriteFrame) @@ -233,97 +402,15 @@ ccui.Scale9Sprite = cc.Scale9Sprite = cc.Node.extend(/** @lends ccui.Scale9Sprit this.initWithFile(file, rectOrCapInsets, capInsets); } } - else { - this.init(); - this.setCascadeColorEnabled(true); - this.setCascadeOpacityEnabled(true); - this.setAnchorPoint(0.5, 0.5); - this._positionsAreDirty = true; - } - }, - - getSprite: function () { - return this._scale9Image; - }, - - /** Original sprite's size. */ - getOriginalSize: function () { - return cc.size(this._originalSize); - }, - - //if the preferredSize component is given as -1, it is ignored - getPreferredSize: function () { - return cc.size(this._preferredSize); - }, - _getPreferredWidth: function () { - return this._preferredSize.width; - }, - _getPreferredHeight: function () { - return this._preferredSize.height; - }, - - _asyncSetPreferredSize: function () { - this.removeEventListener('load', this._asyncSetPreferredSize, this); - this.setPreferredSize(this._cachePreferredSize); - this._cachePreferredSize = null; - }, - setPreferredSize: function (preferredSize) { - if (!preferredSize) return; - if (!this._textureLoaded) { - this._cachePreferredSize = preferredSize; - this.removeEventListener('load', this._asyncSetPreferredSize, this); - this.addEventListener('load', this._asyncSetPreferredSize, this); - return false; - } - this.setContentSize(preferredSize); - this._preferredSize = preferredSize; - if (this._positionsAreDirty) { - this._updatePositions(); - this._positionsAreDirty = false; - this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.cacheDirty); - } - }, - _setPreferredWidth: function (value) { - this._setWidth(value); - this._preferredSize.width = value; - }, - _setPreferredHeight: function (value) { - this._setHeight(value); - this._preferredSize.height = value; - }, - /** Opacity: conforms to CCRGBAProtocol protocol */ - setOpacity: function (opacity) { - cc.Node.prototype.setOpacity.call(this, opacity); - if(this._scale9Enabled) { - var pChildren = this._renderers; - for(var i=0; i 0 && rotatedCenterBounds.height > 0 ) - this._renderers.push(this._centre); - - // Top - if(!this._top) - this._top = new cc.Sprite(); - this._top.initWithTexture(selTexture, rotatedCenterTopBounds, rotated); - if(rotatedCenterTopBounds.width > 0 && rotatedCenterTopBounds.height > 0 ) - this._renderers.push(this._top); - - // Bottom - if(!this._bottom) - this._bottom = new cc.Sprite(); - this._bottom.initWithTexture(selTexture, rotatedCenterBottomBounds, rotated); - if(rotatedCenterBottomBounds.width > 0 && rotatedCenterBottomBounds.height > 0 ) - this._renderers.push(this._bottom); - - // Left - if(!this._left) - this._left = new cc.Sprite(); - this._left.initWithTexture(selTexture, rotatedLeftCenterBounds, rotated); - if(rotatedLeftCenterBounds.width > 0 && rotatedLeftCenterBounds.height > 0 ) - this._renderers.push(this._left); - - // Right - if(!this._right) - this._right = new cc.Sprite(); - this._right.initWithTexture(selTexture, rotatedRightCenterBounds, rotated); - if(rotatedRightCenterBounds.width > 0 && rotatedRightCenterBounds.height > 0 ) - this._renderers.push(this._right); - - // Top left - if(!this._topLeft) - this._topLeft = new cc.Sprite(); - this._topLeft.initWithTexture(selTexture, rotatedLeftTopBounds, rotated); - if(rotatedLeftTopBounds.width > 0 && rotatedLeftTopBounds.height > 0 ) - this._renderers.push(this._topLeft); - - // Top right - if(!this._topRight) - this._topRight = new cc.Sprite(); - this._topRight.initWithTexture(selTexture, rotatedRightTopBounds, rotated); - if(rotatedRightTopBounds.width > 0 && rotatedRightTopBounds.height > 0 ) - this._renderers.push(this._topRight); - - // Bottom left - if(!this._bottomLeft) - this._bottomLeft = new cc.Sprite(); - this._bottomLeft.initWithTexture(selTexture, rotatedLeftBottomBounds, rotated); - if(rotatedLeftBottomBounds.width > 0 && rotatedLeftBottomBounds.height > 0 ) - this._renderers.push(this._bottomLeft); - - // Bottom right - if(!this._bottomRight) - this._bottomRight = new cc.Sprite(); - this._bottomRight.initWithTexture(selTexture, rotatedRightBottomBounds, rotated); - if(rotatedRightBottomBounds.width > 0 && rotatedRightBottomBounds.height > 0 ) - this._renderers.push(this._bottomRight); }, + /** - * @brief Update Scale9Sprite with a specified sprite. + * Sets the source blending function. * - * @param sprite A sprite pointer. - * @param spriteRect A delimitation zone. - * @param spriteFrameRotated Whether the sprite is rotated or not. - * @param offset The offset when slice the sprite. - * @param originalSize The origial size of the sprite. - * @param capInsets The Values to use for the cap insets. - * @return True if update success, false otherwise. + * @param blendFunc A structure with source and destination factor to specify pixel arithmetic. e.g. {GL_ONE, GL_ONE}, {GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA}. */ - updateWithSprite: function(sprite, spriteRect, spriteFrameRotated, offset, originalSize, capInsets) { - if (!sprite) return false; - - this._loader.clear(); - this._textureLoaded = sprite._textureLoaded; - if (!sprite._textureLoaded) { - this._loader.once(sprite, function () { - this.updateWithSprite(sprite, spriteRect, spriteFrameRotated, offset, originalSize, capInsets); - this.dispatchEvent("load"); - }, this); - return false; + setBlendFunc: function (blendFunc, dst) { + if (dst === undefined) { + this._blendFunc.src = blendFunc.src || cc.BLEND_SRC; + this._blendFunc.dst = blendFunc.dst || cc.BLEND_DST; } - - this._scale9Image = sprite; - if(!this._scale9Image) return false; - var tmpTexture = this._scale9Image.getTexture(); - this._textureLoaded = tmpTexture && tmpTexture.isLoaded(); - - var spriteFrame = sprite.getSpriteFrame(); - if (cc._renderType === cc.game.RENDER_TYPE_CANVAS) { - // Clipping will reset the properties - canvas mode - if (spriteFrame && tmpTexture._htmlElementObj instanceof window.HTMLCanvasElement) { - spriteFrameRotated = false; - spriteRect = { x: 0, y: 0, height: spriteRect.height, width: spriteRect.width } - } + else { + this._blendFunc.src = blendFunc || cc.BLEND_SRC; + this._blendFunc.dst = dst || cc.BLEND_DST; } + this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.contentDirty); + }, - var opacity = this.getOpacity(); - var color = this.getColor(); - this._renderers.length = 0; - var rect = spriteRect; - var size = originalSize; + /** + * Returns the blending function that is currently being used. + * + * @return A BlendFunc structure with source and destination factor which specified pixel arithmetic. + */ + getBlendFunc: function () { + return new cc.BlendFunc(this._blendFunc.src, this._blendFunc.dst); + }, - if(cc._rectEqualToZero(rect)) { - var textureSize = tmpTexture.getContentSize(); - rect = cc.rect(0, 0, textureSize.width, textureSize.height); + // overrides + setContentSize: function (width, height) { + if (height === undefined) { + height = width.height; + width = width.width; + } + if (width === this._contentSize.width && height === this._contentSize.height) { + return; } - if(size.width === 0 && size.height === 0) - size = cc.size(rect.width, rect.height); - this._capInsets = capInsets; - this._spriteRect = rect; - this._offset = offset; - this._spriteFrameRotated = spriteFrameRotated; - this._originalSize = size; - this._preferredSize = size; - this._capInsetsInternal = capInsets; - if(this._scale9Enabled) - this.createSlicedSprites(); - else - this._scale9Image.initWithTexture(tmpTexture, this._spriteRect, this._spriteFrameRotated); - this.setState(this._brightState); - this.setContentSize(size); - this.setOpacity(opacity); - this.setColor(color); - return true; + cc.Node.prototype.setContentSize.call(this, width, height); + this._quadsDirty = true; }, - /** - * Update the scale9Sprite with a SpriteBatchNode. - * @param {cc.SpriteBatchNode} batchNode - * @param {cc.Rect} originalRect - * @param {boolean} rotated - * @param {cc.Rect} capInsets - * @returns {boolean} - */ - updateWithBatchNode: function (batchNode, originalRect, rotated, capInsets) { - if (!batchNode) { - return false; - } - var texture = batchNode.getTexture(); - this._loader.clear(); - var loaded = this._textureLoaded = texture.isLoaded(); - if (!loaded) { - this._loader.once(texture, function () { - this.updateWithBatchNode(batchNode, originalRect, rotated, capInsets); - this.dispatchEvent("load"); - }, this); - return false; + getContentSize: function() { + if(this._renderingType === ccui.Scale9Sprite.RenderingType.SIMPLE) { + if(this._spriteFrame) { + return this._spriteFrame._originalSize; + } + return cc.size(this._contentSize); + } else { + return cc.size(this._contentSize); } + }, - var sprite = new cc.Sprite(texture); - var pos = cc.p(0,0); - var originalSize = cc.size(originalRect.width,originalRect.height); + _setWidth: function (value) { + cc.Node.prototype._setWidth.call(this, value); + this._quadsDirty = true; + }, - return this.updateWithSprite(sprite, originalRect, rotated, pos, originalSize, capInsets); + _setHeight: function (value) { + cc.Node.prototype._setHeight.call(this, value); + this._quadsDirty = true; }, /** - * set the sprite frame of ccui.Scale9Sprite - * @param {cc.SpriteFrame} spriteFrame - * @param {cc.rect} capInsets + * Change the state of 9-slice sprite. + * @see `State` + * @param state A enum value in State. */ - setSpriteFrame: function (spriteFrame, capInsets) { - // Reset insets - capInsets = capInsets || cc.rect(); - var texture = spriteFrame.getTexture(); - this._textureLoaded = texture._textureLoaded; - this._loader.clear(); - if (!texture._textureLoaded) { - this._loader.once(spriteFrame, function () { - this.setSpriteFrame(spriteFrame, capInsets); - this.dispatchEvent("load"); - }, this); - return false; - } + setState: function (state) { + this._brightState = state; + this._renderCmd.setState(state); + this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.contentDirty); + }, - var sprite = new cc.Sprite(spriteFrame.getTexture()); - this.updateWithSprite(sprite, spriteFrame.getRect(),spriteFrame.isRotated(),spriteFrame.getOffset(),spriteFrame.getOriginalSize(),capInsets); - this._insetLeft = capInsets.x; - this._insetTop = capInsets.y; - this._insetRight = this._originalSize.width - this._insetLeft - capInsets.width; - this._insetBottom = this._originalSize.height - this._insetTop - capInsets.height; + /** + * Query the current bright state. + * @return @see `State` + */ + getState: function () { + return this._brightState; }, - //v3.3 /** - * Sets ccui.Scale9Sprite's state - * @since v3.3 - * @param {Number} state + * change the rendering type, could be simple or slice + * @return @see `RenderingType` */ - setState: function (state) { - if (state === ccui.Scale9Sprite.state.NORMAL || state === ccui.Scale9Sprite.state.GRAY) { - this._brightState = state; - this._renderCmd.setState(state); - } + setRenderingType: function (type) { + if (this._renderingType === type) return; + + this._renderingType = type; + this._quadsDirty = true; + this._uvsDirty = true; + this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.contentDirty); }, /** - * @brief Toggle 9-slice feature. - * If Scale9Sprite is 9-slice disabled, the Scale9Sprite will rendered as a normal sprite. - * @param {boolean} enabled True to enable 9-slice, false otherwise. + * get the rendering type, could be simple or slice + * @return @see `RenderingType` */ - setScale9Enabled: function (enabled) { - if (this._scale9Enabled === enabled) - { - return; - } - this._scale9Enabled = enabled; - this._renderers.length = 0; - //we must invalide the transform when toggling scale9enabled - cc.Node.transformDirty = true; - if (this._scale9Enabled) { - if (this._scale9Image) { - this.updateWithSprite(this._scale9Image, - this._spriteRect, - this._spriteFrameRotated, - this._offset, - this._originalSize, - this._capInsets); - } - } - this._positionsAreDirty = true; + getRenderingType: function () { + return this._renderingType; }, - - _setRenderersPosition: function() { - if(this._positionsAreDirty) { - this._updatePositions(); - this._adjustScale9ImagePosition(); - this._positionsAreDirty = false; - } + /** + * change the left border of 9 slice sprite, it should be specified before trimmed. + * @param insetLeft left border. + */ + setInsetLeft: function (insetLeft) { + this._insetLeft = insetLeft; + this._quadsDirty = true; + this._uvsDirty = true; + this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.contentDirty); }, - - _adjustScale9ImagePosition: function() { - var image = this._scale9Image; - var contentSize = this._contentSize; - if(image) { - image.x = contentSize.width * image.getAnchorPoint().x; - image.y = contentSize.height * image.getAnchorPoint().y; - } + /** + * get the left border of 9 slice sprite, the result is specified before trimmed. + * @return left border. + */ + getInsetLeft: function () { + return this._insetLeft; }, - - _adjustScale9ImageScale: function() { - var image = this._scale9Image; - var contentSize = this._contentSize; - if(image) { - image.setScale(contentSize.width/image.width, contentSize.height/image.height); - } + /** + * change the top border of 9 slice sprite, it should be specified before trimmed. + * @param insetTop top border. + */ + setInsetTop: function (insetTop) { + this._insetTop = insetTop; + this._quadsDirty = true; + this._uvsDirty = true; + this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.contentDirty); }, /** - * Sets whether the widget should be flipped horizontally or not. - * @since v3.3 - * @param flippedX true if the widget should be flipped horizontally, false otherwise. + * get the top border of 9 slice sprite, the result is specified before trimmed. + * @return top border. */ - setFlippedX: function(flippedX){ - var realScale = this.getScaleX(); - this._flippedX = flippedX; - this.setScaleX(realScale); - this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.cacheDirty); + getInsetTop: function () { + return this._insetTop; }, /** - *

- * Returns the flag which indicates whether the widget is flipped horizontally or not.
- *
- * It only flips the texture of the widget, and not the texture of the widget's children.
- * Also, flipping the texture doesn't alter the anchorPoint.
- * If you want to flip the anchorPoint too, and/or to flip the children too use:
- * widget->setScaleX(sprite->getScaleX() * -1);
- *

- * @since v3.3 - * @return {Boolean} true if the widget is flipped horizontally, false otherwise. + * change the right border of 9 slice sprite, it should be specified before trimmed. + * @param insetRight right border. */ - isFlippedX: function(){ - return this._flippedX; + setInsetRight: function (insetRight) { + this._insetRight = insetRight; + this._quadsDirty = true; + this._uvsDirty = true; + this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.contentDirty); }, /** - * Sets whether the widget should be flipped vertically or not. - * @since v3.3 - * @param flippedY true if the widget should be flipped vertically, false otherwise. + * get the right border of 9 slice sprite, the result is specified before trimmed. + * @return right border. */ - setFlippedY:function(flippedY){ - var realScale = this.getScaleY(); - this._flippedY = flippedY; - this.setScaleY(realScale); - this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.cacheDirty); + getInsetRight: function () { + return this._insetRight; }, /** - *

- * Return the flag which indicates whether the widget is flipped vertically or not.
- *
- * It only flips the texture of the widget, and not the texture of the widget's children.
- * Also, flipping the texture doesn't alter the anchorPoint.
- * If you want to flip the anchorPoint too, and/or to flip the children too use:
- * widget->setScaleY(widget->getScaleY() * -1);
- *

- * @since v3.3 - * @return {Boolean} true if the widget is flipped vertically, false otherwise. + * change the bottom border of 9 slice sprite, it should be specified before trimmed. + * @param insetBottom bottom border. */ - isFlippedY:function(){ - return this._flippedY; + setInsetBottom: function (insetBottom) { + this._insetBottom = insetBottom; + this._quadsDirty = true; + this._uvsDirty = true; + this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.contentDirty); }, - - setScaleX: function (scaleX) { - if (this._flippedX) - scaleX = scaleX * -1; - cc.Node.prototype.setScaleX.call(this, scaleX); - this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.cacheDirty); + /** + * get the bottom border of 9 slice sprite, the result is specified before trimmed. + * @return bottom border. + */ + getInsetBottom: function () { + return this._insetBottom; }, - setScaleY: function (scaleY) { - if (this._flippedY) - scaleY = scaleY * -1; - cc.Node.prototype.setScaleY.call(this, scaleY); - this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.cacheDirty); - }, + _rebuildQuads: function () { + if (!this._spriteFrame || !this._spriteFrame._textureLoaded) { + return; + } - setScale: function (scaleX, scaleY) { - if(scaleY === undefined) - scaleY = scaleX; - this.setScaleX(scaleX); - this.setScaleY(scaleY); - }, + this._updateBlendFunc(); - getScaleX: function () { - var originalScale = cc.Node.prototype.getScaleX.call(this); - if (this._flippedX) - originalScale = originalScale * -1.0; - return originalScale; - }, + this._isTriangle = false; + switch (this._renderingType) { + case RenderingType.SIMPLE: + simpleQuadGenerator._rebuildQuads_base(this, this._spriteFrame, this._contentSize, this._isTrimmedContentSize); + break; + case RenderingType.SLICED: + scale9QuadGenerator._rebuildQuads_base(this, this._spriteFrame, this._contentSize, this._insetLeft, this._insetRight, this._insetTop, this._insetBottom); + break; + default: + this._quadsDirty = false; + this._uvsDirty = false; + cc.error('Can not generate quad'); + return; + } - getScaleY: function () { - var originalScale = cc.Node.prototype.getScaleY.call(this); - if (this._flippedY) - originalScale = originalScale * -1.0; - return originalScale; - }, - getScale: function () { - if(this.getScaleX() !== this.getScaleY()) - cc.log("Scale9Sprite#scale. ScaleX != ScaleY. Don't know which one to return"); - return this.getScaleX(); + this._quadsDirty = false; + this._uvsDirty = false; }, - _createRenderCmd: function(){ - if(cc._renderType === cc.game.RENDER_TYPE_CANVAS) + _createRenderCmd: function () { + if (cc._renderType === cc.game.RENDER_TYPE_CANVAS) return new ccui.Scale9Sprite.CanvasRenderCmd(this); else return new ccui.Scale9Sprite.WebGLRenderCmd(this); @@ -1220,3 +904,15 @@ ccui.Scale9Sprite.POSITIONS_TOPLEFT = 6; ccui.Scale9Sprite.POSITIONS_BOTTOMRIGHT = 7; ccui.Scale9Sprite.state = {NORMAL: 0, GRAY: 1}; + +var RenderingType = ccui.Scale9Sprite.RenderingType = { + /** + * @property {Number} SIMPLE + */ + SIMPLE: 0, + /** + * @property {Number} SLICED + */ + SLICED: 1 +}; +})(); diff --git a/extensions/ccui/base-classes/UIScale9SpriteCanvasRenderCmd.js b/extensions/ccui/base-classes/UIScale9SpriteCanvasRenderCmd.js index 2c97160033..12f1bcaf82 100644 --- a/extensions/ccui/base-classes/UIScale9SpriteCanvasRenderCmd.js +++ b/extensions/ccui/base-classes/UIScale9SpriteCanvasRenderCmd.js @@ -1,5 +1,5 @@ /**************************************************************************** - Copyright (c) 2013-2014 Chukong Technologies Inc. + Copyright (c) 2013-2016 Chukong Technologies Inc. http://www.cocos2d-x.org @@ -25,170 +25,130 @@ (function() { ccui.Scale9Sprite.CanvasRenderCmd = function (renderable) { cc.Node.CanvasRenderCmd.call(this, renderable); - this._cachedParent = null; - this._cacheDirty = false; - this._state = ccui.Scale9Sprite.state.NORMAL; + this._needDraw = true; - var node = this._node; - var locCacheCanvas = this._cacheCanvas = document.createElement('canvas'); - locCacheCanvas.width = 1; - locCacheCanvas.height = 1; - this._cacheContext = new cc.CanvasContextWrapper(locCacheCanvas.getContext("2d")); - var locTexture = this._cacheTexture = new cc.Texture2D(); - locTexture.initWithElement(locCacheCanvas); - locTexture.handleLoadedTexture(); - this._cacheSprite = new cc.Sprite(locTexture); - this._cacheSprite.setAnchorPoint(0,0); - node.addChild(this._cacheSprite); + this._state = ccui.Scale9Sprite.state.NORMAL; + this._originalTexture = this._textureToRender = null; }; var proto = ccui.Scale9Sprite.CanvasRenderCmd.prototype = Object.create(cc.Node.CanvasRenderCmd.prototype); proto.constructor = ccui.Scale9Sprite.CanvasRenderCmd; - proto.visit = function(parentCmd){ - var node = this._node; - if(!node._visible) - return; - - if (node._positionsAreDirty) { - node._updatePositions(); - node._positionsAreDirty = false; - } - - this.originVisit(parentCmd); - }; - - proto.transform = function(parentCmd, recursive) { - var node = this._node; + proto.transform = function(parentCmd, recursive){ this.originTransform(parentCmd, recursive); - if (node._positionsAreDirty) { - node._updatePositions(); - node._positionsAreDirty = false; - } + this._node._rebuildQuads(); + }; - var children = node._children; - for(var i=0; i 0 && sh > 0 && w > 0 && h > 0) { + context.drawImage(image, + sx, sy, sw, sh, + x, y, w, h); + } + } } - else - break; + 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; + + + 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; } } - else { - var tempCmd = node._scale9Image._renderCmd; - node._adjustScale9ImagePosition(); - node._adjustScale9ImageScale(); - tempCmd.updateStatus(); - cc.renderer.pushRenderCommand(node._scale9Image._renderCmd); - } - //draw to cache canvas - var selTexture = node._scale9Image.getTexture(); - if(selTexture && this._state === ccui.Scale9Sprite.state.GRAY) - selTexture._switchToGray(true); - locContext.setTransform(1, 0, 0, 1, 0, 0); - locContext.clearRect(0, 0, sizeInPixels.width, sizeInPixels.height); - cc.renderer._renderingToCacheCanvas(wrapper, node.__instanceId, locScaleFactor, locScaleFactor); - cc.renderer._turnToNormalMode(); - if(selTexture && this._state === ccui.Scale9Sprite.state.GRAY) - selTexture._switchToGray(false); - - if(contentSizeChanged) - this._cacheSprite.setTextureRect(cc.rect(0,0, size.width, size.height)); - - if(!this._cacheSprite.getParent()) - node.addChild(this._cacheSprite, -1); - this._cacheSprite._renderCmd._updateColor(); }; - proto.setState = function(state){ - var locScale9Image = this._node._scale9Image; - if(!locScale9Image) - return; - this._state = state; - this.setDirtyFlag(cc.Node._dirtyFlags.cacheDirty); - }; })(); diff --git a/extensions/ccui/base-classes/UIScale9SpriteWebGLRenderCmd.js b/extensions/ccui/base-classes/UIScale9SpriteWebGLRenderCmd.js index 259496950e..7f249e6580 100644 --- a/extensions/ccui/base-classes/UIScale9SpriteWebGLRenderCmd.js +++ b/extensions/ccui/base-classes/UIScale9SpriteWebGLRenderCmd.js @@ -1,5 +1,5 @@ /**************************************************************************** - Copyright (c) 2013-2014 Chukong Technologies Inc. + Copyright (c) 2013-2016 Chukong Technologies Inc. http://www.cocos2d-x.org @@ -23,184 +23,158 @@ ****************************************************************************/ (function() { - if(!cc.Node.WebGLRenderCmd) - return; + if(!cc.Node.WebGLRenderCmd) return; + ccui.Scale9Sprite.WebGLRenderCmd = function (renderable) { cc.Node.WebGLRenderCmd.call(this, renderable); - this._cachedParent = null; - this._cacheDirty = false; + + this._needDraw = true; + + this._color = new Uint32Array(1); + this._dirty = false; + this._shaderProgram = cc.shaderCache.programForKey(cc.SHADER_SPRITE_POSITION_TEXTURECOLOR); }; + + + var Scale9Sprite = ccui.Scale9Sprite; var proto = ccui.Scale9Sprite.WebGLRenderCmd.prototype = Object.create(cc.Node.WebGLRenderCmd.prototype); proto.constructor = ccui.Scale9Sprite.WebGLRenderCmd; - proto.setShaderProgram = function (shaderProgram) { - var node = this._node; - if (node._scale9Enabled) { - var renderers = node._renderers, l = renderers.length; - for (var i = 0; i < l; i++) { - if (renderers[i]) { - renderers[i]._renderCmd._shaderProgram = shaderProgram; - } - } - } - else { - node._scale9Image._renderCmd._shaderProgram = shaderProgram; - } - this._shaderProgram = shaderProgram; + proto.needDraw = function () { + return this._needDraw && this._node.loaded(); }; - proto.visit = function(parentCmd) { - var node = this._node; - if (!node._visible) - return; - if (!node._scale9Image) - return; - - if (node._positionsAreDirty) { - node._updatePositions(); - node._positionsAreDirty = false; - } - - parentCmd = parentCmd || this.getParentRenderCmd(); - if (node._parent && node._parent._renderCmd) - this._curLevel = node._parent._renderCmd._curLevel + 1; - - this._syncStatus(parentCmd); - - if (node._scale9Enabled) { - var locRenderers = node._renderers; - var rendererLen = locRenderers.length; - for (var j=0; j < rendererLen; j++) { - var renderer = locRenderers[j]; - if (renderer) { - var tempCmd = renderer._renderCmd; - tempCmd.visit(this); - } - else - break; + 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; } } - else { - node._adjustScale9ImageScale(); - node._adjustScale9ImagePosition(); - node._scale9Image._renderCmd.visit(this); - } - this._dirtyFlag = 0; - this.originVisit(parentCmd); + return 36; }; - proto.transform = function(parentCmd, recursive){ - var node = this._node; - parentCmd = parentCmd || this.getParentRenderCmd(); + proto.transform = function (parentCmd, recursive) { this.originTransform(parentCmd, recursive); - if (node._positionsAreDirty) { - node._updatePositions(); - node._positionsAreDirty = false; - } - if(node._scale9Enabled) { - var locRenderers = node._renderers; - var protectChildLen = locRenderers.length; - var flags = cc.Node._dirtyFlags; - for(var j=0; j < protectChildLen; j++) { - var pchild = locRenderers[j]; - if(pchild) { - pchild._vertexZ = parentCmd._node._vertexZ; - var tempCmd = pchild._renderCmd; - tempCmd.transform(this); - tempCmd._dirtyFlag = tempCmd._dirtyFlag & flags.transformDirty ^ tempCmd._dirtyFlag; - } - else { - break; - } - } - } - else { - node._adjustScale9ImageScale(); - node._adjustScale9ImagePosition(); - node._scale9Image._renderCmd.transform(this); - } + this._node._rebuildQuads(); }; - proto.setDirtyFlag = function (dirtyFlag, child) { - // ignore cache dirty, it's only for canvas - if (dirtyFlag === cc.Node._dirtyFlags.cacheDirty) - dirtyFlag = cc.Node._dirtyFlags.transformDirty; - cc.Node.RenderCmd.prototype.setDirtyFlag.call(this, dirtyFlag, child); + proto._setColorDirty = function () { }; - proto._syncStatus = function (parentCmd){ - this._originSyncStatus(parentCmd); - this._updateDisplayColor(this._displayedColor); - this._updateDisplayOpacity(this._displayedOpacity); - }; - - proto._updateDisplayColor = function(parentColor){ - cc.Node.WebGLRenderCmd.prototype._updateDisplayColor.call(this, parentColor); + proto.uploadData = function (f32buffer, ui32buffer, vertexDataOffset){ var node = this._node; - var scale9Image = node._scale9Image; - parentColor = this._displayedColor; - if(node._scale9Enabled) { - var pChildren = node._renderers; - for(var i=0; i Date: Thu, 8 Dec 2016 22:50:25 +0800 Subject: [PATCH 31/42] Improve CCB reader performance --- extensions/ccb-reader/CCBAnimationManager.js | 39 ++- extensions/ccb-reader/CCBReader.js | 117 +++---- .../ccb-reader/CCBRelativePositioning.js | 63 ++-- extensions/ccb-reader/CCBValue.js | 21 -- extensions/ccb-reader/CCControlLoader.js | 10 +- extensions/ccb-reader/CCNodeLoader.js | 298 +++++++++--------- 6 files changed, 266 insertions(+), 282 deletions(-) diff --git a/extensions/ccb-reader/CCBAnimationManager.js b/extensions/ccb-reader/CCBAnimationManager.js index faedbfb6c4..0b65f1e696 100644 --- a/extensions/ccb-reader/CCBAnimationManager.js +++ b/extensions/ccb-reader/CCBAnimationManager.js @@ -24,6 +24,10 @@ THE SOFTWARE. ****************************************************************************/ +(function () { + +var _pos = cc.p(); + cc.BuilderAnimationManagerDelegate = cc.Class.extend({ completedAnimationSequenceNamed: function (name) { } @@ -445,7 +449,7 @@ cc.BuilderAnimationManager = cc.Class.extend({ } else if (propName === "opacity") { return cc.fadeTo(duration, keyframe1.getValue()); } else if (propName === "color") { - var selColor = keyframe1.getValue().getColor(); + var selColor = keyframe1.getValue(); return cc.tintTo(duration, selColor.r, selColor.g, selColor.b); } else if (propName === "visible") { var isVisible = keyframe1.getValue(); @@ -519,7 +523,9 @@ cc.BuilderAnimationManager = cc.Class.extend({ x = value[0]; y = value[1]; - node.setPosition(cc._getAbsolutePosition(x, y, nType, this.getContainerSize(node.getParent()), propName)); + cc._getAbsolutePosition(x, y, nType, this.getContainerSize(node.getParent()), propName, _pos); + node._position.x = _pos.x; + node._position.y = _pos.y; } else if (propName === "scale") { getArr = this._getBaseValue(node, propName); nType = getArr[2]; @@ -531,33 +537,34 @@ cc.BuilderAnimationManager = cc.Class.extend({ } else if (propName === "skew") { x = value[0]; y = value[1]; - node.setSkewX(x); - node.setSkewY(y); + node._skewX = x; + node._skewY = y; } else { // [node setValue:value forKey:name]; // TODO only handle rotation, opacity, displayFrame, color if (propName === "rotation") { node.setRotation(value); - } else if(propName === "rotationX") { - node.setRotationSkewX(value); - } else if(propName === "rotationY") { - node.setRotationSkewY(value); - } else if(propName === "opacity") { - node.setOpacity(value); - } else if(propName === "displayFrame") { + } else if (propName === "rotationX") { + node._rotationX = value; + } else if (propName === "rotationY") { + node._rotationY = value; + } else if (propName === "opacity") { + node._realOpacity = value; + } else if (propName === "displayFrame") { node.setSpriteFrame(value); - } else if(propName === "color") { - var ccColor3B = value.getColor(); - if(ccColor3B.r !== 255 || ccColor3B.g !== 255 || ccColor3B.b !== 255){ - node.setColor(ccColor3B); + } else if (propName === "color") { + if (value.r !== 255 || value.g !== 255 || value.b !== 255) { + node.setColor(value); } } else if (propName === "visible") { value = value || false; node.setVisible(value); } else { cc.log("unsupported property name is " + propName); + return; } } + node.setNodeDirty(); } }, @@ -764,4 +771,4 @@ cc.BuilderSoundEffect.create = function (file, pitch, pan, gain) { } return null; }; - +})(); diff --git a/extensions/ccb-reader/CCBReader.js b/extensions/ccb-reader/CCBReader.js index 5703adf558..0baa27b4ca 100644 --- a/extensions/ccb-reader/CCBReader.js +++ b/extensions/ccb-reader/CCBReader.js @@ -102,21 +102,6 @@ var CCB_SIZETYPE_MULTIPLY_RESOLUTION = 5; var CCB_SCALETYPE_ABSOLUTE = 0; var CCB_SCALETYPE_MULTIPLY_RESOLUTION = 1; -cc.BuilderFile = cc.Node.extend({ - _ccbFileNode:null, - - getCCBFileNode:function () { - return this._ccbFileNode; - }, - setCCBFileNode:function (node) { - this._ccbFileNode = node; - } -}); - -cc.BuilderFile.create = function () { - return new cc.BuilderFile(); -}; - /** * Parse CCBI file which is generated by CocosBuilder */ @@ -340,13 +325,31 @@ cc.BuilderReader = cc.Class.extend({ readInt: function (signed) { var numBits = 0; - while (!this._getBit()) { + var data = this._data[this._currentByte]; + var bit = !!(data & (1 << this._currentBit++)); + while (!bit) { numBits++; + bit = !!(data & (1 << this._currentBit++)); + if (this._currentBit >= 8) { + this._currentBit = 0; + this._currentByte++; + data = this._data[this._currentByte]; + if (this._currentByte > this._data.length) + throw new Error("out of the data bound"); + } } var current = 0; for (var a = numBits - 1; a >= 0; a--) { - if (this._getBit()) { + bit = !!(data & (1 << this._currentBit++)); + if (this._currentBit >= 8) { + this._currentBit = 0; + this._currentByte++; + data = this._data[this._currentByte]; + if (this._currentByte > this._data.length) + throw new Error("out of the data bound"); + } + if (bit) { current |= 1 << a; } } @@ -364,7 +367,10 @@ cc.BuilderReader = cc.Class.extend({ num = current - 1; } - this._alignBits(); + if (this._currentBit) { + this._currentBit = 0; + this._currentByte++; + } return num; }, @@ -376,11 +382,11 @@ cc.BuilderReader = cc.Class.extend({ }, readBool: function () { - return (0 !== this.readByte()); + return !!this._data[this._currentByte++]; }, readFloat: function () { - var type = this.readByte(); + var type = this._data[this._currentByte++]; switch (type) { case CCB_FLOAT0: @@ -406,7 +412,9 @@ cc.BuilderReader = cc.Class.extend({ _decodeFloat: function (precisionBits, exponentBits) { var length = precisionBits + exponentBits + 1; var size = length >> 3; - this._checkSize(length); + if (this._currentByte + size >= this._data.length) { + throw new Error("Index out of bound"); + } var bias = Math.pow(2, exponentBits - 1) - 1; var signal = this._readBitsOnly(precisionBits + exponentBits, 1, size); @@ -415,7 +423,7 @@ cc.BuilderReader = cc.Class.extend({ var divisor = 2; var curByte = 0; //length + (-precisionBits >> 3) - 1; do { - var byteValue = this._readByteOnly(++curByte, size); + var byteValue = this._data[this._currentByte + size - (++curByte) - 1]; var startBit = precisionBits % 8 || 8; var mask = 1 << startBit; while (mask >>= 1) { @@ -440,34 +448,26 @@ cc.BuilderReader = cc.Class.extend({ var lastByte = size + (-(start + length) >> 3); var diff = curByte - lastByte; - var sum = (this._readByteOnly(curByte, size) >> offsetRight) & ((1 << (diff ? 8 - offsetRight : length)) - 1); + var sum = (this._data[this._currentByte + size - curByte - 1] >> offsetRight) & ((1 << (diff ? 8 - offsetRight : length)) - 1); if (diff && offsetLeft) { - sum += (this._readByteOnly(lastByte++, size) & ((1 << offsetLeft) - 1)) << (diff-- << 3) - offsetRight; + sum += (this._data[this._currentByte + size - lastByte - 1] & ((1 << offsetLeft) - 1)) << (diff-- << 3) - offsetRight; + lastByte++; } while (diff) { - sum += this._shl(this._readByteOnly(lastByte++, size), (diff-- << 3) - offsetRight); + sum += this._shl(this._data[this._currentByte + size - lastByte - 1], (diff-- << 3) - offsetRight); + lastByte++; } return sum; }, - _readByteOnly: function (i, size) { - return this._data[this._currentByte + size - i - 1]; - }, - _shl: function (a, b) { for (++b; --b; a = ((a %= 0x7fffffff + 1) & 0x40000000) === 0x40000000 ? a * 2 : (a - 0x40000000) * 2 + 0x7fffffff + 1); return a; }, - _checkSize: function (neededBits) { - if (!(this._currentByte + Math.ceil(neededBits / 8) < this._data.length)) { - throw new Error("Index out of bound"); - } - }, - readCachedString: function () { return this._stringCache[this.readInt(false)]; }, @@ -670,12 +670,11 @@ cc.BuilderReader = cc.Class.extend({ keyframe.setEasingOpt(easingOpt); if (type === CCB_PROPTYPE_CHECK) { - value = this.readBool(); + value = !!this._data[this._currentByte++]; } else if (type === CCB_PROPTYPE_BYTE) { - value = this.readByte(); + value = this._data[this._currentByte++]; } else if (type === CCB_PROPTYPE_COLOR3) { - var c = cc.color(this.readByte(), this.readByte(), this.readByte()); - value = cc.Color3BWapper.create(c); + value = cc.color(this._data[this._currentByte++], this._data[this._currentByte++], this._data[this._currentByte++]); } else if (type === CCB_PROPTYPE_FLOATXY) { value = [this.readFloat(), this.readFloat()]; } else if (type === CCB_PROPTYPE_DEGREES) { @@ -727,7 +726,7 @@ cc.BuilderReader = cc.Class.extend({ return false; } - this._jsControlled = this.readBool(); + this._jsControlled = !!this._data[this._currentByte++]; this._animationManager._jsControlled = this._jsControlled; // no need to set if it is "jscontrolled". It is obvious. return true; @@ -736,13 +735,13 @@ cc.BuilderReader = cc.Class.extend({ _readStringFromBytes: function (startIndex, strLen, reverse) { reverse = reverse || false; var strValue = ""; - var i, locData = this._data, locCurrentByte = this._currentByte; + var i, locData = this._data; if (reverse) { for (i = strLen - 1; i >= 0; i--) - strValue += String.fromCharCode(locData[locCurrentByte + i]); + strValue += String.fromCharCode(locData[startIndex + i]); } else { for (i = 0; i < strLen; i++) - strValue += String.fromCharCode(locData[locCurrentByte + i]); + strValue += String.fromCharCode(locData[startIndex + i]); } return strValue; }, @@ -755,8 +754,8 @@ cc.BuilderReader = cc.Class.extend({ }, _readStringCacheEntry: function () { - var b0 = this.readByte(); - var b1 = this.readByte(); + var b0 = this._data[this._currentByte++]; + var b1 = this._data[this._currentByte++]; var numBytes = b0 << 8 | b1; @@ -838,9 +837,9 @@ cc.BuilderReader = cc.Class.extend({ ccNodeLoader.parseProperties(node, parent, this); //handle sub ccb files(remove middle node) - var isCCBFileNode = node instanceof cc.BuilderFile; + var isCCBFileNode = !!node.ccbFileNode; if (isCCBFileNode) { - var embeddedNode = node.getCCBFileNode(); + var embeddedNode = node.ccbFileNode; embeddedNode.setPosition(node.getPosition()); embeddedNode.setRotation(node.getRotation()); embeddedNode.setScaleX(node.getScaleX()); @@ -850,7 +849,7 @@ cc.BuilderReader = cc.Class.extend({ //embeddedNode.ignoreAnchorPointForPosition(node.isIgnoreAnchorPointForPosition()); locActionManager.moveAnimationsFromNode(node, embeddedNode); - node.setCCBFileNode(null); + node.ccbFileNode = null; node = embeddedNode; } var target = null, locMemberAssigner = null; @@ -926,27 +925,7 @@ cc.BuilderReader = cc.Class.extend({ return node; }, - _getBit:function () { - var bit = (this._data[this._currentByte] & (1 << this._currentBit)) !== 0; - this._currentBit++; - - if (this._currentBit >= 8) { - this._currentBit = 0; - this._currentByte++; - if(this._currentByte > this._data.length) - throw new Error("out of the data bound"); - } - return bit; - }, - - _alignBits:function () { - if (this._currentBit) { - this._currentBit = 0; - this._currentByte++; - } - }, - - _readUTF8:function () { + _readUTF8: function () { } }); diff --git a/extensions/ccb-reader/CCBRelativePositioning.js b/extensions/ccb-reader/CCBRelativePositioning.js index 2b2df87bef..347422c891 100644 --- a/extensions/ccb-reader/CCBRelativePositioning.js +++ b/extensions/ccb-reader/CCBRelativePositioning.js @@ -24,40 +24,41 @@ THE SOFTWARE. ****************************************************************************/ -cc.getAbsolutePosition = function(pt, type, containerSize, propName){ - var absPt = cc.p(0,0); - if(type === CCB_POSITIONTYPE_RELATIVE_BOTTOM_LEFT) - absPt = pt; - else if(type === CCB_POSITIONTYPE_RELATIVE_TOP_LEFT){ - absPt.x = pt.x; - absPt.y = containerSize.height - pt.y; - } else if(type === CCB_POSITIONTYPE_RELATIVE_TOP_RIGHT){ - absPt.x = containerSize.width - pt.x; - absPt.y = containerSize.height - pt.y; - } else if (type === CCB_POSITIONTYPE_RELATIVE_BOTTOM_RIGHT) { - absPt.x = containerSize.width - pt.x; - absPt.y = pt.y; - } else if (type === CCB_POSITIONTYPE_PERCENT) { - absPt.x = (containerSize.width * pt.x / 100.0); - absPt.y = (containerSize.height * pt.y / 100.0); - } else if (type === CCB_POSITIONTYPE_MULTIPLY_RESOLUTION) { +cc.getAbsolutePosition = function (pt, type, containerSize, propName) { + if (type === CCB_POSITIONTYPE_RELATIVE_BOTTOM_LEFT) { + ; + } + else if (type === CCB_POSITIONTYPE_RELATIVE_TOP_LEFT) { + pt.y = containerSize.height - pt.y; + } + else if (type === CCB_POSITIONTYPE_RELATIVE_TOP_RIGHT) { + pt.x = containerSize.width - pt.x; + pt.y = containerSize.height - pt.y; + } + else if (type === CCB_POSITIONTYPE_RELATIVE_BOTTOM_RIGHT) { + pt.x = containerSize.width - pt.x; + } + else if (type === CCB_POSITIONTYPE_PERCENT) { + pt.x = (containerSize.width * pt.x / 100.0); + pt.y = (containerSize.height * pt.y / 100.0); + } + else if (type === CCB_POSITIONTYPE_MULTIPLY_RESOLUTION) { var resolutionScale = cc.BuilderReader.getResolutionScale(); - absPt.x = pt.x * resolutionScale; - absPt.y = pt.y * resolutionScale; + pt.x = pt.x * resolutionScale; + pt.y = pt.y * resolutionScale; } - - return absPt; + return pt; }; -cc._getAbsolutePosition = function(x, y, type, containerSize, propName){ - var absPt = cc.p(0,0); - if(type === CCB_POSITIONTYPE_RELATIVE_BOTTOM_LEFT){ +cc._getAbsolutePosition = function (x, y, type, containerSize, propName, out) { + var absPt = out || cc.p(0, 0); + if (type === CCB_POSITIONTYPE_RELATIVE_BOTTOM_LEFT) { absPt.x = x; absPt.y = y; - } else if(type === CCB_POSITIONTYPE_RELATIVE_TOP_LEFT){ + } else if (type === CCB_POSITIONTYPE_RELATIVE_TOP_LEFT) { absPt.x = x; absPt.y = containerSize.height - y; - } else if(type === CCB_POSITIONTYPE_RELATIVE_TOP_RIGHT){ + } else if (type === CCB_POSITIONTYPE_RELATIVE_TOP_RIGHT) { absPt.x = containerSize.width - x; absPt.y = containerSize.height - y; } else if (type === CCB_POSITIONTYPE_RELATIVE_BOTTOM_RIGHT) { @@ -74,8 +75,8 @@ cc._getAbsolutePosition = function(x, y, type, containerSize, propName){ return absPt; }; -cc.setRelativeScale = function(node,scaleX, scaleY, type, propName){ - if(!node) +cc.setRelativeScale = function (node, scaleX, scaleY, type, propName) { + if (!node) throw new Error("cc.setRelativeScale(): node should be non-null"); if (type === CCB_POSITIONTYPE_MULTIPLY_RESOLUTION) { @@ -85,6 +86,6 @@ cc.setRelativeScale = function(node,scaleX, scaleY, type, propName){ scaleY *= resolutionScale; } - node.setScaleX(scaleX); - node.setScaleY(scaleY); -}; \ No newline at end of file + node._scaleX = scaleX; + node._scaleY = scaleY; +}; diff --git a/extensions/ccb-reader/CCBValue.js b/extensions/ccb-reader/CCBValue.js index 3b8c8f8011..dee4c7ba71 100644 --- a/extensions/ccb-reader/CCBValue.js +++ b/extensions/ccb-reader/CCBValue.js @@ -34,27 +34,6 @@ cc.BOOL_VALUE = 3; cc.UNSIGNEDCHAR_VALUE = 4; - -cc.Color3BWapper = cc.Class.extend({ - _color:null, - ctor:function () { - this._color = cc.color(0, 0, 0); - }, - getColor:function () { - return this._color; - } -}); - -cc.Color3BWapper.create = function (color) { - var ret = new cc.Color3BWapper(); - if (ret) { - ret._color.r = color.r; - ret._color.g = color.g; - ret._color.b = color.b; - } - return ret; -}; - cc.BuilderValue = cc.Class.extend({ _value: null, _type: 0, diff --git a/extensions/ccb-reader/CCControlLoader.js b/extensions/ccb-reader/CCControlLoader.js index 832a005bda..3b1a5d6518 100644 --- a/extensions/ccb-reader/CCControlLoader.js +++ b/extensions/ccb-reader/CCControlLoader.js @@ -27,12 +27,14 @@ var PROPERTY_CCBFILE = "ccbFile"; cc.BuilderFileLoader = cc.NodeLoader.extend({ - _createCCNode:function (parent, ccbReader) { - return cc.BuilderFile.create(); + _createCCNode: function (parent, ccbReader) { + var node = new cc.Node(); + node.ccbFileNode = null; + return node; }, onHandlePropTypeCCBFile: function (node, parent, propertyName, ccbFileNode, ccbReader) { if (propertyName === PROPERTY_CCBFILE) { - node.setCCBFileNode(ccbFileNode); + node.ccbFileNode = ccbFileNode; } else { cc.NodeLoader.prototype.onHandlePropTypeCCBFile.call(this, node, parent, propertyName, ccbFileNode, ccbReader); } @@ -94,7 +96,7 @@ cc.ControlButtonLoader = cc.ControlLoader.extend({ onHandlePropTypeCheck: function (node, parent, propertyName, check, ccbReader) { if (propertyName === PROPERTY_ZOOMONTOUCHDOWN) { - node.setZoomOnTouchDown(check); + node.zoomOnTouchDown = check; } else { cc.ControlLoader.prototype.onHandlePropTypeCheck.call(this, node, parent, propertyName, check, ccbReader); } diff --git a/extensions/ccb-reader/CCNodeLoader.js b/extensions/ccb-reader/CCNodeLoader.js index 536886e098..6d71699886 100644 --- a/extensions/ccb-reader/CCNodeLoader.js +++ b/extensions/ccb-reader/CCNodeLoader.js @@ -55,18 +55,29 @@ function BlockCCControlData(selCCControlHandler, target, controlEvents) { cc.NodeLoader = cc.Class.extend({ _customProperties: null, + _pt: null, + _size: null, + _arr2: null, ctor: function () { this._customProperties = new cc._Dictionary(); + this._pt = cc.p(); + this._size = cc.size(); + this._arr2 = new Array(2); + this._blockControlData = { + selCCControlHandler: null, + target: null, + controlEvents: null + }; }, - loadCCNode:function (parent, ccbReader) { + loadCCNode: function (parent, ccbReader) { return this._createCCNode(parent, ccbReader); //this.parseProperties(node, parent, ccbReader); //return node; }, - parseProperties:function (node, parent, ccbReader) { + parseProperties: function (node, parent, ccbReader) { var numRegularProps = ccbReader.readInt(false); var numExturaProps = ccbReader.readInt(false); var propertyCount = numRegularProps + numExturaProps; @@ -79,26 +90,26 @@ cc.NodeLoader = cc.Class.extend({ // Check if the property can be set for this platform var setProp = false; - var platform = ccbReader.readByte(); - if ((platform === CCB_PLATFORM_ALL) ||(platform === CCB_PLATFORM_IOS) ||(platform === CCB_PLATFORM_MAC) ) + var platform = ccbReader._data[ccbReader._currentByte++]; + if ((platform === CCB_PLATFORM_ALL) || (platform === CCB_PLATFORM_IOS) || (platform === CCB_PLATFORM_MAC)) setProp = true; //forward properties for sub ccb files - if(node instanceof cc.BuilderFile){ - if(node.getCCBFileNode() && isExtraProp){ - node = node.getCCBFileNode(); + if (isExtraProp) { + if (node.ccbFileNode) { + node = node.ccbFileNode; //skip properties that doesn't have a value to override var getExtraPropsNames = node.userObject; setProp = getExtraPropsNames.indexOf(propertyName) !== -1; + } else if (node === ccbReader._animationManager.getRootNode()) { + var extraPropsNames = node.userObject; + if (!extraPropsNames) { + extraPropsNames = []; + node.userObject = extraPropsNames; + } + extraPropsNames.push(propertyName); } - } else if(isExtraProp && node === ccbReader.getAnimationManager().getRootNode()){ - var extraPropsNames = node.userObject; - if(!extraPropsNames){ - extraPropsNames = []; - node.userObject = extraPropsNames; - } - extraPropsNames.push(propertyName); - } + } switch (type) { case CCB_PROPTYPE_POSITION: @@ -341,39 +352,38 @@ cc.NodeLoader = cc.Class.extend({ var type = ccbReader.readInt(false); - var containerSize = ccbReader.getAnimationManager().getContainerSize(parent); - var pt = cc._getAbsolutePosition(x,y,type,containerSize,propertyName); - node.setPosition(cc.getAbsolutePosition(pt,type,containerSize,propertyName)); //different to -x node.setPosition(pt); + // var containerSize = ccbReader._animationManager.getContainerSize(parent); + var containerSize = parent ? parent._contentSize : ccbReader._animationManager._rootContainerSize; + cc._getAbsolutePosition(x, y, type, containerSize, propertyName, this._pt); + node.setPosition(cc.getAbsolutePosition(this._pt, type, containerSize, propertyName)); //different to -x node.setPosition(pt); - if(ccbReader.getAnimatedProperties().indexOf(propertyName) > -1){ - var baseValue = [x,y,type]; - ccbReader.getAnimationManager().setBaseValue(baseValue,node,propertyName); + if (ccbReader._animatedProps.indexOf(propertyName) > -1) { + var baseValue = [x, y, type]; + ccbReader._animationManager.setBaseValue(baseValue, node, propertyName); } - - return pt; + return this._pt; }, - parsePropTypePoint:function (node, parent, ccbReader) { - var x = ccbReader.readFloat(); - var y = ccbReader.readFloat(); - - return cc.p(x, y); + parsePropTypePoint: function (node, parent, ccbReader) { + this._pt.x = ccbReader.readFloat(); + this._pt.y = ccbReader.readFloat(); + return this._pt; }, - parsePropTypePointLock:function (node, parent, ccbReader) { - var x = ccbReader.readFloat(); - var y = ccbReader.readFloat(); - - return cc.p(x, y); + parsePropTypePointLock: function (node, parent, ccbReader) { + this._pt.x = ccbReader.readFloat(); + this._pt.y = ccbReader.readFloat(); + return this._pt; }, - parsePropTypeSize:function (node, parent, ccbReader) { + parsePropTypeSize: function (node, parent, ccbReader) { var width = ccbReader.readFloat(); var height = ccbReader.readFloat(); var type = ccbReader.readInt(false); - var containerSize = ccbReader.getAnimationManager().getContainerSize(parent); + // var containerSize = ccbReader._animationManager.getContainerSize(parent); + var containerSize = parent ? parent._contentSize : ccbReader._animationManager._rootContainerSize; switch (type) { case CCB_SIZETYPE_ABSOLUTE: @@ -402,43 +412,46 @@ cc.NodeLoader = cc.Class.extend({ cc.log("Unknown CCB type."); break; } - - return cc.size(width, height); + this._size.width = width; + this._size.height = height; + return this._size; }, - parsePropTypeScaleLock:function (node, parent, ccbReader, propertyName) { + parsePropTypeScaleLock: function (node, parent, ccbReader, propertyName) { var x = ccbReader.readFloat(); var y = ccbReader.readFloat(); var type = ccbReader.readInt(false); - cc.setRelativeScale(node,x,y,type,propertyName); + // cc.setRelativeScale(node, x, y, type, propertyName); - if(ccbReader.getAnimatedProperties().indexOf(propertyName) > -1){ - ccbReader.getAnimationManager().setBaseValue([x,y,type],node,propertyName); + if (ccbReader._animatedProps.indexOf(propertyName) > -1) { + ccbReader._animationManager.setBaseValue([x, y, type], node, propertyName); } if (type === CCB_SCALETYPE_MULTIPLY_RESOLUTION) { - x *= cc.BuilderReader.getResolutionScale(); - y *= cc.BuilderReader.getResolutionScale(); + var resolutionScale = cc.BuilderReader.getResolutionScale(); + x *= resolutionScale; + y *= resolutionScale; } - - return [x, y]; + this._pt.x = x; + this._pt.y = y; + return this._pt; }, - parsePropTypeFloat:function (node, parent, ccbReader) { + parsePropTypeFloat: function (node, parent, ccbReader) { return ccbReader.readFloat(); }, - parsePropTypeDegrees:function (node, parent, ccbReader, propertyName) { - var ret = ccbReader.readFloat(); - if(ccbReader.getAnimatedProperties().indexOf(propertyName) > -1){ - ccbReader.getAnimationManager().setBaseValue(ret,node, propertyName); + parsePropTypeDegrees: function (node, parent, ccbReader, propertyName) { + var degrees = ccbReader.readFloat(); + if (ccbReader._animatedProps.indexOf(propertyName) > -1) { + ccbReader._animationManager.setBaseValue(degrees, node, propertyName); } - return ret; + return degrees; }, - parsePropTypeFloatScale:function (node, parent, ccbReader) { + parsePropTypeFloatScale: function (node, parent, ccbReader) { var f = ccbReader.readFloat(); var type = ccbReader.readInt(false); @@ -450,36 +463,36 @@ cc.NodeLoader = cc.Class.extend({ return f; }, - parsePropTypeInteger:function (node, parent, ccbReader) { + parsePropTypeInteger: function (node, parent, ccbReader) { return ccbReader.readInt(true); }, - parsePropTypeIntegerLabeled:function (node, parent, ccbReader) { + parsePropTypeIntegerLabeled: function (node, parent, ccbReader) { return ccbReader.readInt(true); }, - parsePropTypeFloatVar:function (node, parent, ccbReader) { - var f = ccbReader.readFloat(); - var fVar = ccbReader.readFloat(); - return [f, fVar]; + parsePropTypeFloatVar: function (node, parent, ccbReader) { + this._arr2[0] = ccbReader.readFloat(); + this._arr2[1] = ccbReader.readFloat(); + return this._arr2; }, - parsePropTypeCheck:function (node, parent, ccbReader, propertyName) { - var ret = ccbReader.readBool(); - if(ccbReader.getAnimatedProperties().indexOf(propertyName) > -1){ - ccbReader.getAnimationManager().setBaseValue(ret,node, propertyName); + parsePropTypeCheck: function (node, parent, ccbReader, propertyName) { + var check = !!ccbReader._data[ccbReader._currentByte++]; + if (ccbReader._animatedProps.indexOf(propertyName) > -1) { + ccbReader._animationManager.setBaseValue(check, node, propertyName); } - return ret; + return check; }, - parsePropTypeSpriteFrame:function (node, parent, ccbReader, propertyName) { + parsePropTypeSpriteFrame: function (node, parent, ccbReader, propertyName) { var spriteSheet = ccbReader.readCachedString(); - var spriteFile = ccbReader.readCachedString(); + var spriteFile = ccbReader.readCachedString(); var spriteFrame; - if(spriteFile != null && spriteFile.length !== 0){ - if(spriteSheet.length === 0){ - spriteFile = ccbReader.getCCBRootPath() + spriteFile; + if (spriteFile) { + if (spriteSheet.length === 0) { + spriteFile = ccbReader._ccbRootPath + spriteFile; var texture = cc.textureCache.addImage(spriteFile); var locContentSize = texture.getContentSize(); @@ -487,24 +500,24 @@ cc.NodeLoader = cc.Class.extend({ spriteFrame = new cc.SpriteFrame(texture, bounds); } else { var frameCache = cc.spriteFrameCache; - spriteSheet = ccbReader.getCCBRootPath() + spriteSheet; + spriteSheet = ccbReader._ccbRootPath + spriteSheet; //load the sprite sheet only if it is not loaded - if(ccbReader.getLoadedSpriteSheet().indexOf(spriteSheet) === -1){ + if (ccbReader._loadedSpriteSheets.indexOf(spriteSheet) === -1) { frameCache.addSpriteFrames(spriteSheet); - ccbReader.getLoadedSpriteSheet().push(spriteSheet); + ccbReader._loadedSpriteSheets.push(spriteSheet); } spriteFrame = frameCache.getSpriteFrame(spriteFile); } - if(ccbReader.getAnimatedProperties().indexOf(propertyName) > -1){ - ccbReader.getAnimationManager().setBaseValue(spriteFrame,node,propertyName); + if (ccbReader._animatedProps.indexOf(propertyName) > -1) { + ccbReader._animationManager.setBaseValue(spriteFrame, node, propertyName); } } return spriteFrame; }, - parsePropTypeAnimation:function (node, parent, ccbReader) { - var animationFile = ccbReader.getCCBRootPath() + ccbReader.readCachedString(); + parsePropTypeAnimation: function (node, parent, ccbReader) { + var animationFile = ccbReader._ccbRootPath + ccbReader.readCachedString(); var animation = ccbReader.readCachedString(); var ccAnimation = null; @@ -517,7 +530,7 @@ cc.NodeLoader = cc.Class.extend({ animation = cc.BuilderReader.lastPathComponent(animation); animationFile = cc.BuilderReader.lastPathComponent(animationFile); - if (animation != null && animation !== "") { + if (animation) { var animationCache = cc.animationCache; animationCache.addAnimations(animationFile); @@ -526,34 +539,34 @@ cc.NodeLoader = cc.Class.extend({ return ccAnimation; }, - parsePropTypeTexture:function (node, parent, ccbReader) { - var spriteFile = ccbReader.getCCBRootPath() + ccbReader.readCachedString(); + parsePropTypeTexture: function (node, parent, ccbReader) { + var spriteFile = ccbReader._ccbRootPath + ccbReader.readCachedString(); - if(spriteFile !== "") + if (spriteFile) return cc.textureCache.addImage(spriteFile); return null; }, - parsePropTypeByte:function (node, parent, ccbReader, propertyName) { - var ret = ccbReader.readByte(); - if(ccbReader.getAnimatedProperties().indexOf(propertyName) > -1){ - ccbReader.getAnimationManager().setBaseValue(ret,node, propertyName); + parsePropTypeByte: function (node, parent, ccbReader, propertyName) { + var ret = ccbReader._data[ccbReader._currentByte++]; + if (ccbReader._animatedProps.indexOf(propertyName) > -1) { + ccbReader._animationManager.setBaseValue(ret, node, propertyName); } return ret; }, - parsePropTypeColor3:function (node, parent, ccbReader, propertyName) { - var red = ccbReader.readByte(); - var green = ccbReader.readByte(); - var blue = ccbReader.readByte(); - var color = {r:red, g:green, b:blue }; - if(ccbReader.getAnimatedProperties().indexOf(propertyName) > -1){ - ccbReader.getAnimationManager().setBaseValue(cc.Color3BWapper.create(color),node, propertyName); + parsePropTypeColor3: function (node, parent, ccbReader, propertyName) { + var red = ccbReader._data[ccbReader._currentByte++]; + var green = ccbReader._data[ccbReader._currentByte++]; + var blue = ccbReader._data[ccbReader._currentByte++]; + var color = cc.color(red, green, blue); + if (ccbReader._animatedProps.indexOf(propertyName) > -1) { + ccbReader._animationManager.setBaseValue(color, node, propertyName); } return color; }, - parsePropTypeColor4FVar:function (node, parent, ccbReader) { + parsePropTypeColor4FVar: function (node, parent, ccbReader) { //TODO Color4F doesn't supports on HTML5 var red = 0 | (ccbReader.readFloat() * 255); var green = 0 | (ccbReader.readFloat() * 255); @@ -566,40 +579,39 @@ cc.NodeLoader = cc.Class.extend({ var alphaVar = ccbReader.readFloat(); alphaVar = alphaVar <= 1 ? (0 | (alphaVar * 255)) : alphaVar; - var colors = []; - colors[0] = {r:red, g:green, b:blue, a:alpha}; - colors[1] = {r:redVar, g:greenVar, b:blueVar, a:alphaVar}; + this._arr2[0] = {r: red, g: green, b: blue, a: alpha}; + this._arr2[1] = {r: redVar, g: greenVar, b: blueVar, a: alphaVar}; - return colors; + return this._arr2; }, - parsePropTypeFlip:function (node, parent, ccbReader) { - var flipX = ccbReader.readBool(); - var flipY = ccbReader.readBool(); + parsePropTypeFlip: function (node, parent, ccbReader) { + this._arr2[0] = !!ccbReader._data[ccbReader._currentByte++]; + this._arr2[1] = !!ccbReader._data[ccbReader._currentByte++]; - return [flipX, flipY]; + return this._arr2; }, - parsePropTypeBlendFunc:function (node, parent, ccbReader) { + parsePropTypeBlendFunc: function (node, parent, ccbReader) { var source = ccbReader.readInt(false); var destination = ccbReader.readInt(false); return new cc.BlendFunc(source, destination); }, - parsePropTypeFntFile:function (node, parent, ccbReader) { + parsePropTypeFntFile: function (node, parent, ccbReader) { return ccbReader.readCachedString(); }, - parsePropTypeString:function (node, parent, ccbReader) { + parsePropTypeString: function (node, parent, ccbReader) { return ccbReader.readCachedString(); }, - parsePropTypeText:function (node, parent, ccbReader) { + parsePropTypeText: function (node, parent, ccbReader) { return ccbReader.readCachedString(); }, - parsePropTypeFontTTF:function (node, parent, ccbReader) { + parsePropTypeFontTTF: function (node, parent, ccbReader) { return ccbReader.readCachedString(); //var ttfEnding = ".ttf"; @@ -607,21 +619,21 @@ cc.NodeLoader = cc.Class.extend({ /* If the fontTTF comes with the ".ttf" extension, prepend the absolute path. * System fonts come without the ".ttf" extension and do not need the path prepended. */ /*if (cc.CCBReader.endsWith(fontTTF.toLowerCase(), ttfEnding)) { - fontTTF = ccbReader.getCCBRootPath() + fontTTF; - }*/ + fontTTF = ccbReader.getCCBRootPath() + fontTTF; + }*/ }, - parsePropTypeBlock:function (node, parent, ccbReader) { + parsePropTypeBlock: function (node, parent, ccbReader) { var selectorName = ccbReader.readCachedString(); var selectorTarget = ccbReader.readInt(false); if (selectorTarget !== CCB_TARGETTYPE_NONE) { var target = null; - if(!ccbReader.isJSControlled()) { + if (!ccbReader._jsControlled) { if (selectorTarget === CCB_TARGETTYPE_DOCUMENTROOT) { - target = ccbReader.getAnimationManager().getRootNode(); + target = ccbReader._animationManager._rootNode; } else if (selectorTarget === CCB_TARGETTYPE_OWNER) { - target = ccbReader.getOwner(); + target = ccbReader._owner; } if (target !== null) { @@ -633,15 +645,15 @@ cc.NodeLoader = cc.Class.extend({ selMenuHandler = target.onResolveCCBCCMenuItemSelector(target, selectorName); if (selMenuHandler === 0) { - var ccbSelectorResolver = ccbReader.getCCBSelectorResolver(); - if (ccbSelectorResolver != null) + var ccbSelectorResolver = ccbReader._ccbSelectorResolver; + if (ccbSelectorResolver) selMenuHandler = ccbSelectorResolver.onResolveCCBCCMenuItemSelector(target, selectorName); } if (selMenuHandler === 0) { - cc.log("Skipping selector '" +selectorName+ "' since no CCBSelectorResolver is present."); + cc.log("Skipping selector '" + selectorName + "' since no CCBSelectorResolver is present."); } else { - return new BlockData(selMenuHandler,target); + return new BlockData(selMenuHandler, target); } } else { cc.log("Unexpected empty selector."); @@ -670,12 +682,12 @@ cc.NodeLoader = cc.Class.extend({ var controlEvents = ccbReader.readInt(false); if (selectorTarget !== CCB_TARGETTYPE_NONE) { - if(!ccbReader.isJSControlled()){ + if (!ccbReader._jsControlled) { var target = null; if (selectorTarget === CCB_TARGETTYPE_DOCUMENTROOT) { - target = ccbReader.getAnimationManager().getRootNode(); + target = ccbReader._animationManager._rootNode; } else if (selectorTarget === CCB_TARGETTYPE_OWNER) { - target = ccbReader.getOwner(); + target = ccbReader._owner; } if (target !== null) { @@ -686,7 +698,7 @@ cc.NodeLoader = cc.Class.extend({ selCCControlHandler = target.onResolveCCBCCControlSelector(target, selectorName); } if (selCCControlHandler === 0) { - var ccbSelectorResolver = ccbReader.getCCBSelectorResolver(); + var ccbSelectorResolver = ccbReader._ccbSelectorResolver; if (ccbSelectorResolver != null) { selCCControlHandler = ccbSelectorResolver.onResolveCCBCCControlSelector(target, selectorName); } @@ -695,7 +707,10 @@ cc.NodeLoader = cc.Class.extend({ if (selCCControlHandler === 0) { cc.log("Skipping selector '" + selectorName + "' since no CCBSelectorResolver is present."); } else { - return new BlockCCControlData(selCCControlHandler,target,controlEvents); + this._blockControlData.selCCControlHandler = selCCControlHandler; + this._blockControlData.target = target; + this._blockControlData.controlEvents = controlEvents; + return this._blockControlData; } } else { cc.log("Unexpected empty selector."); @@ -718,8 +733,8 @@ cc.NodeLoader = cc.Class.extend({ return null; }, - parsePropTypeCCBFile:function (node, parent, ccbReader) { - var ccbFileName = ccbReader.getCCBRootPath() + ccbReader.readCachedString(); + parsePropTypeCCBFile: function (node, parent, ccbReader) { + var ccbFileName = ccbReader._ccbRootPath + ccbReader.readCachedString(); /* Change path extension to .ccbi. */ var ccbFileWithoutPathExtension = cc.BuilderReader.deletePathExtension(ccbFileName); @@ -730,28 +745,29 @@ cc.NodeLoader = cc.Class.extend({ var bytes = cc.loader.getRes(ccbFileName); if (!bytes) { var realUrl = cc.loader.getUrl(ccbFileName); + realUrl = hlddz.convertToDownloadURL(realUrl); bytes = cc.loader.loadBinarySync(realUrl); cc.loader.cache[ccbFileName] = bytes; } - myCCBReader.initWithData(bytes,ccbReader.getOwner()); - myCCBReader.getAnimationManager().setRootContainerSize(parent.getContentSize()); - myCCBReader.setAnimationManagers(ccbReader.getAnimationManagers()); + myCCBReader.initWithData(bytes, ccbReader._owner); + myCCBReader._animationManager.setRootContainerSize(parent._contentSize); + myCCBReader.setAnimationManagers(ccbReader._animationManagers); - myCCBReader.getAnimationManager().setOwner(ccbReader.getOwner()); + myCCBReader._animationManager.setOwner(ccbReader._owner); var ccbFileNode = myCCBReader.readFileWithCleanUp(false); - ccbReader.setAnimationManagers(myCCBReader.getAnimationManagers()); + ccbReader.setAnimationManagers(myCCBReader._animationManagers); - if(ccbFileNode && myCCBReader.getAnimationManager().getAutoPlaySequenceId() !== -1) - myCCBReader.getAnimationManager().runAnimations(myCCBReader.getAnimationManager().getAutoPlaySequenceId(),0); + if (ccbFileNode && myCCBReader._animationManager._autoPlaySequenceId !== -1) + myCCBReader._animationManager.runAnimations(myCCBReader._animationManager._autoPlaySequenceId, 0); return ccbFileNode; }, - parsePropTypeFloatXY:function(node, parent, ccbReader){ - var x = ccbReader.readFloat(); - var y = ccbReader.readFloat(); - return [x,y]; + parsePropTypeFloatXY: function (node, parent, ccbReader) { + this._pt.x = ccbReader.readFloat(); + this._pt.y = ccbReader.readFloat(); + return this._pt; }, onHandlePropTypePosition: function (node, parent, propertyName, position, ccbReader) { @@ -784,24 +800,24 @@ cc.NodeLoader = cc.Class.extend({ onHandlePropTypeScaleLock: function (node, parent, propertyName, scaleLock, ccbReader) { if (propertyName === PROPERTY_SCALE) { - node.setScaleX(scaleLock[0]); - node.setScaleY(scaleLock[1]); + node._scaleX = scaleLock.x; + node._scaleY = scaleLock.y; } else { ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName); } }, onHandlePropTypeFloatXY: function (node, parent, propertyName, xy, ccbReader) { if (propertyName === PROPERTY_SKEW) { - node.setSkewX(xy[0]); - node.setSkewY(xy[1]); + node._skewX = xy.x; + node._skewY = xy.y; } else { var nameX = propertyName + "X"; var nameY = propertyName + "Y"; if (!node[nameX] || !node[nameY]) ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName); //TODO throw an error when source code was confused - node[nameX](xy[0]); - node[nameY](xy[1]); + node[nameX](xy.x); + node[nameY](xy.y); } }, onHandlePropTypeFloat: function (node, parent, propertyName, floatValue, ccbReader) { @@ -824,7 +840,7 @@ cc.NodeLoader = cc.Class.extend({ onHandlePropTypeInteger: function (node, parent, propertyName, integer, ccbReader) { if (propertyName === PROPERTY_TAG) { - node.setTag(integer); + node.tag = integer; } else { ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName); } @@ -840,9 +856,9 @@ cc.NodeLoader = cc.Class.extend({ onHandlePropTypeCheck: function (node, parent, propertyName, check, ccbReader) { if (propertyName === PROPERTY_VISIBLE) { - node.setVisible(check); + node._visible = check; } else if (propertyName === PROPERTY_IGNOREANCHORPOINTFORPOSITION) { - node.ignoreAnchorPointForPosition(check); + node._ignoreAnchorPointForPosition = check; } else { ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName); } From 0bda54c50ce5aef349ef07956a98c58a6e4e0f9c Mon Sep 17 00:00:00 2001 From: pandamicro Date: Thu, 8 Dec 2016 22:50:54 +0800 Subject: [PATCH 32/42] Improve UI Parser 1.x performance --- .../cocostudio/loader/parsers/uiParser-1.x.js | 573 +++++++++--------- 1 file changed, 289 insertions(+), 284 deletions(-) diff --git a/extensions/cocostudio/loader/parsers/uiParser-1.x.js b/extensions/cocostudio/loader/parsers/uiParser-1.x.js index 1e54d745aa..6c58029fe5 100644 --- a/extensions/cocostudio/loader/parsers/uiParser-1.x.js +++ b/extensions/cocostudio/loader/parsers/uiParser-1.x.js @@ -22,49 +22,120 @@ THE SOFTWARE. ****************************************************************************/ -(function(load, baseParser){ +(function (load, baseParser) { + + var _stack = new Array(50); var Parser = baseParser.extend({ - addSpriteFrame: function(textures, resourcePath){ - if(!textures) return; + addSpriteFrame: function (textures, resourcePath) { + if (!textures) return; for (var i = 0; i < textures.length; i++) { cc.spriteFrameCache.addSpriteFrames(resourcePath + textures[i]); } }, - pretreatment: function(json, resourcePath){ + pretreatment: function (json, resourcePath) { this.addSpriteFrame(json["textures"], resourcePath); }, - deferred: function(json, resourcePath, node, file){ - if(node){ - ccs.actionManager.initWithDictionary(file, json["animation"], node); - node.setContentSize(cc.size(json["designWidth"], json["designHeight"])); + parseRecursive: function (json, resourcePath) { + var index = 1; + var rootNode = null; + var parser, curr, className, options, position, anchor, anchorPP, + node, parent, child, children; + _stack[0] = json; + while (index > 0) { + index--; + curr = _stack[index]; + // Avoid memory leak + _stack[index] = null; + if (!curr) continue; + + // Parse node + className = curr["classname"]; + parser = this.parsers[className]; + if (!parser) { + cc.log("Can't find the parser : %s", className); + continue; + } + node = new parser.object(); + if (!node) continue; + if (!rootNode) { + rootNode = node; + } + + // Parse attributes + options = curr["options"]; + this.generalAttributes(node, options); + parser.handle(node, options, resourcePath); + this.colorAttributes(node, options); + + parent = curr.parent; + curr.parent = null; + if (parent instanceof ccui.PageView) { + parent.addPage(node); + } + else if (parent instanceof ccui.ListView) { + parent.pushBackCustomItem(node); + } + else if (parent) { + if (!(parent instanceof ccui.Layout)) { + if (node.getPositionType() === ccui.Widget.POSITION_PERCENT) { + position = node._positionPercent; + anchor = parent._anchorPoint; + node._positionPercent.x = position.x + anchor.x; + node._positionPercent.y = position.y + anchor.y; + } + anchorPP = parent._renderCmd._anchorPointInPoints; + node._position.x += anchorPP.x; + node._position.y += anchorPP.y; + node.setNodeDirty(); + } + parent.addChild(node); + } + + children = curr["children"]; + if (children && children.length > 0) { + for (var i = children.length - 1; i >= 0; i--) { + _stack[index] = children[i]; + _stack[index].parent = node; + index++; + } + } } - } + return rootNode; + }, - }); - var parser = new Parser(); + parse: function (file, json, resourcePath) { + resourcePath = resourcePath || this._dirname(file); + this.pretreatment(json, resourcePath); + var node = this.parseRecursive(json["widgetTree"], resourcePath); - parser.generalAttributes = function(widget, options){ - var ignoreSizeExsit = options["ignoreSize"]; - if(ignoreSizeExsit != null) - widget.ignoreContentAdaptWithSize(ignoreSizeExsit); + node && this.deferred(json, resourcePath, node, file); + return node; + }, - if (options["sizeType"]) - { - widget.setSizeType(options["sizeType"]); + deferred: function (json, resourcePath, node, file) { + if (node) { + ccs.actionManager.initWithDictionary(file, json["animation"], node); + node.setContentSize(json["designWidth"], json["designHeight"]); + } } - if (options["positionType"]) - { - widget.setPositionType(options["positionType"]); - } + }); + var parser = new Parser(); - widget.setSizePercent(cc.p(options["sizePercentX"], options["sizePercentY"])); - widget.setPositionPercent(cc.p(options["positionPercentX"], options["positionPercentY"])); + parser.generalAttributes = function (widget, options) { + widget._ignoreSize = options["ignoreSize"] || false; + widget._sizeType = options["sizeType"] || 0; + widget._positionType = options["positionType"] || 0; + + widget._sizePercent.x = options["sizePercentX"] || 0; + widget._sizePercent.y = options["sizePercentY"] || 0; + widget._positionPercent.x = options["positionPercentX"] || 0; + widget._positionPercent.y = options["positionPercentY"] || 0; /* adapt screen */ var w = 0, h = 0; @@ -74,77 +145,69 @@ w = screenSize.width; h = screenSize.height; } else { - w = options["width"]; - h = options["height"]; + w = options["width"] || 0; + h = options["height"] || 0; } + + var anchorPointX = options["anchorPointX"]; + var anchorPointY = options["anchorPointY"]; + + widget._anchorPoint.x = isNaN(anchorPointX) ? 0.5 : anchorPointX; + widget._anchorPoint.y = isNaN(anchorPointY) ? 0.5 : anchorPointY; + widget.setContentSize(w, h); widget.setTag(options["tag"]); widget.setActionTag(options["actiontag"]); widget.setTouchEnabled(options["touchAble"]); - var name = options["name"]; - var widgetName = name ? name : "default"; - widget.setName(widgetName); - - var x = options["x"]; - var y = options["y"]; - widget.setPosition(x, y); - - var sx = options["scaleX"]!=null ? options["scaleX"] : 1; - widget.setScaleX(sx); - var sy = options["scaleY"]!=null ? options["scaleY"] : 1; - widget.setScaleY(sy); + widget._name = options["name"] || "default"; - var rt = options["rotation"] || 0; - widget.setRotation(rt); + widget._position.x = options["x"] || 0; + widget._position.y = options["y"] || 0; + widget._scaleX = options["scaleX"] || 1; + widget._scaleY = options["scaleY"] || 1; + widget._rotationX = widget._rotationY = options["rotation"] || 0; - var vb = options["visible"] || false; - if(vb != null) - widget.setVisible(vb); - widget.setLocalZOrder(options["ZOrder"]); + widget._visible = options["visible"] || false; + widget._localZOrder = options["ZOrder"] || 0; var layout = options["layoutParameter"]; - if(layout != null){ + if (layout != null) { var layoutParameterDic = options["layoutParameter"]; - var paramType = layoutParameterDic["type"]; + var paramType = isNaN(layoutParameterDic["type"]) ? 2 : layoutParameterDic["type"]; var parameter = null; - switch(paramType){ + switch (paramType) { case 0: break; case 1: parameter = new ccui.LinearLayoutParameter(); - var gravity = layoutParameterDic["gravity"]; - parameter.setGravity(gravity); + parameter._linearGravity = layoutParameterDic["gravity"] || 0; break; case 2: parameter = new ccui.RelativeLayoutParameter(); - var rParameter = parameter; - var relativeName = layoutParameterDic["relativeName"]; - rParameter.setRelativeName(relativeName); - var relativeToName = layoutParameterDic["relativeToName"]; - rParameter.setRelativeToWidgetName(relativeToName); - var align = layoutParameterDic["align"]; - rParameter.setAlign(align); + parameter._relativeLayoutName = layoutParameterDic["relativeName"]; + parameter._relativeWidgetName = layoutParameterDic["relativeToName"]; + parameter._relativeAlign = layoutParameterDic["align"] || 0; break; default: break; } - if(parameter != null){ - var mgl = layoutParameterDic["marginLeft"]||0; - var mgt = layoutParameterDic["marginTop"]||0; - var mgr = layoutParameterDic["marginRight"]||0; - var mgb = layoutParameterDic["marginDown"]||0; - parameter.setMargin(mgl, mgt, mgr, mgb); + if (parameter != null) { + var margin = parameter._margin; + margin.left = layoutParameterDic["marginLeft"] || 0; + margin.top = layoutParameterDic["marginTop"] || 0; + margin.right = layoutParameterDic["marginRight"] || 0; + margin.bottom = layoutParameterDic["marginDown"] || 0; widget.setLayoutParameter(parameter); } } }; - parser.colorAttributes = function(widget, options){ - var op = options["opacity"]; - if(op != null) + parser.colorAttributes = function (widget, options) { + var op = options["opacity"] !== null ? options["opacity"] : 255; + if (op != null) widget.setOpacity(op); var colorR = options["colorR"]; var colorG = options["colorG"]; @@ -155,52 +218,6 @@ widget.setFlippedY(options["flipY"]); }; - parser.anchorPointAttributes = function(widget, options){ - var isAnchorPointXExists = options["anchorPointX"]; - var anchorPointXInFile; - if (isAnchorPointXExists != null) - anchorPointXInFile = options["anchorPointX"]; - else - anchorPointXInFile = widget.getAnchorPoint().x; - - var isAnchorPointYExists = options["anchorPointY"]; - var anchorPointYInFile; - if (isAnchorPointYExists != null) - anchorPointYInFile = options["anchorPointY"]; - else - anchorPointYInFile = widget.getAnchorPoint().y; - - if (isAnchorPointXExists != null || isAnchorPointYExists != null) - widget.setAnchorPoint(cc.p(anchorPointXInFile, anchorPointYInFile)); - }; - - parser.parseChild = function(widget, options, resourcePath){ - var children = options["children"]; - for (var i = 0; i < children.length; i++) { - var child = this.parseNode(children[i], resourcePath); - if(child){ - if(widget instanceof ccui.PageView) - widget.addPage(child); - else { - if(widget instanceof ccui.ListView){ - widget.pushBackCustomItem(child); - } else { - if(!(widget instanceof ccui.Layout)) { - if(child.getPositionType() === ccui.Widget.POSITION_PERCENT) { - var position = child.getPositionPercent(); - var anchor = widget.getAnchorPoint(); - child.setPositionPercent(cc.p(position.x + anchor.x, position.y + anchor.y)); - } - var AnchorPointIn = widget.getAnchorPointInPoints(); - child.setPosition(cc.p(child.getPositionX() + AnchorPointIn.x, child.getPositionY() + AnchorPointIn.y)); - } - widget.addChild(child); - } - } - } - } - }; - var getPath = function (res, type, path, cb) { if (path) { if (type === 0) @@ -221,8 +238,8 @@ w = screenSize.width; h = screenSize.height; } else { - w = options["width"]; - h = options["height"]; + w = options["width"] || 0; + h = options["height"] || 0; } widget.setSize(cc.size(w, h)); @@ -230,25 +247,25 @@ var backGroundScale9Enable = options["backGroundScale9Enable"]; widget.setBackGroundImageScale9Enabled(backGroundScale9Enable); - var cr = options["bgColorR"]; - var cg = options["bgColorG"]; - var cb = options["bgColorB"]; + var cr = options["bgColorR"] || 0; + var cg = options["bgColorG"] || 0; + var cb = options["bgColorB"] || 0; - var scr = options["bgStartColorR"]; - var scg = options["bgStartColorG"]; - var scb = options["bgStartColorB"]; + var scr = isNaN(options["bgStartColorR"]) ? 255 : options["bgStartColorR"]; + var scg = isNaN(options["bgStartColorG"]) ? 255 : options["bgStartColorG"]; + var scb = isNaN(options["bgStartColorB"]) ? 255 : options["bgStartColorB"]; - var ecr = options["bgEndColorR"]; - var ecg = options["bgEndColorG"]; - var ecb = options["bgEndColorB"]; + var ecr = isNaN(options["bgEndColorR"]) ? 255 : options["bgEndColorR"]; + var ecg = isNaN(options["bgEndColorG"]) ? 255 : options["bgEndColorG"]; + var ecb = isNaN(options["bgEndColorB"]) ? 255 : options["bgEndColorB"]; - var bgcv1 = options["vectorX"]; - var bgcv2 = options["vectorY"]; + var bgcv1 = options["vectorX"] || 0; + var bgcv2 = options["vectorY"] || 0; widget.setBackGroundColorVector(cc.p(bgcv1, bgcv2)); - var co = options["bgColorOpacity"]; + var co = options["bgColorOpacity"] || 0; - var colorType = options["colorType"]; + var colorType = options["colorType"] || 0; widget.setBackGroundColorType(colorType/*ui.LayoutBackGroundColorType(colorType)*/); widget.setBackGroundColor(cc.color(scr, scg, scb), cc.color(ecr, ecg, ecb)); widget.setBackGroundColor(cc.color(cr, cg, cb)); @@ -256,82 +273,82 @@ var imageFileNameDic = options["backGroundImageData"]; - if(imageFileNameDic){ - getPath(resourcePath, imageFileNameDic["resourceType"], imageFileNameDic["path"], function(path, type){ + if (imageFileNameDic) { + getPath(resourcePath, imageFileNameDic["resourceType"] || 0, imageFileNameDic["path"], function (path, type) { widget.setBackGroundImage(path, type); }); } - if (backGroundScale9Enable){ - var cx = options["capInsetsX"]; - var cy = options["capInsetsY"]; - var cw = options["capInsetsWidth"]; - var ch = options["capInsetsHeight"]; + if (backGroundScale9Enable) { + var cx = options["capInsetsX"] || 0; + var cy = options["capInsetsY"] || 0; + var cw = isNaN(options["capInsetsWidth"]) ? 1 : options["capInsetsWidth"]; + var ch = isNaN(options["capInsetsHeight"]) ? 1 : options["capInsetsHeight"]; widget.setBackGroundImageCapInsets(cc.rect(cx, cy, cw, ch)); } - if (options["layoutType"]) - { + if (options["layoutType"]) { widget.setLayoutType(options["layoutType"]); } }; /** * Button parser (UIButton) */ - parser.ButtonAttributes = function(widget, options, resourcePath){ + parser.ButtonAttributes = function (widget, options, resourcePath) { var button = widget; var scale9Enable = options["scale9Enable"]; button.setScale9Enabled(scale9Enable); var normalDic = options["normalData"]; - getPath(resourcePath, normalDic["resourceType"], normalDic["path"], function(path, type){ + getPath(resourcePath, normalDic["resourceType"] || 0, normalDic["path"], function (path, type) { button.loadTextureNormal(path, type); }); var pressedDic = options["pressedData"]; - getPath(resourcePath, pressedDic["resourceType"], pressedDic["path"], function(path, type){ + getPath(resourcePath, pressedDic["resourceType"] || 0, pressedDic["path"], function (path, type) { button.loadTexturePressed(path, type); }); var disabledDic = options["disabledData"]; - getPath(resourcePath, disabledDic["resourceType"], disabledDic["path"], function(path, type){ + getPath(resourcePath, disabledDic["resourceType"] || 0, disabledDic["path"], function (path, type) { button.loadTextureDisabled(path, type); }); if (scale9Enable) { - var cx = options["capInsetsX"]; - var cy = options["capInsetsY"]; - var cw = options["capInsetsWidth"]; - var ch = options["capInsetsHeight"]; + var cx = options["capInsetsX"] || 0; + var cy = options["capInsetsY"] || 0; + var cw = isNaN(options["capInsetsWidth"]) ? 1 : options["capInsetsWidth"]; + var ch = isNaN(options["capInsetsHeight"]) ? 1 : options["capInsetsHeight"]; button.setCapInsets(cc.rect(cx, cy, cw, ch)); - var sw = options["scale9Width"]; - var sh = options["scale9Height"]; + var sw = options["scale9Width"] || 0; + var sh = options["scale9Height"] || 0; if (sw != null && sh != null) button.setSize(cc.size(sw, sh)); } - var text = options["text"]; - if (text != null) + var text = options["text"] || ""; + if (text) { button.setTitleText(text); - var cr = options["textColorR"]; - var cg = options["textColorG"]; - var cb = options["textColorB"]; - var cri = cr!==null?options["textColorR"]:255; - var cgi = cg!==null?options["textColorG"]:255; - var cbi = cb!==null?options["textColorB"]:255; - - button.setTitleColor(cc.color(cri,cgi,cbi)); - var fs = options["fontSize"]; - if (fs != null) - button.setTitleFontSize(options["fontSize"]); - var fn = options["fontName"]; - if (fn) - button.setTitleFontName(options["fontName"]); + var cr = options["textColorR"]; + var cg = options["textColorG"]; + var cb = options["textColorB"]; + var cri = (cr !== null) ? options["textColorR"] : 255; + var cgi = (cg !== null) ? options["textColorG"] : 255; + var cbi = (cb !== null) ? options["textColorB"] : 255; + + button.setTitleColor(cc.color(cri, cgi, cbi)); + var fs = options["fontSize"]; + if (fs != null) + button.setTitleFontSize(options["fontSize"]); + var fn = options["fontName"]; + if (fn) + button.setTitleFontName(options["fontName"]); + } }; /** * CheckBox parser (UICheckBox) */ - parser.CheckBoxAttributes = function(widget, options, resourcePath){ + parser.CheckBoxAttributes = function (widget, options, resourcePath) { //load background image var backGroundDic = options["backGroundBoxData"]; - getPath(resourcePath, backGroundDic["resourceType"], backGroundDic["path"], function(path, type){ + getPath(resourcePath, backGroundDic["resourceType"] || 0, backGroundDic["path"], function (path, type) { widget.loadTextureBackGround(path, type); }); @@ -341,13 +358,13 @@ resourcePath, backGroundSelectedDic["resourceType"] || backGroundDic["resourceType"], backGroundSelectedDic["path"] || backGroundDic["path"], - function(path, type){ - widget.loadTextureBackGroundSelected(path, type); - }); + function (path, type) { + widget.loadTextureBackGroundSelected(path, type); + }); //load frontCross image var frontCrossDic = options["frontCrossData"]; - getPath(resourcePath, frontCrossDic["resourceType"], frontCrossDic["path"], function(path, type){ + getPath(resourcePath, frontCrossDic["resourceType"] || 0, frontCrossDic["path"], function (path, type) { widget.loadTextureFrontCross(path, type); }); @@ -357,13 +374,13 @@ resourcePath, backGroundDisabledDic["resourceType"] || frontCrossDic["resourceType"], backGroundDisabledDic["path"] || frontCrossDic["path"], - function(path, type){ - widget.loadTextureBackGroundDisabled(path, type); - }); + function (path, type) { + widget.loadTextureBackGroundDisabled(path, type); + }); ///load frontCrossDisabledData var frontCrossDisabledDic = options["frontCrossDisabledData"]; - getPath(resourcePath, frontCrossDisabledDic["resourceType"], frontCrossDisabledDic["path"], function(path, type){ + getPath(resourcePath, frontCrossDisabledDic["resourceType"] || 0, frontCrossDisabledDic["path"], function (path, type) { widget.loadTextureFrontCrossDisabled(path, type); }); @@ -373,33 +390,32 @@ /** * ImageView parser (UIImageView) */ - parser.ImageViewAttributes = function(widget, options, resourcePath){ + parser.ImageViewAttributes = function (widget, options, resourcePath) { var imageFileNameDic = options["fileNameData"] - getPath(resourcePath, imageFileNameDic["resourceType"], imageFileNameDic["path"], function(path, type){ + getPath(resourcePath, imageFileNameDic["resourceType"] || 0, imageFileNameDic["path"], function (path, type) { widget.loadTexture(path, type); }); var scale9EnableExist = options["scale9Enable"]; var scale9Enable = false; - if (scale9EnableExist){ + if (scale9EnableExist) { scale9Enable = options["scale9Enable"]; } widget.setScale9Enabled(scale9Enable); - if (scale9Enable){ - var sw = options["scale9Width"]; - var sh = options["scale9Height"]; - if (sw && sh) - { - var swf = options["scale9Width"]; - var shf = options["scale9Height"]; + if (scale9Enable) { + var sw = options["scale9Width"] || 0; + var sh = options["scale9Height"] || 0; + if (sw && sh) { + var swf = options["scale9Width"] || 0; + var shf = options["scale9Height"] || 0; widget.setSize(cc.size(swf, shf)); } - var cx = options["capInsetsX"]; - var cy = options["capInsetsY"]; - var cw = options["capInsetsWidth"]; - var ch = options["capInsetsHeight"]; + var cx = options["capInsetsX"] || 0; + var cy = options["capInsetsY"] || 0; + var cw = isNaN(options["capInsetsWidth"]) ? 1 : options["capInsetsWidth"]; + var ch = isNaN(options["capInsetsHeight"]) ? 1 : options["capInsetsHeight"]; widget.setCapInsets(cc.rect(cx, cy, cw, ch)); @@ -408,16 +424,16 @@ /** * TextAtlas parser (UITextAtlas) */ - parser.TextAtlasAttributes = function(widget, options, resourcePath){ + parser.TextAtlasAttributes = function (widget, options, resourcePath) { var sv = options["stringValue"]; var cmf = options["charMapFileData"]; // || options["charMapFile"]; var iw = options["itemWidth"]; var ih = options["itemHeight"]; var scm = options["startCharMap"]; - if (sv != null && cmf && iw != null && ih != null && scm != null){ + if (sv != null && cmf && iw != null && ih != null && scm != null) { var cmftDic = options["charMapFileData"]; - var cmfType = cmftDic["resourceType"]; - switch (cmfType){ + var cmfType = cmftDic["resourceType"] || 0; + switch (cmfType) { case 0: var tp_c = resourcePath; var cmfPath = cmftDic["path"]; @@ -435,9 +451,9 @@ /** * TextBMFont parser (UITextBMFont) */ - parser.TextBMFontAttributes = function(widget, options, resourcePath){ + parser.TextBMFontAttributes = function (widget, options, resourcePath) { var cmftDic = options["fileNameData"]; - var cmfType = cmftDic["resourceType"]; + var cmfType = cmftDic["resourceType"] || 0; switch (cmfType) { case 0: var tp_c = resourcePath; @@ -452,88 +468,92 @@ break; } - var text = options["text"]; + var text = options["text"] || ""; widget.setString(text); }; /** * Text parser (UIText) */ var regTTF = /\.ttf$/; - parser.TextAttributes = function(widget, options, resourcePath){ + parser.TextAttributes = function (widget, options, resourcePath) { var touchScaleChangeAble = options["touchScaleEnable"]; widget.setTouchScaleChangeEnabled(touchScaleChangeAble); - var text = options["text"]; - widget.setString(text); + var text = options["text"] || ""; + if(text) { + widget._setString(text); + } + var fs = options["fontSize"]; - if (fs != null){ - widget.setFontSize(options["fontSize"]); + if (fs != null) { + widget._setFontSize(options["fontSize"]); } var fn = options["fontName"]; - if (fn != null){ - if(cc.sys.isNative){ - if(regTTF.test(fn)){ + if (fn != null) { + if (cc.sys.isNative) { + if (regTTF.test(fn)) { widget.setFontName(cc.path.join(cc.loader.resPath, resourcePath, fn)); - }else{ + } else { widget.setFontName(fn); } - }else{ - widget.setFontName(fn.replace(regTTF, '')); + } else { + widget._setFontName(fn.replace(regTTF, '')); } } - var aw = options["areaWidth"]; - var ah = options["areaHeight"]; - if (aw != null && ah != null){ + var aw = options["areaWidth"] || 0; + var ah = options["areaHeight"] || 0; + if (aw && ah) { var size = cc.size(options["areaWidth"], options["areaHeight"]); - widget.setTextAreaSize(size); + widget._setTextAreaSize(size); } - var ha = options["hAlignment"]; - if (ha != null){ - widget.setTextHorizontalAlignment(options["hAlignment"]); + var ha = options["hAlignment"] || 0; + if (ha != null) { + widget._setTextHorizontalAlignment(ha); } - var va = options["vAlignment"]; - if (va != null){ - widget.setTextVerticalAlignment(options["vAlignment"]); + var va = options["vAlignment"] || 0; + if (va != null) { + widget._setTextVerticalAlignment(va); } + widget._updateUITextContentSize(); }; /** * ListView parser (UIListView) */ - parser.ListViewAttributes = function(widget, options, resoutcePath){ - parser.ScrollViewAttributes(widget, options,resoutcePath); - var direction = options["direction"]; + parser.ListViewAttributes = function (widget, options, resoutcePath) { + parser.ScrollViewAttributes(widget, options, resoutcePath); + var direction = options["direction"] || 1; widget.setDirection(direction); - var gravity = options["gravity"]; + var gravity = options["gravity"] || 0; widget.setGravity(gravity); - var itemMargin = options["itemMargin"]; + var itemMargin = options["itemMargin"] || 0; widget.setItemsMargin(itemMargin); }; /** * LoadingBar parser (UILoadingBar) */ - parser.LoadingBarAttributes = function(widget, options, resourcePath){ + parser.LoadingBarAttributes = function (widget, options, resourcePath) { var imageFileNameDic = options["textureData"]; - getPath(resourcePath, imageFileNameDic["resourceType"], imageFileNameDic["path"], function(path, type){ + getPath(resourcePath, imageFileNameDic["resourceType"] || 0, imageFileNameDic["path"], function (path, type) { widget.loadTexture(path, type); }); var scale9Enable = options["scale9Enable"]; widget.setScale9Enabled(scale9Enable); - if (scale9Enable){ - var cx = options["capInsetsX"]; - var cy = options["capInsetsY"]; - var cw = options["capInsetsWidth"]; - var ch = options["capInsetsHeight"]; + if (scale9Enable) { + var cx = options["capInsetsX"] || 0; + var cy = options["capInsetsY"] || 0; + var cw = isNaN(options["capInsetsWidth"]) ? 1 : options["capInsetsWidth"]; + var ch = isNaN(options["capInsetsHeight"]) ? 1 : options["capInsetsHeight"]; widget.setCapInsets(cc.rect(cx, cy, cw, ch)); - var width = options["width"]; - var height = options["height"]; + var width = options["width"] || 0; + var height = options["height"] || 0; widget.setSize(cc.size(width, height)); } - widget.setDirection(options["direction"]); - widget.setPercent(options["percent"]); + widget.setDirection(options["direction"] || 0); + widget.setPercent(options["percent"] || 0); }; /** * PageView parser (UIPageView) @@ -542,13 +562,13 @@ /** * ScrollView parser (UIScrollView) */ - parser.ScrollViewAttributes = function(widget, options, resoutcePath){ - parser.LayoutAttributes(widget, options,resoutcePath); - var innerWidth = options["innerWidth"]!=null ? options["innerWidth"] : 200; - var innerHeight = options["innerHeight"]!=null ? options["innerHeight"] : 200; + parser.ScrollViewAttributes = function (widget, options, resoutcePath) { + parser.LayoutAttributes(widget, options, resoutcePath); + var innerWidth = options["innerWidth"] != null ? options["innerWidth"] : 200; + var innerHeight = options["innerHeight"] != null ? options["innerHeight"] : 200; widget.setInnerContainerSize(cc.size(innerWidth, innerHeight)); - var direction = options["direction"]!=null ? options["direction"] : 1; + var direction = options["direction"] != null ? options["direction"] : 1; widget.setDirection(direction); widget.setBounceEnabled(options["bounceEnable"]); }; @@ -565,7 +585,7 @@ var barLength = options["length"]; var imageFileNameDic = options["barFileNameData"]; - var imageFileType = imageFileNameDic["resourceType"]; + var imageFileType = imageFileNameDic["resourceType"] || 0; var imageFileName = imageFileNameDic["path"]; if (bt != null) { @@ -582,7 +602,7 @@ } var normalDic = options["ballNormalData"]; - getPath(resourcePath, normalDic["resourceType"], normalDic["path"], function(path, type){ + getPath(resourcePath, normalDic["resourceType"] || 0, normalDic["path"], function (path, type) { slider.loadSlidBallTextureNormal(path, type); }); @@ -596,23 +616,23 @@ }); var disabledDic = options["ballDisabledData"]; - getPath(resourcePath, disabledDic["resourceType"], disabledDic["path"], function(path, type){ + getPath(resourcePath, disabledDic["resourceType"] || 0, disabledDic["path"], function (path, type) { slider.loadSlidBallTextureDisabled(path, type); }); var progressBarDic = options["progressBarData"]; - getPath(resourcePath, progressBarDic["resourceType"], progressBarDic["path"], function(path, type){ + getPath(resourcePath, progressBarDic["resourceType"] || 0, progressBarDic["path"], function (path, type) { slider.loadProgressBarTexture(path, type); }); }; /** * TextField parser (UITextField) */ - parser.TextFieldAttributes = function (widget, options, resourcePath){ - var ph = options["placeHolder"]; + parser.TextFieldAttributes = function (widget, options, resourcePath) { + var ph = options["placeHolder"] || ""; if (ph) widget.setPlaceHolder(ph); - widget.setString(options["text"]||""); + widget.setString(options["text"] || ""); var fs = options["fontSize"]; if (fs) widget.setFontSize(fs); @@ -628,13 +648,13 @@ widget.setFontName(fn.replace(regTTF, '')); } } - var tsw = options["touchSizeWidth"]; - var tsh = options["touchSizeHeight"]; - if (tsw!=null && tsh!=null) + var tsw = options["touchSizeWidth"] || 0; + var tsh = options["touchSizeHeight"] || 0; + if (tsw != null && tsh != null) widget.setTouchSize(tsw, tsh); - var dw = options["width"]; - var dh = options["height"]; + var dw = options["width"] || 0; + var dh = options["height"] || 0; if (dw > 0 || dh > 0) { //textField.setSize(cc.size(dw, dh)); } @@ -650,55 +670,40 @@ if (passwordEnable) widget.setPasswordStyleText(options["passwordStyleText"]); - var aw = options["areaWidth"]; - var ah = options["areaHeight"]; + var aw = options["areaWidth"] || 0; + var ah = options["areaHeight"] || 0; if (aw && ah) { var size = cc.size(aw, ah); widget.setTextAreaSize(size); } - var ha = options["hAlignment"]; + var ha = options["hAlignment"] || 0; if (ha) widget.setTextHorizontalAlignment(ha); - var va = options["vAlignment"]; + var va = options["vAlignment"] || 0; if (va) widget.setTextVerticalAlignment(va); - var r = options["colorR"]; - var g = options["colorG"]; - var b = options["colorB"]; - if (r !== undefined && g !== undefined && b !== undefined) { - widget.setTextColor(cc.color(r, g, b)); - } + var r = isNaN(options["colorR"]) ? 255 : options["colorR"]; + var g = isNaN(options["colorG"]) ? 255 : options["colorG"]; + var b = isNaN(options["colorB"]) ? 255 : options["colorB"]; + widget.setTextColor(cc.color(r, g, b)); }; - var register = [ - {name: "Panel", object: ccui.Layout, handle: parser.LayoutAttributes}, - {name: "Button", object: ccui.Button, handle: parser.ButtonAttributes}, - {name: "CheckBox", object: ccui.CheckBox, handle: parser.CheckBoxAttributes}, - {name: "ImageView", object: ccui.ImageView, handle: parser.ImageViewAttributes}, - {name: "LabelAtlas", object: ccui.TextAtlas, handle: parser.TextAtlasAttributes}, - {name: "LabelBMFont", object: ccui.TextBMFont, handle: parser.TextBMFontAttributes}, - {name: "Label", object: ccui.Text, handle: parser.TextAttributes}, - {name: "ListView", object: ccui.ListView, handle: parser.ListViewAttributes}, - {name: "LoadingBar", object: ccui.LoadingBar, handle: parser.LoadingBarAttributes}, - {name: "PageView", object: ccui.PageView, handle: parser.PageViewAttributes}, - {name: "ScrollView", object: ccui.ScrollView, handle: parser.ScrollViewAttributes}, - {name: "Slider", object: ccui.Slider, handle: parser.SliderAttributes}, - {name: "TextField", object: ccui.TextField, handle: parser.TextFieldAttributes} - ]; - - register.forEach(function(item){ - parser.registerParser(item.name, function(options, resourcePath){ - var widget = new item.object; - var uiOptions = options["options"]; - parser.generalAttributes(widget, uiOptions); - item.handle(widget, uiOptions, resourcePath); - parser.colorAttributes(widget, uiOptions); - parser.anchorPointAttributes(widget, uiOptions); - parser.parseChild.call(this, widget, options, resourcePath); - return widget; - }); - }); + parser.parsers = { + "Panel": {object: ccui.Layout, handle: parser.LayoutAttributes}, + "Button": {object: ccui.Button, handle: parser.ButtonAttributes}, + "CheckBox": {object: ccui.CheckBox, handle: parser.CheckBoxAttributes}, + "ImageView": {object: ccui.ImageView, handle: parser.ImageViewAttributes}, + "LabelAtlas": {object: ccui.TextAtlas, handle: parser.TextAtlasAttributes}, + "LabelBMFont": {object: ccui.TextBMFont, handle: parser.TextBMFontAttributes}, + "Label": {object: ccui.Text, handle: parser.TextAttributes}, + "ListView": {object: ccui.ListView, handle: parser.ListViewAttributes}, + "LoadingBar": {object: ccui.LoadingBar, handle: parser.LoadingBarAttributes}, + "PageView": {object: ccui.PageView, handle: parser.PageViewAttributes}, + "ScrollView": {object: ccui.ScrollView, handle: parser.ScrollViewAttributes}, + "Slider": {object: ccui.Slider, handle: parser.SliderAttributes}, + "TextField": {object: ccui.TextField, handle: parser.TextFieldAttributes} + }; load.registerParser("ccui", "*", parser); From 523b2311da360e4f560c8e456615b5300668a6cb Mon Sep 17 00:00:00 2001 From: pandamicro Date: Thu, 8 Dec 2016 22:55:11 +0800 Subject: [PATCH 33/42] Flat recursive call using stack for onEnter/onExit/cleanup etc --- cocos2d/clipping-nodes/CCClippingNode.js | 8 +- cocos2d/core/CCDirector.js | 36 ++-- cocos2d/core/base-nodes/CCNode.js | 167 +++++++++--------- cocos2d/particle/CCParticleBatchNode.js | 4 +- cocos2d/transitions/CCTransition.js | 18 +- cocos2d/transitions/CCTransitionPageTurn.js | 6 +- .../ccui/base-classes/CCProtectedNode.js | 78 +------- extensions/ccui/layouts/UILayout.js | 8 +- .../armature/display/CCDisplayManager.js | 2 +- 9 files changed, 137 insertions(+), 190 deletions(-) diff --git a/cocos2d/clipping-nodes/CCClippingNode.js b/cocos2d/clipping-nodes/CCClippingNode.js index 0fd6672fd4..2dcf3c606a 100644 --- a/cocos2d/clipping-nodes/CCClippingNode.js +++ b/cocos2d/clipping-nodes/CCClippingNode.js @@ -91,7 +91,7 @@ cc.ClippingNode = cc.Node.extend(/** @lends cc.ClippingNode# */{ onEnter: function () { cc.Node.prototype.onEnter.call(this); if (this._stencil) - this._stencil.onEnter(); + this._stencil._performRecursive(cc.Node._stateCallbackType.onEnter); }, /** @@ -105,7 +105,7 @@ cc.ClippingNode = cc.Node.extend(/** @lends cc.ClippingNode# */{ onEnterTransitionDidFinish: function () { cc.Node.prototype.onEnterTransitionDidFinish.call(this); if (this._stencil) - this._stencil.onEnterTransitionDidFinish(); + this._stencil._performRecursive(cc.Node._stateCallbackType.onEnterTransitionDidFinish); }, /** @@ -117,7 +117,7 @@ cc.ClippingNode = cc.Node.extend(/** @lends cc.ClippingNode# */{ * @function */ onExitTransitionDidStart: function () { - this._stencil.onExitTransitionDidStart(); + this._stencil._performRecursive(cc.Node._stateCallbackType.onExitTransitionDidStart); cc.Node.prototype.onExitTransitionDidStart.call(this); }, @@ -131,7 +131,7 @@ cc.ClippingNode = cc.Node.extend(/** @lends cc.ClippingNode# */{ * @function */ onExit: function () { - this._stencil.onExit(); + this._stencil._performRecursive(cc.Node._stateCallbackType.onExit); cc.Node.prototype.onExit.call(this); }, diff --git a/cocos2d/core/CCDirector.js b/cocos2d/core/CCDirector.js index 9f6a6ce1a0..72d8d25c5e 100644 --- a/cocos2d/core/CCDirector.js +++ b/cocos2d/core/CCDirector.js @@ -400,9 +400,9 @@ cc.Director = cc.Class.extend(/** @lends cc.Director# */{ // They are needed in case the director is run again if (this._runningScene) { - this._runningScene.onExitTransitionDidStart(); - this._runningScene.onExit(); - this._runningScene.cleanup(); + this._runningScene._performRecursive(cc.Node._stateCallbackType.onExitTransitionDidStart); + this._runningScene._performRecursive(cc.Node._stateCallbackType.onExit); + this._runningScene._performRecursive(cc.Node._stateCallbackType.cleanup); } this._runningScene = null; @@ -537,14 +537,14 @@ cc.Director = cc.Class.extend(/** @lends cc.Director# */{ if (!newIsTransition) { var locRunningScene = this._runningScene; if (locRunningScene) { - locRunningScene.onExitTransitionDidStart(); - locRunningScene.onExit(); + locRunningScene._performRecursive(cc.Node._stateCallbackType.onExitTransitionDidStart); + locRunningScene._performRecursive(cc.Node._stateCallbackType.onExit); } // issue #709. the root node (scene) should receive the cleanup message too // otherwise it might be leaked. if (this._sendCleanupToScene && locRunningScene) - locRunningScene.cleanup(); + locRunningScene._performRecursive(cc.Node._stateCallbackType.cleanup); } this._runningScene = this._nextScene; @@ -552,8 +552,8 @@ cc.Director = cc.Class.extend(/** @lends cc.Director# */{ this._nextScene = null; if ((!runningIsTransition) && (this._runningScene !== null)) { - this._runningScene.onEnter(); - this._runningScene.onEnterTransitionDidFinish(); + this._runningScene._performRecursive(cc.Node._stateCallbackType.onEnter); + this._runningScene._performRecursive(cc.Node._stateCallbackType.onEnterTransitionDidFinish); } }, @@ -563,16 +563,16 @@ cc.Director = cc.Class.extend(/** @lends cc.Director# */{ */ setNotificationNode: function (node) { cc.renderer.childrenOrderDirty = true; - if(this._notificationNode){ - this._notificationNode.onExitTransitionDidStart(); - this._notificationNode.onExit(); - this._notificationNode.cleanup(); + if (this._notificationNode) { + this._notificationNode._performRecursive(cc.Node._stateCallbackType.onExitTransitionDidStart); + this._notificationNode._performRecursive(cc.Node._stateCallbackType.onExit); + this._notificationNode._performRecursive(cc.Node._stateCallbackType.cleanup); } this._notificationNode = node; - if(!node) + if (!node) return; - this._notificationNode.onEnter(); - this._notificationNode.onEnterTransitionDidFinish(); + this._notificationNode._performRecursive(cc.Node._stateCallbackType.onEnter); + this._notificationNode._performRecursive(cc.Node._stateCallbackType.onEnterTransitionDidFinish); }, /** @@ -748,10 +748,10 @@ cc.Director = cc.Class.extend(/** @lends cc.Director# */{ while (c > level) { var current = locScenesStack.pop(); if (current.running) { - current.onExitTransitionDidStart(); - current.onExit(); + current._performRecursive(cc.Node._stateCallbackType.onExitTransitionDidStart); + current._performRecursive(cc.Node._stateCallbackType.onExit); } - current.cleanup(); + current._performRecursive(cc.Node._stateCallbackType.cleanup); c--; } this._nextScene = locScenesStack[locScenesStack.length - 1]; diff --git a/cocos2d/core/base-nodes/CCNode.js b/cocos2d/core/base-nodes/CCNode.js index 2cfbd4dd07..92aa978efa 100644 --- a/cocos2d/core/base-nodes/CCNode.js +++ b/cocos2d/core/base-nodes/CCNode.js @@ -216,68 +216,6 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{ return true; }, - _arrayMakeObjectsPerformSelector: function (array, callbackType) { - if (!array || array.length === 0) - return; - - var i, len = array.length, node; - var nodeCallbackType = cc.Node._stateCallbackType; - switch (callbackType) { - case nodeCallbackType.onEnter: - for (i = 0; i < len; i++) { - node = array[i]; - if (node) - node.onEnter(); - } - break; - case nodeCallbackType.onExit: - for (i = 0; i < len; i++) { - node = array[i]; - if (node) - node.onExit(); - } - break; - case nodeCallbackType.onEnterTransitionDidFinish: - for (i = 0; i < len; i++) { - node = array[i]; - if (node) - node.onEnterTransitionDidFinish(); - } - break; - case nodeCallbackType.cleanup: - for (i = 0; i < len; i++) { - node = array[i]; - if (node) - node.cleanup(); - } - break; - case nodeCallbackType.updateTransform: - for (i = 0; i < len; i++) { - node = array[i]; - if (node) - node.updateTransform(); - } - break; - case nodeCallbackType.onExitTransitionDidStart: - for (i = 0; i < len; i++) { - node = array[i]; - if (node) - node.onExitTransitionDidStart(); - } - break; - case nodeCallbackType.sortAllChildren: - for (i = 0; i < len; i++) { - node = array[i]; - if (node) - node.sortAllChildren(); - } - break; - default : - cc.assert(0, cc._LogInfos.Node__arrayMakeObjectsPerformSelector); - break; - } - }, - /** *

Properties configuration function
* All properties in attrs will be set to the node,
@@ -1177,9 +1115,6 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{ // event cc.eventManager.removeListeners(this); - - // timers - this._arrayMakeObjectsPerformSelector(this._children, cc.Node._stateCallbackType.cleanup); }, // composition: GET @@ -1264,10 +1199,10 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{ child.setOrderOfArrival(cc.s_globalOrderOfArrival++); if (this._running) { - child.onEnter(); + child._performRecursive(cc.Node._stateCallbackType.onEnter); // prevent onEnterTransitionDidFinish to be called twice when a node is added in onEnter if (this._isTransitionFinished) - child.onEnterTransitionDidFinish(); + child._performRecursive(cc.Node._stateCallbackType.onEnterTransitionDidFinish); } child._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.transformDirty); if (this._cascadeColorEnabled) @@ -1370,13 +1305,13 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{ var node = __children[i]; if (node) { if (this._running) { - node.onExitTransitionDidStart(); - node.onExit(); + node._performRecursive(cc.Node._stateCallbackType.onExitTransitionDidStart); + node._performRecursive(cc.Node._stateCallbackType.onExit); } // If you don't do cleanup, the node's actions will not get removed and the if (cleanup) - node.cleanup(); + node._performRecursive(cc.Node._stateCallbackType.cleanup); // set parent nil at the end node.parent = null; @@ -1393,13 +1328,13 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{ // -1st do onExit // -2nd cleanup if (this._running) { - child.onExitTransitionDidStart(); - child.onExit(); + child._performRecursive(cc.Node._stateCallbackType.onExitTransitionDidStart); + child._performRecursive(cc.Node._stateCallbackType.onExit); } // If you don't do cleanup, the child's actions will not get removed and the if (doCleanup) - child.cleanup(); + child._performRecursive(cc.Node._stateCallbackType.cleanup); // set parent nil at the end child.parent = null; @@ -1501,10 +1436,72 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{ onEnter: function () { this._isTransitionFinished = false; this._running = true;//should be running before resumeSchedule - this._arrayMakeObjectsPerformSelector(this._children, cc.Node._stateCallbackType.onEnter); this.resume(); }, + _performRecursive: function (callbackType) { + var nodeCallbackType = cc.Node._stateCallbackType; + if (callbackType >= nodeCallbackType.max) { + return; + } + + var index = 0; + var children, child, curr, i, len; + var stack = cc.Node._performStacks[cc.Node._performing]; + if (!stack) { + stack = []; + cc.Node._performStacks.push(stack); + } + stack.length = 0; + cc.Node._performing++; + curr = stack[0] = this; + while (curr) { + // Walk through children + children = curr._children; + if (children && children.length > 0) { + for (i = 0, len = children.length; i < len; ++i) { + child = children[i]; + stack.push(child); + } + } + children = curr._protectedChildren; + if (children && children.length > 0) { + for (i = 0, len = children.length; i < len; ++i) { + child = children[i]; + stack.push(child); + } + } + + index++; + curr = stack[index]; + } + for (i = stack.length - 1; i >= 0; --i) { + curr = stack[i]; + stack[i] = null; + if (!curr) continue; + + // Perform actual action + switch (callbackType) { + case nodeCallbackType.onEnter: + curr.onEnter(); + break; + case nodeCallbackType.onExit: + curr.onExit(); + break; + case nodeCallbackType.onEnterTransitionDidFinish: + curr.onEnterTransitionDidFinish(); + break; + case nodeCallbackType.cleanup: + curr.cleanup(); + break; + case nodeCallbackType.onExitTransitionDidStart: + curr.onExitTransitionDidStart(); + break; + } + } + cc.Node._performing--; + }, + /** *

* Event callback that is invoked when the CCNode enters in the 'stage'.
@@ -1515,7 +1512,6 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{ */ onEnterTransitionDidFinish: function () { this._isTransitionFinished = true; - this._arrayMakeObjectsPerformSelector(this._children, cc.Node._stateCallbackType.onEnterTransitionDidFinish); }, /** @@ -1525,7 +1521,6 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{ * @function */ onExitTransitionDidStart: function () { - this._arrayMakeObjectsPerformSelector(this._children, cc.Node._stateCallbackType.onExitTransitionDidStart); }, /** @@ -1540,7 +1535,6 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{ onExit: function () { this._running = false; this.pause(); - this._arrayMakeObjectsPerformSelector(this._children, cc.Node._stateCallbackType.onExit); this.removeAllComponents(); }, @@ -2011,8 +2005,12 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{ * @function */ updateTransform: function () { - // Recursively iterate over children - this._arrayMakeObjectsPerformSelector(this._children, cc.Node._stateCallbackType.updateTransform); + var children = this._children, node; + for (var i = 0; i < children.length; i++) { + varnode = children[i]; + if (node) + node.updateTransform(); + } }, /** @@ -2541,7 +2539,16 @@ cc.Node.create = function () { return new cc.Node(); }; -cc.Node._stateCallbackType = {onEnter: 1, onExit: 2, cleanup: 3, onEnterTransitionDidFinish: 4, updateTransform: 5, onExitTransitionDidStart: 6, sortAllChildren: 7}; +cc.Node._stateCallbackType = { + onEnter: 1, + onExit: 2, + cleanup: 3, + onEnterTransitionDidFinish: 4, + onExitTransitionDidStart: 5, + max: 6 +}; +cc.Node._performStacks = [[]]; +cc.Node._performing = 0; cc.assert(cc.isFunction(cc._tmp.PrototypeCCNode), cc._LogInfos.MissingFile, "BaseNodesPropertyDefine.js"); cc._tmp.PrototypeCCNode(); diff --git a/cocos2d/particle/CCParticleBatchNode.js b/cocos2d/particle/CCParticleBatchNode.js index b92d6d5a09..05a777d92f 100644 --- a/cocos2d/particle/CCParticleBatchNode.js +++ b/cocos2d/particle/CCParticleBatchNode.js @@ -477,8 +477,8 @@ cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{ child._setLocalZOrder(z); child.parent = this; if (this._running) { - child.onEnter(); - child.onEnterTransitionDidFinish(); + child._performRecursive(cc.Node._stateCallbackType.onEnter); + child._performRecursive(cc.Node._stateCallbackType.onEnterTransitionDidFinish); } return pos; }, diff --git a/cocos2d/transitions/CCTransition.js b/cocos2d/transitions/CCTransition.js index 8673ab9164..09b18228e6 100644 --- a/cocos2d/transitions/CCTransition.js +++ b/cocos2d/transitions/CCTransition.js @@ -133,9 +133,9 @@ cc.TransitionScene = cc.Scene.extend(/** @lends cc.TransitionScene# */{ // outScene should not receive the onEnter callback // only the onExitTransitionDidStart - this._outScene.onExitTransitionDidStart(); + this._outScene._performRecursive(cc.Node._stateCallbackType.onExitTransitionDidStart); - this._inScene.onEnter(); + this._inScene._performRecursive(cc.Node._stateCallbackType.onEnter); }, /** @@ -152,11 +152,11 @@ cc.TransitionScene = cc.Scene.extend(/** @lends cc.TransitionScene# */{ // enable events while transitions cc.eventManager.setEnabled(true); - this._outScene.onExit(); + this._outScene._performRecursive(cc.Node._stateCallbackType.onExit); // _inScene should not receive the onEnter callback // only the onEnterTransitionDidFinish - this._inScene.onEnterTransitionDidFinish(); + this._inScene._performRecursive(cc.Node._stateCallbackType.onEnterTransitionDidFinish); }, /** @@ -166,7 +166,7 @@ cc.TransitionScene = cc.Scene.extend(/** @lends cc.TransitionScene# */{ cc.Node.prototype.cleanup.call(this); if (this._isSendCleanupToScene) - this._outScene.cleanup(); + this._outScene._performRecursive(cc.Node._stateCallbackType.cleanup); }, /** @@ -1120,7 +1120,7 @@ cc.TransitionTurnOffTiles = cc.TransitionScene.extend(/** @lends cc.TransitionTu onEnter: function () { cc.TransitionScene.prototype.onEnter.call(this); this._gridProxy.setTarget(this._outScene); - this._gridProxy.onEnter(); + this._gridProxy._performRecursive(cc.Node._stateCallbackType.onEnter); var winSize = cc.director.getWinSize(); var aspect = winSize.width / winSize.height; @@ -1189,7 +1189,7 @@ cc.TransitionSplitCols = cc.TransitionScene.extend(/** @lends cc.TransitionSplit cc.TransitionScene.prototype.onEnter.call(this); //this._inScene.visible = false; this._gridProxy.setTarget(this._outScene); - this._gridProxy.onEnter(); + this._gridProxy._performRecursive(cc.Node._stateCallbackType.onEnter); var split = this.action(); var seq = cc.sequence( @@ -1202,7 +1202,7 @@ cc.TransitionSplitCols = cc.TransitionScene.extend(/** @lends cc.TransitionSplit onExit: function () { this._gridProxy.setTarget(null); - this._gridProxy.onExit(); + this._gridProxy._performRecursive(cc.Node._stateCallbackType.onExit); cc.TransitionScene.prototype.onExit.call(this); }, @@ -1308,7 +1308,7 @@ cc.TransitionFadeTR = cc.TransitionScene.extend(/** @lends cc.TransitionFadeTR# cc.TransitionScene.prototype.onEnter.call(this); this._gridProxy.setTarget(this._outScene); - this._gridProxy.onEnter(); + this._gridProxy._performRecursive(cc.Node._stateCallbackType.onEnter); var winSize = cc.director.getWinSize(); var aspect = winSize.width / winSize.height; diff --git a/cocos2d/transitions/CCTransitionPageTurn.js b/cocos2d/transitions/CCTransitionPageTurn.js index 5a689945ec..44a6bedd28 100644 --- a/cocos2d/transitions/CCTransitionPageTurn.js +++ b/cocos2d/transitions/CCTransitionPageTurn.js @@ -109,11 +109,11 @@ cc.TransitionPageTurn = cc.TransitionScene.extend(/** @lends cc.TransitionPageTu if (!this._back) { gridProxy.setTarget(this._outScene); - gridProxy.onEnter(); - gridProxy.runAction( cc.sequence(action,cc.callFunc(this.finish, this),cc.stopGrid())); + gridProxy._performRecursive(cc.Node._stateCallbackType.onEnter); + gridProxy.runAction(cc.sequence(action, cc.callFunc(this.finish, this), cc.stopGrid())); } else { gridProxy.setTarget(this._inScene); - gridProxy.onEnter(); + gridProxy._performRecursive(cc.Node._stateCallbackType.onEnter); // to prevent initial flicker this._inScene.visible = false; gridProxy.runAction( diff --git a/extensions/ccui/base-classes/CCProtectedNode.js b/extensions/ccui/base-classes/CCProtectedNode.js index c77c2b5456..8e069ebe51 100644 --- a/extensions/ccui/base-classes/CCProtectedNode.js +++ b/extensions/ccui/base-classes/CCProtectedNode.js @@ -68,10 +68,10 @@ cc.ProtectedNode = cc.Node.extend(/** @lends cc.ProtectedNode# */{ child.setOrderOfArrival(cc.s_globalOrderOfArrival); if (this._running) { - child.onEnter(); + child._performRecursive(cc.Node._stateCallbackType.onEnter); // prevent onEnterTransitionDidFinish to be called twice when a node is added in onEnter if (this._isTransitionFinished) - child.onEnterTransitionDidFinish(); + child._performRecursive(cc.Node._stateCallbackType.onEnterTransitionDidFinish); } if (this._cascadeColorEnabled) this._renderCmd.setCascadeColorEnabledDirty(); @@ -107,14 +107,14 @@ cc.ProtectedNode = cc.Node.extend(/** @lends cc.ProtectedNode# */{ var idx = locChildren.indexOf(child); if (idx > -1) { if (this._running) { - child.onExitTransitionDidStart(); - child.onExit(); + child._performRecursive(cc.Node._stateCallbackType.onExitTransitionDidStart); + child._performRecursive(cc.Node._stateCallbackType.onExit); } // If you don't do cleanup, the child's actions will not get removed and the // its scheduledSelectors_ dict will not get released! if (cleanup) - child.cleanup(); + child._performRecursive(cc.Node._stateCallbackType.cleanup); // set parent nil at the end child.setParent(null); @@ -165,12 +165,12 @@ cc.ProtectedNode = cc.Node.extend(/** @lends cc.ProtectedNode# */{ // -1st do onExit // -2nd cleanup if (this._running) { - child.onExitTransitionDidStart(); - child.onExit(); + child._performRecursive(cc.Node._stateCallbackType.onExitTransitionDidStart); + child._performRecursive(cc.Node._stateCallbackType.onExit); } if (cleanup) - child.cleanup(); + child._performRecursive(cc.Node._stateCallbackType.cleanup); // set parent nil at the end child.setParent(null); } @@ -224,67 +224,7 @@ cc.ProtectedNode = cc.Node.extend(/** @lends cc.ProtectedNode# */{ } }, - _changePosition: function () {}, - - /** - * Stops itself and its children and protected children's all running actions and schedulers - * @override - */ - cleanup: function(){ - cc.Node.prototype.cleanup.call(this); - var locChildren = this._protectedChildren; - for(var i = 0 , len = locChildren.length; i < len; i++) - locChildren[i].cleanup(); - }, - - /** - * Calls its parent's onEnter and calls its protected children's onEnter - * @override - */ - onEnter: function(){ - cc.Node.prototype.onEnter.call(this); - var locChildren = this._protectedChildren; - for(var i = 0, len = locChildren.length;i< len;i++) - locChildren[i].onEnter(); - }, - - /** - *

- * Event callback that is invoked when the Node enters in the 'stage'.
- * If the Node enters the 'stage' with a transition, this event is called when the transition finishes.
- * If you override onEnterTransitionDidFinish, you shall call its parent's one, e.g. Node::onEnterTransitionDidFinish() - *

- * @override - */ - onEnterTransitionDidFinish: function(){ - cc.Node.prototype.onEnterTransitionDidFinish.call(this); - var locChildren = this._protectedChildren; - for(var i = 0, len = locChildren.length;i< len;i++) - locChildren[i].onEnterTransitionDidFinish(); - }, - - /** - * Calls its parent's onExit and calls its protected children's onExit - * @override - */ - onExit:function(){ - cc.Node.prototype.onExit.call(this); - var locChildren = this._protectedChildren; - for(var i = 0, len = locChildren.length;i< len;i++) - locChildren[i].onExit(); - }, - - /** - *

- * Event callback that is called every time the Node leaves the 'stage'.
- * If the Node leaves the 'stage' with a transition, this callback is called when the transition starts. - *

- */ - onExitTransitionDidStart: function(){ - cc.Node.prototype.onExitTransitionDidStart.call(this); - var locChildren = this._protectedChildren; - for(var i = 0, len = locChildren.length;i< len;i++) - locChildren[i].onExitTransitionDidStart(); + _changePosition: function () { }, _createRenderCmd: function () { diff --git a/extensions/ccui/layouts/UILayout.js b/extensions/ccui/layouts/UILayout.js index 48788ac2d5..c9cd68b5fc 100644 --- a/extensions/ccui/layouts/UILayout.js +++ b/extensions/ccui/layouts/UILayout.js @@ -110,7 +110,7 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{ onEnter: function () { ccui.Widget.prototype.onEnter.call(this); if (this._clippingStencil) - this._clippingStencil.onEnter(); + this._clippingStencil._performRecursive(cc.Node._stateCallbackType.onEnter); this._doLayoutDirty = true; this._clippingRectDirty = true; }, @@ -122,7 +122,7 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{ onExit: function () { ccui.Widget.prototype.onExit.call(this); if (this._clippingStencil) - this._clippingStencil.onExit(); + this._clippingStencil._performRecursive(cc.Node._stateCallbackType.onExit); }, /** @@ -341,11 +341,11 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{ this._clippingStencil = new cc.DrawNode(); this._renderCmd.rebindStencilRendering(this._clippingStencil); if (this._running) - this._clippingStencil.onEnter(); + this._clippingStencil._performRecursive(cc.Node._stateCallbackType.onEnter); this._setStencilClippingSize(this._contentSize); } else { if (this._running && this._clippingStencil) - this._clippingStencil.onExit(); + this._clippingStencil._performRecursive(cc.Node._stateCallbackType.onExit); this._clippingStencil = null; } break; diff --git a/extensions/cocostudio/armature/display/CCDisplayManager.js b/extensions/cocostudio/armature/display/CCDisplayManager.js index dfed938c87..584f864b69 100644 --- a/extensions/cocostudio/armature/display/CCDisplayManager.js +++ b/extensions/cocostudio/armature/display/CCDisplayManager.js @@ -120,7 +120,7 @@ ccs.DisplayManager = ccs.Class.extend(/** @lends ccs.DisplayManager */{ } else if (display instanceof cc.ParticleSystem) { displayData = new ccs.ParticleDisplayData(); display.removeFromParent(); - display.cleanup(); + display._performRecursive(cc.Node._stateCallbackType.cleanup); var armature = this._bone.getArmature(); if (armature) display.setParent(armature); From c93c8e14d42e8a24fa4cddc6bc4879bec960edc3 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Fri, 9 Dec 2016 10:40:11 +0800 Subject: [PATCH 34/42] Improve UI and support lazy loading --- extensions/ccui/base-classes/UIWidget.js | 45 ++++++++++++++++++----- extensions/ccui/uiwidgets/UIText.js | 41 +++++++++++++++++++++ extensions/ccui/uiwidgets/UITextAtlas.js | 19 ++++++---- extensions/ccui/uiwidgets/UITextBMFont.js | 16 ++++---- 4 files changed, 97 insertions(+), 24 deletions(-) diff --git a/extensions/ccui/base-classes/UIWidget.js b/extensions/ccui/base-classes/UIWidget.js index 92d9b360b4..0c2d7dfbcc 100644 --- a/extensions/ccui/base-classes/UIWidget.js +++ b/extensions/ccui/base-classes/UIWidget.js @@ -204,6 +204,8 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ cc.eventManager.addListener(locListener, this); if(!this._usingLayoutComponent) this.updateSizeAndPosition(); + if (this._sizeDirty) + this._onSizeChanged(); cc.ProtectedNode.prototype.onEnter.call(this); }, @@ -347,9 +349,10 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ * @override */ setContentSize: function(contentSize, height){ - var locWidth = (height === undefined) ? contentSize.width : contentSize; - var locHeight = (height === undefined) ? contentSize.height : height; - cc.Node.prototype.setContentSize.call(this, locWidth, locHeight); + cc.Node.prototype.setContentSize.call(this, contentSize, height); + + var locWidth = this._contentSize.width; + var locHeight = this._contentSize.height; this._customSize.width = locWidth; this._customSize.height = locHeight; @@ -364,10 +367,18 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ this._sizePercent.x = (pSize.width > 0.0) ? locWidth / pSize.width : 0.0; this._sizePercent.y = (pSize.height > 0.0) ? locHeight / pSize.height : 0.0; } - this._onSizeChanged(); + + if (this._running) { + this._onSizeChanged(); + } else { + this._sizeDirty = true; + } }, _setWidth: function (w) { + if (w === this._contentSize.width) { + return; + } cc.Node.prototype._setWidth.call(this, w); this._customSize.width = w; if(this._unifySize){ @@ -381,9 +392,18 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ var locWidth = widgetParent ? widgetParent.width : this._parent.width; this._sizePercent.x = locWidth > 0 ? this._customSize.width / locWidth : 0; } - this._onSizeChanged(); + + if (this._running) { + this._onSizeChanged(); + } else { + this._sizeDirty = true; + } }, _setHeight: function (h) { + if (h === this._contentSize.height) { + return; + } + cc.Node.prototype._setHeight.call(this, h); this._customSize.height = h; if(this._unifySize){ @@ -397,7 +417,12 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ var locH = widgetParent ? widgetParent.height : this._parent.height; this._sizePercent.y = locH > 0 ? this._customSize.height / locH : 0; } - this._onSizeChanged(); + + if (this._running) { + this._onSizeChanged(); + } else { + this._sizeDirty = true; + } }, /** @@ -629,12 +654,13 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ */ _onSizeChanged: function () { if(!this._usingLayoutComponent){ - var locChildren = this.getChildren(); + var locChildren = this.getChildren(); for (var i = 0, len = locChildren.length; i < len; i++) { var child = locChildren[i]; - if(child instanceof ccui.Widget) + if (child instanceof ccui.Widget) child.updateSizeAndPosition(); } + this._sizeDirty = false; } }, @@ -1196,6 +1222,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ return; } this._positionPercent.x = percent; + this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.transformDirty); }, _setYPercent: function (percent) { if (this._usingLayoutComponent){ @@ -1205,6 +1232,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ return; } this._positionPercent.y = percent; + this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.transformDirty); }, /** @@ -1501,7 +1529,6 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ if (parameter) this.setLayoutParameter(parameter.clone()); } - this._onSizeChanged(); }, /*temp action*/ diff --git a/extensions/ccui/uiwidgets/UIText.js b/extensions/ccui/uiwidgets/UIText.js index c6270a082c..adc25f3573 100644 --- a/extensions/ccui/uiwidgets/UIText.js +++ b/extensions/ccui/uiwidgets/UIText.js @@ -105,6 +105,13 @@ ccui.Text = ccui.Widget.extend(/** @lends ccui.Text# */{ this._labelRendererAdaptDirty = true; }, + _setString: function (text) { + if(text === this._labelRenderer.getString()) return; + + this._labelRenderer.setString(text); + this._labelRendererAdaptDirty = true; + }, + /** * Gets the string value of ccui.Text. * @deprecated since v3.0, please use getString instead. @@ -142,6 +149,12 @@ ccui.Text = ccui.Widget.extend(/** @lends ccui.Text# */{ this._labelRendererAdaptDirty = true; }, + _setFontSize: function (size) { + this._labelRenderer.setFontSize(size); + this._fontSize = size; + this._labelRendererAdaptDirty = true; + }, + /** * Returns font Size of ccui.Text * @returns {Number} @@ -161,6 +174,16 @@ ccui.Text = ccui.Widget.extend(/** @lends ccui.Text# */{ this._labelRendererAdaptDirty = true; }, + _setFontName: function (name) { + this._fontName = name; + this._labelRenderer.setFontName(name); + this._labelRendererAdaptDirty = true; + }, + + _updateUITextContentSize: function () { + this._updateContentSizeWithTextureSize(this._labelRenderer.getContentSize()); + }, + /** * Returns font name of ccui.Text. * @returns {string} @@ -203,6 +226,14 @@ ccui.Text = ccui.Widget.extend(/** @lends ccui.Text# */{ this._labelRendererAdaptDirty = true; }, + _setTextAreaSize: function (size) { + this._labelRenderer.setDimensions(size); + if (!this._ignoreSize){ + this._customSize = size; + } + this._labelRendererAdaptDirty = true; + }, + /** * Returns renderer's dimension. * @returns {cc.Size} @@ -221,6 +252,12 @@ ccui.Text = ccui.Widget.extend(/** @lends ccui.Text# */{ this._labelRendererAdaptDirty = true; }, + + _setTextHorizontalAlignment: function (alignment) { + this._labelRenderer.setHorizontalAlignment(alignment); + this._labelRendererAdaptDirty = true; + }, + /** * Returns Horizontal Alignment of label * @returns {TEXT_ALIGNMENT_LEFT|TEXT_ALIGNMENT_CENTER|TEXT_ALIGNMENT_RIGHT} @@ -239,6 +276,10 @@ ccui.Text = ccui.Widget.extend(/** @lends ccui.Text# */{ this._labelRendererAdaptDirty = true; }, + _setTextVerticalAlignment: function (alignment) { + this._labelRenderer.setVerticalAlignment(alignment); + this._labelRendererAdaptDirty = true; + }, /** * Gets text vertical alignment. * @returns {VERTICAL_TEXT_ALIGNMENT_TOP|VERTICAL_TEXT_ALIGNMENT_CENTER|VERTICAL_TEXT_ALIGNMENT_BOTTOM} diff --git a/extensions/ccui/uiwidgets/UITextAtlas.js b/extensions/ccui/uiwidgets/UITextAtlas.js index b13b34d67e..98c4b89e63 100644 --- a/extensions/ccui/uiwidgets/UITextAtlas.js +++ b/extensions/ccui/uiwidgets/UITextAtlas.js @@ -63,6 +63,11 @@ ccui.TextAtlas = ccui.Widget.extend(/** @lends ccui.TextAtlas# */{ this._labelAtlasRenderer = new cc.LabelAtlas(); this._labelAtlasRenderer.setAnchorPoint(cc.p(0.5, 0.5)); this.addProtectedChild(this._labelAtlasRenderer, ccui.TextAtlas.RENDERER_ZORDER, -1); + + this._labelAtlasRenderer.addEventListener('load', function () { + this._updateContentSizeWithTextureSize(this._labelAtlasRenderer.getContentSize()); + this._findLayout(); + }, this); }, /** @@ -97,7 +102,7 @@ ccui.TextAtlas = ccui.Widget.extend(/** @lends ccui.TextAtlas# */{ * @param {String} value */ setString: function (value) { - if(value === this._labelAtlasRenderer.getString()) + if (value === this._labelAtlasRenderer.getString()) return; this._stringValue = value; this._labelAtlasRenderer.setString(value); @@ -137,7 +142,7 @@ ccui.TextAtlas = ccui.Widget.extend(/** @lends ccui.TextAtlas# */{ * Returns the length of string. * @returns {*|Number|long|int} */ - getStringLength: function(){ + getStringLength: function () { return this._labelAtlasRenderer.getStringLength(); }, @@ -146,8 +151,8 @@ ccui.TextAtlas = ccui.Widget.extend(/** @lends ccui.TextAtlas# */{ this._labelAtlasRendererAdaptDirty = true; }, - _adaptRenderers: function(){ - if (this._labelAtlasRendererAdaptDirty){ + _adaptRenderers: function () { + if (this._labelAtlasRendererAdaptDirty) { this._labelAtlasScaleChangedWithSize(); this._labelAtlasRendererAdaptDirty = false; } @@ -158,7 +163,7 @@ ccui.TextAtlas = ccui.Widget.extend(/** @lends ccui.TextAtlas# */{ * @overrider * @returns {cc.Size} */ - getVirtualRendererSize: function(){ + getVirtualRendererSize: function () { return this._labelAtlasRenderer.getContentSize(); }, @@ -195,7 +200,7 @@ ccui.TextAtlas = ccui.Widget.extend(/** @lends ccui.TextAtlas# */{ }, _copySpecialProperties: function (labelAtlas) { - if (labelAtlas){ + if (labelAtlas) { this.setProperty(labelAtlas._stringValue, labelAtlas._charMapFileName, labelAtlas._itemWidth, labelAtlas._itemHeight, labelAtlas._startCharMap); } }, @@ -228,4 +233,4 @@ ccui.TextAtlas.create = function (stringValue, charMapFile, itemWidth, itemHeigh * The zOrder value of ccui.TextAtlas's renderer. * @type {number} */ -ccui.TextAtlas.RENDERER_ZORDER = -1; \ No newline at end of file +ccui.TextAtlas.RENDERER_ZORDER = -1; diff --git a/extensions/ccui/uiwidgets/UITextBMFont.js b/extensions/ccui/uiwidgets/UITextBMFont.js index 8d61344569..25c92315cb 100644 --- a/extensions/ccui/uiwidgets/UITextBMFont.js +++ b/extensions/ccui/uiwidgets/UITextBMFont.js @@ -49,6 +49,7 @@ ccui.LabelBMFont = ccui.TextBMFont = ccui.Widget.extend(/** @lends ccui.TextBMFo */ ctor: function (text, filename) { ccui.Widget.prototype.ctor.call(this); + this._loader = new cc.Sprite.LoadManager(); if (filename !== undefined) { this.setFntFile(filename); @@ -80,14 +81,6 @@ ccui.LabelBMFont = ccui.TextBMFont = ccui.Widget.extend(/** @lends ccui.TextBMFo if (!locRenderer._textureLoaded) { locRenderer.addEventListener("load", function () { _self.setFntFile(_self._fntFileName); - var parent = _self.parent; - while (parent) { - if (parent.requestDoLayout) { - parent.requestDoLayout(); - break; - } - parent = parent.parent; - } }); } }, @@ -107,6 +100,13 @@ ccui.LabelBMFont = ccui.TextBMFont = ccui.Widget.extend(/** @lends ccui.TextBMFo * @param {String} value */ setString: function (value) { + this._loader.clear(); + if (!this._labelBMFontRenderer._textureLoaded) { + this._loader.add(this._labelBMFontRenderer, function () { + this.setString(value); + }, this); + return; + } if (value === this._labelBMFontRenderer.getString()) return; this._stringValue = value; From 8f05415083a1203f1b8ac2006e320afa46d9ffbb Mon Sep 17 00:00:00 2001 From: pandamicro Date: Fri, 9 Dec 2016 11:48:01 +0800 Subject: [PATCH 35/42] Reformat CCBoot and improve cc.loader implementation --- CCBoot.js | 250 ++++++++++++++---------------- cocos2d/core/platform/CCCommon.js | 20 --- cocos2d/core/platform/CCMacro.js | 7 + 3 files changed, 122 insertions(+), 155 deletions(-) diff --git a/CCBoot.js b/CCBoot.js index 00ba24bee4..a6f851e27f 100644 --- a/CCBoot.js +++ b/CCBoot.js @@ -56,34 +56,6 @@ _p._super; _p.ctor; _p = null; -/** - * Device oriented vertically, home button on the bottom - * @constant - * @type {Number} - */ -cc.ORIENTATION_PORTRAIT = 0; - -/** - * Device oriented vertically, home button on the top - * @constant - * @type {Number} - */ -cc.ORIENTATION_PORTRAIT_UPSIDE_DOWN = 1; - -/** - * Device oriented horizontally, home button on the right - * @constant - * @type {Number} - */ -cc.ORIENTATION_LANDSCAPE_LEFT = 2; - -/** - * Device oriented horizontally, home button on the left - * @constant - * @type {Number} - */ -cc.ORIENTATION_LANDSCAPE_RIGHT = 3; - /** * drawing primitive of game engine * @type {cc.DrawingPrimitive} @@ -110,10 +82,6 @@ cc._canvas = null; cc.container = null; cc._gameDiv = null; -cc.newElement = function (x) { - return document.createElement(x); -}; - /** * Iterate over an object or an array, executing a function for each matched element. * @param {object|array} obj @@ -142,11 +110,11 @@ cc.each = function (obj, iterator, context) { * @param {object} *sources * @returns {object} */ -cc.extend = function(target) { +cc.extend = function (target) { var sources = arguments.length >= 2 ? Array.prototype.slice.call(arguments, 1) : []; - cc.each(sources, function(src) { - for(var key in src) { + cc.each(sources, function (src) { + for (var key in src) { if (src.hasOwnProperty(key)) { target[key] = src[key]; } @@ -155,12 +123,32 @@ cc.extend = function(target) { return target; }; +/** + * Another way to subclass: Using Google Closure. + * The following code was copied + pasted from goog.base / goog.inherits + * @function + * @param {Function} childCtor + * @param {Function} parentCtor + */ +cc.inherits = function (childCtor, parentCtor) { + function tempCtor() {} + tempCtor.prototype = parentCtor.prototype; + childCtor.superClass_ = parentCtor.prototype; + childCtor.prototype = new tempCtor(); + childCtor.prototype.constructor = childCtor; + + // Copy "static" method, but doesn't generate subclasses. + // for( var i in parentCtor ) { + // childCtor[ i ] = parentCtor[ i ]; + // } +}; + /** * Check the obj whether is function or not * @param {*} obj * @returns {boolean} */ -cc.isFunction = function(obj) { +cc.isFunction = function (obj) { return typeof obj === 'function'; }; @@ -169,7 +157,7 @@ cc.isFunction = function(obj) { * @param {*} obj * @returns {boolean} */ -cc.isNumber = function(obj) { +cc.isNumber = function (obj) { return typeof obj === 'number' || Object.prototype.toString.call(obj) === '[object Number]'; }; @@ -178,7 +166,7 @@ cc.isNumber = function(obj) { * @param {*} obj * @returns {boolean} */ -cc.isString = function(obj) { +cc.isString = function (obj) { return typeof obj === 'string' || Object.prototype.toString.call(obj) === '[object String]'; }; @@ -187,7 +175,7 @@ cc.isString = function(obj) { * @param {*} obj * @returns {boolean} */ -cc.isArray = function(obj) { +cc.isArray = function (obj) { return Array.isArray(obj) || (typeof obj === 'object' && Object.prototype.toString.call(obj) === '[object Array]'); }; @@ -197,7 +185,7 @@ cc.isArray = function(obj) { * @param {*} obj * @returns {boolean} */ -cc.isUndefined = function(obj) { +cc.isUndefined = function (obj) { return typeof obj === 'undefined'; }; @@ -206,7 +194,7 @@ cc.isUndefined = function(obj) { * @param {*} obj * @returns {boolean} */ -cc.isObject = function(obj) { +cc.isObject = function (obj) { return typeof obj === "object" && Object.prototype.toString.call(obj) === '[object Object]'; }; @@ -239,8 +227,9 @@ cc.isCrossOrigin = function (url) { * @param {object} target * @constructor */ -cc.AsyncPool = function(srcObj, limit, iterator, onEnd, target){ +cc.AsyncPool = function (srcObj, limit, iterator, onEnd, target) { var self = this; + self._finished = false; self._srcObj = srcObj; self._limit = limit; self._pool = []; @@ -251,8 +240,8 @@ cc.AsyncPool = function(srcObj, limit, iterator, onEnd, target){ self._results = srcObj instanceof Array ? [] : {}; self._errors = srcObj instanceof Array ? [] : {}; - cc.each(srcObj, function(value, index){ - self._pool.push({index : index, value : value}); + cc.each(srcObj, function (value, index) { + self._pool.push({index: index, value: value}); }); self.size = self._pool.length; @@ -261,29 +250,29 @@ cc.AsyncPool = function(srcObj, limit, iterator, onEnd, target){ self._limit = self._limit || self.size; - self.onIterator = function(iterator, target){ + self.onIterator = function (iterator, target) { self._iterator = iterator; self._iteratorTarget = target; }; - self.onEnd = function(endCb, endCbTarget){ + self.onEnd = function (endCb, endCbTarget) { self._onEnd = endCb; self._onEndTarget = endCbTarget; }; - self._handleItem = function(){ + self._handleItem = function () { var self = this; - if(self._pool.length === 0 || self._workingSize >= self._limit) + if (self._pool.length === 0 || self._workingSize >= self._limit) return; //return directly if the array's length = 0 or the working size great equal limit number var item = self._pool.shift(); var value = item.value, index = item.index; self._workingSize++; self._iterator.call(self._iteratorTarget, value, index, - function(err, result) { - - self.finishedSize++; - self._workingSize--; + function (err, result) { + if (self._finished) { + return; + } if (err) { self._errors[this.index] = err; @@ -291,11 +280,12 @@ cc.AsyncPool = function(srcObj, limit, iterator, onEnd, target){ else { self._results[this.index] = result; } + + self.finishedSize++; + self._workingSize--; if (self.finishedSize === self.size) { - if (self._onEnd) { - var errors = self._errors.length === 0 ? null : self._errors; - self._onEnd.call(self._onEndTarget, errors, self._results); - } + var errors = self._errors.length === 0 ? null : self._errors; + self.onEnd(self._onEndTarget, errors, self._results); return; } self._handleItem(); @@ -303,16 +293,27 @@ cc.AsyncPool = function(srcObj, limit, iterator, onEnd, target){ self); }; - self.flow = function(){ + self.flow = function () { var self = this; - if(self._pool.length === 0) { - if(self._onEnd) + if (self._pool.length === 0) { + if (self._onEnd) self._onEnd.call(self._onEndTarget, null, []); return; } - for(var i = 0; i < self._limit; i++) + for (var i = 0; i < self._limit; i++) self._handleItem(); }; + + self.onEnd = function(errors, results) { + self._finished = true; + if (self._onEnd) { + var selector = self._onEnd; + var target = self._onEndTarget; + self._onEnd = null; + self._onEndTarget = null; + selector.call(target, errors, results); + } + } }; /** @@ -326,8 +327,8 @@ cc.async = /** @lends cc.async# */{ * @param {Object} [target] * @return {cc.AsyncPool} */ - series : function(tasks, cb, target){ - var asyncPool = new cc.AsyncPool(tasks, 1, function(func, index, cb1){ + series: function (tasks, cb, target) { + var asyncPool = new cc.AsyncPool(tasks, 1, function (func, index, cb1) { func.call(target, cb1); }, cb, target); asyncPool.flow(); @@ -341,8 +342,8 @@ cc.async = /** @lends cc.async# */{ * @param {Object} [target] * @return {cc.AsyncPool} */ - parallel : function(tasks, cb, target){ - var asyncPool = new cc.AsyncPool(tasks, 0, function(func, index, cb1){ + parallel: function (tasks, cb, target) { + var asyncPool = new cc.AsyncPool(tasks, 0, function (func, index, cb1) { func.call(target, cb1); }, cb, target); asyncPool.flow(); @@ -356,14 +357,14 @@ cc.async = /** @lends cc.async# */{ * @param {Object} [target] * @return {cc.AsyncPool} */ - waterfall : function(tasks, cb, target){ + waterfall: function (tasks, cb, target) { var args = []; var lastResults = [null];//the array to store the last results var asyncPool = new cc.AsyncPool(tasks, 1, function (func, index, cb1) { args.push(function (err) { args = Array.prototype.slice.call(arguments, 1); - if(tasks.length - 1 === index) lastResults = lastResults.concat(args);//while the last task + if (tasks.length - 1 === index) lastResults = lastResults.concat(args);//while the last task cb1.apply(null, arguments); }); func.apply(target, args); @@ -386,9 +387,9 @@ cc.async = /** @lends cc.async# */{ * @param {Object} [target] * @return {cc.AsyncPool} */ - map : function(tasks, iterator, callback, target){ + map: function (tasks, iterator, callback, target) { var locIterator = iterator; - if(typeof(iterator) === "object"){ + if (typeof(iterator) === "object") { callback = iterator.cb; target = iterator.iteratorTarget; locIterator = iterator.iterator; @@ -406,7 +407,7 @@ cc.async = /** @lends cc.async# */{ * @param {function} cb callback * @param {Object} [target] */ - mapLimit : function(tasks, limit, iterator, cb, target){ + mapLimit: function (tasks, limit, iterator, cb, target) { var asyncPool = new cc.AsyncPool(tasks, limit, iterator, cb, target); asyncPool.flow(); return asyncPool; @@ -460,11 +461,11 @@ cc.path = /** @lends cc.path# */{ * @param {string} fileName * @returns {string} */ - mainFileName: function(fileName){ - if(fileName){ + mainFileName: function (fileName) { + if (fileName) { var idx = fileName.lastIndexOf("."); - if(idx !== -1) - return fileName.substring(0,idx); + if (idx !== -1) + return fileName.substring(0, idx); } return fileName; }, @@ -559,14 +560,14 @@ cc.path = /** @lends cc.path# */{ return pathStr.substring(0, index) + basename + ext + tempStr; }, //todo make public after verification - _normalize: function(url){ + _normalize: function (url) { var oldUrl = url = String(url); //removing all ../ do { oldUrl = url; url = url.replace(this.normalizeRE, ""); - } while(oldUrl.length !== url.length); + } while (oldUrl.length !== url.length); return url; } }; @@ -696,12 +697,12 @@ cc.loader = (function () { var d = document, self = this, s = document.createElement('script'); s.async = isAsync; _jsCache[jsPath] = true; - if(cc.game.config["noCache"] && typeof jsPath === "string"){ - if(self._noCacheRex.test(jsPath)) + if (cc.game.config["noCache"] && typeof jsPath === "string") { + if (self._noCacheRex.test(jsPath)) s.src = jsPath + "&_t=" + (new Date() - 0); else s.src = jsPath + "?_t=" + (new Date() - 0); - }else{ + } else { s.src = jsPath; } s.addEventListener('load', function () { @@ -763,17 +764,17 @@ cc.loader = (function () { // IE-specific logic here xhr.setRequestHeader("Accept-Charset", "utf-8"); xhr.onreadystatechange = function () { - if(xhr.readyState === 4) + if (xhr.readyState === 4) xhr.status === 200 ? cb(null, xhr.responseText) : cb({status:xhr.status, errorMessage:errInfo}, null); }; } else { if (xhr.overrideMimeType) xhr.overrideMimeType("text\/plain; charset=utf-8"); xhr.onload = function () { - if(xhr.readyState === 4) + if (xhr.readyState === 4) xhr.status === 200 ? cb(null, xhr.responseText) : cb({status:xhr.status, errorMessage:errInfo}, null); }; - xhr.onerror = function(){ - cb({status:xhr.status, errorMessage:errInfo}, null); + xhr.onerror = function () { + cb({status: xhr.status, errorMessage: errInfo}, null); }; } xhr.send(null); @@ -784,26 +785,6 @@ cc.loader = (function () { }); } }, - _loadTxtSync: function (url) { - if (!cc._isNodeJs) { - var xhr = this.getXMLHttpRequest(); - xhr.open("GET", url, false); - if (/msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent)) { - // IE-specific logic here - xhr.setRequestHeader("Accept-Charset", "utf-8"); - } else { - if (xhr.overrideMimeType) xhr.overrideMimeType("text\/plain; charset=utf-8"); - } - xhr.send(null); - if (!xhr.readyState === 4 || xhr.status !== 200) { - return null; - } - return xhr.responseText; - } else { - var fs = require("fs"); - return fs.readFileSync(url).toString(); - } - }, loadCsb: function(url, cb){ var xhr = new XMLHttpRequest(), @@ -972,14 +953,13 @@ cc.loader = (function () { return cb(); } var realUrl = url; - if (!_urlRegExp.test(url)) - { + if (!_urlRegExp.test(url)) { var basePath = loader.getBasePath ? loader.getBasePath() : self.resPath; realUrl = self.getUrl(basePath, url); } - if(cc.game.config["noCache"] && typeof realUrl === "string"){ - if(self._noCacheRex.test(realUrl)) + if (cc.game.config["noCache"] && typeof realUrl === "string") { + if (self._noCacheRex.test(realUrl)) realUrl += "&_t=" + (new Date() - 0); else realUrl += "?_t=" + (new Date() - 0); @@ -989,7 +969,7 @@ cc.loader = (function () { cc.log(err); self.cache[url] = null; delete self.cache[url]; - cb({status:520, errorMessage:err}, null); + cb({status: 520, errorMessage: err}, null); } else { self.cache[url] = data; cb(null, data); @@ -1033,30 +1013,30 @@ cc.loader = (function () { * @param {function|Object} [loadCallback] * @return {cc.AsyncPool} */ - load : function(resources, option, loadCallback){ + load: function (resources, option, loadCallback) { var self = this; var len = arguments.length; - if(len === 0) + if (len === 0) throw new Error("arguments error!"); - if(len === 3){ - if(typeof option === "function"){ - if(typeof loadCallback === "function") - option = {trigger : option, cb : loadCallback }; + if (len === 3) { + if (typeof option === "function") { + if (typeof loadCallback === "function") + option = {trigger: option, cb: loadCallback}; else - option = { cb : option, cbTarget : loadCallback}; + option = {cb: option, cbTarget: loadCallback}; } - }else if(len === 2){ - if(typeof option === "function") - option = {cb : option}; - }else if(len === 1){ + } else if (len === 2) { + if (typeof option === "function") + option = {cb: option}; + } else if (len === 1) { option = {}; } - if(!(resources instanceof Array)) + if (!(resources instanceof Array)) resources = [resources]; var asyncPool = new cc.AsyncPool( - resources, 0, + resources, cc.CONCURRENCY_HTTP_REQUEST_COUNT, function (value, index, AsyncPoolCallback, aPool) { self._loadResIterator(value, index, function (err) { var arr = Array.prototype.slice.call(arguments, 1); @@ -1190,37 +1170,37 @@ cc.loader = (function () { * cc.formatStr(a, b, c); * @returns {String} */ -cc.formatStr = function(){ +cc.formatStr = function () { var args = arguments; var l = args.length; - if(l < 1) + if (l < 1) return ""; var str = args[0]; var needToFormat = true; - if(typeof str === "object"){ + if (typeof str === "object") { needToFormat = false; } - for(var i = 1; i < l; ++i){ + for (var i = 1; i < l; ++i) { var arg = args[i]; - if(needToFormat){ - while(true){ + if (needToFormat) { + while (true) { var result = null; - if(typeof arg === "number"){ + if (typeof arg === "number") { result = str.match(/(%d)|(%s)/); - if(result){ + if (result) { str = str.replace(/(%d)|(%s)/, arg); break; } } result = str.match(/%s/); - if(result) + if (result) str = str.replace(/%s/, arg); else str += " " + arg; break; } - }else + } else str += " " + arg; } return str; @@ -2506,7 +2486,7 @@ cc.game = /** @lends cc.game# */{ _setAnimFrame: function () { this._lastTime = new Date(); this._frameTime = 1000 / cc.game.config[cc.game.CONFIG_KEY.frameRate]; - if((cc.sys.os === cc.sys.OS_IOS && cc.sys.browserType === cc.sys.BROWSER_TYPE_WECHAT) || cc.game.config[cc.game.CONFIG_KEY.frameRate] !== 60) { + if ((cc.sys.os === cc.sys.OS_IOS && cc.sys.browserType === cc.sys.BROWSER_TYPE_WECHAT) || cc.game.config[cc.game.CONFIG_KEY.frameRate] !== 60) { window.requestAnimFrame = this._stTime; window.cancelAnimationFrame = this._ctTime; } @@ -2530,7 +2510,7 @@ cc.game = /** @lends cc.game# */{ this._ctTime; } }, - _stTime: function(callback){ + _stTime: function (callback) { var currTime = new Date().getTime(); var timeToCall = Math.max(0, cc.game._frameTime - (currTime - cc.game._lastTime)); var id = window.setTimeout(function() { callback(); }, @@ -2538,7 +2518,7 @@ cc.game = /** @lends cc.game# */{ cc.game._lastTime = currTime + timeToCall; return id; }, - _ctTime: function(id){ + _ctTime: function (id) { window.clearTimeout(id); }, //Run game. @@ -2551,7 +2531,7 @@ cc.game = /** @lends cc.game# */{ callback = function () { if (!self._paused) { director.mainLoop(); - if(self._intervalId) + if (self._intervalId) window.cancelAnimationFrame(self._intervalId); self._intervalId = window.requestAnimFrame(callback); } @@ -2747,7 +2727,7 @@ cc.game = /** @lends cc.game# */{ win.addEventListener("focus", onShow, false); } - if(navigator.userAgent.indexOf("MicroMessenger") > -1){ + if (navigator.userAgent.indexOf("MicroMessenger") > -1) { win.onfocus = function(){ onShow() }; } diff --git a/cocos2d/core/platform/CCCommon.js b/cocos2d/core/platform/CCCommon.js index 296193ea75..b99ee95f2f 100644 --- a/cocos2d/core/platform/CCCommon.js +++ b/cocos2d/core/platform/CCCommon.js @@ -245,24 +245,4 @@ cc.getImageFormatByData = function (imgData) { return cc.FMT_TIFF; } return cc.FMT_UNKNOWN; -}; - -/** - * Another way to subclass: Using Google Closure. - * The following code was copied + pasted from goog.base / goog.inherits - * @function - * @param {Function} childCtor - * @param {Function} parentCtor - */ -cc.inherits = function (childCtor, parentCtor) { - function tempCtor() {} - tempCtor.prototype = parentCtor.prototype; - childCtor.superClass_ = parentCtor.prototype; - childCtor.prototype = new tempCtor(); - childCtor.prototype.constructor = childCtor; - - // Copy "static" method, but doesn't generate subclasses. -// for( var i in parentCtor ) { -// childCtor[ i ] = parentCtor[ i ]; -// } }; \ No newline at end of file diff --git a/cocos2d/core/platform/CCMacro.js b/cocos2d/core/platform/CCMacro.js index 588342eb18..30b9547119 100644 --- a/cocos2d/core/platform/CCMacro.js +++ b/cocos2d/core/platform/CCMacro.js @@ -497,6 +497,13 @@ cc.ORIENTATION_LANDSCAPE = 2; */ cc.ORIENTATION_AUTO = 3; +/** + * The limit count for concurrency http request, useful in some mobile browsers + * @constant + * @type Number + */ +cc.CONCURRENCY_HTTP_REQUEST_COUNT = cc.sys.isMobile ? 9 : 0; + // ------------------- vertex attrib flags ----------------------------- /** From f37ba7cf1fe691492beaa882695a272dfa37436d Mon Sep 17 00:00:00 2001 From: pandamicro Date: Fri, 9 Dec 2016 11:48:22 +0800 Subject: [PATCH 36/42] Reformat code and improve CCAudio --- cocos2d/audio/CCAudio.js | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/cocos2d/audio/CCAudio.js b/cocos2d/audio/CCAudio.js index b48b63d411..0ca259b60a 100644 --- a/cocos2d/audio/CCAudio.js +++ b/cocos2d/audio/CCAudio.js @@ -118,7 +118,7 @@ cc.Audio = cc.Class.extend({ cc.Audio.touchPlayList.push({ loop: loop, offset: offset, audio: this._element }); } - if (cc.Audio.bindTouch === false) { + if (cc.Audio.bindTouch === false && this._element.paused) { cc.Audio.bindTouch = true; // Listen to the touchstart body event and play the audio when necessary. cc.game.canvas.addEventListener('touchstart', cc.Audio.touchStart); @@ -391,8 +391,6 @@ cc.Audio.WebAudio.prototype = { if (audio) return cb(null, audio); - var i; - if (cc.loader.audioPath) realUrl = cc.path.join(cc.loader.audioPath, realUrl); @@ -528,6 +526,12 @@ cc.Audio.WebAudio.prototype = { stopMusic: function(releaseData){ var audio = this._currMusic; if (audio) { + var list = cc.Audio.touchPlayList; + for (var i=list.length-1; i>=0; --i) { + if (this[i] && this[i].audio === audio._element) + list.splice(i, 1); + } + audio.stop(); this._currMusic = null; if (releaseData) @@ -541,7 +545,7 @@ cc.Audio.WebAudio.prototype = { * //example * cc.audioEngine.pauseMusic(); */ - pauseMusic: function(){ + pauseMusic: function () { var audio = this._currMusic; if (audio) audio.pause(); @@ -553,7 +557,7 @@ cc.Audio.WebAudio.prototype = { * //example * cc.audioEngine.resumeMusic(); */ - resumeMusic: function(){ + resumeMusic: function () { var audio = this._currMusic; if (audio) audio.resume(); @@ -649,9 +653,7 @@ cc.Audio.WebAudio.prototype = { effectList = this._audioPool[url] = []; } - var i; - - for (i = 0; i < effectList.length; i++) { + for (var i = 0; i < effectList.length; i++) { if (!effectList[i].getPlaying()) { break; } From 467008aaf5bab9e8139c2da0aeb20154199443dc Mon Sep 17 00:00:00 2001 From: pandamicro Date: Mon, 12 Dec 2016 10:23:43 +0800 Subject: [PATCH 37/42] Delay initialize shader cache --- CCBoot.js | 3 +- cocos2d/core/platform/CCMacro.js | 4 +- cocos2d/shaders/CCShaderCache.js | 111 ++++++------------------------- 3 files changed, 22 insertions(+), 96 deletions(-) diff --git a/CCBoot.js b/CCBoot.js index a6f851e27f..385c030f58 100644 --- a/CCBoot.js +++ b/CCBoot.js @@ -313,7 +313,7 @@ cc.AsyncPool = function (srcObj, limit, iterator, onEnd, target) { self._onEndTarget = null; selector.call(target, errors, results); } - } + }; }; /** @@ -2659,7 +2659,6 @@ cc.game = /** @lends cc.game# */{ 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 = {}; diff --git a/cocos2d/core/platform/CCMacro.js b/cocos2d/core/platform/CCMacro.js index 30b9547119..e5e4e3c609 100644 --- a/cocos2d/core/platform/CCMacro.js +++ b/cocos2d/core/platform/CCMacro.js @@ -648,7 +648,7 @@ cc.SHADER_POSITION_TEXTURE = "ShaderPositionTexture"; * @constant * @type {String} */ -cc.SHADER_POSITION_TEXTURE_UCOLOR = "ShaderPositionTexture_uColor"; +cc.SHADER_POSITION_TEXTURE_UCOLOR = "ShaderPositionTextureUColor"; /** * @constant * @type {String} @@ -658,7 +658,7 @@ cc.SHADER_POSITION_TEXTUREA8COLOR = "ShaderPositionTextureA8Color"; * @constant * @type {String} */ -cc.SHADER_POSITION_UCOLOR = "ShaderPosition_uColor"; +cc.SHADER_POSITION_UCOLOR = "ShaderPositionUColor"; /** * @constant * @type {String} diff --git a/cocos2d/shaders/CCShaderCache.js b/cocos2d/shaders/CCShaderCache.js index be23a9cc93..f287633114 100644 --- a/cocos2d/shaders/CCShaderCache.js +++ b/cocos2d/shaders/CCShaderCache.js @@ -107,67 +107,67 @@ cc.shaderCache = /** @lends cc.shaderCache# */{ _programs: {}, _init: function () { - this.loadDefaultShaders(); + // this.loadDefaultShaders(); return true; }, _loadDefaultShader: function (program, type) { switch (type) { - case this.TYPE_POSITION_TEXTURECOLOR: + case cc.SHADER_POSITION_TEXTURECOLOR: program.initWithVertexShaderByteArray(cc.SHADER_POSITION_TEXTURE_COLOR_VERT, cc.SHADER_POSITION_TEXTURE_COLOR_FRAG); program.addAttribute(cc.ATTRIBUTE_NAME_POSITION, cc.VERTEX_ATTRIB_POSITION); program.addAttribute(cc.ATTRIBUTE_NAME_COLOR, cc.VERTEX_ATTRIB_COLOR); program.addAttribute(cc.ATTRIBUTE_NAME_TEX_COORD, cc.VERTEX_ATTRIB_TEX_COORDS); break; - case this.TYPE_SPRITE_POSITION_TEXTURECOLOR: + case cc.SHADER_SPRITE_POSITION_TEXTURECOLOR: program.initWithVertexShaderByteArray(cc.SHADER_SPRITE_POSITION_TEXTURE_COLOR_VERT, cc.SHADER_POSITION_TEXTURE_COLOR_FRAG); program.addAttribute(cc.ATTRIBUTE_NAME_POSITION, cc.VERTEX_ATTRIB_POSITION); program.addAttribute(cc.ATTRIBUTE_NAME_COLOR, cc.VERTEX_ATTRIB_COLOR); program.addAttribute(cc.ATTRIBUTE_NAME_TEX_COORD, cc.VERTEX_ATTRIB_TEX_COORDS); break; - case this.TYPE_POSITION_TEXTURECOLOR_ALPHATEST: + case cc.SHADER_POSITION_TEXTURECOLORALPHATEST: program.initWithVertexShaderByteArray(cc.SHADER_POSITION_TEXTURE_COLOR_VERT, cc.SHADER_POSITION_TEXTURE_COLOR_ALPHATEST_FRAG); program.addAttribute(cc.ATTRIBUTE_NAME_POSITION, cc.VERTEX_ATTRIB_POSITION); program.addAttribute(cc.ATTRIBUTE_NAME_COLOR, cc.VERTEX_ATTRIB_COLOR); program.addAttribute(cc.ATTRIBUTE_NAME_TEX_COORD, cc.VERTEX_ATTRIB_TEX_COORDS); break; - case this.TYPE_SPRITE_POSITION_TEXTURECOLOR_ALPHATEST: + case cc.SHADER_SPRITE_POSITION_TEXTURECOLORALPHATEST: program.initWithVertexShaderByteArray(cc.SHADER_SPRITE_POSITION_TEXTURE_COLOR_VERT, cc.SHADER_POSITION_TEXTURE_COLOR_ALPHATEST_FRAG); program.addAttribute(cc.ATTRIBUTE_NAME_POSITION, cc.VERTEX_ATTRIB_POSITION); program.addAttribute(cc.ATTRIBUTE_NAME_COLOR, cc.VERTEX_ATTRIB_COLOR); program.addAttribute(cc.ATTRIBUTE_NAME_TEX_COORD, cc.VERTEX_ATTRIB_TEX_COORDS); break; - case this.TYPE_POSITION_COLOR: + case cc.SHADER_POSITION_COLOR: program.initWithVertexShaderByteArray(cc.SHADER_POSITION_COLOR_VERT, cc.SHADER_POSITION_COLOR_FRAG); program.addAttribute(cc.ATTRIBUTE_NAME_POSITION, cc.VERTEX_ATTRIB_POSITION); program.addAttribute(cc.ATTRIBUTE_NAME_COLOR, cc.VERTEX_ATTRIB_COLOR); break; - case this.TYPE_SPRITE_POSITION_COLOR: + case cc.SHADER_SPRITE_POSITION_COLOR: program.initWithVertexShaderByteArray(cc.SHADER_SPRITE_POSITION_COLOR_VERT, cc.SHADER_POSITION_COLOR_FRAG); program.addAttribute(cc.ATTRIBUTE_NAME_POSITION, cc.VERTEX_ATTRIB_POSITION); program.addAttribute(cc.ATTRIBUTE_NAME_COLOR, cc.VERTEX_ATTRIB_COLOR); break; - case this.TYPE_POSITION_TEXTURE: + case cc.SHADER_POSITION_TEXTURE: program.initWithVertexShaderByteArray(cc.SHADER_POSITION_TEXTURE_VERT, cc.SHADER_POSITION_TEXTURE_FRAG); program.addAttribute(cc.ATTRIBUTE_NAME_POSITION, cc.VERTEX_ATTRIB_POSITION); program.addAttribute(cc.ATTRIBUTE_NAME_TEX_COORD, cc.VERTEX_ATTRIB_TEX_COORDS); break; - case this.TYPE_POSITION_TEXTURE_UCOLOR: + case cc.SHADER_POSITION_TEXTURE_UCOLOR: program.initWithVertexShaderByteArray(cc.SHADER_POSITION_TEXTURE_UCOLOR_VERT, cc.SHADER_POSITION_TEXTURE_UCOLOR_FRAG); program.addAttribute(cc.ATTRIBUTE_NAME_POSITION, cc.VERTEX_ATTRIB_POSITION); program.addAttribute(cc.ATTRIBUTE_NAME_TEX_COORD, cc.VERTEX_ATTRIB_TEX_COORDS); break; - case this.TYPE_POSITION_TEXTURE_A8COLOR: + case cc.SHADER_POSITION_TEXTUREA8COLOR: program.initWithVertexShaderByteArray(cc.SHADER_POSITION_TEXTURE_A8COLOR_VERT, cc.SHADER_POSITION_TEXTURE_A8COLOR_FRAG); program.addAttribute(cc.ATTRIBUTE_NAME_POSITION, cc.VERTEX_ATTRIB_POSITION); program.addAttribute(cc.ATTRIBUTE_NAME_COLOR, cc.VERTEX_ATTRIB_COLOR); program.addAttribute(cc.ATTRIBUTE_NAME_TEX_COORD, cc.VERTEX_ATTRIB_TEX_COORDS); break; - case this.TYPE_POSITION_UCOLOR: + case cc.SHADER_POSITION_UCOLOR: program.initWithVertexShaderByteArray(cc.SHADER_POSITION_UCOLOR_VERT, cc.SHADER_POSITION_UCOLOR_FRAG); program.addAttribute("aVertex", cc.VERTEX_ATTRIB_POSITION); break; - case this.TYPE_POSITION_LENGTH_TEXTURECOLOR: + case cc.SHADER_POSITION_LENGTHTEXTURECOLOR: program.initWithVertexShaderByteArray(cc.SHADER_POSITION_COLOR_LENGTH_TEXTURE_VERT, cc.SHADER_POSITION_COLOR_LENGTH_TEXTURE_FRAG); program.addAttribute(cc.ATTRIBUTE_NAME_POSITION, cc.VERTEX_ATTRIB_POSITION); program.addAttribute(cc.ATTRIBUTE_NAME_TEX_COORD, cc.VERTEX_ATTRIB_TEX_COORDS); @@ -188,85 +188,6 @@ cc.shaderCache = /** @lends cc.shaderCache# */{ * loads the default shaders */ loadDefaultShaders: function () { - // Position Texture Color shader - var program = new cc.GLProgram(); - this._loadDefaultShader(program, this.TYPE_POSITION_TEXTURECOLOR); - this._programs[cc.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[cc.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[cc.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[cc.SHADER_SPRITE_POSITION_TEXTURECOLORALPHATEST] = program; - this._programs["ShaderSpritePositionTextureColorAlphaTest"] = program; - - // - // Position, Color shader - // - program = new cc.GLProgram(); - this._loadDefaultShader(program, this.TYPE_POSITION_COLOR); - this._programs[cc.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[cc.SHADER_SPRITE_POSITION_COLOR] = program; - this._programs["ShaderSpritePositionColor"] = program; - - // - // Position Texture shader - // - program = new cc.GLProgram(); - this._loadDefaultShader(program, this.TYPE_POSITION_TEXTURE); - this._programs[cc.SHADER_POSITION_TEXTURE] = program; - this._programs["ShaderPositionTexture"] = program; - - // - // Position, Texture attribs, 1 Color as uniform shader - // - program = new cc.GLProgram(); - this._loadDefaultShader(program, this.TYPE_POSITION_TEXTURE_UCOLOR); - this._programs[cc.SHADER_POSITION_TEXTURE_UCOLOR] = program; - this._programs["ShaderPositionTextureUColor"] = program; - - // - // Position Texture A8 Color shader - // - program = new cc.GLProgram(); - this._loadDefaultShader(program, this.TYPE_POSITION_TEXTURE_A8COLOR); - this._programs[cc.SHADER_POSITION_TEXTUREA8COLOR] = program; - this._programs["ShaderPositionTextureA8Color"] = program; - - // - // Position and 1 color passed as a uniform (to similate glColor4ub ) - // - program = new cc.GLProgram(); - this._loadDefaultShader(program, this.TYPE_POSITION_UCOLOR); - this._programs[cc.SHADER_POSITION_UCOLOR] = program; - this._programs["ShaderPositionUColor"] = program; - - // - // Position, Legth(TexCoords, Color (used by Draw Node basically ) - // - program = new cc.GLProgram(); - this._loadDefaultShader(program, this.TYPE_POSITION_LENGTH_TEXTURECOLOR); - this._programs[cc.SHADER_POSITION_LENGTHTEXTURECOLOR] = program; - this._programs["ShaderPositionLengthTextureColor"] = program; }, /** @@ -336,6 +257,12 @@ cc.shaderCache = /** @lends cc.shaderCache# */{ * @param {String} key */ programForKey: function (key) { + if (!this._programs[key]) { + var program = new cc.GLProgram(); + this._loadDefaultShader(program, key); + this._programs[key] = program; + } + return this._programs[key]; }, @@ -345,7 +272,7 @@ cc.shaderCache = /** @lends cc.shaderCache# */{ * @return {cc.GLProgram} */ getProgram: function (shaderName) { - return this._programs[shaderName]; + return this.programForKey(shaderName); }, /** From 4d71e89a036f67a6ef89a0eb4bb0f8a102bbdeae Mon Sep 17 00:00:00 2001 From: pandamicro Date: Mon, 12 Dec 2016 10:25:17 +0800 Subject: [PATCH 38/42] Fix bug --- extensions/spine/CCSkeletonAnimation.js | 2 +- moduleConfig.json | 3 +++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/extensions/spine/CCSkeletonAnimation.js b/extensions/spine/CCSkeletonAnimation.js index f78d56cc89..b5308f2b52 100644 --- a/extensions/spine/CCSkeletonAnimation.js +++ b/extensions/spine/CCSkeletonAnimation.js @@ -343,6 +343,6 @@ sp.SkeletonAnimation = sp.Skeleton.extend(/** @lends sp.SkeletonAnimation# */{ * @param {Number} [scale] scale can be specified on the JSON or binary loader which will scale the bone positions, image sizes, and animation translations. * @returns {sp.Skeleton} */ -sp.SkeletonAnimation.create = function (skeletonDataFile, atlasFile/* or atlas*/, scale) { +sp.SkeletonAnimation.createWithJsonFile = sp.SkeletonAnimation.create = function (skeletonDataFile, atlasFile/* or atlas*/, scale) { return new sp.SkeletonAnimation(skeletonDataFile, atlasFile, scale); }; \ No newline at end of file diff --git a/moduleConfig.json b/moduleConfig.json index b36d7c4121..99e383e35f 100644 --- a/moduleConfig.json +++ b/moduleConfig.json @@ -247,6 +247,9 @@ "tilemap" : [ "core", "compression", + "cocos2d/compression/gzip.js", + "cocos2d/compression/zlib.min.js", + "cocos2d/tilemap/CCTGAlib.js", "cocos2d/tilemap/CCTMXTiledMap.js", "cocos2d/tilemap/CCTMXXMLParser.js", From 6325b105789c646fe8fd1dd581160033b3516966 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Mon, 12 Dec 2016 10:26:14 +0800 Subject: [PATCH 39/42] Improve visit logic, reduce call stack depth --- cocos2d/actions/CCAction.js | 2 +- cocos2d/clipping-nodes/CCClippingNode.js | 35 +++--- .../CCClippingNodeCanvasRenderCmd.js | 33 +++--- .../CCClippingNodeWebGLRenderCmd.js | 31 ++---- cocos2d/core/base-nodes/CCNode.js | 36 ++++++- .../core/base-nodes/CCNodeCanvasRenderCmd.js | 48 +++------ .../core/base-nodes/CCNodeWebGLRenderCmd.js | 2 +- .../labelttf/CCLabelTTFCanvasRenderCmd.js | 2 +- cocos2d/core/layers/CCLayer.js | 83 +++++++++++++++ cocos2d/core/layers/CCLayerCanvasRenderCmd.js | 45 +------- cocos2d/core/layers/CCLayerWebGLRenderCmd.js | 2 +- cocos2d/parallax/CCParallaxNodeRenderCmd.js | 4 +- cocos2d/particle/CCParticleBatchNode.js | 11 ++ .../CCParticleBatchNodeWebGLRenderCmd.js | 22 ---- cocos2d/render-texture/CCRenderTexture.js | 12 +++ .../CCRenderTextureCanvasRenderCmd.js | 7 -- .../CCRenderTextureWebGLRenderCmd.js | 21 ---- .../ccui/base-classes/CCProtectedNode.js | 56 ++++++++++ .../CCProtectedNodeCanvasRenderCmd.js | 52 --------- .../CCProtectedNodeWebGLRenderCmd.js | 55 ---------- .../ccui/base-classes/UIWidgetRenderCmd.js | 36 +++++-- extensions/ccui/layouts/UILayout.js | 100 ++++++++++++------ .../ccui/layouts/UILayoutCanvasRenderCmd.js | 62 +---------- .../ccui/layouts/UILayoutWebGLRenderCmd.js | 75 +++---------- extensions/ccui/uiwidgets/UIVideoPlayer.js | 54 +++++----- extensions/ccui/uiwidgets/UIWebView.js | 55 +++++----- .../uiwidgets/scroll-widget/UIScrollView.js | 76 ++++++++++--- .../UIScrollViewCanvasRenderCmd.js | 15 --- .../UIScrollViewWebGLRenderCmd.js | 17 --- extensions/cocostudio/armature/CCArmature.js | 8 ++ extensions/cocostudio/timeline/CCBoneNode.js | 12 +-- .../cocostudio/timeline/CCSkeletonNode.js | 2 +- extensions/gui/scrollview/CCScrollView.js | 28 +++++ .../scrollview/CCScrollViewCanvasRenderCmd.js | 21 ---- .../scrollview/CCScrollViewWebGLRenderCmd.js | 35 ------ 35 files changed, 531 insertions(+), 624 deletions(-) diff --git a/cocos2d/actions/CCAction.js b/cocos2d/actions/CCAction.js index 1fdc778d29..e5487824aa 100644 --- a/cocos2d/actions/CCAction.js +++ b/cocos2d/actions/CCAction.js @@ -239,7 +239,7 @@ cc.Action.create = cc.action; */ cc.FiniteTimeAction = cc.Action.extend(/** @lends cc.FiniteTimeAction# */{ // duration in seconds - _duration:0, + _duration: 0, /** * Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function. diff --git a/cocos2d/clipping-nodes/CCClippingNode.js b/cocos2d/clipping-nodes/CCClippingNode.js index 2dcf3c606a..14edbc72fc 100644 --- a/cocos2d/clipping-nodes/CCClippingNode.js +++ b/cocos2d/clipping-nodes/CCClippingNode.js @@ -66,19 +66,6 @@ cc.ClippingNode = cc.Node.extend(/** @lends cc.ClippingNode# */{ this._renderCmd.initStencilBits(); }, - /** - * Initialization of the node, please do not call this function by yourself, you should pass the parameters to constructor to initialize it
. - * @function - * @param {cc.Node} [stencil=null] - */ - init: function (stencil) { - this._stencil = stencil; - this.alphaThreshold = 1; - this.inverted = false; - this._renderCmd.initStencilBits(); - return true; - }, - /** *

* Event callback that is invoked every time when node enters the 'stage'.
@@ -135,6 +122,28 @@ cc.ClippingNode = cc.Node.extend(/** @lends cc.ClippingNode# */{ cc.Node.prototype.onExit.call(this); }, + visit: function (parent) { + if (!this._visible) + return; + + this._renderCmd.clippingVisit(parent && parent._renderCmd); + }, + + _visitChildren: function () { + var renderer = cc.renderer; + if (this._reorderChildDirty) { + this.sortAllChildren(); + } + var children = this._children, child; + for (var i = 0, len = children.length; i < len; i++) { + child = children[i]; + if (child && child._visible) { + child.visit(this); + } + } + this._renderCmd._dirtyFlag = 0; + }, + /** *

* The alpha threshold.
diff --git a/cocos2d/clipping-nodes/CCClippingNodeCanvasRenderCmd.js b/cocos2d/clipping-nodes/CCClippingNodeCanvasRenderCmd.js index 588075a538..1ddc0313c3 100644 --- a/cocos2d/clipping-nodes/CCClippingNodeCanvasRenderCmd.js +++ b/cocos2d/clipping-nodes/CCClippingNodeCanvasRenderCmd.js @@ -168,47 +168,40 @@ return cc.ClippingNode.CanvasRenderCmd.prototype._godhelpme; }; - proto.visit = function(parentCmd){ + proto.clippingVisit = function (parentCmd) { var node = this._node; - // quick return if not visible - if (!node._visible) - return; - parentCmd = parentCmd || this.getParentRenderCmd(); - if( parentCmd) - this._curLevel = parentCmd._curLevel + 1; - var transformRenderCmd = this; + this.visit(parentCmd); - this._syncStatus(parentCmd); // Composition mode, costy but support texture stencil this._clipElemType = !(!this._cangodhelpme() && node._stencil instanceof cc.DrawNode); if (!node._stencil || !node._stencil.visible) { if (this.inverted) - this.originVisit(parentCmd); // draw everything + node._visitChildren(); // draw everything return; } cc.renderer.pushRenderCommand(this._rendererSaveCmd); - if(this._clipElemType){ + if (this._clipElemType) { // Draw everything first using node visit function - this.originVisit(parentCmd); - }else{ - node._stencil.visit(this); + node._visitChildren(); + } else { + node._stencil.visit(node); } cc.renderer.pushRenderCommand(this._rendererClipCmd); - if(this._clipElemType){ - node._stencil.visit(transformRenderCmd); - }else{ - var i, children = node._children; + if (this._clipElemType) { + node._stencil.visit(node); + } else { // Clip mode doesn't support recursive stencil, so once we used a clip stencil, // so if it has ClippingNode as a child, the child must uses composition stencil. this._cangodhelpme(true); - var len = children.length; + var children = node._children; + var i, len = children.length; if (len > 0) { node.sortAllChildren(); for (i = 0; i < len; i++) - children[i]._renderCmd.visit(this); + children[i].visit(node); } this._cangodhelpme(false); } diff --git a/cocos2d/clipping-nodes/CCClippingNodeWebGLRenderCmd.js b/cocos2d/clipping-nodes/CCClippingNodeWebGLRenderCmd.js index 623f8c30dd..c276368aff 100644 --- a/cocos2d/clipping-nodes/CCClippingNodeWebGLRenderCmd.js +++ b/cocos2d/clipping-nodes/CCClippingNodeWebGLRenderCmd.js @@ -58,29 +58,26 @@ var node = this._node; this.originTransform(parentCmd, recursive); if (node._stencil) { - node._stencil._renderCmd.transform(this, recursive); + node._stencil._renderCmd.transform(this, true); + node._stencil._dirtyFlag &= ~cc.Node._dirtyFlags.transformDirty; } }; - proto.visit = function(parentCmd){ + proto.clippingVisit = function (parentCmd) { var node = this._node; - // quick return if not visible - if (!node._visible) - return; - - if( node._parent && node._parent._renderCmd) - this._curLevel = node._parent._renderCmd._curLevel + 1; + parentCmd = parentCmd || this.getParentRenderCmd(); + this.visit(parentCmd); // if stencil buffer disabled if (cc.stencilBits < 1) { // draw everything, as if there were no stencil - this.originVisit(parentCmd); + node._visitChildren(); return; } if (!node._stencil || !node._stencil.visible) { if (node.inverted) - this.originVisit(parentCmd); // draw everything + node._visitChildren(); // draw everything return; } @@ -91,20 +88,14 @@ cc.ClippingNode.WebGLRenderCmd._visit_once = false; } // draw everything, as if there were no stencil - this.originVisit(parentCmd); + node._visitChildren(); return; } cc.renderer.pushRenderCommand(this._beforeVisitCmd); - //optimize performance for javascript - var currentStack = cc.current_stack; - currentStack.stack.push(currentStack.top); - this._syncStatus(parentCmd); - currentStack.top = this._stackMatrix; - // node._stencil._stackMatrix = node._stackMatrix; - node._stencil._renderCmd.visit(this); + node._stencil.visit(node); cc.renderer.pushRenderCommand(this._afterDrawStencilCmd); @@ -115,15 +106,13 @@ node.sortAllChildren(); // draw children zOrder < 0 for (var i = 0; i < childLen; i++) { - locChildren[i]._renderCmd.visit(this); + locChildren[i].visit(node); } } cc.renderer.pushRenderCommand(this._afterVisitCmd); this._dirtyFlag = 0; - //optimize performance for javascript - currentStack.top = currentStack.stack.pop(); }; proto.setStencil = function (stencil) { diff --git a/cocos2d/core/base-nodes/CCNode.js b/cocos2d/core/base-nodes/CCNode.js index 92aa978efa..4f05484c47 100644 --- a/cocos2d/core/base-nodes/CCNode.js +++ b/cocos2d/core/base-nodes/CCNode.js @@ -2091,10 +2091,40 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{ /** * Recursive method that visit its children and draw them * @function - * @param {cc.Node.RenderCmd} parentCmd + * @param {cc.Node} parent */ - visit: function(parentCmd){ - this._renderCmd.visit(parentCmd); + visit: function (parent) { + // quick return if not visible + if (!this._visible) + return; + + var renderer = cc.renderer, cmd = this._renderCmd; + cmd.visit(parent && parent._renderCmd); + + var i, children = this._children, len = children.length, child; + if (len > 0) { + if (this._reorderChildDirty) { + this.sortAllChildren(); + } + // draw children zOrder < 0 + for (i = 0; i < len; i++) { + child = children[i]; + if (child._localZOrder < 0) { + child.visit(this); + } + else { + break; + } + } + + renderer.pushRenderCommand(cmd); + for (; i < len; i++) { + children[i].visit(this); + } + } else { + renderer.pushRenderCommand(cmd); + } + cmd._dirtyFlag = 0; }, /** diff --git a/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js b/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js index cd4db111e0..49308ef008 100644 --- a/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js +++ b/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js @@ -46,11 +46,17 @@ var dirtyFlags = cc.Node._dirtyFlags = { }; var ONE_DEGREE = Math.PI / 180; -var stack = new Array(50); function transformChildTree(root) { var index = 1; var children, child, curr, parentCmd, i, len; + var stack = cc.Node._performStacks[cc.Node._performing]; + if (!stack) { + stack = []; + cc.Node._performStacks.push(stack); + } + stack.length = 0; + cc.Node._performing++; stack[0] = root; while (index) { index--; @@ -79,6 +85,7 @@ function transformChildTree(root) { } } } + cc.Node._performing--; } //-------------------------Base ------------------------- @@ -317,9 +324,6 @@ cc.Node.RenderCmd.prototype = { visit: function (parentCmd) { var node = this._node, renderer = cc.renderer; - // quick return if not visible - if (!node._visible) - return; parentCmd = parentCmd || this.getParentRenderCmd(); if (parentCmd) @@ -331,7 +335,6 @@ cc.Node.RenderCmd.prototype = { } this._syncStatus(parentCmd); - this.visitChildren(); }, _updateDisplayColor: function (parentColor) { @@ -436,7 +439,8 @@ cc.Node.RenderCmd.prototype = { this._displayedOpacity = node._realOpacity * parentOpacity / 255.0; }, - _updateColor: function(){}, + _updateColor: function () { + }, updateStatus: function () { var locFlag = this._dirtyFlag; @@ -470,7 +474,7 @@ cc.Node.RenderCmd.prototype = { _syncStatus: function (parentCmd) { // In the visit logic does not restore the _dirtyFlag // Because child elements need parent's _dirtyFlag to change himself - var locFlag = this._dirtyFlag, parentNode = null; + var locFlag = this._dirtyFlag, parentNode = parentCmd ? parentCmd._node : null; // There is a possibility: // The parent element changed color, child element not change @@ -509,39 +513,11 @@ cc.Node.RenderCmd.prototype = { if (locFlag & dirtyFlags.orderDirty) this._dirtyFlag &= ~dirtyFlags.orderDirty; - }, - - visitChildren: function () { - var renderer = cc.renderer; - var node = this._node; - var i, children = node._children, child; - var len = children.length; - if (len > 0) { - node.sortAllChildren(); - // draw children zOrder < 0 - for (i = 0; i < len; i++) { - child = children[i]; - if (child._localZOrder < 0) { - child._renderCmd.visit(this); - } - else { - break; - } - } - - renderer.pushRenderCommand(this); - for (; i < len; i++) { - children[i]._renderCmd.visit(this); - } - } else { - renderer.pushRenderCommand(this); - } - this._dirtyFlag = 0; } }; -cc.Node.RenderCmd.prototype.originVisit = cc.Node.RenderCmd.prototype.visit; cc.Node.RenderCmd.prototype.originTransform = cc.Node.RenderCmd.prototype.transform; +cc.Node.RenderCmd.prototype.originUpdateStatus = cc.Node.RenderCmd.prototype.updateStatus; cc.Node.RenderCmd.prototype._originSyncStatus = cc.Node.RenderCmd.prototype._syncStatus; //-----------------------Canvas --------------------------- diff --git a/cocos2d/core/base-nodes/CCNodeWebGLRenderCmd.js b/cocos2d/core/base-nodes/CCNodeWebGLRenderCmd.js index aa6f3cba61..62e469800e 100644 --- a/cocos2d/core/base-nodes/CCNodeWebGLRenderCmd.js +++ b/cocos2d/core/base-nodes/CCNodeWebGLRenderCmd.js @@ -22,7 +22,7 @@ THE SOFTWARE. ****************************************************************************/ // ------------------------------ The cc.Node's render command for WebGL ---------------------------------- -(function() { +(function () { cc.Node.WebGLRenderCmd = function (renderable) { this._node = renderable; this._anchorPointInPoints = {x: 0, y: 0}; diff --git a/cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js b/cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js index d12ea0896a..2071bd656f 100644 --- a/cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js +++ b/cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js @@ -327,7 +327,7 @@ cc.LabelTTF._firsrEnglish = /^[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]/; if (locFlag & flags.textDirty) this._updateTexture(); - cc.Node.RenderCmd.prototype.updateStatus.call(this); + this.originUpdateStatus(); }; proto._syncStatus = function (parentCmd) { diff --git a/cocos2d/core/layers/CCLayer.js b/cocos2d/core/layers/CCLayer.js index 12030caa7a..b801833db4 100644 --- a/cocos2d/core/layers/CCLayer.js +++ b/cocos2d/core/layers/CCLayer.js @@ -85,6 +85,46 @@ cc.Layer = cc.Node.extend(/** @lends cc.Layer# */{ return this._renderCmd._isBaked; }, + visit: function () { + // quick return if not visible + if (!this._visible) + return; + + var renderer = cc.renderer, cmd = this._renderCmd; + cmd.visit(parent && parent._renderCmd); + + if (cmd._isBaked) { + renderer.pushRenderCommand(cmd); + cmd._bakeSprite.visit(this); + } + else { + var i, children = this._children, len = children.length, child; + if (len > 0) { + if (this._reorderChildDirty) { + this.sortAllChildren(); + } + // draw children zOrder < 0 + for (i = 0; i < len; i++) { + child = children[i]; + if (child._localZOrder < 0) { + child.visit(this); + } + else { + break; + } + } + + renderer.pushRenderCommand(cmd); + for (; i < len; i++) { + children[i].visit(this); + } + } else { + renderer.pushRenderCommand(cmd); + } + } + cmd._dirtyFlag = 0; + }, + addChild: function (child, localZOrder, tag) { cc.Node.prototype.addChild.call(this, child, localZOrder, tag); this._renderCmd._bakeForAddChild(child); @@ -218,6 +258,49 @@ cc.LayerColor = cc.Layer.extend(/** @lends cc.LayerColor# */{ return true; }, + visit: function () { + // quick return if not visible + if (!this._visible) + return; + + var renderer = cc.renderer, cmd = this._renderCmd; + cmd.visit(parent && parent._renderCmd); + + if (cmd._isBaked) { + renderer.pushRenderCommand(cmd._bakeRenderCmd); + //the bakeSprite is drawing + cmd._bakeSprite._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.transformDirty); + cmd._bakeSprite.visit(this); + } + else { + var i, children = this._children, len = children.length; + if (len > 0) { + if (this._reorderChildDirty) { + this.sortAllChildren(); + } + // draw children zOrder < 0 + for (i = 0; i < len; i++) { + child = children[i]; + if (child._localZOrder < 0) { + child.visit(this); + } + else { + break; + } + } + + renderer.pushRenderCommand(cmd); + for (; i < len; i++) { + children[i].visit(this); + } + } else { + renderer.pushRenderCommand(cmd); + } + } + + cmd._dirtyFlag = 0; + }, + /** * Sets the blend func, you can pass either a cc.BlendFunc object or source and destination value separately * @param {Number|cc.BlendFunc} src diff --git a/cocos2d/core/layers/CCLayerCanvasRenderCmd.js b/cocos2d/core/layers/CCLayerCanvasRenderCmd.js index a6f7fd4cff..10e58d1003 100644 --- a/cocos2d/core/layers/CCLayerCanvasRenderCmd.js +++ b/cocos2d/core/layers/CCLayerCanvasRenderCmd.js @@ -64,7 +64,7 @@ this._dirtyFlag = locFlag & flags.orderDirty ^ locFlag; } - cc.Node.RenderCmd.prototype.updateStatus.call(this); + this.originUpdateStatus(); }; proto._syncStatus = function (parentCmd) { @@ -164,26 +164,6 @@ } }; - proto.visit = function(parentCmd){ - if(!this._isBaked){ - this.originVisit(parentCmd); - return; - } - - var node = this._node, children = node._children; - var len = children.length; - // quick return if not visible - if (!node._visible || len === 0) - return; - - this._syncStatus(parentCmd); - cc.renderer.pushRenderCommand(this); - - //the bakeSprite is drawing - this._bakeSprite.visit(this); - this._dirtyFlag = 0; - }; - proto._bakeForAddChild = function (child) { if (child._parent === this._node && this._isBaked) child._renderCmd._setCachedParent(this); @@ -313,27 +293,6 @@ } }; - proto.visit = function(parentCmd){ - if(!this._isBaked){ - this.originVisit(); - return; - } - - var node = this._node; - // quick return if not visible - if (!node._visible) - return; - - this._syncStatus(parentCmd); - - cc.renderer.pushRenderCommand(this._bakeRenderCmd); - - //the bakeSprite is drawing - this._bakeSprite._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.transformDirty); - this._bakeSprite.visit(this); - this._dirtyFlag = 0; - }; - proto._getBoundingBoxForBake = function () { var node = this._node; //default size @@ -409,7 +368,7 @@ this._dirtyFlag = locFlag & flags.gradientDirty ^ locFlag; } - cc.Node.RenderCmd.prototype.updateStatus.call(this); + this.originUpdateStatus(); }; proto._syncStatus = function (parentCmd) { diff --git a/cocos2d/core/layers/CCLayerWebGLRenderCmd.js b/cocos2d/core/layers/CCLayerWebGLRenderCmd.js index 309921e184..ea60a3c70f 100644 --- a/cocos2d/core/layers/CCLayerWebGLRenderCmd.js +++ b/cocos2d/core/layers/CCLayerWebGLRenderCmd.js @@ -184,7 +184,7 @@ this._dirtyFlag = locFlag & flags.gradientDirty ^ locFlag; } - cc.Node.RenderCmd.prototype.updateStatus.call(this); + this.originUpdateStatus(); }; proto._syncStatus = function (parentCmd) { diff --git a/cocos2d/parallax/CCParallaxNodeRenderCmd.js b/cocos2d/parallax/CCParallaxNodeRenderCmd.js index 960a1881a9..2f5031c844 100644 --- a/cocos2d/parallax/CCParallaxNodeRenderCmd.js +++ b/cocos2d/parallax/CCParallaxNodeRenderCmd.js @@ -35,7 +35,7 @@ proto.updateStatus = function () { this._node._updateParallaxPosition(); - cc.Node.CanvasRenderCmd.prototype.updateStatus.call(this); + this.originUpdateStatus(); }; proto._syncStatus = function (parentCmd) { @@ -58,7 +58,7 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () { proto.updateStatus = function () { this._node._updateParallaxPosition(); - cc.Node.WebGLRenderCmd.prototype.updateStatus.call(this); + this.originUpdateStatus(); }; proto._syncStatus = function (parentCmd) { diff --git a/cocos2d/particle/CCParticleBatchNode.js b/cocos2d/particle/CCParticleBatchNode.js index 05a777d92f..3db6117391 100644 --- a/cocos2d/particle/CCParticleBatchNode.js +++ b/cocos2d/particle/CCParticleBatchNode.js @@ -147,6 +147,17 @@ cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{ return this.initWithTexture(tex, capacity); }, + visit: function (parent) { + // quick return if not visible + if (!this._visible) + return; + + var cmd = this._renderCmd; + cmd.visit(parent && parent._renderCmd); + renderer.pushRenderCommand(cmd); + cmd._dirtyFlag = 0; + }, + /** * Add a child into the cc.ParticleBatchNode * @param {cc.ParticleSystem} child diff --git a/cocos2d/particle/CCParticleBatchNodeWebGLRenderCmd.js b/cocos2d/particle/CCParticleBatchNodeWebGLRenderCmd.js index 82e7f290f6..3dda639728 100644 --- a/cocos2d/particle/CCParticleBatchNodeWebGLRenderCmd.js +++ b/cocos2d/particle/CCParticleBatchNodeWebGLRenderCmd.js @@ -58,26 +58,4 @@ proto._initWithTexture = function () { this._shaderProgram = cc.shaderCache.programForKey(cc.SHADER_POSITION_TEXTURECOLOR); }; - - proto.visit = function(parentCmd){ - var node = this._node; - // CAREFUL: - // This visit is almost identical to cc.Node#visit - // with the exception that it doesn't call visit on it's children - // - // The alternative is to have a void cc.Sprite#visit, but - // although this is less mantainable, is faster - // - if (!node._visible) - return; - - parentCmd = parentCmd || this.getParentRenderCmd(); - if (parentCmd) - this._curLevel = parentCmd._curLevel + 1; - this._syncStatus(parentCmd); - - cc.renderer.pushRenderCommand(this); - - this._dirtyFlag = 0; - }; })(); diff --git a/cocos2d/render-texture/CCRenderTexture.js b/cocos2d/render-texture/CCRenderTexture.js index 594142f914..ffb443f002 100644 --- a/cocos2d/render-texture/CCRenderTexture.js +++ b/cocos2d/render-texture/CCRenderTexture.js @@ -132,6 +132,18 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{ return new cc.RenderTexture.WebGLRenderCmd(this); }, + visit: function (parent) { + // quick return if not visible + if (!this._visible) + return; + + var renderer = cc.renderer, cmd = this._renderCmd; + + cmd.visit(parent && parent._renderCmd); + this.sprite.visit(this); + cmd._dirtyFlag = 0; + }, + /** * Clear RenderTexture. * @function diff --git a/cocos2d/render-texture/CCRenderTextureCanvasRenderCmd.js b/cocos2d/render-texture/CCRenderTextureCanvasRenderCmd.js index d15cb963fa..3ad126d9f6 100644 --- a/cocos2d/render-texture/CCRenderTextureCanvasRenderCmd.js +++ b/cocos2d/render-texture/CCRenderTextureCanvasRenderCmd.js @@ -102,11 +102,4 @@ proto.clearDepth = function (depthValue) { cc.log("clearDepth isn't supported on Cocos2d-Html5"); }; - - proto.visit = function(parentCmd){ - var node = this._node; - this._syncStatus(parentCmd); - node.sprite.visit(this); - this._dirtyFlag = 0; - }; })(); diff --git a/cocos2d/render-texture/CCRenderTextureWebGLRenderCmd.js b/cocos2d/render-texture/CCRenderTextureWebGLRenderCmd.js index 2f6994219b..20cc4dec06 100644 --- a/cocos2d/render-texture/CCRenderTextureWebGLRenderCmd.js +++ b/cocos2d/render-texture/CCRenderTextureWebGLRenderCmd.js @@ -365,28 +365,7 @@ }; proto.visit = function (parentCmd) { - var node = this._node; - if (!node._visible) - return; - cc.kmGLPushMatrix(); - - //TODO using GridNode - /* var locGrid = this.grid; - if (locGrid && locGrid.isActive()) { - locGrid.beforeDraw(); - this.transformAncestors(); - }*/ - this._syncStatus(parentCmd); - //this.toRenderer(); cc.renderer.pushRenderCommand(this); - node.sprite.visit(this); - - //TODO GridNode - /* if (locGrid && locGrid.isActive()) - locGrid.afterDraw(this);*/ - - this._dirtyFlag = 0; - cc.kmGLPopMatrix(); }; })(); diff --git a/extensions/ccui/base-classes/CCProtectedNode.js b/extensions/ccui/base-classes/CCProtectedNode.js index 8e069ebe51..4a2bcd367a 100644 --- a/extensions/ccui/base-classes/CCProtectedNode.js +++ b/extensions/ccui/base-classes/CCProtectedNode.js @@ -46,6 +46,62 @@ cc.ProtectedNode = cc.Node.extend(/** @lends cc.ProtectedNode# */{ this._protectedChildren = []; }, + visit: function (parent) { + // quick return if not visible + if (!this._visible) + return; + + var renderer = cc.renderer, cmd = this._renderCmd; + var i, children = this._children, len = children.length, child; + var j, pChildren = this._protectedChildren, pLen = pChildren.length, pChild; + + cmd.visit(parent && parent._renderCmd); + + var locGrid = this.grid; + if (locGrid && locGrid._active) + locGrid.beforeDraw(); + + if (this._reorderChildDirty) this.sortAllChildren(); + if (this._reorderProtectedChildDirty) this.sortAllProtectedChildren(); + + // draw children zOrder < 0 + for (i = 0; i < len; i++) { + child = children[i]; + if (child._localZOrder < 0) { + child.visit(this); + } + else { + break; + } + } + for (j = 0; j < pLen; j++) { + pChild = pChildren[j]; + if (pChild && pChild._localZOrder < 0) { + cmd._changeProtectedChild(pChild); + pChild.visit(this); + } + else + break; + } + + renderer.pushRenderCommand(cmd); + + for (; i < len; i++) { + children[i].visit(this); + } + for (; j < pLen; j++) { + pChild = pChildren[j]; + if (!pChild) continue; + cmd._changeProtectedChild(pChild); + pChild.visit(this); + } + + if (locGrid && locGrid._active) + locGrid.afterDraw(this); + + cmd._dirtyFlag = 0; + }, + /** *

* Adds a child to the container with z order and tag
diff --git a/extensions/ccui/base-classes/CCProtectedNodeCanvasRenderCmd.js b/extensions/ccui/base-classes/CCProtectedNodeCanvasRenderCmd.js index db7594d0d0..1ae8b1e62e 100644 --- a/extensions/ccui/base-classes/CCProtectedNodeCanvasRenderCmd.js +++ b/extensions/ccui/base-classes/CCProtectedNodeCanvasRenderCmd.js @@ -149,57 +149,6 @@ proto.constructor = cc.ProtectedNode.CanvasRenderCmd; proto._pNodeCmdCtor = cc.ProtectedNode.CanvasRenderCmd; - proto.visit = function(parentCmd){ - var node = this._node; - // quick return if not visible - if (!node._visible) - return; - - //visit for canvas - var i, j; - var children = node._children, child; - var locChildren = node._children, locProtectedChildren = node._protectedChildren; - var childLen = locChildren.length, pLen = locProtectedChildren.length; - - this._syncStatus(parentCmd); - - node.sortAllChildren(); - node.sortAllProtectedChildren(); - - var pChild; - // draw children zOrder < 0 - for (i = 0; i < childLen; i++) { - child = children[i]; - if (child._localZOrder < 0) - child.visit(this); - else - break; - } - for (j = 0; j < pLen; j++) { - pChild = locProtectedChildren[j]; - if (pChild && pChild._localZOrder < 0){ - this._changeProtectedChild(pChild); - pChild.visit(this); - } - else - break; - } - - cc.renderer.pushRenderCommand(this); - - for (; i < childLen; i++) - children[i] && children[i].visit(this); - for (; j < pLen; j++){ - pChild = locProtectedChildren[j]; - if(!pChild) continue; - this._changeProtectedChild(pChild); - pChild.visit(this); - } - - this._dirtyFlag = 0; - this._cacheDirty = false; - }; - proto.transform = function (parentCmd, recursive) { var node = this._node; @@ -216,6 +165,5 @@ } }; - proto.pNodeVisit = proto.visit; proto.pNodeTransform = proto.transform; })(); diff --git a/extensions/ccui/base-classes/CCProtectedNodeWebGLRenderCmd.js b/extensions/ccui/base-classes/CCProtectedNodeWebGLRenderCmd.js index 5306e98ba7..b22907d383 100644 --- a/extensions/ccui/base-classes/CCProtectedNodeWebGLRenderCmd.js +++ b/extensions/ccui/base-classes/CCProtectedNodeWebGLRenderCmd.js @@ -34,60 +34,6 @@ proto.constructor = cc.ProtectedNode.WebGLRenderCmd; proto._pNodeCmdCtor = cc.ProtectedNode.WebGLRenderCmd; - proto.visit = function(parentCmd){ - var node = this._node; - // quick return if not visible - if (!node._visible) - return; - var i, j; - - this._syncStatus(parentCmd); - - var locGrid = node.grid; - if (locGrid && locGrid._active) - locGrid.beforeDraw(); - - var locChildren = node._children, locProtectedChildren = node._protectedChildren; - var childLen = locChildren.length, pLen = locProtectedChildren.length; - node.sortAllChildren(); - node.sortAllProtectedChildren(); - - var pChild; - // draw children zOrder < 0 - for (i = 0; i < childLen; i++) { - if (locChildren[i] && locChildren[i]._localZOrder < 0) - locChildren[i].visit(this); - else - break; - } - for(j = 0; j < pLen; j++){ - pChild = locProtectedChildren[j]; - if (pChild && pChild._localZOrder < 0){ - this._changeProtectedChild(pChild); - pChild.visit(this); - }else - break; - } - - cc.renderer.pushRenderCommand(this); - - // draw children zOrder >= 0 - for (; i < childLen; i++) { - locChildren[i] && locChildren[i].visit(this); - } - for (; j < pLen; j++) { - pChild = locProtectedChildren[j]; - if(!pChild) continue; - this._changeProtectedChild(pChild); - pChild.visit(this); - } - - if (locGrid && locGrid._active) - locGrid.afterDraw(node); - - this._dirtyFlag = 0; - }; - proto.transform = function (parentCmd, recursive) { this.originTransform(parentCmd, recursive); @@ -100,6 +46,5 @@ } }; - proto.pNodeVisit = proto.visit; proto.pNodeTransform = proto.transform; })(); diff --git a/extensions/ccui/base-classes/UIWidgetRenderCmd.js b/extensions/ccui/base-classes/UIWidgetRenderCmd.js index bc3d7236d1..d424cd39b8 100644 --- a/extensions/ccui/base-classes/UIWidgetRenderCmd.js +++ b/extensions/ccui/base-classes/UIWidgetRenderCmd.js @@ -33,11 +33,19 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () { proto.constructor = ccui.Widget.CanvasRenderCmd; proto.visit = function (parentCmd) { - var node = this._node; - if (node._visible) { - node._adaptRenderers(); - this.pNodeVisit(parentCmd); + var node = this._node, renderer = cc.renderer; + + parentCmd = parentCmd || this.getParentRenderCmd(); + if (parentCmd) + this._curLevel = parentCmd._curLevel + 1; + + if (isNaN(node._customZ)) { + node._vertexZ = renderer.assignedZ; + renderer.assignedZ += renderer.assignedZStep; } + + node._adaptRenderers(); + this._syncStatus(parentCmd); }; proto.transform = function (parentCmd, recursive) { @@ -63,7 +71,6 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () { } }; - proto.widgetVisit = proto.visit; proto.widgetTransform = proto.transform; } else { ccui.Widget.WebGLRenderCmd = function (renderable) { @@ -75,14 +82,22 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () { proto.constructor = ccui.Widget.WebGLRenderCmd; proto.visit = function (parentCmd) { - var node = this._node; - if (node._visible) { - node._adaptRenderers(); - this.pNodeVisit(parentCmd); + var node = this._node, renderer = cc.renderer; + + parentCmd = parentCmd || this.getParentRenderCmd(); + if (parentCmd) + this._curLevel = parentCmd._curLevel + 1; + + if (isNaN(node._customZ)) { + node._vertexZ = renderer.assignedZ; + renderer.assignedZ += renderer.assignedZStep; } + + node._adaptRenderers(); + this._syncStatus(parentCmd); }; - proto.transform = function(parentCmd, recursive){ + proto.transform = function (parentCmd, recursive) { var node = this._node; if (node._visible && node._running) { node._adaptRenderers(); @@ -101,7 +116,6 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () { } }; - proto.widgetVisit = proto.visit; proto.widgetTransform = proto.transform; } }); diff --git a/extensions/ccui/layouts/UILayout.js b/extensions/ccui/layouts/UILayout.js index c9cd68b5fc..695f7e40f4 100644 --- a/extensions/ccui/layouts/UILayout.js +++ b/extensions/ccui/layouts/UILayout.js @@ -125,6 +125,76 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{ this._clippingStencil._performRecursive(cc.Node._stateCallbackType.onExit); }, + /** + *

+ * Calls adaptRenderers (its subclass will override it.) and do layout. + * If clippingEnabled is true, it will clip/scissor area. + *

+ * @override + * @param {cc.Node} [parent] + */ + visit: function (parent) { + if (!this._visible) + return; + + this._adaptRenderers(); + this._doLayout(); + + var renderer = cc.renderer, cmd = this._renderCmd; + var parentCmd = parent && parent._renderCmd; + cmd.visit(parentCmd); + + var stencilClipping = this._clippingEnabled && this._clippingType === ccui.Layout.CLIPPING_STENCIL; + var scissorClipping = this._clippingEnabled && this._clippingType === ccui.Layout.CLIPPING_SCISSOR; + + if (stencilClipping) { + cmd.stencilClippingVisit(parentCmd); + } + else if (scissorClipping) { + cmd.scissorClippingVisit(parentCmd); + } + + var i, children = this._children, len = children.length, child; + var j, pChildren = this._protectedChildren, pLen = pChildren.length, pChild; + + if (this._reorderChildDirty) this.sortAllChildren(); + if (this._reorderProtectedChildDirty) this.sortAllProtectedChildren(); + // draw children zOrder < 0 + for (i = 0; i < len; i++) { + child = children[i]; + if (child._localZOrder < 0) { + child.visit(this); + } + else break; + } + for (j = 0; j < pLen; j++) { + pChild = pChildren[j]; + if (pChild._localZOrder < 0) { + cmd._changeProtectedChild(pChild); + pChild.visit(this); + } + else break; + } + // draw children zOrder >= 0 + for (; i < len; i++) { + children[i].visit(this); + } + for (; j < pLen; j++) { + pChild = pChildren[j]; + cmd._changeProtectedChild(pChild); + pChild.visit(this); + } + + if (stencilClipping) { + cmd.postStencilVisit(); + } + else if (scissorClipping) { + cmd.postScissorVisit(); + } + + cmd._dirtyFlag = 0; + }, + /** * If a layout is loop focused which means that the focus movement will be inside the layout * @param {Boolean} loop pass true to let the focus movement loop inside the layout @@ -295,36 +365,6 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{ return this._clippingEnabled; }, - /** - *

- * Calls adaptRenderers (its subclass will override it.) and do layout. - * If clippingEnabled is true, it will clip/scissor area. - *

- * @override - * @param {cc.Node.RenderCmd} [parentCmd] - */ - visit: function (parentCmd) { - if (!this._visible) - return; - this._adaptRenderers(); - this._doLayout(); - - if (this._clippingEnabled) { - switch (this._clippingType) { - case ccui.Layout.CLIPPING_STENCIL: - this._renderCmd.stencilClippingVisit(parentCmd); - break; - case ccui.Layout.CLIPPING_SCISSOR: - this._renderCmd.scissorClippingVisit(parentCmd); - break; - default: - break; - } - } else { - ccui.Widget.prototype.visit.call(this, parentCmd); - } - }, - /** * Changes if layout can clip it's content and locChild. * If you really need this, please enable it. But it would reduce the rendering efficiency. diff --git a/extensions/ccui/layouts/UILayoutCanvasRenderCmd.js b/extensions/ccui/layouts/UILayoutCanvasRenderCmd.js index 70ff689777..7d847ccedd 100644 --- a/extensions/ccui/layouts/UILayoutCanvasRenderCmd.js +++ b/extensions/ccui/layouts/UILayoutCanvasRenderCmd.js @@ -37,37 +37,6 @@ proto.constructor = ccui.Layout.CanvasRenderCmd; proto._layoutCmdCtor = ccui.Layout.CanvasRenderCmd; - cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () { - if (ccui.Widget.CanvasRenderCmd) { - ccui.Layout.CanvasRenderCmd.prototype.widgetVisit = ccui.Widget.CanvasRenderCmd.prototype.widgetVisit; - } - }); - - proto.visit = function(parentCmd){ - var node = this._node; - if (!node._visible) - return; - node._adaptRenderers(); - node._doLayout(); - - if (node._clippingEnabled) { - switch (node._clippingType) { - case ccui.Layout.CLIPPING_STENCIL: - this.stencilClippingVisit(parentCmd); - break; - case ccui.Layout.CLIPPING_SCISSOR: - this.scissorClippingVisit(parentCmd); - break; - default: - break; - } - } else { - this.widgetVisit(parentCmd); - } - }; - - proto.layoutVisit = proto.visit; - proto._onRenderSaveCmd = function (ctx, scaleX, scaleY) { var wrapper = ctx || cc._renderContext, context = wrapper.getContext(); wrapper.save(); @@ -122,33 +91,10 @@ node._clippingStencil.visit(this); cc.renderer.pushRenderCommand(this._rendererClipCmd); - node.sortAllChildren(); - node.sortAllProtectedChildren(); - - var children = node._children; - var j=0, locProtectChildren = node._protectedChildren, i = 0, locChild; - var iLen = children.length, jLen = locProtectChildren.length; - - for( ; i < iLen; i++ ){ - locChild = children[i]; - if ( locChild && locChild.getLocalZOrder() < 0 ) - locChild.visit(this); - else - break; - } - for( ; j < jLen; j++ ) { - locChild = locProtectChildren[j]; - if ( locChild && locChild.getLocalZOrder() < 0 ) - locChild.visit(this); - else - break; - } - for (; i < iLen; i++) - children[i].visit(this); - for (; j < jLen; j++) - locProtectChildren[j].visit(this); - cc.renderer.pushRenderCommand(this._rendererRestoreCmd); - this._dirtyFlag = 0; + }; + + proto.postStencilVisit = proto.postScissorVisit = function () { + cc.renderer.pushRenderCommand(this._rendererRestoreCmd); }; ccui.Layout.CanvasRenderCmd._getSharedCache = function () { diff --git a/extensions/ccui/layouts/UILayoutWebGLRenderCmd.js b/extensions/ccui/layouts/UILayoutWebGLRenderCmd.js index 4a05a9d5f1..a2ed43eb12 100644 --- a/extensions/ccui/layouts/UILayoutWebGLRenderCmd.js +++ b/extensions/ccui/layouts/UILayoutWebGLRenderCmd.js @@ -47,35 +47,13 @@ proto.constructor = ccui.Layout.WebGLRenderCmd; proto._layoutCmdCtor = ccui.Layout.CanvasRenderCmd; - proto.visit = function(parentCmd){ - var node = this._node; - if (!node._visible) - return; + proto._syncStatus = function (parentCmd) { + this._originSyncStatus(parentCmd); - if(parentCmd && (parentCmd._dirtyFlag & cc.Node._dirtyFlags.transformDirty)) - node._clippingRectDirty = true; - - node._adaptRenderers(); - node._doLayout(); - - if (node._clippingEnabled) { - switch (node._clippingType) { - case ccui.Layout.CLIPPING_STENCIL: - this.stencilClippingVisit(parentCmd); - break; - case ccui.Layout.CLIPPING_SCISSOR: - this.scissorClippingVisit(parentCmd); - break; - default: - break; - } - } else { - this.pNodeVisit(parentCmd); - } + if (parentCmd && (parentCmd._dirtyFlag & cc.Node._dirtyFlags.transformDirty)) + this._node._clippingRectDirty = true; }; - - proto.layoutVisit = proto.visit; - + proto._onBeforeVisitStencil = function (ctx) { var gl = ctx || cc._renderContext; @@ -184,7 +162,6 @@ ccui.Layout.WebGLRenderCmd._visit_once = false; } // draw everything, as if there where no stencil - cc.Node.prototype.visit.call(node, parentCmd); return; } @@ -199,46 +176,16 @@ //optimize performance for javascript var currentStack = cc.current_stack; currentStack.stack.push(currentStack.top); - this._syncStatus(parentCmd); - this._dirtyFlag = 0; currentStack.top = this._stackMatrix; node._clippingStencil.visit(this); cc.renderer.pushRenderCommand(this._afterDrawStencilCmd); + }; - // draw (according to the stencil test func) this node and its childs - var i = 0; // used by _children - var j = 0; // used by _protectedChildren - - node.sortAllChildren(); - node.sortAllProtectedChildren(); - var locChildren = node._children, locProtectChildren = node._protectedChildren; - var iLen = locChildren.length, jLen = locProtectChildren.length, child; - for( ; i < iLen; i++ ){ - child = locChildren[i]; - if ( child && child.getLocalZOrder() < 0 ) - child.visit(this); - else - break; - } - for( ; j < jLen; j++ ) { - child = locProtectChildren[j]; - if ( child && child.getLocalZOrder() < 0 ) - child.visit(this); - else - break; - } - - for (; i < iLen; i++) - locChildren[i].visit(this); - for (; j < jLen; j++) - locProtectChildren[j].visit(this); - - cc.renderer.pushRenderCommand(this._afterVisitCmdStencil); - - //optimize performance for javascript - currentStack.top = currentStack.stack.pop(); + proto.postStencilVisit = function () { + renderer.pushRenderCommand(cmd._afterVisitCmdStencil); + cc.current_stack.top = cc.current_stack.stack.pop(); }; proto.scissorClippingVisit = function (parentCmd) { @@ -247,7 +194,9 @@ this._afterVisitCmdScissor = new cc.CustomRenderCmd(this, this._onAfterVisitScissor); } cc.renderer.pushRenderCommand(this._beforeVisitCmdScissor); - this.pNodeVisit(parentCmd); + }; + + proto.postScissorVisit = function () { cc.renderer.pushRenderCommand(this._afterVisitCmdScissor); }; diff --git a/extensions/ccui/uiwidgets/UIVideoPlayer.js b/extensions/ccui/uiwidgets/UIVideoPlayer.js index 664415c258..38279832ce 100644 --- a/extensions/ccui/uiwidgets/UIVideoPlayer.js +++ b/extensions/ccui/uiwidgets/UIVideoPlayer.js @@ -49,6 +49,33 @@ ccui.VideoPlayer = ccui.Widget.extend(/** @lends ccui.VideoPlayer# */{ return new ccui.VideoPlayer.RenderCmd(this); }, + visit: function () { + var cmd = this._renderCmd, + div = cmd._div, + container = cc.container, + eventManager = cc.eventManager; + if (this._visible) { + container.appendChild(cmd._video); + if (this._listener === null) + this._listener = cc.eventManager.addCustomListener(cc.game.EVENT_RESIZE, function () { + cmd.resize(); + }); + } else { + var hasChild = false; + if ('contains' in container) { + hasChild = container.contains(cmd._video); + } else { + hasChild = container.compareDocumentPosition(cmd._video) % 16; + } + if (hasChild) + container.removeChild(cmd._video); + eventManager.removeListener(cmd._listener); + cmd._listener = null; + } + cmd.updateStatus(); + cmd.resize(); + }, + /** * Set the video address * Automatically replace extname @@ -353,31 +380,6 @@ ccui.VideoPlayer.EventType = { var proto = ccui.VideoPlayer.RenderCmd.prototype = Object.create(RenderCmd.prototype); proto.constructor = ccui.VideoPlayer.RenderCmd; - proto.visit = function(){ - var self = this, - container = cc.container, - eventManager = cc.eventManager; - if(this._node._visible){ - container.appendChild(this._video); - if(this._listener === null) - this._listener = cc.eventManager.addCustomListener(cc.game.EVENT_RESIZE, function () { - self.resize(); - }); - }else{ - var hasChild = false; - if('contains' in container) { - hasChild = container.contains(this._video); - }else { - hasChild = container.compareDocumentPosition(this._video) % 16; - } - if(hasChild) - container.removeChild(this._video); - eventManager.removeListener(this._listener); - this._listener = null; - } - this.updateStatus(); - }; - proto.transform = function (parentCmd, recursive) { this.originTransform(parentCmd, recursive); this.updateMatrix(this._worldTransform, cc.view._scaleX, cc.view._scaleY); @@ -484,7 +486,7 @@ ccui.VideoPlayer.EventType = { node._playing = false; node._stopped = true; this.initStyle(); - this.visit(); + this._node.visit(); source = document.createElement("source"); source.src = path; diff --git a/extensions/ccui/uiwidgets/UIWebView.js b/extensions/ccui/uiwidgets/UIWebView.js index baac2591bf..3ed36ef467 100644 --- a/extensions/ccui/uiwidgets/UIWebView.js +++ b/extensions/ccui/uiwidgets/UIWebView.js @@ -41,6 +41,34 @@ ccui.WebView = ccui.Widget.extend(/** @lends ccui.WebView# */{ this.loadURL(path); }, + visit: function () { + var cmd = this._renderCmd, + div = cmd._div, + container = cc.container, + eventManager = cc.eventManager; + if (this._visible) { + container.appendChild(div); + if (this._listener === null) + this._listener = eventManager.addCustomListener(cc.game.EVENT_RESIZE, function () { + cmd.resize(); + }); + } else { + var hasChild = false; + if ('contains' in container) { + hasChild = container.contains(div); + } else { + hasChild = container.compareDocumentPosition(div) % 16; + } + if (hasChild) + container.removeChild(div); + var list = eventManager._listenersMap[cc.game.EVENT_RESIZE].getFixedPriorityListeners(); + eventManager._removeListenerInVector(list, cmd._listener); + cmd._listener = null; + } + cmd.updateStatus(); + cmd.resize(cc.view); + }, + setJavascriptInterfaceScheme: function (scheme) { }, loadData: function (data, MIMEType, encoding, baseURL) { @@ -314,33 +342,6 @@ ccui.WebView.EventType = { } }; - proto.visit = function(){ - var self = this, - container = cc.container, - eventManager = cc.eventManager; - if(this._node._visible){ - container.appendChild(this._div); - if(this._listener === null) - this._listener = eventManager.addCustomListener(cc.game.EVENT_RESIZE, function () { - self.resize(); - }); - }else{ - var hasChild = false; - if('contains' in container) { - hasChild = container.contains(this._div); - }else { - hasChild = container.compareDocumentPosition(this._div) % 16; - } - if(hasChild) - container.removeChild(this._div); - var list = eventManager._listenersMap[cc.game.EVENT_RESIZE].getFixedPriorityListeners(); - eventManager._removeListenerInVector(list, this._listener); - this._listener = null; - } - this.updateStatus(); - this.resize(cc.view); - }; - proto.resize = function (view) { view = view || cc.view; var node = this._node, diff --git a/extensions/ccui/uiwidgets/scroll-widget/UIScrollView.js b/extensions/ccui/uiwidgets/scroll-widget/UIScrollView.js index 21030376b7..cbdadaad21 100644 --- a/extensions/ccui/uiwidgets/scroll-widget/UIScrollView.js +++ b/extensions/ccui/uiwidgets/scroll-widget/UIScrollView.js @@ -109,19 +109,6 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{ this.setTouchEnabled(true); }, - /** - * Initializes a ccui.ScrollView. Please do not call this function by yourself, you should pass the parameters to constructor to initialize it. - * @returns {boolean} - */ - init: function () { - if (ccui.Layout.prototype.init.call(this)) { - - - return true; - } - return false; - }, - /** * Calls the parent class' onEnter and schedules update function. * @override @@ -136,6 +123,69 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{ ccui.Layout.prototype.onExit.call(this); }, + visit: function (parent) { + if (!this._visible) + return; + + this._adaptRenderers(); + this._doLayout(); + + var renderer = cc.renderer, cmd = this._renderCmd; + var parentCmd = parent && parent._renderCmd; + cmd.visit(parentCmd); + + renderer.pushRenderCommand(cmd); + if (cmd instanceof ccui.ScrollView.WebGLRenderCmd) { + var currentID = this.__instanceId; + renderer._turnToCacheMode(currentID); + } + + var stencilClipping = this._clippingEnabled && this._clippingType === ccui.Layout.CLIPPING_STENCIL; + var scissorClipping = this._clippingEnabled && this._clippingType === ccui.Layout.CLIPPING_SCISSOR; + + if (stencilClipping) { + cmd.stencilClippingVisit(parentCmd); + } + else if (scissorClipping) { + cmd.scissorClippingVisit(parentCmd); + } + + var i, children = this._children, len = children.length, child; + var j, pChildren = this._protectedChildren, pLen = pChildren.length, pChild; + + if (this._reorderChildDirty) this.sortAllChildren(); + if (this._reorderProtectedChildDirty) this.sortAllProtectedChildren(); + for (i = 0; i < len; i++) { + child = children[i]; + if (child && child._visible) { + child.visit(this); + } + } + for (j = 0; j < pLen; j++) { + pChild = pChildren[j]; + if (pChild && pChild._visible) { + cmd._changeProtectedChild(pChild); + pChild.visit(this); + } + } + + if (stencilClipping) { + cmd.postStencilVisit(); + } + else if (scissorClipping) { + cmd.postScissorVisit(); + } + + if (cmd instanceof ccui.ScrollView.WebGLRenderCmd) { + renderer._turnToNormalMode(); + } + + // Need to update children after do layout + this.updateChildren(); + + cmd._dirtyFlag = 0; + }, + /** * When a widget is in a layout, you could call this method to get the next focused widget within a specified _direction.
* If the widget is not in a layout, it will return itself diff --git a/extensions/ccui/uiwidgets/scroll-widget/UIScrollViewCanvasRenderCmd.js b/extensions/ccui/uiwidgets/scroll-widget/UIScrollViewCanvasRenderCmd.js index 4ddc6e18b0..4607932e9d 100644 --- a/extensions/ccui/uiwidgets/scroll-widget/UIScrollViewCanvasRenderCmd.js +++ b/extensions/ccui/uiwidgets/scroll-widget/UIScrollViewCanvasRenderCmd.js @@ -10,21 +10,6 @@ var proto = ccui.ScrollView.CanvasRenderCmd.prototype = Object.create(ccui.Layout.CanvasRenderCmd.prototype); proto.constructor = ccui.ScrollView.CanvasRenderCmd; - proto.visit = function(parentCmd) { - var node = this._node; - if (!node._visible) - return; - var currentID = node.__instanceId; - - cc.renderer.pushRenderCommand(this); - //cc.renderer._turnToCacheMode(currentID); - - this.layoutVisit(parentCmd); - - this._dirtyFlag = 0; - //cc.renderer._turnToNormalMode(); - }; - proto.rendering = function (ctx) { var currentID = this._node.__instanceId; var i, locCmds = cc.renderer._cacheToCanvasCmds[currentID], len, diff --git a/extensions/ccui/uiwidgets/scroll-widget/UIScrollViewWebGLRenderCmd.js b/extensions/ccui/uiwidgets/scroll-widget/UIScrollViewWebGLRenderCmd.js index abf3fc9278..45d0aa3b2a 100644 --- a/extensions/ccui/uiwidgets/scroll-widget/UIScrollViewWebGLRenderCmd.js +++ b/extensions/ccui/uiwidgets/scroll-widget/UIScrollViewWebGLRenderCmd.js @@ -10,23 +10,6 @@ var proto = ccui.ScrollView.WebGLRenderCmd.prototype = Object.create(ccui.Layout.WebGLRenderCmd.prototype); proto.constructor = ccui.ScrollView.WebGLRenderCmd; - proto.visit = function(parentCmd) { - var node = this._node; - if (!node._visible) - return; - var currentID = this._node.__instanceId; - - cc.renderer.pushRenderCommand(this); - cc.renderer._turnToCacheMode(currentID); - - this.layoutVisit(parentCmd); - // Need to update children after do layout - node.updateChildren(); - - this._dirtyFlag = 0; - cc.renderer._turnToNormalMode(); - }; - proto.rendering = function (ctx) { var currentID = this._node.__instanceId, locCmds = cc.renderer._cacheToBufferCmds[currentID], diff --git a/extensions/cocostudio/armature/CCArmature.js b/extensions/cocostudio/armature/CCArmature.js index 020c83f2b5..4ab51a4478 100644 --- a/extensions/cocostudio/armature/CCArmature.js +++ b/extensions/cocostudio/armature/CCArmature.js @@ -149,6 +149,14 @@ ccs.Armature = ccs.Node.extend(/** @lends ccs.Armature# */{ return true; }, + visit: function (parent) { + // quick return if not visible + if (!this._visible) + return; + + this._renderCmd.visit(parent && parent._renderCmd); + }, + addChild: function (child, localZOrder, tag) { if (child instanceof ccui.Widget) { cc.log("Armature doesn't support to add Widget as its child, it will be fix soon."); diff --git a/extensions/cocostudio/timeline/CCBoneNode.js b/extensions/cocostudio/timeline/CCBoneNode.js index 7a4d82ab41..9ecf5aedc3 100644 --- a/extensions/cocostudio/timeline/CCBoneNode.js +++ b/extensions/cocostudio/timeline/CCBoneNode.js @@ -83,6 +83,10 @@ ccs.BoneNode = (function () { //this._updateColor(); }, + visit: function (parent) { + this._visit && this._visit(parent && parent._renderCmd); + }, + addSkin: function (skin, display, hideOthers/*false*/) { // skin, display // skin, display, hideOthers @@ -531,10 +535,6 @@ ccs.BoneNode = (function () { var proto = BoneNodeCanvasCmd.prototype = Object.create(Node.CanvasRenderCmd.prototype); proto.constructor = BoneNodeCanvasCmd; - proto.visit = function (parentCmd) { - var node = this._node; - node._visit && node._visit(parentCmd); - }; proto.updateDebugPoint = function (points) { this._drawNode.clear(); this._drawNode.drawPoly(points, this._color, 0, this._color); @@ -564,10 +564,6 @@ ccs.BoneNode = (function () { var proto = BoneNodeWebGLCmd.prototype = Object.create(Node.WebGLRenderCmd.prototype); proto.constructor = BoneNodeWebGLCmd; - proto.visit = function (parentCmd) { - var node = this._node; - node._visit && node._visit(parentCmd); - }; proto.updateDebugPoint = function (points) { this._drawNode.clear(); this._drawNode.drawPoly(points, this._color, 0, this._color); diff --git a/extensions/cocostudio/timeline/CCSkeletonNode.js b/extensions/cocostudio/timeline/CCSkeletonNode.js index 044d86770a..7c7a005277 100644 --- a/extensions/cocostudio/timeline/CCSkeletonNode.js +++ b/extensions/cocostudio/timeline/CCSkeletonNode.js @@ -172,7 +172,7 @@ ccs.SkeletonNode = (function () { subOrderedBoneCmd = subOrderedAllBones[i]._renderCmd; cc.renderer.pushRenderCommand(subOrderedBoneCmd._drawNode._renderCmd); } - this._dirtyFlag = 0; + cmd._dirtyFlag = 0; }, _checkSubBonesDirty: function () { diff --git a/extensions/gui/scrollview/CCScrollView.js b/extensions/gui/scrollview/CCScrollView.js index 3834839a8e..d29e6db0ac 100644 --- a/extensions/gui/scrollview/CCScrollView.js +++ b/extensions/gui/scrollview/CCScrollView.js @@ -165,6 +165,34 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{ return false; }, + visit: function (parent) { + if (!this._visible) { + return; + } + + var renderer = cc.renderer, cmd = this._renderCmd; + cmd.visit(parent && parent._renderCmd); + + if (this._clippingToBounds) { + renderer.pushRenderCommand(cmd.startCmd); + } + + var i, children = this._children, len = children.length; + if (len > 0) { + if (this._reorderChildDirty) { + this.sortAllChildren(); + } + for (i = 0; i < len; i++) { + children[i].visit(this); + } + } + + if (this._clippingToBounds) { + renderer.pushRenderCommand(cmd.endCmd); + } + cmd._dirtyFlag = 0; + }, + /** * Sets a new content offset. It ignores max/min offset. It just sets what's given. (just like UIKit's UIScrollView) * diff --git a/extensions/gui/scrollview/CCScrollViewCanvasRenderCmd.js b/extensions/gui/scrollview/CCScrollViewCanvasRenderCmd.js index c323eedbd0..0cc063f846 100644 --- a/extensions/gui/scrollview/CCScrollViewCanvasRenderCmd.js +++ b/extensions/gui/scrollview/CCScrollViewCanvasRenderCmd.js @@ -61,25 +61,4 @@ wrapper = wrapper || cc._renderContext; wrapper.restore(); }; - - proto.visit = function(parentCmd){ - var node = this._node; - if (!node._visible) return; - - var i, locChildren = node._children, childrenLen; - - this._syncStatus(parentCmd); - cc.renderer.pushRenderCommand(this.startCmd); - - if (locChildren && locChildren.length > 0) { - childrenLen = locChildren.length; - node.sortAllChildren(); - for (i = 0; i < childrenLen; i++) { - locChildren[i]._renderCmd.visit(this); - } - } - cc.renderer.pushRenderCommand(this.endCmd); - - this._dirtyFlag = 0; - }; })(); diff --git a/extensions/gui/scrollview/CCScrollViewWebGLRenderCmd.js b/extensions/gui/scrollview/CCScrollViewWebGLRenderCmd.js index 78d3affdbc..3d837db14f 100644 --- a/extensions/gui/scrollview/CCScrollViewWebGLRenderCmd.js +++ b/extensions/gui/scrollview/CCScrollViewWebGLRenderCmd.js @@ -68,39 +68,4 @@ ctx.disable(ctx.SCISSOR_TEST); } }; - - proto.visit = function(parentCmd){ - var node = this._node; - if (!node._visible) return; - - var i, locChildren = node._children, selChild, childrenLen; - - this._syncStatus(parentCmd); - - if (node._clippingToBounds) { - cc.renderer.pushRenderCommand(this.startCmd); - } - - if (locChildren && locChildren.length > 0) { - childrenLen = locChildren.length; - // draw children zOrder < 0 - for (i = 0; i < childrenLen; i++) { - selChild = locChildren[i]; - if (selChild && selChild._localZOrder < 0) - selChild._renderCmd.visit(); - else - break; - } - - // draw children zOrder >= 0 - for (; i < childrenLen; i++) - locChildren[i]._renderCmd.visit(); - } - - if (node._clippingToBounds) { - cc.renderer.pushRenderCommand(this.endCmd); - } - - this._dirtyFlag = 0; - }; })(); From 8c03b450d23d2a2ddfaf88c812cf32d1da81e4d2 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Mon, 12 Dec 2016 16:53:43 +0800 Subject: [PATCH 40/42] Fix 3D projection --- cocos2d/core/CCDirectorWebGL.js | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/cocos2d/core/CCDirectorWebGL.js b/cocos2d/core/CCDirectorWebGL.js index 0ad67fda4a..969ee75997 100644 --- a/cocos2d/core/CCDirectorWebGL.js +++ b/cocos2d/core/CCDirectorWebGL.js @@ -98,13 +98,14 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () { cc.kmGLMultMatrix(matrixPerspective); - cc.kmGLMatrixMode(cc.KM_GL_MODELVIEW); - cc.kmGLLoadIdentity(); var eye = new cc.math.Vec3(-ox + size.width / 2, -oy + size.height / 2, zeye); var center = new cc.math.Vec3( -ox + size.width / 2, -oy + size.height / 2, 0.0); var up = new cc.math.Vec3( 0.0, 1.0, 0.0); matrixLookup.lookAt(eye, center, up); cc.kmGLMultMatrix(matrixLookup); + + cc.kmGLMatrixMode(cc.KM_GL_MODELVIEW); + cc.kmGLLoadIdentity(); break; case cc.Director.PROJECTION_CUSTOM: if (_t._projectionDelegate) From 40cab0a2d29288e66340b8f9d54b303d40377356 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Mon, 12 Dec 2016 16:54:10 +0800 Subject: [PATCH 41/42] Fix getPreferredSize is not a function issue --- extensions/ccui/base-classes/UIScale9Sprite.js | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/extensions/ccui/base-classes/UIScale9Sprite.js b/extensions/ccui/base-classes/UIScale9Sprite.js index f7fcbb08af..01fa9eb0b6 100644 --- a/extensions/ccui/base-classes/UIScale9Sprite.js +++ b/extensions/ccui/base-classes/UIScale9Sprite.js @@ -433,12 +433,6 @@ ccui.Scale9Sprite = cc.Scale9Sprite = cc.Node.extend(/** @lends ccui.Scale9Sprit this._updateCapInsets(this._spriteFrame._rect, this._capInsetsInternal); }, - setPreferredSize: function (preferredSize) { - if (!preferredSize || cc.sizeEqualToSize(this._contentSize, preferredSize)) return; - - this.setContentSize(preferredSize); - }, - _updateCapInsets: function (rect, capInsets) { if(!capInsets || !rect || cc._rectEqualToZero(capInsets)) { rect = rect || {x:0, y:0, width: this._contentSize.width, height: this._contentSize.height}; @@ -650,6 +644,15 @@ ccui.Scale9Sprite = cc.Scale9Sprite = cc.Node.extend(/** @lends ccui.Scale9Sprit return new cc.BlendFunc(this._blendFunc.src, this._blendFunc.dst); }, + setPreferredSize: function (preferredSize) { + if (!preferredSize || cc.sizeEqualToSize(this._contentSize, preferredSize)) return; + this.setContentSize(preferredSize); + }, + + getPreferredSize: function () { + return this.getContentSize(); + }, + // overrides setContentSize: function (width, height) { if (height === undefined) { @@ -664,7 +667,7 @@ ccui.Scale9Sprite = cc.Scale9Sprite = cc.Node.extend(/** @lends ccui.Scale9Sprit this._quadsDirty = true; }, - getContentSize: function() { + getContentSize: function () { if(this._renderingType === ccui.Scale9Sprite.RenderingType.SIMPLE) { if(this._spriteFrame) { return this._spriteFrame._originalSize; From efdd3589bf398e1200a6c46297a08d618a442f89 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Tue, 13 Dec 2016 00:57:19 +0800 Subject: [PATCH 42/42] Fix issues: 1. Add ontimeout for xml http requests 2. CCB parser parse scale issue 3. Fix armature not rendering and not updating issue --- CCBoot.js | 6 +-- cocos2d/audio/CCAudio.js | 3 ++ .../CCClippingNodeCanvasRenderCmd.js | 6 ++- cocos2d/core/layers/CCLayer.js | 15 +------ cocos2d/core/utils/BinaryLoader.js | 1 + extensions/ccb-reader/CCBAnimationManager.js | 4 +- .../ccb-reader/CCBRelativePositioning.js | 31 +------------ extensions/ccb-reader/CCNodeLoader.js | 7 ++- extensions/cocostudio/armature/CCArmature.js | 1 + .../armature/CCArmatureCanvasRenderCmd.js | 20 ++++----- .../armature/CCArmatureWebGLRenderCmd.js | 3 ++ extensions/cocostudio/armature/CCBone.js | 5 +++ .../armature/display/CCSkinRenderCmd.js | 9 +++- extensions/cocostudio/timeline/CCBoneNode.js | 4 +- .../cocostudio/timeline/CCSkeletonNode.js | 2 +- extensions/gui/control-extension/CCControl.js | 43 +++++++++---------- extensions/spine/CCSkeletonWebGLRenderCmd.js | 40 ++++++++--------- 17 files changed, 89 insertions(+), 111 deletions(-) diff --git a/CCBoot.js b/CCBoot.js index 385c030f58..f2a7d39139 100644 --- a/CCBoot.js +++ b/CCBoot.js @@ -285,7 +285,7 @@ cc.AsyncPool = function (srcObj, limit, iterator, onEnd, target) { self._workingSize--; if (self.finishedSize === self.size) { var errors = self._errors.length === 0 ? null : self._errors; - self.onEnd(self._onEndTarget, errors, self._results); + self.onEnd(errors, self._results); return; } self._handleItem(); @@ -773,7 +773,7 @@ cc.loader = (function () { if (xhr.readyState === 4) xhr.status === 200 ? cb(null, xhr.responseText) : cb({status:xhr.status, errorMessage:errInfo}, null); }; - xhr.onerror = function () { + xhr.onerror = xhr.ontimeout = function () { cb({status: xhr.status, errorMessage: errInfo}, null); }; } @@ -800,7 +800,7 @@ cc.loader = (function () { if(xhr.readyState === 4) xhr.status === 200 ? cb(null, xhr.response) : cb({status:xhr.status, errorMessage:errInfo}, null); }; - xhr.onerror = function(){ + xhr.onerror = xhr.ontimeout = function(){ cb({status:xhr.status, errorMessage:errInfo}, null); }; xhr.send(null); diff --git a/cocos2d/audio/CCAudio.js b/cocos2d/audio/CCAudio.js index 0ca259b60a..b10d6cb5a3 100644 --- a/cocos2d/audio/CCAudio.js +++ b/cocos2d/audio/CCAudio.js @@ -378,6 +378,9 @@ cc.Audio.WebAudio.prototype = { request.onerror = function () { cb('request error - ' + url); }; + request.ontimeout = function () { + cb('request timeout - ' + url); + }; request.send(); }, diff --git a/cocos2d/clipping-nodes/CCClippingNodeCanvasRenderCmd.js b/cocos2d/clipping-nodes/CCClippingNodeCanvasRenderCmd.js index 1ddc0313c3..6e4955a8c9 100644 --- a/cocos2d/clipping-nodes/CCClippingNodeCanvasRenderCmd.js +++ b/cocos2d/clipping-nodes/CCClippingNodeCanvasRenderCmd.js @@ -158,8 +158,10 @@ proto.transform = function (parentCmd, recursive) { this.originTransform(parentCmd, recursive); var node = this._node; - if (node._stencil && node._stencil._renderCmd) - node._stencil._renderCmd.transform(this, recursive); + if (node._stencil && node._stencil._renderCmd) { + node._stencil._renderCmd.transform(this, true); + node._stencil._dirtyFlag &= ~cc.Node._dirtyFlags.transformDirty; + } }; proto._cangodhelpme = function (godhelpme) { diff --git a/cocos2d/core/layers/CCLayer.js b/cocos2d/core/layers/CCLayer.js index b801833db4..5e31df75a1 100644 --- a/cocos2d/core/layers/CCLayer.js +++ b/cocos2d/core/layers/CCLayer.js @@ -40,19 +40,8 @@ cc.Layer = cc.Node.extend(/** @lends cc.Layer# */{ this._ignoreAnchorPointForPosition = true; this.setAnchorPoint(0.5, 0.5); this.setContentSize(cc.winSize); - }, - - /** - * Initialization of the layer, please do not call this function by yourself, you should pass the parameters to constructor to initialize a layer - */ - init: function () { - var _t = this; - _t._ignoreAnchorPointForPosition = true; - _t.setAnchorPoint(0.5, 0.5); - _t.setContentSize(cc.winSize); - _t._cascadeColorEnabled = false; - _t._cascadeOpacityEnabled = false; - return true; + this._cascadeColorEnabled = false; + this._cascadeOpacityEnabled = false; }, /** diff --git a/cocos2d/core/utils/BinaryLoader.js b/cocos2d/core/utils/BinaryLoader.js index b95b93e799..7127b1279c 100644 --- a/cocos2d/core/utils/BinaryLoader.js +++ b/cocos2d/core/utils/BinaryLoader.js @@ -77,6 +77,7 @@ cc.loader._str2Uint8Array = function (strData) { cc.loader.loadBinarySync = function (url) { var self = this; var req = this.getXMLHttpRequest(); + req.timeout = 0; var errInfo = "load " + url + " failed!"; req.open('GET', url, false); var arrayInfo = null; diff --git a/extensions/ccb-reader/CCBAnimationManager.js b/extensions/ccb-reader/CCBAnimationManager.js index 0b65f1e696..54ab341f0c 100644 --- a/extensions/ccb-reader/CCBAnimationManager.js +++ b/extensions/ccb-reader/CCBAnimationManager.js @@ -471,7 +471,7 @@ cc.BuilderAnimationManager = cc.Class.extend({ var containerSize = this.getContainerSize(node.getParent()); - var absPos = cc._getAbsolutePosition(x, y, type, containerSize, propName); + var absPos = cc.getAbsolutePosition(x, y, type, containerSize, propName); return cc.moveTo(duration, absPos); } else if (propName === "scale") { @@ -523,7 +523,7 @@ cc.BuilderAnimationManager = cc.Class.extend({ x = value[0]; y = value[1]; - cc._getAbsolutePosition(x, y, nType, this.getContainerSize(node.getParent()), propName, _pos); + cc.getAbsolutePosition(x, y, nType, this.getContainerSize(node.getParent()), propName, _pos); node._position.x = _pos.x; node._position.y = _pos.y; } else if (propName === "scale") { diff --git a/extensions/ccb-reader/CCBRelativePositioning.js b/extensions/ccb-reader/CCBRelativePositioning.js index 347422c891..ed0d29a255 100644 --- a/extensions/ccb-reader/CCBRelativePositioning.js +++ b/extensions/ccb-reader/CCBRelativePositioning.js @@ -24,33 +24,7 @@ THE SOFTWARE. ****************************************************************************/ -cc.getAbsolutePosition = function (pt, type, containerSize, propName) { - if (type === CCB_POSITIONTYPE_RELATIVE_BOTTOM_LEFT) { - ; - } - else if (type === CCB_POSITIONTYPE_RELATIVE_TOP_LEFT) { - pt.y = containerSize.height - pt.y; - } - else if (type === CCB_POSITIONTYPE_RELATIVE_TOP_RIGHT) { - pt.x = containerSize.width - pt.x; - pt.y = containerSize.height - pt.y; - } - else if (type === CCB_POSITIONTYPE_RELATIVE_BOTTOM_RIGHT) { - pt.x = containerSize.width - pt.x; - } - else if (type === CCB_POSITIONTYPE_PERCENT) { - pt.x = (containerSize.width * pt.x / 100.0); - pt.y = (containerSize.height * pt.y / 100.0); - } - else if (type === CCB_POSITIONTYPE_MULTIPLY_RESOLUTION) { - var resolutionScale = cc.BuilderReader.getResolutionScale(); - pt.x = pt.x * resolutionScale; - pt.y = pt.y * resolutionScale; - } - return pt; -}; - -cc._getAbsolutePosition = function (x, y, type, containerSize, propName, out) { +cc.getAbsolutePosition = function (x, y, type, containerSize, propName, out) { var absPt = out || cc.p(0, 0); if (type === CCB_POSITIONTYPE_RELATIVE_BOTTOM_LEFT) { absPt.x = x; @@ -86,6 +60,5 @@ cc.setRelativeScale = function (node, scaleX, scaleY, type, propName) { scaleY *= resolutionScale; } - node._scaleX = scaleX; - node._scaleY = scaleY; + node.setScale(scaleX, scaleY); }; diff --git a/extensions/ccb-reader/CCNodeLoader.js b/extensions/ccb-reader/CCNodeLoader.js index 6d71699886..afa434b4d2 100644 --- a/extensions/ccb-reader/CCNodeLoader.js +++ b/extensions/ccb-reader/CCNodeLoader.js @@ -354,8 +354,8 @@ cc.NodeLoader = cc.Class.extend({ // var containerSize = ccbReader._animationManager.getContainerSize(parent); var containerSize = parent ? parent._contentSize : ccbReader._animationManager._rootContainerSize; - cc._getAbsolutePosition(x, y, type, containerSize, propertyName, this._pt); - node.setPosition(cc.getAbsolutePosition(this._pt, type, containerSize, propertyName)); //different to -x node.setPosition(pt); + cc.getAbsolutePosition(x, y, type, containerSize, propertyName, this._pt); + node.setPosition(this._pt); if (ccbReader._animatedProps.indexOf(propertyName) > -1) { var baseValue = [x, y, type]; @@ -800,8 +800,7 @@ cc.NodeLoader = cc.Class.extend({ onHandlePropTypeScaleLock: function (node, parent, propertyName, scaleLock, ccbReader) { if (propertyName === PROPERTY_SCALE) { - node._scaleX = scaleLock.x; - node._scaleY = scaleLock.y; + node.setScale(scaleLock.x, scaleLock.y); } else { ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName); } diff --git a/extensions/cocostudio/armature/CCArmature.js b/extensions/cocostudio/armature/CCArmature.js index 4ab51a4478..80235b9dd2 100644 --- a/extensions/cocostudio/armature/CCArmature.js +++ b/extensions/cocostudio/armature/CCArmature.js @@ -155,6 +155,7 @@ ccs.Armature = ccs.Node.extend(/** @lends ccs.Armature# */{ return; this._renderCmd.visit(parent && parent._renderCmd); + this._renderCmd._dirtyFlag = 0; }, addChild: function (child, localZOrder, tag) { diff --git a/extensions/cocostudio/armature/CCArmatureCanvasRenderCmd.js b/extensions/cocostudio/armature/CCArmatureCanvasRenderCmd.js index 97617db4f5..bdb35f970f 100644 --- a/extensions/cocostudio/armature/CCArmatureCanvasRenderCmd.js +++ b/extensions/cocostudio/armature/CCArmatureCanvasRenderCmd.js @@ -52,6 +52,9 @@ this._RestoreRenderCmd = new cc.CustomRenderCmd(this, this._RestoreCmdCallback); this._startRenderCmd._canUseDirtyRegion = true; this._RestoreRenderCmd._canUseDirtyRegion = true; + + this._transform = {a: 1, b: 0, c: 0, d: 1, tx: 0, ty: 0}; + this._worldTransform = {a: 1, b: 0, c: 0, d: 1, tx: 0, ty: 0}; }; var proto = ccs.Armature.CanvasRenderCmd.prototype = Object.create(cc.Node.CanvasRenderCmd.prototype); @@ -64,7 +67,6 @@ var wrapper = ctx || cc._renderContext; wrapper.save(); - //set to armature mode wrapper._switchToArmatureMode(true, this._worldTransform, scaleX, scaleY); }; @@ -91,9 +93,9 @@ var colorDirty = boneFlag & flags.colorDirty, opacityDirty = boneFlag & flags.opacityDirty; if (colorDirty) - boneCmd._updateDisplayColor(); + boneCmd._updateDisplayColor(this._displayedColor); if (opacityDirty) - boneCmd._updateDisplayOpacity(); + boneCmd._updateDisplayOpacity(this._displayedOpacity); if (colorDirty || opacityDirty) boneCmd._updateColor(); @@ -114,7 +116,6 @@ proto._RestoreCmdCallback = function (wrapper) { this._cacheDirty = false; - //wrapper.restore(); wrapper._switchToArmatureMode(false); wrapper.restore(); }; @@ -139,17 +140,16 @@ if (null === selNode) continue; - var boneCmd = selBone._renderCmd; - boneCmd._syncStatus(this); + selBone._renderCmd._syncStatus(this); switch (selBone.getDisplayRenderNodeType()) { case ccs.DISPLAY_TYPE_SPRITE: - selNode._renderCmd.visit(boneCmd); + selNode.visit(selBone); break; case ccs.DISPLAY_TYPE_ARMATURE: selNode._renderCmd.rendering(ctx, scaleX, scaleY); break; default: - selNode._renderCmd.visit(boneCmd); + selNode.visit(selBone); break; } } else if (selBone instanceof cc.Node) { @@ -182,13 +182,13 @@ for (i = 0; i < len; i++) { child = children[i]; if (child._localZOrder < 0) - child._renderCmd.visit(cmd); + child.visit(childNode); else break; } cc.renderer.pushRenderCommand(cmd); for (; i < len; i++) - children[i]._renderCmd.visit(cmd); + children[i].visit(childNode); } else { cc.renderer.pushRenderCommand(cmd); } diff --git a/extensions/cocostudio/armature/CCArmatureWebGLRenderCmd.js b/extensions/cocostudio/armature/CCArmatureWebGLRenderCmd.js index ba678dbdf9..bf48084815 100644 --- a/extensions/cocostudio/armature/CCArmatureWebGLRenderCmd.js +++ b/extensions/cocostudio/armature/CCArmatureWebGLRenderCmd.js @@ -30,6 +30,9 @@ this._parentCmd = null; this._realAnchorPointInPoints = new cc.Point(0, 0); + + this._transform = {a: 1, b: 0, c: 0, d: 1, tx: 0, ty: 0}; + this._worldTransform = {a: 1, b: 0, c: 0, d: 1, tx: 0, ty: 0}; }; var proto = ccs.Armature.WebGLRenderCmd.prototype = Object.create(cc.Node.WebGLRenderCmd.prototype); diff --git a/extensions/cocostudio/armature/CCBone.js b/extensions/cocostudio/armature/CCBone.js index 31ce5ae142..953e786b87 100644 --- a/extensions/cocostudio/armature/CCBone.js +++ b/extensions/cocostudio/armature/CCBone.js @@ -688,6 +688,11 @@ ccs.Bone.RenderCmd = { }, transform: function (parentCmd, recursive) { + if (!this._transform) { + this._transform = {a: 1, b: 0, c: 0, d: 1, tx: 0, ty: 0}; + this._worldTransform = {a: 1, b: 0, c: 0, d: 1, tx: 0, ty: 0}; + } + var node = this._node, t = this._transform, wt = this._worldTransform, diff --git a/extensions/cocostudio/armature/display/CCSkinRenderCmd.js b/extensions/cocostudio/armature/display/CCSkinRenderCmd.js index 44c02a907a..eabcd02f00 100644 --- a/extensions/cocostudio/armature/display/CCSkinRenderCmd.js +++ b/extensions/cocostudio/armature/display/CCSkinRenderCmd.js @@ -27,6 +27,11 @@ ccs.Skin.RenderCmd = { _realWorldTM: null, transform: function (parentCmd, recursive) { + if (!this._transform) { + this._transform = {a: 1, b: 0, c: 0, d: 1, tx: 0, ty: 0}; + this._worldTransform = {a: 1, b: 0, c: 0, d: 1, tx: 0, ty: 0}; + } + var node = this._node, pt = parentCmd ? parentCmd._worldTransform : null, t = this._transform, @@ -35,8 +40,8 @@ if (dirty || pt) { this.originTransform(); - cc.affineTransformConcatIn(t, node.bone.getNodeToArmatureTransform()); - this._dirtyFlag = this._dirtyFlag & cc.Node._dirtyFlags.transformDirty ^ this._dirtyFlag; + cc.affineTransformConcatIn(this._transform, node.bone.getNodeToArmatureTransform()); + this._dirtyFlag &= ~cc.Node._dirtyFlags.transformDirty; } if (pt) { diff --git a/extensions/cocostudio/timeline/CCBoneNode.js b/extensions/cocostudio/timeline/CCBoneNode.js index 9ecf5aedc3..e54f931c42 100644 --- a/extensions/cocostudio/timeline/CCBoneNode.js +++ b/extensions/cocostudio/timeline/CCBoneNode.js @@ -437,12 +437,12 @@ ccs.BoneNode = (function () { for (i = 0; i < len; i++) { child = children[i]; if (child._localZOrder < 0) - child._renderCmd.visit(cmd); + child.visit(this); else break; } for (; i < len; i++) - children[i]._renderCmd.visit(cmd); + children[i].visit(this); } cmd._dirtyFlag = 0; }, diff --git a/extensions/cocostudio/timeline/CCSkeletonNode.js b/extensions/cocostudio/timeline/CCSkeletonNode.js index 7c7a005277..28517649d1 100644 --- a/extensions/cocostudio/timeline/CCSkeletonNode.js +++ b/extensions/cocostudio/timeline/CCSkeletonNode.js @@ -155,7 +155,7 @@ ccs.SkeletonNode = (function () { if (this._children.length !== 0) { for (i = 0; i < this._children.length; i++) { node = this._children[i]; - node._renderCmd.visit(cmd); + node.visit(this); } } diff --git a/extensions/gui/control-extension/CCControl.js b/extensions/gui/control-extension/CCControl.js index 2ff72a7ee7..e4071a3ef2 100644 --- a/extensions/gui/control-extension/CCControl.js +++ b/extensions/gui/control-extension/CCControl.js @@ -148,29 +148,26 @@ cc.Control = cc.Layer.extend(/** @lends cc.Control# */{ }, init: function () { - if (cc.Layer.prototype.init.call(this)) { - // Initialise instance variables - this._state = cc.CONTROL_STATE_NORMAL; - this._enabled = true; - this._selected = false; - this._highlighted = false; - - var listener = cc.EventListener.create({ - event: cc.EventListener.TOUCH_ONE_BY_ONE, - swallowTouches: true - }); - if (this.onTouchBegan) - listener.onTouchBegan = this.onTouchBegan.bind(this); - if (this.onTouchMoved) - listener.onTouchMoved = this.onTouchMoved.bind(this); - if (this.onTouchEnded) - listener.onTouchEnded = this.onTouchEnded.bind(this); - if (this.onTouchCancelled) - listener.onTouchCancelled = this.onTouchCancelled.bind(this); - this._touchListener = listener; - return true; - } else - return false; + // Initialise instance variables + this._state = cc.CONTROL_STATE_NORMAL; + this._enabled = true; + this._selected = false; + this._highlighted = false; + + var listener = cc.EventListener.create({ + event: cc.EventListener.TOUCH_ONE_BY_ONE, + swallowTouches: true + }); + if (this.onTouchBegan) + listener.onTouchBegan = this.onTouchBegan.bind(this); + if (this.onTouchMoved) + listener.onTouchMoved = this.onTouchMoved.bind(this); + if (this.onTouchEnded) + listener.onTouchEnded = this.onTouchEnded.bind(this); + if (this.onTouchCancelled) + listener.onTouchCancelled = this.onTouchCancelled.bind(this); + this._touchListener = listener; + return true; }, onEnter: function () { diff --git a/extensions/spine/CCSkeletonWebGLRenderCmd.js b/extensions/spine/CCSkeletonWebGLRenderCmd.js index f287f719b6..ce0c5fb366 100644 --- a/extensions/spine/CCSkeletonWebGLRenderCmd.js +++ b/extensions/spine/CCSkeletonWebGLRenderCmd.js @@ -190,9 +190,9 @@ proto._updateChild = function () { }; - proto._updateRegionAttachmentQuad = function (self, slot, quad, premultipliedAlpha) { + proto._updateRegionAttachmentQuad = function (attachment, slot, quad, premultipliedAlpha) { var vertices = {}; - self.computeVertices(slot.bone.skeleton.x, slot.bone.skeleton.y, slot.bone, vertices); + attachment.computeVertices(slot.bone.skeleton.x, slot.bone.skeleton.y, slot.bone, vertices); var a = slot.bone.skeleton.a * slot.a * attachment.a * 255; var multiplier = premultipliedAlpha ? a : 255; var r = slot.bone.skeleton.r * slot.r * attachment.r * multiplier; @@ -214,19 +214,19 @@ quad.br.vertices.x = vertices[VERTEX.X4]; quad.br.vertices.y = vertices[VERTEX.Y4]; - quad.bl.texCoords.u = self.uvs[VERTEX.X1]; - quad.bl.texCoords.v = self.uvs[VERTEX.Y1]; - quad.tl.texCoords.u = self.uvs[VERTEX.X2]; - quad.tl.texCoords.v = self.uvs[VERTEX.Y2]; - quad.tr.texCoords.u = self.uvs[VERTEX.X3]; - quad.tr.texCoords.v = self.uvs[VERTEX.Y3]; - quad.br.texCoords.u = self.uvs[VERTEX.X4]; - quad.br.texCoords.v = self.uvs[VERTEX.Y4]; + quad.bl.texCoords.u = attachment.uvs[VERTEX.X1]; + quad.bl.texCoords.v = attachment.uvs[VERTEX.Y1]; + quad.tl.texCoords.u = attachment.uvs[VERTEX.X2]; + quad.tl.texCoords.v = attachment.uvs[VERTEX.Y2]; + quad.tr.texCoords.u = attachment.uvs[VERTEX.X3]; + quad.tr.texCoords.v = attachment.uvs[VERTEX.Y3]; + quad.br.texCoords.u = attachment.uvs[VERTEX.X4]; + quad.br.texCoords.v = attachment.uvs[VERTEX.Y4]; }; - proto._updateMeshAttachmentQuad = function (self, slot, quad, premultipliedAlpha) { + proto._updateMeshAttachmentQuad = function (attachment, slot, quad, premultipliedAlpha) { var vertices = {}; - self.computeWorldVertices(slot.bone.x, slot.bone.y, slot, vertices); + attachment.computeWorldVertices(slot.bone.x, slot.bone.y, slot, vertices); var r = slot.bone.skeleton.r * slot.r * 255; var g = slot.bone.skeleton.g * slot.g * 255; var b = slot.bone.skeleton.b * slot.b * 255; @@ -253,13 +253,13 @@ quad.br.vertices.x = vertices[VERTEX.X4]; quad.br.vertices.y = vertices[VERTEX.Y4]; - quad.bl.texCoords.u = self.uvs[VERTEX.X1]; - quad.bl.texCoords.v = self.uvs[VERTEX.Y1]; - quad.tl.texCoords.u = self.uvs[VERTEX.X2]; - quad.tl.texCoords.v = self.uvs[VERTEX.Y2]; - quad.tr.texCoords.u = self.uvs[VERTEX.X3]; - quad.tr.texCoords.v = self.uvs[VERTEX.Y3]; - quad.br.texCoords.u = self.uvs[VERTEX.X4]; - quad.br.texCoords.v = self.uvs[VERTEX.Y4]; + quad.bl.texCoords.u = attachment.uvs[VERTEX.X1]; + quad.bl.texCoords.v = attachment.uvs[VERTEX.Y1]; + quad.tl.texCoords.u = attachment.uvs[VERTEX.X2]; + quad.tl.texCoords.v = attachment.uvs[VERTEX.Y2]; + quad.tr.texCoords.u = attachment.uvs[VERTEX.X3]; + quad.tr.texCoords.v = attachment.uvs[VERTEX.Y3]; + quad.br.texCoords.u = attachment.uvs[VERTEX.X4]; + quad.br.texCoords.v = attachment.uvs[VERTEX.Y4]; }; })();