From ac1940fda5e4b4d493a22bfe6dfd552d4cf27b62 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=91=D0=B5=D1=81=D1=88=D0=B0=D0=BF=D0=BE=D1=88=D0=BD?= =?UTF-8?q?=D0=B8=D0=BA=D0=BE=D0=B2=20=D0=9D=D0=B8=D0=BA=D0=B8=D1=82=D0=B0?= Date: Tue, 27 Sep 2016 10:52:02 +0300 Subject: [PATCH 001/206] Change bright style on 'setEnabled' call of ccui.Widget --- extensions/ccui/base-classes/UIWidget.js | 1 + 1 file changed, 1 insertion(+) diff --git a/extensions/ccui/base-classes/UIWidget.js b/extensions/ccui/base-classes/UIWidget.js index 2bc42f2b71..8dee5c29b3 100644 --- a/extensions/ccui/base-classes/UIWidget.js +++ b/extensions/ccui/base-classes/UIWidget.js @@ -346,6 +346,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ */ setEnabled: function (enabled) { this._enabled = enabled; + this.setBright(enabled); }, /** From 8a710bda6d7618adc16b5ae4f116ba83cdd07273 Mon Sep 17 00:00:00 2001 From: Ron Yeh Date: Sun, 2 Oct 2016 02:03:10 -0700 Subject: [PATCH 002/206] doEnumerateRecursive(node, name, callback) now returns the return value. --- cocos2d/core/base-nodes/CCNode.js | 1 + 1 file changed, 1 insertion(+) diff --git a/cocos2d/core/base-nodes/CCNode.js b/cocos2d/core/base-nodes/CCNode.js index a5df64d76e..f31e704a47 100644 --- a/cocos2d/core/base-nodes/CCNode.js +++ b/cocos2d/core/base-nodes/CCNode.js @@ -2513,6 +2513,7 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{ } } } + return ret; }, doEnumerate: function(name, callback){ From d7f91d694d0f0b23b38dbef135a99ab25da597c1 Mon Sep 17 00:00:00 2001 From: Ron Yeh Date: Sun, 2 Oct 2016 15:10:07 -0700 Subject: [PATCH 003/206] Fix typos in comments and function name. --- cocos2d/actions/CCAction.js | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/cocos2d/actions/CCAction.js b/cocos2d/actions/CCAction.js index bc4dccff85..8e823805b4 100644 --- a/cocos2d/actions/CCAction.js +++ b/cocos2d/actions/CCAction.js @@ -185,7 +185,7 @@ cc.Action = cc.Class.extend(/** @lends cc.Action# */{ }, /** - * Currently JavaScript Bindigns (JSB), in some cases, needs to use retain and release. This is a bug in JSB,
+ * Currently JavaScript Bindings (JSB), in some cases, needs to use retain and release. This is a bug in JSB,
* 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. */ @@ -193,7 +193,7 @@ cc.Action = cc.Class.extend(/** @lends cc.Action# */{ }, /** - * Currently JavaScript Bindigns (JSB), in some cases, needs to use retain and release. This is a bug in JSB,
+ * Currently JavaScript Bindings (JSB), in some cases, needs to use retain and release. This is a bug in JSB,
* 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. */ @@ -238,7 +238,7 @@ cc.Action.create = cc.action; * @extends cc.Action */ cc.FiniteTimeAction = cc.Action.extend(/** @lends cc.FiniteTimeAction# */{ - //! duration in seconds + // duration in seconds _duration:0, /** @@ -562,7 +562,7 @@ cc.Follow = cc.Action.extend(/** @lends cc.Follow# */{ * * @param {Boolean} value */ - setBoudarySet:function (value) { + setBoundarySet:function (value) { this._boundarySet = value; }, From b957fb195f16615b604a5e187f2fc9567b50b57e Mon Sep 17 00:00:00 2001 From: Ron Yeh Date: Thu, 6 Oct 2016 01:41:59 -0700 Subject: [PATCH 004/206] Fix bug where PRIORITY_NON_SYSTEM is NaN. Moved the constant into the cc.Scheduler namespace for consistency with PRIORITY_SYSTEM. --- cocos2d/core/CCScheduler.js | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/cocos2d/core/CCScheduler.js b/cocos2d/core/CCScheduler.js index 4075d970d2..7cb91e69ce 100644 --- a/cocos2d/core/CCScheduler.js +++ b/cocos2d/core/CCScheduler.js @@ -25,12 +25,6 @@ ****************************************************************************/ -/** - * Minimum priority level for user scheduling. - * @constant - * @type Number - */ -cc.PRIORITY_NON_SYSTEM = cc.PRIORITY_SYSTEM + 1; //data structures /** @@ -1029,9 +1023,17 @@ cc.Scheduler = cc.Class.extend(/** @lends cc.Scheduler# */{ this.unscheduleAllWithMinPriority(minPriority); } }); + /** * Priority level reserved for system services. * @constant * @type Number */ cc.Scheduler.PRIORITY_SYSTEM = (-2147483647 - 1); + +/** + * Minimum priority level for user scheduling. + * @constant + * @type Number + */ +cc.Scheduler.PRIORITY_NON_SYSTEM = cc.Scheduler.PRIORITY_SYSTEM + 1; From a700c2193c23461cbade9d3c22c6f07e53d5704f Mon Sep 17 00:00:00 2001 From: dimon4eg Date: Mon, 10 Oct 2016 23:14:19 +0300 Subject: [PATCH 005/206] Fix particle system load from plist generated by x-studio365 --- cocos2d/particle/CCParticleSystem.js | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/cocos2d/particle/CCParticleSystem.js b/cocos2d/particle/CCParticleSystem.js index 3a0d3bdc8a..6239d7adaa 100644 --- a/cocos2d/particle/CCParticleSystem.js +++ b/cocos2d/particle/CCParticleSystem.js @@ -1391,8 +1391,13 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ locModeA.tangentialAccelVar = (pszTmp) ? parseFloat(pszTmp) : 0; // rotation is dir - var locRotationIsDir = locValueForKey("rotationIsDir", dictionary).toLowerCase(); - locModeA.rotationIsDir = (locRotationIsDir != null && (locRotationIsDir === "true" || locRotationIsDir === "1")); + var locRotationIsDir = locValueForKey("rotationIsDir", dictionary); + if (locRotationIsDir !== null) { + locRotationIsDir = locRotationIsDir.toString().toLowerCase(); + locModeA.rotationIsDir = (locRotationIsDir === "true" || locRotationIsDir === "1"); + } + else + locModeA.rotationIsDir = false; } else if (this.emitterMode === cc.ParticleSystem.MODE_RADIUS) { // or Mode B: radius movement var locModeB = this.modeB; From c1d62705d314ace4d4f50381a229f40dbd5d969c Mon Sep 17 00:00:00 2001 From: pandamicro Date: Thu, 13 Oct 2016 22:09:27 +0800 Subject: [PATCH 006/206] Forbidden screen adaptation during edit box focus --- extensions/editbox/CCEditBox.js | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/extensions/editbox/CCEditBox.js b/extensions/editbox/CCEditBox.js index c928dba439..0959500ab2 100644 --- a/extensions/editbox/CCEditBox.js +++ b/extensions/editbox/CCEditBox.js @@ -265,6 +265,7 @@ cc.EditBox = cc.ControlButton.extend({ tmpEdTxt.style.padding = "0"; this.__fullscreen = false; + this.__autoResize = false; var onCanvasClick = function() { this._edTxt.blur();}; this._onCanvasClick = onCanvasClick.bind(this); @@ -285,13 +286,15 @@ cc.EditBox = cc.ControlButton.extend({ this._keyPressEvent = keypressEvent.bind(this); var focusEvent = function () { // Exit fullscreen - if(cc.view.isAutoFullScreenEnabled()) { + if (cc.view.isAutoFullScreenEnabled()) { this.__fullscreen = true; cc.view.enableAutoFullScreen(false); cc.screen.exitFullScreen(); } else { this.__fullscreen = false; } + this.__autoResize = cc.view.__resizeWithBrowserSize; + cc.view.resizeWithBrowserSize(false); if (this._edTxt.value === this._placeholderText) { this._edTxt.value = ""; @@ -309,9 +312,12 @@ cc.EditBox = cc.ControlButton.extend({ this._focusEvent = focusEvent.bind(this); var blurEvent = function () { // Resume fullscreen logic - if(this.__fullscreen) { + if (this.__fullscreen) { cc.view.enableAutoFullScreen(true); } + if (this.__autoResize) { + cc.view.resizeWithBrowserSize(true); + } if (this._edTxt.value === "") { this._edTxt.value = this._placeholderText; From bd872b7db2d6410602d584f549c146eabe299b56 Mon Sep 17 00:00:00 2001 From: DavidDeSimone Date: Wed, 2 Nov 2016 21:27:12 -0700 Subject: [PATCH 007/206] Native spine will default to blend func GL_ONE/GL_ONE_MINUS_SRC_ALPHA, or GL_SRC_ALPHA/GL_ONE_MINUS_SRC_ALPHA, if none are provided. This differs from web, which would just use the nodes blend func. This commit brings web into parity with native --- extensions/spine/CCSkeletonWebGLRenderCmd.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/spine/CCSkeletonWebGLRenderCmd.js b/extensions/spine/CCSkeletonWebGLRenderCmd.js index 9eb185a204..a84ec60f40 100644 --- a/extensions/spine/CCSkeletonWebGLRenderCmd.js +++ b/extensions/spine/CCSkeletonWebGLRenderCmd.js @@ -103,7 +103,7 @@ cc.glBlendFunc(cc.ONE, cc.ONE_MINUS_SRC_COLOR); break; default: - cc.glBlendFunc(locBlendFunc.src, locBlendFunc.dst); + cc.glBlendFunc(premultiAlpha ? cc.ONE : cc.SRC_ALPHA, cc.ONE_MINUS_SRC_ALPHA); } } else if (regionTextureAtlas != textureAtlas && textureAtlas) { textureAtlas.drawQuads(); From 2ff174e27ffa56e37763889ff3aecd5b23b1fddf Mon Sep 17 00:00:00 2001 From: pandamicro Date: Thu, 3 Nov 2016 16:54:13 +0800 Subject: [PATCH 008/206] Improve platform detection --- CCBoot.js | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/CCBoot.js b/CCBoot.js index c901d49cfe..d2910a4391 100644 --- a/CCBoot.js +++ b/CCBoot.js @@ -1666,7 +1666,7 @@ var _initSys = function () { * @name isMobile * @type {Boolean} */ - sys.isMobile = ua.indexOf('mobile') !== -1 || ua.indexOf('android') !== -1; + sys.isMobile = /mobile|android|iphone|ipad/.test(ua); /** * Indicate the running platform @@ -1701,6 +1701,11 @@ var _initSys = function () { iOS = true; osVersion = uaResult[2] || ''; osMainVersion = parseInt(osVersion) || 0; + } + else if (/(iPhone|iPad|iPod)/.exec(nav.platform)) { + iOS = true; + osVersion = ''; + osMainVersion = 0; } var osName = sys.OS_UNKNOWN; @@ -2089,7 +2094,7 @@ function _afterEngineLoaded(config) { if (cc._initDebugSetting) cc._initDebugSetting(config[cc.game.CONFIG_KEY.debugMode]); cc._engineLoaded = true; - cc.log(cc.ENGINE_VERSION); + console.log(cc.ENGINE_VERSION); if (_engineLoadedCallback) _engineLoadedCallback(); } From 34715e7611400a51738e8603f9f61d2f5b8a0caa Mon Sep 17 00:00:00 2001 From: pandamicro Date: Thu, 3 Nov 2016 16:55:03 +0800 Subject: [PATCH 009/206] Unify Scheduler:isScheduled behavior with JSB --- cocos2d/core/CCScheduler.js | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/cocos2d/core/CCScheduler.js b/cocos2d/core/CCScheduler.js index 4075d970d2..4ba83d81a8 100644 --- a/cocos2d/core/CCScheduler.js +++ b/cocos2d/core/CCScheduler.js @@ -768,26 +768,27 @@ cc.Scheduler = cc.Class.extend(/** @lends cc.Scheduler# */{ } }, - isScheduled: function(key, target){ + isScheduled: function(callback, target){ //key, target //selector, target - cc.assert(key, "Argument key must not be empty"); + cc.assert(callback, "Argument callback must not be empty"); cc.assert(target, "Argument target must be non-nullptr"); - var element = this._hashForUpdates[target.__instanceId]; + var element = this._hashForTimers[target.__instanceId]; - if (!element){ + if (!element) { return false; } if (element.timers == null){ return false; - }else{ + } + else { var timers = element.timers; - for (var i = 0; i < timers.length; ++i){ + for (var i = 0; i < timers.length; ++i) { var timer = timers[i]; - if (key === timer.getKey()){ + if (callback === timer._selector){ return true; } } From 6ed695c8f7adff06bcfec4236e944f6c243ed7d2 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Thu, 3 Nov 2016 16:56:23 +0800 Subject: [PATCH 010/206] Fix wechat touch end/cancel not fired issue --- CCBoot.js | 15 +++++++++++++++ cocos2d/core/event-manager/CCTouch.js | 1 + cocos2d/core/platform/CCInputManager.js | 21 +++++++++++++++++++-- 3 files changed, 35 insertions(+), 2 deletions(-) diff --git a/CCBoot.js b/CCBoot.js index d2910a4391..4c77147e6f 100644 --- a/CCBoot.js +++ b/CCBoot.js @@ -2020,6 +2020,21 @@ var _initSys = function () { sys.openURL = function(url){ window.open(url); }; + + /** + * Get the number of milliseconds elapsed since 1 January 1970 00:00:00 UTC. + * @memberof cc.sys + * @name now + * @return {Number} + */ + sys.now = function () { + if (Date.now) { + return Date.now(); + } + else { + return +(new Date); + } + }; }; _initSys(); diff --git a/cocos2d/core/event-manager/CCTouch.js b/cocos2d/core/event-manager/CCTouch.js index c36cea14dc..3c8ea79fb9 100644 --- a/cocos2d/core/event-manager/CCTouch.js +++ b/cocos2d/core/event-manager/CCTouch.js @@ -33,6 +33,7 @@ * @param {Number} id */ cc.Touch = cc.Class.extend(/** @lends cc.Touch# */{ + _lastModified: 0, _point:null, _prevPoint:null, _id:0, diff --git a/cocos2d/core/platform/CCInputManager.js b/cocos2d/core/platform/CCInputManager.js index 7d655130f7..11230c464a 100644 --- a/cocos2d/core/platform/CCInputManager.js +++ b/cocos2d/core/platform/CCInputManager.js @@ -56,6 +56,8 @@ cc.UIInterfaceOrientationPortrait = 0; * @name cc.inputManager */ cc.inputManager = /** @lends cc.inputManager# */{ + TOUCH_TIMEOUT: 5000, + _mousePressed: false, _isRegisterEvent: false, @@ -81,12 +83,21 @@ cc.inputManager = /** @lends cc.inputManager# */{ _getUnUsedIndex: function () { var temp = this._indexBitsUsed; + var now = cc.sys.now(); for (var i = 0; i < this._maxTouches; i++) { if (!(temp & 0x00000001)) { this._indexBitsUsed |= (1 << i); return i; } + else { + var touch = this._touches[i]; + if (now - touch._lastModified > this.TOUCH_TIMEOUT) { + this._removeUsedIndexBit(i); + delete this._touchesIntegerDict[touch.getID()]; + return i; + } + } temp >>= 1; } @@ -110,7 +121,9 @@ cc.inputManager = /** @lends cc.inputManager# */{ * @param {Array} touches */ handleTouchesBegin: function (touches) { - var selTouch, index, curTouch, touchID, handleTouches = [], locTouchIntDict = this._touchesIntegerDict; + var selTouch, index, curTouch, touchID, + handleTouches = [], locTouchIntDict = this._touchesIntegerDict, + now = cc.sys.now(); for(var i = 0, len = touches.length; i< len; i ++){ selTouch = touches[i]; touchID = selTouch.getID(); @@ -124,6 +137,7 @@ cc.inputManager = /** @lends cc.inputManager# */{ } //curTouch = this._touches[unusedIndex] = selTouch; curTouch = this._touches[unusedIndex] = new cc.Touch(selTouch._point.x, selTouch._point.y, selTouch.getID()); + curTouch._lastModified = now; curTouch._setPrevPoint(selTouch._prevPoint); locTouchIntDict[touchID] = unusedIndex; handleTouches.push(curTouch); @@ -142,7 +156,9 @@ cc.inputManager = /** @lends cc.inputManager# */{ * @param {Array} touches */ handleTouchesMove: function(touches){ - var selTouch, index, touchID, handleTouches = [], locTouches = this._touches; + var selTouch, index, touchID, + handleTouches = [], locTouches = this._touches, + now = cc.sys.now(); for(var i = 0, len = touches.length; i< len; i ++){ selTouch = touches[i]; touchID = selTouch.getID(); @@ -155,6 +171,7 @@ cc.inputManager = /** @lends cc.inputManager# */{ if(locTouches[index]){ locTouches[index]._setPoint(selTouch._point); locTouches[index]._setPrevPoint(selTouch._prevPoint); + locTouches[index]._lastModified = now; handleTouches.push(locTouches[index]); } } From 1d856ef34285d58c1688a34bc9f624feb0b9d922 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Thu, 3 Nov 2016 16:56:53 +0800 Subject: [PATCH 011/206] Improve screen adaptation logic --- cocos2d/core/platform/CCEGLView.js | 35 ++++++++++++++++++++---------- 1 file changed, 24 insertions(+), 11 deletions(-) diff --git a/cocos2d/core/platform/CCEGLView.js b/cocos2d/core/platform/CCEGLView.js index a23b8c61ca..5e039bd91d 100644 --- a/cocos2d/core/platform/CCEGLView.js +++ b/cocos2d/core/platform/CCEGLView.js @@ -217,13 +217,14 @@ cc.EGLView = cc.Class.extend(/** @lends cc.view# */{ return; // Frame size changed, do resize works - if (view._resizeCallback) { - view._resizeCallback.call(); - } var width = view._originalDesignResolutionSize.width; var height = view._originalDesignResolutionSize.height; - if (width > 0) { + if (width > 0) view.setDesignResolutionSize(width, height, view._resolutionPolicy); + + cc.eventManager.dispatchCustomEvent('canvas-resize'); + if (view._resizeCallback) { + view._resizeCallback.call(); } }, @@ -287,7 +288,7 @@ cc.EGLView = cc.Class.extend(/** @lends cc.view# */{ * @param {Function|null} callback The callback function */ setResizeCallback: function (callback) { - if (cc.isFunction(callback) || callback == null) { + if (typeof callback === 'function' || callback == null) { this._resizeCallback = callback; } }, @@ -304,6 +305,9 @@ cc.EGLView = cc.Class.extend(/** @lends cc.view# */{ orientation = orientation & cc.ORIENTATION_AUTO; if (orientation) { this._orientation = orientation; + var designWidth = this._originalDesignResolutionSize.width; + var designHeight = this._originalDesignResolutionSize.height; + this.setDesignResolutionSize(designWidth, designHeight, this._resolutionPolicy); } }, @@ -428,7 +432,7 @@ cc.EGLView = cc.Class.extend(/** @lends cc.view# */{ * @param {Boolean} enabled Enable or disable retina display */ enableRetina: function(enabled) { - this._retinaEnabled = enabled ? true : false; + this._retinaEnabled = !!enabled; }, /** @@ -672,6 +676,8 @@ cc.EGLView = cc.Class.extend(/** @lends cc.view# */{ if(cc.sys.isMobile) this._adjustViewportMeta(); + // Permit to re-detect the orientation of device. + this._orientationChanging = true; this._initFrameSize(); this._originalDesignResolutionSize.width = this._designResolutionSize.width = width; @@ -713,6 +719,9 @@ cc.EGLView = cc.Class.extend(/** @lends cc.view# */{ // reset director's member variables to fit visible rect director.setGLDefaultValues(); } + else if (cc._renderType === cc.game.RENDER_TYPE_CANVAS) { + cc.renderer._allNeedDraw = true; + } this._originalScaleX = this._scaleX; this._originalScaleY = this._scaleY; @@ -747,7 +756,7 @@ cc.EGLView = cc.Class.extend(/** @lends cc.view# */{ */ setRealPixelResolution: function (width, height, resolutionPolicy) { // Set viewport's width - this._setViewportMeta({"width": width, "target-densitydpi": cc.DENSITYDPI_DEVICE}, true); + this._setViewportMeta({"width": width}, true); // Set body width to the exact pixel resolution document.body.style.width = width + "px"; @@ -871,10 +880,10 @@ cc.EGLView = cc.Class.extend(/** @lends cc.view# */{ return this._isRotated ? {x: this._viewPortRect.width - y, y: x} : {x: x, y: y}; }, - _convertMouseToLocationInView: function(point, relatedPos) { - var locViewPortRect = this._viewPortRect, _t = this; - point.x = ((_t._devicePixelRatio * (point.x - relatedPos.left)) - locViewPortRect.x) / _t._scaleX; - point.y = (_t._devicePixelRatio * (relatedPos.top + relatedPos.height - point.y) - locViewPortRect.y) / _t._scaleY; + _convertMouseToLocationInView: function (point, relatedPos) { + var viewport = this._viewPortRect, _t = this; + point.x = ((_t._devicePixelRatio * (point.x - relatedPos.left)) - viewport.x) / _t._scaleX; + point.y = (_t._devicePixelRatio * (relatedPos.top + relatedPos.height - point.y) - viewport.y) / _t._scaleY; }, _convertPointWithScale: function (point) { @@ -945,6 +954,10 @@ cc.ContainerStrategy = cc.Class.extend(/** @lends cc.ContainerStrategy# */{ _setupContainer: function (view, w, h) { var locCanvas = cc.game.canvas, locContainer = cc.game.container; + if (cc.sys.os === cc.sys.OS_ANDROID) { + document.body.style.width = (view._isRotated ? h : w) + 'px'; + document.body.style.height = (view._isRotated ? w : h) + 'px'; + } // Setup style locContainer.style.width = locCanvas.style.width = w + 'px'; From 0846e9abb53ba5714b65d303208db774085198c3 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Thu, 3 Nov 2016 16:59:06 +0800 Subject: [PATCH 012/206] Fix skeleton webgl render command --- extensions/spine/CCSkeletonWebGLRenderCmd.js | 16 +++++----------- 1 file changed, 5 insertions(+), 11 deletions(-) diff --git a/extensions/spine/CCSkeletonWebGLRenderCmd.js b/extensions/spine/CCSkeletonWebGLRenderCmd.js index 9eb185a204..dea64ae6ee 100644 --- a/extensions/spine/CCSkeletonWebGLRenderCmd.js +++ b/extensions/spine/CCSkeletonWebGLRenderCmd.js @@ -191,17 +191,11 @@ proto._updateRegionAttachmentQuad = function(self, slot, quad, premultipliedAlpha) { var vertices = {}; self.computeVertices(slot.bone.skeleton.x, slot.bone.skeleton.y, slot.bone, 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; - var normalizedAlpha = slot.bone.skeleton.a * slot.a; - - if (premultipliedAlpha) { - r *= normalizedAlpha; - g *= normalizedAlpha; - b *= normalizedAlpha; - } - var a = normalizedAlpha * 255; + 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; + var g = slot.bone.skeleton.g * slot.g * attachment.g * multiplier; + var b = slot.bone.skeleton.b * slot.b * attachment.b * multiplier; quad.bl.colors.r = quad.tl.colors.r = quad.tr.colors.r = quad.br.colors.r = r; quad.bl.colors.g = quad.tl.colors.g = quad.tr.colors.g = quad.br.colors.g = g; From 02e344696afc42e2ce2f19a0dec7ee5bc525d38d Mon Sep 17 00:00:00 2001 From: pandamicro Date: Thu, 3 Nov 2016 16:59:58 +0800 Subject: [PATCH 013/206] Upgrade EditBox --- cocos2d/core/platform/CCEGLView.js | 3 - extensions/editbox/CCEditBox.js | 1255 +++++++++++++++++++++------- extensions/editbox/CCdomNode.js | 659 --------------- moduleConfig.json | 1 - 4 files changed, 934 insertions(+), 984 deletions(-) delete mode 100644 extensions/editbox/CCdomNode.js diff --git a/cocos2d/core/platform/CCEGLView.js b/cocos2d/core/platform/CCEGLView.js index 5e039bd91d..02a5122324 100644 --- a/cocos2d/core/platform/CCEGLView.js +++ b/cocos2d/core/platform/CCEGLView.js @@ -725,9 +725,6 @@ cc.EGLView = cc.Class.extend(/** @lends cc.view# */{ this._originalScaleX = this._scaleX; this._originalScaleY = this._scaleY; - // For editbox - if (cc.DOM) - cc.DOM._resetEGLViewDiv(); cc.visibleRect && cc.visibleRect.init(this._visibleRect); }, diff --git a/extensions/editbox/CCEditBox.js b/extensions/editbox/CCEditBox.js index 0959500ab2..5d3f23a25a 100644 --- a/extensions/editbox/CCEditBox.js +++ b/extensions/editbox/CCEditBox.js @@ -1,7 +1,7 @@ /**************************************************************************** - Copyright (c) 2011-2012 cocos2d-x.org - Copyright (c) 2013-2014 Chukong Technologies Inc. + Copyright (c) 2013-2016 Chukong Technologies Inc. Copyright (c) 2012 James Chen + Copyright (c) 2011-2012 cocos2d-x.org http://www.cocos2d-x.org @@ -154,14 +154,14 @@ cc.EditBoxDelegate = cc.Class.extend({ * This method is called when an edit box gains focus after keyboard is shown. * @param {cc.EditBox} sender */ - editBoxEditingDidBegin: function (sender) { + editBoxEditingDidBegan: function (sender) { }, /** * This method is called when an edit box loses focus after keyboard is hidden. * @param {cc.EditBox} sender */ - editBoxEditingDidEnd: function (sender) { + editBoxEditingDidEnded: function (sender) { }, /** @@ -176,10 +176,11 @@ cc.EditBoxDelegate = cc.Class.extend({ * This method is called when the return button was pressed. * @param {cc.EditBox} sender */ - editBoxReturn: function (sender) { + editBoxEditingReturn: function (sender) { } }); + /** *

cc.EditBox is a brief Class for edit box.
* You can use this widget to gather small amounts of text from the user.

@@ -204,36 +205,20 @@ cc.EditBoxDelegate = cc.Class.extend({ * @property {Number} returnType - <@writeonly> Return type of edit box, value should be one of the KeyboardReturnType constants. * */ -cc.EditBox = cc.ControlButton.extend({ - _domInputSprite: null, - +cc.EditBox = cc.Node.extend({ + _backgroundSprite: null, _delegate: null, - _editBoxInputMode: cc.EDITBOX_INPUT_MODE_ANY, + _editBoxInputMode: cc.EDITBOX_INPUT_MODE_SINGLELINE, _editBoxInputFlag: cc.EDITBOX_INPUT_FLAG_SENSITIVE, _keyboardReturnType: cc.KEYBOARD_RETURNTYPE_DEFAULT, - - _text: "", - _placeholderText: "", - _textColor: null, - _placeholderColor: null, _maxLength: 50, - _adjustHeight: 18, - - _edTxt: null, - _edFontSize: 14, - _edFontName: "Arial", - - _placeholderFontName: "", + _text: '', + _textColor: null, + _placeholderText: '', + _placeholderFontName: '', _placeholderFontSize: 14, - - _tooltip: false, - _className: "EditBox", - - _onCanvasClick : null, - _inputEvent : null, - _keyPressEvent : null, - _focusEvent : null, - _blurEvent : null, + _placeholderColor: null, + _className: 'EditBox', /** * constructor of cc.EditBox @@ -242,221 +227,201 @@ cc.EditBox = cc.ControlButton.extend({ * @param {cc.Scale9Sprite} press9SpriteBg * @param {cc.Scale9Sprite} disabled9SpriteBg */ - ctor: function (size, normal9SpriteBg, press9SpriteBg, disabled9SpriteBg) { - cc.ControlButton.prototype.ctor.call(this); + ctor: function (size, normal9SpriteBg) { + cc.Node.prototype.ctor.call(this); + this.setAnchorPoint(cc.p(0.5, 0.5)); this._textColor = cc.color.WHITE; this._placeholderColor = cc.color.GRAY; - this.setContentSize(size); - var tmpDOMSprite = this._domInputSprite = new cc.Sprite(); - tmpDOMSprite.draw = function () {}; //redefine draw function - this.addChild(tmpDOMSprite); - var tmpEdTxt = this._edTxt = document.createElement("input"); - tmpEdTxt.type = "text"; - tmpEdTxt.style.fontSize = this._edFontSize + "px"; - tmpEdTxt.style.color = "#000000"; - tmpEdTxt.style.border = 0; - tmpEdTxt.style.background = "transparent"; - //tmpEdTxt.style.paddingLeft = "2px"; - tmpEdTxt.style.width = "100%"; - tmpEdTxt.style.height = "100%"; - tmpEdTxt.style.active = 0; - tmpEdTxt.style.outline = "medium"; - tmpEdTxt.style.padding = "0"; - - this.__fullscreen = false; - this.__autoResize = false; - var onCanvasClick = function() { this._edTxt.blur();}; - this._onCanvasClick = onCanvasClick.bind(this); - - var inputEvent = function () { - if (this._delegate && this._delegate.editBoxTextChanged) - this._delegate.editBoxTextChanged(this, this._edTxt.value); - }; - this._inputEvent = inputEvent.bind(this); - var keypressEvent = function ( e ) { - if (e.keyCode === cc.KEY.enter) { - e.stopPropagation(); - e.preventDefault(); - if (this._delegate && this._delegate.editBoxReturn) - this._delegate.editBoxReturn(this); - cc._canvas.focus(); - } - }; - this._keyPressEvent = keypressEvent.bind(this); - var focusEvent = function () { - // Exit fullscreen - if (cc.view.isAutoFullScreenEnabled()) { - this.__fullscreen = true; - cc.view.enableAutoFullScreen(false); - cc.screen.exitFullScreen(); - } else { - this.__fullscreen = false; - } - this.__autoResize = cc.view.__resizeWithBrowserSize; - cc.view.resizeWithBrowserSize(false); + cc.Node.prototype.setContentSize.call(this, size); - if (this._edTxt.value === this._placeholderText) { - this._edTxt.value = ""; - this._edTxt.style.fontSize = this._edFontSize + "px"; - this._edTxt.style.color = cc.colorToHex(this._textColor); - if (this._editBoxInputFlag === cc.EDITBOX_INPUT_FLAG_PASSWORD) - this._edTxt.type = "password"; - else - this._edTxt.type = "text"; - } - if (this._delegate && this._delegate.editBoxEditingDidBegin) - this._delegate.editBoxEditingDidBegin(this); - cc._canvas.addEventListener("click", this._onCanvasClick); - }; - this._focusEvent = focusEvent.bind(this); - var blurEvent = function () { - // Resume fullscreen logic - if (this.__fullscreen) { - cc.view.enableAutoFullScreen(true); - } - if (this.__autoResize) { - cc.view.resizeWithBrowserSize(true); - } + this._renderCmd._createLabels(); + this.createDomElementIfNeeded(); - if (this._edTxt.value === "") { - this._edTxt.value = this._placeholderText; - this._edTxt.style.fontSize = this._placeholderFontSize + "px"; - this._edTxt.style.color = cc.colorToHex(this._placeholderColor); - this._edTxt.type = "text"; - } - if (this._delegate && this._delegate.editBoxEditingDidEnd) - this._delegate.editBoxEditingDidEnd(this); - cc._canvas.removeEventListener('click', this._onCanvasClick); - }; - this._blurEvent = blurEvent.bind(this); + this.initWithSizeAndBackgroundSprite(size, normal9SpriteBg); + + cc.eventManager.addListener({ + event: cc.EventListener.TOUCH_ONE_BY_ONE, + swallowTouches: true, + onTouchBegan: this._onTouchBegan.bind(this), + onTouchEnded: this._onTouchEnded.bind(this) + }, this); + + this.setInputFlag(this._editBoxInputFlag); + }, + + _createRenderCmd: function () { + if (cc._renderType === cc.game.RENDER_TYPE_CANVAS) { + return new cc.EditBox.CanvasRenderCmd(this); + } else { + return new cc.EditBox.WebGLRenderCmd(this); + } + }, + + setContentSize: function (width, height) { + if (width.width !== undefined && width.height !== undefined) { + height = width.height; + width = width.width; + } + cc.Node.prototype.setContentSize.call(this, width, height); + this._updateEditBoxSize(width, height); + }, - tmpEdTxt.addEventListener("input", this._inputEvent); - tmpEdTxt.addEventListener("keypress", this._keyPressEvent); - tmpEdTxt.addEventListener("focus", this._focusEvent); - tmpEdTxt.addEventListener("blur", this._blurEvent); + setVisible: function ( visible ) { + cc.Node.prototype.setVisible.call(this, visible); + this._renderCmd.updateVisibility(); + }, - cc.DOM.convert(tmpDOMSprite); - tmpDOMSprite.dom.appendChild(tmpEdTxt); - tmpDOMSprite.dom.showTooltipDiv = false; - tmpDOMSprite.dom.style.width = (size.width - 6) + "px"; - tmpDOMSprite.dom.style.height = (size.height - 6) + "px"; + createDomElementIfNeeded: function () { + if(!this._renderCmd._edTxt) { + this._renderCmd.createNativeControl(); + } + }, - //this._domInputSprite.dom.style.borderWidth = "1px"; - //this._domInputSprite.dom.style.borderStyle = "solid"; - //this._domInputSprite.dom.style.borderRadius = "8px"; - tmpDOMSprite.canvas.remove(); + setTabIndex: function(index) { + if(this._renderCmd._edTxt) { + this._renderCmd._edTxt.tabIndex = index; + } + }, - if (this.initWithSizeAndBackgroundSprite(size, normal9SpriteBg)) { - if (press9SpriteBg) - this.setBackgroundSpriteForState(press9SpriteBg, cc.CONTROL_STATE_HIGHLIGHTED); - if (disabled9SpriteBg) - this.setBackgroundSpriteForState(disabled9SpriteBg, cc.CONTROL_STATE_DISABLED); + 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) { + this._renderCmd._edTxt.focus(); + } + }, + + isFocused: function() { + if(this._renderCmd._edTxt) { + return document.activeElement === this._renderCmd._edTxt; + } + cc.warn('The dom control is not created!'); + return false; + }, + + stayOnTop: function (flag) { + if(this._alwaysOnTop === flag) return; + + this._alwaysOnTop = flag; + this._renderCmd.stayOnTop(this._alwaysOnTop); + }, + + cleanup: function () { + this._super(); + + this._renderCmd._removeDomInputControl(); + }, + + _onTouchBegan: function (touch) { + var touchPoint = touch.getLocation(); + var bb = cc.rect(0,0, this._contentSize.width, this._contentSize.height); + var hitted = cc.rectContainsPoint(bb, this.convertToNodeSpace(touchPoint)); + if(hitted) { + return true; + } + else { + this._renderCmd.hidden(); + return false; + } + }, + + _onTouchEnded: function () { + this._renderCmd.show(); + }, + + _updateBackgroundSpriteSize: function (width, height) { + if(this._backgroundSprite) { + this._backgroundSprite.setContentSize(width, height); + } + }, + + _updateEditBoxSize: function(size, height) { + var newWidth = (typeof size.width === 'number') ? size.width : size; + var newHeight = (typeof size.height === 'number') ? size.height : height; + + this._updateBackgroundSpriteSize(newWidth, newHeight); + this._renderCmd.updateSize(newWidth, newHeight); + }, + + setLineHeight: function (lineHeight) { + this._renderCmd.setLineHeight(lineHeight); }, /** - * Set the font. + * Sets the font. * @param {String} fontName The font name. * @param {Number} fontSize The font size. */ setFont: function (fontName, fontSize) { - this._edFontSize = fontSize; - this._edFontName = fontName; - this._setFontToEditBox(); + this._renderCmd.setFont(fontName, fontSize); }, _setFont: function (fontStyle) { - var res = cc.LabelTTF._fontStyleRE.exec(fontStyle); - if (res) { - this._edFontSize = parseInt(res[1]); - this._edFontName = res[2]; - this._setFontToEditBox(); - } + this._renderCmd._setFont(fontStyle); + }, + + getBackgroundSprite: function() { + return this._backgroundSprite; }, /** - * set fontName + * Sets fontName * @param {String} fontName */ setFontName: function (fontName) { - this._edFontName = fontName; - this._setFontToEditBox(); + this._renderCmd.setFontName(fontName); }, /** - * set fontSize + * Sets fontSize * @param {Number} fontSize */ setFontSize: function (fontSize) { - this._edFontSize = fontSize; - this._setFontToEditBox(); - }, - - _setFontToEditBox: function () { - if (this._edTxt.value !== this._placeholderText) { - this._edTxt.style.fontFamily = this._edFontName; - this._edTxt.style.fontSize = this._edFontSize + "px"; - if (this._editBoxInputFlag === cc.EDITBOX_INPUT_FLAG_PASSWORD) - this._edTxt.type = "password"; - else - this._edTxt.type = "text"; - } + this._renderCmd.setFontSize(fontSize); }, /** - * Set the text entered in the edit box. - * @deprecated - * @param {string} text The given text. - */ - setText: function (text) { - cc.log("Please use the setString"); - this.setString(text); - }, - - /** - * Set the text entered in the edit box. + * Sets the text entered in the edit box. * @param {string} text The given text. */ setString: function (text) { - if (text != null) { - if (text === "") { - this._edTxt.value = this._placeholderText; - this._edTxt.style.color = cc.colorToHex(this._placeholderColor); - this._edTxt.type = "text"; - } else { - this._edTxt.value = text; - this._edTxt.style.color = cc.colorToHex(this._textColor); - if (this._editBoxInputFlag === cc.EDITBOX_INPUT_FLAG_PASSWORD) - this._edTxt.type = "password"; - else - this._edTxt.type = "text"; - } + if (text.length >= this._maxLength) { + text = text.slice(0, this._maxLength); } + this._text = text; + this._renderCmd.setString(text); }, /** - * Set the font color of the widget's text. + * Sets the font color of the widget's text. * @param {cc.Color} color */ setFontColor: function (color) { this._textColor = color; - if (this._edTxt.value !== this._placeholderText) { - this._edTxt.style.color = cc.colorToHex(color); - } + this._renderCmd.setFontColor(color); }, /** - *

* Sets the maximum input length of the edit box.
* Setting this value enables multiline input mode by default. - *

* @param {Number} maxLength The maximum length. */ setMaxLength: function (maxLength) { - if (!isNaN(maxLength) && maxLength > 0) { + if (!isNaN(maxLength)) { + 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; + } this._maxLength = maxLength; - this._edTxt.maxLength = maxLength; + this._renderCmd.setMaxLength(maxLength); } }, @@ -469,108 +434,79 @@ cc.EditBox = cc.ControlButton.extend({ }, /** - * Set a text in the edit box that acts as a placeholder when an edit box is empty. + * Sets a text in the edit box that acts as a placeholder when an edit box is empty. * @param {string} text The given text. */ setPlaceHolder: function (text) { - if (text != null) { - var oldPlaceholderText = this._placeholderText; + if (text !== null) { + this._renderCmd.setPlaceHolder(text); this._placeholderText = text; - if (this._edTxt.value === oldPlaceholderText) { - this._edTxt.value = text; - this._edTxt.style.color = cc.colorToHex(this._placeholderColor); - this._setPlaceholderFontToEditText(); - } } }, /** - * Set the placeholder's font. + * Sets the placeholder's font. * @param {String} fontName * @param {Number} fontSize */ setPlaceholderFont: function (fontName, fontSize) { this._placeholderFontName = fontName; this._placeholderFontSize = fontSize; - this._setPlaceholderFontToEditText(); + this._renderCmd._updateDOMPlaceholderFontStyle(); }, + _setPlaceholderFont: function (fontStyle) { var res = cc.LabelTTF._fontStyleRE.exec(fontStyle); if (res) { this._placeholderFontName = res[2]; this._placeholderFontSize = parseInt(res[1]); - this._setPlaceholderFontToEditText(); + this._renderCmd._updateDOMPlaceholderFontStyle(); } }, /** - * Set the placeholder's fontName. + * Sets the placeholder's fontName. * @param {String} fontName */ setPlaceholderFontName: function (fontName) { this._placeholderFontName = fontName; - this._setPlaceholderFontToEditText(); + this._renderCmd._updateDOMPlaceholderFontStyle(); }, /** - * Set the placeholder's fontSize. + * Sets the placeholder's fontSize. * @param {Number} fontSize */ setPlaceholderFontSize: function (fontSize) { this._placeholderFontSize = fontSize; - this._setPlaceholderFontToEditText(); - }, - - _setPlaceholderFontToEditText: function () { - if (this._edTxt.value === this._placeholderText) { - this._edTxt.style.fontFamily = this._placeholderFontName; - this._edTxt.style.fontSize = this._placeholderFontSize + "px"; - this._edTxt.type = "text"; - } + this._renderCmd._updateDOMPlaceholderFontStyle(); }, /** - * Set the font color of the placeholder text when the edit box is empty. + * Sets the font color of the placeholder text when the edit box is empty. * @param {cc.Color} color */ setPlaceholderFontColor: function (color) { this._placeholderColor = color; - if (this._edTxt.value === this._placeholderText) { - this._edTxt.style.color = cc.colorToHex(color); - } + this._renderCmd.setPlaceholderFontColor(color); }, /** - * Set the input flags that are to be applied to the edit box. + * Sets the input flags that are to be applied to the edit box. * @param {Number} inputFlag One of the EditBoxInputFlag constants. * e.g.cc.EDITBOX_INPUT_FLAG_PASSWORD */ setInputFlag: function (inputFlag) { this._editBoxInputFlag = inputFlag; - if ((this._edTxt.value !== this._placeholderText) && (inputFlag === cc.EDITBOX_INPUT_FLAG_PASSWORD)) - this._edTxt.type = "password"; - else - this._edTxt.type = "text"; + this._renderCmd.setInputFlag(inputFlag); }, /** - * Gets the input string of the edit box. - * @deprecated - * @return {string} - */ - getText: function () { - cc.log("Please use the getString"); - return this._edTxt.value; - }, - - /** - * Gets the input string of the edit box. + * Gets the input string of the edit box. * @return {string} */ getString: function () { - if(this._edTxt.value === this._placeholderText) - return ""; - return this._edTxt.value; + return this._text; }, /** @@ -579,23 +515,27 @@ cc.EditBox = cc.ControlButton.extend({ * @param {cc.Color | cc.Scale9Sprite} normal9SpriteBg */ initWithSizeAndBackgroundSprite: function (size, normal9SpriteBg) { - if (this.initWithBackgroundSprite(normal9SpriteBg)) { - this._domInputSprite.x = 3; - this._domInputSprite.y = 3; - - this.setZoomOnTouchDown(false); - this.setPreferredSize(size); - this.x = 0; - this.y = 0; - this._addTargetWithActionForControlEvent(this, this.touchDownAction, cc.CONTROL_EVENT_TOUCH_UP_INSIDE); - return true; + if(this._backgroundSprite) { + this._backgroundSprite.removeFromParent(); } - return false; + this._backgroundSprite = normal9SpriteBg; + this.setContentSize(size); + + if(this._backgroundSprite && !this._backgroundSprite.parent) { + this._backgroundSprite.setAnchorPoint(cc.p(0, 0)); + this.addChild(this._backgroundSprite); + + this._updateBackgroundSpriteSize(size.width, size.height); + } + + + this.x = 0; + this.y = 0; + return true; }, - /* override functions */ /** - * Set the delegate for edit box. + * Sets the delegate for edit box. * @param {cc.EditBoxDelegate} delegate */ setDelegate: function (delegate) { @@ -603,7 +543,7 @@ cc.EditBox = cc.ControlButton.extend({ }, /** - * Get a text in the edit box that acts as a placeholder when an + * Gets the text in the edit box that acts as a placeholder when an * edit box is empty. * @return {String} */ @@ -612,51 +552,30 @@ cc.EditBox = cc.ControlButton.extend({ }, /** - * Set the input mode of the edit box. + * Sets the input mode of the edit box. * @param {Number} inputMode One of the EditBoxInputMode constants. */ setInputMode: function (inputMode) { + if (this._editBoxInputMode === inputMode) return; + + var oldText = this.getString(); this._editBoxInputMode = inputMode; + + this._renderCmd.setInputMode(inputMode); + this._renderCmd.transform(); + + this.setString(oldText); + this._renderCmd._updateLabelPosition(this.getContentSize()); }, /** - * Set the return type that are to be applied to the edit box. + * Sets the return type that are to be applied to the edit box. * @param {Number} returnType One of the CCKeyboardReturnType constants. */ setReturnType: function (returnType) { this._keyboardReturnType = returnType; }, - keyboardWillShow: function (info) { - var rectTracked = cc.EditBox.getRect(this); - // some adjustment for margin between the keyboard and the edit box. - rectTracked.y -= 4; - // if the keyboard area doesn't intersect with the tracking node area, nothing needs to be done. - if (!rectTracked.intersectsRect(info.end)) { - cc.log("needn't to adjust view layout."); - return; - } - - // assume keyboard at the bottom of screen, calculate the vertical adjustment. - this._adjustHeight = info.end.getMaxY() - rectTracked.getMinY(); - // CCLOG("CCEditBox:needAdjustVerticalPosition(%f)", m_fAdjustHeight); - - //callback - }, - keyboardDidShow: function (info) { - }, - keyboardWillHide: function (info) { - //if (m_pEditBoxImpl != NULL) { - // m_pEditBoxImpl->doAnimationWhenKeyboardMove(info.duration, -m_fAdjustHeight); - //} - }, - keyboardDidHide: function (info) { - }, - - touchDownAction: function (sender, controlEvent) { - //this._editBoxImpl.openKeyboard(); - }, - /** * @warning HTML5 Only * @param {cc.Size} size @@ -664,20 +583,10 @@ cc.EditBox = cc.ControlButton.extend({ */ initWithBackgroundColor: function (size, bgColor) { this._edWidth = size.width; - this.dom.style.width = this._edWidth.toString() + "px"; + this.dom.style.width = this._edWidth.toString() + 'px'; this._edHeight = size.height; - this.dom.style.height = this._edHeight.toString() + "px"; + this.dom.style.height = this._edHeight.toString() + 'px'; this.dom.style.backgroundColor = cc.colorToHex(bgColor); - }, - - cleanup : function () { - this._edTxt.removeEventListener("input", this._inputEvent); - this._edTxt.removeEventListener("keypress", this._keyPressEvent); - this._edTxt.removeEventListener("focus", this._focusEvent); - this._edTxt.removeEventListener("blur", this._blurEvent); - cc._canvas.removeEventListener('click', this._onCanvasClick); - - this._super(); } }); @@ -686,64 +595,52 @@ var _p = cc.EditBox.prototype; // Extended properties /** @expose */ _p.font; -cc.defineGetterSetter(_p, "font", null, _p._setFont); +cc.defineGetterSetter(_p, 'font', null, _p._setFont); /** @expose */ _p.fontName; -cc.defineGetterSetter(_p, "fontName", null, _p.setFontName); +cc.defineGetterSetter(_p, 'fontName', null, _p.setFontName); /** @expose */ _p.fontSize; -cc.defineGetterSetter(_p, "fontSize", null, _p.setFontSize); +cc.defineGetterSetter(_p, 'fontSize', null, _p.setFontSize); /** @expose */ _p.fontColor; -cc.defineGetterSetter(_p, "fontColor", null, _p.setFontColor); +cc.defineGetterSetter(_p, 'fontColor', null, _p.setFontColor); /** @expose */ _p.string; -cc.defineGetterSetter(_p, "string", _p.getString, _p.setString); +cc.defineGetterSetter(_p, 'string', _p.getString, _p.setString); /** @expose */ _p.maxLength; -cc.defineGetterSetter(_p, "maxLength", _p.getMaxLength, _p.setMaxLength); +cc.defineGetterSetter(_p, 'maxLength', _p.getMaxLength, _p.setMaxLength); /** @expose */ _p.placeHolder; -cc.defineGetterSetter(_p, "placeHolder", _p.getPlaceHolder, _p.setPlaceHolder); +cc.defineGetterSetter(_p, 'placeholder', _p.getPlaceHolder, _p.setPlaceHolder); /** @expose */ _p.placeHolderFont; -cc.defineGetterSetter(_p, "placeHolderFont", null, _p._setPlaceholderFont); +cc.defineGetterSetter(_p, 'placeholderFont', null, _p._setPlaceholderFont); /** @expose */ _p.placeHolderFontName; -cc.defineGetterSetter(_p, "placeHolderFontName", null, _p.setPlaceholderFontName); +cc.defineGetterSetter(_p, 'placeholderFontName', null, _p.setPlaceholderFontName); /** @expose */ _p.placeHolderFontSize; -cc.defineGetterSetter(_p, "placeHolderFontSize", null, _p.setPlaceholderFontSize); +cc.defineGetterSetter(_p, 'placeholderFontSize', null, _p.setPlaceholderFontSize); /** @expose */ _p.placeHolderFontColor; -cc.defineGetterSetter(_p, "placeHolderFontColor", null, _p.setPlaceholderFontColor); +cc.defineGetterSetter(_p, 'placeholderFontColor', null, _p.setPlaceholderFontColor); /** @expose */ _p.inputFlag; -cc.defineGetterSetter(_p, "inputFlag", null, _p.setInputFlag); +cc.defineGetterSetter(_p, 'inputFlag', null, _p.setInputFlag); /** @expose */ _p.delegate; -cc.defineGetterSetter(_p, "delegate", null, _p.setDelegate); +cc.defineGetterSetter(_p, 'delegate', null, _p.setDelegate); /** @expose */ _p.inputMode; -cc.defineGetterSetter(_p, "inputMode", null, _p.setInputMode); +cc.defineGetterSetter(_p, 'inputMode', null, _p.setInputMode); /** @expose */ _p.returnType; -cc.defineGetterSetter(_p, "returnType", null, _p.setReturnType); +cc.defineGetterSetter(_p, 'returnType', null, _p.setReturnType); _p = null; -/** - * get the rect of a node in world coordinate frame - * @function - * @param {cc.Node} node - * @return {cc.Rect} - */ -cc.EditBox.getRect = function (node) { - var contentSize = node.getContentSize(); - var rect = cc.rect(0, 0, contentSize.width, contentSize.height); - return cc.rectApplyAffineTransform(rect, node.getNodeToWorldTransform()); -}; - /** * create a edit box with size and background-color or * @deprecated since v3.0, please use new cc.EditBox(size, normal9SpriteBg, press9SpriteBg, disabled9SpriteBg) instead @@ -758,5 +655,721 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp }; +(function (editbox) { + editbox._polyfill = { + zoomInvalid: false + }; + + if (cc.sys.OS_ANDROID === cc.sys.os + && (cc.sys.browserType === cc.sys.BROWSER_TYPE_SOUGOU + || cc.sys.browserType === cc.sys.BROWSER_TYPE_360)) { + editbox._polyfill.zoomInvalid = true; + } +})(cc.EditBox); + +(function (polyfill) { + // https://segmentfault.com/q/1010000002914610 + var SCROLLY = 40; + var TIMER_NAME = 400; + var LEFT_PADDING = 2; + + 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; + } + 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); + } + } + + function capitalize (string) { + return string.replace(/(?:^|\s)\S/g, function(a) { return a.toUpperCase(); }); + } + + function capitalizeFirstLetter (string) { + return string.charAt(0).toUpperCase() + string.slice(1); + } + + var EditBoxImpl = function () { + }; + var proto = EditBoxImpl.prototype = Object.create(Object.prototype); + + proto.updateMatrix = function () { + if (!this._edTxt) return; + + var node = this._node, scaleX = cc.view._scaleX, scaleY = cc.view._scaleY; + var dpr = cc.view._devicePixelRatio; + var t = this._worldTransform; + + scaleX /= dpr; + scaleY /= dpr; + + 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 offsetY = container && container.style.paddingBottom && parseInt(container.style.paddingBottom); + var tx = t.tx * scaleX + offsetX, ty = t.ty * scaleY + offsetY; + + if (polyfill.zoomInvalid) { + this.updateSize(node._contentSize.width * a, node._contentSize.height * d); + a = 1; + d = 1; + } + + var matrix = "matrix(" + a + "," + -b + "," + -c + "," + d + "," + tx + "," + -ty + ")"; + this._edTxt.style['transform'] = matrix; + this._edTxt.style['-webkit-transform'] = matrix; + this._edTxt.style['transform-origin'] = '0px 100% 0px'; + this._edTxt.style['-webkit-transform-origin'] = '0px 100% 0px'; + }; + + proto.updateVisibility = function () { + if (!this._edTxt) return; + + var node = this._node; + var editBox = this._edTxt; + if (node.visible) { + editBox.style.visibility = 'visible'; + cc.game.container.appendChild(editBox); + } else { + editBox.style.visibility = 'hidden'; + var hasChild = false; + if('contains' in cc.game.container) { + hasChild = cc.game.container.contains(editBox); + }else { + hasChild = cc.game.container.compareDocumentPosition(editBox) % 16; + } + if(hasChild) + cc.game.container.removeChild(editBox); + } + }; + + proto.stayOnTop = function (flag) { + if(flag) { + this._removeLabels(); + this._edTxt.style.display = ''; + } else { + this._createLabels(); + this._edTxt.style.display = 'none'; + this._updateLabelString(); + } + }; + + proto._createDomInput = function () { + this._removeDomInputControl(); + var thisPointer = this; + var tmpEdTxt = this._edTxt = document.createElement('input'); + tmpEdTxt.type = 'text'; + tmpEdTxt.style.fontSize = this._edFontSize + 'px'; + tmpEdTxt.style.color = '#000000'; + tmpEdTxt.style.border = 0; + tmpEdTxt.style.background = 'transparent'; + tmpEdTxt.style.width = '100%'; + tmpEdTxt.style.height = '100%'; + tmpEdTxt.style.active = 0; + tmpEdTxt.style.outline = 'medium'; + tmpEdTxt.style.padding = '0'; + tmpEdTxt.style.textTransform = 'uppercase'; + tmpEdTxt.style.display = 'none'; + + tmpEdTxt.style.position = "absolute"; + tmpEdTxt.style.bottom = "0px"; + tmpEdTxt.style.left = LEFT_PADDING + "px"; + tmpEdTxt.style.className = "cocosEditBox"; + this.setMaxLength(thisPointer._editBox._maxLength); + + tmpEdTxt.addEventListener('input', function () { + var editBox = thisPointer._editBox; + + + if (this.value.length > this.maxLength) { + this.value = this.value.slice(0, this.maxLength); + } + + if (editBox._delegate && editBox._delegate.editBoxTextChanged) { + if (editBox._text.toLowerCase() !== this.value.toLowerCase()) { + editBox._text = this.value; + thisPointer._updateEditBoxContentStyle(); + editBox._delegate.editBoxTextChanged(editBox, editBox._text); + } + } + }); + tmpEdTxt.addEventListener('keypress', function (e) { + var editBox = thisPointer._editBox; + + if (e.keyCode === cc.KEY.enter) { + e.stopPropagation(); + e.preventDefault(); + if(this.value === '') { + this.style.fontSize = editBox._placeholderFontSize + 'px'; + this.style.color = cc.colorToHex(editBox._placeholderColor); + } + + editBox._text = this.value; + thisPointer._updateEditBoxContentStyle(); + thisPointer.hidden(); + if (editBox._delegate && editBox._delegate.editBoxEditingReturn) { + editBox._delegate.editBoxEditingReturn(editBox); + } + cc._canvas.focus(); + } + }); + + tmpEdTxt.addEventListener('focus', function () { + var editBox = thisPointer._editBox; + this.style.fontSize = thisPointer._edFontSize + 'px'; + this.style.color = cc.colorToHex(editBox._textColor); + thisPointer._hiddenLabels(); + + if(cc.view.isAutoFullScreenEnabled()) { + thisPointer.__fullscreen = true; + cc.view.enableAutoFullScreen(false); + cc.screen.exitFullScreen(); + } else { + thisPointer.__fullscreen = false; + } + this.__autoResize = cc.view.__resizeWithBrowserSize; + cc.view.resizeWithBrowserSize(false); + + scrollWindowUp(editBox); + + if (editBox._delegate && editBox._delegate.editBoxEditingDidBegan) { + editBox._delegate.editBoxEditingDidBegan(editBox); + } + }); + tmpEdTxt.addEventListener('blur', function () { + var editBox = thisPointer._editBox; + editBox._text = this.value; + thisPointer._updateEditBoxContentStyle(); + if(thisPointer.__fullscreen) { + cc.view.enableAutoFullScreen(true); + } + if (this.__autoResize) { + cc.view.resizeWithBrowserSize(true); + } + window.scrollY = 0; + if (editBox._delegate && editBox._delegate.editBoxEditingDidEnded) { + editBox._delegate.editBoxEditingDidEnded(editBox); + } + + if (this.value === '') { + this.style.fontSize = editBox._placeholderFontSize + 'px'; + this.style.color = cc.colorToHex(editBox._placeholderColor); + } + thisPointer.hidden(); + }); + return tmpEdTxt; + }; + + proto._createDomTextArea = function () { + this._removeDomInputControl(); + var thisPointer = this; + var tmpEdTxt = this._edTxt = document.createElement('textarea'); + tmpEdTxt.type = 'text'; + tmpEdTxt.style.fontSize = this._edFontSize + 'px'; + tmpEdTxt.style.color = '#000000'; + tmpEdTxt.style.border = 0; + tmpEdTxt.style.background = 'transparent'; + tmpEdTxt.style.width = '100%'; + tmpEdTxt.style.height = '100%'; + tmpEdTxt.style.active = 0; + tmpEdTxt.style.outline = 'medium'; + tmpEdTxt.style.padding = '0'; + tmpEdTxt.style.resize = 'none'; + tmpEdTxt.style.textTransform = 'uppercase'; + tmpEdTxt.style.overflow_y = 'scroll'; + tmpEdTxt.style.display = 'none'; + tmpEdTxt.style.position = "absolute"; + tmpEdTxt.style.bottom = "0px"; + tmpEdTxt.style.left = LEFT_PADDING + "px"; + tmpEdTxt.style.className = "cocosEditBox"; + this.setMaxLength(thisPointer._editBox._maxLength); + + tmpEdTxt.addEventListener('input', function () { + if (this.value.length > this.maxLength) { + this.value = this.value.slice(0, this.maxLength); + } + + var editBox = thisPointer._editBox; + if (editBox._delegate && editBox._delegate.editBoxTextChanged) { + if(editBox._text.toLowerCase() !== this.value.toLowerCase()) { + editBox._text = this.value; + thisPointer._updateEditBoxContentStyle(); + editBox._delegate.editBoxTextChanged(editBox, editBox._text); + } + } + }); + + tmpEdTxt.addEventListener('focus', function () { + var editBox = thisPointer._editBox; + thisPointer._hiddenLabels(); + + this.style.fontSize = thisPointer._edFontSize + 'px'; + this.style.color = cc.colorToHex(editBox._textColor); + if(cc.view.isAutoFullScreenEnabled()) { + thisPointer.__fullscreen = true; + cc.view.enableAutoFullScreen(false); + cc.screen.exitFullScreen(); + } else { + thisPointer.__fullscreen = false; + } + + scrollWindowUp(editBox); + + if (editBox._delegate && editBox._delegate.editBoxEditingDidBegan) { + editBox._delegate.editBoxEditingDidBegan(editBox); + } + + }); + tmpEdTxt.addEventListener('keypress', function (e) { + var editBox = thisPointer._editBox; + + if (e.keyCode === cc.KEY.enter) { + e.stopPropagation(); + + if (editBox._delegate && editBox._delegate.editBoxEditingReturn) { + editBox._delegate.editBoxEditingReturn(editBox); + } + } + }); + tmpEdTxt.addEventListener('blur', function () { + var editBox = thisPointer._editBox; + editBox._text = this.value; + thisPointer._updateEditBoxContentStyle(); + window.scrollY = 0; + if(thisPointer.__fullscreen) { + cc.view.enableAutoFullScreen(true); + } + + if (editBox._delegate && editBox._delegate.editBoxEditingDidEnded) { + editBox._delegate.editBoxEditingDidEnded(editBox); + } + + if (this.value === '') { + this.style.fontSize = editBox._placeholderFontSize + 'px'; + this.style.color = cc.colorToHex(editBox._placeholderColor); + } + + thisPointer.hidden(); + }); + + return tmpEdTxt; + }; + + proto._createLabels = function () { + var editBoxSize = this._editBox.getContentSize(); + 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) { + this._placeholderLabel = new cc.LabelTTF(); + this._placeholderLabel.setAnchorPoint(cc.p(0, 1)); + this._placeholderLabel.setColor(cc.color.GRAY); + this._editBox.addChild(this._placeholderLabel, 100); + } + + this._updateLabelPosition(editBoxSize); + }; + + proto._removeLabels = function () { + if(!this._textLabel) return; + + this._editBox.removeChild(this._textLabel); + this._textLabel = null; + }; + + proto._updateLabelPosition = function (editBoxSize) { + if(!this._textLabel || !this._placeholderLabel) return; + + var labelContentSize = cc.size(editBoxSize.width - LEFT_PADDING, editBoxSize.height); + this._textLabel.setContentSize(labelContentSize); + this._textLabel.setDimensions(labelContentSize); + this._placeholderLabel.setLineHeight(editBoxSize.height); + var placeholderLabelSize = this._placeholderLabel.getContentSize(); + + 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); + this._textLabel.setVerticalAlignment(cc.VERTICAL_TEXT_ALIGNMENT_TOP); + // this._textLabel.enableWrapText(true); + } + else { + // this._textLabel.enableWrapText(false); + this._textLabel.setPosition(LEFT_PADDING, editBoxSize.height); + this._placeholderLabel.setPosition(LEFT_PADDING, (editBoxSize.height + placeholderLabelSize.height) / 2); + this._placeholderLabel.setVerticalAlignment(cc.VERTICAL_TEXT_ALIGNMENT_CENTER); + this._textLabel.setVerticalAlignment(cc.VERTICAL_TEXT_ALIGNMENT_CENTER); + } + + }; + + proto.setLineHeight = function (lineHeight) { + if(this._textLabel) { + this._textLabel.setLineHeight(lineHeight); + } + }; + + proto._hiddenLabels = function () { + if(this._textLabel) { + this._textLabel.setVisible(false); + } + + if(this._placeholderLabel) { + this._placeholderLabel.setVisible(false); + } + }; + + 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(); + } + else if (inputFlag === cc.EDITBOX_INPUT_FLAG_INITIAL_CAPS_WORD) { + this._editBox._text = capitalize(this._editBox._text); + } + else if (inputFlag === cc.EDITBOX_INPUT_FLAG_INITIAL_CAPS_SENTENCE) { + this._editBox._text = capitalizeFirstLetter(this._editBox._text); + } + }; + + proto._updateLabelString = function() { + this._updateInputType(); + + if(this._textLabel) { + this._textLabel.setVisible(true); + this._textLabel.setString(this._editBox._text); + } + + if (this._edTxt.type === 'password') { + var passwordString = ''; + var len = this._editBox._text.length; + for (var i = 0; i < len; ++i) { + passwordString += '\u25CF'; + } + if(this._textLabel) { + this._textLabel.setString(passwordString); + } + } else { + this._updateEditBoxContentStyle(); + if(this._textLabel) { + this._textLabel.setString(this._editBox._text); + } + } + }; + + proto._showLabels = function () { + this._hiddenLabels(); + if (this._edTxt.value === '') { + if(this._placeholderLabel) { + this._placeholderLabel.setVisible(true); + this._placeholderLabel.setString(this._editBox._placeholderText); + } + } + else { + this._updateLabelString(); + } + }; + + proto.show = function() { + if(!this._editBox._alwaysOnTop) { + if (this._edTxt.style.display === 'none') { + this._edTxt.style.display = ''; + this._edTxt.focus(); + } + } + this._hiddenLabels(); + }; + + proto.hidden = function() { + if(!this._editBox._alwaysOnTop) { + this._edTxt.style.display = 'none'; + } + this._showLabels(); + }; + + proto._setFont = function (fontStyle) { + var res = cc.LabelTTF._fontStyleRE.exec(fontStyle); + var textFontName = res[2]; + var textFontSize = parseInt(res[1]); + if (res) { + this.setFont(textFontName, textFontSize); + } + }; + + proto.setFont = function (fontName, fontSize) { + this._edFontName = fontName || this._edFontName; + this._edFontSize = fontSize || this._edFontSize; + this._updateDOMFontStyle(); + }; + + proto.setFontName = function (fontName) { + this._edFontName = fontName || this._edFontName; + this._updateDOMFontStyle(); + }; + + proto.setFontSize = function (fontSize) { + this._edFontSize = fontSize || this._edFontSize; + this._updateDOMFontStyle(); + }; + + proto.setFontColor = function (color) { + if(!this._edTxt) return; + + if (this._edTxt.value !== this._editBox._placeholderText) { + this._edTxt.style.color = cc.colorToHex(color); + } + if(this._textLabel) { + this._textLabel.setColor(color); + } + }; + + proto.setPlaceHolder = function (text) { + this._placeholderLabel.setString(text); + }; + + proto.setMaxLength = function (maxLength) { + if(!this._edTxt) return; + this._edTxt.maxLength = maxLength; + }; + + proto._updateDOMPlaceholderFontStyle = function () { + this._placeholderLabel.setFontName(this._editBox._placeholderFontName); + this._placeholderLabel.setFontSize(this._editBox._placeholderFontSize); + }; + + proto.setPlaceholderFontColor = function (color) { + this._placeholderLabel.setColor(color); + }; + + proto._updateInputType = function () { + if(this._editBox._keyboardReturnType === cc.KEYBOARD_RETURNTYPE_SEARCH) { + this._edTxt.type = 'search'; + } + + var inputMode = this._editBox._editBoxInputMode; + 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) { + this._edTxt.type = 'number'; + } 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) { + this._edTxt.type = 'url'; + } else { + this._edTxt.type = 'text'; + } + + + if (this._editBox._editBoxInputFlag === cc.EDITBOX_INPUT_FLAG_PASSWORD) { + this._edTxt.type = 'password'; + } + }; + + proto.setInputFlag = function (inputFlag) { + if(!this._edTxt) return; + + this._updateInputType(); + + this._edTxt.style.textTransform = 'none'; + + if (inputFlag === cc.EDITBOX_INPUT_FLAG_INITIAL_CAPS_ALL_CHARACTERS) { + this._edTxt.style.textTransform = 'uppercase'; + } + else if (inputFlag === cc.EDITBOX_INPUT_FLAG_INITIAL_CAPS_WORD) { + this._edTxt.style.textTransform = 'capitalize'; + } + this._updateLabelString(); + }; + + proto.setInputMode = function (inputMode) { + this._removeDomInputControl(); + if (inputMode === cc.EDITBOX_INPUT_MODE_ANY) { + this._createDomTextArea(); + } + else { + this._createDomInput(); + } + this._addDomInputControl(); + + this._updateInputType(); + var contentSize = this._node.getContentSize(); + this.updateSize(contentSize.width, contentSize.height); + }; + + proto.setString = function (text) { + if(!this._edTxt) return; + + if (text !== null) { + this._edTxt.value = text; + + if (text === '') { + if(this._placeholderLabel) { + this._placeholderLabel.setString(this._editBox._placeholderText); + this._placeholderLabel.setColor(this._editBox._placeholderColor); + this._placeholderLabel.setVisible(true); + } + + if(this._textLabel) { + this._textLabel.setVisible(false); + } + } + else { + this._edTxt.style.color = cc.colorToHex(this._editBox._textColor); + if(this._textLabel) { + this._textLabel.setColor(this._editBox._textColor); + } + if(this._placeholderLabel) { + this._placeholderLabel.setVisible(false); + } + + this._updateLabelString(); + } + } + }; + + proto._updateDOMFontStyle = function() { + if(!this._edTxt) return; + + if (this._edTxt.value !== '') { + this._edTxt.style.fontFamily = this._edFontName; + this._edTxt.style.fontSize = this._edFontSize + 'px'; + } + if(this._textLabel) { + this._textLabel.setFontSize(this._edFontSize); + this._textLabel.setFontName(this._edFontName); + } + }; + + + proto.updateSize = function(newWidth, newHeight) { + var editboxDomNode = this._edTxt; + if (!editboxDomNode) return; + + editboxDomNode.style['width'] = newWidth + 'px'; + editboxDomNode.style['height'] = newHeight + 'px'; + + this._updateLabelPosition(cc.size(newWidth, newHeight)); + }; + + proto.createNativeControl = function() { + this._createDomTextArea(); + this._addDomInputControl(); + }; + + proto._addDomInputControl = function () { + cc.game.container.appendChild(this._edTxt); + }; + + proto._removeDomInputControl = function () { + var editBox = this._edTxt; + if(editBox){ + var hasChild = false; + if('contains' in cc.game.container) { + hasChild = cc.game.container.contains(editBox); + }else { + hasChild = cc.game.container.compareDocumentPosition(editBox) % 16; + } + if(hasChild) + cc.game.container.removeChild(editBox); + } + this._edTxt = null; + }; + + proto.initializeRenderCmd = function (node) { + this._editBox = node; + + //it's a dom node, may be assigned with Input or TextArea. + this._edFontSize = 14; + this._edFontName = 'Arial'; + this._textLabel = null; + this._placeholderLabel = null; + }; + + //define the canvas render command + cc.EditBox.CanvasRenderCmd = function (node) { + cc.Node.CanvasRenderCmd.call(this, node); + this.initializeRenderCmd(node); + }; + + var canvasRenderCmdProto = cc.EditBox.CanvasRenderCmd.prototype = Object.create(cc.Node.CanvasRenderCmd.prototype); + + function _getPropertyDescriptor (obj, name) { + var pd = Object.getOwnPropertyDescriptor(obj, name); + if (pd) { + return pd; + } + var p = Object.getPrototypeOf(obj); + if (p) { + return _getPropertyDescriptor(p, name); + } + else { + return null; + } + } + + function _copyprop(name, source, target) { + var pd = _getPropertyDescriptor(source, name); + Object.defineProperty(target, name, pd); + } + + var _mixin = function (obj) { + obj = obj || {}; + for (var i = 1, length = arguments.length; i < length; i++) { + var source = arguments[i]; + if (source) { + if (typeof source !== 'object') { + cc.error('cc.js.mixin: arguments must be type object:', source); + continue; + } + for ( var name in source) { + _copyprop( name, source, obj); + } + } + } + return obj; + }; + + _mixin(canvasRenderCmdProto, proto); + canvasRenderCmdProto.constructor = cc.EditBox.CanvasRenderCmd; + + canvasRenderCmdProto.transform = function (parentCmd, recursive) { + this.originTransform(parentCmd, recursive); + this.updateMatrix(); + }; + + + //define the webgl render command + cc.EditBox.WebGLRenderCmd = function (node) { + cc.Node.WebGLRenderCmd.call(this, node); + this.initializeRenderCmd(node); + }; + + var webGLRenderCmdProto = cc.EditBox.WebGLRenderCmd.prototype = Object.create(cc.Node.WebGLRenderCmd.prototype); + _mixin(webGLRenderCmdProto, proto); + webGLRenderCmdProto.constructor = cc.EditBox.WebGLRenderCmd; + webGLRenderCmdProto.transform = function (parentCmd, recursive) { + this.originTransform(parentCmd, recursive); + this.updateMatrix(); + }; +}(cc.EditBox._polyfill)); diff --git a/extensions/editbox/CCdomNode.js b/extensions/editbox/CCdomNode.js deleted file mode 100644 index 5074596750..0000000000 --- a/extensions/editbox/CCdomNode.js +++ /dev/null @@ -1,659 +0,0 @@ -/**************************************************************************** - 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. - ****************************************************************************/ -/** - * the DOM object - * @namespace - * @name cc.DOM - */ -cc.DOM = {}; - -/** - * @function - * @private - * @param node - */ -cc.DOM._addMethods = function (node) { - for (var funcs in cc.DOM.methods) { - node[funcs] = cc.DOM.methods[funcs]; - } - - // Redefine getter setter - cc.defineGetterSetter(node, "x", node.getPositionX, node.setPositionX); - cc.defineGetterSetter(node, "y", node.getPositionY, node.setPositionY); - cc.defineGetterSetter(node, "width", node._getWidth, node._setWidth); - cc.defineGetterSetter(node, "height", node._getHeight, node._setHeight); - cc.defineGetterSetter(node, "anchorX", node._getAnchorX, node._setAnchorX); - cc.defineGetterSetter(node, "anchorY", node._getAnchorY, node._setAnchorY); - cc.defineGetterSetter(node, "scale", node.getScale, node.setScale); - cc.defineGetterSetter(node, "scaleX", node.getScaleX, node.setScaleX); - cc.defineGetterSetter(node, "scaleY", node.getScaleY, node.setScaleY); - cc.defineGetterSetter(node, "rotation", node.getRotation, node.setRotation); - cc.defineGetterSetter(node, "skewX", node.getSkewX, node.setSkewX); - cc.defineGetterSetter(node, "skewY", node.getSkewY, node.setSkewY); - cc.defineGetterSetter(node, "visible", node.isVisible, node.setVisible); - cc.defineGetterSetter(node, "parent", node.getParent, node.setParent); - cc.defineGetterSetter(node, "opacity", node.getOpacity, node.setOpacity); -}; -cc.DOM.methods = /** @lends cc.DOM# */{ - /** - * Replace the set position of ccNode - * @param {cc.Point|Number} x - * @param {Number} y - */ - setPosition:function (x, y) { - if (y === undefined) { - this._position.x = x.x; - this._position.y = x.y; - } else { - this._position.x = x; - this._position.y = y; - } - this.setNodeDirty(); - this.dom.translates(this._position.x, -this._position.y); - }, - /** - * replace set Position Y of ccNode - * @param {Number} y - */ - setPositionY:function (y) { - this._position.y = y; - this.setNodeDirty(); - this.dom.translates(this._position.x, -this._position.y); - }, - - /** - * replace set Position X of ccNode - * @param {Number} x - */ - setPositionX:function (x) { - this._position.x = x; - this.setNodeDirty(); - this.dom.translates(this._position.x, -this._position.y); - }, - - /** - * replace set Scale of ccNode - * @param {object|Number} scale - * @param {Number} scaleY - */ - setScale:function (scale, scaleY) { - //save dirty region when before change - //this._addDirtyRegionToDirector(this.getBoundingBoxToWorld()); - - this._scaleX = scale; - this._scaleY = scaleY || scale; - - //save dirty region when after changed - //this._addDirtyRegionToDirector(this.getBoundingBoxToWorld()); - this.setNodeDirty(); - this.dom.resize(this._scaleX, this._scaleY); - }, - - /** - * replace set Scale X of ccNode - * @param {Number} x - */ - setScaleX:function (x) { - this._scaleX = x; - this.setNodeDirty(); - this.dom.resize(this._scaleX, this._scaleY); - }, - - /** - * replace set Scale Y of ccNode - * @param {Number} y - */ - setScaleY:function (y) { - this._scaleY = y; - this.setNodeDirty(); - this.dom.resize(this._scaleX, this._scaleY); - }, - - /** - * replace set anchorpoint of ccNode - * @param {cc.Point|Number} point The anchor point of node or The anchor point.x of node. - * @param {Number} [y] The anchor point.y of node. - */ - setAnchorPoint:function (point, y) { - var cmd = this._renderCmd; - - var locAnchorPoint = this._anchorPoint; - if (y === undefined) { - locAnchorPoint.x = point.x; - locAnchorPoint.y = point.y; - } else { - locAnchorPoint.x = point; - locAnchorPoint.y = y; - } - var locAPP = cmd._anchorPointInPoints, locSize = this._contentSize; - locAPP.x = locSize.width * locAnchorPoint.x; - locAPP.y = locSize.height * locAnchorPoint.y; - - this.dom.style[cc.$.pfx + 'TransformOrigin'] = '' + locAPP.x + 'px ' + -locAPP.y + 'px'; - if (this.ignoreAnchor) { - this.dom.style.marginLeft = 0; - this.dom.style.marginBottom = 0; - } else { - this.dom.style.marginLeft = (this.isToggler) ? 0 : -locAPP.x + 'px'; - this.dom.style.marginBottom = -locAPP.y + 'px'; - } - this.setNodeDirty(); - }, - - /** - * replace set anchorpoint x of ccNode - * @param {Number} x The anchor x of node. - */ - _setAnchorX:function (x) { - var locAnchorPoint = this._anchorPoint; - var cmd = this._renderCmd; - - if (x === locAnchorPoint.x) - return; - locAnchorPoint.x = x; - - var locAPP = cmd._anchorPointInPoints, locSize = this._contentSize; - locAPP.x = locSize.width * locAnchorPoint.x; - - this.dom.style[cc.$.pfx + 'TransformOrigin'] = '' + locAPP.x + 'px ' + -locAPP.y + 'px'; - if (this.ignoreAnchor) { - this.dom.style.marginLeft = 0; - this.dom.style.marginBottom = 0; - } else { - this.dom.style.marginLeft = (this.isToggler) ? 0 : -locAPP.x + 'px'; - } - this.setNodeDirty(); - }, - - /** - * replace set anchorpoint y of ccNode - * @param {Number} y The anchor y of node. - */ - _setAnchorY:function (y) { - var locAnchorPoint = this._anchorPoint; - var cmd = this._renderCmd; - - if (y === locAnchorPoint.y) - return; - locAnchorPoint.y = y; - - var locAPP = cmd._anchorPointInPoints, locSize = this._contentSize; - locAPP.y = locSize.height * locAnchorPoint.y; - - this.dom.style[cc.$.pfx + 'TransformOrigin'] = '' + locAPP.x + 'px ' + -locAPP.y + 'px'; - if (this.ignoreAnchor) { - this.dom.style.marginLeft = 0; - this.dom.style.marginBottom = 0; - } else { - this.dom.style.marginBottom = -locAPP.y + 'px'; - } - this.setNodeDirty(); - }, - - /** - * replace set ContentSize of ccNode - * @param {cc.Size|Number} size The untransformed size of the node or The untransformed size's width of the node. - * @param {Number} [height] The untransformed size's height of the node. - */ - setContentSize:function (size, height) { - var cmd = this._renderCmd; - - var locContentSize = this._contentSize; - if (height === undefined) { - locContentSize.width = size.width; - locContentSize.height = size.height; - } else { - locContentSize.width = size; - locContentSize.height = height; - } - var locAPP = cmd._anchorPointInPoints, locAnchorPoint = this._anchorPoint; - locAPP.x = locContentSize.width * locAnchorPoint.x; - locAPP.y = locContentSize.height * locAnchorPoint.y; - this.dom.width = locContentSize.width; - this.dom.height = locContentSize.height; - this.setAnchorPoint(this.getAnchorPoint()); - if (this.canvas) { - this.canvas.width = locContentSize.width; - this.canvas.height = locContentSize.height; - } - this.setNodeDirty(); - this.redraw(); - }, - - /** - * replace set width of ccNode - * @param {Number} width The untransformed size's width of the node. - */ - _setWidth:function (width) { - var locContentSize = this._contentSize; - var cmd = this._renderCmd; - if (width === locContentSize.width) - return; - locContentSize.width = width; - - var locAPP = cmd._anchorPointInPoints, locAnchorPoint = this._anchorPoint; - locAPP.x = locContentSize.width * locAnchorPoint.x; - this.dom.width = locContentSize.width; - this.anchorX = locAnchorPoint.x; - if (this.canvas) { - this.canvas.width = locContentSize.width; - } - this.setNodeDirty(); - this.redraw(); - }, - - /** - * replace set height of ccNode - * @param {Number} height The untransformed size's height of the node. - */ - _setHeight:function (height) { - var locContentSize = this._contentSize; - var cmd = this._renderCmd; - if (height === locContentSize.height) - return; - locContentSize.height = height; - - var locAPP = cmd._anchorPointInPoints, locAnchorPoint = this._anchorPoint; - locAPP.y = locContentSize.height * locAnchorPoint.y; - this.dom.height = locContentSize.height; - this.anchorY = locAnchorPoint.y; - if (this.canvas) { - this.canvas.height = locContentSize.height; - } - this.setNodeDirty(); - this.redraw(); - }, - - /** - * replace set Rotation of ccNode - * @param {Number} newRotation - */ - setRotation:function (newRotation) { - if (this._rotation === newRotation) - return; - - this._rotationX = this._rotationY = newRotation; - this.setNodeDirty(); - this.dom.rotate(newRotation); - }, - - /** - * replace set SkewX of ccNode - * @param {Number} x - */ - setSkewX:function (x) { - this._skewX = x; - this.setNodeDirty(); - this.dom.setSkew(this._skewX, this._skewY); - }, - - /** - * replace set SkewY of ccNode - * @param {Number} y - */ - setSkewY:function (y) { - this._skewY = y; - this.setNodeDirty(); - this.dom.setSkew(this._skewX, this._skewY); - }, - - /** - * replace set Visible of ccNode - * @param {Boolean} x - */ - setVisible:function (x) { - this._visible = x; - this.setNodeDirty(); - if (this.dom) - this.dom.style.display = (x) ? 'block' : 'none'; - }, - _setLocalZOrder:function (z) { - this._localZOrder = z; - this.setNodeDirty(); - if (this.dom) - this.dom.zIndex = z; - }, - - /** - * replace set Parent of ccNode - * @param {cc.Node} p - */ - setParent:function (p) { - this._parent = p; - - if (p !== null) { - p.setAnchorPoint(p.getAnchorPoint()); - this.setNodeDirty(); - cc.DOM.parentDOM(this); - } - }, - - /** - * replace resume Schedule and actions of ccNode - */ - resume:function () { - this.getScheduler().resumeTarget(this); - this.getActionManager().resumeTarget(this); - cc.eventManager.resumeTarget(this); - //if dom does not have parent, but node has no parent and its running - if (this.dom && !this.dom.parentNode) { - if (!this.getParent()) { - if(this.dom.id === ""){ - cc.DOM._createEGLViewDiv(this); - }else{ - this.dom.appendTo(cc.container); - } - } else { - cc.DOM.parentDOM(this); - } - } - if (this.dom) - this.dom.style.visibility = "visible"; - }, - - /** - * replace pause Schedule and Actions of ccNode - */ - pause:function () { - this.getScheduler().pauseTarget(this); - this.getActionManager().pauseTarget(this); - cc.eventManager.pauseTarget(this); - if (this.dom) { - this.dom.style.visibility = 'hidden'; - } - }, - - /** - * replace clean up of ccNode - */ - cleanup:function () { - // actions - this.stopAllActions(); - this.unscheduleAllCallbacks(); - - cc.eventManager.removeListeners(this); - - // timers - this._arrayMakeObjectsPerformSelector(this._children, cc.Node._stateCallbackType.cleanup); - if (this.dom) { - this.dom.remove(); - } - }, - setOpacity:function (o) { - this._opacity = o; - this.dom.style.opacity = o / 255; - }, - /** - * refresh/updates the DOM element - */ - redraw:function () { - if (this.isSprite) { - var tmp = this._children; - this._children = []; - cc.Sprite.prototype.visit.call(this, this.ctx); - this._children = tmp; - } - else { - cc.Sprite.prototype.visit.call(this, this.ctx); - } - } -}; - -cc.DOM._resetEGLViewDiv = function(){ - var div = cc.$("#EGLViewDiv"); - if(div){ - var view = cc.view; - var designSize = view.getDesignResolutionSize(); - var viewPortRect = view.getViewPortRect(); - var screenSize = view.getFrameSize(); - var pixelRatio = view.getDevicePixelRatio(); - var designSizeWidth = designSize.width, designSizeHeight = designSize.height; - var paddingLeft = parseInt(cc.container.style.paddingLeft), - paddingBottom = parseInt(cc.container.style.paddingBottom); - if((designSize.width === 0) && (designSize.height === 0)){ - designSizeWidth = screenSize.width; - designSizeHeight = screenSize.height; - } - - var viewPortWidth = viewPortRect.width/pixelRatio; - if((viewPortRect.width === 0) && (viewPortRect.height === 0)){ - viewPortWidth = screenSize.width; - } - - div.style.position = 'absolute'; - //x.dom.style.display='block'; - div.style.width = designSizeWidth + "px"; - div.style.maxHeight = designSizeHeight + "px"; - div.style.margin = 0; - - div.resize(view.getScaleX()/pixelRatio, view.getScaleY()/pixelRatio); - div.translates(paddingLeft, -paddingBottom); - if (view.getResolutionPolicy() === view._rpNoBorder) { - div.style.left = (view.getFrameSize().width - designSizeWidth)/2 + "px"; - div.style.bottom = (view.getFrameSize().height - designSizeHeight*view.getScaleY()/pixelRatio)/2 + "px"; - } - else { - div.style.left = (designSizeWidth*view.getScaleX()/pixelRatio - designSizeWidth) / 2 + "px"; - div.style.bottom = "0px"; - } - } -}; - -/** - * @function - * @private - * @param x - * @return {Boolean} - */ -cc.DOM.parentDOM = function (x) { - var p = x.getParent(); - //if has parent, parent need to have dom too - if (!p || !x.dom) - return false; - if (!p.dom) { - cc.DOM.placeHolder(p); - p.setParent = cc.DOM.methods.setParent; - } - //if parent have dom, attach self to parent - x.dom.appendTo(p.dom); - p.setAnchorPoint(p.getAnchorPoint()); - - if (p.getParent()) { - cc.DOM.parentDOM(p); - } else { - //parent has no more parent, if its running, then add it to the container - if (p.isRunning()) { - //find EGLView div - var eglViewDiv = cc.$("#EGLViewDiv"); - if (eglViewDiv) { - p.dom.appendTo(eglViewDiv); - } else { - cc.DOM._createEGLViewDiv(p); - } - } - } - return true; -}; - -cc.DOM._createEGLViewDiv = function(p){ - var div = cc.$("#EGLViewDiv"); - if(!div){ - div = cc.$new("div"); - div.id = "EGLViewDiv"; - } - - var view = cc.view; - var designSize = view.getDesignResolutionSize(); - var viewPortRect = view.getViewPortRect(); - var screenSize = view.getFrameSize(); - var pixelRatio = view.getDevicePixelRatio(); - var designSizeWidth = designSize.width, designSizeHeight = designSize.height; - var paddingLeft = parseInt(cc.container.style.paddingLeft), - paddingBottom = parseInt(cc.container.style.paddingBottom); - if ((designSize.width === 0) && (designSize.height === 0)) { - designSizeWidth = screenSize.width; - designSizeHeight = screenSize.height; - } - - var viewPortWidth = viewPortRect.width/pixelRatio; - if ((viewPortRect.width === 0) && (viewPortRect.height === 0)) { - viewPortWidth = screenSize.width; - } - - div.style.position = 'absolute'; - //x.dom.style.display='block'; - div.style.width = designSizeWidth + "px"; - div.style.maxHeight = designSizeHeight + "px"; - div.style.margin = 0; - - div.resize(view.getScaleX()/pixelRatio, view.getScaleY()/pixelRatio); - div.translates(paddingLeft, -paddingBottom); - if (view.getResolutionPolicy() === view._rpNoBorder) { - div.style.left = (screenSize.width - designSizeWidth)/2 + "px"; - div.style.bottom = (screenSize.height - designSizeHeight*view.getScaleY()/pixelRatio)/2 + "px"; - } - else { - div.style.left = (designSizeWidth*view.getScaleX()/pixelRatio - designSizeWidth) / 2 + "px"; - div.style.bottom = "0px"; - } - - p.dom.appendTo(div); - div.appendTo(cc.container); -}; - -/** - * @function - * @private - * @param x - */ -cc.DOM.setTransform = function (x) { - if (x.ctx) { - x.ctx.translate(x.getAnchorPointInPoints().x, x.getAnchorPointInPoints().y); - if (x.isSprite) { - var tmp = x._children; - x._children = []; - cc.Sprite.prototype.visit.call(x); - x._children = tmp; - } - else { - cc.Sprite.prototype.visit.call(x); - } - } - if (x.dom) { - x.dom.position.x = x.getPositionX(); - x.dom.position.y = -x.getPositionY(); - x.dom.rotation = x.getRotation(); - x.dom.scale = {x:x.getScaleX(), y:x.getScaleY()}; - x.dom.skew = {x:x.getSkewX(), y:x.getSkewY()}; - if (x.setAnchorPoint) - x.setAnchorPoint(x.getAnchorPoint()); - x.dom.transforms(); - } - -}; - -/** - * @function - * @private - * @param x - */ -cc.DOM.forSprite = function (x) { - x.dom = cc.$new('div'); - x.canvas = cc.$new('canvas'); - var locContentSize = x.getContentSize(); - x.canvas.width = locContentSize.width; - x.canvas.height = locContentSize.height; - x.dom.style.position = 'absolute'; - x.dom.style.bottom = 0; - x.ctx = x.canvas.getContext('2d'); - x.dom.appendChild(x.canvas); - if (x.getParent()) { - cc.DOM.parentDOM(x); - } - x.isSprite = true; -}; - -/** - * This creates divs for parent Nodes that are related to the current node - * @function - * @private - * @param x - */ -cc.DOM.placeHolder = function (x) { - //creating a placeholder dom to simulate other ccNode in the hierarchy - x.dom = cc.$new('div'); - x.placeholder = true; - x.dom.style.position = 'absolute'; - x.dom.style.bottom = 0; - //x.dom.style.display='block'; - x.dom.style.width = (x.getContentSize().width || cc.director.getWinSize().width) + "px"; - x.dom.style.maxHeight = (x.getContentSize().height || cc.director.getWinSize().height) + "px"; - x.dom.style.margin = 0; - cc.DOM.setTransform(x); - x.dom.transforms(); - cc.DOM._addMethods(x); - //x.dom.style.border = 'red 1px dotted'; -}; - -/** - * Converts cc.Sprite or cc.MenuItem to DOM elements
- * It currently only supports cc.Sprite and cc.MenuItem - * @function - * @param {cc.Sprite|cc.MenuItem|Array} nodeObject - * @example - * // example - * cc.DOM.convert(Sprite1, Sprite2, Menuitem); - * - * var myDOMElements = [Sprite1, Sprite2, MenuItem]; - * cc.DOM.convert(myDOMElements); - */ -cc.DOM.convert = function (nodeObject) { - //if passing by list, make it an array - if (arguments.length > 1) { - cc.DOM.convert(arguments); - return; - } else if (arguments.length === 1 && !arguments[0].length) { - cc.DOM.convert([arguments[0]]); - return; - } - var args = arguments[0]; - for (var i = 0; i < args.length; i++) { - //first check if its sprite - if (args[i] instanceof cc.Sprite) { - // create a canvas - if (!args[i].dom) - cc.DOM.forSprite(args[i]); - } else { - cc.log('DOM converter only supports sprite and menuitems yet'); - } - cc.DOM._addMethods(args[i]); - args[i].visit = function () { - }; - args[i].transform = function () { - }; - cc.DOM.setTransform(args[i]); - args[i].setVisible(args[i].isVisible()); - } -}; diff --git a/moduleConfig.json b/moduleConfig.json index bebf4f2b6c..cc5570bc42 100644 --- a/moduleConfig.json +++ b/moduleConfig.json @@ -292,7 +292,6 @@ "editbox" : [ "core", "gui", - "extensions/editbox/CCdomNode.js", "extensions/editbox/CCEditBox.js" ], "ccpool" : [ From 6d965db866f659e8769c125948ea8c2fb9983b1d Mon Sep 17 00:00:00 2001 From: pandamicro Date: Thu, 3 Nov 2016 17:09:07 +0800 Subject: [PATCH 014/206] Remove overwrite in webgl context object --- cocos2d/core/CCDrawingPrimitivesWebGL.js | 18 +- cocos2d/core/layers/CCLayerWebGLRenderCmd.js | 12 +- cocos2d/core/renderer/GlobalVertexBuffer.js | 4 +- cocos2d/core/renderer/RendererWebGL.js | 6 +- cocos2d/core/textures/CCTextureAtlas.js | 4 +- cocos2d/core/textures/TexturesWebGL.js | 10 +- cocos2d/effects/CCGrid.js | 24 +- cocos2d/motion-streak/CCMotionStreak.js | 6 +- .../CCMotionStreakWebGLRenderCmd.js | 6 +- .../CCParticleSystemWebGLRenderCmd.js | 10 +- .../CCProgressTimerWebGLRenderCmd.js | 4 +- cocos2d/shaders/CCGLStateCache.js | 224 +++++++++--------- cocos2d/shape-nodes/CCDrawNode.js | 2 +- .../UIScrollViewWebGLRenderCmd.js | 2 +- 14 files changed, 169 insertions(+), 163 deletions(-) diff --git a/cocos2d/core/CCDrawingPrimitivesWebGL.js b/cocos2d/core/CCDrawingPrimitivesWebGL.js index f8c9b46d0d..dadf0cf759 100644 --- a/cocos2d/core/CCDrawingPrimitivesWebGL.js +++ b/cocos2d/core/CCDrawingPrimitivesWebGL.js @@ -88,7 +88,7 @@ cc.DrawingPrimitiveWebGL = cc.Class.extend(/** @lends cc.DrawingPrimitiveWebGL# this._shader.setUniformLocationWith1f(this._pointSizeLocation, this._pointSize); var pointBuffer = glContext.createBuffer(); - glContext.bindBuffer(glContext.ARRAY_BUFFER, pointBuffer); + cc.glBindBuffer(glContext.ARRAY_BUFFER, pointBuffer); glContext.bufferData(glContext.ARRAY_BUFFER, new Float32Array([point.x, point.y]), glContext.STATIC_DRAW); glContext.vertexAttribPointer(cc.VERTEX_ATTRIB_POSITION, 2, glContext.FLOAT, false, 0, 0); @@ -117,7 +117,7 @@ cc.DrawingPrimitiveWebGL = cc.Class.extend(/** @lends cc.DrawingPrimitiveWebGL# this._shader.setUniformLocationWith1f(this._pointSizeLocation, this._pointSize); var pointBuffer = glContext.createBuffer(); - glContext.bindBuffer(glContext.ARRAY_BUFFER, pointBuffer); + cc.glBindBuffer(glContext.ARRAY_BUFFER, pointBuffer); glContext.bufferData(glContext.ARRAY_BUFFER, this._pointsToTypeArray(points), glContext.STATIC_DRAW); glContext.vertexAttribPointer(cc.VERTEX_ATTRIB_POSITION, 2, glContext.FLOAT, false, 0, 0); @@ -151,7 +151,7 @@ cc.DrawingPrimitiveWebGL = cc.Class.extend(/** @lends cc.DrawingPrimitiveWebGL# this._shader.setUniformLocationWith4fv(this._colorLocation, this._colorArray); var pointBuffer = glContext.createBuffer(); - glContext.bindBuffer(glContext.ARRAY_BUFFER, pointBuffer); + cc.glBindBuffer(glContext.ARRAY_BUFFER, pointBuffer); glContext.bufferData(glContext.ARRAY_BUFFER, this._pointsToTypeArray([origin, destination]), glContext.STATIC_DRAW); glContext.vertexAttribPointer(cc.VERTEX_ATTRIB_POSITION, 2, glContext.FLOAT, false, 0, 0); @@ -206,7 +206,7 @@ cc.DrawingPrimitiveWebGL = cc.Class.extend(/** @lends cc.DrawingPrimitiveWebGL# this._shader.setUniformLocationWith4fv(this._colorLocation, this._colorArray); var pointBuffer = glContext.createBuffer(); - glContext.bindBuffer(glContext.ARRAY_BUFFER, pointBuffer); + cc.glBindBuffer(glContext.ARRAY_BUFFER, pointBuffer); glContext.bufferData(glContext.ARRAY_BUFFER, this._pointsToTypeArray(vertices), glContext.STATIC_DRAW); glContext.vertexAttribPointer(cc.VERTEX_ATTRIB_POSITION, 2, glContext.FLOAT, false, 0, 0); @@ -237,7 +237,7 @@ cc.DrawingPrimitiveWebGL = cc.Class.extend(/** @lends cc.DrawingPrimitiveWebGL# this._shader.setUniformLocationWith4fv(this._colorLocation, this._colorArray); var pointBuffer = glContext.createBuffer(); - glContext.bindBuffer(glContext.ARRAY_BUFFER, pointBuffer); + cc.glBindBuffer(glContext.ARRAY_BUFFER, pointBuffer); glContext.bufferData(glContext.ARRAY_BUFFER, this._pointsToTypeArray(poli), glContext.STATIC_DRAW); glContext.vertexAttribPointer(cc.VERTEX_ATTRIB_POSITION, 2, glContext.FLOAT, false, 0, 0); glContext.drawArrays(glContext.TRIANGLE_FAN, 0, poli.length); @@ -285,7 +285,7 @@ cc.DrawingPrimitiveWebGL = cc.Class.extend(/** @lends cc.DrawingPrimitiveWebGL# this._shader.setUniformLocationWith4fv(this._colorLocation, this._colorArray); var pointBuffer = glContext.createBuffer(); - glContext.bindBuffer(glContext.ARRAY_BUFFER, pointBuffer); + cc.glBindBuffer(glContext.ARRAY_BUFFER, pointBuffer); glContext.bufferData(glContext.ARRAY_BUFFER, vertices, glContext.STATIC_DRAW); glContext.vertexAttribPointer(cc.VERTEX_ATTRIB_POSITION, 2, glContext.FLOAT, false, 0, 0); @@ -323,7 +323,7 @@ cc.DrawingPrimitiveWebGL = cc.Class.extend(/** @lends cc.DrawingPrimitiveWebGL# this._shader.setUniformLocationWith4fv(this._colorLocation, this._colorArray); var pointBuffer = glContext.createBuffer(); - glContext.bindBuffer(glContext.ARRAY_BUFFER, pointBuffer); + cc.glBindBuffer(glContext.ARRAY_BUFFER, pointBuffer); glContext.bufferData(glContext.ARRAY_BUFFER, vertices, glContext.STATIC_DRAW); glContext.vertexAttribPointer(cc.VERTEX_ATTRIB_POSITION, 2, glContext.FLOAT, false, 0, 0); @@ -362,7 +362,7 @@ cc.DrawingPrimitiveWebGL = cc.Class.extend(/** @lends cc.DrawingPrimitiveWebGL# this._shader.setUniformLocationWith4fv(this._colorLocation, this._colorArray); var pointBuffer = glContext.createBuffer(); - glContext.bindBuffer(glContext.ARRAY_BUFFER, pointBuffer); + cc.glBindBuffer(glContext.ARRAY_BUFFER, pointBuffer); glContext.bufferData(glContext.ARRAY_BUFFER, vertices, glContext.STATIC_DRAW); glContext.vertexAttribPointer(cc.VERTEX_ATTRIB_POSITION, 2, glContext.FLOAT, false, 0, 0); glContext.drawArrays(glContext.LINE_STRIP, 0, segments + 1); @@ -422,7 +422,7 @@ cc.DrawingPrimitiveWebGL = cc.Class.extend(/** @lends cc.DrawingPrimitiveWebGL# this._shader.setUniformLocationWith4fv(this._colorLocation, this._colorArray); var pointBuffer = glContext.createBuffer(); - glContext.bindBuffer(glContext.ARRAY_BUFFER, pointBuffer); + cc.glBindBuffer(glContext.ARRAY_BUFFER, pointBuffer); glContext.bufferData(glContext.ARRAY_BUFFER, vertices, glContext.STATIC_DRAW); glContext.vertexAttribPointer(cc.VERTEX_ATTRIB_POSITION, 2, glContext.FLOAT, false, 0, 0); glContext.drawArrays(glContext.LINE_STRIP, 0, segments + 1); diff --git a/cocos2d/core/layers/CCLayerWebGLRenderCmd.js b/cocos2d/core/layers/CCLayerWebGLRenderCmd.js index 8051a50abe..f39a4814b7 100644 --- a/cocos2d/core/layers/CCLayerWebGLRenderCmd.js +++ b/cocos2d/core/layers/CCLayerWebGLRenderCmd.js @@ -101,10 +101,10 @@ // // Attributes // - context.bindBuffer(context.ARRAY_BUFFER, this._verticesFloat32Buffer); + cc.glBindBuffer(context.ARRAY_BUFFER, this._verticesFloat32Buffer); context.vertexAttribPointer(cc.VERTEX_ATTRIB_POSITION, 3, context.FLOAT, false, 0, 0); - context.bindBuffer(context.ARRAY_BUFFER, this._colorsUint8Buffer); + cc.glBindBuffer(context.ARRAY_BUFFER, this._colorsUint8Buffer); context.vertexAttribPointer(cc.VERTEX_ATTRIB_COLOR, 4, context.UNSIGNED_BYTE, true, 0, 0); context.drawArrays(context.TRIANGLE_STRIP, 0, this._squareVertices.length); @@ -144,13 +144,13 @@ proto._bindLayerVerticesBufferData = function(){ var glContext = cc._renderContext; - glContext.bindBuffer(glContext.ARRAY_BUFFER, this._verticesFloat32Buffer); + cc.glBindBuffer(glContext.ARRAY_BUFFER, this._verticesFloat32Buffer); glContext.bufferData(glContext.ARRAY_BUFFER, this._squareVerticesAB, glContext.DYNAMIC_DRAW); }; proto._bindLayerColorsBufferData = function(){ var glContext = cc._renderContext; - glContext.bindBuffer(glContext.ARRAY_BUFFER, this._colorsUint8Buffer); + cc.glBindBuffer(glContext.ARRAY_BUFFER, this._colorsUint8Buffer); glContext.bufferData(glContext.ARRAY_BUFFER, this._squareColorsAB, glContext.STATIC_DRAW); }; @@ -313,9 +313,9 @@ // // Attributes // - context.bindBuffer(context.ARRAY_BUFFER, this._verticesFloat32Buffer); + cc.glBindBuffer(context.ARRAY_BUFFER, this._verticesFloat32Buffer); context.vertexAttribPointer(cc.VERTEX_ATTRIB_POSITION, 3, context.FLOAT, false, 0, 0); - context.bindBuffer(context.ARRAY_BUFFER, this._colorsUint8Buffer); + cc.glBindBuffer(context.ARRAY_BUFFER, this._colorsUint8Buffer); context.vertexAttribPointer(cc.VERTEX_ATTRIB_COLOR, 4, context.UNSIGNED_BYTE, true, 0, 0); context.drawArrays(context.TRIANGLE_STRIP, 0, this._squareVertices.length); diff --git a/cocos2d/core/renderer/GlobalVertexBuffer.js b/cocos2d/core/renderer/GlobalVertexBuffer.js index 4bb7029805..9cbfd28d21 100644 --- a/cocos2d/core/renderer/GlobalVertexBuffer.js +++ b/cocos2d/core/renderer/GlobalVertexBuffer.js @@ -39,7 +39,7 @@ var GlobalVertexBuffer = function (gl) { this.dataArray = new Float32Array(this.data); // Init buffer data - gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); + cc.glBindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); gl.bufferData(gl.ARRAY_BUFFER, this.dataArray, gl.DYNAMIC_DRAW); this._dirty = false; @@ -114,7 +114,7 @@ GlobalVertexBuffer.prototype = { update: function () { if (this._dirty) { - this.gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); + cc.glBindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); // Note: Can memorize different dirty zones and update them separately, maybe faster this.gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.dataArray); this._dirty = false; diff --git a/cocos2d/core/renderer/RendererWebGL.js b/cocos2d/core/renderer/RendererWebGL.js index 93c692a5d9..34c6c7715d 100644 --- a/cocos2d/core/renderer/RendererWebGL.js +++ b/cocos2d/core/renderer/RendererWebGL.js @@ -315,7 +315,7 @@ return { cc.glBlendFunc(_batchedInfo.blendSrc, _batchedInfo.blendDst); cc.glBindTexture2DN(0, texture); // = cc.glBindTexture2D(texture); - var _bufferchanged = !gl.bindBuffer(gl.ARRAY_BUFFER, _quadVertexBuffer); + var _bufferchanged = !cc.glBindBuffer(gl.ARRAY_BUFFER, _quadVertexBuffer); // upload the vertex data to the gl buffer if (_batchingSize > _vertexSize * 0.5) { gl.bufferData(gl.ARRAY_BUFFER, _vertexDataF32, gl.DYNAMIC_DRAW); @@ -334,7 +334,7 @@ return { gl.vertexAttribPointer(cc.VERTEX_ATTRIB_TEX_COORDS, 2, gl.FLOAT, false, 24, 16); } - gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, _quadIndexBuffer); + cc.glBindBuffer(gl.ELEMENT_ARRAY_BUFFER, _quadIndexBuffer); gl.drawElements(gl.TRIANGLES, count * 6, gl.UNSIGNED_SHORT, 0); cc.g_NumberOfDraws++; @@ -352,7 +352,7 @@ return { context = ctx || cc._renderContext; // Reset buffer for rendering - context.bindBuffer(gl.ARRAY_BUFFER, null); + cc.glBindBuffer(gl.ARRAY_BUFFER, null); for (i = 0, len = locCmds.length; i < len; ++i) { cmd = locCmds[i]; diff --git a/cocos2d/core/textures/CCTextureAtlas.js b/cocos2d/core/textures/CCTextureAtlas.js index b996dc7f42..baa68f0e3c 100644 --- a/cocos2d/core/textures/CCTextureAtlas.js +++ b/cocos2d/core/textures/CCTextureAtlas.js @@ -211,10 +211,10 @@ cc.TextureAtlas = cc.Class.extend(/** @lends cc.TextureAtlas# */{ //WebGL only _mapBuffers: function () { var gl = cc._renderContext; - gl.bindBuffer(gl.ARRAY_BUFFER, this._quadsWebBuffer); + cc.glBindBuffer(gl.ARRAY_BUFFER, this._quadsWebBuffer); gl.bufferData(gl.ARRAY_BUFFER, this._quadsArrayBuffer, gl.DYNAMIC_DRAW); - gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._buffersVBO[1]); + cc.glBindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._buffersVBO[1]); gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this._indices, gl.STATIC_DRAW); }, diff --git a/cocos2d/core/textures/TexturesWebGL.js b/cocos2d/core/textures/TexturesWebGL.js index cf6a2555de..ae55915d95 100644 --- a/cocos2d/core/textures/TexturesWebGL.js +++ b/cocos2d/core/textures/TexturesWebGL.js @@ -795,10 +795,10 @@ cc._tmp.WebGLTextureAtlas = function () { var _t = this; var gl = cc._renderContext; - gl.bindBuffer(gl.ARRAY_BUFFER, _t._quadsWebBuffer); + cc.glBindBuffer(gl.ARRAY_BUFFER, _t._quadsWebBuffer); gl.bufferData(gl.ARRAY_BUFFER, _t._quadsArrayBuffer, gl.DYNAMIC_DRAW); - gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, _t._buffersVBO[1]); + cc.glBindBuffer(gl.ELEMENT_ARRAY_BUFFER, _t._buffersVBO[1]); gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, _t._indices, gl.STATIC_DRAW); //cc.checkGLErrorDebug(); @@ -823,10 +823,10 @@ cc._tmp.WebGLTextureAtlas = function () { // Using VBO without VAO // //vertices - //gl.bindBuffer(gl.ARRAY_BUFFER, _t._buffersVBO[0]); + cc.glBindBuffer(gl.ARRAY_BUFFER, _t._buffersVBO[0]); // XXX: update is done in draw... perhaps it should be done in a timer - gl.bindBuffer(gl.ARRAY_BUFFER, _t._quadsWebBuffer); + cc.glBindBuffer(gl.ARRAY_BUFFER, _t._quadsWebBuffer); if (_t.dirty){ gl.bufferData(gl.ARRAY_BUFFER, _t._quadsArrayBuffer, gl.DYNAMIC_DRAW); _t.dirty = false; @@ -840,7 +840,7 @@ cc._tmp.WebGLTextureAtlas = function () { gl.vertexAttribPointer(cc.VERTEX_ATTRIB_COLOR, 4, gl.UNSIGNED_BYTE, true, 24, 12); // colors gl.vertexAttribPointer(cc.VERTEX_ATTRIB_TEX_COORDS, 2, gl.FLOAT, false, 24, 16); // tex coords - gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, _t._buffersVBO[1]); + cc.glBindBuffer(gl.ELEMENT_ARRAY_BUFFER, _t._buffersVBO[1]); if (cc.TEXTURE_ATLAS_USE_TRIANGLE_STRIP) gl.drawElements(gl.TRIANGLE_STRIP, n * 6, gl.UNSIGNED_SHORT, start * 6 * _t._indices.BYTES_PER_ELEMENT); diff --git a/cocos2d/effects/CCGrid.js b/cocos2d/effects/CCGrid.js index 8c5cd08a22..64e1d3086a 100644 --- a/cocos2d/effects/CCGrid.js +++ b/cocos2d/effects/CCGrid.js @@ -456,18 +456,18 @@ cc.Grid3D = cc.GridBase.extend(/** @lends cc.Grid3D# */{ // Attributes // // position - gl.bindBuffer(gl.ARRAY_BUFFER, this._verticesBuffer); + cc.glBindBuffer(gl.ARRAY_BUFFER, this._verticesBuffer); if (locDirty) gl.bufferData(gl.ARRAY_BUFFER, this._vertices, gl.DYNAMIC_DRAW); gl.vertexAttribPointer(cc.VERTEX_ATTRIB_POSITION, 3, gl.FLOAT, false, 0, 0); // texCoords - gl.bindBuffer(gl.ARRAY_BUFFER, this._texCoordinateBuffer); + cc.glBindBuffer(gl.ARRAY_BUFFER, this._texCoordinateBuffer); if (locDirty) gl.bufferData(gl.ARRAY_BUFFER, this._texCoordinates, gl.DYNAMIC_DRAW); gl.vertexAttribPointer(cc.VERTEX_ATTRIB_TEX_COORDS, 2, gl.FLOAT, false, 0, 0); - gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._indicesBuffer); + cc.glBindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._indicesBuffer); if (locDirty) gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this._indices, gl.STATIC_DRAW); gl.drawElements(gl.TRIANGLES, n * 6, gl.UNSIGNED_SHORT, 0); @@ -553,11 +553,11 @@ cc.Grid3D = cc.GridBase.extend(/** @lends cc.Grid3D# */{ } this._originalVertices = new Float32Array(this._vertices); - gl.bindBuffer(gl.ARRAY_BUFFER, this._verticesBuffer); + cc.glBindBuffer(gl.ARRAY_BUFFER, this._verticesBuffer); gl.bufferData(gl.ARRAY_BUFFER, this._vertices, gl.DYNAMIC_DRAW); - gl.bindBuffer(gl.ARRAY_BUFFER, this._texCoordinateBuffer); + cc.glBindBuffer(gl.ARRAY_BUFFER, this._texCoordinateBuffer); gl.bufferData(gl.ARRAY_BUFFER, this._texCoordinates, gl.DYNAMIC_DRAW); - gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._indicesBuffer); + cc.glBindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._indicesBuffer); gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this._indices, gl.STATIC_DRAW); this._dirty = true; }, @@ -727,18 +727,18 @@ cc.TiledGrid3D = cc.GridBase.extend(/** @lends cc.TiledGrid3D# */{ gl.enableVertexAttribArray(cc.VERTEX_ATTRIB_TEX_COORDS); // position - gl.bindBuffer(gl.ARRAY_BUFFER, this._verticesBuffer); + cc.glBindBuffer(gl.ARRAY_BUFFER, this._verticesBuffer); if (locDirty) gl.bufferData(gl.ARRAY_BUFFER, this._vertices, gl.DYNAMIC_DRAW); gl.vertexAttribPointer(cc.VERTEX_ATTRIB_POSITION, 3, gl.FLOAT, false, 0, this._vertices); // texCoords - gl.bindBuffer(gl.ARRAY_BUFFER, this._texCoordinateBuffer); + cc.glBindBuffer(gl.ARRAY_BUFFER, this._texCoordinateBuffer); if (locDirty) gl.bufferData(gl.ARRAY_BUFFER, this._texCoordinates, gl.DYNAMIC_DRAW); gl.vertexAttribPointer(cc.VERTEX_ATTRIB_TEX_COORDS, 2, gl.FLOAT, false, 0, this._texCoordinates); - gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._indicesBuffer); + cc.glBindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._indicesBuffer); if (locDirty) gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this._indices, gl.STATIC_DRAW); gl.drawElements(gl.TRIANGLES, n * 6, gl.UNSIGNED_SHORT, 0); @@ -832,11 +832,11 @@ cc.TiledGrid3D = cc.GridBase.extend(/** @lends cc.TiledGrid3D# */{ } this._originalVertices = new Float32Array(this._vertices); - gl.bindBuffer(gl.ARRAY_BUFFER, this._verticesBuffer); + cc.glBindBuffer(gl.ARRAY_BUFFER, this._verticesBuffer); gl.bufferData(gl.ARRAY_BUFFER, this._vertices, gl.DYNAMIC_DRAW); - gl.bindBuffer(gl.ARRAY_BUFFER, this._texCoordinateBuffer); + cc.glBindBuffer(gl.ARRAY_BUFFER, this._texCoordinateBuffer); gl.bufferData(gl.ARRAY_BUFFER, this._texCoordinates, gl.DYNAMIC_DRAW); - gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._indicesBuffer); + cc.glBindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._indicesBuffer); gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this._indices, gl.DYNAMIC_DRAW); this._dirty = true; } diff --git a/cocos2d/motion-streak/CCMotionStreak.js b/cocos2d/motion-streak/CCMotionStreak.js index 1553aa4c2a..b3c33947de 100644 --- a/cocos2d/motion-streak/CCMotionStreak.js +++ b/cocos2d/motion-streak/CCMotionStreak.js @@ -290,11 +290,11 @@ cc.MotionStreak = cc.Node.extend(/** @lends cc.MotionStreak# */{ this.scheduleUpdate(); //bind buffer - gl.bindBuffer(gl.ARRAY_BUFFER, this._verticesBuffer); + cc.glBindBuffer(gl.ARRAY_BUFFER, this._verticesBuffer); gl.bufferData(gl.ARRAY_BUFFER, this._vertices, gl.DYNAMIC_DRAW); - gl.bindBuffer(gl.ARRAY_BUFFER, this._texCoordsBuffer); + cc.glBindBuffer(gl.ARRAY_BUFFER, this._texCoordsBuffer); gl.bufferData(gl.ARRAY_BUFFER, this._texCoords, gl.DYNAMIC_DRAW); - gl.bindBuffer(gl.ARRAY_BUFFER, this._colorPointerBuffer); + cc.glBindBuffer(gl.ARRAY_BUFFER, this._colorPointerBuffer); gl.bufferData(gl.ARRAY_BUFFER, this._colorPointer, gl.DYNAMIC_DRAW); return true; diff --git a/cocos2d/motion-streak/CCMotionStreakWebGLRenderCmd.js b/cocos2d/motion-streak/CCMotionStreakWebGLRenderCmd.js index 69f4f12f5f..56914dda6a 100644 --- a/cocos2d/motion-streak/CCMotionStreakWebGLRenderCmd.js +++ b/cocos2d/motion-streak/CCMotionStreakWebGLRenderCmd.js @@ -60,17 +60,17 @@ cc.MotionStreak.WebGLRenderCmd.prototype.rendering = function(ctx){ ctx.enableVertexAttribArray(cc.VERTEX_ATTRIB_TEX_COORDS); //position - ctx.bindBuffer(ctx.ARRAY_BUFFER, node._verticesBuffer); + cc.glBindBuffer(ctx.ARRAY_BUFFER, node._verticesBuffer); ctx.bufferData(ctx.ARRAY_BUFFER, node._vertices, ctx.DYNAMIC_DRAW); ctx.vertexAttribPointer(cc.VERTEX_ATTRIB_POSITION, 2, ctx.FLOAT, false, 0, 0); //texcoords - ctx.bindBuffer(ctx.ARRAY_BUFFER, node._texCoordsBuffer); + cc.glBindBuffer(ctx.ARRAY_BUFFER, node._texCoordsBuffer); ctx.bufferData(ctx.ARRAY_BUFFER, node._texCoords, ctx.DYNAMIC_DRAW); ctx.vertexAttribPointer(cc.VERTEX_ATTRIB_TEX_COORDS, 2, ctx.FLOAT, false, 0, 0); //colors - ctx.bindBuffer(ctx.ARRAY_BUFFER, node._colorPointerBuffer); + cc.glBindBuffer(ctx.ARRAY_BUFFER, node._colorPointerBuffer); ctx.bufferData(ctx.ARRAY_BUFFER, node._colorPointer, ctx.DYNAMIC_DRAW); ctx.vertexAttribPointer(cc.VERTEX_ATTRIB_COLOR, 4, ctx.UNSIGNED_BYTE, true, 0, 0); diff --git a/cocos2d/particle/CCParticleSystemWebGLRenderCmd.js b/cocos2d/particle/CCParticleSystemWebGLRenderCmd.js index 8e684256d3..eb8f3872fe 100644 --- a/cocos2d/particle/CCParticleSystemWebGLRenderCmd.js +++ b/cocos2d/particle/CCParticleSystemWebGLRenderCmd.js @@ -210,12 +210,12 @@ gl.enableVertexAttribArray(cc.VERTEX_ATTRIB_COLOR); gl.enableVertexAttribArray(cc.VERTEX_ATTRIB_TEX_COORDS); - gl.bindBuffer(gl.ARRAY_BUFFER, this._buffersVBO[0]); + cc.glBindBuffer(gl.ARRAY_BUFFER, this._buffersVBO[0]); gl.vertexAttribPointer(cc.VERTEX_ATTRIB_POSITION, 3, gl.FLOAT, false, 24, 0); // vertices gl.vertexAttribPointer(cc.VERTEX_ATTRIB_COLOR, 4, gl.UNSIGNED_BYTE, true, 24, 12); // colors gl.vertexAttribPointer(cc.VERTEX_ATTRIB_TEX_COORDS, 2, gl.FLOAT, false, 24, 16); // tex coords - gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._buffersVBO[1]); + cc.glBindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._buffersVBO[1]); gl.drawElements(gl.TRIANGLES, node._particleIdx * 6, gl.UNSIGNED_SHORT, 0); }; @@ -341,11 +341,11 @@ //gl.deleteBuffer(this._buffersVBO[0]); this._buffersVBO[0] = gl.createBuffer(); - gl.bindBuffer(gl.ARRAY_BUFFER, this._buffersVBO[0]); + cc.glBindBuffer(gl.ARRAY_BUFFER, this._buffersVBO[0]); gl.bufferData(gl.ARRAY_BUFFER, this._quadsArrayBuffer, gl.DYNAMIC_DRAW); this._buffersVBO[1] = gl.createBuffer(); - gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._buffersVBO[1]); + cc.glBindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._buffersVBO[1]); gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this._indices, gl.STATIC_DRAW); //cc.checkGLErrorDebug(); @@ -378,7 +378,7 @@ proto.postStep = function(){ var gl = cc._renderContext; - gl.bindBuffer(gl.ARRAY_BUFFER, this._buffersVBO[0]); + cc.glBindBuffer(gl.ARRAY_BUFFER, this._buffersVBO[0]); gl.bufferSubData(gl.ARRAY_BUFFER, 0, this._quadsArrayBuffer); }; diff --git a/cocos2d/progress-timer/CCProgressTimerWebGLRenderCmd.js b/cocos2d/progress-timer/CCProgressTimerWebGLRenderCmd.js index e1be5255ae..1f57a535f4 100644 --- a/cocos2d/progress-timer/CCProgressTimerWebGLRenderCmd.js +++ b/cocos2d/progress-timer/CCProgressTimerWebGLRenderCmd.js @@ -70,7 +70,7 @@ var blendFunc = node._sprite._blendFunc; cc.glBlendFunc(blendFunc.src, blendFunc.dst); cc.glBindTexture2D(node._sprite.texture); - context.bindBuffer(context.ARRAY_BUFFER, this._vertexWebGLBuffer); + cc.glBindBuffer(context.ARRAY_BUFFER, this._vertexWebGLBuffer); context.enableVertexAttribArray(cc.VERTEX_ATTRIB_POSITION); context.enableVertexAttribArray(cc.VERTEX_ATTRIB_COLOR); @@ -220,7 +220,7 @@ } // Init buffer data - gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexWebGLBuffer); + cc.glBindBuffer(gl.ARRAY_BUFFER, this._vertexWebGLBuffer); gl.bufferData(gl.ARRAY_BUFFER, this._float32View, gl.DYNAMIC_DRAW); this._vertexDataCount = 0; diff --git a/cocos2d/shaders/CCGLStateCache.js b/cocos2d/shaders/CCGLStateCache.js index 127bc2d711..e86109aa6e 100644 --- a/cocos2d/shaders/CCGLStateCache.js +++ b/cocos2d/shaders/CCGLStateCache.js @@ -24,108 +24,112 @@ THE SOFTWARE. ****************************************************************************/ -cc._currentProjectionMatrix = -1; +(function () { -if (cc.ENABLE_GL_STATE_CACHE) { - cc.MAX_ACTIVETEXTURE = 16; +cc.MAX_ACTIVETEXTURE = 16; +var _currentProjectionMatrix = -1, + _currentShaderProgram = -1, + _currentBoundTexture = [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1], + _blendingSource = -1, + _blendingDest = -1, + _GLServerState = 0, + _uVAO = 0, + _currBuffers = {}, + _vertexAttribPosition = false, + _vertexAttribColor = false, + _vertexAttribTexCoords = false, - cc._currentShaderProgram = -1; - cc._currentBoundTexture = [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1]; - cc._blendingSource = -1; - cc._blendingDest = -1; - cc._GLServerState = 0; - if(cc.TEXTURE_ATLAS_USE_VAO) - cc._uVAO = 0; + ENABLE_GL_STATE_CACHE = cc.ENABLE_GL_STATE_CACHE; - var _currBuffers = {}; +// GL State Cache functions - WebGLRenderingContext.prototype.glBindBuffer = WebGLRenderingContext.prototype.bindBuffer; - WebGLRenderingContext.prototype.bindBuffer = function (target, buffer) { - if (_currBuffers[target] !== buffer) { - this.glBindBuffer(target, buffer); - _currBuffers[target] = buffer; - return false; - } - else { - return true; - } - }; +cc.glBindBuffer = ENABLE_GL_STATE_CACHE ? function (target, buffer) { + if (_currBuffers[target] !== buffer) { + cc._renderContext.bindBuffer(target, buffer); + _currBuffers[target] = buffer; + return false; + } + else { + return true; + } +} : function (target, buffer) { + cc._renderContext.bindBuffer(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; - } +cc.glEnableVertexAttribArray = ENABLE_GL_STATE_CACHE ? function (index) { + if (index === macro.VERTEX_ATTRIB_FLAG_POSITION) { + if (!_vertexAttribPosition) { + cc._renderContext.enableVertexAttribArray(index); + _vertexAttribPosition = true; } - else if (index === cc.VERTEX_ATTRIB_FLAG_TEX_COORDS) { - if (!this._vertexAttribTexCoords) { - this.glEnableVertexAttribArray(index); - this._vertexAttribTexCoords = true; - } + } + else if (index === macro.VERTEX_ATTRIB_FLAG_COLOR) { + if (!_vertexAttribColor) { + cc._renderContext.enableVertexAttribArray(index); + _vertexAttribColor = true; } - else { - this.glEnableVertexAttribArray(index); + } + else if (index === macro.VERTEX_ATTRIB_FLAG_TEX_COORDS) { + if (!_vertexAttribTexCoords) { + cc._renderContext.enableVertexAttribArray(index); + _vertexAttribTexCoords = true; } - }; + } + else { + cc._renderContext.enableVertexAttribArray(index); + } +} : function (index) { + cc._renderContext.enableVertexAttribArray(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; - } +cc.glDisableVertexAttribArray = ENABLE_GL_STATE_CACHE ? function (index) { + if (index === macro.VERTEX_ATTRIB_FLAG_COLOR) { + if (_vertexAttribColor) { + cc._renderContext.disableVertexAttribArray(index); + _vertexAttribColor = false; } - else if (index !== 0) { - this.glDisableVertexAttribArray(index); + } + else if (index === macro.VERTEX_ATTRIB_FLAG_TEX_COORDS) { + if (_vertexAttribTexCoords) { + cc._renderContext.disableVertexAttribArray(index); + _vertexAttribTexCoords = false; } - }; -} - -// GL State Cache functions + } + else if (index !== 0) { + cc._renderContext.disableVertexAttribArray(index); + } +} : function (index) { + cc._renderContext.disableVertexAttribArray(index); +}; /** * Invalidates the GL state cache.
- * If CC_ENABLE_GL_STATE_CACHE it will reset the GL state cache. + * If cc.ENABLE_GL_STATE_CACHE it will reset the GL state cache. * @function */ cc.glInvalidateStateCache = function () { cc.kmGLFreeAll(); - cc._currentProjectionMatrix = -1; - if (cc.ENABLE_GL_STATE_CACHE) { - cc._currentShaderProgram = -1; + _currentProjectionMatrix = -1; + if (ENABLE_GL_STATE_CACHE) { + _currentShaderProgram = -1; for (var i = 0; i < cc.MAX_ACTIVETEXTURE; i++) { - cc._currentBoundTexture[i] = -1; + _currentBoundTexture[i] = -1; } - cc._blendingSource = -1; - cc._blendingDest = -1; - cc._GLServerState = 0; + _blendingSource = -1; + _blendingDest = -1; + _GLServerState = 0; } }; /** * Uses the GL program in case program is different than the current one.
- * If CC_ENABLE_GL_STATE_CACHE is disabled, it will the glUseProgram() directly. + * If cc.ENABLE_GL_STATE_CACHE is disabled, it will the glUseProgram() directly. * @function * @param {WebGLProgram} program */ -cc.glUseProgram = cc.ENABLE_GL_STATE_CACHE ? function (program) { - if (program !== cc._currentShaderProgram) { - cc._currentShaderProgram = program; +cc.glUseProgram = ENABLE_GL_STATE_CACHE ? function (program) { + if (program !== _currentShaderProgram) { + _currentShaderProgram = program; cc._renderContext.useProgram(program); } } : function (program) { @@ -134,14 +138,14 @@ cc.glUseProgram = cc.ENABLE_GL_STATE_CACHE ? function (program) { /** * Deletes the GL program. If it is the one that is being used, it invalidates it.
- * If CC_ENABLE_GL_STATE_CACHE is disabled, it will the glDeleteProgram() directly. + * If cc.ENABLE_GL_STATE_CACHE is disabled, it will the glDeleteProgram() directly. * @function * @param {WebGLProgram} program */ cc.glDeleteProgram = function (program) { - if (cc.ENABLE_GL_STATE_CACHE) { - if (program === cc._currentShaderProgram) - cc._currentShaderProgram = -1; + if (ENABLE_GL_STATE_CACHE) { + if (program === _currentShaderProgram) + _currentShaderProgram = -1; } gl.deleteProgram(program); }; @@ -165,15 +169,15 @@ cc.setBlending = function (sfactor, dfactor) { /** * Uses a blending function in case it not already used.
- * If CC_ENABLE_GL_STATE_CACHE is disabled, it will the glBlendFunc() directly. + * If cc.ENABLE_GL_STATE_CACHE is disabled, it will the glBlendFunc() directly. * @function * @param {Number} sfactor * @param {Number} dfactor */ -cc.glBlendFunc = cc.ENABLE_GL_STATE_CACHE ? function (sfactor, dfactor) { - if ((sfactor !== cc._blendingSource) || (dfactor !== cc._blendingDest)) { - cc._blendingSource = sfactor; - cc._blendingDest = dfactor; +cc.glBlendFunc = ENABLE_GL_STATE_CACHE ? function (sfactor, dfactor) { + if ((sfactor !== _blendingSource) || (dfactor !== _blendingDest)) { + _blendingSource = sfactor; + _blendingDest = dfactor; cc.setBlending(sfactor, dfactor); } } : cc.setBlending; @@ -184,9 +188,9 @@ cc.glBlendFunc = cc.ENABLE_GL_STATE_CACHE ? function (sfactor, dfactor) { * @param {Number} dfactor */ cc.glBlendFuncForParticle = function(sfactor, dfactor) { - if ((sfactor !== cc._blendingSource) || (dfactor !== cc._blendingDest)) { - cc._blendingSource = sfactor; - cc._blendingDest = dfactor; + if ((sfactor !== _blendingSource) || (dfactor !== _blendingDest)) { + _blendingSource = sfactor; + _blendingDest = dfactor; var ctx = cc._renderContext; if ((sfactor === ctx.ONE) && (dfactor === ctx.ZERO)) { ctx.disable(ctx.BLEND); @@ -200,14 +204,14 @@ cc.glBlendFuncForParticle = function(sfactor, dfactor) { /** * Resets the blending mode back to the cached state in case you used glBlendFuncSeparate() or glBlendEquation().
- * If CC_ENABLE_GL_STATE_CACHE is disabled, it will just set the default blending mode using GL_FUNC_ADD. + * If cc.ENABLE_GL_STATE_CACHE is disabled, it will just set the default blending mode using GL_FUNC_ADD. * @function */ cc.glBlendResetToCache = function () { var ctx = cc._renderContext; ctx.blendEquation(ctx.FUNC_ADD); - if (cc.ENABLE_GL_STATE_CACHE) - cc.setBlending(cc._blendingSource, cc._blendingDest); + if (ENABLE_GL_STATE_CACHE) + cc.setBlending(_blendingSource, _blendingDest); else cc.setBlending(ctx.BLEND_SRC, ctx.BLEND_DST); }; @@ -217,12 +221,12 @@ cc.glBlendResetToCache = function () { * @function */ cc.setProjectionMatrixDirty = function () { - cc._currentProjectionMatrix = -1; + _currentProjectionMatrix = -1; }; /** * If the texture is not already bound, it binds it.
- * If CC_ENABLE_GL_STATE_CACHE is disabled, it will call glBindTexture() directly. + * If cc.ENABLE_GL_STATE_CACHE is disabled, it will call glBindTexture() directly. * @function * @param {cc.Texture2D} textureId */ @@ -232,15 +236,15 @@ cc.glBindTexture2D = function (textureId) { /** * If the texture is not already bound to a given unit, it binds it.
- * If CC_ENABLE_GL_STATE_CACHE is disabled, it will call glBindTexture() directly. + * If cc.ENABLE_GL_STATE_CACHE is disabled, it will call glBindTexture() directly. * @function * @param {Number} textureUnit * @param {cc.Texture2D} textureId */ -cc.glBindTexture2DN = cc.ENABLE_GL_STATE_CACHE ? function (textureUnit, textureId) { - if (cc._currentBoundTexture[textureUnit] === textureId) +cc.glBindTexture2DN = ENABLE_GL_STATE_CACHE ? function (textureUnit, textureId) { + if (_currentBoundTexture[textureUnit] === textureId) return; - cc._currentBoundTexture[textureUnit] = textureId; + _currentBoundTexture[textureUnit] = textureId; var ctx = cc._renderContext; ctx.activeTexture(ctx.TEXTURE0 + textureUnit); @@ -259,7 +263,7 @@ cc.glBindTexture2DN = cc.ENABLE_GL_STATE_CACHE ? function (textureUnit, textureI /** * It will delete a given texture. If the texture was bound, it will invalidate the cached.
- * If CC_ENABLE_GL_STATE_CACHE is disabled, it will call glDeleteTextures() directly. + * If cc.ENABLE_GL_STATE_CACHE is disabled, it will call glDeleteTextures() directly. * @function * @param {WebGLTexture} textureId */ @@ -269,22 +273,22 @@ cc.glDeleteTexture = function (textureId) { /** * It will delete a given texture. If the texture was bound, it will invalidate the cached for the given texture unit.
- * If CC_ENABLE_GL_STATE_CACHE is disabled, it will call glDeleteTextures() directly. + * If cc.ENABLE_GL_STATE_CACHE is disabled, it will call glDeleteTextures() directly. * @function * @param {Number} textureUnit * @param {WebGLTexture} textureId */ cc.glDeleteTextureN = function (textureUnit, textureId) { - if (cc.ENABLE_GL_STATE_CACHE) { - if (textureId === cc._currentBoundTexture[ textureUnit ]) - cc._currentBoundTexture[ textureUnit ] = -1; + if (ENABLE_GL_STATE_CACHE) { + if (textureId === _currentBoundTexture[ textureUnit ]) + _currentBoundTexture[ textureUnit ] = -1; } cc._renderContext.deleteTexture(textureId._webTextureObj); }; /** * If the vertex array is not already bound, it binds it.
- * If CC_ENABLE_GL_STATE_CACHE is disabled, it will call glBindVertexArray() directly. + * If cc.ENABLE_GL_STATE_CACHE is disabled, it will call glBindVertexArray() directly. * @function * @param {Number} vaoId */ @@ -292,9 +296,9 @@ cc.glBindVAO = function (vaoId) { if (!cc.TEXTURE_ATLAS_USE_VAO) return; - if (cc.ENABLE_GL_STATE_CACHE) { - if (cc._uVAO !== vaoId) { - cc._uVAO = vaoId; + if (ENABLE_GL_STATE_CACHE) { + if (_uVAO !== vaoId) { + _uVAO = vaoId; //TODO need fixed //glBindVertexArray(vaoId); } @@ -305,24 +309,24 @@ cc.glBindVAO = function (vaoId) { /** * It will enable / disable the server side GL states.
- * If CC_ENABLE_GL_STATE_CACHE is disabled, it will call glEnable() directly. + * If cc.ENABLE_GL_STATE_CACHE is disabled, it will call glEnable() directly. * @function * @param {Number} flags */ cc.glEnable = function (flags) { - if (cc.ENABLE_GL_STATE_CACHE) { + if (ENABLE_GL_STATE_CACHE) { /*var enabled; */ /* GL_BLEND */ /* - if ((enabled = (flags & cc.GL_BLEND)) != (cc._GLServerState & cc.GL_BLEND)) { + if ((enabled = (flags & cc.GL_BLEND)) != (_GLServerState & cc.GL_BLEND)) { if (enabled) { cc._renderContext.enable(cc._renderContext.BLEND); - cc._GLServerState |= cc.GL_BLEND; + _GLServerState |= cc.GL_BLEND; } else { cc._renderContext.disable(cc._renderContext.BLEND); - cc._GLServerState &= ~cc.GL_BLEND; + _GLServerState &= ~cc.GL_BLEND; } }*/ } else { @@ -332,3 +336,5 @@ cc.glEnable = function (flags) { cc._renderContext.disable(cc._renderContext.BLEND);*/ } }; + +})(); diff --git a/cocos2d/shape-nodes/CCDrawNode.js b/cocos2d/shape-nodes/CCDrawNode.js index 48cdf4cccc..bb101ab904 100644 --- a/cocos2d/shape-nodes/CCDrawNode.js +++ b/cocos2d/shape-nodes/CCDrawNode.js @@ -664,7 +664,7 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () { _render:function () { var gl = cc._renderContext; - gl.bindBuffer(gl.ARRAY_BUFFER, this._trianglesWebBuffer); + cc.glBindBuffer(gl.ARRAY_BUFFER, this._trianglesWebBuffer); if (this._dirty) { gl.bufferData(gl.ARRAY_BUFFER, this._trianglesArrayBuffer, gl.STREAM_DRAW); this._dirty = false; diff --git a/extensions/ccui/uiwidgets/scroll-widget/UIScrollViewWebGLRenderCmd.js b/extensions/ccui/uiwidgets/scroll-widget/UIScrollViewWebGLRenderCmd.js index 413d23aff0..11696851d3 100644 --- a/extensions/ccui/uiwidgets/scroll-widget/UIScrollViewWebGLRenderCmd.js +++ b/extensions/ccui/uiwidgets/scroll-widget/UIScrollViewWebGLRenderCmd.js @@ -40,7 +40,7 @@ this._node.updateChildren(); // Reset buffer for rendering - context.bindBuffer(gl.ARRAY_BUFFER, null); + cc.glBindBuffer(gl.ARRAY_BUFFER, null); for (i = 0, len = locCmds.length; i < len; i++) { cmd = locCmds[i]; From 80759742e13c03fab83f9c072564b1aacfc2ea19 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Thu, 3 Nov 2016 21:42:02 +0800 Subject: [PATCH 015/206] Revert "Remove overwrite in webgl context object" This reverts commit 6d965db866f659e8769c125948ea8c2fb9983b1d. --- cocos2d/core/CCDrawingPrimitivesWebGL.js | 18 +- cocos2d/core/layers/CCLayerWebGLRenderCmd.js | 12 +- cocos2d/core/renderer/GlobalVertexBuffer.js | 4 +- cocos2d/core/renderer/RendererWebGL.js | 6 +- cocos2d/core/textures/CCTextureAtlas.js | 4 +- cocos2d/core/textures/TexturesWebGL.js | 10 +- cocos2d/effects/CCGrid.js | 24 +- cocos2d/motion-streak/CCMotionStreak.js | 6 +- .../CCMotionStreakWebGLRenderCmd.js | 6 +- .../CCParticleSystemWebGLRenderCmd.js | 10 +- .../CCProgressTimerWebGLRenderCmd.js | 4 +- cocos2d/shaders/CCGLStateCache.js | 224 +++++++++--------- cocos2d/shape-nodes/CCDrawNode.js | 2 +- .../UIScrollViewWebGLRenderCmd.js | 2 +- 14 files changed, 163 insertions(+), 169 deletions(-) diff --git a/cocos2d/core/CCDrawingPrimitivesWebGL.js b/cocos2d/core/CCDrawingPrimitivesWebGL.js index dadf0cf759..f8c9b46d0d 100644 --- a/cocos2d/core/CCDrawingPrimitivesWebGL.js +++ b/cocos2d/core/CCDrawingPrimitivesWebGL.js @@ -88,7 +88,7 @@ cc.DrawingPrimitiveWebGL = cc.Class.extend(/** @lends cc.DrawingPrimitiveWebGL# this._shader.setUniformLocationWith1f(this._pointSizeLocation, this._pointSize); var pointBuffer = glContext.createBuffer(); - cc.glBindBuffer(glContext.ARRAY_BUFFER, pointBuffer); + glContext.bindBuffer(glContext.ARRAY_BUFFER, pointBuffer); glContext.bufferData(glContext.ARRAY_BUFFER, new Float32Array([point.x, point.y]), glContext.STATIC_DRAW); glContext.vertexAttribPointer(cc.VERTEX_ATTRIB_POSITION, 2, glContext.FLOAT, false, 0, 0); @@ -117,7 +117,7 @@ cc.DrawingPrimitiveWebGL = cc.Class.extend(/** @lends cc.DrawingPrimitiveWebGL# this._shader.setUniformLocationWith1f(this._pointSizeLocation, this._pointSize); var pointBuffer = glContext.createBuffer(); - cc.glBindBuffer(glContext.ARRAY_BUFFER, pointBuffer); + glContext.bindBuffer(glContext.ARRAY_BUFFER, pointBuffer); glContext.bufferData(glContext.ARRAY_BUFFER, this._pointsToTypeArray(points), glContext.STATIC_DRAW); glContext.vertexAttribPointer(cc.VERTEX_ATTRIB_POSITION, 2, glContext.FLOAT, false, 0, 0); @@ -151,7 +151,7 @@ cc.DrawingPrimitiveWebGL = cc.Class.extend(/** @lends cc.DrawingPrimitiveWebGL# this._shader.setUniformLocationWith4fv(this._colorLocation, this._colorArray); var pointBuffer = glContext.createBuffer(); - cc.glBindBuffer(glContext.ARRAY_BUFFER, pointBuffer); + glContext.bindBuffer(glContext.ARRAY_BUFFER, pointBuffer); glContext.bufferData(glContext.ARRAY_BUFFER, this._pointsToTypeArray([origin, destination]), glContext.STATIC_DRAW); glContext.vertexAttribPointer(cc.VERTEX_ATTRIB_POSITION, 2, glContext.FLOAT, false, 0, 0); @@ -206,7 +206,7 @@ cc.DrawingPrimitiveWebGL = cc.Class.extend(/** @lends cc.DrawingPrimitiveWebGL# this._shader.setUniformLocationWith4fv(this._colorLocation, this._colorArray); var pointBuffer = glContext.createBuffer(); - cc.glBindBuffer(glContext.ARRAY_BUFFER, pointBuffer); + glContext.bindBuffer(glContext.ARRAY_BUFFER, pointBuffer); glContext.bufferData(glContext.ARRAY_BUFFER, this._pointsToTypeArray(vertices), glContext.STATIC_DRAW); glContext.vertexAttribPointer(cc.VERTEX_ATTRIB_POSITION, 2, glContext.FLOAT, false, 0, 0); @@ -237,7 +237,7 @@ cc.DrawingPrimitiveWebGL = cc.Class.extend(/** @lends cc.DrawingPrimitiveWebGL# this._shader.setUniformLocationWith4fv(this._colorLocation, this._colorArray); var pointBuffer = glContext.createBuffer(); - cc.glBindBuffer(glContext.ARRAY_BUFFER, pointBuffer); + glContext.bindBuffer(glContext.ARRAY_BUFFER, pointBuffer); glContext.bufferData(glContext.ARRAY_BUFFER, this._pointsToTypeArray(poli), glContext.STATIC_DRAW); glContext.vertexAttribPointer(cc.VERTEX_ATTRIB_POSITION, 2, glContext.FLOAT, false, 0, 0); glContext.drawArrays(glContext.TRIANGLE_FAN, 0, poli.length); @@ -285,7 +285,7 @@ cc.DrawingPrimitiveWebGL = cc.Class.extend(/** @lends cc.DrawingPrimitiveWebGL# this._shader.setUniformLocationWith4fv(this._colorLocation, this._colorArray); var pointBuffer = glContext.createBuffer(); - cc.glBindBuffer(glContext.ARRAY_BUFFER, pointBuffer); + glContext.bindBuffer(glContext.ARRAY_BUFFER, pointBuffer); glContext.bufferData(glContext.ARRAY_BUFFER, vertices, glContext.STATIC_DRAW); glContext.vertexAttribPointer(cc.VERTEX_ATTRIB_POSITION, 2, glContext.FLOAT, false, 0, 0); @@ -323,7 +323,7 @@ cc.DrawingPrimitiveWebGL = cc.Class.extend(/** @lends cc.DrawingPrimitiveWebGL# this._shader.setUniformLocationWith4fv(this._colorLocation, this._colorArray); var pointBuffer = glContext.createBuffer(); - cc.glBindBuffer(glContext.ARRAY_BUFFER, pointBuffer); + glContext.bindBuffer(glContext.ARRAY_BUFFER, pointBuffer); glContext.bufferData(glContext.ARRAY_BUFFER, vertices, glContext.STATIC_DRAW); glContext.vertexAttribPointer(cc.VERTEX_ATTRIB_POSITION, 2, glContext.FLOAT, false, 0, 0); @@ -362,7 +362,7 @@ cc.DrawingPrimitiveWebGL = cc.Class.extend(/** @lends cc.DrawingPrimitiveWebGL# this._shader.setUniformLocationWith4fv(this._colorLocation, this._colorArray); var pointBuffer = glContext.createBuffer(); - cc.glBindBuffer(glContext.ARRAY_BUFFER, pointBuffer); + glContext.bindBuffer(glContext.ARRAY_BUFFER, pointBuffer); glContext.bufferData(glContext.ARRAY_BUFFER, vertices, glContext.STATIC_DRAW); glContext.vertexAttribPointer(cc.VERTEX_ATTRIB_POSITION, 2, glContext.FLOAT, false, 0, 0); glContext.drawArrays(glContext.LINE_STRIP, 0, segments + 1); @@ -422,7 +422,7 @@ cc.DrawingPrimitiveWebGL = cc.Class.extend(/** @lends cc.DrawingPrimitiveWebGL# this._shader.setUniformLocationWith4fv(this._colorLocation, this._colorArray); var pointBuffer = glContext.createBuffer(); - cc.glBindBuffer(glContext.ARRAY_BUFFER, pointBuffer); + glContext.bindBuffer(glContext.ARRAY_BUFFER, pointBuffer); glContext.bufferData(glContext.ARRAY_BUFFER, vertices, glContext.STATIC_DRAW); glContext.vertexAttribPointer(cc.VERTEX_ATTRIB_POSITION, 2, glContext.FLOAT, false, 0, 0); glContext.drawArrays(glContext.LINE_STRIP, 0, segments + 1); diff --git a/cocos2d/core/layers/CCLayerWebGLRenderCmd.js b/cocos2d/core/layers/CCLayerWebGLRenderCmd.js index f39a4814b7..8051a50abe 100644 --- a/cocos2d/core/layers/CCLayerWebGLRenderCmd.js +++ b/cocos2d/core/layers/CCLayerWebGLRenderCmd.js @@ -101,10 +101,10 @@ // // Attributes // - cc.glBindBuffer(context.ARRAY_BUFFER, this._verticesFloat32Buffer); + context.bindBuffer(context.ARRAY_BUFFER, this._verticesFloat32Buffer); context.vertexAttribPointer(cc.VERTEX_ATTRIB_POSITION, 3, context.FLOAT, false, 0, 0); - cc.glBindBuffer(context.ARRAY_BUFFER, this._colorsUint8Buffer); + context.bindBuffer(context.ARRAY_BUFFER, this._colorsUint8Buffer); context.vertexAttribPointer(cc.VERTEX_ATTRIB_COLOR, 4, context.UNSIGNED_BYTE, true, 0, 0); context.drawArrays(context.TRIANGLE_STRIP, 0, this._squareVertices.length); @@ -144,13 +144,13 @@ proto._bindLayerVerticesBufferData = function(){ var glContext = cc._renderContext; - cc.glBindBuffer(glContext.ARRAY_BUFFER, this._verticesFloat32Buffer); + glContext.bindBuffer(glContext.ARRAY_BUFFER, this._verticesFloat32Buffer); glContext.bufferData(glContext.ARRAY_BUFFER, this._squareVerticesAB, glContext.DYNAMIC_DRAW); }; proto._bindLayerColorsBufferData = function(){ var glContext = cc._renderContext; - cc.glBindBuffer(glContext.ARRAY_BUFFER, this._colorsUint8Buffer); + glContext.bindBuffer(glContext.ARRAY_BUFFER, this._colorsUint8Buffer); glContext.bufferData(glContext.ARRAY_BUFFER, this._squareColorsAB, glContext.STATIC_DRAW); }; @@ -313,9 +313,9 @@ // // Attributes // - cc.glBindBuffer(context.ARRAY_BUFFER, this._verticesFloat32Buffer); + context.bindBuffer(context.ARRAY_BUFFER, this._verticesFloat32Buffer); context.vertexAttribPointer(cc.VERTEX_ATTRIB_POSITION, 3, context.FLOAT, false, 0, 0); - cc.glBindBuffer(context.ARRAY_BUFFER, this._colorsUint8Buffer); + context.bindBuffer(context.ARRAY_BUFFER, this._colorsUint8Buffer); context.vertexAttribPointer(cc.VERTEX_ATTRIB_COLOR, 4, context.UNSIGNED_BYTE, true, 0, 0); context.drawArrays(context.TRIANGLE_STRIP, 0, this._squareVertices.length); diff --git a/cocos2d/core/renderer/GlobalVertexBuffer.js b/cocos2d/core/renderer/GlobalVertexBuffer.js index 9cbfd28d21..4bb7029805 100644 --- a/cocos2d/core/renderer/GlobalVertexBuffer.js +++ b/cocos2d/core/renderer/GlobalVertexBuffer.js @@ -39,7 +39,7 @@ var GlobalVertexBuffer = function (gl) { this.dataArray = new Float32Array(this.data); // Init buffer data - cc.glBindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); + gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); gl.bufferData(gl.ARRAY_BUFFER, this.dataArray, gl.DYNAMIC_DRAW); this._dirty = false; @@ -114,7 +114,7 @@ GlobalVertexBuffer.prototype = { update: function () { if (this._dirty) { - cc.glBindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); + this.gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); // Note: Can memorize different dirty zones and update them separately, maybe faster this.gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.dataArray); this._dirty = false; diff --git a/cocos2d/core/renderer/RendererWebGL.js b/cocos2d/core/renderer/RendererWebGL.js index 34c6c7715d..93c692a5d9 100644 --- a/cocos2d/core/renderer/RendererWebGL.js +++ b/cocos2d/core/renderer/RendererWebGL.js @@ -315,7 +315,7 @@ return { cc.glBlendFunc(_batchedInfo.blendSrc, _batchedInfo.blendDst); cc.glBindTexture2DN(0, texture); // = cc.glBindTexture2D(texture); - var _bufferchanged = !cc.glBindBuffer(gl.ARRAY_BUFFER, _quadVertexBuffer); + var _bufferchanged = !gl.bindBuffer(gl.ARRAY_BUFFER, _quadVertexBuffer); // upload the vertex data to the gl buffer if (_batchingSize > _vertexSize * 0.5) { gl.bufferData(gl.ARRAY_BUFFER, _vertexDataF32, gl.DYNAMIC_DRAW); @@ -334,7 +334,7 @@ return { gl.vertexAttribPointer(cc.VERTEX_ATTRIB_TEX_COORDS, 2, gl.FLOAT, false, 24, 16); } - cc.glBindBuffer(gl.ELEMENT_ARRAY_BUFFER, _quadIndexBuffer); + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, _quadIndexBuffer); gl.drawElements(gl.TRIANGLES, count * 6, gl.UNSIGNED_SHORT, 0); cc.g_NumberOfDraws++; @@ -352,7 +352,7 @@ return { context = ctx || cc._renderContext; // Reset buffer for rendering - cc.glBindBuffer(gl.ARRAY_BUFFER, null); + context.bindBuffer(gl.ARRAY_BUFFER, null); for (i = 0, len = locCmds.length; i < len; ++i) { cmd = locCmds[i]; diff --git a/cocos2d/core/textures/CCTextureAtlas.js b/cocos2d/core/textures/CCTextureAtlas.js index baa68f0e3c..b996dc7f42 100644 --- a/cocos2d/core/textures/CCTextureAtlas.js +++ b/cocos2d/core/textures/CCTextureAtlas.js @@ -211,10 +211,10 @@ cc.TextureAtlas = cc.Class.extend(/** @lends cc.TextureAtlas# */{ //WebGL only _mapBuffers: function () { var gl = cc._renderContext; - cc.glBindBuffer(gl.ARRAY_BUFFER, this._quadsWebBuffer); + gl.bindBuffer(gl.ARRAY_BUFFER, this._quadsWebBuffer); gl.bufferData(gl.ARRAY_BUFFER, this._quadsArrayBuffer, gl.DYNAMIC_DRAW); - cc.glBindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._buffersVBO[1]); + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._buffersVBO[1]); gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this._indices, gl.STATIC_DRAW); }, diff --git a/cocos2d/core/textures/TexturesWebGL.js b/cocos2d/core/textures/TexturesWebGL.js index ae55915d95..cf6a2555de 100644 --- a/cocos2d/core/textures/TexturesWebGL.js +++ b/cocos2d/core/textures/TexturesWebGL.js @@ -795,10 +795,10 @@ cc._tmp.WebGLTextureAtlas = function () { var _t = this; var gl = cc._renderContext; - cc.glBindBuffer(gl.ARRAY_BUFFER, _t._quadsWebBuffer); + gl.bindBuffer(gl.ARRAY_BUFFER, _t._quadsWebBuffer); gl.bufferData(gl.ARRAY_BUFFER, _t._quadsArrayBuffer, gl.DYNAMIC_DRAW); - cc.glBindBuffer(gl.ELEMENT_ARRAY_BUFFER, _t._buffersVBO[1]); + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, _t._buffersVBO[1]); gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, _t._indices, gl.STATIC_DRAW); //cc.checkGLErrorDebug(); @@ -823,10 +823,10 @@ cc._tmp.WebGLTextureAtlas = function () { // Using VBO without VAO // //vertices - cc.glBindBuffer(gl.ARRAY_BUFFER, _t._buffersVBO[0]); + //gl.bindBuffer(gl.ARRAY_BUFFER, _t._buffersVBO[0]); // XXX: update is done in draw... perhaps it should be done in a timer - cc.glBindBuffer(gl.ARRAY_BUFFER, _t._quadsWebBuffer); + gl.bindBuffer(gl.ARRAY_BUFFER, _t._quadsWebBuffer); if (_t.dirty){ gl.bufferData(gl.ARRAY_BUFFER, _t._quadsArrayBuffer, gl.DYNAMIC_DRAW); _t.dirty = false; @@ -840,7 +840,7 @@ cc._tmp.WebGLTextureAtlas = function () { gl.vertexAttribPointer(cc.VERTEX_ATTRIB_COLOR, 4, gl.UNSIGNED_BYTE, true, 24, 12); // colors gl.vertexAttribPointer(cc.VERTEX_ATTRIB_TEX_COORDS, 2, gl.FLOAT, false, 24, 16); // tex coords - cc.glBindBuffer(gl.ELEMENT_ARRAY_BUFFER, _t._buffersVBO[1]); + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, _t._buffersVBO[1]); if (cc.TEXTURE_ATLAS_USE_TRIANGLE_STRIP) gl.drawElements(gl.TRIANGLE_STRIP, n * 6, gl.UNSIGNED_SHORT, start * 6 * _t._indices.BYTES_PER_ELEMENT); diff --git a/cocos2d/effects/CCGrid.js b/cocos2d/effects/CCGrid.js index 64e1d3086a..8c5cd08a22 100644 --- a/cocos2d/effects/CCGrid.js +++ b/cocos2d/effects/CCGrid.js @@ -456,18 +456,18 @@ cc.Grid3D = cc.GridBase.extend(/** @lends cc.Grid3D# */{ // Attributes // // position - cc.glBindBuffer(gl.ARRAY_BUFFER, this._verticesBuffer); + gl.bindBuffer(gl.ARRAY_BUFFER, this._verticesBuffer); if (locDirty) gl.bufferData(gl.ARRAY_BUFFER, this._vertices, gl.DYNAMIC_DRAW); gl.vertexAttribPointer(cc.VERTEX_ATTRIB_POSITION, 3, gl.FLOAT, false, 0, 0); // texCoords - cc.glBindBuffer(gl.ARRAY_BUFFER, this._texCoordinateBuffer); + gl.bindBuffer(gl.ARRAY_BUFFER, this._texCoordinateBuffer); if (locDirty) gl.bufferData(gl.ARRAY_BUFFER, this._texCoordinates, gl.DYNAMIC_DRAW); gl.vertexAttribPointer(cc.VERTEX_ATTRIB_TEX_COORDS, 2, gl.FLOAT, false, 0, 0); - cc.glBindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._indicesBuffer); + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._indicesBuffer); if (locDirty) gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this._indices, gl.STATIC_DRAW); gl.drawElements(gl.TRIANGLES, n * 6, gl.UNSIGNED_SHORT, 0); @@ -553,11 +553,11 @@ cc.Grid3D = cc.GridBase.extend(/** @lends cc.Grid3D# */{ } this._originalVertices = new Float32Array(this._vertices); - cc.glBindBuffer(gl.ARRAY_BUFFER, this._verticesBuffer); + gl.bindBuffer(gl.ARRAY_BUFFER, this._verticesBuffer); gl.bufferData(gl.ARRAY_BUFFER, this._vertices, gl.DYNAMIC_DRAW); - cc.glBindBuffer(gl.ARRAY_BUFFER, this._texCoordinateBuffer); + gl.bindBuffer(gl.ARRAY_BUFFER, this._texCoordinateBuffer); gl.bufferData(gl.ARRAY_BUFFER, this._texCoordinates, gl.DYNAMIC_DRAW); - cc.glBindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._indicesBuffer); + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._indicesBuffer); gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this._indices, gl.STATIC_DRAW); this._dirty = true; }, @@ -727,18 +727,18 @@ cc.TiledGrid3D = cc.GridBase.extend(/** @lends cc.TiledGrid3D# */{ gl.enableVertexAttribArray(cc.VERTEX_ATTRIB_TEX_COORDS); // position - cc.glBindBuffer(gl.ARRAY_BUFFER, this._verticesBuffer); + gl.bindBuffer(gl.ARRAY_BUFFER, this._verticesBuffer); if (locDirty) gl.bufferData(gl.ARRAY_BUFFER, this._vertices, gl.DYNAMIC_DRAW); gl.vertexAttribPointer(cc.VERTEX_ATTRIB_POSITION, 3, gl.FLOAT, false, 0, this._vertices); // texCoords - cc.glBindBuffer(gl.ARRAY_BUFFER, this._texCoordinateBuffer); + gl.bindBuffer(gl.ARRAY_BUFFER, this._texCoordinateBuffer); if (locDirty) gl.bufferData(gl.ARRAY_BUFFER, this._texCoordinates, gl.DYNAMIC_DRAW); gl.vertexAttribPointer(cc.VERTEX_ATTRIB_TEX_COORDS, 2, gl.FLOAT, false, 0, this._texCoordinates); - cc.glBindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._indicesBuffer); + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._indicesBuffer); if (locDirty) gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this._indices, gl.STATIC_DRAW); gl.drawElements(gl.TRIANGLES, n * 6, gl.UNSIGNED_SHORT, 0); @@ -832,11 +832,11 @@ cc.TiledGrid3D = cc.GridBase.extend(/** @lends cc.TiledGrid3D# */{ } this._originalVertices = new Float32Array(this._vertices); - cc.glBindBuffer(gl.ARRAY_BUFFER, this._verticesBuffer); + gl.bindBuffer(gl.ARRAY_BUFFER, this._verticesBuffer); gl.bufferData(gl.ARRAY_BUFFER, this._vertices, gl.DYNAMIC_DRAW); - cc.glBindBuffer(gl.ARRAY_BUFFER, this._texCoordinateBuffer); + gl.bindBuffer(gl.ARRAY_BUFFER, this._texCoordinateBuffer); gl.bufferData(gl.ARRAY_BUFFER, this._texCoordinates, gl.DYNAMIC_DRAW); - cc.glBindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._indicesBuffer); + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._indicesBuffer); gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this._indices, gl.DYNAMIC_DRAW); this._dirty = true; } diff --git a/cocos2d/motion-streak/CCMotionStreak.js b/cocos2d/motion-streak/CCMotionStreak.js index b3c33947de..1553aa4c2a 100644 --- a/cocos2d/motion-streak/CCMotionStreak.js +++ b/cocos2d/motion-streak/CCMotionStreak.js @@ -290,11 +290,11 @@ cc.MotionStreak = cc.Node.extend(/** @lends cc.MotionStreak# */{ this.scheduleUpdate(); //bind buffer - cc.glBindBuffer(gl.ARRAY_BUFFER, this._verticesBuffer); + gl.bindBuffer(gl.ARRAY_BUFFER, this._verticesBuffer); gl.bufferData(gl.ARRAY_BUFFER, this._vertices, gl.DYNAMIC_DRAW); - cc.glBindBuffer(gl.ARRAY_BUFFER, this._texCoordsBuffer); + gl.bindBuffer(gl.ARRAY_BUFFER, this._texCoordsBuffer); gl.bufferData(gl.ARRAY_BUFFER, this._texCoords, gl.DYNAMIC_DRAW); - cc.glBindBuffer(gl.ARRAY_BUFFER, this._colorPointerBuffer); + gl.bindBuffer(gl.ARRAY_BUFFER, this._colorPointerBuffer); gl.bufferData(gl.ARRAY_BUFFER, this._colorPointer, gl.DYNAMIC_DRAW); return true; diff --git a/cocos2d/motion-streak/CCMotionStreakWebGLRenderCmd.js b/cocos2d/motion-streak/CCMotionStreakWebGLRenderCmd.js index 56914dda6a..69f4f12f5f 100644 --- a/cocos2d/motion-streak/CCMotionStreakWebGLRenderCmd.js +++ b/cocos2d/motion-streak/CCMotionStreakWebGLRenderCmd.js @@ -60,17 +60,17 @@ cc.MotionStreak.WebGLRenderCmd.prototype.rendering = function(ctx){ ctx.enableVertexAttribArray(cc.VERTEX_ATTRIB_TEX_COORDS); //position - cc.glBindBuffer(ctx.ARRAY_BUFFER, node._verticesBuffer); + ctx.bindBuffer(ctx.ARRAY_BUFFER, node._verticesBuffer); ctx.bufferData(ctx.ARRAY_BUFFER, node._vertices, ctx.DYNAMIC_DRAW); ctx.vertexAttribPointer(cc.VERTEX_ATTRIB_POSITION, 2, ctx.FLOAT, false, 0, 0); //texcoords - cc.glBindBuffer(ctx.ARRAY_BUFFER, node._texCoordsBuffer); + ctx.bindBuffer(ctx.ARRAY_BUFFER, node._texCoordsBuffer); ctx.bufferData(ctx.ARRAY_BUFFER, node._texCoords, ctx.DYNAMIC_DRAW); ctx.vertexAttribPointer(cc.VERTEX_ATTRIB_TEX_COORDS, 2, ctx.FLOAT, false, 0, 0); //colors - cc.glBindBuffer(ctx.ARRAY_BUFFER, node._colorPointerBuffer); + ctx.bindBuffer(ctx.ARRAY_BUFFER, node._colorPointerBuffer); ctx.bufferData(ctx.ARRAY_BUFFER, node._colorPointer, ctx.DYNAMIC_DRAW); ctx.vertexAttribPointer(cc.VERTEX_ATTRIB_COLOR, 4, ctx.UNSIGNED_BYTE, true, 0, 0); diff --git a/cocos2d/particle/CCParticleSystemWebGLRenderCmd.js b/cocos2d/particle/CCParticleSystemWebGLRenderCmd.js index eb8f3872fe..8e684256d3 100644 --- a/cocos2d/particle/CCParticleSystemWebGLRenderCmd.js +++ b/cocos2d/particle/CCParticleSystemWebGLRenderCmd.js @@ -210,12 +210,12 @@ gl.enableVertexAttribArray(cc.VERTEX_ATTRIB_COLOR); gl.enableVertexAttribArray(cc.VERTEX_ATTRIB_TEX_COORDS); - cc.glBindBuffer(gl.ARRAY_BUFFER, this._buffersVBO[0]); + gl.bindBuffer(gl.ARRAY_BUFFER, this._buffersVBO[0]); gl.vertexAttribPointer(cc.VERTEX_ATTRIB_POSITION, 3, gl.FLOAT, false, 24, 0); // vertices gl.vertexAttribPointer(cc.VERTEX_ATTRIB_COLOR, 4, gl.UNSIGNED_BYTE, true, 24, 12); // colors gl.vertexAttribPointer(cc.VERTEX_ATTRIB_TEX_COORDS, 2, gl.FLOAT, false, 24, 16); // tex coords - cc.glBindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._buffersVBO[1]); + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._buffersVBO[1]); gl.drawElements(gl.TRIANGLES, node._particleIdx * 6, gl.UNSIGNED_SHORT, 0); }; @@ -341,11 +341,11 @@ //gl.deleteBuffer(this._buffersVBO[0]); this._buffersVBO[0] = gl.createBuffer(); - cc.glBindBuffer(gl.ARRAY_BUFFER, this._buffersVBO[0]); + gl.bindBuffer(gl.ARRAY_BUFFER, this._buffersVBO[0]); gl.bufferData(gl.ARRAY_BUFFER, this._quadsArrayBuffer, gl.DYNAMIC_DRAW); this._buffersVBO[1] = gl.createBuffer(); - cc.glBindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._buffersVBO[1]); + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._buffersVBO[1]); gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this._indices, gl.STATIC_DRAW); //cc.checkGLErrorDebug(); @@ -378,7 +378,7 @@ proto.postStep = function(){ var gl = cc._renderContext; - cc.glBindBuffer(gl.ARRAY_BUFFER, this._buffersVBO[0]); + gl.bindBuffer(gl.ARRAY_BUFFER, this._buffersVBO[0]); gl.bufferSubData(gl.ARRAY_BUFFER, 0, this._quadsArrayBuffer); }; diff --git a/cocos2d/progress-timer/CCProgressTimerWebGLRenderCmd.js b/cocos2d/progress-timer/CCProgressTimerWebGLRenderCmd.js index 1f57a535f4..e1be5255ae 100644 --- a/cocos2d/progress-timer/CCProgressTimerWebGLRenderCmd.js +++ b/cocos2d/progress-timer/CCProgressTimerWebGLRenderCmd.js @@ -70,7 +70,7 @@ var blendFunc = node._sprite._blendFunc; cc.glBlendFunc(blendFunc.src, blendFunc.dst); cc.glBindTexture2D(node._sprite.texture); - cc.glBindBuffer(context.ARRAY_BUFFER, this._vertexWebGLBuffer); + context.bindBuffer(context.ARRAY_BUFFER, this._vertexWebGLBuffer); context.enableVertexAttribArray(cc.VERTEX_ATTRIB_POSITION); context.enableVertexAttribArray(cc.VERTEX_ATTRIB_COLOR); @@ -220,7 +220,7 @@ } // Init buffer data - cc.glBindBuffer(gl.ARRAY_BUFFER, this._vertexWebGLBuffer); + gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexWebGLBuffer); gl.bufferData(gl.ARRAY_BUFFER, this._float32View, gl.DYNAMIC_DRAW); this._vertexDataCount = 0; diff --git a/cocos2d/shaders/CCGLStateCache.js b/cocos2d/shaders/CCGLStateCache.js index e86109aa6e..127bc2d711 100644 --- a/cocos2d/shaders/CCGLStateCache.js +++ b/cocos2d/shaders/CCGLStateCache.js @@ -24,112 +24,108 @@ THE SOFTWARE. ****************************************************************************/ -(function () { +cc._currentProjectionMatrix = -1; -cc.MAX_ACTIVETEXTURE = 16; -var _currentProjectionMatrix = -1, - _currentShaderProgram = -1, - _currentBoundTexture = [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1], - _blendingSource = -1, - _blendingDest = -1, - _GLServerState = 0, - _uVAO = 0, - _currBuffers = {}, - _vertexAttribPosition = false, - _vertexAttribColor = false, - _vertexAttribTexCoords = false, +if (cc.ENABLE_GL_STATE_CACHE) { + cc.MAX_ACTIVETEXTURE = 16; - ENABLE_GL_STATE_CACHE = cc.ENABLE_GL_STATE_CACHE; + cc._currentShaderProgram = -1; + cc._currentBoundTexture = [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1]; + cc._blendingSource = -1; + cc._blendingDest = -1; + cc._GLServerState = 0; + if(cc.TEXTURE_ATLAS_USE_VAO) + cc._uVAO = 0; -// GL State Cache functions + var _currBuffers = {}; -cc.glBindBuffer = ENABLE_GL_STATE_CACHE ? function (target, buffer) { - if (_currBuffers[target] !== buffer) { - cc._renderContext.bindBuffer(target, buffer); - _currBuffers[target] = buffer; - return false; - } - else { - return true; - } -} : function (target, buffer) { - cc._renderContext.bindBuffer(target, buffer); -}; + WebGLRenderingContext.prototype.glBindBuffer = WebGLRenderingContext.prototype.bindBuffer; + WebGLRenderingContext.prototype.bindBuffer = function (target, buffer) { + if (_currBuffers[target] !== buffer) { + this.glBindBuffer(target, buffer); + _currBuffers[target] = buffer; + return false; + } + else { + return true; + } + }; -cc.glEnableVertexAttribArray = ENABLE_GL_STATE_CACHE ? function (index) { - if (index === macro.VERTEX_ATTRIB_FLAG_POSITION) { - if (!_vertexAttribPosition) { - cc._renderContext.enableVertexAttribArray(index); - _vertexAttribPosition = true; + 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 === macro.VERTEX_ATTRIB_FLAG_COLOR) { - if (!_vertexAttribColor) { - cc._renderContext.enableVertexAttribArray(index); - _vertexAttribColor = true; + else if (index === cc.VERTEX_ATTRIB_FLAG_COLOR) { + if (!this._vertexAttribColor) { + this.glEnableVertexAttribArray(index); + this._vertexAttribColor = true; + } } - } - else if (index === macro.VERTEX_ATTRIB_FLAG_TEX_COORDS) { - if (!_vertexAttribTexCoords) { - cc._renderContext.enableVertexAttribArray(index); - _vertexAttribTexCoords = true; + else if (index === cc.VERTEX_ATTRIB_FLAG_TEX_COORDS) { + if (!this._vertexAttribTexCoords) { + this.glEnableVertexAttribArray(index); + this._vertexAttribTexCoords = true; + } } - } - else { - cc._renderContext.enableVertexAttribArray(index); - } -} : function (index) { - cc._renderContext.enableVertexAttribArray(index); -}; + else { + this.glEnableVertexAttribArray(index); + } + }; -cc.glDisableVertexAttribArray = ENABLE_GL_STATE_CACHE ? function (index) { - if (index === macro.VERTEX_ATTRIB_FLAG_COLOR) { - if (_vertexAttribColor) { - cc._renderContext.disableVertexAttribArray(index); - _vertexAttribColor = false; + 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 === macro.VERTEX_ATTRIB_FLAG_TEX_COORDS) { - if (_vertexAttribTexCoords) { - cc._renderContext.disableVertexAttribArray(index); - _vertexAttribTexCoords = false; + else if (index === cc.VERTEX_ATTRIB_FLAG_TEX_COORDS) { + if (this._vertexAttribTexCoords) { + this.glDisableVertexAttribArray(index); + this._vertexAttribTexCoords = false; + } } - } - else if (index !== 0) { - cc._renderContext.disableVertexAttribArray(index); - } -} : function (index) { - cc._renderContext.disableVertexAttribArray(index); -}; + else if (index !== 0) { + this.glDisableVertexAttribArray(index); + } + }; +} + +// GL State Cache functions /** * Invalidates the GL state cache.
- * If cc.ENABLE_GL_STATE_CACHE it will reset the GL state cache. + * If CC_ENABLE_GL_STATE_CACHE it will reset the GL state cache. * @function */ cc.glInvalidateStateCache = function () { cc.kmGLFreeAll(); - _currentProjectionMatrix = -1; - if (ENABLE_GL_STATE_CACHE) { - _currentShaderProgram = -1; + cc._currentProjectionMatrix = -1; + if (cc.ENABLE_GL_STATE_CACHE) { + cc._currentShaderProgram = -1; for (var i = 0; i < cc.MAX_ACTIVETEXTURE; i++) { - _currentBoundTexture[i] = -1; + cc._currentBoundTexture[i] = -1; } - _blendingSource = -1; - _blendingDest = -1; - _GLServerState = 0; + cc._blendingSource = -1; + cc._blendingDest = -1; + cc._GLServerState = 0; } }; /** * Uses the GL program in case program is different than the current one.
- * If cc.ENABLE_GL_STATE_CACHE is disabled, it will the glUseProgram() directly. + * If CC_ENABLE_GL_STATE_CACHE is disabled, it will the glUseProgram() directly. * @function * @param {WebGLProgram} program */ -cc.glUseProgram = ENABLE_GL_STATE_CACHE ? function (program) { - if (program !== _currentShaderProgram) { - _currentShaderProgram = program; +cc.glUseProgram = cc.ENABLE_GL_STATE_CACHE ? function (program) { + if (program !== cc._currentShaderProgram) { + cc._currentShaderProgram = program; cc._renderContext.useProgram(program); } } : function (program) { @@ -138,14 +134,14 @@ cc.glUseProgram = ENABLE_GL_STATE_CACHE ? function (program) { /** * Deletes the GL program. If it is the one that is being used, it invalidates it.
- * If cc.ENABLE_GL_STATE_CACHE is disabled, it will the glDeleteProgram() directly. + * If CC_ENABLE_GL_STATE_CACHE is disabled, it will the glDeleteProgram() directly. * @function * @param {WebGLProgram} program */ cc.glDeleteProgram = function (program) { - if (ENABLE_GL_STATE_CACHE) { - if (program === _currentShaderProgram) - _currentShaderProgram = -1; + if (cc.ENABLE_GL_STATE_CACHE) { + if (program === cc._currentShaderProgram) + cc._currentShaderProgram = -1; } gl.deleteProgram(program); }; @@ -169,15 +165,15 @@ cc.setBlending = function (sfactor, dfactor) { /** * Uses a blending function in case it not already used.
- * If cc.ENABLE_GL_STATE_CACHE is disabled, it will the glBlendFunc() directly. + * If CC_ENABLE_GL_STATE_CACHE is disabled, it will the glBlendFunc() directly. * @function * @param {Number} sfactor * @param {Number} dfactor */ -cc.glBlendFunc = ENABLE_GL_STATE_CACHE ? function (sfactor, dfactor) { - if ((sfactor !== _blendingSource) || (dfactor !== _blendingDest)) { - _blendingSource = sfactor; - _blendingDest = dfactor; +cc.glBlendFunc = cc.ENABLE_GL_STATE_CACHE ? function (sfactor, dfactor) { + if ((sfactor !== cc._blendingSource) || (dfactor !== cc._blendingDest)) { + cc._blendingSource = sfactor; + cc._blendingDest = dfactor; cc.setBlending(sfactor, dfactor); } } : cc.setBlending; @@ -188,9 +184,9 @@ cc.glBlendFunc = ENABLE_GL_STATE_CACHE ? function (sfactor, dfactor) { * @param {Number} dfactor */ cc.glBlendFuncForParticle = function(sfactor, dfactor) { - if ((sfactor !== _blendingSource) || (dfactor !== _blendingDest)) { - _blendingSource = sfactor; - _blendingDest = dfactor; + if ((sfactor !== cc._blendingSource) || (dfactor !== cc._blendingDest)) { + cc._blendingSource = sfactor; + cc._blendingDest = dfactor; var ctx = cc._renderContext; if ((sfactor === ctx.ONE) && (dfactor === ctx.ZERO)) { ctx.disable(ctx.BLEND); @@ -204,14 +200,14 @@ cc.glBlendFuncForParticle = function(sfactor, dfactor) { /** * Resets the blending mode back to the cached state in case you used glBlendFuncSeparate() or glBlendEquation().
- * If cc.ENABLE_GL_STATE_CACHE is disabled, it will just set the default blending mode using GL_FUNC_ADD. + * If CC_ENABLE_GL_STATE_CACHE is disabled, it will just set the default blending mode using GL_FUNC_ADD. * @function */ cc.glBlendResetToCache = function () { var ctx = cc._renderContext; ctx.blendEquation(ctx.FUNC_ADD); - if (ENABLE_GL_STATE_CACHE) - cc.setBlending(_blendingSource, _blendingDest); + if (cc.ENABLE_GL_STATE_CACHE) + cc.setBlending(cc._blendingSource, cc._blendingDest); else cc.setBlending(ctx.BLEND_SRC, ctx.BLEND_DST); }; @@ -221,12 +217,12 @@ cc.glBlendResetToCache = function () { * @function */ cc.setProjectionMatrixDirty = function () { - _currentProjectionMatrix = -1; + cc._currentProjectionMatrix = -1; }; /** * If the texture is not already bound, it binds it.
- * If cc.ENABLE_GL_STATE_CACHE is disabled, it will call glBindTexture() directly. + * If CC_ENABLE_GL_STATE_CACHE is disabled, it will call glBindTexture() directly. * @function * @param {cc.Texture2D} textureId */ @@ -236,15 +232,15 @@ cc.glBindTexture2D = function (textureId) { /** * If the texture is not already bound to a given unit, it binds it.
- * If cc.ENABLE_GL_STATE_CACHE is disabled, it will call glBindTexture() directly. + * If CC_ENABLE_GL_STATE_CACHE is disabled, it will call glBindTexture() directly. * @function * @param {Number} textureUnit * @param {cc.Texture2D} textureId */ -cc.glBindTexture2DN = ENABLE_GL_STATE_CACHE ? function (textureUnit, textureId) { - if (_currentBoundTexture[textureUnit] === textureId) +cc.glBindTexture2DN = cc.ENABLE_GL_STATE_CACHE ? function (textureUnit, textureId) { + if (cc._currentBoundTexture[textureUnit] === textureId) return; - _currentBoundTexture[textureUnit] = textureId; + cc._currentBoundTexture[textureUnit] = textureId; var ctx = cc._renderContext; ctx.activeTexture(ctx.TEXTURE0 + textureUnit); @@ -263,7 +259,7 @@ cc.glBindTexture2DN = ENABLE_GL_STATE_CACHE ? function (textureUnit, textureId) /** * It will delete a given texture. If the texture was bound, it will invalidate the cached.
- * If cc.ENABLE_GL_STATE_CACHE is disabled, it will call glDeleteTextures() directly. + * If CC_ENABLE_GL_STATE_CACHE is disabled, it will call glDeleteTextures() directly. * @function * @param {WebGLTexture} textureId */ @@ -273,22 +269,22 @@ cc.glDeleteTexture = function (textureId) { /** * It will delete a given texture. If the texture was bound, it will invalidate the cached for the given texture unit.
- * If cc.ENABLE_GL_STATE_CACHE is disabled, it will call glDeleteTextures() directly. + * If CC_ENABLE_GL_STATE_CACHE is disabled, it will call glDeleteTextures() directly. * @function * @param {Number} textureUnit * @param {WebGLTexture} textureId */ cc.glDeleteTextureN = function (textureUnit, textureId) { - if (ENABLE_GL_STATE_CACHE) { - if (textureId === _currentBoundTexture[ textureUnit ]) - _currentBoundTexture[ textureUnit ] = -1; + if (cc.ENABLE_GL_STATE_CACHE) { + if (textureId === cc._currentBoundTexture[ textureUnit ]) + cc._currentBoundTexture[ textureUnit ] = -1; } cc._renderContext.deleteTexture(textureId._webTextureObj); }; /** * If the vertex array is not already bound, it binds it.
- * If cc.ENABLE_GL_STATE_CACHE is disabled, it will call glBindVertexArray() directly. + * If CC_ENABLE_GL_STATE_CACHE is disabled, it will call glBindVertexArray() directly. * @function * @param {Number} vaoId */ @@ -296,9 +292,9 @@ cc.glBindVAO = function (vaoId) { if (!cc.TEXTURE_ATLAS_USE_VAO) return; - if (ENABLE_GL_STATE_CACHE) { - if (_uVAO !== vaoId) { - _uVAO = vaoId; + if (cc.ENABLE_GL_STATE_CACHE) { + if (cc._uVAO !== vaoId) { + cc._uVAO = vaoId; //TODO need fixed //glBindVertexArray(vaoId); } @@ -309,24 +305,24 @@ cc.glBindVAO = function (vaoId) { /** * It will enable / disable the server side GL states.
- * If cc.ENABLE_GL_STATE_CACHE is disabled, it will call glEnable() directly. + * If CC_ENABLE_GL_STATE_CACHE is disabled, it will call glEnable() directly. * @function * @param {Number} flags */ cc.glEnable = function (flags) { - if (ENABLE_GL_STATE_CACHE) { + if (cc.ENABLE_GL_STATE_CACHE) { /*var enabled; */ /* GL_BLEND */ /* - if ((enabled = (flags & cc.GL_BLEND)) != (_GLServerState & cc.GL_BLEND)) { + if ((enabled = (flags & cc.GL_BLEND)) != (cc._GLServerState & cc.GL_BLEND)) { if (enabled) { cc._renderContext.enable(cc._renderContext.BLEND); - _GLServerState |= cc.GL_BLEND; + cc._GLServerState |= cc.GL_BLEND; } else { cc._renderContext.disable(cc._renderContext.BLEND); - _GLServerState &= ~cc.GL_BLEND; + cc._GLServerState &= ~cc.GL_BLEND; } }*/ } else { @@ -336,5 +332,3 @@ cc.glEnable = function (flags) { cc._renderContext.disable(cc._renderContext.BLEND);*/ } }; - -})(); diff --git a/cocos2d/shape-nodes/CCDrawNode.js b/cocos2d/shape-nodes/CCDrawNode.js index bb101ab904..48cdf4cccc 100644 --- a/cocos2d/shape-nodes/CCDrawNode.js +++ b/cocos2d/shape-nodes/CCDrawNode.js @@ -664,7 +664,7 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () { _render:function () { var gl = cc._renderContext; - cc.glBindBuffer(gl.ARRAY_BUFFER, this._trianglesWebBuffer); + gl.bindBuffer(gl.ARRAY_BUFFER, this._trianglesWebBuffer); if (this._dirty) { gl.bufferData(gl.ARRAY_BUFFER, this._trianglesArrayBuffer, gl.STREAM_DRAW); this._dirty = false; diff --git a/extensions/ccui/uiwidgets/scroll-widget/UIScrollViewWebGLRenderCmd.js b/extensions/ccui/uiwidgets/scroll-widget/UIScrollViewWebGLRenderCmd.js index 11696851d3..413d23aff0 100644 --- a/extensions/ccui/uiwidgets/scroll-widget/UIScrollViewWebGLRenderCmd.js +++ b/extensions/ccui/uiwidgets/scroll-widget/UIScrollViewWebGLRenderCmd.js @@ -40,7 +40,7 @@ this._node.updateChildren(); // Reset buffer for rendering - cc.glBindBuffer(gl.ARRAY_BUFFER, null); + context.bindBuffer(gl.ARRAY_BUFFER, null); for (i = 0, len = locCmds.length; i < len; i++) { cmd = locCmds[i]; From f60dde1e0ff762421c65113e408eb9560d4976ca Mon Sep 17 00:00:00 2001 From: pandamicro Date: Sun, 6 Nov 2016 18:58:42 +0800 Subject: [PATCH 016/206] Fix texture issue on Android browser by always set vertexAttribPointer --- cocos2d/core/renderer/RendererWebGL.js | 16 +++++++--------- cocos2d/shaders/CCGLStateCache.js | 4 ---- 2 files changed, 7 insertions(+), 13 deletions(-) diff --git a/cocos2d/core/renderer/RendererWebGL.js b/cocos2d/core/renderer/RendererWebGL.js index 93c692a5d9..918c175b71 100644 --- a/cocos2d/core/renderer/RendererWebGL.js +++ b/cocos2d/core/renderer/RendererWebGL.js @@ -315,7 +315,7 @@ return { cc.glBlendFunc(_batchedInfo.blendSrc, _batchedInfo.blendDst); cc.glBindTexture2DN(0, texture); // = cc.glBindTexture2D(texture); - var _bufferchanged = !gl.bindBuffer(gl.ARRAY_BUFFER, _quadVertexBuffer); + gl.bindBuffer(gl.ARRAY_BUFFER, _quadVertexBuffer); // upload the vertex data to the gl buffer if (_batchingSize > _vertexSize * 0.5) { gl.bufferData(gl.ARRAY_BUFFER, _vertexDataF32, gl.DYNAMIC_DRAW); @@ -325,14 +325,12 @@ return { gl.bufferData(gl.ARRAY_BUFFER, view, gl.DYNAMIC_DRAW); } - if (_bufferchanged) { - gl.enableVertexAttribArray(cc.VERTEX_ATTRIB_POSITION); - gl.enableVertexAttribArray(cc.VERTEX_ATTRIB_COLOR); - gl.enableVertexAttribArray(cc.VERTEX_ATTRIB_TEX_COORDS); - gl.vertexAttribPointer(cc.VERTEX_ATTRIB_POSITION, 3, gl.FLOAT, false, 24, 0); - gl.vertexAttribPointer(cc.VERTEX_ATTRIB_COLOR, 4, gl.UNSIGNED_BYTE, true, 24, 12); - gl.vertexAttribPointer(cc.VERTEX_ATTRIB_TEX_COORDS, 2, gl.FLOAT, false, 24, 16); - } + gl.enableVertexAttribArray(cc.VERTEX_ATTRIB_POSITION); + gl.enableVertexAttribArray(cc.VERTEX_ATTRIB_COLOR); + gl.enableVertexAttribArray(cc.VERTEX_ATTRIB_TEX_COORDS); + gl.vertexAttribPointer(cc.VERTEX_ATTRIB_POSITION, 3, gl.FLOAT, false, 24, 0); + gl.vertexAttribPointer(cc.VERTEX_ATTRIB_COLOR, 4, gl.UNSIGNED_BYTE, true, 24, 12); + gl.vertexAttribPointer(cc.VERTEX_ATTRIB_TEX_COORDS, 2, gl.FLOAT, false, 24, 16); gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, _quadIndexBuffer); gl.drawElements(gl.TRIANGLES, count * 6, gl.UNSIGNED_SHORT, 0); diff --git a/cocos2d/shaders/CCGLStateCache.js b/cocos2d/shaders/CCGLStateCache.js index 127bc2d711..edcf86c3b8 100644 --- a/cocos2d/shaders/CCGLStateCache.js +++ b/cocos2d/shaders/CCGLStateCache.js @@ -44,10 +44,6 @@ if (cc.ENABLE_GL_STATE_CACHE) { if (_currBuffers[target] !== buffer) { this.glBindBuffer(target, buffer); _currBuffers[target] = buffer; - return false; - } - else { - return true; } }; From 2032c3a97dd7d476d9d9dc425f6a475bf4e3a1e8 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Mon, 7 Nov 2016 15:53:27 +0800 Subject: [PATCH 017/206] Improve performance for transform by removing recursive logic --- .../core/base-nodes/CCNodeCanvasRenderCmd.js | 107 +++++++++++------- 1 file changed, 66 insertions(+), 41 deletions(-) diff --git a/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js b/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js index 768998f8d2..27ed094b7b 100644 --- a/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js +++ b/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js @@ -38,7 +38,7 @@ cc.CustomRenderCmd = function (target, func) { }; }; -cc.Node._dirtyFlags = { +var dirtyFlags = cc.Node._dirtyFlags = { transformDirty: 1 << 0, visibleDirty: 1 << 1, colorDirty: 1 << 2, opacityDirty: 1 << 3, cacheDirty: 1 << 4, orderDirty: 1 << 5, textDirty: 1 << 6, gradientDirty: 1 << 7, textureDirty: 1 << 8, contentDirty: 1 << 9, @@ -46,6 +46,32 @@ cc.Node._dirtyFlags = { all: (1 << 10) - 1 }; +var ONE_DEGREE = Math.PI / 180; +var stack = new Array(50); + +function transformChildTree (root) { + var index = 1; + var children, child, curr, parentCmd, i, len; + stack[0] = root; + while (index) { + index--; + curr = stack[index]; + // Avoid memory leak + stack[index] = null; + if (!curr) continue; + children = curr._children; + if (children && children.length > 0) { + parentCmd = curr._renderCmd; + for (i = 0, len = children.length; i < len; ++i) { + child = children[i]; + stack[index] = child; + index++; + child._renderCmd.transform(parentCmd); + } + } + } +} + //-------------------------Base ------------------------- cc.Node.RenderCmd = function (renderable) { this._dirtyFlag = 1; //need update the transform at first. @@ -150,7 +176,7 @@ cc.Node.RenderCmd.prototype = { // rotation if (hasRotation) { - var rotationRadiansX = node._rotationX * 0.017453292519943295; //0.017453292519943295 = (Math.PI / 180); for performance + var rotationRadiansX = node._rotationX * ONE_DEGREE; c = Math.sin(rotationRadiansX); d = Math.cos(rotationRadiansX); if (node._rotationY === node._rotationX) { @@ -158,7 +184,7 @@ cc.Node.RenderCmd.prototype = { b = -c; } else { - var rotationRadiansY = node._rotationY * 0.017453292519943295; //0.017453292519943295 = (Math.PI / 180); for performance + var rotationRadiansY = node._rotationY * ONE_DEGREE; a = Math.cos(rotationRadiansY); b = -Math.sin(rotationRadiansY); } @@ -172,8 +198,8 @@ cc.Node.RenderCmd.prototype = { // skew if (hasSkew) { - var skx = Math.tan(node._skewX * Math.PI / 180); - var sky = Math.tan(node._skewY * Math.PI / 180); + var skx = Math.tan(node._skewX * ONE_DEGREE); + var sky = Math.tan(node._skewY * ONE_DEGREE); if (skx === Infinity) skx = 99999999; if (sky === Infinity) @@ -250,17 +276,13 @@ cc.Node.RenderCmd.prototype = { this._transform = cc.affineTransformConcat(t, node._additionalTransform); } - this._updateCurrentRegions && this._updateCurrentRegions(); - this._notifyRegionStatus && this._notifyRegionStatus(cc.Node.CanvasRenderCmd.RegionStatus.DirtyDouble); + if (this._updateCurrentRegions) { + this._updateCurrentRegions(); + this._notifyRegionStatus && this._notifyRegionStatus(cc.Node.CanvasRenderCmd.RegionStatus.DirtyDouble); + } if (recursive) { - var locChildren = this._node._children; - if (!locChildren || locChildren.length === 0) - return; - var i, len; - for (i = 0, len = locChildren.length; i < len; i++) { - locChildren[i]._renderCmd.transform(this, recursive); - } + transformChildTree(node); } this._cacheDirty = true; @@ -331,7 +353,7 @@ cc.Node.RenderCmd.prototype = { } } } - this._dirtyFlag = this._dirtyFlag & cc.Node._dirtyFlags.colorDirty ^ this._dirtyFlag; + this._dirtyFlag &= ~dirtyFlags.colorDirty; }, _updateDisplayOpacity: function (parentOpacity) { @@ -366,7 +388,7 @@ cc.Node.RenderCmd.prototype = { } } } - this._dirtyFlag = this._dirtyFlag & cc.Node._dirtyFlags.opacityDirty ^ this._dirtyFlag; + this._dirtyFlag &= ~dirtyFlags.opacityDirty; }, _syncDisplayColor: function (parentColor) { @@ -394,14 +416,17 @@ cc.Node.RenderCmd.prototype = { this._displayedOpacity = node._realOpacity * parentOpacity / 255.0; }, - _updateColor: function () { - }, + _updateColor: function(){}, updateStatus: function () { - var flags = cc.Node._dirtyFlags, locFlag = this._dirtyFlag; - var colorDirty = locFlag & flags.colorDirty, - opacityDirty = locFlag & flags.opacityDirty; - this._savedDirtyFlag = this._savedDirtyFlag || locFlag; + var locFlag = this._dirtyFlag; + var colorDirty = locFlag & dirtyFlags.colorDirty, + opacityDirty = locFlag & dirtyFlags.opacityDirty; + + if (locFlag & dirtyFlags.contentDirty) { + this._notifyRegionStatus && this._notifyRegionStatus(_ccsg.Node.CanvasRenderCmd.RegionStatus.Dirty); + this._dirtyFlag &= ~dirtyFlags.contentDirty; + } if (colorDirty) this._updateDisplayColor(); @@ -412,20 +437,20 @@ cc.Node.RenderCmd.prototype = { if (colorDirty || opacityDirty) this._updateColor(); - if (locFlag & flags.transformDirty) { + if (locFlag & dirtyFlags.transformDirty) { //update the transform this.transform(this.getParentRenderCmd(), true); - this._dirtyFlag = this._dirtyFlag & flags.transformDirty ^ this._dirtyFlag; + this._dirtyFlag &= ~dirtyFlags.transformDirty; } - if (locFlag & flags.orderDirty) - this._dirtyFlag = this._dirtyFlag & flags.orderDirty ^ this._dirtyFlag; + if (locFlag & dirtyFlags.orderDirty) + this._dirtyFlag &= ~dirtyFlags.orderDirty; }, _syncStatus: function (parentCmd) { // In the visit logic does not restore the _dirtyFlag // Because child elements need parent's _dirtyFlag to change himself - var flags = cc.Node._dirtyFlags, locFlag = this._dirtyFlag, parentNode = null; + var locFlag = this._dirtyFlag, parentNode = null; if (parentCmd) { parentNode = parentCmd._node; this._savedDirtyFlag = this._savedDirtyFlag || parentCmd._savedDirtyFlag || locFlag; @@ -440,37 +465,37 @@ cc.Node.RenderCmd.prototype = { // But while the child element does not enter the circulation // Here will be reset state in last // In order the child elements get the parent state - if (parentNode && parentNode._cascadeColorEnabled && (parentCmd._dirtyFlag & flags.colorDirty)) - locFlag |= flags.colorDirty; + if (parentNode && parentNode._cascadeColorEnabled && (parentCmd._dirtyFlag & dirtyFlags.colorDirty)) + locFlag |= dirtyFlags.colorDirty; - if (parentNode && parentNode._cascadeOpacityEnabled && (parentCmd._dirtyFlag & flags.opacityDirty)) - locFlag |= flags.opacityDirty; + if (parentNode && parentNode._cascadeOpacityEnabled && (parentCmd._dirtyFlag & dirtyFlags.opacityDirty)) + locFlag |= dirtyFlags.opacityDirty; - if (parentCmd && (parentCmd._dirtyFlag & flags.transformDirty)) - locFlag |= flags.transformDirty; + if (parentCmd && (parentCmd._dirtyFlag & dirtyFlags.transformDirty)) + locFlag |= dirtyFlags.transformDirty; - var colorDirty = locFlag & flags.colorDirty, - opacityDirty = locFlag & flags.opacityDirty; + var colorDirty = locFlag & dirtyFlags.colorDirty, + opacityDirty = locFlag & dirtyFlags.opacityDirty; this._dirtyFlag = locFlag; if (colorDirty) - //update the color + //update the color this._syncDisplayColor(); if (opacityDirty) - //update the opacity + //update the opacity this._syncDisplayOpacity(); if (colorDirty || opacityDirty) this._updateColor(); - if (locFlag & flags.transformDirty) + if (locFlag & dirtyFlags.transformDirty) //update the transform this.transform(parentCmd); - if (locFlag & flags.orderDirty) - this._dirtyFlag = this._dirtyFlag & flags.orderDirty ^ this._dirtyFlag; + if (locFlag & dirtyFlags.orderDirty) + this._dirtyFlag &= ~dirtyFlags.orderDirty; }, visitChildren: function () { @@ -612,4 +637,4 @@ cc.Node.RenderCmd.prototype.originTransform = cc.Node.RenderCmd.prototype.transf return "source-over"; } }; -})(); \ No newline at end of file +})(); 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 018/206] 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 019/206] 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 020/206] 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 021/206] 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 022/206] 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 023/206] 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 024/206] 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 025/206] 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 026/206] 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 027/206] 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 028/206] 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 029/206] 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 030/206] 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 031/206] 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 032/206] 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 033/206] 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 034/206] 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 035/206] 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 036/206] 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 037/206] 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 038/206] 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 039/206] 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 040/206] 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 041/206] 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 042/206] 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 043/206] 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 044/206] 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 045/206] 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 046/206] 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 047/206] 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 048/206] 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 049/206] 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 050/206] 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 051/206] 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 052/206] 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 053/206] 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 054/206] 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 055/206] 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 056/206] 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 057/206] 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 058/206] 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]; }; })(); From 10e501b638c66dd3c87f892e9bb7595087837c67 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Tue, 13 Dec 2016 14:39:07 +0800 Subject: [PATCH 059/206] Fix CCClass issue in release mode --- cocos2d/core/platform/CCClass.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos2d/core/platform/CCClass.js b/cocos2d/core/platform/CCClass.js index 1916135594..6b7a2e8043 100644 --- a/cocos2d/core/platform/CCClass.js +++ b/cocos2d/core/platform/CCClass.js @@ -190,7 +190,7 @@ var ClassManager = { // The dummy Class constructor var Class; - if (cc.game.config[cc.game.CONFIG_KEY.exposeClassName]) { + if (cc.game.config && 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"; From 4ed7dc52a22edfd8305d5c1c110c0e26979dcc84 Mon Sep 17 00:00:00 2001 From: David DeSimone Date: Tue, 13 Dec 2016 14:30:06 -0800 Subject: [PATCH 060/206] Porting CCGLProgramState to cocos2d-html5. This will now give the user the ability to bind multiple texture uniforms to a single shader program. It will also allow users to have late-bound uniforms via a callback. --- cocos2d/core/CCDrawingPrimitivesWebGL.js | 18 +- .../base-nodes/CCAtlasNodeWebGLRenderCmd.js | 3 +- cocos2d/core/base-nodes/CCNode.js | 8 + .../core/base-nodes/CCNodeCanvasRenderCmd.js | 26 +- .../core/base-nodes/CCNodeWebGLRenderCmd.js | 22 +- cocos2d/core/layers/CCLayerWebGLRenderCmd.js | 6 +- cocos2d/core/platform/CCMacro.js | 2 +- cocos2d/core/renderer/RendererWebGL.js | 18 +- cocos2d/core/textures/TexturesWebGL.js | 6 +- cocos2d/effects/CCGrid.js | 8 +- .../CCMotionStreakWebGLRenderCmd.js | 3 +- .../CCParticleBatchNodeWebGLRenderCmd.js | 3 +- .../CCParticleSystemWebGLRenderCmd.js | 3 +- .../CCPhysicsDebugNodeWebGLRenderCmd.js | 3 +- .../CCProgressTimerWebGLRenderCmd.js | 2 +- cocos2d/shaders/CCGLProgram.js | 16 +- cocos2d/shaders/CCGLProgramState.js | 325 ++++++++++++++++++ .../shape-nodes/CCDrawNodeWebGLRenderCmd.js | 3 +- moduleConfig.json | 1 + 19 files changed, 417 insertions(+), 59 deletions(-) create mode 100644 cocos2d/shaders/CCGLProgramState.js diff --git a/cocos2d/core/CCDrawingPrimitivesWebGL.js b/cocos2d/core/CCDrawingPrimitivesWebGL.js index f8c9b46d0d..e6fc9b7262 100644 --- a/cocos2d/core/CCDrawingPrimitivesWebGL.js +++ b/cocos2d/core/CCDrawingPrimitivesWebGL.js @@ -81,7 +81,7 @@ cc.DrawingPrimitiveWebGL = cc.Class.extend(/** @lends cc.DrawingPrimitiveWebGL# this.lazy_init(); var glContext = this._renderContext; - this._shader.use(); + this._glProgramState.apply(); this._shader.setUniformForModelViewAndProjectionMatrixWithMat4(); glContext.enableVertexAttribArray(cc.VERTEX_ATTRIB_POSITION); this._shader.setUniformLocationWith4fv(this._colorLocation, this._colorArray); @@ -110,7 +110,7 @@ cc.DrawingPrimitiveWebGL = cc.Class.extend(/** @lends cc.DrawingPrimitiveWebGL# this.lazy_init(); var glContext = this._renderContext; - this._shader.use(); + this._glProgramState.apply(); this._shader.setUniformForModelViewAndProjectionMatrixWithMat4(); glContext.enableVertexAttribArray(cc.VERTEX_ATTRIB_POSITION); this._shader.setUniformLocationWith4fv(this._colorLocation, this._colorArray); @@ -145,7 +145,7 @@ cc.DrawingPrimitiveWebGL = cc.Class.extend(/** @lends cc.DrawingPrimitiveWebGL# this.lazy_init(); var glContext = this._renderContext; - this._shader.use(); + this._glProgramState.apply(); this._shader.setUniformForModelViewAndProjectionMatrixWithMat4(); glContext.enableVertexAttribArray(cc.VERTEX_ATTRIB_POSITION); this._shader.setUniformLocationWith4fv(this._colorLocation, this._colorArray); @@ -200,7 +200,7 @@ cc.DrawingPrimitiveWebGL = cc.Class.extend(/** @lends cc.DrawingPrimitiveWebGL# this.lazy_init(); var glContext = this._renderContext; - this._shader.use(); + this._glProgramState.apply(); this._shader.setUniformForModelViewAndProjectionMatrixWithMat4(); glContext.enableVertexAttribArray(cc.VERTEX_ATTRIB_POSITION); this._shader.setUniformLocationWith4fv(this._colorLocation, this._colorArray); @@ -231,7 +231,7 @@ cc.DrawingPrimitiveWebGL = cc.Class.extend(/** @lends cc.DrawingPrimitiveWebGL# this.setDrawColor(color.r, color.g, color.b, color.a); var glContext = this._renderContext; - this._shader.use(); + this._glProgramState.apply(); this._shader.setUniformForModelViewAndProjectionMatrixWithMat4(); glContext.enableVertexAttribArray(cc.VERTEX_ATTRIB_POSITION); this._shader.setUniformLocationWith4fv(this._colorLocation, this._colorArray); @@ -279,7 +279,7 @@ cc.DrawingPrimitiveWebGL = cc.Class.extend(/** @lends cc.DrawingPrimitiveWebGL# vertices[(segments + 1) * 2 + 1] = center.y; var glContext = this._renderContext; - this._shader.use(); + this._glProgramState.apply(); this._shader.setUniformForModelViewAndProjectionMatrixWithMat4(); glContext.enableVertexAttribArray(cc.VERTEX_ATTRIB_POSITION); this._shader.setUniformLocationWith4fv(this._colorLocation, this._colorArray); @@ -317,7 +317,7 @@ cc.DrawingPrimitiveWebGL = cc.Class.extend(/** @lends cc.DrawingPrimitiveWebGL# vertices[segments * 2 + 1] = destination.y; var glContext = this._renderContext; - this._shader.use(); + this._glProgramState.apply(); this._shader.setUniformForModelViewAndProjectionMatrixWithMat4(); glContext.enableVertexAttribArray(cc.VERTEX_ATTRIB_POSITION); this._shader.setUniformLocationWith4fv(this._colorLocation, this._colorArray); @@ -356,7 +356,7 @@ cc.DrawingPrimitiveWebGL = cc.Class.extend(/** @lends cc.DrawingPrimitiveWebGL# vertices[segments * 2 + 1] = destination.y; var glContext = this._renderContext; - this._shader.use(); + this._glProgramState.apply(); this._shader.setUniformForModelViewAndProjectionMatrixWithMat4(); glContext.enableVertexAttribArray(cc.VERTEX_ATTRIB_POSITION); this._shader.setUniformLocationWith4fv(this._colorLocation, this._colorArray); @@ -416,7 +416,7 @@ cc.DrawingPrimitiveWebGL = cc.Class.extend(/** @lends cc.DrawingPrimitiveWebGL# } var glContext = this._renderContext; - this._shader.use(); + this._glProgramState.apply(); this._shader.setUniformForModelViewAndProjectionMatrixWithMat4(); glContext.enableVertexAttribArray(cc.VERTEX_ATTRIB_POSITION); this._shader.setUniformLocationWith4fv(this._colorLocation, this._colorArray); diff --git a/cocos2d/core/base-nodes/CCAtlasNodeWebGLRenderCmd.js b/cocos2d/core/base-nodes/CCAtlasNodeWebGLRenderCmd.js index 8fce00f8da..5810d00794 100644 --- a/cocos2d/core/base-nodes/CCAtlasNodeWebGLRenderCmd.js +++ b/cocos2d/core/base-nodes/CCAtlasNodeWebGLRenderCmd.js @@ -68,8 +68,7 @@ this._matrix.mat[5] = wt.d; this._matrix.mat[13] = wt.ty; - this._shaderProgram.use(); - this._shaderProgram._setUniformForMVPMatrixWithMat4(this._matrix); + this._glProgramState.apply(this._matrix); cc.glBlendFunc(node._blendFunc.src, node._blendFunc.dst); if (this._uniformColor && this._colorF32Array) { diff --git a/cocos2d/core/base-nodes/CCNode.js b/cocos2d/core/base-nodes/CCNode.js index 4f05484c47..50068dbbef 100644 --- a/cocos2d/core/base-nodes/CCNode.js +++ b/cocos2d/core/base-nodes/CCNode.js @@ -2228,6 +2228,14 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{ this._renderCmd.setShaderProgram(newShaderProgram); }, + setGLProgramState: function (glProgramState) { + this._renderCmd.setGLProgramState(glProgramState); + }, + + getGLProgramState: function () { + return this._renderCmd.getGLProgramState(); + }, + /** * Returns the state of OpenGL server side. * @function diff --git a/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js b/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js index 49308ef008..b7e53eaf39 100644 --- a/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js +++ b/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js @@ -513,7 +513,23 @@ cc.Node.RenderCmd.prototype = { if (locFlag & dirtyFlags.orderDirty) this._dirtyFlag &= ~dirtyFlags.orderDirty; - } + }, + + setShaderProgram: function (shaderProgram) { + //do nothing. + }, + + getShaderProgram: function () { + return null; + }, + + getGLProgramState: function () { + return null; + }, + + setGLProgramState: function (glProgramState) { + // do nothing + }, }; cc.Node.RenderCmd.prototype.originTransform = cc.Node.RenderCmd.prototype.transform; @@ -607,14 +623,6 @@ cc.Node.RenderCmd.prototype._originSyncStatus = cc.Node.RenderCmd.prototype._syn } }; - proto.setShaderProgram = function (shaderProgram) { - //do nothing. - }; - - proto.getShaderProgram = function () { - return null; - }; - //util functions cc.Node.CanvasRenderCmd._getCompositeOperationByBlendFunc = function (blendFunc) { if (!blendFunc) diff --git a/cocos2d/core/base-nodes/CCNodeWebGLRenderCmd.js b/cocos2d/core/base-nodes/CCNodeWebGLRenderCmd.js index 62e469800e..68a3968b90 100644 --- a/cocos2d/core/base-nodes/CCNodeWebGLRenderCmd.js +++ b/cocos2d/core/base-nodes/CCNodeWebGLRenderCmd.js @@ -27,7 +27,7 @@ this._node = renderable; this._anchorPointInPoints = {x: 0, y: 0}; this._displayedColor = cc.color(255, 255, 255, 255); - this._shaderProgram = null; + this._glProgramState = null; }; var proto = cc.Node.WebGLRenderCmd.prototype = Object.create(cc.Node.RenderCmd.prototype); @@ -38,10 +38,26 @@ }; proto.setShaderProgram = function (shaderProgram) { - this._shaderProgram = shaderProgram; + this._glProgramState = cc.GLProgramState.getOrCreateWithGLProgram(shaderProgram); }; proto.getShaderProgram = function () { - return this._shaderProgram; + return this._glProgramState ? this._glProgramState.getGLProgram() : null; }; + + proto.getGLProgramState = function () { + return this._glProgramState; + }; + + proto.setGLProgramState = function (glProgramState) { + this._glProgramState = glProgramState; + }; + + // Use a property getter/setter for backwards compatability, and + // to ease the transition from using glPrograms directly, to + // using glProgramStates. + Object.defineProperty(proto, '_shaderProgram', { + set: function () { this.setShaderProgram.apply(this, arguments); }, + get: function () { return this.getShaderProgram(); } + }); })(); diff --git a/cocos2d/core/layers/CCLayerWebGLRenderCmd.js b/cocos2d/core/layers/CCLayerWebGLRenderCmd.js index ea60a3c70f..a18dd6f9fc 100644 --- a/cocos2d/core/layers/CCLayerWebGLRenderCmd.js +++ b/cocos2d/core/layers/CCLayerWebGLRenderCmd.js @@ -97,8 +97,7 @@ this._matrix.mat[5] = wt.d; this._matrix.mat[13] = wt.ty; - this._shaderProgram.use(); - this._shaderProgram._setUniformForMVPMatrixWithMat4(this._matrix); + this._glProgramState.apply(this._matrix); context.enableVertexAttribArray(cc.VERTEX_ATTRIB_POSITION); context.enableVertexAttribArray(cc.VERTEX_ATTRIB_COLOR); cc.glBlendFunc(node._blendFunc.src, node._blendFunc.dst); @@ -311,8 +310,7 @@ this._matrix.mat[13] = wt.ty; //draw gradient layer - this._shaderProgram.use(); - this._shaderProgram._setUniformForMVPMatrixWithMat4(this._matrix); + this._glProgramState.apply(this._matrix); context.enableVertexAttribArray(cc.VERTEX_ATTRIB_POSITION); context.enableVertexAttribArray(cc.VERTEX_ATTRIB_COLOR); cc.glBlendFunc(node._blendFunc.src, node._blendFunc.dst); diff --git a/cocos2d/core/platform/CCMacro.js b/cocos2d/core/platform/CCMacro.js index e5e4e3c609..71a367618a 100644 --- a/cocos2d/core/platform/CCMacro.js +++ b/cocos2d/core/platform/CCMacro.js @@ -175,7 +175,7 @@ cc.nodeDrawSetup = function (node) { //cc.glEnable(node._glServerState); if (node._shaderProgram) { //cc._renderContext.useProgram(node._shaderProgram._programObj); - node._shaderProgram.use(); + node._glProgramState.apply(); node._shaderProgram.setUniformForModelViewAndProjectionMatrixWithMat4(); } }; diff --git a/cocos2d/core/renderer/RendererWebGL.js b/cocos2d/core/renderer/RendererWebGL.js index 593a4434ef..38f6ce4f66 100644 --- a/cocos2d/core/renderer/RendererWebGL.js +++ b/cocos2d/core/renderer/RendererWebGL.js @@ -33,8 +33,8 @@ var _batchedInfo = { blendSrc: null, // The batched blend destination, all batching element should have the same blend destination blendDst: null, - // The batched shader, all batching element should have the same shader - shader: null + // The batched glProgramState, all batching element should have the same glProgramState + glProgramState: null }, _quadIndexBuffer = null, @@ -280,18 +280,18 @@ return { } var blendSrc = node._blendFunc.src; var blendDst = node._blendFunc.dst; - var shader = cmd._shaderProgram; + var glProgramState = cmd._glProgramState; if (_batchedInfo.texture !== texture || _batchedInfo.blendSrc !== blendSrc || _batchedInfo.blendDst !== blendDst || - _batchedInfo.shader !== shader) { + _batchedInfo.glProgramState !== glProgramState) { // Draw batched elements this._batchRendering(); // Update _batchedInfo _batchedInfo.texture = texture; _batchedInfo.blendSrc = blendSrc; _batchedInfo.blendDst = blendDst; - _batchedInfo.shader = shader; + _batchedInfo.glProgramState = glProgramState; } // Upload vertex data @@ -308,12 +308,12 @@ return { var gl = cc._renderContext; var texture = _batchedInfo.texture; - var shader = _batchedInfo.shader; + var glProgramState = _batchedInfo.glProgramState; var count = _batchingSize / 4; - if (shader) { - shader.use(); - shader._updateProjectionUniform(); + if (glProgramState) { + glProgramState.apply(); + glProgramState.getGLProgram()._updateProjectionUniform(); } cc.glBlendFunc(_batchedInfo.blendSrc, _batchedInfo.blendDst); diff --git a/cocos2d/core/textures/TexturesWebGL.js b/cocos2d/core/textures/TexturesWebGL.js index bcec5bfb53..49a33ae647 100644 --- a/cocos2d/core/textures/TexturesWebGL.js +++ b/cocos2d/core/textures/TexturesWebGL.js @@ -339,8 +339,7 @@ cc._tmp.WebGLTexture2D = function () { point.x, height + point.y, 0.0, width + point.x, height + point.y, 0.0]; - self._shaderProgram.use(); - self._shaderProgram.setUniformsForBuiltins(); + self._glProgramState.apply(); cc.glBindTexture2D(self); @@ -369,8 +368,7 @@ cc._tmp.WebGLTexture2D = function () { rect.x, rect.y + rect.height, /*0.0,*/ rect.x + rect.width, rect.y + rect.height /*0.0*/]; - self._shaderProgram.use(); - self._shaderProgram.setUniformsForBuiltins(); + self._glProgramState.apply(); cc.glBindTexture2D(self); diff --git a/cocos2d/effects/CCGrid.js b/cocos2d/effects/CCGrid.js index f6459a2269..84e08be6af 100644 --- a/cocos2d/effects/CCGrid.js +++ b/cocos2d/effects/CCGrid.js @@ -443,9 +443,7 @@ cc.Grid3D = cc.GridBase.extend(/** @lends cc.Grid3D# */{ this._matrix.mat[5] = wt.d; this._matrix.mat[13] = wt.ty; - this._shaderProgram.use(); - //this._shaderProgram.setUniformsForBuiltins(); - this._shaderProgram._setUniformForMVPMatrixWithMat4(this._matrix); + this._glProgramState.apply(this._matrix); var gl = cc._renderContext, locDirty = this._dirty; @@ -714,9 +712,7 @@ cc.TiledGrid3D = cc.GridBase.extend(/** @lends cc.TiledGrid3D# */{ this._matrix.mat[5] = wt.d; this._matrix.mat[13] = wt.ty; - this._shaderProgram.use(); - this._shaderProgram._setUniformForMVPMatrixWithMat4(this._matrix); - //this._shaderProgram.setUniformsForBuiltins(); + this._glProgramState.apply(this._matrix); // // Attributes diff --git a/cocos2d/motion-streak/CCMotionStreakWebGLRenderCmd.js b/cocos2d/motion-streak/CCMotionStreakWebGLRenderCmd.js index e2d74f574a..a7d793a336 100644 --- a/cocos2d/motion-streak/CCMotionStreakWebGLRenderCmd.js +++ b/cocos2d/motion-streak/CCMotionStreakWebGLRenderCmd.js @@ -49,8 +49,7 @@ cc.MotionStreak.WebGLRenderCmd.prototype.rendering = function (ctx) { this._matrix.mat[5] = wt.d; this._matrix.mat[13] = wt.ty; - this._shaderProgram.use(); - this._shaderProgram._setUniformForMVPMatrixWithMat4(this._matrix); + this._glProgramState.apply(this._matrix); cc.glBlendFunc(node._blendFunc.src, node._blendFunc.dst); cc.glBindTexture2D(node.texture); diff --git a/cocos2d/particle/CCParticleBatchNodeWebGLRenderCmd.js b/cocos2d/particle/CCParticleBatchNodeWebGLRenderCmd.js index 3dda639728..765e7553ad 100644 --- a/cocos2d/particle/CCParticleBatchNodeWebGLRenderCmd.js +++ b/cocos2d/particle/CCParticleBatchNodeWebGLRenderCmd.js @@ -49,8 +49,7 @@ this._matrix.mat[5] = wt.d; this._matrix.mat[13] = wt.ty; - this._shaderProgram.use(); - this._shaderProgram._setUniformForMVPMatrixWithMat4(this._matrix); + this._glProgramState.apply(this._matrix); cc.glBlendFuncForParticle(_t._blendFunc.src, _t._blendFunc.dst); _t.textureAtlas.drawQuads(); }; diff --git a/cocos2d/particle/CCParticleSystemWebGLRenderCmd.js b/cocos2d/particle/CCParticleSystemWebGLRenderCmd.js index 892f8a2d21..54b1236119 100644 --- a/cocos2d/particle/CCParticleSystemWebGLRenderCmd.js +++ b/cocos2d/particle/CCParticleSystemWebGLRenderCmd.js @@ -204,8 +204,7 @@ this._matrix.mat[5] = wt.d; this._matrix.mat[13] = wt.ty; - this._shaderProgram.use(); - this._shaderProgram._setUniformForMVPMatrixWithMat4(this._matrix); //; + this._glProgramState.apply(this._matrix); cc.glBindTexture2D(node._texture); cc.glBlendFuncForParticle(node._blendFunc.src, node._blendFunc.dst); diff --git a/cocos2d/physics/CCPhysicsDebugNodeWebGLRenderCmd.js b/cocos2d/physics/CCPhysicsDebugNodeWebGLRenderCmd.js index 1c2a9fb69a..0b8a18504c 100644 --- a/cocos2d/physics/CCPhysicsDebugNodeWebGLRenderCmd.js +++ b/cocos2d/physics/CCPhysicsDebugNodeWebGLRenderCmd.js @@ -54,8 +54,7 @@ //cc.DrawNode.prototype.draw.call(node); cc.glBlendFunc(node._blendFunc.src, node._blendFunc.dst); - this._shaderProgram.use(); - this._shaderProgram._setUniformForMVPMatrixWithMat4(this._matrix); + this._glProgramState.apply(this._matrix); node._render(); node.clear(); diff --git a/cocos2d/progress-timer/CCProgressTimerWebGLRenderCmd.js b/cocos2d/progress-timer/CCProgressTimerWebGLRenderCmd.js index 8ee5a7da1a..c78b0d5f9d 100644 --- a/cocos2d/progress-timer/CCProgressTimerWebGLRenderCmd.js +++ b/cocos2d/progress-timer/CCProgressTimerWebGLRenderCmd.js @@ -64,7 +64,7 @@ if (this._vertexDataCount === 0 || !node._sprite) return; - this._shaderProgram.use(); + this._glProgramState.apply(); this._shaderProgram._updateProjectionUniform(); var blendFunc = node._sprite._blendFunc; diff --git a/cocos2d/shaders/CCGLProgram.js b/cocos2d/shaders/CCGLProgram.js index d9e59b109d..c7c191fa76 100644 --- a/cocos2d/shaders/CCGLProgram.js +++ b/cocos2d/shaders/CCGLProgram.js @@ -116,6 +116,7 @@ cc.GLProgram = cc.Class.extend(/** @lends cc.GLProgram# */{ ctor: function (vShaderFileName, fShaderFileName, glContext) { this._uniforms = {}; this._hashForUniforms = {}; + this._userUniforms = {}; this._glContext = glContext || cc._renderContext; vShaderFileName && fShaderFileName && this.init(vShaderFileName, fShaderFileName); @@ -231,7 +232,8 @@ cc.GLProgram = cc.Class.extend(/** @lends cc.GLProgram# */{ } this._glContext.linkProgram(this._programObj); - + this._parseUniforms(); + if (this._vertShader) this._glContext.deleteShader(this._vertShader); if (this._fragShader) @@ -253,6 +255,18 @@ cc.GLProgram = cc.Class.extend(/** @lends cc.GLProgram# */{ return true; }, + _parseUniforms: function _parseUniforms() { + var activeUniforms = this._glContext.getProgramParameter(this._programObj, this._glContext.ACTIVE_UNIFORMS); + for (var i = 0; i < activeUniforms; ++i) { + var uniform = this._glContext.getActiveUniform(this._programObj, i); + uniform.location = this._glContext.getUniformLocation(this._programObj, uniform.name); + if (uniform.name.indexOf("CC_") !== 0) { + uniform.location = this._glContext.getUniformLocation(this._programObj, uniform.name); + uniform.name = uniform.name.replace("[]", ""); + this._userUniforms[uniform.name] = uniform; + } + } + }, /** * it will call glUseProgram() */ diff --git a/cocos2d/shaders/CCGLProgramState.js b/cocos2d/shaders/CCGLProgramState.js new file mode 100644 index 0000000000..6457d180fb --- /dev/null +++ b/cocos2d/shaders/CCGLProgramState.js @@ -0,0 +1,325 @@ +/**************************************************************************** + 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. + ****************************************************************************/ + +// @TODO add floatv and intv methods, that take arrays +// and float1..4 methods, which take arguments. + +var types = + { + GL_FLOAT: 0, + GL_INT: 1, + GL_FLOAT_VEC2: 2, + GL_FLOAT_VEC3: 3, + GL_FLOAT_VEC4: 4, + GL_FLOAT_MAT4: 5, + GL_CALLBACK: 6, + GL_TEXTURE: 7 + }; + +cc.UniformValue = cc.Class.extend({ + _uniform: null, + _glprogram: null, + _value: null, + _type: -1, + + ctor: function ctor(uniform, glprogram) { + this._uniform = uniform; + this._glprogram = glprogram; + }, + + setFloat: function setFloat(value) { + this._value = value; + this._type = types.GL_FLOAT; + }, + + setInt: function setInt(value) { + this._value = value; + this._type = types.GL_INT; + }, + + setVec2: function setVec2(v1, v2) { + this._value = [v1, v2]; + this._type = types.GL_FLOAT_VEC2; + }, + + setVec2v: function setVec2v(value) { + this._value = value; + this._type = types.GL_FLOAT_VEC2; + }, + + setVec3: function setVec3(v1, v2, v3) { + this._value = [v1, v2, v3]; + this._type = types.GL_FLOAT_VEC3; + }, + + setVec3v: function setVec3v(value) { + this._value = value; + this._type = types.GL_FLOAT_VEC3; + }, + + setVec4: function setVec4(v1, v2, v3, v4) { + this._value = [v1, v2, v3, v4]; + this._type = types.GL_FLOAT_VEC4; + }, + + setVec4v: function setVec4v(value) { + this._value = value; + this._type = types.GL_FLOAT_VEC4; + }, + + setMat4: function setMat4(value) { + this._value = value; + this._type = types.GL_FLOAT_MAT4; + }, + + setCallback: function setCallback(fn) { + this._value = fn; + this._type = types.GL_CALLBACK; + }, + + setTexture: function setTexture(textureId, textureUnit) { + this._value = textureUnit; + this._textureId = textureId; + this._type = types.GL_TEXTURE; + }, + + apply: function apply() { + switch (this._type) { + case types.GL_INT: + this._glprogram.setUniformLocationWith1i(this._uniform.location, this._value); + break; + case types.GL_FLOAT: + this._glprogram.setUniformLocationWith1f(this._uniform.location, this._value); + break; + case types.GL_FLOAT_VEC2: + this._glprogram.setUniformLocationWith2f(this._uniform.location, this._value[0], this._value[1]); + break; + case types.GL_FLOAT_VEC3: + this._glprogram.setUniformLocationWith3f(this._uniform.location, this._value[0], + this._value[1], this._value[2]); + break; + case types.GL_FLOAT_VEC4: + this._glprogram.setUniformLocationWith3f(this._uniform.location, this._value[0], + this._value[1], this._value[2]); + break; + case types.GL_FLOAT_MAT4: + this._glprogram.setUniformLocationWithMatrix4fv(this._uniform.location, this._value); + break; + case types.GL_CALLBACK: + this._value(this._glprogram, this._uniform); + break; + case types.GL_TEXTURE: + this._glprogram.setUniformLocationWith1i(this._uniform.location, this._value); + cc.glBindTexture2DN(this._value, this._textureId); + break; + default: + cc.Assert(false, "Unsupported type"); + } + }, +}); + +cc.GLProgramState = cc.Class.extend({ + _glprogram: null, + _uniformsByName: null, + _uniformsByLocation: null, + _boundTextureUnits: null, + _textureUnitIndex: 0, + + init: function init(glprogram) { + this._glprogram = glprogram; + this._uniformsByName = {}; + this._uniformsByLocation = {}; + this._boundTextureUnits = {}; + this._textureUnitIndex = 1; // Start at 1, as CC_Texture0 is bound to 0 + var userUniformKeys = Object.keys(glprogram._userUniforms); + for (var i = 0; i < userUniformKeys.length; ++i) { + var uniform = glprogram._userUniforms[userUniformKeys[i]]; + var uniformValue = new cc.UniformValue(uniform, glprogram); + this._uniformsByName[uniform.name] = uniformValue; + this._uniformsByLocation[uniform.location] = uniformValue; + } + }, + + apply: function apply(modelView) { + this.applyGLProgram(modelView); + this.applyUniforms(); + }, + + applyGLProgram: function applyGLProgram(modelView) { + this._glprogram.use(); + if (modelView) { + this._glprogram._setUniformForMVPMatrixWithMat4(modelView); + } + }, + + applyUniforms: function applyUniforms() { + var uniformKeys = Object.keys(this._uniformsByName); + for (var i = 0; i < uniformKeys.length; ++i) { + var uniform = this._uniformsByName[uniformKeys[i]]; + uniform.apply(); + } + }, + + setGLProgram: function setGLProgram(glprogram) { + this._glprogram = glprogram; + }, + + getGLProgram: function getGLProgram() { + return this._glprogram; + }, + + getUniformCount: function getUniformCount() { + return Object.keys(this._uniformsByName).length; + }, + + getUniformValue: function getUniformValue(uniform) + { + if (typeof uniform === 'string') { + return this._uniformsByName[uniform]; + } else { + return this._uniformsByLocation[uniform]; + } + }, + + // Accepts either string or uniform location + setUniformInt: function setUniformInt(uniform, value) { + var v = this.getUniformValue(uniform); + if (v) { + v.setInt(value); + } else { + cc.log("cocos2d: warning: Uniform not found: " + uniform); + } + }, + + setUniformFloat: function setUniformFloat(uniform, value) { + var v = this.getUniformValue(uniform); + if (v) { + v.setFloat(value); + } else { + cc.log("cocos2d: warning: Uniform not found: " + uniform); + } + }, + + setUniformVec2: function setUniformVec2(uniform, v1, v2) { + var v = this.getUniformValue(uniform); + if (v) { + v.setVec2(v1, v2); + } else { + cc.log("cocos2d: warning: Uniform not found: " + uniform); + } + }, + + setUniformVec2v: function setUniformVec2v(uniform, value) { + var v = this.getUniformValue(uniform); + if (v) { + v.setVec2v(value); + } else { + cc.log("cocos2d: warning: Uniform not found: " + uniform); + } + }, + + setUniformVec3: function setUniformVec3(uniform, v1, v2, v3) { + var v = this.getUniformValue(uniform); + if (v) { + v.setVec3(v1, v2, v3); + } else { + cc.log("cocos2d: warning: Uniform not found: " + uniform); + } + }, + + setUniformVec3v: function setUniformVec3v(uniform, value) { + var v = this.getUniformValue(uniform); + if (v) { + v.setVec3v(value); + } else { + cc.log("cocos2d: warning: Uniform not found: " + uniform); + } + }, + + setUniformVec4: function setUniformVec4(uniform, v1, v2, v3, v4) { + var v = this.getUniformValue(uniform); + if (v) { + v.setVec4(v1, v2, v3, v4); + } else { + cc.log("cocos2d: warning: Uniform not found: " + uniform); + } + }, + + setUniformVec4v: function setUniformVec4v(uniform, value) { + var v = this.getUniformValue(uniform); + if (v) { + v.setVec4v(value); + } else { + cc.log("cocos2d: warning: Uniform not found: " + uniform); + } + }, + + + setUniformMat4: function setUniformMat4(uniform, value) { + var v = this.getUniformValue(uniform); + if (v) { + v.setMat4(value); + } else { + cc.log("cocos2d: warning: Uniform not found: " + uniform); + } + + }, + + setUniformCallback: function setUniformCallback(uniform, callback) { + var v = this.getUniformValue(uniform); + if (v) { + v.setCallback(callback); + } else { + cc.log("cocos2d: warning: Uniform not found: " + uniform); + } + + }, + + setUniformTexture: function setUniformTexture(uniform, texture) { + var uniformValue = this.getUniformValue(uniform); + if (uniformValue) { + var textureUnit = this._boundTextureUnits[uniform]; + if (textureUnit) { + uniformValue.setTexture(texture, textureUnit); + } else { + uniformValue.setTexture(texture, this._textureUnitIndex); + this._boundTextureUnits[uniform] = this._textureUnitIndex++; + } + } + } +}); + +cc.GLProgramState._cache = {}; +cc.GLProgramState.getOrCreateWithGLProgram = function (glprogram) { + var programState = cc.GLProgramState._cache[glprogram.__instanceId]; + if (!programState) { + programState = new cc.GLProgramState(); + programState.init(glprogram); + cc.GLProgramState._cache[glprogram.__instanceId] = programState; + } + + return programState; +}; diff --git a/cocos2d/shape-nodes/CCDrawNodeWebGLRenderCmd.js b/cocos2d/shape-nodes/CCDrawNodeWebGLRenderCmd.js index ef9d443c98..cd7ea5125c 100644 --- a/cocos2d/shape-nodes/CCDrawNodeWebGLRenderCmd.js +++ b/cocos2d/shape-nodes/CCDrawNodeWebGLRenderCmd.js @@ -45,8 +45,7 @@ this._matrix.mat[13] = wt.ty; cc.glBlendFunc(node._blendFunc.src, node._blendFunc.dst); - this._shaderProgram.use(); - this._shaderProgram._setUniformForMVPMatrixWithMat4(this._matrix); + this._glProgramState.apply(this._matrix); node._render(); } }; diff --git a/moduleConfig.json b/moduleConfig.json index 99e383e35f..ee6224df60 100644 --- a/moduleConfig.json +++ b/moduleConfig.json @@ -229,6 +229,7 @@ "cocos2d/shaders/CCShaders.js", "cocos2d/shaders/CCShaderCache.js", "cocos2d/shaders/CCGLProgram.js", + "cocos2d/shaders/CCGLProgramState.js", "cocos2d/shaders/CCGLStateCache.js" ], "shape-nodes" : [ From beee1dc96f0ba8181cee778aaab90752f2514535 Mon Sep 17 00:00:00 2001 From: David DeSimone Date: Tue, 13 Dec 2016 15:36:49 -0800 Subject: [PATCH 061/206] Fixing rendering issues in CCAtlastNodeWebGLRenderCmd and CCGrid. --- cocos2d/core/base-nodes/CCAtlasNodeWebGLRenderCmd.js | 6 ++---- cocos2d/effects/CCGrid.js | 6 +++--- cocos2d/shaders/CCGLProgramState.js | 9 +++------ 3 files changed, 8 insertions(+), 13 deletions(-) diff --git a/cocos2d/core/base-nodes/CCAtlasNodeWebGLRenderCmd.js b/cocos2d/core/base-nodes/CCAtlasNodeWebGLRenderCmd.js index 5810d00794..085e3770bb 100644 --- a/cocos2d/core/base-nodes/CCAtlasNodeWebGLRenderCmd.js +++ b/cocos2d/core/base-nodes/CCAtlasNodeWebGLRenderCmd.js @@ -32,14 +32,12 @@ this._textureAtlas = null; this._colorUnmodified = cc.color.WHITE; this._colorF32Array = null; - this._uniformColor = null; this._matrix = new cc.math.Matrix4(); this._matrix.identity(); //shader stuff this._shaderProgram = cc.shaderCache.programForKey(cc.SHADER_POSITION_TEXTURE_UCOLOR); - this._uniformColor = cc._renderContext.getUniformLocation(this._shaderProgram.getProgram(), "u_color"); }; var proto = cc.AtlasNode.WebGLRenderCmd.prototype = Object.create(cc.Node.WebGLRenderCmd.prototype); @@ -71,8 +69,8 @@ this._glProgramState.apply(this._matrix); cc.glBlendFunc(node._blendFunc.src, node._blendFunc.dst); - if (this._uniformColor && this._colorF32Array) { - context.uniform4fv(this._uniformColor, this._colorF32Array); + if (this._colorF32Array) { + this._glProgramState.setUniformVec4v("u_color", this._colorF32Array); this._textureAtlas.drawNumberOfQuads(node.quadsToDraw, 0); } }; diff --git a/cocos2d/effects/CCGrid.js b/cocos2d/effects/CCGrid.js index 84e08be6af..361cba84b3 100644 --- a/cocos2d/effects/CCGrid.js +++ b/cocos2d/effects/CCGrid.js @@ -39,7 +39,7 @@ cc.GridBase = cc.Class.extend(/** @lends cc.GridBase# */{ _step: null, _grabber: null, _isTextureFlipped: false, - _shaderProgram: null, + _glProgramState: null, _directorProjection: 0, _dirty: false, @@ -62,7 +62,7 @@ cc.GridBase = cc.Class.extend(/** @lends cc.GridBase# */{ this._step = cc.p(0, 0); this._grabber = null; this._isTextureFlipped = false; - this._shaderProgram = null; + this._glProgramState = null; this._directorProjection = 0; this._dirty = false; @@ -227,7 +227,7 @@ cc.GridBase = cc.Class.extend(/** @lends cc.GridBase# */{ if (!this._grabber) return false; this._grabber.grab(this._texture); - this._shaderProgram = cc.shaderCache.programForKey(cc.SHADER_POSITION_TEXTURE); + this._glProgramState = cc.GLProgramState.getOrCreateWithGLProgram(cc.shaderCache.programForKey(cc.SHADER_POSITION_TEXTURE)); this.calculateVertexPoints(); return true; }, diff --git a/cocos2d/shaders/CCGLProgramState.js b/cocos2d/shaders/CCGLProgramState.js index 6457d180fb..eb95a3be0c 100644 --- a/cocos2d/shaders/CCGLProgramState.js +++ b/cocos2d/shaders/CCGLProgramState.js @@ -24,9 +24,6 @@ THE SOFTWARE. ****************************************************************************/ -// @TODO add floatv and intv methods, that take arrays -// and float1..4 methods, which take arguments. - var types = { GL_FLOAT: 0, @@ -122,8 +119,8 @@ cc.UniformValue = cc.Class.extend({ this._value[1], this._value[2]); break; case types.GL_FLOAT_VEC4: - this._glprogram.setUniformLocationWith3f(this._uniform.location, this._value[0], - this._value[1], this._value[2]); + this._glprogram.setUniformLocationWith4f(this._uniform.location, this._value[0], + this._value[1], this._value[2], this._value[3]); break; case types.GL_FLOAT_MAT4: this._glprogram.setUniformLocationWithMatrix4fv(this._uniform.location, this._value); @@ -136,7 +133,7 @@ cc.UniformValue = cc.Class.extend({ cc.glBindTexture2DN(this._value, this._textureId); break; default: - cc.Assert(false, "Unsupported type"); + ; } }, }); From c30a2e6e307ca4efde03313adda768339ccfe4d9 Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Wed, 14 Dec 2016 14:08:43 +0800 Subject: [PATCH 062/206] add bmfont and atlas batch commit 053739c779567fc1926a7d56efc73ab66d9c7d93 Author: zilongshanren Date: Wed Dec 14 10:51:54 2016 +0800 refactor labelAtlas to extend bmfont commit 443cf83c8c32f276b924b624bb7b5ca49efc72cb Author: zilongshanren Date: Wed Dec 7 21:35:49 2016 +0800 make fnt frame cache working commit aef313a8a811ee0267ad7393f730d834a7a4f992 Author: zilongshanren Date: Wed Dec 7 20:24:01 2016 +0800 add bmfont batch draw --- cocos2d/labels/CCLabelAtlas.js | 187 ++++++++---------- cocos2d/labels/CCLabelBMFont.js | 143 +++++++++----- cocos2d/labels/CCLabelBMFontWebGLRenderCmd.js | 4 +- moduleConfig.json | 9 +- 4 files changed, 184 insertions(+), 159 deletions(-) diff --git a/cocos2d/labels/CCLabelAtlas.js b/cocos2d/labels/CCLabelAtlas.js index 2b8c06178f..6f2bce2e29 100644 --- a/cocos2d/labels/CCLabelAtlas.js +++ b/cocos2d/labels/CCLabelAtlas.js @@ -27,7 +27,7 @@ /** * using image file to print text label on the screen, might be a bit slower than cc.Label, similar to cc.LabelBMFont * @class - * @extends cc.AtlasNode + * @extends cc.LabelBMFont * * @property {String} string - Content string of label * @@ -43,14 +43,7 @@ * //creates the cc.LabelAtlas with a string, a fnt file * var myLabel = new cc.LabelAtlas('Text to display', 'CharMapFile.plist‘); */ -cc.LabelAtlas = cc.AtlasNode.extend(/** @lends cc.LabelAtlas# */{ - //property String is Getter and Setter - // string to render - _string: null, - // the first char in the charmap - _mapStartChar: null, - - _textureLoaded: false, +cc.LabelAtlas = cc.LabelBMFont.extend(/** @lends cc.LabelBMFont# */{ _className: "LabelAtlas", /** @@ -68,35 +61,47 @@ cc.LabelAtlas = cc.AtlasNode.extend(/** @lends cc.LabelAtlas# */{ * @param {Number} [startCharMap=""] */ ctor: function (strText, charMapFile, itemWidth, itemHeight, startCharMap) { - cc.AtlasNode.prototype.ctor.call(this); + cc.SpriteBatchNode.prototype.ctor.call(this); + this._imageOffset = cc.p(0, 0); + this._cascadeColorEnabled = true; + this._cascadeOpacityEnabled = true; - this._renderCmd.setCascade(); charMapFile && cc.LabelAtlas.prototype.initWithString.call(this, strText, charMapFile, itemWidth, itemHeight, startCharMap); }, - _createRenderCmd: function(){ - if(cc._renderType === cc.game.RENDER_TYPE_WEBGL) - return new cc.LabelAtlas.WebGLRenderCmd(this); + _createRenderCmd: function () { + if (cc._renderType === cc.game.RENDER_TYPE_WEBGL) + return new cc.LabelBMFont.WebGLRenderCmd(this); else - return new cc.LabelAtlas.CanvasRenderCmd(this); + return new cc.LabelBMFont.CanvasRenderCmd(this); }, - /** - * Return texture is loaded. - * @returns {boolean} - */ - textureLoaded: function () { - return this._textureLoaded; - }, + _createFntConfig: function (texture, itemWidth, itemHeight, startCharMap) { + var fnt = {}; + fnt.commonHeight = itemHeight; + + var fontDefDictionary = fnt.fontDefDictionary = {}; + + var textureWidth = texture.pixelsWidth; + var textureHeight = texture.pixelsHeight; + + var startCharCode = startCharMap.charCodeAt(0); + var i = 0; + for (var col = itemHeight; col <= textureHeight; col += itemHeight) { + for (var row = 0; row < textureWidth; row += itemWidth) { + fontDefDictionary[startCharCode+i] = { + rect: {x: row, y: col - itemHeight, width:itemWidth, height: itemHeight }, + xOffset: 0, + yOffset: 0, + xAdvance: itemWidth + }; + ++i; + } + } - /** - * Add texture loaded event listener. - * @param {Function} callback - * @param {cc.Node} target - * @deprecated since 3.1, please use addEventListener instead - */ - addLoadedEventListener: function (callback, target) { - this.addEventListener("load", callback, target); + fnt.kerningDict = {}; + + return fnt; }, /** @@ -116,6 +121,10 @@ cc.LabelAtlas = cc.AtlasNode.extend(/** @lends cc.LabelAtlas# */{ */ initWithString: function (strText, charMapFile, itemWidth, itemHeight, startCharMap) { var label = strText + "", textureFilename, width, height, startChar; + var self = this, theString = label || ""; + this._initialString = theString; + self._string = theString; + if (itemWidth === undefined) { var dict = cc.loader.getRes(charMapFile); if (parseInt(dict["version"], 10) !== 1) { @@ -135,88 +144,60 @@ cc.LabelAtlas = cc.AtlasNode.extend(/** @lends cc.LabelAtlas# */{ startChar = startCharMap || " "; } - var texture = null; - if (textureFilename instanceof cc.Texture2D) - texture = textureFilename; - else - texture = cc.textureCache.addImage(textureFilename); - var locLoaded = texture.isLoaded(); - this._textureLoaded = locLoaded; - if (!locLoaded) { - this._string = label; - texture.addEventListener("load", function (sender) { - this.initWithTexture(texture, width, height, label.length); - this.string = this._string; - this.setColor(this._renderCmd._displayedColor); - this.dispatchEvent("load"); - }, this); - } - if (this.initWithTexture(texture, width, height, label.length)) { - this._mapStartChar = startChar; - this.string = label; - return true; + var texture; + if (charMapFile) { + self._fntFile = "dummy_fnt_file:" + textureFilename; + var spriteFrameBaseName = textureFilename; + var spriteFrame = cc.spriteFrameCache.getSpriteFrame(spriteFrameBaseName) || cc.spriteFrameCache.getSpriteFrame(cc.path.basename(spriteFrameBaseName)); + if(spriteFrame) { + texture = spriteFrame.getTexture(); + this._spriteFrame = spriteFrame; + } else { + texture = cc.textureCache.addImage(textureFilename); + } + + var newConf = this._createFntConfig(texture, width, height, startChar); + newConf.atlasName = textureFilename; + self._config = newConf; + + var locIsLoaded = texture.isLoaded(); + self._textureLoaded = locIsLoaded; + if (!locIsLoaded) { + texture.addEventListener("load", function () { + var self1 = this; + self1._textureLoaded = true; + //reset the LabelBMFont + self1.setString(self1._initialString, true); + self1.dispatchEvent("load"); + }, self); + } + } else { + texture = new cc.Texture2D(); + var image = new Image(); + texture.initWithElement(image); + self._textureLoaded = false; } - return false; - }, + this._texture = texture; - /** - * Set the color. - * @param {cc.Color} color3 - */ - setColor: function (color3) { - cc.AtlasNode.prototype.setColor.call(this, color3); - this._renderCmd.updateAtlasValues(); - }, + self._alignment = cc.TEXT_ALIGNMENT_LEFT; + self._imageOffset = cc.p(0, 0); + self._width = -1; - /** - * return the text of this label - * @return {String} - */ - getString: function () { - return this._string; - }, + self._realOpacity = 255; + self._realColor = cc.color(255, 255, 255, 255); - addChild: function(child, localZOrder, tag){ - this._renderCmd._addChild(child); - cc.Node.prototype.addChild.call(this, child, localZOrder, tag); - }, + self._contentSize.width = 0; + self._contentSize.height = 0; - /** - * Atlas generation - * @function - */ - updateAtlasValues: function(){ - this._renderCmd.updateAtlasValues(); + self.setString(theString, true); + return true; }, - /** - * set the display string - * @function - * @param {String} label - */ - setString: function(label){ - label = String(label); - var len = label.length; - this._string = label; - this.setContentSize(len * this._itemWidth, this._itemHeight); - this._renderCmd.setString(label); - - this._renderCmd.updateAtlasValues(); - this.quadsToDraw = len; + setFntFile: function () { + cc.warn("setFntFile doesn't support with LabelAtlas."); } -}); -(function(){ - var proto = cc.LabelAtlas.prototype; - // Override properties - cc.defineGetterSetter(proto, "opacity", proto.getOpacity, proto.setOpacity); - cc.defineGetterSetter(proto, "color", proto.getColor, proto.setColor); - - // Extended properties - /** @expose */ - proto.string; - cc.defineGetterSetter(proto, "string", proto.getString, proto.setString); -})(); +}); /** *

diff --git a/cocos2d/labels/CCLabelBMFont.js b/cocos2d/labels/CCLabelBMFont.js index 7c261a14b7..e9d5d4ab66 100644 --- a/cocos2d/labels/CCLabelBMFont.js +++ b/cocos2d/labels/CCLabelBMFont.js @@ -80,7 +80,7 @@ * // Example 03 * var label3 = new cc.LabelBMFont("This is a \n test case", "test.fnt", 200, cc.TEXT_ALIGNMENT_LEFT, cc.p(0,0)); */ -cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{ +cc.LabelBMFont = cc.Node.extend(/** @lends cc.LabelBMFont# */{ //property string is Getter and Setter. //property textAlign is Getter and Setter. //property boundingWidth is Getter and Setter. @@ -114,11 +114,9 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{ }, _setString: function (newString, needUpdateLabel) { - if (!needUpdateLabel) { - this._string = newString; - } else { - this._initialString = newString; - } + this._initialString = newString; + this._string = newString; + var locChildren = this._children; if (locChildren) { for (var i = 0; i < locChildren.length; i++) { @@ -226,13 +224,23 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{ if (fntFile) { var newConf = cc.loader.getRes(fntFile); if (!newConf) { - cc.log("cc.LabelBMFont.initWithString(): Impossible to create font. Please check file"); - return false; + newConf = cc.FntFrameCache[fntFile] || cc.FntFrameCache[cc.path.basename(fntFile)]; + if(!newConf) { + cc.log("cc.LabelBMFont.initWithString(): Impossible to create font. Please check file"); + return false; + } } self._config = newConf; self._fntFile = fntFile; - texture = cc.textureCache.addImage(newConf.atlasName); + var spriteFrameBaseName = newConf.atlasName; + var spriteFrame = cc.spriteFrameCache.getSpriteFrame(spriteFrameBaseName) || cc.spriteFrameCache.getSpriteFrame(cc.path.basename(spriteFrameBaseName)); + if(spriteFrame) { + texture = spriteFrame.getTexture(); + this._spriteFrame = spriteFrame; + } else { + texture = cc.textureCache.addImage(newConf.atlasName); + } var locIsLoaded = texture.isLoaded(); self._textureLoaded = locIsLoaded; if (!locIsLoaded) { @@ -240,7 +248,6 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{ var self1 = this; self1._textureLoaded = true; //reset the LabelBMFont - self1.initWithTexture(sender, self1._initialString.length); self1.setString(self1._initialString, true); self1.dispatchEvent("load"); }, self); @@ -251,24 +258,22 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{ texture.initWithElement(image); self._textureLoaded = false; } + this._texture = texture; - if (self.initWithTexture(texture, theString.length)) { - self._alignment = alignment || cc.TEXT_ALIGNMENT_LEFT; - self._imageOffset = imageOffset || cc.p(0, 0); - self._width = (width === undefined) ? -1 : width; + self._alignment = alignment || cc.TEXT_ALIGNMENT_LEFT; + self._imageOffset = imageOffset || cc.p(0, 0); + self._width = (width === undefined) ? -1 : width; - self._realOpacity = 255; - self._realColor = cc.color(255, 255, 255, 255); + self._realOpacity = 255; + self._realColor = cc.color(255, 255, 255, 255); - self._contentSize.width = 0; - self._contentSize.height = 0; + self._contentSize.width = 0; + self._contentSize.height = 0; - self.setAnchorPoint(0.5, 0.5); + self.setAnchorPoint(0.5, 0.5); - self.setString(theString, true); - return true; - } - return false; + self.setString(theString, true); + return true; }, /** @@ -336,15 +341,30 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{ rect.x += self._imageOffset.x; rect.y += self._imageOffset.y; + var isRotated = false; + if(this._spriteFrame) { + var textureWidth = locTexture.width; + var spriteFrameRect = this._spriteFrame._rect; + if(!this._spriteFrame._rotated) { + rect.x = rect.x + spriteFrameRect.x; + rect.y = rect.y + spriteFrameRect.y; + } else { + isRotated = true; + var originalX = rect.x; + rect.x = rect.y + spriteFrameRect.x; + rect.y = originalX + spriteFrameRect.y; + } + } + var fontChar = self.getChildByTag(i); if (!fontChar) { fontChar = new cc.Sprite(); - fontChar.initWithTexture(locTexture, rect, false); + fontChar.initWithTexture(locTexture, rect, isRotated); fontChar._newTextureWhenChangeColor = true; this.addChild(fontChar, 0, i); } else { - cmd._updateCharTexture(fontChar, rect, key); + cmd._updateCharTexture(fontChar, rect, key, isRotated); } // Apply label properties @@ -541,7 +561,7 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{ */ updateLabel: function () { var self = this; - self.string = self._initialString; + self._string = self._initialString; var i, j, characterSprite; // process string // Step 1: Make multiline @@ -564,7 +584,6 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{ wrapString = wrapString + String.fromCharCode(0); self._setString(wrapString, false); } - // Step 2: Make alignment if (self._alignment !== cc.TEXT_ALIGNMENT_LEFT) { i = 0; @@ -797,9 +816,9 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{ //Checking whether the character is a whitespace _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) + 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) { @@ -866,7 +885,11 @@ cc.LabelBMFont.create = function (str, fntFile, width, alignment, imageOffset) { return new cc.LabelBMFont(str, fntFile, width, alignment, imageOffset); }; +cc.FntFrameCache = {}; + var _fntLoader = { + FNT_HEAD: /fntframes [^\n]*(\n|$)/gi, + FNT_FRAME_NAME: /fntframe [^\n]*(\n|$)/gi, INFO_EXP: /info [^\n]*(\n|$)/gi, COMMON_EXP: /common [^\n]*(\n|$)/gi, PAGE_EXP: /page [^\n]*(\n|$)/gi, @@ -892,24 +915,8 @@ var _fntLoader = { return obj; }, - /** - * Parse Fnt string. - * @param fntStr - * @param url - * @returns {{}} - */ - parseFnt: function (fntStr, url) { - var self = this, fnt = {}; - //padding - var infoObj = self._parseStrToObj(fntStr.match(self.INFO_EXP)[0]); - var paddingArr = infoObj["padding"].split(","); - var padding = { - left: parseInt(paddingArr[0]), - top: parseInt(paddingArr[1]), - right: parseInt(paddingArr[2]), - bottom: parseInt(paddingArr[3]) - }; - + _parseFntContent: function (fnt, fntStr, url, useAtlas) { + var self = this; //common var commonObj = self._parseStrToObj(fntStr.match(self.COMMON_EXP)[0]); fnt.commonHeight = commonObj["lineHeight"]; @@ -923,7 +930,11 @@ var _fntLoader = { //page var pageObj = self._parseStrToObj(fntStr.match(self.PAGE_EXP)[0]); if (pageObj["id"] !== 0) cc.log("cc.LabelBMFont._parseImageFileName() : file could not be found"); - fnt.atlasName = cc.path.changeBasename(url, pageObj["file"]); + if(!useAtlas) { + fnt.atlasName = cc.path.changeBasename(url, pageObj["file"]); + } else { + fnt.atlasName = cc.path.join(cc.path.dirname(useAtlas.path) + pageObj["file"]); + } //char var charLines = fntStr.match(self.CHAR_EXP); @@ -948,6 +959,40 @@ var _fntLoader = { kerningDict[(kerningObj["first"] << 16) | (kerningObj["second"] & 0xffff)] = kerningObj["amount"]; } } + + return fnt; + }, + + /** + * Parse Fnt string. + * @param fntStr + * @param url + * @returns {{}} + */ + parseFnt: function (fntStr, url) { + var self = this, fnt = {}; + var headString = fntStr.match(self.FNT_HEAD); + if(headString) { + var headObj = self._parseStrToObj(headString[0]); + if(headObj && headObj.count) { + fntStr = fntStr.substr(headString[0].length); + var fntFrames = fntStr.split("----"); + for(var i = 0; i < headObj.count; ++i) { + var contentString = fntFrames[i]; + var frameNameStr = contentString.match(self.FNT_FRAME_NAME); + if(frameNameStr) { + var frameName = self._parseStrToObj(frameNameStr[0]); + if(frameName && frameName.name) { + fnt = {}; + var realFntPathKey = cc.path.join(cc.path.dirname(url), frameName.name); + cc.FntFrameCache[realFntPathKey] = this._parseFntContent(fnt, contentString.substr(frameNameStr[0].length), url, {path: frameName.name}); + } + } + } + } + } else { + fnt = this._parseFntContent(fnt, fntStr, url); + } return fnt; }, diff --git a/cocos2d/labels/CCLabelBMFontWebGLRenderCmd.js b/cocos2d/labels/CCLabelBMFontWebGLRenderCmd.js index 7e468e37d7..09e18a5f6b 100644 --- a/cocos2d/labels/CCLabelBMFontWebGLRenderCmd.js +++ b/cocos2d/labels/CCLabelBMFontWebGLRenderCmd.js @@ -42,9 +42,9 @@ this._node.setOpacityModifyRGB(this._node._texture.hasPremultipliedAlpha()); }; - proto._updateCharTexture = function (fontChar, rect, key) { + proto._updateCharTexture = function(fontChar, rect, key, isRotated){ // updating previous sprite - fontChar.setTextureRect(rect, false); + fontChar.setTextureRect(rect, isRotated); // restore to default in case they were modified fontChar.visible = true; }; diff --git a/moduleConfig.json b/moduleConfig.json index 99e383e35f..b94181331b 100644 --- a/moduleConfig.json +++ b/moduleConfig.json @@ -153,13 +153,12 @@ ], "labels" : [ "core", - - "cocos2d/labels/CCLabelAtlas.js", - "cocos2d/labels/CCLabelAtlasCanvasRenderCmd.js", - "cocos2d/labels/CCLabelAtlasWebGLRenderCmd.js", "cocos2d/labels/CCLabelBMFont.js", "cocos2d/labels/CCLabelBMFontCanvasRenderCmd.js", - "cocos2d/labels/CCLabelBMFontWebGLRenderCmd.js" + "cocos2d/labels/CCLabelBMFontWebGLRenderCmd.js", + "cocos2d/labels/CCLabelAtlas.js", + "cocos2d/labels/CCLabelAtlasCanvasRenderCmd.js", + "cocos2d/labels/CCLabelAtlasWebGLRenderCmd.js" ], "menus" : [ "core", "actions", From da87a4be8078c3ec14cbb8298e585b9ddac9ccc7 Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Wed, 14 Dec 2016 14:48:10 +0800 Subject: [PATCH 063/206] fix bmfont update logic --- cocos2d/labels/CCLabelBMFont.js | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/cocos2d/labels/CCLabelBMFont.js b/cocos2d/labels/CCLabelBMFont.js index e9d5d4ab66..26a5154db4 100644 --- a/cocos2d/labels/CCLabelBMFont.js +++ b/cocos2d/labels/CCLabelBMFont.js @@ -114,8 +114,11 @@ cc.LabelBMFont = cc.Node.extend(/** @lends cc.LabelBMFont# */{ }, _setString: function (newString, needUpdateLabel) { - this._initialString = newString; - this._string = newString; + if (!needUpdateLabel) { + this._string = newString; + } else { + this._initialString = newString; + } var locChildren = this._children; if (locChildren) { @@ -561,7 +564,8 @@ cc.LabelBMFont = cc.Node.extend(/** @lends cc.LabelBMFont# */{ */ updateLabel: function () { var self = this; - self._string = self._initialString; + self.string = self._initialString; + var i, j, characterSprite; // process string // Step 1: Make multiline From afe94bac616e0edd34ea54113d3d0e3d965a38fe Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Thu, 15 Dec 2016 11:11:48 +0800 Subject: [PATCH 064/206] optimize uibutton and uiimage view --- extensions/ccui/uiwidgets/UIButton.js | 605 ++++++++++------------- extensions/ccui/uiwidgets/UIImageView.js | 78 ++- 2 files changed, 280 insertions(+), 403 deletions(-) diff --git a/extensions/ccui/uiwidgets/UIButton.js b/extensions/ccui/uiwidgets/UIButton.js index fc65d2e6dd..348177fee5 100644 --- a/extensions/ccui/uiwidgets/UIButton.js +++ b/extensions/ccui/uiwidgets/UIButton.js @@ -1,6 +1,7 @@ /**************************************************************************** Copyright (c) 2011-2012 cocos2d-x.org Copyright (c) 2013-2014 Chukong Technologies Inc. + Copyright (c) 2015-2016 zilongshanren http://www.cocos2d-x.org @@ -36,9 +37,10 @@ * @property {Boolean} pressedActionEnabled - Indicate whether button has zoom effect when clicked */ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ - _buttonNormalRenderer: null, - _buttonClickedRenderer: null, - _buttonDisableRenderer: null, + _buttonScale9Renderer: null, + _buttonNormalSpriteFrame: null, + _buttonClickedSpriteFrame: null, + _buttonDisableSpriteFrame: null, _titleRenderer: null, _normalFileName: "", @@ -49,23 +51,15 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ _scale9Enabled: false, _capInsetsNormal: null, - _capInsetsPressed: null, - _capInsetsDisabled: null, _normalTexType: ccui.Widget.LOCAL_TEXTURE, _pressedTexType: ccui.Widget.LOCAL_TEXTURE, _disabledTexType: ccui.Widget.LOCAL_TEXTURE, _normalTextureSize: null, - _pressedTextureSize: null, - _disabledTextureSize: null, pressedActionEnabled: false, _titleColor: null, - _normalTextureScaleXInSize: 1, - _normalTextureScaleYInSize: 1, - _pressedTextureScaleXInSize: 1, - _pressedTextureScaleYInSize: 1, _zoomScale: 0.1, @@ -75,8 +69,6 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ _className: "Button", _normalTextureAdaptDirty: true, - _pressedTextureAdaptDirty: true, - _disabledTextureAdaptDirty: true, _fontName: "Thonburi", _fontSize: 12, @@ -95,33 +87,35 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ */ ctor: function (normalImage, selectedImage, disableImage, texType) { this._capInsetsNormal = cc.rect(0, 0, 0, 0); - this._capInsetsPressed = cc.rect(0, 0, 0, 0); - this._capInsetsDisabled = cc.rect(0, 0, 0, 0); this._normalTextureSize = cc.size(0, 0); - this._pressedTextureSize = cc.size(0, 0); - this._disabledTextureSize = cc.size(0, 0); - this._titleColor = cc.color.WHITE; ccui.Widget.prototype.ctor.call(this); this.setTouchEnabled(true); + this._normalLoader = new cc.Sprite.LoadManager(); + this._clickedLoader = new cc.Sprite.LoadManager(); + this._disabledLoader = new cc.Sprite.LoadManager(); + if (normalImage) { this.loadTextures(normalImage, selectedImage,disableImage, texType); } }, + _createTitleRendererIfNeeded: function ( ) { + if(!this._titleRenderer) { + this._titleRenderer = new cc.LabelTTF(""); + this._titleRenderer.setAnchorPoint(0.5, 0.5); + this._titleColor = cc.color.WHITE; + this._titleRenderer.setVerticalAlignment(cc.VERTICAL_TEXT_ALIGNMENT_CENTER); + this.addProtectedChild(this._titleRenderer, ccui.Button.TITLE_RENDERER_ZORDER, -1); + } + }, + _initRenderer: function () { - //todo create Scale9Sprite - this._buttonNormalRenderer = new cc.Sprite(); - this._buttonClickedRenderer = new cc.Sprite(); - this._buttonDisableRenderer = new cc.Sprite(); - this._titleRenderer = new cc.LabelTTF(""); - this._titleRenderer.setAnchorPoint(0.5, 0.5); - this._titleRenderer.setVerticalAlignment(cc.VERTICAL_TEXT_ALIGNMENT_CENTER); + this._buttonScale9Renderer = new ccui.Scale9Sprite(); + + this._buttonScale9Renderer.setRenderingType(ccui.Scale9Sprite.RenderingType.SIMPLE); - this.addProtectedChild(this._buttonNormalRenderer, ccui.Button.NORMAL_RENDERER_ZORDER, -1); - this.addProtectedChild(this._buttonClickedRenderer, ccui.Button.PRESSED_RENDERER_ZORDER, -1); - this.addProtectedChild(this._buttonDisableRenderer, ccui.Button.DISABLED_RENDERER_ZORDER, -1); - this.addProtectedChild(this._titleRenderer, ccui.Button.TITLE_RENDERER_ZORDER, -1); + this.addProtectedChild(this._buttonScale9Renderer, ccui.Button.DISABLED_RENDERER_ZORDER, -1); }, /** @@ -129,37 +123,18 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ * @param {Boolean} able true that using scale9 renderer, false otherwise. */ setScale9Enabled: function (able) { - //todo create Scale9Sprite if (this._scale9Enabled === able) return; this._brightStyle = ccui.Widget.BRIGHT_STYLE_NONE; this._scale9Enabled = able; - this.removeProtectedChild(this._buttonNormalRenderer); - this.removeProtectedChild(this._buttonClickedRenderer); - this.removeProtectedChild(this._buttonDisableRenderer); - if (this._scale9Enabled) { - this._buttonNormalRenderer = new ccui.Scale9Sprite(); - this._buttonClickedRenderer = new ccui.Scale9Sprite(); - this._buttonDisableRenderer = new ccui.Scale9Sprite(); + this._buttonScale9Renderer.setRenderingType(ccui.Scale9Sprite.RenderingType.SLICED); } else { - this._buttonNormalRenderer = new cc.Sprite(); - this._buttonClickedRenderer = new cc.Sprite(); - this._buttonDisableRenderer = new cc.Sprite(); + this._buttonScale9Renderer.setRenderingType(ccui.Scale9Sprite.RenderingType.SIMPLE); } - this._buttonClickedRenderer.setVisible(false); - this._buttonDisableRenderer.setVisible(false); - - this.loadTextureNormal(this._normalFileName, this._normalTexType); - this.loadTexturePressed(this._clickedFileName, this._pressedTexType); - this.loadTextureDisabled(this._disabledFileName, this._disabledTexType); - - this.addProtectedChild(this._buttonNormalRenderer, ccui.Button.NORMAL_RENDERER_ZORDER, -1); - this.addProtectedChild(this._buttonClickedRenderer, ccui.Button.PRESSED_RENDERER_ZORDER, -1); - this.addProtectedChild(this._buttonDisableRenderer, ccui.Button.DISABLED_RENDERER_ZORDER, -1); if (this._scale9Enabled) { var ignoreBefore = this._ignoreSize; this.ignoreContentAdaptWithSize(false); @@ -167,14 +142,11 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ } else { this.ignoreContentAdaptWithSize(this._prevIgnoreSize); } - this.setCapInsetsNormalRenderer(this._capInsetsNormal); - this.setCapInsetsPressedRenderer(this._capInsetsPressed); - this.setCapInsetsDisabledRenderer(this._capInsetsDisabled); + this.setCapInsets(this._capInsetsNormal); + this.setBright(this._bright); this._normalTextureAdaptDirty = true; - this._pressedTextureAdaptDirty = true; - this._disabledTextureAdaptDirty = true; }, /** @@ -209,8 +181,10 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ if (this._unifySize) return this._getNormalSize(); - if (!this._normalTextureLoaded && this._titleRenderer.getString().length > 0) { - return this._titleRenderer.getContentSize(); + if (!this._normalTextureLoaded ) { + if(this._titleRenderer && this._titleRenderer.getString().length > 0) { + return this._titleRenderer.getContentSize(); + } } return cc.size(this._normalTextureSize); }, @@ -228,52 +202,91 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ this.loadTextureDisabled(disabled, texType); }, + _createSpriteFrameWithFile: function (file) { + var texture = cc.textureCache.getTextureForKey(file); + if (!texture) { + texture = cc.textureCache.addImage(file); + } + if(!texture._textureLoaded) { + return texture; + } + + var textureSize = texture.getContentSize(); + var rect = cc.rect(0, 0, textureSize.width, textureSize.height); + return new cc.SpriteFrame(texture, rect); + }, + + _createSpriteFrameWithName: function (name) { + var frame = cc.spriteFrameCache.getSpriteFrame(name); + if (frame == null) { + cc.log("ccui.Scale9Sprite.initWithSpriteFrameName(): can't find the sprite frame by spriteFrameName"); + return null; + } + + return frame; + }, + /** * Load normal state texture for button. * @param {String} normal normal state of texture's filename. * @param {ccui.Widget.LOCAL_TEXTURE|ccui.Widget.PLIST_TEXTURE} texType */ loadTextureNormal: function (normal, texType) { - if (!normal) - return; + if (!normal) return; + texType = texType || ccui.Widget.LOCAL_TEXTURE; this._normalFileName = normal; this._normalTexType = texType; - var self = this; - var normalRenderer = this._buttonNormalRenderer; - if(!normalRenderer._textureLoaded){ - normalRenderer.addEventListener("load", function(){ - self.loadTextureNormal(self._normalFileName, self._normalTexType); - }); - } + var normalSpriteFrame; switch (this._normalTexType){ case ccui.Widget.LOCAL_TEXTURE: - //SetTexture cannot load resource - normalRenderer.initWithFile(normal); - break; + normalSpriteFrame = this._createSpriteFrameWithFile(normal); + break; case ccui.Widget.PLIST_TEXTURE: - //SetTexture cannot load resource - if (normal[0] === "#") { - normal = normal.substr(1, normal.length - 1); - } - normalRenderer.initWithSpriteFrameName(normal); - break; - default: - break; + if (normal[0] === "#") { + normal = normal.substr(1, normal.length - 1); + } + normalSpriteFrame = this._createSpriteFrameWithName(normal); + break; + default: + break; + } + + if(!normalSpriteFrame) { + return; } - this._normalTextureLoaded = normalRenderer._textureLoaded; + if(!normalSpriteFrame._textureLoaded) { + this._normalLoader.clear(); + this._normalLoader.once(normalSpriteFrame, function () { + this.loadTextureNormal(this._normalFileName, this._normalTexType); + }, this); + return; + } + + this._normalTextureLoaded = normalSpriteFrame._textureLoaded; + this._buttonNormalSpriteFrame = normalSpriteFrame; + this._buttonScale9Renderer.setSpriteFrame(normalSpriteFrame); + if (this._scale9Enabled){ + this._buttonScale9Renderer.setCapInsets(this._capInsetsNormal); + } - this._normalTextureSize = this._buttonNormalRenderer.getContentSize(); + // FIXME: https://github.com/cocos2d/cocos2d-x/issues/12249 + if(!this._ignoreSize && cc.sizeEqualToSize(this._customSize, cc.size(0, 0))) { + this._customSize = this._buttonScale9Renderer.getContentSize(); + } + + this._normalTextureSize = this._buttonScale9Renderer.getContentSize(); this._updateChildrenDisplayedRGBA(); if (this._unifySize){ if (this._scale9Enabled){ - normalRenderer.setCapInsets(this._capInsetsNormal); + this._buttonScale9Renderer.setCapInsets(this._capInsetsNormal); this._updateContentSizeWithTextureSize(this._getNormalSize()); } - }else + }else { this._updateContentSizeWithTextureSize(this._normalTextureSize); + } this._normalTextureAdaptDirty = true; this._findLayout(); @@ -291,39 +304,35 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ this._clickedFileName = selected; this._pressedTexType = texType; - var self = this; - var clickedRenderer = this._buttonClickedRenderer; - if(!clickedRenderer._textureLoaded){ - clickedRenderer.addEventListener("load", function(){ - self.loadTexturePressed(self._clickedFileName, self._pressedTexType); - }); - } - + var clickedSpriteFrame; switch (this._pressedTexType) { - case ccui.Widget.LOCAL_TEXTURE: - //SetTexture cannot load resource - clickedRenderer.initWithFile(selected); - break; - case ccui.Widget.PLIST_TEXTURE: - //SetTexture cannot load resource - if (selected[0] === "#") { - selected = selected.substr(1, selected.length - 1); - } - clickedRenderer.initWithSpriteFrameName(selected); - break; - default: - break; + case ccui.Widget.LOCAL_TEXTURE: + clickedSpriteFrame = this._createSpriteFrameWithFile(selected); + break; + case ccui.Widget.PLIST_TEXTURE: + if (selected[0] === "#") { + selected = selected.substr(1, selected.length - 1); + } + clickedSpriteFrame = this._createSpriteFrameWithName(selected); + break; + default: + break; } - if (this._scale9Enabled) - clickedRenderer.setCapInsets(this._capInsetsPressed); + if(!clickedSpriteFrame) return; - this._pressedTextureSize = this._buttonClickedRenderer.getContentSize(); + if(!clickedSpriteFrame._textureLoaded) { + this._clickedLoader.clear(); + this._clickedLoader.once(clickedSpriteFrame, function () { + this.loadTexturePressed(this._clickedFileName, this._pressedTexType); + }, this); + return; + } + + this._buttonClickedSpriteFrame = clickedSpriteFrame; this._updateChildrenDisplayedRGBA(); this._pressedTextureLoaded = true; - this._pressedTextureAdaptDirty = true; - this._findLayout(); }, /** @@ -339,38 +348,35 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ this._disabledFileName = disabled; this._disabledTexType = texType; - var self = this; - var disabledRenderer = this._buttonDisableRenderer; - if(!disabledRenderer._textureLoaded){ - disabledRenderer.addEventListener("load", function() { - self.loadTextureDisabled(self._disabledFileName, self._disabledTexType); - }); - } - + var disabledSpriteframe; switch (this._disabledTexType) { - case ccui.Widget.LOCAL_TEXTURE: - //SetTexture cannot load resource - disabledRenderer.initWithFile(disabled); - break; - case ccui.Widget.PLIST_TEXTURE: - //SetTexture cannot load resource - if (disabled[0] === "#") { - disabled = disabled.substr(1, disabled.length - 1); - } - disabledRenderer.initWithSpriteFrameName(disabled); - break; - default: - break; + case ccui.Widget.LOCAL_TEXTURE: + disabledSpriteframe = this._createSpriteFrameWithFile(disabled); + break; + case ccui.Widget.PLIST_TEXTURE: + if (disabled[0] === "#") { + disabled = disabled.substr(1, disabled.length - 1); + } + disabledSpriteframe = this._createSpriteFrameWithName(disabled); + break; + default: + break; } - if (this._scale9Enabled) - disabledRenderer.setCapInsets(this._capInsetsDisabled); + if(!disabledSpriteframe) return; - this._disabledTextureSize = this._buttonDisableRenderer.getContentSize(); + if(!disabledSpriteframe._textureLoaded) { + this._disabledLoader.clear(); + this._disabledLoader.once(disabledSpriteframe, function () { + this.loadTextureDisabled(this._disabledFileName, this._disabledTexType); + }, this); + return; + } + + this._buttonDisableSpriteFrame = disabledSpriteframe; this._updateChildrenDisplayedRGBA(); this._disabledTextureLoaded = true; - this._disabledTextureAdaptDirty = true; this._findLayout(); }, @@ -380,8 +386,6 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ */ setCapInsets: function (capInsets) { this.setCapInsetsNormalRenderer(capInsets); - this.setCapInsetsPressedRenderer(capInsets); - this.setCapInsetsDisabledRenderer(capInsets); }, /** @@ -389,7 +393,7 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ * @param {cc.Rect} capInsets */ setCapInsetsNormalRenderer: function (capInsets) { - if(!capInsets) + if(!capInsets || !this._scale9Enabled) return; var x = capInsets.x, y = capInsets.y; @@ -409,9 +413,8 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ locInsets.width = width; locInsets.height = height; - if (!this._scale9Enabled) - return; - this._buttonNormalRenderer.setCapInsets(locInsets); + this._capInsetsNormal = locInsets; + this._buttonScale9Renderer.setCapInsets(locInsets); }, /** @@ -427,28 +430,7 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ * @param {cc.Rect} capInsets */ setCapInsetsPressedRenderer: function (capInsets) { - if(!capInsets || !this._scale9Enabled) - return; - - var x = capInsets.x, y = capInsets.y; - var width = capInsets.width, height = capInsets.height; - - if (this._pressedTextureSize.width < width) { - x = 0; - width = 0; - } - if (this._pressedTextureSize.height < height) { - y = 0; - height = 0; - } - - var locInsets = this._capInsetsPressed; - locInsets.x = x; - locInsets.y = y; - locInsets.width = width; - locInsets.height = height; - - this._buttonClickedRenderer.setCapInsets(locInsets); + this.setCapInsetsNormalRenderer(capInsets); }, /** @@ -456,7 +438,7 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ * @returns {cc.Rect} */ getCapInsetsPressedRenderer: function () { - return cc.rect(this._capInsetsPressed); + return cc.rect(this._capInsetsNormal); }, /** @@ -464,28 +446,7 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ * @param {cc.Rect} capInsets */ setCapInsetsDisabledRenderer: function (capInsets) { - if(!capInsets || !this._scale9Enabled) - return; - - var x = capInsets.x, y = capInsets.y; - var width = capInsets.width, height = capInsets.height; - - if (this._disabledTextureSize.width < width) { - x = 0; - width = 0; - } - if (this._disabledTextureSize.height < height) { - y = 0; - height = 0; - } - - var locInsets = this._capInsetsDisabled; - locInsets.x = x; - locInsets.y = y; - locInsets.width = width; - locInsets.height = height; - - this._buttonDisableRenderer.setCapInsets(locInsets); + this.setCapInsetsNormalRenderer(capInsets); }, /** @@ -493,93 +454,99 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ * @returns {cc.Rect} */ getCapInsetsDisabledRenderer: function () { - return cc.rect(this._capInsetsDisabled); + return cc.rect(this._capInsetsNormal); }, _onPressStateChangedToNormal: function () { - this._buttonNormalRenderer.setVisible(true); - this._buttonClickedRenderer.setVisible(false); - this._buttonDisableRenderer.setVisible(false); - if (this._scale9Enabled) - this._buttonNormalRenderer.setState( ccui.Scale9Sprite.state.NORMAL); + this._buttonScale9Renderer.setSpriteFrame(this._buttonNormalSpriteFrame); + + if (this._scale9Enabled) { + this._buttonScale9Renderer.setState( ccui.Scale9Sprite.state.NORMAL); + } + if (this._pressedTextureLoaded) { if (this.pressedActionEnabled){ - this._buttonNormalRenderer.stopAllActions(); - this._buttonClickedRenderer.stopAllActions(); - //var zoomAction = cc.scaleTo(ccui.Button.ZOOM_ACTION_TIME_STEP, this._normalTextureScaleXInSize, this._normalTextureScaleYInSize); - //fixme: the zoomAction will run in the next frame which will cause the _buttonNormalRenderer to a wrong scale - //this._buttonNormalRenderer.runAction(zoomAction); - this._buttonNormalRenderer.setScale(this._normalTextureScaleXInSize, this._normalTextureScaleYInSize); - this._buttonClickedRenderer.setScale(this._pressedTextureScaleXInSize, this._pressedTextureScaleYInSize); - - this._titleRenderer.stopAllActions(); - if (this._unifySize){ - var zoomTitleAction = cc.scaleTo(ccui.Button.ZOOM_ACTION_TIME_STEP, 1, 1); - this._titleRenderer.runAction(zoomTitleAction); - }else{ - this._titleRenderer.setScaleX(1); - this._titleRenderer.setScaleY(1); + this._buttonScale9Renderer.stopAllActions(); + this._buttonScale9Renderer.setScale(1.0); + + if(this._titleRenderer) { + this._titleRenderer.stopAllActions(); + + if (this._unifySize){ + var zoomTitleAction = cc.scaleTo(ccui.Button.ZOOM_ACTION_TIME_STEP, 1, 1); + this._titleRenderer.runAction(zoomTitleAction); + }else{ + this._titleRenderer.setScaleX(1); + this._titleRenderer.setScaleY(1); + } } + } } else { - this._buttonNormalRenderer.stopAllActions(); - this._buttonNormalRenderer.setScale(this._normalTextureScaleXInSize, this._normalTextureScaleYInSize); + this._buttonScale9Renderer.stopAllActions(); + this._buttonScale9Renderer.setScale(1.0); - this._titleRenderer.stopAllActions(); - if (this._scale9Enabled) - this._buttonNormalRenderer.setColor(cc.color.WHITE); + if (this._scale9Enabled) { + this._buttonScale9Renderer.setColor(cc.color.WHITE); + } + + if(this._titleRenderer) { + this._titleRenderer.stopAllActions(); - this._titleRenderer.setScaleX(1); - this._titleRenderer.setScaleY(1); + this._titleRenderer.setScaleX(1); + this._titleRenderer.setScaleY(1); + } } }, _onPressStateChangedToPressed: function () { - var locNormalRenderer = this._buttonNormalRenderer; - if (this._scale9Enabled) - locNormalRenderer.setState(ccui.Scale9Sprite.state.NORMAL); + if (this._scale9Enabled) { + this._buttonScale9Renderer.setState(ccui.Scale9Sprite.state.NORMAL); + } if (this._pressedTextureLoaded) { - locNormalRenderer.setVisible(false); - this._buttonClickedRenderer.setVisible(true); - this._buttonDisableRenderer.setVisible(false); - if (this.pressedActionEnabled) { - locNormalRenderer.stopAllActions(); - this._buttonClickedRenderer.stopAllActions(); - var zoomAction = cc.scaleTo(ccui.Button.ZOOM_ACTION_TIME_STEP, this._pressedTextureScaleXInSize + this._zoomScale, - this._pressedTextureScaleYInSize + this._zoomScale); - this._buttonClickedRenderer.runAction(zoomAction); - locNormalRenderer.setScale(this._pressedTextureScaleXInSize + this._zoomScale, this._pressedTextureScaleYInSize + this._zoomScale); + this._buttonScale9Renderer.setSpriteFrame(this._buttonClickedSpriteFrame); - this._titleRenderer.stopAllActions(); - this._titleRenderer.runAction(cc.scaleTo(ccui.Button.ZOOM_ACTION_TIME_STEP, 1 + this._zoomScale, 1 + this._zoomScale)); + if (this.pressedActionEnabled) { + this._buttonScale9Renderer.stopAllActions(); + + var zoomAction = cc.scaleTo(ccui.Button.ZOOM_ACTION_TIME_STEP, + 1.0 + this._zoomScale, + 1.0 + this._zoomScale); + this._buttonScale9Renderer.runAction(zoomAction); + + if(this._titleRenderer) { + this._titleRenderer.stopAllActions(); + this._titleRenderer.runAction(cc.scaleTo(ccui.Button.ZOOM_ACTION_TIME_STEP, + 1 + this._zoomScale, + 1 + this._zoomScale)); + } } } else { - locNormalRenderer.setVisible(true); - this._buttonClickedRenderer.setVisible(true); - this._buttonDisableRenderer.setVisible(false); - locNormalRenderer.stopAllActions(); - locNormalRenderer.setScale(this._normalTextureScaleXInSize + this._zoomScale, this._normalTextureScaleYInSize + this._zoomScale); + this._buttonScale9Renderer.setSpriteFrame(this._buttonClickedSpriteFrame); - this._titleRenderer.stopAllActions(); - this._titleRenderer.setScaleX(1 + this._zoomScale); - this._titleRenderer.setScaleY(1 + this._zoomScale); + this._buttonScale9Renderer.stopAllActions(); + this._buttonScale9Renderer.setScale(1.0 + this._zoomScale, 1.0 + this._zoomScale); + + if (this._titleRenderer) { + this._titleRenderer.stopAllActions(); + this._titleRenderer.setScaleX(1 + this._zoomScale); + this._titleRenderer.setScaleY(1 + this._zoomScale); + } } }, _onPressStateChangedToDisabled: function () { //if disable resource is null if (!this._disabledTextureLoaded){ - if (this._normalTextureLoaded && this._scale9Enabled) - this._buttonNormalRenderer.setState(ccui.Scale9Sprite.state.GRAY); + if (this._normalTextureLoaded && this._scale9Enabled) { + this._buttonScale9Renderer.setState(ccui.Scale9Sprite.state.GRAY); + } }else{ - this._buttonNormalRenderer.setVisible(false); - this._buttonDisableRenderer.setVisible(true); + this._buttonScale9Renderer.setSpriteFrame(this._buttonDisableSpriteFrame); } - this._buttonClickedRenderer.setVisible(false); - this._buttonNormalRenderer.setScale(this._normalTextureScaleXInSize, this._normalTextureScaleYInSize); - this._buttonClickedRenderer.setScale(this._pressedTextureScaleXInSize, this._pressedTextureScaleYInSize); + this._buttonScale9Renderer.setScale(1.0); }, _updateContentSize: function(){ @@ -600,10 +567,10 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ _onSizeChanged: function () { ccui.Widget.prototype._onSizeChanged.call(this); - this._updateTitleLocation(); + if(this._titleRenderer) { + this._updateTitleLocation(); + } this._normalTextureAdaptDirty = true; - this._pressedTextureAdaptDirty = true; - this._disabledTextureAdaptDirty = true; }, /** @@ -611,97 +578,12 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ * @returns {cc.Node} */ getVirtualRenderer: function () { - if (this._bright) { - switch (this._brightStyle) { - case ccui.Widget.BRIGHT_STYLE_NORMAL: - return this._buttonNormalRenderer; - case ccui.Widget.BRIGHT_STYLE_HIGH_LIGHT: - return this._buttonClickedRenderer; - default: - return null; - } - } else - return this._buttonDisableRenderer; + return this._buttonScale9Renderer; }, _normalTextureScaleChangedWithSize: function () { - if(this._ignoreSize && !this._unifySize){ - if(!this._scale9Enabled){ - this._buttonNormalRenderer.setScale(1); - this._normalTextureScaleXInSize = this._normalTextureScaleYInSize = 1; - } - }else{ - if (this._scale9Enabled){ - this._buttonNormalRenderer.setPreferredSize(this._contentSize); - this._normalTextureScaleXInSize = this._normalTextureScaleYInSize = 1; - this._buttonNormalRenderer.setScale(this._normalTextureScaleXInSize, this._normalTextureScaleYInSize); - }else{ - var textureSize = this._normalTextureSize; - if (textureSize.width <= 0 || textureSize.height <= 0) - { - this._buttonNormalRenderer.setScale(1); - return; - } - var scaleX = this._contentSize.width / textureSize.width; - var scaleY = this._contentSize.height / textureSize.height; - this._buttonNormalRenderer.setScaleX(scaleX); - this._buttonNormalRenderer.setScaleY(scaleY); - this._normalTextureScaleXInSize = scaleX; - this._normalTextureScaleYInSize = scaleY; - } - } - this._buttonNormalRenderer.setPosition(this._contentSize.width / 2, this._contentSize.height / 2); - }, - - _pressedTextureScaleChangedWithSize: function () { - if (this._ignoreSize && !this._unifySize) { - if (!this._scale9Enabled) { - this._buttonClickedRenderer.setScale(1); - this._pressedTextureScaleXInSize = this._pressedTextureScaleYInSize = 1; - } - } else { - if (this._scale9Enabled) { - this._buttonClickedRenderer.setPreferredSize(this._contentSize); - this._pressedTextureScaleXInSize = this._pressedTextureScaleYInSize = 1; - this._buttonClickedRenderer.setScale(this._pressedTextureScaleXInSize, this._pressedTextureScaleYInSize); - } else { - var textureSize = this._pressedTextureSize; - if (textureSize.width <= 0 || textureSize.height <= 0) { - this._buttonClickedRenderer.setScale(1); - return; - } - var scaleX = this._contentSize.width / textureSize.width; - var scaleY = this._contentSize.height / textureSize.height; - this._buttonClickedRenderer.setScaleX(scaleX); - this._buttonClickedRenderer.setScaleY(scaleY); - this._pressedTextureScaleXInSize = scaleX; - this._pressedTextureScaleYInSize = scaleY; - } - } - this._buttonClickedRenderer.setPosition(this._contentSize.width / 2, this._contentSize.height / 2); - }, - - _disabledTextureScaleChangedWithSize: function () { - if(this._ignoreSize && !this._unifySize){ - if (this._scale9Enabled) - this._buttonDisableRenderer.setScale(1); - }else { - if (this._scale9Enabled){ - this._buttonDisableRenderer.setScale(1); - this._buttonDisableRenderer.setPreferredSize(this._contentSize); - }else{ - var textureSize = this._disabledTextureSize; - if (textureSize.width <= 0 || textureSize.height <= 0) { - this._buttonDisableRenderer.setScale(1); - return; - } - var scaleX = this._contentSize.width / textureSize.width; - var scaleY = this._contentSize.height / textureSize.height; - this._buttonDisableRenderer.setScaleX(scaleX); - this._buttonDisableRenderer.setScaleY(scaleY); - } - } - this._buttonDisableRenderer.setPosition(this._contentSize.width / 2, this._contentSize.height / 2); + this._buttonScale9Renderer.setContentSize(this._contentSize); + this._buttonScale9Renderer.setPosition(this._contentSize.width / 2, this._contentSize.height / 2); }, _adaptRenderers: function(){ @@ -709,14 +591,6 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ this._normalTextureScaleChangedWithSize(); this._normalTextureAdaptDirty = false; } - if (this._pressedTextureAdaptDirty) { - this._pressedTextureScaleChangedWithSize(); - this._pressedTextureAdaptDirty = false; - } - if (this._disabledTextureAdaptDirty) { - this._disabledTextureScaleChangedWithSize(); - this._disabledTextureAdaptDirty = false; - } }, _updateTitleLocation: function(){ @@ -736,8 +610,10 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ * @param {String} text */ setTitleText: function (text) { - if(text === this.getTitleText()) - return; + if(text === this.getTitleText()) return; + + this._createTitleRendererIfNeeded(); + this._titleRenderer.setString(text); if (this._ignoreSize){ var s = this.getVirtualRendererSize(); @@ -752,7 +628,10 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ * @returns {String} text */ getTitleText: function () { - return this._titleRenderer.getString(); + if(this._titleRenderer) { + return this._titleRenderer.getString(); + } + return ""; }, /** @@ -760,6 +639,7 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ * @param {cc.Color} color */ setTitleColor: function (color) { + this._createTitleRendererIfNeeded(); this._titleRenderer.setFontFillColor(color); }, @@ -768,7 +648,10 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ * @returns {cc.Color} */ getTitleColor: function () { - return this._titleRenderer._getFillStyle(); + if (this._titleRenderer) { + return this._titleRenderer._getFillStyle(); + } + return cc.color.WHITE; }, /** @@ -776,6 +659,8 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ * @param {cc.Size} size */ setTitleFontSize: function (size) { + this._createTitleRendererIfNeeded(); + this._titleRenderer.setFontSize(size); this._fontSize = size; }, @@ -785,7 +670,10 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ * @returns {Number} */ getTitleFontSize: function () { - return this._titleRenderer.getFontSize(); + if (this._titleRenderer) { + return this._titleRenderer.getFontSize(); + } + return this._fontSize; }, /** @@ -821,6 +709,8 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ * @param {String} fontName */ setTitleFontName: function (fontName) { + this._createTitleRendererIfNeeded(); + this._titleRenderer.setFontName(fontName); this._fontName = fontName; }, @@ -839,7 +729,10 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ * @returns {String} */ getTitleFontName: function () { - return this._titleRenderer.getFontName(); + if(this._titleRenderer) { + return this._titleRenderer.getFontName(); + } + return this._fontName; }, _setTitleFont: function (font) { @@ -864,17 +757,19 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ _copySpecialProperties: function (uiButton) { this._prevIgnoreSize = uiButton._prevIgnoreSize; + this._capInsetsNormal = uiButton._capInsetsNormal; this.setScale9Enabled(uiButton._scale9Enabled); + this.loadTextureNormal(uiButton._normalFileName, uiButton._normalTexType); this.loadTexturePressed(uiButton._clickedFileName, uiButton._pressedTexType); this.loadTextureDisabled(uiButton._disabledFileName, uiButton._disabledTexType); - this.setCapInsetsNormalRenderer(uiButton._capInsetsNormal); - this.setCapInsetsPressedRenderer(uiButton._capInsetsPressed); - this.setCapInsetsDisabledRenderer(uiButton._capInsetsDisabled); - this.setTitleText(uiButton.getTitleText()); - this.setTitleFontName(uiButton.getTitleFontName()); - this.setTitleFontSize(uiButton.getTitleFontSize()); - this.setTitleColor(uiButton.getTitleColor()); + + if(uiButton._titleRenderer && uiButton._titleRenderer._string) { + this.setTitleText(uiButton.getTitleText()); + this.setTitleFontName(uiButton.getTitleFontName()); + this.setTitleFontSize(uiButton.getTitleFontSize()); + this.setTitleColor(uiButton.getTitleColor()); + } this.setPressedActionEnabled(uiButton.pressedActionEnabled); this.setZoomScale(uiButton._zoomScale); }, @@ -884,9 +779,7 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ if (this._titleRenderer !== null) titleSize = this._titleRenderer.getContentSize(); - var imageSize; - if (this._buttonNormalRenderer !== null) - imageSize = this._buttonNormalRenderer.getContentSize(); + var imageSize = this._buttonScale9Renderer.getContentSize(); var width = titleSize.width > imageSize.width ? titleSize.width : imageSize.width; var height = titleSize.height > imageSize.height ? titleSize.height : imageSize.height; diff --git a/extensions/ccui/uiwidgets/UIImageView.js b/extensions/ccui/uiwidgets/UIImageView.js index b7e6511bf9..970d015160 100644 --- a/extensions/ccui/uiwidgets/UIImageView.js +++ b/extensions/ccui/uiwidgets/UIImageView.js @@ -63,8 +63,8 @@ ccui.ImageView = ccui.Widget.extend(/** @lends ccui.ImageView# */{ }, _initRenderer: function () { - //todo create Scale9Sprite and setScale9Enabled(false) - this._imageRenderer = new cc.Sprite(); + this._imageRenderer = new ccui.Scale9Sprite(); + this._imageRenderer.setRenderingType(ccui.Scale9Sprite.RenderingType.SIMPLE); this.addProtectedChild(this._imageRenderer, ccui.ImageView.RENDERER_ZORDER, -1); }, @@ -74,9 +74,7 @@ ccui.ImageView = ccui.Widget.extend(/** @lends ccui.ImageView# */{ * @param {ccui.Widget.LOCAL_TEXTURE|ccui.Widget.PLIST_TEXTURE} texType */ loadTexture: function (fileName, texType) { - //todo use this code when _initRenderer use Scale9Sprite - //if (!fileName || (this._textureFile == fileName && this._imageTexType == texType)) { - if (!fileName) { + if (!fileName || (this._textureFile == fileName && this._imageTexType == texType)) { return; } var self = this; @@ -87,7 +85,15 @@ ccui.ImageView = ccui.Widget.extend(/** @lends ccui.ImageView# */{ if(!imageRenderer._textureLoaded){ imageRenderer.addEventListener("load", function(){ - self.loadTexture(self._textureFile, self._imageTexType); + if(!self._ignoreSize && cc.sizeEqualToSize(self._customSize, cc.size(0, 0))) { + self._customSize = self._imageRenderer.getContentSize(); + } + + self._imageTextureSize = imageRenderer.getContentSize(); + + self._updateChildrenDisplayedRGBA(); + + self._updateContentSizeWithTextureSize(self._imageTextureSize); }); } @@ -114,6 +120,10 @@ ccui.ImageView = ccui.Widget.extend(/** @lends ccui.ImageView# */{ break; } + if(!this._ignoreSize && cc.sizeEqualToSize(this._customSize, cc.size(0, 0))) { + this._customSize = this._imageRenderer.getContentSize(); + } + self._imageTextureSize = imageRenderer.getContentSize(); this._updateChildrenDisplayedRGBA(); @@ -128,9 +138,8 @@ ccui.ImageView = ccui.Widget.extend(/** @lends ccui.ImageView# */{ * Sets texture rect * @param {cc.Rect} rect */ - setTextureRect: function (rect) { - if (!this._scale9Enabled) - this._imageRenderer.setTextureRect(rect); + setTextureRect: function () { + cc.warn('ImageView.setTextureRect is deprecated!'); }, /** @@ -138,20 +147,17 @@ ccui.ImageView = ccui.Widget.extend(/** @lends ccui.ImageView# */{ * @param {Boolean} able */ setScale9Enabled: function (able) { - //todo setScale9Enabled if (this._scale9Enabled === able) return; this._scale9Enabled = able; - this.removeProtectedChild(this._imageRenderer); - this._imageRenderer = null; + if (this._scale9Enabled) { - this._imageRenderer = new ccui.Scale9Sprite(); + this._imageRenderer.setRenderingType(ccui.Scale9Sprite.RenderingType.SLICED); } else { - this._imageRenderer = new cc.Sprite(); + this._imageRenderer.setRenderingType(ccui.Scale9Sprite.RenderingType.SIMPLE); } - this.loadTexture(this._textureFile, this._imageTexType); - this.addProtectedChild(this._imageRenderer, ccui.ImageView.RENDERER_ZORDER, -1); + if (this._scale9Enabled) { var ignoreBefore = this._ignoreSize; this.ignoreContentAdaptWithSize(false); @@ -187,16 +193,15 @@ ccui.ImageView = ccui.Widget.extend(/** @lends ccui.ImageView# */{ * @param {cc.Rect} capInsets */ setCapInsets: function (capInsets) { - if(!capInsets) - return; + if(!capInsets) return; + var locInsets = this._capInsets; locInsets.x = capInsets.x; locInsets.y = capInsets.y; locInsets.width = capInsets.width; locInsets.height = capInsets.height; - if (!this._scale9Enabled) - return; + if (!this._scale9Enabled) return; this._imageRenderer.setCapInsets(capInsets); }, @@ -238,23 +243,7 @@ ccui.ImageView = ccui.Widget.extend(/** @lends ccui.ImageView# */{ }, _imageTextureScaleChangedWithSize: function () { - if (this._ignoreSize) { - if (!this._scale9Enabled) - this._imageRenderer.setScale(1.0); - } else { - if (this._scale9Enabled){ - this._imageRenderer.setPreferredSize(this._contentSize); - this._imageRenderer.setScale(1); - } else { - var textureSize = this._imageTextureSize; - if (textureSize.width <= 0.0 || textureSize.height <= 0.0) { - this._imageRenderer.setScale(1.0); - return; - } - this._imageRenderer.setScaleX(this._contentSize.width / textureSize.width); - this._imageRenderer.setScaleY(this._contentSize.height / textureSize.height); - } - } + this._imageRenderer.setContentSize(this._contentSize); this._imageRenderer.setPosition(this._contentSize.width / 2.0, this._contentSize.height / 2.0); }, @@ -274,9 +263,9 @@ ccui.ImageView = ccui.Widget.extend(/** @lends ccui.ImageView# */{ _copySpecialProperties: function (imageView) { if(imageView instanceof ccui.ImageView){ this._prevIgnoreSize = imageView._prevIgnoreSize; - this.setScale9Enabled(imageView._scale9Enabled); + this._capInsets = imageView._capInsets; this.loadTexture(imageView._textureFile, imageView._imageTexType); - this.setCapInsets(imageView._capInsets); + this.setScale9Enabled(imageView._scale9Enabled); } }, /** @@ -287,17 +276,12 @@ ccui.ImageView = ccui.Widget.extend(/** @lends ccui.ImageView# */{ * @override */ setContentSize: function(contentSize, height){ - if(height != null) + if (height) { contentSize = cc.size(contentSize, height); - ccui.Widget.prototype.setContentSize.call(this, contentSize); - if(!this._scale9Enabled){ - var iContentSize = this._imageRenderer.getContentSize(); - this._imageRenderer.setScaleX(contentSize.width / iContentSize.width); - this._imageRenderer.setScaleY(contentSize.height / iContentSize.height); - }else{ - this._imageRenderer.setContentSize(contentSize); } + ccui.Widget.prototype.setContentSize.call(this, contentSize); + this._imageRenderer.setContentSize(contentSize); } }); From cef6a7bf6d55793bfb26bc4e9a7a4e9a430dd0b5 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Sun, 18 Dec 2016 17:46:43 +0800 Subject: [PATCH 065/206] Fix Layer bake rendering issue --- cocos2d/core/layers/CCLayer.js | 2 +- cocos2d/core/layers/CCLayerCanvasRenderCmd.js | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/cocos2d/core/layers/CCLayer.js b/cocos2d/core/layers/CCLayer.js index 5e31df75a1..db1e783a2e 100644 --- a/cocos2d/core/layers/CCLayer.js +++ b/cocos2d/core/layers/CCLayer.js @@ -74,7 +74,7 @@ cc.Layer = cc.Node.extend(/** @lends cc.Layer# */{ return this._renderCmd._isBaked; }, - visit: function () { + visit: function (parent) { // quick return if not visible if (!this._visible) return; diff --git a/cocos2d/core/layers/CCLayerCanvasRenderCmd.js b/cocos2d/core/layers/CCLayerCanvasRenderCmd.js index 10e58d1003..3bc0905ebe 100644 --- a/cocos2d/core/layers/CCLayerCanvasRenderCmd.js +++ b/cocos2d/core/layers/CCLayerCanvasRenderCmd.js @@ -275,13 +275,13 @@ for (i = 0; i < len; i++) { child = children[i]; if (child._localZOrder < 0) - child._renderCmd.visit(this); + child.visit(node); else break; } cc.renderer.pushRenderCommand(this); for (; i < len; i++) { - children[i]._renderCmd.visit(this); + children[i].visit(node); } } else cc.renderer.pushRenderCommand(this); From 086cb2050497af43547df4667df92d8a8d3b3a81 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Sun, 18 Dec 2016 17:47:32 +0800 Subject: [PATCH 066/206] Remove useless code in Sprite for old batch node --- CCDebugger.js | 5 +- cocos2d/core/base-nodes/CCNode.js | 7 ++ cocos2d/core/sprites/CCSprite.js | 112 ------------------------------ 3 files changed, 9 insertions(+), 115 deletions(-) diff --git a/CCDebugger.js b/CCDebugger.js index da0b8e28d3..7acfc1cb0d 100644 --- a/CCDebugger.js +++ b/CCDebugger.js @@ -68,7 +68,8 @@ cc._LogInfos = { Node_resumeSchedulerAndActions: "resumeSchedulerAndActions is deprecated, please use resume instead.", Node_pauseSchedulerAndActions: "pauseSchedulerAndActions is deprecated, please use pause instead.", Node__arrayMakeObjectsPerformSelector: "Unknown callback function", - Node_reorderChild: "child must be non-null", + Node_reorderChild: "cc.Node.reorderChild(): child must be non-null", + Node_reorderChild_2: "cc.Node.reorderChild(): this child is not in children list", Node_runAction: "cc.Node.runAction(): action must be non-null", Node_schedule: "callback function must be non-null", Node_schedule_2: "interval must be positive", @@ -119,7 +120,6 @@ cc._LogInfos = { animationCache__parseVersion2_2: "cocos2d: cc.AnimationCache: Animation '%s' refers to frame '%s' which is not currently in the cc.SpriteFrameCache. This frame will not be added to the animation.", animationCache_addAnimations_2: "cc.AnimationCache.addAnimations(): Invalid texture file name", - Sprite_reorderChild: "cc.Sprite.reorderChild(): this child is not in children list", Sprite_ignoreAnchorPointForPosition: "cc.Sprite.ignoreAnchorPointForPosition(): it is invalid in cc.Sprite when using SpriteBatchNode", Sprite_setDisplayFrameWithAnimationName: "cc.Sprite.setDisplayFrameWithAnimationName(): Frame not found", Sprite_setDisplayFrameWithAnimationName_2: "cc.Sprite.setDisplayFrameWithAnimationName(): Invalid frame index", @@ -130,7 +130,6 @@ cc._LogInfos = { Sprite_initWithSpriteFrameName1: " is null, please check.", Sprite_initWithFile: "cc.Sprite.initWithFile(): filename should be non-null", Sprite_setDisplayFrameWithAnimationName_3: "cc.Sprite.setDisplayFrameWithAnimationName(): animationName must be non-null", - Sprite_reorderChild_2: "cc.Sprite.reorderChild(): child should be non-null", Sprite_addChild: "cc.Sprite.addChild(): cc.Sprite only supports cc.Sprites as children when using cc.SpriteBatchNode", Sprite_addChild_2: "cc.Sprite.addChild(): cc.Sprite only supports a sprite using same texture as children when using cc.SpriteBatchNode", Sprite_addChild_3: "cc.Sprite.addChild(): child should be non-null", diff --git a/cocos2d/core/base-nodes/CCNode.js b/cocos2d/core/base-nodes/CCNode.js index 4f05484c47..8e0479a0fc 100644 --- a/cocos2d/core/base-nodes/CCNode.js +++ b/cocos2d/core/base-nodes/CCNode.js @@ -1360,6 +1360,13 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{ */ reorderChild: function (child, zOrder) { cc.assert(child, cc._LogInfos.Node_reorderChild); + if (this._children.indexOf(child) === -1) { + cc.log(cc._LogInfos.Node_reorderChild_2); + return; + } + if (zOrder === child.zIndex) { + return; + } cc.renderer.childrenOrderDirty = this._reorderChildDirty = true; child.arrivalOrder = cc.s_globalOrderOfArrival; cc.s_globalOrderOfArrival++; diff --git a/cocos2d/core/sprites/CCSprite.js b/cocos2d/core/sprites/CCSprite.js index 9314462c67..26a2954ab7 100644 --- a/cocos2d/core/sprites/CCSprite.js +++ b/cocos2d/core/sprites/CCSprite.js @@ -276,8 +276,6 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{ * @param {cc.SpriteBatchNode} batchNode */ useBatchNode: function (batchNode) { - this.textureAtlas = batchNode.getTextureAtlas(); // weak ref - this._batchNode = batchNode; }, /** @@ -299,94 +297,10 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{ this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.transformDirty); }, - /** - * Sort all children of this sprite node. - * @override - */ - sortAllChildren: function () { - if (this._reorderChildDirty) { - var _children = this._children; - - cc.Node.prototype.sortAllChildren.call(this); - - if (this._batchNode) { - this._arrayMakeObjectsPerformSelector(_children, cc.Node._stateCallbackType.sortAllChildren); - } - - //don't need to check children recursively, that's done in visit of each child - this._reorderChildDirty = false; - } - - }, - - /** - * Reorders a child according to a new z value. (override cc.Node ) - * @param {cc.Node} child - * @param {Number} zOrder - * @override - */ - reorderChild: function (child, zOrder) { - cc.assert(child, cc._LogInfos.Sprite_reorderChild_2); - if (this._children.indexOf(child) === -1) { - cc.log(cc._LogInfos.Sprite_reorderChild); - return; - } - - if (zOrder === child.zIndex) - return; - - if (this._batchNode && !this._reorderChildDirty) { - this._setReorderChildDirtyRecursively(); - this._batchNode.reorderBatch(true); - } - cc.Node.prototype.reorderChild.call(this, child, zOrder); - }, - - /** - * Removes a child from the sprite. - * @param child - * @param cleanup whether or not cleanup all running actions - * @override - */ - removeChild: function (child, cleanup) { - if (this._batchNode) - this._batchNode.removeSpriteFromAtlas(child); - cc.Node.prototype.removeChild.call(this, child, cleanup); - }, - - /** - * Removes all children from the container. - * @param cleanup whether or not cleanup all running actions - * @override - */ - removeAllChildren: function (cleanup) { - var locChildren = this._children, locBatchNode = this._batchNode; - if (locBatchNode && locChildren != null) { - for (var i = 0, len = locChildren.length; i < len; i++) - locBatchNode.removeSpriteFromAtlas(locChildren[i]); - } - - cc.Node.prototype.removeAllChildren.call(this, cleanup); - this._hasChildren = false; - }, - // // cc.Node property overloads // - /** - * Sets whether ignore anchor point for positioning - * @param {Boolean} relative - * @override - */ - ignoreAnchorPointForPosition: function (relative) { - if (this._batchNode) { - cc.log(cc._LogInfos.Sprite_ignoreAnchorPointForPosition); - return; - } - cc.Node.prototype.ignoreAnchorPointForPosition.call(this, relative); - }, - /** * Sets whether the sprite should be flipped horizontally or not. * @param {Boolean} flippedX true if the sprite should be flipped horizontally, false otherwise. @@ -494,18 +408,6 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{ return this._batchNode; }, - _setReorderChildDirtyRecursively: function () { - //only set parents flag the first time - if (!this._reorderChildDirty) { - this._reorderChildDirty = true; - var pNode = this._parent; - while (pNode && pNode !== this._batchNode) { - pNode._setReorderChildDirtyRecursively(); - pNode = pNode.parent; - } - } - }, - // CCTextureProtocol /** * Returns the texture of the sprite node @@ -856,20 +758,6 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{ * layer.addChild(batch); */ setBatchNode: function (spriteBatchNode) { - var _t = this; - _t._batchNode = spriteBatchNode; // weak reference - - // self render - if (!_t._batchNode) { - _t.atlasIndex = cc.Sprite.INDEX_NOT_INITIALIZED; - _t.textureAtlas = null; - _t._recursiveDirty = false; - _t.dirty = false; - } else { - // using batch - _t._transformToBatch = cc.affineTransformIdentity(); - _t.textureAtlas = _t._batchNode.getTextureAtlas(); // weak ref - } }, // CCTextureProtocol From 1fe74d377312a213b8c031221f0e635c5f902b70 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Sun, 18 Dec 2016 17:47:57 +0800 Subject: [PATCH 067/206] Improve Layer webgl rendering --- cocos2d/core/layers/CCLayerWebGLRenderCmd.js | 242 +++++++++---------- 1 file changed, 116 insertions(+), 126 deletions(-) diff --git a/cocos2d/core/layers/CCLayerWebGLRenderCmd.js b/cocos2d/core/layers/CCLayerWebGLRenderCmd.js index ea60a3c70f..4a4b1b39e2 100644 --- a/cocos2d/core/layers/CCLayerWebGLRenderCmd.js +++ b/cocos2d/core/layers/CCLayerWebGLRenderCmd.js @@ -55,64 +55,28 @@ * cc.LayerColor's rendering objects of WebGL */ (function () { + var FLOAT_PER_VERTEX = 4; + cc.LayerColor.WebGLRenderCmd = function (renderable) { this._layerCmdCtor(renderable); this._needDraw = true; - this._matrix = new cc.math.Matrix4(); - this._matrix.identity(); - - // - var _t = this; - _t._squareVerticesAB = new ArrayBuffer(48); - _t._squareColorsAB = new ArrayBuffer(16); - - var locSquareVerticesAB = _t._squareVerticesAB, locSquareColorsAB = _t._squareColorsAB; - 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 = [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(); + this._matrix = null; + + this.initData(4); + this._color = new Uint32Array(1); + this._vertexBuffer = null; this._shaderProgram = cc.shaderCache.programForKey(cc.SHADER_POSITION_COLOR); }; var proto = cc.LayerColor.WebGLRenderCmd.prototype = Object.create(cc.Layer.WebGLRenderCmd.prototype); proto.constructor = cc.LayerColor.WebGLRenderCmd; - proto.rendering = function (ctx) { - var context = ctx || cc._renderContext; - var node = this._node; - - var wt = this._worldTransform; - this._matrix.mat[0] = wt.a; - this._matrix.mat[4] = wt.c; - this._matrix.mat[12] = wt.tx; - this._matrix.mat[1] = wt.b; - this._matrix.mat[5] = wt.d; - this._matrix.mat[13] = wt.ty; - - this._shaderProgram.use(); - this._shaderProgram._setUniformForMVPMatrixWithMat4(this._matrix); - context.enableVertexAttribArray(cc.VERTEX_ATTRIB_POSITION); - context.enableVertexAttribArray(cc.VERTEX_ATTRIB_COLOR); - cc.glBlendFunc(node._blendFunc.src, node._blendFunc.dst); - - // - // Attributes - // - context.bindBuffer(context.ARRAY_BUFFER, this._verticesFloat32Buffer); - context.vertexAttribPointer(cc.VERTEX_ATTRIB_POSITION, 3, context.FLOAT, false, 0, 0); - - context.bindBuffer(context.ARRAY_BUFFER, this._colorsUint8Buffer); - context.vertexAttribPointer(cc.VERTEX_ATTRIB_COLOR, 4, context.UNSIGNED_BYTE, true, 0, 0); - - context.drawArrays(context.TRIANGLE_STRIP, 0, this._squareVertices.length); + proto.initData = function (vertexCount) { + this._data = new ArrayBuffer(16 * vertexCount); + this._positionView = new Float32Array(this._data); + this._colorView = new Uint32Array(this._data); + this._dataDirty = true; }; proto.transform = function (parentCmd, recursive) { @@ -122,41 +86,68 @@ width = node._contentSize.width, height = node._contentSize.height; - var locSquareVertices = this._squareVertices; - locSquareVertices[1].x = width; - locSquareVertices[2].y = height; - locSquareVertices[3].x = width; - locSquareVertices[3].y = height; - locSquareVertices[0].z = - locSquareVertices[1].z = - locSquareVertices[2].z = - locSquareVertices[3].z = node._vertexZ; - - this._bindLayerVerticesBufferData(); + var pos = this._positionView; + pos[FLOAT_PER_VERTEX] = width; // br.x + pos[FLOAT_PER_VERTEX * 2 + 1] = height; // tl.y + pos[FLOAT_PER_VERTEX * 3] = width; // tr.x + pos[FLOAT_PER_VERTEX * 3 + 1] = height; // tr.y + pos[2].z = + pos[FLOAT_PER_VERTEX + 2] = + pos[FLOAT_PER_VERTEX * 2 + 2] = + pos[FLOAT_PER_VERTEX * 3 + 2] = node._vertexZ; + + this._dataDirty = true; }; proto._updateColor = function () { - var locDisplayedColor = this._displayedColor, locDisplayedOpacity = this._displayedOpacity, - locSquareColors = this._squareColors; + var color = this._displayedColor; + this._color[0] = ((this._displayedOpacity << 24) | (color.b << 16) | (color.g << 8) | color.r); + + var colors = this._colorView; for (var i = 0; i < 4; i++) { - locSquareColors[i].r = locDisplayedColor.r; - locSquareColors[i].g = locDisplayedColor.g; - locSquareColors[i].b = locDisplayedColor.b; - locSquareColors[i].a = locDisplayedOpacity; + colors[i * FLOAT_PER_VERTEX + 3] = this._color[0]; } - this._bindLayerColorsBufferData(); + this._dataDirty = true; }; - 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.rendering = function (ctx) { + var gl = ctx || cc._renderContext; + var node = this._node; + + if (!this._matrix) { + this._matrix = new cc.math.Matrix4(); + this._matrix.identity(); + } - proto._bindLayerColorsBufferData = function () { - var glContext = cc._renderContext; - glContext.bindBuffer(glContext.ARRAY_BUFFER, this._colorsUint8Buffer); - glContext.bufferData(glContext.ARRAY_BUFFER, this._squareColorsAB, glContext.STATIC_DRAW); + var wt = this._worldTransform; + this._matrix.mat[0] = wt.a; + this._matrix.mat[4] = wt.c; + this._matrix.mat[12] = wt.tx; + this._matrix.mat[1] = wt.b; + this._matrix.mat[5] = wt.d; + this._matrix.mat[13] = wt.ty; + + if (this._dataDirty) { + if (!this._vertexBuffer) { + this._vertexBuffer = gl.createBuffer(); + } + gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); + gl.bufferData(gl.ARRAY_BUFFER, this._data, gl.DYNAMIC_DRAW); + this._dataDirty = false; + } + + this._shaderProgram.use(); + this._shaderProgram._setUniformForMVPMatrixWithMat4(this._matrix); + cc.glBlendFunc(node._blendFunc.src, node._blendFunc.dst); + + gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); + gl.enableVertexAttribArray(cc.VERTEX_ATTRIB_POSITION); + gl.enableVertexAttribArray(cc.VERTEX_ATTRIB_COLOR); + + gl.vertexAttribPointer(cc.VERTEX_ATTRIB_POSITION, 3, gl.FLOAT, false, 16, 0); + gl.vertexAttribPointer(cc.VERTEX_ATTRIB_COLOR, 4, gl.UNSIGNED_BYTE, true, 16, 12); + + gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4); }; proto.updateBlendFunc = function (blendFunc) { @@ -167,6 +158,8 @@ * cc.LayerGradient's rendering objects of WebGL */ (function () { + var FLOAT_PER_VERTEX = 4; + cc.LayerGradient.WebGLRenderCmd = function (renderable) { cc.LayerColor.WebGLRenderCmd.call(this, renderable); this._needDraw = true; @@ -210,15 +203,8 @@ this._clippingRectDirty = true; 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++) { - locVertices.push(new cc.Vertex3F(0, 0, 0, locSquareVerticesAB, locVertex3FLen * i)); - } + if (this._positionView.length / FLOAT_PER_VERTEX < verticesLen) { + this.initData(verticesLen); } //init vertex @@ -244,19 +230,22 @@ 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); transMat = cc.affineTransformScale(transMat, tx, ty); + var pos = this._positionView; 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); - locVertices[i * 2].x = p0.x; - locVertices[i * 2].y = p0.y; - locVertices[i * 2].z = node._vertexZ; + var offset = i * 2 * FLOAT_PER_VERTEX; + pos[offset] = p0.x; + pos[offset + 1] = p0.y; + pos[offset + 2] = node._vertexZ; var p1 = cc.pointApplyAffineTransform(contentSize.width - locAnchor.x, y - locAnchor.y, transMat); - locVertices[i * 2 + 1].x = p1.x; - locVertices[i * 2 + 1].y = p1.y; - locVertices[i * 2 + 1].z = node._vertexZ; + offset += FLOAT_PER_VERTEX; + pos[offset] = p1.x; + pos[offset + 1] = p1.y; + pos[offset + 2] = node._vertexZ; } - this._bindLayerVerticesBufferData(); + this._dataDirty = true; }; proto._updateColor = function () { @@ -264,38 +253,31 @@ if (!stops || stops.length < 2) return; - //init color - var i, stopsLen = stops.length; - var locColors = this._squareColors, verticesLen = stopsLen * 2; - if (locColors.length < verticesLen) { - this._squareColorsAB = new ArrayBuffer(verticesLen * 4); - locColors.length = 0; - var locSquareColorsAB = this._squareColorsAB; - var locColorLen = cc._WebGLColor.BYTES_PER_ELEMENT; - for (i = 0; i < verticesLen; i++) { - locColors.push(new cc._WebGLColor(0, 0, 0, 255, locSquareColorsAB, locColorLen * i)); - } - } - - var opacityf = this._displayedOpacity / 255.0; //, displayColor = this._displayedColor; + var stopsLen = stops.length, + stopColor, + offset, + colors = this._colorView, + opacityf = this._displayedOpacity / 255; 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; - locSquareColor0.b = stopColor.b; - locSquareColor0.a = stopColor.a * opacityf; - - locSquareColor1.r = stopColor.r; - locSquareColor1.g = stopColor.g; - locSquareColor1.b = stopColor.b; - locSquareColor1.a = stopColor.a * opacityf; + stopColor = stops[i].color; + this._color[0] = ((stopColor.a*opacityf) << 24) | (stopColor.b << 16) | (stopColor.g << 8) | stopColor.r; + + offset = i * 2 * FLOAT_PER_VERTEX; + colors[offset + 3] = this._color[0]; + offset += FLOAT_PER_VERTEX; + colors[offset + 3] = this._color[0]; } - this._bindLayerColorsBufferData(); + this._dataDirty = true; }; proto.rendering = function (ctx) { var context = ctx || cc._renderContext, node = this._node; + if (!this._matrix) { + this._matrix = new cc.math.Matrix4(); + this._matrix.identity(); + } + //it is too expensive to use stencil to clip, so it use Scissor, //but it has a bug when layer rotated and layer's content size less than canvas's size. var clippingRect = this._getClippingRect(); @@ -310,20 +292,28 @@ this._matrix.mat[5] = wt.d; this._matrix.mat[13] = wt.ty; + if (this._dataDirty) { + if (!this._vertexBuffer) { + this._vertexBuffer = gl.createBuffer(); + } + gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); + gl.bufferData(gl.ARRAY_BUFFER, this._data, gl.DYNAMIC_DRAW); + this._dataDirty = false; + } + //draw gradient layer this._shaderProgram.use(); this._shaderProgram._setUniformForMVPMatrixWithMat4(this._matrix); - context.enableVertexAttribArray(cc.VERTEX_ATTRIB_POSITION); - context.enableVertexAttribArray(cc.VERTEX_ATTRIB_COLOR); cc.glBlendFunc(node._blendFunc.src, node._blendFunc.dst); - // - // Attributes - // - context.bindBuffer(context.ARRAY_BUFFER, this._verticesFloat32Buffer); - context.vertexAttribPointer(cc.VERTEX_ATTRIB_POSITION, 3, context.FLOAT, false, 0, 0); - context.bindBuffer(context.ARRAY_BUFFER, this._colorsUint8Buffer); - context.vertexAttribPointer(cc.VERTEX_ATTRIB_COLOR, 4, context.UNSIGNED_BYTE, true, 0, 0); - context.drawArrays(context.TRIANGLE_STRIP, 0, this._squareVertices.length); + + gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer); + gl.enableVertexAttribArray(cc.VERTEX_ATTRIB_POSITION); + gl.enableVertexAttribArray(cc.VERTEX_ATTRIB_COLOR); + + gl.vertexAttribPointer(cc.VERTEX_ATTRIB_POSITION, 3, gl.FLOAT, false, 16, 0); + gl.vertexAttribPointer(cc.VERTEX_ATTRIB_COLOR, 4, gl.UNSIGNED_BYTE, true, 16, 12); + + gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4); context.disable(context.SCISSOR_TEST); }; From a66c1752c87ceffb5e17db27993f40ae1d39e8fc Mon Sep 17 00:00:00 2001 From: pandamicro Date: Sun, 18 Dec 2016 17:52:33 +0800 Subject: [PATCH 068/206] Made xhr ontimeout callback work on all browsers --- CCBoot.js | 40 +++++++++++++++++++++++++++++++++------- cocos2d/audio/CCAudio.js | 10 +++++++++- 2 files changed, 42 insertions(+), 8 deletions(-) diff --git a/CCBoot.js b/CCBoot.js index f2a7d39139..a3e182f3b7 100644 --- a/CCBoot.js +++ b/CCBoot.js @@ -623,6 +623,9 @@ cc.loader = (function () { getXMLHttpRequest: function () { var xhr = window.XMLHttpRequest ? new window.XMLHttpRequest() : new ActiveXObject("MSXML2.XMLHTTP"); xhr.timeout = 10000; + if (xhr.ontimeout === undefined) { + xhr._timeoutId = -1; + } return xhr; }, @@ -770,12 +773,24 @@ cc.loader = (function () { } else { if (xhr.overrideMimeType) xhr.overrideMimeType("text\/plain; charset=utf-8"); xhr.onload = function () { - if (xhr.readyState === 4) + if (xhr._timeoutId >= 0) { + clearTimeout(xhr._timeoutId); + } + if (xhr.readyState === 4) { xhr.status === 200 ? cb(null, xhr.responseText) : cb({status:xhr.status, errorMessage:errInfo}, null); + } }; - xhr.onerror = xhr.ontimeout = function () { + xhr.onerror = function () { cb({status: xhr.status, errorMessage: errInfo}, null); }; + if (xhr.ontimeout === undefined) { + xhr._timeoutId = setTimeout(function () { + xhr.ontimeout(); + }, xhr.timeout); + } + xhr.ontimeout = function () { + cb({status: xhr.status, errorMessage: "Request timeout: " + errInfo}, null); + }; } xhr.send(null); } else { @@ -787,22 +802,34 @@ cc.loader = (function () { }, loadCsb: function(url, cb){ - var xhr = new XMLHttpRequest(), + var xhr = cc.loader.getXMLHttpRequest(), errInfo = "load " + url + " failed!"; xhr.open("GET", url, true); xhr.responseType = "arraybuffer"; xhr.onload = function () { + if (xhr._timeoutId >= 0) { + clearTimeout(xhr._timeoutId); + } var arrayBuffer = xhr.response; // Note: not oReq.responseText if (arrayBuffer) { window.msg = arrayBuffer; } - if(xhr.readyState === 4) + if (xhr.readyState === 4) { xhr.status === 200 ? cb(null, xhr.response) : cb({status:xhr.status, errorMessage:errInfo}, null); + } }; - xhr.onerror = xhr.ontimeout = function(){ + xhr.onerror = function(){ cb({status:xhr.status, errorMessage:errInfo}, null); }; + if (xhr.ontimeout === undefined) { + xhr._timeoutId = setTimeout(function () { + xhr.ontimeout(); + }, xhr.timeout); + } + xhr.ontimeout = function () { + cb({status: xhr.status, errorMessage: "Request timeout: " + errInfo}, null); + }; xhr.send(null); }, @@ -2650,8 +2677,7 @@ cc.game = /** @lends cc.game# */{ this._renderContext = cc._renderContext = cc.webglContext = cc.create3DContext(localCanvas, { 'stencil': true, - 'alpha': false, - 'preserveDrawingBuffer': false + 'alpha': false }); } // WebGL context created successfully diff --git a/cocos2d/audio/CCAudio.js b/cocos2d/audio/CCAudio.js index b10d6cb5a3..233160f09c 100644 --- a/cocos2d/audio/CCAudio.js +++ b/cocos2d/audio/CCAudio.js @@ -359,12 +359,15 @@ cc.Audio.WebAudio.prototype = { loadBuffer: function (url, cb) { if (!SWA) return; // WebAudio Buffer - var request = new XMLHttpRequest(); + var request = cc.loader.getXMLHttpRequest(); request.open("GET", url, true); request.responseType = "arraybuffer"; // Our asynchronous callback request.onload = function () { + if (request._timeoutId >= 0) { + clearTimeout(request._timeoutId); + } context["decodeAudioData"](request.response, function (buffer) { //success cb(null, buffer); @@ -378,6 +381,11 @@ cc.Audio.WebAudio.prototype = { request.onerror = function () { cb('request error - ' + url); }; + if (request.ontimeout === undefined) { + request._timeoutId = setTimeout(function () { + request.ontimeout(); + }, request.timeout); + } request.ontimeout = function () { cb('request timeout - ' + url); }; From f8aeb7f1340a3f13f7f382196c7f21e52c4ca391 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Sun, 18 Dec 2016 18:04:54 +0800 Subject: [PATCH 069/206] Try to fix adaptation issue on ios 9.2/9.3 --- cocos2d/core/platform/CCEGLView.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos2d/core/platform/CCEGLView.js b/cocos2d/core/platform/CCEGLView.js index 6588d420e2..27e37a6f50 100644 --- a/cocos2d/core/platform/CCEGLView.js +++ b/cocos2d/core/platform/CCEGLView.js @@ -985,7 +985,7 @@ cc.ContainerStrategy = cc.Class.extend(/** @lends cc.ContainerStrategy# */{ _setupContainer: function (view, w, h) { var locCanvas = cc.game.canvas, locContainer = cc.game.container; - if (cc.sys.os === cc.sys.OS_ANDROID) { + if (cc.sys.isMobile) { document.body.style.width = (view._isRotated ? h : w) + 'px'; document.body.style.height = (view._isRotated ? w : h) + 'px'; } From 3c06801764169e6c6ac104b2fd50b703dfcf9030 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Sun, 18 Dec 2016 19:02:39 +0800 Subject: [PATCH 070/206] Fix clear color not normalized issue --- cocos2d/core/CCDirectorWebGL.js | 5 ----- cocos2d/core/renderer/RendererWebGL.js | 2 +- 2 files changed, 1 insertion(+), 6 deletions(-) diff --git a/cocos2d/core/CCDirectorWebGL.js b/cocos2d/core/CCDirectorWebGL.js index 969ee75997..541ba50702 100644 --- a/cocos2d/core/CCDirectorWebGL.js +++ b/cocos2d/core/CCDirectorWebGL.js @@ -160,11 +160,6 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () { cc.eventManager.setEnabled(true); }; - _p._clear = function () { - var gl = cc._renderContext; - gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); - }; - _p.getVisibleSize = function () { //if (this._openGLView) { return this._openGLView.getVisibleSize(); diff --git a/cocos2d/core/renderer/RendererWebGL.js b/cocos2d/core/renderer/RendererWebGL.js index 593a4434ef..dd717d53e4 100644 --- a/cocos2d/core/renderer/RendererWebGL.js +++ b/cocos2d/core/renderer/RendererWebGL.js @@ -232,7 +232,7 @@ return { clear: function () { var gl = cc._renderContext; - gl.clearColor(this._clearColor.r, this._clearColor.g, this._clearColor.b, this._clearColor.a); + gl.clearColor(this._clearColor.r / 255, this._clearColor.g / 255, this._clearColor.b / 255, this._clearColor.a / 255); gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); }, From 10356b686ff956a24dc868e255632cc17591dcfb Mon Sep 17 00:00:00 2001 From: pandamicro Date: Sun, 18 Dec 2016 19:03:00 +0800 Subject: [PATCH 071/206] Fix armature skipped by RendererWebGL issue --- extensions/cocostudio/armature/CCArmature.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/extensions/cocostudio/armature/CCArmature.js b/extensions/cocostudio/armature/CCArmature.js index 80235b9dd2..29de0934e5 100644 --- a/extensions/cocostudio/armature/CCArmature.js +++ b/extensions/cocostudio/armature/CCArmature.js @@ -41,7 +41,6 @@ ccs.Armature = ccs.Node.extend(/** @lends ccs.Armature# */{ animation: null, armatureData: null, batchNode: null, - _textureAtlas: null, _parentBone: null, _boneDic: null, _topBoneList: null, @@ -70,6 +69,8 @@ ccs.Armature = ccs.Node.extend(/** @lends ccs.Armature# */{ this._armatureTransformDirty = true; this._blendFunc = {src: cc.BLEND_SRC, dst: cc.BLEND_DST}; name && ccs.Armature.prototype.init.call(this, name, parentBone); + // Hack way to avoid RendererWebGL from skipping Armature + this._texture = {}; }, /** From c40c22b2fab9361de69eeb424cc95b4f23b88b52 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Mon, 19 Dec 2016 12:11:17 +0800 Subject: [PATCH 072/206] Update engine version --- cocos2d/core/platform/CCConfig.js | 2 +- tools/build.xml | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/cocos2d/core/platform/CCConfig.js b/cocos2d/core/platform/CCConfig.js index 77f60e2748..027bede099 100644 --- a/cocos2d/core/platform/CCConfig.js +++ b/cocos2d/core/platform/CCConfig.js @@ -31,7 +31,7 @@ * @type {String} * @name cc.ENGINE_VERSION */ -window["CocosEngine"] = cc.ENGINE_VERSION = "Cocos2d-JS v3.13"; +window["CocosEngine"] = cc.ENGINE_VERSION = "Cocos2d-JS v3.14"; /** *

diff --git a/tools/build.xml b/tools/build.xml index a70c8a5a0b..d59cb38233 100644 --- a/tools/build.xml +++ b/tools/build.xml @@ -5,9 +5,9 @@ classpath="./compiler/compiler.jar"/> + sourceMapOutputFile="./../lib/cocos2d-js-v3.14-sourcemap" sourceMapFormat="V3"> @@ -306,9 +306,9 @@ + sourceMapOutputFile="./../lib/cocos2d-js-v3.14-core-sourcemap" sourceMapFormat="V3"> From 889db73791023b595a23319e76ca95fd57f4be5d Mon Sep 17 00:00:00 2001 From: pandamicro Date: Mon, 19 Dec 2016 19:16:54 +0800 Subject: [PATCH 073/206] Fix LabelTTF initial content size, texture rect not correct issue --- cocos2d/core/labelttf/CCLabelTTF.js | 4 +--- cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js | 1 + 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/cocos2d/core/labelttf/CCLabelTTF.js b/cocos2d/core/labelttf/CCLabelTTF.js index 6d367baee8..2342fc555c 100644 --- a/cocos2d/core/labelttf/CCLabelTTF.js +++ b/cocos2d/core/labelttf/CCLabelTTF.js @@ -133,9 +133,7 @@ cc.LabelTTF = cc.Sprite.extend(/** @lends cc.LabelTTF# */{ this._renderCmd._setFontStyle(this._fontName, fontSize, this._fontStyle, this._fontWeight); this.string = strInfo; this._renderCmd._setColorsString(); - if (this._string) { - this._renderCmd._updateTexture(); - } + 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 2071bd656f..51fb3888b4 100644 --- a/cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js +++ b/cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js @@ -402,6 +402,7 @@ cc.LabelTTF._firsrEnglish = /^[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]/; proto._updateTexture = function () { this._dirtyFlag = this._dirtyFlag & cc.Node._dirtyFlags.textDirty ^ this._dirtyFlag; var node = this._node; + node._needUpdateTexture = false; var locContentSize = node._contentSize; this._updateTTF(); var width = locContentSize.width, height = locContentSize.height; From 5ab5a4497daf3daf3efebcca1b0902b635d0af5f Mon Sep 17 00:00:00 2001 From: pandamicro Date: Mon, 19 Dec 2016 19:17:00 +0800 Subject: [PATCH 074/206] Fix widget ignoreSize default value issue --- extensions/cocostudio/loader/parsers/uiParser-1.x.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/cocostudio/loader/parsers/uiParser-1.x.js b/extensions/cocostudio/loader/parsers/uiParser-1.x.js index 6c58029fe5..e6904df62d 100644 --- a/extensions/cocostudio/loader/parsers/uiParser-1.x.js +++ b/extensions/cocostudio/loader/parsers/uiParser-1.x.js @@ -128,7 +128,7 @@ var parser = new Parser(); parser.generalAttributes = function (widget, options) { - widget._ignoreSize = options["ignoreSize"] || false; + widget._ignoreSize = options["ignoreSize"] || true; widget._sizeType = options["sizeType"] || 0; widget._positionType = options["positionType"] || 0; From fdaa7e27f7c0ab13e5a3b08342e0b0742189ba94 Mon Sep 17 00:00:00 2001 From: David DeSimone Date: Mon, 19 Dec 2016 14:55:42 -0500 Subject: [PATCH 075/206] Updating CCGLProgramState based on code review feedback. Removing uneeded object creation and lookup. Removing uneeded repeated calls to bind uniform values. Changing GLProgramState to not use cc.Class but instead using classic prototypical inheritance. --- cocos2d/shaders/CCGLProgram.js | 14 - cocos2d/shaders/CCGLProgramState.js | 574 ++++++++++++++-------------- 2 files changed, 288 insertions(+), 300 deletions(-) diff --git a/cocos2d/shaders/CCGLProgram.js b/cocos2d/shaders/CCGLProgram.js index c7c191fa76..eda7e7fc46 100644 --- a/cocos2d/shaders/CCGLProgram.js +++ b/cocos2d/shaders/CCGLProgram.js @@ -116,7 +116,6 @@ cc.GLProgram = cc.Class.extend(/** @lends cc.GLProgram# */{ ctor: function (vShaderFileName, fShaderFileName, glContext) { this._uniforms = {}; this._hashForUniforms = {}; - this._userUniforms = {}; this._glContext = glContext || cc._renderContext; vShaderFileName && fShaderFileName && this.init(vShaderFileName, fShaderFileName); @@ -232,7 +231,6 @@ cc.GLProgram = cc.Class.extend(/** @lends cc.GLProgram# */{ } this._glContext.linkProgram(this._programObj); - this._parseUniforms(); if (this._vertShader) this._glContext.deleteShader(this._vertShader); @@ -255,18 +253,6 @@ cc.GLProgram = cc.Class.extend(/** @lends cc.GLProgram# */{ return true; }, - _parseUniforms: function _parseUniforms() { - var activeUniforms = this._glContext.getProgramParameter(this._programObj, this._glContext.ACTIVE_UNIFORMS); - for (var i = 0; i < activeUniforms; ++i) { - var uniform = this._glContext.getActiveUniform(this._programObj, i); - uniform.location = this._glContext.getUniformLocation(this._programObj, uniform.name); - if (uniform.name.indexOf("CC_") !== 0) { - uniform.location = this._glContext.getUniformLocation(this._programObj, uniform.name); - uniform.name = uniform.name.replace("[]", ""); - this._userUniforms[uniform.name] = uniform; - } - } - }, /** * it will call glUseProgram() */ diff --git a/cocos2d/shaders/CCGLProgramState.js b/cocos2d/shaders/CCGLProgramState.js index eb95a3be0c..39aee7c290 100644 --- a/cocos2d/shaders/CCGLProgramState.js +++ b/cocos2d/shaders/CCGLProgramState.js @@ -25,298 +25,300 @@ ****************************************************************************/ var types = - { - GL_FLOAT: 0, - GL_INT: 1, - GL_FLOAT_VEC2: 2, - GL_FLOAT_VEC3: 3, - GL_FLOAT_VEC4: 4, - GL_FLOAT_MAT4: 5, - GL_CALLBACK: 6, - GL_TEXTURE: 7 - }; - -cc.UniformValue = cc.Class.extend({ - _uniform: null, - _glprogram: null, - _value: null, - _type: -1, - - ctor: function ctor(uniform, glprogram) { - this._uniform = uniform; - this._glprogram = glprogram; - }, - - setFloat: function setFloat(value) { - this._value = value; - this._type = types.GL_FLOAT; - }, - - setInt: function setInt(value) { - this._value = value; - this._type = types.GL_INT; - }, - - setVec2: function setVec2(v1, v2) { - this._value = [v1, v2]; - this._type = types.GL_FLOAT_VEC2; - }, - - setVec2v: function setVec2v(value) { - this._value = value; - this._type = types.GL_FLOAT_VEC2; - }, - - setVec3: function setVec3(v1, v2, v3) { - this._value = [v1, v2, v3]; - this._type = types.GL_FLOAT_VEC3; - }, - - setVec3v: function setVec3v(value) { - this._value = value; - this._type = types.GL_FLOAT_VEC3; - }, - - setVec4: function setVec4(v1, v2, v3, v4) { - this._value = [v1, v2, v3, v4]; - this._type = types.GL_FLOAT_VEC4; - }, - - setVec4v: function setVec4v(value) { - this._value = value; - this._type = types.GL_FLOAT_VEC4; - }, - - setMat4: function setMat4(value) { - this._value = value; - this._type = types.GL_FLOAT_MAT4; - }, - - setCallback: function setCallback(fn) { - this._value = fn; - this._type = types.GL_CALLBACK; - }, - - setTexture: function setTexture(textureId, textureUnit) { - this._value = textureUnit; - this._textureId = textureId; - this._type = types.GL_TEXTURE; - }, - - apply: function apply() { - switch (this._type) { - case types.GL_INT: - this._glprogram.setUniformLocationWith1i(this._uniform.location, this._value); - break; - case types.GL_FLOAT: - this._glprogram.setUniformLocationWith1f(this._uniform.location, this._value); - break; - case types.GL_FLOAT_VEC2: - this._glprogram.setUniformLocationWith2f(this._uniform.location, this._value[0], this._value[1]); - break; - case types.GL_FLOAT_VEC3: - this._glprogram.setUniformLocationWith3f(this._uniform.location, this._value[0], - this._value[1], this._value[2]); - break; - case types.GL_FLOAT_VEC4: - this._glprogram.setUniformLocationWith4f(this._uniform.location, this._value[0], - this._value[1], this._value[2], this._value[3]); - break; - case types.GL_FLOAT_MAT4: - this._glprogram.setUniformLocationWithMatrix4fv(this._uniform.location, this._value); - break; - case types.GL_CALLBACK: - this._value(this._glprogram, this._uniform); - break; - case types.GL_TEXTURE: - this._glprogram.setUniformLocationWith1i(this._uniform.location, this._value); - cc.glBindTexture2DN(this._value, this._textureId); - break; - default: - ; - } - }, -}); - -cc.GLProgramState = cc.Class.extend({ - _glprogram: null, - _uniformsByName: null, - _uniformsByLocation: null, - _boundTextureUnits: null, - _textureUnitIndex: 0, - - init: function init(glprogram) { - this._glprogram = glprogram; - this._uniformsByName = {}; - this._uniformsByLocation = {}; - this._boundTextureUnits = {}; - this._textureUnitIndex = 1; // Start at 1, as CC_Texture0 is bound to 0 - var userUniformKeys = Object.keys(glprogram._userUniforms); - for (var i = 0; i < userUniformKeys.length; ++i) { - var uniform = glprogram._userUniforms[userUniformKeys[i]]; - var uniformValue = new cc.UniformValue(uniform, glprogram); - this._uniformsByName[uniform.name] = uniformValue; - this._uniformsByLocation[uniform.location] = uniformValue; - } - }, - - apply: function apply(modelView) { - this.applyGLProgram(modelView); - this.applyUniforms(); - }, - - applyGLProgram: function applyGLProgram(modelView) { - this._glprogram.use(); - if (modelView) { - this._glprogram._setUniformForMVPMatrixWithMat4(modelView); - } - }, - - applyUniforms: function applyUniforms() { - var uniformKeys = Object.keys(this._uniformsByName); - for (var i = 0; i < uniformKeys.length; ++i) { - var uniform = this._uniformsByName[uniformKeys[i]]; - uniform.apply(); - } - }, - - setGLProgram: function setGLProgram(glprogram) { - this._glprogram = glprogram; - }, - - getGLProgram: function getGLProgram() { - return this._glprogram; - }, - - getUniformCount: function getUniformCount() { - return Object.keys(this._uniformsByName).length; - }, - - getUniformValue: function getUniformValue(uniform) - { - if (typeof uniform === 'string') { - return this._uniformsByName[uniform]; - } else { - return this._uniformsByLocation[uniform]; - } - }, - - // Accepts either string or uniform location - setUniformInt: function setUniformInt(uniform, value) { - var v = this.getUniformValue(uniform); - if (v) { - v.setInt(value); - } else { - cc.log("cocos2d: warning: Uniform not found: " + uniform); - } - }, - - setUniformFloat: function setUniformFloat(uniform, value) { - var v = this.getUniformValue(uniform); - if (v) { - v.setFloat(value); - } else { - cc.log("cocos2d: warning: Uniform not found: " + uniform); - } - }, - - setUniformVec2: function setUniformVec2(uniform, v1, v2) { - var v = this.getUniformValue(uniform); - if (v) { - v.setVec2(v1, v2); - } else { - cc.log("cocos2d: warning: Uniform not found: " + uniform); - } - }, + { + GL_FLOAT: 0, + GL_INT: 1, + GL_FLOAT_VEC2: 2, + GL_FLOAT_VEC3: 3, + GL_FLOAT_VEC4: 4, + GL_FLOAT_MAT4: 5, + GL_CALLBACK: 6, + GL_TEXTURE: 7 + }; + + + +cc.UniformValue = function (uniform, glprogram) { + this._uniform = uniform; + this._glprogram = glprogram; + + this._value = null; + this._currentBoundValue = null; + this._type = -1; +}; + +cc.UniformValue.prototype = { + setFloat: function setFloat(value) { + this._value = value; + this._type = types.GL_FLOAT; + }, + + setInt: function setInt(value) { + this._value = value; + this._type = types.GL_INT; + }, + + setVec2: function setVec2(v1, v2) { + this._value = [v1, v2]; + this._type = types.GL_FLOAT_VEC2; + }, + + setVec2v: function setVec2v(value) { + this._value = value; + this._type = types.GL_FLOAT_VEC2; + }, + + setVec3: function setVec3(v1, v2, v3) { + this._value = [v1, v2, v3]; + this._type = types.GL_FLOAT_VEC3; + }, + + setVec3v: function setVec3v(value) { + this._value = value; + this._type = types.GL_FLOAT_VEC3; + }, + + setVec4: function setVec4(v1, v2, v3, v4) { + this._value = [v1, v2, v3, v4]; + this._type = types.GL_FLOAT_VEC4; + }, + + setVec4v: function setVec4v(value) { + this._value = value; + this._type = types.GL_FLOAT_VEC4; + }, + + setMat4: function setMat4(value) { + this._value = value; + this._type = types.GL_FLOAT_MAT4; + }, + + setCallback: function setCallback(fn) { + this._value = fn; + this._type = types.GL_CALLBACK; + }, + + setTexture: function setTexture(textureId, textureUnit) { + this._value = textureUnit; + this._textureId = textureId; + this._type = types.GL_TEXTURE; + }, + + apply: function apply() { + if (this._currentBoundValue === this._value + && this._type !== types.GL_CALLBACK) { + return; + } + + this._currentBoundValue = this._value; + switch (this._type) { + case types.GL_INT: + this._glprogram.setUniformLocationWith1i(this._uniform.location, this._value); + break; + case types.GL_FLOAT: + this._glprogram.setUniformLocationWith1f(this._uniform.location, this._value); + break; + case types.GL_FLOAT_VEC2: + this._glprogram.setUniformLocationWith2f(this._uniform.location, this._value[0], this._value[1]); + break; + case types.GL_FLOAT_VEC3: + this._glprogram.setUniformLocationWith3f(this._uniform.location, this._value[0], + this._value[1], this._value[2]); + break; + case types.GL_FLOAT_VEC4: + this._glprogram.setUniformLocationWith4f(this._uniform.location, this._value[0], + this._value[1], this._value[2], this._value[3]); + break; + case types.GL_FLOAT_MAT4: + this._glprogram.setUniformLocationWithMatrix4fv(this._uniform.location, this._value); + break; + case types.GL_CALLBACK: + this._value(this._glprogram, this._uniform); + break; + case types.GL_TEXTURE: + this._glprogram.setUniformLocationWith1i(this._uniform.location, this._value); + cc.glBindTexture2DN(this._value, this._textureId); + break; + default: + ; + } + }, +}; + +cc.GLProgramState = function (glprogram) { + this._glprogram = glprogram; + this._uniforms = []; + this._uniformsByName = {}; + this._uniformsByLocation = {}; + this._boundTextureUnits = {}; + this._textureUnitIndex = 1; // Start at 1, as CC_Texture0 is bound to 0 + + + var activeUniforms = glprogram._glContext.getProgramParameter(glprogram._programObj, + glprogram._glContext.ACTIVE_UNIFORMS); - setUniformVec2v: function setUniformVec2v(uniform, value) { - var v = this.getUniformValue(uniform); - if (v) { - v.setVec2v(value); - } else { - cc.log("cocos2d: warning: Uniform not found: " + uniform); - } - }, + for (var i = 0; i < activeUniforms; ++i) { + var uniform = glprogram._glContext.getActiveUniform(glprogram._programObj, i); + if (uniform.name.indexOf("CC_") !== 0) { + uniform.location = glprogram._glContext.getUniformLocation(glprogram._programObj, + uniform.name); + uniform.name = uniform.name.replace("[]", ""); + var uniformValue = new cc.UniformValue(uniform, glprogram); + this._uniforms.push(uniformValue); + this._uniformsByName[uniform.name] = i; + this._uniformsByLocation[uniform.location] = i; + } + } +}; + +cc.GLProgramState.prototype = { + apply: function apply(modelView) { + this._glprogram.use(); + if (modelView) { + this._glprogram._setUniformForMVPMatrixWithMat4(modelView); + } + + for (var i = 0; i < this._uniforms.length; ++i) { + this._uniforms[i].apply(); + } + }, + + setGLProgram: function setGLProgram(glprogram) { + this._glprogram = glprogram; + }, + + getGLProgram: function getGLProgram() { + return this._glprogram; + }, + + getUniformCount: function getUniformCount() { + return this._uniforms.length; + }, + + getUniformValue: function getUniformValue(uniform) + { + if (typeof uniform === 'string') { + return this._uniforms[this._uniformsByName[uniform]]; + } else { + return this._uniforms[this._uniformsByLocation[uniform]]; + } + }, + + // Accepts either string or uniform location + setUniformInt: function setUniformInt(uniform, value) { + var v = this.getUniformValue(uniform); + if (v) { + v.setInt(value); + } else { + cc.log("cocos2d: warning: Uniform not found: " + uniform); + } + }, + + setUniformFloat: function setUniformFloat(uniform, value) { + var v = this.getUniformValue(uniform); + if (v) { + v.setFloat(value); + } else { + cc.log("cocos2d: warning: Uniform not found: " + uniform); + } + }, + + setUniformVec2: function setUniformVec2(uniform, v1, v2) { + var v = this.getUniformValue(uniform); + if (v) { + v.setVec2(v1, v2); + } else { + cc.log("cocos2d: warning: Uniform not found: " + uniform); + } + }, + + setUniformVec2v: function setUniformVec2v(uniform, value) { + var v = this.getUniformValue(uniform); + if (v) { + v.setVec2v(value); + } else { + cc.log("cocos2d: warning: Uniform not found: " + uniform); + } + }, - setUniformVec3: function setUniformVec3(uniform, v1, v2, v3) { - var v = this.getUniformValue(uniform); - if (v) { - v.setVec3(v1, v2, v3); - } else { - cc.log("cocos2d: warning: Uniform not found: " + uniform); - } - }, - - setUniformVec3v: function setUniformVec3v(uniform, value) { - var v = this.getUniformValue(uniform); - if (v) { - v.setVec3v(value); - } else { - cc.log("cocos2d: warning: Uniform not found: " + uniform); - } - }, + setUniformVec3: function setUniformVec3(uniform, v1, v2, v3) { + var v = this.getUniformValue(uniform); + if (v) { + v.setVec3(v1, v2, v3); + } else { + cc.log("cocos2d: warning: Uniform not found: " + uniform); + } + }, + + setUniformVec3v: function setUniformVec3v(uniform, value) { + var v = this.getUniformValue(uniform); + if (v) { + v.setVec3v(value); + } else { + cc.log("cocos2d: warning: Uniform not found: " + uniform); + } + }, - setUniformVec4: function setUniformVec4(uniform, v1, v2, v3, v4) { - var v = this.getUniformValue(uniform); - if (v) { - v.setVec4(v1, v2, v3, v4); - } else { - cc.log("cocos2d: warning: Uniform not found: " + uniform); - } - }, - - setUniformVec4v: function setUniformVec4v(uniform, value) { - var v = this.getUniformValue(uniform); - if (v) { - v.setVec4v(value); - } else { - cc.log("cocos2d: warning: Uniform not found: " + uniform); - } - }, + setUniformVec4: function setUniformVec4(uniform, v1, v2, v3, v4) { + var v = this.getUniformValue(uniform); + if (v) { + v.setVec4(v1, v2, v3, v4); + } else { + cc.log("cocos2d: warning: Uniform not found: " + uniform); + } + }, + + setUniformVec4v: function setUniformVec4v(uniform, value) { + var v = this.getUniformValue(uniform); + if (v) { + v.setVec4v(value); + } else { + cc.log("cocos2d: warning: Uniform not found: " + uniform); + } + }, - setUniformMat4: function setUniformMat4(uniform, value) { - var v = this.getUniformValue(uniform); - if (v) { - v.setMat4(value); - } else { - cc.log("cocos2d: warning: Uniform not found: " + uniform); - } - - }, - - setUniformCallback: function setUniformCallback(uniform, callback) { - var v = this.getUniformValue(uniform); - if (v) { - v.setCallback(callback); - } else { - cc.log("cocos2d: warning: Uniform not found: " + uniform); - } - - }, - - setUniformTexture: function setUniformTexture(uniform, texture) { - var uniformValue = this.getUniformValue(uniform); - if (uniformValue) { - var textureUnit = this._boundTextureUnits[uniform]; - if (textureUnit) { - uniformValue.setTexture(texture, textureUnit); - } else { - uniformValue.setTexture(texture, this._textureUnitIndex); - this._boundTextureUnits[uniform] = this._textureUnitIndex++; - } - } - } -}); + setUniformMat4: function setUniformMat4(uniform, value) { + var v = this.getUniformValue(uniform); + if (v) { + v.setMat4(value); + } else { + cc.log("cocos2d: warning: Uniform not found: " + uniform); + } + + }, + + setUniformCallback: function setUniformCallback(uniform, callback) { + var v = this.getUniformValue(uniform); + if (v) { + v.setCallback(callback); + } else { + cc.log("cocos2d: warning: Uniform not found: " + uniform); + } + + }, + + setUniformTexture: function setUniformTexture(uniform, texture) { + var uniformValue = this.getUniformValue(uniform); + if (uniformValue) { + var textureUnit = this._boundTextureUnits[uniform]; + if (textureUnit) { + uniformValue.setTexture(texture, textureUnit); + } else { + uniformValue.setTexture(texture, this._textureUnitIndex); + this._boundTextureUnits[uniform] = this._textureUnitIndex++; + } + } + } +}; cc.GLProgramState._cache = {}; cc.GLProgramState.getOrCreateWithGLProgram = function (glprogram) { - var programState = cc.GLProgramState._cache[glprogram.__instanceId]; - if (!programState) { - programState = new cc.GLProgramState(); - programState.init(glprogram); - cc.GLProgramState._cache[glprogram.__instanceId] = programState; - } - - return programState; + var programState = cc.GLProgramState._cache[glprogram.__instanceId]; + if (!programState) { + programState = new cc.GLProgramState(glprogram); + cc.GLProgramState._cache[glprogram.__instanceId] = programState; + } + + return programState; }; From 721abd1eab939a32a5f5d835fc0075ab40f2b2c2 Mon Sep 17 00:00:00 2001 From: David DeSimone Date: Mon, 19 Dec 2016 16:15:17 -0500 Subject: [PATCH 076/206] Preventing issue where mutating the value of an array after setting it may propigate to changing the GLProgramState --- cocos2d/shaders/CCGLProgramState.js | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/cocos2d/shaders/CCGLProgramState.js b/cocos2d/shaders/CCGLProgramState.js index 39aee7c290..1da5103db6 100644 --- a/cocos2d/shaders/CCGLProgramState.js +++ b/cocos2d/shaders/CCGLProgramState.js @@ -64,7 +64,7 @@ cc.UniformValue.prototype = { }, setVec2v: function setVec2v(value) { - this._value = value; + this._value = value.slice(0); this._type = types.GL_FLOAT_VEC2; }, @@ -74,7 +74,7 @@ cc.UniformValue.prototype = { }, setVec3v: function setVec3v(value) { - this._value = value; + this._value = value.slice(0); this._type = types.GL_FLOAT_VEC3; }, @@ -84,12 +84,12 @@ cc.UniformValue.prototype = { }, setVec4v: function setVec4v(value) { - this._value = value; + this._value = value.slice(0); this._type = types.GL_FLOAT_VEC4; }, setMat4: function setMat4(value) { - this._value = value; + this._value = value.slice(0); this._type = types.GL_FLOAT_MAT4; }, From 2c13088e5b77c5a76d4bc045f1dd07ff981b6443 Mon Sep 17 00:00:00 2001 From: David DeSimone Date: Mon, 19 Dec 2016 16:41:01 -0500 Subject: [PATCH 077/206] Fixing color/opacity rendering issue with CCAtlastNodeWebGLRendering. Fixing missing function call to setUniformsForBuiltins in TextureWebGL --- cocos2d/core/base-nodes/CCAtlasNodeWebGLRenderCmd.js | 6 ++++-- cocos2d/core/textures/TexturesWebGL.js | 2 ++ 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/cocos2d/core/base-nodes/CCAtlasNodeWebGLRenderCmd.js b/cocos2d/core/base-nodes/CCAtlasNodeWebGLRenderCmd.js index 085e3770bb..5810d00794 100644 --- a/cocos2d/core/base-nodes/CCAtlasNodeWebGLRenderCmd.js +++ b/cocos2d/core/base-nodes/CCAtlasNodeWebGLRenderCmd.js @@ -32,12 +32,14 @@ this._textureAtlas = null; this._colorUnmodified = cc.color.WHITE; this._colorF32Array = null; + this._uniformColor = null; this._matrix = new cc.math.Matrix4(); this._matrix.identity(); //shader stuff this._shaderProgram = cc.shaderCache.programForKey(cc.SHADER_POSITION_TEXTURE_UCOLOR); + this._uniformColor = cc._renderContext.getUniformLocation(this._shaderProgram.getProgram(), "u_color"); }; var proto = cc.AtlasNode.WebGLRenderCmd.prototype = Object.create(cc.Node.WebGLRenderCmd.prototype); @@ -69,8 +71,8 @@ this._glProgramState.apply(this._matrix); cc.glBlendFunc(node._blendFunc.src, node._blendFunc.dst); - if (this._colorF32Array) { - this._glProgramState.setUniformVec4v("u_color", this._colorF32Array); + if (this._uniformColor && this._colorF32Array) { + context.uniform4fv(this._uniformColor, this._colorF32Array); this._textureAtlas.drawNumberOfQuads(node.quadsToDraw, 0); } }; diff --git a/cocos2d/core/textures/TexturesWebGL.js b/cocos2d/core/textures/TexturesWebGL.js index 49a33ae647..42d0d3e7ec 100644 --- a/cocos2d/core/textures/TexturesWebGL.js +++ b/cocos2d/core/textures/TexturesWebGL.js @@ -340,6 +340,7 @@ cc._tmp.WebGLTexture2D = function () { width + point.x, height + point.y, 0.0]; self._glProgramState.apply(); + self._glProgramState._glprogram.setUniformsForBuiltins(); cc.glBindTexture2D(self); @@ -369,6 +370,7 @@ cc._tmp.WebGLTexture2D = function () { rect.x + rect.width, rect.y + rect.height /*0.0*/]; self._glProgramState.apply(); + self._glProgramState._glprogram.setUniformsForBuiltins(); cc.glBindTexture2D(self); From 781c3c8b01f304814b97911901fff0e78b4370fa Mon Sep 17 00:00:00 2001 From: David DeSimone Date: Mon, 19 Dec 2016 17:13:20 -0500 Subject: [PATCH 078/206] Fixing improper logical error in assigning values to uniformByName and uniformByLocation map --- cocos2d/shaders/CCGLProgramState.js | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/cocos2d/shaders/CCGLProgramState.js b/cocos2d/shaders/CCGLProgramState.js index 1da5103db6..edfa2ae175 100644 --- a/cocos2d/shaders/CCGLProgramState.js +++ b/cocos2d/shaders/CCGLProgramState.js @@ -156,7 +156,8 @@ cc.GLProgramState = function (glprogram) { var activeUniforms = glprogram._glContext.getProgramParameter(glprogram._programObj, glprogram._glContext.ACTIVE_UNIFORMS); - + + var count = 0; for (var i = 0; i < activeUniforms; ++i) { var uniform = glprogram._glContext.getActiveUniform(glprogram._programObj, i); if (uniform.name.indexOf("CC_") !== 0) { @@ -165,8 +166,9 @@ cc.GLProgramState = function (glprogram) { uniform.name = uniform.name.replace("[]", ""); var uniformValue = new cc.UniformValue(uniform, glprogram); this._uniforms.push(uniformValue); - this._uniformsByName[uniform.name] = i; - this._uniformsByLocation[uniform.location] = i; + this._uniformsByName[uniform.name] = count; + this._uniformsByLocation[uniform.location] = count; + count++; } } }; From c83d33b33209d5c6210d8b7e0c169b6caeafd135 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Tue, 20 Dec 2016 11:53:50 +0800 Subject: [PATCH 079/206] Fix issues reported by QA --- cocos2d/core/utils/CCProfiler.js | 6 +++--- cocos2d/particle/CCParticleBatchNode.js | 2 +- cocos2d/render-texture/CCRenderTexture.js | 1 + cocos2d/render-texture/CCRenderTextureWebGLRenderCmd.js | 7 +------ extensions/ccui/uiwidgets/UIVideoPlayer.js | 9 ++++++--- extensions/ccui/uiwidgets/UIWebView.js | 9 ++++++--- 6 files changed, 18 insertions(+), 16 deletions(-) diff --git a/cocos2d/core/utils/CCProfiler.js b/cocos2d/core/utils/CCProfiler.js index 5d314f629d..94d0c41eb4 100644 --- a/cocos2d/core/utils/CCProfiler.js +++ b/cocos2d/core/utils/CCProfiler.js @@ -86,9 +86,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).toString() + mode; - _drawsLabel.innerText = (0 | cc.g_NumberOfDraws).toString(); + _SPFLabel.innerHTML = _lastSPF.toFixed(3); + _FPSLabel.innerHTML = _frameRate.toFixed(1).toString() + mode; + _drawsLabel.innerHTML = (0 | cc.g_NumberOfDraws).toString(); } } }; diff --git a/cocos2d/particle/CCParticleBatchNode.js b/cocos2d/particle/CCParticleBatchNode.js index 3db6117391..38959df638 100644 --- a/cocos2d/particle/CCParticleBatchNode.js +++ b/cocos2d/particle/CCParticleBatchNode.js @@ -154,7 +154,7 @@ cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{ var cmd = this._renderCmd; cmd.visit(parent && parent._renderCmd); - renderer.pushRenderCommand(cmd); + cc.renderer.pushRenderCommand(cmd); cmd._dirtyFlag = 0; }, diff --git a/cocos2d/render-texture/CCRenderTexture.js b/cocos2d/render-texture/CCRenderTexture.js index ffb443f002..97bd77700a 100644 --- a/cocos2d/render-texture/CCRenderTexture.js +++ b/cocos2d/render-texture/CCRenderTexture.js @@ -140,6 +140,7 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{ var renderer = cc.renderer, cmd = this._renderCmd; cmd.visit(parent && parent._renderCmd); + renderer.pushRenderCommand(cmd); this.sprite.visit(this); cmd._dirtyFlag = 0; }, diff --git a/cocos2d/render-texture/CCRenderTextureWebGLRenderCmd.js b/cocos2d/render-texture/CCRenderTextureWebGLRenderCmd.js index 20cc4dec06..9abe91feaf 100644 --- a/cocos2d/render-texture/CCRenderTextureWebGLRenderCmd.js +++ b/cocos2d/render-texture/CCRenderTextureWebGLRenderCmd.js @@ -100,7 +100,7 @@ for (var i = 0; i < locChildren.length; i++) { var getChild = locChildren[i]; if (getChild !== node.sprite) { - getChild._renderCmd.visit(node.sprite._renderCmd); //TODO it's very Strange + getChild.visit(node.sprite); //TODO it's very Strange } } node.end(); @@ -363,9 +363,4 @@ gl.clearDepth(depthClearValue); node.end(); }; - - proto.visit = function (parentCmd) { - this._syncStatus(parentCmd); - cc.renderer.pushRenderCommand(this); - }; })(); diff --git a/extensions/ccui/uiwidgets/UIVideoPlayer.js b/extensions/ccui/uiwidgets/UIVideoPlayer.js index 38279832ce..e4e3351040 100644 --- a/extensions/ccui/uiwidgets/UIVideoPlayer.js +++ b/extensions/ccui/uiwidgets/UIVideoPlayer.js @@ -420,14 +420,17 @@ ccui.VideoPlayer.EventType = { scaleY = scaleY / dpr; } if (this._loaded === false) return; - var cw = node._contentSize.width, + var containerStyle = cc.game.container.style, + offsetX = parseInt(containerStyle.paddingLeft), + offsetY = parseInt(containerStyle.paddingBottom), + cw = node._contentSize.width, ch = node._contentSize.height; var a = t.a * scaleX, b = t.b, c = t.c, d = t.d * scaleY, - tx = t.tx * scaleX - cw / 2 + cw * node._scaleX / 2 * scaleX, - ty = t.ty * scaleY - ch / 2 + ch * node._scaleY / 2 * scaleY; + tx = offsetX + t.tx * scaleX - cw / 2 + cw * node._scaleX / 2 * scaleX, + ty = offsetY + t.ty * scaleY - ch / 2 + ch * node._scaleY / 2 * scaleY; var matrix = "matrix(" + a + "," + b + "," + c + "," + d + "," + tx + "," + -ty + ")"; this._video.style["transform"] = matrix; this._video.style["-webkit-transform"] = matrix; diff --git a/extensions/ccui/uiwidgets/UIWebView.js b/extensions/ccui/uiwidgets/UIWebView.js index 3ed36ef467..b301a9580f 100644 --- a/extensions/ccui/uiwidgets/UIWebView.js +++ b/extensions/ccui/uiwidgets/UIWebView.js @@ -363,14 +363,17 @@ ccui.WebView.EventType = { scaleY = scaleY / dpr; } if (this._loaded === false) return; - var cw = node._contentSize.width, + var containerStyle = cc.game.container.style, + offsetX = parseInt(containerStyle.paddingLeft), + offsetY = parseInt(containerStyle.paddingBottom), + cw = node._contentSize.width, ch = node._contentSize.height; var a = t.a * scaleX, b = t.b, c = t.c, d = t.d * scaleY, - tx = t.tx * scaleX - cw / 2 + cw * node._scaleX / 2 * scaleX, - ty = t.ty * scaleY - ch / 2 + ch * node._scaleY / 2 * scaleY; + tx = offsetX + t.tx * scaleX - cw / 2 + cw * node._scaleX / 2 * scaleX, + ty = offsetY + t.ty * scaleY - ch / 2 + ch * node._scaleY / 2 * scaleY; var matrix = "matrix(" + a + "," + b + "," + c + "," + d + "," + tx + "," + -ty + ")"; this._div.style["transform"] = matrix; this._div.style["-webkit-transform"] = matrix; From 725a8990410161b9d8281b33145697b4921ce6fe Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Tue, 20 Dec 2016 14:26:08 +0800 Subject: [PATCH 080/206] useWebAudio --- cocos2d/audio/CCAudio.js | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/cocos2d/audio/CCAudio.js b/cocos2d/audio/CCAudio.js index 233160f09c..0e1428e855 100644 --- a/cocos2d/audio/CCAudio.js +++ b/cocos2d/audio/CCAudio.js @@ -354,7 +354,7 @@ cc.Audio.WebAudio.prototype = { cache: {}, - useWebAudio: false, + useWebAudio: true, loadBuffer: function (url, cb) { if (!SWA) return; // WebAudio Buffer @@ -712,6 +712,7 @@ cc.Audio.WebAudio.prototype = { } + var cache = loader.useWebAudio; loader.useWebAudio = true; cc.loader.load(url, function (audio) { audio = cc.loader.getRes(url); @@ -720,7 +721,7 @@ cc.Audio.WebAudio.prototype = { audio.play(0, loop || false); effectList.push(audio); }); - loader.useWebAudio = false; + loader.useWebAudio = cache; return audio; }, From cfbb0c7f21e29163bfd1ee66e8e01769815ff526 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Mon, 26 Dec 2016 11:34:20 +0800 Subject: [PATCH 081/206] Force reset texture rect when sprite texture changed --- .../core/sprites/CCSpriteWebGLRenderCmd.js | 29 +++++++++---------- 1 file changed, 13 insertions(+), 16 deletions(-) diff --git a/cocos2d/core/sprites/CCSpriteWebGLRenderCmd.js b/cocos2d/core/sprites/CCSpriteWebGLRenderCmd.js index f10773b1d7..060908aca2 100644 --- a/cocos2d/core/sprites/CCSpriteWebGLRenderCmd.js +++ b/cocos2d/core/sprites/CCSpriteWebGLRenderCmd.js @@ -230,22 +230,19 @@ proto._setTexture = function (texture) { var node = this._node; - // If batchnode, then texture id should be the same - if (node._batchNode) { - if (node._batchNode.texture !== texture) { - cc.log(cc._LogInfos.Sprite_setTexture); - return; - } - } else { - if (node._texture !== texture) { - node._textureLoaded = texture ? texture._textureLoaded : false; - node._texture = texture; - this._updateBlendFunc(); - - if (node._textureLoaded) { - // Force refresh the render command list - cc.renderer.childrenOrderDirty = true; - } + if (node._texture !== texture) { + node._textureLoaded = texture ? texture._textureLoaded : false; + node._texture = texture; + + // Update texture rect and blend func + var texSize = texture._contentSize; + var rect = cc.rect(0, 0, texSize.width, texSize.height); + node.setTextureRect(rect); + this._updateBlendFunc(); + + if (node._textureLoaded) { + // Force refresh the render command list + cc.renderer.childrenOrderDirty = true; } } }; From ced6bc4307e110d4e90073a16249600a818b20dd Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Mon, 26 Dec 2016 14:19:41 +0800 Subject: [PATCH 082/206] fix bitmap font rendering issue --- cocos2d/labels/CCLabelAtlas.js | 25 +++++++++-------- cocos2d/labels/CCLabelBMFont.js | 28 +++++++++++-------- .../ccui/base-classes/UIScale9Sprite.js | 1 + 3 files changed, 31 insertions(+), 23 deletions(-) diff --git a/cocos2d/labels/CCLabelAtlas.js b/cocos2d/labels/CCLabelAtlas.js index 6f2bce2e29..c5cd81669b 100644 --- a/cocos2d/labels/CCLabelAtlas.js +++ b/cocos2d/labels/CCLabelAtlas.js @@ -163,10 +163,11 @@ cc.LabelAtlas = cc.LabelBMFont.extend(/** @lends cc.LabelBMFont# */{ var locIsLoaded = texture.isLoaded(); self._textureLoaded = locIsLoaded; if (!locIsLoaded) { - texture.addEventListener("load", function () { + texture.addEventListener("load", function (sender) { var self1 = this; self1._textureLoaded = true; //reset the LabelBMFont + self1.initWithTexture(sender, self1._initialString.length); self1.setString(self1._initialString, true); self1.dispatchEvent("load"); }, self); @@ -177,20 +178,22 @@ cc.LabelAtlas = cc.LabelBMFont.extend(/** @lends cc.LabelBMFont# */{ texture.initWithElement(image); self._textureLoaded = false; } - this._texture = texture; - self._alignment = cc.TEXT_ALIGNMENT_LEFT; - self._imageOffset = cc.p(0, 0); - self._width = -1; + if (self.initWithTexture(texture, theString.length)) { + self._alignment = cc.TEXT_ALIGNMENT_LEFT; + self._imageOffset = cc.p(0, 0); + self._width = -1; - self._realOpacity = 255; - self._realColor = cc.color(255, 255, 255, 255); + self._realOpacity = 255; + self._realColor = cc.color(255, 255, 255, 255); - self._contentSize.width = 0; - self._contentSize.height = 0; + self._contentSize.width = 0; + self._contentSize.height = 0; - self.setString(theString, true); - return true; + self.setString(theString, true); + return true; + } + return false; }, setFntFile: function () { diff --git a/cocos2d/labels/CCLabelBMFont.js b/cocos2d/labels/CCLabelBMFont.js index 26a5154db4..388f0e858c 100644 --- a/cocos2d/labels/CCLabelBMFont.js +++ b/cocos2d/labels/CCLabelBMFont.js @@ -80,7 +80,7 @@ * // Example 03 * var label3 = new cc.LabelBMFont("This is a \n test case", "test.fnt", 200, cc.TEXT_ALIGNMENT_LEFT, cc.p(0,0)); */ -cc.LabelBMFont = cc.Node.extend(/** @lends cc.LabelBMFont# */{ +cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{ //property string is Getter and Setter. //property textAlign is Getter and Setter. //property boundingWidth is Getter and Setter. @@ -251,6 +251,7 @@ cc.LabelBMFont = cc.Node.extend(/** @lends cc.LabelBMFont# */{ var self1 = this; self1._textureLoaded = true; //reset the LabelBMFont + self1.initWithTexture(sender, self1._initialString.length); self1.setString(self1._initialString, true); self1.dispatchEvent("load"); }, self); @@ -261,22 +262,25 @@ cc.LabelBMFont = cc.Node.extend(/** @lends cc.LabelBMFont# */{ texture.initWithElement(image); self._textureLoaded = false; } - this._texture = texture; - self._alignment = alignment || cc.TEXT_ALIGNMENT_LEFT; - self._imageOffset = imageOffset || cc.p(0, 0); - self._width = (width === undefined) ? -1 : width; + if (self.initWithTexture(texture, theString.length)) { + self._alignment = alignment || cc.TEXT_ALIGNMENT_LEFT; + self._imageOffset = imageOffset || cc.p(0, 0); + self._width = (width === undefined) ? -1 : width; + + self._realOpacity = 255; + self._realColor = cc.color(255, 255, 255, 255); - self._realOpacity = 255; - self._realColor = cc.color(255, 255, 255, 255); + self._contentSize.width = 0; + self._contentSize.height = 0; - self._contentSize.width = 0; - self._contentSize.height = 0; + self.setAnchorPoint(0.5, 0.5); - self.setAnchorPoint(0.5, 0.5); + self.setString(theString, true); - self.setString(theString, true); - return true; + return true; + } + return false; }, /** diff --git a/extensions/ccui/base-classes/UIScale9Sprite.js b/extensions/ccui/base-classes/UIScale9Sprite.js index 01fa9eb0b6..e9d635641b 100644 --- a/extensions/ccui/base-classes/UIScale9Sprite.js +++ b/extensions/ccui/base-classes/UIScale9Sprite.js @@ -367,6 +367,7 @@ ccui.Scale9Sprite = cc.Scale9Sprite = cc.Node.extend(/** @lends ccui.Scale9Sprit //v3.3 _flippedX: false, _flippedY: false, + _className: "Scale9Sprite", /** * Constructor function. From cefb4eb611ef465fe9b089d8b846f37752a1ca68 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Mon, 26 Dec 2016 15:00:01 +0800 Subject: [PATCH 083/206] Fixed a bug about playMusic --- cocos2d/audio/CCAudio.js | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/cocos2d/audio/CCAudio.js b/cocos2d/audio/CCAudio.js index 0e1428e855..048240309d 100644 --- a/cocos2d/audio/CCAudio.js +++ b/cocos2d/audio/CCAudio.js @@ -516,12 +516,18 @@ cc.Audio.WebAudio.prototype = { if (bgMusic && bgMusic.getPlaying()) { bgMusic.stop(); } + var musicVolume = this._musicVolume; var audio = cc.loader.getRes(url); if (!audio) { - cc.loader.load(url); + cc.loader.load(url, function () { + if (!audio.getPlaying()) { + audio.setVolume(musicVolume); + audio.play(0, loop || false); + } + }); audio = cc.loader.getRes(url); } - audio.setVolume(this._musicVolume); + audio.setVolume(musicVolume); audio.play(0, loop || false); this._currMusic = audio; From 1b018b284e94c15381de4716c01fcc4e520c618a Mon Sep 17 00:00:00 2001 From: pandamicro Date: Mon, 26 Dec 2016 16:09:36 +0800 Subject: [PATCH 084/206] Small fixes --- cocos2d/actions/CCActionInterval.js | 2 +- cocos2d/core/base-nodes/CCNode.js | 2 +- extensions/ccui/base-classes/UIWidgetRenderCmd.js | 5 +++++ extensions/ccui/layouts/UILayoutWebGLRenderCmd.js | 1 - 4 files changed, 7 insertions(+), 3 deletions(-) diff --git a/cocos2d/actions/CCActionInterval.js b/cocos2d/actions/CCActionInterval.js index 274dc48651..74a855748e 100644 --- a/cocos2d/actions/CCActionInterval.js +++ b/cocos2d/actions/CCActionInterval.js @@ -3363,7 +3363,7 @@ cc.Animate = cc.ActionInterval.extend(/** @lends cc.Animate# */{ startWithTarget: function (target) { cc.ActionInterval.prototype.startWithTarget.call(this, target); if (this._animation.getRestoreOriginalFrame()) - this._origFrame = target.displayFrame(); + this._origFrame = target.getSpriteFrame(); this._nextFrame = 0; this._executedLoops = 0; }, diff --git a/cocos2d/core/base-nodes/CCNode.js b/cocos2d/core/base-nodes/CCNode.js index 8e0479a0fc..8e8b25a35d 100644 --- a/cocos2d/core/base-nodes/CCNode.js +++ b/cocos2d/core/base-nodes/CCNode.js @@ -1717,7 +1717,7 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{ cc.assert(interval >= 0, cc._LogInfos.Node_schedule_2); interval = interval || 0; - repeat = (repeat == null) ? cc.REPEAT_FOREVER : repeat; + repeat = isNaN(repeat) ? cc.REPEAT_FOREVER : repeat; delay = delay || 0; this.scheduler.schedule(callback, this, interval, repeat, delay, !this._running, key); diff --git a/extensions/ccui/base-classes/UIWidgetRenderCmd.js b/extensions/ccui/base-classes/UIWidgetRenderCmd.js index d424cd39b8..fca76f9735 100644 --- a/extensions/ccui/base-classes/UIWidgetRenderCmd.js +++ b/extensions/ccui/base-classes/UIWidgetRenderCmd.js @@ -98,6 +98,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/UILayoutWebGLRenderCmd.js b/extensions/ccui/layouts/UILayoutWebGLRenderCmd.js index a2ed43eb12..e83dc0c765 100644 --- a/extensions/ccui/layouts/UILayoutWebGLRenderCmd.js +++ b/extensions/ccui/layouts/UILayoutWebGLRenderCmd.js @@ -77,7 +77,6 @@ gl.stencilMask(mask_layer); gl.clear(gl.STENCIL_BUFFER_BIT); - }; proto._onAfterDrawStencil = function (ctx) { From 6748dfc86f3baad96351d789ee829dd1a4c7952d Mon Sep 17 00:00:00 2001 From: pandamicro Date: Mon, 26 Dec 2016 16:10:02 +0800 Subject: [PATCH 085/206] Fix clipping node rendering issue when alphaThreshold = 1 --- cocos2d/clipping-nodes/CCClippingNode.js | 20 ++++++++++++++++--- .../CCClippingNodeWebGLRenderCmd.js | 8 ++++++++ .../core/sprites/CCSpriteWebGLRenderCmd.js | 2 +- 3 files changed, 26 insertions(+), 4 deletions(-) diff --git a/cocos2d/clipping-nodes/CCClippingNode.js b/cocos2d/clipping-nodes/CCClippingNode.js index 14edbc72fc..c7a1921b27 100644 --- a/cocos2d/clipping-nodes/CCClippingNode.js +++ b/cocos2d/clipping-nodes/CCClippingNode.js @@ -47,12 +47,14 @@ cc.stencilBits = -1; * @property {cc.Node} stencil - he cc.Node to use as a stencil to do the clipping. */ cc.ClippingNode = cc.Node.extend(/** @lends cc.ClippingNode# */{ - alphaThreshold: 0, inverted: false, + _alphaThreshold: 0, _stencil: null, _className: "ClippingNode", + _originStencilProgram: null, + /** * Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function. * @param {cc.Node} [stencil=null] @@ -61,6 +63,9 @@ cc.ClippingNode = cc.Node.extend(/** @lends cc.ClippingNode# */{ stencil = stencil || null; cc.Node.prototype.ctor.call(this); this._stencil = stencil; + if (stencil) { + this._originStencilProgram = stencil.getShaderProgram(); + } this.alphaThreshold = 1; this.inverted = false; this._renderCmd.initStencilBits(); @@ -154,7 +159,7 @@ cc.ClippingNode = cc.Node.extend(/** @lends cc.ClippingNode# */{ * @return {Number} */ getAlphaThreshold: function () { - return this.alphaThreshold; + return this._alphaThreshold; }, /** @@ -162,7 +167,11 @@ cc.ClippingNode = cc.Node.extend(/** @lends cc.ClippingNode# */{ * @param {Number} alphaThreshold */ setAlphaThreshold: function (alphaThreshold) { - this.alphaThreshold = alphaThreshold; + if (alphaThreshold === 1 && alphaThreshold !== this._alphaThreshold) { + // should reset program used by _stencil + this._renderCmd.resetProgramByStencil(); + } + this._alphaThreshold = alphaThreshold; }, /** @@ -202,6 +211,8 @@ cc.ClippingNode = cc.Node.extend(/** @lends cc.ClippingNode# */{ setStencil: function (stencil) { if (this._stencil === stencil) return; + if (stencil) + this._originStencilProgram = stencil.getShaderProgram(); this._renderCmd.setStencil(stencil); }, @@ -219,6 +230,9 @@ var _p = cc.ClippingNode.prototype; /** @expose */ _p.stencil; cc.defineGetterSetter(_p, "stencil", _p.getStencil, _p.setStencil); +/** @expose */ +_p.alphaThreshold; +cc.defineGetterSetter(_p, "alphaThreshold", _p.getAlphaThreshold, _p.setAlphaThreshold); /** diff --git a/cocos2d/clipping-nodes/CCClippingNodeWebGLRenderCmd.js b/cocos2d/clipping-nodes/CCClippingNodeWebGLRenderCmd.js index c276368aff..9126b5ca92 100644 --- a/cocos2d/clipping-nodes/CCClippingNodeWebGLRenderCmd.js +++ b/cocos2d/clipping-nodes/CCClippingNodeWebGLRenderCmd.js @@ -124,6 +124,14 @@ node._stencil._parent = node; }; + proto.resetProgramByStencil = function () { + var node = this._node; + if (node._stencil) { + var program = node._originStencilProgram; + setProgram(node._stencil, program); + } + }; + proto._onBeforeVisit = function (ctx) { var gl = ctx || cc._renderContext, node = this._node; cc.ClippingNode.WebGLRenderCmd._layer++; diff --git a/cocos2d/core/sprites/CCSpriteWebGLRenderCmd.js b/cocos2d/core/sprites/CCSpriteWebGLRenderCmd.js index 060908aca2..79e0c4b58f 100644 --- a/cocos2d/core/sprites/CCSpriteWebGLRenderCmd.js +++ b/cocos2d/core/sprites/CCSpriteWebGLRenderCmd.js @@ -39,7 +39,7 @@ this._dirty = false; this._recursiveDirty = false; - this._shaderProgram = cc.shaderCache.programForKey(cc.SHADER_SPRITE_POSITION_TEXTURECOLORALPHATEST); + this._shaderProgram = cc.shaderCache.programForKey(cc.SHADER_SPRITE_POSITION_TEXTURECOLOR); }; var proto = cc.Sprite.WebGLRenderCmd.prototype = Object.create(cc.Node.WebGLRenderCmd.prototype); From 9df9cbc1c59c6eb6e2072197425b683e0a3599f5 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Mon, 26 Dec 2016 16:10:22 +0800 Subject: [PATCH 086/206] Fix nested scroll view rendering issue --- .../ccui/uiwidgets/scroll-widget/UIScrollViewWebGLRenderCmd.js | 2 -- 1 file changed, 2 deletions(-) diff --git a/extensions/ccui/uiwidgets/scroll-widget/UIScrollViewWebGLRenderCmd.js b/extensions/ccui/uiwidgets/scroll-widget/UIScrollViewWebGLRenderCmd.js index 45d0aa3b2a..97ba7ff66b 100644 --- a/extensions/ccui/uiwidgets/scroll-widget/UIScrollViewWebGLRenderCmd.js +++ b/extensions/ccui/uiwidgets/scroll-widget/UIScrollViewWebGLRenderCmd.js @@ -27,8 +27,6 @@ for (i = 0, len = locCmds.length; i < len; i++) { cmd = locCmds[i]; checkNode = cmd._node; - if (checkNode instanceof ccui.ScrollView) - continue; if (checkNode && checkNode._parent && checkNode._parent._inViewRect === false) continue; From a9cba77264c68dc1d010655f44a494e26fec6852 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Mon, 26 Dec 2016 16:10:44 +0800 Subject: [PATCH 087/206] Made orderDirty flag properly set for node --- cocos2d/core/base-nodes/CCNode.js | 1 - 1 file changed, 1 deletion(-) diff --git a/cocos2d/core/base-nodes/CCNode.js b/cocos2d/core/base-nodes/CCNode.js index 8e8b25a35d..ff3d1694ff 100644 --- a/cocos2d/core/base-nodes/CCNode.js +++ b/cocos2d/core/base-nodes/CCNode.js @@ -306,7 +306,6 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{ * @param {Number} localZOrder */ setLocalZOrder: function (localZOrder) { - this._localZOrder = localZOrder; if (this._parent) this._parent.reorderChild(this, localZOrder); cc.eventManager._setDirtyForNode(this); From 62f7aaaedc65a63d193f7a0ee4e168528af29357 Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Mon, 26 Dec 2016 16:27:02 +0800 Subject: [PATCH 088/206] add gray shader to default shader --- cocos2d/core/platform/CCMacro.js | 5 +++ cocos2d/shaders/CCShaderCache.js | 23 +++++++++++-- cocos2d/shaders/CCShaders.js | 14 ++++++-- .../UIScale9SpriteWebGLRenderCmd.js | 32 +------------------ 4 files changed, 38 insertions(+), 36 deletions(-) diff --git a/cocos2d/core/platform/CCMacro.js b/cocos2d/core/platform/CCMacro.js index e5e4e3c609..3e3355aa99 100644 --- a/cocos2d/core/platform/CCMacro.js +++ b/cocos2d/core/platform/CCMacro.js @@ -619,6 +619,11 @@ cc.SHADER_POSITION_TEXTURECOLOR = "ShaderPositionTextureColor"; * @type {String} */ cc.SHADER_SPRITE_POSITION_TEXTURECOLOR = "ShaderSpritePositionTextureColor"; +/** + * @constant + * @type {String} + */ +cc.SHADER_SPRITE_POSITION_TEXTURECOLOR_GRAY = "ShaderSpritePositionTextureColorGray"; /** * @constant * @type {String} diff --git a/cocos2d/shaders/CCShaderCache.js b/cocos2d/shaders/CCShaderCache.js index f287633114..b064719f8d 100644 --- a/cocos2d/shaders/CCShaderCache.js +++ b/cocos2d/shaders/CCShaderCache.js @@ -102,7 +102,13 @@ cc.shaderCache = /** @lends cc.shaderCache# */{ * @constant * @type {Number} */ - TYPE_MAX: 10, + TYPE_SPRITE_POSITION_TEXTURECOLOR_GRAY: 11, + /** + * @public + * @constant + * @type {Number} + */ + TYPE_MAX: 11, _programs: {}, @@ -124,7 +130,13 @@ cc.shaderCache = /** @lends cc.shaderCache# */{ 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; + break; + case cc.SHADER_SPRITE_POSITION_TEXTURECOLOR_GRAY: + program.initWithVertexShaderByteArray(cc.SHADER_SPRITE_POSITION_TEXTURE_COLOR_VERT, cc.SHADER_SPRITE_POSITION_TEXTURE_COLOR_GRAY_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 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); @@ -230,6 +242,11 @@ cc.shaderCache = /** @lends cc.shaderCache# */{ program.reset(); this._loadDefaultShader(program, this.TYPE_POSITION_TEXTURE); + //Position Texture Gray shader + program = this.programForKey(cc.SHADER_SPRITE_POSITION_TEXTURE_COLOR_GRAY_FRAG); + program.reset(); + this._loadDefaultShader(program, this.TYPE_SPRITE_POSITION_TEXTURECOLOR_GRAY); + // // Position, Texture attribs, 1 Color as uniform shader // @@ -283,4 +300,4 @@ cc.shaderCache = /** @lends cc.shaderCache# */{ addProgram: function (program, key) { this._programs[key] = program; } -}; \ No newline at end of file +}; diff --git a/cocos2d/shaders/CCShaders.js b/cocos2d/shaders/CCShaders.js index c092340059..eb656c55ba 100644 --- a/cocos2d/shaders/CCShaders.js +++ b/cocos2d/shaders/CCShaders.js @@ -262,8 +262,18 @@ cc.SHADER_SPRITE_POSITION_TEXTURE_COLOR_VERT = + " gl_Position = CC_PMatrix * a_position; \n" + " v_fragmentColor = a_color; \n" + " v_texCoord = a_texCoord; \n" - + "}"; + + "}"; +cc.SHADER_SPRITE_POSITION_TEXTURE_COLOR_GRAY_FRAG = + "precision lowp float;\n" + + "varying vec4 v_fragmentColor; \n" + + "varying vec2 v_texCoord; \n" + + "void main() \n" + + "{ \n" + + " vec4 c = texture2D(CC_Texture0, v_texCoord); \n" + + " gl_FragColor.xyz = vec3(0.2126*c.r + 0.7152*c.g + 0.0722*c.b); \n" + +" gl_FragColor.w = c.w ; \n" + + "}"; //-----------------------Shader_PositionTextureColorAlphaTest_frag Shader Source---------------------------- /** * @constant @@ -301,4 +311,4 @@ cc.SHADEREX_SWITCHMASK_FRAG = + " vec4 maskColor = texture2D(u_mask, v_texCoord); \n" + " vec4 finalColor = vec4(texColor.r, texColor.g, texColor.b, maskColor.a * texColor.a); \n" + " gl_FragColor = v_fragmentColor * finalColor; \n" - + "}"; \ No newline at end of file + + "}"; diff --git a/extensions/ccui/base-classes/UIScale9SpriteWebGLRenderCmd.js b/extensions/ccui/base-classes/UIScale9SpriteWebGLRenderCmd.js index 7f249e6580..16df4ee947 100644 --- a/extensions/ccui/base-classes/UIScale9SpriteWebGLRenderCmd.js +++ b/extensions/ccui/base-classes/UIScale9SpriteWebGLRenderCmd.js @@ -151,39 +151,9 @@ if (state === Scale9Sprite.state.NORMAL) { this._shaderProgram = cc.shaderCache.programForKey(cc.SHADER_SPRITE_POSITION_TEXTURECOLOR); } else if (state === Scale9Sprite.state.GRAY) { - this._shaderProgram = Scale9Sprite.WebGLRenderCmd._getGrayShaderProgram(); + this._shaderProgram = cc.shaderCache.programForKey(cc.SHADER_SPRITE_POSITION_TEXTURECOLOR_GRAY); } }; - Scale9Sprite.WebGLRenderCmd._grayShaderProgram = null; - Scale9Sprite.WebGLRenderCmd._getGrayShaderProgram = function(){ - var grayShader = Scale9Sprite.WebGLRenderCmd._grayShaderProgram; - if (grayShader) - return grayShader; - - grayShader = new cc.GLProgram(); - grayShader.initWithVertexShaderByteArray(cc.SHADER_SPRITE_POSITION_TEXTURE_COLOR_VERT, - ccui.Scale9Sprite.WebGLRenderCmd._grayShaderFragment); - grayShader.addAttribute(cc.ATTRIBUTE_NAME_POSITION, cc.VERTEX_ATTRIB_POSITION); - grayShader.addAttribute(cc.ATTRIBUTE_NAME_COLOR, cc.VERTEX_ATTRIB_COLOR); - grayShader.addAttribute(cc.ATTRIBUTE_NAME_TEX_COORD, cc.VERTEX_ATTRIB_TEX_COORDS); - grayShader.link(); - grayShader.updateUniforms(); - - Scale9Sprite.WebGLRenderCmd._grayShaderProgram = grayShader; - return grayShader; - }; - - Scale9Sprite.WebGLRenderCmd._grayShaderFragment = - "precision lowp float;\n" - + "varying vec4 v_fragmentColor; \n" - + "varying vec2 v_texCoord; \n" - + "void main() \n" - + "{ \n" - + " vec4 c = texture2D(CC_Texture0, v_texCoord); \n" - + " gl_FragColor.xyz = vec3(0.2126*c.r + 0.7152*c.g + 0.0722*c.b); \n" - +" gl_FragColor.w = c.w ; \n" - + "}"; - })(); From f7f50202baadee637011718ae7eeb801b0b5e380 Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Mon, 26 Dec 2016 16:36:18 +0800 Subject: [PATCH 089/206] fix button gray state --- extensions/ccui/uiwidgets/UIButton.js | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/extensions/ccui/uiwidgets/UIButton.js b/extensions/ccui/uiwidgets/UIButton.js index 348177fee5..4feff73686 100644 --- a/extensions/ccui/uiwidgets/UIButton.js +++ b/extensions/ccui/uiwidgets/UIButton.js @@ -460,9 +460,7 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ _onPressStateChangedToNormal: function () { this._buttonScale9Renderer.setSpriteFrame(this._buttonNormalSpriteFrame); - if (this._scale9Enabled) { - this._buttonScale9Renderer.setState( ccui.Scale9Sprite.state.NORMAL); - } + this._buttonScale9Renderer.setState( ccui.Scale9Sprite.state.NORMAL); if (this._pressedTextureLoaded) { if (this.pressedActionEnabled){ @@ -500,9 +498,7 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ }, _onPressStateChangedToPressed: function () { - if (this._scale9Enabled) { - this._buttonScale9Renderer.setState(ccui.Scale9Sprite.state.NORMAL); - } + this._buttonScale9Renderer.setState(ccui.Scale9Sprite.state.NORMAL); if (this._pressedTextureLoaded) { this._buttonScale9Renderer.setSpriteFrame(this._buttonClickedSpriteFrame); @@ -539,7 +535,7 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ _onPressStateChangedToDisabled: function () { //if disable resource is null if (!this._disabledTextureLoaded){ - if (this._normalTextureLoaded && this._scale9Enabled) { + if (this._normalTextureLoaded) { this._buttonScale9Renderer.setState(ccui.Scale9Sprite.state.GRAY); } }else{ From ed5fdbeaf277d618ac066af52bd7aaf963c07cf1 Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Mon, 26 Dec 2016 16:46:39 +0800 Subject: [PATCH 090/206] implement slider ball turn gray effect --- extensions/ccui/base-classes/UIWidget.js | 8 ++++++++ extensions/ccui/uiwidgets/UISlider.js | 5 +++++ 2 files changed, 13 insertions(+) diff --git a/extensions/ccui/base-classes/UIWidget.js b/extensions/ccui/base-classes/UIWidget.js index 0c2d7dfbcc..b01ac526db 100644 --- a/extensions/ccui/base-classes/UIWidget.js +++ b/extensions/ccui/base-classes/UIWidget.js @@ -1692,6 +1692,14 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{ cc.arrayRemoveObject(this._nodes, node); }, + _getNormalGLProgram: function () { + return cc.shaderCache.programForKey(cc.SHADER_SPRITE_POSITION_TEXTURECOLOR); + }, + + _getGrayGLProgram: function () { + return cc.shaderCache.programForKey(cc.SHADER_SPRITE_POSITION_TEXTURECOLOR_GRAY); + }, + /** * Removes node by tag * @deprecated since v3.0, please use removeChildByTag instead. diff --git a/extensions/ccui/uiwidgets/UISlider.js b/extensions/ccui/uiwidgets/UISlider.js index 2507116baf..89b124cb6c 100644 --- a/extensions/ccui/uiwidgets/UISlider.js +++ b/extensions/ccui/uiwidgets/UISlider.js @@ -648,6 +648,7 @@ ccui.Slider = ccui.Widget.extend(/** @lends ccui.Slider# */{ this._slidBallDisabledRenderer.setVisible(false); this._slidBallNormalRenderer.setScale(this._sliderBallNormalTextureScaleX, this._sliderBallNormalTextureScaleY); + this._slidBallNormalRenderer._renderCmd._shaderProgram = this._getNormalGLProgram(); }, _onPressStateChangedToPressed: function () { @@ -658,12 +659,16 @@ ccui.Slider = ccui.Widget.extend(/** @lends ccui.Slider# */{ this._slidBallPressedRenderer.setVisible(true); this._slidBallDisabledRenderer.setVisible(false); } + this._slidBallNormalRenderer._renderCmd._shaderProgram = this._getNormalGLProgram(); }, _onPressStateChangedToDisabled: function () { if (this._slidBallDisabledTextureFile) { this._slidBallNormalRenderer.setVisible(false); this._slidBallDisabledRenderer.setVisible(true); + } else { + this._slidBallNormalRenderer.setVisible(true); + this._slidBallNormalRenderer._renderCmd._shaderProgram = this._getGrayGLProgram(); } this._slidBallNormalRenderer.setScale(this._sliderBallNormalTextureScaleX, this._sliderBallNormalTextureScaleY); this._slidBallPressedRenderer.setVisible(false); From 50399ae241ef6c3deffd5182a5568bb1d5c3dc88 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Mon, 26 Dec 2016 18:05:23 +0800 Subject: [PATCH 091/206] Improve log and preset value for cc.CONCURRENCY_HTTP_REQUEST_COUNT --- cocos2d/core/platform/CCMacro.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/cocos2d/core/platform/CCMacro.js b/cocos2d/core/platform/CCMacro.js index e5e4e3c609..2aa46f5c28 100644 --- a/cocos2d/core/platform/CCMacro.js +++ b/cocos2d/core/platform/CCMacro.js @@ -499,10 +499,11 @@ cc.ORIENTATION_AUTO = 3; /** * The limit count for concurrency http request, useful in some mobile browsers + * Adjust its value with the test results based on your game, the preset value is just a placeholder * @constant * @type Number */ -cc.CONCURRENCY_HTTP_REQUEST_COUNT = cc.sys.isMobile ? 9 : 0; +cc.CONCURRENCY_HTTP_REQUEST_COUNT = cc.sys.isMobile ? 20 : 0; // ------------------- vertex attrib flags ----------------------------- From fe7f99ce26b0d939740dada4643b9799344c38b3 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Mon, 26 Dec 2016 18:05:43 +0800 Subject: [PATCH 092/206] Fix cc.Color alpha setter issue --- cocos2d/core/platform/CCTypes.js | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/cocos2d/core/platform/CCTypes.js b/cocos2d/core/platform/CCTypes.js index 84bc1ab3fb..252061782d 100644 --- a/cocos2d/core/platform/CCTypes.js +++ b/cocos2d/core/platform/CCTypes.js @@ -60,12 +60,10 @@ _p._getB = function () { _p._setB = function (value) { this._val = (this._val & 0xffff00ff) | (value << 8); }; - _p._getA = function () { return this._val & 0x000000ff; }; - -_p.setA = function (value) { +_p._setA = function (value) { this._val = (this._val & 0xffffff00) | value; }; From f92348549fa791e38b6c3c483c10949eb4de9e85 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Mon, 26 Dec 2016 18:06:11 +0800 Subject: [PATCH 093/206] Fix reverted particle system dictionary parser --- cocos2d/particle/CCParticleSystem.js | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/cocos2d/particle/CCParticleSystem.js b/cocos2d/particle/CCParticleSystem.js index 01e2759c33..7a18fa4f32 100644 --- a/cocos2d/particle/CCParticleSystem.js +++ b/cocos2d/particle/CCParticleSystem.js @@ -1405,8 +1405,14 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{ locModeA.tangentialAccelVar = (pszTmp) ? parseFloat(pszTmp) : 0; // rotation is dir - var locRotationIsDir = locValueForKey("rotationIsDir", dictionary).toLowerCase(); - locModeA.rotationIsDir = (locRotationIsDir != null && (locRotationIsDir === "true" || locRotationIsDir === "1")); + var locRotationIsDir = locValueForKey("rotationIsDir", dictionary); + if (locRotationIsDir !== null) { + locRotationIsDir = locRotationIsDir.toString().toLowerCase(); + locModeA.rotationIsDir = (locRotationIsDir === "true" || locRotationIsDir === "1"); + } + else { + locModeA.rotationIsDir = false; + } } else if (this.emitterMode === cc.ParticleSystem.MODE_RADIUS) { // or Mode B: radius movement var locModeB = this.modeB; From 68deb55cfa6dda570f5c3eecec6548e7edb07770 Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Mon, 26 Dec 2016 18:40:55 +0800 Subject: [PATCH 094/206] fix canvas issue --- extensions/ccui/uiwidgets/UISlider.js | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/extensions/ccui/uiwidgets/UISlider.js b/extensions/ccui/uiwidgets/UISlider.js index 89b124cb6c..c8362ffdd7 100644 --- a/extensions/ccui/uiwidgets/UISlider.js +++ b/extensions/ccui/uiwidgets/UISlider.js @@ -648,7 +648,11 @@ ccui.Slider = ccui.Widget.extend(/** @lends ccui.Slider# */{ this._slidBallDisabledRenderer.setVisible(false); this._slidBallNormalRenderer.setScale(this._sliderBallNormalTextureScaleX, this._sliderBallNormalTextureScaleY); - this._slidBallNormalRenderer._renderCmd._shaderProgram = this._getNormalGLProgram(); + if (cc._renderType === cc.game.RENDER_TYPE_WEBGL) { + this._slidBallNormalRenderer._renderCmd._shaderProgram = this._getNormalGLProgram(); + } else { + // TODO: add canvas support + } }, _onPressStateChangedToPressed: function () { @@ -659,7 +663,11 @@ ccui.Slider = ccui.Widget.extend(/** @lends ccui.Slider# */{ this._slidBallPressedRenderer.setVisible(true); this._slidBallDisabledRenderer.setVisible(false); } - this._slidBallNormalRenderer._renderCmd._shaderProgram = this._getNormalGLProgram(); + if (cc._renderType === cc.game.RENDER_TYPE_WEBGL) { + this._slidBallNormalRenderer._renderCmd._shaderProgram = this._getNormalGLProgram(); + } else { + // TODO: add canvas support + } }, _onPressStateChangedToDisabled: function () { @@ -668,7 +676,11 @@ ccui.Slider = ccui.Widget.extend(/** @lends ccui.Slider# */{ this._slidBallDisabledRenderer.setVisible(true); } else { this._slidBallNormalRenderer.setVisible(true); - this._slidBallNormalRenderer._renderCmd._shaderProgram = this._getGrayGLProgram(); + if (cc._renderType === cc.game.RENDER_TYPE_WEBGL) { + this._slidBallNormalRenderer._renderCmd._shaderProgram = this._getGrayGLProgram(); + } else { + // TODO: add canvas support + } } this._slidBallNormalRenderer.setScale(this._sliderBallNormalTextureScaleX, this._sliderBallNormalTextureScaleY); this._slidBallPressedRenderer.setVisible(false); From 4ce186dc1881f6a1e92a7e4e7f8a5eb655da2b36 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Tue, 27 Dec 2016 15:50:11 +0800 Subject: [PATCH 095/206] Fix typo --- cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js b/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js index 49308ef008..1cc0bef5f6 100644 --- a/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js +++ b/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js @@ -448,7 +448,7 @@ cc.Node.RenderCmd.prototype = { opacityDirty = locFlag & dirtyFlags.opacityDirty; if (locFlag & dirtyFlags.contentDirty) { - this._notifyRegionStatus && this._notifyRegionStatus(_ccsg.Node.CanvasRenderCmd.RegionStatus.Dirty); + this._notifyRegionStatus && this._notifyRegionStatus(cc.Node.CanvasRenderCmd.RegionStatus.Dirty); this._dirtyFlag &= ~dirtyFlags.contentDirty; } From b54750ada33ae10e76ca07c73b4da88a32f521db Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Thu, 29 Dec 2016 17:14:32 +0800 Subject: [PATCH 096/206] Fixed a bug about pauseMusic --- cocos2d/audio/CCAudio.js | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/cocos2d/audio/CCAudio.js b/cocos2d/audio/CCAudio.js index 048240309d..2dd9086e9f 100644 --- a/cocos2d/audio/CCAudio.js +++ b/cocos2d/audio/CCAudio.js @@ -503,6 +503,7 @@ cc.Audio.WebAudio.prototype = { return false; }, + _waitLoadPlayFlag: true, /** * Play music. * @param {String} url The path of the music file without filename extension. @@ -512,15 +513,17 @@ cc.Audio.WebAudio.prototype = { * cc.audioEngine.playMusic(path, false); */ playMusic: function(url, loop){ + this._waitLoadPlayFlag = true; var bgMusic = this._currMusic; if (bgMusic && bgMusic.getPlaying()) { bgMusic.stop(); } var musicVolume = this._musicVolume; var audio = cc.loader.getRes(url); + var self = this; if (!audio) { cc.loader.load(url, function () { - if (!audio.getPlaying()) { + if (self._waitLoadPlayFlag && !audio.getPlaying()) { audio.setVolume(musicVolume); audio.play(0, loop || false); } @@ -542,6 +545,7 @@ cc.Audio.WebAudio.prototype = { */ stopMusic: function(releaseData){ var audio = this._currMusic; + this._waitLoadPlayFlag = false; if (audio) { var list = cc.Audio.touchPlayList; for (var i=list.length-1; i>=0; --i) { @@ -564,6 +568,7 @@ cc.Audio.WebAudio.prototype = { */ pauseMusic: function () { var audio = this._currMusic; + this._waitLoadPlayFlag = false; if (audio) audio.pause(); }, From dfbf0bc91ef2b5dbebbba0e33905bd07cc336691 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Fri, 30 Dec 2016 11:22:13 +0800 Subject: [PATCH 097/206] =?UTF-8?q?Fix=20local=20z=20order=20not=20being?= =?UTF-8?q?=20set=20when=20node=20doesn=E2=80=99t=20have=20a=20parent=20is?= =?UTF-8?q?sue?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- cocos2d/core/base-nodes/CCNode.js | 2 ++ 1 file changed, 2 insertions(+) diff --git a/cocos2d/core/base-nodes/CCNode.js b/cocos2d/core/base-nodes/CCNode.js index ff3d1694ff..2b62bc06c4 100644 --- a/cocos2d/core/base-nodes/CCNode.js +++ b/cocos2d/core/base-nodes/CCNode.js @@ -308,6 +308,8 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{ setLocalZOrder: function (localZOrder) { if (this._parent) this._parent.reorderChild(this, localZOrder); + else + this._localZOrder = localZOrder; cc.eventManager._setDirtyForNode(this); }, From 73b2b3cf53b194952ccdf896562db06f7447aa2e Mon Sep 17 00:00:00 2001 From: pandamicro Date: Fri, 30 Dec 2016 11:22:33 +0800 Subject: [PATCH 098/206] Enable FIX_ARTIFACTS_BY_STRECHING_TEXEL by default --- cocos2d/core/platform/CCConfig.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos2d/core/platform/CCConfig.js b/cocos2d/core/platform/CCConfig.js index 027bede099..b3a2c73f32 100644 --- a/cocos2d/core/platform/CCConfig.js +++ b/cocos2d/core/platform/CCConfig.js @@ -56,7 +56,7 @@ window["CocosEngine"] = cc.ENGINE_VERSION = "Cocos2d-JS v3.14"; * @constant * @type {Number} */ -cc.FIX_ARTIFACTS_BY_STRECHING_TEXEL = 0; +cc.FIX_ARTIFACTS_BY_STRECHING_TEXEL = 1; /** * Position of the FPS (Default: 0,0 (bottom-left corner))
From 6856e33e603d5f8643388832932ce742924372dc Mon Sep 17 00:00:00 2001 From: pandamicro Date: Mon, 2 Jan 2017 15:12:34 +0800 Subject: [PATCH 099/206] Fix canvas crash and rendering issues --- .../clipping-nodes/CCClippingNodeCanvasRenderCmd.js | 4 ++++ cocos2d/core/layers/CCLayerCanvasRenderCmd.js | 6 +++--- cocos2d/core/layers/CCLayerWebGLRenderCmd.js | 4 ++-- cocos2d/core/sprites/CCSprite.js | 2 +- cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js | 10 +++++----- .../render-texture/CCRenderTextureCanvasRenderCmd.js | 2 +- .../ccui/base-classes/UIScale9SpriteCanvasRenderCmd.js | 2 +- 7 files changed, 17 insertions(+), 13 deletions(-) diff --git a/cocos2d/clipping-nodes/CCClippingNodeCanvasRenderCmd.js b/cocos2d/clipping-nodes/CCClippingNodeCanvasRenderCmd.js index 6e4955a8c9..de4989921e 100644 --- a/cocos2d/clipping-nodes/CCClippingNodeCanvasRenderCmd.js +++ b/cocos2d/clipping-nodes/CCClippingNodeCanvasRenderCmd.js @@ -38,6 +38,10 @@ var proto = cc.ClippingNode.CanvasRenderCmd.prototype = Object.create(cc.Node.CanvasRenderCmd.prototype); proto.constructor = cc.ClippingNode.CanvasRenderCmd; + proto.resetProgramByStencil = function () { + + }; + proto.initStencilBits = function () { }; diff --git a/cocos2d/core/layers/CCLayerCanvasRenderCmd.js b/cocos2d/core/layers/CCLayerCanvasRenderCmd.js index 3bc0905ebe..3149895ee3 100644 --- a/cocos2d/core/layers/CCLayerCanvasRenderCmd.js +++ b/cocos2d/core/layers/CCLayerCanvasRenderCmd.js @@ -61,7 +61,7 @@ this._cacheDirty = true; if (this._updateCache === 0) this._updateCache = 2; - this._dirtyFlag = locFlag & flags.orderDirty ^ locFlag; + this._dirtyFlag &= ~flags.orderDirty; } this.originUpdateStatus(); @@ -365,7 +365,7 @@ var flags = cc.Node._dirtyFlags, locFlag = this._dirtyFlag; if (locFlag & flags.gradientDirty) { this._dirtyFlag |= flags.colorDirty; - this._dirtyFlag = locFlag & flags.gradientDirty ^ locFlag; + this._dirtyFlag &= ~flags.gradientDirty; } this.originUpdateStatus(); @@ -375,7 +375,7 @@ var flags = cc.Node._dirtyFlags, locFlag = this._dirtyFlag; if (locFlag & flags.gradientDirty) { this._dirtyFlag |= flags.colorDirty; - this._dirtyFlag = locFlag & flags.gradientDirty ^ locFlag; + this._dirtyFlag &= ~flags.gradientDirty; } this._originSyncStatus(parentCmd); diff --git a/cocos2d/core/layers/CCLayerWebGLRenderCmd.js b/cocos2d/core/layers/CCLayerWebGLRenderCmd.js index 4a4b1b39e2..544428278b 100644 --- a/cocos2d/core/layers/CCLayerWebGLRenderCmd.js +++ b/cocos2d/core/layers/CCLayerWebGLRenderCmd.js @@ -174,7 +174,7 @@ if (locFlag & flags.gradientDirty) { this._dirtyFlag |= flags.colorDirty; this._updateVertex(); - this._dirtyFlag = locFlag & flags.gradientDirty ^ locFlag; + this._dirtyFlag &= ~flags.gradientDirty; } this.originUpdateStatus(); @@ -185,7 +185,7 @@ if (locFlag & flags.gradientDirty) { this._dirtyFlag |= flags.colorDirty; this._updateVertex(); - this._dirtyFlag = locFlag & flags.gradientDirty ^ locFlag; + this._dirtyFlag &= ~flags.gradientDirty; } this._originSyncStatus(parentCmd); diff --git a/cocos2d/core/sprites/CCSprite.js b/cocos2d/core/sprites/CCSprite.js index 26a2954ab7..d450424083 100644 --- a/cocos2d/core/sprites/CCSprite.js +++ b/cocos2d/core/sprites/CCSprite.js @@ -677,7 +677,7 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{ var _t = this; if (typeof newFrame === 'string') { newFrame = cc.spriteFrameCache.getSpriteFrame(newFrame); - cc.assert(newFrame, cc._LogInfos.Sprite_setSpriteFrame) + cc.assert(newFrame, cc._LogInfos.Sprite_setSpriteFrame); } this._loader.clear(); diff --git a/cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js b/cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js index eaa8bbfecb..87da2606e5 100644 --- a/cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js +++ b/cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js @@ -51,12 +51,12 @@ proto._setTexture = function (texture) { var node = this._node; if (node._texture !== texture) { - if (texture) { - node._textureLoaded = texture._textureLoaded; - } else { - node._textureLoaded = false; - } + node._textureLoaded = texture ? texture._textureLoaded : false; node._texture = texture; + + var texSize = texture._contentSize; + var rect = cc.rect(0, 0, texSize.width, texSize.height); + node.setTextureRect(rect); this._updateColor(); } }; diff --git a/cocos2d/render-texture/CCRenderTextureCanvasRenderCmd.js b/cocos2d/render-texture/CCRenderTextureCanvasRenderCmd.js index 3ad126d9f6..c55f9e7ad1 100644 --- a/cocos2d/render-texture/CCRenderTextureCanvasRenderCmd.js +++ b/cocos2d/render-texture/CCRenderTextureCanvasRenderCmd.js @@ -25,7 +25,7 @@ (function () { cc.RenderTexture.CanvasRenderCmd = function (renderableObject) { this._rootCtor(renderableObject); - this._needDraw = true; + this._needDraw = false; this._clearColorStr = "rgba(255,255,255,1)"; this._cacheCanvas = document.createElement('canvas'); diff --git a/extensions/ccui/base-classes/UIScale9SpriteCanvasRenderCmd.js b/extensions/ccui/base-classes/UIScale9SpriteCanvasRenderCmd.js index 12f1bcaf82..0a96e14c47 100644 --- a/extensions/ccui/base-classes/UIScale9SpriteCanvasRenderCmd.js +++ b/extensions/ccui/base-classes/UIScale9SpriteCanvasRenderCmd.js @@ -70,7 +70,7 @@ if (this._textureToRender === null || this._originalTexture !== locTexture) { this._textureToRender = this._originalTexture = locTexture; if (cc.Scale9Sprite.state.GRAY === this._state) { - this._textureToRender = this._textureToRender._generateGrayTexture(); + this._textureToRender = this._textureToRender._switchToGray(); } var color = node.getDisplayedColor(); if (locTexture && (color.r !== 255 || color.g !==255 || color.b !== 255)) From 298a456d3239e818c8e303bfe4575f67f9a88e2a Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Mon, 2 Jan 2017 21:57:04 +0800 Subject: [PATCH 100/206] Audio play flags move to cc.Audio --- cocos2d/audio/CCAudio.js | 28 ++++++++++++++++++---------- 1 file changed, 18 insertions(+), 10 deletions(-) diff --git a/cocos2d/audio/CCAudio.js b/cocos2d/audio/CCAudio.js index 2dd9086e9f..84ba432311 100644 --- a/cocos2d/audio/CCAudio.js +++ b/cocos2d/audio/CCAudio.js @@ -83,6 +83,7 @@ * Encapsulate DOM and webAudio */ cc.Audio = cc.Class.extend({ + interruptPlay: false, src: null, _element: null, _AUDIO_TYPE: "AUDIO", @@ -110,7 +111,10 @@ cc.Audio = cc.Class.extend({ }, play: function (offset, loop) { - if (!this._element) return; + if (!this._element) { + this.interruptPlay = false; + return; + } this._element.loop = loop; this._element.play(); if (this._AUDIO_TYPE === 'AUDIO' && this._element.paused) { @@ -131,7 +135,10 @@ cc.Audio = cc.Class.extend({ }, stop: function () { - if (!this._element) return; + if (!this._element) { + this.interruptPlay = true; + return; + } this._element.pause(); try { this._element.currentTime = 0; @@ -140,12 +147,18 @@ cc.Audio = cc.Class.extend({ }, pause: function () { - if (!this._element) return; + if (!this._element) { + this.interruptPlay = true; + return; + } this._element.pause(); }, resume: function () { - if (!this._element) return; + if (!this._element) { + this.interruptPlay = false; + return; + } this._element.play(); }, @@ -503,7 +516,6 @@ cc.Audio.WebAudio.prototype = { return false; }, - _waitLoadPlayFlag: true, /** * Play music. * @param {String} url The path of the music file without filename extension. @@ -513,17 +525,15 @@ cc.Audio.WebAudio.prototype = { * cc.audioEngine.playMusic(path, false); */ playMusic: function(url, loop){ - this._waitLoadPlayFlag = true; var bgMusic = this._currMusic; if (bgMusic && bgMusic.getPlaying()) { bgMusic.stop(); } var musicVolume = this._musicVolume; var audio = cc.loader.getRes(url); - var self = this; if (!audio) { cc.loader.load(url, function () { - if (self._waitLoadPlayFlag && !audio.getPlaying()) { + if (!audio.getPlaying() && !audio.interruptPlay) { audio.setVolume(musicVolume); audio.play(0, loop || false); } @@ -545,7 +555,6 @@ cc.Audio.WebAudio.prototype = { */ stopMusic: function(releaseData){ var audio = this._currMusic; - this._waitLoadPlayFlag = false; if (audio) { var list = cc.Audio.touchPlayList; for (var i=list.length-1; i>=0; --i) { @@ -568,7 +577,6 @@ cc.Audio.WebAudio.prototype = { */ pauseMusic: function () { var audio = this._currMusic; - this._waitLoadPlayFlag = false; if (audio) audio.pause(); }, From b5748c3fc75170c098b565b2ac00ed63958d521a Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Mon, 2 Jan 2017 22:13:11 +0800 Subject: [PATCH 101/206] Should not play the suspended music --- CCBoot.js | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/CCBoot.js b/CCBoot.js index a3e182f3b7..77fe403ff8 100644 --- a/CCBoot.js +++ b/CCBoot.js @@ -2349,8 +2349,7 @@ cc.game = /** @lends cc.game# */{ this._paused = true; // Pause audio engine if (cc.audioEngine) { - cc.audioEngine.stopAllEffects(); - cc.audioEngine.pauseMusic(); + cc.audioEngine._pausePlaying(); } // Pause main loop if (this._intervalId) @@ -2366,7 +2365,7 @@ cc.game = /** @lends cc.game# */{ this._paused = false; // Resume audio engine if (cc.audioEngine) { - cc.audioEngine.resumeMusic(); + cc.audioEngine._resumePlaying(); } // Resume main loop this._runMainLoop(); From 6387dedf7ad44cbbe5059b3605b4d69e061ceb06 Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Tue, 3 Jan 2017 11:27:29 +0800 Subject: [PATCH 102/206] add _generateGrayTexture --- cocos2d/core/textures/CCTexture2D.js | 12 +++++++++++- .../base-classes/UIScale9SpriteCanvasRenderCmd.js | 2 +- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/cocos2d/core/textures/CCTexture2D.js b/cocos2d/core/textures/CCTexture2D.js index 41b1726168..cd0a9ff153 100644 --- a/cocos2d/core/textures/CCTexture2D.js +++ b/cocos2d/core/textures/CCTexture2D.js @@ -419,7 +419,17 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () { if (this._backupElement !== null) this._htmlElementObj = this._backupElement; } - } + }, + + _generateGrayTexture: function() { + if(!this._textureLoaded) + return null; + var grayElement = cc.Texture2D._generateGrayTexture(this._htmlElementObj); + var newTexture = new cc.Texture2D(); + newTexture.initWithElement(grayElement); + newTexture.handleLoadedTexture(); + return newTexture; + }, }; var renderToCache = function (image, cache) { diff --git a/extensions/ccui/base-classes/UIScale9SpriteCanvasRenderCmd.js b/extensions/ccui/base-classes/UIScale9SpriteCanvasRenderCmd.js index 0a96e14c47..12f1bcaf82 100644 --- a/extensions/ccui/base-classes/UIScale9SpriteCanvasRenderCmd.js +++ b/extensions/ccui/base-classes/UIScale9SpriteCanvasRenderCmd.js @@ -70,7 +70,7 @@ if (this._textureToRender === null || this._originalTexture !== locTexture) { this._textureToRender = this._originalTexture = locTexture; if (cc.Scale9Sprite.state.GRAY === this._state) { - this._textureToRender = this._textureToRender._switchToGray(); + this._textureToRender = this._textureToRender._generateGrayTexture(); } var color = node.getDisplayedColor(); if (locTexture && (color.r !== 255 || color.g !==255 || color.b !== 255)) From 4f9276e1c97e7264c762567de078f75164df4f80 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Tue, 10 Jan 2017 13:53:23 +0800 Subject: [PATCH 103/206] Improve browser detection for QQ --- CCBoot.js | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/CCBoot.js b/CCBoot.js index 77fe403ff8..2b3c7d8e6c 100644 --- a/CCBoot.js +++ b/CCBoot.js @@ -1727,14 +1727,24 @@ var _initSys = function () { /* Determine the browser type */ (function(){ var typeReg1 = /micromessenger|mqqbrowser|sogou|qzone|liebao|ucbrowser|360 aphone|360browser|baiduboxapp|baidubrowser|maxthon|mxbrowser|trident|miuibrowser/i; - var typeReg2 = /qqbrowser|chrome|safari|firefox|opr|oupeng|opera/i; + var typeReg2 = /qqbrowser|qq|chrome|safari|firefox|opr|oupeng|opera/i; var browserTypes = typeReg1.exec(ua); if(!browserTypes) browserTypes = typeReg2.exec(ua); var browserType = browserTypes ? browserTypes[0] : sys.BROWSER_TYPE_UNKNOWN; if (browserType === 'micromessenger') browserType = sys.BROWSER_TYPE_WECHAT; - else if (browserType === "safari" && (ua.match(/android.*applewebkit/))) + else if (browserType === "safari" && isAndroid) browserType = sys.BROWSER_TYPE_ANDROID; + else if (browserType === "qq") { + if (iOS) + browserType = sys.BROWSER_TYPE_SAFARI; + else if (ua.match(/android.*applewebkit/i)) + brwoserType = sys.BROWSER_TYPE_ANDROID; + else if (sys.isMobile) + browserType = sys.BROWSER_TYPE_MOBILE_QQ; + else + browserType = sys.BROWSER_TYPE_QQ; + } else if (browserType === "trident") browserType = sys.BROWSER_TYPE_IE; else if (browserType === "360 aphone") @@ -2732,6 +2742,10 @@ cc.game = /** @lends cc.game# */{ visibilityChange = "webkitvisibilitychange"; } + if (cc.sys.browserType === cc.sys.BROWSER_TYPE_QQ || cc.sys.browserType === cc.sys.BROWSER_TYPE_MOBILE_QQ) { + visibilityChange = "qbrowserVisibilityChange" + } + var onHidden = function () { if (cc.eventManager && cc.game._eventHide) cc.eventManager.dispatchEvent(cc.game._eventHide); From 068846566649f29cf5dddb2d73523eb1d6d48c8d Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Tue, 10 Jan 2017 16:50:07 +0800 Subject: [PATCH 104/206] Add qq app type. --- CCBoot.js | 43 ++++++++++++++++++++----------------------- 1 file changed, 20 insertions(+), 23 deletions(-) diff --git a/CCBoot.js b/CCBoot.js index 2b3c7d8e6c..126ea7bff2 100644 --- a/CCBoot.js +++ b/CCBoot.js @@ -1610,6 +1610,7 @@ var _initSys = function () { sys.BROWSER_TYPE_WECHAT = "wechat"; sys.BROWSER_TYPE_ANDROID = "androidbrowser"; sys.BROWSER_TYPE_IE = "ie"; + sys.BROWSER_TYPE_QQ_APP = "qq"; // QQ App sys.BROWSER_TYPE_QQ = "qqbrowser"; sys.BROWSER_TYPE_MOBILE_QQ = "mqqbrowser"; sys.BROWSER_TYPE_UC = "ucbrowser"; @@ -1735,16 +1736,6 @@ var _initSys = function () { browserType = sys.BROWSER_TYPE_WECHAT; else if (browserType === "safari" && isAndroid) browserType = sys.BROWSER_TYPE_ANDROID; - else if (browserType === "qq") { - if (iOS) - browserType = sys.BROWSER_TYPE_SAFARI; - else if (ua.match(/android.*applewebkit/i)) - brwoserType = sys.BROWSER_TYPE_ANDROID; - else if (sys.isMobile) - browserType = sys.BROWSER_TYPE_MOBILE_QQ; - else - browserType = sys.BROWSER_TYPE_QQ; - } else if (browserType === "trident") browserType = sys.BROWSER_TYPE_IE; else if (browserType === "360 aphone") @@ -2717,7 +2708,7 @@ cc.game = /** @lends cc.game# */{ }, _initEvents: function () { - var win = window, self = this, hidden, visibilityChange, _undef = "undefined"; + var win = window, hidden; this._eventHide = this._eventHide || new cc.EventCustom(this.EVENT_HIDE); this._eventHide.setUserData(this); @@ -2730,22 +2721,21 @@ cc.game = /** @lends cc.game# */{ if (!cc.isUndefined(document.hidden)) { hidden = "hidden"; - visibilityChange = "visibilitychange"; } else if (!cc.isUndefined(document.mozHidden)) { hidden = "mozHidden"; - visibilityChange = "mozvisibilitychange"; } else if (!cc.isUndefined(document.msHidden)) { hidden = "msHidden"; - visibilityChange = "msvisibilitychange"; } else if (!cc.isUndefined(document.webkitHidden)) { hidden = "webkitHidden"; - visibilityChange = "webkitvisibilitychange"; - } - - if (cc.sys.browserType === cc.sys.BROWSER_TYPE_QQ || cc.sys.browserType === cc.sys.BROWSER_TYPE_MOBILE_QQ) { - visibilityChange = "qbrowserVisibilityChange" } + var changeList = [ + "visibilitychange", + "mozvisibilitychange", + "msvisibilitychange", + "webkitvisibilitychange", + "qbrowserVisibilityChange" + ]; var onHidden = function () { if (cc.eventManager && cc.game._eventHide) cc.eventManager.dispatchEvent(cc.game._eventHide); @@ -2756,10 +2746,17 @@ cc.game = /** @lends cc.game# */{ }; if (hidden) { - document.addEventListener(visibilityChange, function () { - if (document[hidden]) onHidden(); - else onShow(); - }, false); + for (var i=0; i Date: Tue, 10 Jan 2017 17:20:52 +0800 Subject: [PATCH 105/206] Review - remove func --- CCBoot.js | 16 +++++++--------- 1 file changed, 7 insertions(+), 9 deletions(-) diff --git a/CCBoot.js b/CCBoot.js index 126ea7bff2..a048a028b3 100644 --- a/CCBoot.js +++ b/CCBoot.js @@ -2747,15 +2747,13 @@ cc.game = /** @lends cc.game# */{ if (hidden) { for (var i=0; i Date: Tue, 10 Jan 2017 18:18:45 +0800 Subject: [PATCH 106/206] webAudio paused is true --- cocos2d/audio/CCAudio.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos2d/audio/CCAudio.js b/cocos2d/audio/CCAudio.js index 84ba432311..4cb0e0340f 100644 --- a/cocos2d/audio/CCAudio.js +++ b/cocos2d/audio/CCAudio.js @@ -122,7 +122,7 @@ cc.Audio = cc.Class.extend({ cc.Audio.touchPlayList.push({ loop: loop, offset: offset, audio: this._element }); } - if (cc.Audio.bindTouch === false && this._element.paused) { + if (cc.Audio.bindTouch === false) { cc.Audio.bindTouch = true; // Listen to the touchstart body event and play the audio when necessary. cc.game.canvas.addEventListener('touchstart', cc.Audio.touchStart); From c55e0b73a9e711a1ad8c8c197ebec2d8cb9fcd76 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Wed, 11 Jan 2017 18:05:41 +0800 Subject: [PATCH 107/206] setProgram is not define --- cocos2d/clipping-nodes/CCClippingNodeWebGLRenderCmd.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos2d/clipping-nodes/CCClippingNodeWebGLRenderCmd.js b/cocos2d/clipping-nodes/CCClippingNodeWebGLRenderCmd.js index 9126b5ca92..d563fb711c 100644 --- a/cocos2d/clipping-nodes/CCClippingNodeWebGLRenderCmd.js +++ b/cocos2d/clipping-nodes/CCClippingNodeWebGLRenderCmd.js @@ -128,7 +128,7 @@ var node = this._node; if (node._stencil) { var program = node._originStencilProgram; - setProgram(node._stencil, program); + cc.setProgram(node._stencil, program); } }; From 8a3b0b48cfd44beed7a6a5f293194a757a23f7c6 Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Thu, 12 Jan 2017 11:12:15 +0800 Subject: [PATCH 108/206] fix uiscale9sprite content scale9 factor issue --- extensions/ccui/base-classes/UIScale9Sprite.js | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/extensions/ccui/base-classes/UIScale9Sprite.js b/extensions/ccui/base-classes/UIScale9Sprite.js index e9d635641b..33d77dfa85 100644 --- a/extensions/ccui/base-classes/UIScale9Sprite.js +++ b/extensions/ccui/base-classes/UIScale9Sprite.js @@ -254,12 +254,15 @@ var scale9QuadGenerator = { var leftWidth, centerWidth, rightWidth; var topHeight, centerHeight, bottomHeight; var textureRect = spriteFrame._rect; + textureRect = cc.rectPointsToPixels(textureRect); + rect = cc.rectPointsToPixels(rect); + var scale = cc.contentScaleFactor(); - leftWidth = insetLeft; - rightWidth = insetRight; + leftWidth = insetLeft * scale; + rightWidth = insetRight * scale; centerWidth = rect.width - leftWidth - rightWidth; - topHeight = insetTop; - bottomHeight = insetBottom; + topHeight = insetTop * scale; + bottomHeight = insetBottom * scale; centerHeight = rect.height - topHeight - bottomHeight; if (uvs.length < 32) { From d6b3344978b346dd850c16c4876609525c4d2ba2 Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Thu, 12 Jan 2017 11:26:35 +0800 Subject: [PATCH 109/206] fix simple mode texture coordinate mapping in retina display --- extensions/ccui/base-classes/UIScale9Sprite.js | 1 + 1 file changed, 1 insertion(+) diff --git a/extensions/ccui/base-classes/UIScale9Sprite.js b/extensions/ccui/base-classes/UIScale9Sprite.js index 33d77dfa85..ae32c96a5b 100644 --- a/extensions/ccui/base-classes/UIScale9Sprite.js +++ b/extensions/ccui/base-classes/UIScale9Sprite.js @@ -136,6 +136,7 @@ var simpleQuadGenerator = { var atlasWidth = spriteFrame._texture._pixelsWide; var atlasHeight = spriteFrame._texture._pixelsHigh; var textureRect = spriteFrame._rect; + textureRect = cc.rectPointsToPixels(textureRect); if (uvs.length < 8) { dataPool.put(uvs); From 18b867f0735bbdb11219ff28a66db756eaebc4ea Mon Sep 17 00:00:00 2001 From: pandamicro Date: Thu, 12 Jan 2017 10:14:05 +0800 Subject: [PATCH 110/206] Fix cc.textureCache.removeTextureForKey not releasing texture issue --- cocos2d/core/textures/CCTextureCache.js | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/cocos2d/core/textures/CCTextureCache.js b/cocos2d/core/textures/CCTextureCache.js index 19cac4b9fa..2099565eb3 100644 --- a/cocos2d/core/textures/CCTextureCache.js +++ b/cocos2d/core/textures/CCTextureCache.js @@ -214,8 +214,11 @@ cc.textureCache = /** @lends cc.textureCache# */{ removeTextureForKey: function (textureKeyName) { if (textureKeyName == null) return; - if (this._textures[textureKeyName]) + var tex = this._textures[textureKeyName]; + if (tex) { + tex.releaseTexture(); delete(this._textures[textureKeyName]); + } }, //addImage move to Canvas/WebGL From 24ed0d2fe1d332f5c2377023c03d1d537a8e7722 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Thu, 12 Jan 2017 10:14:15 +0800 Subject: [PATCH 111/206] Small improvements --- cocos2d/core/CCDirector.js | 2 +- cocos2d/core/CCDirectorWebGL.js | 2 +- cocos2d/core/platform/CCConfig.js | 2 +- cocos2d/core/platform/CCEGLView.js | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) mode change 100644 => 100755 cocos2d/core/platform/CCEGLView.js diff --git a/cocos2d/core/CCDirector.js b/cocos2d/core/CCDirector.js index 72d8d25c5e..b906a7fbd7 100644 --- a/cocos2d/core/CCDirector.js +++ b/cocos2d/core/CCDirector.js @@ -939,7 +939,7 @@ cc.Director.PROJECTION_3D = 1; cc.Director.PROJECTION_CUSTOM = 3; /** - * Constant for default projection of cc.Director, default projection is 3D projection + * Constant for default projection of cc.Director, default projection is 2D projection * @constant * @type {Number} */ diff --git a/cocos2d/core/CCDirectorWebGL.js b/cocos2d/core/CCDirectorWebGL.js index 541ba50702..50ae30bdce 100644 --- a/cocos2d/core/CCDirectorWebGL.js +++ b/cocos2d/core/CCDirectorWebGL.js @@ -177,7 +177,7 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () { }; _p.getZEye = function () { - return (this._winSizeInPoints.height / 1.1566 ); + return (this._winSizeInPoints.height / 1.15469993750 ); }; _p.setViewport = function () { diff --git a/cocos2d/core/platform/CCConfig.js b/cocos2d/core/platform/CCConfig.js index b3a2c73f32..027bede099 100644 --- a/cocos2d/core/platform/CCConfig.js +++ b/cocos2d/core/platform/CCConfig.js @@ -56,7 +56,7 @@ window["CocosEngine"] = cc.ENGINE_VERSION = "Cocos2d-JS v3.14"; * @constant * @type {Number} */ -cc.FIX_ARTIFACTS_BY_STRECHING_TEXEL = 1; +cc.FIX_ARTIFACTS_BY_STRECHING_TEXEL = 0; /** * Position of the FPS (Default: 0,0 (bottom-left corner))
diff --git a/cocos2d/core/platform/CCEGLView.js b/cocos2d/core/platform/CCEGLView.js old mode 100644 new mode 100755 index 27e37a6f50..37c89fd688 --- a/cocos2d/core/platform/CCEGLView.js +++ b/cocos2d/core/platform/CCEGLView.js @@ -303,7 +303,7 @@ cc.EGLView = cc.Class.extend(/** @lends cc.view# */{ */ setOrientation: function (orientation) { orientation = orientation & cc.ORIENTATION_AUTO; - if (orientation) { + if (orientation && this._orientation !== orientation) { this._orientation = orientation; var designWidth = this._originalDesignResolutionSize.width; var designHeight = this._originalDesignResolutionSize.height; From 8f3425334c5398e7bdd4f734555b43c1b4d0a3b0 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Mon, 16 Jan 2017 11:55:27 +0800 Subject: [PATCH 112/206] check context integrity --- cocos2d/audio/CCAudio.js | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/cocos2d/audio/CCAudio.js b/cocos2d/audio/CCAudio.js index 84ba432311..cfcc519c51 100644 --- a/cocos2d/audio/CCAudio.js +++ b/cocos2d/audio/CCAudio.js @@ -352,6 +352,15 @@ cc.Audio.WebAudio.prototype = { if (SWA) { var context = new (window.AudioContext || window.webkitAudioContext || window.mozAudioContext)(); cc.Audio._context = context; + // check context integrity + if ( + !context["createBufferSource"] || + !context["createGain"] || + !context["destination"] || + !context["decodeAudioData"] + ) { + throw 'context is incomplete'; + } if (polyfill.DELAY_CREATE_CTX) setTimeout(function () { context = new (window.AudioContext || window.webkitAudioContext || window.mozAudioContext)(); From d34f09ea178c2083572c793c0f2ed494b2b1d234 Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Thu, 19 Jan 2017 15:21:54 +0800 Subject: [PATCH 113/206] fix imageview possible memory leaks --- .../ccui/base-classes/UIScale9Sprite.js | 12 ++++++- extensions/ccui/uiwidgets/UIImageView.js | 32 +++++++++++-------- 2 files changed, 29 insertions(+), 15 deletions(-) diff --git a/extensions/ccui/base-classes/UIScale9Sprite.js b/extensions/ccui/base-classes/UIScale9Sprite.js index e9d635641b..7f052b4dce 100644 --- a/extensions/ccui/base-classes/UIScale9Sprite.js +++ b/extensions/ccui/base-classes/UIScale9Sprite.js @@ -1,3 +1,5 @@ +/* global ccui */ + /**************************************************************************** Copyright (c) 2008-2010 Ricardo Quesada Copyright (c) 2011-2012 cocos2d-x.org @@ -363,6 +365,7 @@ ccui.Scale9Sprite = cc.Scale9Sprite = cc.Node.extend(/** @lends ccui.Scale9Sprit _uvsDirty: true, _isTriangle: false, _isTrimmedContentSize: false, + _textureLoaded: false, //v3.3 _flippedX: false, @@ -410,6 +413,10 @@ ccui.Scale9Sprite = cc.Scale9Sprite = cc.Node.extend(/** @lends ccui.Scale9Sprit } }, + textureLoaded: function () { + return this._textureLoaded; + }, + getCapInsets: function () { return cc.rect(this._capInsetsInternal); }, @@ -473,6 +480,7 @@ ccui.Scale9Sprite = cc.Scale9Sprite = cc.Node.extend(/** @lends ccui.Scale9Sprit } var locLoaded = texture.isLoaded(); + this._textureLoaded = locLoaded; this._loader.clear(); if (!locLoaded) { this._loader.once(texture, function () { @@ -604,10 +612,12 @@ ccui.Scale9Sprite = cc.Scale9Sprite = cc.Node.extend(/** @lends ccui.Scale9Sprit if (cc.sizeEqualToSize(self._contentSize, cc.size(0, 0))) { self.setContentSize(self._spriteFrame._rect); } + self._textureLoaded = true; self._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.contentDirty); cc.renderer.childrenOrderDirty = true; }; - if (spriteFrame.textureLoaded()) { + self._textureLoaded = spriteFrame.textureLoaded(); + if (self._textureLoaded) { onResourceDataLoaded(); } else { this._loader.clear(); diff --git a/extensions/ccui/uiwidgets/UIImageView.js b/extensions/ccui/uiwidgets/UIImageView.js index 970d015160..fed3c958db 100644 --- a/extensions/ccui/uiwidgets/UIImageView.js +++ b/extensions/ccui/uiwidgets/UIImageView.js @@ -83,20 +83,6 @@ ccui.ImageView = ccui.Widget.extend(/** @lends ccui.ImageView# */{ this._imageTexType = texType; var imageRenderer = self._imageRenderer; - if(!imageRenderer._textureLoaded){ - imageRenderer.addEventListener("load", function(){ - if(!self._ignoreSize && cc.sizeEqualToSize(self._customSize, cc.size(0, 0))) { - self._customSize = self._imageRenderer.getContentSize(); - } - - self._imageTextureSize = imageRenderer.getContentSize(); - - self._updateChildrenDisplayedRGBA(); - - self._updateContentSizeWithTextureSize(self._imageTextureSize); - }); - } - switch (self._imageTexType) { case ccui.Widget.LOCAL_TEXTURE: if(self._scale9Enabled){ @@ -120,6 +106,24 @@ ccui.ImageView = ccui.Widget.extend(/** @lends ccui.ImageView# */{ break; } + if(!imageRenderer._textureLoaded){ + var handleTextureLoadedEvent = function(){ + imageRenderer.removeEventListener("load", handleTextureLoadedEvent); + + if(!self._ignoreSize && cc.sizeEqualToSize(self._customSize, cc.size(0, 0))) { + self._customSize = self._imageRenderer.getContentSize(); + } + + self._imageTextureSize = imageRenderer.getContentSize(); + + self._updateChildrenDisplayedRGBA(); + + self._updateContentSizeWithTextureSize(self._imageTextureSize); + }; + + imageRenderer.addEventListener("load", handleTextureLoadedEvent); + } + if(!this._ignoreSize && cc.sizeEqualToSize(this._customSize, cc.size(0, 0))) { this._customSize = this._imageRenderer.getContentSize(); } From ed8955117531a89ed48dce30bd99511f39b3ce4c Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Sun, 22 Jan 2017 11:18:18 +0800 Subject: [PATCH 114/206] improve uiText.js --- extensions/ccui/uiwidgets/UIText.js | 26 ++++++-------------------- 1 file changed, 6 insertions(+), 20 deletions(-) diff --git a/extensions/ccui/uiwidgets/UIText.js b/extensions/ccui/uiwidgets/UIText.js index adc25f3573..5d72e061c4 100644 --- a/extensions/ccui/uiwidgets/UIText.js +++ b/extensions/ccui/uiwidgets/UIText.js @@ -99,15 +99,12 @@ ccui.Text = ccui.Widget.extend(/** @lends ccui.Text# */{ */ setString: function (text) { if(text === this._labelRenderer.getString()) return; + this._setString(text); - this._labelRenderer.setString(text); this._updateContentSizeWithTextureSize(this._labelRenderer.getContentSize()); - this._labelRendererAdaptDirty = true; }, _setString: function (text) { - if(text === this._labelRenderer.getString()) return; - this._labelRenderer.setString(text); this._labelRendererAdaptDirty = true; }, @@ -143,10 +140,8 @@ ccui.Text = ccui.Widget.extend(/** @lends ccui.Text# */{ * @param {Number} size */ setFontSize: function (size) { - this._labelRenderer.setFontSize(size); - this._fontSize = size; + this._setFontSize(size); this._updateContentSizeWithTextureSize(this._labelRenderer.getContentSize()); - this._labelRendererAdaptDirty = true; }, _setFontSize: function (size) { @@ -168,10 +163,8 @@ ccui.Text = ccui.Widget.extend(/** @lends ccui.Text# */{ * @return {String} name */ setFontName: function (name) { - this._fontName = name; - this._labelRenderer.setFontName(name); + this._setFontName(name); this._updateContentSizeWithTextureSize(this._labelRenderer.getContentSize()); - this._labelRendererAdaptDirty = true; }, _setFontName: function (name) { @@ -218,12 +211,8 @@ ccui.Text = ccui.Widget.extend(/** @lends ccui.Text# */{ * @param {cc.Size} size */ setTextAreaSize: function (size) { - this._labelRenderer.setDimensions(size); - if (!this._ignoreSize) { - this._customSize = size; - } + this._setTextAreaSize(size); this._updateContentSizeWithTextureSize(this._labelRenderer.getContentSize()); - this._labelRendererAdaptDirty = true; }, _setTextAreaSize: function (size) { @@ -247,9 +236,8 @@ ccui.Text = ccui.Widget.extend(/** @lends ccui.Text# */{ * @param {cc.TEXT_ALIGNMENT_LEFT|cc.TEXT_ALIGNMENT_CENTER|cc.TEXT_ALIGNMENT_RIGHT} alignment Horizontal Alignment */ setTextHorizontalAlignment: function (alignment) { - this._labelRenderer.setHorizontalAlignment(alignment); + this._setTextHorizontalAlignment(alignment); this._updateContentSizeWithTextureSize(this._labelRenderer.getContentSize()); - this._labelRendererAdaptDirty = true; }, @@ -271,9 +259,8 @@ ccui.Text = ccui.Widget.extend(/** @lends ccui.Text# */{ * @param {cc.VERTICAL_TEXT_ALIGNMENT_TOP|cc.VERTICAL_TEXT_ALIGNMENT_CENTER|cc.VERTICAL_TEXT_ALIGNMENT_BOTTOM} alignment */ setTextVerticalAlignment: function (alignment) { - this._labelRenderer.setVerticalAlignment(alignment); + this._setTextVerticalAlignment(alignment); this._updateContentSizeWithTextureSize(this._labelRenderer.getContentSize()); - this._labelRendererAdaptDirty = true; }, _setTextVerticalAlignment: function (alignment) { @@ -364,7 +351,6 @@ ccui.Text = ccui.Widget.extend(/** @lends ccui.Text# */{ _labelScaleChangedWithSize: function () { var locContentSize = this._contentSize; if (this._ignoreSize) { - this._labelRenderer.setDimensions(0, 0); this._labelRenderer.setScale(1.0); this._normalScaleValueX = this._normalScaleValueY = 1; } else { From a69cbc19f5f09128cf0509c3f72dcca7f8475180 Mon Sep 17 00:00:00 2001 From: nmve Date: Sun, 22 Jan 2017 06:37:08 +0200 Subject: [PATCH 115/206] Update README.mdown --- README.mdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.mdown b/README.mdown index c41b79bc2c..57823c8723 100644 --- a/README.mdown +++ b/README.mdown @@ -1,7 +1,7 @@ Cocos2d-html5 ================== -[Cocos2d-html5][1] is a cross-platform 2D game engine written in Javascript, based on [Cocos2d-X][2] and licensed under MIT. +[Cocos2d-html5][1] is a cross-platform 2D game engine written in JavaScript, based on [Cocos2d-X][2] and licensed under MIT. It incorporates the same high level api as “Cocos2d JS-binding engine” and compatible with Cocos2d-X. It currently supports canvas and WebGL renderer. @@ -49,4 +49,4 @@ Contact us [5]: http://forum.cocos2d-x.org "http://forum.cocos2d-x.org" [6]: http://www.twitter.com/cocos2dhtml5 "http://www.twitter.com/cocos2dhtml5" [7]: http://t.sina.com.cn/cocos2dhtml5 "http://t.sina.com.cn/cocos2dhtml5" -[8]: http://bower.io "http://bower.io" \ No newline at end of file +[8]: http://bower.io "http://bower.io" From 9613342cfdc97c45bfa1ca17f1376c138ed8b0fa Mon Sep 17 00:00:00 2001 From: giuseppelt Date: Thu, 26 Jan 2017 12:12:27 +0100 Subject: [PATCH 116/206] Fix DrawNode canvas displayedOpacity rendering --- cocos2d/shape-nodes/CCDrawNodeCanvasRenderCmd.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos2d/shape-nodes/CCDrawNodeCanvasRenderCmd.js b/cocos2d/shape-nodes/CCDrawNodeCanvasRenderCmd.js index 771f852748..92189454b7 100644 --- a/cocos2d/shape-nodes/CCDrawNodeCanvasRenderCmd.js +++ b/cocos2d/shape-nodes/CCDrawNodeCanvasRenderCmd.js @@ -44,7 +44,7 @@ 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; + var alpha = this._displayedOpacity / 255; if (alpha === 0) return; From 83540d8ec258bb75a86a64c51688b982640c54d5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alicia=20Boya=20Garc=C3=ADa?= Date: Tue, 31 Jan 2017 15:59:52 +0100 Subject: [PATCH 117/206] Text wrapping support for more languages --- .../labelttf/CCLabelTTFCanvasRenderCmd.js | 26 ++++++++++++++----- 1 file changed, 19 insertions(+), 7 deletions(-) diff --git a/cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js b/cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js index 51fb3888b4..fe036fcf2a 100644 --- a/cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js +++ b/cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js @@ -24,13 +24,25 @@ cc.LabelTTF._textBaseline = ["top", "middle", "bottom"]; //check the first character cc.LabelTTF.wrapInspection = true; -//Support: English French German -//Other as Oriental Language -cc.LabelTTF._wordRex = /([a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]+|\S)/; -cc.LabelTTF._symbolRex = /^[!,.:;}\]%\?>、‘“》?。,!]/; -cc.LabelTTF._lastWordRex = /([a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]+|\S)$/; -cc.LabelTTF._lastEnglish = /[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]+$/; -cc.LabelTTF._firsrEnglish = /^[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]/; +// These regular expressions consider a word any sequence of characters +// from these Unicode (sub)blocks: +// - Basic Latin (letters and numbers only, plus the hypen-minus '-') +// - Latin-1 Supplement (accentuated letters only) +// - Latin Extended-A (complete) +// - Latin Extended-B (complete) +// - IPA Extensions (complete) +// - Spacing Modifier Letters (complete) +// - Combining Diacritical Marks (Combining Grapheme Joiner excluded) +// - Greek and Coptic (complete, including reserved code points) +// - Cyrillic (complete) +// - Cyrillic Supplement (complete) +// - General Punctuation (Non-Breaking Hyphen [U+2011] only*) +// * Note that Hyphen [U+2010] is considered a word boundary. +cc.LabelTTF._wordRex = /([a-zA-Z0-9À-ÖØ-öø-ʯ\u0300-\u034e\u0350-\u036FͰ-ԯ\u2011]+|\S)/; +cc.LabelTTF._symbolRex = /^[!,.:;}\]%\?>、‘“》»?。,!\u2010]/; +cc.LabelTTF._lastWordRex = /([a-zA-Z0-9À-ÖØ-öø-ʯ\u0300-\u034e\u0350-\u036FͰ-ԯ\u2011]+|\S)$/; +cc.LabelTTF._lastEnglish = /[a-zA-Z0-9À-ÖØ-öø-ʯ\u0300-\u034e\u0350-\u036FͰ-ԯ\u2011]+$/; +cc.LabelTTF._firsrEnglish = /^[a-zA-Z0-9À-ÖØ-öø-ʯ\u0300-\u034e\u0350-\u036FͰ-ԯ\u2011]/; (function () { cc.LabelTTF.RenderCmd = function () { From fa3d2faff9f11a346ceb0cd1a8278a05c6e03842 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alicia=20Boya=20Garc=C3=ADa?= Date: Tue, 31 Jan 2017 18:57:03 +0100 Subject: [PATCH 118/206] =?UTF-8?q?Text=20wrap=20regexp:=20handle=20=C2=BF?= =?UTF-8?q?=C2=A1=20add=20the=20hyphen-minus=20and=20more=20quotation=20ma?= =?UTF-8?q?rks?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../core/labelttf/CCLabelTTFCanvasRenderCmd.js | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js b/cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js index fe036fcf2a..42d5ccf3d4 100644 --- a/cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js +++ b/cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js @@ -26,8 +26,8 @@ cc.LabelTTF.wrapInspection = true; // These regular expressions consider a word any sequence of characters // from these Unicode (sub)blocks: -// - Basic Latin (letters and numbers only, plus the hypen-minus '-') -// - Latin-1 Supplement (accentuated letters only) +// - Basic Latin (letters and numbers, plus the hypen-minus '-') +// - Latin-1 Supplement (accentuated letters and ¿¡ only) // - Latin Extended-A (complete) // - Latin Extended-B (complete) // - IPA Extensions (complete) @@ -36,13 +36,13 @@ cc.LabelTTF.wrapInspection = true; // - Greek and Coptic (complete, including reserved code points) // - Cyrillic (complete) // - Cyrillic Supplement (complete) -// - General Punctuation (Non-Breaking Hyphen [U+2011] only*) +// - General Punctuation (Non-Breaking Hyphen* [U+2011] and quotation marks) // * Note that Hyphen [U+2010] is considered a word boundary. -cc.LabelTTF._wordRex = /([a-zA-Z0-9À-ÖØ-öø-ʯ\u0300-\u034e\u0350-\u036FͰ-ԯ\u2011]+|\S)/; -cc.LabelTTF._symbolRex = /^[!,.:;}\]%\?>、‘“》»?。,!\u2010]/; -cc.LabelTTF._lastWordRex = /([a-zA-Z0-9À-ÖØ-öø-ʯ\u0300-\u034e\u0350-\u036FͰ-ԯ\u2011]+|\S)$/; -cc.LabelTTF._lastEnglish = /[a-zA-Z0-9À-ÖØ-öø-ʯ\u0300-\u034e\u0350-\u036FͰ-ԯ\u2011]+$/; -cc.LabelTTF._firsrEnglish = /^[a-zA-Z0-9À-ÖØ-öø-ʯ\u0300-\u034e\u0350-\u036FͰ-ԯ\u2011]/; +cc.LabelTTF._wordRex = /([a-zA-Z0-9\-¿¡«À-ÖØ-öø-ʯ\u0300-\u034e\u0350-\u036FͰ-ԯ\u2011‵-‷‹⁅]+|\S)/; +cc.LabelTTF._symbolRex = /^[!,.:;}\]%\?>、‘“》»?。,!\u2010′-‴›‼⁆⁇-⁉]/; +cc.LabelTTF._lastWordRex = /([a-zA-Z0-9\-¿¡«À-ÖØ-öø-ʯ\u0300-\u034e\u0350-\u036FͰ-ԯ\u2011‵-‷‹⁅]+|\S)$/; +cc.LabelTTF._lastEnglish = /[a-zA-Z0-9\-¿¡«À-ÖØ-öø-ʯ\u0300-\u034e\u0350-\u036FͰ-ԯ\u2011‵-‷‹⁅]+$/; +cc.LabelTTF._firsrEnglish = /^[a-zA-Z0-9\-¿¡«À-ÖØ-öø-ʯ\u0300-\u034e\u0350-\u036FͰ-ԯ\u2011‵-‷‹⁅]/; (function () { cc.LabelTTF.RenderCmd = function () { From c4f9f39bf59cfa8e9739e703020b215cb4234f7a Mon Sep 17 00:00:00 2001 From: giuseppelt Date: Wed, 8 Feb 2017 21:26:09 +0100 Subject: [PATCH 119/206] Fix node.updateTransform var typo --- cocos2d/core/base-nodes/CCNode.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos2d/core/base-nodes/CCNode.js b/cocos2d/core/base-nodes/CCNode.js index 2b62bc06c4..723b27fe5f 100644 --- a/cocos2d/core/base-nodes/CCNode.js +++ b/cocos2d/core/base-nodes/CCNode.js @@ -2015,7 +2015,7 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{ updateTransform: function () { var children = this._children, node; for (var i = 0; i < children.length; i++) { - varnode = children[i]; + node = children[i]; if (node) node.updateTransform(); } From 88fa7ff69e410d3d1449bf3197cadff6d335dba1 Mon Sep 17 00:00:00 2001 From: minggo Date: Fri, 17 Feb 2017 14:36:08 +0800 Subject: [PATCH 120/206] spine works on canvas --- extensions/spine/CCSkeleton.js | 26 +- extensions/spine/CCSkeletonAnimation.js | 17 +- extensions/spine/CCSkeletonCanvasRenderCmd.js | 55 +- extensions/spine/CCSkeletonTexture.js | 68 + extensions/spine/Spine.js | 8081 +++++++++++------ moduleConfig.json | 1 + 6 files changed, 5467 insertions(+), 2781 deletions(-) create mode 100644 extensions/spine/CCSkeletonTexture.js diff --git a/extensions/spine/CCSkeleton.js b/extensions/spine/CCSkeleton.js index 9bab9e8d16..a4385588e7 100644 --- a/extensions/spine/CCSkeleton.js +++ b/extensions/spine/CCSkeleton.js @@ -183,7 +183,7 @@ sp.Skeleton = cc.Node.extend(/** @lends sp.Skeleton# */{ if (cc.isString(argAtlasFile)) { var data = cc.loader.getRes(argAtlasFile); sp._atlasLoader.setAtlasFile(argAtlasFile); - atlas = new spine.Atlas(data, sp._atlasLoader); + atlas = new spine.TextureAtlas(data, sp._atlasLoader.load.bind(sp._atlasLoader)); } else { atlas = atlasFile; } @@ -212,14 +212,14 @@ sp.Skeleton = cc.Node.extend(/** @lends sp.Skeleton# */{ getBoundingBox: function () { var minX = cc.FLT_MAX, minY = cc.FLT_MAX, maxX = cc.FLT_MIN, maxY = cc.FLT_MIN; var scaleX = this.getScaleX(), scaleY = this.getScaleY(), vertices = [], - slots = this._skeleton.slots, VERTEX = sp.VERTEX_INDEX; + slots = this._skeleton.slots, VERTEX = spine.RegionAttachment; for (var i = 0, slotCount = slots.length; i < slotCount; ++i) { var slot = slots[i]; - if (!slot.attachment || slot.attachment.type != sp.ATTACHMENT_TYPE.REGION) + if (!slot.attachment || ! (attachment instanceof spine.RegionAttachment)) continue; var attachment = slot.attachment; - this._computeRegionAttachmentWorldVertices(attachment, slot.bone.skeleton.x, slot.bone.skeleton.y, slot.bone, vertices); + vertices = attachment.updateWorldVertices(slot, false); minX = Math.min(minX, vertices[VERTEX.X1] * scaleX, vertices[VERTEX.X4] * scaleX, vertices[VERTEX.X2] * scaleX, vertices[VERTEX.X3] * scaleX); minY = Math.min(minY, vertices[VERTEX.Y1] * scaleY, vertices[VERTEX.Y4] * scaleY, vertices[VERTEX.Y2] * scaleY, vertices[VERTEX.Y3] * scaleY); maxX = Math.max(maxX, vertices[VERTEX.X1] * scaleX, vertices[VERTEX.X4] * scaleX, vertices[VERTEX.X2] * scaleX, vertices[VERTEX.X3] * scaleX); @@ -229,20 +229,6 @@ sp.Skeleton = cc.Node.extend(/** @lends sp.Skeleton# */{ return cc.rect(position.x + minX, position.y + minY, maxX - minX, maxY - minY); }, - _computeRegionAttachmentWorldVertices : function(self, x, y, bone, vertices){ - var offset = self.offset, vertexIndex = sp.VERTEX_INDEX; - x += bone.worldX; - y += bone.worldY; - vertices[vertexIndex.X1] = offset[vertexIndex.X1] * bone.m00 + offset[vertexIndex.Y1] * bone.m01 + x; - vertices[vertexIndex.Y1] = offset[vertexIndex.X1] * bone.m10 + offset[vertexIndex.Y1] * bone.m11 + y; - vertices[vertexIndex.X2] = offset[vertexIndex.X2] * bone.m00 + offset[vertexIndex.Y2] * bone.m01 + x; - vertices[vertexIndex.Y2] = offset[vertexIndex.X2] * bone.m10 + offset[vertexIndex.Y2] * bone.m11 + y; - vertices[vertexIndex.X3] = offset[vertexIndex.X3] * bone.m00 + offset[vertexIndex.Y3] * bone.m01 + x; - vertices[vertexIndex.Y3] = offset[vertexIndex.X3] * bone.m10 + offset[vertexIndex.Y3] * bone.m11 + y; - vertices[vertexIndex.X4] = offset[vertexIndex.X4] * bone.m00 + offset[vertexIndex.Y4] * bone.m01 + x; - vertices[vertexIndex.Y4] = offset[vertexIndex.X4] * bone.m10 + offset[vertexIndex.Y4] * bone.m11 + y; - }, - /** * Computes the world SRT from the local SRT for each bone. */ @@ -305,7 +291,7 @@ sp.Skeleton = cc.Node.extend(/** @lends sp.Skeleton# */{ * @returns {spine.RegionAttachment|spine.BoundingBoxAttachment} */ getAttachment: function (slotName, attachmentName) { - return this._skeleton.getAttachmentBySlotName(slotName, attachmentName); + return this._skeleton.getAttachmentByName(slotName, attachmentName); }, /** @@ -356,7 +342,7 @@ sp.Skeleton = cc.Node.extend(/** @lends sp.Skeleton# */{ * @returns {cc.Node} */ getTextureAtlas: function (regionAttachment) { - return regionAttachment.rendererObject.page.rendererObject; + return regionAttachment.region; }, /** diff --git a/extensions/spine/CCSkeletonAnimation.js b/extensions/spine/CCSkeletonAnimation.js index b5308f2b52..9d787c5fbf 100644 --- a/extensions/spine/CCSkeletonAnimation.js +++ b/extensions/spine/CCSkeletonAnimation.js @@ -47,12 +47,13 @@ sp._atlasLoader = { setAtlasFile:function(spAtlasFile){ this.spAtlasFile = spAtlasFile; }, - load:function(page, line, spAtlas){ + load:function(line){ var texturePath = cc.path.join(cc.path.dirname(this.spAtlasFile), line); - if (cc._renderType === cc.game.RENDER_TYPE_WEBGL) - sp._atlasPage_createTexture_webGL(page,texturePath); - else - sp._atlasPage_createTexture_canvas(page,texturePath); + var texture = cc.textureCache.addImage(texturePath); + var tex = new sp.SkeletonTexture(); + tex._image = { width: texture.getPixelsWide(), height: texture.getPixelsHigh() }; + tex.setRealTexture(texture); + return tex; }, unload:function(obj){ } @@ -139,7 +140,7 @@ sp.SkeletonAnimation = sp.Skeleton.extend(/** @lends sp.SkeletonAnimation# */{ * @param {Number} duration */ setMix: function (fromAnimation, toAnimation, duration) { - this._state.data.setMixByName(fromAnimation, toAnimation, duration); + this._state.data.setMixWith(fromAnimation, toAnimation, duration); }, /** @@ -165,7 +166,7 @@ sp.SkeletonAnimation = sp.Skeleton.extend(/** @lends sp.SkeletonAnimation# */{ cc.log("Spine: Animation not found: " + name); return null; } - return this._state.setAnimation(trackIndex, animation, loop); + return this._state.setAnimationWith(trackIndex, animation, loop); }, /** @@ -183,7 +184,7 @@ sp.SkeletonAnimation = sp.Skeleton.extend(/** @lends sp.SkeletonAnimation# */{ cc.log("Spine: Animation not found:" + name); return null; } - return this._state.addAnimation(trackIndex, animation, loop, delay); + return this._state.addAnimationWith(trackIndex, animation, loop, delay); }, /** diff --git a/extensions/spine/CCSkeletonCanvasRenderCmd.js b/extensions/spine/CCSkeletonCanvasRenderCmd.js index 073c8ab045..2b20f3f97c 100644 --- a/extensions/spine/CCSkeletonCanvasRenderCmd.js +++ b/extensions/spine/CCSkeletonCanvasRenderCmd.js @@ -60,7 +60,7 @@ var points = []; for (i = 0, n = locSkeleton.slots.length; i < n; i++) { slot = locSkeleton.drawOrder[i]; - if (!slot.attachment || slot.attachment.type != sp.ATTACHMENT_TYPE.REGION) + if (!slot.attachment || !(slot.attachment instanceof spine.RegionAttachment)) continue; attachment = slot.attachment; this._updateRegionAttachmentSlot(attachment, slot, points); @@ -76,8 +76,8 @@ for (i = 0, n = locSkeleton.bones.length; i < n; i++) { bone = locSkeleton.bones[i]; - var x = bone.data.length * bone.m00 + bone.worldX; - var y = bone.data.length * bone.m10 + bone.worldY; + var x = bone.data.length * bone.a + bone.worldX; + var y = bone.data.length * bone.c + bone.worldY; drawingUtil.drawLine( {x: bone.worldX, y: bone.worldY}, {x: x, y: y}); @@ -100,8 +100,8 @@ if (!points) return; - var vertices = {}, VERTEX = sp.VERTEX_INDEX, bone = slot.bone; - attachment.computeVertices(bone.skeleton.x, bone.skeleton.y, bone, vertices); + var vertices = attachment.updateWorldVertices(slot, false); + var VERTEX = spine.RegionAttachment; points.length = 0; points.push(cc.p(vertices[VERTEX.X1], vertices[VERTEX.Y1])); points.push(cc.p(vertices[VERTEX.X4], vertices[VERTEX.Y4])); @@ -118,7 +118,7 @@ slot._slotNode = slotNode; if (attachment instanceof spine.RegionAttachment) { - spriteName = attachment.rendererObject.name; + spriteName = attachment.region.name; sprite = this._createSprite(slot, attachment); slot.currentSprite = sprite; slot.currentSpriteName = spriteName; @@ -141,8 +141,8 @@ }; proto._createSprite = function (slot, attachment) { - var rendererObject = attachment.rendererObject; - var texture = rendererObject.page._texture; + var rendererObject = attachment.region; + var texture = rendererObject.texture.getRealTexture(); var sprite = new cc.Sprite(); if (texture.isLoaded()) { loaded(sprite, texture, rendererObject, attachment); @@ -158,7 +158,8 @@ proto._updateChild = function () { var locSkeleton = this._node._skeleton, slots = locSkeleton.slots; - var i, n, selSprite; + var color = this._displayedColor, opacity = this._displayedOpacity; + var i, n, selSprite, ax, ay; var slot, attachment, slotNode; for (i = 0, n = slots.length; i < n; i++) { @@ -169,11 +170,10 @@ slotNode.setVisible(false); continue; } - var type = attachment.type; - if (type === spine.AttachmentType.region) { - if (attachment.rendererObject) { + if (attachment instanceof spine.RegionAttachment){ + if (attachment.region) { if (!slot.currentSpriteName || slot.currentSpriteName !== attachment.name) { - var spriteName = attachment.rendererObject.name; + var spriteName = attachment.region.name; if (slot.currentSprite !== undefined) slot.currentSprite.setVisible(false); slot.sprites = slot.sprites || {}; @@ -188,28 +188,37 @@ } } var bone = slot.bone; - slotNode.setPosition(bone.worldX + attachment.x * bone.m00 + attachment.y * bone.m01, - bone.worldY + attachment.x * bone.m10 + attachment.y * bone.m11); - slotNode.setScale(bone.worldScaleX, bone.worldScaleY); + if (attachment.region.offsetX === 0 && attachment.region.offsetY === 0) { + ax = attachment.x; + ay = attachment.y; + } + else { + //var regionScaleX = attachment.width / attachment.regionOriginalWidth * attachment.scaleX; + //ax = attachment.x + attachment.regionOffsetX * regionScaleX - (attachment.width * attachment.scaleX - attachment.regionWidth * regionScaleX) / 2; + ax = (attachment.offset[0] + attachment.offset[4]) * 0.5; + ay = (attachment.offset[1] + attachment.offset[5]) * 0.5; + } + slotNode.setPosition(bone.worldX + ax * bone.a + ay * bone.b, bone.worldY + ax * bone.c + ay * bone.d); + slotNode.setScale(bone.getWorldScaleX(), bone.getWorldScaleY()); //set the color and opacity selSprite = slot.currentSprite; - selSprite._flippedX = bone.worldFlipX; - selSprite._flippedY = bone.worldFlipY; + selSprite._flippedX = bone.skeleton.flipX; + selSprite._flippedY = bone.skeleton.flipY; if (selSprite._flippedY || selSprite._flippedX) { - slotNode.setRotation(bone.worldRotation); + slotNode.setRotation(bone.getWorldRotationX()); selSprite.setRotation(attachment.rotation); } else { - slotNode.setRotation(-bone.worldRotation); + slotNode.setRotation(-bone.getWorldRotationX()); selSprite.setRotation(-attachment.rotation); } //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._renderCmd._displayedOpacity = 0 | (opacity * slot.color.a); + var r = 0 | (color.r * slot.color.r), g = 0 | (color.g * slot.color.g), b = 0 | (color.b * slot.color.b); selSprite.setColor(cc.color(r, g, b)); selSprite._renderCmd._updateColor(); - } else if (type === spine.AttachmentType.skinnedmesh) { + } else if (attachment instanceof spine.MeshAttachment) { //todo for mesh } else { slotNode.setVisible(false); diff --git a/extensions/spine/CCSkeletonTexture.js b/extensions/spine/CCSkeletonTexture.js new file mode 100644 index 0000000000..997065b339 --- /dev/null +++ b/extensions/spine/CCSkeletonTexture.js @@ -0,0 +1,68 @@ +/**************************************************************************** + Copyright (c) 2017 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. + ****************************************************************************/ + +sp.SkeletonTexture = cc.Class.extend({ + name: 'sp.SkeletonTexture', + _texture: null, + + setRealTexture: function(tex) { + this._texture = tex; + }, + + getRealTexture: function() { + return this._texture; + }, + + setFilters: function(minFilter, magFilter) { + if (cc._renderType === cc.game.RENDER_TYPE_WEBGL) { + var gl = cc._renderContext; + this.bind(); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter); + } + }, + + setWraps: function(uWrap, vWrap) { + if (cc._renderType === cc.game.RENDER_TYPE_WEBGL) { + var gl = cc._renderContext; + this.bind(); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, uWrap); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, vWrap); + } + }, + + dispose: function() { + }, + + bind: function() { + if (cc._renderType === cc.game.RENDER_TYPE_WEBGL) { + cc.glBindTexture2D(this._texture); + } + } +}); + +var proto = sp.SkeletonTexture.prototype; +cc.extend(proto, spine.Texture.prototype); +// proto.constructor = spine.Texture; + diff --git a/extensions/spine/Spine.js b/extensions/spine/Spine.js index 4fe7807715..2007cb45e9 100644 --- a/extensions/spine/Spine.js +++ b/extensions/spine/Spine.js @@ -1,2731 +1,5352 @@ -/****************************************************************************** - * Spine Runtimes Software License - * Version 2.3 - * - * Copyright (c) 2013-2015, Esoteric Software - * All rights reserved. - * - * You are granted a perpetual, non-exclusive, non-sublicensable and - * non-transferable license to use, install, execute and perform the Spine - * Runtimes Software (the "Software") and derivative works solely for personal - * or internal use. Without the written permission of Esoteric Software (see - * Section 2 of the Spine Software License Agreement), you may not (a) modify, - * translate, adapt or otherwise create derivative works, improvements of the - * Software or develop new applications using the Software or (b) remove, - * delete, alter or obscure any trademarks or any copyright, trademark, patent - * or other intellectual property or proprietary rights notices on or in the - * Software, including any copy thereof. Redistributions in binary or source - * form must include this license and terms. - * - * THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE "AS IS" AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO - * EVENT SHALL ESOTERIC SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - *****************************************************************************/ - -var spine = { - radDeg: 180 / Math.PI, - degRad: Math.PI / 180, - temp: [], - Float32Array: (typeof(Float32Array) === 'undefined') ? Array : Float32Array, - Uint16Array: (typeof(Uint16Array) === 'undefined') ? Array : Uint16Array -}; - -spine.BoneData = function (name, parent) { - this.length = this.x = this.y = this.rotation = 0; - this.scaleX = this.scaleY = 1; - - this.name = name; - this.parent = parent; -}; - -spine.BoneData.prototype = { - length: 0, - x: 0, y: 0, - rotation: 0, - scaleX: 1, scaleY: 1, - inheritScale: true, - inheritRotation: true, - flipX: false, flipY: false -}; - -spine.BlendMode = { - normal: 0, - additive: 1, - multiply: 2, - screen: 3 -}; - -spine.SlotData = function (name, boneData) { - this.r = this.g = this.b = this.a = 1; - this.blendMode = spine.BlendMode.normal; - - this.name = name; - this.boneData = boneData; -}; -spine.SlotData.prototype = { - r: 1, g: 1, b: 1, a: 1, - attachmentName: null, - blendMode: spine.BlendMode.normal -}; - -spine.IkConstraintData = function (name) { - this.bendDirection = this.mix = 1; - - this.name = name; - this.bones = []; -}; -spine.IkConstraintData.prototype = { - target: null, - bendDirection: 1, - mix: 1 -}; - -spine.Bone = function (boneData, skeleton, parent) { - this.x = this.y = this.rotation = this.rotationIK = 0; - this.scaleX = this.scaleY = 1; - this.flipX = this.flipY = false; - this.m00 = this.m01 = this.worldX = 0; // a b x - this.m10 = this.m11= this.worldY = 0; // c d y - this.worldRotation = 0; - this.worldScaleX = this.worldScaleY = 1; - this.worldFlipX = this.worldFlipY = false; - - this.data = boneData; - this.skeleton = skeleton; - this.parent = parent; - this.setToSetupPose(); -}; -spine.Bone.yDown = false; -spine.Bone.prototype = { - x: 0, y: 0, - rotation: 0, rotationIK: 0, - scaleX: 1, scaleY: 1, - flipX: false, flipY: false, - m00: 0, m01: 0, worldX: 0, // a b x - m10: 0, m11: 0, worldY: 0, // c d y - worldRotation: 0, - worldScaleX: 1, worldScaleY: 1, - worldFlipX: false, worldFlipY: false, - updateWorldTransform: function () { - var parent = this.parent; - if (parent) { - this.worldX = this.x * parent.m00 + this.y * parent.m01 + parent.worldX; - this.worldY = this.x * parent.m10 + this.y * parent.m11 + parent.worldY; - if (this.data.inheritScale) { - this.worldScaleX = parent.worldScaleX * this.scaleX; - this.worldScaleY = parent.worldScaleY * this.scaleY; - } else { - this.worldScaleX = this.scaleX; - this.worldScaleY = this.scaleY; - } - this.worldRotation = this.data.inheritRotation ? (parent.worldRotation + this.rotationIK) : this.rotationIK; - this.worldFlipX = parent.worldFlipX != this.flipX; - this.worldFlipY = parent.worldFlipY != this.flipY; - } else { - var skeletonFlipX = this.skeleton.flipX, skeletonFlipY = this.skeleton.flipY; - this.worldX = skeletonFlipX ? -this.x : this.x; - this.worldY = (skeletonFlipY != spine.Bone.yDown) ? -this.y : this.y; - this.worldScaleX = this.scaleX; - this.worldScaleY = this.scaleY; - this.worldRotation = this.rotationIK; - this.worldFlipX = skeletonFlipX != this.flipX; - this.worldFlipY = skeletonFlipY != this.flipY; - } - var radians = this.worldRotation * spine.degRad; - var cos = Math.cos(radians); - var sin = Math.sin(radians); - if (this.worldFlipX) { - this.m00 = -cos * this.worldScaleX; - this.m01 = sin * this.worldScaleY; - } else { - this.m00 = cos * this.worldScaleX; - this.m01 = -sin * this.worldScaleY; - } - if (this.worldFlipY != spine.Bone.yDown) { - this.m10 = -sin * this.worldScaleX; - this.m11 = -cos * this.worldScaleY; - } else { - this.m10 = sin * this.worldScaleX; - this.m11 = cos * this.worldScaleY; - } - }, - setToSetupPose: function () { - var data = this.data; - this.x = data.x; - this.y = data.y; - this.rotation = data.rotation; - this.rotationIK = this.rotation; - this.scaleX = data.scaleX; - this.scaleY = data.scaleY; - this.flipX = data.flipX; - this.flipY = data.flipY; - }, - worldToLocal: function (world) { - var dx = world[0] - this.worldX, dy = world[1] - this.worldY; - var m00 = this.m00, m10 = this.m10, m01 = this.m01, m11 = this.m11; - if (this.worldFlipX != (this.worldFlipY != spine.Bone.yDown)) { - m00 = -m00; - m11 = -m11; - } - var invDet = 1 / (m00 * m11 - m01 * m10); - world[0] = dx * m00 * invDet - dy * m01 * invDet; - world[1] = dy * m11 * invDet - dx * m10 * invDet; - }, - localToWorld: function (local) { - var localX = local[0], localY = local[1]; - local[0] = localX * this.m00 + localY * this.m01 + this.worldX; - local[1] = localX * this.m10 + localY * this.m11 + this.worldY; - } -}; - -spine.Slot = function (slotData, bone) { - this.r = this.g = this.b = this.a = 1; - this._attachmentTime = 0; - - this.data = slotData; - this.bone = bone; - this.setToSetupPose(); -}; -spine.Slot.prototype = { - r: 1, g: 1, b: 1, a: 1, - _attachmentTime: 0, - attachment: null, - attachmentVertices: [], - setAttachment: function (attachment) { - this.attachment = attachment; - this._attachmentTime = this.bone.skeleton.time; - this.attachmentVertices.length = 0; - }, - setAttachmentTime: function (time) { - this._attachmentTime = this.bone.skeleton.time - time; - }, - getAttachmentTime: function () { - return this.bone.skeleton.time - this._attachmentTime; - }, - setToSetupPose: function () { - var data = this.data; - this.r = data.r; - this.g = data.g; - this.b = data.b; - this.a = data.a; - - var slotDatas = this.bone.skeleton.data.slots; - for (var i = 0, n = slotDatas.length; i < n; i++) { - if (slotDatas[i] == data) { - this.setAttachment(!data.attachmentName ? null : this.bone.skeleton.getAttachmentBySlotIndex(i, data.attachmentName)); - break; - } - } - } -}; - -spine.IkConstraint = function (data, skeleton) { - this.data = data; - this.mix = data.mix; - this.bendDirection = data.bendDirection; - - this.bones = []; - for (var i = 0, n = data.bones.length; i < n; i++) - this.bones.push(skeleton.findBone(data.bones[i].name)); - this.target = skeleton.findBone(data.target.name); -}; -spine.IkConstraint.prototype = { - apply: function () { - var target = this.target; - var bones = this.bones; - switch (bones.length) { - case 1: - spine.IkConstraint.apply1(bones[0], target.worldX, target.worldY, this.mix); - break; - case 2: - spine.IkConstraint.apply2(bones[0], bones[1], target.worldX, target.worldY, this.bendDirection, this.mix); - break; - } - } -}; -/** Adjusts the bone rotation so the tip is as close to the target position as possible. The target is specified in the world - * coordinate system. */ -spine.IkConstraint.apply1 = function (bone, targetX, targetY, alpha) { - var parentRotation = (!bone.data.inheritRotation || !bone.parent) ? 0 : bone.parent.worldRotation; - var rotation = bone.rotation; - var rotationIK = Math.atan2(targetY - bone.worldY, targetX - bone.worldX) * spine.radDeg; - if (bone.worldFlipX != (bone.worldFlipY != spine.Bone.yDown)) rotationIK = -rotationIK; - rotationIK -= parentRotation; - bone.rotationIK = rotation + (rotationIK - rotation) * alpha; -}; -/** Adjusts the parent and child bone rotations so the tip of the child is as close to the target position as possible. The - * target is specified in the world coordinate system. - * @param child Any descendant bone of the parent. */ -spine.IkConstraint.apply2 = function (parent, child, targetX, targetY, bendDirection, alpha) { - var childRotation = child.rotation, parentRotation = parent.rotation; - if (!alpha) { - child.rotationIK = childRotation; - parent.rotationIK = parentRotation; - return; - } - var positionX, positionY, tempPosition = spine.temp; - var parentParent = parent.parent; - if (parentParent) { - tempPosition[0] = targetX; - tempPosition[1] = targetY; - parentParent.worldToLocal(tempPosition); - targetX = (tempPosition[0] - parent.x) * parentParent.worldScaleX; - targetY = (tempPosition[1] - parent.y) * parentParent.worldScaleY; - } else { - targetX -= parent.x; - targetY -= parent.y; - } - if (child.parent == parent) { - positionX = child.x; - positionY = child.y; - } else { - tempPosition[0] = child.x; - tempPosition[1] = child.y; - child.parent.localToWorld(tempPosition); - parent.worldToLocal(tempPosition); - positionX = tempPosition[0]; - positionY = tempPosition[1]; - } - var childX = positionX * parent.worldScaleX, childY = positionY * parent.worldScaleY; - var offset = Math.atan2(childY, childX); - var len1 = Math.sqrt(childX * childX + childY * childY), len2 = child.data.length * child.worldScaleX; - // Based on code by Ryan Juckett with permission: Copyright (c) 2008-2009 Ryan Juckett, http://www.ryanjuckett.com/ - var cosDenom = 2 * len1 * len2; - if (cosDenom < 0.0001) { - child.rotationIK = childRotation + (Math.atan2(targetY, targetX) * spine.radDeg - parentRotation - childRotation) * alpha; - return; - } - var cos = (targetX * targetX + targetY * targetY - len1 * len1 - len2 * len2) / cosDenom; - if (cos < -1) - cos = -1; - else if (cos > 1) - cos = 1; - var childAngle = Math.acos(cos) * bendDirection; - var adjacent = len1 + len2 * cos, opposite = len2 * Math.sin(childAngle); - var parentAngle = Math.atan2(targetY * adjacent - targetX * opposite, targetX * adjacent + targetY * opposite); - var rotation = (parentAngle - offset) * spine.radDeg - parentRotation; - if (rotation > 180) - rotation -= 360; - else if (rotation < -180) // - rotation += 360; - parent.rotationIK = parentRotation + rotation * alpha; - rotation = (childAngle + offset) * spine.radDeg - childRotation; - if (rotation > 180) - rotation -= 360; - else if (rotation < -180) // - rotation += 360; - child.rotationIK = childRotation + (rotation + parent.worldRotation - child.parent.worldRotation) * alpha; -}; - -spine.Skin = function (name) { - this.name = name; - this.attachments = {}; -}; -spine.Skin.prototype = { - addAttachment: function (slotIndex, name, attachment) { - this.attachments[slotIndex + ":" + name] = attachment; - }, - getAttachment: function (slotIndex, name) { - return this.attachments[slotIndex + ":" + name]; - }, - _attachAll: function (skeleton, oldSkin) { - for (var key in oldSkin.attachments) { - var colon = key.indexOf(":"); - var slotIndex = parseInt(key.substring(0, colon)); - var name = key.substring(colon + 1); - var slot = skeleton.slots[slotIndex]; - if (slot.attachment && slot.attachment.name == name) { - var attachment = this.getAttachment(slotIndex, name); - if (attachment) slot.setAttachment(attachment); - } - } - } -}; - -spine.Animation = function (name, timelines, duration) { - this.name = name; - this.timelines = timelines; - this.duration = duration; -}; -spine.Animation.prototype = { - apply: function (skeleton, lastTime, time, loop, events) { - if (loop && this.duration != 0) { - time %= this.duration; - lastTime %= this.duration; - } - var timelines = this.timelines; - for (var i = 0, n = timelines.length; i < n; i++) - timelines[i].apply(skeleton, lastTime, time, events, 1); - }, - mix: function (skeleton, lastTime, time, loop, events, alpha) { - if (loop && this.duration != 0) { - time %= this.duration; - lastTime %= this.duration; - } - var timelines = this.timelines; - for (var i = 0, n = timelines.length; i < n; i++) - timelines[i].apply(skeleton, lastTime, time, events, alpha); - } -}; -spine.Animation.binarySearch = function (values, target, step) { - var low = 0; - var high = Math.floor(values.length / step) - 2; - if (!high) return step; - var current = high >>> 1; - while (true) { - if (values[(current + 1) * step] <= target) - low = current + 1; - else - high = current; - if (low == high) return (low + 1) * step; - current = (low + high) >>> 1; - } -}; -spine.Animation.binarySearch1 = function (values, target) { - var low = 0; - var high = values.length - 2; - if (!high) return 1; - var current = high >>> 1; - while (true) { - if (values[current + 1] <= target) - low = current + 1; - else - high = current; - if (low == high) return low + 1; - current = (low + high) >>> 1; - } -}; -spine.Animation.linearSearch = function (values, target, step) { - for (var i = 0, last = values.length - step; i <= last; i += step) - if (values[i] > target) return i; - return -1; -}; - -spine.Curves = function (frameCount) { - this.curves = []; // type, x, y, ... - //this.curves.length = (frameCount - 1) * 19/*BEZIER_SIZE*/; -}; -spine.Curves.prototype = { - setLinear: function (frameIndex) { - this.curves[frameIndex * 19/*BEZIER_SIZE*/] = 0/*LINEAR*/; - }, - setStepped: function (frameIndex) { - this.curves[frameIndex * 19/*BEZIER_SIZE*/] = 1/*STEPPED*/; - }, - /** Sets the control handle positions for an interpolation bezier curve used to transition from this keyframe to the next. - * cx1 and cx2 are from 0 to 1, representing the percent of time between the two keyframes. cy1 and cy2 are the percent of - * the difference between the keyframe's values. */ - setCurve: function (frameIndex, cx1, cy1, cx2, cy2) { - var subdiv1 = 1 / 10/*BEZIER_SEGMENTS*/, subdiv2 = subdiv1 * subdiv1, subdiv3 = subdiv2 * subdiv1; - var pre1 = 3 * subdiv1, pre2 = 3 * subdiv2, pre4 = 6 * subdiv2, pre5 = 6 * subdiv3; - var tmp1x = -cx1 * 2 + cx2, tmp1y = -cy1 * 2 + cy2, tmp2x = (cx1 - cx2) * 3 + 1, tmp2y = (cy1 - cy2) * 3 + 1; - var dfx = cx1 * pre1 + tmp1x * pre2 + tmp2x * subdiv3, dfy = cy1 * pre1 + tmp1y * pre2 + tmp2y * subdiv3; - var ddfx = tmp1x * pre4 + tmp2x * pre5, ddfy = tmp1y * pre4 + tmp2y * pre5; - var dddfx = tmp2x * pre5, dddfy = tmp2y * pre5; - - var i = frameIndex * 19/*BEZIER_SIZE*/; - var curves = this.curves; - curves[i++] = 2/*BEZIER*/; - - var x = dfx, y = dfy; - for (var n = i + 19/*BEZIER_SIZE*/ - 1; i < n; i += 2) { - curves[i] = x; - curves[i + 1] = y; - dfx += ddfx; - dfy += ddfy; - ddfx += dddfx; - ddfy += dddfy; - x += dfx; - y += dfy; - } - }, - getCurvePercent: function (frameIndex, percent) { - percent = percent < 0 ? 0 : (percent > 1 ? 1 : percent); - var curves = this.curves; - var i = frameIndex * 19/*BEZIER_SIZE*/; - var type = curves[i]; - if (type === 0/*LINEAR*/) return percent; - if (type == 1/*STEPPED*/) return 0; - i++; - var x = 0; - for (var start = i, n = i + 19/*BEZIER_SIZE*/ - 1; i < n; i += 2) { - x = curves[i]; - if (x >= percent) { - var prevX, prevY; - if (i == start) { - prevX = 0; - prevY = 0; - } else { - prevX = curves[i - 2]; - prevY = curves[i - 1]; - } - return prevY + (curves[i + 1] - prevY) * (percent - prevX) / (x - prevX); - } - } - var y = curves[i - 1]; - return y + (1 - y) * (percent - x) / (1 - x); // Last point is 1,1. - } -}; - -spine.RotateTimeline = function (frameCount) { - this.boneIndex = 0; - - this.curves = new spine.Curves(frameCount); - this.frames = []; // time, angle, ... - this.frames.length = frameCount * 2; -}; -spine.RotateTimeline.prototype = { - boneIndex: 0, - getFrameCount: function () { - return this.frames.length / 2; - }, - setFrame: function (frameIndex, time, angle) { - frameIndex *= 2; - this.frames[frameIndex] = time; - this.frames[frameIndex + 1] = angle; - }, - apply: function (skeleton, lastTime, time, firedEvents, alpha) { - var frames = this.frames; - if (time < frames[0]) return; // Time is before first frame. - - var bone = skeleton.bones[this.boneIndex]; - - if (time >= frames[frames.length - 2]) { // Time is after last frame. - var amount = bone.data.rotation + frames[frames.length - 1] - bone.rotation; - while (amount > 180) - amount -= 360; - while (amount < -180) - amount += 360; - bone.rotation += amount * alpha; - return; - } - - // Interpolate between the previous frame and the current frame. - var frameIndex = spine.Animation.binarySearch(frames, time, 2); - var prevFrameValue = frames[frameIndex - 1]; - var frameTime = frames[frameIndex]; - var percent = 1 - (time - frameTime) / (frames[frameIndex - 2/*PREV_FRAME_TIME*/] - frameTime); - percent = this.curves.getCurvePercent(frameIndex / 2 - 1, percent); - - var amount = frames[frameIndex + 1/*FRAME_VALUE*/] - prevFrameValue; - while (amount > 180) - amount -= 360; - while (amount < -180) - amount += 360; - amount = bone.data.rotation + (prevFrameValue + amount * percent) - bone.rotation; - while (amount > 180) - amount -= 360; - while (amount < -180) - amount += 360; - bone.rotation += amount * alpha; - } -}; - -spine.TranslateTimeline = function (frameCount) { - this.boneIndex = 0; - - this.curves = new spine.Curves(frameCount); - this.frames = []; // time, x, y, ... - this.frames.length = frameCount * 3; -}; -spine.TranslateTimeline.prototype = { - boneIndex: 0, - getFrameCount: function () { - return this.frames.length / 3; - }, - setFrame: function (frameIndex, time, x, y) { - frameIndex *= 3; - this.frames[frameIndex] = time; - this.frames[frameIndex + 1] = x; - this.frames[frameIndex + 2] = y; - }, - apply: function (skeleton, lastTime, time, firedEvents, alpha) { - var frames = this.frames; - if (time < frames[0]) return; // Time is before first frame. - - var bone = skeleton.bones[this.boneIndex]; - - if (time >= frames[frames.length - 3]) { // Time is after last frame. - bone.x += (bone.data.x + frames[frames.length - 2] - bone.x) * alpha; - bone.y += (bone.data.y + frames[frames.length - 1] - bone.y) * alpha; - return; - } - - // Interpolate between the previous frame and the current frame. - var frameIndex = spine.Animation.binarySearch(frames, time, 3); - var prevFrameX = frames[frameIndex - 2]; - var prevFrameY = frames[frameIndex - 1]; - var frameTime = frames[frameIndex]; - var percent = 1 - (time - frameTime) / (frames[frameIndex + -3/*PREV_FRAME_TIME*/] - frameTime); - percent = this.curves.getCurvePercent(frameIndex / 3 - 1, percent); - - bone.x += (bone.data.x + prevFrameX + (frames[frameIndex + 1/*FRAME_X*/] - prevFrameX) * percent - bone.x) * alpha; - bone.y += (bone.data.y + prevFrameY + (frames[frameIndex + 2/*FRAME_Y*/] - prevFrameY) * percent - bone.y) * alpha; - } -}; - -spine.ScaleTimeline = function (frameCount) { - this.boneIndex = 0; - - this.curves = new spine.Curves(frameCount); - this.frames = []; // time, x, y, ... - this.frames.length = frameCount * 3; -}; -spine.ScaleTimeline.prototype = { - boneIndex: 0, - getFrameCount: function () { - return this.frames.length / 3; - }, - setFrame: function (frameIndex, time, x, y) { - frameIndex *= 3; - this.frames[frameIndex] = time; - this.frames[frameIndex + 1] = x; - this.frames[frameIndex + 2] = y; - }, - apply: function (skeleton, lastTime, time, firedEvents, alpha) { - var frames = this.frames; - if (time < frames[0]) return; // Time is before first frame. - - var bone = skeleton.bones[this.boneIndex]; - - if (time >= frames[frames.length - 3]) { // Time is after last frame. - bone.scaleX += (bone.data.scaleX * frames[frames.length - 2] - bone.scaleX) * alpha; - bone.scaleY += (bone.data.scaleY * frames[frames.length - 1] - bone.scaleY) * alpha; - return; - } - - // Interpolate between the previous frame and the current frame. - var frameIndex = spine.Animation.binarySearch(frames, time, 3); - var prevFrameX = frames[frameIndex - 2]; - var prevFrameY = frames[frameIndex - 1]; - var frameTime = frames[frameIndex]; - var percent = 1 - (time - frameTime) / (frames[frameIndex + -3/*PREV_FRAME_TIME*/] - frameTime); - percent = this.curves.getCurvePercent(frameIndex / 3 - 1, percent); - - bone.scaleX += (bone.data.scaleX * (prevFrameX + (frames[frameIndex + 1/*FRAME_X*/] - prevFrameX) * percent) - bone.scaleX) * alpha; - bone.scaleY += (bone.data.scaleY * (prevFrameY + (frames[frameIndex + 2/*FRAME_Y*/] - prevFrameY) * percent) - bone.scaleY) * alpha; - } -}; - -spine.ColorTimeline = function (frameCount) { - this.boneIndex = 0; - - this.curves = new spine.Curves(frameCount); - this.frames = []; // time, r, g, b, a, ... - this.frames.length = frameCount * 5; -}; -spine.ColorTimeline.prototype = { - slotIndex: 0, - getFrameCount: function () { - return this.frames.length / 5; - }, - setFrame: function (frameIndex, time, r, g, b, a) { - frameIndex *= 5; - this.frames[frameIndex] = time; - this.frames[frameIndex + 1] = r; - this.frames[frameIndex + 2] = g; - this.frames[frameIndex + 3] = b; - this.frames[frameIndex + 4] = a; - }, - apply: function (skeleton, lastTime, time, firedEvents, alpha) { - var frames = this.frames; - if (time < frames[0]) return; // Time is before first frame. - - var r, g, b, a; - if (time >= frames[frames.length - 5]) { - // Time is after last frame. - var i = frames.length - 1; - r = frames[i - 3]; - g = frames[i - 2]; - b = frames[i - 1]; - a = frames[i]; - } else { - // Interpolate between the previous frame and the current frame. - var frameIndex = spine.Animation.binarySearch(frames, time, 5); - var prevFrameR = frames[frameIndex - 4]; - var prevFrameG = frames[frameIndex - 3]; - var prevFrameB = frames[frameIndex - 2]; - var prevFrameA = frames[frameIndex - 1]; - var frameTime = frames[frameIndex]; - var percent = 1 - (time - frameTime) / (frames[frameIndex - 5/*PREV_FRAME_TIME*/] - frameTime); - percent = this.curves.getCurvePercent(frameIndex / 5 - 1, percent); - - r = prevFrameR + (frames[frameIndex + 1/*FRAME_R*/] - prevFrameR) * percent; - g = prevFrameG + (frames[frameIndex + 2/*FRAME_G*/] - prevFrameG) * percent; - b = prevFrameB + (frames[frameIndex + 3/*FRAME_B*/] - prevFrameB) * percent; - a = prevFrameA + (frames[frameIndex + 4/*FRAME_A*/] - prevFrameA) * percent; - } - var slot = skeleton.slots[this.slotIndex]; - if (alpha < 1) { - slot.r += (r - slot.r) * alpha; - slot.g += (g - slot.g) * alpha; - slot.b += (b - slot.b) * alpha; - slot.a += (a - slot.a) * alpha; - } else { - slot.r = r; - slot.g = g; - slot.b = b; - slot.a = a; - } - } -}; - -spine.AttachmentTimeline = function (frameCount) { - this.slotIndex = 0; - - this.curves = new spine.Curves(frameCount); - this.frames = []; // time, ... - this.frames.length = frameCount; - this.attachmentNames = []; - this.attachmentNames.length = frameCount; -}; -spine.AttachmentTimeline.prototype = { - slotIndex: 0, - getFrameCount: function () { - return this.frames.length; - }, - setFrame: function (frameIndex, time, attachmentName) { - this.frames[frameIndex] = time; - this.attachmentNames[frameIndex] = attachmentName; - }, - apply: function (skeleton, lastTime, time, firedEvents, alpha) { - var frames = this.frames; - if (time < frames[0]) { - if (lastTime > time) this.apply(skeleton, lastTime, Number.MAX_VALUE, null, 0); - return; - } else if (lastTime > time) // - lastTime = -1; - - var frameIndex = time >= frames[frames.length - 1] ? frames.length - 1 : spine.Animation.binarySearch1(frames, time) - 1; - if (frames[frameIndex] < lastTime) return; - - var attachmentName = this.attachmentNames[frameIndex]; - skeleton.slots[this.slotIndex].setAttachment( - !attachmentName ? null : skeleton.getAttachmentBySlotIndex(this.slotIndex, attachmentName)); - } -}; - -spine.EventTimeline = function (frameCount) { - this.frames = []; // time, ... - this.frames.length = frameCount; - this.events = []; - this.events.length = frameCount; -}; -spine.EventTimeline.prototype = { - getFrameCount: function () { - return this.frames.length; - }, - setFrame: function (frameIndex, time, event) { - this.frames[frameIndex] = time; - this.events[frameIndex] = event; - }, - /** Fires events for frames > lastTime and <= time. */ - apply: function (skeleton, lastTime, time, firedEvents, alpha) { - if (!firedEvents) return; - - var frames = this.frames; - var frameCount = frames.length; - - if (lastTime > time) { // Fire events after last time for looped animations. - this.apply(skeleton, lastTime, Number.MAX_VALUE, firedEvents, alpha); - lastTime = -1; - } else if (lastTime >= frames[frameCount - 1]) // Last time is after last frame. - return; - if (time < frames[0]) return; // Time is before first frame. - - var frameIndex; - if (lastTime < frames[0]) - frameIndex = 0; - else { - frameIndex = spine.Animation.binarySearch1(frames, lastTime); - var frame = frames[frameIndex]; - while (frameIndex > 0) { // Fire multiple events with the same frame. - if (frames[frameIndex - 1] != frame) break; - frameIndex--; - } - } - var events = this.events; - for (; frameIndex < frameCount && time >= frames[frameIndex]; frameIndex++) - firedEvents.push(events[frameIndex]); - } -}; - -spine.DrawOrderTimeline = function (frameCount) { - this.frames = []; // time, ... - this.frames.length = frameCount; - this.drawOrders = []; - this.drawOrders.length = frameCount; -}; -spine.DrawOrderTimeline.prototype = { - getFrameCount: function () { - return this.frames.length; - }, - setFrame: function (frameIndex, time, drawOrder) { - this.frames[frameIndex] = time; - this.drawOrders[frameIndex] = drawOrder; - }, - apply: function (skeleton, lastTime, time, firedEvents, alpha) { - var frames = this.frames; - if (time < frames[0]) return; // Time is before first frame. - - var frameIndex; - if (time >= frames[frames.length - 1]) // Time is after last frame. - frameIndex = frames.length - 1; - else - frameIndex = spine.Animation.binarySearch1(frames, time) - 1; - - var drawOrder = skeleton.drawOrder; - var slots = skeleton.slots; - var drawOrderToSetupIndex = this.drawOrders[frameIndex]; - if (!drawOrderToSetupIndex) { - for (var i = 0, n = slots.length; i < n; i++) - drawOrder[i] = slots[i]; - } else { - for (var i = 0, n = drawOrderToSetupIndex.length; i < n; i++) - drawOrder[i] = skeleton.slots[drawOrderToSetupIndex[i]]; - } - - } -}; - -spine.FfdTimeline = function (frameCount) { - this.slotIndex = this.attachment = 0; - - this.curves = new spine.Curves(frameCount); - this.frames = []; - this.frames.length = frameCount; - this.frameVertices = []; - this.frameVertices.length = frameCount; -}; -spine.FfdTimeline.prototype = { - slotIndex: 0, - attachment: 0, - getFrameCount: function () { - return this.frames.length; - }, - setFrame: function (frameIndex, time, vertices) { - this.frames[frameIndex] = time; - this.frameVertices[frameIndex] = vertices; - }, - apply: function (skeleton, lastTime, time, firedEvents, alpha) { - var slot = skeleton.slots[this.slotIndex]; - if (slot.attachment != this.attachment) return; - - var frames = this.frames; - if (time < frames[0]) return; // Time is before first frame. - - var frameVertices = this.frameVertices; - var vertexCount = frameVertices[0].length; - - var vertices = slot.attachmentVertices; - if (vertices.length != vertexCount) alpha = 1; - vertices.length = vertexCount; - - if (time >= frames[frames.length - 1]) { // Time is after last frame. - var lastVertices = frameVertices[frames.length - 1]; - if (alpha < 1) { - for (var i = 0; i < vertexCount; i++) - vertices[i] += (lastVertices[i] - vertices[i]) * alpha; - } else { - for (var i = 0; i < vertexCount; i++) - vertices[i] = lastVertices[i]; - } - return; - } - - // Interpolate between the previous frame and the current frame. - var frameIndex = spine.Animation.binarySearch1(frames, time); - var frameTime = frames[frameIndex]; - var percent = 1 - (time - frameTime) / (frames[frameIndex - 1] - frameTime); - percent = this.curves.getCurvePercent(frameIndex - 1, percent < 0 ? 0 : (percent > 1 ? 1 : percent)); - - var prevVertices = frameVertices[frameIndex - 1]; - var nextVertices = frameVertices[frameIndex]; - - if (alpha < 1) { - for (var i = 0; i < vertexCount; i++) { - var prev = prevVertices[i]; - vertices[i] += (prev + (nextVertices[i] - prev) * percent - vertices[i]) * alpha; - } - } else { - for (var i = 0; i < vertexCount; i++) { - var prev = prevVertices[i]; - vertices[i] = prev + (nextVertices[i] - prev) * percent; - } - } - } -}; - -spine.IkConstraintTimeline = function (frameCount) { - this.ikConstraintIndex = 0; - - this.curves = new spine.Curves(frameCount); - this.frames = []; // time, mix, bendDirection, ... - this.frames.length = frameCount * 3; -}; -spine.IkConstraintTimeline.prototype = { - ikConstraintIndex: 0, - getFrameCount: function () { - return this.frames.length / 3; - }, - setFrame: function (frameIndex, time, mix, bendDirection) { - frameIndex *= 3; - this.frames[frameIndex] = time; - this.frames[frameIndex + 1] = mix; - this.frames[frameIndex + 2] = bendDirection; - }, - apply: function (skeleton, lastTime, time, firedEvents, alpha) { - var frames = this.frames; - if (time < frames[0]) return; // Time is before first frame. - - var ikConstraint = skeleton.ikConstraints[this.ikConstraintIndex]; - - if (time >= frames[frames.length - 3]) { // Time is after last frame. - ikConstraint.mix += (frames[frames.length - 2] - ikConstraint.mix) * alpha; - ikConstraint.bendDirection = frames[frames.length - 1]; - return; - } - - // Interpolate between the previous frame and the current frame. - var frameIndex = spine.Animation.binarySearch(frames, time, 3); - var prevFrameMix = frames[frameIndex + -2/*PREV_FRAME_MIX*/]; - var frameTime = frames[frameIndex]; - var percent = 1 - (time - frameTime) / (frames[frameIndex + -3/*PREV_FRAME_TIME*/] - frameTime); - percent = this.curves.getCurvePercent(frameIndex / 3 - 1, percent); - - var mix = prevFrameMix + (frames[frameIndex + 1/*FRAME_MIX*/] - prevFrameMix) * percent; - ikConstraint.mix += (mix - ikConstraint.mix) * alpha; - ikConstraint.bendDirection = frames[frameIndex + -1/*PREV_FRAME_BEND_DIRECTION*/]; - } -}; - -spine.FlipXTimeline = function (frameCount) { - this.boneIndex = 0; - - this.curves = new spine.Curves(frameCount); - this.frames = []; // time, flip, ... - this.frames.length = frameCount * 2; -}; -spine.FlipXTimeline.prototype = { - boneIndex: 0, - getFrameCount: function () { - return this.frames.length / 2; - }, - setFrame: function (frameIndex, time, flip) { - frameIndex *= 2; - this.frames[frameIndex] = time; - this.frames[frameIndex + 1] = flip ? 1 : 0; - }, - apply: function (skeleton, lastTime, time, firedEvents, alpha) { - var frames = this.frames; - if (time < frames[0]) { - if (lastTime > time) this.apply(skeleton, lastTime, Number.MAX_VALUE, null, 0); - return; - } else if (lastTime > time) // - lastTime = -1; - var frameIndex = (time >= frames[frames.length - 2] ? frames.length : spine.Animation.binarySearch(frames, time, 2)) - 2; - if (frames[frameIndex] < lastTime) return; - skeleton.bones[this.boneIndex].flipX = frames[frameIndex + 1] != 0; - } -}; - -spine.FlipYTimeline = function (frameCount) { - this.boneIndex = 0; - - this.curves = new spine.Curves(frameCount); - this.frames = []; // time, flip, ... - this.frames.length = frameCount * 2; -}; -spine.FlipYTimeline.prototype = { - boneIndex: 0, - getFrameCount: function () { - return this.frames.length / 2; - }, - setFrame: function (frameIndex, time, flip) { - frameIndex *= 2; - this.frames[frameIndex] = time; - this.frames[frameIndex + 1] = flip ? 1 : 0; - }, - apply: function (skeleton, lastTime, time, firedEvents, alpha) { - var frames = this.frames; - if (time < frames[0]) { - if (lastTime > time) this.apply(skeleton, lastTime, Number.MAX_VALUE, null, 0); - return; - } else if (lastTime > time) // - lastTime = -1; - var frameIndex = (time >= frames[frames.length - 2] ? frames.length : spine.Animation.binarySearch(frames, time, 2)) - 2; - if (frames[frameIndex] < lastTime) return; - skeleton.bones[this.boneIndex].flipY = frames[frameIndex + 1] != 0; - } -}; - -spine.SkeletonData = function () { - this.width = this.height = 0; - - this.bones = []; - this.slots = []; - this.skins = []; - this.events = []; - this.animations = []; - this.ikConstraints = []; -}; -spine.SkeletonData.prototype = { - name: null, - defaultSkin: null, - width: 0, height: 0, - version: null, hash: null, - /** @return May be null. */ - findBone: function (boneName) { - var bones = this.bones; - for (var i = 0, n = bones.length; i < n; i++) - if (bones[i].name == boneName) return bones[i]; - return null; - }, - /** @return -1 if the bone was not found. */ - findBoneIndex: function (boneName) { - var bones = this.bones; - for (var i = 0, n = bones.length; i < n; i++) - if (bones[i].name == boneName) return i; - return -1; - }, - /** @return May be null. */ - findSlot: function (slotName) { - var slots = this.slots; - for (var i = 0, n = slots.length; i < n; i++) { - if (slots[i].name == slotName) return slot[i]; - } - return null; - }, - /** @return -1 if the bone was not found. */ - findSlotIndex: function (slotName) { - var slots = this.slots; - for (var i = 0, n = slots.length; i < n; i++) - if (slots[i].name == slotName) return i; - return -1; - }, - /** @return May be null. */ - findSkin: function (skinName) { - var skins = this.skins; - for (var i = 0, n = skins.length; i < n; i++) - if (skins[i].name == skinName) return skins[i]; - return null; - }, - /** @return May be null. */ - findEvent: function (eventName) { - var events = this.events; - for (var i = 0, n = events.length; i < n; i++) - if (events[i].name == eventName) return events[i]; - return null; - }, - /** @return May be null. */ - findAnimation: function (animationName) { - var animations = this.animations; - for (var i = 0, n = animations.length; i < n; i++) - if (animations[i].name == animationName) return animations[i]; - return null; - }, - /** @return May be null. */ - findIkConstraint: function (ikConstraintName) { - var ikConstraints = this.ikConstraints; - for (var i = 0, n = ikConstraints.length; i < n; i++) - if (ikConstraints[i].name == ikConstraintName) return ikConstraints[i]; - return null; - } -}; - -spine.Skeleton = function (skeletonData) { - this.x = this.y = 0; - this.r = this.g = this.b = this.a = 1; - this.time = 0; - this.flipX = this.flipY = false; - - this.data = skeletonData; - - this.bones = []; - for (var i = 0, n = skeletonData.bones.length; i < n; i++) { - var boneData = skeletonData.bones[i]; - var parent = !boneData.parent ? null : this.bones[skeletonData.bones.indexOf(boneData.parent)]; - this.bones.push(new spine.Bone(boneData, this, parent)); - } - - this.slots = []; - this.drawOrder = []; - for (var i = 0, n = skeletonData.slots.length; i < n; i++) { - var slotData = skeletonData.slots[i]; - var bone = this.bones[skeletonData.bones.indexOf(slotData.boneData)]; - var slot = new spine.Slot(slotData, bone); - this.slots.push(slot); - this.drawOrder.push(slot); - } - - this.ikConstraints = []; - for (var i = 0, n = skeletonData.ikConstraints.length; i < n; i++) - this.ikConstraints.push(new spine.IkConstraint(skeletonData.ikConstraints[i], this)); - - this.boneCache = []; - this.updateCache(); -}; -spine.Skeleton.prototype = { - x: 0, y: 0, - skin: null, - r: 1, g: 1, b: 1, a: 1, - time: 0, - flipX: false, flipY: false, - /** Caches information about bones and IK constraints. Must be called if bones or IK constraints are added or removed. */ - updateCache: function () { - var ikConstraints = this.ikConstraints; - var ikConstraintsCount = ikConstraints.length; - - var arrayCount = ikConstraintsCount + 1; - var boneCache = this.boneCache; - if (boneCache.length > arrayCount) boneCache.length = arrayCount; - for (var i = 0, n = boneCache.length; i < n; i++) - boneCache[i].length = 0; - while (boneCache.length < arrayCount) - boneCache[boneCache.length] = []; - - var nonIkBones = boneCache[0]; - var bones = this.bones; - - outer: - for (var i = 0, n = bones.length; i < n; i++) { - var bone = bones[i]; - var current = bone; - do { - for (var ii = 0; ii < ikConstraintsCount; ii++) { - var ikConstraint = ikConstraints[ii]; - var parent = ikConstraint.bones[0]; - var child= ikConstraint.bones[ikConstraint.bones.length - 1]; - while (true) { - if (current == child) { - boneCache[ii].push(bone); - boneCache[ii + 1].push(bone); - continue outer; - } - if (child == parent) break; - child = child.parent; - } - } - current = current.parent; - } while (current); - nonIkBones[nonIkBones.length] = bone; - } - }, - /** Updates the world transform for each bone. */ - updateWorldTransform: function () { - var bones = this.bones; - for (var i = 0, n = bones.length; i < n; i++) { - var bone = bones[i]; - bone.rotationIK = bone.rotation; - } - var i = 0, last = this.boneCache.length - 1; - while (true) { - var cacheBones = this.boneCache[i]; - for (var ii = 0, nn = cacheBones.length; ii < nn; ii++) - cacheBones[ii].updateWorldTransform(); - if (i == last) break; - this.ikConstraints[i].apply(); - i++; - } - }, - /** Sets the bones and slots to their setup pose values. */ - setToSetupPose: function () { - this.setBonesToSetupPose(); - this.setSlotsToSetupPose(); - }, - setBonesToSetupPose: function () { - var bones = this.bones; - for (var i = 0, n = bones.length; i < n; i++) - bones[i].setToSetupPose(); - - var ikConstraints = this.ikConstraints; - for (var i = 0, n = ikConstraints.length; i < n; i++) { - var ikConstraint = ikConstraints[i]; - ikConstraint.bendDirection = ikConstraint.data.bendDirection; - ikConstraint.mix = ikConstraint.data.mix; - } - }, - setSlotsToSetupPose: function () { - var slots = this.slots; - var drawOrder = this.drawOrder; - for (var i = 0, n = slots.length; i < n; i++) { - drawOrder[i] = slots[i]; - slots[i].setToSetupPose(i); - } - }, - /** @return May return null. */ - getRootBone: function () { - return this.bones.length ? this.bones[0] : null; - }, - /** @return May be null. */ - findBone: function (boneName) { - var bones = this.bones; - for (var i = 0, n = bones.length; i < n; i++) - if (bones[i].data.name == boneName) return bones[i]; - return null; - }, - /** @return -1 if the bone was not found. */ - findBoneIndex: function (boneName) { - var bones = this.bones; - for (var i = 0, n = bones.length; i < n; i++) - if (bones[i].data.name == boneName) return i; - return -1; - }, - /** @return May be null. */ - findSlot: function (slotName) { - var slots = this.slots; - for (var i = 0, n = slots.length; i < n; i++) - if (slots[i].data.name == slotName) return slots[i]; - return null; - }, - /** @return -1 if the bone was not found. */ - findSlotIndex: function (slotName) { - var slots = this.slots; - for (var i = 0, n = slots.length; i < n; i++) - if (slots[i].data.name == slotName) return i; - return -1; - }, - setSkinByName: function (skinName) { - var skin = this.data.findSkin(skinName); - if (!skin) throw new Error("Skin not found: " + skinName); - this.setSkin(skin); - }, - /** Sets the skin used to look up attachments before looking in the {@link SkeletonData#getDefaultSkin() default skin}. - * Attachments from the new skin are attached if the corresponding attachment from the old skin was attached. If there was - * no old skin, each slot's setup mode attachment is attached from the new skin. - * @param newSkin May be null. */ - setSkin: function (newSkin) { - if (newSkin) { - if (this.skin) - newSkin._attachAll(this, this.skin); - else { - var slots = this.slots; - for (var i = 0, n = slots.length; i < n; i++) { - var slot = slots[i]; - var name = slot.data.attachmentName; - if (name) { - var attachment = newSkin.getAttachment(i, name); - if (attachment) slot.setAttachment(attachment); - } - } - } - } - this.skin = newSkin; - }, - /** @return May be null. */ - getAttachmentBySlotName: function (slotName, attachmentName) { - return this.getAttachmentBySlotIndex(this.data.findSlotIndex(slotName), attachmentName); - }, - /** @return May be null. */ - getAttachmentBySlotIndex: function (slotIndex, attachmentName) { - if (this.skin) { - var attachment = this.skin.getAttachment(slotIndex, attachmentName); - if (attachment) return attachment; - } - if (this.data.defaultSkin) return this.data.defaultSkin.getAttachment(slotIndex, attachmentName); - return null; - }, - /** @param attachmentName May be null. */ - setAttachment: function (slotName, attachmentName) { - var slots = this.slots; - for (var i = 0, n = slots.length; i < n; i++) { - var slot = slots[i]; - if (slot.data.name == slotName) { - var attachment = null; - if (attachmentName) { - attachment = this.getAttachmentBySlotIndex(i, attachmentName); - if (!attachment) throw new Error("Attachment not found: " + attachmentName + ", for slot: " + slotName); - } - slot.setAttachment(attachment); - return; - } - } - throw new Error("Slot not found: " + slotName); - }, - /** @return May be null. */ - findIkConstraint: function (ikConstraintName) { - var ikConstraints = this.ikConstraints; - for (var i = 0, n = ikConstraints.length; i < n; i++) - if (ikConstraints[i].data.name == ikConstraintName) return ikConstraints[i]; - return null; - }, - update: function (delta) { - this.time += delta; - } -}; - -spine.EventData = function (name) { - this.intValue = this.floatValue = 0; - - this.name = name; -}; -spine.EventData.prototype = { - intValue: 0, - floatValue: 0, - stringValue: null -}; - -spine.Event = function (data) { - this.intValue = this.floatValue = 0; - - this.data = data; -}; -spine.Event.prototype = { - intValue: 0, - floatValue: 0, - stringValue: null -}; - -spine.AttachmentType = { - region: 0, - boundingbox: 1, - mesh: 2, - skinnedmesh: 3 -}; - -spine.RegionAttachment = function (name) { - this.type = spine.AttachmentType.region; - this.x = this.y = this.rotation = 0; - this.scaleX = this.scaleY = 1; - this.width = this.height = 0; - this.r = this.g = this.b = this.a = 1; - this.regionOffsetX = this.regionOffsetY = this.regionWidth = this.regionHeight = this.regionOriginalWidth = this.regionOriginalHeight = 0; - - this.name = name; - this.offset = []; - this.offset.length = 8; - this.uvs = []; - this.uvs.length = 8; -}; -spine.RegionAttachment.prototype = { - x: 0, y: 0, - rotation: 0, - scaleX: 1, scaleY: 1, - width: 0, height: 0, - r: 1, g: 1, b: 1, a: 1, - path: null, - rendererObject: null, - regionOffsetX: 0, regionOffsetY: 0, - regionWidth: 0, regionHeight: 0, - regionOriginalWidth: 0, regionOriginalHeight: 0, - setUVs: function (u, v, u2, v2, rotate) { - var uvs = this.uvs; - if (rotate) { - uvs[2/*X2*/] = u; - uvs[3/*Y2*/] = v2; - uvs[4/*X3*/] = u; - uvs[5/*Y3*/] = v; - uvs[6/*X4*/] = u2; - uvs[7/*Y4*/] = v; - uvs[0/*X1*/] = u2; - uvs[1/*Y1*/] = v2; - } else { - uvs[0/*X1*/] = u; - uvs[1/*Y1*/] = v2; - uvs[2/*X2*/] = u; - uvs[3/*Y2*/] = v; - uvs[4/*X3*/] = u2; - uvs[5/*Y3*/] = v; - uvs[6/*X4*/] = u2; - uvs[7/*Y4*/] = v2; - } - }, - updateOffset: function () { - var regionScaleX = this.width / this.regionOriginalWidth * this.scaleX; - var regionScaleY = this.height / this.regionOriginalHeight * this.scaleY; - var localX = -this.width / 2 * this.scaleX + this.regionOffsetX * regionScaleX; - var localY = -this.height / 2 * this.scaleY + this.regionOffsetY * regionScaleY; - var localX2 = localX + this.regionWidth * regionScaleX; - var localY2 = localY + this.regionHeight * regionScaleY; - var radians = this.rotation * spine.degRad; - var cos = Math.cos(radians); - var sin = Math.sin(radians); - var localXCos = localX * cos + this.x; - var localXSin = localX * sin; - var localYCos = localY * cos + this.y; - var localYSin = localY * sin; - var localX2Cos = localX2 * cos + this.x; - var localX2Sin = localX2 * sin; - var localY2Cos = localY2 * cos + this.y; - var localY2Sin = localY2 * sin; - var offset = this.offset; - offset[0/*X1*/] = localXCos - localYSin; - offset[1/*Y1*/] = localYCos + localXSin; - offset[2/*X2*/] = localXCos - localY2Sin; - offset[3/*Y2*/] = localY2Cos + localXSin; - offset[4/*X3*/] = localX2Cos - localY2Sin; - offset[5/*Y3*/] = localY2Cos + localX2Sin; - offset[6/*X4*/] = localX2Cos - localYSin; - offset[7/*Y4*/] = localYCos + localX2Sin; - }, - computeVertices: function (x, y, bone, vertices) { - x += bone.worldX; - y += bone.worldY; - var m00 = bone.m00, m01 = bone.m01, m10 = bone.m10, m11 = bone.m11; - var offset = this.offset; - vertices[0/*X1*/] = offset[0/*X1*/] * m00 + offset[1/*Y1*/] * m01 + x; - vertices[1/*Y1*/] = offset[0/*X1*/] * m10 + offset[1/*Y1*/] * m11 + y; - vertices[2/*X2*/] = offset[2/*X2*/] * m00 + offset[3/*Y2*/] * m01 + x; - vertices[3/*Y2*/] = offset[2/*X2*/] * m10 + offset[3/*Y2*/] * m11 + y; - vertices[4/*X3*/] = offset[4/*X3*/] * m00 + offset[5/*X3*/] * m01 + x; - vertices[5/*X3*/] = offset[4/*X3*/] * m10 + offset[5/*X3*/] * m11 + y; - vertices[6/*X4*/] = offset[6/*X4*/] * m00 + offset[7/*Y4*/] * m01 + x; - vertices[7/*Y4*/] = offset[6/*X4*/] * m10 + offset[7/*Y4*/] * m11 + y; - } -}; - -spine.MeshAttachment = function (name) { - this.type = spine.AttachmentType.mesh; - this.hullLength = 0; - this.r = this.g = this.b = this.a = 1; - this.regionU = this.regionV = this.regionV2 = 0; - this.regionRotate = false; - this.regionOffsetX = this.regionOffsetY = this.regionWidth = this.regionHeight = this.regionOriginalWidth = this.regionOriginalHeight = 0; - this.width = this.height = 0; - - this.name = name; -}; -spine.MeshAttachment.prototype = { - vertices: null, - uvs: null, - regionUVs: null, - triangles: null, - hullLength: 0, - r: 1, g: 1, b: 1, a: 1, - path: null, - rendererObject: null, - regionU: 0, regionV: 0, regionU2: 0, regionV2: 0, regionRotate: false, - regionOffsetX: 0, regionOffsetY: 0, - regionWidth: 0, regionHeight: 0, - regionOriginalWidth: 0, regionOriginalHeight: 0, - edges: null, - width: 0, height: 0, - updateUVs: function () { - var width = this.regionU2 - this.regionU, height = this.regionV2 - this.regionV; - var n = this.regionUVs.length; - if (!this.uvs || this.uvs.length != n) { - this.uvs = new spine.Float32Array(n); - } - if (this.regionRotate) { - for (var i = 0; i < n; i += 2) { - this.uvs[i] = this.regionU + this.regionUVs[i + 1] * width; - this.uvs[i + 1] = this.regionV + height - this.regionUVs[i] * height; - } - } else { - for (var i = 0; i < n; i += 2) { - this.uvs[i] = this.regionU + this.regionUVs[i] * width; - this.uvs[i + 1] = this.regionV + this.regionUVs[i + 1] * height; - } - } - }, - computeWorldVertices: function (x, y, slot, worldVertices) { - var bone = slot.bone; - x += bone.worldX; - y += bone.worldY; - var m00 = bone.m00, m01 = bone.m01, m10 = bone.m10, m11 = bone.m11; - var vertices = this.vertices; - var verticesCount = vertices.length; - if (slot.attachmentVertices.length == verticesCount) vertices = slot.attachmentVertices; - for (var i = 0; i < verticesCount; i += 2) { - var vx = vertices[i]; - var vy = vertices[i + 1]; - worldVertices[i] = vx * m00 + vy * m01 + x; - worldVertices[i + 1] = vx * m10 + vy * m11 + y; - } - } -}; - -spine.SkinnedMeshAttachment = function (name) { - this.type = spine.AttachmentType.skinnedmesh; - this.hullLength = 0; - this.r = this.g = this.b = this.a = 1; - this.regionU = this.regionV = this.regionU2 = this.regionV2 = 0; - this.regionRotate = false; - this.regionOffsetX = this.regionOffsetY = this.regionWidth = this.regionHeight = this.regionOriginalWidth = this.regionOriginalHeight = 0; - this.width = this.height = 0; - - this.name = name; -}; -spine.SkinnedMeshAttachment.prototype = { - bones: null, - weights: null, - uvs: null, - regionUVs: null, - triangles: null, - hullLength: 0, - r: 1, g: 1, b: 1, a: 1, - path: null, - rendererObject: null, - regionU: 0, regionV: 0, regionU2: 0, regionV2: 0, regionRotate: false, - regionOffsetX: 0, regionOffsetY: 0, - regionWidth: 0, regionHeight: 0, - regionOriginalWidth: 0, regionOriginalHeight: 0, - edges: null, - width: 0, height: 0, - updateUVs: function (u, v, u2, v2, rotate) { - var width = this.regionU2 - this.regionU, height = this.regionV2 - this.regionV; - var n = this.regionUVs.length; - if (!this.uvs || this.uvs.length != n) { - this.uvs = new spine.Float32Array(n); - } - if (this.regionRotate) { - for (var i = 0; i < n; i += 2) { - this.uvs[i] = this.regionU + this.regionUVs[i + 1] * width; - this.uvs[i + 1] = this.regionV + height - this.regionUVs[i] * height; - } - } else { - for (var i = 0; i < n; i += 2) { - this.uvs[i] = this.regionU + this.regionUVs[i] * width; - this.uvs[i + 1] = this.regionV + this.regionUVs[i + 1] * height; - } - } - }, - computeWorldVertices: function (x, y, slot, worldVertices) { - var skeletonBones = slot.bone.skeleton.bones; - var weights = this.weights; - var bones = this.bones; - - var w = 0, v = 0, b = 0, f = 0, n = bones.length, nn; - var wx, wy, bone, vx, vy, weight; - if (!slot.attachmentVertices.length) { - for (; v < n; w += 2) { - wx = 0; - wy = 0; - nn = bones[v++] + v; - for (; v < nn; v++, b += 3) { - bone = skeletonBones[bones[v]]; - vx = weights[b]; - vy = weights[b + 1]; - weight = weights[b + 2]; - wx += (vx * bone.m00 + vy * bone.m01 + bone.worldX) * weight; - wy += (vx * bone.m10 + vy * bone.m11 + bone.worldY) * weight; - } - worldVertices[w] = wx + x; - worldVertices[w + 1] = wy + y; - } - } else { - var ffd = slot.attachmentVertices; - for (; v < n; w += 2) { - wx = 0; - wy = 0; - nn = bones[v++] + v; - for (; v < nn; v++, b += 3, f += 2) { - bone = skeletonBones[bones[v]]; - vx = weights[b] + ffd[f]; - vy = weights[b + 1] + ffd[f + 1]; - weight = weights[b + 2]; - wx += (vx * bone.m00 + vy * bone.m01 + bone.worldX) * weight; - wy += (vx * bone.m10 + vy * bone.m11 + bone.worldY) * weight; - } - worldVertices[w] = wx + x; - worldVertices[w + 1] = wy + y; - } - } - } -}; - -spine.BoundingBoxAttachment = function (name) { - this.type = spine.AttachmentType.boundingbox; - - this.name = name; - this.vertices = []; -}; -spine.BoundingBoxAttachment.prototype = { - computeWorldVertices: function (x, y, bone, worldVertices) { - x += bone.worldX; - y += bone.worldY; - var m00 = bone.m00, m01 = bone.m01, m10 = bone.m10, m11 = bone.m11; - var vertices = this.vertices; - for (var i = 0, n = vertices.length; i < n; i += 2) { - var px = vertices[i]; - var py = vertices[i + 1]; - worldVertices[i] = px * m00 + py * m01 + x; - worldVertices[i + 1] = px * m10 + py * m11 + y; - } - } -}; - -spine.AnimationStateData = function (skeletonData) { - this.skeletonData = skeletonData; - this.animationToMixTime = {}; - - this.defaultMix = 0; -}; -spine.AnimationStateData.prototype = { - defaultMix: 0, - setMixByName: function (fromName, toName, duration) { - var from = this.skeletonData.findAnimation(fromName); - if (!from) throw new Error("Animation not found: " + fromName); - var to = this.skeletonData.findAnimation(toName); - if (!to) throw new Error("Animation not found: " + toName); - this.setMix(from, to, duration); - }, - setMix: function (from, to, duration) { - this.animationToMixTime[from.name + ":" + to.name] = duration; - }, - getMix: function (from, to) { - var key = from.name + ":" + to.name; - return this.animationToMixTime.hasOwnProperty(key) ? this.animationToMixTime[key] : this.defaultMix; - } -}; - -spine.TrackEntry = function () { - this.delay = this.time = this.endTime = 0; - this.lastTime = -1; - this.timeScale = 1; - this.mixTime = this.mixDuration = 1; - this.mix = 1; -}; -spine.TrackEntry.prototype = { - next: null, previous: null, - animation: null, - loop: false, - delay: 0, time: 0, lastTime: -1, endTime: 0, - timeScale: 1, - mixTime: 0, mixDuration: 0, mix: 1, - onStart: null, onEnd: null, onComplete: null, onEvent: null -}; - -spine.AnimationState = function (stateData) { - this.timeScale = 1; - - this.data = stateData; - this.tracks = []; - this.events = []; -}; -spine.AnimationState.prototype = { - onStart: null, - onEnd: null, - onComplete: null, - onEvent: null, - timeScale: 1, - update: function (delta) { - delta *= this.timeScale; - for (var i = 0; i < this.tracks.length; i++) { - var current = this.tracks[i]; - if (!current) continue; - - current.time += delta * current.timeScale; - if (current.previous) { - var previousDelta = delta * current.previous.timeScale; - current.previous.time += previousDelta; - current.mixTime += previousDelta; - } - - var next = current.next; - if (next) { - next.time = current.lastTime - next.delay; - if (next.time >= 0) this.setCurrent(i, next); - } else { - // End non-looping animation when it reaches its end time and there is no next entry. - if (!current.loop && current.lastTime >= current.endTime) this.clearTrack(i); - } - } - }, - apply: function (skeleton) { - for (var i = 0; i < this.tracks.length; i++) { - var current = this.tracks[i]; - if (!current) continue; - - this.events.length = 0; - - var time = current.time; - var lastTime = current.lastTime; - var endTime = current.endTime; - var loop = current.loop; - if (!loop && time > endTime) time = endTime; - - var previous = current.previous; - if (!previous) { - if (current.mix == 1) - current.animation.apply(skeleton, current.lastTime, time, loop, this.events); - else - current.animation.mix(skeleton, current.lastTime, time, loop, this.events, current.mix); - } else { - var previousTime = previous.time; - if (!previous.loop && previousTime > previous.endTime) previousTime = previous.endTime; - previous.animation.apply(skeleton, previousTime, previousTime, previous.loop, null); - - var alpha = current.mixTime / current.mixDuration * current.mix; - if (alpha >= 1) { - alpha = 1; - current.previous = null; - } - current.animation.mix(skeleton, current.lastTime, time, loop, this.events, alpha); - } - - for (var ii = 0, nn = this.events.length; ii < nn; ii++) { - var event = this.events[ii]; - if (current.onEvent) current.onEvent(i, event); - if (this.onEvent) this.onEvent(i, event); - } - - // Check if completed the animation or a loop iteration. - if (loop ? (lastTime % endTime > time % endTime) : (lastTime < endTime && time >= endTime)) { - var count = Math.floor(time / endTime); - if (current.onComplete) current.onComplete(i, count); - if (this.onComplete) this.onComplete(i, count); - } - - current.lastTime = current.time; - } - }, - clearTracks: function () { - for (var i = 0, n = this.tracks.length; i < n; i++) - this.clearTrack(i); - this.tracks.length = 0; - }, - clearTrack: function (trackIndex) { - if (trackIndex >= this.tracks.length) return; - var current = this.tracks[trackIndex]; - if (!current) return; - - if (current.onEnd) current.onEnd(trackIndex); - if (this.onEnd) this.onEnd(trackIndex); - - this.tracks[trackIndex] = null; - }, - _expandToIndex: function (index) { - if (index < this.tracks.length) return this.tracks[index]; - while (index >= this.tracks.length) - this.tracks.push(null); - return null; - }, - setCurrent: function (index, entry) { - var current = this._expandToIndex(index); - if (current) { - var previous = current.previous; - current.previous = null; - - if (current.onEnd) current.onEnd(index); - if (this.onEnd) this.onEnd(index); - - entry.mixDuration = this.data.getMix(current.animation, entry.animation); - if (entry.mixDuration > 0) { - entry.mixTime = 0; - // If a mix is in progress, mix from the closest animation. - if (previous && current.mixTime / current.mixDuration < 0.5) - entry.previous = previous; - else - entry.previous = current; - } - } - - this.tracks[index] = entry; - - if (entry.onStart) entry.onStart(index); - if (this.onStart) this.onStart(index); - }, - setAnimationByName: function (trackIndex, animationName, loop) { - var animation = this.data.skeletonData.findAnimation(animationName); - if (!animation) throw new Error("Animation not found: " + animationName); - return this.setAnimation(trackIndex, animation, loop); - }, - /** Set the current animation. Any queued animations are cleared. */ - setAnimation: function (trackIndex, animation, loop) { - var entry = new spine.TrackEntry(); - entry.animation = animation; - entry.loop = loop; - entry.endTime = animation.duration; - this.setCurrent(trackIndex, entry); - return entry; - }, - addAnimationByName: function (trackIndex, animationName, loop, delay) { - var animation = this.data.skeletonData.findAnimation(animationName); - if (!animation) throw new Error("Animation not found: " + animationName); - return this.addAnimation(trackIndex, animation, loop, delay); - }, - /** Adds an animation to be played delay seconds after the current or last queued animation. - * @param delay May be <= 0 to use duration of previous animation minus any mix duration plus the negative delay. */ - addAnimation: function (trackIndex, animation, loop, delay) { - var entry = new spine.TrackEntry(); - entry.animation = animation; - entry.loop = loop; - entry.endTime = animation.duration; - - var last = this._expandToIndex(trackIndex); - if (last) { - while (last.next) - last = last.next; - last.next = entry; - } else - this.tracks[trackIndex] = entry; - - if (delay <= 0) { - if (last) - delay += last.endTime - this.data.getMix(last.animation, animation); - else - delay = 0; - } - entry.delay = delay; - - return entry; - }, - /** May be null. */ - getCurrent: function (trackIndex) { - if (trackIndex >= this.tracks.length) return null; - return this.tracks[trackIndex]; - } -}; - -spine.SkeletonJson = function (attachmentLoader) { - this.scale = 1; - - this.attachmentLoader = attachmentLoader; -}; -spine.SkeletonJson.prototype = { - scale: 1, - readSkeletonData: function (root, name) { - var skeletonData = new spine.SkeletonData(); - skeletonData.name = name; - - // Skeleton. - var skeletonMap = root["skeleton"]; - if (skeletonMap) { - skeletonData.hash = skeletonMap["hash"]; - skeletonData.version = skeletonMap["spine"]; - skeletonData.width = skeletonMap["width"] || 0; - skeletonData.height = skeletonMap["height"] || 0; - } - - // Bones. - var bones = root["bones"]; - for (var i = 0, n = bones.length; i < n; i++) { - var boneMap = bones[i]; - var parent = null; - if (boneMap["parent"]) { - parent = skeletonData.findBone(boneMap["parent"]); - if (!parent) throw new Error("Parent bone not found: " + boneMap["parent"]); - } - var boneData = new spine.BoneData(boneMap["name"], parent); - boneData.length = (boneMap["length"] || 0) * this.scale; - boneData.x = (boneMap["x"] || 0) * this.scale; - boneData.y = (boneMap["y"] || 0) * this.scale; - boneData.rotation = (boneMap["rotation"] || 0); - boneData.scaleX = boneMap.hasOwnProperty("scaleX") ? boneMap["scaleX"] : 1; - boneData.scaleY = boneMap.hasOwnProperty("scaleY") ? boneMap["scaleY"] : 1; - boneData.inheritScale = boneMap.hasOwnProperty("inheritScale") ? boneMap["inheritScale"] : true; - boneData.inheritRotation = boneMap.hasOwnProperty("inheritRotation") ? boneMap["inheritRotation"] : true; - skeletonData.bones.push(boneData); - } - - // IK constraints. - var ik = root["ik"]; - if (ik) { - for (var i = 0, n = ik.length; i < n; i++) { - var ikMap = ik[i]; - var ikConstraintData = new spine.IkConstraintData(ikMap["name"]); - - var bones = ikMap["bones"]; - for (var ii = 0, nn = bones.length; ii < nn; ii++) { - var bone = skeletonData.findBone(bones[ii]); - if (!bone) throw new Error("IK bone not found: " + bones[ii]); - ikConstraintData.bones.push(bone); - } - - ikConstraintData.target = skeletonData.findBone(ikMap["target"]); - if (!ikConstraintData.target) throw new Error("Target bone not found: " + ikMap["target"]); - - ikConstraintData.bendDirection = (!ikMap.hasOwnProperty("bendPositive") || ikMap["bendPositive"]) ? 1 : -1; - ikConstraintData.mix = ikMap.hasOwnProperty("mix") ? ikMap["mix"] : 1; - - skeletonData.ikConstraints.push(ikConstraintData); - } - } - - // Slots. - var slots = root["slots"]; - for (var i = 0, n = slots.length; i < n; i++) { - var slotMap = slots[i]; - var boneData = skeletonData.findBone(slotMap["bone"]); - if (!boneData) throw new Error("Slot bone not found: " + slotMap["bone"]); - var slotData = new spine.SlotData(slotMap["name"], boneData); - - var color = slotMap["color"]; - if (color) { - slotData.r = this.toColor(color, 0); - slotData.g = this.toColor(color, 1); - slotData.b = this.toColor(color, 2); - slotData.a = this.toColor(color, 3); - } - - slotData.attachmentName = slotMap["attachment"]; - slotData.blendMode = spine.BlendMode[slotMap["blend"] || "normal"]; - - skeletonData.slots.push(slotData); - } - - // Skins. - var skins = root["skins"]; - for (var skinName in skins) { - if (!skins.hasOwnProperty(skinName)) continue; - var skinMap = skins[skinName]; - var skin = new spine.Skin(skinName); - for (var slotName in skinMap) { - if (!skinMap.hasOwnProperty(slotName)) continue; - var slotIndex = skeletonData.findSlotIndex(slotName); - var slotEntry = skinMap[slotName]; - for (var attachmentName in slotEntry) { - if (!slotEntry.hasOwnProperty(attachmentName)) continue; - var attachment = this.readAttachment(skin, attachmentName, slotEntry[attachmentName]); - if (attachment) skin.addAttachment(slotIndex, attachmentName, attachment); - } - } - skeletonData.skins.push(skin); - if (skin.name == "default") skeletonData.defaultSkin = skin; - } - - // Events. - var events = root["events"]; - for (var eventName in events) { - if (!events.hasOwnProperty(eventName)) continue; - var eventMap = events[eventName]; - var eventData = new spine.EventData(eventName); - eventData.intValue = eventMap["int"] || 0; - eventData.floatValue = eventMap["float"] || 0; - eventData.stringValue = eventMap["string"] || null; - skeletonData.events.push(eventData); - } - - // Animations. - var animations = root["animations"]; - for (var animationName in animations) { - if (!animations.hasOwnProperty(animationName)) continue; - this.readAnimation(animationName, animations[animationName], skeletonData); - } - - return skeletonData; - }, - readAttachment: function (skin, name, map) { - name = map["name"] || name; - - var type = spine.AttachmentType[map["type"] || "region"]; - var path = map["path"] || name; - - var scale = this.scale; - if (type == spine.AttachmentType.region) { - var region = this.attachmentLoader.newRegionAttachment(skin, name, path); - if (!region) return null; - region.path = path; - region.x = (map["x"] || 0) * scale; - region.y = (map["y"] || 0) * scale; - region.scaleX = map.hasOwnProperty("scaleX") ? map["scaleX"] : 1; - region.scaleY = map.hasOwnProperty("scaleY") ? map["scaleY"] : 1; - region.rotation = map["rotation"] || 0; - region.width = (map["width"] || 0) * scale; - region.height = (map["height"] || 0) * scale; - - var color = map["color"]; - if (color) { - region.r = this.toColor(color, 0); - region.g = this.toColor(color, 1); - region.b = this.toColor(color, 2); - region.a = this.toColor(color, 3); - } - - region.updateOffset(); - return region; - } else if (type == spine.AttachmentType.mesh) { - var mesh = this.attachmentLoader.newMeshAttachment(skin, name, path); - if (!mesh) return null; - mesh.path = path; - mesh.vertices = this.getFloatArray(map, "vertices", scale); - mesh.triangles = this.getIntArray(map, "triangles"); - mesh.regionUVs = this.getFloatArray(map, "uvs", 1); - mesh.updateUVs(); - - color = map["color"]; - if (color) { - mesh.r = this.toColor(color, 0); - mesh.g = this.toColor(color, 1); - mesh.b = this.toColor(color, 2); - mesh.a = this.toColor(color, 3); - } - - mesh.hullLength = (map["hull"] || 0) * 2; - if (map["edges"]) mesh.edges = this.getIntArray(map, "edges"); - mesh.width = (map["width"] || 0) * scale; - mesh.height = (map["height"] || 0) * scale; - return mesh; - } else if (type == spine.AttachmentType.skinnedmesh) { - var mesh = this.attachmentLoader.newSkinnedMeshAttachment(skin, name, path); - if (!mesh) return null; - mesh.path = path; - - var uvs = this.getFloatArray(map, "uvs", 1); - var vertices = this.getFloatArray(map, "vertices", 1); - var weights = []; - var bones = []; - for (var i = 0, n = vertices.length; i < n; ) { - var boneCount = vertices[i++] | 0; - bones[bones.length] = boneCount; - for (var nn = i + boneCount * 4; i < nn; ) { - bones[bones.length] = vertices[i]; - weights[weights.length] = vertices[i + 1] * scale; - weights[weights.length] = vertices[i + 2] * scale; - weights[weights.length] = vertices[i + 3]; - i += 4; - } - } - mesh.bones = bones; - mesh.weights = weights; - mesh.triangles = this.getIntArray(map, "triangles"); - mesh.regionUVs = uvs; - mesh.updateUVs(); - - color = map["color"]; - if (color) { - mesh.r = this.toColor(color, 0); - mesh.g = this.toColor(color, 1); - mesh.b = this.toColor(color, 2); - mesh.a = this.toColor(color, 3); - } - - mesh.hullLength = (map["hull"] || 0) * 2; - if (map["edges"]) mesh.edges = this.getIntArray(map, "edges"); - mesh.width = (map["width"] || 0) * scale; - mesh.height = (map["height"] || 0) * scale; - return mesh; - } else if (type == spine.AttachmentType.boundingbox) { - var attachment = this.attachmentLoader.newBoundingBoxAttachment(skin, name); - var vertices = map["vertices"]; - for (var i = 0, n = vertices.length; i < n; i++) - attachment.vertices.push(vertices[i] * scale); - return attachment; - } - throw new Error("Unknown attachment type: " + type); - }, - readAnimation: function (name, map, skeletonData) { - var timelines = []; - var duration = 0; - - var slots = map["slots"]; - for (var slotName in slots) { - if (!slots.hasOwnProperty(slotName)) continue; - var slotMap = slots[slotName]; - var slotIndex = skeletonData.findSlotIndex(slotName); - - for (var timelineName in slotMap) { - if (!slotMap.hasOwnProperty(timelineName)) continue; - var values = slotMap[timelineName]; - if (timelineName == "color") { - var timeline = new spine.ColorTimeline(values.length); - timeline.slotIndex = slotIndex; - - var frameIndex = 0; - for (var i = 0, n = values.length; i < n; i++) { - var valueMap = values[i]; - var color = valueMap["color"]; - var r = this.toColor(color, 0); - var g = this.toColor(color, 1); - var b = this.toColor(color, 2); - var a = this.toColor(color, 3); - timeline.setFrame(frameIndex, valueMap["time"], r, g, b, a); - this.readCurve(timeline, frameIndex, valueMap); - frameIndex++; - } - timelines.push(timeline); - duration = Math.max(duration, timeline.frames[timeline.getFrameCount() * 5 - 5]); - - } else if (timelineName == "attachment") { - var timeline = new spine.AttachmentTimeline(values.length); - timeline.slotIndex = slotIndex; - - var frameIndex = 0; - for (var i = 0, n = values.length; i < n; i++) { - var valueMap = values[i]; - timeline.setFrame(frameIndex++, valueMap["time"], valueMap["name"]); - } - timelines.push(timeline); - duration = Math.max(duration, timeline.frames[timeline.getFrameCount() - 1]); - - } else - throw new Error("Invalid timeline type for a slot: " + timelineName + " (" + slotName + ")"); - } - } - - var bones = map["bones"]; - for (var boneName in bones) { - if (!bones.hasOwnProperty(boneName)) continue; - var boneIndex = skeletonData.findBoneIndex(boneName); - if (boneIndex == -1) throw new Error("Bone not found: " + boneName); - var boneMap = bones[boneName]; - - for (var timelineName in boneMap) { - if (!boneMap.hasOwnProperty(timelineName)) continue; - var values = boneMap[timelineName]; - if (timelineName == "rotate") { - var timeline = new spine.RotateTimeline(values.length); - timeline.boneIndex = boneIndex; - - var frameIndex = 0; - for (var i = 0, n = values.length; i < n; i++) { - var valueMap = values[i]; - timeline.setFrame(frameIndex, valueMap["time"], valueMap["angle"]); - this.readCurve(timeline, frameIndex, valueMap); - frameIndex++; - } - timelines.push(timeline); - duration = Math.max(duration, timeline.frames[timeline.getFrameCount() * 2 - 2]); - - } else if (timelineName == "translate" || timelineName == "scale") { - var timeline; - var timelineScale = 1; - if (timelineName == "scale") - timeline = new spine.ScaleTimeline(values.length); - else { - timeline = new spine.TranslateTimeline(values.length); - timelineScale = this.scale; - } - timeline.boneIndex = boneIndex; - - var frameIndex = 0; - for (var i = 0, n = values.length; i < n; i++) { - var valueMap = values[i]; - var x = (valueMap["x"] || 0) * timelineScale; - var y = (valueMap["y"] || 0) * timelineScale; - timeline.setFrame(frameIndex, valueMap["time"], x, y); - this.readCurve(timeline, frameIndex, valueMap); - frameIndex++; - } - timelines.push(timeline); - duration = Math.max(duration, timeline.frames[timeline.getFrameCount() * 3 - 3]); - - } else if (timelineName == "flipX" || timelineName == "flipY") { - var x = timelineName == "flipX"; - var timeline = x ? new spine.FlipXTimeline(values.length) : new spine.FlipYTimeline(values.length); - timeline.boneIndex = boneIndex; - - var field = x ? "x" : "y"; - var frameIndex = 0; - for (var i = 0, n = values.length; i < n; i++) { - var valueMap = values[i]; - timeline.setFrame(frameIndex, valueMap["time"], valueMap[field] || false); - frameIndex++; - } - timelines.push(timeline); - duration = Math.max(duration, timeline.frames[timeline.getFrameCount() * 2 - 2]); - } else - throw new Error("Invalid timeline type for a bone: " + timelineName + " (" + boneName + ")"); - } - } - - var ikMap = map["ik"]; - for (var ikConstraintName in ikMap) { - if (!ikMap.hasOwnProperty(ikConstraintName)) continue; - var ikConstraint = skeletonData.findIkConstraint(ikConstraintName); - var values = ikMap[ikConstraintName]; - var timeline = new spine.IkConstraintTimeline(values.length); - timeline.ikConstraintIndex = skeletonData.ikConstraints.indexOf(ikConstraint); - var frameIndex = 0; - for (var i = 0, n = values.length; i < n; i++) { - var valueMap = values[i]; - var mix = valueMap.hasOwnProperty("mix") ? valueMap["mix"] : 1; - var bendDirection = (!valueMap.hasOwnProperty("bendPositive") || valueMap["bendPositive"]) ? 1 : -1; - timeline.setFrame(frameIndex, valueMap["time"], mix, bendDirection); - this.readCurve(timeline, frameIndex, valueMap); - frameIndex++; - } - timelines.push(timeline); - duration = Math.max(duration, timeline.frames[timeline.frameCount * 3 - 3]); - } - - var ffd = map["ffd"]; - for (var skinName in ffd) { - var skin = skeletonData.findSkin(skinName); - var slotMap = ffd[skinName]; - for (slotName in slotMap) { - var slotIndex = skeletonData.findSlotIndex(slotName); - var meshMap = slotMap[slotName]; - for (var meshName in meshMap) { - var values = meshMap[meshName]; - var timeline = new spine.FfdTimeline(values.length); - var attachment = skin.getAttachment(slotIndex, meshName); - if (!attachment) throw new Error("FFD attachment not found: " + meshName); - timeline.slotIndex = slotIndex; - timeline.attachment = attachment; - - var isMesh = attachment.type == spine.AttachmentType.mesh; - var vertexCount; - if (isMesh) - vertexCount = attachment.vertices.length; - else - vertexCount = attachment.weights.length / 3 * 2; - - var frameIndex = 0; - for (var i = 0, n = values.length; i < n; i++) { - var valueMap = values[i]; - var vertices; - if (!valueMap["vertices"]) { - if (isMesh) - vertices = attachment.vertices; - else { - vertices = []; - vertices.length = vertexCount; - } - } else { - var verticesValue = valueMap["vertices"]; - var vertices = []; - vertices.length = vertexCount; - var start = valueMap["offset"] || 0; - var nn = verticesValue.length; - if (this.scale == 1) { - for (var ii = 0; ii < nn; ii++) - vertices[ii + start] = verticesValue[ii]; - } else { - for (var ii = 0; ii < nn; ii++) - vertices[ii + start] = verticesValue[ii] * this.scale; - } - if (isMesh) { - var meshVertices = attachment.vertices; - for (var ii = 0, nn = vertices.length; ii < nn; ii++) - vertices[ii] += meshVertices[ii]; - } - } - - timeline.setFrame(frameIndex, valueMap["time"], vertices); - this.readCurve(timeline, frameIndex, valueMap); - frameIndex++; - } - timelines[timelines.length] = timeline; - duration = Math.max(duration, timeline.frames[timeline.frameCount - 1]); - } - } - } - - var drawOrderValues = map["drawOrder"]; - if (!drawOrderValues) drawOrderValues = map["draworder"]; - if (drawOrderValues) { - var timeline = new spine.DrawOrderTimeline(drawOrderValues.length); - var slotCount = skeletonData.slots.length; - var frameIndex = 0; - for (var i = 0, n = drawOrderValues.length; i < n; i++) { - var drawOrderMap = drawOrderValues[i]; - var drawOrder = null; - if (drawOrderMap["offsets"]) { - drawOrder = []; - drawOrder.length = slotCount; - for (var ii = slotCount - 1; ii >= 0; ii--) - drawOrder[ii] = -1; - var offsets = drawOrderMap["offsets"]; - var unchanged = []; - unchanged.length = slotCount - offsets.length; - var originalIndex = 0, unchangedIndex = 0; - for (var ii = 0, nn = offsets.length; ii < nn; ii++) { - var offsetMap = offsets[ii]; - var slotIndex = skeletonData.findSlotIndex(offsetMap["slot"]); - if (slotIndex == -1) throw new Error("Slot not found: " + offsetMap["slot"]); - // Collect unchanged items. - while (originalIndex != slotIndex) - unchanged[unchangedIndex++] = originalIndex++; - // Set changed items. - drawOrder[originalIndex + offsetMap["offset"]] = originalIndex++; - } - // Collect remaining unchanged items. - while (originalIndex < slotCount) - unchanged[unchangedIndex++] = originalIndex++; - // Fill in unchanged items. - for (var ii = slotCount - 1; ii >= 0; ii--) - if (drawOrder[ii] == -1) drawOrder[ii] = unchanged[--unchangedIndex]; - } - timeline.setFrame(frameIndex++, drawOrderMap["time"], drawOrder); - } - timelines.push(timeline); - duration = Math.max(duration, timeline.frames[timeline.getFrameCount() - 1]); - } - - var events = map["events"]; - if (events) { - var timeline = new spine.EventTimeline(events.length); - var frameIndex = 0; - for (var i = 0, n = events.length; i < n; i++) { - var eventMap = events[i]; - var eventData = skeletonData.findEvent(eventMap["name"]); - if (!eventData) throw new Error("Event not found: " + eventMap["name"]); - var event = new spine.Event(eventData); - event.intValue = eventMap.hasOwnProperty("int") ? eventMap["int"] : eventData.intValue; - event.floatValue = eventMap.hasOwnProperty("float") ? eventMap["float"] : eventData.floatValue; - event.stringValue = eventMap.hasOwnProperty("string") ? eventMap["string"] : eventData.stringValue; - timeline.setFrame(frameIndex++, eventMap["time"], event); - } - timelines.push(timeline); - duration = Math.max(duration, timeline.frames[timeline.getFrameCount() - 1]); - } - - skeletonData.animations.push(new spine.Animation(name, timelines, duration)); - }, - readCurve: function (timeline, frameIndex, valueMap) { - var curve = valueMap["curve"]; - if (!curve) - timeline.curves.setLinear(frameIndex); - else if (curve == "stepped") - timeline.curves.setStepped(frameIndex); - else if (curve instanceof Array) - timeline.curves.setCurve(frameIndex, curve[0], curve[1], curve[2], curve[3]); - }, - toColor: function (hexString, colorIndex) { - if (hexString.length != 8) throw new Error("Color hexadecimal length must be 8, received: " + hexString); - return parseInt(hexString.substring(colorIndex * 2, (colorIndex * 2) + 2), 16) / 255; - }, - getFloatArray: function (map, name, scale) { - var list = map[name]; - var values = new spine.Float32Array(list.length); - var i = 0, n = list.length; - if (scale == 1) { - for (; i < n; i++) - values[i] = list[i]; - } else { - for (; i < n; i++) - values[i] = list[i] * scale; - } - return values; - }, - getIntArray: function (map, name) { - var list = map[name]; - var values = new spine.Uint16Array(list.length); - for (var i = 0, n = list.length; i < n; i++) - values[i] = list[i] | 0; - return values; - } -}; - -spine.Atlas = function (atlasText, textureLoader) { - this.textureLoader = textureLoader; - this.pages = []; - this.regions = []; - - var reader = new spine.AtlasReader(atlasText); - var tuple = []; - tuple.length = 4; - var page = null; - while (true) { - var line = reader.readLine(); - if (line === null) break; - line = reader.trim(line); - if (!line.length) - page = null; - else if (!page) { - page = new spine.AtlasPage(); - page.name = line; - - if (reader.readTuple(tuple) == 2) { // size is only optional for an atlas packed with an old TexturePacker. - page.width = parseInt(tuple[0]); - page.height = parseInt(tuple[1]); - reader.readTuple(tuple); - } - page.format = spine.Atlas.Format[tuple[0]]; - - reader.readTuple(tuple); - page.minFilter = spine.Atlas.TextureFilter[tuple[0]]; - page.magFilter = spine.Atlas.TextureFilter[tuple[1]]; - - var direction = reader.readValue(); - page.uWrap = spine.Atlas.TextureWrap.clampToEdge; - page.vWrap = spine.Atlas.TextureWrap.clampToEdge; - if (direction == "x") - page.uWrap = spine.Atlas.TextureWrap.repeat; - else if (direction == "y") - page.vWrap = spine.Atlas.TextureWrap.repeat; - else if (direction == "xy") - page.uWrap = page.vWrap = spine.Atlas.TextureWrap.repeat; - - textureLoader.load(page, line, this); - - this.pages.push(page); - - } else { - var region = new spine.AtlasRegion(); - region.name = line; - region.page = page; - - region.rotate = reader.readValue() == "true"; - - reader.readTuple(tuple); - var x = parseInt(tuple[0]); - var y = parseInt(tuple[1]); - - reader.readTuple(tuple); - var width = parseInt(tuple[0]); - var height = parseInt(tuple[1]); - - region.u = x / page.width; - region.v = y / page.height; - if (region.rotate) { - region.u2 = (x + height) / page.width; - region.v2 = (y + width) / page.height; - } else { - region.u2 = (x + width) / page.width; - region.v2 = (y + height) / page.height; - } - region.x = x; - region.y = y; - region.width = Math.abs(width); - region.height = Math.abs(height); - - if (reader.readTuple(tuple) == 4) { // split is optional - region.splits = [parseInt(tuple[0]), parseInt(tuple[1]), parseInt(tuple[2]), parseInt(tuple[3])]; - - if (reader.readTuple(tuple) == 4) { // pad is optional, but only present with splits - region.pads = [parseInt(tuple[0]), parseInt(tuple[1]), parseInt(tuple[2]), parseInt(tuple[3])]; - - reader.readTuple(tuple); - } - } - - region.originalWidth = parseInt(tuple[0]); - region.originalHeight = parseInt(tuple[1]); - - reader.readTuple(tuple); - region.offsetX = parseInt(tuple[0]); - region.offsetY = parseInt(tuple[1]); - - region.index = parseInt(reader.readValue()); - - this.regions.push(region); - } - } -}; -spine.Atlas.prototype = { - findRegion: function (name) { - var regions = this.regions; - for (var i = 0, n = regions.length; i < n; i++) - if (regions[i].name == name) return regions[i]; - return null; - }, - dispose: function () { - var pages = this.pages; - for (var i = 0, n = pages.length; i < n; i++) - this.textureLoader.unload(pages[i].rendererObject); - }, - updateUVs: function (page) { - var regions = this.regions; - for (var i = 0, n = regions.length; i < n; i++) { - var region = regions[i]; - if (region.page != page) continue; - region.u = region.x / page.width; - region.v = region.y / page.height; - if (region.rotate) { - region.u2 = (region.x + region.height) / page.width; - region.v2 = (region.y + region.width) / page.height; - } else { - region.u2 = (region.x + region.width) / page.width; - region.v2 = (region.y + region.height) / page.height; - } - } - } -}; - -spine.Atlas.Format = { - alpha: 0, - intensity: 1, - luminanceAlpha: 2, - rgb565: 3, - rgba4444: 4, - rgb888: 5, - rgba8888: 6 -}; - -spine.Atlas.TextureFilter = { - nearest: 0, - linear: 1, - mipMap: 2, - mipMapNearestNearest: 3, - mipMapLinearNearest: 4, - mipMapNearestLinear: 5, - mipMapLinearLinear: 6 -}; - -spine.Atlas.TextureWrap = { - mirroredRepeat: 0, - clampToEdge: 1, - repeat: 2 -}; - -spine.AtlasPage = function () { - this.width = this.height = 0; -}; -spine.AtlasPage.prototype = { - name: null, - format: null, - minFilter: null, - magFilter: null, - uWrap: null, - vWrap: null, - rendererObject: null, - width: 0, - height: 0 -}; - -spine.AtlasRegion = function () { - this.x = this.y = this.width = this.height = - this.u = this.v = this.u2 = this.v2 = - this.offsetX = this.offsetY = - this.originalWidth = this.originalHeight = 0; - this.index = 0; -}; -spine.AtlasRegion.prototype = { - page: null, - name: null, - x: 0, y: 0, - width: 0, height: 0, - u: 0, v: 0, u2: 0, v2: 0, - offsetX: 0, offsetY: 0, - originalWidth: 0, originalHeight: 0, - index: 0, - rotate: false, - splits: null, - pads: null -}; - -spine.AtlasReader = function (text) { - this.index = 0; - - this.lines = text.split(/\r\n|\r|\n/); -}; -spine.AtlasReader.prototype = { - index: 0, - trim: function (value) { - return value.replace(/^\s+|\s+$/g, ""); - }, - readLine: function () { - if (this.index >= this.lines.length) return null; - return this.lines[this.index++]; - }, - readValue: function () { - var line = this.readLine(); - var colon = line.indexOf(":"); - if (colon == -1) throw new Error("Invalid line: " + line); - return this.trim(line.substring(colon + 1)); - }, - /** Returns the number of tuple values read (1, 2 or 4). */ - readTuple: function (tuple) { - var line = this.readLine(); - var colon = line.indexOf(":"); - if (colon == -1) throw new Error("Invalid line: " + line); - var i = 0, lastMatch = colon + 1; - for (; i < 3; i++) { - var comma = line.indexOf(",", lastMatch); - if (comma == -1) break; - tuple[i] = this.trim(line.substr(lastMatch, comma - lastMatch)); - lastMatch = comma + 1; - } - tuple[i] = this.trim(line.substring(lastMatch)); - return i + 1; - } -}; - -spine.AtlasAttachmentLoader = function (atlas) { - this.atlas = atlas; -}; -spine.AtlasAttachmentLoader.prototype = { - newRegionAttachment: function (skin, name, path) { - var region = this.atlas.findRegion(path); - if (!region) throw new Error("Region not found in atlas: " + path + " (region attachment: " + name + ")"); - var attachment = new spine.RegionAttachment(name); - attachment.rendererObject = region; - attachment.setUVs(region.u, region.v, region.u2, region.v2, region.rotate); - attachment.regionOffsetX = region.offsetX; - attachment.regionOffsetY = region.offsetY; - attachment.regionWidth = region.width; - attachment.regionHeight = region.height; - attachment.regionOriginalWidth = region.originalWidth; - attachment.regionOriginalHeight = region.originalHeight; - return attachment; - }, - newMeshAttachment: function (skin, name, path) { - var region = this.atlas.findRegion(path); - if (!region) throw new Error("Region not found in atlas: " + path + " (mesh attachment: " + name + ")"); - var attachment = new spine.MeshAttachment(name); - attachment.rendererObject = region; - attachment.regionU = region.u; - attachment.regionV = region.v; - attachment.regionU2 = region.u2; - attachment.regionV2 = region.v2; - attachment.regionRotate = region.rotate; - attachment.regionOffsetX = region.offsetX; - attachment.regionOffsetY = region.offsetY; - attachment.regionWidth = region.width; - attachment.regionHeight = region.height; - attachment.regionOriginalWidth = region.originalWidth; - attachment.regionOriginalHeight = region.originalHeight; - return attachment; - }, - newSkinnedMeshAttachment: function (skin, name, path) { - var region = this.atlas.findRegion(path); - if (!region) throw new Error("Region not found in atlas: " + path + " (skinned mesh attachment: " + name + ")"); - var attachment = new spine.SkinnedMeshAttachment(name); - attachment.rendererObject = region; - attachment.regionU = region.u; - attachment.regionV = region.v; - attachment.regionU2 = region.u2; - attachment.regionV2 = region.v2; - attachment.regionRotate = region.rotate; - attachment.regionOffsetX = region.offsetX; - attachment.regionOffsetY = region.offsetY; - attachment.regionWidth = region.width; - attachment.regionHeight = region.height; - attachment.regionOriginalWidth = region.originalWidth; - attachment.regionOriginalHeight = region.originalHeight; - return attachment; - }, - newBoundingBoxAttachment: function (skin, name) { - return new spine.BoundingBoxAttachment(name); - } -}; - -spine.SkeletonBounds = function () { - this.minX = this.minY = this.maxX = this.maxY = 0; - - this.polygonPool = []; - this.polygons = []; - this.boundingBoxes = []; -}; -spine.SkeletonBounds.prototype = { - minX: 0, minY: 0, maxX: 0, maxY: 0, - update: function (skeleton, updateAabb) { - var slots = skeleton.slots; - var slotCount = slots.length; - var x = skeleton.x, y = skeleton.y; - var boundingBoxes = this.boundingBoxes; - var polygonPool = this.polygonPool; - var polygons = this.polygons; - - boundingBoxes.length = 0; - for (var i = 0, n = polygons.length; i < n; i++) - polygonPool.push(polygons[i]); - polygons.length = 0; - - for (var i = 0; i < slotCount; i++) { - var slot = slots[i]; - var boundingBox = slot.attachment; - if (boundingBox.type != spine.AttachmentType.boundingbox) continue; - boundingBoxes.push(boundingBox); - - var poolCount = polygonPool.length, polygon; - if (poolCount > 0) { - polygon = polygonPool[poolCount - 1]; - polygonPool.splice(poolCount - 1, 1); - } else - polygon = []; - polygons.push(polygon); - - polygon.length = boundingBox.vertices.length; - boundingBox.computeWorldVertices(x, y, slot.bone, polygon); - } - - if (updateAabb) this.aabbCompute(); - }, - aabbCompute: function () { - var polygons = this.polygons; - var minX = Number.MAX_VALUE, minY = Number.MAX_VALUE, maxX = Number.MIN_VALUE, maxY = Number.MIN_VALUE; - for (var i = 0, n = polygons.length; i < n; i++) { - var vertices = polygons[i]; - for (var ii = 0, nn = vertices.length; ii < nn; ii += 2) { - var x = vertices[ii]; - var y = vertices[ii + 1]; - minX = Math.min(minX, x); - minY = Math.min(minY, y); - maxX = Math.max(maxX, x); - maxY = Math.max(maxY, y); - } - } - this.minX = minX; - this.minY = minY; - this.maxX = maxX; - this.maxY = maxY; - }, - /** Returns true if the axis aligned bounding box contains the point. */ - aabbContainsPoint: function (x, y) { - return x >= this.minX && x <= this.maxX && y >= this.minY && y <= this.maxY; - }, - /** Returns true if the axis aligned bounding box intersects the line segment. */ - aabbIntersectsSegment: function (x1, y1, x2, y2) { - var minX = this.minX, minY = this.minY, maxX = this.maxX, maxY = this.maxY; - if ((x1 <= minX && x2 <= minX) || (y1 <= minY && y2 <= minY) || (x1 >= maxX && x2 >= maxX) || (y1 >= maxY && y2 >= maxY)) - return false; - var m = (y2 - y1) / (x2 - x1); - var y = m * (minX - x1) + y1; - if (y > minY && y < maxY) return true; - y = m * (maxX - x1) + y1; - if (y > minY && y < maxY) return true; - var x = (minY - y1) / m + x1; - if (x > minX && x < maxX) return true; - x = (maxY - y1) / m + x1; - if (x > minX && x < maxX) return true; - return false; - }, - /** Returns true if the axis aligned bounding box intersects the axis aligned bounding box of the specified bounds. */ - aabbIntersectsSkeleton: function (bounds) { - return this.minX < bounds.maxX && this.maxX > bounds.minX && this.minY < bounds.maxY && this.maxY > bounds.minY; - }, - /** Returns the first bounding box attachment that contains the point, or null. When doing many checks, it is usually more - * efficient to only call this method if {@link #aabbContainsPoint(float, float)} returns true. */ - containsPoint: function (x, y) { - var polygons = this.polygons; - for (var i = 0, n = polygons.length; i < n; i++) - if (this.polygonContainsPoint(polygons[i], x, y)) return this.boundingBoxes[i]; - return null; - }, - /** Returns the first bounding box attachment that contains the line segment, or null. When doing many checks, it is usually - * more efficient to only call this method if {@link #aabbIntersectsSegment(float, float, float, float)} returns true. */ - intersectsSegment: function (x1, y1, x2, y2) { - var polygons = this.polygons; - for (var i = 0, n = polygons.length; i < n; i++) - if (polygons[i].intersectsSegment(x1, y1, x2, y2)) return this.boundingBoxes[i]; - return null; - }, - /** Returns true if the polygon contains the point. */ - polygonContainsPoint: function (polygon, x, y) { - var nn = polygon.length; - var prevIndex = nn - 2; - var inside = false; - for (var ii = 0; ii < nn; ii += 2) { - var vertexY = polygon[ii + 1]; - var prevY = polygon[prevIndex + 1]; - if ((vertexY < y && prevY >= y) || (prevY < y && vertexY >= y)) { - var vertexX = polygon[ii]; - if (vertexX + (y - vertexY) / (prevY - vertexY) * (polygon[prevIndex] - vertexX) < x) inside = !inside; - } - prevIndex = ii; - } - return inside; - }, - /** Returns true if the polygon contains the line segment. */ - polygonIntersectsSegment: function (polygon, x1, y1, x2, y2) { - var nn = polygon.length; - var width12 = x1 - x2, height12 = y1 - y2; - var det1 = x1 * y2 - y1 * x2; - var x3 = polygon[nn - 2], y3 = polygon[nn - 1]; - for (var ii = 0; ii < nn; ii += 2) { - var x4 = polygon[ii], y4 = polygon[ii + 1]; - var det2 = x3 * y4 - y3 * x4; - var width34 = x3 - x4, height34 = y3 - y4; - var det3 = width12 * height34 - height12 * width34; - var x = (det1 * width34 - width12 * det2) / det3; - if (((x >= x3 && x <= x4) || (x >= x4 && x <= x3)) && ((x >= x1 && x <= x2) || (x >= x2 && x <= x1))) { - var y = (det1 * height34 - height12 * det2) / det3; - if (((y >= y3 && y <= y4) || (y >= y4 && y <= y3)) && ((y >= y1 && y <= y2) || (y >= y2 && y <= y1))) return true; - } - x3 = x4; - y3 = y4; - } - return false; - }, - getPolygon: function (attachment) { - var index = this.boundingBoxes.indexOf(attachment); - return index == -1 ? null : this.polygons[index]; - }, - getWidth: function () { - return this.maxX - this.minX; - }, - getHeight: function () { - return this.maxY - this.minY; - } +var __extends = (this && this.__extends) || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; +var spine; +(function (spine) { + var Animation = (function () { + function Animation(name, timelines, duration) { + if (name == null) + throw new Error("name cannot be null."); + if (timelines == null) + throw new Error("timelines cannot be null."); + this.name = name; + this.timelines = timelines; + this.duration = duration; + } + Animation.prototype.apply = function (skeleton, lastTime, time, loop, events, alpha, setupPose, mixingOut) { + if (skeleton == null) + throw new Error("skeleton cannot be null."); + if (loop && this.duration != 0) { + time %= this.duration; + if (lastTime > 0) + lastTime %= this.duration; + } + var timelines = this.timelines; + for (var i = 0, n = timelines.length; i < n; i++) + timelines[i].apply(skeleton, lastTime, time, events, alpha, setupPose, mixingOut); + }; + Animation.binarySearch = function (values, target, step) { + if (step === void 0) { step = 1; } + var low = 0; + var high = values.length / step - 2; + if (high == 0) + return step; + var current = high >>> 1; + while (true) { + if (values[(current + 1) * step] <= target) + low = current + 1; + else + high = current; + if (low == high) + return (low + 1) * step; + current = (low + high) >>> 1; + } + }; + Animation.linearSearch = function (values, target, step) { + for (var i = 0, last = values.length - step; i <= last; i += step) + if (values[i] > target) + return i; + return -1; + }; + return Animation; + }()); + spine.Animation = Animation; + (function (TimelineType) { + TimelineType[TimelineType["rotate"] = 0] = "rotate"; + TimelineType[TimelineType["translate"] = 1] = "translate"; + TimelineType[TimelineType["scale"] = 2] = "scale"; + TimelineType[TimelineType["shear"] = 3] = "shear"; + TimelineType[TimelineType["attachment"] = 4] = "attachment"; + TimelineType[TimelineType["color"] = 5] = "color"; + TimelineType[TimelineType["deform"] = 6] = "deform"; + TimelineType[TimelineType["event"] = 7] = "event"; + TimelineType[TimelineType["drawOrder"] = 8] = "drawOrder"; + TimelineType[TimelineType["ikConstraint"] = 9] = "ikConstraint"; + TimelineType[TimelineType["transformConstraint"] = 10] = "transformConstraint"; + TimelineType[TimelineType["pathConstraintPosition"] = 11] = "pathConstraintPosition"; + TimelineType[TimelineType["pathConstraintSpacing"] = 12] = "pathConstraintSpacing"; + TimelineType[TimelineType["pathConstraintMix"] = 13] = "pathConstraintMix"; + })(spine.TimelineType || (spine.TimelineType = {})); + var TimelineType = spine.TimelineType; + var CurveTimeline = (function () { + function CurveTimeline(frameCount) { + if (frameCount <= 0) + throw new Error("frameCount must be > 0: " + frameCount); + this.curves = spine.Utils.newFloatArray((frameCount - 1) * CurveTimeline.BEZIER_SIZE); + } + CurveTimeline.prototype.getFrameCount = function () { + return this.curves.length / CurveTimeline.BEZIER_SIZE + 1; + }; + CurveTimeline.prototype.setLinear = function (frameIndex) { + this.curves[frameIndex * CurveTimeline.BEZIER_SIZE] = CurveTimeline.LINEAR; + }; + CurveTimeline.prototype.setStepped = function (frameIndex) { + this.curves[frameIndex * CurveTimeline.BEZIER_SIZE] = CurveTimeline.STEPPED; + }; + CurveTimeline.prototype.getCurveType = function (frameIndex) { + var index = frameIndex * CurveTimeline.BEZIER_SIZE; + if (index == this.curves.length) + return CurveTimeline.LINEAR; + var type = this.curves[index]; + if (type == CurveTimeline.LINEAR) + return CurveTimeline.LINEAR; + if (type == CurveTimeline.STEPPED) + return CurveTimeline.STEPPED; + return CurveTimeline.BEZIER; + }; + CurveTimeline.prototype.setCurve = function (frameIndex, cx1, cy1, cx2, cy2) { + var tmpx = (-cx1 * 2 + cx2) * 0.03, tmpy = (-cy1 * 2 + cy2) * 0.03; + var dddfx = ((cx1 - cx2) * 3 + 1) * 0.006, dddfy = ((cy1 - cy2) * 3 + 1) * 0.006; + var ddfx = tmpx * 2 + dddfx, ddfy = tmpy * 2 + dddfy; + var dfx = cx1 * 0.3 + tmpx + dddfx * 0.16666667, dfy = cy1 * 0.3 + tmpy + dddfy * 0.16666667; + var i = frameIndex * CurveTimeline.BEZIER_SIZE; + var curves = this.curves; + curves[i++] = CurveTimeline.BEZIER; + var x = dfx, y = dfy; + for (var n = i + CurveTimeline.BEZIER_SIZE - 1; i < n; i += 2) { + curves[i] = x; + curves[i + 1] = y; + dfx += ddfx; + dfy += ddfy; + ddfx += dddfx; + ddfy += dddfy; + x += dfx; + y += dfy; + } + }; + CurveTimeline.prototype.getCurvePercent = function (frameIndex, percent) { + percent = spine.MathUtils.clamp(percent, 0, 1); + var curves = this.curves; + var i = frameIndex * CurveTimeline.BEZIER_SIZE; + var type = curves[i]; + if (type == CurveTimeline.LINEAR) + return percent; + if (type == CurveTimeline.STEPPED) + return 0; + i++; + var x = 0; + for (var start = i, n = i + CurveTimeline.BEZIER_SIZE - 1; i < n; i += 2) { + x = curves[i]; + if (x >= percent) { + var prevX = void 0, prevY = void 0; + if (i == start) { + prevX = 0; + prevY = 0; + } + else { + prevX = curves[i - 2]; + prevY = curves[i - 1]; + } + return prevY + (curves[i + 1] - prevY) * (percent - prevX) / (x - prevX); + } + } + var y = curves[i - 1]; + return y + (1 - y) * (percent - x) / (1 - x); + }; + CurveTimeline.LINEAR = 0; + CurveTimeline.STEPPED = 1; + CurveTimeline.BEZIER = 2; + CurveTimeline.BEZIER_SIZE = 10 * 2 - 1; + return CurveTimeline; + }()); + spine.CurveTimeline = CurveTimeline; + var RotateTimeline = (function (_super) { + __extends(RotateTimeline, _super); + function RotateTimeline(frameCount) { + _super.call(this, frameCount); + this.frames = spine.Utils.newFloatArray(frameCount << 1); + } + RotateTimeline.prototype.getPropertyId = function () { + return (TimelineType.rotate << 24) + this.boneIndex; + }; + RotateTimeline.prototype.setFrame = function (frameIndex, time, degrees) { + frameIndex <<= 1; + this.frames[frameIndex] = time; + this.frames[frameIndex + RotateTimeline.ROTATION] = degrees; + }; + RotateTimeline.prototype.apply = function (skeleton, lastTime, time, events, alpha, setupPose, mixingOut) { + var frames = this.frames; + var bone = skeleton.bones[this.boneIndex]; + if (time < frames[0]) { + if (setupPose) + bone.rotation = bone.data.rotation; + return; + } + if (time >= frames[frames.length - RotateTimeline.ENTRIES]) { + if (setupPose) + bone.rotation = bone.data.rotation + frames[frames.length + RotateTimeline.PREV_ROTATION] * alpha; + else { + var r_1 = bone.data.rotation + frames[frames.length + RotateTimeline.PREV_ROTATION] - bone.rotation; + r_1 -= (16384 - ((16384.499999999996 - r_1 / 360) | 0)) * 360; + bone.rotation += r_1 * alpha; + } + return; + } + var frame = Animation.binarySearch(frames, time, RotateTimeline.ENTRIES); + var prevRotation = frames[frame + RotateTimeline.PREV_ROTATION]; + var frameTime = frames[frame]; + var percent = this.getCurvePercent((frame >> 1) - 1, 1 - (time - frameTime) / (frames[frame + RotateTimeline.PREV_TIME] - frameTime)); + var r = frames[frame + RotateTimeline.ROTATION] - prevRotation; + r -= (16384 - ((16384.499999999996 - r / 360) | 0)) * 360; + r = prevRotation + r * percent; + if (setupPose) { + r -= (16384 - ((16384.499999999996 - r / 360) | 0)) * 360; + bone.rotation = bone.data.rotation + r * alpha; + } + else { + r = bone.data.rotation + r - bone.rotation; + r -= (16384 - ((16384.499999999996 - r / 360) | 0)) * 360; + bone.rotation += r * alpha; + } + }; + RotateTimeline.ENTRIES = 2; + RotateTimeline.PREV_TIME = -2; + RotateTimeline.PREV_ROTATION = -1; + RotateTimeline.ROTATION = 1; + return RotateTimeline; + }(CurveTimeline)); + spine.RotateTimeline = RotateTimeline; + var TranslateTimeline = (function (_super) { + __extends(TranslateTimeline, _super); + function TranslateTimeline(frameCount) { + _super.call(this, frameCount); + this.frames = spine.Utils.newFloatArray(frameCount * TranslateTimeline.ENTRIES); + } + TranslateTimeline.prototype.getPropertyId = function () { + return (TimelineType.translate << 24) + this.boneIndex; + }; + TranslateTimeline.prototype.setFrame = function (frameIndex, time, x, y) { + frameIndex *= TranslateTimeline.ENTRIES; + this.frames[frameIndex] = time; + this.frames[frameIndex + TranslateTimeline.X] = x; + this.frames[frameIndex + TranslateTimeline.Y] = y; + }; + TranslateTimeline.prototype.apply = function (skeleton, lastTime, time, events, alpha, setupPose, mixingOut) { + var frames = this.frames; + var bone = skeleton.bones[this.boneIndex]; + if (time < frames[0]) { + if (setupPose) { + bone.x = bone.data.x; + bone.y = bone.data.y; + } + return; + } + var x = 0, y = 0; + if (time >= frames[frames.length - TranslateTimeline.ENTRIES]) { + x = frames[frames.length + TranslateTimeline.PREV_X]; + y = frames[frames.length + TranslateTimeline.PREV_Y]; + } + else { + var frame = Animation.binarySearch(frames, time, TranslateTimeline.ENTRIES); + x = frames[frame + TranslateTimeline.PREV_X]; + y = frames[frame + TranslateTimeline.PREV_Y]; + var frameTime = frames[frame]; + var percent = this.getCurvePercent(frame / TranslateTimeline.ENTRIES - 1, 1 - (time - frameTime) / (frames[frame + TranslateTimeline.PREV_TIME] - frameTime)); + x += (frames[frame + TranslateTimeline.X] - x) * percent; + y += (frames[frame + TranslateTimeline.Y] - y) * percent; + } + if (setupPose) { + bone.x = bone.data.x + x * alpha; + bone.y = bone.data.y + y * alpha; + } + else { + bone.x += (bone.data.x + x - bone.x) * alpha; + bone.y += (bone.data.y + y - bone.y) * alpha; + } + }; + TranslateTimeline.ENTRIES = 3; + TranslateTimeline.PREV_TIME = -3; + TranslateTimeline.PREV_X = -2; + TranslateTimeline.PREV_Y = -1; + TranslateTimeline.X = 1; + TranslateTimeline.Y = 2; + return TranslateTimeline; + }(CurveTimeline)); + spine.TranslateTimeline = TranslateTimeline; + var ScaleTimeline = (function (_super) { + __extends(ScaleTimeline, _super); + function ScaleTimeline(frameCount) { + _super.call(this, frameCount); + } + ScaleTimeline.prototype.getPropertyId = function () { + return (TimelineType.scale << 24) + this.boneIndex; + }; + ScaleTimeline.prototype.apply = function (skeleton, lastTime, time, events, alpha, setupPose, mixingOut) { + var frames = this.frames; + var bone = skeleton.bones[this.boneIndex]; + if (time < frames[0]) { + if (setupPose) { + bone.scaleX = bone.data.scaleX; + bone.scaleY = bone.data.scaleY; + } + return; + } + var x = 0, y = 0; + if (time >= frames[frames.length - ScaleTimeline.ENTRIES]) { + x = frames[frames.length + ScaleTimeline.PREV_X] * bone.data.scaleX; + y = frames[frames.length + ScaleTimeline.PREV_Y] * bone.data.scaleY; + } + else { + var frame = Animation.binarySearch(frames, time, ScaleTimeline.ENTRIES); + x = frames[frame + ScaleTimeline.PREV_X]; + y = frames[frame + ScaleTimeline.PREV_Y]; + var frameTime = frames[frame]; + var percent = this.getCurvePercent(frame / ScaleTimeline.ENTRIES - 1, 1 - (time - frameTime) / (frames[frame + ScaleTimeline.PREV_TIME] - frameTime)); + x = (x + (frames[frame + ScaleTimeline.X] - x) * percent) * bone.data.scaleX; + y = (y + (frames[frame + ScaleTimeline.Y] - y) * percent) * bone.data.scaleY; + } + if (alpha == 1) { + bone.scaleX = x; + bone.scaleY = y; + } + else { + var bx = 0, by = 0; + if (setupPose) { + bx = bone.data.scaleX; + by = bone.data.scaleY; + } + else { + bx = bone.scaleX; + by = bone.scaleY; + } + if (mixingOut) { + x = Math.abs(x) * spine.MathUtils.signum(bx); + y = Math.abs(y) * spine.MathUtils.signum(by); + } + else { + bx = Math.abs(bx) * spine.MathUtils.signum(x); + by = Math.abs(by) * spine.MathUtils.signum(y); + } + bone.scaleX = bx + (x - bx) * alpha; + bone.scaleY = by + (y - by) * alpha; + } + }; + return ScaleTimeline; + }(TranslateTimeline)); + spine.ScaleTimeline = ScaleTimeline; + var ShearTimeline = (function (_super) { + __extends(ShearTimeline, _super); + function ShearTimeline(frameCount) { + _super.call(this, frameCount); + } + ShearTimeline.prototype.getPropertyId = function () { + return (TimelineType.shear << 24) + this.boneIndex; + }; + ShearTimeline.prototype.apply = function (skeleton, lastTime, time, events, alpha, setupPose, mixingOut) { + var frames = this.frames; + var bone = skeleton.bones[this.boneIndex]; + if (time < frames[0]) { + if (setupPose) { + bone.shearX = bone.data.shearX; + bone.shearY = bone.data.shearY; + } + return; + } + var x = 0, y = 0; + if (time >= frames[frames.length - ShearTimeline.ENTRIES]) { + x = frames[frames.length + ShearTimeline.PREV_X]; + y = frames[frames.length + ShearTimeline.PREV_Y]; + } + else { + var frame = Animation.binarySearch(frames, time, ShearTimeline.ENTRIES); + x = frames[frame + ShearTimeline.PREV_X]; + y = frames[frame + ShearTimeline.PREV_Y]; + var frameTime = frames[frame]; + var percent = this.getCurvePercent(frame / ShearTimeline.ENTRIES - 1, 1 - (time - frameTime) / (frames[frame + ShearTimeline.PREV_TIME] - frameTime)); + x = x + (frames[frame + ShearTimeline.X] - x) * percent; + y = y + (frames[frame + ShearTimeline.Y] - y) * percent; + } + if (setupPose) { + bone.shearX = bone.data.shearX + x * alpha; + bone.shearY = bone.data.shearY + y * alpha; + } + else { + bone.shearX += (bone.data.shearX + x - bone.shearX) * alpha; + bone.shearY += (bone.data.shearY + y - bone.shearY) * alpha; + } + }; + return ShearTimeline; + }(TranslateTimeline)); + spine.ShearTimeline = ShearTimeline; + var ColorTimeline = (function (_super) { + __extends(ColorTimeline, _super); + function ColorTimeline(frameCount) { + _super.call(this, frameCount); + this.frames = spine.Utils.newFloatArray(frameCount * ColorTimeline.ENTRIES); + } + ColorTimeline.prototype.getPropertyId = function () { + return (TimelineType.color << 24) + this.slotIndex; + }; + ColorTimeline.prototype.setFrame = function (frameIndex, time, r, g, b, a) { + frameIndex *= ColorTimeline.ENTRIES; + this.frames[frameIndex] = time; + this.frames[frameIndex + ColorTimeline.R] = r; + this.frames[frameIndex + ColorTimeline.G] = g; + this.frames[frameIndex + ColorTimeline.B] = b; + this.frames[frameIndex + ColorTimeline.A] = a; + }; + ColorTimeline.prototype.apply = function (skeleton, lastTime, time, events, alpha, setupPose, mixingOut) { + var slot = skeleton.slots[this.slotIndex]; + var frames = this.frames; + if (time < frames[0]) { + if (setupPose) + slot.color.setFromColor(slot.data.color); + return; + } + var r = 0, g = 0, b = 0, a = 0; + if (time >= frames[frames.length - ColorTimeline.ENTRIES]) { + var i = frames.length; + r = frames[i + ColorTimeline.PREV_R]; + g = frames[i + ColorTimeline.PREV_G]; + b = frames[i + ColorTimeline.PREV_B]; + a = frames[i + ColorTimeline.PREV_A]; + } + else { + var frame = Animation.binarySearch(frames, time, ColorTimeline.ENTRIES); + r = frames[frame + ColorTimeline.PREV_R]; + g = frames[frame + ColorTimeline.PREV_G]; + b = frames[frame + ColorTimeline.PREV_B]; + a = frames[frame + ColorTimeline.PREV_A]; + var frameTime = frames[frame]; + var percent = this.getCurvePercent(frame / ColorTimeline.ENTRIES - 1, 1 - (time - frameTime) / (frames[frame + ColorTimeline.PREV_TIME] - frameTime)); + r += (frames[frame + ColorTimeline.R] - r) * percent; + g += (frames[frame + ColorTimeline.G] - g) * percent; + b += (frames[frame + ColorTimeline.B] - b) * percent; + a += (frames[frame + ColorTimeline.A] - a) * percent; + } + if (alpha == 1) + slot.color.set(r, g, b, a); + else { + var color = slot.color; + if (setupPose) + color.setFromColor(slot.data.color); + color.add((r - color.r) * alpha, (g - color.g) * alpha, (b - color.b) * alpha, (a - color.a) * alpha); + } + }; + ColorTimeline.ENTRIES = 5; + ColorTimeline.PREV_TIME = -5; + ColorTimeline.PREV_R = -4; + ColorTimeline.PREV_G = -3; + ColorTimeline.PREV_B = -2; + ColorTimeline.PREV_A = -1; + ColorTimeline.R = 1; + ColorTimeline.G = 2; + ColorTimeline.B = 3; + ColorTimeline.A = 4; + return ColorTimeline; + }(CurveTimeline)); + spine.ColorTimeline = ColorTimeline; + var AttachmentTimeline = (function () { + function AttachmentTimeline(frameCount) { + this.frames = spine.Utils.newFloatArray(frameCount); + this.attachmentNames = new Array(frameCount); + } + AttachmentTimeline.prototype.getPropertyId = function () { + return (TimelineType.attachment << 24) + this.slotIndex; + }; + AttachmentTimeline.prototype.getFrameCount = function () { + return this.frames.length; + }; + AttachmentTimeline.prototype.setFrame = function (frameIndex, time, attachmentName) { + this.frames[frameIndex] = time; + this.attachmentNames[frameIndex] = attachmentName; + }; + AttachmentTimeline.prototype.apply = function (skeleton, lastTime, time, events, alpha, setupPose, mixingOut) { + var slot = skeleton.slots[this.slotIndex]; + if (mixingOut && setupPose) { + var attachmentName_1 = slot.data.attachmentName; + slot.setAttachment(attachmentName_1 == null ? null : skeleton.getAttachment(this.slotIndex, attachmentName_1)); + return; + } + var frames = this.frames; + if (time < frames[0]) { + if (setupPose) { + var attachmentName_2 = slot.data.attachmentName; + slot.setAttachment(attachmentName_2 == null ? null : skeleton.getAttachment(this.slotIndex, attachmentName_2)); + } + return; + } + var frameIndex = 0; + if (time >= frames[frames.length - 1]) + frameIndex = frames.length - 1; + else + frameIndex = Animation.binarySearch(frames, time, 1) - 1; + var attachmentName = this.attachmentNames[frameIndex]; + skeleton.slots[this.slotIndex] + .setAttachment(attachmentName == null ? null : skeleton.getAttachment(this.slotIndex, attachmentName)); + }; + return AttachmentTimeline; + }()); + spine.AttachmentTimeline = AttachmentTimeline; + var DeformTimeline = (function (_super) { + __extends(DeformTimeline, _super); + function DeformTimeline(frameCount) { + _super.call(this, frameCount); + this.frames = spine.Utils.newFloatArray(frameCount); + this.frameVertices = new Array(frameCount); + } + DeformTimeline.prototype.getPropertyId = function () { + return (TimelineType.deform << 24) + this.slotIndex; + }; + DeformTimeline.prototype.setFrame = function (frameIndex, time, vertices) { + this.frames[frameIndex] = time; + this.frameVertices[frameIndex] = vertices; + }; + DeformTimeline.prototype.apply = function (skeleton, lastTime, time, firedEvents, alpha, setupPose, mixingOut) { + var slot = skeleton.slots[this.slotIndex]; + var slotAttachment = slot.getAttachment(); + if (!(slotAttachment instanceof spine.VertexAttachment) || !slotAttachment.applyDeform(this.attachment)) + return; + var frames = this.frames; + var verticesArray = slot.attachmentVertices; + if (time < frames[0]) { + if (setupPose) + spine.Utils.setArraySize(verticesArray, 0); + return; + } + var frameVertices = this.frameVertices; + var vertexCount = frameVertices[0].length; + if (verticesArray.length != vertexCount) + alpha = 1; + var vertices = spine.Utils.setArraySize(verticesArray, vertexCount); + if (time >= frames[frames.length - 1]) { + var lastVertices = frameVertices[frames.length - 1]; + if (alpha == 1) { + spine.Utils.arrayCopy(lastVertices, 0, vertices, 0, vertexCount); + } + else if (setupPose) { + var vertexAttachment = slotAttachment; + if (vertexAttachment.bones == null) { + var setupVertices = vertexAttachment.vertices; + for (var i = 0; i < vertexCount; i++) { + var setup = setupVertices[i]; + vertices[i] = setup + (lastVertices[i] - setup) * alpha; + } + } + else { + for (var i = 0; i < vertexCount; i++) + vertices[i] = lastVertices[i] * alpha; + } + } + else { + for (var i = 0; i < vertexCount; i++) + vertices[i] += (lastVertices[i] - vertices[i]) * alpha; + } + return; + } + var frame = Animation.binarySearch(frames, time); + var prevVertices = frameVertices[frame - 1]; + var nextVertices = frameVertices[frame]; + var frameTime = frames[frame]; + var percent = this.getCurvePercent(frame - 1, 1 - (time - frameTime) / (frames[frame - 1] - frameTime)); + if (alpha == 1) { + for (var i = 0; i < vertexCount; i++) { + var prev = prevVertices[i]; + vertices[i] = prev + (nextVertices[i] - prev) * percent; + } + } + else if (setupPose) { + var vertexAttachment = slotAttachment; + if (vertexAttachment.bones == null) { + var setupVertices = vertexAttachment.vertices; + for (var i = 0; i < vertexCount; i++) { + var prev = prevVertices[i], setup = setupVertices[i]; + vertices[i] = setup + (prev + (nextVertices[i] - prev) * percent - setup) * alpha; + } + } + else { + for (var i = 0; i < vertexCount; i++) { + var prev = prevVertices[i]; + vertices[i] = (prev + (nextVertices[i] - prev) * percent) * alpha; + } + } + } + else { + for (var i = 0; i < vertexCount; i++) { + var prev = prevVertices[i]; + vertices[i] += (prev + (nextVertices[i] - prev) * percent - vertices[i]) * alpha; + } + } + }; + return DeformTimeline; + }(CurveTimeline)); + spine.DeformTimeline = DeformTimeline; + var EventTimeline = (function () { + function EventTimeline(frameCount) { + this.frames = spine.Utils.newFloatArray(frameCount); + this.events = new Array(frameCount); + } + EventTimeline.prototype.getPropertyId = function () { + return TimelineType.event << 24; + }; + EventTimeline.prototype.getFrameCount = function () { + return this.frames.length; + }; + EventTimeline.prototype.setFrame = function (frameIndex, event) { + this.frames[frameIndex] = event.time; + this.events[frameIndex] = event; + }; + EventTimeline.prototype.apply = function (skeleton, lastTime, time, firedEvents, alpha, setupPose, mixingOut) { + if (firedEvents == null) + return; + var frames = this.frames; + var frameCount = this.frames.length; + if (lastTime > time) { + this.apply(skeleton, lastTime, Number.MAX_VALUE, firedEvents, alpha, setupPose, mixingOut); + lastTime = -1; + } + else if (lastTime >= frames[frameCount - 1]) + return; + if (time < frames[0]) + return; + var frame = 0; + if (lastTime < frames[0]) + frame = 0; + else { + frame = Animation.binarySearch(frames, lastTime); + var frameTime = frames[frame]; + while (frame > 0) { + if (frames[frame - 1] != frameTime) + break; + frame--; + } + } + for (; frame < frameCount && time >= frames[frame]; frame++) + firedEvents.push(this.events[frame]); + }; + return EventTimeline; + }()); + spine.EventTimeline = EventTimeline; + var DrawOrderTimeline = (function () { + function DrawOrderTimeline(frameCount) { + this.frames = spine.Utils.newFloatArray(frameCount); + this.drawOrders = new Array(frameCount); + } + DrawOrderTimeline.prototype.getPropertyId = function () { + return TimelineType.drawOrder << 24; + }; + DrawOrderTimeline.prototype.getFrameCount = function () { + return this.frames.length; + }; + DrawOrderTimeline.prototype.setFrame = function (frameIndex, time, drawOrder) { + this.frames[frameIndex] = time; + this.drawOrders[frameIndex] = drawOrder; + }; + DrawOrderTimeline.prototype.apply = function (skeleton, lastTime, time, firedEvents, alpha, setupPose, mixingOut) { + var drawOrder = skeleton.drawOrder; + var slots = skeleton.slots; + if (mixingOut && setupPose) { + spine.Utils.arrayCopy(skeleton.slots, 0, skeleton.drawOrder, 0, skeleton.slots.length); + return; + } + var frames = this.frames; + if (time < frames[0]) { + if (setupPose) + spine.Utils.arrayCopy(skeleton.slots, 0, skeleton.drawOrder, 0, skeleton.slots.length); + return; + } + var frame = 0; + if (time >= frames[frames.length - 1]) + frame = frames.length - 1; + else + frame = Animation.binarySearch(frames, time) - 1; + var drawOrderToSetupIndex = this.drawOrders[frame]; + if (drawOrderToSetupIndex == null) + spine.Utils.arrayCopy(slots, 0, drawOrder, 0, slots.length); + else { + for (var i = 0, n = drawOrderToSetupIndex.length; i < n; i++) + drawOrder[i] = slots[drawOrderToSetupIndex[i]]; + } + }; + return DrawOrderTimeline; + }()); + spine.DrawOrderTimeline = DrawOrderTimeline; + var IkConstraintTimeline = (function (_super) { + __extends(IkConstraintTimeline, _super); + function IkConstraintTimeline(frameCount) { + _super.call(this, frameCount); + this.frames = spine.Utils.newFloatArray(frameCount * IkConstraintTimeline.ENTRIES); + } + IkConstraintTimeline.prototype.getPropertyId = function () { + return (TimelineType.ikConstraint << 24) + this.ikConstraintIndex; + }; + IkConstraintTimeline.prototype.setFrame = function (frameIndex, time, mix, bendDirection) { + frameIndex *= IkConstraintTimeline.ENTRIES; + this.frames[frameIndex] = time; + this.frames[frameIndex + IkConstraintTimeline.MIX] = mix; + this.frames[frameIndex + IkConstraintTimeline.BEND_DIRECTION] = bendDirection; + }; + IkConstraintTimeline.prototype.apply = function (skeleton, lastTime, time, firedEvents, alpha, setupPose, mixingOut) { + var frames = this.frames; + var constraint = skeleton.ikConstraints[this.ikConstraintIndex]; + if (time < frames[0]) { + if (setupPose) { + constraint.mix = constraint.data.mix; + constraint.bendDirection = constraint.data.bendDirection; + } + return; + } + if (time >= frames[frames.length - IkConstraintTimeline.ENTRIES]) { + if (setupPose) { + constraint.mix = constraint.data.mix + (frames[frames.length + IkConstraintTimeline.PREV_MIX] - constraint.data.mix) * alpha; + constraint.bendDirection = mixingOut ? constraint.data.bendDirection + : frames[frames.length + IkConstraintTimeline.PREV_BEND_DIRECTION]; + } + else { + constraint.mix += (frames[frames.length + IkConstraintTimeline.PREV_MIX] - constraint.mix) * alpha; + if (!mixingOut) + constraint.bendDirection = frames[frames.length + IkConstraintTimeline.PREV_BEND_DIRECTION]; + } + return; + } + var frame = Animation.binarySearch(frames, time, IkConstraintTimeline.ENTRIES); + var mix = frames[frame + IkConstraintTimeline.PREV_MIX]; + var frameTime = frames[frame]; + var percent = this.getCurvePercent(frame / IkConstraintTimeline.ENTRIES - 1, 1 - (time - frameTime) / (frames[frame + IkConstraintTimeline.PREV_TIME] - frameTime)); + if (setupPose) { + constraint.mix = constraint.data.mix + (mix + (frames[frame + IkConstraintTimeline.MIX] - mix) * percent - constraint.data.mix) * alpha; + constraint.bendDirection = mixingOut ? constraint.data.bendDirection : frames[frame + IkConstraintTimeline.PREV_BEND_DIRECTION]; + } + else { + constraint.mix += (mix + (frames[frame + IkConstraintTimeline.MIX] - mix) * percent - constraint.mix) * alpha; + if (!mixingOut) + constraint.bendDirection = frames[frame + IkConstraintTimeline.PREV_BEND_DIRECTION]; + } + }; + IkConstraintTimeline.ENTRIES = 3; + IkConstraintTimeline.PREV_TIME = -3; + IkConstraintTimeline.PREV_MIX = -2; + IkConstraintTimeline.PREV_BEND_DIRECTION = -1; + IkConstraintTimeline.MIX = 1; + IkConstraintTimeline.BEND_DIRECTION = 2; + return IkConstraintTimeline; + }(CurveTimeline)); + spine.IkConstraintTimeline = IkConstraintTimeline; + var TransformConstraintTimeline = (function (_super) { + __extends(TransformConstraintTimeline, _super); + function TransformConstraintTimeline(frameCount) { + _super.call(this, frameCount); + this.frames = spine.Utils.newFloatArray(frameCount * TransformConstraintTimeline.ENTRIES); + } + TransformConstraintTimeline.prototype.getPropertyId = function () { + return (TimelineType.transformConstraint << 24) + this.transformConstraintIndex; + }; + TransformConstraintTimeline.prototype.setFrame = function (frameIndex, time, rotateMix, translateMix, scaleMix, shearMix) { + frameIndex *= TransformConstraintTimeline.ENTRIES; + this.frames[frameIndex] = time; + this.frames[frameIndex + TransformConstraintTimeline.ROTATE] = rotateMix; + this.frames[frameIndex + TransformConstraintTimeline.TRANSLATE] = translateMix; + this.frames[frameIndex + TransformConstraintTimeline.SCALE] = scaleMix; + this.frames[frameIndex + TransformConstraintTimeline.SHEAR] = shearMix; + }; + TransformConstraintTimeline.prototype.apply = function (skeleton, lastTime, time, firedEvents, alpha, setupPose, mixingOut) { + var frames = this.frames; + var constraint = skeleton.transformConstraints[this.transformConstraintIndex]; + if (time < frames[0]) { + if (setupPose) { + var data = constraint.data; + constraint.rotateMix = data.rotateMix; + constraint.translateMix = data.rotateMix; + constraint.scaleMix = data.scaleMix; + constraint.shearMix = data.shearMix; + } + return; + } + var rotate = 0, translate = 0, scale = 0, shear = 0; + if (time >= frames[frames.length - TransformConstraintTimeline.ENTRIES]) { + var i = frames.length; + rotate = frames[i + TransformConstraintTimeline.PREV_ROTATE]; + translate = frames[i + TransformConstraintTimeline.PREV_TRANSLATE]; + scale = frames[i + TransformConstraintTimeline.PREV_SCALE]; + shear = frames[i + TransformConstraintTimeline.PREV_SHEAR]; + } + else { + var frame = Animation.binarySearch(frames, time, TransformConstraintTimeline.ENTRIES); + rotate = frames[frame + TransformConstraintTimeline.PREV_ROTATE]; + translate = frames[frame + TransformConstraintTimeline.PREV_TRANSLATE]; + scale = frames[frame + TransformConstraintTimeline.PREV_SCALE]; + shear = frames[frame + TransformConstraintTimeline.PREV_SHEAR]; + var frameTime = frames[frame]; + var percent = this.getCurvePercent(frame / TransformConstraintTimeline.ENTRIES - 1, 1 - (time - frameTime) / (frames[frame + TransformConstraintTimeline.PREV_TIME] - frameTime)); + rotate += (frames[frame + TransformConstraintTimeline.ROTATE] - rotate) * percent; + translate += (frames[frame + TransformConstraintTimeline.TRANSLATE] - translate) * percent; + scale += (frames[frame + TransformConstraintTimeline.SCALE] - scale) * percent; + shear += (frames[frame + TransformConstraintTimeline.SHEAR] - shear) * percent; + } + if (setupPose) { + var data = constraint.data; + constraint.rotateMix = data.rotateMix + (rotate - data.rotateMix) * alpha; + constraint.translateMix = data.translateMix + (translate - data.translateMix) * alpha; + constraint.scaleMix = data.scaleMix + (scale - data.scaleMix) * alpha; + constraint.shearMix = data.shearMix + (shear - data.shearMix) * alpha; + } + else { + constraint.rotateMix += (rotate - constraint.rotateMix) * alpha; + constraint.translateMix += (translate - constraint.translateMix) * alpha; + constraint.scaleMix += (scale - constraint.scaleMix) * alpha; + constraint.shearMix += (shear - constraint.shearMix) * alpha; + } + }; + TransformConstraintTimeline.ENTRIES = 5; + TransformConstraintTimeline.PREV_TIME = -5; + TransformConstraintTimeline.PREV_ROTATE = -4; + TransformConstraintTimeline.PREV_TRANSLATE = -3; + TransformConstraintTimeline.PREV_SCALE = -2; + TransformConstraintTimeline.PREV_SHEAR = -1; + TransformConstraintTimeline.ROTATE = 1; + TransformConstraintTimeline.TRANSLATE = 2; + TransformConstraintTimeline.SCALE = 3; + TransformConstraintTimeline.SHEAR = 4; + return TransformConstraintTimeline; + }(CurveTimeline)); + spine.TransformConstraintTimeline = TransformConstraintTimeline; + var PathConstraintPositionTimeline = (function (_super) { + __extends(PathConstraintPositionTimeline, _super); + function PathConstraintPositionTimeline(frameCount) { + _super.call(this, frameCount); + this.frames = spine.Utils.newFloatArray(frameCount * PathConstraintPositionTimeline.ENTRIES); + } + PathConstraintPositionTimeline.prototype.getPropertyId = function () { + return (TimelineType.pathConstraintPosition << 24) + this.pathConstraintIndex; + }; + PathConstraintPositionTimeline.prototype.setFrame = function (frameIndex, time, value) { + frameIndex *= PathConstraintPositionTimeline.ENTRIES; + this.frames[frameIndex] = time; + this.frames[frameIndex + PathConstraintPositionTimeline.VALUE] = value; + }; + PathConstraintPositionTimeline.prototype.apply = function (skeleton, lastTime, time, firedEvents, alpha, setupPose, mixingOut) { + var frames = this.frames; + var constraint = skeleton.pathConstraints[this.pathConstraintIndex]; + if (time < frames[0]) { + if (setupPose) + constraint.position = constraint.data.position; + return; + } + var position = 0; + if (time >= frames[frames.length - PathConstraintPositionTimeline.ENTRIES]) + position = frames[frames.length + PathConstraintPositionTimeline.PREV_VALUE]; + else { + var frame = Animation.binarySearch(frames, time, PathConstraintPositionTimeline.ENTRIES); + position = frames[frame + PathConstraintPositionTimeline.PREV_VALUE]; + var frameTime = frames[frame]; + var percent = this.getCurvePercent(frame / PathConstraintPositionTimeline.ENTRIES - 1, 1 - (time - frameTime) / (frames[frame + PathConstraintPositionTimeline.PREV_TIME] - frameTime)); + position += (frames[frame + PathConstraintPositionTimeline.VALUE] - position) * percent; + } + if (setupPose) + constraint.position = constraint.data.position + (position - constraint.data.position) * alpha; + else + constraint.position += (position - constraint.position) * alpha; + }; + PathConstraintPositionTimeline.ENTRIES = 2; + PathConstraintPositionTimeline.PREV_TIME = -2; + PathConstraintPositionTimeline.PREV_VALUE = -1; + PathConstraintPositionTimeline.VALUE = 1; + return PathConstraintPositionTimeline; + }(CurveTimeline)); + spine.PathConstraintPositionTimeline = PathConstraintPositionTimeline; + var PathConstraintSpacingTimeline = (function (_super) { + __extends(PathConstraintSpacingTimeline, _super); + function PathConstraintSpacingTimeline(frameCount) { + _super.call(this, frameCount); + } + PathConstraintSpacingTimeline.prototype.getPropertyId = function () { + return (TimelineType.pathConstraintSpacing << 24) + this.pathConstraintIndex; + }; + PathConstraintSpacingTimeline.prototype.apply = function (skeleton, lastTime, time, firedEvents, alpha, setupPose, mixingOut) { + var frames = this.frames; + var constraint = skeleton.pathConstraints[this.pathConstraintIndex]; + if (time < frames[0]) { + if (setupPose) + constraint.spacing = constraint.data.spacing; + return; + } + var spacing = 0; + if (time >= frames[frames.length - PathConstraintSpacingTimeline.ENTRIES]) + spacing = frames[frames.length + PathConstraintSpacingTimeline.PREV_VALUE]; + else { + var frame = Animation.binarySearch(frames, time, PathConstraintSpacingTimeline.ENTRIES); + spacing = frames[frame + PathConstraintSpacingTimeline.PREV_VALUE]; + var frameTime = frames[frame]; + var percent = this.getCurvePercent(frame / PathConstraintSpacingTimeline.ENTRIES - 1, 1 - (time - frameTime) / (frames[frame + PathConstraintSpacingTimeline.PREV_TIME] - frameTime)); + spacing += (frames[frame + PathConstraintSpacingTimeline.VALUE] - spacing) * percent; + } + if (setupPose) + constraint.spacing = constraint.data.spacing + (spacing - constraint.data.spacing) * alpha; + else + constraint.spacing += (spacing - constraint.spacing) * alpha; + }; + return PathConstraintSpacingTimeline; + }(PathConstraintPositionTimeline)); + spine.PathConstraintSpacingTimeline = PathConstraintSpacingTimeline; + var PathConstraintMixTimeline = (function (_super) { + __extends(PathConstraintMixTimeline, _super); + function PathConstraintMixTimeline(frameCount) { + _super.call(this, frameCount); + this.frames = spine.Utils.newFloatArray(frameCount * PathConstraintMixTimeline.ENTRIES); + } + PathConstraintMixTimeline.prototype.getPropertyId = function () { + return (TimelineType.pathConstraintMix << 24) + this.pathConstraintIndex; + }; + PathConstraintMixTimeline.prototype.setFrame = function (frameIndex, time, rotateMix, translateMix) { + frameIndex *= PathConstraintMixTimeline.ENTRIES; + this.frames[frameIndex] = time; + this.frames[frameIndex + PathConstraintMixTimeline.ROTATE] = rotateMix; + this.frames[frameIndex + PathConstraintMixTimeline.TRANSLATE] = translateMix; + }; + PathConstraintMixTimeline.prototype.apply = function (skeleton, lastTime, time, firedEvents, alpha, setupPose, mixingOut) { + var frames = this.frames; + var constraint = skeleton.pathConstraints[this.pathConstraintIndex]; + if (time < frames[0]) { + if (setupPose) { + constraint.rotateMix = constraint.data.rotateMix; + constraint.translateMix = constraint.data.translateMix; + } + return; + } + var rotate = 0, translate = 0; + if (time >= frames[frames.length - PathConstraintMixTimeline.ENTRIES]) { + rotate = frames[frames.length + PathConstraintMixTimeline.PREV_ROTATE]; + translate = frames[frames.length + PathConstraintMixTimeline.PREV_TRANSLATE]; + } + else { + var frame = Animation.binarySearch(frames, time, PathConstraintMixTimeline.ENTRIES); + rotate = frames[frame + PathConstraintMixTimeline.PREV_ROTATE]; + translate = frames[frame + PathConstraintMixTimeline.PREV_TRANSLATE]; + var frameTime = frames[frame]; + var percent = this.getCurvePercent(frame / PathConstraintMixTimeline.ENTRIES - 1, 1 - (time - frameTime) / (frames[frame + PathConstraintMixTimeline.PREV_TIME] - frameTime)); + rotate += (frames[frame + PathConstraintMixTimeline.ROTATE] - rotate) * percent; + translate += (frames[frame + PathConstraintMixTimeline.TRANSLATE] - translate) * percent; + } + if (setupPose) { + constraint.rotateMix = constraint.data.rotateMix + (rotate - constraint.data.rotateMix) * alpha; + constraint.translateMix = constraint.data.translateMix + (translate - constraint.data.translateMix) * alpha; + } + else { + constraint.rotateMix += (rotate - constraint.rotateMix) * alpha; + constraint.translateMix += (translate - constraint.translateMix) * alpha; + } + }; + PathConstraintMixTimeline.ENTRIES = 3; + PathConstraintMixTimeline.PREV_TIME = -3; + PathConstraintMixTimeline.PREV_ROTATE = -2; + PathConstraintMixTimeline.PREV_TRANSLATE = -1; + PathConstraintMixTimeline.ROTATE = 1; + PathConstraintMixTimeline.TRANSLATE = 2; + return PathConstraintMixTimeline; + }(CurveTimeline)); + spine.PathConstraintMixTimeline = PathConstraintMixTimeline; +})(spine || (spine = {})); +var spine; +(function (spine) { + var AnimationState = (function () { + function AnimationState(data) { + this.tracks = new Array(); + this.events = new Array(); + this.listeners = new Array(); + this.queue = new EventQueue(this); + this.propertyIDs = new spine.IntSet(); + this.animationsChanged = false; + this.timeScale = 1; + this.trackEntryPool = new spine.Pool(function () { return new TrackEntry(); }); + this.data = data; + } + AnimationState.prototype.update = function (delta) { + delta *= this.timeScale; + var tracks = this.tracks; + for (var i = 0, n = tracks.length; i < n; i++) { + var current = tracks[i]; + if (current == null) + continue; + current.animationLast = current.nextAnimationLast; + current.trackLast = current.nextTrackLast; + var currentDelta = delta * current.timeScale; + if (current.delay > 0) { + current.delay -= currentDelta; + if (current.delay > 0) + continue; + currentDelta = -current.delay; + current.delay = 0; + } + var next = current.next; + if (next != null) { + var nextTime = current.trackLast - next.delay; + if (nextTime >= 0) { + next.delay = 0; + next.trackTime = nextTime + delta * next.timeScale; + current.trackTime += currentDelta; + this.setCurrent(i, next, true); + while (next.mixingFrom != null) { + next.mixTime += currentDelta; + next = next.mixingFrom; + } + continue; + } + } + else { + if (current.trackLast >= current.trackEnd && current.mixingFrom == null) { + tracks[i] = null; + this.queue.end(current); + this.disposeNext(current); + continue; + } + } + this.updateMixingFrom(current, delta); + current.trackTime += currentDelta; + } + this.queue.drain(); + }; + AnimationState.prototype.updateMixingFrom = function (entry, delta) { + var from = entry.mixingFrom; + if (from == null) + return; + this.updateMixingFrom(from, delta); + if (entry.mixTime >= entry.mixDuration && from.mixingFrom != null && entry.mixTime > 0) { + entry.mixingFrom = null; + this.queue.end(from); + return; + } + from.animationLast = from.nextAnimationLast; + from.trackLast = from.nextTrackLast; + from.trackTime += delta * from.timeScale; + entry.mixTime += delta * from.timeScale; + }; + AnimationState.prototype.apply = function (skeleton) { + if (skeleton == null) + throw new Error("skeleton cannot be null."); + if (this.animationsChanged) + this._animationsChanged(); + var events = this.events; + var tracks = this.tracks; + for (var i = 0, n = tracks.length; i < n; i++) { + var current = tracks[i]; + if (current == null || current.delay > 0) + continue; + var mix = current.alpha; + if (current.mixingFrom != null) + mix *= this.applyMixingFrom(current, skeleton); + else if (current.trackTime >= current.trackEnd) + mix = 0; + var animationLast = current.animationLast, animationTime = current.getAnimationTime(); + var timelineCount = current.animation.timelines.length; + var timelines = current.animation.timelines; + if (mix == 1) { + for (var ii = 0; ii < timelineCount; ii++) + timelines[ii].apply(skeleton, animationLast, animationTime, events, 1, true, false); + } + else { + var firstFrame = current.timelinesRotation.length == 0; + if (firstFrame) + spine.Utils.setArraySize(current.timelinesRotation, timelineCount << 1, null); + var timelinesRotation = current.timelinesRotation; + var timelinesFirst = current.timelinesFirst; + for (var ii = 0; ii < timelineCount; ii++) { + var timeline = timelines[ii]; + if (timeline instanceof spine.RotateTimeline) { + this.applyRotateTimeline(timeline, skeleton, animationTime, mix, timelinesFirst[ii], timelinesRotation, ii << 1, firstFrame); + } + else + timeline.apply(skeleton, animationLast, animationTime, events, mix, timelinesFirst[ii], false); + } + } + this.queueEvents(current, animationTime); + current.nextAnimationLast = animationTime; + current.nextTrackLast = current.trackTime; + } + this.queue.drain(); + }; + AnimationState.prototype.applyMixingFrom = function (entry, skeleton) { + var from = entry.mixingFrom; + if (from.mixingFrom != null) + this.applyMixingFrom(from, skeleton); + var mix = 0; + if (entry.mixDuration == 0) + mix = 1; + else { + mix = entry.mixTime / entry.mixDuration; + if (mix > 1) + mix = 1; + } + var events = mix < from.eventThreshold ? this.events : null; + var attachments = mix < from.attachmentThreshold, drawOrder = mix < from.drawOrderThreshold; + var animationLast = from.animationLast, animationTime = from.getAnimationTime(); + var timelineCount = from.animation.timelines.length; + var timelines = from.animation.timelines; + var timelinesFirst = from.timelinesFirst; + var alpha = from.alpha * entry.mixAlpha * (1 - mix); + var firstFrame = from.timelinesRotation.length == 0; + if (firstFrame) + spine.Utils.setArraySize(from.timelinesRotation, timelineCount << 1, null); + var timelinesRotation = from.timelinesRotation; + for (var i = 0; i < timelineCount; i++) { + var timeline = timelines[i]; + var setupPose = timelinesFirst[i]; + if (timeline instanceof spine.RotateTimeline) + this.applyRotateTimeline(timeline, skeleton, animationTime, alpha, setupPose, timelinesRotation, i << 1, firstFrame); + else { + if (!setupPose) { + if (!attachments && timeline instanceof spine.AttachmentTimeline) + continue; + if (!drawOrder && timeline instanceof spine.DrawOrderTimeline) + continue; + } + timeline.apply(skeleton, animationLast, animationTime, events, alpha, setupPose, true); + } + } + this.queueEvents(from, animationTime); + from.nextAnimationLast = animationTime; + from.nextTrackLast = from.trackTime; + return mix; + }; + AnimationState.prototype.applyRotateTimeline = function (timeline, skeleton, time, alpha, setupPose, timelinesRotation, i, firstFrame) { + if (firstFrame) + timelinesRotation[i] = 0; + if (alpha == 1) { + timeline.apply(skeleton, 0, time, null, 1, setupPose, false); + return; + } + var rotateTimeline = timeline; + var frames = rotateTimeline.frames; + var bone = skeleton.bones[rotateTimeline.boneIndex]; + if (time < frames[0]) { + if (setupPose) + bone.rotation = bone.data.rotation; + return; + } + var r2 = 0; + if (time >= frames[frames.length - spine.RotateTimeline.ENTRIES]) + r2 = bone.data.rotation + frames[frames.length + spine.RotateTimeline.PREV_ROTATION]; + else { + var frame = spine.Animation.binarySearch(frames, time, spine.RotateTimeline.ENTRIES); + var prevRotation = frames[frame + spine.RotateTimeline.PREV_ROTATION]; + var frameTime = frames[frame]; + var percent = rotateTimeline.getCurvePercent((frame >> 1) - 1, 1 - (time - frameTime) / (frames[frame + spine.RotateTimeline.PREV_TIME] - frameTime)); + r2 = frames[frame + spine.RotateTimeline.ROTATION] - prevRotation; + r2 -= (16384 - ((16384.499999999996 - r2 / 360) | 0)) * 360; + r2 = prevRotation + r2 * percent + bone.data.rotation; + r2 -= (16384 - ((16384.499999999996 - r2 / 360) | 0)) * 360; + } + var r1 = setupPose ? bone.data.rotation : bone.rotation; + var total = 0, diff = r2 - r1; + if (diff == 0) { + total = timelinesRotation[i]; + } + else { + diff -= (16384 - ((16384.499999999996 - diff / 360) | 0)) * 360; + var lastTotal = 0, lastDiff = 0; + if (firstFrame) { + lastTotal = 0; + lastDiff = diff; + } + else { + lastTotal = timelinesRotation[i]; + lastDiff = timelinesRotation[i + 1]; + } + var current = diff > 0, dir = lastTotal >= 0; + if (spine.MathUtils.signum(lastDiff) != spine.MathUtils.signum(diff) && Math.abs(lastDiff) <= 90) { + if (Math.abs(lastTotal) > 180) + lastTotal += 360 * spine.MathUtils.signum(lastTotal); + dir = current; + } + total = diff + lastTotal - lastTotal % 360; + if (dir != current) + total += 360 * spine.MathUtils.signum(lastTotal); + timelinesRotation[i] = total; + } + timelinesRotation[i + 1] = diff; + r1 += total * alpha; + bone.rotation = r1 - (16384 - ((16384.499999999996 - r1 / 360) | 0)) * 360; + }; + AnimationState.prototype.queueEvents = function (entry, animationTime) { + var animationStart = entry.animationStart, animationEnd = entry.animationEnd; + var duration = animationEnd - animationStart; + var trackLastWrapped = entry.trackLast % duration; + var events = this.events; + var i = 0, n = events.length; + for (; i < n; i++) { + var event_1 = events[i]; + if (event_1.time < trackLastWrapped) + break; + if (event_1.time > animationEnd) + continue; + this.queue.event(entry, event_1); + } + if (entry.loop ? (trackLastWrapped > entry.trackTime % duration) + : (animationTime >= animationEnd && entry.animationLast < animationEnd)) { + this.queue.complete(entry); + } + for (; i < n; i++) { + var event_2 = events[i]; + if (event_2.time < animationStart) + continue; + this.queue.event(entry, events[i]); + } + this.events.length = 0; + }; + AnimationState.prototype.clearTracks = function () { + this.queue.drainDisabled = true; + for (var i = 0, n = this.tracks.length; i < n; i++) + this.clearTrack(i); + this.tracks.length = 0; + this.queue.drainDisabled = false; + this.queue.drain(); + }; + AnimationState.prototype.clearTrack = function (trackIndex) { + if (trackIndex >= this.tracks.length) + return; + var current = this.tracks[trackIndex]; + if (current == null) + return; + this.queue.end(current); + this.disposeNext(current); + var entry = current; + while (true) { + var from = entry.mixingFrom; + if (from == null) + break; + this.queue.end(from); + entry.mixingFrom = null; + entry = from; + } + this.tracks[current.trackIndex] = null; + this.queue.drain(); + }; + AnimationState.prototype.setCurrent = function (index, current, interrupt) { + var from = this.expandToIndex(index); + this.tracks[index] = current; + if (from != null) { + if (interrupt) + this.queue.interrupt(from); + current.mixingFrom = from; + current.mixTime = 0; + from.timelinesRotation.length = 0; + if (from.mixingFrom != null) + current.mixAlpha *= Math.min(from.mixTime / from.mixDuration, 1); + } + this.queue.start(current); + }; + AnimationState.prototype.setAnimation = function (trackIndex, animationName, loop) { + var animation = this.data.skeletonData.findAnimation(animationName); + if (animation == null) + throw new Error("Animation not found: " + animationName); + return this.setAnimationWith(trackIndex, animation, loop); + }; + AnimationState.prototype.setAnimationWith = function (trackIndex, animation, loop) { + if (animation == null) + throw new Error("animation cannot be null."); + var interrupt = true; + var current = this.expandToIndex(trackIndex); + if (current != null) { + if (current.nextTrackLast == -1) { + this.tracks[trackIndex] = current.mixingFrom; + this.queue.interrupt(current); + this.queue.end(current); + this.disposeNext(current); + current = current.mixingFrom; + interrupt = false; + } + else + this.disposeNext(current); + } + var entry = this.trackEntry(trackIndex, animation, loop, current); + this.setCurrent(trackIndex, entry, interrupt); + this.queue.drain(); + return entry; + }; + AnimationState.prototype.addAnimation = function (trackIndex, animationName, loop, delay) { + var animation = this.data.skeletonData.findAnimation(animationName); + if (animation == null) + throw new Error("Animation not found: " + animationName); + return this.addAnimationWith(trackIndex, animation, loop, delay); + }; + AnimationState.prototype.addAnimationWith = function (trackIndex, animation, loop, delay) { + if (animation == null) + throw new Error("animation cannot be null."); + var last = this.expandToIndex(trackIndex); + if (last != null) { + while (last.next != null) + last = last.next; + } + var entry = this.trackEntry(trackIndex, animation, loop, last); + if (last == null) { + this.setCurrent(trackIndex, entry, true); + this.queue.drain(); + } + else { + last.next = entry; + if (delay <= 0) { + var duration = last.animationEnd - last.animationStart; + if (duration != 0) + delay += duration * (1 + ((last.trackTime / duration) | 0)) - this.data.getMix(last.animation, animation); + else + delay = 0; + } + } + entry.delay = delay; + return entry; + }; + AnimationState.prototype.setEmptyAnimation = function (trackIndex, mixDuration) { + var entry = this.setAnimationWith(trackIndex, AnimationState.emptyAnimation, false); + entry.mixDuration = mixDuration; + entry.trackEnd = mixDuration; + return entry; + }; + AnimationState.prototype.addEmptyAnimation = function (trackIndex, mixDuration, delay) { + if (delay <= 0) + delay -= mixDuration; + var entry = this.addAnimationWith(trackIndex, AnimationState.emptyAnimation, false, delay); + entry.mixDuration = mixDuration; + entry.trackEnd = mixDuration; + return entry; + }; + AnimationState.prototype.setEmptyAnimations = function (mixDuration) { + this.queue.drainDisabled = true; + for (var i = 0, n = this.tracks.length; i < n; i++) { + var current = this.tracks[i]; + if (current != null) + this.setEmptyAnimation(current.trackIndex, mixDuration); + } + this.queue.drainDisabled = false; + this.queue.drain(); + }; + AnimationState.prototype.expandToIndex = function (index) { + if (index < this.tracks.length) + return this.tracks[index]; + spine.Utils.ensureArrayCapacity(this.tracks, index - this.tracks.length + 1, null); + this.tracks.length = index + 1; + return null; + }; + AnimationState.prototype.trackEntry = function (trackIndex, animation, loop, last) { + var entry = this.trackEntryPool.obtain(); + entry.trackIndex = trackIndex; + entry.animation = animation; + entry.loop = loop; + entry.eventThreshold = 0; + entry.attachmentThreshold = 0; + entry.drawOrderThreshold = 0; + entry.animationStart = 0; + entry.animationEnd = animation.duration; + entry.animationLast = -1; + entry.nextAnimationLast = -1; + entry.delay = 0; + entry.trackTime = 0; + entry.trackLast = -1; + entry.nextTrackLast = -1; + entry.trackEnd = loop ? Number.MAX_VALUE : entry.animationEnd; + entry.timeScale = 1; + entry.alpha = 1; + entry.mixAlpha = 1; + entry.mixTime = 0; + entry.mixDuration = last == null ? 0 : this.data.getMix(last.animation, animation); + return entry; + }; + AnimationState.prototype.disposeNext = function (entry) { + var next = entry.next; + while (next != null) { + this.queue.dispose(next); + next = next.next; + } + entry.next = null; + }; + AnimationState.prototype._animationsChanged = function () { + this.animationsChanged = false; + var propertyIDs = this.propertyIDs; + var i = 0, n = this.tracks.length; + propertyIDs.clear(); + for (; i < n; i++) { + var entry = this.tracks[i]; + if (entry == null) + continue; + this.setTimelinesFirst(entry); + i++; + break; + } + for (; i < n; i++) { + var entry = this.tracks[i]; + if (entry != null) + this.checkTimelinesFirst(entry); + } + }; + AnimationState.prototype.setTimelinesFirst = function (entry) { + if (entry.mixingFrom != null) { + this.setTimelinesFirst(entry.mixingFrom); + this.checkTimelinesUsage(entry, entry.timelinesFirst); + return; + } + var propertyIDs = this.propertyIDs; + var timelines = entry.animation.timelines; + var n = timelines.length; + var usage = spine.Utils.setArraySize(entry.timelinesFirst, n, false); + for (var i = 0; i < n; i++) { + propertyIDs.add(timelines[i].getPropertyId()); + usage[i] = true; + } + }; + AnimationState.prototype.checkTimelinesFirst = function (entry) { + if (entry.mixingFrom != null) + this.checkTimelinesFirst(entry.mixingFrom); + this.checkTimelinesUsage(entry, entry.timelinesFirst); + }; + AnimationState.prototype.checkTimelinesUsage = function (entry, usageArray) { + var propertyIDs = this.propertyIDs; + var timelines = entry.animation.timelines; + var n = timelines.length; + var usage = spine.Utils.setArraySize(usageArray, n); + for (var i = 0; i < n; i++) + usage[i] = propertyIDs.add(timelines[i].getPropertyId()); + }; + AnimationState.prototype.getCurrent = function (trackIndex) { + if (trackIndex >= this.tracks.length) + return null; + return this.tracks[trackIndex]; + }; + AnimationState.prototype.addListener = function (listener) { + if (listener == null) + throw new Error("listener cannot be null."); + this.listeners.push(listener); + }; + AnimationState.prototype.removeListener = function (listener) { + var index = this.listeners.indexOf(listener); + if (index >= 0) + this.listeners.splice(index, 1); + }; + AnimationState.prototype.clearListeners = function () { + this.listeners.length = 0; + }; + AnimationState.prototype.clearListenerNotifications = function () { + this.queue.clear(); + }; + AnimationState.emptyAnimation = new spine.Animation("", [], 0); + return AnimationState; + }()); + spine.AnimationState = AnimationState; + var TrackEntry = (function () { + function TrackEntry() { + this.timelinesFirst = new Array(); + this.timelinesRotation = new Array(); + } + TrackEntry.prototype.reset = function () { + this.next = null; + this.mixingFrom = null; + this.animation = null; + this.listener = null; + this.timelinesFirst.length = 0; + this.timelinesRotation.length = 0; + }; + TrackEntry.prototype.getAnimationTime = function () { + if (this.loop) { + var duration = this.animationEnd - this.animationStart; + if (duration == 0) + return this.animationStart; + return (this.trackTime % duration) + this.animationStart; + } + return Math.min(this.trackTime + this.animationStart, this.animationEnd); + }; + TrackEntry.prototype.setAnimationLast = function (animationLast) { + this.animationLast = animationLast; + this.nextAnimationLast = animationLast; + }; + TrackEntry.prototype.isComplete = function () { + return this.trackTime >= this.animationEnd - this.animationStart; + }; + TrackEntry.prototype.resetRotationDirections = function () { + this.timelinesRotation.length = 0; + }; + return TrackEntry; + }()); + spine.TrackEntry = TrackEntry; + var EventQueue = (function () { + function EventQueue(animState) { + this.objects = []; + this.drainDisabled = false; + this.animState = animState; + } + EventQueue.prototype.start = function (entry) { + this.objects.push(EventType.start); + this.objects.push(entry); + this.animState.animationsChanged = true; + }; + EventQueue.prototype.interrupt = function (entry) { + this.objects.push(EventType.interrupt); + this.objects.push(entry); + }; + EventQueue.prototype.end = function (entry) { + this.objects.push(EventType.end); + this.objects.push(entry); + this.animState.animationsChanged = true; + }; + EventQueue.prototype.dispose = function (entry) { + this.objects.push(EventType.dispose); + this.objects.push(entry); + }; + EventQueue.prototype.complete = function (entry) { + this.objects.push(EventType.complete); + this.objects.push(entry); + }; + EventQueue.prototype.event = function (entry, event) { + this.objects.push(EventType.event); + this.objects.push(entry); + this.objects.push(event); + }; + EventQueue.prototype.drain = function () { + if (this.drainDisabled) + return; + this.drainDisabled = true; + var objects = this.objects; + var listeners = this.animState.listeners; + for (var i = 0; i < objects.length; i += 2) { + var type = objects[i]; + var entry = objects[i + 1]; + switch (type) { + case EventType.start: + if (entry.listener != null && entry.listener.start) + entry.listener.start(entry); + for (var ii = 0; ii < listeners.length; ii++) + if (listeners[ii].start) + listeners[ii].start(entry); + break; + case EventType.interrupt: + if (entry.listener != null && entry.listener.interrupt) + entry.listener.interrupt(entry); + for (var ii = 0; ii < listeners.length; ii++) + if (listeners[ii].interrupt) + listeners[ii].interrupt(entry); + break; + case EventType.end: + if (entry.listener != null && entry.listener.end) + entry.listener.end(entry); + for (var ii = 0; ii < listeners.length; ii++) + if (listeners[ii].end) + listeners[ii].end(entry); + case EventType.dispose: + if (entry.listener != null && entry.listener.dispose) + entry.listener.dispose(entry); + for (var ii = 0; ii < listeners.length; ii++) + if (listeners[ii].dispose) + listeners[ii].dispose(entry); + this.animState.trackEntryPool.free(entry); + break; + case EventType.complete: + if (entry.listener != null && entry.listener.complete) + entry.listener.complete(entry); + for (var ii = 0; ii < listeners.length; ii++) + if (listeners[ii].complete) + listeners[ii].complete(entry); + break; + case EventType.event: + var event_3 = objects[i++ + 2]; + if (entry.listener != null && entry.listener.event) + entry.listener.event(entry, event_3); + for (var ii = 0; ii < listeners.length; ii++) + if (listeners[ii].event) + listeners[ii].event(entry, event_3); + break; + } + } + this.clear(); + this.drainDisabled = false; + }; + EventQueue.prototype.clear = function () { + this.objects.length = 0; + }; + return EventQueue; + }()); + spine.EventQueue = EventQueue; + (function (EventType) { + EventType[EventType["start"] = 0] = "start"; + EventType[EventType["interrupt"] = 1] = "interrupt"; + EventType[EventType["end"] = 2] = "end"; + EventType[EventType["dispose"] = 3] = "dispose"; + EventType[EventType["complete"] = 4] = "complete"; + EventType[EventType["event"] = 5] = "event"; + })(spine.EventType || (spine.EventType = {})); + var EventType = spine.EventType; + var AnimationStateAdapter2 = (function () { + function AnimationStateAdapter2() { + } + AnimationStateAdapter2.prototype.start = function (entry) { + }; + AnimationStateAdapter2.prototype.interrupt = function (entry) { + }; + AnimationStateAdapter2.prototype.end = function (entry) { + }; + AnimationStateAdapter2.prototype.dispose = function (entry) { + }; + AnimationStateAdapter2.prototype.complete = function (entry) { + }; + AnimationStateAdapter2.prototype.event = function (entry, event) { + }; + return AnimationStateAdapter2; + }()); + spine.AnimationStateAdapter2 = AnimationStateAdapter2; +})(spine || (spine = {})); +var spine; +(function (spine) { + var AnimationStateData = (function () { + function AnimationStateData(skeletonData) { + this.animationToMixTime = {}; + this.defaultMix = 0; + if (skeletonData == null) + throw new Error("skeletonData cannot be null."); + this.skeletonData = skeletonData; + } + AnimationStateData.prototype.setMix = function (fromName, toName, duration) { + var from = this.skeletonData.findAnimation(fromName); + if (from == null) + throw new Error("Animation not found: " + fromName); + var to = this.skeletonData.findAnimation(toName); + if (to == null) + throw new Error("Animation not found: " + toName); + this.setMixWith(from, to, duration); + }; + AnimationStateData.prototype.setMixWith = function (from, to, duration) { + if (from == null) + throw new Error("from cannot be null."); + if (to == null) + throw new Error("to cannot be null."); + var key = from.name + to.name; + this.animationToMixTime[key] = duration; + }; + AnimationStateData.prototype.getMix = function (from, to) { + var key = from.name + to.name; + var value = this.animationToMixTime[key]; + return value === undefined ? this.defaultMix : value; + }; + return AnimationStateData; + }()); + spine.AnimationStateData = AnimationStateData; +})(spine || (spine = {})); +var spine; +(function (spine) { + var AssetManager = (function () { + function AssetManager(textureLoader, pathPrefix) { + if (pathPrefix === void 0) { pathPrefix = ""; } + this.assets = {}; + this.errors = {}; + this.toLoad = 0; + this.loaded = 0; + this.textureLoader = textureLoader; + this.pathPrefix = pathPrefix; + } + AssetManager.prototype.loadText = function (path, success, error) { + var _this = this; + if (success === void 0) { success = null; } + if (error === void 0) { error = null; } + path = this.pathPrefix + path; + this.toLoad++; + var request = new XMLHttpRequest(); + request.onreadystatechange = function () { + if (request.readyState == XMLHttpRequest.DONE) { + if (request.status >= 200 && request.status < 300) { + _this.assets[path] = request.responseText; + if (success) + success(path, request.responseText); + } + else { + _this.errors[path] = "Couldn't load text " + path + ": status " + request.status + ", " + request.responseText; + if (error) + error(path, "Couldn't load text " + path + ": status " + request.status + ", " + request.responseText); + } + _this.toLoad--; + _this.loaded++; + } + }; + request.open("GET", path, true); + request.send(); + }; + AssetManager.prototype.loadTexture = function (path, success, error) { + var _this = this; + if (success === void 0) { success = null; } + if (error === void 0) { error = null; } + path = this.pathPrefix + path; + this.toLoad++; + var img = new Image(); + img.crossOrigin = "anonymous"; + img.src = path; + img.onload = function (ev) { + var texture = _this.textureLoader(img); + _this.assets[path] = texture; + _this.toLoad--; + _this.loaded++; + if (success) + success(path, img); + }; + img.onerror = function (ev) { + _this.errors[path] = "Couldn't load image " + path; + _this.toLoad--; + _this.loaded++; + if (error) + error(path, "Couldn't load image " + path); + }; + }; + AssetManager.prototype.get = function (path) { + path = this.pathPrefix + path; + return this.assets[path]; + }; + AssetManager.prototype.remove = function (path) { + path = this.pathPrefix + path; + var asset = this.assets[path]; + if (asset.dispose) + asset.dispose(); + this.assets[path] = null; + }; + AssetManager.prototype.removeAll = function () { + for (var key in this.assets) { + var asset = this.assets[key]; + if (asset.dispose) + asset.dispose(); + } + this.assets = {}; + }; + AssetManager.prototype.isLoadingComplete = function () { + return this.toLoad == 0; + }; + AssetManager.prototype.getToLoad = function () { + return this.toLoad; + }; + AssetManager.prototype.getLoaded = function () { + return this.loaded; + }; + AssetManager.prototype.dispose = function () { + this.removeAll(); + }; + AssetManager.prototype.hasErrors = function () { + return Object.keys(this.errors).length > 0; + }; + AssetManager.prototype.getErrors = function () { + return this.errors; + }; + return AssetManager; + }()); + spine.AssetManager = AssetManager; +})(spine || (spine = {})); +var spine; +(function (spine) { + var AtlasAttachmentLoader = (function () { + function AtlasAttachmentLoader(atlas) { + this.atlas = atlas; + } + AtlasAttachmentLoader.prototype.newRegionAttachment = function (skin, name, path) { + var region = this.atlas.findRegion(path); + if (region == null) + throw new Error("Region not found in atlas: " + path + " (region attachment: " + name + ")"); + region.renderObject = region; + var attachment = new spine.RegionAttachment(name); + attachment.setRegion(region); + return attachment; + }; + AtlasAttachmentLoader.prototype.newMeshAttachment = function (skin, name, path) { + var region = this.atlas.findRegion(path); + if (region == null) + throw new Error("Region not found in atlas: " + path + " (mesh attachment: " + name + ")"); + region.renderObject = region; + var attachment = new spine.MeshAttachment(name); + attachment.region = region; + return attachment; + }; + AtlasAttachmentLoader.prototype.newBoundingBoxAttachment = function (skin, name) { + return new spine.BoundingBoxAttachment(name); + }; + AtlasAttachmentLoader.prototype.newPathAttachment = function (skin, name) { + return new spine.PathAttachment(name); + }; + return AtlasAttachmentLoader; + }()); + spine.AtlasAttachmentLoader = AtlasAttachmentLoader; +})(spine || (spine = {})); +var spine; +(function (spine) { + var Attachment = (function () { + function Attachment(name) { + if (name == null) + throw new Error("name cannot be null."); + this.name = name; + } + return Attachment; + }()); + spine.Attachment = Attachment; + var VertexAttachment = (function (_super) { + __extends(VertexAttachment, _super); + function VertexAttachment(name) { + _super.call(this, name); + this.worldVerticesLength = 0; + } + VertexAttachment.prototype.computeWorldVertices = function (slot, worldVertices) { + this.computeWorldVerticesWith(slot, 0, this.worldVerticesLength, worldVertices, 0); + }; + VertexAttachment.prototype.computeWorldVerticesWith = function (slot, start, count, worldVertices, offset) { + count += offset; + var skeleton = slot.bone.skeleton; + var deformArray = slot.attachmentVertices; + var vertices = this.vertices; + var bones = this.bones; + if (bones == null) { + if (deformArray.length > 0) + vertices = deformArray; + var bone = slot.bone; + var x = bone.worldX; + var y = bone.worldY; + var a = bone.a, b = bone.b, c = bone.c, d = bone.d; + for (var v_1 = start, w = offset; w < count; v_1 += 2, w += 2) { + var vx = vertices[v_1], vy = vertices[v_1 + 1]; + worldVertices[w] = vx * a + vy * b + x; + worldVertices[w + 1] = vx * c + vy * d + y; + } + return; + } + var v = 0, skip = 0; + for (var i = 0; i < start; i += 2) { + var n = bones[v]; + v += n + 1; + skip += n; + } + var skeletonBones = skeleton.bones; + if (deformArray.length == 0) { + for (var w = offset, b = skip * 3; w < count; w += 2) { + var wx = 0, wy = 0; + var n = bones[v++]; + n += v; + for (; v < n; v++, b += 3) { + var bone = skeletonBones[bones[v]]; + var vx = vertices[b], vy = vertices[b + 1], weight = vertices[b + 2]; + wx += (vx * bone.a + vy * bone.b + bone.worldX) * weight; + wy += (vx * bone.c + vy * bone.d + bone.worldY) * weight; + } + worldVertices[w] = wx; + worldVertices[w + 1] = wy; + } + } + else { + var deform = deformArray; + for (var w = offset, b = skip * 3, f = skip << 1; w < count; w += 2) { + var wx = 0, wy = 0; + var n = bones[v++]; + n += v; + for (; v < n; v++, b += 3, f += 2) { + var bone = skeletonBones[bones[v]]; + var vx = vertices[b] + deform[f], vy = vertices[b + 1] + deform[f + 1], weight = vertices[b + 2]; + wx += (vx * bone.a + vy * bone.b + bone.worldX) * weight; + wy += (vx * bone.c + vy * bone.d + bone.worldY) * weight; + } + worldVertices[w] = wx; + worldVertices[w + 1] = wy; + } + } + }; + VertexAttachment.prototype.applyDeform = function (sourceAttachment) { + return this == sourceAttachment; + }; + return VertexAttachment; + }(Attachment)); + spine.VertexAttachment = VertexAttachment; +})(spine || (spine = {})); +var spine; +(function (spine) { + (function (AttachmentType) { + AttachmentType[AttachmentType["Region"] = 0] = "Region"; + AttachmentType[AttachmentType["BoundingBox"] = 1] = "BoundingBox"; + AttachmentType[AttachmentType["Mesh"] = 2] = "Mesh"; + AttachmentType[AttachmentType["LinkedMesh"] = 3] = "LinkedMesh"; + AttachmentType[AttachmentType["Path"] = 4] = "Path"; + })(spine.AttachmentType || (spine.AttachmentType = {})); + var AttachmentType = spine.AttachmentType; +})(spine || (spine = {})); +var spine; +(function (spine) { + var BoundingBoxAttachment = (function (_super) { + __extends(BoundingBoxAttachment, _super); + function BoundingBoxAttachment(name) { + _super.call(this, name); + this.color = new spine.Color(1, 1, 1, 1); + } + return BoundingBoxAttachment; + }(spine.VertexAttachment)); + spine.BoundingBoxAttachment = BoundingBoxAttachment; +})(spine || (spine = {})); +var spine; +(function (spine) { + var MeshAttachment = (function (_super) { + __extends(MeshAttachment, _super); + function MeshAttachment(name) { + _super.call(this, name); + this.color = new spine.Color(1, 1, 1, 1); + this.inheritDeform = false; + this.tempColor = new spine.Color(0, 0, 0, 0); + } + MeshAttachment.prototype.updateUVs = function () { + var regionUVs = this.regionUVs; + var verticesLength = regionUVs.length; + var worldVerticesLength = (verticesLength >> 1) * 8; + if (this.worldVertices == null || this.worldVertices.length != worldVerticesLength) + this.worldVertices = spine.Utils.newFloatArray(worldVerticesLength); + var u = 0, v = 0, width = 0, height = 0; + if (this.region == null) { + u = v = 0; + width = height = 1; + } + else { + u = this.region.u; + v = this.region.v; + width = this.region.u2 - u; + height = this.region.v2 - v; + } + if (this.region.rotate) { + for (var i = 0, w = 6; i < verticesLength; i += 2, w += 8) { + this.worldVertices[w] = u + regionUVs[i + 1] * width; + this.worldVertices[w + 1] = v + height - regionUVs[i] * height; + } + } + else { + for (var i = 0, w = 6; i < verticesLength; i += 2, w += 8) { + this.worldVertices[w] = u + regionUVs[i] * width; + this.worldVertices[w + 1] = v + regionUVs[i + 1] * height; + } + } + }; + MeshAttachment.prototype.updateWorldVertices = function (slot, premultipliedAlpha) { + var skeleton = slot.bone.skeleton; + var skeletonColor = skeleton.color, slotColor = slot.color, meshColor = this.color; + var alpha = skeletonColor.a * slotColor.a * meshColor.a; + var multiplier = premultipliedAlpha ? alpha : 1; + var color = this.tempColor; + color.set(skeletonColor.r * slotColor.r * meshColor.r * multiplier, skeletonColor.g * slotColor.g * meshColor.g * multiplier, skeletonColor.b * slotColor.b * meshColor.b * multiplier, alpha); + var deformArray = slot.attachmentVertices; + var vertices = this.vertices, worldVertices = this.worldVertices; + var bones = this.bones; + if (bones == null) { + var verticesLength = vertices.length; + if (deformArray.length > 0) + vertices = deformArray; + var bone = slot.bone; + var x = bone.worldX; + var y = bone.worldY; + var a = bone.a, b = bone.b, c = bone.c, d = bone.d; + for (var v = 0, w = 0; v < verticesLength; v += 2, w += 8) { + var vx = vertices[v], vy = vertices[v + 1]; + worldVertices[w] = vx * a + vy * b + x; + worldVertices[w + 1] = vx * c + vy * d + y; + worldVertices[w + 2] = color.r; + worldVertices[w + 3] = color.g; + worldVertices[w + 4] = color.b; + worldVertices[w + 5] = color.a; + } + return worldVertices; + } + var skeletonBones = skeleton.bones; + if (deformArray.length == 0) { + for (var w = 0, v = 0, b = 0, n = bones.length; v < n; w += 8) { + var wx = 0, wy = 0; + var nn = bones[v++] + v; + for (; v < nn; v++, b += 3) { + var bone = skeletonBones[bones[v]]; + var vx = vertices[b], vy = vertices[b + 1], weight = vertices[b + 2]; + wx += (vx * bone.a + vy * bone.b + bone.worldX) * weight; + wy += (vx * bone.c + vy * bone.d + bone.worldY) * weight; + } + worldVertices[w] = wx; + worldVertices[w + 1] = wy; + worldVertices[w + 2] = color.r; + worldVertices[w + 3] = color.g; + worldVertices[w + 4] = color.b; + worldVertices[w + 5] = color.a; + } + } + else { + var deform = deformArray; + for (var w = 0, v = 0, b = 0, f = 0, n = bones.length; v < n; w += 8) { + var wx = 0, wy = 0; + var nn = bones[v++] + v; + for (; v < nn; v++, b += 3, f += 2) { + var bone = skeletonBones[bones[v]]; + var vx = vertices[b] + deform[f], vy = vertices[b + 1] + deform[f + 1], weight = vertices[b + 2]; + wx += (vx * bone.a + vy * bone.b + bone.worldX) * weight; + wy += (vx * bone.c + vy * bone.d + bone.worldY) * weight; + } + worldVertices[w] = wx; + worldVertices[w + 1] = wy; + worldVertices[w + 2] = color.r; + worldVertices[w + 3] = color.g; + worldVertices[w + 4] = color.b; + worldVertices[w + 5] = color.a; + } + } + return worldVertices; + }; + MeshAttachment.prototype.applyDeform = function (sourceAttachment) { + return this == sourceAttachment || (this.inheritDeform && this.parentMesh == sourceAttachment); + }; + MeshAttachment.prototype.getParentMesh = function () { + return this.parentMesh; + }; + MeshAttachment.prototype.setParentMesh = function (parentMesh) { + this.parentMesh = parentMesh; + if (parentMesh != null) { + this.bones = parentMesh.bones; + this.vertices = parentMesh.vertices; + this.regionUVs = parentMesh.regionUVs; + this.triangles = parentMesh.triangles; + this.hullLength = parentMesh.hullLength; + } + }; + return MeshAttachment; + }(spine.VertexAttachment)); + spine.MeshAttachment = MeshAttachment; +})(spine || (spine = {})); +var spine; +(function (spine) { + var PathAttachment = (function (_super) { + __extends(PathAttachment, _super); + function PathAttachment(name) { + _super.call(this, name); + this.closed = false; + this.constantSpeed = false; + this.color = new spine.Color(1, 1, 1, 1); + } + return PathAttachment; + }(spine.VertexAttachment)); + spine.PathAttachment = PathAttachment; +})(spine || (spine = {})); +var spine; +(function (spine) { + var RegionAttachment = (function (_super) { + __extends(RegionAttachment, _super); + function RegionAttachment(name) { + _super.call(this, name); + this.x = 0; + this.y = 0; + this.scaleX = 1; + this.scaleY = 1; + this.rotation = 0; + this.width = 0; + this.height = 0; + this.color = new spine.Color(1, 1, 1, 1); + this.offset = spine.Utils.newFloatArray(8); + this.vertices = spine.Utils.newFloatArray(8 * 4); + this.tempColor = new spine.Color(1, 1, 1, 1); + } + RegionAttachment.prototype.setRegion = function (region) { + var vertices = this.vertices; + if (region.rotate) { + vertices[RegionAttachment.U2] = region.u; + vertices[RegionAttachment.V2] = region.v2; + vertices[RegionAttachment.U3] = region.u; + vertices[RegionAttachment.V3] = region.v; + vertices[RegionAttachment.U4] = region.u2; + vertices[RegionAttachment.V4] = region.v; + vertices[RegionAttachment.U1] = region.u2; + vertices[RegionAttachment.V1] = region.v2; + } + else { + vertices[RegionAttachment.U1] = region.u; + vertices[RegionAttachment.V1] = region.v2; + vertices[RegionAttachment.U2] = region.u; + vertices[RegionAttachment.V2] = region.v; + vertices[RegionAttachment.U3] = region.u2; + vertices[RegionAttachment.V3] = region.v; + vertices[RegionAttachment.U4] = region.u2; + vertices[RegionAttachment.V4] = region.v2; + } + this.region = region; + }; + RegionAttachment.prototype.updateOffset = function () { + var regionScaleX = this.width / this.region.originalWidth * this.scaleX; + var regionScaleY = this.height / this.region.originalHeight * this.scaleY; + var localX = -this.width / 2 * this.scaleX + this.region.offsetX * regionScaleX; + var localY = -this.height / 2 * this.scaleY + this.region.offsetY * regionScaleY; + var localX2 = localX + this.region.width * regionScaleX; + var localY2 = localY + this.region.height * regionScaleY; + var radians = this.rotation * Math.PI / 180; + var cos = Math.cos(radians); + var sin = Math.sin(radians); + var localXCos = localX * cos + this.x; + var localXSin = localX * sin; + var localYCos = localY * cos + this.y; + var localYSin = localY * sin; + var localX2Cos = localX2 * cos + this.x; + var localX2Sin = localX2 * sin; + var localY2Cos = localY2 * cos + this.y; + var localY2Sin = localY2 * sin; + var offset = this.offset; + offset[RegionAttachment.OX1] = localXCos - localYSin; + offset[RegionAttachment.OY1] = localYCos + localXSin; + offset[RegionAttachment.OX2] = localXCos - localY2Sin; + offset[RegionAttachment.OY2] = localY2Cos + localXSin; + offset[RegionAttachment.OX3] = localX2Cos - localY2Sin; + offset[RegionAttachment.OY3] = localY2Cos + localX2Sin; + offset[RegionAttachment.OX4] = localX2Cos - localYSin; + offset[RegionAttachment.OY4] = localYCos + localX2Sin; + }; + RegionAttachment.prototype.updateWorldVertices = function (slot, premultipliedAlpha) { + var skeleton = slot.bone.skeleton; + var skeletonColor = skeleton.color; + var slotColor = slot.color; + var regionColor = this.color; + var alpha = skeletonColor.a * slotColor.a * regionColor.a; + var multiplier = premultipliedAlpha ? alpha : 1; + var color = this.tempColor; + color.set(skeletonColor.r * slotColor.r * regionColor.r * multiplier, skeletonColor.g * slotColor.g * regionColor.g * multiplier, skeletonColor.b * slotColor.b * regionColor.b * multiplier, alpha); + var vertices = this.vertices; + var offset = this.offset; + var bone = slot.bone; + var x = bone.worldX, y = bone.worldY; + var a = bone.a, b = bone.b, c = bone.c, d = bone.d; + var offsetX = 0, offsetY = 0; + offsetX = offset[RegionAttachment.OX1]; + offsetY = offset[RegionAttachment.OY1]; + vertices[RegionAttachment.X1] = offsetX * a + offsetY * b + x; + vertices[RegionAttachment.Y1] = offsetX * c + offsetY * d + y; + vertices[RegionAttachment.C1R] = color.r; + vertices[RegionAttachment.C1G] = color.g; + vertices[RegionAttachment.C1B] = color.b; + vertices[RegionAttachment.C1A] = color.a; + offsetX = offset[RegionAttachment.OX2]; + offsetY = offset[RegionAttachment.OY2]; + vertices[RegionAttachment.X2] = offsetX * a + offsetY * b + x; + vertices[RegionAttachment.Y2] = offsetX * c + offsetY * d + y; + vertices[RegionAttachment.C2R] = color.r; + vertices[RegionAttachment.C2G] = color.g; + vertices[RegionAttachment.C2B] = color.b; + vertices[RegionAttachment.C2A] = color.a; + offsetX = offset[RegionAttachment.OX3]; + offsetY = offset[RegionAttachment.OY3]; + vertices[RegionAttachment.X3] = offsetX * a + offsetY * b + x; + vertices[RegionAttachment.Y3] = offsetX * c + offsetY * d + y; + vertices[RegionAttachment.C3R] = color.r; + vertices[RegionAttachment.C3G] = color.g; + vertices[RegionAttachment.C3B] = color.b; + vertices[RegionAttachment.C3A] = color.a; + offsetX = offset[RegionAttachment.OX4]; + offsetY = offset[RegionAttachment.OY4]; + vertices[RegionAttachment.X4] = offsetX * a + offsetY * b + x; + vertices[RegionAttachment.Y4] = offsetX * c + offsetY * d + y; + vertices[RegionAttachment.C4R] = color.r; + vertices[RegionAttachment.C4G] = color.g; + vertices[RegionAttachment.C4B] = color.b; + vertices[RegionAttachment.C4A] = color.a; + return vertices; + }; + RegionAttachment.OX1 = 0; + RegionAttachment.OY1 = 1; + RegionAttachment.OX2 = 2; + RegionAttachment.OY2 = 3; + RegionAttachment.OX3 = 4; + RegionAttachment.OY3 = 5; + RegionAttachment.OX4 = 6; + RegionAttachment.OY4 = 7; + RegionAttachment.X1 = 0; + RegionAttachment.Y1 = 1; + RegionAttachment.C1R = 2; + RegionAttachment.C1G = 3; + RegionAttachment.C1B = 4; + RegionAttachment.C1A = 5; + RegionAttachment.U1 = 6; + RegionAttachment.V1 = 7; + RegionAttachment.X2 = 8; + RegionAttachment.Y2 = 9; + RegionAttachment.C2R = 10; + RegionAttachment.C2G = 11; + RegionAttachment.C2B = 12; + RegionAttachment.C2A = 13; + RegionAttachment.U2 = 14; + RegionAttachment.V2 = 15; + RegionAttachment.X3 = 16; + RegionAttachment.Y3 = 17; + RegionAttachment.C3R = 18; + RegionAttachment.C3G = 19; + RegionAttachment.C3B = 20; + RegionAttachment.C3A = 21; + RegionAttachment.U3 = 22; + RegionAttachment.V3 = 23; + RegionAttachment.X4 = 24; + RegionAttachment.Y4 = 25; + RegionAttachment.C4R = 26; + RegionAttachment.C4G = 27; + RegionAttachment.C4B = 28; + RegionAttachment.C4A = 29; + RegionAttachment.U4 = 30; + RegionAttachment.V4 = 31; + return RegionAttachment; + }(spine.Attachment)); + spine.RegionAttachment = RegionAttachment; +})(spine || (spine = {})); +var spine; +(function (spine) { + (function (BlendMode) { + BlendMode[BlendMode["Normal"] = 0] = "Normal"; + BlendMode[BlendMode["Additive"] = 1] = "Additive"; + BlendMode[BlendMode["Multiply"] = 2] = "Multiply"; + BlendMode[BlendMode["Screen"] = 3] = "Screen"; + })(spine.BlendMode || (spine.BlendMode = {})); + var BlendMode = spine.BlendMode; +})(spine || (spine = {})); +var spine; +(function (spine) { + var Bone = (function () { + function Bone(data, skeleton, parent) { + this.children = new Array(); + this.x = 0; + this.y = 0; + this.rotation = 0; + this.scaleX = 0; + this.scaleY = 0; + this.shearX = 0; + this.shearY = 0; + this.ax = 0; + this.ay = 0; + this.arotation = 0; + this.ascaleX = 0; + this.ascaleY = 0; + this.ashearX = 0; + this.ashearY = 0; + this.appliedValid = false; + this.a = 0; + this.b = 0; + this.worldX = 0; + this.c = 0; + this.d = 0; + this.worldY = 0; + this.sorted = false; + if (data == null) + throw new Error("data cannot be null."); + if (skeleton == null) + throw new Error("skeleton cannot be null."); + this.data = data; + this.skeleton = skeleton; + this.parent = parent; + this.setToSetupPose(); + } + Bone.prototype.update = function () { + this.updateWorldTransformWith(this.x, this.y, this.rotation, this.scaleX, this.scaleY, this.shearX, this.shearY); + }; + Bone.prototype.updateWorldTransform = function () { + this.updateWorldTransformWith(this.x, this.y, this.rotation, this.scaleX, this.scaleY, this.shearX, this.shearY); + }; + Bone.prototype.updateWorldTransformWith = function (x, y, rotation, scaleX, scaleY, shearX, shearY) { + this.ax = x; + this.ay = y; + this.arotation = rotation; + this.ascaleX = scaleX; + this.ascaleY = scaleY; + this.ashearX = shearX; + this.ashearY = shearY; + this.appliedValid = true; + var parent = this.parent; + if (parent == null) { + var rotationY = rotation + 90 + shearY; + var la = spine.MathUtils.cosDeg(rotation + shearX) * scaleX; + var lb = spine.MathUtils.cosDeg(rotationY) * scaleY; + var lc = spine.MathUtils.sinDeg(rotation + shearX) * scaleX; + var ld = spine.MathUtils.sinDeg(rotationY) * scaleY; + var skeleton = this.skeleton; + if (skeleton.flipX) { + x = -x; + la = -la; + lb = -lb; + } + if (skeleton.flipY) { + y = -y; + lc = -lc; + ld = -ld; + } + this.a = la; + this.b = lb; + this.c = lc; + this.d = ld; + this.worldX = x + skeleton.x; + this.worldY = y + skeleton.y; + return; + } + var pa = parent.a, pb = parent.b, pc = parent.c, pd = parent.d; + this.worldX = pa * x + pb * y + parent.worldX; + this.worldY = pc * x + pd * y + parent.worldY; + switch (this.data.transformMode) { + case spine.TransformMode.Normal: { + var rotationY = rotation + 90 + shearY; + var la = spine.MathUtils.cosDeg(rotation + shearX) * scaleX; + var lb = spine.MathUtils.cosDeg(rotationY) * scaleY; + var lc = spine.MathUtils.sinDeg(rotation + shearX) * scaleX; + var ld = spine.MathUtils.sinDeg(rotationY) * scaleY; + this.a = pa * la + pb * lc; + this.b = pa * lb + pb * ld; + this.c = pc * la + pd * lc; + this.d = pc * lb + pd * ld; + return; + } + case spine.TransformMode.OnlyTranslation: { + var rotationY = rotation + 90 + shearY; + this.a = spine.MathUtils.cosDeg(rotation + shearX) * scaleX; + this.b = spine.MathUtils.cosDeg(rotationY) * scaleY; + this.c = spine.MathUtils.sinDeg(rotation + shearX) * scaleX; + this.d = spine.MathUtils.sinDeg(rotationY) * scaleY; + break; + } + case spine.TransformMode.NoRotationOrReflection: { + var s = pa * pa + pc * pc; + var prx = 0; + if (s > 0.0001) { + s = Math.abs(pa * pd - pb * pc) / s; + pb = pc * s; + pd = pa * s; + prx = Math.atan2(pc, pa) * spine.MathUtils.radDeg; + } + else { + pa = 0; + pc = 0; + prx = 90 - Math.atan2(pd, pb) * spine.MathUtils.radDeg; + } + var rx = rotation + shearX - prx; + var ry = rotation + shearY - prx + 90; + var la = spine.MathUtils.cosDeg(rx) * scaleX; + var lb = spine.MathUtils.cosDeg(ry) * scaleY; + var lc = spine.MathUtils.sinDeg(rx) * scaleX; + var ld = spine.MathUtils.sinDeg(ry) * scaleY; + this.a = pa * la - pb * lc; + this.b = pa * lb - pb * ld; + this.c = pc * la + pd * lc; + this.d = pc * lb + pd * ld; + break; + } + case spine.TransformMode.NoScale: + case spine.TransformMode.NoScaleOrReflection: { + var cos = spine.MathUtils.cosDeg(rotation); + var sin = spine.MathUtils.sinDeg(rotation); + var za = pa * cos + pb * sin; + var zc = pc * cos + pd * sin; + var s = Math.sqrt(za * za + zc * zc); + if (s > 0.00001) + s = 1 / s; + za *= s; + zc *= s; + s = Math.sqrt(za * za + zc * zc); + var r = Math.PI / 2 + Math.atan2(zc, za); + var zb = Math.cos(r) * s; + var zd = Math.sin(r) * s; + var la = spine.MathUtils.cosDeg(shearX) * scaleX; + var lb = spine.MathUtils.cosDeg(90 + shearY) * scaleY; + var lc = spine.MathUtils.sinDeg(shearX) * scaleX; + var ld = spine.MathUtils.sinDeg(90 + shearY) * scaleY; + this.a = za * la + zb * lc; + this.b = za * lb + zb * ld; + this.c = zc * la + zd * lc; + this.d = zc * lb + zd * ld; + if (this.data.transformMode != spine.TransformMode.NoScaleOrReflection ? pa * pd - pb * pc < 0 : this.skeleton.flipX != this.skeleton.flipY) { + this.b = -this.b; + this.d = -this.d; + } + return; + } + } + if (this.skeleton.flipX) { + this.a = -this.a; + this.b = -this.b; + } + if (this.skeleton.flipY) { + this.c = -this.c; + this.d = -this.d; + } + }; + Bone.prototype.setToSetupPose = function () { + var data = this.data; + this.x = data.x; + this.y = data.y; + this.rotation = data.rotation; + this.scaleX = data.scaleX; + this.scaleY = data.scaleY; + this.shearX = data.shearX; + this.shearY = data.shearY; + }; + Bone.prototype.getWorldRotationX = function () { + return Math.atan2(this.c, this.a) * spine.MathUtils.radDeg; + }; + Bone.prototype.getWorldRotationY = function () { + return Math.atan2(this.d, this.b) * spine.MathUtils.radDeg; + }; + Bone.prototype.getWorldScaleX = function () { + return Math.sqrt(this.a * this.a + this.c * this.c); + }; + Bone.prototype.getWorldScaleY = function () { + return Math.sqrt(this.b * this.b + this.d * this.d); + }; + Bone.prototype.worldToLocalRotationX = function () { + var parent = this.parent; + if (parent == null) + return this.arotation; + var pa = parent.a, pb = parent.b, pc = parent.c, pd = parent.d, a = this.a, c = this.c; + return Math.atan2(pa * c - pc * a, pd * a - pb * c) * spine.MathUtils.radDeg; + }; + Bone.prototype.worldToLocalRotationY = function () { + var parent = this.parent; + if (parent == null) + return this.arotation; + var pa = parent.a, pb = parent.b, pc = parent.c, pd = parent.d, b = this.b, d = this.d; + return Math.atan2(pa * d - pc * b, pd * b - pb * d) * spine.MathUtils.radDeg; + }; + Bone.prototype.rotateWorld = function (degrees) { + var a = this.a, b = this.b, c = this.c, d = this.d; + var cos = spine.MathUtils.cosDeg(degrees), sin = spine.MathUtils.sinDeg(degrees); + this.a = cos * a - sin * c; + this.b = cos * b - sin * d; + this.c = sin * a + cos * c; + this.d = sin * b + cos * d; + this.appliedValid = false; + }; + Bone.prototype.updateAppliedTransform = function () { + this.appliedValid = true; + var parent = this.parent; + if (parent == null) { + this.ax = this.worldX; + this.ay = this.worldY; + this.arotation = Math.atan2(this.c, this.a) * spine.MathUtils.radDeg; + this.ascaleX = Math.sqrt(this.a * this.a + this.c * this.c); + this.ascaleY = Math.sqrt(this.b * this.b + this.d * this.d); + this.ashearX = 0; + this.ashearY = Math.atan2(this.a * this.b + this.c * this.d, this.a * this.d - this.b * this.c) * spine.MathUtils.radDeg; + return; + } + var pa = parent.a, pb = parent.b, pc = parent.c, pd = parent.d; + var pid = 1 / (pa * pd - pb * pc); + var dx = this.worldX - parent.worldX, dy = this.worldY - parent.worldY; + this.ax = (dx * pd * pid - dy * pb * pid); + this.ay = (dy * pa * pid - dx * pc * pid); + var ia = pid * pd; + var id = pid * pa; + var ib = pid * pb; + var ic = pid * pc; + var ra = ia * this.a - ib * this.c; + var rb = ia * this.b - ib * this.d; + var rc = id * this.c - ic * this.a; + var rd = id * this.d - ic * this.b; + this.ashearX = 0; + this.ascaleX = Math.sqrt(ra * ra + rc * rc); + if (this.ascaleX > 0.0001) { + var det = ra * rd - rb * rc; + this.ascaleY = det / this.ascaleX; + this.ashearY = Math.atan2(ra * rb + rc * rd, det) * spine.MathUtils.radDeg; + this.arotation = Math.atan2(rc, ra) * spine.MathUtils.radDeg; + } + else { + this.ascaleX = 0; + this.ascaleY = Math.sqrt(rb * rb + rd * rd); + this.ashearY = 0; + this.arotation = 90 - Math.atan2(rd, rb) * spine.MathUtils.radDeg; + } + }; + Bone.prototype.worldToLocal = function (world) { + var a = this.a, b = this.b, c = this.c, d = this.d; + var invDet = 1 / (a * d - b * c); + var x = world.x - this.worldX, y = world.y - this.worldY; + world.x = (x * d * invDet - y * b * invDet); + world.y = (y * a * invDet - x * c * invDet); + return world; + }; + Bone.prototype.localToWorld = function (local) { + var x = local.x, y = local.y; + local.x = x * this.a + y * this.b + this.worldX; + local.y = x * this.c + y * this.d + this.worldY; + return local; + }; + return Bone; + }()); + spine.Bone = Bone; +})(spine || (spine = {})); +var spine; +(function (spine) { + var BoneData = (function () { + function BoneData(index, name, parent) { + this.x = 0; + this.y = 0; + this.rotation = 0; + this.scaleX = 1; + this.scaleY = 1; + this.shearX = 0; + this.shearY = 0; + this.transformMode = TransformMode.Normal; + if (index < 0) + throw new Error("index must be >= 0."); + if (name == null) + throw new Error("name cannot be null."); + this.index = index; + this.name = name; + this.parent = parent; + } + return BoneData; + }()); + spine.BoneData = BoneData; + (function (TransformMode) { + TransformMode[TransformMode["Normal"] = 0] = "Normal"; + TransformMode[TransformMode["OnlyTranslation"] = 1] = "OnlyTranslation"; + TransformMode[TransformMode["NoRotationOrReflection"] = 2] = "NoRotationOrReflection"; + TransformMode[TransformMode["NoScale"] = 3] = "NoScale"; + TransformMode[TransformMode["NoScaleOrReflection"] = 4] = "NoScaleOrReflection"; + })(spine.TransformMode || (spine.TransformMode = {})); + var TransformMode = spine.TransformMode; +})(spine || (spine = {})); +var spine; +(function (spine) { + var Event = (function () { + function Event(time, data) { + if (data == null) + throw new Error("data cannot be null."); + this.time = time; + this.data = data; + } + return Event; + }()); + spine.Event = Event; +})(spine || (spine = {})); +var spine; +(function (spine) { + var EventData = (function () { + function EventData(name) { + this.name = name; + } + return EventData; + }()); + spine.EventData = EventData; +})(spine || (spine = {})); +var spine; +(function (spine) { + var IkConstraint = (function () { + function IkConstraint(data, skeleton) { + this.mix = 1; + this.bendDirection = 0; + if (data == null) + throw new Error("data cannot be null."); + if (skeleton == null) + throw new Error("skeleton cannot be null."); + this.data = data; + this.mix = data.mix; + this.bendDirection = data.bendDirection; + this.bones = new Array(); + for (var i = 0; i < data.bones.length; i++) + this.bones.push(skeleton.findBone(data.bones[i].name)); + this.target = skeleton.findBone(data.target.name); + } + IkConstraint.prototype.getOrder = function () { + return this.data.order; + }; + IkConstraint.prototype.apply = function () { + this.update(); + }; + IkConstraint.prototype.update = function () { + var target = this.target; + var bones = this.bones; + switch (bones.length) { + case 1: + this.apply1(bones[0], target.worldX, target.worldY, this.mix); + break; + case 2: + this.apply2(bones[0], bones[1], target.worldX, target.worldY, this.bendDirection, this.mix); + break; + } + }; + IkConstraint.prototype.apply1 = function (bone, targetX, targetY, alpha) { + if (!bone.appliedValid) + bone.updateAppliedTransform(); + var p = bone.parent; + var id = 1 / (p.a * p.d - p.b * p.c); + var x = targetX - p.worldX, y = targetY - p.worldY; + var tx = (x * p.d - y * p.b) * id - bone.ax, ty = (y * p.a - x * p.c) * id - bone.ay; + var rotationIK = Math.atan2(ty, tx) * spine.MathUtils.radDeg - bone.ashearX - bone.arotation; + if (bone.ascaleX < 0) + rotationIK += 180; + if (rotationIK > 180) + rotationIK -= 360; + else if (rotationIK < -180) + rotationIK += 360; + bone.updateWorldTransformWith(bone.ax, bone.ay, bone.arotation + rotationIK * alpha, bone.ascaleX, bone.ascaleY, bone.ashearX, bone.ashearY); + }; + IkConstraint.prototype.apply2 = function (parent, child, targetX, targetY, bendDir, alpha) { + if (alpha == 0) { + child.updateWorldTransform(); + return; + } + if (!parent.appliedValid) + parent.updateAppliedTransform(); + if (!child.appliedValid) + child.updateAppliedTransform(); + var px = parent.ax, py = parent.ay, psx = parent.ascaleX, psy = parent.ascaleY, csx = child.ascaleX; + var os1 = 0, os2 = 0, s2 = 0; + if (psx < 0) { + psx = -psx; + os1 = 180; + s2 = -1; + } + else { + os1 = 0; + s2 = 1; + } + if (psy < 0) { + psy = -psy; + s2 = -s2; + } + if (csx < 0) { + csx = -csx; + os2 = 180; + } + else + os2 = 0; + var cx = child.ax, cy = 0, cwx = 0, cwy = 0, a = parent.a, b = parent.b, c = parent.c, d = parent.d; + var u = Math.abs(psx - psy) <= 0.0001; + if (!u) { + cy = 0; + cwx = a * cx + parent.worldX; + cwy = c * cx + parent.worldY; + } + else { + cy = child.ay; + cwx = a * cx + b * cy + parent.worldX; + cwy = c * cx + d * cy + parent.worldY; + } + var pp = parent.parent; + a = pp.a; + b = pp.b; + c = pp.c; + d = pp.d; + var id = 1 / (a * d - b * c), x = targetX - pp.worldX, y = targetY - pp.worldY; + var tx = (x * d - y * b) * id - px, ty = (y * a - x * c) * id - py; + x = cwx - pp.worldX; + y = cwy - pp.worldY; + var dx = (x * d - y * b) * id - px, dy = (y * a - x * c) * id - py; + var l1 = Math.sqrt(dx * dx + dy * dy), l2 = child.data.length * csx, a1 = 0, a2 = 0; + outer: if (u) { + l2 *= psx; + var cos = (tx * tx + ty * ty - l1 * l1 - l2 * l2) / (2 * l1 * l2); + if (cos < -1) + cos = -1; + else if (cos > 1) + cos = 1; + a2 = Math.acos(cos) * bendDir; + a = l1 + l2 * cos; + b = l2 * Math.sin(a2); + a1 = Math.atan2(ty * a - tx * b, tx * a + ty * b); + } + else { + a = psx * l2; + b = psy * l2; + var aa = a * a, bb = b * b, dd = tx * tx + ty * ty, ta = Math.atan2(ty, tx); + c = bb * l1 * l1 + aa * dd - aa * bb; + var c1 = -2 * bb * l1, c2 = bb - aa; + d = c1 * c1 - 4 * c2 * c; + if (d >= 0) { + var q = Math.sqrt(d); + if (c1 < 0) + q = -q; + q = -(c1 + q) / 2; + var r0 = q / c2, r1 = c / q; + var r = Math.abs(r0) < Math.abs(r1) ? r0 : r1; + if (r * r <= dd) { + y = Math.sqrt(dd - r * r) * bendDir; + a1 = ta - Math.atan2(y, r); + a2 = Math.atan2(y / psy, (r - l1) / psx); + break outer; + } + } + var minAngle = 0, minDist = Number.MAX_VALUE, minX = 0, minY = 0; + var maxAngle = 0, maxDist = 0, maxX = 0, maxY = 0; + x = l1 + a; + d = x * x; + if (d > maxDist) { + maxAngle = 0; + maxDist = d; + maxX = x; + } + x = l1 - a; + d = x * x; + if (d < minDist) { + minAngle = spine.MathUtils.PI; + minDist = d; + minX = x; + } + var angle = Math.acos(-a * l1 / (aa - bb)); + x = a * Math.cos(angle) + l1; + y = b * Math.sin(angle); + d = x * x + y * y; + if (d < minDist) { + minAngle = angle; + minDist = d; + minX = x; + minY = y; + } + if (d > maxDist) { + maxAngle = angle; + maxDist = d; + maxX = x; + maxY = y; + } + if (dd <= (minDist + maxDist) / 2) { + a1 = ta - Math.atan2(minY * bendDir, minX); + a2 = minAngle * bendDir; + } + else { + a1 = ta - Math.atan2(maxY * bendDir, maxX); + a2 = maxAngle * bendDir; + } + } + var os = Math.atan2(cy, cx) * s2; + var rotation = parent.arotation; + a1 = (a1 - os) * spine.MathUtils.radDeg + os1 - rotation; + if (a1 > 180) + a1 -= 360; + else if (a1 < -180) + a1 += 360; + parent.updateWorldTransformWith(px, py, rotation + a1 * alpha, parent.ascaleX, parent.ascaleY, 0, 0); + rotation = child.arotation; + a2 = ((a2 + os) * spine.MathUtils.radDeg - child.ashearX) * s2 + os2 - rotation; + if (a2 > 180) + a2 -= 360; + else if (a2 < -180) + a2 += 360; + child.updateWorldTransformWith(cx, cy, rotation + a2 * alpha, child.ascaleX, child.ascaleY, child.ashearX, child.ashearY); + }; + return IkConstraint; + }()); + spine.IkConstraint = IkConstraint; +})(spine || (spine = {})); +var spine; +(function (spine) { + var IkConstraintData = (function () { + function IkConstraintData(name) { + this.order = 0; + this.bones = new Array(); + this.bendDirection = 1; + this.mix = 1; + this.name = name; + } + return IkConstraintData; + }()); + spine.IkConstraintData = IkConstraintData; +})(spine || (spine = {})); +var spine; +(function (spine) { + var PathConstraint = (function () { + function PathConstraint(data, skeleton) { + this.position = 0; + this.spacing = 0; + this.rotateMix = 0; + this.translateMix = 0; + this.spaces = new Array(); + this.positions = new Array(); + this.world = new Array(); + this.curves = new Array(); + this.lengths = new Array(); + this.segments = new Array(); + if (data == null) + throw new Error("data cannot be null."); + if (skeleton == null) + throw new Error("skeleton cannot be null."); + this.data = data; + this.bones = new Array(); + for (var i = 0, n = data.bones.length; i < n; i++) + this.bones.push(skeleton.findBone(data.bones[i].name)); + this.target = skeleton.findSlot(data.target.name); + this.position = data.position; + this.spacing = data.spacing; + this.rotateMix = data.rotateMix; + this.translateMix = data.translateMix; + } + PathConstraint.prototype.apply = function () { + this.update(); + }; + PathConstraint.prototype.update = function () { + var attachment = this.target.getAttachment(); + if (!(attachment instanceof spine.PathAttachment)) + return; + var rotateMix = this.rotateMix, translateMix = this.translateMix; + var translate = translateMix > 0, rotate = rotateMix > 0; + if (!translate && !rotate) + return; + var data = this.data; + var spacingMode = data.spacingMode; + var lengthSpacing = spacingMode == spine.SpacingMode.Length; + var rotateMode = data.rotateMode; + var tangents = rotateMode == spine.RotateMode.Tangent, scale = rotateMode == spine.RotateMode.ChainScale; + var boneCount = this.bones.length, spacesCount = tangents ? boneCount : boneCount + 1; + var bones = this.bones; + var spaces = spine.Utils.setArraySize(this.spaces, spacesCount), lengths = null; + var spacing = this.spacing; + if (scale || lengthSpacing) { + if (scale) + lengths = spine.Utils.setArraySize(this.lengths, boneCount); + for (var i = 0, n = spacesCount - 1; i < n;) { + var bone = bones[i]; + var length_1 = bone.data.length, x = length_1 * bone.a, y = length_1 * bone.c; + length_1 = Math.sqrt(x * x + y * y); + if (scale) + lengths[i] = length_1; + spaces[++i] = lengthSpacing ? Math.max(0, length_1 + spacing) : spacing; + } + } + else { + for (var i = 1; i < spacesCount; i++) + spaces[i] = spacing; + } + var positions = this.computeWorldPositions(attachment, spacesCount, tangents, data.positionMode == spine.PositionMode.Percent, spacingMode == spine.SpacingMode.Percent); + var boneX = positions[0], boneY = positions[1], offsetRotation = data.offsetRotation; + var tip = false; + if (offsetRotation == 0) + tip = rotateMode == spine.RotateMode.Chain; + else { + tip = false; + var p = this.target.bone; + offsetRotation *= p.a * p.d - p.b * p.c > 0 ? spine.MathUtils.degRad : -spine.MathUtils.degRad; + } + for (var i = 0, p = 3; i < boneCount; i++, p += 3) { + var bone = bones[i]; + bone.worldX += (boneX - bone.worldX) * translateMix; + bone.worldY += (boneY - bone.worldY) * translateMix; + var x = positions[p], y = positions[p + 1], dx = x - boneX, dy = y - boneY; + if (scale) { + var length_2 = lengths[i]; + if (length_2 != 0) { + var s = (Math.sqrt(dx * dx + dy * dy) / length_2 - 1) * rotateMix + 1; + bone.a *= s; + bone.c *= s; + } + } + boneX = x; + boneY = y; + if (rotate) { + var a = bone.a, b = bone.b, c = bone.c, d = bone.d, r = 0, cos = 0, sin = 0; + if (tangents) + r = positions[p - 1]; + else if (spaces[i + 1] == 0) + r = positions[p + 2]; + else + r = Math.atan2(dy, dx); + r -= Math.atan2(c, a); + if (tip) { + cos = Math.cos(r); + sin = Math.sin(r); + var length_3 = bone.data.length; + boneX += (length_3 * (cos * a - sin * c) - dx) * rotateMix; + boneY += (length_3 * (sin * a + cos * c) - dy) * rotateMix; + } + else { + r += offsetRotation; + } + if (r > spine.MathUtils.PI) + r -= spine.MathUtils.PI2; + else if (r < -spine.MathUtils.PI) + r += spine.MathUtils.PI2; + r *= rotateMix; + cos = Math.cos(r); + sin = Math.sin(r); + bone.a = cos * a - sin * c; + bone.b = cos * b - sin * d; + bone.c = sin * a + cos * c; + bone.d = sin * b + cos * d; + } + bone.appliedValid = false; + } + }; + PathConstraint.prototype.computeWorldPositions = function (path, spacesCount, tangents, percentPosition, percentSpacing) { + var target = this.target; + var position = this.position; + var spaces = this.spaces, out = spine.Utils.setArraySize(this.positions, spacesCount * 3 + 2), world = null; + var closed = path.closed; + var verticesLength = path.worldVerticesLength, curveCount = verticesLength / 6, prevCurve = PathConstraint.NONE; + if (!path.constantSpeed) { + var lengths = path.lengths; + curveCount -= closed ? 1 : 2; + var pathLength_1 = lengths[curveCount]; + if (percentPosition) + position *= pathLength_1; + if (percentSpacing) { + for (var i = 0; i < spacesCount; i++) + spaces[i] *= pathLength_1; + } + world = spine.Utils.setArraySize(this.world, 8); + for (var i = 0, o = 0, curve = 0; i < spacesCount; i++, o += 3) { + var space = spaces[i]; + position += space; + var p = position; + if (closed) { + p %= pathLength_1; + if (p < 0) + p += pathLength_1; + curve = 0; + } + else if (p < 0) { + if (prevCurve != PathConstraint.BEFORE) { + prevCurve = PathConstraint.BEFORE; + path.computeWorldVerticesWith(target, 2, 4, world, 0); + } + this.addBeforePosition(p, world, 0, out, o); + continue; + } + else if (p > pathLength_1) { + if (prevCurve != PathConstraint.AFTER) { + prevCurve = PathConstraint.AFTER; + path.computeWorldVerticesWith(target, verticesLength - 6, 4, world, 0); + } + this.addAfterPosition(p - pathLength_1, world, 0, out, o); + continue; + } + for (;; curve++) { + var length_4 = lengths[curve]; + if (p > length_4) + continue; + if (curve == 0) + p /= length_4; + else { + var prev = lengths[curve - 1]; + p = (p - prev) / (length_4 - prev); + } + break; + } + if (curve != prevCurve) { + prevCurve = curve; + if (closed && curve == curveCount) { + path.computeWorldVerticesWith(target, verticesLength - 4, 4, world, 0); + path.computeWorldVerticesWith(target, 0, 4, world, 4); + } + else + path.computeWorldVerticesWith(target, curve * 6 + 2, 8, world, 0); + } + this.addCurvePosition(p, world[0], world[1], world[2], world[3], world[4], world[5], world[6], world[7], out, o, tangents || (i > 0 && space == 0)); + } + return out; + } + if (closed) { + verticesLength += 2; + world = spine.Utils.setArraySize(this.world, verticesLength); + path.computeWorldVerticesWith(target, 2, verticesLength - 4, world, 0); + path.computeWorldVerticesWith(target, 0, 2, world, verticesLength - 4); + world[verticesLength - 2] = world[0]; + world[verticesLength - 1] = world[1]; + } + else { + curveCount--; + verticesLength -= 4; + world = spine.Utils.setArraySize(this.world, verticesLength); + path.computeWorldVerticesWith(target, 2, verticesLength, world, 0); + } + var curves = spine.Utils.setArraySize(this.curves, curveCount); + var pathLength = 0; + var x1 = world[0], y1 = world[1], cx1 = 0, cy1 = 0, cx2 = 0, cy2 = 0, x2 = 0, y2 = 0; + var tmpx = 0, tmpy = 0, dddfx = 0, dddfy = 0, ddfx = 0, ddfy = 0, dfx = 0, dfy = 0; + for (var i = 0, w = 2; i < curveCount; i++, w += 6) { + cx1 = world[w]; + cy1 = world[w + 1]; + cx2 = world[w + 2]; + cy2 = world[w + 3]; + x2 = world[w + 4]; + y2 = world[w + 5]; + tmpx = (x1 - cx1 * 2 + cx2) * 0.1875; + tmpy = (y1 - cy1 * 2 + cy2) * 0.1875; + dddfx = ((cx1 - cx2) * 3 - x1 + x2) * 0.09375; + dddfy = ((cy1 - cy2) * 3 - y1 + y2) * 0.09375; + ddfx = tmpx * 2 + dddfx; + ddfy = tmpy * 2 + dddfy; + dfx = (cx1 - x1) * 0.75 + tmpx + dddfx * 0.16666667; + dfy = (cy1 - y1) * 0.75 + tmpy + dddfy * 0.16666667; + pathLength += Math.sqrt(dfx * dfx + dfy * dfy); + dfx += ddfx; + dfy += ddfy; + ddfx += dddfx; + ddfy += dddfy; + pathLength += Math.sqrt(dfx * dfx + dfy * dfy); + dfx += ddfx; + dfy += ddfy; + pathLength += Math.sqrt(dfx * dfx + dfy * dfy); + dfx += ddfx + dddfx; + dfy += ddfy + dddfy; + pathLength += Math.sqrt(dfx * dfx + dfy * dfy); + curves[i] = pathLength; + x1 = x2; + y1 = y2; + } + if (percentPosition) + position *= pathLength; + if (percentSpacing) { + for (var i = 0; i < spacesCount; i++) + spaces[i] *= pathLength; + } + var segments = this.segments; + var curveLength = 0; + for (var i = 0, o = 0, curve = 0, segment = 0; i < spacesCount; i++, o += 3) { + var space = spaces[i]; + position += space; + var p = position; + if (closed) { + p %= pathLength; + if (p < 0) + p += pathLength; + curve = 0; + } + else if (p < 0) { + this.addBeforePosition(p, world, 0, out, o); + continue; + } + else if (p > pathLength) { + this.addAfterPosition(p - pathLength, world, verticesLength - 4, out, o); + continue; + } + for (;; curve++) { + var length_5 = curves[curve]; + if (p > length_5) + continue; + if (curve == 0) + p /= length_5; + else { + var prev = curves[curve - 1]; + p = (p - prev) / (length_5 - prev); + } + break; + } + if (curve != prevCurve) { + prevCurve = curve; + var ii = curve * 6; + x1 = world[ii]; + y1 = world[ii + 1]; + cx1 = world[ii + 2]; + cy1 = world[ii + 3]; + cx2 = world[ii + 4]; + cy2 = world[ii + 5]; + x2 = world[ii + 6]; + y2 = world[ii + 7]; + tmpx = (x1 - cx1 * 2 + cx2) * 0.03; + tmpy = (y1 - cy1 * 2 + cy2) * 0.03; + dddfx = ((cx1 - cx2) * 3 - x1 + x2) * 0.006; + dddfy = ((cy1 - cy2) * 3 - y1 + y2) * 0.006; + ddfx = tmpx * 2 + dddfx; + ddfy = tmpy * 2 + dddfy; + dfx = (cx1 - x1) * 0.3 + tmpx + dddfx * 0.16666667; + dfy = (cy1 - y1) * 0.3 + tmpy + dddfy * 0.16666667; + curveLength = Math.sqrt(dfx * dfx + dfy * dfy); + segments[0] = curveLength; + for (ii = 1; ii < 8; ii++) { + dfx += ddfx; + dfy += ddfy; + ddfx += dddfx; + ddfy += dddfy; + curveLength += Math.sqrt(dfx * dfx + dfy * dfy); + segments[ii] = curveLength; + } + dfx += ddfx; + dfy += ddfy; + curveLength += Math.sqrt(dfx * dfx + dfy * dfy); + segments[8] = curveLength; + dfx += ddfx + dddfx; + dfy += ddfy + dddfy; + curveLength += Math.sqrt(dfx * dfx + dfy * dfy); + segments[9] = curveLength; + segment = 0; + } + p *= curveLength; + for (;; segment++) { + var length_6 = segments[segment]; + if (p > length_6) + continue; + if (segment == 0) + p /= length_6; + else { + var prev = segments[segment - 1]; + p = segment + (p - prev) / (length_6 - prev); + } + break; + } + this.addCurvePosition(p * 0.1, x1, y1, cx1, cy1, cx2, cy2, x2, y2, out, o, tangents || (i > 0 && space == 0)); + } + return out; + }; + PathConstraint.prototype.addBeforePosition = function (p, temp, i, out, o) { + var x1 = temp[i], y1 = temp[i + 1], dx = temp[i + 2] - x1, dy = temp[i + 3] - y1, r = Math.atan2(dy, dx); + out[o] = x1 + p * Math.cos(r); + out[o + 1] = y1 + p * Math.sin(r); + out[o + 2] = r; + }; + PathConstraint.prototype.addAfterPosition = function (p, temp, i, out, o) { + var x1 = temp[i + 2], y1 = temp[i + 3], dx = x1 - temp[i], dy = y1 - temp[i + 1], r = Math.atan2(dy, dx); + out[o] = x1 + p * Math.cos(r); + out[o + 1] = y1 + p * Math.sin(r); + out[o + 2] = r; + }; + PathConstraint.prototype.addCurvePosition = function (p, x1, y1, cx1, cy1, cx2, cy2, x2, y2, out, o, tangents) { + if (p == 0 || isNaN(p)) + p = 0.0001; + var tt = p * p, ttt = tt * p, u = 1 - p, uu = u * u, uuu = uu * u; + var ut = u * p, ut3 = ut * 3, uut3 = u * ut3, utt3 = ut3 * p; + var x = x1 * uuu + cx1 * uut3 + cx2 * utt3 + x2 * ttt, y = y1 * uuu + cy1 * uut3 + cy2 * utt3 + y2 * ttt; + out[o] = x; + out[o + 1] = y; + if (tangents) + out[o + 2] = Math.atan2(y - (y1 * uu + cy1 * ut * 2 + cy2 * tt), x - (x1 * uu + cx1 * ut * 2 + cx2 * tt)); + }; + PathConstraint.prototype.getOrder = function () { + return this.data.order; + }; + PathConstraint.NONE = -1; + PathConstraint.BEFORE = -2; + PathConstraint.AFTER = -3; + return PathConstraint; + }()); + spine.PathConstraint = PathConstraint; +})(spine || (spine = {})); +var spine; +(function (spine) { + var PathConstraintData = (function () { + function PathConstraintData(name) { + this.order = 0; + this.bones = new Array(); + this.name = name; + } + return PathConstraintData; + }()); + spine.PathConstraintData = PathConstraintData; + (function (PositionMode) { + PositionMode[PositionMode["Fixed"] = 0] = "Fixed"; + PositionMode[PositionMode["Percent"] = 1] = "Percent"; + })(spine.PositionMode || (spine.PositionMode = {})); + var PositionMode = spine.PositionMode; + (function (SpacingMode) { + SpacingMode[SpacingMode["Length"] = 0] = "Length"; + SpacingMode[SpacingMode["Fixed"] = 1] = "Fixed"; + SpacingMode[SpacingMode["Percent"] = 2] = "Percent"; + })(spine.SpacingMode || (spine.SpacingMode = {})); + var SpacingMode = spine.SpacingMode; + (function (RotateMode) { + RotateMode[RotateMode["Tangent"] = 0] = "Tangent"; + RotateMode[RotateMode["Chain"] = 1] = "Chain"; + RotateMode[RotateMode["ChainScale"] = 2] = "ChainScale"; + })(spine.RotateMode || (spine.RotateMode = {})); + var RotateMode = spine.RotateMode; +})(spine || (spine = {})); +var spine; +(function (spine) { + var Assets = (function () { + function Assets(clientId) { + this.toLoad = new Array(); + this.assets = {}; + this.clientId = clientId; + } + Assets.prototype.loaded = function () { + var i = 0; + for (var v in this.assets) + i++; + return i; + }; + return Assets; + }()); + var SharedAssetManager = (function () { + function SharedAssetManager(pathPrefix) { + if (pathPrefix === void 0) { pathPrefix = ""; } + this.clientAssets = {}; + this.queuedAssets = {}; + this.rawAssets = {}; + this.errors = {}; + this.pathPrefix = pathPrefix; + } + SharedAssetManager.prototype.queueAsset = function (clientId, textureLoader, path) { + var clientAssets = this.clientAssets[clientId]; + if (clientAssets === null || clientAssets === undefined) { + clientAssets = new Assets(clientId); + this.clientAssets[clientId] = clientAssets; + } + if (textureLoader !== null) + clientAssets.textureLoader = textureLoader; + clientAssets.toLoad.push(path); + if (this.queuedAssets[path] === path) { + return false; + } + else { + this.queuedAssets[path] = path; + return true; + } + }; + SharedAssetManager.prototype.loadText = function (clientId, path) { + var _this = this; + path = this.pathPrefix + path; + if (!this.queueAsset(clientId, null, path)) + return; + var request = new XMLHttpRequest(); + request.onreadystatechange = function () { + if (request.readyState == XMLHttpRequest.DONE) { + if (request.status >= 200 && request.status < 300) { + _this.rawAssets[path] = request.responseText; + } + else { + _this.errors[path] = "Couldn't load text " + path + ": status " + request.status + ", " + request.responseText; + } + } + }; + request.open("GET", path, true); + request.send(); + }; + SharedAssetManager.prototype.loadJson = function (clientId, path) { + var _this = this; + path = this.pathPrefix + path; + if (!this.queueAsset(clientId, null, path)) + return; + var request = new XMLHttpRequest(); + request.onreadystatechange = function () { + if (request.readyState == XMLHttpRequest.DONE) { + if (request.status >= 200 && request.status < 300) { + _this.rawAssets[path] = JSON.parse(request.responseText); + } + else { + _this.errors[path] = "Couldn't load text " + path + ": status " + request.status + ", " + request.responseText; + } + } + }; + request.open("GET", path, true); + request.send(); + }; + SharedAssetManager.prototype.loadTexture = function (clientId, textureLoader, path) { + var _this = this; + path = this.pathPrefix + path; + if (!this.queueAsset(clientId, textureLoader, path)) + return; + var img = new Image(); + img.src = path; + img.crossOrigin = "anonymous"; + img.onload = function (ev) { + _this.rawAssets[path] = img; + }; + img.onerror = function (ev) { + _this.errors[path] = "Couldn't load image " + path; + }; + }; + SharedAssetManager.prototype.get = function (clientId, path) { + path = this.pathPrefix + path; + var clientAssets = this.clientAssets[clientId]; + if (clientAssets === null || clientAssets === undefined) + return true; + return clientAssets.assets[path]; + }; + SharedAssetManager.prototype.updateClientAssets = function (clientAssets) { + for (var i = 0; i < clientAssets.toLoad.length; i++) { + var path = clientAssets.toLoad[i]; + var asset = clientAssets.assets[path]; + if (asset === null || asset === undefined) { + var rawAsset = this.rawAssets[path]; + if (rawAsset === null || rawAsset === undefined) + continue; + if (rawAsset instanceof HTMLImageElement) { + clientAssets.assets[path] = clientAssets.textureLoader(rawAsset); + } + else { + clientAssets.assets[path] = rawAsset; + } + } + } + }; + SharedAssetManager.prototype.isLoadingComplete = function (clientId) { + var clientAssets = this.clientAssets[clientId]; + if (clientAssets === null || clientAssets === undefined) + return true; + this.updateClientAssets(clientAssets); + return clientAssets.toLoad.length == clientAssets.loaded(); + }; + SharedAssetManager.prototype.dispose = function () { + }; + SharedAssetManager.prototype.hasErrors = function () { + return Object.keys(this.errors).length > 0; + }; + SharedAssetManager.prototype.getErrors = function () { + return this.errors; + }; + return SharedAssetManager; + }()); + spine.SharedAssetManager = SharedAssetManager; +})(spine || (spine = {})); +var spine; +(function (spine) { + var Skeleton = (function () { + function Skeleton(data) { + this._updateCache = new Array(); + this.updateCacheReset = new Array(); + this.time = 0; + this.flipX = false; + this.flipY = false; + this.x = 0; + this.y = 0; + if (data == null) + throw new Error("data cannot be null."); + this.data = data; + this.bones = new Array(); + for (var i = 0; i < data.bones.length; i++) { + var boneData = data.bones[i]; + var bone = void 0; + if (boneData.parent == null) + bone = new spine.Bone(boneData, this, null); + else { + var parent_1 = this.bones[boneData.parent.index]; + bone = new spine.Bone(boneData, this, parent_1); + parent_1.children.push(bone); + } + this.bones.push(bone); + } + this.slots = new Array(); + this.drawOrder = new Array(); + for (var i = 0; i < data.slots.length; i++) { + var slotData = data.slots[i]; + var bone = this.bones[slotData.boneData.index]; + var slot = new spine.Slot(slotData, bone); + this.slots.push(slot); + this.drawOrder.push(slot); + } + this.ikConstraints = new Array(); + for (var i = 0; i < data.ikConstraints.length; i++) { + var ikConstraintData = data.ikConstraints[i]; + this.ikConstraints.push(new spine.IkConstraint(ikConstraintData, this)); + } + this.transformConstraints = new Array(); + for (var i = 0; i < data.transformConstraints.length; i++) { + var transformConstraintData = data.transformConstraints[i]; + this.transformConstraints.push(new spine.TransformConstraint(transformConstraintData, this)); + } + this.pathConstraints = new Array(); + for (var i = 0; i < data.pathConstraints.length; i++) { + var pathConstraintData = data.pathConstraints[i]; + this.pathConstraints.push(new spine.PathConstraint(pathConstraintData, this)); + } + this.color = new spine.Color(1, 1, 1, 1); + this.updateCache(); + } + Skeleton.prototype.updateCache = function () { + var updateCache = this._updateCache; + updateCache.length = 0; + var bones = this.bones; + for (var i = 0, n = bones.length; i < n; i++) + bones[i].sorted = false; + var ikConstraints = this.ikConstraints; + var transformConstraints = this.transformConstraints; + var pathConstraints = this.pathConstraints; + var ikCount = ikConstraints.length, transformCount = transformConstraints.length, pathCount = pathConstraints.length; + var constraintCount = ikCount + transformCount + pathCount; + outer: for (var i = 0; i < constraintCount; i++) { + for (var ii = 0; ii < ikCount; ii++) { + var constraint = ikConstraints[ii]; + if (constraint.data.order == i) { + this.sortIkConstraint(constraint); + continue outer; + } + } + for (var ii = 0; ii < transformCount; ii++) { + var constraint = transformConstraints[ii]; + if (constraint.data.order == i) { + this.sortTransformConstraint(constraint); + continue outer; + } + } + for (var ii = 0; ii < pathCount; ii++) { + var constraint = pathConstraints[ii]; + if (constraint.data.order == i) { + this.sortPathConstraint(constraint); + continue outer; + } + } + } + for (var i = 0, n = bones.length; i < n; i++) + this.sortBone(bones[i]); + }; + Skeleton.prototype.sortIkConstraint = function (constraint) { + var target = constraint.target; + this.sortBone(target); + var constrained = constraint.bones; + var parent = constrained[0]; + this.sortBone(parent); + if (constrained.length > 1) { + var child = constrained[constrained.length - 1]; + if (!(this._updateCache.indexOf(child) > -1)) + this.updateCacheReset.push(child); + } + this._updateCache.push(constraint); + this.sortReset(parent.children); + constrained[constrained.length - 1].sorted = true; + }; + Skeleton.prototype.sortPathConstraint = function (constraint) { + var slot = constraint.target; + var slotIndex = slot.data.index; + var slotBone = slot.bone; + if (this.skin != null) + this.sortPathConstraintAttachment(this.skin, slotIndex, slotBone); + if (this.data.defaultSkin != null && this.data.defaultSkin != this.skin) + this.sortPathConstraintAttachment(this.data.defaultSkin, slotIndex, slotBone); + for (var ii = 0, nn = this.data.skins.length; ii < nn; ii++) + this.sortPathConstraintAttachment(this.data.skins[ii], slotIndex, slotBone); + var attachment = slot.getAttachment(); + if (attachment instanceof spine.PathAttachment) + this.sortPathConstraintAttachmentWith(attachment, slotBone); + var constrained = constraint.bones; + var boneCount = constrained.length; + for (var ii = 0; ii < boneCount; ii++) + this.sortBone(constrained[ii]); + this._updateCache.push(constraint); + for (var ii = 0; ii < boneCount; ii++) + this.sortReset(constrained[ii].children); + for (var ii = 0; ii < boneCount; ii++) + constrained[ii].sorted = true; + }; + Skeleton.prototype.sortTransformConstraint = function (constraint) { + this.sortBone(constraint.target); + var constrained = constraint.bones; + var boneCount = constrained.length; + for (var ii = 0; ii < boneCount; ii++) + this.sortBone(constrained[ii]); + this._updateCache.push(constraint); + for (var ii = 0; ii < boneCount; ii++) + this.sortReset(constrained[ii].children); + for (var ii = 0; ii < boneCount; ii++) + constrained[ii].sorted = true; + }; + Skeleton.prototype.sortPathConstraintAttachment = function (skin, slotIndex, slotBone) { + var attachments = skin.attachments[slotIndex]; + if (!attachments) + return; + for (var key in attachments) { + this.sortPathConstraintAttachmentWith(attachments[key], slotBone); + } + }; + Skeleton.prototype.sortPathConstraintAttachmentWith = function (attachment, slotBone) { + if (!(attachment instanceof spine.PathAttachment)) + return; + var pathBones = attachment.bones; + if (pathBones == null) + this.sortBone(slotBone); + else { + var bones = this.bones; + var i = 0; + while (i < pathBones.length) { + var boneCount = pathBones[i++]; + for (var n = i + boneCount; i < n; i++) { + var boneIndex = pathBones[i]; + this.sortBone(bones[boneIndex]); + } + } + } + }; + Skeleton.prototype.sortBone = function (bone) { + if (bone.sorted) + return; + var parent = bone.parent; + if (parent != null) + this.sortBone(parent); + bone.sorted = true; + this._updateCache.push(bone); + }; + Skeleton.prototype.sortReset = function (bones) { + for (var i = 0, n = bones.length; i < n; i++) { + var bone = bones[i]; + if (bone.sorted) + this.sortReset(bone.children); + bone.sorted = false; + } + }; + Skeleton.prototype.updateWorldTransform = function () { + var updateCacheReset = this.updateCacheReset; + for (var i = 0, n = updateCacheReset.length; i < n; i++) { + var bone = updateCacheReset[i]; + bone.ax = bone.x; + bone.ay = bone.y; + bone.arotation = bone.rotation; + bone.ascaleX = bone.scaleX; + bone.ascaleY = bone.scaleY; + bone.ashearX = bone.shearX; + bone.ashearY = bone.shearY; + bone.appliedValid = true; + } + var updateCache = this._updateCache; + for (var i = 0, n = updateCache.length; i < n; i++) + updateCache[i].update(); + }; + Skeleton.prototype.setToSetupPose = function () { + this.setBonesToSetupPose(); + this.setSlotsToSetupPose(); + }; + Skeleton.prototype.setBonesToSetupPose = function () { + var bones = this.bones; + for (var i = 0, n = bones.length; i < n; i++) + bones[i].setToSetupPose(); + var ikConstraints = this.ikConstraints; + for (var i = 0, n = ikConstraints.length; i < n; i++) { + var constraint = ikConstraints[i]; + constraint.bendDirection = constraint.data.bendDirection; + constraint.mix = constraint.data.mix; + } + var transformConstraints = this.transformConstraints; + for (var i = 0, n = transformConstraints.length; i < n; i++) { + var constraint = transformConstraints[i]; + var data = constraint.data; + constraint.rotateMix = data.rotateMix; + constraint.translateMix = data.translateMix; + constraint.scaleMix = data.scaleMix; + constraint.shearMix = data.shearMix; + } + var pathConstraints = this.pathConstraints; + for (var i = 0, n = pathConstraints.length; i < n; i++) { + var constraint = pathConstraints[i]; + var data = constraint.data; + constraint.position = data.position; + constraint.spacing = data.spacing; + constraint.rotateMix = data.rotateMix; + constraint.translateMix = data.translateMix; + } + }; + Skeleton.prototype.setSlotsToSetupPose = function () { + var slots = this.slots; + spine.Utils.arrayCopy(slots, 0, this.drawOrder, 0, slots.length); + for (var i = 0, n = slots.length; i < n; i++) + slots[i].setToSetupPose(); + }; + Skeleton.prototype.getRootBone = function () { + if (this.bones.length == 0) + return null; + return this.bones[0]; + }; + Skeleton.prototype.findBone = function (boneName) { + if (boneName == null) + throw new Error("boneName cannot be null."); + var bones = this.bones; + for (var i = 0, n = bones.length; i < n; i++) { + var bone = bones[i]; + if (bone.data.name == boneName) + return bone; + } + return null; + }; + Skeleton.prototype.findBoneIndex = function (boneName) { + if (boneName == null) + throw new Error("boneName cannot be null."); + var bones = this.bones; + for (var i = 0, n = bones.length; i < n; i++) + if (bones[i].data.name == boneName) + return i; + return -1; + }; + Skeleton.prototype.findSlot = function (slotName) { + if (slotName == null) + throw new Error("slotName cannot be null."); + var slots = this.slots; + for (var i = 0, n = slots.length; i < n; i++) { + var slot = slots[i]; + if (slot.data.name == slotName) + return slot; + } + return null; + }; + Skeleton.prototype.findSlotIndex = function (slotName) { + if (slotName == null) + throw new Error("slotName cannot be null."); + var slots = this.slots; + for (var i = 0, n = slots.length; i < n; i++) + if (slots[i].data.name == slotName) + return i; + return -1; + }; + Skeleton.prototype.setSkinByName = function (skinName) { + var skin = this.data.findSkin(skinName); + if (skin == null) + throw new Error("Skin not found: " + skinName); + this.setSkin(skin); + }; + Skeleton.prototype.setSkin = function (newSkin) { + if (newSkin != null) { + if (this.skin != null) + newSkin.attachAll(this, this.skin); + else { + var slots = this.slots; + for (var i = 0, n = slots.length; i < n; i++) { + var slot = slots[i]; + var name_1 = slot.data.attachmentName; + if (name_1 != null) { + var attachment = newSkin.getAttachment(i, name_1); + if (attachment != null) + slot.setAttachment(attachment); + } + } + } + } + this.skin = newSkin; + }; + Skeleton.prototype.getAttachmentByName = function (slotName, attachmentName) { + return this.getAttachment(this.data.findSlotIndex(slotName), attachmentName); + }; + Skeleton.prototype.getAttachment = function (slotIndex, attachmentName) { + if (attachmentName == null) + throw new Error("attachmentName cannot be null."); + if (this.skin != null) { + var attachment = this.skin.getAttachment(slotIndex, attachmentName); + if (attachment != null) + return attachment; + } + if (this.data.defaultSkin != null) + return this.data.defaultSkin.getAttachment(slotIndex, attachmentName); + return null; + }; + Skeleton.prototype.setAttachment = function (slotName, attachmentName) { + if (slotName == null) + throw new Error("slotName cannot be null."); + var slots = this.slots; + for (var i = 0, n = slots.length; i < n; i++) { + var slot = slots[i]; + if (slot.data.name == slotName) { + var attachment = null; + if (attachmentName != null) { + attachment = this.getAttachment(i, attachmentName); + if (attachment == null) + throw new Error("Attachment not found: " + attachmentName + ", for slot: " + slotName); + } + slot.setAttachment(attachment); + return; + } + } + throw new Error("Slot not found: " + slotName); + }; + Skeleton.prototype.findIkConstraint = function (constraintName) { + if (constraintName == null) + throw new Error("constraintName cannot be null."); + var ikConstraints = this.ikConstraints; + for (var i = 0, n = ikConstraints.length; i < n; i++) { + var ikConstraint = ikConstraints[i]; + if (ikConstraint.data.name == constraintName) + return ikConstraint; + } + return null; + }; + Skeleton.prototype.findTransformConstraint = function (constraintName) { + if (constraintName == null) + throw new Error("constraintName cannot be null."); + var transformConstraints = this.transformConstraints; + for (var i = 0, n = transformConstraints.length; i < n; i++) { + var constraint = transformConstraints[i]; + if (constraint.data.name == constraintName) + return constraint; + } + return null; + }; + Skeleton.prototype.findPathConstraint = function (constraintName) { + if (constraintName == null) + throw new Error("constraintName cannot be null."); + var pathConstraints = this.pathConstraints; + for (var i = 0, n = pathConstraints.length; i < n; i++) { + var constraint = pathConstraints[i]; + if (constraint.data.name == constraintName) + return constraint; + } + return null; + }; + Skeleton.prototype.getBounds = function (offset, size) { + if (offset == null) + throw new Error("offset cannot be null."); + if (size == null) + throw new Error("size cannot be null."); + var drawOrder = this.drawOrder; + var minX = Number.POSITIVE_INFINITY, minY = Number.POSITIVE_INFINITY, maxX = Number.NEGATIVE_INFINITY, maxY = Number.NEGATIVE_INFINITY; + for (var i = 0, n = drawOrder.length; i < n; i++) { + var slot = drawOrder[i]; + var vertices = null; + var attachment = slot.getAttachment(); + if (attachment instanceof spine.RegionAttachment) + vertices = attachment.updateWorldVertices(slot, false); + else if (attachment instanceof spine.MeshAttachment) + vertices = attachment.updateWorldVertices(slot, true); + if (vertices != null) { + for (var ii = 0, nn = vertices.length; ii < nn; ii += 8) { + var x = vertices[ii], y = vertices[ii + 1]; + minX = Math.min(minX, x); + minY = Math.min(minY, y); + maxX = Math.max(maxX, x); + maxY = Math.max(maxY, y); + } + } + } + offset.set(minX, minY); + size.set(maxX - minX, maxY - minY); + }; + Skeleton.prototype.update = function (delta) { + this.time += delta; + }; + return Skeleton; + }()); + spine.Skeleton = Skeleton; +})(spine || (spine = {})); +var spine; +(function (spine) { + var SkeletonBounds = (function () { + function SkeletonBounds() { + this.minX = 0; + this.minY = 0; + this.maxX = 0; + this.maxY = 0; + this.boundingBoxes = new Array(); + this.polygons = new Array(); + this.polygonPool = new spine.Pool(function () { + return spine.Utils.newFloatArray(16); + }); + } + SkeletonBounds.prototype.update = function (skeleton, updateAabb) { + if (skeleton == null) + throw new Error("skeleton cannot be null."); + var boundingBoxes = this.boundingBoxes; + var polygons = this.polygons; + var polygonPool = this.polygonPool; + var slots = skeleton.slots; + var slotCount = slots.length; + boundingBoxes.length = 0; + polygonPool.freeAll(polygons); + polygons.length = 0; + for (var i = 0; i < slotCount; i++) { + var slot = slots[i]; + var attachment = slot.getAttachment(); + if (attachment instanceof spine.BoundingBoxAttachment) { + var boundingBox = attachment; + boundingBoxes.push(boundingBox); + var polygon = polygonPool.obtain(); + if (polygon.length != boundingBox.worldVerticesLength) { + polygon = spine.Utils.newFloatArray(boundingBox.worldVerticesLength); + } + polygons.push(polygon); + boundingBox.computeWorldVertices(slot, polygon); + } + } + if (updateAabb) { + this.aabbCompute(); + } + else { + this.minX = Number.POSITIVE_INFINITY; + this.minY = Number.POSITIVE_INFINITY; + this.maxX = Number.NEGATIVE_INFINITY; + this.maxY = Number.NEGATIVE_INFINITY; + } + }; + SkeletonBounds.prototype.aabbCompute = function () { + var minX = Number.POSITIVE_INFINITY, minY = Number.POSITIVE_INFINITY, maxX = Number.NEGATIVE_INFINITY, maxY = Number.NEGATIVE_INFINITY; + var polygons = this.polygons; + for (var i = 0, n = polygons.length; i < n; i++) { + var polygon = polygons[i]; + var vertices = polygon; + for (var ii = 0, nn = polygon.length; ii < nn; ii += 2) { + var x = vertices[ii]; + var y = vertices[ii + 1]; + minX = Math.min(minX, x); + minY = Math.min(minY, y); + maxX = Math.max(maxX, x); + maxY = Math.max(maxY, y); + } + } + this.minX = minX; + this.minY = minY; + this.maxX = maxX; + this.maxY = maxY; + }; + SkeletonBounds.prototype.aabbContainsPoint = function (x, y) { + return x >= this.minX && x <= this.maxX && y >= this.minY && y <= this.maxY; + }; + SkeletonBounds.prototype.aabbIntersectsSegment = function (x1, y1, x2, y2) { + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + if ((x1 <= minX && x2 <= minX) || (y1 <= minY && y2 <= minY) || (x1 >= maxX && x2 >= maxX) || (y1 >= maxY && y2 >= maxY)) + return false; + var m = (y2 - y1) / (x2 - x1); + var y = m * (minX - x1) + y1; + if (y > minY && y < maxY) + return true; + y = m * (maxX - x1) + y1; + if (y > minY && y < maxY) + return true; + var x = (minY - y1) / m + x1; + if (x > minX && x < maxX) + return true; + x = (maxY - y1) / m + x1; + if (x > minX && x < maxX) + return true; + return false; + }; + SkeletonBounds.prototype.aabbIntersectsSkeleton = function (bounds) { + return this.minX < bounds.maxX && this.maxX > bounds.minX && this.minY < bounds.maxY && this.maxY > bounds.minY; + }; + SkeletonBounds.prototype.containsPoint = function (x, y) { + var polygons = this.polygons; + for (var i = 0, n = polygons.length; i < n; i++) + if (this.containsPointPolygon(polygons[i], x, y)) + return this.boundingBoxes[i]; + return null; + }; + SkeletonBounds.prototype.containsPointPolygon = function (polygon, x, y) { + var vertices = polygon; + var nn = polygon.length; + var prevIndex = nn - 2; + var inside = false; + for (var ii = 0; ii < nn; ii += 2) { + var vertexY = vertices[ii + 1]; + var prevY = vertices[prevIndex + 1]; + if ((vertexY < y && prevY >= y) || (prevY < y && vertexY >= y)) { + var vertexX = vertices[ii]; + if (vertexX + (y - vertexY) / (prevY - vertexY) * (vertices[prevIndex] - vertexX) < x) + inside = !inside; + } + prevIndex = ii; + } + return inside; + }; + SkeletonBounds.prototype.intersectsSegment = function (x1, y1, x2, y2) { + var polygons = this.polygons; + for (var i = 0, n = polygons.length; i < n; i++) + if (this.intersectsSegmentPolygon(polygons[i], x1, y1, x2, y2)) + return this.boundingBoxes[i]; + return null; + }; + SkeletonBounds.prototype.intersectsSegmentPolygon = function (polygon, x1, y1, x2, y2) { + var vertices = polygon; + var nn = polygon.length; + var width12 = x1 - x2, height12 = y1 - y2; + var det1 = x1 * y2 - y1 * x2; + var x3 = vertices[nn - 2], y3 = vertices[nn - 1]; + for (var ii = 0; ii < nn; ii += 2) { + var x4 = vertices[ii], y4 = vertices[ii + 1]; + var det2 = x3 * y4 - y3 * x4; + var width34 = x3 - x4, height34 = y3 - y4; + var det3 = width12 * height34 - height12 * width34; + var x = (det1 * width34 - width12 * det2) / det3; + if (((x >= x3 && x <= x4) || (x >= x4 && x <= x3)) && ((x >= x1 && x <= x2) || (x >= x2 && x <= x1))) { + var y = (det1 * height34 - height12 * det2) / det3; + if (((y >= y3 && y <= y4) || (y >= y4 && y <= y3)) && ((y >= y1 && y <= y2) || (y >= y2 && y <= y1))) + return true; + } + x3 = x4; + y3 = y4; + } + return false; + }; + SkeletonBounds.prototype.getPolygon = function (boundingBox) { + if (boundingBox == null) + throw new Error("boundingBox cannot be null."); + var index = this.boundingBoxes.indexOf(boundingBox); + return index == -1 ? null : this.polygons[index]; + }; + SkeletonBounds.prototype.getWidth = function () { + return this.maxX - this.minX; + }; + SkeletonBounds.prototype.getHeight = function () { + return this.maxY - this.minY; + }; + return SkeletonBounds; + }()); + spine.SkeletonBounds = SkeletonBounds; +})(spine || (spine = {})); +var spine; +(function (spine) { + var SkeletonData = (function () { + function SkeletonData() { + this.bones = new Array(); + this.slots = new Array(); + this.skins = new Array(); + this.events = new Array(); + this.animations = new Array(); + this.ikConstraints = new Array(); + this.transformConstraints = new Array(); + this.pathConstraints = new Array(); + this.fps = 0; + } + SkeletonData.prototype.findBone = function (boneName) { + if (boneName == null) + throw new Error("boneName cannot be null."); + var bones = this.bones; + for (var i = 0, n = bones.length; i < n; i++) { + var bone = bones[i]; + if (bone.name == boneName) + return bone; + } + return null; + }; + SkeletonData.prototype.findBoneIndex = function (boneName) { + if (boneName == null) + throw new Error("boneName cannot be null."); + var bones = this.bones; + for (var i = 0, n = bones.length; i < n; i++) + if (bones[i].name == boneName) + return i; + return -1; + }; + SkeletonData.prototype.findSlot = function (slotName) { + if (slotName == null) + throw new Error("slotName cannot be null."); + var slots = this.slots; + for (var i = 0, n = slots.length; i < n; i++) { + var slot = slots[i]; + if (slot.name == slotName) + return slot; + } + return null; + }; + SkeletonData.prototype.findSlotIndex = function (slotName) { + if (slotName == null) + throw new Error("slotName cannot be null."); + var slots = this.slots; + for (var i = 0, n = slots.length; i < n; i++) + if (slots[i].name == slotName) + return i; + return -1; + }; + SkeletonData.prototype.findSkin = function (skinName) { + if (skinName == null) + throw new Error("skinName cannot be null."); + var skins = this.skins; + for (var i = 0, n = skins.length; i < n; i++) { + var skin = skins[i]; + if (skin.name == skinName) + return skin; + } + return null; + }; + SkeletonData.prototype.findEvent = function (eventDataName) { + if (eventDataName == null) + throw new Error("eventDataName cannot be null."); + var events = this.events; + for (var i = 0, n = events.length; i < n; i++) { + var event_4 = events[i]; + if (event_4.name == eventDataName) + return event_4; + } + return null; + }; + SkeletonData.prototype.findAnimation = function (animationName) { + if (animationName == null) + throw new Error("animationName cannot be null."); + var animations = this.animations; + for (var i = 0, n = animations.length; i < n; i++) { + var animation = animations[i]; + if (animation.name == animationName) + return animation; + } + return null; + }; + SkeletonData.prototype.findIkConstraint = function (constraintName) { + if (constraintName == null) + throw new Error("constraintName cannot be null."); + var ikConstraints = this.ikConstraints; + for (var i = 0, n = ikConstraints.length; i < n; i++) { + var constraint = ikConstraints[i]; + if (constraint.name == constraintName) + return constraint; + } + return null; + }; + SkeletonData.prototype.findTransformConstraint = function (constraintName) { + if (constraintName == null) + throw new Error("constraintName cannot be null."); + var transformConstraints = this.transformConstraints; + for (var i = 0, n = transformConstraints.length; i < n; i++) { + var constraint = transformConstraints[i]; + if (constraint.name == constraintName) + return constraint; + } + return null; + }; + SkeletonData.prototype.findPathConstraint = function (constraintName) { + if (constraintName == null) + throw new Error("constraintName cannot be null."); + var pathConstraints = this.pathConstraints; + for (var i = 0, n = pathConstraints.length; i < n; i++) { + var constraint = pathConstraints[i]; + if (constraint.name == constraintName) + return constraint; + } + return null; + }; + SkeletonData.prototype.findPathConstraintIndex = function (pathConstraintName) { + if (pathConstraintName == null) + throw new Error("pathConstraintName cannot be null."); + var pathConstraints = this.pathConstraints; + for (var i = 0, n = pathConstraints.length; i < n; i++) + if (pathConstraints[i].name == pathConstraintName) + return i; + return -1; + }; + return SkeletonData; + }()); + spine.SkeletonData = SkeletonData; +})(spine || (spine = {})); +var spine; +(function (spine) { + var SkeletonJson = (function () { + function SkeletonJson(attachmentLoader) { + this.scale = 1; + this.linkedMeshes = new Array(); + this.attachmentLoader = attachmentLoader; + } + SkeletonJson.prototype.readSkeletonData = function (json) { + var scale = this.scale; + var skeletonData = new spine.SkeletonData(); + var root = typeof (json) === "string" ? JSON.parse(json) : json; + var skeletonMap = root.skeleton; + if (skeletonMap != null) { + skeletonData.hash = skeletonMap.hash; + skeletonData.version = skeletonMap.spine; + skeletonData.width = skeletonMap.width; + skeletonData.height = skeletonMap.height; + skeletonData.fps = skeletonMap.fps; + skeletonData.imagesPath = skeletonMap.images; + } + if (root.bones) { + for (var i = 0; i < root.bones.length; i++) { + var boneMap = root.bones[i]; + var parent_2 = null; + var parentName = this.getValue(boneMap, "parent", null); + if (parentName != null) { + parent_2 = skeletonData.findBone(parentName); + if (parent_2 == null) + throw new Error("Parent bone not found: " + parentName); + } + var data = new spine.BoneData(skeletonData.bones.length, boneMap.name, parent_2); + data.length = this.getValue(boneMap, "length", 0) * scale; + data.x = this.getValue(boneMap, "x", 0) * scale; + data.y = this.getValue(boneMap, "y", 0) * scale; + data.rotation = this.getValue(boneMap, "rotation", 0); + data.scaleX = this.getValue(boneMap, "scaleX", 1); + data.scaleY = this.getValue(boneMap, "scaleY", 1); + data.shearX = this.getValue(boneMap, "shearX", 0); + data.shearY = this.getValue(boneMap, "shearY", 0); + data.transformMode = SkeletonJson.transformModeFromString(this.getValue(boneMap, "transform", "normal")); + skeletonData.bones.push(data); + } + } + if (root.slots) { + for (var i = 0; i < root.slots.length; i++) { + var slotMap = root.slots[i]; + var slotName = slotMap.name; + var boneName = slotMap.bone; + var boneData = skeletonData.findBone(boneName); + if (boneData == null) + throw new Error("Slot bone not found: " + boneName); + var data = new spine.SlotData(skeletonData.slots.length, slotName, boneData); + var color = this.getValue(slotMap, "color", null); + if (color != null) + data.color.setFromString(color); + data.attachmentName = this.getValue(slotMap, "attachment", null); + data.blendMode = SkeletonJson.blendModeFromString(this.getValue(slotMap, "blend", "normal")); + skeletonData.slots.push(data); + } + } + if (root.ik) { + for (var i = 0; i < root.ik.length; i++) { + var constraintMap = root.ik[i]; + var data = new spine.IkConstraintData(constraintMap.name); + data.order = this.getValue(constraintMap, "order", 0); + for (var j = 0; j < constraintMap.bones.length; j++) { + var boneName = constraintMap.bones[j]; + var bone = skeletonData.findBone(boneName); + if (bone == null) + throw new Error("IK bone not found: " + boneName); + data.bones.push(bone); + } + var targetName = constraintMap.target; + data.target = skeletonData.findBone(targetName); + if (data.target == null) + throw new Error("IK target bone not found: " + targetName); + data.bendDirection = this.getValue(constraintMap, "bendPositive", true) ? 1 : -1; + data.mix = this.getValue(constraintMap, "mix", 1); + skeletonData.ikConstraints.push(data); + } + } + if (root.transform) { + for (var i = 0; i < root.transform.length; i++) { + var constraintMap = root.transform[i]; + var data = new spine.TransformConstraintData(constraintMap.name); + data.order = this.getValue(constraintMap, "order", 0); + for (var j = 0; j < constraintMap.bones.length; j++) { + var boneName = constraintMap.bones[j]; + var bone = skeletonData.findBone(boneName); + if (bone == null) + throw new Error("Transform constraint bone not found: " + boneName); + data.bones.push(bone); + } + var targetName = constraintMap.target; + data.target = skeletonData.findBone(targetName); + if (data.target == null) + throw new Error("Transform constraint target bone not found: " + targetName); + data.offsetRotation = this.getValue(constraintMap, "rotation", 0); + data.offsetX = this.getValue(constraintMap, "x", 0) * scale; + data.offsetY = this.getValue(constraintMap, "y", 0) * scale; + data.offsetScaleX = this.getValue(constraintMap, "scaleX", 0); + data.offsetScaleY = this.getValue(constraintMap, "scaleY", 0); + data.offsetShearY = this.getValue(constraintMap, "shearY", 0); + data.rotateMix = this.getValue(constraintMap, "rotateMix", 1); + data.translateMix = this.getValue(constraintMap, "translateMix", 1); + data.scaleMix = this.getValue(constraintMap, "scaleMix", 1); + data.shearMix = this.getValue(constraintMap, "shearMix", 1); + skeletonData.transformConstraints.push(data); + } + } + if (root.path) { + for (var i = 0; i < root.path.length; i++) { + var constraintMap = root.path[i]; + var data = new spine.PathConstraintData(constraintMap.name); + data.order = this.getValue(constraintMap, "order", 0); + for (var j = 0; j < constraintMap.bones.length; j++) { + var boneName = constraintMap.bones[j]; + var bone = skeletonData.findBone(boneName); + if (bone == null) + throw new Error("Transform constraint bone not found: " + boneName); + data.bones.push(bone); + } + var targetName = constraintMap.target; + data.target = skeletonData.findSlot(targetName); + if (data.target == null) + throw new Error("Path target slot not found: " + targetName); + data.positionMode = SkeletonJson.positionModeFromString(this.getValue(constraintMap, "positionMode", "percent")); + data.spacingMode = SkeletonJson.spacingModeFromString(this.getValue(constraintMap, "spacingMode", "length")); + data.rotateMode = SkeletonJson.rotateModeFromString(this.getValue(constraintMap, "rotateMode", "tangent")); + data.offsetRotation = this.getValue(constraintMap, "rotation", 0); + data.position = this.getValue(constraintMap, "position", 0); + if (data.positionMode == spine.PositionMode.Fixed) + data.position *= scale; + data.spacing = this.getValue(constraintMap, "spacing", 0); + if (data.spacingMode == spine.SpacingMode.Length || data.spacingMode == spine.SpacingMode.Fixed) + data.spacing *= scale; + data.rotateMix = this.getValue(constraintMap, "rotateMix", 1); + data.translateMix = this.getValue(constraintMap, "translateMix", 1); + skeletonData.pathConstraints.push(data); + } + } + if (root.skins) { + for (var skinName in root.skins) { + var skinMap = root.skins[skinName]; + var skin = new spine.Skin(skinName); + for (var slotName in skinMap) { + var slotIndex = skeletonData.findSlotIndex(slotName); + if (slotIndex == -1) + throw new Error("Slot not found: " + slotName); + var slotMap = skinMap[slotName]; + for (var entryName in slotMap) { + var attachment = this.readAttachment(slotMap[entryName], skin, slotIndex, entryName); + if (attachment != null) + skin.addAttachment(slotIndex, entryName, attachment); + } + } + skeletonData.skins.push(skin); + if (skin.name == "default") + skeletonData.defaultSkin = skin; + } + } + for (var i = 0, n = this.linkedMeshes.length; i < n; i++) { + var linkedMesh = this.linkedMeshes[i]; + var skin = linkedMesh.skin == null ? skeletonData.defaultSkin : skeletonData.findSkin(linkedMesh.skin); + if (skin == null) + throw new Error("Skin not found: " + linkedMesh.skin); + var parent_3 = skin.getAttachment(linkedMesh.slotIndex, linkedMesh.parent); + if (parent_3 == null) + throw new Error("Parent mesh not found: " + linkedMesh.parent); + linkedMesh.mesh.setParentMesh(parent_3); + linkedMesh.mesh.updateUVs(); + } + this.linkedMeshes.length = 0; + if (root.events) { + for (var eventName in root.events) { + var eventMap = root.events[eventName]; + var data = new spine.EventData(eventName); + data.intValue = this.getValue(eventMap, "int", 0); + data.floatValue = this.getValue(eventMap, "float", 0); + data.stringValue = this.getValue(eventMap, "string", ""); + skeletonData.events.push(data); + } + } + if (root.animations) { + for (var animationName in root.animations) { + var animationMap = root.animations[animationName]; + this.readAnimation(animationMap, animationName, skeletonData); + } + } + return skeletonData; + }; + SkeletonJson.prototype.readAttachment = function (map, skin, slotIndex, name) { + var scale = this.scale; + name = this.getValue(map, "name", name); + var type = this.getValue(map, "type", "region"); + switch (type) { + case "region": { + var path = this.getValue(map, "path", name); + var region = this.attachmentLoader.newRegionAttachment(skin, name, path); + if (region == null) + return null; + region.path = path; + region.x = this.getValue(map, "x", 0) * scale; + region.y = this.getValue(map, "y", 0) * scale; + region.scaleX = this.getValue(map, "scaleX", 1); + region.scaleY = this.getValue(map, "scaleY", 1); + region.rotation = this.getValue(map, "rotation", 0); + region.width = map.width * scale; + region.height = map.height * scale; + var color = this.getValue(map, "color", null); + if (color != null) + region.color.setFromString(color); + region.updateOffset(); + return region; + } + case "boundingbox": { + var box = this.attachmentLoader.newBoundingBoxAttachment(skin, name); + if (box == null) + return null; + this.readVertices(map, box, map.vertexCount << 1); + var color = this.getValue(map, "color", null); + if (color != null) + box.color.setFromString(color); + return box; + } + case "mesh": + case "linkedmesh": { + var path = this.getValue(map, "path", name); + var mesh = this.attachmentLoader.newMeshAttachment(skin, name, path); + if (mesh == null) + return null; + mesh.path = path; + var color = this.getValue(map, "color", null); + if (color != null) + mesh.color.setFromString(color); + var parent_4 = this.getValue(map, "parent", null); + if (parent_4 != null) { + mesh.inheritDeform = this.getValue(map, "deform", true); + this.linkedMeshes.push(new LinkedMesh(mesh, this.getValue(map, "skin", null), slotIndex, parent_4)); + return mesh; + } + var uvs = map.uvs; + this.readVertices(map, mesh, uvs.length); + mesh.triangles = map.triangles; + mesh.regionUVs = uvs; + mesh.updateUVs(); + mesh.hullLength = this.getValue(map, "hull", 0) * 2; + return mesh; + } + case "path": { + var path = this.attachmentLoader.newPathAttachment(skin, name); + if (path == null) + return null; + path.closed = this.getValue(map, "closed", false); + path.constantSpeed = this.getValue(map, "constantSpeed", true); + var vertexCount = map.vertexCount; + this.readVertices(map, path, vertexCount << 1); + var lengths = spine.Utils.newArray(vertexCount / 3, 0); + for (var i = 0; i < map.lengths.length; i++) + lengths[i++] = map.lengths[i] * scale; + path.lengths = lengths; + var color = this.getValue(map, "color", null); + if (color != null) + path.color.setFromString(color); + return path; + } + } + return null; + }; + SkeletonJson.prototype.readVertices = function (map, attachment, verticesLength) { + var scale = this.scale; + attachment.worldVerticesLength = verticesLength; + var vertices = map.vertices; + if (verticesLength == vertices.length) { + if (scale != 1) { + for (var i = 0, n = vertices.length; i < n; i++) + vertices[i] *= scale; + } + attachment.vertices = spine.Utils.toFloatArray(vertices); + return; + } + var weights = new Array(); + var bones = new Array(); + for (var i = 0, n = vertices.length; i < n;) { + var boneCount = vertices[i++]; + bones.push(boneCount); + for (var nn = i + boneCount * 4; i < nn; i += 4) { + bones.push(vertices[i]); + weights.push(vertices[i + 1] * scale); + weights.push(vertices[i + 2] * scale); + weights.push(vertices[i + 3]); + } + } + attachment.bones = bones; + attachment.vertices = spine.Utils.toFloatArray(weights); + }; + SkeletonJson.prototype.readAnimation = function (map, name, skeletonData) { + var scale = this.scale; + var timelines = new Array(); + var duration = 0; + if (map.slots) { + for (var slotName in map.slots) { + var slotMap = map.slots[slotName]; + var slotIndex = skeletonData.findSlotIndex(slotName); + if (slotIndex == -1) + throw new Error("Slot not found: " + slotName); + for (var timelineName in slotMap) { + var timelineMap = slotMap[timelineName]; + if (timelineName == "color") { + var timeline = new spine.ColorTimeline(timelineMap.length); + timeline.slotIndex = slotIndex; + var frameIndex = 0; + for (var i = 0; i < timelineMap.length; i++) { + var valueMap = timelineMap[i]; + var color = new spine.Color(); + color.setFromString(valueMap.color); + timeline.setFrame(frameIndex, valueMap.time, color.r, color.g, color.b, color.a); + this.readCurve(valueMap, timeline, frameIndex); + frameIndex++; + } + timelines.push(timeline); + duration = Math.max(duration, timeline.frames[(timeline.getFrameCount() - 1) * spine.ColorTimeline.ENTRIES]); + } + else if (timelineName = "attachment") { + var timeline = new spine.AttachmentTimeline(timelineMap.length); + timeline.slotIndex = slotIndex; + var frameIndex = 0; + for (var i = 0; i < timelineMap.length; i++) { + var valueMap = timelineMap[i]; + timeline.setFrame(frameIndex++, valueMap.time, valueMap.name); + } + timelines.push(timeline); + duration = Math.max(duration, timeline.frames[timeline.getFrameCount() - 1]); + } + else + throw new Error("Invalid timeline type for a slot: " + timelineName + " (" + slotName + ")"); + } + } + } + if (map.bones) { + for (var boneName in map.bones) { + var boneMap = map.bones[boneName]; + var boneIndex = skeletonData.findBoneIndex(boneName); + if (boneIndex == -1) + throw new Error("Bone not found: " + boneName); + for (var timelineName in boneMap) { + var timelineMap = boneMap[timelineName]; + if (timelineName === "rotate") { + var timeline = new spine.RotateTimeline(timelineMap.length); + timeline.boneIndex = boneIndex; + var frameIndex = 0; + for (var i = 0; i < timelineMap.length; i++) { + var valueMap = timelineMap[i]; + timeline.setFrame(frameIndex, valueMap.time, valueMap.angle); + this.readCurve(valueMap, timeline, frameIndex); + frameIndex++; + } + timelines.push(timeline); + duration = Math.max(duration, timeline.frames[(timeline.getFrameCount() - 1) * spine.RotateTimeline.ENTRIES]); + } + else if (timelineName === "translate" || timelineName === "scale" || timelineName === "shear") { + var timeline = null; + var timelineScale = 1; + if (timelineName === "scale") + timeline = new spine.ScaleTimeline(timelineMap.length); + else if (timelineName === "shear") + timeline = new spine.ShearTimeline(timelineMap.length); + else { + timeline = new spine.TranslateTimeline(timelineMap.length); + timelineScale = scale; + } + timeline.boneIndex = boneIndex; + var frameIndex = 0; + for (var i = 0; i < timelineMap.length; i++) { + var valueMap = timelineMap[i]; + var x = this.getValue(valueMap, "x", 0), y = this.getValue(valueMap, "y", 0); + timeline.setFrame(frameIndex, valueMap.time, x * timelineScale, y * timelineScale); + this.readCurve(valueMap, timeline, frameIndex); + frameIndex++; + } + timelines.push(timeline); + duration = Math.max(duration, timeline.frames[(timeline.getFrameCount() - 1) * spine.TranslateTimeline.ENTRIES]); + } + else + throw new Error("Invalid timeline type for a bone: " + timelineName + " (" + boneName + ")"); + } + } + } + if (map.ik) { + for (var constraintName in map.ik) { + var constraintMap = map.ik[constraintName]; + var constraint = skeletonData.findIkConstraint(constraintName); + var timeline = new spine.IkConstraintTimeline(constraintMap.length); + timeline.ikConstraintIndex = skeletonData.ikConstraints.indexOf(constraint); + var frameIndex = 0; + for (var i = 0; i < constraintMap.length; i++) { + var valueMap = constraintMap[i]; + timeline.setFrame(frameIndex, valueMap.time, this.getValue(valueMap, "mix", 1), this.getValue(valueMap, "bendPositive", true) ? 1 : -1); + this.readCurve(valueMap, timeline, frameIndex); + frameIndex++; + } + timelines.push(timeline); + duration = Math.max(duration, timeline.frames[(timeline.getFrameCount() - 1) * spine.IkConstraintTimeline.ENTRIES]); + } + } + if (map.transform) { + for (var constraintName in map.transform) { + var constraintMap = map.transform[constraintName]; + var constraint = skeletonData.findTransformConstraint(constraintName); + var timeline = new spine.TransformConstraintTimeline(constraintMap.length); + timeline.transformConstraintIndex = skeletonData.transformConstraints.indexOf(constraint); + var frameIndex = 0; + for (var i = 0; i < constraintMap.length; i++) { + var valueMap = constraintMap[i]; + timeline.setFrame(frameIndex, valueMap.time, this.getValue(valueMap, "rotateMix", 1), this.getValue(valueMap, "translateMix", 1), this.getValue(valueMap, "scaleMix", 1), this.getValue(valueMap, "shearMix", 1)); + this.readCurve(valueMap, timeline, frameIndex); + frameIndex++; + } + timelines.push(timeline); + duration = Math.max(duration, timeline.frames[(timeline.getFrameCount() - 1) * spine.TransformConstraintTimeline.ENTRIES]); + } + } + if (map.paths) { + for (var constraintName in map.paths) { + var constraintMap = map.paths[constraintName]; + var index = skeletonData.findPathConstraintIndex(constraintName); + if (index == -1) + throw new Error("Path constraint not found: " + constraintName); + var data = skeletonData.pathConstraints[index]; + for (var timelineName in constraintMap) { + var timelineMap = constraintMap[timelineName]; + if (timelineName === "position" || timelineName === "spacing") { + var timeline = null; + var timelineScale = 1; + if (timelineName === "spacing") { + timeline = new spine.PathConstraintSpacingTimeline(timelineMap.length); + if (data.spacingMode == spine.SpacingMode.Length || data.spacingMode == spine.SpacingMode.Fixed) + timelineScale = scale; + } + else { + timeline = new spine.PathConstraintPositionTimeline(timelineMap.length); + if (data.positionMode == spine.PositionMode.Fixed) + timelineScale = scale; + } + timeline.pathConstraintIndex = index; + var frameIndex = 0; + for (var i = 0; i < timelineMap.length; i++) { + var valueMap = timelineMap[i]; + timeline.setFrame(frameIndex, valueMap.time, this.getValue(valueMap, timelineName, 0) * timelineScale); + this.readCurve(valueMap, timeline, frameIndex); + frameIndex++; + } + timelines.push(timeline); + duration = Math.max(duration, timeline.frames[(timeline.getFrameCount() - 1) * spine.PathConstraintPositionTimeline.ENTRIES]); + } + else if (timelineName === "mix") { + var timeline = new spine.PathConstraintMixTimeline(timelineMap.length); + timeline.pathConstraintIndex = index; + var frameIndex = 0; + for (var i = 0; i < timelineMap.length; i++) { + var valueMap = timelineMap[i]; + timeline.setFrame(frameIndex, valueMap.time, this.getValue(valueMap, "rotateMix", 1), this.getValue(valueMap, "translateMix", 1)); + this.readCurve(valueMap, timeline, frameIndex); + frameIndex++; + } + timelines.push(timeline); + duration = Math.max(duration, timeline.frames[(timeline.getFrameCount() - 1) * spine.PathConstraintMixTimeline.ENTRIES]); + } + } + } + } + if (map.deform) { + for (var deformName in map.deform) { + var deformMap = map.deform[deformName]; + var skin = skeletonData.findSkin(deformName); + if (skin == null) + throw new Error("Skin not found: " + deformName); + for (var slotName in deformMap) { + var slotMap = deformMap[slotName]; + var slotIndex = skeletonData.findSlotIndex(slotName); + if (slotIndex == -1) + throw new Error("Slot not found: " + slotMap.name); + for (var timelineName in slotMap) { + var timelineMap = slotMap[timelineName]; + var attachment = skin.getAttachment(slotIndex, timelineName); + if (attachment == null) + throw new Error("Deform attachment not found: " + timelineMap.name); + var weighted = attachment.bones != null; + var vertices = attachment.vertices; + var deformLength = weighted ? vertices.length / 3 * 2 : vertices.length; + var timeline = new spine.DeformTimeline(timelineMap.length); + timeline.slotIndex = slotIndex; + timeline.attachment = attachment; + var frameIndex = 0; + for (var j = 0; j < timelineMap.length; j++) { + var valueMap = timelineMap[j]; + var deform = void 0; + var verticesValue = this.getValue(valueMap, "vertices", null); + if (verticesValue == null) + deform = weighted ? spine.Utils.newFloatArray(deformLength) : vertices; + else { + deform = spine.Utils.newFloatArray(deformLength); + var start = this.getValue(valueMap, "offset", 0); + spine.Utils.arrayCopy(verticesValue, 0, deform, start, verticesValue.length); + if (scale != 1) { + for (var i = start, n = i + verticesValue.length; i < n; i++) + deform[i] *= scale; + } + if (!weighted) { + for (var i = 0; i < deformLength; i++) + deform[i] += vertices[i]; + } + } + timeline.setFrame(frameIndex, valueMap.time, deform); + this.readCurve(valueMap, timeline, frameIndex); + frameIndex++; + } + timelines.push(timeline); + duration = Math.max(duration, timeline.frames[timeline.getFrameCount() - 1]); + } + } + } + } + var drawOrderNode = map.drawOrder; + if (drawOrderNode == null) + drawOrderNode = map.draworder; + if (drawOrderNode != null) { + var timeline = new spine.DrawOrderTimeline(drawOrderNode.length); + var slotCount = skeletonData.slots.length; + var frameIndex = 0; + for (var j = 0; j < drawOrderNode.length; j++) { + var drawOrderMap = drawOrderNode[j]; + var drawOrder = null; + var offsets = this.getValue(drawOrderMap, "offsets", null); + if (offsets != null) { + drawOrder = spine.Utils.newArray(slotCount, -1); + var unchanged = spine.Utils.newArray(slotCount - offsets.length, 0); + var originalIndex = 0, unchangedIndex = 0; + for (var i = 0; i < offsets.length; i++) { + var offsetMap = offsets[i]; + var slotIndex = skeletonData.findSlotIndex(offsetMap.slot); + if (slotIndex == -1) + throw new Error("Slot not found: " + offsetMap.slot); + while (originalIndex != slotIndex) + unchanged[unchangedIndex++] = originalIndex++; + drawOrder[originalIndex + offsetMap.offset] = originalIndex++; + } + while (originalIndex < slotCount) + unchanged[unchangedIndex++] = originalIndex++; + for (var i = slotCount - 1; i >= 0; i--) + if (drawOrder[i] == -1) + drawOrder[i] = unchanged[--unchangedIndex]; + } + timeline.setFrame(frameIndex++, drawOrderMap.time, drawOrder); + } + timelines.push(timeline); + duration = Math.max(duration, timeline.frames[timeline.getFrameCount() - 1]); + } + if (map.events) { + var timeline = new spine.EventTimeline(map.events.length); + var frameIndex = 0; + for (var i = 0; i < map.events.length; i++) { + var eventMap = map.events[i]; + var eventData = skeletonData.findEvent(eventMap.name); + if (eventData == null) + throw new Error("Event not found: " + eventMap.name); + var event_5 = new spine.Event(eventMap.time, eventData); + event_5.intValue = this.getValue(eventMap, "int", eventData.intValue); + event_5.floatValue = this.getValue(eventMap, "float", eventData.floatValue); + event_5.stringValue = this.getValue(eventMap, "string", eventData.stringValue); + timeline.setFrame(frameIndex++, event_5); + } + timelines.push(timeline); + duration = Math.max(duration, timeline.frames[timeline.getFrameCount() - 1]); + } + if (isNaN(duration)) { + throw new Error("Error while parsing animation, duration is NaN"); + } + skeletonData.animations.push(new spine.Animation(name, timelines, duration)); + }; + SkeletonJson.prototype.readCurve = function (map, timeline, frameIndex) { + if (!map.curve) + return; + if (map.curve === "stepped") + timeline.setStepped(frameIndex); + else if (Object.prototype.toString.call(map.curve) === '[object Array]') { + var curve = map.curve; + timeline.setCurve(frameIndex, curve[0], curve[1], curve[2], curve[3]); + } + }; + SkeletonJson.prototype.getValue = function (map, prop, defaultValue) { + return map[prop] !== undefined ? map[prop] : defaultValue; + }; + SkeletonJson.blendModeFromString = function (str) { + str = str.toLowerCase(); + if (str == "normal") + return spine.BlendMode.Normal; + if (str == "additive") + return spine.BlendMode.Additive; + if (str == "multiply") + return spine.BlendMode.Multiply; + if (str == "screen") + return spine.BlendMode.Screen; + throw new Error("Unknown blend mode: " + str); + }; + SkeletonJson.positionModeFromString = function (str) { + str = str.toLowerCase(); + if (str == "fixed") + return spine.PositionMode.Fixed; + if (str == "percent") + return spine.PositionMode.Percent; + throw new Error("Unknown position mode: " + str); + }; + SkeletonJson.spacingModeFromString = function (str) { + str = str.toLowerCase(); + if (str == "length") + return spine.SpacingMode.Length; + if (str == "fixed") + return spine.SpacingMode.Fixed; + if (str == "percent") + return spine.SpacingMode.Percent; + throw new Error("Unknown position mode: " + str); + }; + SkeletonJson.rotateModeFromString = function (str) { + str = str.toLowerCase(); + if (str == "tangent") + return spine.RotateMode.Tangent; + if (str == "chain") + return spine.RotateMode.Chain; + if (str == "chainscale") + return spine.RotateMode.ChainScale; + throw new Error("Unknown rotate mode: " + str); + }; + SkeletonJson.transformModeFromString = function (str) { + str = str.toLowerCase(); + if (str == "normal") + return spine.TransformMode.Normal; + if (str == "onlytranslation") + return spine.TransformMode.OnlyTranslation; + if (str == "norotationorreflection") + return spine.TransformMode.NoRotationOrReflection; + if (str == "noscale") + return spine.TransformMode.NoScale; + if (str == "noscaleorreflection") + return spine.TransformMode.NoScaleOrReflection; + throw new Error("Unknown transform mode: " + str); + }; + return SkeletonJson; + }()); + spine.SkeletonJson = SkeletonJson; + var LinkedMesh = (function () { + function LinkedMesh(mesh, skin, slotIndex, parent) { + this.mesh = mesh; + this.skin = skin; + this.slotIndex = slotIndex; + this.parent = parent; + } + return LinkedMesh; + }()); +})(spine || (spine = {})); +var spine; +(function (spine) { + var Skin = (function () { + function Skin(name) { + this.attachments = new Array(); + if (name == null) + throw new Error("name cannot be null."); + this.name = name; + } + Skin.prototype.addAttachment = function (slotIndex, name, attachment) { + if (attachment == null) + throw new Error("attachment cannot be null."); + var attachments = this.attachments; + if (slotIndex >= attachments.length) + attachments.length = slotIndex + 1; + if (!attachments[slotIndex]) + attachments[slotIndex] = {}; + attachments[slotIndex][name] = attachment; + }; + Skin.prototype.getAttachment = function (slotIndex, name) { + var dictionary = this.attachments[slotIndex]; + return dictionary ? dictionary[name] : null; + }; + Skin.prototype.attachAll = function (skeleton, oldSkin) { + var slotIndex = 0; + for (var i = 0; i < skeleton.slots.length; i++) { + var slot = skeleton.slots[i]; + var slotAttachment = slot.getAttachment(); + if (slotAttachment && slotIndex < oldSkin.attachments.length) { + var dictionary = oldSkin.attachments[slotIndex]; + for (var key in dictionary) { + var skinAttachment = dictionary[key]; + if (slotAttachment == skinAttachment) { + var attachment = this.getAttachment(slotIndex, key); + if (attachment != null) + slot.setAttachment(attachment); + break; + } + } + } + slotIndex++; + } + }; + return Skin; + }()); + spine.Skin = Skin; +})(spine || (spine = {})); +var spine; +(function (spine) { + var Slot = (function () { + function Slot(data, bone) { + this.attachmentVertices = new Array(); + if (data == null) + throw new Error("data cannot be null."); + if (bone == null) + throw new Error("bone cannot be null."); + this.data = data; + this.bone = bone; + this.color = new spine.Color(); + this.setToSetupPose(); + } + Slot.prototype.getAttachment = function () { + return this.attachment; + }; + Slot.prototype.setAttachment = function (attachment) { + if (this.attachment == attachment) + return; + this.attachment = attachment; + this.attachmentTime = this.bone.skeleton.time; + this.attachmentVertices.length = 0; + }; + Slot.prototype.setAttachmentTime = function (time) { + this.attachmentTime = this.bone.skeleton.time - time; + }; + Slot.prototype.getAttachmentTime = function () { + return this.bone.skeleton.time - this.attachmentTime; + }; + Slot.prototype.setToSetupPose = function () { + this.color.setFromColor(this.data.color); + if (this.data.attachmentName == null) + this.attachment = null; + else { + this.attachment = null; + this.setAttachment(this.bone.skeleton.getAttachment(this.data.index, this.data.attachmentName)); + } + }; + return Slot; + }()); + spine.Slot = Slot; +})(spine || (spine = {})); +var spine; +(function (spine) { + var SlotData = (function () { + function SlotData(index, name, boneData) { + this.color = new spine.Color(1, 1, 1, 1); + if (index < 0) + throw new Error("index must be >= 0."); + if (name == null) + throw new Error("name cannot be null."); + if (boneData == null) + throw new Error("boneData cannot be null."); + this.index = index; + this.name = name; + this.boneData = boneData; + } + return SlotData; + }()); + spine.SlotData = SlotData; +})(spine || (spine = {})); +var spine; +(function (spine) { + var Texture = (function () { + function Texture(image) { + this._image = image; + } + Texture.prototype.getImage = function () { + return this._image; + }; + Texture.filterFromString = function (text) { + switch (text.toLowerCase()) { + case "nearest": return TextureFilter.Nearest; + case "linear": return TextureFilter.Linear; + case "mipmap": return TextureFilter.MipMap; + case "mipmapnearestnearest": return TextureFilter.MipMapNearestNearest; + case "mipmaplinearnearest": return TextureFilter.MipMapLinearNearest; + case "mipmapnearestlinear": return TextureFilter.MipMapNearestLinear; + case "mipmaplinearlinear": return TextureFilter.MipMapLinearLinear; + default: throw new Error("Unknown texture filter " + text); + } + }; + Texture.wrapFromString = function (text) { + switch (text.toLowerCase()) { + case "mirroredtepeat": return TextureWrap.MirroredRepeat; + case "clamptoedge": return TextureWrap.ClampToEdge; + case "repeat": return TextureWrap.Repeat; + default: throw new Error("Unknown texture wrap " + text); + } + }; + return Texture; + }()); + spine.Texture = Texture; + (function (TextureFilter) { + TextureFilter[TextureFilter["Nearest"] = 9728] = "Nearest"; + TextureFilter[TextureFilter["Linear"] = 9729] = "Linear"; + TextureFilter[TextureFilter["MipMap"] = 9987] = "MipMap"; + TextureFilter[TextureFilter["MipMapNearestNearest"] = 9984] = "MipMapNearestNearest"; + TextureFilter[TextureFilter["MipMapLinearNearest"] = 9985] = "MipMapLinearNearest"; + TextureFilter[TextureFilter["MipMapNearestLinear"] = 9986] = "MipMapNearestLinear"; + TextureFilter[TextureFilter["MipMapLinearLinear"] = 9987] = "MipMapLinearLinear"; + })(spine.TextureFilter || (spine.TextureFilter = {})); + var TextureFilter = spine.TextureFilter; + (function (TextureWrap) { + TextureWrap[TextureWrap["MirroredRepeat"] = 33648] = "MirroredRepeat"; + TextureWrap[TextureWrap["ClampToEdge"] = 33071] = "ClampToEdge"; + TextureWrap[TextureWrap["Repeat"] = 10497] = "Repeat"; + })(spine.TextureWrap || (spine.TextureWrap = {})); + var TextureWrap = spine.TextureWrap; + var TextureRegion = (function () { + function TextureRegion() { + this.u = 0; + this.v = 0; + this.u2 = 0; + this.v2 = 0; + this.width = 0; + this.height = 0; + this.rotate = false; + this.offsetX = 0; + this.offsetY = 0; + this.originalWidth = 0; + this.originalHeight = 0; + } + return TextureRegion; + }()); + spine.TextureRegion = TextureRegion; +})(spine || (spine = {})); +var spine; +(function (spine) { + var TextureAtlas = (function () { + function TextureAtlas(atlasText, textureLoader) { + this.pages = new Array(); + this.regions = new Array(); + this.load(atlasText, textureLoader); + } + TextureAtlas.prototype.load = function (atlasText, textureLoader) { + if (textureLoader == null) + throw new Error("textureLoader cannot be null."); + var reader = new TextureAtlasReader(atlasText); + var tuple = new Array(4); + var page = null; + while (true) { + var line = reader.readLine(); + if (line == null) + break; + line = line.trim(); + if (line.length == 0) + page = null; + else if (!page) { + page = new TextureAtlasPage(); + page.name = line; + if (reader.readTuple(tuple) == 2) { + page.width = parseInt(tuple[0]); + page.height = parseInt(tuple[1]); + reader.readTuple(tuple); + } + reader.readTuple(tuple); + page.minFilter = spine.Texture.filterFromString(tuple[0]); + page.magFilter = spine.Texture.filterFromString(tuple[1]); + var direction = reader.readValue(); + page.uWrap = spine.TextureWrap.ClampToEdge; + page.vWrap = spine.TextureWrap.ClampToEdge; + if (direction == "x") + page.uWrap = spine.TextureWrap.Repeat; + else if (direction == "y") + page.vWrap = spine.TextureWrap.Repeat; + else if (direction == "xy") + page.uWrap = page.vWrap = spine.TextureWrap.Repeat; + page.texture = textureLoader(line); + page.texture.setFilters(page.minFilter, page.magFilter); + page.texture.setWraps(page.uWrap, page.vWrap); + page.width = page.texture.getImage().width; + page.height = page.texture.getImage().height; + this.pages.push(page); + } + else { + var region = new TextureAtlasRegion(); + region.name = line; + region.page = page; + region.rotate = reader.readValue() == "true"; + reader.readTuple(tuple); + var x = parseInt(tuple[0]); + var y = parseInt(tuple[1]); + reader.readTuple(tuple); + var width = parseInt(tuple[0]); + var height = parseInt(tuple[1]); + region.u = x / page.width; + region.v = y / page.height; + if (region.rotate) { + region.u2 = (x + height) / page.width; + region.v2 = (y + width) / page.height; + } + else { + region.u2 = (x + width) / page.width; + region.v2 = (y + height) / page.height; + } + region.x = x; + region.y = y; + region.width = Math.abs(width); + region.height = Math.abs(height); + if (reader.readTuple(tuple) == 4) { + if (reader.readTuple(tuple) == 4) { + reader.readTuple(tuple); + } + } + region.originalWidth = parseInt(tuple[0]); + region.originalHeight = parseInt(tuple[1]); + reader.readTuple(tuple); + region.offsetX = parseInt(tuple[0]); + region.offsetY = parseInt(tuple[1]); + region.index = parseInt(reader.readValue()); + region.texture = page.texture; + this.regions.push(region); + } + } + }; + TextureAtlas.prototype.findRegion = function (name) { + for (var i = 0; i < this.regions.length; i++) { + if (this.regions[i].name == name) { + return this.regions[i]; + } + } + return null; + }; + TextureAtlas.prototype.dispose = function () { + for (var i = 0; i < this.pages.length; i++) { + this.pages[i].texture.dispose(); + } + }; + return TextureAtlas; + }()); + spine.TextureAtlas = TextureAtlas; + var TextureAtlasReader = (function () { + function TextureAtlasReader(text) { + this.index = 0; + this.lines = text.split(/\r\n|\r|\n/); + } + TextureAtlasReader.prototype.readLine = function () { + if (this.index >= this.lines.length) + return null; + return this.lines[this.index++]; + }; + TextureAtlasReader.prototype.readValue = function () { + var line = this.readLine(); + var colon = line.indexOf(":"); + if (colon == -1) + throw new Error("Invalid line: " + line); + return line.substring(colon + 1).trim(); + }; + TextureAtlasReader.prototype.readTuple = function (tuple) { + var line = this.readLine(); + var colon = line.indexOf(":"); + if (colon == -1) + throw new Error("Invalid line: " + line); + var i = 0, lastMatch = colon + 1; + for (; i < 3; i++) { + var comma = line.indexOf(",", lastMatch); + if (comma == -1) + break; + tuple[i] = line.substr(lastMatch, comma - lastMatch).trim(); + lastMatch = comma + 1; + } + tuple[i] = line.substring(lastMatch).trim(); + return i + 1; + }; + return TextureAtlasReader; + }()); + var TextureAtlasPage = (function () { + function TextureAtlasPage() { + } + return TextureAtlasPage; + }()); + spine.TextureAtlasPage = TextureAtlasPage; + var TextureAtlasRegion = (function (_super) { + __extends(TextureAtlasRegion, _super); + function TextureAtlasRegion() { + _super.apply(this, arguments); + } + return TextureAtlasRegion; + }(spine.TextureRegion)); + spine.TextureAtlasRegion = TextureAtlasRegion; +})(spine || (spine = {})); +var spine; +(function (spine) { + var TransformConstraint = (function () { + function TransformConstraint(data, skeleton) { + this.rotateMix = 0; + this.translateMix = 0; + this.scaleMix = 0; + this.shearMix = 0; + this.temp = new spine.Vector2(); + if (data == null) + throw new Error("data cannot be null."); + if (skeleton == null) + throw new Error("skeleton cannot be null."); + this.data = data; + this.rotateMix = data.rotateMix; + this.translateMix = data.translateMix; + this.scaleMix = data.scaleMix; + this.shearMix = data.shearMix; + this.bones = new Array(); + for (var i = 0; i < data.bones.length; i++) + this.bones.push(skeleton.findBone(data.bones[i].name)); + this.target = skeleton.findBone(data.target.name); + } + TransformConstraint.prototype.apply = function () { + this.update(); + }; + TransformConstraint.prototype.update = function () { + var rotateMix = this.rotateMix, translateMix = this.translateMix, scaleMix = this.scaleMix, shearMix = this.shearMix; + var target = this.target; + var ta = target.a, tb = target.b, tc = target.c, td = target.d; + var degRadReflect = ta * td - tb * tc > 0 ? spine.MathUtils.degRad : -spine.MathUtils.degRad; + var offsetRotation = this.data.offsetRotation * degRadReflect; + var offsetShearY = this.data.offsetShearY * degRadReflect; + var bones = this.bones; + for (var i = 0, n = bones.length; i < n; i++) { + var bone = bones[i]; + var modified = false; + if (rotateMix != 0) { + var a = bone.a, b = bone.b, c = bone.c, d = bone.d; + var r = Math.atan2(tc, ta) - Math.atan2(c, a) + offsetRotation; + if (r > spine.MathUtils.PI) + r -= spine.MathUtils.PI2; + else if (r < -spine.MathUtils.PI) + r += spine.MathUtils.PI2; + r *= rotateMix; + var cos = Math.cos(r), sin = Math.sin(r); + bone.a = cos * a - sin * c; + bone.b = cos * b - sin * d; + bone.c = sin * a + cos * c; + bone.d = sin * b + cos * d; + modified = true; + } + if (translateMix != 0) { + var temp = this.temp; + target.localToWorld(temp.set(this.data.offsetX, this.data.offsetY)); + bone.worldX += (temp.x - bone.worldX) * translateMix; + bone.worldY += (temp.y - bone.worldY) * translateMix; + modified = true; + } + if (scaleMix > 0) { + var s = Math.sqrt(bone.a * bone.a + bone.c * bone.c); + var ts = Math.sqrt(ta * ta + tc * tc); + if (s > 0.00001) + s = (s + (ts - s + this.data.offsetScaleX) * scaleMix) / s; + bone.a *= s; + bone.c *= s; + s = Math.sqrt(bone.b * bone.b + bone.d * bone.d); + ts = Math.sqrt(tb * tb + td * td); + if (s > 0.00001) + s = (s + (ts - s + this.data.offsetScaleY) * scaleMix) / s; + bone.b *= s; + bone.d *= s; + modified = true; + } + if (shearMix > 0) { + var b = bone.b, d = bone.d; + var by = Math.atan2(d, b); + var r = Math.atan2(td, tb) - Math.atan2(tc, ta) - (by - Math.atan2(bone.c, bone.a)); + if (r > spine.MathUtils.PI) + r -= spine.MathUtils.PI2; + else if (r < -spine.MathUtils.PI) + r += spine.MathUtils.PI2; + r = by + (r + offsetShearY) * shearMix; + var s = Math.sqrt(b * b + d * d); + bone.b = Math.cos(r) * s; + bone.d = Math.sin(r) * s; + modified = true; + } + if (modified) + bone.appliedValid = false; + } + }; + TransformConstraint.prototype.getOrder = function () { + return this.data.order; + }; + return TransformConstraint; + }()); + spine.TransformConstraint = TransformConstraint; +})(spine || (spine = {})); +var spine; +(function (spine) { + var TransformConstraintData = (function () { + function TransformConstraintData(name) { + this.order = 0; + this.bones = new Array(); + this.rotateMix = 0; + this.translateMix = 0; + this.scaleMix = 0; + this.shearMix = 0; + this.offsetRotation = 0; + this.offsetX = 0; + this.offsetY = 0; + this.offsetScaleX = 0; + this.offsetScaleY = 0; + this.offsetShearY = 0; + if (name == null) + throw new Error("name cannot be null."); + this.name = name; + } + return TransformConstraintData; + }()); + spine.TransformConstraintData = TransformConstraintData; +})(spine || (spine = {})); +var spine; +(function (spine) { + var IntSet = (function () { + function IntSet() { + this.array = new Array(); + } + IntSet.prototype.add = function (value) { + var contains = this.contains(value); + this.array[value | 0] = value | 0; + return !contains; + }; + IntSet.prototype.contains = function (value) { + return this.array[value | 0] != undefined; + }; + IntSet.prototype.remove = function (value) { + this.array[value | 0] = undefined; + }; + IntSet.prototype.clear = function () { + this.array.length = 0; + }; + return IntSet; + }()); + spine.IntSet = IntSet; + var Color = (function () { + function Color(r, g, b, a) { + if (r === void 0) { r = 0; } + if (g === void 0) { g = 0; } + if (b === void 0) { b = 0; } + if (a === void 0) { a = 0; } + this.r = r; + this.g = g; + this.b = b; + this.a = a; + } + Color.prototype.set = function (r, g, b, a) { + this.r = r; + this.g = g; + this.b = b; + this.a = a; + this.clamp(); + return this; + }; + Color.prototype.setFromColor = function (c) { + this.r = c.r; + this.g = c.g; + this.b = c.b; + this.a = c.a; + return this; + }; + Color.prototype.setFromString = function (hex) { + hex = hex.charAt(0) == '#' ? hex.substr(1) : hex; + this.r = parseInt(hex.substr(0, 2), 16) / 255.0; + this.g = parseInt(hex.substr(2, 2), 16) / 255.0; + this.b = parseInt(hex.substr(4, 2), 16) / 255.0; + this.a = (hex.length != 8 ? 255 : parseInt(hex.substr(6, 2), 16)) / 255.0; + return this; + }; + Color.prototype.add = function (r, g, b, a) { + this.r += r; + this.g += g; + this.b += b; + this.a += a; + this.clamp(); + return this; + }; + Color.prototype.clamp = function () { + if (this.r < 0) + this.r = 0; + else if (this.r > 1) + this.r = 1; + if (this.g < 0) + this.g = 0; + else if (this.g > 1) + this.g = 1; + if (this.b < 0) + this.b = 0; + else if (this.b > 1) + this.b = 1; + if (this.a < 0) + this.a = 0; + else if (this.a > 1) + this.a = 1; + return this; + }; + Color.WHITE = new Color(1, 1, 1, 1); + Color.RED = new Color(1, 0, 0, 1); + Color.GREEN = new Color(0, 1, 0, 1); + Color.BLUE = new Color(0, 0, 1, 1); + Color.MAGENTA = new Color(1, 0, 1, 1); + return Color; + }()); + spine.Color = Color; + var MathUtils = (function () { + function MathUtils() { + } + MathUtils.clamp = function (value, min, max) { + if (value < min) + return min; + if (value > max) + return max; + return value; + }; + MathUtils.cosDeg = function (degrees) { + return Math.cos(degrees * MathUtils.degRad); + }; + MathUtils.sinDeg = function (degrees) { + return Math.sin(degrees * MathUtils.degRad); + }; + MathUtils.signum = function (value) { + return value > 0 ? 1 : value < 0 ? -1 : 0; + }; + MathUtils.toInt = function (x) { + return x > 0 ? Math.floor(x) : Math.ceil(x); + }; + MathUtils.cbrt = function (x) { + var y = Math.pow(Math.abs(x), 1 / 3); + return x < 0 ? -y : y; + }; + MathUtils.PI = 3.1415927; + MathUtils.PI2 = MathUtils.PI * 2; + MathUtils.radiansToDegrees = 180 / MathUtils.PI; + MathUtils.radDeg = MathUtils.radiansToDegrees; + MathUtils.degreesToRadians = MathUtils.PI / 180; + MathUtils.degRad = MathUtils.degreesToRadians; + return MathUtils; + }()); + spine.MathUtils = MathUtils; + var Utils = (function () { + function Utils() { + } + Utils.arrayCopy = function (source, sourceStart, dest, destStart, numElements) { + for (var i = sourceStart, j = destStart; i < sourceStart + numElements; i++, j++) { + dest[j] = source[i]; + } + }; + Utils.setArraySize = function (array, size, value) { + if (value === void 0) { value = 0; } + var oldSize = array.length; + if (oldSize == size) + return array; + array.length = size; + if (oldSize < size) { + for (var i = oldSize; i < size; i++) + array[i] = value; + } + return array; + }; + Utils.ensureArrayCapacity = function (array, size, value) { + if (value === void 0) { value = 0; } + if (array.length >= size) + return array; + return Utils.setArraySize(array, size, value); + }; + Utils.newArray = function (size, defaultValue) { + var array = new Array(size); + for (var i = 0; i < size; i++) + array[i] = defaultValue; + return array; + }; + Utils.newFloatArray = function (size) { + if (Utils.SUPPORTS_TYPED_ARRAYS) { + return new Float32Array(size); + } + else { + var array = new Array(size); + for (var i = 0; i < array.length; i++) + array[i] = 0; + return array; + } + }; + Utils.toFloatArray = function (array) { + return Utils.SUPPORTS_TYPED_ARRAYS ? new Float32Array(array) : array; + }; + Utils.SUPPORTS_TYPED_ARRAYS = typeof (Float32Array) !== "undefined"; + return Utils; + }()); + spine.Utils = Utils; + var DebugUtils = (function () { + function DebugUtils() { + } + DebugUtils.logBones = function (skeleton) { + for (var i = 0; i < skeleton.bones.length; i++) { + var bone = skeleton.bones[i]; + console.log(bone.data.name + ", " + bone.a + ", " + bone.b + ", " + bone.c + ", " + bone.d + ", " + bone.worldX + ", " + bone.worldY); + } + }; + return DebugUtils; + }()); + spine.DebugUtils = DebugUtils; + var Pool = (function () { + function Pool(instantiator) { + this.items = new Array(); + this.instantiator = instantiator; + } + Pool.prototype.obtain = function () { + return this.items.length > 0 ? this.items.pop() : this.instantiator(); + }; + Pool.prototype.free = function (item) { + if (item.reset) + item.reset(); + this.items.push(item); + }; + Pool.prototype.freeAll = function (items) { + for (var i = 0; i < items.length; i++) { + if (items[i].reset) + items[i].reset(); + this.items[i] = items[i]; + } + }; + Pool.prototype.clear = function () { + this.items.length = 0; + }; + return Pool; + }()); + spine.Pool = Pool; + var Vector2 = (function () { + function Vector2(x, y) { + if (x === void 0) { x = 0; } + if (y === void 0) { y = 0; } + this.x = x; + this.y = y; + } + Vector2.prototype.set = function (x, y) { + this.x = x; + this.y = y; + return this; + }; + Vector2.prototype.length = function () { + var x = this.x; + var y = this.y; + return Math.sqrt(x * x + y * y); + }; + Vector2.prototype.normalize = function () { + var len = this.length(); + if (len != 0) { + this.x /= len; + this.y /= len; + } + return this; + }; + return Vector2; + }()); + spine.Vector2 = Vector2; + var TimeKeeper = (function () { + function TimeKeeper() { + this.maxDelta = 0.064; + this.framesPerSecond = 0; + this.delta = 0; + this.totalTime = 0; + this.lastTime = Date.now() / 1000; + this.frameCount = 0; + this.frameTime = 0; + } + TimeKeeper.prototype.update = function () { + var now = Date.now() / 1000; + this.delta = now - this.lastTime; + this.frameTime += this.delta; + this.totalTime += this.delta; + if (this.delta > this.maxDelta) + this.delta = this.maxDelta; + this.lastTime = now; + this.frameCount++; + if (this.frameTime > 1) { + this.framesPerSecond = this.frameCount / this.frameTime; + this.frameTime = 0; + this.frameCount = 0; + } + }; + return TimeKeeper; + }()); + spine.TimeKeeper = TimeKeeper; +})(spine || (spine = {})); +//# sourceMappingURL=spine-core.js.map \ No newline at end of file diff --git a/moduleConfig.json b/moduleConfig.json index b94181331b..1b147f43c6 100644 --- a/moduleConfig.json +++ b/moduleConfig.json @@ -440,6 +440,7 @@ "extensions/spine/Spine.js", "extensions/spine/CCSkeleton.js", "extensions/spine/CCSkeletonAnimation.js", + "extensions/spine/CCSkeletonTexture.js", "extensions/spine/CCSkeletonCanvasRenderCmd.js", "extensions/spine/CCSkeletonWebGLRenderCmd.js" ], From 320af085e305ec61b1a960cfd14aaf9c698754e6 Mon Sep 17 00:00:00 2001 From: zhangbin Date: Tue, 21 Feb 2017 10:46:22 +0800 Subject: [PATCH 121/206] Support Spine Mesh in WebGL. --- cocos2d/core/renderer/RendererWebGL.js | 204 +++++++++--- extensions/spine/CCSkeleton.js | 4 +- extensions/spine/CCSkeletonAnimation.js | 18 - extensions/spine/CCSkeletonWebGLRenderCmd.js | 332 +++++++++++-------- extensions/spine/Spine.js | 5 +- 5 files changed, 352 insertions(+), 211 deletions(-) diff --git a/cocos2d/core/renderer/RendererWebGL.js b/cocos2d/core/renderer/RendererWebGL.js index dd717d53e4..f7616a5a36 100644 --- a/cocos2d/core/renderer/RendererWebGL.js +++ b/cocos2d/core/renderer/RendererWebGL.js @@ -37,72 +37,82 @@ var _batchedInfo = { shader: null }, - _quadIndexBuffer = null, - _quadVertexBuffer = null, + _batchBroken = false, + _indexBuffer = null, + _vertexBuffer = null, // Total vertex size - _vertexSize = 0, + _maxVertexSize = 0, // Current batching vertex size _batchingSize = 0, + // Current batching index size + _indexSize = 0, + // Float size per vertex _sizePerVertex = 6, // buffer data and views _vertexData = null, _vertexDataSize = 0, _vertexDataF32 = null, _vertexDataUI32 = null, + _indexData = null, + _prevIndexSize = 0, + _pureQuad = true, _IS_IOS = false; // Inspired from @Heishe's gotta-batch-them-all branch // https://github.com/Talisca/cocos2d-html5/commit/de731f16414eb9bcaa20480006897ca6576d362c -function updateQuadBuffer (numQuads) { +function updateBuffer (numVertex) { var gl = cc._renderContext; - // Update index buffer and fill up - if (_quadIndexBuffer) { - gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, _quadIndexBuffer); - - var indices = new Uint16Array(numQuads * 6); + // Update index buffer size + if (_indexBuffer) { + var indexCount = Math.ceil(numVertex / 4) * 6; + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, _indexBuffer); + _indexData = new Uint16Array(indexCount); var currentQuad = 0; - for (var i = 0, len = numQuads * 6; i < len; i += 6) { - indices[i] = currentQuad + 0; - indices[i + 1] = currentQuad + 1; - indices[i + 2] = currentQuad + 2; - indices[i + 3] = currentQuad + 1; - indices[i + 4] = currentQuad + 2; - indices[i + 5] = currentQuad + 3; + for (var i = 0, len = indexCount; i < len; i += 6) { + _indexData[i] = currentQuad + 0; + _indexData[i + 1] = currentQuad + 1; + _indexData[i + 2] = currentQuad + 2; + _indexData[i + 3] = currentQuad + 1; + _indexData[i + 4] = currentQuad + 2; + _indexData[i + 5] = currentQuad + 3; currentQuad += 4; } - gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, indices, gl.STATIC_DRAW); + gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, _indexData, gl.DYNAMIC_DRAW); } - - if (_quadVertexBuffer) { - _vertexDataSize = numQuads * 4 * _sizePerVertex; + // Update vertex buffer size + if (_vertexBuffer) { + _vertexDataSize = numVertex * _sizePerVertex; var byteLength = _vertexDataSize * 4; _vertexData = new ArrayBuffer(byteLength); _vertexDataF32 = new Float32Array(_vertexData); _vertexDataUI32 = new Uint32Array(_vertexData); // Init buffer data - gl.bindBuffer(gl.ARRAY_BUFFER, _quadVertexBuffer); + gl.bindBuffer(gl.ARRAY_BUFFER, _vertexBuffer); gl.bufferData(gl.ARRAY_BUFFER, _vertexDataF32, gl.DYNAMIC_DRAW); } - _vertexSize = numQuads * 4; + // Downsize by 200 to avoid vertex data overflow + _maxVertexSize = numVertex - 200; } // Inspired from @Heishe's gotta-batch-them-all branch // https://github.com/Talisca/cocos2d-html5/commit/de731f16414eb9bcaa20480006897ca6576d362c -function initQuadBuffer (numQuads) { +function initQuadBuffer (numVertex) { var gl = cc._renderContext; - if (_quadIndexBuffer === null) { + if (_indexBuffer === null) { // TODO do user need to release the memory ? - _quadVertexBuffer = gl.createBuffer(); - _quadIndexBuffer = gl.createBuffer(); - - updateQuadBuffer(numQuads); - } - else { - updateQuadBuffer(numQuads); + _vertexBuffer = gl.createBuffer(); + _indexBuffer = gl.createBuffer(); } + updateBuffer(numVertex); } +var VertexType = { + QUAD : 0, + TRIANGLE : 1, + CUSTOM: 2 +}; + return { mat4Identity: null, @@ -110,6 +120,8 @@ return { assignedZ: 0, assignedZStep: 1 / 100, + VertexType: VertexType, + _transformNodePool: [], //save nodes transform dirty _renderCmds: [], //save renderer commands @@ -126,14 +138,14 @@ return { this.mat4Identity = new cc.math.Matrix4(); this.mat4Identity.identity(); - initQuadBuffer(500); + initQuadBuffer(2000); if (cc.sys.os === cc.sys.OS_IOS) { _IS_IOS = true; } }, getVertexSize: function () { - return _vertexSize; + return _maxVertexSize; }, getRenderCmd: function (renderableObject) { @@ -249,7 +261,7 @@ return { }, pushRenderCommand: function (cmd) { - if (!cmd.needDraw()) + if (!cmd.rendering && !cmd.uploadData) return; if (this._isCacheToBufferOn) { var currentId = this._currentID, locCmdBuffer = this._cacheToBufferCmds; @@ -263,25 +275,76 @@ return { } }, - _increaseBatchingSize: function (increment) { + _increaseBatchingSize: function (increment, vertexType, indices) { + vertexType = vertexType || VertexType.QUAD; + var i, curr; + switch (vertexType) { + case VertexType.QUAD: + for (i = 0; i < increment; i += 4) { + curr = _batchingSize + i; + _indexData[_indexSize++] = curr + 0; + _indexData[_indexSize++] = curr + 1; + _indexData[_indexSize++] = curr + 2; + _indexData[_indexSize++] = curr + 1; + _indexData[_indexSize++] = curr + 2; + _indexData[_indexSize++] = curr + 3; + } + break; + case VertexType.TRIANGLE: + _pureQuad = false; + for (i = 0; i < increment; i += 3) { + curr = _batchingSize + i; + _indexData[_indexSize++] = curr + 0; + _indexData[_indexSize++] = curr + 1; + _indexData[_indexSize++] = curr + 2; + } + break; + case VertexType.CUSTOM: + // CUSTOM type increase the indices data + _pureQuad = false; + var len = indices.length; + for (i = 0; i < len; i++) { + _indexData[_indexSize++] = _batchingSize + indices[i]; + } + break; + default: + return; + } _batchingSize += increment; }, + _updateBatchedInfo: function (texture, blendFunc, shaderProgram) { + if (texture) { + _batchedInfo.texture = texture; + } + + if (blendFunc) { + _batchedInfo.blendSrc = blendFunc.src; + _batchedInfo.blendDst = blendFunc.dst; + } + + if (shaderProgram) { + _batchedInfo.shader = shaderProgram; + } + }, + + _breakBatch: function () { + _batchBroken = true; + }, + _uploadBufferData: function (cmd) { - if (_batchingSize >= _vertexSize) { + if (_batchingSize >= _maxVertexSize) { this._batchRendering(); } // Check batching var node = cmd._node; 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; - if (_batchedInfo.texture !== texture || + if (_batchBroken || + _batchedInfo.texture !== texture || _batchedInfo.blendSrc !== blendSrc || _batchedInfo.blendDst !== blendDst || _batchedInfo.shader !== shader) { @@ -292,11 +355,43 @@ return { _batchedInfo.blendSrc = blendSrc; _batchedInfo.blendDst = blendDst; _batchedInfo.shader = shader; + _batchBroken = false; } // Upload vertex data var len = cmd.uploadData(_vertexDataF32, _vertexDataUI32, _batchingSize * _sizePerVertex); if (len > 0) { + var i, curr, type = cmd.vertexType || VertexType.QUAD; + switch (type) { + case VertexType.QUAD: + for (i = 0; i < len; i += 4) { + curr = _batchingSize + i; + _indexData[_indexSize++] = curr + 0; + _indexData[_indexSize++] = curr + 1; + _indexData[_indexSize++] = curr + 2; + _indexData[_indexSize++] = curr + 1; + _indexData[_indexSize++] = curr + 2; + _indexData[_indexSize++] = curr + 3; + } + break; + case VertexType.TRIANGLE: + _pureQuad = false; + for (i = 0; i < len; i += 3) { + curr = _batchingSize + i; + _indexData[_indexSize++] = curr + 0; + _indexData[_indexSize++] = curr + 1; + _indexData[_indexSize++] = curr + 2; + } + break; + case VertexType.CUSTOM: + _pureQuad = false; + if (cmd.uploadIndexData) { + _indexSize += cmd.uploadIndexData(_indexData, _indexSize, _batchingSize); + } + break; + default: + return; + } _batchingSize += len; } }, @@ -309,7 +404,7 @@ return { var gl = cc._renderContext; var texture = _batchedInfo.texture; var shader = _batchedInfo.shader; - var count = _batchingSize / 4; + var uploadAll = _batchingSize > _maxVertexSize * 0.5; if (shader) { shader.use(); @@ -319,9 +414,9 @@ return { cc.glBlendFunc(_batchedInfo.blendSrc, _batchedInfo.blendDst); cc.glBindTexture2DN(0, texture); // = cc.glBindTexture2D(texture); - gl.bindBuffer(gl.ARRAY_BUFFER, _quadVertexBuffer); + gl.bindBuffer(gl.ARRAY_BUFFER, _vertexBuffer); // upload the vertex data to the gl buffer - if (_batchingSize > _vertexSize * 0.5) { + if (uploadAll) { gl.bufferData(gl.ARRAY_BUFFER, _vertexDataF32, gl.DYNAMIC_DRAW); } else { @@ -336,12 +431,28 @@ return { gl.vertexAttribPointer(cc.VERTEX_ATTRIB_COLOR, 4, gl.UNSIGNED_BYTE, true, 24, 12); gl.vertexAttribPointer(cc.VERTEX_ATTRIB_TEX_COORDS, 2, gl.FLOAT, false, 24, 16); - gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, _quadIndexBuffer); - gl.drawElements(gl.TRIANGLES, count * 6, gl.UNSIGNED_SHORT, 0); + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, _indexBuffer); + if (!_prevIndexSize || !_pureQuad || _indexSize > _prevIndexSize) { + if (uploadAll) { + gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, _indexData, gl.DYNAMIC_DRAW); + } + else { + gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, _indexData.subarray(0, _indexSize), gl.DYNAMIC_DRAW); + } + } + gl.drawElements(gl.TRIANGLES, _indexSize, gl.UNSIGNED_SHORT, 0); cc.g_NumberOfDraws++; + if (_pureQuad) { + _prevIndexSize = _indexSize; + } + else { + _prevIndexSize = 0; + _pureQuad = true; + } _batchingSize = 0; + _indexSize = 0; }, /** @@ -350,7 +461,7 @@ return { */ rendering: function (ctx, cmds) { var locCmds = cmds || this._renderCmds, - i, len, cmd, next, batchCount, + i, len, cmd, context = ctx || cc._renderContext; // Reset buffer for rendering @@ -358,6 +469,7 @@ return { for (i = 0, len = locCmds.length; i < len; ++i) { cmd = locCmds[i]; + if (!cmd.needDraw()) continue; if (cmd.uploadData) { this._uploadBufferData(cmd); diff --git a/extensions/spine/CCSkeleton.js b/extensions/spine/CCSkeleton.js index a4385588e7..d7f35ebf71 100644 --- a/extensions/spine/CCSkeleton.js +++ b/extensions/spine/CCSkeleton.js @@ -216,9 +216,9 @@ sp.Skeleton = cc.Node.extend(/** @lends sp.Skeleton# */{ for (var i = 0, slotCount = slots.length; i < slotCount; ++i) { var slot = slots[i]; - if (!slot.attachment || ! (attachment instanceof spine.RegionAttachment)) - continue; var attachment = slot.attachment; + if (!attachment || ! (attachment instanceof spine.RegionAttachment)) + continue; vertices = attachment.updateWorldVertices(slot, false); minX = Math.min(minX, vertices[VERTEX.X1] * scaleX, vertices[VERTEX.X4] * scaleX, vertices[VERTEX.X2] * scaleX, vertices[VERTEX.X3] * scaleX); minY = Math.min(minY, vertices[VERTEX.Y1] * scaleY, vertices[VERTEX.Y4] * scaleY, vertices[VERTEX.Y2] * scaleY, vertices[VERTEX.Y3] * scaleY); diff --git a/extensions/spine/CCSkeletonAnimation.js b/extensions/spine/CCSkeletonAnimation.js index 9d787c5fbf..6ad1c189d2 100644 --- a/extensions/spine/CCSkeletonAnimation.js +++ b/extensions/spine/CCSkeletonAnimation.js @@ -24,24 +24,6 @@ THE SOFTWARE. ****************************************************************************/ -/** - * @ignore - */ -sp._atlasPage_createTexture_webGL = function (self, path) { - var texture = cc.textureCache.addImage(path); - self.rendererObject = new cc.TextureAtlas(texture, 128); - self.width = texture.getPixelsWide(); - self.height = texture.getPixelsHigh(); -}; - -sp._atlasPage_createTexture_canvas = function(self, path) { - self._texture = cc.textureCache.addImage(path); -}; - -sp._atlasPage_disposeTexture = function (self) { - self.rendererObject.release(); -}; - sp._atlasLoader = { spAtlasFile:null, setAtlasFile:function(spAtlasFile){ diff --git a/extensions/spine/CCSkeletonWebGLRenderCmd.js b/extensions/spine/CCSkeletonWebGLRenderCmd.js index ce0c5fb366..e9fc27601a 100644 --- a/extensions/spine/CCSkeletonWebGLRenderCmd.js +++ b/extensions/spine/CCSkeletonWebGLRenderCmd.js @@ -28,32 +28,38 @@ this._needDraw = true; this._matrix = new cc.math.Matrix4(); this._matrix.identity(); - this._tmpQuad = new cc.V3F_C4B_T2F_Quad(); + this.vertexType = cc.renderer.VertexType.CUSTOM; this.setShaderProgram(cc.shaderCache.programForKey(cc.SHADER_POSITION_TEXTURECOLOR)); }; var proto = sp.Skeleton.WebGLRenderCmd.prototype = Object.create(cc.Node.WebGLRenderCmd.prototype); proto.constructor = sp.Skeleton.WebGLRenderCmd; - proto.rendering = function (ctx) { - var node = this._node, tmpQuad = this._tmpQuad; + proto.uploadData = function (f32buffer, ui32buffer, vertexDataOffset){ + + // rendering the cached data first + cc.renderer._batchRendering(); + vertexDataOffset = 0; + + var node = this._node; var color = node.getColor(), locSkeleton = node._skeleton; - var blendMode, textureAtlas, attachment, slot, i, n; - var locBlendFunc = node._blendFunc; + var textureAtlas, attachment, slot, i, n; var premultiAlpha = node._premultipliedAlpha; - - var wt = this._worldTransform; - this._matrix.mat[0] = wt.a; - this._matrix.mat[4] = wt.c; - this._matrix.mat[12] = wt.tx; - this._matrix.mat[1] = wt.b; - this._matrix.mat[5] = wt.d; - this._matrix.mat[13] = wt.ty; + var blendMode = -1; + var dataInited = false; + var cachedVertices = 0; + + var wt = this._worldTransform, mat = this._matrix.mat; + mat[0] = wt.a; + mat[4] = wt.c; + mat[12] = wt.tx; + mat[1] = wt.b; + mat[5] = wt.d; + mat[13] = wt.ty; this._shaderProgram.use(); this._shaderProgram._setUniformForMVPMatrixWithMat4(this._matrix); - // cc.glBlendFunc(locBlendFunc.src, locBlendFunc.dst); locSkeleton.r = color.r / 255; locSkeleton.g = color.g / 255; locSkeleton.b = color.b / 255; @@ -64,67 +70,88 @@ locSkeleton.b *= locSkeleton.a; } - //for (i = 0, n = locSkeleton.slots.length; i < n; i++) { + var debugSlotsInfo = null; + if (this._node._debugSlots) { + debugSlotsInfo = []; + } + for (i = 0, n = locSkeleton.drawOrder.length; i < n; i++) { slot = locSkeleton.drawOrder[i]; if (!slot.attachment) continue; attachment = slot.attachment; - switch (slot.attachment.type) { - case sp.ATTACHMENT_TYPE.REGION: - this._updateRegionAttachmentQuad(attachment, slot, tmpQuad, premultiAlpha); - break; - case sp.ATTACHMENT_TYPE.MESH: - this._updateMeshAttachmentQuad(attachment, slot, tmpQuad, premultiAlpha); - break; - case sp.ATTACHMENT_TYPE.SKINNED_MESH: - break; - default: - continue; + // get the vertices length + var vertCount = 0; + if (attachment instanceof spine.RegionAttachment) { + vertCount = 6; // a quad = two triangles = six vertices + } + else if (attachment instanceof spine.MeshAttachment) { + vertCount = attachment.regionUVs.length / 2; + } + else { + continue; } + // no vertices to render + if (vertCount === 0) { + continue; + } var regionTextureAtlas = node.getTextureAtlas(attachment); + // init data at the first time + if (!dataInited) { + textureAtlas = regionTextureAtlas; + blendMode = slot.data.blendMode; + cc.renderer._updateBatchedInfo(textureAtlas.texture.getRealTexture(), this._getBlendFunc(blendMode, premultiAlpha), this.getShaderProgram()); + dataInited = true; + } - if (slot.data.blendMode != blendMode) { - if (textureAtlas) { - textureAtlas.drawQuads(); - textureAtlas.removeAllQuads(); - } + // if data changed or the vertices will be overflow + if ((cachedVertices + vertCount) * 6 > f32buffer.length || + textureAtlas !== regionTextureAtlas || + blendMode !== slot.data.blendMode) { + // render the cached data + cc.renderer._batchRendering(); + vertexDataOffset = 0; + cachedVertices = 0; + + // update the batched info + textureAtlas = regionTextureAtlas; blendMode = slot.data.blendMode; - switch (blendMode) { - case spine.BlendMode.additive: - cc.glBlendFunc(premultiAlpha ? cc.ONE : cc.SRC_ALPHA, cc.ONE); - break; - case spine.BlendMode.multiply: - cc.glBlendFunc(cc.DST_COLOR, cc.ONE_MINUS_SRC_ALPHA); - break; - case spine.BlendMode.screen: - cc.glBlendFunc(cc.ONE, cc.ONE_MINUS_SRC_COLOR); - break; - default: - cc.glBlendFunc(premultiAlpha ? cc.ONE : cc.SRC_ALPHA, cc.ONE_MINUS_SRC_ALPHA); - } - } else if (regionTextureAtlas != textureAtlas && textureAtlas) { - textureAtlas.drawQuads(); - textureAtlas.removeAllQuads(); + cc.renderer._updateBatchedInfo(textureAtlas.texture.getRealTexture(), this._getBlendFunc(blendMode, premultiAlpha), this.getShaderProgram()); + } + + // update the vertex buffer + var slotDebugPoints = null; + if (attachment instanceof spine.RegionAttachment) { + slotDebugPoints = this._uploadRegionAttachmentData(attachment, slot, premultiAlpha, f32buffer, ui32buffer, vertexDataOffset); } - textureAtlas = regionTextureAtlas; - - var quadCount = textureAtlas.getTotalQuads(); - if (textureAtlas.getCapacity() == quadCount) { - textureAtlas.drawQuads(); - textureAtlas.removeAllQuads(); - if (!textureAtlas.resizeCapacity(textureAtlas.getCapacity() * 2)) - return; + else if (attachment instanceof spine.MeshAttachment) { + this._uploadMeshAttachmentData(attachment, slot, premultiAlpha, f32buffer, ui32buffer, vertexDataOffset); + } + else { + continue; + } + + if (this._node._debugSlots) { + debugSlotsInfo[i] = slotDebugPoints; } - textureAtlas.updateQuad(tmpQuad, quadCount); + // update the index buffer + if (attachment instanceof spine.RegionAttachment) { + cc.renderer._increaseBatchingSize(vertCount, cc.renderer.VertexType.TRIANGLE); + } else { + cc.renderer._increaseBatchingSize(vertCount, cc.renderer.VertexType.CUSTOM, attachment.triangles); + } + + // update the index data + cachedVertices += vertCount; + vertexDataOffset += vertCount * 6; } - if (textureAtlas) { - textureAtlas.drawQuads(); - textureAtlas.removeAllQuads(); + // render the left vertices + if (cachedVertices > 0) { + cc.renderer._batchRendering(); } if (node._debugBones || node._debugSlots) { @@ -133,25 +160,16 @@ cc.current_stack.top = this._matrix; var drawingUtil = cc._drawingUtil; - if (node._debugSlots) { + if (node._debugSlots && debugSlotsInfo && debugSlotsInfo.length > 0) { // Slots. drawingUtil.setDrawColor(0, 0, 255, 255); drawingUtil.setLineWidth(1); for (i = 0, n = locSkeleton.slots.length; i < n; i++) { - slot = locSkeleton.drawOrder[i]; - if (!slot.attachment || slot.attachment.type != sp.ATTACHMENT_TYPE.REGION) - continue; - attachment = slot.attachment; - this._updateRegionAttachmentQuad(attachment, slot, tmpQuad); - - var points = []; - points.push(cc.p(tmpQuad.bl.vertices.x, tmpQuad.bl.vertices.y)); - points.push(cc.p(tmpQuad.br.vertices.x, tmpQuad.br.vertices.y)); - points.push(cc.p(tmpQuad.tr.vertices.x, tmpQuad.tr.vertices.y)); - points.push(cc.p(tmpQuad.tl.vertices.x, tmpQuad.tl.vertices.y)); - - drawingUtil.drawPoly(points, 4, true); + var points = debugSlotsInfo[i]; + if (points) { + drawingUtil.drawPoly(points, 4, true); + } } } @@ -163,8 +181,8 @@ for (i = 0, n = locSkeleton.bones.length; i < n; i++) { bone = locSkeleton.bones[i]; - var x = bone.data.length * bone.m00 + bone.worldX; - var y = bone.data.length * bone.m10 + bone.worldY; + var x = bone.data.length * bone.a + bone.worldX; + var y = bone.data.length * bone.c + bone.worldY; drawingUtil.drawLine(cc.p(bone.worldX, bone.worldY), cc.p(x, y)); } @@ -182,6 +200,35 @@ } cc.kmGLPopMatrix(); } + + return 0; + }; + + proto._getBlendFunc = function (blendMode, premultiAlpha) { + var ret = {}; + switch (blendMode) { + case spine.BlendMode.Normal: + ret.src = premultiAlpha ? cc.ONE : cc.SRC_ALPHA; + ret.dst = cc.ONE_MINUS_SRC_ALPHA; + break; + case spine.BlendMode.Additive: + ret.src = premultiAlpha ? cc.ONE : cc.SRC_ALPHA; + ret.dst = cc.ONE; + break; + case spine.BlendMode.Multiply: + ret.src = cc.DST_COLOR; + ret.dst = cc.ONE_MINUS_SRC_ALPHA; + break; + case spine.BlendMode.Screen: + ret.src = cc.ONE; + ret.dst = cc.ONE_MINUS_SRC_COLOR; + break; + default: + ret = this._node._blendFunc; + break; + } + + return ret; }; proto._createChildFormSkeletonData = function () { @@ -190,76 +237,75 @@ proto._updateChild = function () { }; - proto._updateRegionAttachmentQuad = function (attachment, slot, quad, premultipliedAlpha) { - var 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; - var g = slot.bone.skeleton.g * slot.g * attachment.g * multiplier; - var b = slot.bone.skeleton.b * slot.b * attachment.b * multiplier; - - quad.bl.colors.r = quad.tl.colors.r = quad.tr.colors.r = quad.br.colors.r = r; - quad.bl.colors.g = quad.tl.colors.g = quad.tr.colors.g = quad.br.colors.g = g; - quad.bl.colors.b = quad.tl.colors.b = quad.tr.colors.b = quad.br.colors.b = b; - quad.bl.colors.a = quad.tl.colors.a = quad.tr.colors.a = quad.br.colors.a = a; - - var VERTEX = sp.VERTEX_INDEX; - quad.bl.vertices.x = vertices[VERTEX.X1]; - quad.bl.vertices.y = vertices[VERTEX.Y1]; - quad.tl.vertices.x = vertices[VERTEX.X2]; - quad.tl.vertices.y = vertices[VERTEX.Y2]; - quad.tr.vertices.x = vertices[VERTEX.X3]; - quad.tr.vertices.y = vertices[VERTEX.Y3]; - quad.br.vertices.x = vertices[VERTEX.X4]; - quad.br.vertices.y = vertices[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._uploadRegionAttachmentData = function(attachment, slot, premultipliedAlpha, f32buffer, ui32buffer, vertexDataOffset) { + // the vertices in format: + // [ + // X1, Y1, C1R, C1G, C1B, C1A, U1, V1, // bottom left + // X2, Y2, C2R, C2G, C2B, C2A, U2, V2, // top left + // X3, Y3, C3R, C3G, C3B, C3A, U3, V3, // top right + // X4, Y4, C4R, C4G, C4B, C4A, U4, V4 // bottom right + // ] + // + var nodeColor = this._displayedColor; + var nodeR = nodeColor.r, + nodeG = nodeColor.g, + nodeB = nodeColor.b, + nodeA = nodeColor.a; + var vertices = attachment.updateWorldVertices(slot, premultipliedAlpha); + var offset = vertexDataOffset; + // generate 6 vertices data (two triangles) from the quad vertices + // using two angles : (0, 1, 2) & (0, 2, 3) + for (var i = 0; i < 6; i++) { + var srcIdx = i < 4 ? i % 3 : i - 2; + var r = vertices[srcIdx * 8 + 2] * nodeR, + g = vertices[srcIdx * 8 + 3] * nodeG, + b = vertices[srcIdx * 8 + 4] * nodeB, + a = vertices[srcIdx * 8 + 5] * nodeA; + var color = ((a<<24) | (b<<16) | (g<<8) | r); + f32buffer[offset] = vertices[srcIdx * 8]; + f32buffer[offset + 1] = vertices[srcIdx * 8 + 1]; + f32buffer[offset + 2] = this._node.vertexZ; + ui32buffer[offset + 3] = color; + f32buffer[offset + 4] = vertices[srcIdx * 8 + 6]; + f32buffer[offset + 5] = vertices[srcIdx * 8 + 7]; + offset += 6; + } + + if (this._node._debugSlots) { + // return the quad points info if debug slot enabled + var VERTEX = spine.RegionAttachment; + return [ + cc.p(vertices[VERTEX.X1], vertices[VERTEX.Y1]), + cc.p(vertices[VERTEX.X2], vertices[VERTEX.Y2]), + cc.p(vertices[VERTEX.X3], vertices[VERTEX.Y3]), + cc.p(vertices[VERTEX.X4], vertices[VERTEX.Y4]) + ]; + } }; - proto._updateMeshAttachmentQuad = function (attachment, slot, quad, premultipliedAlpha) { - var 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; - var normalizedAlpha = slot.bone.skeleton.a * slot.a; - if (premultipliedAlpha) { - r *= normalizedAlpha; - g *= normalizedAlpha; - b *= normalizedAlpha; + proto._uploadMeshAttachmentData = function(attachment, slot, premultipliedAlpha, f32buffer, ui32buffer, vertexDataOffset) { + // get the vertex data + var vertices = attachment.updateWorldVertices(slot, premultipliedAlpha); + var offset = vertexDataOffset; + var nodeColor = this._displayedColor; + var nodeR = nodeColor.r, + nodeG = nodeColor.g, + nodeB = nodeColor.b, + nodeA = nodeColor.a; + for (var i = 0, n = vertices.length; i < n; i += 8) { + var r = vertices[i + 2] * nodeR, + g = vertices[i + 3] * nodeG, + b = vertices[i + 4] * nodeB, + a = vertices[i + 5] * nodeA; + var color = ((a<<24) | (b<<16) | (g<<8) | r); + + f32buffer[offset] = vertices[i]; + f32buffer[offset + 1] = vertices[i + 1]; + f32buffer[offset + 2] = this._node.vertexZ; + ui32buffer[offset + 3] = color; + f32buffer[offset + 4] = vertices[i + 6]; + f32buffer[offset + 5] = vertices[i + 7]; + offset += 6; } - var a = normalizedAlpha * 255; - - quad.bl.colors.r = quad.tl.colors.r = quad.tr.colors.r = quad.br.colors.r = r; - quad.bl.colors.g = quad.tl.colors.g = quad.tr.colors.g = quad.br.colors.g = g; - quad.bl.colors.b = quad.tl.colors.b = quad.tr.colors.b = quad.br.colors.b = b; - quad.bl.colors.a = quad.tl.colors.a = quad.tr.colors.a = quad.br.colors.a = a; - - var VERTEX = sp.VERTEX_INDEX; - quad.bl.vertices.x = vertices[VERTEX.X1]; - quad.bl.vertices.y = vertices[VERTEX.Y1]; - quad.tl.vertices.x = vertices[VERTEX.X2]; - quad.tl.vertices.y = vertices[VERTEX.Y2]; - quad.tr.vertices.x = vertices[VERTEX.X3]; - quad.tr.vertices.y = vertices[VERTEX.Y3]; - quad.br.vertices.x = vertices[VERTEX.X4]; - quad.br.vertices.y = vertices[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]; }; })(); diff --git a/extensions/spine/Spine.js b/extensions/spine/Spine.js index 2007cb45e9..404cc51ff1 100644 --- a/extensions/spine/Spine.js +++ b/extensions/spine/Spine.js @@ -4237,12 +4237,13 @@ var spine; var scale = this.scale; attachment.worldVerticesLength = verticesLength; var vertices = map.vertices; + var scaledVertices = []; if (verticesLength == vertices.length) { if (scale != 1) { for (var i = 0, n = vertices.length; i < n; i++) - vertices[i] *= scale; + scaledVertices.push(vertices[i] * scale); } - attachment.vertices = spine.Utils.toFloatArray(vertices); + attachment.vertices = spine.Utils.toFloatArray(scaledVertices); return; } var weights = new Array(); From e1b33affed526c53e4ed4426f70db3d26b9006c3 Mon Sep 17 00:00:00 2001 From: zhangbin Date: Tue, 21 Feb 2017 18:21:38 +0800 Subject: [PATCH 122/206] Solve the error effect of Spine Mesh support. --- extensions/spine/CCSkeleton.js | 5 ++++- extensions/spine/Spine.js | 5 ++--- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/extensions/spine/CCSkeleton.js b/extensions/spine/CCSkeleton.js index d7f35ebf71..cf77bd3839 100644 --- a/extensions/spine/CCSkeleton.js +++ b/extensions/spine/CCSkeleton.js @@ -194,7 +194,10 @@ sp.Skeleton = cc.Node.extend(/** @lends sp.Skeleton# */{ skeletonJsonReader.scale = scale; var skeletonJson = cc.loader.getRes(argSkeletonFile); - skeletonData = skeletonJsonReader.readSkeletonData(skeletonJson); + // TODO: FIXME: This operation added for avoid the bug of spine runtime: + // https://github.com/EsotericSoftware/spine-runtimes/pull/838 + var clonedJsonObj = JSON.parse(JSON.stringify(skeletonJson)); + skeletonData = skeletonJsonReader.readSkeletonData(clonedJsonObj); atlas.dispose(skeletonJsonReader); ownsSkeletonData = true; } else { diff --git a/extensions/spine/Spine.js b/extensions/spine/Spine.js index 404cc51ff1..2007cb45e9 100644 --- a/extensions/spine/Spine.js +++ b/extensions/spine/Spine.js @@ -4237,13 +4237,12 @@ var spine; var scale = this.scale; attachment.worldVerticesLength = verticesLength; var vertices = map.vertices; - var scaledVertices = []; if (verticesLength == vertices.length) { if (scale != 1) { for (var i = 0, n = vertices.length; i < n; i++) - scaledVertices.push(vertices[i] * scale); + vertices[i] *= scale; } - attachment.vertices = spine.Utils.toFloatArray(scaledVertices); + attachment.vertices = spine.Utils.toFloatArray(vertices); return; } var weights = new Array(); From 7c021d1ce819156ce24cad14e905b816cd9fc5e0 Mon Sep 17 00:00:00 2001 From: zhangbin Date: Wed, 22 Feb 2017 12:03:08 +0800 Subject: [PATCH 123/206] Solve the error logic in spine runtime. --- extensions/spine/CCSkeleton.js | 5 +---- extensions/spine/Spine.js | 5 +++-- 2 files changed, 4 insertions(+), 6 deletions(-) diff --git a/extensions/spine/CCSkeleton.js b/extensions/spine/CCSkeleton.js index cf77bd3839..d7f35ebf71 100644 --- a/extensions/spine/CCSkeleton.js +++ b/extensions/spine/CCSkeleton.js @@ -194,10 +194,7 @@ sp.Skeleton = cc.Node.extend(/** @lends sp.Skeleton# */{ skeletonJsonReader.scale = scale; var skeletonJson = cc.loader.getRes(argSkeletonFile); - // TODO: FIXME: This operation added for avoid the bug of spine runtime: - // https://github.com/EsotericSoftware/spine-runtimes/pull/838 - var clonedJsonObj = JSON.parse(JSON.stringify(skeletonJson)); - skeletonData = skeletonJsonReader.readSkeletonData(clonedJsonObj); + skeletonData = skeletonJsonReader.readSkeletonData(skeletonJson); atlas.dispose(skeletonJsonReader); ownsSkeletonData = true; } else { diff --git a/extensions/spine/Spine.js b/extensions/spine/Spine.js index 2007cb45e9..0d4533c3f0 100644 --- a/extensions/spine/Spine.js +++ b/extensions/spine/Spine.js @@ -4237,12 +4237,13 @@ var spine; var scale = this.scale; attachment.worldVerticesLength = verticesLength; var vertices = map.vertices; + var scaledVertices = spine.Utils.toFloatArray(vertices); if (verticesLength == vertices.length) { if (scale != 1) { for (var i = 0, n = vertices.length; i < n; i++) - vertices[i] *= scale; + scaledVertices[i] *= scale; } - attachment.vertices = spine.Utils.toFloatArray(vertices); + attachment.vertices = scaledVertices; return; } var weights = new Array(); From 94bff726e2062e973b446cc4683437bda1306f56 Mon Sep 17 00:00:00 2001 From: zhangbin Date: Wed, 22 Feb 2017 17:29:12 +0800 Subject: [PATCH 124/206] Fix the problem: Spine event callbacks are not work. --- extensions/spine/CCSkeletonAnimation.js | 196 +++++++++++++----------- 1 file changed, 103 insertions(+), 93 deletions(-) diff --git a/extensions/spine/CCSkeletonAnimation.js b/extensions/spine/CCSkeletonAnimation.js index 6ad1c189d2..496f31e2b7 100644 --- a/extensions/spine/CCSkeletonAnimation.js +++ b/extensions/spine/CCSkeletonAnimation.js @@ -48,28 +48,85 @@ sp._atlasLoader = { */ sp.ANIMATION_EVENT_TYPE = { START: 0, - END: 1, - COMPLETE: 2, - EVENT: 3 + INTERRUPT: 1, + END: 2, + DISPOSE: 3, + COMPLETE: 4, + EVENT: 5 }; -sp.TrackEntryListeners = function(startListener, endListener, completeListener, eventListener){ +sp.TrackEntryListeners = function(startListener, endListener, completeListener, eventListener, interruptListener, disposeListener){ this.startListener = startListener || null; this.endListener = endListener || null; this.completeListener = completeListener || null; this.eventListener = eventListener || null; + this.interruptListener = interruptListener || null; + this.disposeListener = disposeListener || null; + this.callback = null; + this.callbackTarget = null; + this.skeletonNode = null; + + this.start = function(trackEntry) { + if (this.startListener) { + this.startListener(trackEntry); + } + if (this.callback && this.callbackTarget) { + this.callback.call(this.callbackTarget, this.skeletonNode, trackEntry, animEventType.START, null, 0); + } + }; + + this.interrupt = function(trackEntry) { + if (this.interruptListener) { + this.interruptListener(trackEntry); + } + if (this.callback && this.callbackTarget) { + this.callback.call(this.callbackTarget, this.skeletonNode, trackEntry, animEventType.INTERRUPT, null, 0); + } + }; + + this.end = function (trackEntry) { + if (this.endListener) { + this.endListener(trackEntry); + } + if (this.callback && this.callbackTarget) { + this.callback.call(this.callbackTarget, this.skeletonNode, trackEntry, animEventType.END, null, 0); + } + }; + + this.dispose = function (trackEntry) { + if (this.disposeListener) { + this.disposeListener(trackEntry); + } + if (this.callback && this.callbackTarget) { + this.callback.call(this.callbackTarget, this.skeletonNode, trackEntry, animEventType.DISPOSE, null, 0); + } + }; + + this.complete = function (trackEntry) { + var loopCount = Math.floor(trackEntry.trackTime / trackEntry.animationEnd); + if (this.completeListener) { + this.completeListener(trackEntry, loopCount); + } + if (this.callback && this.callbackTarget) { + this.callback.call(this.callbackTarget, this.skeletonNode, trackEntry, animEventType.COMPLETE, null, loopCount); + } + }; + + this.event = function (trackEntry, event) { + if (this.eventListener) { + this.eventListener(trackEntry, event); + } + if (this.callback && this.callbackTarget) { + this.callback.call(this.callbackTarget, this.skeletonNode, trackEntry, animEventType.EVENT, event, 0); + } + }; }; sp.TrackEntryListeners.getListeners = function(entry){ - if(!entry.rendererObject){ - entry.rendererObject = new sp.TrackEntryListeners(); - entry.listener = sp.trackEntryCallback; + if(!entry.listener){ + entry.listener = new sp.TrackEntryListeners(); } - return entry.rendererObject; -}; - -sp.trackEntryCallback = function(state, trackIndex, type, event, loopCount) { - state.rendererObject.onTrackEntryEvent(trackIndex, type, event, loopCount); + return entry.listener; }; /** @@ -82,14 +139,9 @@ sp.trackEntryCallback = function(state, trackIndex, type, event, loopCount) { */ sp.SkeletonAnimation = sp.Skeleton.extend(/** @lends sp.SkeletonAnimation# */{ _state: null, - _target: null, - _callback: null, _ownsAnimationStateData: false, - _startListener: null, - _endListener: null, - _completeListener: null, - _eventListener: null, + _listener: null, /** * Initializes a sp.SkeletonAnimation. please do not call this function by yourself, you should pass the parameters to constructor to initialize it. @@ -107,11 +159,9 @@ sp.SkeletonAnimation = sp.Skeleton.extend(/** @lends sp.SkeletonAnimation# */{ */ setAnimationStateData: function (stateData) { var state = new spine.AnimationState(stateData); + this._listener = new sp.TrackEntryListeners(); state.rendererObject = this; - state.onStart = this._onAnimationStateStart.bind(this); - state.onComplete = this._onAnimationStateComplete.bind(this); - state.onEnd = this._onAnimationStateEnd.bind(this); - state.onEvent = this._onAnimationStateEvent.bind(this); + state.addListener(this._listener); this._state = state; }, @@ -131,8 +181,9 @@ sp.SkeletonAnimation = sp.Skeleton.extend(/** @lends sp.SkeletonAnimation# */{ * @param {Function} callback */ setAnimationListener: function (target, callback) { - this._target = target; - this._callback = callback; + this._listener.callbackTarget = target; + this._listener.callback = callback; + this._listener.skeletonNode = this; }, /** @@ -213,7 +264,15 @@ sp.SkeletonAnimation = sp.Skeleton.extend(/** @lends sp.SkeletonAnimation# */{ * @param {function} listener */ setStartListener: function(listener){ - this._startListener = listener; + this._listener.startListener = listener; + }, + + /** + * Set the interrupt listener + * @param {function} listener + */ + setInterruptListener: function(listener) { + this._listener.interruptListener = listener; }, /** @@ -221,25 +280,41 @@ sp.SkeletonAnimation = sp.Skeleton.extend(/** @lends sp.SkeletonAnimation# */{ * @param {function} listener */ setEndListener: function(listener) { - this._endListener = listener; + this._listener.endListener = listener; + }, + + /** + * Set the dispose listener + * @param {function} listener + */ + setDisposeListener: function(listener) { + this._listener.disposeListener = listener; }, setCompleteListener: function(listener) { - this._completeListener = listener; + this._listener.completeListener = listener; }, setEventListener: function(listener){ - this._eventListener = listener; + this._listener.eventListener = listener; }, setTrackStartListener: function(entry, listener){ sp.TrackEntryListeners.getListeners(entry).startListener = listener; }, + setTrackInterruptListener: function(entry, listener){ + sp.TrackEntryListeners.getListeners(entry).interruptListener = listener; + }, + setTrackEndListener: function(entry, listener){ sp.TrackEntryListeners.getListeners(entry).endListener = listener; }, + setTrackDisposeListener: function(entry, listener){ + sp.TrackEntryListeners.getListeners(entry).disposeListener = listener; + }, + setTrackCompleteListener: function(entry, listener){ sp.TrackEntryListeners.getListeners(entry).completeListener = listener; }, @@ -248,73 +323,8 @@ sp.SkeletonAnimation = sp.Skeleton.extend(/** @lends sp.SkeletonAnimation# */{ sp.TrackEntryListeners.getListeners(entry).eventListener = listener; }, - onTrackEntryEvent: function(traceIndex, type, event, loopCount){ - var entry = this._state.getCurrent(traceIndex); - if(!entry.rendererObject) - return; - var listeners = entry.rendererObject; - switch (type){ - case sp.ANIMATION_EVENT_TYPE.START: - if(listeners.startListener) - listeners.startListener(traceIndex); - break; - case sp.ANIMATION_EVENT_TYPE.END: - if(listeners.endListener) - listeners.endListener(traceIndex); - break; - case sp.ANIMATION_EVENT_TYPE.COMPLETE: - if(listeners.completeListener) - listeners.completeListener(traceIndex, loopCount); - break; - case sp.ANIMATION_EVENT_TYPE.EVENT: - if(listeners.eventListener) - listeners.eventListener(traceIndex, event); - break; - } - }, - - onAnimationStateEvent: function(trackIndex, type, event, loopCount) { - switch(type){ - case sp.ANIMATION_EVENT_TYPE.START: - if(this._startListener) - this._startListener(trackIndex); - break; - case sp.ANIMATION_EVENT_TYPE.END: - if(this._endListener) - this._endListener(trackIndex); - break; - case sp.ANIMATION_EVENT_TYPE.COMPLETE: - if(this._completeListener) - this._completeListener(trackIndex, loopCount); - break; - case sp.ANIMATION_EVENT_TYPE.EVENT: - if(this._eventListener) - this._eventListener(trackIndex, event); - break; - } - }, - getState: function(){ return this._state; - }, - - _onAnimationStateStart: function (trackIndex) { - this._animationStateCallback(trackIndex, sp.ANIMATION_EVENT_TYPE.START, null, 0); - }, - _onAnimationStateEnd: function (trackIndex) { - this._animationStateCallback(trackIndex, sp.ANIMATION_EVENT_TYPE.END, null, 0); - }, - _onAnimationStateComplete: function (trackIndex, count) { - this._animationStateCallback(trackIndex, sp.ANIMATION_EVENT_TYPE.COMPLETE, null, count); - }, - _onAnimationStateEvent: function (trackIndex, event) { - this._animationStateCallback(trackIndex, sp.ANIMATION_EVENT_TYPE.EVENT, event, 0); - }, - _animationStateCallback: function (trackIndex, type, event, loopCount) { - this.onAnimationStateEvent(trackIndex, type, event, loopCount); - if (this._target && this._callback) { - this._callback.call(this._target, this, trackIndex, type, event, loopCount) - } } }); From 21466ef3733a25919e97ae4692c7fd50b0eefeb5 Mon Sep 17 00:00:00 2001 From: zhangbin Date: Wed, 22 Feb 2017 18:00:02 +0800 Subject: [PATCH 125/206] Solve the reviewed issues. --- extensions/spine/CCSkeletonAnimation.js | 99 +++++++++++++------------ 1 file changed, 50 insertions(+), 49 deletions(-) diff --git a/extensions/spine/CCSkeletonAnimation.js b/extensions/spine/CCSkeletonAnimation.js index 496f31e2b7..aa81be3318 100644 --- a/extensions/spine/CCSkeletonAnimation.js +++ b/extensions/spine/CCSkeletonAnimation.js @@ -65,61 +65,62 @@ sp.TrackEntryListeners = function(startListener, endListener, completeListener, this.callback = null; this.callbackTarget = null; this.skeletonNode = null; +}; - this.start = function(trackEntry) { - if (this.startListener) { - this.startListener(trackEntry); - } - if (this.callback && this.callbackTarget) { - this.callback.call(this.callbackTarget, this.skeletonNode, trackEntry, animEventType.START, null, 0); - } - }; +var proto = sp.TrackEntryListeners.prototype; +proto.start = function(trackEntry) { + if (this.startListener) { + this.startListener(trackEntry); + } + if (this.callback) { + this.callback.call(this.callbackTarget, this.skeletonNode, trackEntry, animEventType.START, null, 0); + } +}; - this.interrupt = function(trackEntry) { - if (this.interruptListener) { - this.interruptListener(trackEntry); - } - if (this.callback && this.callbackTarget) { - this.callback.call(this.callbackTarget, this.skeletonNode, trackEntry, animEventType.INTERRUPT, null, 0); - } - }; +proto.interrupt = function(trackEntry) { + if (this.interruptListener) { + this.interruptListener(trackEntry); + } + if (this.callback) { + this.callback.call(this.callbackTarget, this.skeletonNode, trackEntry, animEventType.INTERRUPT, null, 0); + } +}; - this.end = function (trackEntry) { - if (this.endListener) { - this.endListener(trackEntry); - } - if (this.callback && this.callbackTarget) { - this.callback.call(this.callbackTarget, this.skeletonNode, trackEntry, animEventType.END, null, 0); - } - }; +proto.end = function (trackEntry) { + if (this.endListener) { + this.endListener(trackEntry); + } + if (this.callback) { + this.callback.call(this.callbackTarget, this.skeletonNode, trackEntry, animEventType.END, null, 0); + } +}; - this.dispose = function (trackEntry) { - if (this.disposeListener) { - this.disposeListener(trackEntry); - } - if (this.callback && this.callbackTarget) { - this.callback.call(this.callbackTarget, this.skeletonNode, trackEntry, animEventType.DISPOSE, null, 0); - } - }; +proto.dispose = function (trackEntry) { + if (this.disposeListener) { + this.disposeListener(trackEntry); + } + if (this.callback) { + this.callback.call(this.callbackTarget, this.skeletonNode, trackEntry, animEventType.DISPOSE, null, 0); + } +}; - this.complete = function (trackEntry) { - var loopCount = Math.floor(trackEntry.trackTime / trackEntry.animationEnd); - if (this.completeListener) { - this.completeListener(trackEntry, loopCount); - } - if (this.callback && this.callbackTarget) { - this.callback.call(this.callbackTarget, this.skeletonNode, trackEntry, animEventType.COMPLETE, null, loopCount); - } - }; +proto.complete = function (trackEntry) { + var loopCount = Math.floor(trackEntry.trackTime / trackEntry.animationEnd); + if (this.completeListener) { + this.completeListener(trackEntry, loopCount); + } + if (this.callback) { + this.callback.call(this.callbackTarget, this.skeletonNode, trackEntry, animEventType.COMPLETE, null, loopCount); + } +}; - this.event = function (trackEntry, event) { - if (this.eventListener) { - this.eventListener(trackEntry, event); - } - if (this.callback && this.callbackTarget) { - this.callback.call(this.callbackTarget, this.skeletonNode, trackEntry, animEventType.EVENT, event, 0); - } - }; +proto.event = function (trackEntry, event) { + if (this.eventListener) { + this.eventListener(trackEntry, event); + } + if (this.callback) { + this.callback.call(this.callbackTarget, this.skeletonNode, trackEntry, animEventType.EVENT, event, 0); + } }; sp.TrackEntryListeners.getListeners = function(entry){ From 05bfb2f3cf74962006a13e12edb4839d491a9d86 Mon Sep 17 00:00:00 2001 From: zhangbin Date: Wed, 22 Feb 2017 18:10:33 +0800 Subject: [PATCH 126/206] Solve spine event callback error. --- extensions/spine/CCSkeletonAnimation.js | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/extensions/spine/CCSkeletonAnimation.js b/extensions/spine/CCSkeletonAnimation.js index aa81be3318..339bd08f15 100644 --- a/extensions/spine/CCSkeletonAnimation.js +++ b/extensions/spine/CCSkeletonAnimation.js @@ -73,7 +73,7 @@ proto.start = function(trackEntry) { this.startListener(trackEntry); } if (this.callback) { - this.callback.call(this.callbackTarget, this.skeletonNode, trackEntry, animEventType.START, null, 0); + this.callback.call(this.callbackTarget, this.skeletonNode, trackEntry, sp.ANIMATION_EVENT_TYPE.START, null, 0); } }; @@ -82,7 +82,7 @@ proto.interrupt = function(trackEntry) { this.interruptListener(trackEntry); } if (this.callback) { - this.callback.call(this.callbackTarget, this.skeletonNode, trackEntry, animEventType.INTERRUPT, null, 0); + this.callback.call(this.callbackTarget, this.skeletonNode, trackEntry, sp.ANIMATION_EVENT_TYPE.INTERRUPT, null, 0); } }; @@ -91,7 +91,7 @@ proto.end = function (trackEntry) { this.endListener(trackEntry); } if (this.callback) { - this.callback.call(this.callbackTarget, this.skeletonNode, trackEntry, animEventType.END, null, 0); + this.callback.call(this.callbackTarget, this.skeletonNode, trackEntry, sp.ANIMATION_EVENT_TYPE.END, null, 0); } }; @@ -100,7 +100,7 @@ proto.dispose = function (trackEntry) { this.disposeListener(trackEntry); } if (this.callback) { - this.callback.call(this.callbackTarget, this.skeletonNode, trackEntry, animEventType.DISPOSE, null, 0); + this.callback.call(this.callbackTarget, this.skeletonNode, trackEntry, sp.ANIMATION_EVENT_TYPE.DISPOSE, null, 0); } }; @@ -110,7 +110,7 @@ proto.complete = function (trackEntry) { this.completeListener(trackEntry, loopCount); } if (this.callback) { - this.callback.call(this.callbackTarget, this.skeletonNode, trackEntry, animEventType.COMPLETE, null, loopCount); + this.callback.call(this.callbackTarget, this.skeletonNode, trackEntry, sp.ANIMATION_EVENT_TYPE.COMPLETE, null, loopCount); } }; @@ -119,7 +119,7 @@ proto.event = function (trackEntry, event) { this.eventListener(trackEntry, event); } if (this.callback) { - this.callback.call(this.callbackTarget, this.skeletonNode, trackEntry, animEventType.EVENT, event, 0); + this.callback.call(this.callbackTarget, this.skeletonNode, trackEntry, sp.ANIMATION_EVENT_TYPE.EVENT, event, 0); } }; From 414bf8faac2438626915f28d0749664d712f05d4 Mon Sep 17 00:00:00 2001 From: zhangbin Date: Mon, 6 Mar 2017 16:50:11 +0800 Subject: [PATCH 127/206] Solve the error logic in spine runtime. Sync the runtime to the state of this commit: https://github.com/EsotericSoftware/spine-runtimes/commit/3ced1e1daf722793740130094b9352e07b3dced7 --- extensions/spine/Spine.js | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/extensions/spine/Spine.js b/extensions/spine/Spine.js index 0d4533c3f0..401e6b84c3 100644 --- a/extensions/spine/Spine.js +++ b/extensions/spine/Spine.js @@ -1051,6 +1051,7 @@ var spine; } } this.queueEvents(current, animationTime); + events.length = 0; current.nextAnimationLast = animationTime; current.nextTrackLast = current.trackTime; } @@ -1094,7 +1095,9 @@ var spine; timeline.apply(skeleton, animationLast, animationTime, events, alpha, setupPose, true); } } + if (entry.mixDuration > 0) this.queueEvents(from, animationTime); + this.events.length = 0; from.nextAnimationLast = animationTime; from.nextTrackLast = from.trackTime; return mix; @@ -1182,7 +1185,6 @@ var spine; continue; this.queue.event(entry, events[i]); } - this.events.length = 0; }; AnimationState.prototype.clearTracks = function () { this.queue.drainDisabled = true; @@ -1221,7 +1223,7 @@ var spine; current.mixingFrom = from; current.mixTime = 0; from.timelinesRotation.length = 0; - if (from.mixingFrom != null) + if (from.mixingFrom != null && from.mixDuration > 0) current.mixAlpha *= Math.min(from.mixTime / from.mixDuration, 1); } this.queue.start(current); @@ -1333,7 +1335,7 @@ var spine; entry.trackTime = 0; entry.trackLast = -1; entry.nextTrackLast = -1; - entry.trackEnd = loop ? Number.MAX_VALUE : entry.animationEnd; + entry.trackEnd = Number.MAX_VALUE; entry.timeScale = 1; entry.alpha = 1; entry.mixAlpha = 1; From f9a30bb9d55fcce42988d768728e4b13a3b0060a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=91=D0=B5=D1=81=D1=88=D0=B0=D0=BF=D0=BE=D1=88=D0=BD?= =?UTF-8?q?=D0=B8=D0=BA=D0=BE=D0=B2=20=D0=9D=D0=B8=D0=BA=D0=B8=D1=82=D0=B0?= Date: Tue, 7 Mar 2017 15:52:35 +0300 Subject: [PATCH 128/206] Enable support of retina displays --- cocos2d/core/platform/CCConfig.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos2d/core/platform/CCConfig.js b/cocos2d/core/platform/CCConfig.js index 027bede099..7344ff1bfc 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 = 0; +cc.IS_RETINA_DISPLAY_SUPPORTED = 1; /** * Default engine From 86d84741da31b9374032dca28e80a1676e18db36 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=91=D0=B5=D1=81=D1=88=D0=B0=D0=BF=D0=BE=D1=88=D0=BD?= =?UTF-8?q?=D0=B8=D0=BA=D0=BE=D0=B2=20=D0=9D=D0=B8=D0=BA=D0=B8=D1=82=D0=B0?= Date: Wed, 8 Mar 2017 10:28:35 +0300 Subject: [PATCH 129/206] =?UTF-8?q?Remove=20useless=20cc.IS=5FRETINA=5FDIS?= =?UTF-8?q?PLAY=5FSUPPORTED=20macro=20and=20it=E2=80=99s=20usage?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- cocos2d/core/platform/CCConfig.js | 7 ------- cocos2d/core/platform/CCMacro.js | 12 +++--------- 2 files changed, 3 insertions(+), 16 deletions(-) diff --git a/cocos2d/core/platform/CCConfig.js b/cocos2d/core/platform/CCConfig.js index 7344ff1bfc..76730a0ac9 100644 --- a/cocos2d/core/platform/CCConfig.js +++ b/cocos2d/core/platform/CCConfig.js @@ -262,13 +262,6 @@ cc.LABELATLAS_DEBUG_DRAW = 0; cc.DRAWNODE_TOTAL_VERTICES = 20000; -/** - * Whether or not support retina display - * @constant - * @type {Number} - */ -cc.IS_RETINA_DISPLAY_SUPPORTED = 1; - /** * Default engine * @constant diff --git a/cocos2d/core/platform/CCMacro.js b/cocos2d/core/platform/CCMacro.js index 8ee902585b..a89331c9f1 100644 --- a/cocos2d/core/platform/CCMacro.js +++ b/cocos2d/core/platform/CCMacro.js @@ -244,10 +244,8 @@ cc.FLT_EPSILON = 0.0000001192092896; * @return {Number} * @function */ -cc.contentScaleFactor = cc.IS_RETINA_DISPLAY_SUPPORTED ? function () { +cc.contentScaleFactor = function () { return cc.director._contentScaleFactor; -} : function () { - return 1; }; /** @@ -312,12 +310,10 @@ cc._sizePixelsToPointsOut = function (sizeInPixels, outSize) { * @return {cc.Rect} * @function */ -cc.rectPixelsToPoints = cc.IS_RETINA_DISPLAY_SUPPORTED ? function (pixel) { +cc.rectPixelsToPoints = function (pixel) { var scale = cc.contentScaleFactor(); return cc.rect(pixel.x / scale, pixel.y / scale, pixel.width / scale, pixel.height / scale); -} : function (p) { - return p; }; /** @@ -326,12 +322,10 @@ cc.rectPixelsToPoints = cc.IS_RETINA_DISPLAY_SUPPORTED ? function (pixel) { * @return {cc.Rect} * @function */ -cc.rectPointsToPixels = cc.IS_RETINA_DISPLAY_SUPPORTED ? function (point) { +cc.rectPointsToPixels = function (point) { var scale = cc.contentScaleFactor(); return cc.rect(point.x * scale, point.y * scale, point.width * scale, point.height * scale); -} : function (p) { - return p; }; //some gl constant variable From 7d04cbc1bc18deb178b7db5a8b38879b76ab55bf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=91=D0=B5=D1=81=D1=88=D0=B0=D0=BF=D0=BE=D1=88=D0=BD?= =?UTF-8?q?=D0=B8=D0=BA=D0=BE=D0=B2=20=D0=9D=D0=B8=D0=BA=D0=B8=D1=82=D0=B0?= Date: Wed, 8 Mar 2017 10:31:26 +0300 Subject: [PATCH 130/206] Remove cc.RETINA_DISPLAY_SUPPORT deprecated macro. --- cocos2d/core/platform/CCConfig.js | 17 ----------------- 1 file changed, 17 deletions(-) diff --git a/cocos2d/core/platform/CCConfig.js b/cocos2d/core/platform/CCConfig.js index 76730a0ac9..920ef69528 100644 --- a/cocos2d/core/platform/CCConfig.js +++ b/cocos2d/core/platform/CCConfig.js @@ -165,23 +165,6 @@ cc.TEXTURE_ATLAS_USE_VAO = 0; */ cc.TEXTURE_NPOT_SUPPORT = 0; -/** - *

- * If enabled, cocos2d supports retina display.
- * For performance reasons, it's recommended disable it in games without retina display support, like iPad only games.
- *
- * To enable set it to 1. Use 0 to disable it. Enabled by default.
- *
- * This value governs only the PNG, GIF, BMP, images.
- * This value DOES NOT govern the PVR (PVR.GZ, PVR.CCZ) files. If NPOT PVR is loaded, then it will create an NPOT texture ignoring this value.
- * To modify it, in Web engine please refer to CCConfig.js, in JSB please refer to CCConfig.h - *

- * @constant - * @type {Number} - * @deprecated This value will be removed in 1.1 and NPOT textures will be loaded by default if the device supports it. - */ -cc.RETINA_DISPLAY_SUPPORT = 1; - /** *

* It's the suffix that will be appended to the files in order to load "retina display" images.
From fb2a31b4cdc729c925cc2cd80f7c1db7fb013aa3 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Wed, 15 Mar 2017 16:12:44 +0800 Subject: [PATCH 131/206] Fix clippingNodeRenderCmd setProgram issue --- .../clipping-nodes/CCClippingNodeWebGLRenderCmd.js | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/cocos2d/clipping-nodes/CCClippingNodeWebGLRenderCmd.js b/cocos2d/clipping-nodes/CCClippingNodeWebGLRenderCmd.js index d563fb711c..6d8956a32b 100644 --- a/cocos2d/clipping-nodes/CCClippingNodeWebGLRenderCmd.js +++ b/cocos2d/clipping-nodes/CCClippingNodeWebGLRenderCmd.js @@ -22,6 +22,17 @@ THE SOFTWARE. ****************************************************************************/ +function setProgram (node, program) { + node.shaderProgram = program; + + var children = node.children; + if (!children) + return; + + for (var i = 0; i < children.length; i++) + setProgram(children[i], program); +} + // ------------------------------- ClippingNode's WebGL render cmd ------------------------------ (function () { cc.ClippingNode.WebGLRenderCmd = function (renderable) { @@ -128,7 +139,7 @@ var node = this._node; if (node._stencil) { var program = node._originStencilProgram; - cc.setProgram(node._stencil, program); + setProgram(node._stencil, program); } }; From 4dfad9f8fcafc2448c7177e0a6039ebcd90ca291 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Wed, 15 Mar 2017 16:14:14 +0800 Subject: [PATCH 132/206] Fix a bunch of issues --- cocos2d/core/CCDirector.js | 4 ++-- cocos2d/core/base-nodes/CCNode.js | 2 +- cocos2d/core/layers/CCLayer.js | 2 +- cocos2d/core/scenes/CCLoaderScene.js | 3 ++- cocos2d/core/sprites/CCSpriteFrameCache.js | 2 +- cocos2d/core/sprites/CCSpriteWebGLRenderCmd.js | 10 ++++++---- .../cocostudio/loader/parsers/timelineParser-2.x.js | 8 ++++---- 7 files changed, 17 insertions(+), 14 deletions(-) diff --git a/cocos2d/core/CCDirector.js b/cocos2d/core/CCDirector.js index b906a7fbd7..bfc8481d68 100644 --- a/cocos2d/core/CCDirector.js +++ b/cocos2d/core/CCDirector.js @@ -183,7 +183,7 @@ cc.Director = cc.Class.extend(/** @lends cc.Director# */{ convertToGL: function (uiPoint) { var docElem = document.documentElement; var view = cc.view; - var box = element.getBoundingClientRect(); + var box = docElem.getBoundingClientRect(); box.left += window.pageXOffset - docElem.clientLeft; box.top += window.pageYOffset - docElem.clientTop; var x = view._devicePixelRatio * (uiPoint.x - box.left); @@ -202,7 +202,7 @@ cc.Director = cc.Class.extend(/** @lends cc.Director# */{ convertToUI: function (glPoint) { var docElem = document.documentElement; var view = cc.view; - var box = element.getBoundingClientRect(); + var box = docElem.getBoundingClientRect(); box.left += window.pageXOffset - docElem.clientLeft; box.top += window.pageYOffset - docElem.clientTop; var uiPoint = {x: 0, y: 0}; diff --git a/cocos2d/core/base-nodes/CCNode.js b/cocos2d/core/base-nodes/CCNode.js index 2b62bc06c4..f13eaf6ae8 100644 --- a/cocos2d/core/base-nodes/CCNode.js +++ b/cocos2d/core/base-nodes/CCNode.js @@ -2015,7 +2015,7 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{ updateTransform: function () { var children = this._children, node; for (var i = 0; i < children.length; i++) { - varnode = children[i]; + var node = children[i]; if (node) node.updateTransform(); } diff --git a/cocos2d/core/layers/CCLayer.js b/cocos2d/core/layers/CCLayer.js index db1e783a2e..626dcfc01a 100644 --- a/cocos2d/core/layers/CCLayer.js +++ b/cocos2d/core/layers/CCLayer.js @@ -247,7 +247,7 @@ cc.LayerColor = cc.Layer.extend(/** @lends cc.LayerColor# */{ return true; }, - visit: function () { + visit: function (parent) { // quick return if not visible if (!this._visible) return; diff --git a/cocos2d/core/scenes/CCLoaderScene.js b/cocos2d/core/scenes/CCLoaderScene.js index 12c482c476..2f051811b1 100644 --- a/cocos2d/core/scenes/CCLoaderScene.js +++ b/cocos2d/core/scenes/CCLoaderScene.js @@ -33,6 +33,7 @@ cc.LoaderScene = cc.Scene.extend({ _interval : null, _label : null, + _logo : null, _className:"LoaderScene", cb: null, target: null, @@ -132,7 +133,7 @@ cc.LoaderScene = cc.Scene.extend({ this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.transformDirty); this._bgLayer._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.transformDirty); this._label._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.transformDirty); - this._logo._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.transformDirty); + this._logo && this._logo._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.transformDirty); } }); /** diff --git a/cocos2d/core/sprites/CCSpriteFrameCache.js b/cocos2d/core/sprites/CCSpriteFrameCache.js index d8df34823b..7d38e89a5b 100644 --- a/cocos2d/core/sprites/CCSpriteFrameCache.js +++ b/cocos2d/core/sprites/CCSpriteFrameCache.js @@ -169,7 +169,7 @@ cc.spriteFrameCache = /** @lends cc.spriteFrameCache# */{ var frame = frames[key]; var spriteFrame = spriteFrames[key]; if (!spriteFrame) { - spriteFrame = new cc.SpriteFrame(texture, frame.rect, frame.rotated, frame.offset, frame.size); + spriteFrame = new cc.SpriteFrame(texture, cc.rect(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++) { diff --git a/cocos2d/core/sprites/CCSpriteWebGLRenderCmd.js b/cocos2d/core/sprites/CCSpriteWebGLRenderCmd.js index 79e0c4b58f..4a543a616c 100644 --- a/cocos2d/core/sprites/CCSpriteWebGLRenderCmd.js +++ b/cocos2d/core/sprites/CCSpriteWebGLRenderCmd.js @@ -235,10 +235,12 @@ node._texture = texture; // Update texture rect and blend func - var texSize = texture._contentSize; - var rect = cc.rect(0, 0, texSize.width, texSize.height); - node.setTextureRect(rect); - this._updateBlendFunc(); + if (texture) { + var texSize = texture._contentSize; + var rect = cc.rect(0, 0, texSize.width, texSize.height); + node.setTextureRect(rect); + this._updateBlendFunc(); + } if (node._textureLoaded) { // Force refresh the render command list diff --git a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js index e79ab9b791..c823ce8737 100644 --- a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js +++ b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js @@ -1078,18 +1078,18 @@ * @returns {ccui.TextBMFont} */ parser.initTextBMFont = function (json, resourcePath) { - var widget = new ccui.TextBMFont(); this.widgetAttributes(widget, json); - var text = json["LabelText"]; - widget.setString(text); - 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); }); + + var text = json["LabelText"]; + widget.setString(text); + widget.ignoreContentAdaptWithSize(true); return widget; }; From ca0a6ae0b97866812b6eebf7d834dd4ed91e64fb Mon Sep 17 00:00:00 2001 From: pandamicro Date: Wed, 15 Mar 2017 16:15:04 +0800 Subject: [PATCH 133/206] Use rAF instead of setTimeout for 30 fps --- CCBoot.js | 20 ++++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/CCBoot.js b/CCBoot.js index a048a028b3..0a7968264e 100644 --- a/CCBoot.js +++ b/CCBoot.js @@ -2330,6 +2330,7 @@ cc.game = /** @lends cc.game# */{ config[CONFIG_KEY.frameRate] = frameRate; if (self._intervalId) window.cancelAnimationFrame(self._intervalId); + self._intervalId = 0; self._paused = true; self._setAnimFrame(); self._runMainLoop(); @@ -2512,8 +2513,9 @@ cc.game = /** @lends cc.game# */{ // @Time ticker section _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) { + var frameRate = cc.game.config[cc.game.CONFIG_KEY.frameRate]; + this._frameTime = 1000 / frameRate; + if (frameRate !== 60 && frameRate !== 30) { window.requestAnimFrame = this._stTime; window.cancelAnimationFrame = this._ctTime; } @@ -2551,20 +2553,26 @@ cc.game = /** @lends cc.game# */{ //Run game. _runMainLoop: function () { var self = this, callback, config = self.config, CONFIG_KEY = self.CONFIG_KEY, - director = cc.director; + director = cc.director, + skip = true, frameRate = config[CONFIG_KEY.frameRate]; director.setDisplayStats(config[CONFIG_KEY.showFPS]); callback = function () { if (!self._paused) { + if (frameRate === 30) { + if (skip = !skip) { + self._intervalId = window.requestAnimFrame(callback); + return; + } + } + director.mainLoop(); - if (self._intervalId) - window.cancelAnimationFrame(self._intervalId); self._intervalId = window.requestAnimFrame(callback); } }; - window.requestAnimFrame(callback); + self._intervalId = window.requestAnimFrame(callback); self._paused = false; }, From 37638e46240c95824eb67809b74f83ffae150bab Mon Sep 17 00:00:00 2001 From: pandamicro Date: Wed, 15 Mar 2017 16:15:29 +0800 Subject: [PATCH 134/206] Improve webgl compatibility --- CCBoot.js | 5 +++-- cocos2d/shaders/CCGLProgram.js | 4 ++-- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/CCBoot.js b/CCBoot.js index 0a7968264e..48179d84e3 100644 --- a/CCBoot.js +++ b/CCBoot.js @@ -916,6 +916,7 @@ cc.loader = (function () { var self = this; var errorCallback = function () { + this.removeEventListener('load', loadCallback, false); this.removeEventListener('error', errorCallback, false); if (img.crossOrigin && img.crossOrigin.toLowerCase() === "anonymous") { @@ -1757,7 +1758,7 @@ var _initSys = function () { sys.browserVersion = ""; /* Determine the browser version number */ (function(){ - var versionReg1 = /(micromessenger|qq|mx|maxthon|baidu|sogou)(mobile)?(browser)?\/?([\d.]+)/i; + var versionReg1 = /(micromessenger|mqqbrowser|qq|maxthon|baidu|sogou)(mobile)?(browser)?\/?([\d.]+)/i; var versionReg2 = /(msie |rv:|firefox|chrome|ucbrowser|oupeng|opera|opr|safari|miui)(mobile)?(browser)?\/?([\d.]+)/i; var tmp = ua.match(versionReg1); if(!tmp) tmp = ua.match(versionReg2); @@ -1844,7 +1845,7 @@ var _initSys = function () { var tmpCanvas = document.createElement("CANVAS"); try{ var context = cc.create3DContext(tmpCanvas); - if (context && context.getShaderPrecisionFormat) { + if (context) { _supportWebGL = true; } diff --git a/cocos2d/shaders/CCGLProgram.js b/cocos2d/shaders/CCGLProgram.js index d9e59b109d..30c6176f11 100644 --- a/cocos2d/shaders/CCGLProgram.js +++ b/cocos2d/shaders/CCGLProgram.js @@ -795,8 +795,8 @@ cc.GLProgram.create = function (vShaderFileName, fShaderFileName) { cc.GLProgram._highpSupported = null; cc.GLProgram._isHighpSupported = function () { - if (cc.GLProgram._highpSupported == null) { - var ctx = cc._renderContext; + var ctx = cc._renderContext; + if (ctx.getShaderPrecisionFormat && cc.GLProgram._highpSupported == null) { var highp = ctx.getShaderPrecisionFormat(ctx.FRAGMENT_SHADER, ctx.HIGH_FLOAT); cc.GLProgram._highpSupported = highp.precision !== 0; } From 9f7810631a3c0c0e421d79cc964b3e74d4cb114e Mon Sep 17 00:00:00 2001 From: pandamicro Date: Wed, 15 Mar 2017 16:20:33 +0800 Subject: [PATCH 135/206] Improve screen adaptation for iframe --- cocos2d/core/platform/CCEGLView.js | 46 +++++++++++++++++++----------- 1 file changed, 29 insertions(+), 17 deletions(-) diff --git a/cocos2d/core/platform/CCEGLView.js b/cocos2d/core/platform/CCEGLView.js index 37c89fd688..46d92f94b4 100755 --- a/cocos2d/core/platform/CCEGLView.js +++ b/cocos2d/core/platform/CCEGLView.js @@ -140,6 +140,7 @@ cc.EGLView = cc.Class.extend(/** @lends cc.view# */{ _resizeCallback: null, _orientationChanging: true, + _resizing: false, _scaleX: 1, _originalScaleX: 1, @@ -187,8 +188,6 @@ cc.EGLView = cc.Class.extend(/** @lends cc.view# */{ _t._viewName = "Cocos2dHTML5"; var sys = cc.sys; - _t.enableRetina(sys.os === sys.OS_IOS || sys.os === sys.OS_OSX); - _t.enableAutoFullScreen(sys.isMobile && sys.browserType !== sys.BROWSER_TYPE_BAIDU); cc.visibleRect && cc.visibleRect.init(_t._visibleRect); // Setup system default resolution policies @@ -212,15 +211,29 @@ cc.EGLView = cc.Class.extend(/** @lends cc.view# */{ // Check frame size changed or not var prevFrameW = view._frameSize.width, prevFrameH = view._frameSize.height, prevRotated = view._isRotated; - view._initFrameSize(); + if (cc.sys.isMobile) { + var containerStyle = cc.game.container.style, + margin = containerStyle.margin; + containerStyle.margin = '0'; + containerStyle.display = 'none'; + view._initFrameSize(); + containerStyle.margin = margin; + containerStyle.display = 'block'; + } + else { + view._initFrameSize(); + } if (view._isRotated === prevRotated && view._frameSize.width === prevFrameW && view._frameSize.height === prevFrameH) return; // Frame size changed, do resize works var width = view._originalDesignResolutionSize.width; var height = view._originalDesignResolutionSize.height; - if (width > 0) + view._resizing = true; + if (width > 0) { view.setDesignResolutionSize(width, height, view._resolutionPolicy); + } + view._resizing = false; cc.eventManager.dispatchCustomEvent('canvas-resize'); if (view._resizeCallback) { @@ -347,9 +360,11 @@ cc.EGLView = cc.Class.extend(/** @lends cc.view# */{ cc.container.style.transformOrigin = '0px 0px 0px'; this._isRotated = true; } - setTimeout(function () { - cc.view._orientationChanging = false; - }, 1000); + if (this._orientationChanging) { + setTimeout(function () { + cc.view._orientationChanging = false; + }, 1000); + } }, // hack @@ -482,12 +497,6 @@ cc.EGLView = cc.Class.extend(/** @lends cc.view# */{ return this._autoFullScreen; }, - /** - * Force destroying EGL view, subclass must implement this method. - */ - end: function () { - }, - /** * Get whether render system is ready(no matter opengl or canvas),
* this name is for the compatibility with cocos2d-x, subclass must implement this method. @@ -688,7 +697,8 @@ cc.EGLView = cc.Class.extend(/** @lends cc.view# */{ // Permit to re-detect the orientation of device. this._orientationChanging = true; - this._initFrameSize(); + if (!this._resizing) + this._initFrameSize(); if (!policy) { cc.log(cc._LogInfos.EGLView_setDesignResolutionSize_2); @@ -771,8 +781,10 @@ cc.EGLView = cc.Class.extend(/** @lends cc.view# */{ this._setViewportMeta({"width": width}, true); // Set body width to the exact pixel resolution - document.documentElement.style.width = width + 'px'; - document.body.style.width = "100%"; + document.documentElement.style.width = width + "px"; + document.body.style.width = width + "px"; + document.body.style.left = "0px"; + document.body.style.top = "0px"; // Reset the resolution size and policy this.setDesignResolutionSize(width, height, resolutionPolicy); @@ -985,7 +997,7 @@ cc.ContainerStrategy = cc.Class.extend(/** @lends cc.ContainerStrategy# */{ _setupContainer: function (view, w, h) { var locCanvas = cc.game.canvas, locContainer = cc.game.container; - if (cc.sys.isMobile) { + if (cc.sys.os === cc.sys.OS_ANDROID) { document.body.style.width = (view._isRotated ? h : w) + 'px'; document.body.style.height = (view._isRotated ? w : h) + 'px'; } From b8a85eaee3627d3eb639848d4bbb5746b5f03fda Mon Sep 17 00:00:00 2001 From: pandamicro Date: Wed, 15 Mar 2017 16:20:48 +0800 Subject: [PATCH 136/206] Refactor ShaderCache implementation --- cocos2d/shaders/CCShaderCache.js | 41 +++++++++++++++++++++++--------- 1 file changed, 30 insertions(+), 11 deletions(-) diff --git a/cocos2d/shaders/CCShaderCache.js b/cocos2d/shaders/CCShaderCache.js index b064719f8d..462f208d21 100644 --- a/cocos2d/shaders/CCShaderCache.js +++ b/cocos2d/shaders/CCShaderCache.js @@ -110,10 +110,25 @@ cc.shaderCache = /** @lends cc.shaderCache# */{ */ TYPE_MAX: 11, + _keyMap: [ + cc.SHADER_POSITION_TEXTURECOLOR, + cc.SHADER_POSITION_TEXTURECOLORALPHATEST, + cc.SHADER_POSITION_COLOR, + cc.SHADER_POSITION_TEXTURE, + cc.SHADER_POSITION_TEXTURE_UCOLOR, + cc.SHADER_POSITION_TEXTUREA8COLOR, + cc.SHADER_POSITION_UCOLOR, + cc.SHADER_POSITION_LENGTHTEXTURECOLOR, + cc.SHADER_SPRITE_POSITION_TEXTURECOLOR, + cc.SHADER_SPRITE_POSITION_TEXTURECOLORALPHATEST, + cc.SHADER_SPRITE_POSITION_COLOR, + cc.SHADER_SPRITE_POSITION_TEXTURECOLOR_GRAY + ], + _programs: {}, _init: function () { - // this.loadDefaultShaders(); + this.loadDefaultShaders(); return true; }, @@ -200,6 +215,10 @@ cc.shaderCache = /** @lends cc.shaderCache# */{ * loads the default shaders */ loadDefaultShaders: function () { + for (var i = 0; i < this.TYPE_MAX; ++i) { + var key = this._keyMap[i]; + this.programForKey(key); + } }, /** @@ -211,62 +230,62 @@ cc.shaderCache = /** @lends cc.shaderCache# */{ // Position Texture Color shader var program = this.programForKey(cc.SHADER_POSITION_TEXTURECOLOR); program.reset(); - this._loadDefaultShader(program, this.TYPE_POSITION_TEXTURECOLOR); + this._loadDefaultShader(program, cc.SHADER_POSITION_TEXTURECOLOR); // Sprite Position Texture Color shader program = this.programForKey(cc.SHADER_SPRITE_POSITION_TEXTURECOLOR); program.reset(); - this._loadDefaultShader(program, this.TYPE_SPRITE_POSITION_TEXTURECOLOR); + this._loadDefaultShader(program, cc.SHADER_SPRITE_POSITION_TEXTURECOLOR); // Position Texture Color alpha test program = this.programForKey(cc.SHADER_POSITION_TEXTURECOLORALPHATEST); program.reset(); - this._loadDefaultShader(program, this.TYPE_POSITION_TEXTURECOLOR_ALPHATEST); + this._loadDefaultShader(program, cc.SHADER_POSITION_TEXTURECOLORALPHATEST); // Sprite Position Texture Color alpha shader program = this.programForKey(cc.SHADER_SPRITE_POSITION_TEXTURECOLORALPHATEST); program.reset(); - this._loadDefaultShader(program, this.TYPE_SPRITE_POSITION_TEXTURECOLOR_ALPHATEST); + this._loadDefaultShader(program, cc.SHADER_SPRITE_POSITION_TEXTURECOLORALPHATEST); // // Position, Color shader // program = this.programForKey(cc.SHADER_POSITION_COLOR); program.reset(); - this._loadDefaultShader(program, this.TYPE_POSITION_COLOR); + this._loadDefaultShader(program, cc.SHADER_POSITION_COLOR); // // Position Texture shader // program = this.programForKey(cc.SHADER_POSITION_TEXTURE); program.reset(); - this._loadDefaultShader(program, this.TYPE_POSITION_TEXTURE); + this._loadDefaultShader(program, cc.SHADER_POSITION_TEXTURE); //Position Texture Gray shader program = this.programForKey(cc.SHADER_SPRITE_POSITION_TEXTURE_COLOR_GRAY_FRAG); program.reset(); - this._loadDefaultShader(program, this.TYPE_SPRITE_POSITION_TEXTURECOLOR_GRAY); + this._loadDefaultShader(program, cc.SHADER_SPRITE_POSITION_TEXTURE_COLOR_GRAY_FRAG); // // Position, Texture attribs, 1 Color as uniform shader // program = this.programForKey(cc.SHADER_POSITION_TEXTURE_UCOLOR); program.reset(); - this._loadDefaultShader(program, this.TYPE_POSITION_TEXTURE_UCOLOR); + this._loadDefaultShader(program, cc.SHADER_POSITION_TEXTURE_UCOLOR); // // Position Texture A8 Color shader // program = this.programForKey(cc.SHADER_POSITION_TEXTUREA8COLOR); program.reset(); - this._loadDefaultShader(program, this.TYPE_POSITION_TEXTURE_A8COLOR); + this._loadDefaultShader(program, cc.SHADER_POSITION_TEXTUREA8COLOR); // // Position and 1 color passed as a uniform (to similate glColor4ub ) // program = this.programForKey(cc.SHADER_POSITION_UCOLOR); program.reset(); - this._loadDefaultShader(program, this.TYPE_POSITION_UCOLOR); + this._loadDefaultShader(program, cc.SHADER_POSITION_UCOLOR); }, /** From 1fec2d2ece083d631862386289f3290295b46db8 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Wed, 15 Mar 2017 16:21:04 +0800 Subject: [PATCH 137/206] Fix draw node calculation issues --- cocos2d/core/support/CCPointExtension.js | 4 +++- cocos2d/shape-nodes/CCDrawNode.js | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/cocos2d/core/support/CCPointExtension.js b/cocos2d/core/support/CCPointExtension.js index d2ea212435..3171a5f7ea 100644 --- a/cocos2d/core/support/CCPointExtension.js +++ b/cocos2d/core/support/CCPointExtension.js @@ -510,5 +510,7 @@ cc.pAddIn = function(v1, v2) { * @param {cc.Point} v */ cc.pNormalizeIn = function(v) { - cc.pMultIn(v, 1.0 / Math.sqrt(v.x * v.x + v.y * v.y)); + var n = Math.sqrt(v.x * v.x + v.y * v.y); + if (n !== 0) + cc.pMultIn(v, 1.0 / n); }; diff --git a/cocos2d/shape-nodes/CCDrawNode.js b/cocos2d/shape-nodes/CCDrawNode.js index 732bd8cda8..d0843ec6b6 100644 --- a/cocos2d/shape-nodes/CCDrawNode.js +++ b/cocos2d/shape-nodes/CCDrawNode.js @@ -570,7 +570,7 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () { // Copy old data if (prev !== 0 && prevOffset !== offset) { // offset is in byte, we need to transform to float32 index - var last = (prevOffset + prev) / 4; + var last = prevOffset / 4 + prev * FLOAT_PER_VERTEX; for (var i = offset / 4, j = prevOffset / 4; j < last; i++, j++) { _sharedBuffer.dataArray[i] = _sharedBuffer.dataArray[j]; } From f65e972c14edef48b7b0ed5e0d636a13569e0526 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Thu, 23 Mar 2017 16:23:31 +0800 Subject: [PATCH 138/206] Fix browser version regular expression --- CCBoot.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/CCBoot.js b/CCBoot.js index 48179d84e3..f1aca8bcf2 100644 --- a/CCBoot.js +++ b/CCBoot.js @@ -1758,8 +1758,8 @@ var _initSys = function () { sys.browserVersion = ""; /* Determine the browser version number */ (function(){ - var versionReg1 = /(micromessenger|mqqbrowser|qq|maxthon|baidu|sogou)(mobile)?(browser)?\/?([\d.]+)/i; - var versionReg2 = /(msie |rv:|firefox|chrome|ucbrowser|oupeng|opera|opr|safari|miui)(mobile)?(browser)?\/?([\d.]+)/i; + var versionReg1 = /(mqqbrowser|micromessenger|sogou|qzone|liebao|maxthon|baidu)(mobile)?(browser)?\/?([\d.]+)/i; + var versionReg2 = /(msie |rv:|firefox|chrome|ucbrowser|qq|oupeng|opera|opr|safari|miui)(mobile)?(browser)?\/?([\d.]+)/i; var tmp = ua.match(versionReg1); if(!tmp) tmp = ua.match(versionReg2); sys.browserVersion = tmp ? tmp[4] : ""; From dbe06b6e3f2527423210fcb4b7d380810bc84095 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Thu, 23 Mar 2017 16:24:19 +0800 Subject: [PATCH 139/206] Improve cc.view adaptation logic --- cocos2d/core/platform/CCEGLView.js | 50 ++++++++++-------------------- 1 file changed, 16 insertions(+), 34 deletions(-) diff --git a/cocos2d/core/platform/CCEGLView.js b/cocos2d/core/platform/CCEGLView.js index 46d92f94b4..68feb552e2 100755 --- a/cocos2d/core/platform/CCEGLView.js +++ b/cocos2d/core/platform/CCEGLView.js @@ -37,7 +37,7 @@ cc.DENSITYDPI_LOW = "low-dpi"; var __BrowserGetter = { init: function () { - this.html = document.getElementsByTagName("html")[0]; + this.html = document.documentElement; }, availWidth: function (frame) { if (!frame || frame === this.html) @@ -66,25 +66,11 @@ if (cc.sys.os === cc.sys.OS_IOS) // All browsers are WebView switch (__BrowserGetter.adaptationType) { case cc.sys.BROWSER_TYPE_SAFARI: __BrowserGetter.meta["minimal-ui"] = "true"; - __BrowserGetter.availWidth = function (frame) { - return frame.clientWidth; - }; - __BrowserGetter.availHeight = function (frame) { - return frame.clientHeight; - }; break; case cc.sys.BROWSER_TYPE_CHROME: __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) { - return frame.clientWidth; - }; - __BrowserGetter.availHeight = function (frame) { - return frame.clientHeight; - }; break; case cc.sys.BROWSER_TYPE_MIUI: __BrowserGetter.init = function (view) { @@ -318,9 +304,11 @@ cc.EGLView = cc.Class.extend(/** @lends cc.view# */{ orientation = orientation & cc.ORIENTATION_AUTO; if (orientation && this._orientation !== orientation) { this._orientation = orientation; - var designWidth = this._originalDesignResolutionSize.width; - var designHeight = this._originalDesignResolutionSize.height; - this.setDesignResolutionSize(designWidth, designHeight, this._resolutionPolicy); + if (this._resolutionPolicy) { + var designWidth = this._originalDesignResolutionSize.width; + var designHeight = this._originalDesignResolutionSize.height; + this.setDesignResolutionSize(designWidth, designHeight, this._resolutionPolicy); + } } }, @@ -342,7 +330,7 @@ cc.EGLView = cc.Class.extend(/** @lends cc.view# */{ var h = __BrowserGetter.availHeight(this._frame); var isLandscape = w >= h; - if (!this._orientationChanging || !cc.sys.isMobile || + if (!cc.sys.isMobile || (isLandscape && this._orientation & cc.ORIENTATION_LANDSCAPE) || (!isLandscape && this._orientation & cc.ORIENTATION_PORTRAIT)) { locFrameSize.width = w; @@ -577,17 +565,10 @@ cc.EGLView = cc.Class.extend(/** @lends cc.view# */{ this._frameSize.height = height; this._frame.style.width = width + "px"; this._frame.style.height = height + "px"; - //this.centerWindow(); this._resizeEvent(); cc.director.setProjection(cc.director.getProjection()); }, - /** - * Empty function - */ - centerWindow: function () { - }, - /** * Returns the visible area size of the view port. * @return {cc.Size} @@ -697,6 +678,7 @@ cc.EGLView = cc.Class.extend(/** @lends cc.view# */{ // Permit to re-detect the orientation of device. this._orientationChanging = true; + // If resizing, then frame size is already initialized, this logic should be improved if (!this._resizing) this._initFrameSize(); @@ -850,13 +832,13 @@ cc.EGLView = cc.Class.extend(/** @lends cc.view# */{ 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; + var scaleXFactor = 1 / this._scaleX; + var scaleYFactor = 1 / this._scaleY; return cc.rect( - (_scissorRect.x - this._viewPortRect.x) / scaleX, - (_scissorRect.y - this._viewPortRect.y) / scaleY, - _scissorRect.width / scaleX, - _scissorRect.height / scaleY + (_scissorRect.x - this._viewPortRect.x) * scaleXFactor, + (_scissorRect.y - this._viewPortRect.y) * scaleYFactor, + _scissorRect.width * scaleXFactor, + _scissorRect.height * scaleYFactor ); }, @@ -1106,7 +1088,7 @@ cc.ContentStrategy = cc.Class.extend(/** @lends cc.ContentStrategy# */{ this._setupContainer(view, view._frameSize.width, view._frameSize.height); // Setup container's margin and padding if (view._isRotated) { - containerStyle.marginLeft = frameH + 'px'; + containerStyle.margin = '0 0 0 ' + frameH + 'px'; } else { containerStyle.margin = '0px'; @@ -1136,7 +1118,7 @@ cc.ContentStrategy = cc.Class.extend(/** @lends cc.ContentStrategy# */{ this._setupContainer(view, containerW, containerH); // Setup container's margin and padding if (view._isRotated) { - containerStyle.marginLeft = frameH + 'px'; + containerStyle.margin = '0 0 0 ' + frameH + 'px'; } else { containerStyle.margin = '0px'; From ec6048d1db25cc088ac5870d62bbba140fbfe8a7 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Thu, 23 Mar 2017 16:25:15 +0800 Subject: [PATCH 140/206] Fix renderer canvas clear color issue --- cocos2d/core/renderer/RendererCanvas.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/cocos2d/core/renderer/RendererCanvas.js b/cocos2d/core/renderer/RendererCanvas.js index 65d2a8835c..57e569cd81 100644 --- a/cocos2d/core/renderer/RendererCanvas.js +++ b/cocos2d/core/renderer/RendererCanvas.js @@ -163,9 +163,9 @@ cc.rendererCanvas = { ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.clearRect(0, 0, viewport.width, viewport.height); - if (this._clearColor.r !== 0 || - this._clearColor.g !== 0 || - this._clearColor.b !== 0) { + if (this._clearColor.r !== 255 || + this._clearColor.g !== 255 || + this._clearColor.b !== 255) { wrapper.setFillStyle(this._clearFillStyle); wrapper.setGlobalAlpha(this._clearColor.a); ctx.fillRect(0, 0, viewport.width, viewport.height); From 3131889269ed6ade0550df159094299b5d039fbf Mon Sep 17 00:00:00 2001 From: pandamicro Date: Thu, 23 Mar 2017 16:26:22 +0800 Subject: [PATCH 141/206] Refactor Editbox to have better user experience (special when orientation set) --- extensions/editbox/CCEditBox.js | 322 ++++++++++++++++---------------- 1 file changed, 163 insertions(+), 159 deletions(-) diff --git a/extensions/editbox/CCEditBox.js b/extensions/editbox/CCEditBox.js index 758f04934f..3f271550f5 100644 --- a/extensions/editbox/CCEditBox.js +++ b/extensions/editbox/CCEditBox.js @@ -186,7 +186,7 @@ cc.EditBoxDelegate = cc.Class.extend({ * You can use this widget to gather small amounts of text from the user.

* * @class - * @extends cc.ControlButton + * @extends cc.Node * * @property {String} string - Content string of edit box * @property {String} maxLength - Max length of the content string @@ -230,14 +230,12 @@ cc.EditBox = cc.Node.extend({ ctor: function (size, normal9SpriteBg) { cc.Node.prototype.ctor.call(this); - this.setAnchorPoint(cc.p(0.5, 0.5)); + this._anchorPoint = cc.p(0.5, 0.5); this._textColor = cc.color.WHITE; this._placeholderColor = cc.color.GRAY; - cc.Node.prototype.setContentSize.call(this, size); this._renderCmd._createLabels(); this.createDomElementIfNeeded(); - this.initWithSizeAndBackgroundSprite(size, normal9SpriteBg); cc.eventManager.addListener({ @@ -274,7 +272,7 @@ cc.EditBox = cc.Node.extend({ createDomElementIfNeeded: function () { if (!this._renderCmd._edTxt) { - this._renderCmd.createNativeControl(); + this._renderCmd._createDomTextArea(); } }, @@ -316,7 +314,7 @@ cc.EditBox = cc.Node.extend({ cleanup: function () { this._super(); - this._renderCmd._removeDomInputControl(); + this._renderCmd._removeDomFromGameContainer(); }, _onTouchBegan: function (touch) { @@ -327,13 +325,13 @@ cc.EditBox = cc.Node.extend({ return true; } else { - this._renderCmd.hidden(); + this._renderCmd._endEditing(); return false; } }, _onTouchEnded: function () { - this._renderCmd.show(); + this._renderCmd._beginEditing(); }, _updateBackgroundSpriteSize: function (width, height) { @@ -528,7 +526,6 @@ cc.EditBox = cc.Node.extend({ this._updateBackgroundSpriteSize(size.width, size.height); } - this.x = 0; this.y = 0; return true; @@ -574,6 +571,7 @@ cc.EditBox = cc.Node.extend({ */ setReturnType: function (returnType) { this._keyboardReturnType = returnType; + this._renderCmd._updateDomInputType(); }, /** @@ -673,31 +671,27 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp var TIMER_NAME = 400; var LEFT_PADDING = 2; - function scrollWindowUp(editBox) { - // if (cc.sys.os === cc.sys.OS_IOS && cc.sys.osMainVersion === 9) { - var worldPos = editBox.convertToWorldSpace(cc.p(0, 0)); + function adjustEditBoxPosition (editBox) { + 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) { + if(windowWidth > windowHeight) { factor = 0.7; } - setTimeout(function () { - if (window.scrollY < SCROLLY && worldPos.y < windowHeight * factor) { + 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); + window.scrollTo(scrollOffset, scrollOffset); } }, TIMER_NAME); - // } } - function capitalize(string) { - return string.replace(/(?:^|\s)\S/g, function (a) { - return a.toUpperCase(); - }); - } + var capitalize = function(string) { + return string.replace(/(?:^|\s)\S/g, function(a) { return a.toUpperCase(); }); + }; function capitalizeFirstLetter(string) { return string.charAt(0).toUpperCase() + string.slice(1); @@ -740,21 +734,10 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp proto.updateVisibility = function () { if (!this._edTxt) return; - var node = this._node; - var editBox = this._edTxt; - if (node.visible) { - editBox.style.visibility = 'visible'; - cc.game.container.appendChild(editBox); + if (this._node.visible) { + this._edTxt.style.visibility = 'visible'; } else { - editBox.style.visibility = 'hidden'; - var hasChild = false; - if ('contains' in cc.game.container) { - hasChild = cc.game.container.contains(editBox); - } else { - hasChild = cc.game.container.compareDocumentPosition(editBox) % 16; - } - if (hasChild) - cc.game.container.removeChild(editBox); + this._edTxt.style.visibility = 'hidden'; } }; @@ -765,12 +748,77 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp } else { this._createLabels(); this._edTxt.style.display = 'none'; - this._updateLabelString(); + this._showLabels(); } }; + // Called before editbox focus to register cc.view status + proto._beginEditingOnMobile = function (editBox) { + this.__orientationChanged = function () { + adjustEditBoxPosition(editBox); + }; + + window.addEventListener('orientationchange', this.__orientationChanged); + + if (cc.view.isAutoFullScreenEnabled()) { + this.__fullscreen = true; + cc.view.enableAutoFullScreen(false); + cc.screen.exitFullScreen(); + } else { + this.__fullscreen = false; + } + this.__autoResize = cc.view.__resizeWithBrowserSize; + cc.view.resizeWithBrowserSize(false); + }; + // Called after keyboard disappeared to readapte the game view + proto._endEditingOnMobile = function () { + if (this.__rotateScreen) { + var containerStyle = cc.game.container.style; + containerStyle['-webkit-transform'] = 'rotate(90deg)'; + containerStyle.transform = 'rotate(90deg)'; + + var view = cc.view; + var width = view._originalDesignResolutionSize.width; + var height = view._originalDesignResolutionSize.height; + if (width > 0) { + view.setDesignResolutionSize(width, height, view._resolutionPolicy); + } + this.__rotateScreen = false; + } + + window.removeEventListener('orientationchange', this.__orientationChanged); + + window.scrollTo(0, 0); + if (this.__fullscreen) { + cc.view.enableAutoFullScreen(true); + } + if (this.__autoResize) { + cc.view.resizeWithBrowserSize(true); + } + }; + // Called after editbox focus to readapte the game view + proto._onFocusOnMobile = function (editBox) { + if (cc.view._isRotated) { + var containerStyle = cc.game.container.style; + containerStyle['-webkit-transform'] = 'rotate(0deg)'; + containerStyle.transform = 'rotate(0deg)'; + containerStyle.margin = '0px'; + // cc.view._isRotated = false; + // var policy = cc.view.getResolutionPolicy(); + // policy.apply(cc.view, cc.view.getDesignResolutionSize()); + // cc.view._isRotated = true; + //use window scrollTo to adjust the input area + window.scrollTo(35, 35); + this.__rotateScreen = true; + } else { + this.__rotateScreen = false; + } + adjustEditBoxPosition(editBox); + }; + + proto._createDomInput = function () { - this._removeDomInputControl(); + this._removeDomFromGameContainer(); var thisPointer = this; var tmpEdTxt = this._edTxt = document.createElement('input'); tmpEdTxt.type = 'text'; @@ -803,7 +851,7 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp if (editBox._delegate && editBox._delegate.editBoxTextChanged) { if (editBox._text.toLowerCase() !== this.value.toLowerCase()) { editBox._text = this.value; - thisPointer._updateEditBoxContentStyle(); + thisPointer._updateDomTextCases(); editBox._delegate.editBoxTextChanged(editBox, editBox._text); } } @@ -820,8 +868,9 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp } editBox._text = this.value; - thisPointer._updateEditBoxContentStyle(); - thisPointer.hidden(); + thisPointer._updateDomTextCases(); + + thisPointer._endEditing(); if (editBox._delegate && editBox._delegate.editBoxEditingReturn) { editBox._delegate.editBoxEditingReturn(editBox); } @@ -835,17 +884,9 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp this.style.color = cc.colorToHex(editBox._textColor); thisPointer._hiddenLabels(); - if (cc.view.isAutoFullScreenEnabled()) { - thisPointer.__fullscreen = true; - cc.view.enableAutoFullScreen(false); - cc.screen.exitFullScreen(); - } else { - thisPointer.__fullscreen = false; + if (cc.sys.isMobile) { + thisPointer._onFocusOnMobile(editBox); } - this.__autoResize = cc.view.__resizeWithBrowserSize; - cc.view.resizeWithBrowserSize(false); - - scrollWindowUp(editBox); if (editBox._delegate && editBox._delegate.editBoxEditingDidBegan) { editBox._delegate.editBoxEditingDidBegan(editBox); @@ -854,14 +895,8 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp tmpEdTxt.addEventListener('blur', function () { var editBox = thisPointer._editBox; editBox._text = this.value; - thisPointer._updateEditBoxContentStyle(); - if (thisPointer.__fullscreen) { - cc.view.enableAutoFullScreen(true); - } - if (this.__autoResize) { - cc.view.resizeWithBrowserSize(true); - } - window.scrollY = 0; + thisPointer._updateDomTextCases(); + if (editBox._delegate && editBox._delegate.editBoxEditingDidEnded) { editBox._delegate.editBoxEditingDidEnded(editBox); } @@ -870,13 +905,15 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp this.style.fontSize = editBox._placeholderFontSize + 'px'; this.style.color = cc.colorToHex(editBox._placeholderColor); } - thisPointer.hidden(); + thisPointer._endEditing(); }); + + this._addDomToGameContainer(); return tmpEdTxt; }; proto._createDomTextArea = function () { - this._removeDomInputControl(); + this._removeDomFromGameContainer(); var thisPointer = this; var tmpEdTxt = this._edTxt = document.createElement('textarea'); tmpEdTxt.type = 'text'; @@ -908,7 +945,7 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp if (editBox._delegate && editBox._delegate.editBoxTextChanged) { if (editBox._text.toLowerCase() !== this.value.toLowerCase()) { editBox._text = this.value; - thisPointer._updateEditBoxContentStyle(); + thisPointer._updateDomTextCases(); editBox._delegate.editBoxTextChanged(editBox, editBox._text); } } @@ -920,17 +957,10 @@ 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()) { - thisPointer.__fullscreen = true; - cc.view.enableAutoFullScreen(false); - cc.screen.exitFullScreen(); - } else { - thisPointer.__fullscreen = false; - } - this.__autoResize = cc.view.__resizeWithBrowserSize; - cc.view.resizeWithBrowserSize(false); - scrollWindowUp(editBox); + if (cc.sys.isMobile) { + thisPointer._onFocusOnMobile(editBox); + } if (editBox._delegate && editBox._delegate.editBoxEditingDidBegan) { editBox._delegate.editBoxEditingDidBegan(editBox); @@ -951,14 +981,7 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp tmpEdTxt.addEventListener('blur', function () { var editBox = thisPointer._editBox; editBox._text = this.value; - thisPointer._updateEditBoxContentStyle(); - window.scrollY = 0; - if (thisPointer.__fullscreen) { - cc.view.enableAutoFullScreen(true); - } - if (this.__autoResize) { - cc.view.resizeWithBrowserSize(true); - } + thisPointer._updateDomTextCases(); if (editBox._delegate && editBox._delegate.editBoxEditingDidEnded) { editBox._delegate.editBoxEditingDidEnded(editBox); @@ -969,9 +992,10 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp this.style.color = cc.colorToHex(editBox._placeholderColor); } - thisPointer.hidden(); + thisPointer._endEditing(); }); + this._addDomToGameContainer(); return tmpEdTxt; }; @@ -979,7 +1003,6 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp var editBoxSize = this._editBox.getContentSize(); 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); } @@ -1043,7 +1066,7 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp } }; - proto._updateEditBoxContentStyle = function () { + proto._updateDomTextCases = function () { var inputFlag = this._editBox._editBoxInputFlag; if (inputFlag === cc.EDITBOX_INPUT_FLAG_INITIAL_CAPS_ALL_CHARACTERS) { this._editBox._text = this._editBox._text.toUpperCase(); @@ -1056,14 +1079,7 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp } }; - proto._updateLabelString = function () { - this._updateInputType(); - - if (this._textLabel) { - this._textLabel.setVisible(true); - this._textLabel.setString(this._editBox._text); - } - + proto._updateLabelStringStyle = function () { if (this._edTxt.type === 'password') { var passwordString = ''; var len = this._editBox._text.length; @@ -1074,7 +1090,7 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp this._textLabel.setString(passwordString); } } else { - this._updateEditBoxContentStyle(); + this._updateDomTextCases(); if (this._textLabel) { this._textLabel.setString(this._editBox._text); } @@ -1090,25 +1106,42 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp } } else { - this._updateLabelString(); + if (this._textLabel) { + this._textLabel.setVisible(true); + this._textLabel.setString(this._editBox._text); + } } + this._updateLabelStringStyle(); }; - proto.show = function () { + proto._beginEditing = function () { if (!this._editBox._alwaysOnTop) { if (this._edTxt.style.display === 'none') { this._edTxt.style.display = ''; this._edTxt.focus(); } } - this._hiddenLabels(); + + if (cc.sys.isMobile && !this._editingMode) { + // Pre adaptation and + this._beginEditingOnMobile(this._editBox); + } + this._editingMode = true; }; - proto.hidden = function () { + proto._endEditing = function () { if (!this._editBox._alwaysOnTop) { this._edTxt.style.display = 'none'; } this._showLabels(); + if (cc.sys.isMobile && this._editingMode) { + var self = this; + // Delay end editing adaptation to ensure virtual keyboard is disapeared + setTimeout(function () { + self._endEditingOnMobile(); + }, TIMER_NAME); + } + this._editingMode = false; }; proto._setFont = function (fontStyle) { @@ -1165,11 +1198,7 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp this._placeholderLabel.setColor(color); }; - proto._updateInputType = function () { - if (this._editBox._keyboardReturnType === cc.KEYBOARD_RETURNTYPE_SEARCH) { - this._edTxt.type = 'search'; - } - + proto._updateDomInputType = function () { var inputMode = this._editBox._editBoxInputMode; if (inputMode === cc.EDITBOX_INPUT_MODE_EMAILADDR) { this._edTxt.type = 'email'; @@ -1183,8 +1212,11 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp this._edTxt.type = 'url'; } else { this._edTxt.type = 'text'; - } + if (this._editBox._keyboardReturnType === cc.KEYBOARD_RETURNTYPE_SEARCH) { + this._edTxt.type = 'search'; + } + } if (this._editBox._editBoxInputFlag === cc.EDITBOX_INPUT_FLAG_PASSWORD) { this._edTxt.type = 'password'; @@ -1194,7 +1226,7 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp proto.setInputFlag = function (inputFlag) { if (!this._edTxt) return; - this._updateInputType(); + this._updateDomInputType(); this._edTxt.style.textTransform = 'none'; @@ -1204,20 +1236,18 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp else if (inputFlag === cc.EDITBOX_INPUT_FLAG_INITIAL_CAPS_WORD) { this._edTxt.style.textTransform = 'capitalize'; } - this._updateLabelString(); + this._updateLabelStringStyle(); }; proto.setInputMode = function (inputMode) { - this._removeDomInputControl(); if (inputMode === cc.EDITBOX_INPUT_MODE_ANY) { this._createDomTextArea(); } else { this._createDomInput(); } - this._addDomInputControl(); - this._updateInputType(); + this._updateDomInputType(); var contentSize = this._node.getContentSize(); this.updateSize(contentSize.width, contentSize.height); }; @@ -1232,11 +1262,15 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp if (this._placeholderLabel) { this._placeholderLabel.setString(this._editBox._placeholderText); this._placeholderLabel.setColor(this._editBox._placeholderColor); - this._placeholderLabel.setVisible(true); } - - if (this._textLabel) { - this._textLabel.setVisible(false); + if (!this._editingMode) { + if (this._placeholderLabel) { + this._placeholderLabel.setVisible(true); + } + + if (this._textLabel) { + this._textLabel.setVisible(false); + } } } else { @@ -1244,11 +1278,16 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp if (this._textLabel) { this._textLabel.setColor(this._editBox._textColor); } - if (this._placeholderLabel) { - this._placeholderLabel.setVisible(false); + if (!this._editingMode) { + if (this._placeholderLabel) { + this._placeholderLabel.setVisible(false); + } + if (this._textLabel) { + this._textLabel.setVisible(true); + } } - this._updateLabelString(); + this._updateLabelStringStyle(); } } }; @@ -1277,16 +1316,11 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp this._updateLabelPosition(cc.size(newWidth, newHeight)); }; - proto.createNativeControl = function () { - this._createDomTextArea(); - this._addDomInputControl(); - }; - - proto._addDomInputControl = function () { + proto._addDomToGameContainer = function () { cc.game.container.appendChild(this._edTxt); }; - proto._removeDomInputControl = function () { + proto._removeDomFromGameContainer = function () { var editBox = this._edTxt; if (editBox) { var hasChild = false; @@ -1309,6 +1343,12 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp this._edFontName = 'Arial'; this._textLabel = null; this._placeholderLabel = null; + this._editingMode = false; + + this.__fullscreen = false; + this.__autoResize = false; + this.__rotateScreen = false; + this.__orientationChanged = null; }; //define the canvas render command @@ -1319,43 +1359,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) { - var pd = Object.getOwnPropertyDescriptor(obj, name); - if (pd) { - return pd; - } - var p = Object.getPrototypeOf(obj); - if (p) { - return _getPropertyDescriptor(p, name); - } - else { - return null; - } - } - - function _copyprop(name, source, target) { - var pd = _getPropertyDescriptor(source, name); - Object.defineProperty(target, name, pd); - } - - var _mixin = function (obj) { - obj = obj || {}; - for (var i = 1, length = arguments.length; i < length; i++) { - var source = arguments[i]; - if (source) { - if (typeof source !== 'object') { - cc.error('cc.js.mixin: arguments must be type object:', source); - continue; - } - for (var name in source) { - _copyprop(name, source, obj); - } - } - } - return obj; - }; - - _mixin(canvasRenderCmdProto, proto); + cc.inject(proto, canvasRenderCmdProto); canvasRenderCmdProto.constructor = cc.EditBox.CanvasRenderCmd; canvasRenderCmdProto.transform = function (parentCmd, recursive) { @@ -1371,7 +1375,7 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp }; var webGLRenderCmdProto = cc.EditBox.WebGLRenderCmd.prototype = Object.create(cc.Node.WebGLRenderCmd.prototype); - _mixin(webGLRenderCmdProto, proto); + cc.inject(proto, webGLRenderCmdProto); webGLRenderCmdProto.constructor = cc.EditBox.WebGLRenderCmd; webGLRenderCmdProto.transform = function (parentCmd, recursive) { From b41f830f98d36de9f130300c9543040280202765 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Tue, 28 Mar 2017 11:06:59 +0800 Subject: [PATCH 142/206] Fix editbox text comparison 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 3f271550f5..5fa8044506 100644 --- a/extensions/editbox/CCEditBox.js +++ b/extensions/editbox/CCEditBox.js @@ -849,7 +849,7 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp } if (editBox._delegate && editBox._delegate.editBoxTextChanged) { - if (editBox._text.toLowerCase() !== this.value.toLowerCase()) { + if (editBox._text !== this.value) { editBox._text = this.value; thisPointer._updateDomTextCases(); editBox._delegate.editBoxTextChanged(editBox, editBox._text); From dd4df1ca88fdc43e5e9ed563c8ef42f12610656d Mon Sep 17 00:00:00 2001 From: pandamicro Date: Tue, 28 Mar 2017 11:07:09 +0800 Subject: [PATCH 143/206] Fix API doc for RenderTexture.clear --- cocos2d/render-texture/CCRenderTexture.js | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/cocos2d/render-texture/CCRenderTexture.js b/cocos2d/render-texture/CCRenderTexture.js index 97bd77700a..050672a66f 100644 --- a/cocos2d/render-texture/CCRenderTexture.js +++ b/cocos2d/render-texture/CCRenderTexture.js @@ -235,10 +235,10 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{ /** * clears the texture with a color - * @param {Number|cc.Rect} r red 0-1 - * @param {Number} g green 0-1 - * @param {Number} b blue 0-1 - * @param {Number} a alpha 0-1 + * @param {Number|cc.Rect} r red 0-255 + * @param {Number} g green 0-255 + * @param {Number} b blue 0-255 + * @param {Number} a alpha 0-255 */ clear: function (r, g, b, a) { this.beginWithClear(r, g, b, a); From 4013fa7231e0bf2ed1dfa1ada343746026615a95 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Tue, 28 Mar 2017 11:07:17 +0800 Subject: [PATCH 144/206] Fix draw node onEnter/onExit issue --- cocos2d/shape-nodes/CCDrawNode.js | 2 ++ 1 file changed, 2 insertions(+) diff --git a/cocos2d/shape-nodes/CCDrawNode.js b/cocos2d/shape-nodes/CCDrawNode.js index d0843ec6b6..48caafa13f 100644 --- a/cocos2d/shape-nodes/CCDrawNode.js +++ b/cocos2d/shape-nodes/CCDrawNode.js @@ -530,6 +530,7 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () { }, onEnter: function () { + cc.Node.prototype.onEnter.call(this); if (this._occupiedSize < this._bufferCapacity) { this._ensureCapacity(this._bufferCapacity); } @@ -539,6 +540,7 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () { if (!this.manualRelease) { this.release(); } + cc.Node.prototype.onExit.call(this); }, release: function () { From 6e912153cff254a226f2f826ef90ff40887cdcd2 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Fri, 31 Mar 2017 13:59:07 +0800 Subject: [PATCH 145/206] Improve adaptation logic when iframe wrapped the page on iOS --- CCBoot.js | 2 +- cocos2d/core/platform/CCEGLView.js | 18 ++++++++++-------- 2 files changed, 11 insertions(+), 9 deletions(-) diff --git a/CCBoot.js b/CCBoot.js index f1aca8bcf2..a366001d74 100644 --- a/CCBoot.js +++ b/CCBoot.js @@ -1758,7 +1758,7 @@ var _initSys = function () { sys.browserVersion = ""; /* Determine the browser version number */ (function(){ - var versionReg1 = /(mqqbrowser|micromessenger|sogou|qzone|liebao|maxthon|baidu)(mobile)?(browser)?\/?([\d.]+)/i; + var versionReg1 = /(mqqbrowser|micromessenger|sogou|qzone|liebao|maxthon|mxbrowser|baidu)(mobile)?(browser)?\/?([\d.]+)/i; var versionReg2 = /(msie |rv:|firefox|chrome|ucbrowser|qq|oupeng|opera|opr|safari|miui)(mobile)?(browser)?\/?([\d.]+)/i; var tmp = ua.match(versionReg1); if(!tmp) tmp = ua.match(versionReg2); diff --git a/cocos2d/core/platform/CCEGLView.js b/cocos2d/core/platform/CCEGLView.js index 68feb552e2..6093dc0b04 100755 --- a/cocos2d/core/platform/CCEGLView.js +++ b/cocos2d/core/platform/CCEGLView.js @@ -194,6 +194,9 @@ cc.EGLView = cc.Class.extend(/** @lends cc.view# */{ } else { view = cc.view; } + if (view._orientationChanging) { + return; + } // Check frame size changed or not var prevFrameW = view._frameSize.width, prevFrameH = view._frameSize.height, prevRotated = view._isRotated; @@ -229,7 +232,13 @@ cc.EGLView = cc.Class.extend(/** @lends cc.view# */{ _orientationChange: function () { cc.view._orientationChanging = true; - cc.view._resizeEvent(); + if (cc.sys.isMobile) { + cc.game.container.style.display = "none"; + } + setTimeout(function () { + cc.view._orientationChanging = false; + cc.view._resizeEvent(); + }, 300); }, /** @@ -348,11 +357,6 @@ cc.EGLView = cc.Class.extend(/** @lends cc.view# */{ cc.container.style.transformOrigin = '0px 0px 0px'; this._isRotated = true; } - if (this._orientationChanging) { - setTimeout(function () { - cc.view._orientationChanging = false; - }, 1000); - } }, // hack @@ -676,8 +680,6 @@ cc.EGLView = cc.Class.extend(/** @lends cc.view# */{ if (cc.sys.isMobile) this._adjustViewportMeta(); - // Permit to re-detect the orientation of device. - this._orientationChanging = true; // If resizing, then frame size is already initialized, this logic should be improved if (!this._resizing) this._initFrameSize(); From c7e689f0b4bcb6d31a8751e1465f3869dff24cb0 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Fri, 31 Mar 2017 15:59:48 +0800 Subject: [PATCH 146/206] Update engine version --- cocos2d/core/platform/CCConfig.js | 2 +- tools/build.xml | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/cocos2d/core/platform/CCConfig.js b/cocos2d/core/platform/CCConfig.js index 920ef69528..4fb22921f8 100644 --- a/cocos2d/core/platform/CCConfig.js +++ b/cocos2d/core/platform/CCConfig.js @@ -31,7 +31,7 @@ * @type {String} * @name cc.ENGINE_VERSION */ -window["CocosEngine"] = cc.ENGINE_VERSION = "Cocos2d-JS v3.14"; +window["CocosEngine"] = cc.ENGINE_VERSION = "Cocos2d-JS v3.15"; /** *

diff --git a/tools/build.xml b/tools/build.xml index d59cb38233..519f9867e9 100644 --- a/tools/build.xml +++ b/tools/build.xml @@ -5,9 +5,9 @@ classpath="./compiler/compiler.jar"/> + sourceMapOutputFile="./../lib/cocos2d-js-v3.15-sourcemap" sourceMapFormat="V3"> @@ -306,9 +306,9 @@ + sourceMapOutputFile="./../lib/cocos2d-js-v3.15-core-sourcemap" sourceMapFormat="V3"> From f8079214f1f052cf3eb548522dcc62b774fa8f39 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Wed, 12 Apr 2017 11:08:17 +0800 Subject: [PATCH 147/206] Fix dirty flags not send down to invisible child nodes issue --- cocos2d/clipping-nodes/CCClippingNode.js | 3 --- cocos2d/core/base-nodes/CCNode.js | 10 +++++++--- .../core/base-nodes/CCNodeCanvasRenderCmd.js | 16 +++++++++++++++ cocos2d/core/layers/CCLayer.js | 20 +++++++++++++------ cocos2d/particle/CCParticleBatchNode.js | 9 ++++++--- cocos2d/render-texture/CCRenderTexture.js | 10 +++++++--- .../ccui/base-classes/CCProtectedNode.js | 10 +++++++--- extensions/ccui/layouts/UILayout.js | 10 +++++++--- .../uiwidgets/scroll-widget/UIScrollView.js | 10 +++++++--- extensions/cocostudio/armature/CCArmature.js | 10 +++++++--- .../cocostudio/timeline/CCSkeletonNode.js | 8 ++++++-- extensions/gui/scrollview/CCScrollView.js | 8 ++++++-- 12 files changed, 90 insertions(+), 34 deletions(-) diff --git a/cocos2d/clipping-nodes/CCClippingNode.js b/cocos2d/clipping-nodes/CCClippingNode.js index c7a1921b27..7214ea13e7 100644 --- a/cocos2d/clipping-nodes/CCClippingNode.js +++ b/cocos2d/clipping-nodes/CCClippingNode.js @@ -128,9 +128,6 @@ cc.ClippingNode = cc.Node.extend(/** @lends cc.ClippingNode# */{ }, visit: function (parent) { - if (!this._visible) - return; - this._renderCmd.clippingVisit(parent && parent._renderCmd); }, diff --git a/cocos2d/core/base-nodes/CCNode.js b/cocos2d/core/base-nodes/CCNode.js index 723b27fe5f..98d5ccc828 100644 --- a/cocos2d/core/base-nodes/CCNode.js +++ b/cocos2d/core/base-nodes/CCNode.js @@ -2102,12 +2102,16 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{ * @param {cc.Node} parent */ visit: function (parent) { + var cmd = this._renderCmd, parentCmd = parent ? parent._renderCmd : null; + // quick return if not visible - if (!this._visible) + if (!this._visible) { + cmd._propagateFlagsDown(parentCmd); return; + } - var renderer = cc.renderer, cmd = this._renderCmd; - cmd.visit(parent && parent._renderCmd); + var renderer = cc.renderer; + cmd.visit(parentCmd); var i, children = this._children, len = children.length, child; if (len > 0) { diff --git a/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js b/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js index 1cc0bef5f6..6b4d170ce1 100644 --- a/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js +++ b/cocos2d/core/base-nodes/CCNodeCanvasRenderCmd.js @@ -442,6 +442,22 @@ cc.Node.RenderCmd.prototype = { _updateColor: function () { }, + _propagateFlagsDown: function (parentCmd) { + var locFlag = this._dirtyFlag; + var parentNode = parentCmd ? parentCmd._node : null; + + if(parentNode && parentNode._cascadeColorEnabled && (parentCmd._dirtyFlag & dirtyFlags.colorDirty)) + locFlag |= dirtyFlags.colorDirty; + + if(parentNode && parentNode._cascadeOpacityEnabled && (parentCmd._dirtyFlag & dirtyFlags.opacityDirty)) + locFlag |= dirtyFlags.opacityDirty; + + if(parentCmd && (parentCmd._dirtyFlag & dirtyFlags.transformDirty)) + locFlag |= dirtyFlags.transformDirty; + + this._dirtyFlag = locFlag; + }, + updateStatus: function () { var locFlag = this._dirtyFlag; var colorDirty = locFlag & dirtyFlags.colorDirty, diff --git a/cocos2d/core/layers/CCLayer.js b/cocos2d/core/layers/CCLayer.js index 626dcfc01a..c752ad814f 100644 --- a/cocos2d/core/layers/CCLayer.js +++ b/cocos2d/core/layers/CCLayer.js @@ -75,12 +75,16 @@ cc.Layer = cc.Node.extend(/** @lends cc.Layer# */{ }, visit: function (parent) { + var cmd = this._renderCmd, parentCmd = parent ? parent._renderCmd : null; + // quick return if not visible - if (!this._visible) + if (!this._visible) { + cmd._propagateFlagsDown(parentCmd); return; + } - var renderer = cc.renderer, cmd = this._renderCmd; - cmd.visit(parent && parent._renderCmd); + var renderer = cc.renderer; + cmd.visit(parentCmd); if (cmd._isBaked) { renderer.pushRenderCommand(cmd); @@ -248,12 +252,16 @@ cc.LayerColor = cc.Layer.extend(/** @lends cc.LayerColor# */{ }, visit: function (parent) { + var cmd = this._renderCmd, parentCmd = parent ? parent._renderCmd : null; + // quick return if not visible - if (!this._visible) + if (!this._visible) { + cmd._propagateFlagsDown(parentCmd); return; + } - var renderer = cc.renderer, cmd = this._renderCmd; - cmd.visit(parent && parent._renderCmd); + var renderer = cc.renderer; + cmd.visit(parentCmd); if (cmd._isBaked) { renderer.pushRenderCommand(cmd._bakeRenderCmd); diff --git a/cocos2d/particle/CCParticleBatchNode.js b/cocos2d/particle/CCParticleBatchNode.js index 38959df638..3952bcdbbb 100644 --- a/cocos2d/particle/CCParticleBatchNode.js +++ b/cocos2d/particle/CCParticleBatchNode.js @@ -148,12 +148,15 @@ cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{ }, visit: function (parent) { + var cmd = this._renderCmd, parentCmd = parent ? parent._renderCmd : null; + // quick return if not visible - if (!this._visible) + if (!this._visible) { + cmd._propagateFlagsDown(parentCmd); return; + } - var cmd = this._renderCmd; - cmd.visit(parent && parent._renderCmd); + cmd.visit(parentCmd); cc.renderer.pushRenderCommand(cmd); cmd._dirtyFlag = 0; }, diff --git a/cocos2d/render-texture/CCRenderTexture.js b/cocos2d/render-texture/CCRenderTexture.js index 050672a66f..5cc00ae45a 100644 --- a/cocos2d/render-texture/CCRenderTexture.js +++ b/cocos2d/render-texture/CCRenderTexture.js @@ -133,13 +133,17 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{ }, visit: function (parent) { + var cmd = this._renderCmd, parentCmd = parent ? parent._renderCmd : null; + // quick return if not visible - if (!this._visible) + if (!this._visible) { + cmd._propagateFlagsDown(parentCmd); return; + } - var renderer = cc.renderer, cmd = this._renderCmd; + var renderer = cc.renderer; - cmd.visit(parent && parent._renderCmd); + cmd.visit(parentCmd); renderer.pushRenderCommand(cmd); this.sprite.visit(this); cmd._dirtyFlag = 0; diff --git a/extensions/ccui/base-classes/CCProtectedNode.js b/extensions/ccui/base-classes/CCProtectedNode.js index 4a2bcd367a..1925572fa5 100644 --- a/extensions/ccui/base-classes/CCProtectedNode.js +++ b/extensions/ccui/base-classes/CCProtectedNode.js @@ -47,15 +47,19 @@ cc.ProtectedNode = cc.Node.extend(/** @lends cc.ProtectedNode# */{ }, visit: function (parent) { + var cmd = this._renderCmd, parentCmd = parent ? parent._renderCmd : null; + // quick return if not visible - if (!this._visible) + if (!this._visible) { + cmd._propagateFlagsDown(parentCmd); return; + } - var renderer = cc.renderer, cmd = this._renderCmd; + var renderer = cc.renderer; var i, children = this._children, len = children.length, child; var j, pChildren = this._protectedChildren, pLen = pChildren.length, pChild; - cmd.visit(parent && parent._renderCmd); + cmd.visit(parentCmd); var locGrid = this.grid; if (locGrid && locGrid._active) diff --git a/extensions/ccui/layouts/UILayout.js b/extensions/ccui/layouts/UILayout.js index 695f7e40f4..34361aa8a9 100644 --- a/extensions/ccui/layouts/UILayout.js +++ b/extensions/ccui/layouts/UILayout.js @@ -134,14 +134,18 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{ * @param {cc.Node} [parent] */ visit: function (parent) { - if (!this._visible) + var cmd = this._renderCmd, parentCmd = parent ? parent._renderCmd : null; + + // quick return if not visible + if (!this._visible) { + cmd._propagateFlagsDown(parentCmd); return; + } this._adaptRenderers(); this._doLayout(); - var renderer = cc.renderer, cmd = this._renderCmd; - var parentCmd = parent && parent._renderCmd; + var renderer = cc.renderer; cmd.visit(parentCmd); var stencilClipping = this._clippingEnabled && this._clippingType === ccui.Layout.CLIPPING_STENCIL; diff --git a/extensions/ccui/uiwidgets/scroll-widget/UIScrollView.js b/extensions/ccui/uiwidgets/scroll-widget/UIScrollView.js index cbdadaad21..79741c9525 100644 --- a/extensions/ccui/uiwidgets/scroll-widget/UIScrollView.js +++ b/extensions/ccui/uiwidgets/scroll-widget/UIScrollView.js @@ -124,14 +124,18 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{ }, visit: function (parent) { - if (!this._visible) + var cmd = this._renderCmd, parentCmd = parent ? parent._renderCmd : null; + + // quick return if not visible + if (!this._visible) { + cmd._propagateFlagsDown(parentCmd); return; + } this._adaptRenderers(); this._doLayout(); - var renderer = cc.renderer, cmd = this._renderCmd; - var parentCmd = parent && parent._renderCmd; + var renderer = cc.renderer; cmd.visit(parentCmd); renderer.pushRenderCommand(cmd); diff --git a/extensions/cocostudio/armature/CCArmature.js b/extensions/cocostudio/armature/CCArmature.js index 29de0934e5..3836c34afd 100644 --- a/extensions/cocostudio/armature/CCArmature.js +++ b/extensions/cocostudio/armature/CCArmature.js @@ -151,12 +151,16 @@ ccs.Armature = ccs.Node.extend(/** @lends ccs.Armature# */{ }, visit: function (parent) { + var cmd = this._renderCmd, parentCmd = parent ? parent._renderCmd : null; + // quick return if not visible - if (!this._visible) + if (!this._visible) { + cmd._propagateFlagsDown(parentCmd); return; + } - this._renderCmd.visit(parent && parent._renderCmd); - this._renderCmd._dirtyFlag = 0; + cmd.visit(parentCmd); + cmd._dirtyFlag = 0; }, addChild: function (child, localZOrder, tag) { diff --git a/extensions/cocostudio/timeline/CCSkeletonNode.js b/extensions/cocostudio/timeline/CCSkeletonNode.js index 28517649d1..2bd075f51e 100644 --- a/extensions/cocostudio/timeline/CCSkeletonNode.js +++ b/extensions/cocostudio/timeline/CCSkeletonNode.js @@ -145,10 +145,14 @@ ccs.SkeletonNode = (function () { }, _visit: function (parentCmd) { - if (!this._visible) - return; var cmd = this._renderCmd; parentCmd = parentCmd || cmd.getParentRenderCmd(); + + // quick return if not visible + if (!this._visible) { + cmd._propagateFlagsDown(parentCmd); + return; + } cmd._syncStatus(parentCmd); var i, node; diff --git a/extensions/gui/scrollview/CCScrollView.js b/extensions/gui/scrollview/CCScrollView.js index d29e6db0ac..bedba0ac04 100644 --- a/extensions/gui/scrollview/CCScrollView.js +++ b/extensions/gui/scrollview/CCScrollView.js @@ -166,12 +166,16 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{ }, visit: function (parent) { + var cmd = this._renderCmd, parentCmd = parent ? parent._renderCmd : null; + + // quick return if not visible if (!this._visible) { + cmd._propagateFlagsDown(parentCmd); return; } - var renderer = cc.renderer, cmd = this._renderCmd; - cmd.visit(parent && parent._renderCmd); + var renderer = cc.renderer; + cmd.visit(parentCmd); if (this._clippingToBounds) { renderer.pushRenderCommand(cmd.startCmd); From f336066bbccd2b3cd573dae27b23a9c04302c780 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Wed, 12 Apr 2017 11:08:52 +0800 Subject: [PATCH 148/206] Init cc.Color with default alpha value as 255 --- cocos2d/core/platform/CCTypes.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos2d/core/platform/CCTypes.js b/cocos2d/core/platform/CCTypes.js index 252061782d..e076fe2ae4 100644 --- a/cocos2d/core/platform/CCTypes.js +++ b/cocos2d/core/platform/CCTypes.js @@ -37,7 +37,7 @@ cc.Color = function (r, g, b, a) { r = r || 0; g = g || 0; b = b || 0; - a = a || 0; + a = typeof a === 'number' ? a : 255; this._val = ((r << 24) >>> 0) + (g << 16) + (b << 8) + a; }; From cb5f8273fe25a7bcd58377074bab8d0f3df84fea Mon Sep 17 00:00:00 2001 From: pandamicro Date: Wed, 12 Apr 2017 11:09:24 +0800 Subject: [PATCH 149/206] Fix LabelTTF reset dirty flag during updateStatus --- cocos2d/core/labelttf/CCLabelTTF.js | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/cocos2d/core/labelttf/CCLabelTTF.js b/cocos2d/core/labelttf/CCLabelTTF.js index 2342fc555c..ac988109b9 100644 --- a/cocos2d/core/labelttf/CCLabelTTF.js +++ b/cocos2d/core/labelttf/CCLabelTTF.js @@ -826,7 +826,11 @@ cc.LabelTTF = cc.Sprite.extend(/** @lends cc.LabelTTF# */{ _t._rectRotated = rotated || false; _t.setContentSize(untrimmedSize || rect); - _t.setVertexRect(rect); + var locRect = _t._rect; + locRect.x = rect.x; + locRect.y = rect.y; + locRect.width = rect.width; + locRect.height = rect.height; _t._renderCmd._setTextureCoords(rect, false); var relativeOffsetX = _t._unflippedOffsetPositionFromCenter.x, relativeOffsetY = _t._unflippedOffsetPositionFromCenter.y; @@ -834,7 +838,6 @@ cc.LabelTTF = cc.Sprite.extend(/** @lends cc.LabelTTF# */{ 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; }, From 245c22fdb497fd5c90eebde77b430eb3cbec61e2 Mon Sep 17 00:00:00 2001 From: jordanth Date: Thu, 20 Apr 2017 13:21:08 -0700 Subject: [PATCH 150/206] Wrap the created localCanvas element with the cc.$ class .addClass(...) is called on it a few lines later, which throws an error if localCanvas is a regular HTML element. --- CCBoot.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CCBoot.js b/CCBoot.js index a366001d74..deeba9da56 100644 --- a/CCBoot.js +++ b/CCBoot.js @@ -2669,7 +2669,7 @@ cc.game = /** @lends cc.game# */{ } width = width || element.clientWidth; height = height || element.clientHeight; - this.canvas = cc._canvas = localCanvas = document.createElement("CANVAS"); + this.canvas = cc._canvas = localCanvas = cc.$(document.createElement("CANVAS")); this.container = cc.container = localContainer = document.createElement("DIV"); element.appendChild(localContainer); } From 811ca72104bbd5ef860924510c997249c18b3848 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Tue, 9 May 2017 11:32:50 +0800 Subject: [PATCH 151/206] Use imagePool to reduce image memory usage in WebGL mode --- CCBoot.js | 55 ++++++++++++++----- .../labelttf/CCLabelTTFCanvasRenderCmd.js | 10 +++- cocos2d/core/platform/CCLoaders.js | 10 +++- cocos2d/core/textures/CCTexture2D.js | 4 +- cocos2d/core/textures/CCTextureCache.js | 9 +-- cocos2d/core/textures/TexturesWebGL.js | 11 ++-- 6 files changed, 67 insertions(+), 32 deletions(-) diff --git a/CCBoot.js b/CCBoot.js index a366001d74..cbd4628a78 100644 --- a/CCBoot.js +++ b/CCBoot.js @@ -583,6 +583,33 @@ cc.path = /** @lends cc.path# */{ * @see cc.loader */ +var imagePool = { + _pool: new Array(10), + _MAX: 10, + _smallImg: "data:image/gif;base64,R0lGODlhAQABAAAAACwAAAAAAQABAAA=", + + count: 0, + get: function () { + if (this.count > 0) { + this.count--; + var result = this._pool[this.count]; + this._pool[this.count] = null; + return result; + } + else { + return new Image(); + } + }, + put: function (img) { + var pool = this._pool; + if (img instanceof HTMLImageElement && this.count < this._MAX) { + img.src = this._smallImg; + pool[this.count] = img; + this.count++; + } + } +}; + /** * Singleton instance of cc.Loader. * @name cc.loader @@ -867,7 +894,7 @@ cc.loader = (function () { * @param {function} callback * @returns {Image} */ - loadImg: function (url, option, callback) { + loadImg: function (url, option, callback, img) { var opt = { isCrossOrigin: true }; @@ -876,30 +903,22 @@ cc.loader = (function () { else if (option !== undefined) callback = option; - var img = this.getRes(url); - if (img) { - callback && callback(null, img); - return img; - } - var queue = _queue[url]; if (queue) { queue.callbacks.push(callback); return queue.img; } - img = new Image(); + img = img || imagePool.get(); if (opt.isCrossOrigin && location.origin !== "file://") img.crossOrigin = "Anonymous"; + else + img.crossOrigin = null; var loadCallback = function () { this.removeEventListener('load', loadCallback, false); this.removeEventListener('error', errorCallback, false); - if (!_urlRegExp.test(url)) { - cc.loader.cache[url] = img; - } - var queue = _queue[url]; if (queue) { var callbacks = queue.callbacks; @@ -912,6 +931,10 @@ cc.loader = (function () { queue.img = null; delete _queue[url]; } + + if (cc._renderType === cc.game.RENDER_TYPE_WEBGL) { + imagePool.put(img); + } }; var self = this; @@ -919,10 +942,10 @@ cc.loader = (function () { this.removeEventListener('load', loadCallback, false); this.removeEventListener('error', errorCallback, false); - if (img.crossOrigin && img.crossOrigin.toLowerCase() === "anonymous") { + if (window.location.protocol !== 'https:' && img.crossOrigin && img.crossOrigin.toLowerCase() === "anonymous") { opt.isCrossOrigin = false; self.release(url); - cc.loader.loadImg(url, opt, callback); + cc.loader.loadImg(url, opt, callback, img); } else { var queue = _queue[url]; if (queue) { @@ -936,6 +959,10 @@ cc.loader = (function () { queue.img = null; delete _queue[url]; } + + if (cc._renderType === cc.game.RENDER_TYPE_WEBGL) { + imagePool.put(img); + } } }; diff --git a/cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js b/cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js index 51fb3888b4..d6d691265d 100644 --- a/cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js +++ b/cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js @@ -418,7 +418,10 @@ cc.LabelTTF._firsrEnglish = /^[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]/; if (node._string.length === 0) { locLabelCanvas.width = 1; locLabelCanvas.height = locContentSize.height || 1; - node._texture && node._texture.handleLoadedTexture(); + if (node._texture) { + node._texture._htmlElementObj = this._labelCanvas; + node._texture.handleLoadedTexture(); + } node.setTextureRect(cc.rect(0, 0, 1, locContentSize.height)); return true; } @@ -432,7 +435,10 @@ cc.LabelTTF._firsrEnglish = /^[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]/; if (flag) locContext.clearRect(0, 0, width, height); this._saveStatus(); this._drawTTFInCanvas(locContext); - node._texture && node._texture.handleLoadedTexture(); + if (node._texture) { + node._texture._htmlElementObj = this._labelCanvas; + node._texture.handleLoadedTexture(); + } node.setTextureRect(cc.rect(0, 0, width, height)); return true; }; diff --git a/cocos2d/core/platform/CCLoaders.js b/cocos2d/core/platform/CCLoaders.js index 69c8e9430f..9d91344a23 100644 --- a/cocos2d/core/platform/CCLoaders.js +++ b/cocos2d/core/platform/CCLoaders.js @@ -54,9 +54,13 @@ cc._imgLoader = { callback = function (err, img) { if (err) return cb(err); - cc.loader.cache[url] = img; - cc.textureCache.handleLoadedTexture(url); - cb(null, img); + + var tex = cc.textureCache.getTextureForKey(url) || new cc.Texture2D(); + tex.url = url; + tex.initWithElement(img); + tex.handleLoadedTexture(); + cc.textureCache.cacheImage(url, tex); + cb(null, tex); }; } cc.loader.loadImg(realUrl, callback); diff --git a/cocos2d/core/textures/CCTexture2D.js b/cocos2d/core/textures/CCTexture2D.js index cd0a9ff153..687a5e3929 100644 --- a/cocos2d/core/textures/CCTexture2D.js +++ b/cocos2d/core/textures/CCTexture2D.js @@ -192,9 +192,7 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () { var self = this; if (self._textureLoaded) return; if (!self._htmlElementObj) { - var img = cc.loader.getRes(self.url); - if (!img) return; - self.initWithElement(img); + return; } var locElement = self._htmlElementObj; diff --git a/cocos2d/core/textures/CCTextureCache.js b/cocos2d/core/textures/CCTextureCache.js index 2099565eb3..afd8af3e61 100644 --- a/cocos2d/core/textures/CCTextureCache.js +++ b/cocos2d/core/textures/CCTextureCache.js @@ -313,7 +313,7 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () { var _p = cc.textureCache; - _p.handleLoadedTexture = function (url) { + _p.handleLoadedTexture = function (url, img) { var locTexs = this._textures; //remove judge var tex = locTexs[url]; @@ -321,6 +321,7 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () { tex = locTexs[url] = new cc.Texture2D(); tex.url = url; } + tex.initWithElement(img); tex.handleLoadedTexture(); }; @@ -365,12 +366,12 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () { if (err) return cb && cb.call(target, err); + cc.textureCache.handleLoadedTexture(url, img); + var texResult = locTexs[url]; if (!cc.loader.cache[url]) { - cc.loader.cache[url] = img; + cc.loader.cache[url] = texResult; } - cc.textureCache.handleLoadedTexture(url); - var texResult = locTexs[url]; cb && cb.call(target, texResult); }); diff --git a/cocos2d/core/textures/TexturesWebGL.js b/cocos2d/core/textures/TexturesWebGL.js index bcec5bfb53..5d704e25df 100644 --- a/cocos2d/core/textures/TexturesWebGL.js +++ b/cocos2d/core/textures/TexturesWebGL.js @@ -457,11 +457,8 @@ cc._tmp.WebGLTexture2D = function () { // Not sure about this ! Some texture need to be updated even after loaded if (!cc.game._rendererInitialized) return; - if (!self._htmlElementObj) { - var img = cc.loader.getRes(self.url); - if (!img) return; - self.initWithElement(img); - } + if (!self._htmlElementObj) + return; if (!self._htmlElementObj.width || !self._htmlElementObj.height) return; @@ -498,6 +495,7 @@ cc._tmp.WebGLTexture2D = function () { self._hasPremultipliedAlpha = premultiplied; self._hasMipmaps = false; + self._htmlElementObj = null; //dispatch load event to listener. self.dispatchEvent("load"); @@ -854,7 +852,7 @@ cc._tmp.WebGLTextureAtlas = function () { cc._tmp.WebGLTextureCache = function () { var _p = cc.textureCache; - _p.handleLoadedTexture = function (url) { + _p.handleLoadedTexture = function (url, img) { var locTexs = this._textures, tex, ext; //remove judge(webgl) if (!cc.game._rendererInitialized) { @@ -865,6 +863,7 @@ cc._tmp.WebGLTextureCache = function () { tex = locTexs[url] = new cc.Texture2D(); tex.url = url; } + tex.initWithElement(img); ext = cc.path.extname(url); if (ext === ".png") { tex.handleLoadedTexture(true); From d4d9cdfd19ee00eec57025c5becb96563ef86efc Mon Sep 17 00:00:00 2001 From: pandamicro Date: Tue, 9 May 2017 11:54:55 +0800 Subject: [PATCH 152/206] Fix eventManager memory leak --- cocos2d/core/event-manager/CCEventListener.js | 76 ++++++++++--------- cocos2d/core/event-manager/CCEventManager.js | 6 +- 2 files changed, 42 insertions(+), 40 deletions(-) diff --git a/cocos2d/core/event-manager/CCEventListener.js b/cocos2d/core/event-manager/CCEventListener.js index 06e5bd4eee..c970c43fdf 100644 --- a/cocos2d/core/event-manager/CCEventListener.js +++ b/cocos2d/core/event-manager/CCEventListener.js @@ -277,15 +277,16 @@ cc.EventListener.CUSTOM = 8; cc._EventListenerCustom = cc.EventListener.extend({ _onCustomEvent: null, - ctor: function (listenerId, callback) { + ctor: function (listenerId, callback, target) { this._onCustomEvent = callback; - var selfPointer = this; - var listener = function (event) { - if (selfPointer._onCustomEvent !== null) - selfPointer._onCustomEvent(event); - }; + this._target = target; - cc.EventListener.prototype.ctor.call(this, cc.EventListener.CUSTOM, listenerId, listener); + cc.EventListener.prototype.ctor.call(this, cc.EventListener.CUSTOM, listenerId, this._callback); + }, + + _callback: function (event) { + if (this._onCustomEvent !== null) + this._onCustomEvent.call(this._target, event); }, checkAvailable: function () { @@ -308,31 +309,31 @@ cc._EventListenerMouse = cc.EventListener.extend({ onMouseScroll: null, ctor: function () { - var selfPointer = this; - var listener = function (event) { - var eventType = cc.EventMouse; - switch (event._eventType) { - case eventType.DOWN: - if (selfPointer.onMouseDown) - selfPointer.onMouseDown(event); - break; - case eventType.UP: - if (selfPointer.onMouseUp) - selfPointer.onMouseUp(event); - break; - case eventType.MOVE: - if (selfPointer.onMouseMove) - selfPointer.onMouseMove(event); - break; - case eventType.SCROLL: - if (selfPointer.onMouseScroll) - selfPointer.onMouseScroll(event); - break; - default: - break; - } - }; - cc.EventListener.prototype.ctor.call(this, cc.EventListener.MOUSE, cc._EventListenerMouse.LISTENER_ID, listener); + cc.EventListener.prototype.ctor.call(this, cc.EventListener.MOUSE, cc._EventListenerMouse.LISTENER_ID, this._callback); + }, + + _callback: function (event) { + var eventType = cc.EventMouse; + switch (event._eventType) { + case eventType.DOWN: + if (this.onMouseDown) + this.onMouseDown(event); + break; + case eventType.UP: + if (this.onMouseUp) + this.onMouseUp(event); + break; + case eventType.MOVE: + if (this.onMouseMove) + this.onMouseMove(event); + break; + case eventType.SCROLL: + if (this.onMouseScroll) + this.onMouseScroll(event); + break; + default: + break; + } }, clone: function () { @@ -501,11 +502,12 @@ cc._EventListenerFocus = cc.EventListener.extend({ }, onFocusChanged: null, ctor: function(){ - var listener = function(event){ - if(this.onFocusChanged) - this.onFocusChanged(event._widgetLoseFocus, event._widgetGetFocus); - }; - cc.EventListener.prototype.ctor.call(this, cc.EventListener.FOCUS, cc._EventListenerFocus.LISTENER_ID, listener); + cc.EventListener.prototype.ctor.call(this, cc.EventListener.FOCUS, cc._EventListenerFocus.LISTENER_ID, this._callback); + }, + _callback: function (event) { + if (this.onFocusChanged) { + this.onFocusChanged(event._widgetLoseFocus, event._widgetGetFocus); + } } }); diff --git a/cocos2d/core/event-manager/CCEventManager.js b/cocos2d/core/event-manager/CCEventManager.js index 890ba5bf7c..7f54f03939 100644 --- a/cocos2d/core/event-manager/CCEventManager.js +++ b/cocos2d/core/event-manager/CCEventManager.js @@ -258,8 +258,8 @@ cc.eventManager = /** @lends cc.eventManager# */{ if (!this._inDispatch) { listeners.clear(); - delete this._listenersMap[listenerID]; } + delete this._listenersMap[listenerID]; } var locToAddedListeners = this._toAddedListeners, listener; @@ -751,8 +751,8 @@ cc.eventManager = /** @lends cc.eventManager# */{ * @param {function} callback * @return {cc.EventListener} the generated event. Needed in order to remove the event from the dispatcher */ - addCustomListener: function (eventName, callback) { - var listener = new cc._EventListenerCustom(eventName, callback); + addCustomListener: function (eventName, callback, target) { + var listener = new cc._EventListenerCustom(eventName, callback, target); this.addListener(listener, 1); return listener; }, From f192b7d12737143dcef5edf8e73621435f78c289 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Tue, 9 May 2017 11:55:47 +0800 Subject: [PATCH 153/206] Listen to orientationChange event only on mobile --- cocos2d/core/platform/CCEGLView.js | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/cocos2d/core/platform/CCEGLView.js b/cocos2d/core/platform/CCEGLView.js index 6093dc0b04..448f1b2f1b 100755 --- a/cocos2d/core/platform/CCEGLView.js +++ b/cocos2d/core/platform/CCEGLView.js @@ -184,6 +184,10 @@ cc.EGLView = cc.Class.extend(/** @lends cc.view# */{ _t._rpFixedWidth = new cc.ResolutionPolicy(_strategyer.EQUAL_TO_FRAME, _strategy.FIXED_WIDTH); _t._targetDensityDPI = cc.DENSITYDPI_HIGH; + + if (sys.isMobile) { + window.addEventListener('orientationchange', this._orientationChange); + } }, // Resize helper functions @@ -276,14 +280,12 @@ cc.EGLView = cc.Class.extend(/** @lends cc.view# */{ if (!this.__resizeWithBrowserSize) { this.__resizeWithBrowserSize = true; window.addEventListener('resize', this._resizeEvent); - window.addEventListener('orientationchange', this._orientationChange); } } else { //disable if (this.__resizeWithBrowserSize) { this.__resizeWithBrowserSize = false; window.removeEventListener('resize', this._resizeEvent); - window.removeEventListener('orientationchange', this._orientationChange); } } }, From 0ff97d0972d2a24e6bb03b38f11627c89b28fcf1 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Tue, 9 May 2017 11:56:16 +0800 Subject: [PATCH 154/206] Fix texture cache.dumpCachedTextureInfo --- cocos2d/core/textures/CCTextureCache.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/cocos2d/core/textures/CCTextureCache.js b/cocos2d/core/textures/CCTextureCache.js index afd8af3e61..07442c8d3d 100644 --- a/cocos2d/core/textures/CCTextureCache.js +++ b/cocos2d/core/textures/CCTextureCache.js @@ -279,11 +279,11 @@ cc.textureCache = /** @lends cc.textureCache# */{ var selTexture = locTextures[key]; count++; if (selTexture.getHtmlElementObj() instanceof HTMLImageElement) - cc.log(cc._LogInfos.textureCache_dumpCachedTextureInfo, key, selTexture.getHtmlElementObj().src, selTexture.pixelsWidth, selTexture.pixelsHeight); + cc.log(cc._LogInfos.textureCache_dumpCachedTextureInfo, key, selTexture.getHtmlElementObj().src, selTexture.getPixelsWide(), selTexture.getPixelsHigh()); else { - cc.log(cc._LogInfos.textureCache_dumpCachedTextureInfo_2, key, selTexture.pixelsWidth, selTexture.pixelsHeight); + cc.log(cc._LogInfos.textureCache_dumpCachedTextureInfo_2, key, selTexture.getPixelsWide(), selTexture.getPixelsHigh()); } - totalBytes += selTexture.pixelsWidth * selTexture.pixelsHeight * 4; + totalBytes += selTexture.getPixelsWide() * selTexture.getPixelsHigh() * 4; } var locTextureColorsCache = this._textureColorsCache; From 7c9a8b5bfaa78cd2ecf5a1651b04cf4f2572fa61 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Wed, 10 May 2017 10:59:52 +0800 Subject: [PATCH 155/206] Improve image loader and fix issues --- CCBoot.js | 6 ++++++ cocos2d/core/platform/CCLoaders.js | 8 ++------ cocos2d/core/textures/CCTexture2D.js | 1 + cocos2d/core/textures/CCTextureCache.js | 8 ++------ cocos2d/core/textures/TexturesWebGL.js | 9 +++------ 5 files changed, 14 insertions(+), 18 deletions(-) diff --git a/CCBoot.js b/CCBoot.js index cbd4628a78..8ac4065c37 100644 --- a/CCBoot.js +++ b/CCBoot.js @@ -903,6 +903,12 @@ cc.loader = (function () { else if (option !== undefined) callback = option; + var texture = this.getRes(url); + if (texture) { + callback && callback(null, texture); + return null; + } + var queue = _queue[url]; if (queue) { queue.callbacks.push(callback); diff --git a/cocos2d/core/platform/CCLoaders.js b/cocos2d/core/platform/CCLoaders.js index 9d91344a23..5826fd215d 100644 --- a/cocos2d/core/platform/CCLoaders.js +++ b/cocos2d/core/platform/CCLoaders.js @@ -54,12 +54,8 @@ cc._imgLoader = { callback = function (err, img) { if (err) return cb(err); - - var tex = cc.textureCache.getTextureForKey(url) || new cc.Texture2D(); - tex.url = url; - tex.initWithElement(img); - tex.handleLoadedTexture(); - cc.textureCache.cacheImage(url, tex); + + var tex = cc.textureCache.handleLoadedTexture(url, img); cb(null, tex); }; } diff --git a/cocos2d/core/textures/CCTexture2D.js b/cocos2d/core/textures/CCTexture2D.js index 687a5e3929..b80aec1274 100644 --- a/cocos2d/core/textures/CCTexture2D.js +++ b/cocos2d/core/textures/CCTexture2D.js @@ -227,6 +227,7 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () { }, releaseTexture: function () { + this._htmlElementObj = null; cc.loader.release(this.url); }, diff --git a/cocos2d/core/textures/CCTextureCache.js b/cocos2d/core/textures/CCTextureCache.js index 07442c8d3d..5e59c2f83c 100644 --- a/cocos2d/core/textures/CCTextureCache.js +++ b/cocos2d/core/textures/CCTextureCache.js @@ -323,6 +323,7 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () { } tex.initWithElement(img); tex.handleLoadedTexture(); + return tex; }; /** @@ -366,12 +367,7 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () { if (err) return cb && cb.call(target, err); - cc.textureCache.handleLoadedTexture(url, img); - var texResult = locTexs[url]; - if (!cc.loader.cache[url]) { - cc.loader.cache[url] = texResult; - } - + var texResult = cc.textureCache.handleLoadedTexture(url, img); cb && cb.call(target, texResult); }); diff --git a/cocos2d/core/textures/TexturesWebGL.js b/cocos2d/core/textures/TexturesWebGL.js index 5d704e25df..58a2ced557 100644 --- a/cocos2d/core/textures/TexturesWebGL.js +++ b/cocos2d/core/textures/TexturesWebGL.js @@ -83,6 +83,7 @@ cc._tmp.WebGLTexture2D = function () { releaseTexture: function () { if (this._webTextureObj) cc._renderContext.deleteTexture(this._webTextureObj); + this._htmlElementObj = null; cc.loader.release(this.url); }, @@ -871,6 +872,7 @@ cc._tmp.WebGLTextureCache = function () { else { tex.handleLoadedTexture(); } + return tex; }; /** @@ -916,12 +918,7 @@ cc._tmp.WebGLTextureCache = function () { if (err) return cb && cb.call(target, err); - if (!cc.loader.cache[url]) { - cc.loader.cache[url] = img; - } - cc.textureCache.handleLoadedTexture(url); - - var texResult = locTexs[url]; + var texResult = cc.textureCache.handleLoadedTexture(url, img); cb && cb.call(target, texResult); }); From 7bf6632bca51c66443d97dbb40c99b4c7378ae53 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Wed, 10 May 2017 11:56:21 +0800 Subject: [PATCH 156/206] Fix duplicated loading will overwrite image into loader cache --- cocos2d/core/platform/CCLoaders.js | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/cocos2d/core/platform/CCLoaders.js b/cocos2d/core/platform/CCLoaders.js index 5826fd215d..16749a0949 100644 --- a/cocos2d/core/platform/CCLoaders.js +++ b/cocos2d/core/platform/CCLoaders.js @@ -48,13 +48,17 @@ cc._imgLoader = { load: function (realUrl, url, res, cb) { var callback; if (cc.loader.isLoading(realUrl)) { - callback = cb; + callback = function (err, img) { + if (err) + return cb(err); + var tex = cc.textureCache.getTextureForKey(url) || cc.textureCache.handleLoadedTexture(url, img); + cb(null, tex); + }; } else { callback = function (err, img) { if (err) return cb(err); - var tex = cc.textureCache.handleLoadedTexture(url, img); cb(null, tex); }; From 192a3052f6a5f430eb2f2a09554f44171b002ef5 Mon Sep 17 00:00:00 2001 From: giuseppelt Date: Fri, 19 May 2017 01:13:10 +0200 Subject: [PATCH 157/206] ParticleSystem: Mark as ChangeColor only if needed This avoid a waste of resources (particle image redraw), if the delta is only the alpha, which is handled by the context's globalAlpha --- cocos2d/particle/CCParticleSystemCanvasRenderCmd.js | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/cocos2d/particle/CCParticleSystemCanvasRenderCmd.js b/cocos2d/particle/CCParticleSystemCanvasRenderCmd.js index 781baf7004..5f602e99f2 100644 --- a/cocos2d/particle/CCParticleSystemCanvasRenderCmd.js +++ b/cocos2d/particle/CCParticleSystemCanvasRenderCmd.js @@ -195,11 +195,12 @@ }; proto._updateDeltaColor = function (selParticle, dt) { if (!this._node._dontTint) { - selParticle.color.r += selParticle.deltaColor.r * dt; - selParticle.color.g += selParticle.deltaColor.g * dt; - selParticle.color.b += selParticle.deltaColor.b * dt; - selParticle.color.a += selParticle.deltaColor.a * dt; - selParticle.isChangeColor = true; + var deltaColor = selParticle.deltaColor; + selParticle.color.r += deltaColor.r * dt; + selParticle.color.g += deltaColor.g * dt; + selParticle.color.b += deltaColor.b * dt; + selParticle.color.a += deltaColor.a * dt; + selParticle.isChangeColor = deltaColor.r !== 0 || deltaColor.g !== 0 || deltaColor.b !== 0; } }; })(); From 5d989f0e95cb14d160bde830224e065e4f9d12d8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ricardo=20Petr=C3=A9re?= Date: Tue, 13 Jun 2017 09:29:41 -0300 Subject: [PATCH 158/206] fix on moveTo() and MoveTo.create() JSDoc position can be passed as Number too (coordinate x) and both methods return cc.MoveTo --- cocos2d/actions/CCActionInterval.js | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/cocos2d/actions/CCActionInterval.js b/cocos2d/actions/CCActionInterval.js index 74a855748e..4031671993 100644 --- a/cocos2d/actions/CCActionInterval.js +++ b/cocos2d/actions/CCActionInterval.js @@ -1311,7 +1311,7 @@ cc.RotateBy.create = cc.rotateBy; * @param {cc.Point|Number} deltaPos * @param {Number} [deltaY] * @example - * var actionTo = cc.moveBy(2, cc.p(windowSize.width - 40, windowSize.height - 40)); + * var actionBy = cc.moveBy(2, cc.p(windowSize.width - 40, windowSize.height - 40)); */ cc.MoveBy = cc.ActionInterval.extend(/** @lends cc.MoveBy# */{ _positionDelta: null, @@ -1430,7 +1430,7 @@ cc.MoveBy = cc.ActionInterval.extend(/** @lends cc.MoveBy# */{ * @return {cc.MoveBy} * @example * // example - * var actionTo = cc.moveBy(2, cc.p(windowSize.width - 40, windowSize.height - 40)); + * var actionBy = cc.moveBy(2, cc.p(windowSize.width - 40, windowSize.height - 40)); */ cc.moveBy = function (duration, deltaPos, deltaY) { return new cc.MoveBy(duration, deltaPos, deltaY); @@ -1458,7 +1458,7 @@ cc.MoveBy.create = cc.moveBy; * @param {cc.Point|Number} position * @param {Number} y * @example - * var actionBy = new cc.MoveTo(2, cc.p(80, 80)); + * var actionTo = new cc.MoveTo(2, cc.p(80, 80)); */ cc.MoveTo = cc.MoveBy.extend(/** @lends cc.MoveTo# */{ _endPosition: null, @@ -1524,12 +1524,12 @@ cc.MoveTo = cc.MoveBy.extend(/** @lends cc.MoveTo# */{ * Moving to the specified coordinates. * @function * @param {Number} duration duration in seconds - * @param {cc.Point} position + * @param {cc.Point|Number} position * @param {Number} y - * @return {cc.MoveBy} + * @return {cc.MoveTo} * @example * // example - * var actionBy = cc.moveTo(2, cc.p(80, 80)); + * var actionTo = cc.moveTo(2, cc.p(80, 80)); */ cc.moveTo = function (duration, position, y) { return new cc.MoveTo(duration, position, y); @@ -1540,9 +1540,9 @@ cc.moveTo = function (duration, position, y) { * @static * @deprecated since v3.0
Please use cc.moveTo instead. * @param {Number} duration duration in seconds - * @param {cc.Point} position + * @param {cc.Point|Number} position * @param {Number} y - * @return {cc.MoveBy} + * @return {cc.MoveTo} */ cc.MoveTo.create = cc.moveTo; From ea5cbd342fdd5b88ca1e85e5ede8322babd71f17 Mon Sep 17 00:00:00 2001 From: Nick Dong Date: Thu, 22 Jun 2017 10:44:09 +0700 Subject: [PATCH 159/206] Fix typo of error message --- cocos2d/core/CCActionManager.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos2d/core/CCActionManager.js b/cocos2d/core/CCActionManager.js index f3c90b46ab..b677944086 100644 --- a/cocos2d/core/CCActionManager.js +++ b/cocos2d/core/CCActionManager.js @@ -116,7 +116,7 @@ cc.ActionManager = cc.Class.extend(/** @lends cc.ActionManager# */{ if(!action) throw new Error("cc.ActionManager.addAction(): action must be non-null"); if(!target) - throw new Error("cc.ActionManager.addAction(): action must be non-null"); + throw new Error("cc.ActionManager.addAction(): target must be non-null"); //check if the action target already exists var element = this._hashTargets[target.__instanceId]; From ad478831538f25b734fbc166ae27895bfc7754cd Mon Sep 17 00:00:00 2001 From: pandamicro Date: Wed, 28 Jun 2017 12:27:20 +0800 Subject: [PATCH 160/206] Add ENABLE_IMAEG_POOL setting --- CCBoot.js | 4 +++- cocos2d/core/textures/TexturesWebGL.js | 4 +++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/CCBoot.js b/CCBoot.js index 94006c0d1a..06ec6e67df 100644 --- a/CCBoot.js +++ b/CCBoot.js @@ -82,6 +82,8 @@ cc._canvas = null; cc.container = null; cc._gameDiv = null; +window.ENABLE_IMAEG_POOL = true; + /** * Iterate over an object or an array, executing a function for each matched element. * @param {object|array} obj @@ -938,7 +940,7 @@ cc.loader = (function () { delete _queue[url]; } - if (cc._renderType === cc.game.RENDER_TYPE_WEBGL) { + if (ENABLE_IMAEG_POOL && cc._renderType === cc.game.RENDER_TYPE_WEBGL) { imagePool.put(img); } }; diff --git a/cocos2d/core/textures/TexturesWebGL.js b/cocos2d/core/textures/TexturesWebGL.js index 58a2ced557..6505accd52 100644 --- a/cocos2d/core/textures/TexturesWebGL.js +++ b/cocos2d/core/textures/TexturesWebGL.js @@ -496,7 +496,9 @@ cc._tmp.WebGLTexture2D = function () { self._hasPremultipliedAlpha = premultiplied; self._hasMipmaps = false; - self._htmlElementObj = null; + if (ENABLE_IMAEG_POOL) { + self._htmlElementObj = null; + } //dispatch load event to listener. self.dispatchEvent("load"); From d4751be3f300ca90dcfc58c70974c30dfc8db089 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Wed, 28 Jun 2017 12:53:14 +0800 Subject: [PATCH 161/206] Small improvements to GLProgramState implementation --- cocos2d/core/base-nodes/CCNodeWebGLRenderCmd.js | 2 +- cocos2d/shaders/CCGLProgramState.js | 8 +++++--- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/cocos2d/core/base-nodes/CCNodeWebGLRenderCmd.js b/cocos2d/core/base-nodes/CCNodeWebGLRenderCmd.js index 68a3968b90..0506dd522b 100644 --- a/cocos2d/core/base-nodes/CCNodeWebGLRenderCmd.js +++ b/cocos2d/core/base-nodes/CCNodeWebGLRenderCmd.js @@ -57,7 +57,7 @@ // to ease the transition from using glPrograms directly, to // using glProgramStates. Object.defineProperty(proto, '_shaderProgram', { - set: function () { this.setShaderProgram.apply(this, arguments); }, + set: function (value) { this.setShaderProgram(value); }, get: function () { return this.getShaderProgram(); } }); })(); diff --git a/cocos2d/shaders/CCGLProgramState.js b/cocos2d/shaders/CCGLProgramState.js index edfa2ae175..0a9cef01cb 100644 --- a/cocos2d/shaders/CCGLProgramState.js +++ b/cocos2d/shaders/CCGLProgramState.js @@ -153,7 +153,6 @@ cc.GLProgramState = function (glprogram) { this._boundTextureUnits = {}; this._textureUnitIndex = 1; // Start at 1, as CC_Texture0 is bound to 0 - var activeUniforms = glprogram._glContext.getProgramParameter(glprogram._programObj, glprogram._glContext.ACTIVE_UNIFORMS); @@ -168,7 +167,7 @@ cc.GLProgramState = function (glprogram) { this._uniforms.push(uniformValue); this._uniformsByName[uniform.name] = count; this._uniformsByLocation[uniform.location] = count; - count++; + count++; } } }; @@ -181,7 +180,10 @@ cc.GLProgramState.prototype = { } for (var i = 0; i < this._uniforms.length; ++i) { - this._uniforms[i].apply(); + var uniform = this._uniforms[i]; + if (uniform._currentBoundValue !== uniform._value) { + uniform.apply(); + } } }, From 34b8218b919e74c9646c28690be2bcdd4aeb303e Mon Sep 17 00:00:00 2001 From: llq <664301573@qq.com> Date: Thu, 29 Jun 2017 09:59:18 +0800 Subject: [PATCH 162/206] web UIButton support BMFont --- extensions/ccui/uiwidgets/UIButton.js | 28 ++++++++++++++++++++------- 1 file changed, 21 insertions(+), 7 deletions(-) diff --git a/extensions/ccui/uiwidgets/UIButton.js b/extensions/ccui/uiwidgets/UIButton.js index 4feff73686..af3a868d86 100644 --- a/extensions/ccui/uiwidgets/UIButton.js +++ b/extensions/ccui/uiwidgets/UIButton.js @@ -100,12 +100,22 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ } }, - _createTitleRendererIfNeeded: function ( ) { + _createTitleRendererIfNeeded: function (fntFile) { if(!this._titleRenderer) { - this._titleRenderer = new cc.LabelTTF(""); - this._titleRenderer.setAnchorPoint(0.5, 0.5); + if(fntFile != null) + { + this._titleRenderer = new cc.LabelBMFont("", fntFile); + this._titleRenderer.setAlignment(cc.TEXT_ALIGNMENT_CENTER); + } + else + { + this._titleRenderer = new cc.LabelTTF(""); + this._titleRenderer.setVerticalAlignment(cc.VERTICAL_TEXT_ALIGNMENT_CENTER); + } + + this._titleRenderer.setAnchorPoint(0.5, 0.4); this._titleColor = cc.color.WHITE; - this._titleRenderer.setVerticalAlignment(cc.VERTICAL_TEXT_ALIGNMENT_CENTER); + this.addProtectedChild(this._titleRenderer, ccui.Button.TITLE_RENDERER_ZORDER, -1); } }, @@ -657,7 +667,11 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ setTitleFontSize: function (size) { this._createTitleRendererIfNeeded(); - this._titleRenderer.setFontSize(size); + if(this._titleRenderer.setFontSize) + this._titleRenderer.setFontSize(size); + else + this._titleRenderer.setBoundingWidth(size); + this._fontSize = size; }, @@ -705,9 +719,9 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ * @param {String} fontName */ setTitleFontName: function (fontName) { - this._createTitleRendererIfNeeded(); + this._createTitleRendererIfNeeded(fontName); - this._titleRenderer.setFontName(fontName); + this._titleRenderer.setFontName && this._titleRenderer.setFontName(fontName); this._fontName = fontName; }, From a3f21e4ca534d636d5ebc8d8a9966fa45909435f Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Wed, 5 Jul 2017 14:59:28 +0800 Subject: [PATCH 163/206] improve editbox touch handling --- extensions/editbox/CCEditBox.js | 74 ++++++++++++++++++++++++--------- 1 file changed, 55 insertions(+), 19 deletions(-) diff --git a/extensions/editbox/CCEditBox.js b/extensions/editbox/CCEditBox.js index 758f04934f..25963fe24f 100644 --- a/extensions/editbox/CCEditBox.js +++ b/extensions/editbox/CCEditBox.js @@ -154,14 +154,14 @@ cc.EditBoxDelegate = cc.Class.extend({ * This method is called when an edit box gains focus after keyboard is shown. * @param {cc.EditBox} sender */ - editBoxEditingDidBegan: function (sender) { + editBoxEditingDidBegin: function (sender) { }, /** * This method is called when an edit box loses focus after keyboard is hidden. * @param {cc.EditBox} sender */ - editBoxEditingDidEnded: function (sender) { + editBoxEditingDidEnd: function (sender) { }, /** @@ -176,7 +176,7 @@ cc.EditBoxDelegate = cc.Class.extend({ * This method is called when the return button was pressed. * @param {cc.EditBox} sender */ - editBoxEditingReturn: function (sender) { + editBoxReturn: function (sender) { } }); @@ -219,6 +219,8 @@ cc.EditBox = cc.Node.extend({ _placeholderFontSize: 14, _placeholderColor: null, _className: 'EditBox', + _touchListener: null, + _touchEnabled: true, /** * constructor of cc.EditBox @@ -240,16 +242,29 @@ cc.EditBox = cc.Node.extend({ this.initWithSizeAndBackgroundSprite(size, normal9SpriteBg); - cc.eventManager.addListener({ + this._touchListener = cc.EventListener.create({ event: cc.EventListener.TOUCH_ONE_BY_ONE, swallowTouches: true, onTouchBegan: this._onTouchBegan.bind(this), onTouchEnded: this._onTouchEnded.bind(this) - }, this); + }); + cc.eventManager.addListener(this._touchListener, this); this.setInputFlag(this._editBoxInputFlag); }, + setTouchEnabled: function (enable) { + if (this._touchEnabled === enable) { + return; + } + this._touchEnabled = enable; + if (this._touchEnabled) { + cc.eventManager.addListener(this._touchListener, this); + } else { + cc.eventManager.removeListener(this._touchListener); + } + }, + _createRenderCmd: function () { if (cc._renderType === cc.game.RENDER_TYPE_CANVAS) { return new cc.EditBox.CanvasRenderCmd(this); @@ -319,7 +334,21 @@ cc.EditBox = cc.Node.extend({ this._renderCmd._removeDomInputControl(); }, + _isAncestorsVisible: function (node) { + if (null == node) + return true; + + var parent = node.getParent(); + + if (parent && !parent.isVisible()) + return false; + return this._isAncestorsVisible(parent); + }, + _onTouchBegan: function (touch) { + if (!this.isVisible() || !this._isAncestorsVisible(this)) { + return; + } var touchPoint = touch.getLocation(); var bb = cc.rect(0, 0, this._contentSize.width, this._contentSize.height); var hitted = cc.rectContainsPoint(bb, this.convertToNodeSpace(touchPoint)); @@ -333,6 +362,9 @@ cc.EditBox = cc.Node.extend({ }, _onTouchEnded: function () { + if (!this.isVisible() || !this._isAncestorsVisible(this)) { + return; + } this._renderCmd.show(); }, @@ -822,8 +854,8 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp editBox._text = this.value; thisPointer._updateEditBoxContentStyle(); thisPointer.hidden(); - if (editBox._delegate && editBox._delegate.editBoxEditingReturn) { - editBox._delegate.editBoxEditingReturn(editBox); + if (editBox._delegate && editBox._delegate.editBoxReturn) { + editBox._delegate.editBoxReturn(editBox); } cc._canvas.focus(); } @@ -845,10 +877,12 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp this.__autoResize = cc.view.__resizeWithBrowserSize; cc.view.resizeWithBrowserSize(false); - scrollWindowUp(editBox); + if (cc.sys.isMobile) { + scrollWindowUp(editBox); + } - if (editBox._delegate && editBox._delegate.editBoxEditingDidBegan) { - editBox._delegate.editBoxEditingDidBegan(editBox); + if (editBox._delegate && editBox._delegate.editBoxEditingDidBegin) { + editBox._delegate.editBoxEditingDidBegin(editBox); } }); tmpEdTxt.addEventListener('blur', function () { @@ -862,8 +896,8 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp cc.view.resizeWithBrowserSize(true); } window.scrollY = 0; - if (editBox._delegate && editBox._delegate.editBoxEditingDidEnded) { - editBox._delegate.editBoxEditingDidEnded(editBox); + if (editBox._delegate && editBox._delegate.editBoxEditingDidEnd) { + editBox._delegate.editBoxEditingDidEnd(editBox); } if (this.value === '') { @@ -930,10 +964,12 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp this.__autoResize = cc.view.__resizeWithBrowserSize; cc.view.resizeWithBrowserSize(false); - scrollWindowUp(editBox); + if (cc.sys.isMobile) { + scrollWindowUp(editBox); + } - if (editBox._delegate && editBox._delegate.editBoxEditingDidBegan) { - editBox._delegate.editBoxEditingDidBegan(editBox); + if (editBox._delegate && editBox._delegate.editBoxEditingDidBegin) { + editBox._delegate.editBoxEditingDidBegin(editBox); } }); @@ -943,8 +979,8 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp if (e.keyCode === cc.KEY.enter) { e.stopPropagation(); - if (editBox._delegate && editBox._delegate.editBoxEditingReturn) { - editBox._delegate.editBoxEditingReturn(editBox); + if (editBox._delegate && editBox._delegate.editBoxReturn) { + editBox._delegate.editBoxReturn(editBox); } } }); @@ -960,8 +996,8 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp cc.view.resizeWithBrowserSize(true); } - if (editBox._delegate && editBox._delegate.editBoxEditingDidEnded) { - editBox._delegate.editBoxEditingDidEnded(editBox); + if (editBox._delegate && editBox._delegate.editBoxEditingDidEnd) { + editBox._delegate.editBoxEditingDidEnd(editBox); } if (this.value === '') { From 1fa0ac444d3f29019da5df2779ebd362dbec5f4d Mon Sep 17 00:00:00 2001 From: pandamicro Date: Thu, 13 Jul 2017 18:20:49 +0800 Subject: [PATCH 164/206] Improve renderer webgl to support mesh rendering --- cocos2d/core/platform/CCMacro.js | 7 +++ cocos2d/core/renderer/RendererWebGL.js | 62 ++++++++------------------ 2 files changed, 25 insertions(+), 44 deletions(-) diff --git a/cocos2d/core/platform/CCMacro.js b/cocos2d/core/platform/CCMacro.js index 5bb6eb7ab7..a52958c3dc 100644 --- a/cocos2d/core/platform/CCMacro.js +++ b/cocos2d/core/platform/CCMacro.js @@ -499,6 +499,13 @@ cc.ORIENTATION_AUTO = 3; */ cc.CONCURRENCY_HTTP_REQUEST_COUNT = cc.sys.isMobile ? 20 : 0; +/** + * The maximum vertex count for a single batched draw call. + * @constant + * @type Number + */ +cc.BATCH_VERTEX_COUNT = 2000; + // ------------------- vertex attrib flags ----------------------------- /** diff --git a/cocos2d/core/renderer/RendererWebGL.js b/cocos2d/core/renderer/RendererWebGL.js index 7df0452993..d0655f6f28 100644 --- a/cocos2d/core/renderer/RendererWebGL.js +++ b/cocos2d/core/renderer/RendererWebGL.js @@ -33,7 +33,7 @@ var _batchedInfo = { blendSrc: null, // The batched blend destination, all batching element should have the same blend destination blendDst: null, - // The batched glProgramState, all batching element should have the same glProgramState + // The batched gl program state, all batching element should have the same state glProgramState: null }, @@ -129,7 +129,7 @@ return { _cacheToBufferCmds: {}, // an array saves the renderer commands need for cache to other canvas _cacheInstanceIds: [], _currentID: 0, - _clearColor: cc.color(), //background color,default BLACK + _clearColor: cc.color(0, 0, 0, 255), //background color,default BLACK init: function () { var gl = cc._renderContext; @@ -138,7 +138,7 @@ return { this.mat4Identity = new cc.math.Matrix4(); this.mat4Identity.identity(); - initQuadBuffer(2000); + initQuadBuffer(cc.BATCH_VERTEX_COUNT); if (cc.sys.os === cc.sys.OS_IOS) { _IS_IOS = true; } @@ -313,18 +313,23 @@ return { _batchingSize += increment; }, - _updateBatchedInfo: function (texture, blendFunc, shaderProgram) { - if (texture) { + _updateBatchedInfo: function (texture, blendFunc, glProgramState) { + if (texture !== _batchedInfo.texture || + blendFunc.src !== _batchedInfo.blendSrc || + blendFunc.dst !== _batchedInfo.blendDst || + glProgramState !== _batchedInfo.glProgramState) { + // Draw batched elements + this._batchRendering(); + // Update _batchedInfo _batchedInfo.texture = texture; - } - - if (blendFunc) { _batchedInfo.blendSrc = blendFunc.src; _batchedInfo.blendDst = blendFunc.dst; - } + _batchedInfo.glProgramState = glProgramState; - if (shaderProgram) { - _batchedInfo.shader = shaderProgram; + return true; + } + else { + return false; } }, @@ -339,7 +344,7 @@ return { // Check batching var node = cmd._node; - var texture = node._texture || (node._spriteFrame ? node._spriteFrame._texture : null); + var texture = node._texture || (node._spriteFrame && node._spriteFrame._texture); var blendSrc = node._blendFunc.src; var blendDst = node._blendFunc.dst; var glProgramState = cmd._glProgramState; @@ -361,38 +366,7 @@ return { // Upload vertex data var len = cmd.uploadData(_vertexDataF32, _vertexDataUI32, _batchingSize * _sizePerVertex); if (len > 0) { - var i, curr, type = cmd.vertexType || VertexType.QUAD; - switch (type) { - case VertexType.QUAD: - for (i = 0; i < len; i += 4) { - curr = _batchingSize + i; - _indexData[_indexSize++] = curr + 0; - _indexData[_indexSize++] = curr + 1; - _indexData[_indexSize++] = curr + 2; - _indexData[_indexSize++] = curr + 1; - _indexData[_indexSize++] = curr + 2; - _indexData[_indexSize++] = curr + 3; - } - break; - case VertexType.TRIANGLE: - _pureQuad = false; - for (i = 0; i < len; i += 3) { - curr = _batchingSize + i; - _indexData[_indexSize++] = curr + 0; - _indexData[_indexSize++] = curr + 1; - _indexData[_indexSize++] = curr + 2; - } - break; - case VertexType.CUSTOM: - _pureQuad = false; - if (cmd.uploadIndexData) { - _indexSize += cmd.uploadIndexData(_indexData, _indexSize, _batchingSize); - } - break; - default: - return; - } - _batchingSize += len; + this._increaseBatchingSize(len, cmd.vertexType); } }, From aa69d8c336b5fba6048539cc84b5615116e32245 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Thu, 13 Jul 2017 18:21:16 +0800 Subject: [PATCH 165/206] Improve ActionManager performance and fix memory leak caused by element pool --- cocos2d/core/CCActionManager.js | 80 +++++++++------------------------ 1 file changed, 20 insertions(+), 60 deletions(-) diff --git a/cocos2d/core/CCActionManager.js b/cocos2d/core/CCActionManager.js index f3c90b46ab..9ecc3c4886 100644 --- a/cocos2d/core/CCActionManager.js +++ b/cocos2d/core/CCActionManager.js @@ -30,25 +30,13 @@ * @example * var element = new cc.HashElement(); */ -cc.HashElement = cc.Class.extend(/** @lends cc.HashElement# */{ - actions:null, - target:null, //ccobject - actionIndex:0, - currentAction:null, //CCAction - currentActionSalvaged:false, - paused:false, - /** - * Constructor - */ - ctor:function () { - this.actions = []; - this.target = null; - this.actionIndex = 0; - this.currentAction = null; //CCAction - this.currentActionSalvaged = false; - this.paused = false; - } -}); +cc.HashElement = function () { + this.actions = []; + this.target = null; + this.actionIndex = 0; + this.currentAction = null; //CCAction + this.paused = false; +}; /** * cc.ActionManager is a class that can manage actions.
@@ -64,10 +52,6 @@ cc.HashElement = cc.Class.extend(/** @lends cc.HashElement# */{ * var mng = new cc.ActionManager(); */ cc.ActionManager = cc.Class.extend(/** @lends cc.ActionManager# */{ - _hashTargets:null, - _arrayTargets:null, - _currentTarget:null, - _currentTargetSalvaged:false, _elementPool: [], _searchElementByTarget:function (arr, target) { @@ -82,7 +66,6 @@ cc.ActionManager = cc.Class.extend(/** @lends cc.ActionManager# */{ this._hashTargets = {}; this._arrayTargets = []; this._currentTarget = null; - this._currentTargetSalvaged = false; }, _getElement: function (target, paused) { @@ -99,8 +82,8 @@ cc.ActionManager = cc.Class.extend(/** @lends cc.ActionManager# */{ element.actions.length = 0; element.actionIndex = 0; element.currentAction = null; - element.currentActionSalvaged = false; element.paused = false; + element.target = null; this._elementPool.push(element); }, @@ -156,15 +139,8 @@ cc.ActionManager = cc.Class.extend(/** @lends cc.ActionManager# */{ return; var element = this._hashTargets[target.__instanceId]; if (element) { - if (element.actions.indexOf(element.currentAction) !== -1 && !(element.currentActionSalvaged)) - element.currentActionSalvaged = true; - element.actions.length = 0; - if (this._currentTarget === element && !forceDelete) { - this._currentTargetSalvaged = true; - } else { - this._deleteHashElement(element); - } + this._deleteHashElement(element); } }, /** Removes an action given an action reference. @@ -181,6 +157,9 @@ cc.ActionManager = cc.Class.extend(/** @lends cc.ActionManager# */{ for (var i = 0; i < element.actions.length; i++) { if (element.actions[i] === action) { element.actions.splice(i, 1); + // update actionIndex in case we are in tick. looping over the actions + if (element.actionIndex >= i) + element.actionIndex--; break; } } @@ -291,10 +270,10 @@ cc.ActionManager = cc.Class.extend(/** @lends cc.ActionManager# */{ * @param {Array} targetsToResume */ resumeTargets:function(targetsToResume){ - if(!targetsToResume) + if (!targetsToResume) return; - for(var i = 0 ; i< targetsToResume.length; i++){ + for (var i = 0; i< targetsToResume.length; i++) { if(targetsToResume[i]) this.resumeTarget(targetsToResume[i]); } @@ -311,9 +290,6 @@ cc.ActionManager = cc.Class.extend(/** @lends cc.ActionManager# */{ _removeActionAtIndex:function (index, element) { var action = element.actions[index]; - if ((action === element.currentAction) && (!element.currentActionSalvaged)) - element.currentActionSalvaged = true; - element.actions.splice(index, 1); // update actionIndex in case we are in tick. looping over the actions @@ -321,11 +297,7 @@ cc.ActionManager = cc.Class.extend(/** @lends cc.ActionManager# */{ element.actionIndex--; if (element.actions.length === 0) { - if (this._currentTarget === element) { - this._currentTargetSalvaged = true; - } else { - this._deleteHashElement(element); - } + this._deleteHashElement(element); } }, @@ -356,25 +328,17 @@ cc.ActionManager = cc.Class.extend(/** @lends cc.ActionManager# */{ for (var elt = 0; elt < locTargets.length; elt++) { this._currentTarget = locTargets[elt]; locCurrTarget = this._currentTarget; - //this._currentTargetSalvaged = false; - if (!locCurrTarget.paused) { + if (!locCurrTarget.paused && locCurrTarget.actions) { // The 'actions' CCMutableArray may change while inside this loop. - for (locCurrTarget.actionIndex = 0; - locCurrTarget.actionIndex < (locCurrTarget.actions ? locCurrTarget.actions.length : 0); - locCurrTarget.actionIndex++) { + for (locCurrTarget.actionIndex = 0; locCurrTarget.actionIndex < locCurrTarget.actions.length; locCurrTarget.actionIndex++) { locCurrTarget.currentAction = locCurrTarget.actions[locCurrTarget.actionIndex]; if (!locCurrTarget.currentAction) continue; - locCurrTarget.currentActionSalvaged = false; //use for speed locCurrTarget.currentAction.step(dt * ( locCurrTarget.currentAction._speedMethod ? locCurrTarget.currentAction._speed : 1 ) ); - if (locCurrTarget.currentActionSalvaged) { - // The currentAction told the node to remove it. To prevent the action from - // accidentally deallocating itself before finishing its step, we retained - // it. Now that step is done, it's safe to release it. - locCurrTarget.currentAction = null;//release - } else if (locCurrTarget.currentAction.isDone()) { + + if (locCurrTarget.currentAction.isDone()) { locCurrTarget.currentAction.stop(); var action = locCurrTarget.currentAction; // Make currentAction nil to prevent removeAction from salvaging it. @@ -385,12 +349,8 @@ cc.ActionManager = cc.Class.extend(/** @lends cc.ActionManager# */{ locCurrTarget.currentAction = null; } } - - // elt, at this moment, is still valid - // so it is safe to ask this here (issue #490) - // only delete currentTarget if no actions were scheduled during the cycle (issue #481) - if (this._currentTargetSalvaged && locCurrTarget.actions.length === 0) { + if (locCurrTarget.actions.length === 0) { this._deleteHashElement(locCurrTarget) && elt--; } } From c44b97cb3ca37fcf44ea3a9b6bd1120e442968ce Mon Sep 17 00:00:00 2001 From: pandamicro Date: Thu, 13 Jul 2017 18:21:49 +0800 Subject: [PATCH 166/206] Improve spine rendering --- cocos2d/core/textures/CCTexture2D.js | 1 - extensions/spine/CCSkeleton.js | 54 +- extensions/spine/CCSkeletonAnimation.js | 25 +- extensions/spine/CCSkeletonCanvasRenderCmd.js | 400 +++++++------- extensions/spine/CCSkeletonTexture.js | 13 +- extensions/spine/CCSkeletonWebGLRenderCmd.js | 522 +++++++++--------- extensions/spine/LICENSE | 27 + extensions/spine/Spine.js | 13 +- 8 files changed, 558 insertions(+), 497 deletions(-) create mode 100644 extensions/spine/LICENSE diff --git a/cocos2d/core/textures/CCTexture2D.js b/cocos2d/core/textures/CCTexture2D.js index b80aec1274..b69d83cfd9 100644 --- a/cocos2d/core/textures/CCTexture2D.js +++ b/cocos2d/core/textures/CCTexture2D.js @@ -190,7 +190,6 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () { */ handleLoadedTexture: function () { var self = this; - if (self._textureLoaded) return; if (!self._htmlElementObj) { return; } diff --git a/extensions/spine/CCSkeleton.js b/extensions/spine/CCSkeleton.js index d7f35ebf71..eec8aa2fbb 100644 --- a/extensions/spine/CCSkeleton.js +++ b/extensions/spine/CCSkeleton.js @@ -59,6 +59,8 @@ sp.ATTACHMENT_TYPE = { SKINNED_MESH:3 }; +var spine = sp.spine; + /** *

* The skeleton of Spine.
@@ -78,7 +80,6 @@ sp.Skeleton = cc.Node.extend(/** @lends sp.Skeleton# */{ _premultipliedAlpha: false, _ownsSkeletonData: null, _atlas: null, - _blendFunc: null, /** * The constructor of sp.Skeleton. override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function. @@ -105,7 +106,6 @@ sp.Skeleton = cc.Node.extend(/** @lends sp.Skeleton# */{ init: function () { cc.Node.prototype.init.call(this); this._premultipliedAlpha = (cc._renderType === cc.game.RENDER_TYPE_WEBGL && cc.OPTIMIZE_BLEND_FUNC_FOR_PREMULTIPLIED_ALPHA); - this._blendFunc = {src: cc.BLEND_SRC, dst: cc.BLEND_DST}; this.scheduleUpdate(); }, @@ -171,7 +171,7 @@ sp.Skeleton = cc.Node.extend(/** @lends sp.Skeleton# */{ /** * Initializes sp.Skeleton with Data. - * @param {spine.SkeletonData|String} skeletonDataFile + * @param {sp.spine.SkeletonData|String} skeletonDataFile * @param {String|spine.Atlas|spine.SkeletonData} atlasFile atlas filename or atlas data or owns SkeletonData * @param {Number} [scale] scale can be specified on the JSON or binary loader which will scale the bone positions, image sizes, and animation translations. */ @@ -211,13 +211,13 @@ sp.Skeleton = cc.Node.extend(/** @lends sp.Skeleton# */{ */ getBoundingBox: function () { var minX = cc.FLT_MAX, minY = cc.FLT_MAX, maxX = cc.FLT_MIN, maxY = cc.FLT_MIN; - var scaleX = this.getScaleX(), scaleY = this.getScaleY(), vertices = [], + var scaleX = this.getScaleX(), scaleY = this.getScaleY(), vertices, slots = this._skeleton.slots, VERTEX = spine.RegionAttachment; for (var i = 0, slotCount = slots.length; i < slotCount; ++i) { var slot = slots[i]; var attachment = slot.attachment; - if (!attachment || ! (attachment instanceof spine.RegionAttachment)) + if (!attachment || !(attachment instanceof spine.RegionAttachment)) continue; vertices = attachment.updateWorldVertices(slot, false); minX = Math.min(minX, vertices[VERTEX.X1] * scaleX, vertices[VERTEX.X4] * scaleX, vertices[VERTEX.X2] * scaleX, vertices[VERTEX.X3] * scaleX); @@ -260,7 +260,7 @@ sp.Skeleton = cc.Node.extend(/** @lends sp.Skeleton# */{ /** * Finds a bone by name. This does a string comparison for every bone. * @param {String} boneName - * @returns {spine.Bone} + * @returns {sp.spine.Bone} */ findBone: function (boneName) { return this._skeleton.findBone(boneName); @@ -269,7 +269,7 @@ sp.Skeleton = cc.Node.extend(/** @lends sp.Skeleton# */{ /** * Finds a slot by name. This does a string comparison for every slot. * @param {String} slotName - * @returns {spine.Slot} + * @returns {sp.spine.Slot} */ findSlot: function (slotName) { return this._skeleton.findSlot(slotName); @@ -278,7 +278,7 @@ sp.Skeleton = cc.Node.extend(/** @lends sp.Skeleton# */{ /** * Finds a skin by name and makes it the active skin. This does a string comparison for every skin. Note that setting the skin does not change which attachments are visible. * @param {string} skinName - * @returns {spine.Skin} + * @returns {sp.spine.Skin} */ setSkin: function (skinName) { return this._skeleton.setSkinByName(skinName); @@ -288,7 +288,7 @@ sp.Skeleton = cc.Node.extend(/** @lends sp.Skeleton# */{ * Returns the attachment for the slot and attachment name. The skeleton looks first in its skin, then in the skeleton data’s default skin. * @param {String} slotName * @param {String} attachmentName - * @returns {spine.RegionAttachment|spine.BoundingBoxAttachment} + * @returns {sp.spine.Attachment} */ getAttachment: function (slotName, attachmentName) { return this._skeleton.getAttachmentByName(slotName, attachmentName); @@ -321,8 +321,8 @@ sp.Skeleton = cc.Node.extend(/** @lends sp.Skeleton# */{ /** * Sets skeleton data to sp.Skeleton. - * @param {spine.SkeletonData} skeletonData - * @param {spine.SkeletonData} ownsSkeletonData + * @param {sp.spine.SkeletonData} skeletonData + * @param {sp.spine.SkeletonData} ownsSkeletonData */ setSkeletonData: function (skeletonData, ownsSkeletonData) { if(skeletonData.width != null && skeletonData.height != null) @@ -338,8 +338,8 @@ sp.Skeleton = cc.Node.extend(/** @lends sp.Skeleton# */{ /** * Return the renderer of attachment. - * @param {spine.RegionAttachment|spine.BoundingBoxAttachment} regionAttachment - * @returns {cc.Node} + * @param {sp.spine.RegionAttachment|sp.spine.BoundingBoxAttachment} regionAttachment + * @returns {sp.spine.TextureAtlasRegion} */ getTextureAtlas: function (regionAttachment) { return regionAttachment.region; @@ -350,23 +350,23 @@ sp.Skeleton = cc.Node.extend(/** @lends sp.Skeleton# */{ * @returns {cc.BlendFunc} */ getBlendFunc: function () { - return this._blendFunc; + var slot = this._skeleton.drawOrder[0]; + if (slot) { + var blend = this._renderCmd._getBlendFunc(slot.data.blendMode, this._premultipliedAlpha); + return blend; + } + else { + return {}; + } }, /** - * Sets the blendFunc of sp.Skeleton. + * Sets the blendFunc of sp.Skeleton, it won't have any effect for skeleton, skeleton is using slot's data to determine the blend function. * @param {cc.BlendFunc|Number} src * @param {Number} [dst] */ setBlendFunc: function (src, dst) { - var locBlendFunc = this._blendFunc; - if (dst === undefined) { - locBlendFunc.src = src.src; - locBlendFunc.dst = src.dst; - } else { - locBlendFunc.src = src; - locBlendFunc.dst = dst; - } + return; }, /** @@ -378,6 +378,14 @@ sp.Skeleton = cc.Node.extend(/** @lends sp.Skeleton# */{ } }); +cc.defineGetterSetter(sp.Skeleton.prototype, "opacityModifyRGB", sp.Skeleton.prototype.isOpacityModifyRGB); + +// For renderer webgl to identify skeleton's default texture and blend function +cc.defineGetterSetter(sp.Skeleton.prototype, "_blendFunc", sp.Skeleton.prototype.getBlendFunc); +cc.defineGetterSetter(sp.Skeleton.prototype, '_texture', function () { + return this._renderCmd._currTexture; +}); + /** * Creates a skeleton object. * @deprecated since v3.0, please use new sp.Skeleton(skeletonDataFile, atlasFile, scale) instead. diff --git a/extensions/spine/CCSkeletonAnimation.js b/extensions/spine/CCSkeletonAnimation.js index 339bd08f15..17f0f25675 100644 --- a/extensions/spine/CCSkeletonAnimation.js +++ b/extensions/spine/CCSkeletonAnimation.js @@ -32,8 +32,7 @@ sp._atlasLoader = { load:function(line){ var texturePath = cc.path.join(cc.path.dirname(this.spAtlasFile), line); var texture = cc.textureCache.addImage(texturePath); - var tex = new sp.SkeletonTexture(); - tex._image = { width: texture.getPixelsWide(), height: texture.getPixelsHigh() }; + var tex = new sp.SkeletonTexture({ width: texture.getPixelsWide(), height: texture.getPixelsHigh() }); tex.setRealTexture(texture); return tex; }, @@ -55,7 +54,7 @@ sp.ANIMATION_EVENT_TYPE = { EVENT: 5 }; -sp.TrackEntryListeners = function(startListener, endListener, completeListener, eventListener, interruptListener, disposeListener){ +sp.TrackEntryListeners = function (startListener, endListener, completeListener, eventListener, interruptListener, disposeListener) { this.startListener = startListener || null; this.endListener = endListener || null; this.completeListener = completeListener || null; @@ -156,7 +155,7 @@ sp.SkeletonAnimation = sp.Skeleton.extend(/** @lends sp.SkeletonAnimation# */{ /** * Sets animation state data to sp.SkeletonAnimation. - * @param {spine.AnimationStateData} stateData + * @param {sp.spine.AnimationStateData} stateData */ setAnimationStateData: function (stateData) { var state = new spine.AnimationState(stateData); @@ -192,7 +191,7 @@ sp.SkeletonAnimation = sp.Skeleton.extend(/** @lends sp.SkeletonAnimation# */{ * @param {Number} trackIndex * @param {String} name * @param {Boolean} loop - * @returns {spine.TrackEntry|null} + * @returns {sp.spine.TrackEntry|null} */ setAnimation: function (trackIndex, name, loop) { var animation = this._skeleton.data.findAnimation(name); @@ -209,7 +208,7 @@ sp.SkeletonAnimation = sp.Skeleton.extend(/** @lends sp.SkeletonAnimation# */{ * @param {String} name * @param {Boolean} loop * @param {Number} [delay=0] - * @returns {spine.TrackEntry|null} + * @returns {sp.spine.TrackEntry|null} */ addAnimation: function (trackIndex, name, loop, delay) { delay = delay == null ? 0 : delay; @@ -221,10 +220,19 @@ sp.SkeletonAnimation = sp.Skeleton.extend(/** @lends sp.SkeletonAnimation# */{ return this._state.addAnimationWith(trackIndex, animation, loop, delay); }, + /** + * Find animation with specified name + * @param {String} name + * @returns {sp.spine.Animation|null} + */ + findAnimation: function (name) { + return this._skeleton.data.findAnimation(name); + }, + /** * Returns track entry by trackIndex. * @param trackIndex - * @returns {spine.TrackEntry|null} + * @returns {sp.spine.TrackEntry|null} */ getCurrent: function (trackIndex) { return this._state.getCurrent(trackIndex); @@ -254,6 +262,7 @@ sp.SkeletonAnimation = sp.Skeleton.extend(/** @lends sp.SkeletonAnimation# */{ update: function (dt) { this._super(dt); dt *= this._timeScale; + this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.contentDirty); this._state.update(dt); this._state.apply(this._skeleton); this._skeleton.updateWorldTransform(); @@ -339,4 +348,4 @@ sp.SkeletonAnimation = sp.Skeleton.extend(/** @lends sp.SkeletonAnimation# */{ */ 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/extensions/spine/CCSkeletonCanvasRenderCmd.js b/extensions/spine/CCSkeletonCanvasRenderCmd.js index 2b20f3f97c..0c37adb83d 100644 --- a/extensions/spine/CCSkeletonCanvasRenderCmd.js +++ b/extensions/spine/CCSkeletonCanvasRenderCmd.js @@ -23,208 +23,224 @@ ****************************************************************************/ (function () { - sp.Skeleton.CanvasRenderCmd = function (renderableObject) { - this._rootCtor(renderableObject); - this._needDraw = true; - }; - - var proto = sp.Skeleton.CanvasRenderCmd.prototype = Object.create(cc.Node.CanvasRenderCmd.prototype); - proto.constructor = sp.Skeleton.CanvasRenderCmd; - - proto.rendering = function (wrapper, scaleX, scaleY) { - var node = this._node, i, n, slot, slotNode; - wrapper = wrapper || cc._renderContext; - - var locSkeleton = node._skeleton, drawOrder = locSkeleton.drawOrder; - for (i = 0, n = drawOrder.length; i < n; i++) { - slot = drawOrder[i]; - slotNode = slot._slotNode; - 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; - } - } - if (!node._debugSlots && !node._debugBones) - return; - - wrapper.setTransform(this._worldTransform, scaleX, scaleY); - wrapper.setGlobalAlpha(1); - var attachment, drawingUtil = cc._drawingUtil; - if (node._debugSlots) { - // Slots. - drawingUtil.setDrawColor(0, 0, 255, 255); - drawingUtil.setLineWidth(1); - - var points = []; - for (i = 0, n = locSkeleton.slots.length; i < n; i++) { - slot = locSkeleton.drawOrder[i]; - if (!slot.attachment || !(slot.attachment instanceof spine.RegionAttachment)) - continue; - attachment = slot.attachment; - this._updateRegionAttachmentSlot(attachment, slot, points); - drawingUtil.drawPoly(points, 4, true); - } - } +var spine = sp.spine; - if (node._debugBones) { - // Bone lengths. - var bone; - drawingUtil.setLineWidth(2); - drawingUtil.setDrawColor(255, 0, 0, 255); - - for (i = 0, n = locSkeleton.bones.length; i < n; i++) { - bone = locSkeleton.bones[i]; - var x = bone.data.length * bone.a + bone.worldX; - var y = bone.data.length * bone.c + bone.worldY; - drawingUtil.drawLine( - {x: bone.worldX, y: bone.worldY}, - {x: x, y: y}); - } +sp.Skeleton.CanvasRenderCmd = function (renderableObject) { + this._rootCtor(renderableObject); + this._needDraw = true; +}; - // Bone origins. - drawingUtil.setPointSize(4); - drawingUtil.setDrawColor(0, 0, 255, 255); // Root bone is blue. +var proto = sp.Skeleton.CanvasRenderCmd.prototype = Object.create(cc.Node.CanvasRenderCmd.prototype); +proto.constructor = sp.Skeleton.CanvasRenderCmd; - for (i = 0, n = locSkeleton.bones.length; i < n; i++) { - bone = locSkeleton.bones[i]; - drawingUtil.drawPoint({x: bone.worldX, y: bone.worldY}); - if (i === 0) - drawingUtil.setDrawColor(0, 255, 0, 255); - } +proto.rendering = function (wrapper, scaleX, scaleY) { + var node = this._node, i, n, slot, slotNode; + wrapper = wrapper || cc._renderContext; + + var locSkeleton = node._skeleton, drawOrder = locSkeleton.drawOrder; + for (i = 0, n = drawOrder.length; i < n; i++) { + slot = drawOrder[i]; + slotNode = slot._slotNode; + 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; } - }; - - proto._updateRegionAttachmentSlot = function (attachment, slot, points) { - if (!points) - return; - - var vertices = attachment.updateWorldVertices(slot, false); - var VERTEX = spine.RegionAttachment; - points.length = 0; - points.push(cc.p(vertices[VERTEX.X1], vertices[VERTEX.Y1])); - points.push(cc.p(vertices[VERTEX.X4], vertices[VERTEX.Y4])); - points.push(cc.p(vertices[VERTEX.X3], vertices[VERTEX.Y3])); - points.push(cc.p(vertices[VERTEX.X2], vertices[VERTEX.Y2])); - }; - - proto._createChildFormSkeletonData = function () { - var node = this._node; - var locSkeleton = node._skeleton, spriteName, sprite; - for (var i = 0, n = locSkeleton.slots.length; i < n; i++) { - var slot = locSkeleton.slots[i], attachment = slot.attachment; - var slotNode = new cc.Node(); - slot._slotNode = slotNode; - - if (attachment instanceof spine.RegionAttachment) { - spriteName = attachment.region.name; - sprite = this._createSprite(slot, attachment); - slot.currentSprite = sprite; - slot.currentSpriteName = spriteName; - slotNode.addChild(sprite); - } else if (attachment instanceof spine.MeshAttachment) { - //todo for mesh - } + } + + if (!node._debugSlots && !node._debugBones) + return; + + wrapper.setTransform(this._worldTransform, scaleX, scaleY); + wrapper.setGlobalAlpha(1); + var attachment, drawingUtil = cc._drawingUtil; + if (node._debugSlots) { + // Slots. + drawingUtil.setDrawColor(0, 0, 255, 255); + drawingUtil.setLineWidth(1); + + var points = []; + for (i = 0, n = locSkeleton.slots.length; i < n; i++) { + slot = locSkeleton.drawOrder[i]; + if (!slot.attachment || !(slot.attachment instanceof spine.RegionAttachment)) + continue; + attachment = slot.attachment; + this._updateRegionAttachmentSlot(attachment, slot, points); + drawingUtil.drawPoly(points, 4, true); } - }; - - var loaded = function (sprite, texture, rendererObject, attachment) { - var rect = new cc.Rect(rendererObject.x, rendererObject.y, rendererObject.width, rendererObject.height); - sprite.initWithTexture(texture, rect, rendererObject.rotate, false); - sprite._rect.width = attachment.width; - sprite._rect.height = attachment.height; - sprite.setContentSize(attachment.width, attachment.height); - sprite.setRotation(-attachment.rotation); - sprite.setScale(rendererObject.width / rendererObject.originalWidth * attachment.scaleX, - rendererObject.height / rendererObject.originalHeight * attachment.scaleY); - }; - - proto._createSprite = function (slot, attachment) { - var rendererObject = attachment.region; - var texture = rendererObject.texture.getRealTexture(); - var sprite = new cc.Sprite(); - if (texture.isLoaded()) { - loaded(sprite, texture, rendererObject, attachment); - } else { - texture.addEventListener('load', function () { - loaded(sprite, texture, rendererObject, attachment); - }, this); + } + + if (node._debugBones) { + // Bone lengths. + var bone; + drawingUtil.setLineWidth(2); + drawingUtil.setDrawColor(255, 0, 0, 255); + + for (i = 0, n = locSkeleton.bones.length; i < n; i++) { + bone = locSkeleton.bones[i]; + var x = bone.data.length * bone.a + bone.worldX; + var y = bone.data.length * bone.c + bone.worldY; + drawingUtil.drawLine( + {x: bone.worldX, y: bone.worldY}, + {x: x, y: y}); } - slot.sprites = slot.sprites || {}; - slot.sprites[rendererObject.name] = sprite; - return sprite; - }; - - proto._updateChild = function () { - var locSkeleton = this._node._skeleton, slots = locSkeleton.slots; - var color = this._displayedColor, opacity = this._displayedOpacity; - var i, n, selSprite, ax, ay; - - var slot, attachment, slotNode; - for (i = 0, n = slots.length; i < n; i++) { - slot = slots[i]; - attachment = slot.attachment; - slotNode = slot._slotNode; - if (!attachment) { - slotNode.setVisible(false); - continue; - } - if (attachment instanceof spine.RegionAttachment){ - if (attachment.region) { - if (!slot.currentSpriteName || slot.currentSpriteName !== attachment.name) { - var spriteName = attachment.region.name; - if (slot.currentSprite !== undefined) - slot.currentSprite.setVisible(false); - slot.sprites = slot.sprites || {}; - if (slot.sprites[spriteName] !== undefined) - slot.sprites[spriteName].setVisible(true); - else { - var sprite = this._createSprite(slot, attachment); - slotNode.addChild(sprite); - } - slot.currentSprite = slot.sprites[spriteName]; - slot.currentSpriteName = spriteName; + + // Bone origins. + drawingUtil.setPointSize(4); + drawingUtil.setDrawColor(0, 0, 255, 255); // Root bone is blue. + + for (i = 0, n = locSkeleton.bones.length; i < n; i++) { + bone = locSkeleton.bones[i]; + drawingUtil.drawPoint({x: bone.worldX, y: bone.worldY}); + if (i === 0) + drawingUtil.setDrawColor(0, 255, 0, 255); + } + } +}; + +proto.updateStatus = function() { + this.originUpdateStatus(); + this._updateCurrentRegions(); + this._regionFlag = _ccsg.Node.CanvasRenderCmd.RegionStatus.DirtyDouble; + this._dirtyFlag &= ~_ccsg.Node._dirtyFlags.contentDirty; +}; + +proto.getLocalBB = function() { + return this._node.getBoundingBox(); +}; + +proto._updateRegionAttachmentSlot = function (attachment, slot, points) { + if (!points) + return; + + var vertices = attachment.updateWorldVertices(slot, false); + var VERTEX = spine.RegionAttachment; + points.length = 0; + points.push(cc.p(vertices[VERTEX.X1], vertices[VERTEX.Y1])); + points.push(cc.p(vertices[VERTEX.X4], vertices[VERTEX.Y4])); + points.push(cc.p(vertices[VERTEX.X3], vertices[VERTEX.Y3])); + points.push(cc.p(vertices[VERTEX.X2], vertices[VERTEX.Y2])); +}; + +proto._createChildFormSkeletonData = function () { + var node = this._node; + var locSkeleton = node._skeleton, spriteName, sprite; + for (var i = 0, n = locSkeleton.slots.length; i < n; i++) { + var slot = locSkeleton.slots[i], attachment = slot.attachment; + var slotNode = new cc.Node(); + slot._slotNode = slotNode; + + if (attachment instanceof spine.RegionAttachment) { + spriteName = attachment.region.name; + sprite = this._createSprite(slot, attachment); + slot.currentSprite = sprite; + slot.currentSpriteName = spriteName; + slotNode.addChild(sprite); + } else if (attachment instanceof spine.MeshAttachment) { + //todo for mesh + } + } +}; + +var loaded = function (sprite, texture, attachment) { + var rendererObject = attachment.region; + var rect = new cc.Rect(rendererObject.x, rendererObject.y, rendererObject.width, rendererObject.height); + sprite.initWithTexture(texture, rect, rendererObject.rotate, false); + sprite._rect.width = attachment.width; + sprite._rect.height = attachment.height; + sprite.setContentSize(attachment.width, attachment.height); + sprite.setRotation(-attachment.rotation); + sprite.setScale(rendererObject.width / rendererObject.originalWidth * attachment.scaleX, + rendererObject.height / rendererObject.originalHeight * attachment.scaleY); +}; + +proto._createSprite = function (slot, attachment) { + var rendererObject = attachment.region; + var texture = rendererObject.texture.getRealTexture(); + var sprite = new cc.Sprite(); + if (texture.isLoaded()) { + loaded(sprite, texture, attachment); + } else { + texture.addEventListener('load', function () { + loaded(sprite, texture, attachment); + }, this); + } + slot.sprites = slot.sprites || {}; + slot.sprites[rendererObject.name] = sprite; + return sprite; +}; + +proto._updateChild = function () { + var locSkeleton = this._node._skeleton, slots = locSkeleton.slots; + var color = this._displayedColor, opacity = this._displayedOpacity; + var i, n, selSprite, ax, ay; + + var slot, attachment, slotNode; + for (i = 0, n = slots.length; i < n; i++) { + slot = slots[i]; + attachment = slot.attachment; + slotNode = slot._slotNode; + if (!attachment) { + slotNode.setVisible(false); + continue; + } + if (attachment instanceof spine.RegionAttachment) { + if (attachment.region) { + if (!slot.currentSpriteName || slot.currentSpriteName !== attachment.name) { + var spriteName = attachment.region.name; + if (slot.currentSprite !== undefined) + slot.currentSprite.setVisible(false); + slot.sprites = slot.sprites || {}; + if (slot.sprites[spriteName] !== undefined) + slot.sprites[spriteName].setVisible(true); + else { + var sprite = this._createSprite(slot, attachment); + slotNode.addChild(sprite); } + slot.currentSprite = slot.sprites[spriteName]; + slot.currentSpriteName = spriteName; } - var bone = slot.bone; - if (attachment.region.offsetX === 0 && attachment.region.offsetY === 0) { - ax = attachment.x; - ay = attachment.y; - } - else { - //var regionScaleX = attachment.width / attachment.regionOriginalWidth * attachment.scaleX; - //ax = attachment.x + attachment.regionOffsetX * regionScaleX - (attachment.width * attachment.scaleX - attachment.regionWidth * regionScaleX) / 2; - ax = (attachment.offset[0] + attachment.offset[4]) * 0.5; - ay = (attachment.offset[1] + attachment.offset[5]) * 0.5; - } - slotNode.setPosition(bone.worldX + ax * bone.a + ay * bone.b, bone.worldY + ax * bone.c + ay * bone.d); - slotNode.setScale(bone.getWorldScaleX(), bone.getWorldScaleY()); - - //set the color and opacity - selSprite = slot.currentSprite; - selSprite._flippedX = bone.skeleton.flipX; - selSprite._flippedY = bone.skeleton.flipY; - if (selSprite._flippedY || selSprite._flippedX) { - slotNode.setRotation(bone.getWorldRotationX()); - selSprite.setRotation(attachment.rotation); - } else { - slotNode.setRotation(-bone.getWorldRotationX()); - selSprite.setRotation(-attachment.rotation); - } - - //hack for sprite - selSprite._renderCmd._displayedOpacity = 0 | (opacity * slot.color.a); - var r = 0 | (color.r * slot.color.r), g = 0 | (color.g * slot.color.g), b = 0 | (color.b * slot.color.b); - selSprite.setColor(cc.color(r, g, b)); - selSprite._renderCmd._updateColor(); - } else if (attachment instanceof spine.MeshAttachment) { - //todo for mesh + } + var bone = slot.bone; + if (attachment.region.offsetX === 0 && attachment.region.offsetY === 0) { + ax = attachment.x; + ay = attachment.y; + } + else { + //var regionScaleX = attachment.width / attachment.regionOriginalWidth * attachment.scaleX; + //ax = attachment.x + attachment.regionOffsetX * regionScaleX - (attachment.width * attachment.scaleX - attachment.regionWidth * regionScaleX) / 2; + ax = (attachment.offset[0] + attachment.offset[4]) * 0.5; + ay = (attachment.offset[1] + attachment.offset[5]) * 0.5; + } + slotNode.setPosition(bone.worldX + ax * bone.a + ay * bone.b, bone.worldY + ax * bone.c + ay * bone.d); + slotNode.setScale(bone.getWorldScaleX(), bone.getWorldScaleY()); + + //set the color and opacity + selSprite = slot.currentSprite; + selSprite._flippedX = bone.skeleton.flipX; + selSprite._flippedY = bone.skeleton.flipY; + if (selSprite._flippedY || selSprite._flippedX) { + slotNode.setRotation(bone.getWorldRotationX()); + selSprite.setRotation(attachment.rotation); } else { - slotNode.setVisible(false); - continue; + slotNode.setRotation(-bone.getWorldRotationX()); + selSprite.setRotation(-attachment.rotation); } - slotNode.setVisible(true); + + //hack for sprite + selSprite._renderCmd._displayedOpacity = 0 | (opacity * slot.color.a); + var r = 0 | (color.r * slot.color.r), g = 0 | (color.g * slot.color.g), b = 0 | (color.b * slot.color.b); + selSprite.setColor(cc.color(r, g, b)); + selSprite._renderCmd._updateColor(); + } else if (attachment instanceof spine.MeshAttachment) { + // Can not render mesh + } else { + slotNode.setVisible(false); + continue; } - }; + slotNode.setVisible(true); + } +}; + })(); diff --git a/extensions/spine/CCSkeletonTexture.js b/extensions/spine/CCSkeletonTexture.js index 997065b339..9250369c30 100644 --- a/extensions/spine/CCSkeletonTexture.js +++ b/extensions/spine/CCSkeletonTexture.js @@ -22,7 +22,11 @@ THE SOFTWARE. ****************************************************************************/ -sp.SkeletonTexture = cc.Class.extend({ +sp.SkeletonTexture = function (image) { + sp.spine.Texture.call(this, image); +}; +cc.inherits(sp.SkeletonTexture, sp.spine.Texture); +cc.extend(sp.SkeletonTexture.prototype, { name: 'sp.SkeletonTexture', _texture: null, @@ -60,9 +64,4 @@ sp.SkeletonTexture = cc.Class.extend({ cc.glBindTexture2D(this._texture); } } -}); - -var proto = sp.SkeletonTexture.prototype; -cc.extend(proto, spine.Texture.prototype); -// proto.constructor = spine.Texture; - +}); \ No newline at end of file diff --git a/extensions/spine/CCSkeletonWebGLRenderCmd.js b/extensions/spine/CCSkeletonWebGLRenderCmd.js index e9fc27601a..221546ed75 100644 --- a/extensions/spine/CCSkeletonWebGLRenderCmd.js +++ b/extensions/spine/CCSkeletonWebGLRenderCmd.js @@ -23,289 +23,289 @@ ****************************************************************************/ (function () { - sp.Skeleton.WebGLRenderCmd = function (renderableObject) { - this._rootCtor(renderableObject); - this._needDraw = true; - this._matrix = new cc.math.Matrix4(); - this._matrix.identity(); - this.vertexType = cc.renderer.VertexType.CUSTOM; - this.setShaderProgram(cc.shaderCache.programForKey(cc.SHADER_POSITION_TEXTURECOLOR)); - }; - var proto = sp.Skeleton.WebGLRenderCmd.prototype = Object.create(cc.Node.WebGLRenderCmd.prototype); - proto.constructor = sp.Skeleton.WebGLRenderCmd; - - proto.uploadData = function (f32buffer, ui32buffer, vertexDataOffset){ +var spine = sp.spine; + +sp.Skeleton.WebGLRenderCmd = function (renderableObject) { + this._rootCtor(renderableObject); + this._needDraw = true; + this._matrix = new cc.math.Matrix4(); + this._matrix.identity(); + this._currTexture = null; + this._currBlendFunc = {}; + this.vertexType = cc.renderer.VertexType.CUSTOM; + this.setShaderProgram(cc.shaderCache.programForKey(cc.SHADER_SPRITE_POSITION_TEXTURECOLOR)); +}; + +var proto = sp.Skeleton.WebGLRenderCmd.prototype = Object.create(cc.Node.WebGLRenderCmd.prototype); +proto.constructor = sp.Skeleton.WebGLRenderCmd; + +proto.uploadData = function (f32buffer, ui32buffer, vertexDataOffset){ + var node = this._node; + var color = this._displayedColor, locSkeleton = node._skeleton; + + var attachment, slot, i, n; + var premultiAlpha = node._premultipliedAlpha; + + locSkeleton.r = color.r / 255; + locSkeleton.g = color.g / 255; + locSkeleton.b = color.b / 255; + locSkeleton.a = this._displayedOpacity / 255; + if (premultiAlpha) { + locSkeleton.r *= locSkeleton.a; + locSkeleton.g *= locSkeleton.a; + locSkeleton.b *= locSkeleton.a; + } + + var debugSlotsInfo = null; + if (this._node._debugSlots) { + debugSlotsInfo = []; + } + + for (i = 0, n = locSkeleton.drawOrder.length; i < n; i++) { + slot = locSkeleton.drawOrder[i]; + if (!slot.attachment) + continue; + attachment = slot.attachment; + + // get the vertices length + var vertCount = 0; + if (attachment instanceof spine.RegionAttachment) { + vertCount = 6; // a quad = two triangles = six vertices + } + else if (attachment instanceof spine.MeshAttachment) { + vertCount = attachment.regionUVs.length / 2; + } + else { + continue; + } - // rendering the cached data first - cc.renderer._batchRendering(); - vertexDataOffset = 0; + // no vertices to render + if (vertCount === 0) { + continue; + } - var node = this._node; - var color = node.getColor(), locSkeleton = node._skeleton; + var regionTextureAtlas = node.getTextureAtlas(attachment); - var textureAtlas, attachment, slot, i, n; - var premultiAlpha = node._premultipliedAlpha; - var blendMode = -1; - var dataInited = false; - var cachedVertices = 0; + // Broken for changing batch info + this._currTexture = regionTextureAtlas.texture.getRealTexture(); + var batchBroken = cc.renderer._updateBatchedInfo(this._currTexture, this._getBlendFunc(slot.data.blendMode, premultiAlpha), this._glProgramState); - var wt = this._worldTransform, mat = this._matrix.mat; - mat[0] = wt.a; - mat[4] = wt.c; - mat[12] = wt.tx; - mat[1] = wt.b; - mat[5] = wt.d; - mat[13] = wt.ty; + // Broken for vertex data overflow + if (!batchBroken && vertexDataOffset + vertCount * 6 > f32buffer.length) { + // render the cached data + cc.renderer._batchRendering(); + batchBroken = true; + } + if (batchBroken) { + vertexDataOffset = 0; + } - this._shaderProgram.use(); - this._shaderProgram._setUniformForMVPMatrixWithMat4(this._matrix); - locSkeleton.r = color.r / 255; - locSkeleton.g = color.g / 255; - locSkeleton.b = color.b / 255; - locSkeleton.a = node.getOpacity() / 255; - if (premultiAlpha) { - locSkeleton.r *= locSkeleton.a; - locSkeleton.g *= locSkeleton.a; - locSkeleton.b *= locSkeleton.a; + // update the vertex buffer + var slotDebugPoints = null; + if (attachment instanceof spine.RegionAttachment) { + slotDebugPoints = this._uploadRegionAttachmentData(attachment, slot, premultiAlpha, f32buffer, ui32buffer, vertexDataOffset); + } + else if (attachment instanceof spine.MeshAttachment) { + this._uploadMeshAttachmentData(attachment, slot, premultiAlpha, f32buffer, ui32buffer, vertexDataOffset); + } + else { + continue; } - var debugSlotsInfo = null; if (this._node._debugSlots) { - debugSlotsInfo = []; + debugSlotsInfo[i] = slotDebugPoints; } - for (i = 0, n = locSkeleton.drawOrder.length; i < n; i++) { - slot = locSkeleton.drawOrder[i]; - if (!slot.attachment) - continue; - attachment = slot.attachment; - - // get the vertices length - var vertCount = 0; - if (attachment instanceof spine.RegionAttachment) { - vertCount = 6; // a quad = two triangles = six vertices - } - else if (attachment instanceof spine.MeshAttachment) { - vertCount = attachment.regionUVs.length / 2; - } - else { - continue; - } - - // no vertices to render - if (vertCount === 0) { - continue; - } - var regionTextureAtlas = node.getTextureAtlas(attachment); - // init data at the first time - if (!dataInited) { - textureAtlas = regionTextureAtlas; - blendMode = slot.data.blendMode; - cc.renderer._updateBatchedInfo(textureAtlas.texture.getRealTexture(), this._getBlendFunc(blendMode, premultiAlpha), this.getShaderProgram()); - dataInited = true; - } + // update the index buffer + if (attachment instanceof spine.RegionAttachment) { + cc.renderer._increaseBatchingSize(vertCount, cc.renderer.VertexType.TRIANGLE); + } else { + cc.renderer._increaseBatchingSize(vertCount, cc.renderer.VertexType.CUSTOM, attachment.triangles); + } - // if data changed or the vertices will be overflow - if ((cachedVertices + vertCount) * 6 > f32buffer.length || - textureAtlas !== regionTextureAtlas || - blendMode !== slot.data.blendMode) { - // render the cached data - cc.renderer._batchRendering(); - vertexDataOffset = 0; - cachedVertices = 0; - - // update the batched info - textureAtlas = regionTextureAtlas; - blendMode = slot.data.blendMode; - cc.renderer._updateBatchedInfo(textureAtlas.texture.getRealTexture(), this._getBlendFunc(blendMode, premultiAlpha), this.getShaderProgram()); - } + // update the index data + vertexDataOffset += vertCount * 6; + } - // update the vertex buffer - var slotDebugPoints = null; - if (attachment instanceof spine.RegionAttachment) { - slotDebugPoints = this._uploadRegionAttachmentData(attachment, slot, premultiAlpha, f32buffer, ui32buffer, vertexDataOffset); - } - else if (attachment instanceof spine.MeshAttachment) { - this._uploadMeshAttachmentData(attachment, slot, premultiAlpha, f32buffer, ui32buffer, vertexDataOffset); - } - else { - continue; - } - - if (this._node._debugSlots) { - debugSlotsInfo[i] = slotDebugPoints; - } + if (node._debugBones || node._debugSlots) { + // flush previous vertices + cc.renderer._batchRendering(); - // update the index buffer - if (attachment instanceof spine.RegionAttachment) { - cc.renderer._increaseBatchingSize(vertCount, cc.renderer.VertexType.TRIANGLE); - } else { - cc.renderer._increaseBatchingSize(vertCount, cc.renderer.VertexType.CUSTOM, attachment.triangles); + var wt = this._worldTransform, mat = this._matrix.mat; + mat[0] = wt.a; + mat[4] = wt.c; + mat[12] = wt.tx; + mat[1] = wt.b; + mat[5] = wt.d; + mat[13] = wt.ty; + cc.kmGLMatrixMode(cc.KM_GL_MODELVIEW); + cc.current_stack.stack.push(cc.current_stack.top); + cc.current_stack.top = this._matrix; + var drawingUtil = cc._drawingUtil; + + if (node._debugSlots && debugSlotsInfo && debugSlotsInfo.length > 0) { + // Slots. + drawingUtil.setDrawColor(0, 0, 255, 255); + drawingUtil.setLineWidth(1); + + for (i = 0, n = locSkeleton.slots.length; i < n; i++) { + var points = debugSlotsInfo[i]; + if (points) { + drawingUtil.drawPoly(points, 4, true); + } } - - // update the index data - cachedVertices += vertCount; - vertexDataOffset += vertCount * 6; } - // render the left vertices - if (cachedVertices > 0) { - cc.renderer._batchRendering(); - } - - if (node._debugBones || node._debugSlots) { - cc.kmGLMatrixMode(cc.KM_GL_MODELVIEW); - cc.current_stack.stack.push(cc.current_stack.top); - cc.current_stack.top = this._matrix; - var drawingUtil = cc._drawingUtil; - - if (node._debugSlots && debugSlotsInfo && debugSlotsInfo.length > 0) { - // Slots. - drawingUtil.setDrawColor(0, 0, 255, 255); - drawingUtil.setLineWidth(1); - - for (i = 0, n = locSkeleton.slots.length; i < n; i++) { - var points = debugSlotsInfo[i]; - if (points) { - drawingUtil.drawPoly(points, 4, true); - } - } + if (node._debugBones) { + // Bone lengths. + var bone; + drawingUtil.setLineWidth(2); + drawingUtil.setDrawColor(255, 0, 0, 255); + + for (i = 0, n = locSkeleton.bones.length; i < n; i++) { + bone = locSkeleton.bones[i]; + var x = bone.data.length * bone.a + bone.worldX; + var y = bone.data.length * bone.c + bone.worldY; + drawingUtil.drawLine(cc.p(bone.worldX, bone.worldY), cc.p(x, y)); } - if (node._debugBones) { - // Bone lengths. - var bone; - drawingUtil.setLineWidth(2); - drawingUtil.setDrawColor(255, 0, 0, 255); - - for (i = 0, n = locSkeleton.bones.length; i < n; i++) { - bone = locSkeleton.bones[i]; - var x = bone.data.length * bone.a + bone.worldX; - var y = bone.data.length * bone.c + bone.worldY; - drawingUtil.drawLine(cc.p(bone.worldX, bone.worldY), cc.p(x, y)); - } - - // Bone origins. - drawingUtil.setPointSize(4); - drawingUtil.setDrawColor(0, 0, 255, 255); // Root bone is blue. + // Bone origins. + drawingUtil.setPointSize(4); + drawingUtil.setDrawColor(0, 0, 255, 255); // Root bone is blue. - for (i = 0, n = locSkeleton.bones.length; i < n; i++) { - bone = locSkeleton.bones[i]; - drawingUtil.drawPoint(cc.p(bone.worldX, bone.worldY)); - if (i == 0) { - drawingUtil.setDrawColor(0, 255, 0, 255); - } + for (i = 0, n = locSkeleton.bones.length; i < n; i++) { + bone = locSkeleton.bones[i]; + drawingUtil.drawPoint(cc.p(bone.worldX, bone.worldY)); + if (i == 0) { + drawingUtil.setDrawColor(0, 255, 0, 255); } } - cc.kmGLPopMatrix(); } + cc.kmGLPopMatrix(); + } + + return 0; +}; + +proto._getBlendFunc = function (blendMode, premultiAlpha) { + var ret = this._currBlendFunc; + switch (blendMode) { + case spine.BlendMode.Normal: + ret.src = premultiAlpha ? cc.ONE : cc.SRC_ALPHA; + ret.dst = cc.ONE_MINUS_SRC_ALPHA; + break; + case spine.BlendMode.Additive: + ret.src = premultiAlpha ? cc.ONE : cc.SRC_ALPHA; + ret.dst = cc.ONE; + break; + case spine.BlendMode.Multiply: + ret.src = cc.DST_COLOR; + ret.dst = cc.ONE_MINUS_SRC_ALPHA; + break; + case spine.BlendMode.Screen: + ret.src = cc.ONE; + ret.dst = cc.ONE_MINUS_SRC_COLOR; + break; + default: + ret = this._node._blendFunc; + break; + } + + return ret; +}; + +proto._createChildFormSkeletonData = function(){}; + +proto._updateChild = function(){}; + +proto._uploadRegionAttachmentData = function(attachment, slot, premultipliedAlpha, f32buffer, ui32buffer, vertexDataOffset) { + // the vertices in format: + // [ + // X1, Y1, C1R, C1G, C1B, C1A, U1, V1, // bottom left + // X2, Y2, C2R, C2G, C2B, C2A, U2, V2, // top left + // X3, Y3, C3R, C3G, C3B, C3A, U3, V3, // top right + // X4, Y4, C4R, C4G, C4B, C4A, U4, V4 // bottom right + // ] + // + var nodeColor = this._displayedColor; + var nodeR = nodeColor.r, + nodeG = nodeColor.g, + nodeB = nodeColor.b, + nodeA = this._displayedOpacity; + var vertices = attachment.updateWorldVertices(slot, premultipliedAlpha); + var wt = this._worldTransform, + wa = wt.a, wb = wt.b, wc = wt.c, wd = wt.d, + wx = wt.tx, wy = wt.ty, + z = this._node.vertexZ; + + var offset = vertexDataOffset; + // generate 6 vertices data (two triangles) from the quad vertices + // using two angles : (0, 1, 2) & (0, 2, 3) + for (var i = 0; i < 6; i++) { + var srcIdx = i < 4 ? i % 3 : i - 2; + var vx = vertices[srcIdx * 8], + vy = vertices[srcIdx * 8 + 1]; + var x = vx * wa + vy * wb + wx, + y = vx * wc + vy * wd + wy; + var r = vertices[srcIdx * 8 + 2] * nodeR, + g = vertices[srcIdx * 8 + 3] * nodeG, + b = vertices[srcIdx * 8 + 4] * nodeB, + a = vertices[srcIdx * 8 + 5] * nodeA; + var color = ((a<<24) | (b<<16) | (g<<8) | r); + f32buffer[offset] = x; + f32buffer[offset + 1] = y; + f32buffer[offset + 2] = z; + ui32buffer[offset + 3] = color; + f32buffer[offset + 4] = vertices[srcIdx * 8 + 6]; + f32buffer[offset + 5] = vertices[srcIdx * 8 + 7]; + offset += 6; + } + + if (this._node._debugSlots) { + // return the quad points info if debug slot enabled + var VERTEX = spine.RegionAttachment; + return [ + cc.p(vertices[VERTEX.X1], vertices[VERTEX.Y1]), + cc.p(vertices[VERTEX.X2], vertices[VERTEX.Y2]), + cc.p(vertices[VERTEX.X3], vertices[VERTEX.Y3]), + cc.p(vertices[VERTEX.X4], vertices[VERTEX.Y4]) + ]; + } +}; + +proto._uploadMeshAttachmentData = function(attachment, slot, premultipliedAlpha, f32buffer, ui32buffer, vertexDataOffset) { + var wt = this._worldTransform, + wa = wt.a, wb = wt.b, wc = wt.c, wd = wt.d, + wx = wt.tx, wy = wt.ty, + z = this._node.vertexZ; + // get the vertex data + var vertices = attachment.updateWorldVertices(slot, premultipliedAlpha); + var offset = vertexDataOffset; + var nodeColor = this._displayedColor; + var nodeR = nodeColor.r, + nodeG = nodeColor.g, + nodeB = nodeColor.b, + nodeA = this._displayedOpacity; + for (var i = 0, n = vertices.length; i < n; i += 8) { + var vx = vertices[i], + vy = vertices[i + 1]; + var x = vx * wa + vy * wb + wx, + y = vx * wc + vy * wd + wy; + var r = vertices[i + 2] * nodeR, + g = vertices[i + 3] * nodeG, + b = vertices[i + 4] * nodeB, + a = vertices[i + 5] * nodeA; + var color = ((a<<24) | (b<<16) | (g<<8) | r); + + f32buffer[offset] = x; + f32buffer[offset + 1] = y; + f32buffer[offset + 2] = z; + ui32buffer[offset + 3] = color; + f32buffer[offset + 4] = vertices[i + 6]; + f32buffer[offset + 5] = vertices[i + 7]; + offset += 6; + } +}; - return 0; - }; - - proto._getBlendFunc = function (blendMode, premultiAlpha) { - var ret = {}; - switch (blendMode) { - case spine.BlendMode.Normal: - ret.src = premultiAlpha ? cc.ONE : cc.SRC_ALPHA; - ret.dst = cc.ONE_MINUS_SRC_ALPHA; - break; - case spine.BlendMode.Additive: - ret.src = premultiAlpha ? cc.ONE : cc.SRC_ALPHA; - ret.dst = cc.ONE; - break; - case spine.BlendMode.Multiply: - ret.src = cc.DST_COLOR; - ret.dst = cc.ONE_MINUS_SRC_ALPHA; - break; - case spine.BlendMode.Screen: - ret.src = cc.ONE; - ret.dst = cc.ONE_MINUS_SRC_COLOR; - break; - default: - ret = this._node._blendFunc; - break; - } - - return ret; - }; - - proto._createChildFormSkeletonData = function () { - }; - - proto._updateChild = function () { - }; - - proto._uploadRegionAttachmentData = function(attachment, slot, premultipliedAlpha, f32buffer, ui32buffer, vertexDataOffset) { - // the vertices in format: - // [ - // X1, Y1, C1R, C1G, C1B, C1A, U1, V1, // bottom left - // X2, Y2, C2R, C2G, C2B, C2A, U2, V2, // top left - // X3, Y3, C3R, C3G, C3B, C3A, U3, V3, // top right - // X4, Y4, C4R, C4G, C4B, C4A, U4, V4 // bottom right - // ] - // - var nodeColor = this._displayedColor; - var nodeR = nodeColor.r, - nodeG = nodeColor.g, - nodeB = nodeColor.b, - nodeA = nodeColor.a; - var vertices = attachment.updateWorldVertices(slot, premultipliedAlpha); - var offset = vertexDataOffset; - // generate 6 vertices data (two triangles) from the quad vertices - // using two angles : (0, 1, 2) & (0, 2, 3) - for (var i = 0; i < 6; i++) { - var srcIdx = i < 4 ? i % 3 : i - 2; - var r = vertices[srcIdx * 8 + 2] * nodeR, - g = vertices[srcIdx * 8 + 3] * nodeG, - b = vertices[srcIdx * 8 + 4] * nodeB, - a = vertices[srcIdx * 8 + 5] * nodeA; - var color = ((a<<24) | (b<<16) | (g<<8) | r); - f32buffer[offset] = vertices[srcIdx * 8]; - f32buffer[offset + 1] = vertices[srcIdx * 8 + 1]; - f32buffer[offset + 2] = this._node.vertexZ; - ui32buffer[offset + 3] = color; - f32buffer[offset + 4] = vertices[srcIdx * 8 + 6]; - f32buffer[offset + 5] = vertices[srcIdx * 8 + 7]; - offset += 6; - } - - if (this._node._debugSlots) { - // return the quad points info if debug slot enabled - var VERTEX = spine.RegionAttachment; - return [ - cc.p(vertices[VERTEX.X1], vertices[VERTEX.Y1]), - cc.p(vertices[VERTEX.X2], vertices[VERTEX.Y2]), - cc.p(vertices[VERTEX.X3], vertices[VERTEX.Y3]), - cc.p(vertices[VERTEX.X4], vertices[VERTEX.Y4]) - ]; - } - }; - - proto._uploadMeshAttachmentData = function(attachment, slot, premultipliedAlpha, f32buffer, ui32buffer, vertexDataOffset) { - // get the vertex data - var vertices = attachment.updateWorldVertices(slot, premultipliedAlpha); - var offset = vertexDataOffset; - var nodeColor = this._displayedColor; - var nodeR = nodeColor.r, - nodeG = nodeColor.g, - nodeB = nodeColor.b, - nodeA = nodeColor.a; - for (var i = 0, n = vertices.length; i < n; i += 8) { - var r = vertices[i + 2] * nodeR, - g = vertices[i + 3] * nodeG, - b = vertices[i + 4] * nodeB, - a = vertices[i + 5] * nodeA; - var color = ((a<<24) | (b<<16) | (g<<8) | r); - - f32buffer[offset] = vertices[i]; - f32buffer[offset + 1] = vertices[i + 1]; - f32buffer[offset + 2] = this._node.vertexZ; - ui32buffer[offset + 3] = color; - f32buffer[offset + 4] = vertices[i + 6]; - f32buffer[offset + 5] = vertices[i + 7]; - offset += 6; - } - }; })(); diff --git a/extensions/spine/LICENSE b/extensions/spine/LICENSE new file mode 100644 index 0000000000..daceab94a4 --- /dev/null +++ b/extensions/spine/LICENSE @@ -0,0 +1,27 @@ +Spine Runtimes Software License v2.5 + +Copyright (c) 2013-2016, Esoteric Software +All rights reserved. + +You are granted a perpetual, non-exclusive, non-sublicensable, and +non-transferable license to use, install, execute, and perform the Spine +Runtimes software and derivative works solely for personal or internal +use. Without the written permission of Esoteric Software (see Section 2 of +the Spine Software License Agreement), you may not (a) modify, translate, +adapt, or develop new applications using the Spine Runtimes or otherwise +create derivative works or improvements of the Spine Runtimes or (b) remove, +delete, alter, or obscure any trademarks or any copyright, trademark, patent, +or other intellectual property or proprietary rights notices on or in the +Software, including any copy thereof. Redistributions in binary or source +form must include this license and terms. + +THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE "AS IS" AND ANY EXPRESS OR +IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO +EVENT SHALL ESOTERIC SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, BUSINESS INTERRUPTION, OR LOSS OF +USE, DATA, OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. \ No newline at end of file diff --git a/extensions/spine/Spine.js b/extensions/spine/Spine.js index 401e6b84c3..c845c19f41 100644 --- a/extensions/spine/Spine.js +++ b/extensions/spine/Spine.js @@ -1,3 +1,5 @@ +// Spine runtime version 3.5.35 + var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } @@ -1096,7 +1098,7 @@ var spine; } } if (entry.mixDuration > 0) - this.queueEvents(from, animationTime); + this.queueEvents(from, animationTime); this.events.length = 0; from.nextAnimationLast = animationTime; from.nextTrackLast = from.trackTime; @@ -4239,13 +4241,12 @@ var spine; var scale = this.scale; attachment.worldVerticesLength = verticesLength; var vertices = map.vertices; - var scaledVertices = spine.Utils.toFloatArray(vertices); if (verticesLength == vertices.length) { if (scale != 1) { for (var i = 0, n = vertices.length; i < n; i++) - scaledVertices[i] *= scale; + vertices[i] *= scale; } - attachment.vertices = scaledVertices; + attachment.vertices = spine.Utils.toFloatArray(vertices); return; } var weights = new Array(); @@ -5352,4 +5353,6 @@ var spine; }()); spine.TimeKeeper = TimeKeeper; })(spine || (spine = {})); -//# sourceMappingURL=spine-core.js.map \ No newline at end of file + +var sp = sp || {}; +sp.spine = spine; From f65a2303c15dd8eba797c447980772ec7c88c36e Mon Sep 17 00:00:00 2001 From: pandamicro Date: Fri, 14 Jul 2017 12:07:00 +0800 Subject: [PATCH 167/206] Fix action recycling issue with lock --- cocos2d/actions/CCActionInterval.js | 2 +- cocos2d/core/CCActionManager.js | 9 ++++++--- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/cocos2d/actions/CCActionInterval.js b/cocos2d/actions/CCActionInterval.js index 74a855748e..b7149df915 100644 --- a/cocos2d/actions/CCActionInterval.js +++ b/cocos2d/actions/CCActionInterval.js @@ -1083,7 +1083,7 @@ cc.RotateTo = cc.ActionInterval.extend(/** @lends cc.RotateTo# */{ initWithDuration: function (duration, deltaAngleX, deltaAngleY) { if (cc.ActionInterval.prototype.initWithDuration.call(this, duration)) { this._dstAngleX = deltaAngleX || 0; - this._dstAngleY = deltaAngleY || this._dstAngleX; + this._dstAngleY = deltaAngleY !== undefined ? deltaAngleY : this._dstAngleX; return true; } return false; diff --git a/cocos2d/core/CCActionManager.js b/cocos2d/core/CCActionManager.js index 9ecc3c4886..c0777396a6 100644 --- a/cocos2d/core/CCActionManager.js +++ b/cocos2d/core/CCActionManager.js @@ -36,6 +36,7 @@ cc.HashElement = function () { this.actionIndex = 0; this.currentAction = null; //CCAction this.paused = false; + this.lock = false; }; /** @@ -84,6 +85,7 @@ cc.ActionManager = cc.Class.extend(/** @lends cc.ActionManager# */{ element.currentAction = null; element.paused = false; element.target = null; + element.lock = false; this._elementPool.push(element); }, @@ -303,7 +305,7 @@ cc.ActionManager = cc.Class.extend(/** @lends cc.ActionManager# */{ _deleteHashElement:function (element) { var ret = false; - if (element) { + if (element && !element.lock) { if (this._hashTargets[element.target.__instanceId]) { delete this._hashTargets[element.target.__instanceId]; var targets = this._arrayTargets; @@ -329,6 +331,7 @@ cc.ActionManager = cc.Class.extend(/** @lends cc.ActionManager# */{ this._currentTarget = locTargets[elt]; locCurrTarget = this._currentTarget; if (!locCurrTarget.paused && locCurrTarget.actions) { + locCurrTarget.lock = true; // The 'actions' CCMutableArray may change while inside this loop. for (locCurrTarget.actionIndex = 0; locCurrTarget.actionIndex < locCurrTarget.actions.length; locCurrTarget.actionIndex++) { locCurrTarget.currentAction = locCurrTarget.actions[locCurrTarget.actionIndex]; @@ -338,16 +341,16 @@ cc.ActionManager = cc.Class.extend(/** @lends cc.ActionManager# */{ //use for speed locCurrTarget.currentAction.step(dt * ( locCurrTarget.currentAction._speedMethod ? locCurrTarget.currentAction._speed : 1 ) ); - if (locCurrTarget.currentAction.isDone()) { + if (locCurrTarget.currentAction && locCurrTarget.currentAction.isDone()) { locCurrTarget.currentAction.stop(); var action = locCurrTarget.currentAction; - // Make currentAction nil to prevent removeAction from salvaging it. locCurrTarget.currentAction = null; this.removeAction(action); } locCurrTarget.currentAction = null; } + locCurrTarget.lock = false; } // only delete currentTarget if no actions were scheduled during the cycle (issue #481) if (locCurrTarget.actions.length === 0) { From 1d1c5e2d8ee219f378b9b69a72a9d6336b254b88 Mon Sep 17 00:00:00 2001 From: Nick Dong Date: Wed, 26 Jul 2017 11:39:28 +0700 Subject: [PATCH 168/206] Fix 'titleColor' attribute name for UIButton https://github.com/cocos2d/cocos2d-html5/blob/develop/extensions/ccui/uiwidgets/UIButton.js#L803 --- extensions/ccui/uiwidgets/UIButton.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/ccui/uiwidgets/UIButton.js b/extensions/ccui/uiwidgets/UIButton.js index 4feff73686..4741e2e767 100644 --- a/extensions/ccui/uiwidgets/UIButton.js +++ b/extensions/ccui/uiwidgets/UIButton.js @@ -33,7 +33,7 @@ * @property {String} titleFont - The content string font of the button title * @property {Number} titleFontSize - The content string font size of the button title * @property {String} titleFontName - The content string font name of the button title - * @property {cc.Color} titleFontColor - The content string font color of the button title + * @property {cc.Color} titleColor - The content string font color of the button title * @property {Boolean} pressedActionEnabled - Indicate whether button has zoom effect when clicked */ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ From 6efd2a21c4ae49e670927534700ac5332f027a78 Mon Sep 17 00:00:00 2001 From: Administrator <363012115@qq.com> Date: Tue, 8 Aug 2017 15:55:36 +0800 Subject: [PATCH 169/206] fix the problem of loading local resources failed when the protocol is 'file://' --- CCBoot.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/CCBoot.js b/CCBoot.js index 06ec6e67df..8f4bafd3cd 100644 --- a/CCBoot.js +++ b/CCBoot.js @@ -797,7 +797,7 @@ cc.loader = (function () { xhr.setRequestHeader("Accept-Charset", "utf-8"); xhr.onreadystatechange = function () { if (xhr.readyState === 4) - xhr.status === 200 ? cb(null, xhr.responseText) : cb({status:xhr.status, errorMessage:errInfo}, null); + (xhr.status === 200||xhr.status === 0) ? cb(null, xhr.responseText) : cb({status:xhr.status, errorMessage:errInfo}, null); }; } else { if (xhr.overrideMimeType) xhr.overrideMimeType("text\/plain; charset=utf-8"); @@ -806,7 +806,7 @@ cc.loader = (function () { clearTimeout(xhr._timeoutId); } if (xhr.readyState === 4) { - xhr.status === 200 ? cb(null, xhr.responseText) : cb({status:xhr.status, errorMessage:errInfo}, null); + (xhr.status === 200||xhr.status === 0) ? cb(null, xhr.responseText) : cb({status:xhr.status, errorMessage:errInfo}, null); } }; xhr.onerror = function () { @@ -845,7 +845,7 @@ cc.loader = (function () { window.msg = arrayBuffer; } if (xhr.readyState === 4) { - xhr.status === 200 ? cb(null, xhr.response) : cb({status:xhr.status, errorMessage:errInfo}, null); + (xhr.status === 200||xhr.status === 0) ? cb(null, xhr.response) : cb({status:xhr.status, errorMessage:errInfo}, null); } }; xhr.onerror = function(){ From 87c456cd78cba6ffc7cdbaa5de0e90d7a05f98dd Mon Sep 17 00:00:00 2001 From: Danilo Neves Cruz Date: Sat, 2 Sep 2017 03:59:59 -0300 Subject: [PATCH 170/206] fix cc.GLProgramState.apply --- cocos2d/shaders/CCGLProgramState.js | 12 +----------- 1 file changed, 1 insertion(+), 11 deletions(-) diff --git a/cocos2d/shaders/CCGLProgramState.js b/cocos2d/shaders/CCGLProgramState.js index 0a9cef01cb..80e25b3ade 100644 --- a/cocos2d/shaders/CCGLProgramState.js +++ b/cocos2d/shaders/CCGLProgramState.js @@ -43,7 +43,6 @@ cc.UniformValue = function (uniform, glprogram) { this._glprogram = glprogram; this._value = null; - this._currentBoundValue = null; this._type = -1; }; @@ -105,12 +104,6 @@ cc.UniformValue.prototype = { }, apply: function apply() { - if (this._currentBoundValue === this._value - && this._type !== types.GL_CALLBACK) { - return; - } - - this._currentBoundValue = this._value; switch (this._type) { case types.GL_INT: this._glprogram.setUniformLocationWith1i(this._uniform.location, this._value); @@ -180,10 +173,7 @@ cc.GLProgramState.prototype = { } for (var i = 0; i < this._uniforms.length; ++i) { - var uniform = this._uniforms[i]; - if (uniform._currentBoundValue !== uniform._value) { - uniform.apply(); - } + this._uniforms[i].apply(); } }, From 444c237e145fba57785f9128bce53afb3fa9cb29 Mon Sep 17 00:00:00 2001 From: Danilo Neves Cruz Date: Sat, 2 Sep 2017 21:35:32 -0300 Subject: [PATCH 171/206] fix cc.GLProgram uniform cache --- cocos2d/shaders/CCGLProgram.js | 327 +++++++++++++++++----------- cocos2d/shaders/CCGLProgramState.js | 69 +++--- 2 files changed, 222 insertions(+), 174 deletions(-) diff --git a/cocos2d/shaders/CCGLProgram.js b/cocos2d/shaders/CCGLProgram.js index 8708db54f5..67e23db2d7 100644 --- a/cocos2d/shaders/CCGLProgram.js +++ b/cocos2d/shaders/CCGLProgram.js @@ -42,28 +42,22 @@ cc.GLProgram = cc.Class.extend(/** @lends cc.GLProgram# */{ _projectionUpdated: -1, // Uniform cache - _updateUniformLocation: function (location) { - if (!location) + _updateUniform: function (name) { + if (!name) return false; - var updated; - var element = this._hashForUniforms[location]; - - if (!element) { - element = [ - arguments[1], - arguments[2], - arguments[3], - arguments[4] - ]; - this._hashForUniforms[location] = element; + var updated = false; + var element = this._hashForUniforms[name]; + var args = Array.isArray(arguments[1]) ? arguments[1] : + Array.prototype.slice.call(arguments, 1); + + if (!element || element.length !== args.length) { + this._hashForUniforms[name] = args.slice(); updated = true; } else { - updated = false; - var count = arguments.length - 1; - for (var i = 0; i < count; ++i) { - if (arguments[i + 1] !== element[i]) { - element[i] = arguments[i + 1]; + for (var i = 0; i < args.length; i += 1) { + if (args[i] !== element[i]) { + element[i] = args[i]; updated = true; } } @@ -169,9 +163,7 @@ cc.GLProgram = cc.Class.extend(/** @lends cc.GLProgram# */{ if (this._fragShader) locGL.attachShader(this._programObj, this._fragShader); - for (var key in this._hashForUniforms) { - delete this._hashForUniforms[key]; - } + if (Object.keys(this._hashForUniforms).length > 0) this._hashForUniforms = {}; cc.checkGLErrorDebug(); return true; @@ -231,7 +223,7 @@ cc.GLProgram = cc.Class.extend(/** @lends cc.GLProgram# */{ } this._glContext.linkProgram(this._programObj); - + if (this._vertShader) this._glContext.deleteShader(this._vertShader); if (this._fragShader) @@ -268,18 +260,13 @@ cc.GLProgram = cc.Class.extend(/** @lends cc.GLProgram# */{ * cc.UNIFORM_SAMPLER */ updateUniforms: function () { - this._uniforms[cc.UNIFORM_PMATRIX_S] = this._glContext.getUniformLocation(this._programObj, cc.UNIFORM_PMATRIX_S); - this._uniforms[cc.UNIFORM_MVMATRIX_S] = this._glContext.getUniformLocation(this._programObj, cc.UNIFORM_MVMATRIX_S); - this._uniforms[cc.UNIFORM_MVPMATRIX_S] = this._glContext.getUniformLocation(this._programObj, cc.UNIFORM_MVPMATRIX_S); - this._uniforms[cc.UNIFORM_TIME_S] = this._glContext.getUniformLocation(this._programObj, cc.UNIFORM_TIME_S); - this._uniforms[cc.UNIFORM_SINTIME_S] = this._glContext.getUniformLocation(this._programObj, cc.UNIFORM_SINTIME_S); - this._uniforms[cc.UNIFORM_COSTIME_S] = this._glContext.getUniformLocation(this._programObj, cc.UNIFORM_COSTIME_S); - + [cc.UNIFORM_PMATRIX_S, cc.UNIFORM_MVMATRIX_S, cc.UNIFORM_MVPMATRIX_S, + cc.UNIFORM_TIME_S, cc.UNIFORM_SINTIME_S, cc.UNIFORM_COSTIME_S, + cc.UNIFORM_RANDOM01_S, cc.UNIFORM_SAMPLER_S].forEach(function(name) { + this._addUniformLocation(name); + }.bind(this)); this._usesTime = (this._uniforms[cc.UNIFORM_TIME_S] != null || this._uniforms[cc.UNIFORM_SINTIME_S] != null || this._uniforms[cc.UNIFORM_COSTIME_S] != null); - this._uniforms[cc.UNIFORM_RANDOM01_S] = this._glContext.getUniformLocation(this._programObj, cc.UNIFORM_RANDOM01_S); - this._uniforms[cc.UNIFORM_SAMPLER_S] = this._glContext.getUniformLocation(this._programObj, cc.UNIFORM_SAMPLER_S); - this.use(); // Since sample most probably won't change, set it to 0 now. this.setUniformLocationWith1i(this._uniforms[cc.UNIFORM_SAMPLER_S], 0); @@ -287,7 +274,9 @@ cc.GLProgram = cc.Class.extend(/** @lends cc.GLProgram# */{ _addUniformLocation: function (name) { var location = this._glContext.getUniformLocation(this._programObj, name); + if (location) location._name = name; this._uniforms[name] = location; + return location; }, /** @@ -301,7 +290,7 @@ cc.GLProgram = cc.Class.extend(/** @lends cc.GLProgram# */{ if (!this._programObj) throw new Error("cc.GLProgram.getUniformLocationForName(): Invalid operation. Cannot get uniform location when program is not initialized"); - var location = this._uniforms[name] || this._glContext.getUniformLocation(this._programObj, name); + var location = this._uniforms[name] || this._addUniformLocation(name); return location; }, @@ -327,16 +316,15 @@ cc.GLProgram = cc.Class.extend(/** @lends cc.GLProgram# */{ * @param {Number} i1 */ setUniformLocationWith1i: function (location, i1) { - var gl = this._glContext; - if (typeof location === 'string') { - var updated = this._updateUniformLocation(location, i1); - if (updated) { - var locObj = this.getUniformLocationForName(location); - gl.uniform1i(locObj, i1); + var isString = typeof location === 'string'; + var name = isString ? location : location && location._name; + if (name) { + if (this._updateUniform(name, i1)) { + if (isString) location = this.getUniformLocationForName(name); + this._glContext.uniform1i(location, i1); } - } - else { - gl.uniform1i(location, i1); + } else { + this._glContext.uniform1i(location, i1); } }, @@ -347,16 +335,15 @@ cc.GLProgram = cc.Class.extend(/** @lends cc.GLProgram# */{ * @param {Number} i2 */ setUniformLocationWith2i: function (location, i1, i2) { - var gl = this._glContext; - if (typeof location === 'string') { - var updated = this._updateUniformLocation(location, i1, i2); - if (updated) { - var locObj = this.getUniformLocationForName(location); - gl.uniform2i(locObj, i1, i2); + var isString = typeof location === 'string'; + var name = isString ? location : location && location._name; + if (name) { + if (this._updateUniform(name, i1, i2)) { + if (isString) location = this.getUniformLocationForName(name); + this._glContext.uniform2i(location, i1, i2); } - } - else { - gl.uniform2i(location, i1, i2); + } else { + this._glContext.uniform2i(location, i1, i2); } }, @@ -368,16 +355,15 @@ cc.GLProgram = cc.Class.extend(/** @lends cc.GLProgram# */{ * @param {Number} i3 */ setUniformLocationWith3i: function (location, i1, i2, i3) { - var gl = this._glContext; - if (typeof location === 'string') { - var updated = this._updateUniformLocation(location, i1, i2, i3); - if (updated) { - var locObj = this.getUniformLocationForName(location); - gl.uniform3i(locObj, i1, i2, i3); + var isString = typeof location === 'string'; + var name = isString ? location : location && location._name; + if (name) { + if (this._updateUniform(name, i1, i2, i3)) { + if (isString) location = this.getUniformLocationForName(name); + this._glContext.uniform3i(location, i1, i2, i3); } - } - else { - gl.uniform3i(location, i1, i2, i3); + } else { + this._glContext.uniform3i(location, i1, i2, i3); } }, @@ -390,16 +376,15 @@ cc.GLProgram = cc.Class.extend(/** @lends cc.GLProgram# */{ * @param {Number} i4 */ setUniformLocationWith4i: function (location, i1, i2, i3, i4) { - var gl = this._glContext; - if (typeof location === 'string') { - var updated = this._updateUniformLocation(location, i1, i2, i3, i4); - if (updated) { - var locObj = this.getUniformLocationForName(location); - gl.uniform4i(locObj, i1, i2, i3, i4); + var isString = typeof location === 'string'; + var name = isString ? location : location && location._name; + if (name) { + if (this._updateUniform(name, i1, i2, i3, i4)) { + if (isString) location = this.getUniformLocationForName(name); + this._glContext.uniform4i(location, i1, i2, i3, i4); } - } - else { - gl.uniform4i(location, i1, i2, i3, i4); + } else { + this._glContext.uniform4i(location, i1, i2, i3, i4); } }, @@ -410,8 +395,16 @@ cc.GLProgram = cc.Class.extend(/** @lends cc.GLProgram# */{ * @param {Number} numberOfArrays */ setUniformLocationWith2iv: function (location, intArray) { - var locObj = typeof location === 'string' ? this.getUniformLocationForName(location) : location; - this._glContext.uniform2iv(locObj, intArray); + var isString = typeof location === 'string'; + var name = isString ? location : location && location._name; + if (name) { + if (this._updateUniform(name, intArray)) { + if (isString) location = this.getUniformLocationForName(name); + this._glContext.uniform2iv(location, intArray); + } + } else { + this._glContext.uniform2iv(location, intArray); + } }, /** @@ -420,8 +413,16 @@ cc.GLProgram = cc.Class.extend(/** @lends cc.GLProgram# */{ * @param {Int32Array} intArray */ setUniformLocationWith3iv: function (location, intArray) { - var locObj = typeof location === 'string' ? this.getUniformLocationForName(location) : location; - this._glContext.uniform3iv(locObj, intArray); + var isString = typeof location === 'string'; + var name = isString ? location : location && location._name; + if (name) { + if (this._updateUniform(name, intArray)) { + if (isString) location = this.getUniformLocationForName(name); + this._glContext.uniform3iv(location, intArray); + } + } else { + this._glContext.uniform3iv(location, intArray); + } }, /** @@ -430,8 +431,16 @@ cc.GLProgram = cc.Class.extend(/** @lends cc.GLProgram# */{ * @param {Int32Array} intArray */ setUniformLocationWith4iv: function (location, intArray) { - var locObj = typeof location === 'string' ? this.getUniformLocationForName(location) : location; - this._glContext.uniform4iv(locObj, intArray); + var isString = typeof location === 'string'; + var name = isString ? location : location && location._name; + if (name) { + if (this._updateUniform(name, intArray)) { + if (isString) location = this.getUniformLocationForName(name); + this._glContext.uniform4iv(location, intArray); + } + } else { + this._glContext.uniform4iv(location, intArray); + } }, /** @@ -449,16 +458,15 @@ cc.GLProgram = cc.Class.extend(/** @lends cc.GLProgram# */{ * @param {Number} f1 */ setUniformLocationWith1f: function (location, f1) { - var gl = this._glContext; - if (typeof location === 'string') { - var updated = this._updateUniformLocation(location, f1); - if (updated) { - var locObj = this.getUniformLocationForName(location); - gl.uniform1f(locObj, f1); + var isString = typeof location === 'string'; + var name = isString ? location : location && location._name; + if (name) { + if (this._updateUniform(name, f1)) { + if (isString) location = this.getUniformLocationForName(name); + this._glContext.uniform1f(location, f1); } - } - else { - gl.uniform1f(location, f1); + } else { + this._glContext.uniform1f(location, f1); } }, @@ -469,16 +477,15 @@ cc.GLProgram = cc.Class.extend(/** @lends cc.GLProgram# */{ * @param {Number} f2 */ setUniformLocationWith2f: function (location, f1, f2) { - var gl = this._glContext; - if (typeof location === 'string') { - var updated = this._updateUniformLocation(location, f1, f2); - if (updated) { - var locObj = this.getUniformLocationForName(location); - gl.uniform2f(locObj, f1, f2); + var isString = typeof location === 'string'; + var name = isString ? location : location && location._name; + if (name) { + if (this._updateUniform(name, f1, f2)) { + if (isString) location = this.getUniformLocationForName(name); + this._glContext.uniform2f(location, f1, f2); } - } - else { - gl.uniform2f(location, f1, f2); + } else { + this._glContext.uniform2f(location, f1, f2); } }, @@ -490,16 +497,15 @@ cc.GLProgram = cc.Class.extend(/** @lends cc.GLProgram# */{ * @param {Number} f3 */ setUniformLocationWith3f: function (location, f1, f2, f3) { - var gl = this._glContext; - if (typeof location === 'string') { - var updated = this._updateUniformLocation(location, f1, f2, f3); - if (updated) { - var locObj = this.getUniformLocationForName(location); - gl.uniform3f(locObj, f1, f2, f3); + var isString = typeof location === 'string'; + var name = isString ? location : location && location._name; + if (name) { + if (this._updateUniform(name, f1, f2, f3)) { + if (isString) location = this.getUniformLocationForName(name); + this._glContext.uniform3f(location, f1, f2, f3); } - } - else { - gl.uniform3f(location, f1, f2, f3); + } else { + this._glContext.uniform3f(location, f1, f2, f3); } }, @@ -512,16 +518,16 @@ cc.GLProgram = cc.Class.extend(/** @lends cc.GLProgram# */{ * @param {Number} f4 */ setUniformLocationWith4f: function (location, f1, f2, f3, f4) { - var gl = this._glContext; - if (typeof location === 'string') { - var updated = this._updateUniformLocation(location, f1, f2, f3, f4); - if (updated) { - var locObj = this.getUniformLocationForName(location); - gl.uniform4f(locObj, f1, f2, f3, f4); + var isString = typeof location === 'string'; + var name = isString ? location : location && location._name; + if (name) { + if (this._updateUniform(name, f1, f2, f3, f4)) { + if (isString) location = this.getUniformLocationForName(name); + this._glContext.uniform4f(location, f1, f2, f3, f4); } - } - else { - gl.uniform4f(location, f1, f2, f3, f4); + } else { + this._glContext.uniform4f(location, f1, f2, f3, f4); + cc.log('uniform4f', f1, f2, f3, f4); } }, @@ -531,8 +537,16 @@ cc.GLProgram = cc.Class.extend(/** @lends cc.GLProgram# */{ * @param {Float32Array} floatArray */ setUniformLocationWith2fv: function (location, floatArray) { - var locObj = typeof location === 'string' ? this.getUniformLocationForName(location) : location; - this._glContext.uniform2fv(locObj, floatArray); + var isString = typeof location === 'string'; + var name = isString ? location : location && location._name; + if (name) { + if (this._updateUniform(name, floatArray)) { + if (isString) location = this.getUniformLocationForName(name); + this._glContext.uniform2fv(location, floatArray); + } + } else { + this._glContext.uniform2fv(location, floatArray); + } }, /** @@ -541,8 +555,16 @@ cc.GLProgram = cc.Class.extend(/** @lends cc.GLProgram# */{ * @param {Float32Array} floatArray */ setUniformLocationWith3fv: function (location, floatArray) { - var locObj = typeof location === 'string' ? this.getUniformLocationForName(location) : location; - this._glContext.uniform3fv(locObj, floatArray); + var isString = typeof location === 'string'; + var name = isString ? location : location && location._name; + if (name) { + if (this._updateUniform(name, floatArray)) { + if (isString) location = this.getUniformLocationForName(name); + this._glContext.uniform3fv(location, floatArray); + } + } else { + this._glContext.uniform3fv(location, floatArray); + } }, /** @@ -551,17 +573,53 @@ cc.GLProgram = cc.Class.extend(/** @lends cc.GLProgram# */{ * @param {Float32Array} floatArray */ setUniformLocationWith4fv: function (location, floatArray) { - var locObj = typeof location === 'string' ? this.getUniformLocationForName(location) : location; - this._glContext.uniform4fv(locObj, floatArray); + var isString = typeof location === 'string'; + var name = isString ? location : location && location._name; + if (name) { + if (this._updateUniform(name, floatArray)) { + if (isString) location = this.getUniformLocationForName(name); + this._glContext.uniform4fv(location, floatArray); + } + } else { + this._glContext.uniform4fv(location, floatArray); + cc.log('uniform4fv', floatArray); + } }, + + /** + * calls glUniformMatrix2fv + * @param {WebGLUniformLocation|String} location + * @param {Float32Array} matrixArray + */ + setUniformLocationWithMatrix2fv: function (location, matrixArray) { + var isString = typeof location === 'string'; + var name = isString ? location : location && location._name; + if (name) { + if (this._updateUniform(name, matrixArray)) { + if (isString) location = this.getUniformLocationForName(name); + this._glContext.uniformMatrix2fv(location, false, matrixArray); + } + } else { + this._glContext.uniformMatrix2fv(location, false, matrixArray); + } + }, + /** * calls glUniformMatrix3fv * @param {WebGLUniformLocation|String} location * @param {Float32Array} matrixArray */ setUniformLocationWithMatrix3fv: function (location, matrixArray) { - var locObj = typeof location === 'string' ? this.getUniformLocationForName(location) : location; - this._glContext.uniformMatrix3fv(locObj, false, matrixArray); + var isString = typeof location === 'string'; + var name = isString ? location : location && location._name; + if (name) { + if (this._updateUniform(name, matrixArray)) { + if (isString) location = this.getUniformLocationForName(name); + this._glContext.uniformMatrix3fv(location, false, matrixArray); + } + } else { + this._glContext.uniformMatrix3fv(location, false, matrixArray); + } }, /** @@ -570,8 +628,16 @@ cc.GLProgram = cc.Class.extend(/** @lends cc.GLProgram# */{ * @param {Float32Array} matrixArray */ setUniformLocationWithMatrix4fv: function (location, matrixArray) { - var locObj = typeof location === 'string' ? this.getUniformLocationForName(location) : location; - this._glContext.uniformMatrix4fv(locObj, false, matrixArray); + var isString = typeof location === 'string'; + var name = isString ? location : location && location._name; + if (name) { + if (this._updateUniform(name, matrixArray)) { + if (isString) location = this.getUniformLocationForName(name); + this._glContext.uniformMatrix4fv(location, false, matrixArray); + } + } else { + this._glContext.uniformMatrix4fv(location, false, matrixArray); + } }, setUniformLocationF32: function () { @@ -664,25 +730,25 @@ cc.GLProgram = cc.Class.extend(/** @lends cc.GLProgram# */{ * will update the MVP matrix on the MVP uniform if it is different than the previous call for this same shader program. */ setUniformForModelViewProjectionMatrix: function () { - this._glContext.uniformMatrix4fv(this._uniforms[cc.UNIFORM_MVPMATRIX_S], false, + this.setUniformLocationWithMatrix4fv(this._uniforms[cc.UNIFORM_MVPMATRIX_S], cc.getMat4MultiplyValue(cc.projection_matrix_stack.top, cc.modelview_matrix_stack.top)); }, setUniformForModelViewProjectionMatrixWithMat4: function (swapMat4) { cc.kmMat4Multiply(swapMat4, cc.projection_matrix_stack.top, cc.modelview_matrix_stack.top); - this._glContext.uniformMatrix4fv(this._uniforms[cc.UNIFORM_MVPMATRIX_S], false, swapMat4.mat); + this.setUniformLocationWithMatrix4fv(this._uniforms[cc.UNIFORM_MVPMATRIX_S], swapMat4.mat); }, setUniformForModelViewAndProjectionMatrixWithMat4: function () { - this._glContext.uniformMatrix4fv(this._uniforms[cc.UNIFORM_MVMATRIX_S], false, cc.modelview_matrix_stack.top.mat); - this._glContext.uniformMatrix4fv(this._uniforms[cc.UNIFORM_PMATRIX_S], false, cc.projection_matrix_stack.top.mat); + this.setUniformLocationWithMatrix4fv(this._uniforms[cc.UNIFORM_MVMATRIX_S], cc.modelview_matrix_stack.top.mat); + this.setUniformLocationWithMatrix4fv(this._uniforms[cc.UNIFORM_PMATRIX_S], cc.projection_matrix_stack.top.mat); }, _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); + this.setUniformLocationWithMatrix4fv(this._uniforms[cc.UNIFORM_MVMATRIX_S], modelViewMatrix.mat); + this.setUniformLocationWithMatrix4fv(this._uniforms[cc.UNIFORM_PMATRIX_S], cc.projection_matrix_stack.top.mat); }, _updateProjectionUniform: function () { @@ -748,7 +814,7 @@ cc.GLProgram = cc.Class.extend(/** @lends cc.GLProgram# */{ reset: function () { this._vertShader = null; this._fragShader = null; - this._uniforms.length = 0; + if (Object.keys(this._uniforms).length > 0) this._uniforms = {}; // it is already deallocated by android //ccGLDeleteProgram(m_uProgram); @@ -756,10 +822,7 @@ cc.GLProgram = cc.Class.extend(/** @lends cc.GLProgram# */{ this._programObj = null; // Purge uniform hash - for (var key in this._hashForUniforms) { - this._hashForUniforms[key].length = 0; - delete this._hashForUniforms[key]; - } + if (Object.keys(this._hashForUniforms).length > 0) this._hashForUniforms = {}; }, /** diff --git a/cocos2d/shaders/CCGLProgramState.js b/cocos2d/shaders/CCGLProgramState.js index 80e25b3ade..2e9ec348ee 100644 --- a/cocos2d/shaders/CCGLProgramState.js +++ b/cocos2d/shaders/CCGLProgramState.js @@ -24,7 +24,7 @@ THE SOFTWARE. ****************************************************************************/ -var types = +var types = { GL_FLOAT: 0, GL_INT: 1, @@ -50,7 +50,7 @@ cc.UniformValue.prototype = { setFloat: function setFloat(value) { this._value = value; this._type = types.GL_FLOAT; - }, + }, setInt: function setInt(value) { this._value = value; @@ -106,30 +106,28 @@ cc.UniformValue.prototype = { apply: function apply() { switch (this._type) { case types.GL_INT: - this._glprogram.setUniformLocationWith1i(this._uniform.location, this._value); + this._glprogram.setUniformLocationWith1i(this._uniform._location, this._value); break; case types.GL_FLOAT: - this._glprogram.setUniformLocationWith1f(this._uniform.location, this._value); + this._glprogram.setUniformLocationWith1f(this._uniform._location, this._value); break; case types.GL_FLOAT_VEC2: - this._glprogram.setUniformLocationWith2f(this._uniform.location, this._value[0], this._value[1]); + this._glprogram.setUniformLocationWith2fv(this._uniform._location, this._value); break; case types.GL_FLOAT_VEC3: - this._glprogram.setUniformLocationWith3f(this._uniform.location, this._value[0], - this._value[1], this._value[2]); + this._glprogram.setUniformLocationWith3fv(this._uniform._location, this._value); break; case types.GL_FLOAT_VEC4: - this._glprogram.setUniformLocationWith4f(this._uniform.location, this._value[0], - this._value[1], this._value[2], this._value[3]); + this._glprogram.setUniformLocationWith4fv(this._uniform._location, this._value); break; case types.GL_FLOAT_MAT4: - this._glprogram.setUniformLocationWithMatrix4fv(this._uniform.location, this._value); + this._glprogram.setUniformLocationWithMatrix4fv(this._uniform._location, this._value); break; case types.GL_CALLBACK: this._value(this._glprogram, this._uniform); break; case types.GL_TEXTURE: - this._glprogram.setUniformLocationWith1i(this._uniform.location, this._value); + this._glprogram.setUniformLocationWith1i(this._uniform._location, this._value); cc.glBindTexture2DN(this._value, this._textureId); break; default: @@ -140,27 +138,20 @@ cc.UniformValue.prototype = { cc.GLProgramState = function (glprogram) { this._glprogram = glprogram; - this._uniforms = []; - this._uniformsByName = {}; - this._uniformsByLocation = {}; + this._uniforms = {}; this._boundTextureUnits = {}; this._textureUnitIndex = 1; // Start at 1, as CC_Texture0 is bound to 0 var activeUniforms = glprogram._glContext.getProgramParameter(glprogram._programObj, glprogram._glContext.ACTIVE_UNIFORMS); - var count = 0; - for (var i = 0; i < activeUniforms; ++i) { - var uniform = glprogram._glContext.getActiveUniform(glprogram._programObj, i); + for (var i = 0; i < activeUniforms; i += 1) { + var uniform = glprogram._glContext.getActiveUniform(glprogram._programObj, i); if (uniform.name.indexOf("CC_") !== 0) { - uniform.location = glprogram._glContext.getUniformLocation(glprogram._programObj, - uniform.name); - uniform.name = uniform.name.replace("[]", ""); + uniform._location = glprogram._glContext.getUniformLocation(glprogram._programObj, uniform.name); + uniform._location._name = uniform.name; var uniformValue = new cc.UniformValue(uniform, glprogram); - this._uniforms.push(uniformValue); - this._uniformsByName[uniform.name] = count; - this._uniformsByLocation[uniform.location] = count; - count++; + this._uniforms[uniform.name] = uniformValue; } } }; @@ -171,10 +162,10 @@ cc.GLProgramState.prototype = { if (modelView) { this._glprogram._setUniformForMVPMatrixWithMat4(modelView); } - - for (var i = 0; i < this._uniforms.length; ++i) { - this._uniforms[i].apply(); - } + + Object.values(this._uniforms).forEach(function(uniform) { + uniform.apply(); + }); }, setGLProgram: function setGLProgram(glprogram) { @@ -189,16 +180,10 @@ cc.GLProgramState.prototype = { return this._uniforms.length; }, - getUniformValue: function getUniformValue(uniform) - { - if (typeof uniform === 'string') { - return this._uniforms[this._uniformsByName[uniform]]; - } else { - return this._uniforms[this._uniformsByLocation[uniform]]; - } + getUniformValue: function getUniformValue(uniform) { + return this._uniforms[uniform]; }, - // Accepts either string or uniform location setUniformInt: function setUniformInt(uniform, value) { var v = this.getUniformValue(uniform); if (v) { @@ -225,7 +210,7 @@ cc.GLProgramState.prototype = { cc.log("cocos2d: warning: Uniform not found: " + uniform); } }, - + setUniformVec2v: function setUniformVec2v(uniform, value) { var v = this.getUniformValue(uniform); if (v) { @@ -234,7 +219,7 @@ cc.GLProgramState.prototype = { cc.log("cocos2d: warning: Uniform not found: " + uniform); } }, - + setUniformVec3: function setUniformVec3(uniform, v1, v2, v3) { var v = this.getUniformValue(uniform); if (v) { @@ -252,7 +237,7 @@ cc.GLProgramState.prototype = { cc.log("cocos2d: warning: Uniform not found: " + uniform); } }, - + setUniformVec4: function setUniformVec4(uniform, v1, v2, v3, v4) { var v = this.getUniformValue(uniform); if (v) { @@ -271,7 +256,7 @@ cc.GLProgramState.prototype = { } }, - + setUniformMat4: function setUniformMat4(uniform, value) { var v = this.getUniformValue(uniform); if (v) { @@ -291,7 +276,7 @@ cc.GLProgramState.prototype = { } }, - + setUniformTexture: function setUniformTexture(uniform, texture) { var uniformValue = this.getUniformValue(uniform); if (uniformValue) { @@ -300,7 +285,7 @@ cc.GLProgramState.prototype = { uniformValue.setTexture(texture, textureUnit); } else { uniformValue.setTexture(texture, this._textureUnitIndex); - this._boundTextureUnits[uniform] = this._textureUnitIndex++; + this._boundTextureUnits[uniform] = this._textureUnitIndex++; } } } From d3ae8440757d720580aa66f425fdbfebdc8225a2 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Fri, 8 Sep 2017 10:11:12 +0800 Subject: [PATCH 172/206] Improve loader listeners --- CCBoot.js | 76 ++++++++++++++++++++++++++++++++++++++++++++++--------- 1 file changed, 64 insertions(+), 12 deletions(-) diff --git a/CCBoot.js b/CCBoot.js index 06ec6e67df..9cfc1ae2db 100644 --- a/CCBoot.js +++ b/CCBoot.js @@ -801,25 +801,51 @@ cc.loader = (function () { }; } else { if (xhr.overrideMimeType) xhr.overrideMimeType("text\/plain; charset=utf-8"); - xhr.onload = function () { + var loadCallback = function () { + xhr.removeEventListener('load', loadCallback); + xhr.removeEventListener('error', errorCallback); if (xhr._timeoutId >= 0) { clearTimeout(xhr._timeoutId); } + else { + xhr.removeEventListener('timeout', timeoutCallback); + } if (xhr.readyState === 4) { xhr.status === 200 ? cb(null, xhr.responseText) : cb({status:xhr.status, errorMessage:errInfo}, null); } }; - xhr.onerror = function () { + var errorCallback = function () { + xhr.removeEventListener('load', loadCallback); + xhr.removeEventListener('error', errorCallback); + if (xhr._timeoutId >= 0) { + clearTimeout(xhr._timeoutId); + } + else { + xhr.removeEventListener('timeout', timeoutCallback); + } cb({status: xhr.status, errorMessage: errInfo}, null); }; + var timeoutCallback = function () { + xhr.removeEventListener('load', loadCallback); + xhr.removeEventListener('error', errorCallback); + if (xhr._timeoutId >= 0) { + clearTimeout(xhr._timeoutId); + } + else { + xhr.removeEventListener('timeout', timeoutCallback); + } + cb({status: xhr.status, errorMessage: "Request timeout: " + errInfo}, null); + }; + xhr.addEventListener('load', loadCallback); + xhr.addEventListener('error', errorCallback); if (xhr.ontimeout === undefined) { xhr._timeoutId = setTimeout(function () { - xhr.ontimeout(); + timeoutCallback(); }, xhr.timeout); } - xhr.ontimeout = function () { - cb({status: xhr.status, errorMessage: "Request timeout: " + errInfo}, null); - }; + else { + xhr.addEventListener('timeout', timeoutCallback); + } } xhr.send(null); } else { @@ -836,10 +862,15 @@ cc.loader = (function () { xhr.open("GET", url, true); xhr.responseType = "arraybuffer"; - xhr.onload = function () { + var loadCallback = function () { + xhr.removeEventListener('load', loadCallback); + xhr.removeEventListener('error', errorCallback); if (xhr._timeoutId >= 0) { clearTimeout(xhr._timeoutId); } + else { + xhr.removeEventListener('timeout', timeoutCallback); + } var arrayBuffer = xhr.response; // Note: not oReq.responseText if (arrayBuffer) { window.msg = arrayBuffer; @@ -848,17 +879,38 @@ cc.loader = (function () { xhr.status === 200 ? cb(null, xhr.response) : cb({status:xhr.status, errorMessage:errInfo}, null); } }; - xhr.onerror = function(){ + var errorCallback = function(){ + xhr.removeEventListener('load', loadCallback); + xhr.removeEventListener('error', errorCallback); + if (xhr._timeoutId >= 0) { + clearTimeout(xhr._timeoutId); + } + else { + xhr.removeEventListener('timeout', timeoutCallback); + } cb({status:xhr.status, errorMessage:errInfo}, null); }; + var timeoutCallback = function () { + xhr.removeEventListener('load', loadCallback); + xhr.removeEventListener('error', errorCallback); + if (xhr._timeoutId >= 0) { + clearTimeout(xhr._timeoutId); + } + else { + xhr.removeEventListener('timeout', timeoutCallback); + } + cb({status: xhr.status, errorMessage: "Request timeout: " + errInfo}, null); + }; + xhr.addEventListener('load', loadCallback); + xhr.addEventListener('error', errorCallback); if (xhr.ontimeout === undefined) { xhr._timeoutId = setTimeout(function () { - xhr.ontimeout(); + timeoutCallback(); }, xhr.timeout); } - xhr.ontimeout = function () { - cb({status: xhr.status, errorMessage: "Request timeout: " + errInfo}, null); - }; + else { + xhr.addEventListener('timeout', timeoutCallback); + } xhr.send(null); }, From bb603feefe03783397b14c40a36e43b71c22bcde Mon Sep 17 00:00:00 2001 From: pandamicro Date: Fri, 8 Sep 2017 10:30:11 +0800 Subject: [PATCH 173/206] Fix leak --- cocos2d/core/CCScheduler.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos2d/core/CCScheduler.js b/cocos2d/core/CCScheduler.js index 0c75dc15af..1504bd70c0 100644 --- a/cocos2d/core/CCScheduler.js +++ b/cocos2d/core/CCScheduler.js @@ -385,7 +385,7 @@ cc.Scheduler = cc.Class.extend(/** @lends cc.Scheduler# */{ _removeUpdateFromHash:function (entry) { var self = this; - element = self._hashForUpdates[entry.target.__instanceId]; + var element = self._hashForUpdates[entry.target.__instanceId]; if (element) { // Remove list entry from list var list = element.list, listEntry = element.entry; From d30a1361014fe525ed0ed7926f53f3c66e0d302e Mon Sep 17 00:00:00 2001 From: pandamicro Date: Fri, 8 Sep 2017 10:30:46 +0800 Subject: [PATCH 174/206] Do not register accelerometer event by default --- cocos2d/core/platform/CCInputManager.js | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/cocos2d/core/platform/CCInputManager.js b/cocos2d/core/platform/CCInputManager.js index 382b1f86ed..270c535c7d 100644 --- a/cocos2d/core/platform/CCInputManager.js +++ b/cocos2d/core/platform/CCInputManager.js @@ -601,7 +601,7 @@ cc.inputManager = /** @lends cc.inputManager# */{ this._registerKeyboardEvent(); //register Accelerometer event - this._registerAccelerometerEvent(); + // this._registerAccelerometerEvent(); this._isRegisterEvent = true; }, @@ -609,6 +609,10 @@ cc.inputManager = /** @lends cc.inputManager# */{ _registerKeyboardEvent: function () { }, + /** + * Register Accelerometer event + * @function + */ _registerAccelerometerEvent: function () { }, From 5a643248331a0fd976f3d799e35cd885242cca29 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Fri, 8 Sep 2017 10:32:34 +0800 Subject: [PATCH 175/206] Fix spine issues --- cocos2d/core/sprites/CCSpriteWebGLRenderCmd.js | 2 +- extensions/spine/CCSkeleton.js | 9 +++++++++ extensions/spine/CCSkeletonCanvasRenderCmd.js | 4 ++-- extensions/spine/CCSkeletonWebGLRenderCmd.js | 8 ++++---- 4 files changed, 16 insertions(+), 7 deletions(-) diff --git a/cocos2d/core/sprites/CCSpriteWebGLRenderCmd.js b/cocos2d/core/sprites/CCSpriteWebGLRenderCmd.js index 4a543a616c..51ea5024cb 100644 --- a/cocos2d/core/sprites/CCSpriteWebGLRenderCmd.js +++ b/cocos2d/core/sprites/CCSpriteWebGLRenderCmd.js @@ -298,7 +298,7 @@ proto.uploadData = function (f32buffer, ui32buffer, vertexDataOffset) { var node = this._node, locTexture = node._texture; if (!(locTexture && locTexture._textureLoaded && node._rect.width && node._rect.height) || !this._displayedOpacity) - return false; + return 0; // Fill in vertex data with quad information (4 vertices for sprite) var opacity = this._displayedOpacity; diff --git a/extensions/spine/CCSkeleton.js b/extensions/spine/CCSkeleton.js index eec8aa2fbb..0f0d3ebdf3 100644 --- a/extensions/spine/CCSkeleton.js +++ b/extensions/spine/CCSkeleton.js @@ -106,9 +106,18 @@ sp.Skeleton = cc.Node.extend(/** @lends sp.Skeleton# */{ init: function () { cc.Node.prototype.init.call(this); this._premultipliedAlpha = (cc._renderType === cc.game.RENDER_TYPE_WEBGL && cc.OPTIMIZE_BLEND_FUNC_FOR_PREMULTIPLIED_ALPHA); + }, + + onEnter: function () { + cc.Node.prototype.onEnter.call(this); this.scheduleUpdate(); }, + onExit: function () { + this.unscheduleUpdate(); + cc.Node.prototype.onExit.call(this); + }, + /** * Sets whether open debug slots. * @param {boolean} enable true to open, false to close. diff --git a/extensions/spine/CCSkeletonCanvasRenderCmd.js b/extensions/spine/CCSkeletonCanvasRenderCmd.js index 0c37adb83d..1348ba920e 100644 --- a/extensions/spine/CCSkeletonCanvasRenderCmd.js +++ b/extensions/spine/CCSkeletonCanvasRenderCmd.js @@ -102,8 +102,8 @@ proto.rendering = function (wrapper, scaleX, scaleY) { proto.updateStatus = function() { this.originUpdateStatus(); this._updateCurrentRegions(); - this._regionFlag = _ccsg.Node.CanvasRenderCmd.RegionStatus.DirtyDouble; - this._dirtyFlag &= ~_ccsg.Node._dirtyFlags.contentDirty; + this._regionFlag = cc.Node.CanvasRenderCmd.RegionStatus.DirtyDouble; + this._dirtyFlag &= ~cc.Node._dirtyFlags.contentDirty; }; proto.getLocalBB = function() { diff --git a/extensions/spine/CCSkeletonWebGLRenderCmd.js b/extensions/spine/CCSkeletonWebGLRenderCmd.js index 221546ed75..af232c1dbb 100644 --- a/extensions/spine/CCSkeletonWebGLRenderCmd.js +++ b/extensions/spine/CCSkeletonWebGLRenderCmd.js @@ -246,8 +246,8 @@ proto._uploadRegionAttachmentData = function(attachment, slot, premultipliedAlph var srcIdx = i < 4 ? i % 3 : i - 2; var vx = vertices[srcIdx * 8], vy = vertices[srcIdx * 8 + 1]; - var x = vx * wa + vy * wb + wx, - y = vx * wc + vy * wd + wy; + var x = vx * wa + vy * wc + wx, + y = vx * wb + vy * wd + wy; var r = vertices[srcIdx * 8 + 2] * nodeR, g = vertices[srcIdx * 8 + 3] * nodeG, b = vertices[srcIdx * 8 + 4] * nodeB, @@ -290,8 +290,8 @@ proto._uploadMeshAttachmentData = function(attachment, slot, premultipliedAlpha, for (var i = 0, n = vertices.length; i < n; i += 8) { var vx = vertices[i], vy = vertices[i + 1]; - var x = vx * wa + vy * wb + wx, - y = vx * wc + vy * wd + wy; + var x = vx * wa + vy * wc + wx, + y = vx * wb + vy * wd + wy; var r = vertices[i + 2] * nodeR, g = vertices[i + 3] * nodeG, b = vertices[i + 4] * nodeB, From e9370a4d95c94e3c8e7eaf9e0ef89cd87e49d670 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Fri, 8 Sep 2017 11:03:32 +0800 Subject: [PATCH 176/206] Update version --- cocos2d/core/platform/CCConfig.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos2d/core/platform/CCConfig.js b/cocos2d/core/platform/CCConfig.js index 4fb22921f8..ceeddbf5d8 100644 --- a/cocos2d/core/platform/CCConfig.js +++ b/cocos2d/core/platform/CCConfig.js @@ -31,7 +31,7 @@ * @type {String} * @name cc.ENGINE_VERSION */ -window["CocosEngine"] = cc.ENGINE_VERSION = "Cocos2d-JS v3.15"; +window["CocosEngine"] = cc.ENGINE_VERSION = "Cocos2d-JS v3.16"; /** *

From cd3cb0063378eb23d5b18a375ba8a8ee05c5015f Mon Sep 17 00:00:00 2001 From: pandamicro Date: Fri, 8 Sep 2017 14:14:47 +0800 Subject: [PATCH 177/206] Enable 3d projection --- cocos2d/core/CCDirector.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos2d/core/CCDirector.js b/cocos2d/core/CCDirector.js index bfc8481d68..d0a9cfa7b5 100644 --- a/cocos2d/core/CCDirector.js +++ b/cocos2d/core/CCDirector.js @@ -943,4 +943,4 @@ cc.Director.PROJECTION_CUSTOM = 3; * @constant * @type {Number} */ -cc.Director.PROJECTION_DEFAULT = cc.Director.PROJECTION_2D; +cc.Director.PROJECTION_DEFAULT = cc.Director.PROJECTION_3D; From eaa5199205b6020c77ba7539b4c05a24b65a2dd4 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Fri, 8 Sep 2017 14:56:40 +0800 Subject: [PATCH 178/206] Fix glProgramState undefined issue in DrawingPrimitives --- cocos2d/core/CCDrawingPrimitivesWebGL.js | 1 + 1 file changed, 1 insertion(+) diff --git a/cocos2d/core/CCDrawingPrimitivesWebGL.js b/cocos2d/core/CCDrawingPrimitivesWebGL.js index e6fc9b7262..db8047aacc 100644 --- a/cocos2d/core/CCDrawingPrimitivesWebGL.js +++ b/cocos2d/core/CCDrawingPrimitivesWebGL.js @@ -61,6 +61,7 @@ cc.DrawingPrimitiveWebGL = cc.Class.extend(/** @lends cc.DrawingPrimitiveWebGL# _t._shader = cc.shaderCache.programForKey(cc.SHADER_POSITION_UCOLOR); _t._shader._addUniformLocation(this._colorLocation); _t._shader._addUniformLocation(this._pointSizeLocation); + _t._glProgramState = new cc.GLProgramState(_t._shader); _t._initialized = true; } From b2b9b6e7d65e02a0be3e8a81cd3fdc324768596d Mon Sep 17 00:00:00 2001 From: pandamicro Date: Fri, 8 Sep 2017 15:10:24 +0800 Subject: [PATCH 179/206] Use default scheduler to control action manager --- cocos2d/core/CCDirector.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos2d/core/CCDirector.js b/cocos2d/core/CCDirector.js index d0a9cfa7b5..b8a021f43c 100644 --- a/cocos2d/core/CCDirector.js +++ b/cocos2d/core/CCDirector.js @@ -136,6 +136,7 @@ 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; } @@ -228,7 +229,6 @@ 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); } From a3c5d98bfa11fdfb6213a3f2132b1aee3bae1f2e Mon Sep 17 00:00:00 2001 From: pandamicro Date: Fri, 8 Sep 2017 16:23:01 +0800 Subject: [PATCH 180/206] reorderChild can update arrival order --- cocos2d/core/base-nodes/CCNode.js | 5 ++--- cocos2d/particle/CCParticleBatchNode.js | 3 --- 2 files changed, 2 insertions(+), 6 deletions(-) diff --git a/cocos2d/core/base-nodes/CCNode.js b/cocos2d/core/base-nodes/CCNode.js index 62bd9e4a38..9d3e6f15e5 100644 --- a/cocos2d/core/base-nodes/CCNode.js +++ b/cocos2d/core/base-nodes/CCNode.js @@ -306,6 +306,8 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{ * @param {Number} localZOrder */ setLocalZOrder: function (localZOrder) { + if (localZOrder === this._localZOrder) + return; if (this._parent) this._parent.reorderChild(this, localZOrder); else @@ -1365,9 +1367,6 @@ cc.Node = cc.Class.extend(/** @lends cc.Node# */{ cc.log(cc._LogInfos.Node_reorderChild_2); return; } - if (zOrder === child.zIndex) { - return; - } cc.renderer.childrenOrderDirty = this._reorderChildDirty = true; child.arrivalOrder = cc.s_globalOrderOfArrival; cc.s_globalOrderOfArrival++; diff --git a/cocos2d/particle/CCParticleBatchNode.js b/cocos2d/particle/CCParticleBatchNode.js index 3952bcdbbb..53c381fc30 100644 --- a/cocos2d/particle/CCParticleBatchNode.js +++ b/cocos2d/particle/CCParticleBatchNode.js @@ -278,9 +278,6 @@ cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{ return; } - if (zOrder === child.zIndex) - return; - // no reordering if only 1 child if (this._children.length > 1) { var getIndexes = this._getCurrentIndex(child, zOrder); From 869af73494b0d2172b61b6ff0d75f0f4afdba6ca Mon Sep 17 00:00:00 2001 From: pandamicro Date: Fri, 8 Sep 2017 16:29:58 +0800 Subject: [PATCH 181/206] Fix infinite call stack in ArmatureWebGLRenderCmd --- cocos2d/core/CCDrawingPrimitivesWebGL.js | 2 +- extensions/cocostudio/armature/CCArmatureWebGLRenderCmd.js | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/cocos2d/core/CCDrawingPrimitivesWebGL.js b/cocos2d/core/CCDrawingPrimitivesWebGL.js index db8047aacc..6daa60cb01 100644 --- a/cocos2d/core/CCDrawingPrimitivesWebGL.js +++ b/cocos2d/core/CCDrawingPrimitivesWebGL.js @@ -61,7 +61,7 @@ cc.DrawingPrimitiveWebGL = cc.Class.extend(/** @lends cc.DrawingPrimitiveWebGL# _t._shader = cc.shaderCache.programForKey(cc.SHADER_POSITION_UCOLOR); _t._shader._addUniformLocation(this._colorLocation); _t._shader._addUniformLocation(this._pointSizeLocation); - _t._glProgramState = new cc.GLProgramState(_t._shader); + _t._glProgramState = cc.GLProgramState.getOrCreateWithGLProgram(_t._shader); _t._initialized = true; } diff --git a/extensions/cocostudio/armature/CCArmatureWebGLRenderCmd.js b/extensions/cocostudio/armature/CCArmatureWebGLRenderCmd.js index bf48084815..6f24c7b677 100644 --- a/extensions/cocostudio/armature/CCArmatureWebGLRenderCmd.js +++ b/extensions/cocostudio/armature/CCArmatureWebGLRenderCmd.js @@ -118,7 +118,7 @@ }; proto.setShaderProgram = function (shaderProgram) { - this._shaderProgram = shaderProgram; + this._glProgramState = cc.GLProgramState.getOrCreateWithGLProgram(shaderProgram); }; proto._updateColorAndOpacity = function (skinRenderCmd, bone) { From b08573693a9f3d7b102140d6b1e1706d48110a78 Mon Sep 17 00:00:00 2001 From: Stefan Nguyen Date: Sun, 10 Sep 2017 17:06:42 +0700 Subject: [PATCH 182/206] Fix label stroke is rendered ugly on web platform --- cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js b/cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js index 8693c850d1..44c8f1866f 100644 --- a/cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js +++ b/cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js @@ -387,8 +387,10 @@ cc.LabelTTF._firsrEnglish = /^[a-zA-Z0-9\-¿¡«À-ÖØ-öø-ʯ\u0300-\u034e\u03 var locStrLen = this._strings.length; for (var i = 0; i < locStrLen; i++) { var line = this._strings[i]; - if (locStrokeEnabled) + if (locStrokeEnabled) { + context.lineJoin = 'round'; context.strokeText(line, xOffset, yOffsetArray[i]); + } context.fillText(line, xOffset, yOffsetArray[i]); } cc.g_NumberOfDraws++; From 6adee332b9fdcaf90e94fe1395ab11777a133dfd Mon Sep 17 00:00:00 2001 From: pandamicro Date: Wed, 13 Sep 2017 11:30:27 +0800 Subject: [PATCH 183/206] Fix ProgressTimer vertex not updating when transform changing --- cocos2d/progress-timer/CCProgressTimerWebGLRenderCmd.js | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/cocos2d/progress-timer/CCProgressTimerWebGLRenderCmd.js b/cocos2d/progress-timer/CCProgressTimerWebGLRenderCmd.js index c78b0d5f9d..8a89913eed 100644 --- a/cocos2d/progress-timer/CCProgressTimerWebGLRenderCmd.js +++ b/cocos2d/progress-timer/CCProgressTimerWebGLRenderCmd.js @@ -35,6 +35,7 @@ this._bl = cc.p(); this._tr = cc.p(); + this._transformUpdating = false; this.initCmd(); }; @@ -55,7 +56,9 @@ this._tr.x = rx * wt.a + ty * wt.c + wt.tx; this._tr.y = rx * wt.b + ty * wt.d + wt.ty; + this._transformUpdating = true; this._updateProgressData(); + this._transformUpdating = false; }; proto.rendering = function (ctx) { @@ -449,7 +452,7 @@ this._updateColor(); var locVertexData = this._vertexData; - if (!sameIndexCount) { + if (this._transformUpdating || !sameIndexCount) { // First we populate the array with the m_tMidpoint, then all // vertices/texcoords/colors of the 12 'o clock start and edges and the hitpoint this._textureCoordFromAlphaPoint(locVertexData[0].texCoords, locMidPoint.x, locMidPoint.y); From d67a8b3a8e34e02be91c9cfd2171961a57b889e4 Mon Sep 17 00:00:00 2001 From: danilo neves cruz Date: Wed, 13 Sep 2017 02:32:22 -0300 Subject: [PATCH 184/206] optimize uniform cache performance --- cocos2d/shaders/CCGLProgram.js | 26 ++++++++++++++++++-------- cocos2d/shaders/CCGLProgramState.js | 6 +++--- 2 files changed, 21 insertions(+), 11 deletions(-) diff --git a/cocos2d/shaders/CCGLProgram.js b/cocos2d/shaders/CCGLProgram.js index 67e23db2d7..4e8301d50b 100644 --- a/cocos2d/shaders/CCGLProgram.js +++ b/cocos2d/shaders/CCGLProgram.js @@ -48,11 +48,18 @@ cc.GLProgram = cc.Class.extend(/** @lends cc.GLProgram# */{ var updated = false; var element = this._hashForUniforms[name]; - var args = Array.isArray(arguments[1]) ? arguments[1] : - Array.prototype.slice.call(arguments, 1); + var args; + if (Array.isArray(arguments[1])) { + args = arguments[1]; + } else { + args = new Array(arguments.length - 1); + for (var i = 1; i < arguments.length; i += 1) { + args[i - 1] = arguments[i]; + } + } if (!element || element.length !== args.length) { - this._hashForUniforms[name] = args.slice(); + this._hashForUniforms[name] = [].concat(args); updated = true; } else { for (var i = 0; i < args.length; i += 1) { @@ -260,11 +267,14 @@ cc.GLProgram = cc.Class.extend(/** @lends cc.GLProgram# */{ * cc.UNIFORM_SAMPLER */ updateUniforms: function () { - [cc.UNIFORM_PMATRIX_S, cc.UNIFORM_MVMATRIX_S, cc.UNIFORM_MVPMATRIX_S, - cc.UNIFORM_TIME_S, cc.UNIFORM_SINTIME_S, cc.UNIFORM_COSTIME_S, - cc.UNIFORM_RANDOM01_S, cc.UNIFORM_SAMPLER_S].forEach(function(name) { - this._addUniformLocation(name); - }.bind(this)); + this._addUniformLocation(cc.UNIFORM_PMATRIX_S); + this._addUniformLocation(cc.UNIFORM_MVMATRIX_S); + this._addUniformLocation(cc.UNIFORM_MVPMATRIX_S); + this._addUniformLocation(cc.UNIFORM_TIME_S); + this._addUniformLocation(cc.UNIFORM_SINTIME_S); + this._addUniformLocation(cc.UNIFORM_COSTIME_S); + this._addUniformLocation(cc.UNIFORM_RANDOM01_S); + this._addUniformLocation(cc.UNIFORM_SAMPLER_S); this._usesTime = (this._uniforms[cc.UNIFORM_TIME_S] != null || this._uniforms[cc.UNIFORM_SINTIME_S] != null || this._uniforms[cc.UNIFORM_COSTIME_S] != null); this.use(); diff --git a/cocos2d/shaders/CCGLProgramState.js b/cocos2d/shaders/CCGLProgramState.js index 2e9ec348ee..c5bc2fd428 100644 --- a/cocos2d/shaders/CCGLProgramState.js +++ b/cocos2d/shaders/CCGLProgramState.js @@ -163,9 +163,9 @@ cc.GLProgramState.prototype = { this._glprogram._setUniformForMVPMatrixWithMat4(modelView); } - Object.values(this._uniforms).forEach(function(uniform) { - uniform.apply(); - }); + for (var name in this._uniforms) { + this._uniforms[name].apply(); + }; }, setGLProgram: function setGLProgram(glprogram) { From 5db5d52126c7e4961dafb2cc971fa1641ab7b924 Mon Sep 17 00:00:00 2001 From: Minh Quy Date: Tue, 19 Sep 2017 14:22:13 +0700 Subject: [PATCH 185/206] Use the same family font in tmpEdTxt and edTxt --- extensions/editbox/CCEditBox.js | 2 ++ 1 file changed, 2 insertions(+) diff --git a/extensions/editbox/CCEditBox.js b/extensions/editbox/CCEditBox.js index ca112fdab4..3a535438f2 100644 --- a/extensions/editbox/CCEditBox.js +++ b/extensions/editbox/CCEditBox.js @@ -854,6 +854,7 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp var thisPointer = this; var tmpEdTxt = this._edTxt = document.createElement('input'); tmpEdTxt.type = 'text'; + tmpEdTxt.style.fontFamily = this._edFontName; tmpEdTxt.style.fontSize = this._edFontSize + 'px'; tmpEdTxt.style.color = '#000000'; tmpEdTxt.style.border = 0; @@ -949,6 +950,7 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp var thisPointer = this; var tmpEdTxt = this._edTxt = document.createElement('textarea'); tmpEdTxt.type = 'text'; + tmpEdTxt.style.fontFamily = this._edFontName; tmpEdTxt.style.fontSize = this._edFontSize + 'px'; tmpEdTxt.style.color = '#000000'; tmpEdTxt.style.border = 0; From 639073564df67c2f086d39abac469d56bb41ad4d Mon Sep 17 00:00:00 2001 From: pandamicro Date: Thu, 21 Sep 2017 22:45:35 +0800 Subject: [PATCH 186/206] Fix acceleration event crash --- cocos2d/core/platform/CCInputExtension.js | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/cocos2d/core/platform/CCInputExtension.js b/cocos2d/core/platform/CCInputExtension.js index 6f780104b1..e61f58459a 100644 --- a/cocos2d/core/platform/CCInputExtension.js +++ b/cocos2d/core/platform/CCInputExtension.js @@ -39,10 +39,12 @@ _p.setAccelerometerEnabled = function(isEnable){ var scheduler = cc.director.getScheduler(); if(_t._accelEnabled){ _t._accelCurTime = 0; + _t._registerAccelerometerEvent(); scheduler.scheduleUpdate(_t); } else { _t._accelCurTime = 0; - scheduler.scheduleUpdate(_t); + _t._unregisterAccelerometerEvent(); + scheduler.unscheduleUpdate(_t); } }; @@ -85,7 +87,14 @@ _p._registerAccelerometerEvent = function(){ _t._minus = -1; } - w.addEventListener(_deviceEventType, _t.didAccelerate.bind(_t), false); + _t.didAccelerateCallback = _t.didAccelerate.bind(_t); + w.addEventListener(_deviceEventType, _t.didAccelerateCallback, false); +}; + +_p._unregisterAccelerometerEvent = function () { + this._acceleration = null; + var _deviceEventType = (this._accelDeviceEvent === window.DeviceMotionEvent) ? "devicemotion" : "deviceorientation"; + window.removeEventListener(_deviceEventType, this.didAccelerateCallback, false); }; _p.didAccelerate = function (eventData) { From c27fa163cdcbda86101adaf77bf5cec2c7740c34 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Fri, 22 Sep 2017 01:21:00 +0800 Subject: [PATCH 187/206] Fix advanced release mode --- CCBoot.js | 2 +- .../core/base-nodes/CCNodeWebGLRenderCmd.js | 2 ++ cocos2d/core/platform/CCClass.js | 26 +++++++++---------- cocos2d/core/textures/TexturesWebGL.js | 2 +- 4 files changed, 17 insertions(+), 15 deletions(-) diff --git a/CCBoot.js b/CCBoot.js index 9cfc1ae2db..f6ec16bc1f 100644 --- a/CCBoot.js +++ b/CCBoot.js @@ -992,7 +992,7 @@ cc.loader = (function () { delete _queue[url]; } - if (ENABLE_IMAEG_POOL && cc._renderType === cc.game.RENDER_TYPE_WEBGL) { + if (window.ENABLE_IMAEG_POOL && cc._renderType === cc.game.RENDER_TYPE_WEBGL) { imagePool.put(img); } }; diff --git a/cocos2d/core/base-nodes/CCNodeWebGLRenderCmd.js b/cocos2d/core/base-nodes/CCNodeWebGLRenderCmd.js index 0506dd522b..7680017273 100644 --- a/cocos2d/core/base-nodes/CCNodeWebGLRenderCmd.js +++ b/cocos2d/core/base-nodes/CCNodeWebGLRenderCmd.js @@ -60,4 +60,6 @@ set: function (value) { this.setShaderProgram(value); }, get: function () { return this.getShaderProgram(); } }); + /** @expose */ + proto._shaderProgram; })(); diff --git a/cocos2d/core/platform/CCClass.js b/cocos2d/core/platform/CCClass.js index 6b7a2e8043..be34ad92eb 100644 --- a/cocos2d/core/platform/CCClass.js +++ b/cocos2d/core/platform/CCClass.js @@ -140,19 +140,19 @@ cc.inject = function (srcPrototype, destPrototype) { * @namespace * @name ClassManager */ -var ClassManager = { - id : (0|(Math.random()*998)), +var ClassManager = function () { + var id = (0|(Math.random()*998)); + var instanceId = (0|(Math.random()*998)); - instanceId : (0|(Math.random()*998)), - - getNewID : function(){ - return this.id++; - }, + this.getNewID = function () { + return id++; + }; - getNewInstanceId : function(){ - return this.instanceId++; - } + this.getNewInstanceId = function () { + return instanceId++; + }; }; +var classManager = new ClassManager(); /* Managed JavaScript Inheritance * Based on John Resig's Simple JavaScript Inheritance http://ejohn.org/blog/simple-javascript-inheritance/ @@ -192,7 +192,7 @@ var ClassManager = { var Class; if (cc.game.config && 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 += " this.__instanceId = classManager.getNewInstanceId();\n"; constructor += " if (this.ctor) {\n"; constructor += " switch (arguments.length) {\n"; constructor += " case 0: this.ctor(); break;\n"; @@ -208,7 +208,7 @@ var ClassManager = { } else { Class = function (arg0, arg1, arg2, arg3, arg4) { - this.__instanceId = ClassManager.getNewInstanceId(); + this.__instanceId = classManager.getNewInstanceId(); if (this.ctor) { switch (arguments.length) { case 0: this.ctor(); break; @@ -223,7 +223,7 @@ var ClassManager = { }; } - desc.value = ClassManager.getNewID(); + desc.value = classManager.getNewID(); Object.defineProperty(prototype, '__pid', desc); // Populate our constructed prototype object diff --git a/cocos2d/core/textures/TexturesWebGL.js b/cocos2d/core/textures/TexturesWebGL.js index 5811f159ef..2dfe145e56 100644 --- a/cocos2d/core/textures/TexturesWebGL.js +++ b/cocos2d/core/textures/TexturesWebGL.js @@ -496,7 +496,7 @@ cc._tmp.WebGLTexture2D = function () { self._hasPremultipliedAlpha = premultiplied; self._hasMipmaps = false; - if (ENABLE_IMAEG_POOL) { + if (window.ENABLE_IMAEG_POOL) { self._htmlElementObj = null; } From ac10928ad55a8a799e47a9b7bfe3b8a484bc74be Mon Sep 17 00:00:00 2001 From: pandamicro Date: Fri, 22 Sep 2017 10:23:04 +0800 Subject: [PATCH 188/206] Revert "web UIButton support BMFont" --- extensions/ccui/uiwidgets/UIButton.js | 28 +++++++-------------------- 1 file changed, 7 insertions(+), 21 deletions(-) diff --git a/extensions/ccui/uiwidgets/UIButton.js b/extensions/ccui/uiwidgets/UIButton.js index 1c3f102a4f..4741e2e767 100644 --- a/extensions/ccui/uiwidgets/UIButton.js +++ b/extensions/ccui/uiwidgets/UIButton.js @@ -100,22 +100,12 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ } }, - _createTitleRendererIfNeeded: function (fntFile) { + _createTitleRendererIfNeeded: function ( ) { if(!this._titleRenderer) { - if(fntFile != null) - { - this._titleRenderer = new cc.LabelBMFont("", fntFile); - this._titleRenderer.setAlignment(cc.TEXT_ALIGNMENT_CENTER); - } - else - { - this._titleRenderer = new cc.LabelTTF(""); - this._titleRenderer.setVerticalAlignment(cc.VERTICAL_TEXT_ALIGNMENT_CENTER); - } - - this._titleRenderer.setAnchorPoint(0.5, 0.4); + this._titleRenderer = new cc.LabelTTF(""); + this._titleRenderer.setAnchorPoint(0.5, 0.5); this._titleColor = cc.color.WHITE; - + this._titleRenderer.setVerticalAlignment(cc.VERTICAL_TEXT_ALIGNMENT_CENTER); this.addProtectedChild(this._titleRenderer, ccui.Button.TITLE_RENDERER_ZORDER, -1); } }, @@ -667,11 +657,7 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ setTitleFontSize: function (size) { this._createTitleRendererIfNeeded(); - if(this._titleRenderer.setFontSize) - this._titleRenderer.setFontSize(size); - else - this._titleRenderer.setBoundingWidth(size); - + this._titleRenderer.setFontSize(size); this._fontSize = size; }, @@ -719,9 +705,9 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{ * @param {String} fontName */ setTitleFontName: function (fontName) { - this._createTitleRendererIfNeeded(fontName); + this._createTitleRendererIfNeeded(); - this._titleRenderer.setFontName && this._titleRenderer.setFontName(fontName); + this._titleRenderer.setFontName(fontName); this._fontName = fontName; }, From 926dc6b24177ed72de93098a7b02010449e5bbc5 Mon Sep 17 00:00:00 2001 From: linkqjlin Date: Wed, 6 Sep 2017 21:14:19 +0800 Subject: [PATCH 189/206] Use arraybuffer responseType in BinaryLoader --- cocos2d/core/utils/BinaryLoader.js | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/cocos2d/core/utils/BinaryLoader.js b/cocos2d/core/utils/BinaryLoader.js index 7127b1279c..01e5c6194b 100644 --- a/cocos2d/core/utils/BinaryLoader.js +++ b/cocos2d/core/utils/BinaryLoader.js @@ -37,6 +37,7 @@ cc.loader.loadBinary = function (url, cb) { var xhr = this.getXMLHttpRequest(), errInfo = "load " + url + " failed!"; xhr.open("GET", url, true); + xhr.responseType = 'arraybuffer'; if (cc.loader.loadBinary._IEFilter) { // IE-specific logic here xhr.setRequestHeader("Accept-Charset", "x-user-defined"); @@ -49,7 +50,7 @@ cc.loader.loadBinary = function (url, cb) { } else { if (xhr.overrideMimeType) xhr.overrideMimeType("text\/plain; charset=x-user-defined"); xhr.onload = function () { - xhr.readyState === 4 && xhr.status === 200 ? cb(null, self._str2Uint8Array(xhr.responseText)) : cb(errInfo); + xhr.readyState === 4 && xhr.status === 200 ? cb(null, xhr.response) : cb(errInfo); }; } xhr.send(null); @@ -80,6 +81,7 @@ cc.loader.loadBinarySync = function (url) { req.timeout = 0; var errInfo = "load " + url + " failed!"; req.open('GET', url, false); + req.responseType = 'arraybuffer'; var arrayInfo = null; if (cc.loader.loadBinary._IEFilter) { req.setRequestHeader("Accept-Charset", "x-user-defined"); @@ -102,7 +104,7 @@ cc.loader.loadBinarySync = function (url) { return null; } - arrayInfo = this._str2Uint8Array(req.responseText); + arrayInfo = req.response; } return arrayInfo; }; @@ -151,4 +153,4 @@ if (cc.loader.loadBinary._IEFilter) { return byteMapping[match]; }) + lastChr; }; -} \ No newline at end of file +} From 56118065f0b11b298aab41356688758d79b75f7b Mon Sep 17 00:00:00 2001 From: pandamicro Date: Fri, 29 Sep 2017 10:21:39 +0800 Subject: [PATCH 190/206] Return Uint8Array in BinaryLoader (keep consistency) --- cocos2d/core/utils/BinaryLoader.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cocos2d/core/utils/BinaryLoader.js b/cocos2d/core/utils/BinaryLoader.js index 01e5c6194b..67f1a4ccff 100644 --- a/cocos2d/core/utils/BinaryLoader.js +++ b/cocos2d/core/utils/BinaryLoader.js @@ -50,7 +50,7 @@ cc.loader.loadBinary = function (url, cb) { } else { if (xhr.overrideMimeType) xhr.overrideMimeType("text\/plain; charset=x-user-defined"); xhr.onload = function () { - xhr.readyState === 4 && xhr.status === 200 ? cb(null, xhr.response) : cb(errInfo); + xhr.readyState === 4 && xhr.status === 200 ? cb(null, new Uint8Array(xhr.response)) : cb(errInfo); }; } xhr.send(null); @@ -104,7 +104,7 @@ cc.loader.loadBinarySync = function (url) { return null; } - arrayInfo = req.response; + arrayInfo = new Uint8Array(req.response); } return arrayInfo; }; From f63c49d0cef6cbefef5304a831b22670e6901a2f Mon Sep 17 00:00:00 2001 From: pandamicro Date: Fri, 29 Sep 2017 12:47:23 +0800 Subject: [PATCH 191/206] Fix matrix array not being updated in gl program issue (fix cocos2d/cocos2d-html5/3511) --- cocos2d/shaders/CCGLProgram.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/cocos2d/shaders/CCGLProgram.js b/cocos2d/shaders/CCGLProgram.js index 4e8301d50b..0cf9f4702d 100644 --- a/cocos2d/shaders/CCGLProgram.js +++ b/cocos2d/shaders/CCGLProgram.js @@ -63,7 +63,8 @@ cc.GLProgram = cc.Class.extend(/** @lends cc.GLProgram# */{ updated = true; } else { for (var i = 0; i < args.length; i += 1) { - if (args[i] !== element[i]) { + // Array and Typed Array inner values could be changed, so we must update them + if (args[i] !== element[i] || typeof args[i] === 'object') { element[i] = args[i]; updated = true; } From 0e6eda354422d1c3eb1e759db6d20f49d74d685a Mon Sep 17 00:00:00 2001 From: pandamicro Date: Fri, 29 Sep 2017 17:51:31 +0800 Subject: [PATCH 192/206] Revert wrong changes to Spine --- extensions/spine/CCSkeletonWebGLRenderCmd.js | 4 ++-- extensions/spine/Spine.js | 7 ++++--- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/extensions/spine/CCSkeletonWebGLRenderCmd.js b/extensions/spine/CCSkeletonWebGLRenderCmd.js index af232c1dbb..bbe4cd805d 100644 --- a/extensions/spine/CCSkeletonWebGLRenderCmd.js +++ b/extensions/spine/CCSkeletonWebGLRenderCmd.js @@ -290,8 +290,8 @@ proto._uploadMeshAttachmentData = function(attachment, slot, premultipliedAlpha, for (var i = 0, n = vertices.length; i < n; i += 8) { var vx = vertices[i], vy = vertices[i + 1]; - var x = vx * wa + vy * wc + wx, - y = vx * wb + vy * wd + wy; + var x = vx * wa + vy * wb + wx, + y = vx * wc + vy * wd + wy; var r = vertices[i + 2] * nodeR, g = vertices[i + 3] * nodeG, b = vertices[i + 4] * nodeB, diff --git a/extensions/spine/Spine.js b/extensions/spine/Spine.js index c845c19f41..9da03c2974 100644 --- a/extensions/spine/Spine.js +++ b/extensions/spine/Spine.js @@ -4241,12 +4241,13 @@ var spine; var scale = this.scale; attachment.worldVerticesLength = verticesLength; var vertices = map.vertices; - if (verticesLength == vertices.length) { + var scaledVertices = spine.Utils.toFloatArray(vertices); + if (verticesLength == scaledVertices.length) { if (scale != 1) { for (var i = 0, n = vertices.length; i < n; i++) - vertices[i] *= scale; + scaledVertices[i] *= scale; } - attachment.vertices = spine.Utils.toFloatArray(vertices); + attachment.vertices = scaledVertices; return; } var weights = new Array(); From b2095577b23f06a168a3dd5e14fa56b7bf4e8e41 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Sat, 30 Sep 2017 12:38:15 +0800 Subject: [PATCH 193/206] Avoid setting responseType in synchronous xhr --- cocos2d/core/utils/BinaryLoader.js | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/cocos2d/core/utils/BinaryLoader.js b/cocos2d/core/utils/BinaryLoader.js index 67f1a4ccff..46b82b65cf 100644 --- a/cocos2d/core/utils/BinaryLoader.js +++ b/cocos2d/core/utils/BinaryLoader.js @@ -81,7 +81,6 @@ cc.loader.loadBinarySync = function (url) { req.timeout = 0; var errInfo = "load " + url + " failed!"; req.open('GET', url, false); - req.responseType = 'arraybuffer'; var arrayInfo = null; if (cc.loader.loadBinary._IEFilter) { req.setRequestHeader("Accept-Charset", "x-user-defined"); @@ -104,7 +103,7 @@ cc.loader.loadBinarySync = function (url) { return null; } - arrayInfo = new Uint8Array(req.response); + arrayInfo = self._str2Uint8Array(req.responseText); } return arrayInfo; }; From 473efb56d38d2f6c70559cc30505c41fff653da8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ricardo=20Petre=CC=81re?= Date: Wed, 11 Oct 2017 09:32:57 -0300 Subject: [PATCH 194/206] Resize event on browser not working --- cocos2d/core/platform/CCEGLView.js | 2 ++ 1 file changed, 2 insertions(+) diff --git a/cocos2d/core/platform/CCEGLView.js b/cocos2d/core/platform/CCEGLView.js index 448f1b2f1b..f91e54b8b8 100755 --- a/cocos2d/core/platform/CCEGLView.js +++ b/cocos2d/core/platform/CCEGLView.js @@ -187,6 +187,8 @@ cc.EGLView = cc.Class.extend(/** @lends cc.view# */{ if (sys.isMobile) { window.addEventListener('orientationchange', this._orientationChange); + } else { + this._orientationChanging = false; } }, From 749c764583f9d9e9d25598dc4d4527d5d8248fbb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ricardo=20Petre=CC=81re?= Date: Tue, 12 Dec 2017 18:10:23 -0200 Subject: [PATCH 195/206] Some few text fixes --- CCBoot.js | 2 +- cocos2d/actions/CCActionInterval.js | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/CCBoot.js b/CCBoot.js index ebe862bedb..22c50494b6 100644 --- a/CCBoot.js +++ b/CCBoot.js @@ -1064,7 +1064,7 @@ cc.loader = (function () { loader = _register[type.toLowerCase()]; } if (!loader) { - cc.error("loader for [" + type + "] not exists!"); + cc.error("loader for [" + type + "] doesn't exist!"); return cb(); } var realUrl = url; diff --git a/cocos2d/actions/CCActionInterval.js b/cocos2d/actions/CCActionInterval.js index 7534d17fca..905d72b0a2 100644 --- a/cocos2d/actions/CCActionInterval.js +++ b/cocos2d/actions/CCActionInterval.js @@ -137,7 +137,7 @@ cc.ActionInterval = cc.FiniteTimeAction.extend(/** @lends cc.ActionInterval# */{ * * @example * //example - * action.easeing(cc.easeIn(3.0)); + * action.easing(cc.easeIn(3.0)); * @param {Object} easeObj * @returns {cc.ActionInterval} */ @@ -997,7 +997,7 @@ cc.Spawn = cc.ActionInterval.extend(/** @lends cc.Spawn# */{ * Create a spawn action which runs several actions in parallel. * @function * @param {Array|cc.FiniteTimeAction}tempArray - * @return {cc.FiniteTimeAction} + * @return {cc.Spawn} * @example * // example * var action = cc.spawn(cc.jumpBy(2, cc.p(300, 0), 50, 4), cc.rotateBy(2, 720)); @@ -1022,7 +1022,7 @@ cc.spawn = function (/*Multiple Arguments*/tempArray) { * @static * @deprecated since v3.0
Please use cc.spawn instead. * @param {Array|cc.FiniteTimeAction}tempArray - * @return {cc.FiniteTimeAction} + * @return {cc.Spawn} */ cc.Spawn.create = cc.spawn; From 71eac1e696200ccb835d98d1982faf5dcedf575d Mon Sep 17 00:00:00 2001 From: drelaptop Date: Tue, 10 Apr 2018 14:50:51 +0800 Subject: [PATCH 196/206] update spine-core to 3.6.39 --- extensions/spine/Spine.js | 2884 +++++++++++++++++++++++++------------ 1 file changed, 1990 insertions(+), 894 deletions(-) diff --git a/extensions/spine/Spine.js b/extensions/spine/Spine.js index 9da03c2974..b4ffec4b15 100644 --- a/extensions/spine/Spine.js +++ b/extensions/spine/Spine.js @@ -1,10 +1,15 @@ -// Spine runtime version 3.5.35 +// Spine runtime version 3.6.39 -var __extends = (this && this.__extends) || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -}; +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); var spine; (function (spine) { var Animation = (function () { @@ -17,7 +22,7 @@ var spine; this.timelines = timelines; this.duration = duration; } - Animation.prototype.apply = function (skeleton, lastTime, time, loop, events, alpha, setupPose, mixingOut) { + Animation.prototype.apply = function (skeleton, lastTime, time, loop, events, alpha, pose, direction) { if (skeleton == null) throw new Error("skeleton cannot be null."); if (loop && this.duration != 0) { @@ -27,7 +32,7 @@ var spine; } var timelines = this.timelines; for (var i = 0, n = timelines.length; i < n; i++) - timelines[i].apply(skeleton, lastTime, time, events, alpha, setupPose, mixingOut); + timelines[i].apply(skeleton, lastTime, time, events, alpha, pose, direction); }; Animation.binarySearch = function (values, target, step) { if (step === void 0) { step = 1; } @@ -55,6 +60,18 @@ var spine; return Animation; }()); spine.Animation = Animation; + var MixPose; + (function (MixPose) { + MixPose[MixPose["setup"] = 0] = "setup"; + MixPose[MixPose["current"] = 1] = "current"; + MixPose[MixPose["currentLayered"] = 2] = "currentLayered"; + })(MixPose = spine.MixPose || (spine.MixPose = {})); + var MixDirection; + (function (MixDirection) { + MixDirection[MixDirection["in"] = 0] = "in"; + MixDirection[MixDirection["out"] = 1] = "out"; + })(MixDirection = spine.MixDirection || (spine.MixDirection = {})); + var TimelineType; (function (TimelineType) { TimelineType[TimelineType["rotate"] = 0] = "rotate"; TimelineType[TimelineType["translate"] = 1] = "translate"; @@ -70,8 +87,8 @@ var spine; TimelineType[TimelineType["pathConstraintPosition"] = 11] = "pathConstraintPosition"; TimelineType[TimelineType["pathConstraintSpacing"] = 12] = "pathConstraintSpacing"; TimelineType[TimelineType["pathConstraintMix"] = 13] = "pathConstraintMix"; - })(spine.TimelineType || (spine.TimelineType = {})); - var TimelineType = spine.TimelineType; + TimelineType[TimelineType["twoColor"] = 14] = "twoColor"; + })(TimelineType = spine.TimelineType || (spine.TimelineType = {})); var CurveTimeline = (function () { function CurveTimeline(frameCount) { if (frameCount <= 0) @@ -147,18 +164,19 @@ var spine; var y = curves[i - 1]; return y + (1 - y) * (percent - x) / (1 - x); }; - CurveTimeline.LINEAR = 0; - CurveTimeline.STEPPED = 1; - CurveTimeline.BEZIER = 2; - CurveTimeline.BEZIER_SIZE = 10 * 2 - 1; return CurveTimeline; }()); + CurveTimeline.LINEAR = 0; + CurveTimeline.STEPPED = 1; + CurveTimeline.BEZIER = 2; + CurveTimeline.BEZIER_SIZE = 10 * 2 - 1; spine.CurveTimeline = CurveTimeline; var RotateTimeline = (function (_super) { __extends(RotateTimeline, _super); function RotateTimeline(frameCount) { - _super.call(this, frameCount); - this.frames = spine.Utils.newFloatArray(frameCount << 1); + var _this = _super.call(this, frameCount) || this; + _this.frames = spine.Utils.newFloatArray(frameCount << 1); + return _this; } RotateTimeline.prototype.getPropertyId = function () { return (TimelineType.rotate << 24) + this.boneIndex; @@ -168,21 +186,28 @@ var spine; this.frames[frameIndex] = time; this.frames[frameIndex + RotateTimeline.ROTATION] = degrees; }; - RotateTimeline.prototype.apply = function (skeleton, lastTime, time, events, alpha, setupPose, mixingOut) { + RotateTimeline.prototype.apply = function (skeleton, lastTime, time, events, alpha, pose, direction) { var frames = this.frames; var bone = skeleton.bones[this.boneIndex]; if (time < frames[0]) { - if (setupPose) - bone.rotation = bone.data.rotation; + switch (pose) { + case MixPose.setup: + bone.rotation = bone.data.rotation; + return; + case MixPose.current: + var r_1 = bone.data.rotation - bone.rotation; + r_1 -= (16384 - ((16384.499999999996 - r_1 / 360) | 0)) * 360; + bone.rotation += r_1 * alpha; + } return; } if (time >= frames[frames.length - RotateTimeline.ENTRIES]) { - if (setupPose) + if (pose == MixPose.setup) bone.rotation = bone.data.rotation + frames[frames.length + RotateTimeline.PREV_ROTATION] * alpha; else { - var r_1 = bone.data.rotation + frames[frames.length + RotateTimeline.PREV_ROTATION] - bone.rotation; - r_1 -= (16384 - ((16384.499999999996 - r_1 / 360) | 0)) * 360; - bone.rotation += r_1 * alpha; + var r_2 = bone.data.rotation + frames[frames.length + RotateTimeline.PREV_ROTATION] - bone.rotation; + r_2 -= (16384 - ((16384.499999999996 - r_2 / 360) | 0)) * 360; + bone.rotation += r_2 * alpha; } return; } @@ -193,7 +218,7 @@ var spine; var r = frames[frame + RotateTimeline.ROTATION] - prevRotation; r -= (16384 - ((16384.499999999996 - r / 360) | 0)) * 360; r = prevRotation + r * percent; - if (setupPose) { + if (pose == MixPose.setup) { r -= (16384 - ((16384.499999999996 - r / 360) | 0)) * 360; bone.rotation = bone.data.rotation + r * alpha; } @@ -203,18 +228,19 @@ var spine; bone.rotation += r * alpha; } }; - RotateTimeline.ENTRIES = 2; - RotateTimeline.PREV_TIME = -2; - RotateTimeline.PREV_ROTATION = -1; - RotateTimeline.ROTATION = 1; return RotateTimeline; }(CurveTimeline)); + RotateTimeline.ENTRIES = 2; + RotateTimeline.PREV_TIME = -2; + RotateTimeline.PREV_ROTATION = -1; + RotateTimeline.ROTATION = 1; spine.RotateTimeline = RotateTimeline; var TranslateTimeline = (function (_super) { __extends(TranslateTimeline, _super); function TranslateTimeline(frameCount) { - _super.call(this, frameCount); - this.frames = spine.Utils.newFloatArray(frameCount * TranslateTimeline.ENTRIES); + var _this = _super.call(this, frameCount) || this; + _this.frames = spine.Utils.newFloatArray(frameCount * TranslateTimeline.ENTRIES); + return _this; } TranslateTimeline.prototype.getPropertyId = function () { return (TimelineType.translate << 24) + this.boneIndex; @@ -225,13 +251,18 @@ var spine; this.frames[frameIndex + TranslateTimeline.X] = x; this.frames[frameIndex + TranslateTimeline.Y] = y; }; - TranslateTimeline.prototype.apply = function (skeleton, lastTime, time, events, alpha, setupPose, mixingOut) { + TranslateTimeline.prototype.apply = function (skeleton, lastTime, time, events, alpha, pose, direction) { var frames = this.frames; var bone = skeleton.bones[this.boneIndex]; if (time < frames[0]) { - if (setupPose) { - bone.x = bone.data.x; - bone.y = bone.data.y; + switch (pose) { + case MixPose.setup: + bone.x = bone.data.x; + bone.y = bone.data.y; + return; + case MixPose.current: + bone.x += (bone.data.x - bone.x) * alpha; + bone.y += (bone.data.y - bone.y) * alpha; } return; } @@ -249,7 +280,7 @@ var spine; x += (frames[frame + TranslateTimeline.X] - x) * percent; y += (frames[frame + TranslateTimeline.Y] - y) * percent; } - if (setupPose) { + if (pose == MixPose.setup) { bone.x = bone.data.x + x * alpha; bone.y = bone.data.y + y * alpha; } @@ -258,30 +289,35 @@ var spine; bone.y += (bone.data.y + y - bone.y) * alpha; } }; - TranslateTimeline.ENTRIES = 3; - TranslateTimeline.PREV_TIME = -3; - TranslateTimeline.PREV_X = -2; - TranslateTimeline.PREV_Y = -1; - TranslateTimeline.X = 1; - TranslateTimeline.Y = 2; return TranslateTimeline; }(CurveTimeline)); + TranslateTimeline.ENTRIES = 3; + TranslateTimeline.PREV_TIME = -3; + TranslateTimeline.PREV_X = -2; + TranslateTimeline.PREV_Y = -1; + TranslateTimeline.X = 1; + TranslateTimeline.Y = 2; spine.TranslateTimeline = TranslateTimeline; var ScaleTimeline = (function (_super) { __extends(ScaleTimeline, _super); function ScaleTimeline(frameCount) { - _super.call(this, frameCount); + return _super.call(this, frameCount) || this; } ScaleTimeline.prototype.getPropertyId = function () { return (TimelineType.scale << 24) + this.boneIndex; }; - ScaleTimeline.prototype.apply = function (skeleton, lastTime, time, events, alpha, setupPose, mixingOut) { + ScaleTimeline.prototype.apply = function (skeleton, lastTime, time, events, alpha, pose, direction) { var frames = this.frames; var bone = skeleton.bones[this.boneIndex]; if (time < frames[0]) { - if (setupPose) { - bone.scaleX = bone.data.scaleX; - bone.scaleY = bone.data.scaleY; + switch (pose) { + case MixPose.setup: + bone.scaleX = bone.data.scaleX; + bone.scaleY = bone.data.scaleY; + return; + case MixPose.current: + bone.scaleX += (bone.data.scaleX - bone.scaleX) * alpha; + bone.scaleY += (bone.data.scaleY - bone.scaleY) * alpha; } return; } @@ -305,7 +341,7 @@ var spine; } else { var bx = 0, by = 0; - if (setupPose) { + if (pose == MixPose.setup) { bx = bone.data.scaleX; by = bone.data.scaleY; } @@ -313,7 +349,7 @@ var spine; bx = bone.scaleX; by = bone.scaleY; } - if (mixingOut) { + if (direction == MixDirection.out) { x = Math.abs(x) * spine.MathUtils.signum(bx); y = Math.abs(y) * spine.MathUtils.signum(by); } @@ -331,18 +367,23 @@ var spine; var ShearTimeline = (function (_super) { __extends(ShearTimeline, _super); function ShearTimeline(frameCount) { - _super.call(this, frameCount); + return _super.call(this, frameCount) || this; } ShearTimeline.prototype.getPropertyId = function () { return (TimelineType.shear << 24) + this.boneIndex; }; - ShearTimeline.prototype.apply = function (skeleton, lastTime, time, events, alpha, setupPose, mixingOut) { + ShearTimeline.prototype.apply = function (skeleton, lastTime, time, events, alpha, pose, direction) { var frames = this.frames; var bone = skeleton.bones[this.boneIndex]; if (time < frames[0]) { - if (setupPose) { - bone.shearX = bone.data.shearX; - bone.shearY = bone.data.shearY; + switch (pose) { + case MixPose.setup: + bone.shearX = bone.data.shearX; + bone.shearY = bone.data.shearY; + return; + case MixPose.current: + bone.shearX += (bone.data.shearX - bone.shearX) * alpha; + bone.shearY += (bone.data.shearY - bone.shearY) * alpha; } return; } @@ -360,7 +401,7 @@ var spine; x = x + (frames[frame + ShearTimeline.X] - x) * percent; y = y + (frames[frame + ShearTimeline.Y] - y) * percent; } - if (setupPose) { + if (pose == MixPose.setup) { bone.shearX = bone.data.shearX + x * alpha; bone.shearY = bone.data.shearY + y * alpha; } @@ -375,8 +416,9 @@ var spine; var ColorTimeline = (function (_super) { __extends(ColorTimeline, _super); function ColorTimeline(frameCount) { - _super.call(this, frameCount); - this.frames = spine.Utils.newFloatArray(frameCount * ColorTimeline.ENTRIES); + var _this = _super.call(this, frameCount) || this; + _this.frames = spine.Utils.newFloatArray(frameCount * ColorTimeline.ENTRIES); + return _this; } ColorTimeline.prototype.getPropertyId = function () { return (TimelineType.color << 24) + this.slotIndex; @@ -389,12 +431,18 @@ var spine; this.frames[frameIndex + ColorTimeline.B] = b; this.frames[frameIndex + ColorTimeline.A] = a; }; - ColorTimeline.prototype.apply = function (skeleton, lastTime, time, events, alpha, setupPose, mixingOut) { + ColorTimeline.prototype.apply = function (skeleton, lastTime, time, events, alpha, pose, direction) { var slot = skeleton.slots[this.slotIndex]; var frames = this.frames; if (time < frames[0]) { - if (setupPose) - slot.color.setFromColor(slot.data.color); + switch (pose) { + case MixPose.setup: + slot.color.setFromColor(slot.data.color); + return; + case MixPose.current: + var color = slot.color, setup = slot.data.color; + color.add((setup.r - color.r) * alpha, (setup.g - color.g) * alpha, (setup.b - color.b) * alpha, (setup.a - color.a) * alpha); + } return; } var r = 0, g = 0, b = 0, a = 0; @@ -422,24 +470,124 @@ var spine; slot.color.set(r, g, b, a); else { var color = slot.color; - if (setupPose) + if (pose == MixPose.setup) color.setFromColor(slot.data.color); color.add((r - color.r) * alpha, (g - color.g) * alpha, (b - color.b) * alpha, (a - color.a) * alpha); } }; - ColorTimeline.ENTRIES = 5; - ColorTimeline.PREV_TIME = -5; - ColorTimeline.PREV_R = -4; - ColorTimeline.PREV_G = -3; - ColorTimeline.PREV_B = -2; - ColorTimeline.PREV_A = -1; - ColorTimeline.R = 1; - ColorTimeline.G = 2; - ColorTimeline.B = 3; - ColorTimeline.A = 4; return ColorTimeline; }(CurveTimeline)); + ColorTimeline.ENTRIES = 5; + ColorTimeline.PREV_TIME = -5; + ColorTimeline.PREV_R = -4; + ColorTimeline.PREV_G = -3; + ColorTimeline.PREV_B = -2; + ColorTimeline.PREV_A = -1; + ColorTimeline.R = 1; + ColorTimeline.G = 2; + ColorTimeline.B = 3; + ColorTimeline.A = 4; spine.ColorTimeline = ColorTimeline; + var TwoColorTimeline = (function (_super) { + __extends(TwoColorTimeline, _super); + function TwoColorTimeline(frameCount) { + var _this = _super.call(this, frameCount) || this; + _this.frames = spine.Utils.newFloatArray(frameCount * TwoColorTimeline.ENTRIES); + return _this; + } + TwoColorTimeline.prototype.getPropertyId = function () { + return (TimelineType.twoColor << 24) + this.slotIndex; + }; + TwoColorTimeline.prototype.setFrame = function (frameIndex, time, r, g, b, a, r2, g2, b2) { + frameIndex *= TwoColorTimeline.ENTRIES; + this.frames[frameIndex] = time; + this.frames[frameIndex + TwoColorTimeline.R] = r; + this.frames[frameIndex + TwoColorTimeline.G] = g; + this.frames[frameIndex + TwoColorTimeline.B] = b; + this.frames[frameIndex + TwoColorTimeline.A] = a; + this.frames[frameIndex + TwoColorTimeline.R2] = r2; + this.frames[frameIndex + TwoColorTimeline.G2] = g2; + this.frames[frameIndex + TwoColorTimeline.B2] = b2; + }; + TwoColorTimeline.prototype.apply = function (skeleton, lastTime, time, events, alpha, pose, direction) { + var slot = skeleton.slots[this.slotIndex]; + var frames = this.frames; + if (time < frames[0]) { + switch (pose) { + case MixPose.setup: + slot.color.setFromColor(slot.data.color); + slot.darkColor.setFromColor(slot.data.darkColor); + return; + case MixPose.current: + var light = slot.color, dark = slot.darkColor, setupLight = slot.data.color, setupDark = slot.data.darkColor; + light.add((setupLight.r - light.r) * alpha, (setupLight.g - light.g) * alpha, (setupLight.b - light.b) * alpha, (setupLight.a - light.a) * alpha); + dark.add((setupDark.r - dark.r) * alpha, (setupDark.g - dark.g) * alpha, (setupDark.b - dark.b) * alpha, 0); + } + return; + } + var r = 0, g = 0, b = 0, a = 0, r2 = 0, g2 = 0, b2 = 0; + if (time >= frames[frames.length - TwoColorTimeline.ENTRIES]) { + var i = frames.length; + r = frames[i + TwoColorTimeline.PREV_R]; + g = frames[i + TwoColorTimeline.PREV_G]; + b = frames[i + TwoColorTimeline.PREV_B]; + a = frames[i + TwoColorTimeline.PREV_A]; + r2 = frames[i + TwoColorTimeline.PREV_R2]; + g2 = frames[i + TwoColorTimeline.PREV_G2]; + b2 = frames[i + TwoColorTimeline.PREV_B2]; + } + else { + var frame = Animation.binarySearch(frames, time, TwoColorTimeline.ENTRIES); + r = frames[frame + TwoColorTimeline.PREV_R]; + g = frames[frame + TwoColorTimeline.PREV_G]; + b = frames[frame + TwoColorTimeline.PREV_B]; + a = frames[frame + TwoColorTimeline.PREV_A]; + r2 = frames[frame + TwoColorTimeline.PREV_R2]; + g2 = frames[frame + TwoColorTimeline.PREV_G2]; + b2 = frames[frame + TwoColorTimeline.PREV_B2]; + var frameTime = frames[frame]; + var percent = this.getCurvePercent(frame / TwoColorTimeline.ENTRIES - 1, 1 - (time - frameTime) / (frames[frame + TwoColorTimeline.PREV_TIME] - frameTime)); + r += (frames[frame + TwoColorTimeline.R] - r) * percent; + g += (frames[frame + TwoColorTimeline.G] - g) * percent; + b += (frames[frame + TwoColorTimeline.B] - b) * percent; + a += (frames[frame + TwoColorTimeline.A] - a) * percent; + r2 += (frames[frame + TwoColorTimeline.R2] - r2) * percent; + g2 += (frames[frame + TwoColorTimeline.G2] - g2) * percent; + b2 += (frames[frame + TwoColorTimeline.B2] - b2) * percent; + } + if (alpha == 1) { + slot.color.set(r, g, b, a); + slot.darkColor.set(r2, g2, b2, 1); + } + else { + var light = slot.color, dark = slot.darkColor; + if (pose == MixPose.setup) { + light.setFromColor(slot.data.color); + dark.setFromColor(slot.data.darkColor); + } + light.add((r - light.r) * alpha, (g - light.g) * alpha, (b - light.b) * alpha, (a - light.a) * alpha); + dark.add((r2 - dark.r) * alpha, (g2 - dark.g) * alpha, (b2 - dark.b) * alpha, 0); + } + }; + return TwoColorTimeline; + }(CurveTimeline)); + TwoColorTimeline.ENTRIES = 8; + TwoColorTimeline.PREV_TIME = -8; + TwoColorTimeline.PREV_R = -7; + TwoColorTimeline.PREV_G = -6; + TwoColorTimeline.PREV_B = -5; + TwoColorTimeline.PREV_A = -4; + TwoColorTimeline.PREV_R2 = -3; + TwoColorTimeline.PREV_G2 = -2; + TwoColorTimeline.PREV_B2 = -1; + TwoColorTimeline.R = 1; + TwoColorTimeline.G = 2; + TwoColorTimeline.B = 3; + TwoColorTimeline.A = 4; + TwoColorTimeline.R2 = 5; + TwoColorTimeline.G2 = 6; + TwoColorTimeline.B2 = 7; + spine.TwoColorTimeline = TwoColorTimeline; var AttachmentTimeline = (function () { function AttachmentTimeline(frameCount) { this.frames = spine.Utils.newFloatArray(frameCount); @@ -455,16 +603,16 @@ var spine; this.frames[frameIndex] = time; this.attachmentNames[frameIndex] = attachmentName; }; - AttachmentTimeline.prototype.apply = function (skeleton, lastTime, time, events, alpha, setupPose, mixingOut) { + AttachmentTimeline.prototype.apply = function (skeleton, lastTime, time, events, alpha, pose, direction) { var slot = skeleton.slots[this.slotIndex]; - if (mixingOut && setupPose) { + if (direction == MixDirection.out && pose == MixPose.setup) { var attachmentName_1 = slot.data.attachmentName; slot.setAttachment(attachmentName_1 == null ? null : skeleton.getAttachment(this.slotIndex, attachmentName_1)); return; } var frames = this.frames; if (time < frames[0]) { - if (setupPose) { + if (pose == MixPose.setup) { var attachmentName_2 = slot.data.attachmentName; slot.setAttachment(attachmentName_2 == null ? null : skeleton.getAttachment(this.slotIndex, attachmentName_2)); } @@ -482,59 +630,87 @@ var spine; return AttachmentTimeline; }()); spine.AttachmentTimeline = AttachmentTimeline; + var zeros = null; var DeformTimeline = (function (_super) { __extends(DeformTimeline, _super); function DeformTimeline(frameCount) { - _super.call(this, frameCount); - this.frames = spine.Utils.newFloatArray(frameCount); - this.frameVertices = new Array(frameCount); + var _this = _super.call(this, frameCount) || this; + _this.frames = spine.Utils.newFloatArray(frameCount); + _this.frameVertices = new Array(frameCount); + if (zeros == null) + zeros = spine.Utils.newFloatArray(64); + return _this; } DeformTimeline.prototype.getPropertyId = function () { - return (TimelineType.deform << 24) + this.slotIndex; + return (TimelineType.deform << 27) + +this.attachment.id + this.slotIndex; }; DeformTimeline.prototype.setFrame = function (frameIndex, time, vertices) { this.frames[frameIndex] = time; this.frameVertices[frameIndex] = vertices; }; - DeformTimeline.prototype.apply = function (skeleton, lastTime, time, firedEvents, alpha, setupPose, mixingOut) { + DeformTimeline.prototype.apply = function (skeleton, lastTime, time, firedEvents, alpha, pose, direction) { var slot = skeleton.slots[this.slotIndex]; var slotAttachment = slot.getAttachment(); if (!(slotAttachment instanceof spine.VertexAttachment) || !slotAttachment.applyDeform(this.attachment)) return; - var frames = this.frames; var verticesArray = slot.attachmentVertices; - if (time < frames[0]) { - if (setupPose) - spine.Utils.setArraySize(verticesArray, 0); - return; - } var frameVertices = this.frameVertices; var vertexCount = frameVertices[0].length; - if (verticesArray.length != vertexCount) - alpha = 1; var vertices = spine.Utils.setArraySize(verticesArray, vertexCount); + var frames = this.frames; + if (time < frames[0]) { + var vertexAttachment = slotAttachment; + switch (pose) { + case MixPose.setup: + var zeroVertices; + if (vertexAttachment.bones == null) { + zeroVertices = vertexAttachment.vertices; + } + else { + zeroVertices = zeros; + if (zeroVertices.length < vertexCount) + zeros = zeroVertices = spine.Utils.newFloatArray(vertexCount); + } + spine.Utils.arrayCopy(zeroVertices, 0, vertices, 0, vertexCount); + return; + case MixPose.current: + if (alpha == 1) + break; + if (vertexAttachment.bones == null) { + var setupVertices = vertexAttachment.vertices; + for (var i = 0; i < vertexCount; i++) + vertices[i] += (setupVertices[i] - vertices[i]) * alpha; + } + else { + alpha = 1 - alpha; + for (var i = 0; i < vertexCount; i++) + vertices[i] *= alpha; + } + } + return; + } if (time >= frames[frames.length - 1]) { var lastVertices = frameVertices[frames.length - 1]; if (alpha == 1) { spine.Utils.arrayCopy(lastVertices, 0, vertices, 0, vertexCount); } - else if (setupPose) { + else if (pose == MixPose.setup) { var vertexAttachment = slotAttachment; if (vertexAttachment.bones == null) { - var setupVertices = vertexAttachment.vertices; - for (var i = 0; i < vertexCount; i++) { - var setup = setupVertices[i]; - vertices[i] = setup + (lastVertices[i] - setup) * alpha; + var setupVertices_1 = vertexAttachment.vertices; + for (var i_1 = 0; i_1 < vertexCount; i_1++) { + var setup = setupVertices_1[i_1]; + vertices[i_1] = setup + (lastVertices[i_1] - setup) * alpha; } } else { - for (var i = 0; i < vertexCount; i++) - vertices[i] = lastVertices[i] * alpha; + for (var i_2 = 0; i_2 < vertexCount; i_2++) + vertices[i_2] = lastVertices[i_2] * alpha; } } else { - for (var i = 0; i < vertexCount; i++) - vertices[i] += (lastVertices[i] - vertices[i]) * alpha; + for (var i_3 = 0; i_3 < vertexCount; i_3++) + vertices[i_3] += (lastVertices[i_3] - vertices[i_3]) * alpha; } return; } @@ -544,31 +720,31 @@ var spine; var frameTime = frames[frame]; var percent = this.getCurvePercent(frame - 1, 1 - (time - frameTime) / (frames[frame - 1] - frameTime)); if (alpha == 1) { - for (var i = 0; i < vertexCount; i++) { - var prev = prevVertices[i]; - vertices[i] = prev + (nextVertices[i] - prev) * percent; + for (var i_4 = 0; i_4 < vertexCount; i_4++) { + var prev = prevVertices[i_4]; + vertices[i_4] = prev + (nextVertices[i_4] - prev) * percent; } } - else if (setupPose) { + else if (pose == MixPose.setup) { var vertexAttachment = slotAttachment; if (vertexAttachment.bones == null) { - var setupVertices = vertexAttachment.vertices; - for (var i = 0; i < vertexCount; i++) { - var prev = prevVertices[i], setup = setupVertices[i]; - vertices[i] = setup + (prev + (nextVertices[i] - prev) * percent - setup) * alpha; + var setupVertices_2 = vertexAttachment.vertices; + for (var i_5 = 0; i_5 < vertexCount; i_5++) { + var prev = prevVertices[i_5], setup = setupVertices_2[i_5]; + vertices[i_5] = setup + (prev + (nextVertices[i_5] - prev) * percent - setup) * alpha; } } else { - for (var i = 0; i < vertexCount; i++) { - var prev = prevVertices[i]; - vertices[i] = (prev + (nextVertices[i] - prev) * percent) * alpha; + for (var i_6 = 0; i_6 < vertexCount; i_6++) { + var prev = prevVertices[i_6]; + vertices[i_6] = (prev + (nextVertices[i_6] - prev) * percent) * alpha; } } } else { - for (var i = 0; i < vertexCount; i++) { - var prev = prevVertices[i]; - vertices[i] += (prev + (nextVertices[i] - prev) * percent - vertices[i]) * alpha; + for (var i_7 = 0; i_7 < vertexCount; i_7++) { + var prev = prevVertices[i_7]; + vertices[i_7] += (prev + (nextVertices[i_7] - prev) * percent - vertices[i_7]) * alpha; } } }; @@ -590,13 +766,13 @@ var spine; this.frames[frameIndex] = event.time; this.events[frameIndex] = event; }; - EventTimeline.prototype.apply = function (skeleton, lastTime, time, firedEvents, alpha, setupPose, mixingOut) { + EventTimeline.prototype.apply = function (skeleton, lastTime, time, firedEvents, alpha, pose, direction) { if (firedEvents == null) return; var frames = this.frames; var frameCount = this.frames.length; if (lastTime > time) { - this.apply(skeleton, lastTime, Number.MAX_VALUE, firedEvents, alpha, setupPose, mixingOut); + this.apply(skeleton, lastTime, Number.MAX_VALUE, firedEvents, alpha, pose, direction); lastTime = -1; } else if (lastTime >= frames[frameCount - 1]) @@ -636,16 +812,16 @@ var spine; this.frames[frameIndex] = time; this.drawOrders[frameIndex] = drawOrder; }; - DrawOrderTimeline.prototype.apply = function (skeleton, lastTime, time, firedEvents, alpha, setupPose, mixingOut) { + DrawOrderTimeline.prototype.apply = function (skeleton, lastTime, time, firedEvents, alpha, pose, direction) { var drawOrder = skeleton.drawOrder; var slots = skeleton.slots; - if (mixingOut && setupPose) { + if (direction == MixDirection.out && pose == MixPose.setup) { spine.Utils.arrayCopy(skeleton.slots, 0, skeleton.drawOrder, 0, skeleton.slots.length); return; } var frames = this.frames; if (time < frames[0]) { - if (setupPose) + if (pose == MixPose.setup) spine.Utils.arrayCopy(skeleton.slots, 0, skeleton.drawOrder, 0, skeleton.slots.length); return; } @@ -668,8 +844,9 @@ var spine; var IkConstraintTimeline = (function (_super) { __extends(IkConstraintTimeline, _super); function IkConstraintTimeline(frameCount) { - _super.call(this, frameCount); - this.frames = spine.Utils.newFloatArray(frameCount * IkConstraintTimeline.ENTRIES); + var _this = _super.call(this, frameCount) || this; + _this.frames = spine.Utils.newFloatArray(frameCount * IkConstraintTimeline.ENTRIES); + return _this; } IkConstraintTimeline.prototype.getPropertyId = function () { return (TimelineType.ikConstraint << 24) + this.ikConstraintIndex; @@ -680,25 +857,30 @@ var spine; this.frames[frameIndex + IkConstraintTimeline.MIX] = mix; this.frames[frameIndex + IkConstraintTimeline.BEND_DIRECTION] = bendDirection; }; - IkConstraintTimeline.prototype.apply = function (skeleton, lastTime, time, firedEvents, alpha, setupPose, mixingOut) { + IkConstraintTimeline.prototype.apply = function (skeleton, lastTime, time, firedEvents, alpha, pose, direction) { var frames = this.frames; var constraint = skeleton.ikConstraints[this.ikConstraintIndex]; if (time < frames[0]) { - if (setupPose) { - constraint.mix = constraint.data.mix; - constraint.bendDirection = constraint.data.bendDirection; + switch (pose) { + case MixPose.setup: + constraint.mix = constraint.data.mix; + constraint.bendDirection = constraint.data.bendDirection; + return; + case MixPose.current: + constraint.mix += (constraint.data.mix - constraint.mix) * alpha; + constraint.bendDirection = constraint.data.bendDirection; } return; } if (time >= frames[frames.length - IkConstraintTimeline.ENTRIES]) { - if (setupPose) { + if (pose == MixPose.setup) { constraint.mix = constraint.data.mix + (frames[frames.length + IkConstraintTimeline.PREV_MIX] - constraint.data.mix) * alpha; - constraint.bendDirection = mixingOut ? constraint.data.bendDirection + constraint.bendDirection = direction == MixDirection.out ? constraint.data.bendDirection : frames[frames.length + IkConstraintTimeline.PREV_BEND_DIRECTION]; } else { constraint.mix += (frames[frames.length + IkConstraintTimeline.PREV_MIX] - constraint.mix) * alpha; - if (!mixingOut) + if (direction == MixDirection["in"]) constraint.bendDirection = frames[frames.length + IkConstraintTimeline.PREV_BEND_DIRECTION]; } return; @@ -707,30 +889,31 @@ var spine; var mix = frames[frame + IkConstraintTimeline.PREV_MIX]; var frameTime = frames[frame]; var percent = this.getCurvePercent(frame / IkConstraintTimeline.ENTRIES - 1, 1 - (time - frameTime) / (frames[frame + IkConstraintTimeline.PREV_TIME] - frameTime)); - if (setupPose) { + if (pose == MixPose.setup) { constraint.mix = constraint.data.mix + (mix + (frames[frame + IkConstraintTimeline.MIX] - mix) * percent - constraint.data.mix) * alpha; - constraint.bendDirection = mixingOut ? constraint.data.bendDirection : frames[frame + IkConstraintTimeline.PREV_BEND_DIRECTION]; + constraint.bendDirection = direction == MixDirection.out ? constraint.data.bendDirection : frames[frame + IkConstraintTimeline.PREV_BEND_DIRECTION]; } else { constraint.mix += (mix + (frames[frame + IkConstraintTimeline.MIX] - mix) * percent - constraint.mix) * alpha; - if (!mixingOut) + if (direction == MixDirection["in"]) constraint.bendDirection = frames[frame + IkConstraintTimeline.PREV_BEND_DIRECTION]; } }; - IkConstraintTimeline.ENTRIES = 3; - IkConstraintTimeline.PREV_TIME = -3; - IkConstraintTimeline.PREV_MIX = -2; - IkConstraintTimeline.PREV_BEND_DIRECTION = -1; - IkConstraintTimeline.MIX = 1; - IkConstraintTimeline.BEND_DIRECTION = 2; return IkConstraintTimeline; }(CurveTimeline)); + IkConstraintTimeline.ENTRIES = 3; + IkConstraintTimeline.PREV_TIME = -3; + IkConstraintTimeline.PREV_MIX = -2; + IkConstraintTimeline.PREV_BEND_DIRECTION = -1; + IkConstraintTimeline.MIX = 1; + IkConstraintTimeline.BEND_DIRECTION = 2; spine.IkConstraintTimeline = IkConstraintTimeline; var TransformConstraintTimeline = (function (_super) { __extends(TransformConstraintTimeline, _super); function TransformConstraintTimeline(frameCount) { - _super.call(this, frameCount); - this.frames = spine.Utils.newFloatArray(frameCount * TransformConstraintTimeline.ENTRIES); + var _this = _super.call(this, frameCount) || this; + _this.frames = spine.Utils.newFloatArray(frameCount * TransformConstraintTimeline.ENTRIES); + return _this; } TransformConstraintTimeline.prototype.getPropertyId = function () { return (TimelineType.transformConstraint << 24) + this.transformConstraintIndex; @@ -743,16 +926,23 @@ var spine; this.frames[frameIndex + TransformConstraintTimeline.SCALE] = scaleMix; this.frames[frameIndex + TransformConstraintTimeline.SHEAR] = shearMix; }; - TransformConstraintTimeline.prototype.apply = function (skeleton, lastTime, time, firedEvents, alpha, setupPose, mixingOut) { + TransformConstraintTimeline.prototype.apply = function (skeleton, lastTime, time, firedEvents, alpha, pose, direction) { var frames = this.frames; var constraint = skeleton.transformConstraints[this.transformConstraintIndex]; if (time < frames[0]) { - if (setupPose) { - var data = constraint.data; - constraint.rotateMix = data.rotateMix; - constraint.translateMix = data.rotateMix; - constraint.scaleMix = data.scaleMix; - constraint.shearMix = data.shearMix; + var data = constraint.data; + switch (pose) { + case MixPose.setup: + constraint.rotateMix = data.rotateMix; + constraint.translateMix = data.translateMix; + constraint.scaleMix = data.scaleMix; + constraint.shearMix = data.shearMix; + return; + case MixPose.current: + constraint.rotateMix += (data.rotateMix - constraint.rotateMix) * alpha; + constraint.translateMix += (data.translateMix - constraint.translateMix) * alpha; + constraint.scaleMix += (data.scaleMix - constraint.scaleMix) * alpha; + constraint.shearMix += (data.shearMix - constraint.shearMix) * alpha; } return; } @@ -777,7 +967,7 @@ var spine; scale += (frames[frame + TransformConstraintTimeline.SCALE] - scale) * percent; shear += (frames[frame + TransformConstraintTimeline.SHEAR] - shear) * percent; } - if (setupPose) { + if (pose == MixPose.setup) { var data = constraint.data; constraint.rotateMix = data.rotateMix + (rotate - data.rotateMix) * alpha; constraint.translateMix = data.translateMix + (translate - data.translateMix) * alpha; @@ -791,24 +981,25 @@ var spine; constraint.shearMix += (shear - constraint.shearMix) * alpha; } }; - TransformConstraintTimeline.ENTRIES = 5; - TransformConstraintTimeline.PREV_TIME = -5; - TransformConstraintTimeline.PREV_ROTATE = -4; - TransformConstraintTimeline.PREV_TRANSLATE = -3; - TransformConstraintTimeline.PREV_SCALE = -2; - TransformConstraintTimeline.PREV_SHEAR = -1; - TransformConstraintTimeline.ROTATE = 1; - TransformConstraintTimeline.TRANSLATE = 2; - TransformConstraintTimeline.SCALE = 3; - TransformConstraintTimeline.SHEAR = 4; return TransformConstraintTimeline; }(CurveTimeline)); + TransformConstraintTimeline.ENTRIES = 5; + TransformConstraintTimeline.PREV_TIME = -5; + TransformConstraintTimeline.PREV_ROTATE = -4; + TransformConstraintTimeline.PREV_TRANSLATE = -3; + TransformConstraintTimeline.PREV_SCALE = -2; + TransformConstraintTimeline.PREV_SHEAR = -1; + TransformConstraintTimeline.ROTATE = 1; + TransformConstraintTimeline.TRANSLATE = 2; + TransformConstraintTimeline.SCALE = 3; + TransformConstraintTimeline.SHEAR = 4; spine.TransformConstraintTimeline = TransformConstraintTimeline; var PathConstraintPositionTimeline = (function (_super) { __extends(PathConstraintPositionTimeline, _super); function PathConstraintPositionTimeline(frameCount) { - _super.call(this, frameCount); - this.frames = spine.Utils.newFloatArray(frameCount * PathConstraintPositionTimeline.ENTRIES); + var _this = _super.call(this, frameCount) || this; + _this.frames = spine.Utils.newFloatArray(frameCount * PathConstraintPositionTimeline.ENTRIES); + return _this; } PathConstraintPositionTimeline.prototype.getPropertyId = function () { return (TimelineType.pathConstraintPosition << 24) + this.pathConstraintIndex; @@ -818,12 +1009,17 @@ var spine; this.frames[frameIndex] = time; this.frames[frameIndex + PathConstraintPositionTimeline.VALUE] = value; }; - PathConstraintPositionTimeline.prototype.apply = function (skeleton, lastTime, time, firedEvents, alpha, setupPose, mixingOut) { + PathConstraintPositionTimeline.prototype.apply = function (skeleton, lastTime, time, firedEvents, alpha, pose, direction) { var frames = this.frames; var constraint = skeleton.pathConstraints[this.pathConstraintIndex]; if (time < frames[0]) { - if (setupPose) - constraint.position = constraint.data.position; + switch (pose) { + case MixPose.setup: + constraint.position = constraint.data.position; + return; + case MixPose.current: + constraint.position += (constraint.data.position - constraint.position) * alpha; + } return; } var position = 0; @@ -836,32 +1032,37 @@ var spine; var percent = this.getCurvePercent(frame / PathConstraintPositionTimeline.ENTRIES - 1, 1 - (time - frameTime) / (frames[frame + PathConstraintPositionTimeline.PREV_TIME] - frameTime)); position += (frames[frame + PathConstraintPositionTimeline.VALUE] - position) * percent; } - if (setupPose) + if (pose == MixPose.setup) constraint.position = constraint.data.position + (position - constraint.data.position) * alpha; else constraint.position += (position - constraint.position) * alpha; }; - PathConstraintPositionTimeline.ENTRIES = 2; - PathConstraintPositionTimeline.PREV_TIME = -2; - PathConstraintPositionTimeline.PREV_VALUE = -1; - PathConstraintPositionTimeline.VALUE = 1; return PathConstraintPositionTimeline; }(CurveTimeline)); + PathConstraintPositionTimeline.ENTRIES = 2; + PathConstraintPositionTimeline.PREV_TIME = -2; + PathConstraintPositionTimeline.PREV_VALUE = -1; + PathConstraintPositionTimeline.VALUE = 1; spine.PathConstraintPositionTimeline = PathConstraintPositionTimeline; var PathConstraintSpacingTimeline = (function (_super) { __extends(PathConstraintSpacingTimeline, _super); function PathConstraintSpacingTimeline(frameCount) { - _super.call(this, frameCount); + return _super.call(this, frameCount) || this; } PathConstraintSpacingTimeline.prototype.getPropertyId = function () { return (TimelineType.pathConstraintSpacing << 24) + this.pathConstraintIndex; }; - PathConstraintSpacingTimeline.prototype.apply = function (skeleton, lastTime, time, firedEvents, alpha, setupPose, mixingOut) { + PathConstraintSpacingTimeline.prototype.apply = function (skeleton, lastTime, time, firedEvents, alpha, pose, direction) { var frames = this.frames; var constraint = skeleton.pathConstraints[this.pathConstraintIndex]; if (time < frames[0]) { - if (setupPose) - constraint.spacing = constraint.data.spacing; + switch (pose) { + case MixPose.setup: + constraint.spacing = constraint.data.spacing; + return; + case MixPose.current: + constraint.spacing += (constraint.data.spacing - constraint.spacing) * alpha; + } return; } var spacing = 0; @@ -874,7 +1075,7 @@ var spine; var percent = this.getCurvePercent(frame / PathConstraintSpacingTimeline.ENTRIES - 1, 1 - (time - frameTime) / (frames[frame + PathConstraintSpacingTimeline.PREV_TIME] - frameTime)); spacing += (frames[frame + PathConstraintSpacingTimeline.VALUE] - spacing) * percent; } - if (setupPose) + if (pose == MixPose.setup) constraint.spacing = constraint.data.spacing + (spacing - constraint.data.spacing) * alpha; else constraint.spacing += (spacing - constraint.spacing) * alpha; @@ -885,8 +1086,9 @@ var spine; var PathConstraintMixTimeline = (function (_super) { __extends(PathConstraintMixTimeline, _super); function PathConstraintMixTimeline(frameCount) { - _super.call(this, frameCount); - this.frames = spine.Utils.newFloatArray(frameCount * PathConstraintMixTimeline.ENTRIES); + var _this = _super.call(this, frameCount) || this; + _this.frames = spine.Utils.newFloatArray(frameCount * PathConstraintMixTimeline.ENTRIES); + return _this; } PathConstraintMixTimeline.prototype.getPropertyId = function () { return (TimelineType.pathConstraintMix << 24) + this.pathConstraintIndex; @@ -897,13 +1099,18 @@ var spine; this.frames[frameIndex + PathConstraintMixTimeline.ROTATE] = rotateMix; this.frames[frameIndex + PathConstraintMixTimeline.TRANSLATE] = translateMix; }; - PathConstraintMixTimeline.prototype.apply = function (skeleton, lastTime, time, firedEvents, alpha, setupPose, mixingOut) { + PathConstraintMixTimeline.prototype.apply = function (skeleton, lastTime, time, firedEvents, alpha, pose, direction) { var frames = this.frames; var constraint = skeleton.pathConstraints[this.pathConstraintIndex]; if (time < frames[0]) { - if (setupPose) { - constraint.rotateMix = constraint.data.rotateMix; - constraint.translateMix = constraint.data.translateMix; + switch (pose) { + case MixPose.setup: + constraint.rotateMix = constraint.data.rotateMix; + constraint.translateMix = constraint.data.translateMix; + return; + case MixPose.current: + constraint.rotateMix += (constraint.data.rotateMix - constraint.rotateMix) * alpha; + constraint.translateMix += (constraint.data.translateMix - constraint.translateMix) * alpha; } return; } @@ -921,7 +1128,7 @@ var spine; rotate += (frames[frame + PathConstraintMixTimeline.ROTATE] - rotate) * percent; translate += (frames[frame + PathConstraintMixTimeline.TRANSLATE] - translate) * percent; } - if (setupPose) { + if (pose == MixPose.setup) { constraint.rotateMix = constraint.data.rotateMix + (rotate - constraint.data.rotateMix) * alpha; constraint.translateMix = constraint.data.translateMix + (translate - constraint.data.translateMix) * alpha; } @@ -930,14 +1137,14 @@ var spine; constraint.translateMix += (translate - constraint.translateMix) * alpha; } }; - PathConstraintMixTimeline.ENTRIES = 3; - PathConstraintMixTimeline.PREV_TIME = -3; - PathConstraintMixTimeline.PREV_ROTATE = -2; - PathConstraintMixTimeline.PREV_TRANSLATE = -1; - PathConstraintMixTimeline.ROTATE = 1; - PathConstraintMixTimeline.TRANSLATE = 2; return PathConstraintMixTimeline; }(CurveTimeline)); + PathConstraintMixTimeline.ENTRIES = 3; + PathConstraintMixTimeline.PREV_TIME = -3; + PathConstraintMixTimeline.PREV_ROTATE = -2; + PathConstraintMixTimeline.PREV_TRANSLATE = -1; + PathConstraintMixTimeline.ROTATE = 1; + PathConstraintMixTimeline.TRANSLATE = 2; spine.PathConstraintMixTimeline = PathConstraintMixTimeline; })(spine || (spine = {})); var spine; @@ -949,6 +1156,7 @@ var spine; this.listeners = new Array(); this.queue = new EventQueue(this); this.propertyIDs = new spine.IntSet(); + this.mixingTo = new Array(); this.animationsChanged = false; this.timeScale = 1; this.trackEntryPool = new spine.Pool(function () { return new TrackEntry(); }); @@ -986,33 +1194,42 @@ var spine; continue; } } - else { - if (current.trackLast >= current.trackEnd && current.mixingFrom == null) { - tracks[i] = null; - this.queue.end(current); - this.disposeNext(current); - continue; + else if (current.trackLast >= current.trackEnd && current.mixingFrom == null) { + tracks[i] = null; + this.queue.end(current); + this.disposeNext(current); + continue; + } + if (current.mixingFrom != null && this.updateMixingFrom(current, delta)) { + var from = current.mixingFrom; + current.mixingFrom = null; + while (from != null) { + this.queue.end(from); + from = from.mixingFrom; } } - this.updateMixingFrom(current, delta); current.trackTime += currentDelta; } this.queue.drain(); }; - AnimationState.prototype.updateMixingFrom = function (entry, delta) { - var from = entry.mixingFrom; + AnimationState.prototype.updateMixingFrom = function (to, delta) { + var from = to.mixingFrom; if (from == null) - return; - this.updateMixingFrom(from, delta); - if (entry.mixTime >= entry.mixDuration && from.mixingFrom != null && entry.mixTime > 0) { - entry.mixingFrom = null; - this.queue.end(from); - return; + return true; + var finished = this.updateMixingFrom(from, delta); + if (to.mixTime > 0 && (to.mixTime >= to.mixDuration || to.timeScale == 0)) { + if (from.totalAlpha == 0 || to.mixDuration == 0) { + to.mixingFrom = from.mixingFrom; + to.interruptAlpha = from.interruptAlpha; + this.queue.end(from); + } + return finished; } from.animationLast = from.nextAnimationLast; from.trackLast = from.nextTrackLast; from.trackTime += delta * from.timeScale; - entry.mixTime += delta * from.timeScale; + to.mixTime += delta * to.timeScale; + return false; }; AnimationState.prototype.apply = function (skeleton) { if (skeleton == null) @@ -1021,35 +1238,39 @@ var spine; this._animationsChanged(); var events = this.events; var tracks = this.tracks; + var applied = false; for (var i = 0, n = tracks.length; i < n; i++) { var current = tracks[i]; if (current == null || current.delay > 0) continue; + applied = true; + var currentPose = i == 0 ? spine.MixPose.current : spine.MixPose.currentLayered; var mix = current.alpha; if (current.mixingFrom != null) - mix *= this.applyMixingFrom(current, skeleton); - else if (current.trackTime >= current.trackEnd) + mix *= this.applyMixingFrom(current, skeleton, currentPose); + else if (current.trackTime >= current.trackEnd && current.next == null) mix = 0; var animationLast = current.animationLast, animationTime = current.getAnimationTime(); var timelineCount = current.animation.timelines.length; var timelines = current.animation.timelines; if (mix == 1) { for (var ii = 0; ii < timelineCount; ii++) - timelines[ii].apply(skeleton, animationLast, animationTime, events, 1, true, false); + timelines[ii].apply(skeleton, animationLast, animationTime, events, 1, spine.MixPose.setup, spine.MixDirection["in"]); } else { + var timelineData = current.timelineData; var firstFrame = current.timelinesRotation.length == 0; if (firstFrame) spine.Utils.setArraySize(current.timelinesRotation, timelineCount << 1, null); var timelinesRotation = current.timelinesRotation; - var timelinesFirst = current.timelinesFirst; for (var ii = 0; ii < timelineCount; ii++) { var timeline = timelines[ii]; + var pose = timelineData[ii] >= AnimationState.FIRST ? spine.MixPose.setup : currentPose; if (timeline instanceof spine.RotateTimeline) { - this.applyRotateTimeline(timeline, skeleton, animationTime, mix, timelinesFirst[ii], timelinesRotation, ii << 1, firstFrame); + this.applyRotateTimeline(timeline, skeleton, animationTime, mix, pose, timelinesRotation, ii << 1, firstFrame); } else - timeline.apply(skeleton, animationLast, animationTime, events, mix, timelinesFirst[ii], false); + timeline.apply(skeleton, animationLast, animationTime, events, mix, pose, spine.MixDirection["in"]); } } this.queueEvents(current, animationTime); @@ -1058,16 +1279,17 @@ var spine; current.nextTrackLast = current.trackTime; } this.queue.drain(); + return applied; }; - AnimationState.prototype.applyMixingFrom = function (entry, skeleton) { - var from = entry.mixingFrom; + AnimationState.prototype.applyMixingFrom = function (to, skeleton, currentPose) { + var from = to.mixingFrom; if (from.mixingFrom != null) - this.applyMixingFrom(from, skeleton); + this.applyMixingFrom(from, skeleton, currentPose); var mix = 0; - if (entry.mixDuration == 0) + if (to.mixDuration == 0) mix = 1; else { - mix = entry.mixTime / entry.mixDuration; + mix = to.mixTime / to.mixDuration; if (mix > 1) mix = 1; } @@ -1076,46 +1298,67 @@ var spine; var animationLast = from.animationLast, animationTime = from.getAnimationTime(); var timelineCount = from.animation.timelines.length; var timelines = from.animation.timelines; - var timelinesFirst = from.timelinesFirst; - var alpha = from.alpha * entry.mixAlpha * (1 - mix); + var timelineData = from.timelineData; + var timelineDipMix = from.timelineDipMix; var firstFrame = from.timelinesRotation.length == 0; if (firstFrame) spine.Utils.setArraySize(from.timelinesRotation, timelineCount << 1, null); var timelinesRotation = from.timelinesRotation; + var pose; + var alphaDip = from.alpha * to.interruptAlpha, alphaMix = alphaDip * (1 - mix), alpha = 0; + from.totalAlpha = 0; for (var i = 0; i < timelineCount; i++) { var timeline = timelines[i]; - var setupPose = timelinesFirst[i]; - if (timeline instanceof spine.RotateTimeline) - this.applyRotateTimeline(timeline, skeleton, animationTime, alpha, setupPose, timelinesRotation, i << 1, firstFrame); - else { - if (!setupPose) { + switch (timelineData[i]) { + case AnimationState.SUBSEQUENT: if (!attachments && timeline instanceof spine.AttachmentTimeline) continue; if (!drawOrder && timeline instanceof spine.DrawOrderTimeline) continue; - } - timeline.apply(skeleton, animationLast, animationTime, events, alpha, setupPose, true); + pose = currentPose; + alpha = alphaMix; + break; + case AnimationState.FIRST: + pose = spine.MixPose.setup; + alpha = alphaMix; + break; + case AnimationState.DIP: + pose = spine.MixPose.setup; + alpha = alphaDip; + break; + default: + pose = spine.MixPose.setup; + alpha = alphaDip; + var dipMix = timelineDipMix[i]; + alpha *= Math.max(0, 1 - dipMix.mixTime / dipMix.mixDuration); + break; + } + from.totalAlpha += alpha; + if (timeline instanceof spine.RotateTimeline) + this.applyRotateTimeline(timeline, skeleton, animationTime, alpha, pose, timelinesRotation, i << 1, firstFrame); + else { + timeline.apply(skeleton, animationLast, animationTime, events, alpha, pose, spine.MixDirection.out); } } - if (entry.mixDuration > 0) + if (to.mixDuration > 0) this.queueEvents(from, animationTime); this.events.length = 0; from.nextAnimationLast = animationTime; from.nextTrackLast = from.trackTime; return mix; }; - AnimationState.prototype.applyRotateTimeline = function (timeline, skeleton, time, alpha, setupPose, timelinesRotation, i, firstFrame) { + AnimationState.prototype.applyRotateTimeline = function (timeline, skeleton, time, alpha, pose, timelinesRotation, i, firstFrame) { if (firstFrame) timelinesRotation[i] = 0; if (alpha == 1) { - timeline.apply(skeleton, 0, time, null, 1, setupPose, false); + timeline.apply(skeleton, 0, time, null, 1, pose, spine.MixDirection["in"]); return; } var rotateTimeline = timeline; var frames = rotateTimeline.frames; var bone = skeleton.bones[rotateTimeline.boneIndex]; if (time < frames[0]) { - if (setupPose) + if (pose == spine.MixPose.setup) bone.rotation = bone.data.rotation; return; } @@ -1132,7 +1375,7 @@ var spine; r2 = prevRotation + r2 * percent + bone.data.rotation; r2 -= (16384 - ((16384.499999999996 - r2 / 360) | 0)) * 360; } - var r1 = setupPose ? bone.data.rotation : bone.rotation; + var r1 = pose == spine.MixPose.setup ? bone.data.rotation : bone.rotation; var total = 0, diff = r2 - r1; if (diff == 0) { total = timelinesRotation[i]; @@ -1189,11 +1432,12 @@ var spine; } }; AnimationState.prototype.clearTracks = function () { + var oldDrainDisabled = this.queue.drainDisabled; this.queue.drainDisabled = true; for (var i = 0, n = this.tracks.length; i < n; i++) this.clearTrack(i); this.tracks.length = 0; - this.queue.drainDisabled = false; + this.queue.drainDisabled = oldDrainDisabled; this.queue.drain(); }; AnimationState.prototype.clearTrack = function (trackIndex) { @@ -1224,9 +1468,9 @@ var spine; this.queue.interrupt(from); current.mixingFrom = from; current.mixTime = 0; - from.timelinesRotation.length = 0; if (from.mixingFrom != null && from.mixDuration > 0) - current.mixAlpha *= Math.min(from.mixTime / from.mixDuration, 1); + current.interruptAlpha *= Math.min(1, from.mixTime / from.mixDuration); + from.timelinesRotation.length = 0; } this.queue.start(current); }; @@ -1305,13 +1549,14 @@ var spine; return entry; }; AnimationState.prototype.setEmptyAnimations = function (mixDuration) { + var oldDrainDisabled = this.queue.drainDisabled; this.queue.drainDisabled = true; for (var i = 0, n = this.tracks.length; i < n; i++) { var current = this.tracks[i]; if (current != null) this.setEmptyAnimation(current.trackIndex, mixDuration); } - this.queue.drainDisabled = false; + this.queue.drainDisabled = oldDrainDisabled; this.queue.drain(); }; AnimationState.prototype.expandToIndex = function (index) { @@ -1340,7 +1585,7 @@ var spine; entry.trackEnd = Number.MAX_VALUE; entry.timeScale = 1; entry.alpha = 1; - entry.mixAlpha = 1; + entry.interruptAlpha = 1; entry.mixTime = 0; entry.mixDuration = last == null ? 0 : this.data.getMix(last.animation, animation); return entry; @@ -1356,50 +1601,14 @@ var spine; AnimationState.prototype._animationsChanged = function () { this.animationsChanged = false; var propertyIDs = this.propertyIDs; - var i = 0, n = this.tracks.length; propertyIDs.clear(); - for (; i < n; i++) { - var entry = this.tracks[i]; - if (entry == null) - continue; - this.setTimelinesFirst(entry); - i++; - break; - } - for (; i < n; i++) { + var mixingTo = this.mixingTo; + for (var i = 0, n = this.tracks.length; i < n; i++) { var entry = this.tracks[i]; if (entry != null) - this.checkTimelinesFirst(entry); - } - }; - AnimationState.prototype.setTimelinesFirst = function (entry) { - if (entry.mixingFrom != null) { - this.setTimelinesFirst(entry.mixingFrom); - this.checkTimelinesUsage(entry, entry.timelinesFirst); - return; - } - var propertyIDs = this.propertyIDs; - var timelines = entry.animation.timelines; - var n = timelines.length; - var usage = spine.Utils.setArraySize(entry.timelinesFirst, n, false); - for (var i = 0; i < n; i++) { - propertyIDs.add(timelines[i].getPropertyId()); - usage[i] = true; + entry.setTimelineData(null, mixingTo, propertyIDs); } }; - AnimationState.prototype.checkTimelinesFirst = function (entry) { - if (entry.mixingFrom != null) - this.checkTimelinesFirst(entry.mixingFrom); - this.checkTimelinesUsage(entry, entry.timelinesFirst); - }; - AnimationState.prototype.checkTimelinesUsage = function (entry, usageArray) { - var propertyIDs = this.propertyIDs; - var timelines = entry.animation.timelines; - var n = timelines.length; - var usage = spine.Utils.setArraySize(usageArray, n); - for (var i = 0; i < n; i++) - usage[i] = propertyIDs.add(timelines[i].getPropertyId()); - }; AnimationState.prototype.getCurrent = function (trackIndex) { if (trackIndex >= this.tracks.length) return null; @@ -1421,13 +1630,18 @@ var spine; AnimationState.prototype.clearListenerNotifications = function () { this.queue.clear(); }; - AnimationState.emptyAnimation = new spine.Animation("", [], 0); return AnimationState; }()); + AnimationState.emptyAnimation = new spine.Animation("", [], 0); + AnimationState.SUBSEQUENT = 0; + AnimationState.FIRST = 1; + AnimationState.DIP = 2; + AnimationState.DIP_MIX = 3; spine.AnimationState = AnimationState; var TrackEntry = (function () { function TrackEntry() { - this.timelinesFirst = new Array(); + this.timelineData = new Array(); + this.timelineDipMix = new Array(); this.timelinesRotation = new Array(); } TrackEntry.prototype.reset = function () { @@ -1435,9 +1649,52 @@ var spine; this.mixingFrom = null; this.animation = null; this.listener = null; - this.timelinesFirst.length = 0; + this.timelineData.length = 0; + this.timelineDipMix.length = 0; this.timelinesRotation.length = 0; }; + TrackEntry.prototype.setTimelineData = function (to, mixingToArray, propertyIDs) { + if (to != null) + mixingToArray.push(to); + var lastEntry = this.mixingFrom != null ? this.mixingFrom.setTimelineData(this, mixingToArray, propertyIDs) : this; + if (to != null) + mixingToArray.pop(); + var mixingTo = mixingToArray; + var mixingToLast = mixingToArray.length - 1; + var timelines = this.animation.timelines; + var timelinesCount = this.animation.timelines.length; + var timelineData = spine.Utils.setArraySize(this.timelineData, timelinesCount); + this.timelineDipMix.length = 0; + var timelineDipMix = spine.Utils.setArraySize(this.timelineDipMix, timelinesCount); + outer: for (var i = 0; i < timelinesCount; i++) { + var id = timelines[i].getPropertyId(); + if (!propertyIDs.add(id)) + timelineData[i] = AnimationState.SUBSEQUENT; + else if (to == null || !to.hasTimeline(id)) + timelineData[i] = AnimationState.FIRST; + else { + for (var ii = mixingToLast; ii >= 0; ii--) { + var entry = mixingTo[ii]; + if (!entry.hasTimeline(id)) { + if (entry.mixDuration > 0) { + timelineData[i] = AnimationState.DIP_MIX; + timelineDipMix[i] = entry; + continue outer; + } + } + } + timelineData[i] = AnimationState.DIP; + } + } + return lastEntry; + }; + TrackEntry.prototype.hasTimeline = function (id) { + var timelines = this.animation.timelines; + for (var i = 0, n = timelines.length; i < n; i++) + if (timelines[i].getPropertyId() == id) + return true; + return false; + }; TrackEntry.prototype.getAnimationTime = function () { if (this.loop) { var duration = this.animationEnd - this.animationStart; @@ -1557,6 +1814,7 @@ var spine; return EventQueue; }()); spine.EventQueue = EventQueue; + var EventType; (function (EventType) { EventType[EventType["start"] = 0] = "start"; EventType[EventType["interrupt"] = 1] = "interrupt"; @@ -1564,8 +1822,7 @@ var spine; EventType[EventType["dispose"] = 3] = "dispose"; EventType[EventType["complete"] = 4] = "complete"; EventType[EventType["event"] = 5] = "event"; - })(spine.EventType || (spine.EventType = {})); - var EventType = spine.EventType; + })(EventType = spine.EventType || (spine.EventType = {})); var AnimationStateAdapter2 = (function () { function AnimationStateAdapter2() { } @@ -1667,7 +1924,30 @@ var spine; this.toLoad++; var img = new Image(); img.crossOrigin = "anonymous"; + img.onload = function (ev) { + var texture = _this.textureLoader(img); + _this.assets[path] = texture; + _this.toLoad--; + _this.loaded++; + if (success) + success(path, img); + }; + img.onerror = function (ev) { + _this.errors[path] = "Couldn't load image " + path; + _this.toLoad--; + _this.loaded++; + if (error) + error(path, "Couldn't load image " + path); + }; img.src = path; + }; + AssetManager.prototype.loadTextureData = function (path, data, success, error) { + var _this = this; + if (success === void 0) { success = null; } + if (error === void 0) { error = null; } + path = this.pathPrefix + path; + this.toLoad++; + var img = new Image(); img.onload = function (ev) { var texture = _this.textureLoader(img); _this.assets[path] = texture; @@ -1683,6 +1963,7 @@ var spine; if (error) error(path, "Couldn't load image " + path); }; + img.src = data; }; AssetManager.prototype.get = function (path) { path = this.pathPrefix + path; @@ -1755,511 +2036,102 @@ var spine; AtlasAttachmentLoader.prototype.newPathAttachment = function (skin, name) { return new spine.PathAttachment(name); }; + AtlasAttachmentLoader.prototype.newPointAttachment = function (skin, name) { + return new spine.PointAttachment(name); + }; + AtlasAttachmentLoader.prototype.newClippingAttachment = function (skin, name) { + return new spine.ClippingAttachment(name); + }; return AtlasAttachmentLoader; }()); spine.AtlasAttachmentLoader = AtlasAttachmentLoader; })(spine || (spine = {})); var spine; (function (spine) { - var Attachment = (function () { - function Attachment(name) { - if (name == null) - throw new Error("name cannot be null."); - this.name = name; - } - return Attachment; - }()); - spine.Attachment = Attachment; - var VertexAttachment = (function (_super) { - __extends(VertexAttachment, _super); - function VertexAttachment(name) { - _super.call(this, name); - this.worldVerticesLength = 0; + var BlendMode; + (function (BlendMode) { + BlendMode[BlendMode["Normal"] = 0] = "Normal"; + BlendMode[BlendMode["Additive"] = 1] = "Additive"; + BlendMode[BlendMode["Multiply"] = 2] = "Multiply"; + BlendMode[BlendMode["Screen"] = 3] = "Screen"; + })(BlendMode = spine.BlendMode || (spine.BlendMode = {})); +})(spine || (spine = {})); +var spine; +(function (spine) { + var Bone = (function () { + function Bone(data, skeleton, parent) { + this.children = new Array(); + this.x = 0; + this.y = 0; + this.rotation = 0; + this.scaleX = 0; + this.scaleY = 0; + this.shearX = 0; + this.shearY = 0; + this.ax = 0; + this.ay = 0; + this.arotation = 0; + this.ascaleX = 0; + this.ascaleY = 0; + this.ashearX = 0; + this.ashearY = 0; + this.appliedValid = false; + this.a = 0; + this.b = 0; + this.worldX = 0; + this.c = 0; + this.d = 0; + this.worldY = 0; + this.sorted = false; + if (data == null) + throw new Error("data cannot be null."); + if (skeleton == null) + throw new Error("skeleton cannot be null."); + this.data = data; + this.skeleton = skeleton; + this.parent = parent; + this.setToSetupPose(); } - VertexAttachment.prototype.computeWorldVertices = function (slot, worldVertices) { - this.computeWorldVerticesWith(slot, 0, this.worldVerticesLength, worldVertices, 0); + Bone.prototype.update = function () { + this.updateWorldTransformWith(this.x, this.y, this.rotation, this.scaleX, this.scaleY, this.shearX, this.shearY); }; - VertexAttachment.prototype.computeWorldVerticesWith = function (slot, start, count, worldVertices, offset) { - count += offset; - var skeleton = slot.bone.skeleton; - var deformArray = slot.attachmentVertices; - var vertices = this.vertices; - var bones = this.bones; - if (bones == null) { - if (deformArray.length > 0) - vertices = deformArray; - var bone = slot.bone; - var x = bone.worldX; - var y = bone.worldY; - var a = bone.a, b = bone.b, c = bone.c, d = bone.d; - for (var v_1 = start, w = offset; w < count; v_1 += 2, w += 2) { - var vx = vertices[v_1], vy = vertices[v_1 + 1]; - worldVertices[w] = vx * a + vy * b + x; - worldVertices[w + 1] = vx * c + vy * d + y; + Bone.prototype.updateWorldTransform = function () { + this.updateWorldTransformWith(this.x, this.y, this.rotation, this.scaleX, this.scaleY, this.shearX, this.shearY); + }; + Bone.prototype.updateWorldTransformWith = function (x, y, rotation, scaleX, scaleY, shearX, shearY) { + this.ax = x; + this.ay = y; + this.arotation = rotation; + this.ascaleX = scaleX; + this.ascaleY = scaleY; + this.ashearX = shearX; + this.ashearY = shearY; + this.appliedValid = true; + var parent = this.parent; + if (parent == null) { + var rotationY = rotation + 90 + shearY; + var la = spine.MathUtils.cosDeg(rotation + shearX) * scaleX; + var lb = spine.MathUtils.cosDeg(rotationY) * scaleY; + var lc = spine.MathUtils.sinDeg(rotation + shearX) * scaleX; + var ld = spine.MathUtils.sinDeg(rotationY) * scaleY; + var skeleton = this.skeleton; + if (skeleton.flipX) { + x = -x; + la = -la; + lb = -lb; } - return; - } - var v = 0, skip = 0; - for (var i = 0; i < start; i += 2) { - var n = bones[v]; - v += n + 1; - skip += n; - } - var skeletonBones = skeleton.bones; - if (deformArray.length == 0) { - for (var w = offset, b = skip * 3; w < count; w += 2) { - var wx = 0, wy = 0; - var n = bones[v++]; - n += v; - for (; v < n; v++, b += 3) { - var bone = skeletonBones[bones[v]]; - var vx = vertices[b], vy = vertices[b + 1], weight = vertices[b + 2]; - wx += (vx * bone.a + vy * bone.b + bone.worldX) * weight; - wy += (vx * bone.c + vy * bone.d + bone.worldY) * weight; - } - worldVertices[w] = wx; - worldVertices[w + 1] = wy; + if (skeleton.flipY) { + y = -y; + lc = -lc; + ld = -ld; } - } - else { - var deform = deformArray; - for (var w = offset, b = skip * 3, f = skip << 1; w < count; w += 2) { - var wx = 0, wy = 0; - var n = bones[v++]; - n += v; - for (; v < n; v++, b += 3, f += 2) { - var bone = skeletonBones[bones[v]]; - var vx = vertices[b] + deform[f], vy = vertices[b + 1] + deform[f + 1], weight = vertices[b + 2]; - wx += (vx * bone.a + vy * bone.b + bone.worldX) * weight; - wy += (vx * bone.c + vy * bone.d + bone.worldY) * weight; - } - worldVertices[w] = wx; - worldVertices[w + 1] = wy; - } - } - }; - VertexAttachment.prototype.applyDeform = function (sourceAttachment) { - return this == sourceAttachment; - }; - return VertexAttachment; - }(Attachment)); - spine.VertexAttachment = VertexAttachment; -})(spine || (spine = {})); -var spine; -(function (spine) { - (function (AttachmentType) { - AttachmentType[AttachmentType["Region"] = 0] = "Region"; - AttachmentType[AttachmentType["BoundingBox"] = 1] = "BoundingBox"; - AttachmentType[AttachmentType["Mesh"] = 2] = "Mesh"; - AttachmentType[AttachmentType["LinkedMesh"] = 3] = "LinkedMesh"; - AttachmentType[AttachmentType["Path"] = 4] = "Path"; - })(spine.AttachmentType || (spine.AttachmentType = {})); - var AttachmentType = spine.AttachmentType; -})(spine || (spine = {})); -var spine; -(function (spine) { - var BoundingBoxAttachment = (function (_super) { - __extends(BoundingBoxAttachment, _super); - function BoundingBoxAttachment(name) { - _super.call(this, name); - this.color = new spine.Color(1, 1, 1, 1); - } - return BoundingBoxAttachment; - }(spine.VertexAttachment)); - spine.BoundingBoxAttachment = BoundingBoxAttachment; -})(spine || (spine = {})); -var spine; -(function (spine) { - var MeshAttachment = (function (_super) { - __extends(MeshAttachment, _super); - function MeshAttachment(name) { - _super.call(this, name); - this.color = new spine.Color(1, 1, 1, 1); - this.inheritDeform = false; - this.tempColor = new spine.Color(0, 0, 0, 0); - } - MeshAttachment.prototype.updateUVs = function () { - var regionUVs = this.regionUVs; - var verticesLength = regionUVs.length; - var worldVerticesLength = (verticesLength >> 1) * 8; - if (this.worldVertices == null || this.worldVertices.length != worldVerticesLength) - this.worldVertices = spine.Utils.newFloatArray(worldVerticesLength); - var u = 0, v = 0, width = 0, height = 0; - if (this.region == null) { - u = v = 0; - width = height = 1; - } - else { - u = this.region.u; - v = this.region.v; - width = this.region.u2 - u; - height = this.region.v2 - v; - } - if (this.region.rotate) { - for (var i = 0, w = 6; i < verticesLength; i += 2, w += 8) { - this.worldVertices[w] = u + regionUVs[i + 1] * width; - this.worldVertices[w + 1] = v + height - regionUVs[i] * height; - } - } - else { - for (var i = 0, w = 6; i < verticesLength; i += 2, w += 8) { - this.worldVertices[w] = u + regionUVs[i] * width; - this.worldVertices[w + 1] = v + regionUVs[i + 1] * height; - } - } - }; - MeshAttachment.prototype.updateWorldVertices = function (slot, premultipliedAlpha) { - var skeleton = slot.bone.skeleton; - var skeletonColor = skeleton.color, slotColor = slot.color, meshColor = this.color; - var alpha = skeletonColor.a * slotColor.a * meshColor.a; - var multiplier = premultipliedAlpha ? alpha : 1; - var color = this.tempColor; - color.set(skeletonColor.r * slotColor.r * meshColor.r * multiplier, skeletonColor.g * slotColor.g * meshColor.g * multiplier, skeletonColor.b * slotColor.b * meshColor.b * multiplier, alpha); - var deformArray = slot.attachmentVertices; - var vertices = this.vertices, worldVertices = this.worldVertices; - var bones = this.bones; - if (bones == null) { - var verticesLength = vertices.length; - if (deformArray.length > 0) - vertices = deformArray; - var bone = slot.bone; - var x = bone.worldX; - var y = bone.worldY; - var a = bone.a, b = bone.b, c = bone.c, d = bone.d; - for (var v = 0, w = 0; v < verticesLength; v += 2, w += 8) { - var vx = vertices[v], vy = vertices[v + 1]; - worldVertices[w] = vx * a + vy * b + x; - worldVertices[w + 1] = vx * c + vy * d + y; - worldVertices[w + 2] = color.r; - worldVertices[w + 3] = color.g; - worldVertices[w + 4] = color.b; - worldVertices[w + 5] = color.a; - } - return worldVertices; - } - var skeletonBones = skeleton.bones; - if (deformArray.length == 0) { - for (var w = 0, v = 0, b = 0, n = bones.length; v < n; w += 8) { - var wx = 0, wy = 0; - var nn = bones[v++] + v; - for (; v < nn; v++, b += 3) { - var bone = skeletonBones[bones[v]]; - var vx = vertices[b], vy = vertices[b + 1], weight = vertices[b + 2]; - wx += (vx * bone.a + vy * bone.b + bone.worldX) * weight; - wy += (vx * bone.c + vy * bone.d + bone.worldY) * weight; - } - worldVertices[w] = wx; - worldVertices[w + 1] = wy; - worldVertices[w + 2] = color.r; - worldVertices[w + 3] = color.g; - worldVertices[w + 4] = color.b; - worldVertices[w + 5] = color.a; - } - } - else { - var deform = deformArray; - for (var w = 0, v = 0, b = 0, f = 0, n = bones.length; v < n; w += 8) { - var wx = 0, wy = 0; - var nn = bones[v++] + v; - for (; v < nn; v++, b += 3, f += 2) { - var bone = skeletonBones[bones[v]]; - var vx = vertices[b] + deform[f], vy = vertices[b + 1] + deform[f + 1], weight = vertices[b + 2]; - wx += (vx * bone.a + vy * bone.b + bone.worldX) * weight; - wy += (vx * bone.c + vy * bone.d + bone.worldY) * weight; - } - worldVertices[w] = wx; - worldVertices[w + 1] = wy; - worldVertices[w + 2] = color.r; - worldVertices[w + 3] = color.g; - worldVertices[w + 4] = color.b; - worldVertices[w + 5] = color.a; - } - } - return worldVertices; - }; - MeshAttachment.prototype.applyDeform = function (sourceAttachment) { - return this == sourceAttachment || (this.inheritDeform && this.parentMesh == sourceAttachment); - }; - MeshAttachment.prototype.getParentMesh = function () { - return this.parentMesh; - }; - MeshAttachment.prototype.setParentMesh = function (parentMesh) { - this.parentMesh = parentMesh; - if (parentMesh != null) { - this.bones = parentMesh.bones; - this.vertices = parentMesh.vertices; - this.regionUVs = parentMesh.regionUVs; - this.triangles = parentMesh.triangles; - this.hullLength = parentMesh.hullLength; - } - }; - return MeshAttachment; - }(spine.VertexAttachment)); - spine.MeshAttachment = MeshAttachment; -})(spine || (spine = {})); -var spine; -(function (spine) { - var PathAttachment = (function (_super) { - __extends(PathAttachment, _super); - function PathAttachment(name) { - _super.call(this, name); - this.closed = false; - this.constantSpeed = false; - this.color = new spine.Color(1, 1, 1, 1); - } - return PathAttachment; - }(spine.VertexAttachment)); - spine.PathAttachment = PathAttachment; -})(spine || (spine = {})); -var spine; -(function (spine) { - var RegionAttachment = (function (_super) { - __extends(RegionAttachment, _super); - function RegionAttachment(name) { - _super.call(this, name); - this.x = 0; - this.y = 0; - this.scaleX = 1; - this.scaleY = 1; - this.rotation = 0; - this.width = 0; - this.height = 0; - this.color = new spine.Color(1, 1, 1, 1); - this.offset = spine.Utils.newFloatArray(8); - this.vertices = spine.Utils.newFloatArray(8 * 4); - this.tempColor = new spine.Color(1, 1, 1, 1); - } - RegionAttachment.prototype.setRegion = function (region) { - var vertices = this.vertices; - if (region.rotate) { - vertices[RegionAttachment.U2] = region.u; - vertices[RegionAttachment.V2] = region.v2; - vertices[RegionAttachment.U3] = region.u; - vertices[RegionAttachment.V3] = region.v; - vertices[RegionAttachment.U4] = region.u2; - vertices[RegionAttachment.V4] = region.v; - vertices[RegionAttachment.U1] = region.u2; - vertices[RegionAttachment.V1] = region.v2; - } - else { - vertices[RegionAttachment.U1] = region.u; - vertices[RegionAttachment.V1] = region.v2; - vertices[RegionAttachment.U2] = region.u; - vertices[RegionAttachment.V2] = region.v; - vertices[RegionAttachment.U3] = region.u2; - vertices[RegionAttachment.V3] = region.v; - vertices[RegionAttachment.U4] = region.u2; - vertices[RegionAttachment.V4] = region.v2; - } - this.region = region; - }; - RegionAttachment.prototype.updateOffset = function () { - var regionScaleX = this.width / this.region.originalWidth * this.scaleX; - var regionScaleY = this.height / this.region.originalHeight * this.scaleY; - var localX = -this.width / 2 * this.scaleX + this.region.offsetX * regionScaleX; - var localY = -this.height / 2 * this.scaleY + this.region.offsetY * regionScaleY; - var localX2 = localX + this.region.width * regionScaleX; - var localY2 = localY + this.region.height * regionScaleY; - var radians = this.rotation * Math.PI / 180; - var cos = Math.cos(radians); - var sin = Math.sin(radians); - var localXCos = localX * cos + this.x; - var localXSin = localX * sin; - var localYCos = localY * cos + this.y; - var localYSin = localY * sin; - var localX2Cos = localX2 * cos + this.x; - var localX2Sin = localX2 * sin; - var localY2Cos = localY2 * cos + this.y; - var localY2Sin = localY2 * sin; - var offset = this.offset; - offset[RegionAttachment.OX1] = localXCos - localYSin; - offset[RegionAttachment.OY1] = localYCos + localXSin; - offset[RegionAttachment.OX2] = localXCos - localY2Sin; - offset[RegionAttachment.OY2] = localY2Cos + localXSin; - offset[RegionAttachment.OX3] = localX2Cos - localY2Sin; - offset[RegionAttachment.OY3] = localY2Cos + localX2Sin; - offset[RegionAttachment.OX4] = localX2Cos - localYSin; - offset[RegionAttachment.OY4] = localYCos + localX2Sin; - }; - RegionAttachment.prototype.updateWorldVertices = function (slot, premultipliedAlpha) { - var skeleton = slot.bone.skeleton; - var skeletonColor = skeleton.color; - var slotColor = slot.color; - var regionColor = this.color; - var alpha = skeletonColor.a * slotColor.a * regionColor.a; - var multiplier = premultipliedAlpha ? alpha : 1; - var color = this.tempColor; - color.set(skeletonColor.r * slotColor.r * regionColor.r * multiplier, skeletonColor.g * slotColor.g * regionColor.g * multiplier, skeletonColor.b * slotColor.b * regionColor.b * multiplier, alpha); - var vertices = this.vertices; - var offset = this.offset; - var bone = slot.bone; - var x = bone.worldX, y = bone.worldY; - var a = bone.a, b = bone.b, c = bone.c, d = bone.d; - var offsetX = 0, offsetY = 0; - offsetX = offset[RegionAttachment.OX1]; - offsetY = offset[RegionAttachment.OY1]; - vertices[RegionAttachment.X1] = offsetX * a + offsetY * b + x; - vertices[RegionAttachment.Y1] = offsetX * c + offsetY * d + y; - vertices[RegionAttachment.C1R] = color.r; - vertices[RegionAttachment.C1G] = color.g; - vertices[RegionAttachment.C1B] = color.b; - vertices[RegionAttachment.C1A] = color.a; - offsetX = offset[RegionAttachment.OX2]; - offsetY = offset[RegionAttachment.OY2]; - vertices[RegionAttachment.X2] = offsetX * a + offsetY * b + x; - vertices[RegionAttachment.Y2] = offsetX * c + offsetY * d + y; - vertices[RegionAttachment.C2R] = color.r; - vertices[RegionAttachment.C2G] = color.g; - vertices[RegionAttachment.C2B] = color.b; - vertices[RegionAttachment.C2A] = color.a; - offsetX = offset[RegionAttachment.OX3]; - offsetY = offset[RegionAttachment.OY3]; - vertices[RegionAttachment.X3] = offsetX * a + offsetY * b + x; - vertices[RegionAttachment.Y3] = offsetX * c + offsetY * d + y; - vertices[RegionAttachment.C3R] = color.r; - vertices[RegionAttachment.C3G] = color.g; - vertices[RegionAttachment.C3B] = color.b; - vertices[RegionAttachment.C3A] = color.a; - offsetX = offset[RegionAttachment.OX4]; - offsetY = offset[RegionAttachment.OY4]; - vertices[RegionAttachment.X4] = offsetX * a + offsetY * b + x; - vertices[RegionAttachment.Y4] = offsetX * c + offsetY * d + y; - vertices[RegionAttachment.C4R] = color.r; - vertices[RegionAttachment.C4G] = color.g; - vertices[RegionAttachment.C4B] = color.b; - vertices[RegionAttachment.C4A] = color.a; - return vertices; - }; - RegionAttachment.OX1 = 0; - RegionAttachment.OY1 = 1; - RegionAttachment.OX2 = 2; - RegionAttachment.OY2 = 3; - RegionAttachment.OX3 = 4; - RegionAttachment.OY3 = 5; - RegionAttachment.OX4 = 6; - RegionAttachment.OY4 = 7; - RegionAttachment.X1 = 0; - RegionAttachment.Y1 = 1; - RegionAttachment.C1R = 2; - RegionAttachment.C1G = 3; - RegionAttachment.C1B = 4; - RegionAttachment.C1A = 5; - RegionAttachment.U1 = 6; - RegionAttachment.V1 = 7; - RegionAttachment.X2 = 8; - RegionAttachment.Y2 = 9; - RegionAttachment.C2R = 10; - RegionAttachment.C2G = 11; - RegionAttachment.C2B = 12; - RegionAttachment.C2A = 13; - RegionAttachment.U2 = 14; - RegionAttachment.V2 = 15; - RegionAttachment.X3 = 16; - RegionAttachment.Y3 = 17; - RegionAttachment.C3R = 18; - RegionAttachment.C3G = 19; - RegionAttachment.C3B = 20; - RegionAttachment.C3A = 21; - RegionAttachment.U3 = 22; - RegionAttachment.V3 = 23; - RegionAttachment.X4 = 24; - RegionAttachment.Y4 = 25; - RegionAttachment.C4R = 26; - RegionAttachment.C4G = 27; - RegionAttachment.C4B = 28; - RegionAttachment.C4A = 29; - RegionAttachment.U4 = 30; - RegionAttachment.V4 = 31; - return RegionAttachment; - }(spine.Attachment)); - spine.RegionAttachment = RegionAttachment; -})(spine || (spine = {})); -var spine; -(function (spine) { - (function (BlendMode) { - BlendMode[BlendMode["Normal"] = 0] = "Normal"; - BlendMode[BlendMode["Additive"] = 1] = "Additive"; - BlendMode[BlendMode["Multiply"] = 2] = "Multiply"; - BlendMode[BlendMode["Screen"] = 3] = "Screen"; - })(spine.BlendMode || (spine.BlendMode = {})); - var BlendMode = spine.BlendMode; -})(spine || (spine = {})); -var spine; -(function (spine) { - var Bone = (function () { - function Bone(data, skeleton, parent) { - this.children = new Array(); - this.x = 0; - this.y = 0; - this.rotation = 0; - this.scaleX = 0; - this.scaleY = 0; - this.shearX = 0; - this.shearY = 0; - this.ax = 0; - this.ay = 0; - this.arotation = 0; - this.ascaleX = 0; - this.ascaleY = 0; - this.ashearX = 0; - this.ashearY = 0; - this.appliedValid = false; - this.a = 0; - this.b = 0; - this.worldX = 0; - this.c = 0; - this.d = 0; - this.worldY = 0; - this.sorted = false; - if (data == null) - throw new Error("data cannot be null."); - if (skeleton == null) - throw new Error("skeleton cannot be null."); - this.data = data; - this.skeleton = skeleton; - this.parent = parent; - this.setToSetupPose(); - } - Bone.prototype.update = function () { - this.updateWorldTransformWith(this.x, this.y, this.rotation, this.scaleX, this.scaleY, this.shearX, this.shearY); - }; - Bone.prototype.updateWorldTransform = function () { - this.updateWorldTransformWith(this.x, this.y, this.rotation, this.scaleX, this.scaleY, this.shearX, this.shearY); - }; - Bone.prototype.updateWorldTransformWith = function (x, y, rotation, scaleX, scaleY, shearX, shearY) { - this.ax = x; - this.ay = y; - this.arotation = rotation; - this.ascaleX = scaleX; - this.ascaleY = scaleY; - this.ashearX = shearX; - this.ashearY = shearY; - this.appliedValid = true; - var parent = this.parent; - if (parent == null) { - var rotationY = rotation + 90 + shearY; - var la = spine.MathUtils.cosDeg(rotation + shearX) * scaleX; - var lb = spine.MathUtils.cosDeg(rotationY) * scaleY; - var lc = spine.MathUtils.sinDeg(rotation + shearX) * scaleX; - var ld = spine.MathUtils.sinDeg(rotationY) * scaleY; - var skeleton = this.skeleton; - if (skeleton.flipX) { - x = -x; - la = -la; - lb = -lb; - } - if (skeleton.flipY) { - y = -y; - lc = -lc; - ld = -ld; - } - this.a = la; - this.b = lb; - this.c = lc; - this.d = ld; - this.worldX = x + skeleton.x; - this.worldY = y + skeleton.y; - return; + this.a = la; + this.b = lb; + this.c = lc; + this.d = ld; + this.worldX = x + skeleton.x; + this.worldY = y + skeleton.y; + return; } var pa = parent.a, pb = parent.b, pc = parent.c, pd = parent.d; this.worldX = pa * x + pb * y + parent.worldX; @@ -2330,14 +2202,14 @@ var spine; var lb = spine.MathUtils.cosDeg(90 + shearY) * scaleY; var lc = spine.MathUtils.sinDeg(shearX) * scaleX; var ld = spine.MathUtils.sinDeg(90 + shearY) * scaleY; + if (this.data.transformMode != spine.TransformMode.NoScaleOrReflection ? pa * pd - pb * pc < 0 : this.skeleton.flipX != this.skeleton.flipY) { + zb = -zb; + zd = -zd; + } this.a = za * la + zb * lc; this.b = za * lb + zb * ld; this.c = zc * la + zd * lc; this.d = zc * lb + zd * ld; - if (this.data.transformMode != spine.TransformMode.NoScaleOrReflection ? pa * pd - pb * pc < 0 : this.skeleton.flipX != this.skeleton.flipY) { - this.b = -this.b; - this.d = -this.d; - } return; } } @@ -2372,29 +2244,6 @@ var spine; Bone.prototype.getWorldScaleY = function () { return Math.sqrt(this.b * this.b + this.d * this.d); }; - Bone.prototype.worldToLocalRotationX = function () { - var parent = this.parent; - if (parent == null) - return this.arotation; - var pa = parent.a, pb = parent.b, pc = parent.c, pd = parent.d, a = this.a, c = this.c; - return Math.atan2(pa * c - pc * a, pd * a - pb * c) * spine.MathUtils.radDeg; - }; - Bone.prototype.worldToLocalRotationY = function () { - var parent = this.parent; - if (parent == null) - return this.arotation; - var pa = parent.a, pb = parent.b, pc = parent.c, pd = parent.d, b = this.b, d = this.d; - return Math.atan2(pa * d - pc * b, pd * b - pb * d) * spine.MathUtils.radDeg; - }; - Bone.prototype.rotateWorld = function (degrees) { - var a = this.a, b = this.b, c = this.c, d = this.d; - var cos = spine.MathUtils.cosDeg(degrees), sin = spine.MathUtils.sinDeg(degrees); - this.a = cos * a - sin * c; - this.b = cos * b - sin * d; - this.c = sin * a + cos * c; - this.d = sin * b + cos * d; - this.appliedValid = false; - }; Bone.prototype.updateAppliedTransform = function () { this.appliedValid = true; var parent = this.parent; @@ -2450,6 +2299,23 @@ var spine; local.y = x * this.c + y * this.d + this.worldY; return local; }; + Bone.prototype.worldToLocalRotation = function (worldRotation) { + var sin = spine.MathUtils.sinDeg(worldRotation), cos = spine.MathUtils.cosDeg(worldRotation); + return Math.atan2(this.a * sin - this.c * cos, this.d * cos - this.b * sin) * spine.MathUtils.radDeg; + }; + Bone.prototype.localToWorldRotation = function (localRotation) { + var sin = spine.MathUtils.sinDeg(localRotation), cos = spine.MathUtils.cosDeg(localRotation); + return Math.atan2(cos * this.c + sin * this.d, cos * this.a + sin * this.b) * spine.MathUtils.radDeg; + }; + Bone.prototype.rotateWorld = function (degrees) { + var a = this.a, b = this.b, c = this.c, d = this.d; + var cos = spine.MathUtils.cosDeg(degrees), sin = spine.MathUtils.sinDeg(degrees); + this.a = cos * a - sin * c; + this.b = cos * b - sin * d; + this.c = sin * a + cos * c; + this.d = sin * b + cos * d; + this.appliedValid = false; + }; return Bone; }()); spine.Bone = Bone; @@ -2477,14 +2343,14 @@ var spine; return BoneData; }()); spine.BoneData = BoneData; + var TransformMode; (function (TransformMode) { TransformMode[TransformMode["Normal"] = 0] = "Normal"; TransformMode[TransformMode["OnlyTranslation"] = 1] = "OnlyTranslation"; TransformMode[TransformMode["NoRotationOrReflection"] = 2] = "NoRotationOrReflection"; TransformMode[TransformMode["NoScale"] = 3] = "NoScale"; TransformMode[TransformMode["NoScaleOrReflection"] = 4] = "NoScaleOrReflection"; - })(spine.TransformMode || (spine.TransformMode = {})); - var TransformMode = spine.TransformMode; + })(TransformMode = spine.TransformMode || (spine.TransformMode = {})); })(spine || (spine = {})); var spine; (function (spine) { @@ -2647,37 +2513,26 @@ var spine; break outer; } } - var minAngle = 0, minDist = Number.MAX_VALUE, minX = 0, minY = 0; - var maxAngle = 0, maxDist = 0, maxX = 0, maxY = 0; - x = l1 + a; - d = x * x; - if (d > maxDist) { - maxAngle = 0; - maxDist = d; - maxX = x; - } - x = l1 - a; - d = x * x; - if (d < minDist) { - minAngle = spine.MathUtils.PI; - minDist = d; - minX = x; - } - var angle = Math.acos(-a * l1 / (aa - bb)); - x = a * Math.cos(angle) + l1; - y = b * Math.sin(angle); - d = x * x + y * y; - if (d < minDist) { - minAngle = angle; - minDist = d; - minX = x; - minY = y; - } - if (d > maxDist) { - maxAngle = angle; - maxDist = d; - maxX = x; - maxY = y; + var minAngle = spine.MathUtils.PI, minX = l1 - a, minDist = minX * minX, minY = 0; + var maxAngle = 0, maxX = l1 + a, maxDist = maxX * maxX, maxY = 0; + c = -a * l1 / (aa - bb); + if (c >= -1 && c <= 1) { + c = Math.acos(c); + x = a * Math.cos(c) + l1; + y = b * Math.sin(c); + d = x * x + y * y; + if (d < minDist) { + minAngle = c; + minDist = d; + minX = x; + minY = y; + } + if (d > maxDist) { + maxAngle = c; + maxDist = d; + maxX = x; + maxY = y; + } } if (dd <= (minDist + maxDist) / 2) { a1 = ta - Math.atan2(minY * bendDir, minX); @@ -2775,11 +2630,14 @@ var spine; lengths = spine.Utils.setArraySize(this.lengths, boneCount); for (var i = 0, n = spacesCount - 1; i < n;) { var bone = bones[i]; - var length_1 = bone.data.length, x = length_1 * bone.a, y = length_1 * bone.c; - length_1 = Math.sqrt(x * x + y * y); + var setupLength = bone.data.length; + if (setupLength == 0) + setupLength = 0.0000001; + var x = setupLength * bone.a, y = setupLength * bone.c; + var length_1 = Math.sqrt(x * x + y * y); if (scale) lengths[i] = length_1; - spaces[++i] = lengthSpacing ? Math.max(0, length_1 + spacing) : spacing; + spaces[++i] = (lengthSpacing ? setupLength + spacing : spacing) * length_1 / setupLength; } } else { @@ -2875,7 +2733,7 @@ var spine; else if (p < 0) { if (prevCurve != PathConstraint.BEFORE) { prevCurve = PathConstraint.BEFORE; - path.computeWorldVerticesWith(target, 2, 4, world, 0); + path.computeWorldVertices(target, 2, 4, world, 0, 2); } this.addBeforePosition(p, world, 0, out, o); continue; @@ -2883,7 +2741,7 @@ var spine; else if (p > pathLength_1) { if (prevCurve != PathConstraint.AFTER) { prevCurve = PathConstraint.AFTER; - path.computeWorldVerticesWith(target, verticesLength - 6, 4, world, 0); + path.computeWorldVertices(target, verticesLength - 6, 4, world, 0, 2); } this.addAfterPosition(p - pathLength_1, world, 0, out, o); continue; @@ -2903,11 +2761,11 @@ var spine; if (curve != prevCurve) { prevCurve = curve; if (closed && curve == curveCount) { - path.computeWorldVerticesWith(target, verticesLength - 4, 4, world, 0); - path.computeWorldVerticesWith(target, 0, 4, world, 4); + path.computeWorldVertices(target, verticesLength - 4, 4, world, 0, 2); + path.computeWorldVertices(target, 0, 4, world, 4, 2); } else - path.computeWorldVerticesWith(target, curve * 6 + 2, 8, world, 0); + path.computeWorldVertices(target, curve * 6 + 2, 8, world, 0, 2); } this.addCurvePosition(p, world[0], world[1], world[2], world[3], world[4], world[5], world[6], world[7], out, o, tangents || (i > 0 && space == 0)); } @@ -2916,8 +2774,8 @@ var spine; if (closed) { verticesLength += 2; world = spine.Utils.setArraySize(this.world, verticesLength); - path.computeWorldVerticesWith(target, 2, verticesLength - 4, world, 0); - path.computeWorldVerticesWith(target, 0, 2, world, verticesLength - 4); + path.computeWorldVertices(target, 2, verticesLength - 4, world, 0, 2); + path.computeWorldVertices(target, 0, 2, world, verticesLength - 4, 2); world[verticesLength - 2] = world[0]; world[verticesLength - 1] = world[1]; } @@ -2925,7 +2783,7 @@ var spine; curveCount--; verticesLength -= 4; world = spine.Utils.setArraySize(this.world, verticesLength); - path.computeWorldVerticesWith(target, 2, verticesLength, world, 0); + path.computeWorldVertices(target, 2, verticesLength, world, 0, 2); } var curves = spine.Utils.setArraySize(this.curves, curveCount); var pathLength = 0; @@ -3082,11 +2940,11 @@ var spine; PathConstraint.prototype.getOrder = function () { return this.data.order; }; - PathConstraint.NONE = -1; - PathConstraint.BEFORE = -2; - PathConstraint.AFTER = -3; return PathConstraint; }()); + PathConstraint.NONE = -1; + PathConstraint.BEFORE = -2; + PathConstraint.AFTER = -3; spine.PathConstraint = PathConstraint; })(spine || (spine = {})); var spine; @@ -3100,24 +2958,33 @@ var spine; return PathConstraintData; }()); spine.PathConstraintData = PathConstraintData; + var PositionMode; (function (PositionMode) { PositionMode[PositionMode["Fixed"] = 0] = "Fixed"; PositionMode[PositionMode["Percent"] = 1] = "Percent"; - })(spine.PositionMode || (spine.PositionMode = {})); - var PositionMode = spine.PositionMode; + })(PositionMode = spine.PositionMode || (spine.PositionMode = {})); + var SpacingMode; (function (SpacingMode) { SpacingMode[SpacingMode["Length"] = 0] = "Length"; SpacingMode[SpacingMode["Fixed"] = 1] = "Fixed"; SpacingMode[SpacingMode["Percent"] = 2] = "Percent"; - })(spine.SpacingMode || (spine.SpacingMode = {})); - var SpacingMode = spine.SpacingMode; + })(SpacingMode = spine.SpacingMode || (spine.SpacingMode = {})); + var RotateMode; (function (RotateMode) { RotateMode[RotateMode["Tangent"] = 0] = "Tangent"; RotateMode[RotateMode["Chain"] = 1] = "Chain"; RotateMode[RotateMode["ChainScale"] = 2] = "ChainScale"; - })(spine.RotateMode || (spine.RotateMode = {})); - var RotateMode = spine.RotateMode; + })(RotateMode = spine.RotateMode || (spine.RotateMode = {})); })(spine || (spine = {})); +(function () { + if (!Math.fround) { + Math.fround = (function (array) { + return function (x) { + return array[0] = x, array[0]; + }; + })(new Float32Array(1)); + } +})(); var spine; (function (spine) { var Assets = (function () { @@ -3313,6 +3180,7 @@ var spine; Skeleton.prototype.updateCache = function () { var updateCache = this._updateCache; updateCache.length = 0; + this.updateCacheReset.length = 0; var bones = this.bones; for (var i = 0, n = bones.length; i < n; i++) bones[i].sorted = false; @@ -3370,27 +3238,38 @@ var spine; this.sortPathConstraintAttachment(this.skin, slotIndex, slotBone); if (this.data.defaultSkin != null && this.data.defaultSkin != this.skin) this.sortPathConstraintAttachment(this.data.defaultSkin, slotIndex, slotBone); - for (var ii = 0, nn = this.data.skins.length; ii < nn; ii++) - this.sortPathConstraintAttachment(this.data.skins[ii], slotIndex, slotBone); + for (var i = 0, n = this.data.skins.length; i < n; i++) + this.sortPathConstraintAttachment(this.data.skins[i], slotIndex, slotBone); var attachment = slot.getAttachment(); if (attachment instanceof spine.PathAttachment) this.sortPathConstraintAttachmentWith(attachment, slotBone); var constrained = constraint.bones; var boneCount = constrained.length; - for (var ii = 0; ii < boneCount; ii++) - this.sortBone(constrained[ii]); + for (var i = 0; i < boneCount; i++) + this.sortBone(constrained[i]); this._updateCache.push(constraint); - for (var ii = 0; ii < boneCount; ii++) - this.sortReset(constrained[ii].children); - for (var ii = 0; ii < boneCount; ii++) - constrained[ii].sorted = true; + for (var i = 0; i < boneCount; i++) + this.sortReset(constrained[i].children); + for (var i = 0; i < boneCount; i++) + constrained[i].sorted = true; }; Skeleton.prototype.sortTransformConstraint = function (constraint) { this.sortBone(constraint.target); var constrained = constraint.bones; var boneCount = constrained.length; - for (var ii = 0; ii < boneCount; ii++) - this.sortBone(constrained[ii]); + if (constraint.data.local) { + for (var i = 0; i < boneCount; i++) { + var child = constrained[i]; + this.sortBone(child.parent); + if (!(this._updateCache.indexOf(child) > -1)) + this.updateCacheReset.push(child); + } + } + else { + for (var i = 0; i < boneCount; i++) { + this.sortBone(constrained[i]); + } + } this._updateCache.push(constraint); for (var ii = 0; ii < boneCount; ii++) this.sortReset(constrained[ii].children); @@ -3633,7 +3512,7 @@ var spine; } return null; }; - Skeleton.prototype.getBounds = function (offset, size) { + Skeleton.prototype.getBounds = function (offset, size, temp) { if (offset == null) throw new Error("offset cannot be null."); if (size == null) @@ -3642,14 +3521,22 @@ var spine; var minX = Number.POSITIVE_INFINITY, minY = Number.POSITIVE_INFINITY, maxX = Number.NEGATIVE_INFINITY, maxY = Number.NEGATIVE_INFINITY; for (var i = 0, n = drawOrder.length; i < n; i++) { var slot = drawOrder[i]; + var verticesLength = 0; var vertices = null; var attachment = slot.getAttachment(); - if (attachment instanceof spine.RegionAttachment) - vertices = attachment.updateWorldVertices(slot, false); - else if (attachment instanceof spine.MeshAttachment) - vertices = attachment.updateWorldVertices(slot, true); + if (attachment instanceof spine.RegionAttachment) { + verticesLength = 8; + vertices = spine.Utils.setArraySize(temp, verticesLength, 0); + attachment.computeWorldVertices(slot.bone, vertices, 0, 2); + } + else if (attachment instanceof spine.MeshAttachment) { + var mesh = attachment; + verticesLength = mesh.worldVerticesLength; + vertices = spine.Utils.setArraySize(temp, verticesLength, 0); + mesh.computeWorldVertices(slot, 0, verticesLength, vertices, 0, 2); + } if (vertices != null) { - for (var ii = 0, nn = vertices.length; ii < nn; ii += 8) { + for (var ii = 0, nn = vertices.length; ii < nn; ii += 2) { var x = vertices[ii], y = vertices[ii + 1]; minX = Math.min(minX, x); minY = Math.min(minY, y); @@ -3704,7 +3591,7 @@ var spine; polygon = spine.Utils.newFloatArray(boundingBox.worldVerticesLength); } polygons.push(polygon); - boundingBox.computeWorldVertices(slot, polygon); + boundingBox.computeWorldVertices(slot, 0, boundingBox.worldVerticesLength, polygon, 0, 2); } } if (updateAabb) { @@ -3835,6 +3722,286 @@ var spine; spine.SkeletonBounds = SkeletonBounds; })(spine || (spine = {})); var spine; +(function (spine) { + var SkeletonClipping = (function () { + function SkeletonClipping() { + this.triangulator = new spine.Triangulator(); + this.clippingPolygon = new Array(); + this.clipOutput = new Array(); + this.clippedVertices = new Array(); + this.clippedTriangles = new Array(); + this.scratch = new Array(); + } + SkeletonClipping.prototype.clipStart = function (slot, clip) { + if (this.clipAttachment != null) + return 0; + this.clipAttachment = clip; + var n = clip.worldVerticesLength; + var vertices = spine.Utils.setArraySize(this.clippingPolygon, n); + clip.computeWorldVertices(slot, 0, n, vertices, 0, 2); + var clippingPolygon = this.clippingPolygon; + SkeletonClipping.makeClockwise(clippingPolygon); + var clippingPolygons = this.clippingPolygons = this.triangulator.decompose(clippingPolygon, this.triangulator.triangulate(clippingPolygon)); + for (var i = 0, n_1 = clippingPolygons.length; i < n_1; i++) { + var polygon = clippingPolygons[i]; + SkeletonClipping.makeClockwise(polygon); + polygon.push(polygon[0]); + polygon.push(polygon[1]); + } + return clippingPolygons.length; + }; + SkeletonClipping.prototype.clipEndWithSlot = function (slot) { + if (this.clipAttachment != null && this.clipAttachment.endSlot == slot.data) + this.clipEnd(); + }; + SkeletonClipping.prototype.clipEnd = function () { + if (this.clipAttachment == null) + return; + this.clipAttachment = null; + this.clippingPolygons = null; + this.clippedVertices.length = 0; + this.clippedTriangles.length = 0; + this.clippingPolygon.length = 0; + }; + SkeletonClipping.prototype.isClipping = function () { + return this.clipAttachment != null; + }; + SkeletonClipping.prototype.clipTriangles = function (vertices, verticesLength, triangles, trianglesLength, uvs, light, dark, twoColor) { + var clipOutput = this.clipOutput, clippedVertices = this.clippedVertices; + var clippedTriangles = this.clippedTriangles; + var polygons = this.clippingPolygons; + var polygonsCount = this.clippingPolygons.length; + var vertexSize = twoColor ? 12 : 8; + var index = 0; + clippedVertices.length = 0; + clippedTriangles.length = 0; + outer: for (var i = 0; i < trianglesLength; i += 3) { + var vertexOffset = triangles[i] << 1; + var x1 = vertices[vertexOffset], y1 = vertices[vertexOffset + 1]; + var u1 = uvs[vertexOffset], v1 = uvs[vertexOffset + 1]; + vertexOffset = triangles[i + 1] << 1; + var x2 = vertices[vertexOffset], y2 = vertices[vertexOffset + 1]; + var u2 = uvs[vertexOffset], v2 = uvs[vertexOffset + 1]; + vertexOffset = triangles[i + 2] << 1; + var x3 = vertices[vertexOffset], y3 = vertices[vertexOffset + 1]; + var u3 = uvs[vertexOffset], v3 = uvs[vertexOffset + 1]; + for (var p = 0; p < polygonsCount; p++) { + var s = clippedVertices.length; + if (this.clip(x1, y1, x2, y2, x3, y3, polygons[p], clipOutput)) { + var clipOutputLength = clipOutput.length; + if (clipOutputLength == 0) + continue; + var d0 = y2 - y3, d1 = x3 - x2, d2 = x1 - x3, d4 = y3 - y1; + var d = 1 / (d0 * d2 + d1 * (y1 - y3)); + var clipOutputCount = clipOutputLength >> 1; + var clipOutputItems = this.clipOutput; + var clippedVerticesItems = spine.Utils.setArraySize(clippedVertices, s + clipOutputCount * vertexSize); + for (var ii = 0; ii < clipOutputLength; ii += 2) { + var x = clipOutputItems[ii], y = clipOutputItems[ii + 1]; + clippedVerticesItems[s] = x; + clippedVerticesItems[s + 1] = y; + clippedVerticesItems[s + 2] = light.r; + clippedVerticesItems[s + 3] = light.g; + clippedVerticesItems[s + 4] = light.b; + clippedVerticesItems[s + 5] = light.a; + var c0 = x - x3, c1 = y - y3; + var a = (d0 * c0 + d1 * c1) * d; + var b = (d4 * c0 + d2 * c1) * d; + var c = 1 - a - b; + clippedVerticesItems[s + 6] = u1 * a + u2 * b + u3 * c; + clippedVerticesItems[s + 7] = v1 * a + v2 * b + v3 * c; + if (twoColor) { + clippedVerticesItems[s + 8] = dark.r; + clippedVerticesItems[s + 9] = dark.g; + clippedVerticesItems[s + 10] = dark.b; + clippedVerticesItems[s + 11] = dark.a; + } + s += vertexSize; + } + s = clippedTriangles.length; + var clippedTrianglesItems = spine.Utils.setArraySize(clippedTriangles, s + 3 * (clipOutputCount - 2)); + clipOutputCount--; + for (var ii = 1; ii < clipOutputCount; ii++) { + clippedTrianglesItems[s] = index; + clippedTrianglesItems[s + 1] = (index + ii); + clippedTrianglesItems[s + 2] = (index + ii + 1); + s += 3; + } + index += clipOutputCount + 1; + } + else { + var clippedVerticesItems = spine.Utils.setArraySize(clippedVertices, s + 3 * vertexSize); + clippedVerticesItems[s] = x1; + clippedVerticesItems[s + 1] = y1; + clippedVerticesItems[s + 2] = light.r; + clippedVerticesItems[s + 3] = light.g; + clippedVerticesItems[s + 4] = light.b; + clippedVerticesItems[s + 5] = light.a; + if (!twoColor) { + clippedVerticesItems[s + 6] = u1; + clippedVerticesItems[s + 7] = v1; + clippedVerticesItems[s + 8] = x2; + clippedVerticesItems[s + 9] = y2; + clippedVerticesItems[s + 10] = light.r; + clippedVerticesItems[s + 11] = light.g; + clippedVerticesItems[s + 12] = light.b; + clippedVerticesItems[s + 13] = light.a; + clippedVerticesItems[s + 14] = u2; + clippedVerticesItems[s + 15] = v2; + clippedVerticesItems[s + 16] = x3; + clippedVerticesItems[s + 17] = y3; + clippedVerticesItems[s + 18] = light.r; + clippedVerticesItems[s + 19] = light.g; + clippedVerticesItems[s + 20] = light.b; + clippedVerticesItems[s + 21] = light.a; + clippedVerticesItems[s + 22] = u3; + clippedVerticesItems[s + 23] = v3; + } + else { + clippedVerticesItems[s + 6] = u1; + clippedVerticesItems[s + 7] = v1; + clippedVerticesItems[s + 8] = dark.r; + clippedVerticesItems[s + 9] = dark.g; + clippedVerticesItems[s + 10] = dark.b; + clippedVerticesItems[s + 11] = dark.a; + clippedVerticesItems[s + 12] = x2; + clippedVerticesItems[s + 13] = y2; + clippedVerticesItems[s + 14] = light.r; + clippedVerticesItems[s + 15] = light.g; + clippedVerticesItems[s + 16] = light.b; + clippedVerticesItems[s + 17] = light.a; + clippedVerticesItems[s + 18] = u2; + clippedVerticesItems[s + 19] = v2; + clippedVerticesItems[s + 20] = dark.r; + clippedVerticesItems[s + 21] = dark.g; + clippedVerticesItems[s + 22] = dark.b; + clippedVerticesItems[s + 23] = dark.a; + clippedVerticesItems[s + 24] = x3; + clippedVerticesItems[s + 25] = y3; + clippedVerticesItems[s + 26] = light.r; + clippedVerticesItems[s + 27] = light.g; + clippedVerticesItems[s + 28] = light.b; + clippedVerticesItems[s + 29] = light.a; + clippedVerticesItems[s + 30] = u3; + clippedVerticesItems[s + 31] = v3; + clippedVerticesItems[s + 32] = dark.r; + clippedVerticesItems[s + 33] = dark.g; + clippedVerticesItems[s + 34] = dark.b; + clippedVerticesItems[s + 35] = dark.a; + } + s = clippedTriangles.length; + var clippedTrianglesItems = spine.Utils.setArraySize(clippedTriangles, s + 3); + clippedTrianglesItems[s] = index; + clippedTrianglesItems[s + 1] = (index + 1); + clippedTrianglesItems[s + 2] = (index + 2); + index += 3; + continue outer; + } + } + } + }; + SkeletonClipping.prototype.clip = function (x1, y1, x2, y2, x3, y3, clippingArea, output) { + var originalOutput = output; + var clipped = false; + var input = null; + if (clippingArea.length % 4 >= 2) { + input = output; + output = this.scratch; + } + else + input = this.scratch; + input.length = 0; + input.push(x1); + input.push(y1); + input.push(x2); + input.push(y2); + input.push(x3); + input.push(y3); + input.push(x1); + input.push(y1); + output.length = 0; + var clippingVertices = clippingArea; + var clippingVerticesLast = clippingArea.length - 4; + for (var i = 0;; i += 2) { + var edgeX = clippingVertices[i], edgeY = clippingVertices[i + 1]; + var edgeX2 = clippingVertices[i + 2], edgeY2 = clippingVertices[i + 3]; + var deltaX = edgeX - edgeX2, deltaY = edgeY - edgeY2; + var inputVertices = input; + var inputVerticesLength = input.length - 2, outputStart = output.length; + for (var ii = 0; ii < inputVerticesLength; ii += 2) { + var inputX = inputVertices[ii], inputY = inputVertices[ii + 1]; + var inputX2 = inputVertices[ii + 2], inputY2 = inputVertices[ii + 3]; + var side2 = deltaX * (inputY2 - edgeY2) - deltaY * (inputX2 - edgeX2) > 0; + if (deltaX * (inputY - edgeY2) - deltaY * (inputX - edgeX2) > 0) { + if (side2) { + output.push(inputX2); + output.push(inputY2); + continue; + } + var c0 = inputY2 - inputY, c2 = inputX2 - inputX; + var ua = (c2 * (edgeY - inputY) - c0 * (edgeX - inputX)) / (c0 * (edgeX2 - edgeX) - c2 * (edgeY2 - edgeY)); + output.push(edgeX + (edgeX2 - edgeX) * ua); + output.push(edgeY + (edgeY2 - edgeY) * ua); + } + else if (side2) { + var c0 = inputY2 - inputY, c2 = inputX2 - inputX; + var ua = (c2 * (edgeY - inputY) - c0 * (edgeX - inputX)) / (c0 * (edgeX2 - edgeX) - c2 * (edgeY2 - edgeY)); + output.push(edgeX + (edgeX2 - edgeX) * ua); + output.push(edgeY + (edgeY2 - edgeY) * ua); + output.push(inputX2); + output.push(inputY2); + } + clipped = true; + } + if (outputStart == output.length) { + originalOutput.length = 0; + return true; + } + output.push(output[0]); + output.push(output[1]); + if (i == clippingVerticesLast) + break; + var temp = output; + output = input; + output.length = 0; + input = temp; + } + if (originalOutput != output) { + originalOutput.length = 0; + for (var i = 0, n = output.length - 2; i < n; i++) + originalOutput[i] = output[i]; + } + else + originalOutput.length = originalOutput.length - 2; + return clipped; + }; + SkeletonClipping.makeClockwise = function (polygon) { + var vertices = polygon; + var verticeslength = polygon.length; + var area = vertices[verticeslength - 2] * vertices[1] - vertices[0] * vertices[verticeslength - 1], p1x = 0, p1y = 0, p2x = 0, p2y = 0; + for (var i = 0, n = verticeslength - 3; i < n; i += 2) { + p1x = vertices[i]; + p1y = vertices[i + 1]; + p2x = vertices[i + 2]; + p2y = vertices[i + 3]; + area += p1x * p2y - p2x * p1y; + } + if (area < 0) + return; + for (var i = 0, lastX = verticeslength - 2, n = verticeslength >> 1; i < n; i += 2) { + var x = vertices[i], y = vertices[i + 1]; + var other = lastX - i; + vertices[i] = vertices[other]; + vertices[i + 1] = vertices[other + 1]; + vertices[other] = x; + vertices[other + 1] = y; + } + }; + return SkeletonClipping; + }()); + spine.SkeletonClipping = SkeletonClipping; +})(spine || (spine = {})); +var spine; (function (spine) { var SkeletonData = (function () { function SkeletonData() { @@ -4023,6 +4190,11 @@ var spine; var color = this.getValue(slotMap, "color", null); if (color != null) data.color.setFromString(color); + var dark = this.getValue(slotMap, "dark", null); + if (dark != null) { + data.darkColor = new spine.Color(1, 1, 1, 1); + data.darkColor.setFromString(dark); + } data.attachmentName = this.getValue(slotMap, "attachment", null); data.blendMode = SkeletonJson.blendModeFromString(this.getValue(slotMap, "blend", "normal")); skeletonData.slots.push(data); @@ -4065,6 +4237,8 @@ var spine; data.target = skeletonData.findBone(targetName); if (data.target == null) throw new Error("Transform constraint target bone not found: " + targetName); + data.local = this.getValue(constraintMap, "local", false); + data.relative = this.getValue(constraintMap, "relative", false); data.offsetRotation = this.getValue(constraintMap, "rotation", 0); data.offsetX = this.getValue(constraintMap, "x", 0) * scale; data.offsetY = this.getValue(constraintMap, "y", 0) * scale; @@ -4119,7 +4293,7 @@ var spine; throw new Error("Slot not found: " + slotName); var slotMap = skinMap[slotName]; for (var entryName in slotMap) { - var attachment = this.readAttachment(slotMap[entryName], skin, slotIndex, entryName); + var attachment = this.readAttachment(slotMap[entryName], skin, slotIndex, entryName, skeletonData); if (attachment != null) skin.addAttachment(slotIndex, entryName, attachment); } @@ -4159,7 +4333,7 @@ var spine; } return skeletonData; }; - SkeletonJson.prototype.readAttachment = function (map, skin, slotIndex, name) { + SkeletonJson.prototype.readAttachment = function (map, skin, slotIndex, name, skeletonData) { var scale = this.scale; name = this.getValue(map, "name", name); var type = this.getValue(map, "type", "region"); @@ -4227,13 +4401,43 @@ var spine; this.readVertices(map, path, vertexCount << 1); var lengths = spine.Utils.newArray(vertexCount / 3, 0); for (var i = 0; i < map.lengths.length; i++) - lengths[i++] = map.lengths[i] * scale; + lengths[i] = map.lengths[i] * scale; path.lengths = lengths; var color = this.getValue(map, "color", null); if (color != null) path.color.setFromString(color); return path; } + case "point": { + var point = this.attachmentLoader.newPointAttachment(skin, name); + if (point == null) + return null; + point.x = this.getValue(map, "x", 0) * scale; + point.y = this.getValue(map, "y", 0) * scale; + point.rotation = this.getValue(map, "rotation", 0); + var color = this.getValue(map, "color", null); + if (color != null) + point.color.setFromString(color); + return point; + } + case "clipping": { + var clip = this.attachmentLoader.newClippingAttachment(skin, name); + if (clip == null) + return null; + var end = this.getValue(map, "end", null); + if (end != null) { + var slot = skeletonData.findSlot(end); + if (slot == null) + throw new Error("Clipping end slot not found: " + end); + clip.endSlot = slot; + } + var vertexCount = map.vertexCount; + this.readVertices(map, clip, vertexCount << 1); + var color = this.getValue(map, "color", null); + if (color != null) + clip.color.setFromString(color); + return clip; + } } return null; }; @@ -4241,8 +4445,8 @@ var spine; var scale = this.scale; attachment.worldVerticesLength = verticesLength; var vertices = map.vertices; - var scaledVertices = spine.Utils.toFloatArray(vertices); - if (verticesLength == scaledVertices.length) { + if (verticesLength == vertices.length) { + var scaledVertices = spine.Utils.toFloatArray(vertices); if (scale != 1) { for (var i = 0, n = vertices.length; i < n; i++) scaledVertices[i] *= scale; @@ -4277,7 +4481,18 @@ var spine; throw new Error("Slot not found: " + slotName); for (var timelineName in slotMap) { var timelineMap = slotMap[timelineName]; - if (timelineName == "color") { + if (timelineName == "attachment") { + var timeline = new spine.AttachmentTimeline(timelineMap.length); + timeline.slotIndex = slotIndex; + var frameIndex = 0; + for (var i = 0; i < timelineMap.length; i++) { + var valueMap = timelineMap[i]; + timeline.setFrame(frameIndex++, valueMap.time, valueMap.name); + } + timelines.push(timeline); + duration = Math.max(duration, timeline.frames[timeline.getFrameCount() - 1]); + } + else if (timelineName == "color") { var timeline = new spine.ColorTimeline(timelineMap.length); timeline.slotIndex = slotIndex; var frameIndex = 0; @@ -4292,16 +4507,22 @@ var spine; timelines.push(timeline); duration = Math.max(duration, timeline.frames[(timeline.getFrameCount() - 1) * spine.ColorTimeline.ENTRIES]); } - else if (timelineName = "attachment") { - var timeline = new spine.AttachmentTimeline(timelineMap.length); + else if (timelineName == "twoColor") { + var timeline = new spine.TwoColorTimeline(timelineMap.length); timeline.slotIndex = slotIndex; var frameIndex = 0; for (var i = 0; i < timelineMap.length; i++) { var valueMap = timelineMap[i]; - timeline.setFrame(frameIndex++, valueMap.time, valueMap.name); + var light = new spine.Color(); + var dark = new spine.Color(); + light.setFromString(valueMap.light); + dark.setFromString(valueMap.dark); + timeline.setFrame(frameIndex, valueMap.time, light.r, light.g, light.b, light.a, dark.r, dark.g, dark.b); + this.readCurve(valueMap, timeline, frameIndex); + frameIndex++; } timelines.push(timeline); - duration = Math.max(duration, timeline.frames[timeline.getFrameCount() - 1]); + duration = Math.max(duration, timeline.frames[(timeline.getFrameCount() - 1) * spine.TwoColorTimeline.ENTRIES]); } else throw new Error("Invalid timeline type for a slot: " + timelineName + " (" + slotName + ")"); @@ -4535,7 +4756,7 @@ var spine; var eventData = skeletonData.findEvent(eventMap.name); if (eventData == null) throw new Error("Event not found: " + eventMap.name); - var event_5 = new spine.Event(eventMap.time, eventData); + var event_5 = new spine.Event(spine.Utils.toSinglePrecision(eventMap.time), eventData); event_5.intValue = this.getValue(eventMap, "int", eventData.intValue); event_5.floatValue = this.getValue(eventMap, "float", eventData.floatValue); event_5.stringValue = this.getValue(eventMap, "string", eventData.stringValue); @@ -4688,6 +4909,7 @@ var spine; this.data = data; this.bone = bone; this.color = new spine.Color(); + this.darkColor = data.darkColor == null ? null : new spine.Color(); this.setToSetupPose(); } Slot.prototype.getAttachment = function () { @@ -4708,6 +4930,8 @@ var spine; }; Slot.prototype.setToSetupPose = function () { this.color.setFromColor(this.data.color); + if (this.darkColor != null) + this.darkColor.setFromColor(this.data.darkColor); if (this.data.attachmentName == null) this.attachment = null; else { @@ -4770,6 +4994,7 @@ var spine; return Texture; }()); spine.Texture = Texture; + var TextureFilter; (function (TextureFilter) { TextureFilter[TextureFilter["Nearest"] = 9728] = "Nearest"; TextureFilter[TextureFilter["Linear"] = 9729] = "Linear"; @@ -4778,14 +5003,13 @@ var spine; TextureFilter[TextureFilter["MipMapLinearNearest"] = 9985] = "MipMapLinearNearest"; TextureFilter[TextureFilter["MipMapNearestLinear"] = 9986] = "MipMapNearestLinear"; TextureFilter[TextureFilter["MipMapLinearLinear"] = 9987] = "MipMapLinearLinear"; - })(spine.TextureFilter || (spine.TextureFilter = {})); - var TextureFilter = spine.TextureFilter; + })(TextureFilter = spine.TextureFilter || (spine.TextureFilter = {})); + var TextureWrap; (function (TextureWrap) { TextureWrap[TextureWrap["MirroredRepeat"] = 33648] = "MirroredRepeat"; TextureWrap[TextureWrap["ClampToEdge"] = 33071] = "ClampToEdge"; TextureWrap[TextureWrap["Repeat"] = 10497] = "Repeat"; - })(spine.TextureWrap || (spine.TextureWrap = {})); - var TextureWrap = spine.TextureWrap; + })(TextureWrap = spine.TextureWrap || (spine.TextureWrap = {})); var TextureRegion = (function () { function TextureRegion() { this.u = 0; @@ -4953,7 +5177,7 @@ var spine; var TextureAtlasRegion = (function (_super) { __extends(TextureAtlasRegion, _super); function TextureAtlasRegion() { - _super.apply(this, arguments); + return _super !== null && _super.apply(this, arguments) || this; } return TextureAtlasRegion; }(spine.TextureRegion)); @@ -4986,6 +5210,20 @@ var spine; this.update(); }; TransformConstraint.prototype.update = function () { + if (this.data.local) { + if (this.data.relative) + this.applyRelativeLocal(); + else + this.applyAbsoluteLocal(); + } + else { + if (this.data.relative) + this.applyRelativeWorld(); + else + this.applyAbsoluteWorld(); + } + }; + TransformConstraint.prototype.applyAbsoluteWorld = function () { var rotateMix = this.rotateMix, translateMix = this.translateMix, scaleMix = this.scaleMix, shearMix = this.shearMix; var target = this.target; var ta = target.a, tb = target.b, tc = target.c, td = target.d; @@ -5051,6 +5289,132 @@ var spine; bone.appliedValid = false; } }; + TransformConstraint.prototype.applyRelativeWorld = function () { + var rotateMix = this.rotateMix, translateMix = this.translateMix, scaleMix = this.scaleMix, shearMix = this.shearMix; + var target = this.target; + var ta = target.a, tb = target.b, tc = target.c, td = target.d; + var degRadReflect = ta * td - tb * tc > 0 ? spine.MathUtils.degRad : -spine.MathUtils.degRad; + var offsetRotation = this.data.offsetRotation * degRadReflect, offsetShearY = this.data.offsetShearY * degRadReflect; + var bones = this.bones; + for (var i = 0, n = bones.length; i < n; i++) { + var bone = bones[i]; + var modified = false; + if (rotateMix != 0) { + var a = bone.a, b = bone.b, c = bone.c, d = bone.d; + var r = Math.atan2(tc, ta) + offsetRotation; + if (r > spine.MathUtils.PI) + r -= spine.MathUtils.PI2; + else if (r < -spine.MathUtils.PI) + r += spine.MathUtils.PI2; + r *= rotateMix; + var cos = Math.cos(r), sin = Math.sin(r); + bone.a = cos * a - sin * c; + bone.b = cos * b - sin * d; + bone.c = sin * a + cos * c; + bone.d = sin * b + cos * d; + modified = true; + } + if (translateMix != 0) { + var temp = this.temp; + target.localToWorld(temp.set(this.data.offsetX, this.data.offsetY)); + bone.worldX += temp.x * translateMix; + bone.worldY += temp.y * translateMix; + modified = true; + } + if (scaleMix > 0) { + var s = (Math.sqrt(ta * ta + tc * tc) - 1 + this.data.offsetScaleX) * scaleMix + 1; + bone.a *= s; + bone.c *= s; + s = (Math.sqrt(tb * tb + td * td) - 1 + this.data.offsetScaleY) * scaleMix + 1; + bone.b *= s; + bone.d *= s; + modified = true; + } + if (shearMix > 0) { + var r = Math.atan2(td, tb) - Math.atan2(tc, ta); + if (r > spine.MathUtils.PI) + r -= spine.MathUtils.PI2; + else if (r < -spine.MathUtils.PI) + r += spine.MathUtils.PI2; + var b = bone.b, d = bone.d; + r = Math.atan2(d, b) + (r - spine.MathUtils.PI / 2 + offsetShearY) * shearMix; + var s = Math.sqrt(b * b + d * d); + bone.b = Math.cos(r) * s; + bone.d = Math.sin(r) * s; + modified = true; + } + if (modified) + bone.appliedValid = false; + } + }; + TransformConstraint.prototype.applyAbsoluteLocal = function () { + var rotateMix = this.rotateMix, translateMix = this.translateMix, scaleMix = this.scaleMix, shearMix = this.shearMix; + var target = this.target; + if (!target.appliedValid) + target.updateAppliedTransform(); + var bones = this.bones; + for (var i = 0, n = bones.length; i < n; i++) { + var bone = bones[i]; + if (!bone.appliedValid) + bone.updateAppliedTransform(); + var rotation = bone.arotation; + if (rotateMix != 0) { + var r = target.arotation - rotation + this.data.offsetRotation; + r -= (16384 - ((16384.499999999996 - r / 360) | 0)) * 360; + rotation += r * rotateMix; + } + var x = bone.ax, y = bone.ay; + if (translateMix != 0) { + x += (target.ax - x + this.data.offsetX) * translateMix; + y += (target.ay - y + this.data.offsetY) * translateMix; + } + var scaleX = bone.ascaleX, scaleY = bone.ascaleY; + if (scaleMix > 0) { + if (scaleX > 0.00001) + scaleX = (scaleX + (target.ascaleX - scaleX + this.data.offsetScaleX) * scaleMix) / scaleX; + if (scaleY > 0.00001) + scaleY = (scaleY + (target.ascaleY - scaleY + this.data.offsetScaleY) * scaleMix) / scaleY; + } + var shearY = bone.ashearY; + if (shearMix > 0) { + var r = target.ashearY - shearY + this.data.offsetShearY; + r -= (16384 - ((16384.499999999996 - r / 360) | 0)) * 360; + bone.shearY += r * shearMix; + } + bone.updateWorldTransformWith(x, y, rotation, scaleX, scaleY, bone.ashearX, shearY); + } + }; + TransformConstraint.prototype.applyRelativeLocal = function () { + var rotateMix = this.rotateMix, translateMix = this.translateMix, scaleMix = this.scaleMix, shearMix = this.shearMix; + var target = this.target; + if (!target.appliedValid) + target.updateAppliedTransform(); + var bones = this.bones; + for (var i = 0, n = bones.length; i < n; i++) { + var bone = bones[i]; + if (!bone.appliedValid) + bone.updateAppliedTransform(); + var rotation = bone.arotation; + if (rotateMix != 0) + rotation += (target.arotation + this.data.offsetRotation) * rotateMix; + var x = bone.ax, y = bone.ay; + if (translateMix != 0) { + x += (target.ax + this.data.offsetX) * translateMix; + y += (target.ay + this.data.offsetY) * translateMix; + } + var scaleX = bone.ascaleX, scaleY = bone.ascaleY; + if (scaleMix > 0) { + if (scaleX > 0.00001) + scaleX *= ((target.ascaleX - 1 + this.data.offsetScaleX) * scaleMix) + 1; + if (scaleY > 0.00001) + scaleY *= ((target.ascaleY - 1 + this.data.offsetScaleY) * scaleMix) + 1; + } + var shearY = bone.ashearY; + if (shearMix > 0) + shearY += (target.ashearY + this.data.offsetShearY) * shearMix; + bone.updateWorldTransformWith(x, y, rotation, scaleX, scaleY, bone.ashearX, shearY); + } + }; TransformConstraint.prototype.getOrder = function () { return this.data.order; }; @@ -5074,13 +5438,227 @@ var spine; this.offsetScaleX = 0; this.offsetScaleY = 0; this.offsetShearY = 0; + this.relative = false; + this.local = false; if (name == null) throw new Error("name cannot be null."); this.name = name; } return TransformConstraintData; }()); - spine.TransformConstraintData = TransformConstraintData; + spine.TransformConstraintData = TransformConstraintData; +})(spine || (spine = {})); +var spine; +(function (spine) { + var Triangulator = (function () { + function Triangulator() { + this.convexPolygons = new Array(); + this.convexPolygonsIndices = new Array(); + this.indicesArray = new Array(); + this.isConcaveArray = new Array(); + this.triangles = new Array(); + this.polygonPool = new spine.Pool(function () { + return new Array(); + }); + this.polygonIndicesPool = new spine.Pool(function () { + return new Array(); + }); + } + Triangulator.prototype.triangulate = function (verticesArray) { + var vertices = verticesArray; + var vertexCount = verticesArray.length >> 1; + var indices = this.indicesArray; + indices.length = 0; + for (var i = 0; i < vertexCount; i++) + indices[i] = i; + var isConcave = this.isConcaveArray; + isConcave.length = 0; + for (var i = 0, n = vertexCount; i < n; ++i) + isConcave[i] = Triangulator.isConcave(i, vertexCount, vertices, indices); + var triangles = this.triangles; + triangles.length = 0; + while (vertexCount > 3) { + var previous = vertexCount - 1, i = 0, next = 1; + while (true) { + outer: if (!isConcave[i]) { + var p1 = indices[previous] << 1, p2 = indices[i] << 1, p3 = indices[next] << 1; + var p1x = vertices[p1], p1y = vertices[p1 + 1]; + var p2x = vertices[p2], p2y = vertices[p2 + 1]; + var p3x = vertices[p3], p3y = vertices[p3 + 1]; + for (var ii = (next + 1) % vertexCount; ii != previous; ii = (ii + 1) % vertexCount) { + if (!isConcave[ii]) + continue; + var v = indices[ii] << 1; + var vx = vertices[v], vy = vertices[v + 1]; + if (Triangulator.positiveArea(p3x, p3y, p1x, p1y, vx, vy)) { + if (Triangulator.positiveArea(p1x, p1y, p2x, p2y, vx, vy)) { + if (Triangulator.positiveArea(p2x, p2y, p3x, p3y, vx, vy)) + break outer; + } + } + } + break; + } + if (next == 0) { + do { + if (!isConcave[i]) + break; + i--; + } while (i > 0); + break; + } + previous = i; + i = next; + next = (next + 1) % vertexCount; + } + triangles.push(indices[(vertexCount + i - 1) % vertexCount]); + triangles.push(indices[i]); + triangles.push(indices[(i + 1) % vertexCount]); + indices.splice(i, 1); + isConcave.splice(i, 1); + vertexCount--; + var previousIndex = (vertexCount + i - 1) % vertexCount; + var nextIndex = i == vertexCount ? 0 : i; + isConcave[previousIndex] = Triangulator.isConcave(previousIndex, vertexCount, vertices, indices); + isConcave[nextIndex] = Triangulator.isConcave(nextIndex, vertexCount, vertices, indices); + } + if (vertexCount == 3) { + triangles.push(indices[2]); + triangles.push(indices[0]); + triangles.push(indices[1]); + } + return triangles; + }; + Triangulator.prototype.decompose = function (verticesArray, triangles) { + var vertices = verticesArray; + var convexPolygons = this.convexPolygons; + this.polygonPool.freeAll(convexPolygons); + convexPolygons.length = 0; + var convexPolygonsIndices = this.convexPolygonsIndices; + this.polygonIndicesPool.freeAll(convexPolygonsIndices); + convexPolygonsIndices.length = 0; + var polygonIndices = this.polygonIndicesPool.obtain(); + polygonIndices.length = 0; + var polygon = this.polygonPool.obtain(); + polygon.length = 0; + var fanBaseIndex = -1, lastWinding = 0; + for (var i = 0, n = triangles.length; i < n; i += 3) { + var t1 = triangles[i] << 1, t2 = triangles[i + 1] << 1, t3 = triangles[i + 2] << 1; + var x1 = vertices[t1], y1 = vertices[t1 + 1]; + var x2 = vertices[t2], y2 = vertices[t2 + 1]; + var x3 = vertices[t3], y3 = vertices[t3 + 1]; + var merged = false; + if (fanBaseIndex == t1) { + var o = polygon.length - 4; + var winding1 = Triangulator.winding(polygon[o], polygon[o + 1], polygon[o + 2], polygon[o + 3], x3, y3); + var winding2 = Triangulator.winding(x3, y3, polygon[0], polygon[1], polygon[2], polygon[3]); + if (winding1 == lastWinding && winding2 == lastWinding) { + polygon.push(x3); + polygon.push(y3); + polygonIndices.push(t3); + merged = true; + } + } + if (!merged) { + if (polygon.length > 0) { + convexPolygons.push(polygon); + convexPolygonsIndices.push(polygonIndices); + } + else { + this.polygonPool.free(polygon); + this.polygonIndicesPool.free(polygonIndices); + } + polygon = this.polygonPool.obtain(); + polygon.length = 0; + polygon.push(x1); + polygon.push(y1); + polygon.push(x2); + polygon.push(y2); + polygon.push(x3); + polygon.push(y3); + polygonIndices = this.polygonIndicesPool.obtain(); + polygonIndices.length = 0; + polygonIndices.push(t1); + polygonIndices.push(t2); + polygonIndices.push(t3); + lastWinding = Triangulator.winding(x1, y1, x2, y2, x3, y3); + fanBaseIndex = t1; + } + } + if (polygon.length > 0) { + convexPolygons.push(polygon); + convexPolygonsIndices.push(polygonIndices); + } + for (var i = 0, n = convexPolygons.length; i < n; i++) { + polygonIndices = convexPolygonsIndices[i]; + if (polygonIndices.length == 0) + continue; + var firstIndex = polygonIndices[0]; + var lastIndex = polygonIndices[polygonIndices.length - 1]; + polygon = convexPolygons[i]; + var o = polygon.length - 4; + var prevPrevX = polygon[o], prevPrevY = polygon[o + 1]; + var prevX = polygon[o + 2], prevY = polygon[o + 3]; + var firstX = polygon[0], firstY = polygon[1]; + var secondX = polygon[2], secondY = polygon[3]; + var winding = Triangulator.winding(prevPrevX, prevPrevY, prevX, prevY, firstX, firstY); + for (var ii = 0; ii < n; ii++) { + if (ii == i) + continue; + var otherIndices = convexPolygonsIndices[ii]; + if (otherIndices.length != 3) + continue; + var otherFirstIndex = otherIndices[0]; + var otherSecondIndex = otherIndices[1]; + var otherLastIndex = otherIndices[2]; + var otherPoly = convexPolygons[ii]; + var x3 = otherPoly[otherPoly.length - 2], y3 = otherPoly[otherPoly.length - 1]; + if (otherFirstIndex != firstIndex || otherSecondIndex != lastIndex) + continue; + var winding1 = Triangulator.winding(prevPrevX, prevPrevY, prevX, prevY, x3, y3); + var winding2 = Triangulator.winding(x3, y3, firstX, firstY, secondX, secondY); + if (winding1 == winding && winding2 == winding) { + otherPoly.length = 0; + otherIndices.length = 0; + polygon.push(x3); + polygon.push(y3); + polygonIndices.push(otherLastIndex); + prevPrevX = prevX; + prevPrevY = prevY; + prevX = x3; + prevY = y3; + ii = 0; + } + } + } + for (var i = convexPolygons.length - 1; i >= 0; i--) { + polygon = convexPolygons[i]; + if (polygon.length == 0) { + convexPolygons.splice(i, 1); + this.polygonPool.free(polygon); + polygonIndices = convexPolygonsIndices[i]; + convexPolygonsIndices.splice(i, 1); + this.polygonIndicesPool.free(polygonIndices); + } + } + return convexPolygons; + }; + Triangulator.isConcave = function (index, vertexCount, vertices, indices) { + var previous = indices[(vertexCount + index - 1) % vertexCount] << 1; + var current = indices[index] << 1; + var next = indices[(index + 1) % vertexCount] << 1; + return !this.positiveArea(vertices[previous], vertices[previous + 1], vertices[current], vertices[current + 1], vertices[next], vertices[next + 1]); + }; + Triangulator.positiveArea = function (p1x, p1y, p2x, p2y, p3x, p3y) { + return p1x * (p3y - p2y) + p2x * (p1y - p3y) + p3x * (p2y - p1y) >= 0; + }; + Triangulator.winding = function (p1x, p1y, p2x, p2y, p3x, p3y) { + var px = p2x - p1x, py = p2y - p1y; + return p3x * py - p3y * px + px * p1y - p1x * py >= 0 ? 1 : -1; + }; + return Triangulator; + }()); + spine.Triangulator = Triangulator; })(spine || (spine = {})); var spine; (function (spine) { @@ -5166,13 +5744,13 @@ var spine; this.a = 1; return this; }; - Color.WHITE = new Color(1, 1, 1, 1); - Color.RED = new Color(1, 0, 0, 1); - Color.GREEN = new Color(0, 1, 0, 1); - Color.BLUE = new Color(0, 0, 1, 1); - Color.MAGENTA = new Color(1, 0, 1, 1); return Color; }()); + Color.WHITE = new Color(1, 1, 1, 1); + Color.RED = new Color(1, 0, 0, 1); + Color.GREEN = new Color(0, 1, 0, 1); + Color.BLUE = new Color(0, 0, 1, 1); + Color.MAGENTA = new Color(1, 0, 1, 1); spine.Color = Color; var MathUtils = (function () { function MathUtils() { @@ -5200,15 +5778,61 @@ var spine; var y = Math.pow(Math.abs(x), 1 / 3); return x < 0 ? -y : y; }; - MathUtils.PI = 3.1415927; - MathUtils.PI2 = MathUtils.PI * 2; - MathUtils.radiansToDegrees = 180 / MathUtils.PI; - MathUtils.radDeg = MathUtils.radiansToDegrees; - MathUtils.degreesToRadians = MathUtils.PI / 180; - MathUtils.degRad = MathUtils.degreesToRadians; + MathUtils.randomTriangular = function (min, max) { + return MathUtils.randomTriangularWith(min, max, (min + max) * 0.5); + }; + MathUtils.randomTriangularWith = function (min, max, mode) { + var u = Math.random(); + var d = max - min; + if (u <= (mode - min) / d) + return min + Math.sqrt(u * d * (mode - min)); + return max - Math.sqrt((1 - u) * d * (max - mode)); + }; return MathUtils; }()); + MathUtils.PI = 3.1415927; + MathUtils.PI2 = MathUtils.PI * 2; + MathUtils.radiansToDegrees = 180 / MathUtils.PI; + MathUtils.radDeg = MathUtils.radiansToDegrees; + MathUtils.degreesToRadians = MathUtils.PI / 180; + MathUtils.degRad = MathUtils.degreesToRadians; spine.MathUtils = MathUtils; + var Interpolation = (function () { + function Interpolation() { + } + Interpolation.prototype.apply = function (start, end, a) { + return start + (end - start) * this.applyInternal(a); + }; + return Interpolation; + }()); + spine.Interpolation = Interpolation; + var Pow = (function (_super) { + __extends(Pow, _super); + function Pow(power) { + var _this = _super.call(this) || this; + _this.power = 2; + _this.power = power; + return _this; + } + Pow.prototype.applyInternal = function (a) { + if (a <= 0.5) + return Math.pow(a * 2, this.power) / 2; + return Math.pow((a - 1) * 2, this.power) / (this.power % 2 == 0 ? -2 : 2) + 1; + }; + return Pow; + }(Interpolation)); + spine.Pow = Pow; + var PowOut = (function (_super) { + __extends(PowOut, _super); + function PowOut(power) { + return _super.call(this, power) || this; + } + PowOut.prototype.applyInternal = function (a) { + return Math.pow(a - 1, this.power) * (this.power % 2 == 0 ? -1 : 1) + 1; + }; + return PowOut; + }(Pow)); + spine.PowOut = PowOut; var Utils = (function () { function Utils() { } @@ -5252,12 +5876,26 @@ var spine; return array; } }; + Utils.newShortArray = function (size) { + if (Utils.SUPPORTS_TYPED_ARRAYS) { + return new Int16Array(size); + } + else { + var array = new Array(size); + for (var i = 0; i < array.length; i++) + array[i] = 0; + return array; + } + }; Utils.toFloatArray = function (array) { return Utils.SUPPORTS_TYPED_ARRAYS ? new Float32Array(array) : array; }; - Utils.SUPPORTS_TYPED_ARRAYS = typeof (Float32Array) !== "undefined"; + Utils.toSinglePrecision = function (value) { + return Utils.SUPPORTS_TYPED_ARRAYS ? Math.fround(value) : value; + }; return Utils; }()); + Utils.SUPPORTS_TYPED_ARRAYS = typeof (Float32Array) !== "undefined"; spine.Utils = Utils; var DebugUtils = (function () { function DebugUtils() { @@ -5353,7 +5991,465 @@ var spine; return TimeKeeper; }()); spine.TimeKeeper = TimeKeeper; + var WindowedMean = (function () { + function WindowedMean(windowSize) { + if (windowSize === void 0) { windowSize = 32; } + this.addedValues = 0; + this.lastValue = 0; + this.mean = 0; + this.dirty = true; + this.values = new Array(windowSize); + } + WindowedMean.prototype.hasEnoughData = function () { + return this.addedValues >= this.values.length; + }; + WindowedMean.prototype.addValue = function (value) { + if (this.addedValues < this.values.length) + this.addedValues++; + this.values[this.lastValue++] = value; + if (this.lastValue > this.values.length - 1) + this.lastValue = 0; + this.dirty = true; + }; + WindowedMean.prototype.getMean = function () { + if (this.hasEnoughData()) { + if (this.dirty) { + var mean = 0; + for (var i = 0; i < this.values.length; i++) { + mean += this.values[i]; + } + this.mean = mean / this.values.length; + this.dirty = false; + } + return this.mean; + } + else { + return 0; + } + }; + return WindowedMean; + }()); + spine.WindowedMean = WindowedMean; +})(spine || (spine = {})); +var spine; +(function (spine) { + var Attachment = (function () { + function Attachment(name) { + if (name == null) + throw new Error("name cannot be null."); + this.name = name; + } + return Attachment; + }()); + spine.Attachment = Attachment; + var VertexAttachment = (function (_super) { + __extends(VertexAttachment, _super); + function VertexAttachment(name) { + var _this = _super.call(this, name) || this; + _this.id = (VertexAttachment.nextID++ & 65535) << 11; + _this.worldVerticesLength = 0; + return _this; + } + VertexAttachment.prototype.computeWorldVertices = function (slot, start, count, worldVertices, offset, stride) { + count = offset + (count >> 1) * stride; + var skeleton = slot.bone.skeleton; + var deformArray = slot.attachmentVertices; + var vertices = this.vertices; + var bones = this.bones; + if (bones == null) { + if (deformArray.length > 0) + vertices = deformArray; + var bone = slot.bone; + var x = bone.worldX; + var y = bone.worldY; + var a = bone.a, b = bone.b, c = bone.c, d = bone.d; + for (var v_1 = start, w = offset; w < count; v_1 += 2, w += stride) { + var vx = vertices[v_1], vy = vertices[v_1 + 1]; + worldVertices[w] = vx * a + vy * b + x; + worldVertices[w + 1] = vx * c + vy * d + y; + } + return; + } + var v = 0, skip = 0; + for (var i = 0; i < start; i += 2) { + var n = bones[v]; + v += n + 1; + skip += n; + } + var skeletonBones = skeleton.bones; + if (deformArray.length == 0) { + for (var w = offset, b = skip * 3; w < count; w += stride) { + var wx = 0, wy = 0; + var n = bones[v++]; + n += v; + for (; v < n; v++, b += 3) { + var bone = skeletonBones[bones[v]]; + var vx = vertices[b], vy = vertices[b + 1], weight = vertices[b + 2]; + wx += (vx * bone.a + vy * bone.b + bone.worldX) * weight; + wy += (vx * bone.c + vy * bone.d + bone.worldY) * weight; + } + worldVertices[w] = wx; + worldVertices[w + 1] = wy; + } + } + else { + var deform = deformArray; + for (var w = offset, b = skip * 3, f = skip << 1; w < count; w += stride) { + var wx = 0, wy = 0; + var n = bones[v++]; + n += v; + for (; v < n; v++, b += 3, f += 2) { + var bone = skeletonBones[bones[v]]; + var vx = vertices[b] + deform[f], vy = vertices[b + 1] + deform[f + 1], weight = vertices[b + 2]; + wx += (vx * bone.a + vy * bone.b + bone.worldX) * weight; + wy += (vx * bone.c + vy * bone.d + bone.worldY) * weight; + } + worldVertices[w] = wx; + worldVertices[w + 1] = wy; + } + } + }; + VertexAttachment.prototype.applyDeform = function (sourceAttachment) { + return this == sourceAttachment; + }; + return VertexAttachment; + }(Attachment)); + VertexAttachment.nextID = 0; + spine.VertexAttachment = VertexAttachment; +})(spine || (spine = {})); +var spine; +(function (spine) { + var AttachmentType; + (function (AttachmentType) { + AttachmentType[AttachmentType["Region"] = 0] = "Region"; + AttachmentType[AttachmentType["BoundingBox"] = 1] = "BoundingBox"; + AttachmentType[AttachmentType["Mesh"] = 2] = "Mesh"; + AttachmentType[AttachmentType["LinkedMesh"] = 3] = "LinkedMesh"; + AttachmentType[AttachmentType["Path"] = 4] = "Path"; + AttachmentType[AttachmentType["Point"] = 5] = "Point"; + })(AttachmentType = spine.AttachmentType || (spine.AttachmentType = {})); +})(spine || (spine = {})); +var spine; +(function (spine) { + var BoundingBoxAttachment = (function (_super) { + __extends(BoundingBoxAttachment, _super); + function BoundingBoxAttachment(name) { + var _this = _super.call(this, name) || this; + _this.color = new spine.Color(1, 1, 1, 1); + return _this; + } + return BoundingBoxAttachment; + }(spine.VertexAttachment)); + spine.BoundingBoxAttachment = BoundingBoxAttachment; +})(spine || (spine = {})); +var spine; +(function (spine) { + var ClippingAttachment = (function (_super) { + __extends(ClippingAttachment, _super); + function ClippingAttachment(name) { + var _this = _super.call(this, name) || this; + _this.color = new spine.Color(0.2275, 0.2275, 0.8078, 1); + return _this; + } + return ClippingAttachment; + }(spine.VertexAttachment)); + spine.ClippingAttachment = ClippingAttachment; +})(spine || (spine = {})); +var spine; +(function (spine) { + var MeshAttachment = (function (_super) { + __extends(MeshAttachment, _super); + function MeshAttachment(name) { + var _this = _super.call(this, name) || this; + _this.color = new spine.Color(1, 1, 1, 1); + _this.inheritDeform = false; + _this.tempColor = new spine.Color(0, 0, 0, 0); + return _this; + } + MeshAttachment.prototype.updateUVs = function () { + var u = 0, v = 0, width = 0, height = 0; + if (this.region == null) { + u = v = 0; + width = height = 1; + } + else { + u = this.region.u; + v = this.region.v; + width = this.region.u2 - u; + height = this.region.v2 - v; + } + var regionUVs = this.regionUVs; + if (this.uvs == null || this.uvs.length != regionUVs.length) + this.uvs = spine.Utils.newFloatArray(regionUVs.length); + var uvs = this.uvs; + if (this.region.rotate) { + for (var i = 0, n = uvs.length; i < n; i += 2) { + uvs[i] = u + regionUVs[i + 1] * width; + uvs[i + 1] = v + height - regionUVs[i] * height; + } + } + else { + for (var i = 0, n = uvs.length; i < n; i += 2) { + uvs[i] = u + regionUVs[i] * width; + uvs[i + 1] = v + regionUVs[i + 1] * height; + } + } + }; + MeshAttachment.prototype.applyDeform = function (sourceAttachment) { + return this == sourceAttachment || (this.inheritDeform && this.parentMesh == sourceAttachment); + }; + MeshAttachment.prototype.getParentMesh = function () { + return this.parentMesh; + }; + MeshAttachment.prototype.setParentMesh = function (parentMesh) { + this.parentMesh = parentMesh; + if (parentMesh != null) { + this.bones = parentMesh.bones; + this.vertices = parentMesh.vertices; + this.worldVerticesLength = parentMesh.worldVerticesLength; + this.regionUVs = parentMesh.regionUVs; + this.triangles = parentMesh.triangles; + this.hullLength = parentMesh.hullLength; + this.worldVerticesLength = parentMesh.worldVerticesLength; + } + }; + return MeshAttachment; + }(spine.VertexAttachment)); + spine.MeshAttachment = MeshAttachment; +})(spine || (spine = {})); +var spine; +(function (spine) { + var PathAttachment = (function (_super) { + __extends(PathAttachment, _super); + function PathAttachment(name) { + var _this = _super.call(this, name) || this; + _this.closed = false; + _this.constantSpeed = false; + _this.color = new spine.Color(1, 1, 1, 1); + return _this; + } + return PathAttachment; + }(spine.VertexAttachment)); + spine.PathAttachment = PathAttachment; +})(spine || (spine = {})); +var spine; +(function (spine) { + var PointAttachment = (function (_super) { + __extends(PointAttachment, _super); + function PointAttachment(name) { + var _this = _super.call(this, name) || this; + _this.color = new spine.Color(0.38, 0.94, 0, 1); + return _this; + } + PointAttachment.prototype.computeWorldPosition = function (bone, point) { + point.x = this.x * bone.a + this.y * bone.b + bone.worldX; + point.y = this.x * bone.c + this.y * bone.d + bone.worldY; + return point; + }; + PointAttachment.prototype.computeWorldRotation = function (bone) { + var cos = spine.MathUtils.cosDeg(this.rotation), sin = spine.MathUtils.sinDeg(this.rotation); + var x = cos * bone.a + sin * bone.b; + var y = cos * bone.c + sin * bone.d; + return Math.atan2(y, x) * spine.MathUtils.radDeg; + }; + return PointAttachment; + }(spine.VertexAttachment)); + spine.PointAttachment = PointAttachment; +})(spine || (spine = {})); +var spine; +(function (spine) { + var RegionAttachment = (function (_super) { + __extends(RegionAttachment, _super); + function RegionAttachment(name) { + var _this = _super.call(this, name) || this; + _this.x = 0; + _this.y = 0; + _this.scaleX = 1; + _this.scaleY = 1; + _this.rotation = 0; + _this.width = 0; + _this.height = 0; + _this.color = new spine.Color(1, 1, 1, 1); + _this.offset = spine.Utils.newFloatArray(8); + _this.uvs = spine.Utils.newFloatArray(8); + _this.tempColor = new spine.Color(1, 1, 1, 1); + return _this; + } + RegionAttachment.prototype.updateOffset = function () { + var regionScaleX = this.width / this.region.originalWidth * this.scaleX; + var regionScaleY = this.height / this.region.originalHeight * this.scaleY; + var localX = -this.width / 2 * this.scaleX + this.region.offsetX * regionScaleX; + var localY = -this.height / 2 * this.scaleY + this.region.offsetY * regionScaleY; + var localX2 = localX + this.region.width * regionScaleX; + var localY2 = localY + this.region.height * regionScaleY; + var radians = this.rotation * Math.PI / 180; + var cos = Math.cos(radians); + var sin = Math.sin(radians); + var localXCos = localX * cos + this.x; + var localXSin = localX * sin; + var localYCos = localY * cos + this.y; + var localYSin = localY * sin; + var localX2Cos = localX2 * cos + this.x; + var localX2Sin = localX2 * sin; + var localY2Cos = localY2 * cos + this.y; + var localY2Sin = localY2 * sin; + var offset = this.offset; + offset[RegionAttachment.OX1] = localXCos - localYSin; + offset[RegionAttachment.OY1] = localYCos + localXSin; + offset[RegionAttachment.OX2] = localXCos - localY2Sin; + offset[RegionAttachment.OY2] = localY2Cos + localXSin; + offset[RegionAttachment.OX3] = localX2Cos - localY2Sin; + offset[RegionAttachment.OY3] = localY2Cos + localX2Sin; + offset[RegionAttachment.OX4] = localX2Cos - localYSin; + offset[RegionAttachment.OY4] = localYCos + localX2Sin; + }; + RegionAttachment.prototype.setRegion = function (region) { + this.region = region; + var uvs = this.uvs; + if (region.rotate) { + uvs[2] = region.u; + uvs[3] = region.v2; + uvs[4] = region.u; + uvs[5] = region.v; + uvs[6] = region.u2; + uvs[7] = region.v; + uvs[0] = region.u2; + uvs[1] = region.v2; + } + else { + uvs[0] = region.u; + uvs[1] = region.v2; + uvs[2] = region.u; + uvs[3] = region.v; + uvs[4] = region.u2; + uvs[5] = region.v; + uvs[6] = region.u2; + uvs[7] = region.v2; + } + }; + RegionAttachment.prototype.computeWorldVertices = function (bone, worldVertices, offset, stride) { + var vertexOffset = this.offset; + var x = bone.worldX, y = bone.worldY; + var a = bone.a, b = bone.b, c = bone.c, d = bone.d; + var offsetX = 0, offsetY = 0; + offsetX = vertexOffset[RegionAttachment.OX1]; + offsetY = vertexOffset[RegionAttachment.OY1]; + worldVertices[offset] = offsetX * a + offsetY * b + x; + worldVertices[offset + 1] = offsetX * c + offsetY * d + y; + offset += stride; + offsetX = vertexOffset[RegionAttachment.OX2]; + offsetY = vertexOffset[RegionAttachment.OY2]; + worldVertices[offset] = offsetX * a + offsetY * b + x; + worldVertices[offset + 1] = offsetX * c + offsetY * d + y; + offset += stride; + offsetX = vertexOffset[RegionAttachment.OX3]; + offsetY = vertexOffset[RegionAttachment.OY3]; + worldVertices[offset] = offsetX * a + offsetY * b + x; + worldVertices[offset + 1] = offsetX * c + offsetY * d + y; + offset += stride; + offsetX = vertexOffset[RegionAttachment.OX4]; + offsetY = vertexOffset[RegionAttachment.OY4]; + worldVertices[offset] = offsetX * a + offsetY * b + x; + worldVertices[offset + 1] = offsetX * c + offsetY * d + y; + }; + return RegionAttachment; + }(spine.Attachment)); + RegionAttachment.OX1 = 0; + RegionAttachment.OY1 = 1; + RegionAttachment.OX2 = 2; + RegionAttachment.OY2 = 3; + RegionAttachment.OX3 = 4; + RegionAttachment.OY3 = 5; + RegionAttachment.OX4 = 6; + RegionAttachment.OY4 = 7; + RegionAttachment.X1 = 0; + RegionAttachment.Y1 = 1; + RegionAttachment.C1R = 2; + RegionAttachment.C1G = 3; + RegionAttachment.C1B = 4; + RegionAttachment.C1A = 5; + RegionAttachment.U1 = 6; + RegionAttachment.V1 = 7; + RegionAttachment.X2 = 8; + RegionAttachment.Y2 = 9; + RegionAttachment.C2R = 10; + RegionAttachment.C2G = 11; + RegionAttachment.C2B = 12; + RegionAttachment.C2A = 13; + RegionAttachment.U2 = 14; + RegionAttachment.V2 = 15; + RegionAttachment.X3 = 16; + RegionAttachment.Y3 = 17; + RegionAttachment.C3R = 18; + RegionAttachment.C3G = 19; + RegionAttachment.C3B = 20; + RegionAttachment.C3A = 21; + RegionAttachment.U3 = 22; + RegionAttachment.V3 = 23; + RegionAttachment.X4 = 24; + RegionAttachment.Y4 = 25; + RegionAttachment.C4R = 26; + RegionAttachment.C4G = 27; + RegionAttachment.C4B = 28; + RegionAttachment.C4A = 29; + RegionAttachment.U4 = 30; + RegionAttachment.V4 = 31; + spine.RegionAttachment = RegionAttachment; +})(spine || (spine = {})); +var spine; +(function (spine) { + var JitterEffect = (function () { + function JitterEffect(jitterX, jitterY) { + this.jitterX = 0; + this.jitterY = 0; + this.jitterX = jitterX; + this.jitterY = jitterY; + } + JitterEffect.prototype.begin = function (skeleton) { + }; + JitterEffect.prototype.transform = function (position, uv, light, dark) { + position.x += spine.MathUtils.randomTriangular(-this.jitterX, this.jitterY); + position.y += spine.MathUtils.randomTriangular(-this.jitterX, this.jitterY); + }; + JitterEffect.prototype.end = function () { + }; + return JitterEffect; + }()); + spine.JitterEffect = JitterEffect; +})(spine || (spine = {})); +var spine; +(function (spine) { + var SwirlEffect = (function () { + function SwirlEffect(radius) { + this.centerX = 0; + this.centerY = 0; + this.radius = 0; + this.angle = 0; + this.worldX = 0; + this.worldY = 0; + this.radius = radius; + } + SwirlEffect.prototype.begin = function (skeleton) { + this.worldX = skeleton.x + this.centerX; + this.worldY = skeleton.y + this.centerY; + }; + SwirlEffect.prototype.transform = function (position, uv, light, dark) { + var radAngle = this.angle * spine.MathUtils.degreesToRadians; + var x = position.x - this.worldX; + var y = position.y - this.worldY; + var dist = Math.sqrt(x * x + y * y); + if (dist < this.radius) { + var theta = SwirlEffect.interpolation.apply(0, radAngle, (this.radius - dist) / this.radius); + var cos = Math.cos(theta); + var sin = Math.sin(theta); + position.x = cos * x - sin * y + this.worldX; + position.y = sin * x + cos * y + this.worldY; + } + }; + SwirlEffect.prototype.end = function () { + }; + return SwirlEffect; + }()); + SwirlEffect.interpolation = new spine.PowOut(2); + spine.SwirlEffect = SwirlEffect; })(spine || (spine = {})); - -var sp = sp || {}; -sp.spine = spine; From bf393b9856e86fc3154aa9e9ebf7b2376385a988 Mon Sep 17 00:00:00 2001 From: drelaptop Date: Tue, 10 Apr 2018 18:13:21 +0800 Subject: [PATCH 197/206] run success, but effect wrong --- extensions/spine/CCSkeleton.js | 4 +++- extensions/spine/CCSkeletonCanvasRenderCmd.js | 5 ++++- extensions/spine/CCSkeletonWebGLRenderCmd.js | 13 ++++++++++--- extensions/spine/Spine.js | 3 +++ 4 files changed, 20 insertions(+), 5 deletions(-) diff --git a/extensions/spine/CCSkeleton.js b/extensions/spine/CCSkeleton.js index 0f0d3ebdf3..0ab0ad2b72 100644 --- a/extensions/spine/CCSkeleton.js +++ b/extensions/spine/CCSkeleton.js @@ -228,7 +228,9 @@ sp.Skeleton = cc.Node.extend(/** @lends sp.Skeleton# */{ var attachment = slot.attachment; if (!attachment || !(attachment instanceof spine.RegionAttachment)) continue; - vertices = attachment.updateWorldVertices(slot, false); + // 3.5 vertices = attachment.updateWorldVertices(slot, false); + vertices = spine.Utils.setArraySize(new Array(), 8, 0); + attachment.computeWorldVertices(slot.bone, vertices, 0, 8); minX = Math.min(minX, vertices[VERTEX.X1] * scaleX, vertices[VERTEX.X4] * scaleX, vertices[VERTEX.X2] * scaleX, vertices[VERTEX.X3] * scaleX); minY = Math.min(minY, vertices[VERTEX.Y1] * scaleY, vertices[VERTEX.Y4] * scaleY, vertices[VERTEX.Y2] * scaleY, vertices[VERTEX.Y3] * scaleY); maxX = Math.max(maxX, vertices[VERTEX.X1] * scaleX, vertices[VERTEX.X4] * scaleX, vertices[VERTEX.X2] * scaleX, vertices[VERTEX.X3] * scaleX); diff --git a/extensions/spine/CCSkeletonCanvasRenderCmd.js b/extensions/spine/CCSkeletonCanvasRenderCmd.js index 1348ba920e..96de903a55 100644 --- a/extensions/spine/CCSkeletonCanvasRenderCmd.js +++ b/extensions/spine/CCSkeletonCanvasRenderCmd.js @@ -87,6 +87,7 @@ proto.rendering = function (wrapper, scaleX, scaleY) { } // Bone origins. + // FIXME: point position wrong, might due to scale drawingUtil.setPointSize(4); drawingUtil.setDrawColor(0, 0, 255, 255); // Root bone is blue. @@ -114,7 +115,9 @@ proto._updateRegionAttachmentSlot = function (attachment, slot, points) { if (!points) return; - var vertices = attachment.updateWorldVertices(slot, false); + // 3.5 var vertices = attachment.updateWorldVertices(slot, false); + var vertices = spine.Utils.setArraySize(new Array(), 8, 0); + attachment.computeWorldVertices(slot.bone, vertices, 0, 8); var VERTEX = spine.RegionAttachment; points.length = 0; points.push(cc.p(vertices[VERTEX.X1], vertices[VERTEX.Y1])); diff --git a/extensions/spine/CCSkeletonWebGLRenderCmd.js b/extensions/spine/CCSkeletonWebGLRenderCmd.js index bbe4cd805d..6204b12bb5 100644 --- a/extensions/spine/CCSkeletonWebGLRenderCmd.js +++ b/extensions/spine/CCSkeletonWebGLRenderCmd.js @@ -233,7 +233,11 @@ proto._uploadRegionAttachmentData = function(attachment, slot, premultipliedAlph nodeG = nodeColor.g, nodeB = nodeColor.b, nodeA = this._displayedOpacity; - var vertices = attachment.updateWorldVertices(slot, premultipliedAlpha); + // 3.5 var vertices = attachment.updateWorldVertices(slot, premultipliedAlpha); + // FIXME: lose premultipliedAlpha? + var vertices = spine.Utils.setArraySize(new Array(), 8, 0); + attachment.computeWorldVertices(slot.bone, vertices, 0, 8); + var wt = this._worldTransform, wa = wt.a, wb = wt.b, wc = wt.c, wd = wt.d, wx = wt.tx, wy = wt.ty, @@ -280,14 +284,17 @@ proto._uploadMeshAttachmentData = function(attachment, slot, premultipliedAlpha, wx = wt.tx, wy = wt.ty, z = this._node.vertexZ; // get the vertex data - var vertices = attachment.updateWorldVertices(slot, premultipliedAlpha); + // 3.5 var vertices = attachment.updateWorldVertices(slot, premultipliedAlpha); + var verticesLength = attachment.worldVerticesLength; + var vertices = spine.Utils.setArraySize(new Array(), verticesLength, 0); + attachment.computeWorldVertices(slot, 0, verticesLength, vertices, 0, 2); var offset = vertexDataOffset; var nodeColor = this._displayedColor; var nodeR = nodeColor.r, nodeG = nodeColor.g, nodeB = nodeColor.b, nodeA = this._displayedOpacity; - for (var i = 0, n = vertices.length; i < n; i += 8) { + for (var i = 0, n = vertices.length; i < n; i += 2) { var vx = vertices[i], vy = vertices[i + 1]; var x = vx * wa + vy * wb + wx, diff --git a/extensions/spine/Spine.js b/extensions/spine/Spine.js index b4ffec4b15..e7c0d894ea 100644 --- a/extensions/spine/Spine.js +++ b/extensions/spine/Spine.js @@ -6453,3 +6453,6 @@ var spine; SwirlEffect.interpolation = new spine.PowOut(2); spine.SwirlEffect = SwirlEffect; })(spine || (spine = {})); + +var sp = sp || {}; +sp.spine = spine; From 72e75f3e46747f0462616d57f076d88de0e48b48 Mon Sep 17 00:00:00 2001 From: drelaptop Date: Thu, 12 Apr 2018 10:08:05 +0800 Subject: [PATCH 198/206] adapts uvs --- extensions/spine/CCSkeleton.js | 5 ++- extensions/spine/CCSkeletonCanvasRenderCmd.js | 11 +++---- extensions/spine/CCSkeletonWebGLRenderCmd.js | 32 +++++++++++-------- 3 files changed, 27 insertions(+), 21 deletions(-) diff --git a/extensions/spine/CCSkeleton.js b/extensions/spine/CCSkeleton.js index 0ab0ad2b72..1317a31ffb 100644 --- a/extensions/spine/CCSkeleton.js +++ b/extensions/spine/CCSkeleton.js @@ -56,7 +56,10 @@ sp.ATTACHMENT_TYPE = { REGION: 0, BOUNDING_BOX: 1, MESH: 2, - SKINNED_MESH:3 + SKINNED_MESH:3, + PATH:4, + POINT:5, + CLIPPING:6 }; var spine = sp.spine; diff --git a/extensions/spine/CCSkeletonCanvasRenderCmd.js b/extensions/spine/CCSkeletonCanvasRenderCmd.js index 96de903a55..285eb463b7 100644 --- a/extensions/spine/CCSkeletonCanvasRenderCmd.js +++ b/extensions/spine/CCSkeletonCanvasRenderCmd.js @@ -115,15 +115,14 @@ proto._updateRegionAttachmentSlot = function (attachment, slot, points) { if (!points) return; - // 3.5 var vertices = attachment.updateWorldVertices(slot, false); var vertices = spine.Utils.setArraySize(new Array(), 8, 0); - attachment.computeWorldVertices(slot.bone, vertices, 0, 8); + attachment.computeWorldVertices(slot.bone, vertices, 0, 2); var VERTEX = spine.RegionAttachment; points.length = 0; - points.push(cc.p(vertices[VERTEX.X1], vertices[VERTEX.Y1])); - points.push(cc.p(vertices[VERTEX.X4], vertices[VERTEX.Y4])); - points.push(cc.p(vertices[VERTEX.X3], vertices[VERTEX.Y3])); - points.push(cc.p(vertices[VERTEX.X2], vertices[VERTEX.Y2])); + points.push(cc.p(vertices[VERTEX.OX1], vertices[VERTEX.OY1])); + points.push(cc.p(vertices[VERTEX.OX4], vertices[VERTEX.OY4])); + points.push(cc.p(vertices[VERTEX.OX3], vertices[VERTEX.OY3])); + points.push(cc.p(vertices[VERTEX.OX2], vertices[VERTEX.OY2])); }; proto._createChildFormSkeletonData = function () { diff --git a/extensions/spine/CCSkeletonWebGLRenderCmd.js b/extensions/spine/CCSkeletonWebGLRenderCmd.js index 6204b12bb5..323eb583e4 100644 --- a/extensions/spine/CCSkeletonWebGLRenderCmd.js +++ b/extensions/spine/CCSkeletonWebGLRenderCmd.js @@ -234,9 +234,12 @@ proto._uploadRegionAttachmentData = function(attachment, slot, premultipliedAlph nodeB = nodeColor.b, nodeA = this._displayedOpacity; // 3.5 var vertices = attachment.updateWorldVertices(slot, premultipliedAlpha); - // FIXME: lose premultipliedAlpha? + // FIXME: lose premultipliedAlpha? alpha impl innner, "vertices, 0, 8);" -> "vertices, 0, 2);" var vertices = spine.Utils.setArraySize(new Array(), 8, 0); - attachment.computeWorldVertices(slot.bone, vertices, 0, 8); + attachment.computeWorldVertices(slot.bone, vertices, 0, 2); + + var uvs = attachment.uvs; + var color = attachment.color; var wt = this._worldTransform, wa = wt.a, wb = wt.b, wc = wt.c, wd = wt.d, @@ -248,21 +251,21 @@ proto._uploadRegionAttachmentData = function(attachment, slot, premultipliedAlph // using two angles : (0, 1, 2) & (0, 2, 3) for (var i = 0; i < 6; i++) { var srcIdx = i < 4 ? i % 3 : i - 2; - var vx = vertices[srcIdx * 8], - vy = vertices[srcIdx * 8 + 1]; + var vx = vertices[srcIdx * 2], + vy = vertices[srcIdx * 2 + 1]; var x = vx * wa + vy * wc + wx, y = vx * wb + vy * wd + wy; - var r = vertices[srcIdx * 8 + 2] * nodeR, - g = vertices[srcIdx * 8 + 3] * nodeG, - b = vertices[srcIdx * 8 + 4] * nodeB, - a = vertices[srcIdx * 8 + 5] * nodeA; + var r = color.r * nodeR, + g = color.g * nodeG, + b = color.b * nodeB, + a = color.a * nodeA; var color = ((a<<24) | (b<<16) | (g<<8) | r); f32buffer[offset] = x; f32buffer[offset + 1] = y; f32buffer[offset + 2] = z; ui32buffer[offset + 3] = color; - f32buffer[offset + 4] = vertices[srcIdx * 8 + 6]; - f32buffer[offset + 5] = vertices[srcIdx * 8 + 7]; + f32buffer[offset + 4] = uvs[srcIdx * 2]; + f32buffer[offset + 5] = uvs[srcIdx * 2 + 1]; offset += 6; } @@ -270,10 +273,10 @@ proto._uploadRegionAttachmentData = function(attachment, slot, premultipliedAlph // return the quad points info if debug slot enabled var VERTEX = spine.RegionAttachment; return [ - cc.p(vertices[VERTEX.X1], vertices[VERTEX.Y1]), - cc.p(vertices[VERTEX.X2], vertices[VERTEX.Y2]), - cc.p(vertices[VERTEX.X3], vertices[VERTEX.Y3]), - cc.p(vertices[VERTEX.X4], vertices[VERTEX.Y4]) + cc.p(vertices[VERTEX.OX1], vertices[VERTEX.OY1]), + cc.p(vertices[VERTEX.OX2], vertices[VERTEX.OY2]), + cc.p(vertices[VERTEX.OX3], vertices[VERTEX.OY3]), + cc.p(vertices[VERTEX.OX4], vertices[VERTEX.OY4]) ]; } }; @@ -285,6 +288,7 @@ proto._uploadMeshAttachmentData = function(attachment, slot, premultipliedAlpha, z = this._node.vertexZ; // get the vertex data // 3.5 var vertices = attachment.updateWorldVertices(slot, premultipliedAlpha); + // FIXME, NOT USED THIS FUNCTION? var verticesLength = attachment.worldVerticesLength; var vertices = spine.Utils.setArraySize(new Array(), verticesLength, 0); attachment.computeWorldVertices(slot, 0, verticesLength, vertices, 0, 2); From fef59ea825c380a3412e94869059d19e6319f27d Mon Sep 17 00:00:00 2001 From: drelaptop Date: Thu, 12 Apr 2018 10:39:52 +0800 Subject: [PATCH 199/206] adapt region render color --- extensions/spine/CCSkeletonWebGLRenderCmd.js | 21 +++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/extensions/spine/CCSkeletonWebGLRenderCmd.js b/extensions/spine/CCSkeletonWebGLRenderCmd.js index 323eb583e4..e29a3c468a 100644 --- a/extensions/spine/CCSkeletonWebGLRenderCmd.js +++ b/extensions/spine/CCSkeletonWebGLRenderCmd.js @@ -233,13 +233,20 @@ proto._uploadRegionAttachmentData = function(attachment, slot, premultipliedAlph nodeG = nodeColor.g, nodeB = nodeColor.b, nodeA = this._displayedOpacity; - // 3.5 var vertices = attachment.updateWorldVertices(slot, premultipliedAlpha); - // FIXME: lose premultipliedAlpha? alpha impl innner, "vertices, 0, 8);" -> "vertices, 0, 2);" + var vertices = spine.Utils.setArraySize(new Array(), 8, 0); attachment.computeWorldVertices(slot.bone, vertices, 0, 2); var uvs = attachment.uvs; - var color = attachment.color; + + var skeleton = slot.bone.skeleton; + var skeletonColor = skeleton.color; + var slotColor = slot.color; + var regionColor = attachment.color; + var alpha = skeletonColor.a * slotColor.a * regionColor.a; + var multiplier = premultipliedAlpha ? alpha : 1; + var colors = attachment.tempColor; + colors.set(skeletonColor.r * slotColor.r * regionColor.r * multiplier, skeletonColor.g * slotColor.g * regionColor.g * multiplier, skeletonColor.b * slotColor.b * regionColor.b * multiplier, alpha); var wt = this._worldTransform, wa = wt.a, wb = wt.b, wc = wt.c, wd = wt.d, @@ -255,10 +262,10 @@ proto._uploadRegionAttachmentData = function(attachment, slot, premultipliedAlph vy = vertices[srcIdx * 2 + 1]; var x = vx * wa + vy * wc + wx, y = vx * wb + vy * wd + wy; - var r = color.r * nodeR, - g = color.g * nodeG, - b = color.b * nodeB, - a = color.a * nodeA; + var r = colors.r * nodeR, + g = colors.g * nodeG, + b = colors.b * nodeB, + a = colors.a * nodeA; var color = ((a<<24) | (b<<16) | (g<<8) | r); f32buffer[offset] = x; f32buffer[offset + 1] = y; From e14b5727b766d78222cceea422a0ac76e67940e2 Mon Sep 17 00:00:00 2001 From: drelaptop Date: Thu, 12 Apr 2018 11:18:30 +0800 Subject: [PATCH 200/206] adapt mesh render clolor --- extensions/spine/CCSkeletonWebGLRenderCmd.js | 34 ++++++++++++++------ 1 file changed, 25 insertions(+), 9 deletions(-) diff --git a/extensions/spine/CCSkeletonWebGLRenderCmd.js b/extensions/spine/CCSkeletonWebGLRenderCmd.js index e29a3c468a..13a6946032 100644 --- a/extensions/spine/CCSkeletonWebGLRenderCmd.js +++ b/extensions/spine/CCSkeletonWebGLRenderCmd.js @@ -239,6 +239,7 @@ proto._uploadRegionAttachmentData = function(attachment, slot, premultipliedAlph var uvs = attachment.uvs; + // get the colors data var skeleton = slot.bone.skeleton; var skeletonColor = skeleton.color; var slotColor = slot.color; @@ -246,7 +247,10 @@ proto._uploadRegionAttachmentData = function(attachment, slot, premultipliedAlph var alpha = skeletonColor.a * slotColor.a * regionColor.a; var multiplier = premultipliedAlpha ? alpha : 1; var colors = attachment.tempColor; - colors.set(skeletonColor.r * slotColor.r * regionColor.r * multiplier, skeletonColor.g * slotColor.g * regionColor.g * multiplier, skeletonColor.b * slotColor.b * regionColor.b * multiplier, alpha); + colors.set(skeletonColor.r * slotColor.r * regionColor.r * multiplier, + skeletonColor.g * slotColor.g * regionColor.g * multiplier, + skeletonColor.b * slotColor.b * regionColor.b * multiplier, + alpha); var wt = this._worldTransform, wa = wt.a, wb = wt.b, wc = wt.c, wd = wt.d, @@ -294,11 +298,23 @@ proto._uploadMeshAttachmentData = function(attachment, slot, premultipliedAlpha, wx = wt.tx, wy = wt.ty, z = this._node.vertexZ; // get the vertex data - // 3.5 var vertices = attachment.updateWorldVertices(slot, premultipliedAlpha); - // FIXME, NOT USED THIS FUNCTION? var verticesLength = attachment.worldVerticesLength; var vertices = spine.Utils.setArraySize(new Array(), verticesLength, 0); attachment.computeWorldVertices(slot, 0, verticesLength, vertices, 0, 2); + + var uvs = attachment.uvs; + + // get the colors data + var skeleton = slot.bone.skeleton; + var skeletonColor = skeleton.color, slotColor = slot.color, meshColor = attachment.color; + var alpha = skeletonColor.a * slotColor.a * meshColor.a; + var multiplier = premultipliedAlpha ? alpha : 1; + var colors = attachment.tempColor; + colors.set(skeletonColor.r * slotColor.r * meshColor.r * multiplier, + skeletonColor.g * slotColor.g * meshColor.g * multiplier, + skeletonColor.b * slotColor.b * meshColor.b * multiplier, + alpha); + var offset = vertexDataOffset; var nodeColor = this._displayedColor; var nodeR = nodeColor.r, @@ -310,18 +326,18 @@ proto._uploadMeshAttachmentData = function(attachment, slot, premultipliedAlpha, vy = vertices[i + 1]; var x = vx * wa + vy * wb + wx, y = vx * wc + vy * wd + wy; - var r = vertices[i + 2] * nodeR, - g = vertices[i + 3] * nodeG, - b = vertices[i + 4] * nodeB, - a = vertices[i + 5] * nodeA; + var r = colors.r * nodeR, + g = colors.g * nodeG, + b = colors.b * nodeB, + a = colors.a * nodeA; var color = ((a<<24) | (b<<16) | (g<<8) | r); f32buffer[offset] = x; f32buffer[offset + 1] = y; f32buffer[offset + 2] = z; ui32buffer[offset + 3] = color; - f32buffer[offset + 4] = vertices[i + 6]; - f32buffer[offset + 5] = vertices[i + 7]; + f32buffer[offset + 4] = uvs[i]; + f32buffer[offset + 5] = uvs[i + 1]; offset += 6; } }; From 7eb4663aa522edf8254bec60fa99278c7cd3b381 Mon Sep 17 00:00:00 2001 From: drelaptop Date: Thu, 12 Apr 2018 11:33:14 +0800 Subject: [PATCH 201/206] change version number --- cocos2d/core/platform/CCConfig.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos2d/core/platform/CCConfig.js b/cocos2d/core/platform/CCConfig.js index ceeddbf5d8..b4795155ed 100644 --- a/cocos2d/core/platform/CCConfig.js +++ b/cocos2d/core/platform/CCConfig.js @@ -31,7 +31,7 @@ * @type {String} * @name cc.ENGINE_VERSION */ -window["CocosEngine"] = cc.ENGINE_VERSION = "Cocos2d-JS v3.16"; +window["CocosEngine"] = cc.ENGINE_VERSION = "Cocos2d-JS v3.17"; /** *

From 4b19b786845f549d79948e746b51d20a5289e1ef Mon Sep 17 00:00:00 2001 From: drelaptop Date: Thu, 12 Apr 2018 14:36:05 +0800 Subject: [PATCH 202/206] fix canvas draw point error --- cocos2d/core/CCDrawingPrimitivesCanvas.js | 15 +++++---------- extensions/spine/CCSkeletonCanvasRenderCmd.js | 5 ++--- 2 files changed, 7 insertions(+), 13 deletions(-) diff --git a/cocos2d/core/CCDrawingPrimitivesCanvas.js b/cocos2d/core/CCDrawingPrimitivesCanvas.js index ce4c914a85..f94b4ca297 100644 --- a/cocos2d/core/CCDrawingPrimitivesCanvas.js +++ b/cocos2d/core/CCDrawingPrimitivesCanvas.js @@ -56,11 +56,9 @@ cc.DrawingPrimitiveCanvas = cc.Class.extend(/** @lends cc.DrawingPrimitiveCanvas if (!size) { size = 1; } - var locScaleX = cc.view.getScaleX(), locScaleY = cc.view.getScaleY(); - var newPoint = cc.p(point.x * locScaleX, point.y * locScaleY); var ctx = this._renderContext.getContext(); ctx.beginPath(); - ctx.arc(newPoint.x, -newPoint.y, size * locScaleX, 0, Math.PI * 2, false); + ctx.arc(point.x, -point.y, size, 0, Math.PI * 2, false); ctx.closePath(); ctx.fill(); }, @@ -79,11 +77,11 @@ cc.DrawingPrimitiveCanvas = cc.Class.extend(/** @lends cc.DrawingPrimitiveCanvas if (!size) { size = 1; } - var locContext = this._renderContext.getContext(),locScaleX = cc.view.getScaleX(), locScaleY = cc.view.getScaleY(); + var locContext = this._renderContext.getContext(); locContext.beginPath(); for (var i = 0, len = points.length; i < len; i++) - locContext.arc(points[i].x * locScaleX, -points[i].y * locScaleY, size * locScaleX, 0, Math.PI * 2, false); + locContext.arc(points[i].x, -points[i].y, size, 0, Math.PI * 2, false); locContext.closePath(); locContext.fill(); }, @@ -95,7 +93,7 @@ cc.DrawingPrimitiveCanvas = cc.Class.extend(/** @lends cc.DrawingPrimitiveCanvas * @param {cc.Point} destination */ drawLine:function (origin, destination) { - var locContext = this._renderContext.getContext(), locScaleX = cc.view.getScaleX(), locScaleY = cc.view.getScaleY(); + var locContext = this._renderContext.getContext(); locContext.beginPath(); locContext.moveTo(origin.x , -origin.y ); locContext.lineTo(destination.x, -destination.y ); @@ -151,7 +149,6 @@ cc.DrawingPrimitiveCanvas = cc.Class.extend(/** @lends cc.DrawingPrimitiveCanvas throw new Error("Polygon's point must greater than 2"); var firstPoint = vertices[0], locContext = this._renderContext.getContext(); - var locScaleX = cc.view.getScaleX(), locScaleY = cc.view.getScaleY(); locContext.beginPath(); locContext.moveTo(firstPoint.x , -firstPoint.y ); for (var i = 1, len = vertices.length; i < len; i++) @@ -189,7 +186,6 @@ cc.DrawingPrimitiveCanvas = cc.Class.extend(/** @lends cc.DrawingPrimitiveCanvas drawCircle: function (center, radius, angle, segments, drawLineToCenter) { drawLineToCenter = drawLineToCenter || false; var locContext = this._renderContext.getContext(); - var locScaleX = cc.view.getScaleX(), locScaleY = cc.view.getScaleY(); locContext.beginPath(); var endAngle = angle - Math.PI * 2; locContext.arc(0 | (center.x ), 0 | -(center.y ), radius , -angle, -endAngle, false); @@ -379,7 +375,6 @@ cc.DrawingPrimitiveCanvas = cc.Class.extend(/** @lends cc.DrawingPrimitiveCanvas drawColorBall:function (ctx, radius, color) { var wrapper = ctx || this._renderContext; var context = wrapper.getContext(); - radius *= cc.view.getScaleX(); var colorStr = "rgba(" +(0|color.r) + "," + (0|color.g) + "," + (0|color.b); var subRadius = radius / 10; @@ -432,6 +427,6 @@ cc.DrawingPrimitiveCanvas = cc.Class.extend(/** @lends cc.DrawingPrimitiveCanvas * @param {Number} width */ setLineWidth:function (width) { - this._renderContext.getContext().lineWidth = width * cc.view.getScaleX(); + this._renderContext.getContext().lineWidth = width; } }); \ No newline at end of file diff --git a/extensions/spine/CCSkeletonCanvasRenderCmd.js b/extensions/spine/CCSkeletonCanvasRenderCmd.js index 285eb463b7..f31924ec19 100644 --- a/extensions/spine/CCSkeletonCanvasRenderCmd.js +++ b/extensions/spine/CCSkeletonCanvasRenderCmd.js @@ -87,13 +87,12 @@ proto.rendering = function (wrapper, scaleX, scaleY) { } // Bone origins. - // FIXME: point position wrong, might due to scale - drawingUtil.setPointSize(4); + var pointSize = 4; drawingUtil.setDrawColor(0, 0, 255, 255); // Root bone is blue. for (i = 0, n = locSkeleton.bones.length; i < n; i++) { bone = locSkeleton.bones[i]; - drawingUtil.drawPoint({x: bone.worldX, y: bone.worldY}); + drawingUtil.drawPoint({x: bone.worldX, y: bone.worldY}, pointSize); if (i === 0) drawingUtil.setDrawColor(0, 255, 0, 255); } From d26ddb24c068df59972e1c0f11f23f16c97ebc4a Mon Sep 17 00:00:00 2001 From: drelaptop Date: Thu, 12 Apr 2018 14:55:26 +0800 Subject: [PATCH 203/206] remove unused struct --- extensions/spine/CCSkeleton.js | 42 ++++------------------------------ 1 file changed, 5 insertions(+), 37 deletions(-) diff --git a/extensions/spine/CCSkeleton.js b/extensions/spine/CCSkeleton.js index 1317a31ffb..97a99f4edb 100644 --- a/extensions/spine/CCSkeleton.js +++ b/extensions/spine/CCSkeleton.js @@ -31,37 +31,6 @@ */ var sp = sp || {}; -/** - * The vertex index of spine. - * @constant - * @type {{X1: number, Y1: number, X2: number, Y2: number, X3: number, Y3: number, X4: number, Y4: number}} - */ -sp.VERTEX_INDEX = { - X1: 0, - Y1: 1, - X2: 2, - Y2: 3, - X3: 4, - Y3: 5, - X4: 6, - Y4: 7 -}; - -/** - * The attachment type of spine. It contains three type: REGION(0), BOUNDING_BOX(1), MESH(2) and SKINNED_MESH. - * @constant - * @type {{REGION: number, BOUNDING_BOX: number, REGION_SEQUENCE: number, MESH: number}} - */ -sp.ATTACHMENT_TYPE = { - REGION: 0, - BOUNDING_BOX: 1, - MESH: 2, - SKINNED_MESH:3, - PATH:4, - POINT:5, - CLIPPING:6 -}; - var spine = sp.spine; /** @@ -231,13 +200,12 @@ sp.Skeleton = cc.Node.extend(/** @lends sp.Skeleton# */{ var attachment = slot.attachment; if (!attachment || !(attachment instanceof spine.RegionAttachment)) continue; - // 3.5 vertices = attachment.updateWorldVertices(slot, false); vertices = spine.Utils.setArraySize(new Array(), 8, 0); - attachment.computeWorldVertices(slot.bone, vertices, 0, 8); - minX = Math.min(minX, vertices[VERTEX.X1] * scaleX, vertices[VERTEX.X4] * scaleX, vertices[VERTEX.X2] * scaleX, vertices[VERTEX.X3] * scaleX); - minY = Math.min(minY, vertices[VERTEX.Y1] * scaleY, vertices[VERTEX.Y4] * scaleY, vertices[VERTEX.Y2] * scaleY, vertices[VERTEX.Y3] * scaleY); - maxX = Math.max(maxX, vertices[VERTEX.X1] * scaleX, vertices[VERTEX.X4] * scaleX, vertices[VERTEX.X2] * scaleX, vertices[VERTEX.X3] * scaleX); - maxY = Math.max(maxY, vertices[VERTEX.Y1] * scaleY, vertices[VERTEX.Y4] * scaleY, vertices[VERTEX.Y2] * scaleY, vertices[VERTEX.Y3] * scaleY); + attachment.computeWorldVertices(slot.bone, vertices, 0, 2); + minX = Math.min(minX, vertices[VERTEX.OX1] * scaleX, vertices[VERTEX.OX4] * scaleX, vertices[VERTEX.OX2] * scaleX, vertices[VERTEX.OX3] * scaleX); + minY = Math.min(minY, vertices[VERTEX.OY1] * scaleY, vertices[VERTEX.OY4] * scaleY, vertices[VERTEX.OY2] * scaleY, vertices[VERTEX.OY3] * scaleY); + maxX = Math.max(maxX, vertices[VERTEX.OX1] * scaleX, vertices[VERTEX.OX4] * scaleX, vertices[VERTEX.OX2] * scaleX, vertices[VERTEX.OX3] * scaleX); + maxY = Math.max(maxY, vertices[VERTEX.OY1] * scaleY, vertices[VERTEX.OY4] * scaleY, vertices[VERTEX.OY2] * scaleY, vertices[VERTEX.OY3] * scaleY); } var position = this.getPosition(); return cc.rect(position.x + minX, position.y + minY, maxX - minX, maxY - minY); From adeefef3a840e0ddb9529cf9038616fcc4fcdde5 Mon Sep 17 00:00:00 2001 From: drelaptop Date: Fri, 13 Apr 2018 14:38:47 +0800 Subject: [PATCH 204/206] avoid vertex data overflow --- extensions/spine/CCSkeletonWebGLRenderCmd.js | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/extensions/spine/CCSkeletonWebGLRenderCmd.js b/extensions/spine/CCSkeletonWebGLRenderCmd.js index 13a6946032..535e4c0ac5 100644 --- a/extensions/spine/CCSkeletonWebGLRenderCmd.js +++ b/extensions/spine/CCSkeletonWebGLRenderCmd.js @@ -91,8 +91,10 @@ proto.uploadData = function (f32buffer, ui32buffer, vertexDataOffset){ this._currTexture = regionTextureAtlas.texture.getRealTexture(); var batchBroken = cc.renderer._updateBatchedInfo(this._currTexture, this._getBlendFunc(slot.data.blendMode, premultiAlpha), this._glProgramState); + // keep the same logic with RendererWebGL.js, avoid vertex data overflow + var uploadAll = vertexDataOffset / 6 + vertCount > (cc.BATCH_VERTEX_COUNT - 200) * 0.5; // Broken for vertex data overflow - if (!batchBroken && vertexDataOffset + vertCount * 6 > f32buffer.length) { + if (!batchBroken && uploadAll) { // render the cached data cc.renderer._batchRendering(); batchBroken = true; From fe148d3b7ba2b35ce8c206feb653ae8d5557301b Mon Sep 17 00:00:00 2001 From: Shun Lin Date: Mon, 25 Feb 2019 18:39:03 +0800 Subject: [PATCH 205/206] Update the latest status of Cocos2d-html5 Now Cocos2d-html5 is the renderer engine of Cocos Creator. --- README.mdown | 28 ++++++---------------------- 1 file changed, 6 insertions(+), 22 deletions(-) diff --git a/README.mdown b/README.mdown index 57823c8723..843c669833 100644 --- a/README.mdown +++ b/README.mdown @@ -5,36 +5,18 @@ Cocos2d-html5 It incorporates the same high level api as “Cocos2d JS-binding engine” and compatible with Cocos2d-X. It currently supports canvas and WebGL renderer. +#### Cocos2d-html5 has evolved to Cocos Creator, new generation of Cocos game engine with a full featured editor and content creation friendly workflow. The latest repository is maintained in here [Engine of Cocos Creator][9]. + Cross Platform ------------- * Popular browsers: Chrome 14+, Safari 5.0+, IE9+, Firefox 3.5+. - * Mobile platforms: coming soon. + * Mobile platforms: Mobile browsers,Facebook Instant Games and Mini Games. * Native App: Same piece of code can run on "Cocos2d JS-Binding Engine" without or with little modification. Documentation ------------------ * Website: [www.cocos2d-x.org][3] - * API References: [http://www.cocos2d-x.org/wiki/Reference] [4] - - -Installing from [bower][8] (version >=3.4) ------------------- - -```shell -$ bower install cocos2d-html5 -``` - -Running the tests (version <3) ------------------- - -```shell -$ git clone git://github.com/cocos2d/cocos2d-html5.git -$ cd cocos2d-html5 -$ git submodule update --init -$ python -m SimpleHTTPServer -``` -... and then open a browser and go to `http://localhost:8000/tests` - + * Cocos Creator download: [Cocos Creator][10] Contact us ------------------ @@ -50,3 +32,5 @@ Contact us [6]: http://www.twitter.com/cocos2dhtml5 "http://www.twitter.com/cocos2dhtml5" [7]: http://t.sina.com.cn/cocos2dhtml5 "http://t.sina.com.cn/cocos2dhtml5" [8]: http://bower.io "http://bower.io" +[9]: https://github.com/cocos-creator/engine +[10]: http://cocos2d-x.org/download From c0324ad511b7e327a597d9a0d27e5a7d9f4fbc07 Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Fri, 13 Mar 2020 17:27:56 +0800 Subject: [PATCH 206/206] Update README.mdown --- README.mdown | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/README.mdown b/README.mdown index 843c669833..3b13c27fac 100644 --- a/README.mdown +++ b/README.mdown @@ -5,7 +5,11 @@ Cocos2d-html5 It incorporates the same high level api as “Cocos2d JS-binding engine” and compatible with Cocos2d-X. It currently supports canvas and WebGL renderer. -#### Cocos2d-html5 has evolved to Cocos Creator, new generation of Cocos game engine with a full featured editor and content creation friendly workflow. The latest repository is maintained in here [Engine of Cocos Creator][9]. +------------- + +#### Cocos2d-html5 has evolved to [Cocos Creator][11], new generation of Cocos game engine with a full featured editor and content creation friendly workflow. It supports all major platforms allowing games to be quickly released for the web, iOS, Android, Windows, Mac, and various mini-game platforms. A pure JavaScript-developed engine runtime is available on the web and mini-game platforms for better performance and smaller packages. On other native platforms, C++ is used to implement the underlying framework, providing greater operational efficiency. The latest repository is maintained in here [Engine of Cocos Creator][9]. + +------------- Cross Platform ------------- @@ -34,3 +38,4 @@ Contact us [8]: http://bower.io "http://bower.io" [9]: https://github.com/cocos-creator/engine [10]: http://cocos2d-x.org/download +[11]: https://www.cocos.com/en/products#CocosCreator "https://www.cocos.com"